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