e5e30b617073417edd2e5fc5a661fd28f567f2ea
[pandora-kernel.git] / kernel / kmod.c
1 /*
2         kmod, the new module loader (replaces kerneld)
3         Kirk Petersen
4
5         Reorganized not to be a daemon by Adam Richter, with guidance
6         from Greg Zornetzer.
7
8         Modified to avoid chroot and file sharing problems.
9         Mikael Pettersson
10
11         Limit the concurrent number of kmod modprobes to catch loops from
12         "modprobe needs a service that is in a module".
13         Keith Owens <kaos@ocs.com.au> December 1999
14
15         Unblock all signals when we exec a usermode process.
16         Shuu Yamaguchi <shuu@wondernetworkresources.com> December 2000
17
18         call_usermodehelper wait flag, and remove exec_usermodehelper.
19         Rusty Russell <rusty@rustcorp.com.au>  Jan 2003
20 */
21 #include <linux/module.h>
22 #include <linux/sched.h>
23 #include <linux/syscalls.h>
24 #include <linux/unistd.h>
25 #include <linux/kmod.h>
26 #include <linux/slab.h>
27 #include <linux/completion.h>
28 #include <linux/cred.h>
29 #include <linux/file.h>
30 #include <linux/fdtable.h>
31 #include <linux/workqueue.h>
32 #include <linux/security.h>
33 #include <linux/mount.h>
34 #include <linux/kernel.h>
35 #include <linux/init.h>
36 #include <linux/resource.h>
37 #include <linux/notifier.h>
38 #include <linux/suspend.h>
39 #include <asm/uaccess.h>
40
41 #include <trace/events/module.h>
42
43 extern int max_threads;
44
45 static struct workqueue_struct *khelper_wq;
46
47 #define CAP_BSET        (void *)1
48 #define CAP_PI          (void *)2
49
50 static kernel_cap_t usermodehelper_bset = CAP_FULL_SET;
51 static kernel_cap_t usermodehelper_inheritable = CAP_FULL_SET;
52 static DEFINE_SPINLOCK(umh_sysctl_lock);
53
54 #ifdef CONFIG_MODULES
55
56 /*
57         modprobe_path is set via /proc/sys.
58 */
59 char modprobe_path[KMOD_PATH_LEN] = "/sbin/modprobe";
60
61 /**
62  * __request_module - try to load a kernel module
63  * @wait: wait (or not) for the operation to complete
64  * @fmt: printf style format string for the name of the module
65  * @...: arguments as specified in the format string
66  *
67  * Load a module using the user mode module loader. The function returns
68  * zero on success or a negative errno code on failure. Note that a
69  * successful module load does not mean the module did not then unload
70  * and exit on an error of its own. Callers must check that the service
71  * they requested is now available not blindly invoke it.
72  *
73  * If module auto-loading support is disabled then this function
74  * becomes a no-operation.
75  */
76 int __request_module(bool wait, const char *fmt, ...)
77 {
78         va_list args;
79         char module_name[MODULE_NAME_LEN];
80         unsigned int max_modprobes;
81         int ret;
82         char *argv[] = { modprobe_path, "-q", "--", module_name, NULL };
83         static char *envp[] = { "HOME=/",
84                                 "TERM=linux",
85                                 "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
86                                 NULL };
87         static atomic_t kmod_concurrent = ATOMIC_INIT(0);
88 #define MAX_KMOD_CONCURRENT 50  /* Completely arbitrary value - KAO */
89         static int kmod_loop_msg;
90
91         va_start(args, fmt);
92         ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
93         va_end(args);
94         if (ret >= MODULE_NAME_LEN)
95                 return -ENAMETOOLONG;
96
97         ret = security_kernel_module_request(module_name);
98         if (ret)
99                 return ret;
100
101         /* If modprobe needs a service that is in a module, we get a recursive
102          * loop.  Limit the number of running kmod threads to max_threads/2 or
103          * MAX_KMOD_CONCURRENT, whichever is the smaller.  A cleaner method
104          * would be to run the parents of this process, counting how many times
105          * kmod was invoked.  That would mean accessing the internals of the
106          * process tables to get the command line, proc_pid_cmdline is static
107          * and it is not worth changing the proc code just to handle this case. 
108          * KAO.
109          *
110          * "trace the ppid" is simple, but will fail if someone's
111          * parent exits.  I think this is as good as it gets. --RR
112          */
113         max_modprobes = min(max_threads/2, MAX_KMOD_CONCURRENT);
114         atomic_inc(&kmod_concurrent);
115         if (atomic_read(&kmod_concurrent) > max_modprobes) {
116                 /* We may be blaming an innocent here, but unlikely */
117                 if (kmod_loop_msg < 5) {
118                         printk(KERN_ERR
119                                "request_module: runaway loop modprobe %s\n",
120                                module_name);
121                         kmod_loop_msg++;
122                 }
123                 atomic_dec(&kmod_concurrent);
124                 return -ENOMEM;
125         }
126
127         trace_module_request(module_name, wait, _RET_IP_);
128
129         ret = call_usermodehelper_fns(modprobe_path, argv, envp,
130                         wait ? UMH_WAIT_PROC : UMH_WAIT_EXEC,
131                         NULL, NULL, NULL);
132
133         atomic_dec(&kmod_concurrent);
134         return ret;
135 }
136 EXPORT_SYMBOL(__request_module);
137 #endif /* CONFIG_MODULES */
138
139 /*
140  * This is the task which runs the usermode application
141  */
142 static int ____call_usermodehelper(void *data)
143 {
144         struct subprocess_info *sub_info = data;
145         struct cred *new;
146         int retval;
147
148         spin_lock_irq(&current->sighand->siglock);
149         flush_signal_handlers(current, 1);
150         spin_unlock_irq(&current->sighand->siglock);
151
152         /* We can run anywhere, unlike our parent keventd(). */
153         set_cpus_allowed_ptr(current, cpu_all_mask);
154
155         /*
156          * Our parent is keventd, which runs with elevated scheduling priority.
157          * Avoid propagating that into the userspace child.
158          */
159         set_user_nice(current, 0);
160
161         retval = -ENOMEM;
162         new = prepare_kernel_cred(current);
163         if (!new)
164                 goto fail;
165
166         spin_lock(&umh_sysctl_lock);
167         new->cap_bset = cap_intersect(usermodehelper_bset, new->cap_bset);
168         new->cap_inheritable = cap_intersect(usermodehelper_inheritable,
169                                              new->cap_inheritable);
170         spin_unlock(&umh_sysctl_lock);
171
172         if (sub_info->init) {
173                 retval = sub_info->init(sub_info, new);
174                 if (retval) {
175                         abort_creds(new);
176                         goto fail;
177                 }
178         }
179
180         commit_creds(new);
181
182         retval = kernel_execve(sub_info->path,
183                                (const char *const *)sub_info->argv,
184                                (const char *const *)sub_info->envp);
185
186         /* Exec failed? */
187 fail:
188         sub_info->retval = retval;
189         do_exit(0);
190 }
191
192 void call_usermodehelper_freeinfo(struct subprocess_info *info)
193 {
194         if (info->cleanup)
195                 (*info->cleanup)(info);
196         kfree(info);
197 }
198 EXPORT_SYMBOL(call_usermodehelper_freeinfo);
199
200 static void umh_complete(struct subprocess_info *sub_info)
201 {
202         complete(sub_info->complete);
203 }
204
205 /* Keventd can't block, but this (a child) can. */
206 static int wait_for_helper(void *data)
207 {
208         struct subprocess_info *sub_info = data;
209         pid_t pid;
210
211         /* If SIGCLD is ignored sys_wait4 won't populate the status. */
212         spin_lock_irq(&current->sighand->siglock);
213         current->sighand->action[SIGCHLD-1].sa.sa_handler = SIG_DFL;
214         spin_unlock_irq(&current->sighand->siglock);
215
216         pid = kernel_thread(____call_usermodehelper, sub_info, SIGCHLD);
217         if (pid < 0) {
218                 sub_info->retval = pid;
219         } else {
220                 int ret = -ECHILD;
221                 /*
222                  * Normally it is bogus to call wait4() from in-kernel because
223                  * wait4() wants to write the exit code to a userspace address.
224                  * But wait_for_helper() always runs as keventd, and put_user()
225                  * to a kernel address works OK for kernel threads, due to their
226                  * having an mm_segment_t which spans the entire address space.
227                  *
228                  * Thus the __user pointer cast is valid here.
229                  */
230                 sys_wait4(pid, (int __user *)&ret, 0, NULL);
231
232                 /*
233                  * If ret is 0, either ____call_usermodehelper failed and the
234                  * real error code is already in sub_info->retval or
235                  * sub_info->retval is 0 anyway, so don't mess with it then.
236                  */
237                 if (ret)
238                         sub_info->retval = ret;
239         }
240
241         umh_complete(sub_info);
242         return 0;
243 }
244
245 /* This is run by khelper thread  */
246 static void __call_usermodehelper(struct work_struct *work)
247 {
248         struct subprocess_info *sub_info =
249                 container_of(work, struct subprocess_info, work);
250         enum umh_wait wait = sub_info->wait;
251         pid_t pid;
252
253         /* CLONE_VFORK: wait until the usermode helper has execve'd
254          * successfully We need the data structures to stay around
255          * until that is done.  */
256         if (wait == UMH_WAIT_PROC)
257                 pid = kernel_thread(wait_for_helper, sub_info,
258                                     CLONE_FS | CLONE_FILES | SIGCHLD);
259         else
260                 pid = kernel_thread(____call_usermodehelper, sub_info,
261                                     CLONE_VFORK | SIGCHLD);
262
263         switch (wait) {
264         case UMH_NO_WAIT:
265                 call_usermodehelper_freeinfo(sub_info);
266                 break;
267
268         case UMH_WAIT_PROC:
269                 if (pid > 0)
270                         break;
271                 /* FALLTHROUGH */
272         case UMH_WAIT_EXEC:
273                 if (pid < 0)
274                         sub_info->retval = pid;
275                 umh_complete(sub_info);
276         }
277 }
278
279 /*
280  * If set, call_usermodehelper_exec() will exit immediately returning -EBUSY
281  * (used for preventing user land processes from being created after the user
282  * land has been frozen during a system-wide hibernation or suspend operation).
283  */
284 static int usermodehelper_disabled = 1;
285
286 /* Number of helpers running */
287 static atomic_t running_helpers = ATOMIC_INIT(0);
288
289 /*
290  * Wait queue head used by usermodehelper_pm_callback() to wait for all running
291  * helpers to finish.
292  */
293 static DECLARE_WAIT_QUEUE_HEAD(running_helpers_waitq);
294
295 /*
296  * Time to wait for running_helpers to become zero before the setting of
297  * usermodehelper_disabled in usermodehelper_pm_callback() fails
298  */
299 #define RUNNING_HELPERS_TIMEOUT (5 * HZ)
300
301 /**
302  * usermodehelper_disable - prevent new helpers from being started
303  */
304 int usermodehelper_disable(void)
305 {
306         long retval;
307
308         usermodehelper_disabled = 1;
309         smp_mb();
310         /*
311          * From now on call_usermodehelper_exec() won't start any new
312          * helpers, so it is sufficient if running_helpers turns out to
313          * be zero at one point (it may be increased later, but that
314          * doesn't matter).
315          */
316         retval = wait_event_timeout(running_helpers_waitq,
317                                         atomic_read(&running_helpers) == 0,
318                                         RUNNING_HELPERS_TIMEOUT);
319         if (retval)
320                 return 0;
321
322         usermodehelper_disabled = 0;
323         return -EAGAIN;
324 }
325
326 /**
327  * usermodehelper_enable - allow new helpers to be started again
328  */
329 void usermodehelper_enable(void)
330 {
331         usermodehelper_disabled = 0;
332 }
333
334 /**
335  * usermodehelper_is_disabled - check if new helpers are allowed to be started
336  */
337 bool usermodehelper_is_disabled(void)
338 {
339         return usermodehelper_disabled;
340 }
341 EXPORT_SYMBOL_GPL(usermodehelper_is_disabled);
342
343 static void helper_lock(void)
344 {
345         atomic_inc(&running_helpers);
346         smp_mb__after_atomic_inc();
347 }
348
349 static void helper_unlock(void)
350 {
351         if (atomic_dec_and_test(&running_helpers))
352                 wake_up(&running_helpers_waitq);
353 }
354
355 /**
356  * call_usermodehelper_setup - prepare to call a usermode helper
357  * @path: path to usermode executable
358  * @argv: arg vector for process
359  * @envp: environment for process
360  * @gfp_mask: gfp mask for memory allocation
361  *
362  * Returns either %NULL on allocation failure, or a subprocess_info
363  * structure.  This should be passed to call_usermodehelper_exec to
364  * exec the process and free the structure.
365  */
366 struct subprocess_info *call_usermodehelper_setup(char *path, char **argv,
367                                                   char **envp, gfp_t gfp_mask)
368 {
369         struct subprocess_info *sub_info;
370         sub_info = kzalloc(sizeof(struct subprocess_info), gfp_mask);
371         if (!sub_info)
372                 goto out;
373
374         INIT_WORK(&sub_info->work, __call_usermodehelper);
375         sub_info->path = path;
376         sub_info->argv = argv;
377         sub_info->envp = envp;
378   out:
379         return sub_info;
380 }
381 EXPORT_SYMBOL(call_usermodehelper_setup);
382
383 /**
384  * call_usermodehelper_setfns - set a cleanup/init function
385  * @info: a subprocess_info returned by call_usermodehelper_setup
386  * @cleanup: a cleanup function
387  * @init: an init function
388  * @data: arbitrary context sensitive data
389  *
390  * The init function is used to customize the helper process prior to
391  * exec.  A non-zero return code causes the process to error out, exit,
392  * and return the failure to the calling process
393  *
394  * The cleanup function is just before ethe subprocess_info is about to
395  * be freed.  This can be used for freeing the argv and envp.  The
396  * Function must be runnable in either a process context or the
397  * context in which call_usermodehelper_exec is called.
398  */
399 void call_usermodehelper_setfns(struct subprocess_info *info,
400                     int (*init)(struct subprocess_info *info, struct cred *new),
401                     void (*cleanup)(struct subprocess_info *info),
402                     void *data)
403 {
404         info->cleanup = cleanup;
405         info->init = init;
406         info->data = data;
407 }
408 EXPORT_SYMBOL(call_usermodehelper_setfns);
409
410 /**
411  * call_usermodehelper_exec - start a usermode application
412  * @sub_info: information about the subprocessa
413  * @wait: wait for the application to finish and return status.
414  *        when -1 don't wait at all, but you get no useful error back when
415  *        the program couldn't be exec'ed. This makes it safe to call
416  *        from interrupt context.
417  *
418  * Runs a user-space application.  The application is started
419  * asynchronously if wait is not set, and runs as a child of keventd.
420  * (ie. it runs with full root capabilities).
421  */
422 int call_usermodehelper_exec(struct subprocess_info *sub_info,
423                              enum umh_wait wait)
424 {
425         DECLARE_COMPLETION_ONSTACK(done);
426         int retval = 0;
427
428         helper_lock();
429         if (sub_info->path[0] == '\0')
430                 goto out;
431
432         if (!khelper_wq || usermodehelper_disabled) {
433                 retval = -EBUSY;
434                 goto out;
435         }
436
437         sub_info->complete = &done;
438         sub_info->wait = wait;
439
440         queue_work(khelper_wq, &sub_info->work);
441         if (wait == UMH_NO_WAIT)        /* task has freed sub_info */
442                 goto unlock;
443         wait_for_completion(&done);
444         retval = sub_info->retval;
445
446 out:
447         call_usermodehelper_freeinfo(sub_info);
448 unlock:
449         helper_unlock();
450         return retval;
451 }
452 EXPORT_SYMBOL(call_usermodehelper_exec);
453
454 static int proc_cap_handler(struct ctl_table *table, int write,
455                          void __user *buffer, size_t *lenp, loff_t *ppos)
456 {
457         struct ctl_table t;
458         unsigned long cap_array[_KERNEL_CAPABILITY_U32S];
459         kernel_cap_t new_cap;
460         int err, i;
461
462         if (write && (!capable(CAP_SETPCAP) ||
463                       !capable(CAP_SYS_MODULE)))
464                 return -EPERM;
465
466         /*
467          * convert from the global kernel_cap_t to the ulong array to print to
468          * userspace if this is a read.
469          */
470         spin_lock(&umh_sysctl_lock);
471         for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)  {
472                 if (table->data == CAP_BSET)
473                         cap_array[i] = usermodehelper_bset.cap[i];
474                 else if (table->data == CAP_PI)
475                         cap_array[i] = usermodehelper_inheritable.cap[i];
476                 else
477                         BUG();
478         }
479         spin_unlock(&umh_sysctl_lock);
480
481         t = *table;
482         t.data = &cap_array;
483
484         /*
485          * actually read or write and array of ulongs from userspace.  Remember
486          * these are least significant 32 bits first
487          */
488         err = proc_doulongvec_minmax(&t, write, buffer, lenp, ppos);
489         if (err < 0)
490                 return err;
491
492         /*
493          * convert from the sysctl array of ulongs to the kernel_cap_t
494          * internal representation
495          */
496         for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)
497                 new_cap.cap[i] = cap_array[i];
498
499         /*
500          * Drop everything not in the new_cap (but don't add things)
501          */
502         spin_lock(&umh_sysctl_lock);
503         if (write) {
504                 if (table->data == CAP_BSET)
505                         usermodehelper_bset = cap_intersect(usermodehelper_bset, new_cap);
506                 if (table->data == CAP_PI)
507                         usermodehelper_inheritable = cap_intersect(usermodehelper_inheritable, new_cap);
508         }
509         spin_unlock(&umh_sysctl_lock);
510
511         return 0;
512 }
513
514 struct ctl_table usermodehelper_table[] = {
515         {
516                 .procname       = "bset",
517                 .data           = CAP_BSET,
518                 .maxlen         = _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
519                 .mode           = 0600,
520                 .proc_handler   = proc_cap_handler,
521         },
522         {
523                 .procname       = "inheritable",
524                 .data           = CAP_PI,
525                 .maxlen         = _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
526                 .mode           = 0600,
527                 .proc_handler   = proc_cap_handler,
528         },
529         { }
530 };
531
532 void __init usermodehelper_init(void)
533 {
534         khelper_wq = create_singlethread_workqueue("khelper");
535         BUG_ON(!khelper_wq);
536 }