xref: /netbsd/sys/kern/kern_fork.c (revision c4a72b64)
1 /*	$NetBSD: kern_fork.c,v 1.101 2002/12/05 16:24:46 jdolecek Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999, 2001 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  *
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. All advertising materials mentioning features or use of this software
58  *    must display the following acknowledgement:
59  *	This product includes software developed by the University of
60  *	California, Berkeley and its contributors.
61  * 4. Neither the name of the University nor the names of its contributors
62  *    may be used to endorse or promote products derived from this software
63  *    without specific prior written permission.
64  *
65  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
66  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
69  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
73  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
74  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
75  * SUCH DAMAGE.
76  *
77  *	@(#)kern_fork.c	8.8 (Berkeley) 2/14/95
78  */
79 
80 #include <sys/cdefs.h>
81 __KERNEL_RCSID(0, "$NetBSD: kern_fork.c,v 1.101 2002/12/05 16:24:46 jdolecek Exp $");
82 
83 #include "opt_ktrace.h"
84 #include "opt_systrace.h"
85 #include "opt_multiprocessor.h"
86 
87 #include <sys/param.h>
88 #include <sys/systm.h>
89 #include <sys/filedesc.h>
90 #include <sys/kernel.h>
91 #include <sys/malloc.h>
92 #include <sys/pool.h>
93 #include <sys/mount.h>
94 #include <sys/proc.h>
95 #include <sys/ras.h>
96 #include <sys/resourcevar.h>
97 #include <sys/vnode.h>
98 #include <sys/file.h>
99 #include <sys/acct.h>
100 #include <sys/ktrace.h>
101 #include <sys/vmmeter.h>
102 #include <sys/sched.h>
103 #include <sys/signalvar.h>
104 #include <sys/systrace.h>
105 
106 #include <sys/syscallargs.h>
107 
108 #include <uvm/uvm_extern.h>
109 
110 
111 int	nprocs = 1;		/* process 0 */
112 
113 /*ARGSUSED*/
114 int
115 sys_fork(struct proc *p, void *v, register_t *retval)
116 {
117 
118 	return (fork1(p, 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 proc *p, void *v, register_t *retval)
128 {
129 
130 	return (fork1(p, 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 proc *p, void *v, register_t *retval)
141 {
142 
143 	return (fork1(p, 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 proc *p, void *v, register_t *retval)
152 {
153 	struct sys___clone_args /* {
154 		syscallarg(int) flags;
155 		syscallarg(void *) stack;
156 	} */ *uap = v;
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 	flags = 0;
166 
167 	if (SCARG(uap, flags) & CLONE_VM)
168 		flags |= FORK_SHAREVM;
169 	if (SCARG(uap, flags) & CLONE_FS)
170 		flags |= FORK_SHARECWD;
171 	if (SCARG(uap, flags) & CLONE_FILES)
172 		flags |= FORK_SHAREFILES;
173 	if (SCARG(uap, flags) & CLONE_SIGHAND)
174 		flags |= FORK_SHARESIGS;
175 	if (SCARG(uap, flags) & CLONE_VFORK)
176 		flags |= FORK_PPWAIT;
177 
178 	sig = SCARG(uap, flags) & CLONE_CSIGNAL;
179 	if (sig < 0 || sig >= _NSIG)
180 		return (EINVAL);
181 
182 	/*
183 	 * Note that the Linux API does not provide a portable way of
184 	 * specifying the stack area; the caller must know if the stack
185 	 * grows up or down.  So, we pass a stack size of 0, so that the
186 	 * code that makes this adjustment is a noop.
187 	 */
188 	return (fork1(p, flags, sig, SCARG(uap, stack), 0,
189 	    NULL, NULL, retval, NULL));
190 }
191 
192 /* print the 'table full' message once per 10 seconds */
193 struct timeval fork_tfmrate = { 10, 0 };
194 
195 int
196 fork1(struct proc *p1, int flags, int exitsig, void *stack, size_t stacksize,
197     void (*func)(void *), void *arg, register_t *retval,
198     struct proc **rnewprocp)
199 {
200 	struct proc	*p2, *tp;
201 	uid_t		uid;
202 	int		count, s;
203 	vaddr_t		uaddr;
204 	boolean_t	inmem;
205 	static int	nextpid, pidchecked;
206 
207 	/*
208 	 * Although process entries are dynamically created, we still keep
209 	 * a global limit on the maximum number we will create.  Don't allow
210 	 * a nonprivileged user to use the last few processes; don't let root
211 	 * exceed the limit. The variable nprocs is the current number of
212 	 * processes, maxproc is the limit.
213 	 */
214 	uid = p1->p_cred->p_ruid;
215 	if (__predict_false((nprocs >= maxproc - 5 && uid != 0) ||
216 			    nprocs >= maxproc)) {
217 		static struct timeval lasttfm;
218 
219 		if (ratecheck(&lasttfm, &fork_tfmrate))
220 			tablefull("proc", "increase kern.maxproc or NPROC");
221 		(void)tsleep(&nprocs, PUSER, "forkmx", hz / 2);
222 		return (EAGAIN);
223 	}
224 	nprocs++;
225 
226 	/*
227 	 * Increment the count of procs running with this uid. Don't allow
228 	 * a nonprivileged user to exceed their current limit.
229 	 */
230 	count = chgproccnt(uid, 1);
231 	if (__predict_false(uid != 0 && count >
232 			    p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
233 		(void)chgproccnt(uid, -1);
234 		nprocs--;
235 		(void)tsleep(&nprocs, PUSER, "forkulim", hz / 2);
236 		return (EAGAIN);
237 	}
238 
239 	/*
240 	 * Allocate virtual address space for the U-area now, while it
241 	 * is still easy to abort the fork operation if we're out of
242 	 * kernel virtual address space.  The actual U-area pages will
243 	 * be allocated and wired in uvm_fork() if needed.
244 	 */
245 
246 	inmem = uvm_uarea_alloc(&uaddr);
247 	if (__predict_false(uaddr == 0)) {
248 		(void)chgproccnt(uid, -1);
249 		nprocs--;
250 		return (ENOMEM);
251 	}
252 
253 	/*
254 	 * We are now committed to the fork.  From here on, we may
255 	 * block on resources, but resource allocation may NOT fail.
256 	 */
257 
258 	/* Allocate new proc. */
259 	p2 = pool_get(&proc_pool, PR_WAITOK);
260 
261 	/*
262 	 * Make a proc table entry for the new process.
263 	 * Start by zeroing the section of proc that is zero-initialized,
264 	 * then copy the section that is copied directly from the parent.
265 	 */
266 	memset(&p2->p_startzero, 0,
267 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
268 	memcpy(&p2->p_startcopy, &p1->p_startcopy,
269 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
270 
271 #if !defined(MULTIPROCESSOR)
272 	/*
273 	 * In the single-processor case, all processes will always run
274 	 * on the same CPU.  So, initialize the child's CPU to the parent's
275 	 * now.  In the multiprocessor case, the child's CPU will be
276 	 * initialized in the low-level context switch code when the
277 	 * process runs.
278 	 */
279 	p2->p_cpu = p1->p_cpu;
280 #else
281 	/*
282 	 * zero child's cpu pointer so we don't get trash.
283 	 */
284 	p2->p_cpu = NULL;
285 #endif /* ! MULTIPROCESSOR */
286 
287 	/*
288 	 * Duplicate sub-structures as needed.
289 	 * Increase reference counts on shared objects.
290 	 * The p_stats and p_sigacts substructs are set in uvm_fork().
291 	 */
292 	p2->p_flag = (inmem ? P_INMEM : 0) | (p1->p_flag & P_SUGID);
293 	p2->p_emul = p1->p_emul;
294 	p2->p_execsw = p1->p_execsw;
295 
296 	if (p1->p_flag & P_PROFIL)
297 		startprofclock(p2);
298 	p2->p_cred = pool_get(&pcred_pool, PR_WAITOK);
299 	memcpy(p2->p_cred, p1->p_cred, sizeof(*p2->p_cred));
300 	p2->p_cred->p_refcnt = 1;
301 	crhold(p1->p_ucred);
302 
303 	LIST_INIT(&p2->p_raslist);
304 	p2->p_nras = 0;
305 	simple_lock_init(&p2->p_raslock);
306 #if defined(__HAVE_RAS)
307 	ras_fork(p1, p2);
308 #endif
309 
310 	/* bump references to the text vnode (for procfs) */
311 	p2->p_textvp = p1->p_textvp;
312 	if (p2->p_textvp)
313 		VREF(p2->p_textvp);
314 
315 	if (flags & FORK_SHAREFILES)
316 		fdshare(p1, p2);
317 	else if (flags & FORK_CLEANFILES)
318 		p2->p_fd = fdinit(p1);
319 	else
320 		p2->p_fd = fdcopy(p1);
321 
322 	if (flags & FORK_SHARECWD)
323 		cwdshare(p1, p2);
324 	else
325 		p2->p_cwdi = cwdinit(p1);
326 
327 	/*
328 	 * If p_limit is still copy-on-write, bump refcnt,
329 	 * otherwise get a copy that won't be modified.
330 	 * (If PL_SHAREMOD is clear, the structure is shared
331 	 * copy-on-write.)
332 	 */
333 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
334 		p2->p_limit = limcopy(p1->p_limit);
335 	else {
336 		p2->p_limit = p1->p_limit;
337 		p2->p_limit->p_refcnt++;
338 	}
339 
340 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
341 		p2->p_flag |= P_CONTROLT;
342 	if (flags & FORK_PPWAIT)
343 		p2->p_flag |= P_PPWAIT;
344 	LIST_INSERT_AFTER(p1, p2, p_pglist);
345 	p2->p_pptr = (flags & FORK_NOWAIT) ? initproc : p1;
346 	LIST_INSERT_HEAD(&p2->p_pptr->p_children, p2, p_sibling);
347 	LIST_INIT(&p2->p_children);
348 
349 	callout_init(&p2->p_realit_ch);
350 	callout_init(&p2->p_tsleep_ch);
351 
352 #ifdef KTRACE
353 	/*
354 	 * Copy traceflag and tracefile if enabled.
355 	 * If not inherited, these were zeroed above.
356 	 */
357 	if (p1->p_traceflag & KTRFAC_INHERIT) {
358 		p2->p_traceflag = p1->p_traceflag;
359 		if ((p2->p_tracep = p1->p_tracep) != NULL)
360 			ktradref(p2);
361 	}
362 #endif
363 
364 	scheduler_fork_hook(p1, p2);
365 
366 	/*
367 	 * Create signal actions for the child process.
368 	 */
369 	sigactsinit(p2, p1, flags & FORK_SHARESIGS);
370 
371 	/*
372 	 * If emulation has process fork hook, call it now.
373 	 */
374 	if (p2->p_emul->e_proc_fork)
375 		(*p2->p_emul->e_proc_fork)(p2, p1);
376 
377 	/*
378 	 * This begins the section where we must prevent the parent
379 	 * from being swapped.
380 	 */
381 	PHOLD(p1);
382 
383 	/*
384 	 * Finish creating the child process.  It will return through a
385 	 * different path later.
386 	 */
387 	p2->p_addr = (struct user *)uaddr;
388 	uvm_fork(p1, p2, (flags & FORK_SHAREVM) ? TRUE : FALSE,
389 	    stack, stacksize,
390 	    (func != NULL) ? func : child_return,
391 	    (arg != NULL) ? arg : p2);
392 
393 	/*
394 	 * BEGIN PID ALLOCATION.
395 	 */
396 	s = proclist_lock_write();
397 
398 	/*
399 	 * Find an unused process ID.  We remember a range of unused IDs
400 	 * ready to use (from nextpid+1 through pidchecked-1).
401 	 */
402 	nextpid++;
403  retry:
404 	/*
405 	 * If the process ID prototype has wrapped around,
406 	 * restart somewhat above 0, as the low-numbered procs
407 	 * tend to include daemons that don't exit.
408 	 */
409 	if (nextpid >= PID_MAX) {
410 		nextpid = 500;
411 		pidchecked = 0;
412 	}
413 	if (nextpid >= pidchecked) {
414 		const struct proclist_desc *pd;
415 
416 		pidchecked = PID_MAX;
417 		/*
418 		 * Scan the process lists to check whether this pid
419 		 * is in use.  Remember the lowest pid that's greater
420 		 * than nextpid, so we can avoid checking for a while.
421 		 */
422 		pd = proclists;
423  again:
424 		LIST_FOREACH(tp, pd->pd_list, p_list) {
425 			while (tp->p_pid == nextpid ||
426 			    tp->p_pgrp->pg_id == nextpid ||
427 			    tp->p_session->s_sid == nextpid) {
428 				nextpid++;
429 				if (nextpid >= pidchecked)
430 					goto retry;
431 			}
432 			if (tp->p_pid > nextpid && pidchecked > tp->p_pid)
433 				pidchecked = tp->p_pid;
434 
435 			if (tp->p_pgrp->pg_id > nextpid &&
436 			    pidchecked > tp->p_pgrp->pg_id)
437 				pidchecked = tp->p_pgrp->pg_id;
438 
439 			if (tp->p_session->s_sid > nextpid &&
440 			    pidchecked > tp->p_session->s_sid)
441 				pidchecked = tp->p_session->s_sid;
442 		}
443 
444 		/*
445 		 * If there's another list, scan it.  If we have checked
446 		 * them all, we've found one!
447 		 */
448 		pd++;
449 		if (pd->pd_list != NULL)
450 			goto again;
451 	}
452 
453 	/*
454 	 * Put the proc on allproc before unlocking PID allocation
455 	 * so that waiters won't grab it as soon as we unlock.
456 	 */
457 
458 	p2->p_stat = SIDL;			/* protect against others */
459 	p2->p_pid = nextpid;
460 	p2->p_exitsig = exitsig;		/* signal for parent on exit */
461 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
462 
463 	LIST_INSERT_HEAD(&allproc, p2, p_list);
464 
465 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
466 
467 	/*
468 	 * END PID ALLOCATION.
469 	 */
470 	proclist_unlock_write(s);
471 
472 #ifdef SYSTRACE
473 	/* Tell systrace what's happening. */
474 	if (ISSET(p1->p_flag, P_SYSTRACE))
475 		systrace_sys_fork(p1, p2);
476 #endif
477 
478 #ifdef __HAVE_SYSCALL_INTERN
479 	(*p2->p_emul->e_syscall_intern)(p2);
480 #endif
481 
482 	/*
483 	 * Make child runnable, set start time, and add to run queue
484 	 * except if the parent requested the child to start in SSTOP state.
485 	 */
486 	SCHED_LOCK(s);
487 	p2->p_stats->p_start = time;
488 	p2->p_acflag = AFORK;
489 	if (p1->p_flag & P_STOPFORK) {
490 		p2->p_stat = SSTOP;
491 	} else {
492 		p2->p_stat = SRUN;
493 		setrunqueue(p2);
494 	}
495 	SCHED_UNLOCK(s);
496 
497 	/*
498 	 * Inherit STOPFORK and STOPEXEC flags
499 	 */
500 	if (p1->p_flag & P_STOPFORK)
501 		p2->p_flag |= P_STOPFORK;
502 	if (p1->p_flag & P_STOPEXEC)
503 		p2->p_flag |= P_STOPEXEC;
504 
505 	/*
506 	 * Now can be swapped.
507 	 */
508 	PRELE(p1);
509 
510 	/*
511 	 * Notify any interested parties about the new process.
512 	 */
513 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
514 
515 	/*
516 	 * Update stats now that we know the fork was successful.
517 	 */
518 	uvmexp.forks++;
519 	if (flags & FORK_PPWAIT)
520 		uvmexp.forks_ppwait++;
521 	if (flags & FORK_SHAREVM)
522 		uvmexp.forks_sharevm++;
523 
524 	/*
525 	 * Pass a pointer to the new process to the caller.
526 	 */
527 	if (rnewprocp != NULL)
528 		*rnewprocp = p2;
529 
530 #ifdef KTRACE
531 	if (KTRPOINT(p2, KTR_EMUL))
532 		ktremul(p2);
533 #endif
534 
535 	/*
536 	 * Preserve synchronization semantics of vfork.  If waiting for
537 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
538 	 * proc (in case of exit).
539 	 */
540 	if (flags & FORK_PPWAIT)
541 		while (p2->p_flag & P_PPWAIT)
542 			tsleep(p1, PWAIT, "ppwait", 0);
543 
544 	/*
545 	 * Return child pid to parent process,
546 	 * marking us as parent via retval[1].
547 	 */
548 	if (retval != NULL) {
549 		retval[0] = p2->p_pid;
550 		retval[1] = 0;
551 	}
552 
553 	return (0);
554 }
555 
556 #if defined(MULTIPROCESSOR)
557 /*
558  * XXX This is a slight hack to get newly-formed processes to
559  * XXX acquire the kernel lock as soon as they run.
560  */
561 void
562 proc_trampoline_mp(void)
563 {
564 	struct proc *p;
565 
566 	p = curproc;
567 
568 	SCHED_ASSERT_UNLOCKED();
569 	KERNEL_PROC_LOCK(p);
570 }
571 #endif
572