Merge remote-tracking branch 'origin/clustered' into aks_dev_clus
[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(
207                 current->pid,sub_info->remote_pid,sub_info->remote_cpu);
208     } 
209
210         retval = kernel_execve(sub_info->path,
211                                (const char *const *)sub_info->argv,
212                                (const char *const *)sub_info->envp);
213     
214         /* Exec failed? */
215 fail:
216         printk("%s: failed retval{%d}\n", __func__, retval);
217         sub_info->retval = retval;
218         do_exit(0);
219 }
220
221 void call_usermodehelper_freeinfo(struct subprocess_info *info)
222 {
223         if (info->cleanup)
224                 (*info->cleanup)(info);
225         kfree(info);
226 }
227 EXPORT_SYMBOL(call_usermodehelper_freeinfo);
228
229 /* Keventd can't block, but this (a child) can. */
230 static int wait_for_helper(void *data)
231 {
232         struct subprocess_info *sub_info = data;
233         pid_t pid;
234
235         /* If SIGCLD is ignored sys_wait4 won't populate the status. */
236         spin_lock_irq(&current->sighand->siglock);
237         current->sighand->action[SIGCHLD-1].sa.sa_handler = SIG_DFL;
238         spin_unlock_irq(&current->sighand->siglock);
239
240         pid = kernel_thread(____call_usermodehelper, sub_info, SIGCHLD);
241         if (pid < 0) {
242                 sub_info->retval = pid;
243         } else {
244                 int ret = -ECHILD;
245                 /*
246                  * Normally it is bogus to call wait4() from in-kernel because
247                  * wait4() wants to write the exit code to a userspace address.
248                  * But wait_for_helper() always runs as keventd, and put_user()
249                  * to a kernel address works OK for kernel threads, due to their
250                  * having an mm_segment_t which spans the entire address space.
251                  *
252                  * Thus the __user pointer cast is valid here.
253                  */
254                 sys_wait4(pid, (int __user *)&ret, 0, NULL);
255
256                 /*
257                  * If ret is 0, either ____call_usermodehelper failed and the
258                  * real error code is already in sub_info->retval or
259                  * sub_info->retval is 0 anyway, so don't mess with it then.
260                  */
261                 if (ret)
262                         sub_info->retval = ret;
263         }
264
265         complete(sub_info->complete);
266         return 0;
267 }
268
269 /* This is run by khelper thread  */
270 static void __call_usermodehelper(struct work_struct *work)
271 {
272         struct subprocess_info *sub_info =
273                 container_of(work, struct subprocess_info, work);
274         enum umh_wait wait = sub_info->wait;
275         pid_t pid;
276
277         /* CLONE_VFORK: wait until the usermode helper has execve'd
278          * successfully We need the data structures to stay around
279          * until that is done.  */
280         if (wait == UMH_WAIT_PROC)
281                 pid = kernel_thread(wait_for_helper, sub_info,
282                                     CLONE_FS | CLONE_FILES | SIGCHLD);
283         else
284                 pid = kernel_thread(____call_usermodehelper, sub_info,
285                                     CLONE_VFORK | SIGCHLD);
286
287         switch (wait) {
288         case UMH_NO_WAIT:
289                 call_usermodehelper_freeinfo(sub_info);
290                 break;
291
292         case UMH_WAIT_PROC:
293                 if (pid > 0)
294                         break;
295                 /* FALLTHROUGH */
296         case UMH_WAIT_EXEC:
297                 if (pid < 0)
298                         sub_info->retval = pid;
299                 complete(sub_info->complete);
300         }
301 }
302
303 /*
304  * If set, call_usermodehelper_exec() will exit immediately returning -EBUSY
305  * (used for preventing user land processes from being created after the user
306  * land has been frozen during a system-wide hibernation or suspend operation).
307  */
308 static int usermodehelper_disabled = 1;
309
310 /* Number of helpers running */
311 static atomic_t running_helpers = ATOMIC_INIT(0);
312
313 /*
314  * Wait queue head used by usermodehelper_pm_callback() to wait for all running
315  * helpers to finish.
316  */
317 static DECLARE_WAIT_QUEUE_HEAD(running_helpers_waitq);
318
319 /*
320  * Time to wait for running_helpers to become zero before the setting of
321  * usermodehelper_disabled in usermodehelper_pm_callback() fails
322  */
323 #define RUNNING_HELPERS_TIMEOUT (5 * HZ)
324
325 /**
326  * usermodehelper_disable - prevent new helpers from being started
327  */
328 int usermodehelper_disable(void)
329 {
330         long retval;
331
332         usermodehelper_disabled = 1;
333         smp_mb();
334         /*
335          * From now on call_usermodehelper_exec() won't start any new
336          * helpers, so it is sufficient if running_helpers turns out to
337          * be zero at one point (it may be increased later, but that
338          * doesn't matter).
339          */
340         retval = wait_event_timeout(running_helpers_waitq,
341                                         atomic_read(&running_helpers) == 0,
342                                         RUNNING_HELPERS_TIMEOUT);
343         if (retval)
344                 return 0;
345
346         usermodehelper_disabled = 0;
347         return -EAGAIN;
348 }
349
350 /**
351  * usermodehelper_enable - allow new helpers to be started again
352  */
353 void usermodehelper_enable(void)
354 {
355         usermodehelper_disabled = 0;
356 }
357
358 /**
359  * usermodehelper_is_disabled - check if new helpers are allowed to be started
360  */
361 bool usermodehelper_is_disabled(void)
362 {
363         return usermodehelper_disabled;
364 }
365 EXPORT_SYMBOL_GPL(usermodehelper_is_disabled);
366
367 static void helper_lock(void)
368 {
369         atomic_inc(&running_helpers);
370         smp_mb__after_atomic_inc();
371 }
372
373 static void helper_unlock(void)
374 {
375         if (atomic_dec_and_test(&running_helpers))
376                 wake_up(&running_helpers_waitq);
377 }
378
379 /**
380  * call_usermodehelper_setup - prepare to call a usermode helper
381  * @path: path to usermode executable
382  * @argv: arg vector for process
383  * @envp: environment for process
384  * @gfp_mask: gfp mask for memory allocation
385  *
386  * Returns either %NULL on allocation failure, or a subprocess_info
387  * structure.  This should be passed to call_usermodehelper_exec to
388  * exec the process and free the structure.
389  */
390 struct subprocess_info *call_usermodehelper_setup(char *path, char **argv,
391                                                   char **envp, gfp_t gfp_mask)
392 {
393         struct subprocess_info *sub_info;
394         sub_info = kzalloc(sizeof(struct subprocess_info), gfp_mask);
395         if (!sub_info)
396                 goto out;
397
398         INIT_WORK(&sub_info->work, __call_usermodehelper);
399         sub_info->path = path;
400         sub_info->argv = argv;
401         sub_info->envp = envp;
402     sub_info->delegated = 0;  // multikernel
403   out:
404         return sub_info;
405 }
406 EXPORT_SYMBOL(call_usermodehelper_setup);
407
408 /**
409  * call_usermodehelper_setfns - set a cleanup/init function
410  * @info: a subprocess_info returned by call_usermodehelper_setup
411  * @cleanup: a cleanup function
412  * @init: an init function
413  * @data: arbitrary context sensitive data
414  *
415  * The init function is used to customize the helper process prior to
416  * exec.  A non-zero return code causes the process to error out, exit,
417  * and return the failure to the calling process
418  *
419  * The cleanup function is just before ethe subprocess_info is about to
420  * be freed.  This can be used for freeing the argv and envp.  The
421  * Function must be runnable in either a process context or the
422  * context in which call_usermodehelper_exec is called.
423  */
424 void call_usermodehelper_setfns(struct subprocess_info *info,
425                     int (*init)(struct subprocess_info *info, struct cred *new),
426                     void (*cleanup)(struct subprocess_info *info),
427                     void *data)
428 {
429         info->cleanup = cleanup;
430         info->init = init;
431         info->data = data;
432 }
433 EXPORT_SYMBOL(call_usermodehelper_setfns);
434
435 /**
436  * call_usermodehelper_exec - start a usermode application
437  * @sub_info: information about the subprocessa
438  * @wait: wait for the application to finish and return status.
439  *        when -1 don't wait at all, but you get no useful error back when
440  *        the program couldn't be exec'ed. This makes it safe to call
441  *        from interrupt context.
442  *
443  * Runs a user-space application.  The application is started
444  * asynchronously if wait is not set, and runs as a child of keventd.
445  * (ie. it runs with full root capabilities).
446  */
447 int call_usermodehelper_exec(struct subprocess_info *sub_info,
448                              enum umh_wait wait)
449 {
450         DECLARE_COMPLETION_ONSTACK(done);
451         int retval = 0;
452
453         helper_lock();
454         if (sub_info->path[0] == '\0')
455                 goto out;
456
457         if (!khelper_wq || usermodehelper_disabled) {
458                 retval = -EBUSY;
459                 goto out;
460         }
461
462         sub_info->complete = &done;
463         sub_info->wait = wait;
464
465         queue_work(khelper_wq, &sub_info->work);
466         if (wait == UMH_NO_WAIT)        /* task has freed sub_info */
467                 goto unlock;
468         wait_for_completion(&done);
469         retval = sub_info->retval;
470
471 out:
472         call_usermodehelper_freeinfo(sub_info);
473 unlock:
474         helper_unlock();
475         return retval;
476 }
477 EXPORT_SYMBOL(call_usermodehelper_exec);
478
479 static int proc_cap_handler(struct ctl_table *table, int write,
480                          void __user *buffer, size_t *lenp, loff_t *ppos)
481 {
482         struct ctl_table t;
483         unsigned long cap_array[_KERNEL_CAPABILITY_U32S];
484         kernel_cap_t new_cap;
485         int err, i;
486
487         if (write && (!capable(CAP_SETPCAP) ||
488                       !capable(CAP_SYS_MODULE)))
489                 return -EPERM;
490
491         /*
492          * convert from the global kernel_cap_t to the ulong array to print to
493          * userspace if this is a read.
494          */
495         spin_lock(&umh_sysctl_lock);
496         for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)  {
497                 if (table->data == CAP_BSET)
498                         cap_array[i] = usermodehelper_bset.cap[i];
499                 else if (table->data == CAP_PI)
500                         cap_array[i] = usermodehelper_inheritable.cap[i];
501                 else
502                         BUG();
503         }
504         spin_unlock(&umh_sysctl_lock);
505
506         t = *table;
507         t.data = &cap_array;
508
509         /*
510          * actually read or write and array of ulongs from userspace.  Remember
511          * these are least significant 32 bits first
512          */
513         err = proc_doulongvec_minmax(&t, write, buffer, lenp, ppos);
514         if (err < 0)
515                 return err;
516
517         /*
518          * convert from the sysctl array of ulongs to the kernel_cap_t
519          * internal representation
520          */
521         for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)
522                 new_cap.cap[i] = cap_array[i];
523
524         /*
525          * Drop everything not in the new_cap (but don't add things)
526          */
527         spin_lock(&umh_sysctl_lock);
528         if (write) {
529                 if (table->data == CAP_BSET)
530                         usermodehelper_bset = cap_intersect(usermodehelper_bset, new_cap);
531                 if (table->data == CAP_PI)
532                         usermodehelper_inheritable = cap_intersect(usermodehelper_inheritable, new_cap);
533         }
534         spin_unlock(&umh_sysctl_lock);
535
536         return 0;
537 }
538
539 struct ctl_table usermodehelper_table[] = {
540         {
541                 .procname       = "bset",
542                 .data           = CAP_BSET,
543                 .maxlen         = _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
544                 .mode           = 0600,
545                 .proc_handler   = proc_cap_handler,
546         },
547         {
548                 .procname       = "inheritable",
549                 .data           = CAP_PI,
550                 .maxlen         = _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
551                 .mode           = 0600,
552                 .proc_handler   = proc_cap_handler,
553         },
554         { }
555 };
556
557 void __init usermodehelper_init(void)
558 {
559         khelper_wq = create_singlethread_workqueue("khelper");
560         BUG_ON(!khelper_wq);
561 }