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