kern_fork.c revision 1.163.2.1 1 /* $NetBSD: kern_fork.c,v 1.163.2.1 2008/05/10 23:49:03 wrstuden Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2001, 2004, 2006, 2007, 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center, by Charles M. Hannum, and by Andrew Doran.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Copyright (c) 1982, 1986, 1989, 1991, 1993
35 * The Regents of the University of California. All rights reserved.
36 * (c) UNIX System Laboratories, Inc.
37 * All or some portions of this file are derived from material licensed
38 * to the University of California by American Telephone and Telegraph
39 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
40 * the permission of UNIX System Laboratories, Inc.
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)kern_fork.c 8.8 (Berkeley) 2/14/95
67 */
68
69 #include <sys/cdefs.h>
70 __KERNEL_RCSID(0, "$NetBSD: kern_fork.c,v 1.163.2.1 2008/05/10 23:49:03 wrstuden Exp $");
71
72 #include "opt_ktrace.h"
73 #include "opt_multiprocessor.h"
74
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/filedesc.h>
78 #include <sys/kernel.h>
79 #include <sys/malloc.h>
80 #include <sys/pool.h>
81 #include <sys/mount.h>
82 #include <sys/proc.h>
83 #include <sys/ras.h>
84 #include <sys/resourcevar.h>
85 #include <sys/vnode.h>
86 #include <sys/file.h>
87 #include <sys/acct.h>
88 #include <sys/ktrace.h>
89 #include <sys/vmmeter.h>
90 #include <sys/sched.h>
91 #include <sys/signalvar.h>
92 #include <sys/kauth.h>
93 #include <sys/atomic.h>
94 #include <sys/sa.h>
95 #include <sys/syscallargs.h>
96
97 #include <uvm/uvm_extern.h>
98
99 u_int nprocs = 1; /* process 0 */
100
101 /*
102 * Number of ticks to sleep if fork() would fail due to process hitting
103 * limits. Exported in miliseconds to userland via sysctl.
104 */
105 int forkfsleep = 0;
106
107 /*ARGSUSED*/
108 int
109 sys_fork(struct lwp *l, const void *v, register_t *retval)
110 {
111
112 return (fork1(l, 0, SIGCHLD, NULL, 0, NULL, NULL, retval, NULL));
113 }
114
115 /*
116 * vfork(2) system call compatible with 4.4BSD (i.e. BSD with Mach VM).
117 * Address space is not shared, but parent is blocked until child exit.
118 */
119 /*ARGSUSED*/
120 int
121 sys_vfork(struct lwp *l, const void *v, register_t *retval)
122 {
123
124 return (fork1(l, FORK_PPWAIT, SIGCHLD, NULL, 0, NULL, NULL,
125 retval, NULL));
126 }
127
128 /*
129 * New vfork(2) system call for NetBSD, which implements original 3BSD vfork(2)
130 * semantics. Address space is shared, and parent is blocked until child exit.
131 */
132 /*ARGSUSED*/
133 int
134 sys___vfork14(struct lwp *l, const void *v, register_t *retval)
135 {
136
137 return (fork1(l, FORK_PPWAIT|FORK_SHAREVM, SIGCHLD, NULL, 0,
138 NULL, NULL, retval, NULL));
139 }
140
141 /*
142 * Linux-compatible __clone(2) system call.
143 */
144 int
145 sys___clone(struct lwp *l, const struct sys___clone_args *uap, register_t *retval)
146 {
147 /* {
148 syscallarg(int) flags;
149 syscallarg(void *) stack;
150 } */
151 int flags, sig;
152
153 /*
154 * We don't support the CLONE_PID or CLONE_PTRACE flags.
155 */
156 if (SCARG(uap, flags) & (CLONE_PID|CLONE_PTRACE))
157 return (EINVAL);
158
159 /*
160 * Linux enforces CLONE_VM with CLONE_SIGHAND, do same.
161 */
162 if (SCARG(uap, flags) & CLONE_SIGHAND
163 && (SCARG(uap, flags) & CLONE_VM) == 0)
164 return (EINVAL);
165
166 flags = 0;
167
168 if (SCARG(uap, flags) & CLONE_VM)
169 flags |= FORK_SHAREVM;
170 if (SCARG(uap, flags) & CLONE_FS)
171 flags |= FORK_SHARECWD;
172 if (SCARG(uap, flags) & CLONE_FILES)
173 flags |= FORK_SHAREFILES;
174 if (SCARG(uap, flags) & CLONE_SIGHAND)
175 flags |= FORK_SHARESIGS;
176 if (SCARG(uap, flags) & CLONE_VFORK)
177 flags |= FORK_PPWAIT;
178
179 sig = SCARG(uap, flags) & CLONE_CSIGNAL;
180 if (sig < 0 || sig >= _NSIG)
181 return (EINVAL);
182
183 /*
184 * Note that the Linux API does not provide a portable way of
185 * specifying the stack area; the caller must know if the stack
186 * grows up or down. So, we pass a stack size of 0, so that the
187 * code that makes this adjustment is a noop.
188 */
189 return (fork1(l, flags, sig, SCARG(uap, stack), 0,
190 NULL, NULL, retval, NULL));
191 }
192
193 /* print the 'table full' message once per 10 seconds */
194 struct timeval fork_tfmrate = { 10, 0 };
195
196 /*
197 * General fork call. Note that another LWP in the process may call exec()
198 * or exit() while we are forking. It's safe to continue here, because
199 * neither operation will complete until all LWPs have exited the process.
200 */
201 int
202 fork1(struct lwp *l1, int flags, int exitsig, void *stack, size_t stacksize,
203 void (*func)(void *), void *arg, register_t *retval,
204 struct proc **rnewprocp)
205 {
206 struct proc *p1, *p2, *parent;
207 struct plimit *p1_lim;
208 uid_t uid;
209 struct lwp *l2;
210 int count;
211 vaddr_t uaddr;
212 bool inmem;
213 int tmp;
214 int tnprocs;
215 int error = 0;
216
217 p1 = l1->l_proc;
218 uid = kauth_cred_getuid(l1->l_cred);
219 tnprocs = atomic_inc_uint_nv(&nprocs);
220
221 /*
222 * Although process entries are dynamically created, we still keep
223 * a global limit on the maximum number we will create.
224 */
225 if (__predict_false(tnprocs >= maxproc))
226 error = -1;
227 else
228 error = kauth_authorize_process(l1->l_cred,
229 KAUTH_PROCESS_FORK, p1, KAUTH_ARG(tnprocs), NULL, NULL);
230
231 if (error) {
232 static struct timeval lasttfm;
233 atomic_dec_uint(&nprocs);
234 if (ratecheck(&lasttfm, &fork_tfmrate))
235 tablefull("proc", "increase kern.maxproc or NPROC");
236 if (forkfsleep)
237 (void)tsleep(&nprocs, PUSER, "forkmx", forkfsleep);
238 return (EAGAIN);
239 }
240
241 /*
242 * Enforce limits.
243 */
244 count = chgproccnt(uid, 1);
245 if (uid != 0 &&
246 __predict_false(count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
247 (void)chgproccnt(uid, -1);
248 atomic_dec_uint(&nprocs);
249 if (forkfsleep)
250 (void)tsleep(&nprocs, PUSER, "forkulim", forkfsleep);
251 return (EAGAIN);
252 }
253
254 /*
255 * Allocate virtual address space for the U-area now, while it
256 * is still easy to abort the fork operation if we're out of
257 * kernel virtual address space. The actual U-area pages will
258 * be allocated and wired in uvm_fork() if needed.
259 */
260
261 inmem = uvm_uarea_alloc(&uaddr);
262 if (__predict_false(uaddr == 0)) {
263 (void)chgproccnt(uid, -1);
264 atomic_dec_uint(&nprocs);
265 return (ENOMEM);
266 }
267
268 /*
269 * We are now committed to the fork. From here on, we may
270 * block on resources, but resource allocation may NOT fail.
271 */
272
273 /* Allocate new proc. */
274 p2 = proc_alloc();
275
276 /*
277 * Make a proc table entry for the new process.
278 * Start by zeroing the section of proc that is zero-initialized,
279 * then copy the section that is copied directly from the parent.
280 */
281 memset(&p2->p_startzero, 0,
282 (unsigned) ((char *)&p2->p_endzero - (char *)&p2->p_startzero));
283 memcpy(&p2->p_startcopy, &p1->p_startcopy,
284 (unsigned) ((char *)&p2->p_endcopy - (char *)&p2->p_startcopy));
285
286 CIRCLEQ_INIT(&p2->p_sigpend.sp_info);
287
288 LIST_INIT(&p2->p_lwps);
289 LIST_INIT(&p2->p_sigwaiters);
290
291 /*
292 * Duplicate sub-structures as needed.
293 * Increase reference counts on shared objects.
294 * The p_stats and p_sigacts substructs are set in uvm_fork().
295 * Inherit flags we want to keep. The flags related to SIGCHLD
296 * handling are important in order to keep a consistent behaviour
297 * for the child after the fork.
298 */
299 p2->p_flag = p1->p_flag & (PK_SUGID | PK_NOCLDWAIT | PK_CLDSIGIGN);
300 p2->p_emul = p1->p_emul;
301 p2->p_execsw = p1->p_execsw;
302
303 if (flags & FORK_SYSTEM) {
304 /*
305 * Mark it as a system process. Set P_NOCLDWAIT so that
306 * children are reparented to init(8) when they exit.
307 * init(8) can easily wait them out for us.
308 */
309 p2->p_flag |= (PK_SYSTEM | PK_NOCLDWAIT);
310 }
311
312 mutex_init(&p2->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
313 mutex_init(&p2->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
314 rw_init(&p2->p_reflock);
315 cv_init(&p2->p_waitcv, "wait");
316 cv_init(&p2->p_lwpcv, "lwpwait");
317
318 /*
319 * Share a lock between the processes if they are to share signal
320 * state: we must synchronize access to it.
321 */
322 if (flags & FORK_SHARESIGS) {
323 p2->p_lock = p1->p_lock;
324 mutex_obj_hold(p1->p_lock);
325 } else
326 p2->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
327
328 kauth_proc_fork(p1, p2);
329
330 p2->p_raslist = NULL;
331 #if defined(__HAVE_RAS)
332 ras_fork(p1, p2);
333 #endif
334
335 /* bump references to the text vnode (for procfs) */
336 p2->p_textvp = p1->p_textvp;
337 if (p2->p_textvp)
338 VREF(p2->p_textvp);
339
340 if (flags & FORK_SHAREFILES)
341 fd_share(p2);
342 else if (flags & FORK_CLEANFILES)
343 p2->p_fd = fd_init(NULL);
344 else
345 p2->p_fd = fd_copy();
346
347 if (flags & FORK_SHARECWD)
348 cwdshare(p2);
349 else
350 p2->p_cwdi = cwdinit();
351
352 /*
353 * p_limit (rlimit stuff) is usually copy-on-write, so we just need
354 * to bump pl_refcnt.
355 * However in some cases (see compat irix, and plausibly from clone)
356 * the parent and child share limits - in which case nothing else
357 * must have a copy of the limits (PL_SHAREMOD is set).
358 */
359 if (__predict_false(flags & FORK_SHARELIMIT))
360 lim_privatise(p1, 1);
361 p1_lim = p1->p_limit;
362 if (p1_lim->pl_flags & PL_WRITEABLE && !(flags & FORK_SHARELIMIT))
363 p2->p_limit = lim_copy(p1_lim);
364 else {
365 lim_addref(p1_lim);
366 p2->p_limit = p1_lim;
367 }
368
369 p2->p_sflag = ((flags & FORK_PPWAIT) ? PS_PPWAIT : 0);
370 p2->p_lflag = 0;
371 p2->p_slflag = 0;
372 parent = (flags & FORK_NOWAIT) ? initproc : p1;
373 p2->p_pptr = parent;
374 LIST_INIT(&p2->p_children);
375
376 p2->p_aio = NULL;
377
378 #ifdef KTRACE
379 /*
380 * Copy traceflag and tracefile if enabled.
381 * If not inherited, these were zeroed above.
382 */
383 if (p1->p_traceflag & KTRFAC_INHERIT) {
384 mutex_enter(&ktrace_lock);
385 p2->p_traceflag = p1->p_traceflag;
386 if ((p2->p_tracep = p1->p_tracep) != NULL)
387 ktradref(p2);
388 mutex_exit(&ktrace_lock);
389 }
390 #endif
391
392 /*
393 * Create signal actions for the child process.
394 */
395 p2->p_sigacts = sigactsinit(p1, flags & FORK_SHARESIGS);
396 mutex_enter(p1->p_lock);
397 p2->p_sflag |=
398 (p1->p_sflag & (PS_STOPFORK | PS_STOPEXEC | PS_NOCLDSTOP));
399 sched_proc_fork(p1, p2);
400 mutex_exit(p1->p_lock);
401
402 p2->p_stflag = p1->p_stflag;
403
404 /*
405 * p_stats.
406 * Copy parts of p_stats, and zero out the rest.
407 */
408 p2->p_stats = pstatscopy(p1->p_stats);
409
410 /*
411 * If emulation has process fork hook, call it now.
412 */
413 if (p2->p_emul->e_proc_fork)
414 (*p2->p_emul->e_proc_fork)(p2, p1, flags);
415
416 /*
417 * ...and finally, any other random fork hooks that subsystems
418 * might have registered.
419 */
420 doforkhooks(p2, p1);
421
422 /*
423 * This begins the section where we must prevent the parent
424 * from being swapped.
425 */
426 uvm_lwp_hold(l1);
427 uvm_proc_fork(p1, p2, (flags & FORK_SHAREVM) ? true : false);
428
429 /*
430 * Finish creating the child process.
431 * It will return through a different path later.
432 */
433 lwp_create(l1, p2, uaddr, inmem, 0, stack, stacksize,
434 (func != NULL) ? func : child_return, arg, &l2,
435 l1->l_class);
436
437 /*
438 * It's now safe for the scheduler and other processes to see the
439 * child process.
440 */
441 mutex_enter(proc_lock);
442
443 if (p1->p_session->s_ttyvp != NULL && p1->p_lflag & PL_CONTROLT)
444 p2->p_lflag |= PL_CONTROLT;
445
446 LIST_INSERT_HEAD(&parent->p_children, p2, p_sibling);
447 p2->p_exitsig = exitsig; /* signal for parent on exit */
448
449 LIST_INSERT_AFTER(p1, p2, p_pglist);
450 LIST_INSERT_HEAD(&allproc, p2, p_list);
451
452 p2->p_trace_enabled = trace_is_enabled(p2);
453 #ifdef __HAVE_SYSCALL_INTERN
454 (*p2->p_emul->e_syscall_intern)(p2);
455 #endif
456
457 /*
458 * Update stats now that we know the fork was successful.
459 */
460 uvmexp.forks++;
461 if (flags & FORK_PPWAIT)
462 uvmexp.forks_ppwait++;
463 if (flags & FORK_SHAREVM)
464 uvmexp.forks_sharevm++;
465
466 /*
467 * Pass a pointer to the new process to the caller.
468 */
469 if (rnewprocp != NULL)
470 *rnewprocp = p2;
471
472 if (ktrpoint(KTR_EMUL))
473 p2->p_traceflag |= KTRFAC_TRC_EMUL;
474
475 /*
476 * Now can be swapped.
477 */
478 uvm_lwp_rele(l1);
479
480 /*
481 * Notify any interested parties about the new process.
482 */
483 if (!SLIST_EMPTY(&p1->p_klist)) {
484 mutex_exit(proc_lock);
485 KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
486 mutex_enter(proc_lock);
487 }
488
489 /*
490 * Make child runnable, set start time, and add to run queue except
491 * if the parent requested the child to start in SSTOP state.
492 */
493 tmp = (p2->p_userret != NULL ? LW_WUSERRET : 0);
494 mutex_enter(p2->p_lock);
495
496 getmicrotime(&p2->p_stats->p_start);
497 p2->p_acflag = AFORK;
498 if (p2->p_sflag & PS_STOPFORK) {
499 lwp_lock(l2);
500 p2->p_nrlwps = 0;
501 p2->p_stat = SSTOP;
502 p2->p_waited = 0;
503 p1->p_nstopchild++;
504 l2->l_stat = LSSTOP;
505 l2->l_flag |= tmp;
506 lwp_unlock(l2);
507 } else {
508 p2->p_nrlwps = 1;
509 p2->p_stat = SACTIVE;
510 lwp_lock(l2);
511 l2->l_stat = LSRUN;
512 l2->l_flag |= tmp;
513 sched_enqueue(l2, false);
514 lwp_unlock(l2);
515 }
516
517 mutex_exit(proc_lock);
518
519 /*
520 * Start profiling.
521 */
522 if ((p2->p_stflag & PST_PROFIL) != 0) {
523 mutex_spin_enter(&p2->p_stmutex);
524 startprofclock(p2);
525 mutex_spin_exit(&p2->p_stmutex);
526 }
527
528
529 /*
530 * Preserve synchronization semantics of vfork. If waiting for
531 * child to exec or exit, set PS_PPWAIT on child, and sleep on our
532 * proc (in case of exit).
533 */
534 if (flags & FORK_PPWAIT)
535 while (p2->p_sflag & PS_PPWAIT)
536 cv_wait(&p1->p_waitcv, p2->p_lock);
537
538 mutex_exit(p2->p_lock);
539
540 /*
541 * Return child pid to parent process,
542 * marking us as parent via retval[1].
543 */
544 if (retval != NULL) {
545 retval[0] = p2->p_pid;
546 retval[1] = 0;
547 }
548
549 return (0);
550 }
551