xref: /freebsd/sys/kern/kern_fork.c (revision 71fe318b852b8dfb3e799cb12ef184750f7f8eac)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
39  * $FreeBSD$
40  */
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/sysctl.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/pioctl.h>
55 #include <sys/resourcevar.h>
56 #include <sys/sched.h>
57 #include <sys/syscall.h>
58 #include <sys/vnode.h>
59 #include <sys/acct.h>
60 #include <sys/ktr.h>
61 #include <sys/ktrace.h>
62 #include <sys/kthread.h>
63 #include <sys/unistd.h>
64 #include <sys/jail.h>
65 #include <sys/sx.h>
66 
67 #include <vm/vm.h>
68 #include <vm/pmap.h>
69 #include <vm/vm_map.h>
70 #include <vm/vm_extern.h>
71 #include <vm/uma.h>
72 
73 #include <sys/vmmeter.h>
74 #include <sys/user.h>
75 #include <machine/critical.h>
76 
77 static MALLOC_DEFINE(M_ATFORK, "atfork", "atfork callback");
78 
79 /*
80  * These are the stuctures used to create a callout list for things to do
81  * when forking a process
82  */
83 struct forklist {
84 	forklist_fn function;
85 	TAILQ_ENTRY(forklist) next;
86 };
87 
88 static struct sx fork_list_lock;
89 
90 TAILQ_HEAD(forklist_head, forklist);
91 static struct forklist_head fork_list = TAILQ_HEAD_INITIALIZER(fork_list);
92 
93 #ifndef _SYS_SYSPROTO_H_
94 struct fork_args {
95 	int     dummy;
96 };
97 #endif
98 
99 int forksleep; /* Place for fork1() to sleep on. */
100 
101 static void
102 init_fork_list(void *data __unused)
103 {
104 
105 	sx_init(&fork_list_lock, "fork list");
106 }
107 SYSINIT(fork_list, SI_SUB_INTRINSIC, SI_ORDER_ANY, init_fork_list, NULL);
108 
109 /*
110  * MPSAFE
111  */
112 /* ARGSUSED */
113 int
114 fork(td, uap)
115 	struct thread *td;
116 	struct fork_args *uap;
117 {
118 	int error;
119 	struct proc *p2;
120 
121 	mtx_lock(&Giant);
122 	error = fork1(td, RFFDG | RFPROC, 0, &p2);
123 	if (error == 0) {
124 		td->td_retval[0] = p2->p_pid;
125 		td->td_retval[1] = 0;
126 	}
127 	mtx_unlock(&Giant);
128 	return error;
129 }
130 
131 /*
132  * MPSAFE
133  */
134 /* ARGSUSED */
135 int
136 vfork(td, uap)
137 	struct thread *td;
138 	struct vfork_args *uap;
139 {
140 	int error;
141 	struct proc *p2;
142 
143 	mtx_lock(&Giant);
144 	error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
145 	if (error == 0) {
146 		td->td_retval[0] = p2->p_pid;
147 		td->td_retval[1] = 0;
148 	}
149 	mtx_unlock(&Giant);
150 	return error;
151 }
152 
153 /*
154  * MPSAFE
155  */
156 int
157 rfork(td, uap)
158 	struct thread *td;
159 	struct rfork_args *uap;
160 {
161 	int error;
162 	struct proc *p2;
163 
164 	/* Don't allow kernel only flags. */
165 	if ((uap->flags & RFKERNELONLY) != 0)
166 		return (EINVAL);
167 	mtx_lock(&Giant);
168 	error = fork1(td, uap->flags, 0, &p2);
169 	if (error == 0) {
170 		td->td_retval[0] = p2 ? p2->p_pid : 0;
171 		td->td_retval[1] = 0;
172 	}
173 	mtx_unlock(&Giant);
174 	return error;
175 }
176 
177 
178 int	nprocs = 1;				/* process 0 */
179 int	lastpid = 0;
180 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
181     "Last used PID");
182 
183 /*
184  * Random component to lastpid generation.  We mix in a random factor to make
185  * it a little harder to predict.  We sanity check the modulus value to avoid
186  * doing it in critical paths.  Don't let it be too small or we pointlessly
187  * waste randomness entropy, and don't let it be impossibly large.  Using a
188  * modulus that is too big causes a LOT more process table scans and slows
189  * down fork processing as the pidchecked caching is defeated.
190  */
191 static int randompid = 0;
192 
193 static int
194 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
195 {
196 	int error, pid;
197 
198 	sysctl_wire_old_buffer(req, sizeof(int));
199 	sx_xlock(&allproc_lock);
200 	pid = randompid;
201 	error = sysctl_handle_int(oidp, &pid, 0, req);
202 	if (error == 0 && req->newptr != NULL) {
203 		if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
204 			pid = PID_MAX - 100;
205 		else if (pid < 2)			/* NOP */
206 			pid = 0;
207 		else if (pid < 100)			/* Make it reasonable */
208 			pid = 100;
209 		randompid = pid;
210 	}
211 	sx_xunlock(&allproc_lock);
212 	return (error);
213 }
214 
215 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
216     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
217 
218 int
219 fork1(td, flags, pages, procp)
220 	struct thread *td;			/* parent proc */
221 	int flags;
222 	int pages;
223 	struct proc **procp;			/* child proc */
224 {
225 	struct proc *p2, *pptr;
226 	uid_t uid;
227 	struct proc *newproc;
228 	int trypid;
229 	int ok;
230 	static int pidchecked = 0;
231 	struct forklist *ep;
232 	struct filedesc *fd;
233 	struct proc *p1 = td->td_proc;
234 	struct thread *td2;
235 	struct kse *ke2;
236 	struct ksegrp *kg2;
237 	struct sigacts *newsigacts;
238 	struct procsig *newprocsig;
239 	int error;
240 
241 	GIANT_REQUIRED;
242 
243 	/* Can't copy and clear */
244 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
245 		return (EINVAL);
246 
247 	/*
248 	 * Here we don't create a new process, but we divorce
249 	 * certain parts of a process from itself.
250 	 */
251 	if ((flags & RFPROC) == 0) {
252 		vm_forkproc(td, NULL, NULL, flags);
253 
254 		/*
255 		 * Close all file descriptors.
256 		 */
257 		if (flags & RFCFDG) {
258 			struct filedesc *fdtmp;
259 			fdtmp = fdinit(td);	/* XXXKSE */
260 			fdfree(td);		/* XXXKSE */
261 			p1->p_fd = fdtmp;
262 		}
263 
264 		/*
265 		 * Unshare file descriptors (from parent.)
266 		 */
267 		if (flags & RFFDG) {
268 			FILEDESC_LOCK(p1->p_fd);
269 			if (p1->p_fd->fd_refcnt > 1) {
270 				struct filedesc *newfd;
271 
272 				newfd = fdcopy(td);
273 				FILEDESC_UNLOCK(p1->p_fd);
274 				fdfree(td);
275 				p1->p_fd = newfd;
276 			} else
277 				FILEDESC_UNLOCK(p1->p_fd);
278 		}
279 		*procp = NULL;
280 		return (0);
281 	}
282 
283 	if (p1->p_flag & P_KSES) {
284 		/*
285 		 * Idle the other threads for a second.
286 		 * Since the user space is copied, it must remain stable.
287 		 * In addition, all threads (from the user perspective)
288 		 * need to either be suspended or in the kernel,
289 		 * where they will try restart in the parent and will
290 		 * be aborted in the child.
291 		 */
292 		PROC_LOCK(p1);
293 		if (thread_single(SINGLE_NO_EXIT)) {
294 			/* Abort.. someone else is single threading before us */
295 			PROC_UNLOCK(p1);
296 			return (ERESTART);
297 		}
298 		PROC_UNLOCK(p1);
299 		/*
300 		 * All other activity in this process
301 		 * is now suspended at the user boundary,
302 		 * (or other safe places if we think of any).
303 		 */
304 	}
305 
306 	/* Allocate new proc. */
307 	newproc = uma_zalloc(proc_zone, M_WAITOK);
308 
309 	/*
310 	 * Although process entries are dynamically created, we still keep
311 	 * a global limit on the maximum number we will create.  Don't allow
312 	 * a nonprivileged user to use the last ten processes; don't let root
313 	 * exceed the limit. The variable nprocs is the current number of
314 	 * processes, maxproc is the limit.
315 	 */
316 	sx_xlock(&allproc_lock);
317 	uid = td->td_ucred->cr_ruid;
318 	if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) {
319 		error = EAGAIN;
320 		goto fail;
321 	}
322 
323 	/*
324 	 * Increment the count of procs running with this uid. Don't allow
325 	 * a nonprivileged user to exceed their current limit.
326 	 */
327 	PROC_LOCK(p1);
328 	ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
329 		(uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
330 	PROC_UNLOCK(p1);
331 	if (!ok) {
332 		error = EAGAIN;
333 		goto fail;
334 	}
335 
336 	/*
337 	 * Increment the nprocs resource before blocking can occur.  There
338 	 * are hard-limits as to the number of processes that can run.
339 	 */
340 	nprocs++;
341 
342 	/*
343 	 * Find an unused process ID.  We remember a range of unused IDs
344 	 * ready to use (from lastpid+1 through pidchecked-1).
345 	 *
346 	 * If RFHIGHPID is set (used during system boot), do not allocate
347 	 * low-numbered pids.
348 	 */
349 	trypid = lastpid + 1;
350 	if (flags & RFHIGHPID) {
351 		if (trypid < 10) {
352 			trypid = 10;
353 		}
354 	} else {
355 		if (randompid)
356 			trypid += arc4random() % randompid;
357 	}
358 retry:
359 	/*
360 	 * If the process ID prototype has wrapped around,
361 	 * restart somewhat above 0, as the low-numbered procs
362 	 * tend to include daemons that don't exit.
363 	 */
364 	if (trypid >= PID_MAX) {
365 		trypid = trypid % PID_MAX;
366 		if (trypid < 100)
367 			trypid += 100;
368 		pidchecked = 0;
369 	}
370 	if (trypid >= pidchecked) {
371 		int doingzomb = 0;
372 
373 		pidchecked = PID_MAX;
374 		/*
375 		 * Scan the active and zombie procs to check whether this pid
376 		 * is in use.  Remember the lowest pid that's greater
377 		 * than trypid, so we can avoid checking for a while.
378 		 */
379 		p2 = LIST_FIRST(&allproc);
380 again:
381 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
382 			PROC_LOCK(p2);
383 			while (p2->p_pid == trypid ||
384 			    p2->p_pgrp->pg_id == trypid ||
385 			    p2->p_session->s_sid == trypid) {
386 				trypid++;
387 				if (trypid >= pidchecked) {
388 					PROC_UNLOCK(p2);
389 					goto retry;
390 				}
391 			}
392 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
393 				pidchecked = p2->p_pid;
394 			if (p2->p_pgrp->pg_id > trypid &&
395 			    pidchecked > p2->p_pgrp->pg_id)
396 				pidchecked = p2->p_pgrp->pg_id;
397 			if (p2->p_session->s_sid > trypid &&
398 			    pidchecked > p2->p_session->s_sid)
399 				pidchecked = p2->p_session->s_sid;
400 			PROC_UNLOCK(p2);
401 		}
402 		if (!doingzomb) {
403 			doingzomb = 1;
404 			p2 = LIST_FIRST(&zombproc);
405 			goto again;
406 		}
407 	}
408 
409 	/*
410 	 * RFHIGHPID does not mess with the lastpid counter during boot.
411 	 */
412 	if (flags & RFHIGHPID)
413 		pidchecked = 0;
414 	else
415 		lastpid = trypid;
416 
417 	p2 = newproc;
418 	p2->p_state = PRS_NEW;		/* protect against others */
419 	p2->p_pid = trypid;
420 	LIST_INSERT_HEAD(&allproc, p2, p_list);
421 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
422 	sx_xunlock(&allproc_lock);
423 
424 	/*
425 	 * Malloc things while we don't hold any locks.
426 	 */
427 	if (flags & RFSIGSHARE) {
428 		MALLOC(newsigacts, struct sigacts *,
429 		    sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
430 		newprocsig = NULL;
431 	} else {
432 		newsigacts = NULL;
433 		MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
434 		    M_SUBPROC, M_WAITOK);
435 	}
436 
437 	/*
438 	 * Copy filedesc.
439 	 * XXX: This is busted.  fd*() need to not take proc
440 	 * arguments or something.
441 	 */
442 	if (flags & RFCFDG)
443 		fd = fdinit(td);
444 	else if (flags & RFFDG) {
445 		FILEDESC_LOCK(p1->p_fd);
446 		fd = fdcopy(td);
447 		FILEDESC_UNLOCK(p1->p_fd);
448 	} else
449 		fd = fdshare(p1);
450 
451 	/*
452 	 * Make a proc table entry for the new process.
453 	 * Start by zeroing the section of proc that is zero-initialized,
454 	 * then copy the section that is copied directly from the parent.
455 	 */
456 	td2 = FIRST_THREAD_IN_PROC(p2);
457 	kg2 = FIRST_KSEGRP_IN_PROC(p2);
458 	ke2 = FIRST_KSE_IN_KSEGRP(kg2);
459 
460 	/* Allocate and switch to an alternate kstack if specified */
461 	if (pages != 0)
462 		pmap_new_altkstack(td2, pages);
463 
464 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
465 
466 	bzero(&p2->p_startzero,
467 	    (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
468 	bzero(&ke2->ke_startzero,
469 	    (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
470 	bzero(&td2->td_startzero,
471 	    (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
472 	bzero(&kg2->kg_startzero,
473 	    (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
474 
475 	mtx_init(&p2->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
476 	PROC_LOCK(p2);
477 	PROC_LOCK(p1);
478 
479 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
480 	    (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
481 	bcopy(&td->td_startcopy, &td2->td_startcopy,
482 	    (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
483 	bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
484 	    (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
485 #undef RANGEOF
486 
487 	/* Set up the thread as an active thread (as if runnable). */
488 	ke2->ke_state = KES_THREAD;
489 	ke2->ke_thread = td2;
490 	td2->td_kse = ke2;
491 	td2->td_flags &= ~TDF_UNBOUND; /* For the rest of this syscall. */
492 
493 	/*
494 	 * Duplicate sub-structures as needed.
495 	 * Increase reference counts on shared objects.
496 	 * The p_stats and p_sigacts substructs are set in vm_forkproc.
497 	 */
498 	p2->p_flag = 0;
499 	mtx_lock_spin(&sched_lock);
500 	p2->p_sflag = PS_INMEM;
501 	if (p1->p_sflag & PS_PROFIL)
502 		startprofclock(p2);
503 	/*
504 	 * Allow the scheduler to adjust the priority of the child and
505 	 * parent while we hold the sched_lock.
506 	 */
507 	sched_fork(td->td_ksegrp, kg2);
508 
509 	mtx_unlock_spin(&sched_lock);
510 	p2->p_ucred = crhold(td->td_ucred);
511 	td2->td_ucred = crhold(p2->p_ucred);	/* XXXKSE */
512 
513 	pargs_hold(p2->p_args);
514 
515 	if (flags & RFSIGSHARE) {
516 		p2->p_procsig = p1->p_procsig;
517 		p2->p_procsig->ps_refcnt++;
518 		if (p1->p_sigacts == &p1->p_uarea->u_sigacts) {
519 			/*
520 			 * Set p_sigacts to the new shared structure.
521 			 * Note that this is updating p1->p_sigacts at the
522 			 * same time, since p_sigacts is just a pointer to
523 			 * the shared p_procsig->ps_sigacts.
524 			 */
525 			p2->p_sigacts  = newsigacts;
526 			newsigacts = NULL;
527 			*p2->p_sigacts = p1->p_uarea->u_sigacts;
528 		}
529 	} else {
530 		p2->p_procsig = newprocsig;
531 		newprocsig = NULL;
532 		bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
533 		p2->p_procsig->ps_refcnt = 1;
534 		p2->p_sigacts = NULL;	/* finished in vm_forkproc() */
535 	}
536 	if (flags & RFLINUXTHPN)
537 	        p2->p_sigparent = SIGUSR1;
538 	else
539 	        p2->p_sigparent = SIGCHLD;
540 
541 	/* Bump references to the text vnode (for procfs) */
542 	p2->p_textvp = p1->p_textvp;
543 	if (p2->p_textvp)
544 		VREF(p2->p_textvp);
545 	p2->p_fd = fd;
546 	PROC_UNLOCK(p1);
547 	PROC_UNLOCK(p2);
548 
549 	/*
550 	 * If p_limit is still copy-on-write, bump refcnt,
551 	 * otherwise get a copy that won't be modified.
552 	 * (If PL_SHAREMOD is clear, the structure is shared
553 	 * copy-on-write.)
554 	 */
555 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
556 		p2->p_limit = limcopy(p1->p_limit);
557 	else {
558 		p2->p_limit = p1->p_limit;
559 		p2->p_limit->p_refcnt++;
560 	}
561 
562 	/*
563 	 * Setup linkage for kernel based threading
564 	 */
565 	if((flags & RFTHREAD) != 0) {
566 		mtx_lock(&ppeers_lock);
567 		p2->p_peers = p1->p_peers;
568 		p1->p_peers = p2;
569 		p2->p_leader = p1->p_leader;
570 		mtx_unlock(&ppeers_lock);
571 		PROC_LOCK(p1->p_leader);
572 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
573 			PROC_UNLOCK(p1->p_leader);
574 			/*
575 			 * The task leader is exiting, so process p1 is
576 			 * going to be killed shortly.  Since p1 obviously
577 			 * isn't dead yet, we know that the leader is either
578 			 * sending SIGKILL's to all the processes in this
579 			 * task or is sleeping waiting for all the peers to
580 			 * exit.  We let p1 complete the fork, but we need
581 			 * to go ahead and kill the new process p2 since
582 			 * the task leader may not get a chance to send
583 			 * SIGKILL to it.  We leave it on the list so that
584 			 * the task leader will wait for this new process
585 			 * to commit suicide.
586 			 */
587 			PROC_LOCK(p2);
588 			psignal(p2, SIGKILL);
589 			PROC_UNLOCK(p2);
590 		}
591 	} else {
592 		p2->p_peers = NULL;
593 		p2->p_leader = p2;
594 	}
595 
596 	sx_xlock(&proctree_lock);
597 	PGRP_LOCK(p1->p_pgrp);
598 	PROC_LOCK(p2);
599 	PROC_LOCK(p1);
600 
601 	/*
602 	 * Preserve some more flags in subprocess.  PS_PROFIL has already
603 	 * been preserved.
604 	 */
605 	p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
606 	SESS_LOCK(p1->p_session);
607 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
608 		p2->p_flag |= P_CONTROLT;
609 	SESS_UNLOCK(p1->p_session);
610 	if (flags & RFPPWAIT)
611 		p2->p_flag |= P_PPWAIT;
612 
613 	LIST_INSERT_AFTER(p1, p2, p_pglist);
614 	PGRP_UNLOCK(p1->p_pgrp);
615 	LIST_INIT(&p2->p_children);
616 
617 	callout_init(&p2->p_itcallout, 0);
618 
619 #ifdef KTRACE
620 	/*
621 	 * Copy traceflag and tracefile if enabled.
622 	 */
623 	mtx_lock(&ktrace_mtx);
624 	KASSERT(p2->p_tracep == NULL, ("new process has a ktrace vnode"));
625 	if (p1->p_traceflag & KTRFAC_INHERIT) {
626 		p2->p_traceflag = p1->p_traceflag;
627 		if ((p2->p_tracep = p1->p_tracep) != NULL)
628 			VREF(p2->p_tracep);
629 	}
630 	mtx_unlock(&ktrace_mtx);
631 #endif
632 
633 	/*
634 	 * If PF_FORK is set, the child process inherits the
635 	 * procfs ioctl flags from its parent.
636 	 */
637 	if (p1->p_pfsflags & PF_FORK) {
638 		p2->p_stops = p1->p_stops;
639 		p2->p_pfsflags = p1->p_pfsflags;
640 	}
641 
642 	/*
643 	 * This begins the section where we must prevent the parent
644 	 * from being swapped.
645 	 */
646 	_PHOLD(p1);
647 	PROC_UNLOCK(p1);
648 
649 	/*
650 	 * Attach the new process to its parent.
651 	 *
652 	 * If RFNOWAIT is set, the newly created process becomes a child
653 	 * of init.  This effectively disassociates the child from the
654 	 * parent.
655 	 */
656 	if (flags & RFNOWAIT)
657 		pptr = initproc;
658 	else
659 		pptr = p1;
660 	p2->p_pptr = pptr;
661 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
662 	PROC_UNLOCK(p2);
663 	sx_xunlock(&proctree_lock);
664 
665 	KASSERT(newprocsig == NULL, ("unused newprocsig"));
666 	if (newsigacts != NULL)
667 		FREE(newsigacts, M_SUBPROC);
668 	/*
669 	 * Finish creating the child process.  It will return via a different
670 	 * execution path later.  (ie: directly into user mode)
671 	 */
672 	vm_forkproc(td, p2, td2, flags);
673 
674 	if (flags == (RFFDG | RFPROC)) {
675 		cnt.v_forks++;
676 		cnt.v_forkpages += p2->p_vmspace->vm_dsize +
677 		    p2->p_vmspace->vm_ssize;
678 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
679 		cnt.v_vforks++;
680 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize +
681 		    p2->p_vmspace->vm_ssize;
682 	} else if (p1 == &proc0) {
683 		cnt.v_kthreads++;
684 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize +
685 		    p2->p_vmspace->vm_ssize;
686 	} else {
687 		cnt.v_rforks++;
688 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize +
689 		    p2->p_vmspace->vm_ssize;
690 	}
691 
692 	/*
693 	 * Both processes are set up, now check if any loadable modules want
694 	 * to adjust anything.
695 	 *   What if they have an error? XXX
696 	 */
697 	sx_slock(&fork_list_lock);
698 	TAILQ_FOREACH(ep, &fork_list, next) {
699 		(*ep->function)(p1, p2, flags);
700 	}
701 	sx_sunlock(&fork_list_lock);
702 
703 	/*
704 	 * If RFSTOPPED not requested, make child runnable and add to
705 	 * run queue.
706 	 */
707 	microtime(&(p2->p_stats->p_start));
708 	p2->p_acflag = AFORK;
709 	if ((flags & RFSTOPPED) == 0) {
710 		mtx_lock_spin(&sched_lock);
711 		p2->p_state = PRS_NORMAL;
712 		TD_SET_CAN_RUN(td2);
713 		setrunqueue(td2);
714 		mtx_unlock_spin(&sched_lock);
715 	}
716 
717 	/*
718 	 * Now can be swapped.
719 	 */
720 	PROC_LOCK(p1);
721 	_PRELE(p1);
722 
723 	/*
724 	 * tell any interested parties about the new process
725 	 */
726 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
727 	PROC_UNLOCK(p1);
728 
729 	/*
730 	 * Preserve synchronization semantics of vfork.  If waiting for
731 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
732 	 * proc (in case of exit).
733 	 */
734 	PROC_LOCK(p2);
735 	while (p2->p_flag & P_PPWAIT)
736 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
737 	PROC_UNLOCK(p2);
738 
739 	/*
740 	 * If other threads are waiting, let them continue now
741 	 */
742 	if (p1->p_flag & P_KSES) {
743 		PROC_LOCK(p1);
744 		thread_single_end();
745 		PROC_UNLOCK(p1);
746 	}
747 
748 	/*
749 	 * Return child proc pointer to parent.
750 	 */
751 	*procp = p2;
752 	return (0);
753 fail:
754 	sx_xunlock(&allproc_lock);
755 	uma_zfree(proc_zone, newproc);
756 	if (p1->p_flag & P_KSES) {
757 		PROC_LOCK(p1);
758 		thread_single_end();
759 		PROC_UNLOCK(p1);
760 	}
761 	tsleep(&forksleep, PUSER, "fork", hz / 2);
762 	return (error);
763 }
764 
765 /*
766  * The next two functionms are general routines to handle adding/deleting
767  * items on the fork callout list.
768  *
769  * at_fork():
770  * Take the arguments given and put them onto the fork callout list,
771  * However first make sure that it's not already there.
772  * Returns 0 on success or a standard error number.
773  */
774 
775 int
776 at_fork(function)
777 	forklist_fn function;
778 {
779 	struct forklist *ep;
780 
781 #ifdef INVARIANTS
782 	/* let the programmer know if he's been stupid */
783 	if (rm_at_fork(function))
784 		printf("WARNING: fork callout entry (%p) already present\n",
785 		    function);
786 #endif
787 	ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
788 	if (ep == NULL)
789 		return (ENOMEM);
790 	ep->function = function;
791 	sx_xlock(&fork_list_lock);
792 	TAILQ_INSERT_TAIL(&fork_list, ep, next);
793 	sx_xunlock(&fork_list_lock);
794 	return (0);
795 }
796 
797 /*
798  * Scan the exit callout list for the given item and remove it..
799  * Returns the number of items removed (0 or 1)
800  */
801 
802 int
803 rm_at_fork(function)
804 	forklist_fn function;
805 {
806 	struct forklist *ep;
807 
808 	sx_xlock(&fork_list_lock);
809 	TAILQ_FOREACH(ep, &fork_list, next) {
810 		if (ep->function == function) {
811 			TAILQ_REMOVE(&fork_list, ep, next);
812 			sx_xunlock(&fork_list_lock);
813 			free(ep, M_ATFORK);
814 			return(1);
815 		}
816 	}
817 	sx_xunlock(&fork_list_lock);
818 	return (0);
819 }
820 
821 /*
822  * Handle the return of a child process from fork1().  This function
823  * is called from the MD fork_trampoline() entry point.
824  */
825 void
826 fork_exit(callout, arg, frame)
827 	void (*callout)(void *, struct trapframe *);
828 	void *arg;
829 	struct trapframe *frame;
830 {
831 	struct thread *td = curthread;
832 	struct proc *p = td->td_proc;
833 
834 	td->td_kse->ke_oncpu = PCPU_GET(cpuid);
835 	p->p_state = PRS_NORMAL;
836 	/*
837 	 * Finish setting up thread glue.  We need to initialize
838 	 * the thread into a td_critnest=1 state.  Some platforms
839 	 * may have already partially or fully initialized td_critnest
840 	 * and/or td_md.md_savecrit (when applciable).
841 	 *
842 	 * see <arch>/<arch>/critical.c
843 	 */
844 	sched_lock.mtx_lock = (uintptr_t)td;
845 	sched_lock.mtx_recurse = 0;
846 	cpu_critical_fork_exit();
847 	CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
848 	    p->p_comm);
849 	if (PCPU_GET(switchtime.sec) == 0)
850 		binuptime(PCPU_PTR(switchtime));
851 	PCPU_SET(switchticks, ticks);
852 	mtx_unlock_spin(&sched_lock);
853 
854 	/*
855 	 * cpu_set_fork_handler intercepts this function call to
856          * have this call a non-return function to stay in kernel mode.
857          * initproc has its own fork handler, but it does return.
858          */
859 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
860 	callout(arg, frame);
861 
862 	/*
863 	 * Check if a kernel thread misbehaved and returned from its main
864 	 * function.
865 	 */
866 	PROC_LOCK(p);
867 	if (p->p_flag & P_KTHREAD) {
868 		PROC_UNLOCK(p);
869 		mtx_lock(&Giant);
870 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
871 		    p->p_comm, p->p_pid);
872 		kthread_exit(0);
873 	}
874 	PROC_UNLOCK(p);
875 #ifdef DIAGNOSTIC
876 	cred_free_thread(td);
877 #endif
878 	mtx_assert(&Giant, MA_NOTOWNED);
879 }
880 
881 /*
882  * Simplified back end of syscall(), used when returning from fork()
883  * directly into user mode.  Giant is not held on entry, and must not
884  * be held on return.  This function is passed in to fork_exit() as the
885  * first parameter and is called when returning to a new userland process.
886  */
887 void
888 fork_return(td, frame)
889 	struct thread *td;
890 	struct trapframe *frame;
891 {
892 
893 	userret(td, frame, 0);
894 #ifdef KTRACE
895 	if (KTRPOINT(td, KTR_SYSRET))
896 		ktrsysret(SYS_fork, 0, 0);
897 #endif
898 	mtx_assert(&Giant, MA_NOTOWNED);
899 }
900