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