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