PM: disable usermode helper before hibernation and suspend
[safe/jmp/linux-2.6] / 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/mnt_namespace.h>
28 #include <linux/completion.h>
29 #include <linux/file.h>
30 #include <linux/workqueue.h>
31 #include <linux/security.h>
32 #include <linux/mount.h>
33 #include <linux/kernel.h>
34 #include <linux/init.h>
35 #include <linux/resource.h>
36 #include <linux/notifier.h>
37 #include <linux/suspend.h>
38 #include <asm/uaccess.h>
39
40 extern int max_threads;
41
42 static struct workqueue_struct *khelper_wq;
43
44 /*
45  * If set, both call_usermodehelper_keys() and call_usermodehelper_pipe() exit
46  * immediately returning -EBUSY.  Used for preventing user land processes from
47  * being created after the user land has been frozen during a system-wide
48  * hibernation or suspend operation.
49  */
50 static int usermodehelper_disabled;
51
52 #ifdef CONFIG_KMOD
53
54 /*
55         modprobe_path is set via /proc/sys.
56 */
57 char modprobe_path[KMOD_PATH_LEN] = "/sbin/modprobe";
58
59 /**
60  * request_module - try to load a kernel module
61  * @fmt:     printf style format string for the name of the module
62  * @varargs: arguements as specified in the format string
63  *
64  * Load a module using the user mode module loader. The function returns
65  * zero on success or a negative errno code on failure. Note that a
66  * successful module load does not mean the module did not then unload
67  * and exit on an error of its own. Callers must check that the service
68  * they requested is now available not blindly invoke it.
69  *
70  * If module auto-loading support is disabled then this function
71  * becomes a no-operation.
72  */
73 int request_module(const char *fmt, ...)
74 {
75         va_list args;
76         char module_name[MODULE_NAME_LEN];
77         unsigned int max_modprobes;
78         int ret;
79         char *argv[] = { modprobe_path, "-q", "--", module_name, NULL };
80         static char *envp[] = { "HOME=/",
81                                 "TERM=linux",
82                                 "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
83                                 NULL };
84         static atomic_t kmod_concurrent = ATOMIC_INIT(0);
85 #define MAX_KMOD_CONCURRENT 50  /* Completely arbitrary value - KAO */
86         static int kmod_loop_msg;
87
88         va_start(args, fmt);
89         ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
90         va_end(args);
91         if (ret >= MODULE_NAME_LEN)
92                 return -ENAMETOOLONG;
93
94         /* If modprobe needs a service that is in a module, we get a recursive
95          * loop.  Limit the number of running kmod threads to max_threads/2 or
96          * MAX_KMOD_CONCURRENT, whichever is the smaller.  A cleaner method
97          * would be to run the parents of this process, counting how many times
98          * kmod was invoked.  That would mean accessing the internals of the
99          * process tables to get the command line, proc_pid_cmdline is static
100          * and it is not worth changing the proc code just to handle this case. 
101          * KAO.
102          *
103          * "trace the ppid" is simple, but will fail if someone's
104          * parent exits.  I think this is as good as it gets. --RR
105          */
106         max_modprobes = min(max_threads/2, MAX_KMOD_CONCURRENT);
107         atomic_inc(&kmod_concurrent);
108         if (atomic_read(&kmod_concurrent) > max_modprobes) {
109                 /* We may be blaming an innocent here, but unlikely */
110                 if (kmod_loop_msg++ < 5)
111                         printk(KERN_ERR
112                                "request_module: runaway loop modprobe %s\n",
113                                module_name);
114                 atomic_dec(&kmod_concurrent);
115                 return -ENOMEM;
116         }
117
118         ret = call_usermodehelper(modprobe_path, argv, envp, 1);
119         atomic_dec(&kmod_concurrent);
120         return ret;
121 }
122 EXPORT_SYMBOL(request_module);
123 #endif /* CONFIG_KMOD */
124
125 struct subprocess_info {
126         struct work_struct work;
127         struct completion *complete;
128         char *path;
129         char **argv;
130         char **envp;
131         struct key *ring;
132         enum umh_wait wait;
133         int retval;
134         struct file *stdin;
135         void (*cleanup)(char **argv, char **envp);
136 };
137
138 /*
139  * This is the task which runs the usermode application
140  */
141 static int ____call_usermodehelper(void *data)
142 {
143         struct subprocess_info *sub_info = data;
144         struct key *new_session, *old_session;
145         int retval;
146
147         /* Unblock all signals and set the session keyring. */
148         new_session = key_get(sub_info->ring);
149         spin_lock_irq(&current->sighand->siglock);
150         old_session = __install_session_keyring(current, new_session);
151         flush_signal_handlers(current, 1);
152         sigemptyset(&current->blocked);
153         recalc_sigpending();
154         spin_unlock_irq(&current->sighand->siglock);
155
156         key_put(old_session);
157
158         /* Install input pipe when needed */
159         if (sub_info->stdin) {
160                 struct files_struct *f = current->files;
161                 struct fdtable *fdt;
162                 /* no races because files should be private here */
163                 sys_close(0);
164                 fd_install(0, sub_info->stdin);
165                 spin_lock(&f->file_lock);
166                 fdt = files_fdtable(f);
167                 FD_SET(0, fdt->open_fds);
168                 FD_CLR(0, fdt->close_on_exec);
169                 spin_unlock(&f->file_lock);
170
171                 /* and disallow core files too */
172                 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){0, 0};
173         }
174
175         /* We can run anywhere, unlike our parent keventd(). */
176         set_cpus_allowed(current, CPU_MASK_ALL);
177
178         /*
179          * Our parent is keventd, which runs with elevated scheduling priority.
180          * Avoid propagating that into the userspace child.
181          */
182         set_user_nice(current, 0);
183
184         retval = -EPERM;
185         if (current->fs->root)
186                 retval = kernel_execve(sub_info->path,
187                                 sub_info->argv, sub_info->envp);
188
189         /* Exec failed? */
190         sub_info->retval = retval;
191         do_exit(0);
192 }
193
194 void call_usermodehelper_freeinfo(struct subprocess_info *info)
195 {
196         if (info->cleanup)
197                 (*info->cleanup)(info->argv, info->envp);
198         kfree(info);
199 }
200 EXPORT_SYMBOL(call_usermodehelper_freeinfo);
201
202 /* Keventd can't block, but this (a child) can. */
203 static int wait_for_helper(void *data)
204 {
205         struct subprocess_info *sub_info = data;
206         pid_t pid;
207
208         /* Install a handler: if SIGCLD isn't handled sys_wait4 won't
209          * populate the status, but will return -ECHILD. */
210         allow_signal(SIGCHLD);
211
212         pid = kernel_thread(____call_usermodehelper, sub_info, SIGCHLD);
213         if (pid < 0) {
214                 sub_info->retval = pid;
215         } else {
216                 int ret;
217
218                 /*
219                  * Normally it is bogus to call wait4() from in-kernel because
220                  * wait4() wants to write the exit code to a userspace address.
221                  * But wait_for_helper() always runs as keventd, and put_user()
222                  * to a kernel address works OK for kernel threads, due to their
223                  * having an mm_segment_t which spans the entire address space.
224                  *
225                  * Thus the __user pointer cast is valid here.
226                  */
227                 sys_wait4(pid, (int __user *)&ret, 0, NULL);
228
229                 /*
230                  * If ret is 0, either ____call_usermodehelper failed and the
231                  * real error code is already in sub_info->retval or
232                  * sub_info->retval is 0 anyway, so don't mess with it then.
233                  */
234                 if (ret)
235                         sub_info->retval = ret;
236         }
237
238         if (sub_info->wait == UMH_NO_WAIT)
239                 call_usermodehelper_freeinfo(sub_info);
240         else
241                 complete(sub_info->complete);
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         pid_t pid;
251         enum umh_wait wait = sub_info->wait;
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 || wait == UMH_NO_WAIT)
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                 break;
266
267         case UMH_WAIT_PROC:
268                 if (pid > 0)
269                         break;
270                 sub_info->retval = pid;
271                 /* FALLTHROUGH */
272
273         case UMH_WAIT_EXEC:
274                 complete(sub_info->complete);
275         }
276 }
277
278 static int usermodehelper_pm_callback(struct notifier_block *nfb,
279                                         unsigned long action,
280                                         void *ignored)
281 {
282         switch (action) {
283         case PM_HIBERNATION_PREPARE:
284         case PM_SUSPEND_PREPARE:
285                 usermodehelper_disabled = 1;
286                 return NOTIFY_OK;
287         case PM_POST_HIBERNATION:
288         case PM_POST_SUSPEND:
289                 usermodehelper_disabled = 0;
290                 return NOTIFY_OK;
291         }
292
293         return NOTIFY_DONE;
294 }
295
296 /**
297  * call_usermodehelper_setup - prepare to call a usermode helper
298  * @path - path to usermode executable
299  * @argv - arg vector for process
300  * @envp - environment for process
301  *
302  * Returns either NULL on allocation failure, or a subprocess_info
303  * structure.  This should be passed to call_usermodehelper_exec to
304  * exec the process and free the structure.
305  */
306 struct subprocess_info *call_usermodehelper_setup(char *path,
307                                                   char **argv, char **envp)
308 {
309         struct subprocess_info *sub_info;
310         sub_info = kzalloc(sizeof(struct subprocess_info),  GFP_ATOMIC);
311         if (!sub_info)
312                 goto out;
313
314         INIT_WORK(&sub_info->work, __call_usermodehelper);
315         sub_info->path = path;
316         sub_info->argv = argv;
317         sub_info->envp = envp;
318
319   out:
320         return sub_info;
321 }
322 EXPORT_SYMBOL(call_usermodehelper_setup);
323
324 /**
325  * call_usermodehelper_setkeys - set the session keys for usermode helper
326  * @info: a subprocess_info returned by call_usermodehelper_setup
327  * @session_keyring: the session keyring for the process
328  */
329 void call_usermodehelper_setkeys(struct subprocess_info *info,
330                                  struct key *session_keyring)
331 {
332         info->ring = session_keyring;
333 }
334 EXPORT_SYMBOL(call_usermodehelper_setkeys);
335
336 /**
337  * call_usermodehelper_setcleanup - set a cleanup function
338  * @info: a subprocess_info returned by call_usermodehelper_setup
339  * @cleanup: a cleanup function
340  *
341  * The cleanup function is just befor ethe subprocess_info is about to
342  * be freed.  This can be used for freeing the argv and envp.  The
343  * Function must be runnable in either a process context or the
344  * context in which call_usermodehelper_exec is called.
345  */
346 void call_usermodehelper_setcleanup(struct subprocess_info *info,
347                                     void (*cleanup)(char **argv, char **envp))
348 {
349         info->cleanup = cleanup;
350 }
351 EXPORT_SYMBOL(call_usermodehelper_setcleanup);
352
353 /**
354  * call_usermodehelper_stdinpipe - set up a pipe to be used for stdin
355  * @sub_info: a subprocess_info returned by call_usermodehelper_setup
356  * @filp: set to the write-end of a pipe
357  *
358  * This constructs a pipe, and sets the read end to be the stdin of the
359  * subprocess, and returns the write-end in *@filp.
360  */
361 int call_usermodehelper_stdinpipe(struct subprocess_info *sub_info,
362                                   struct file **filp)
363 {
364         struct file *f;
365
366         f = create_write_pipe();
367         if (IS_ERR(f))
368                 return PTR_ERR(f);
369         *filp = f;
370
371         f = create_read_pipe(f);
372         if (IS_ERR(f)) {
373                 free_write_pipe(*filp);
374                 return PTR_ERR(f);
375         }
376         sub_info->stdin = f;
377
378         return 0;
379 }
380 EXPORT_SYMBOL(call_usermodehelper_stdinpipe);
381
382 /**
383  * call_usermodehelper_exec - start a usermode application
384  * @sub_info: information about the subprocessa
385  * @wait: wait for the application to finish and return status.
386  *        when -1 don't wait at all, but you get no useful error back when
387  *        the program couldn't be exec'ed. This makes it safe to call
388  *        from interrupt context.
389  *
390  * Runs a user-space application.  The application is started
391  * asynchronously if wait is not set, and runs as a child of keventd.
392  * (ie. it runs with full root capabilities).
393  */
394 int call_usermodehelper_exec(struct subprocess_info *sub_info,
395                              enum umh_wait wait)
396 {
397         DECLARE_COMPLETION_ONSTACK(done);
398         int retval;
399
400         if (sub_info->path[0] == '\0') {
401                 retval = 0;
402                 goto out;
403         }
404
405         if (!khelper_wq || usermodehelper_disabled) {
406                 retval = -EBUSY;
407                 goto out;
408         }
409
410         sub_info->complete = &done;
411         sub_info->wait = wait;
412
413         queue_work(khelper_wq, &sub_info->work);
414         if (wait == UMH_NO_WAIT) /* task has freed sub_info */
415                 return 0;
416         wait_for_completion(&done);
417         retval = sub_info->retval;
418
419   out:
420         call_usermodehelper_freeinfo(sub_info);
421         return retval;
422 }
423 EXPORT_SYMBOL(call_usermodehelper_exec);
424
425 /**
426  * call_usermodehelper_pipe - call a usermode helper process with a pipe stdin
427  * @path: path to usermode executable
428  * @argv: arg vector for process
429  * @envp: environment for process
430  * @filp: set to the write-end of a pipe
431  *
432  * This is a simple wrapper which executes a usermode-helper function
433  * with a pipe as stdin.  It is implemented entirely in terms of
434  * lower-level call_usermodehelper_* functions.
435  */
436 int call_usermodehelper_pipe(char *path, char **argv, char **envp,
437                              struct file **filp)
438 {
439         struct subprocess_info *sub_info;
440         int ret;
441
442         sub_info = call_usermodehelper_setup(path, argv, envp);
443         if (sub_info == NULL)
444                 return -ENOMEM;
445
446         ret = call_usermodehelper_stdinpipe(sub_info, filp);
447         if (ret < 0)
448                 goto out;
449
450         return call_usermodehelper_exec(sub_info, 1);
451
452   out:
453         call_usermodehelper_freeinfo(sub_info);
454         return ret;
455 }
456 EXPORT_SYMBOL(call_usermodehelper_pipe);
457
458 void __init usermodehelper_init(void)
459 {
460         khelper_wq = create_singlethread_workqueue("khelper");
461         BUG_ON(!khelper_wq);
462         pm_notifier(usermodehelper_pm_callback, 0);
463 }