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