xref: /freebsd/sys/kern/kern_fork.c (revision aff5735784df44945af1de1cf35b5df0779bb097)
19454b2d8SWarner Losh /*-
2df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
4df8bae1dSRodney W. Grimes  * (c) UNIX System Laboratories, Inc.
5df8bae1dSRodney W. Grimes  * All or some portions of this file are derived from material licensed
6df8bae1dSRodney W. Grimes  * to the University of California by American Telephone and Telegraph
7df8bae1dSRodney W. Grimes  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8df8bae1dSRodney W. Grimes  * the permission of UNIX System Laboratories, Inc.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
11df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
12df8bae1dSRodney W. Grimes  * are met:
13df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
15df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
17df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
18df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
19df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
20df8bae1dSRodney W. Grimes  *    without specific prior written permission.
21df8bae1dSRodney W. Grimes  *
22df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
33df8bae1dSRodney W. Grimes  *
34df8bae1dSRodney W. Grimes  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
35df8bae1dSRodney W. Grimes  */
36df8bae1dSRodney W. Grimes 
37677b542eSDavid E. O'Brien #include <sys/cdefs.h>
38677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
39677b542eSDavid E. O'Brien 
40db6a20e2SGarrett Wollman #include "opt_ktrace.h"
418a945d10SKonstantin Belousov #include "opt_kstack_pages.h"
42db6a20e2SGarrett Wollman 
43df8bae1dSRodney W. Grimes #include <sys/param.h>
44df8bae1dSRodney W. Grimes #include <sys/systm.h>
45d2d3e875SBruce Evans #include <sys/sysproto.h>
4675b8b3b2SJohn Baldwin #include <sys/eventhandler.h>
47cfb5f768SJonathan Anderson #include <sys/fcntl.h>
48df8bae1dSRodney W. Grimes #include <sys/filedesc.h>
490304c731SJamie Gritton #include <sys/jail.h>
50df8bae1dSRodney W. Grimes #include <sys/kernel.h>
5170fca427SJohn Baldwin #include <sys/kthread.h>
52c76e95c3SPeter Wemm #include <sys/sysctl.h>
5319284646SJohn Baldwin #include <sys/lock.h>
54df8bae1dSRodney W. Grimes #include <sys/malloc.h>
5535e0e5b3SJohn Baldwin #include <sys/mutex.h>
56acd3428bSRobert Watson #include <sys/priv.h>
57df8bae1dSRodney W. Grimes #include <sys/proc.h>
58cfb5f768SJonathan Anderson #include <sys/procdesc.h>
599ccba881SMatthew N. Dodd #include <sys/pioctl.h>
60189ac973SJohn Baldwin #include <sys/ptrace.h>
61097055e2SEdward Tomasz Napierala #include <sys/racct.h>
62df8bae1dSRodney W. Grimes #include <sys/resourcevar.h>
63b43179fbSJeff Roberson #include <sys/sched.h>
64a7b124c3SJohn Baldwin #include <sys/syscall.h>
6570fca427SJohn Baldwin #include <sys/vmmeter.h>
66df8bae1dSRodney W. Grimes #include <sys/vnode.h>
67df8bae1dSRodney W. Grimes #include <sys/acct.h>
680384fff8SJason Evans #include <sys/ktr.h>
69df8bae1dSRodney W. Grimes #include <sys/ktrace.h>
70b71fec07SBruce Evans #include <sys/unistd.h>
715d217f17SJohn Birrell #include <sys/sdt.h>
7257934cd3SJohn Baldwin #include <sys/sx.h>
73e5d81ef1SDmitry Chagin #include <sys/sysent.h>
746004362eSDavid Schultz #include <sys/signalvar.h>
75df8bae1dSRodney W. Grimes 
76fcf7f27aSRobert Watson #include <security/audit/audit.h>
77aed55708SRobert Watson #include <security/mac/mac_framework.h>
78fcf7f27aSRobert Watson 
79d93f860cSPoul-Henning Kamp #include <vm/vm.h>
80dabee6feSPeter Wemm #include <vm/pmap.h>
81dabee6feSPeter Wemm #include <vm/vm_map.h>
82efeaf95aSDavid Greenman #include <vm/vm_extern.h>
83c897b813SJeff Roberson #include <vm/uma.h>
846520495aSAdrian Chadd #include <vm/vm_domain.h>
85d93f860cSPoul-Henning Kamp 
865d217f17SJohn Birrell #ifdef KDTRACE_HOOKS
875d217f17SJohn Birrell #include <sys/dtrace_bsd.h>
885d217f17SJohn Birrell dtrace_fork_func_t	dtrace_fasttrap_fork;
895d217f17SJohn Birrell #endif
905d217f17SJohn Birrell 
915d217f17SJohn Birrell SDT_PROVIDER_DECLARE(proc);
92d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(proc, kernel, , create, "struct proc *",
937b77e1feSMark Johnston     "struct proc *", "int");
9488c5ea45SJulian Elischer 
95d2d3e875SBruce Evans #ifndef _SYS_SYSPROTO_H_
96ad7507e2SSteven Wallace struct fork_args {
97ad7507e2SSteven Wallace 	int     dummy;
98ad7507e2SSteven Wallace };
99d2d3e875SBruce Evans #endif
100ad7507e2SSteven Wallace 
101df8bae1dSRodney W. Grimes /* ARGSUSED */
10226f9a767SRodney W. Grimes int
1038451d0ddSKip Macy sys_fork(struct thread *td, struct fork_args *uap)
104df8bae1dSRodney W. Grimes {
105df8abd0bSPeter Wemm 	int error;
106df8abd0bSPeter Wemm 	struct proc *p2;
107be67169aSBruce Evans 
108367a13f9SEd Schouten 	error = fork1(td, RFFDG | RFPROC, 0, &p2, NULL, 0, NULL);
109df8abd0bSPeter Wemm 	if (error == 0) {
110b40ce416SJulian Elischer 		td->td_retval[0] = p2->p_pid;
111b40ce416SJulian Elischer 		td->td_retval[1] = 0;
112df8abd0bSPeter Wemm 	}
11370fca427SJohn Baldwin 	return (error);
114df8bae1dSRodney W. Grimes }
115df8bae1dSRodney W. Grimes 
116cfb5f768SJonathan Anderson /* ARGUSED */
117cfb5f768SJonathan Anderson int
1188451d0ddSKip Macy sys_pdfork(td, uap)
119cfb5f768SJonathan Anderson 	struct thread *td;
120cfb5f768SJonathan Anderson 	struct pdfork_args *uap;
121cfb5f768SJonathan Anderson {
122cfb5f768SJonathan Anderson 	int error, fd;
123cfb5f768SJonathan Anderson 	struct proc *p2;
124cfb5f768SJonathan Anderson 
125cfb5f768SJonathan Anderson 	/*
126cfb5f768SJonathan Anderson 	 * It is necessary to return fd by reference because 0 is a valid file
127cfb5f768SJonathan Anderson 	 * descriptor number, and the child needs to be able to distinguish
128cfb5f768SJonathan Anderson 	 * itself from the parent using the return value.
129cfb5f768SJonathan Anderson 	 */
130cfb5f768SJonathan Anderson 	error = fork1(td, RFFDG | RFPROC | RFPROCDESC, 0, &p2,
131367a13f9SEd Schouten 	    &fd, uap->flags, NULL);
132cfb5f768SJonathan Anderson 	if (error == 0) {
133cfb5f768SJonathan Anderson 		td->td_retval[0] = p2->p_pid;
134cfb5f768SJonathan Anderson 		td->td_retval[1] = 0;
135cfb5f768SJonathan Anderson 		error = copyout(&fd, uap->fdp, sizeof(fd));
136cfb5f768SJonathan Anderson 	}
137cfb5f768SJonathan Anderson 	return (error);
138cfb5f768SJonathan Anderson }
139cfb5f768SJonathan Anderson 
140df8bae1dSRodney W. Grimes /* ARGSUSED */
14126f9a767SRodney W. Grimes int
1428451d0ddSKip Macy sys_vfork(struct thread *td, struct vfork_args *uap)
143df8bae1dSRodney W. Grimes {
14450d6e424SKip Macy 	int error, flags;
145df8abd0bSPeter Wemm 	struct proc *p2;
146be67169aSBruce Evans 
14750d6e424SKip Macy 	flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
148367a13f9SEd Schouten 	error = fork1(td, flags, 0, &p2, NULL, 0, NULL);
149df8abd0bSPeter Wemm 	if (error == 0) {
150b40ce416SJulian Elischer 		td->td_retval[0] = p2->p_pid;
151b40ce416SJulian Elischer 		td->td_retval[1] = 0;
152df8abd0bSPeter Wemm 	}
15370fca427SJohn Baldwin 	return (error);
154df8bae1dSRodney W. Grimes }
155df8bae1dSRodney W. Grimes 
156dabee6feSPeter Wemm int
1578451d0ddSKip Macy sys_rfork(struct thread *td, struct rfork_args *uap)
158dabee6feSPeter Wemm {
159df8abd0bSPeter Wemm 	struct proc *p2;
160c8564ad4SBruce Evans 	int error;
161be67169aSBruce Evans 
162c8564ad4SBruce Evans 	/* Don't allow kernel-only flags. */
163885ccc61SJohn Baldwin 	if ((uap->flags & RFKERNELONLY) != 0)
164885ccc61SJohn Baldwin 		return (EINVAL);
165c8564ad4SBruce Evans 
16614961ba7SRobert Watson 	AUDIT_ARG_FFLAGS(uap->flags);
167367a13f9SEd Schouten 	error = fork1(td, uap->flags, 0, &p2, NULL, 0, NULL);
168df8abd0bSPeter Wemm 	if (error == 0) {
169b40ce416SJulian Elischer 		td->td_retval[0] = p2 ? p2->p_pid : 0;
170b40ce416SJulian Elischer 		td->td_retval[1] = 0;
171df8abd0bSPeter Wemm 	}
17270fca427SJohn Baldwin 	return (error);
173dabee6feSPeter Wemm }
174dabee6feSPeter Wemm 
175df8bae1dSRodney W. Grimes int	nprocs = 1;		/* process 0 */
1768f7e4eb5SDag-Erling Smørgrav int	lastpid = 0;
1778f7e4eb5SDag-Erling Smørgrav SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
178d941d475SRobert Watson     "Last used PID");
179df8bae1dSRodney W. Grimes 
180bb6a234eSPeter Wemm /*
1818f7e4eb5SDag-Erling Smørgrav  * Random component to lastpid generation.  We mix in a random factor to make
182bb6a234eSPeter Wemm  * it a little harder to predict.  We sanity check the modulus value to avoid
183bb6a234eSPeter Wemm  * doing it in critical paths.  Don't let it be too small or we pointlessly
184bb6a234eSPeter Wemm  * waste randomness entropy, and don't let it be impossibly large.  Using a
185bb6a234eSPeter Wemm  * modulus that is too big causes a LOT more process table scans and slows
186bb6a234eSPeter Wemm  * down fork processing as the pidchecked caching is defeated.
187bb6a234eSPeter Wemm  */
188ee3fd601SDan Moschuk static int randompid = 0;
189bb6a234eSPeter Wemm 
190bb6a234eSPeter Wemm static int
19182d9ae4eSPoul-Henning Kamp sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
192bb6a234eSPeter Wemm {
193bb6a234eSPeter Wemm 	int error, pid;
194bb6a234eSPeter Wemm 
19547934cefSDon Lewis 	error = sysctl_wire_old_buffer(req, sizeof(int));
19647934cefSDon Lewis 	if (error != 0)
19747934cefSDon Lewis 		return(error);
1983fc755c1SJohn Baldwin 	sx_xlock(&allproc_lock);
199bb6a234eSPeter Wemm 	pid = randompid;
200bb6a234eSPeter Wemm 	error = sysctl_handle_int(oidp, &pid, 0, req);
2013fc755c1SJohn Baldwin 	if (error == 0 && req->newptr != NULL) {
20202c6fc21SKonstantin Belousov 		if (pid < 0 || pid > pid_max - 100)	/* out of range */
20302c6fc21SKonstantin Belousov 			pid = pid_max - 100;
204bb6a234eSPeter Wemm 		else if (pid < 2)			/* NOP */
205bb6a234eSPeter Wemm 			pid = 0;
206bb6a234eSPeter Wemm 		else if (pid < 100)			/* Make it reasonable */
207bb6a234eSPeter Wemm 			pid = 100;
208bb6a234eSPeter Wemm 		randompid = pid;
2093fc755c1SJohn Baldwin 	}
2103fc755c1SJohn Baldwin 	sx_xunlock(&allproc_lock);
211bb6a234eSPeter Wemm 	return (error);
212bb6a234eSPeter Wemm }
213bb6a234eSPeter Wemm 
214bb6a234eSPeter Wemm SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
215bb6a234eSPeter Wemm     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
216ee3fd601SDan Moschuk 
2171d845e86SEdward Tomasz Napierala static int
218afd01097SEdward Tomasz Napierala fork_findpid(int flags)
219afd01097SEdward Tomasz Napierala {
220afd01097SEdward Tomasz Napierala 	struct proc *p;
221afd01097SEdward Tomasz Napierala 	int trypid;
222afd01097SEdward Tomasz Napierala 	static int pidchecked = 0;
223afd01097SEdward Tomasz Napierala 
2243e73ff1eSEdward Tomasz Napierala 	/*
2253e73ff1eSEdward Tomasz Napierala 	 * Requires allproc_lock in order to iterate over the list
2263e73ff1eSEdward Tomasz Napierala 	 * of processes, and proctree_lock to access p_pgrp.
2273e73ff1eSEdward Tomasz Napierala 	 */
2283e73ff1eSEdward Tomasz Napierala 	sx_assert(&allproc_lock, SX_LOCKED);
2293e73ff1eSEdward Tomasz Napierala 	sx_assert(&proctree_lock, SX_LOCKED);
230afd01097SEdward Tomasz Napierala 
231afd01097SEdward Tomasz Napierala 	/*
232afd01097SEdward Tomasz Napierala 	 * Find an unused process ID.  We remember a range of unused IDs
233afd01097SEdward Tomasz Napierala 	 * ready to use (from lastpid+1 through pidchecked-1).
234afd01097SEdward Tomasz Napierala 	 *
235afd01097SEdward Tomasz Napierala 	 * If RFHIGHPID is set (used during system boot), do not allocate
236afd01097SEdward Tomasz Napierala 	 * low-numbered pids.
237afd01097SEdward Tomasz Napierala 	 */
238afd01097SEdward Tomasz Napierala 	trypid = lastpid + 1;
239afd01097SEdward Tomasz Napierala 	if (flags & RFHIGHPID) {
240afd01097SEdward Tomasz Napierala 		if (trypid < 10)
241afd01097SEdward Tomasz Napierala 			trypid = 10;
242afd01097SEdward Tomasz Napierala 	} else {
243afd01097SEdward Tomasz Napierala 		if (randompid)
244afd01097SEdward Tomasz Napierala 			trypid += arc4random() % randompid;
245afd01097SEdward Tomasz Napierala 	}
246afd01097SEdward Tomasz Napierala retry:
247afd01097SEdward Tomasz Napierala 	/*
248afd01097SEdward Tomasz Napierala 	 * If the process ID prototype has wrapped around,
249afd01097SEdward Tomasz Napierala 	 * restart somewhat above 0, as the low-numbered procs
250afd01097SEdward Tomasz Napierala 	 * tend to include daemons that don't exit.
251afd01097SEdward Tomasz Napierala 	 */
25202c6fc21SKonstantin Belousov 	if (trypid >= pid_max) {
25302c6fc21SKonstantin Belousov 		trypid = trypid % pid_max;
254afd01097SEdward Tomasz Napierala 		if (trypid < 100)
255afd01097SEdward Tomasz Napierala 			trypid += 100;
256afd01097SEdward Tomasz Napierala 		pidchecked = 0;
257afd01097SEdward Tomasz Napierala 	}
258afd01097SEdward Tomasz Napierala 	if (trypid >= pidchecked) {
259afd01097SEdward Tomasz Napierala 		int doingzomb = 0;
260afd01097SEdward Tomasz Napierala 
261afd01097SEdward Tomasz Napierala 		pidchecked = PID_MAX;
262afd01097SEdward Tomasz Napierala 		/*
263afd01097SEdward Tomasz Napierala 		 * Scan the active and zombie procs to check whether this pid
264afd01097SEdward Tomasz Napierala 		 * is in use.  Remember the lowest pid that's greater
265afd01097SEdward Tomasz Napierala 		 * than trypid, so we can avoid checking for a while.
266237623b0SKonstantin Belousov 		 *
267237623b0SKonstantin Belousov 		 * Avoid reuse of the process group id, session id or
268237623b0SKonstantin Belousov 		 * the reaper subtree id.  Note that for process group
269237623b0SKonstantin Belousov 		 * and sessions, the amount of reserved pids is
270237623b0SKonstantin Belousov 		 * limited by process limit.  For the subtree ids, the
271237623b0SKonstantin Belousov 		 * id is kept reserved only while there is a
272237623b0SKonstantin Belousov 		 * non-reaped process in the subtree, so amount of
273237623b0SKonstantin Belousov 		 * reserved pids is limited by process limit times
274237623b0SKonstantin Belousov 		 * two.
275afd01097SEdward Tomasz Napierala 		 */
276afd01097SEdward Tomasz Napierala 		p = LIST_FIRST(&allproc);
277afd01097SEdward Tomasz Napierala again:
278afd01097SEdward Tomasz Napierala 		for (; p != NULL; p = LIST_NEXT(p, p_list)) {
279afd01097SEdward Tomasz Napierala 			while (p->p_pid == trypid ||
280237623b0SKonstantin Belousov 			    p->p_reapsubtree == trypid ||
281afd01097SEdward Tomasz Napierala 			    (p->p_pgrp != NULL &&
282afd01097SEdward Tomasz Napierala 			    (p->p_pgrp->pg_id == trypid ||
283afd01097SEdward Tomasz Napierala 			    (p->p_session != NULL &&
284afd01097SEdward Tomasz Napierala 			    p->p_session->s_sid == trypid)))) {
285afd01097SEdward Tomasz Napierala 				trypid++;
286afd01097SEdward Tomasz Napierala 				if (trypid >= pidchecked)
287afd01097SEdward Tomasz Napierala 					goto retry;
288afd01097SEdward Tomasz Napierala 			}
289afd01097SEdward Tomasz Napierala 			if (p->p_pid > trypid && pidchecked > p->p_pid)
290afd01097SEdward Tomasz Napierala 				pidchecked = p->p_pid;
291afd01097SEdward Tomasz Napierala 			if (p->p_pgrp != NULL) {
292afd01097SEdward Tomasz Napierala 				if (p->p_pgrp->pg_id > trypid &&
293afd01097SEdward Tomasz Napierala 				    pidchecked > p->p_pgrp->pg_id)
294afd01097SEdward Tomasz Napierala 					pidchecked = p->p_pgrp->pg_id;
295afd01097SEdward Tomasz Napierala 				if (p->p_session != NULL &&
296afd01097SEdward Tomasz Napierala 				    p->p_session->s_sid > trypid &&
297afd01097SEdward Tomasz Napierala 				    pidchecked > p->p_session->s_sid)
298afd01097SEdward Tomasz Napierala 					pidchecked = p->p_session->s_sid;
299afd01097SEdward Tomasz Napierala 			}
300afd01097SEdward Tomasz Napierala 		}
301afd01097SEdward Tomasz Napierala 		if (!doingzomb) {
302afd01097SEdward Tomasz Napierala 			doingzomb = 1;
303afd01097SEdward Tomasz Napierala 			p = LIST_FIRST(&zombproc);
304afd01097SEdward Tomasz Napierala 			goto again;
305afd01097SEdward Tomasz Napierala 		}
306afd01097SEdward Tomasz Napierala 	}
307afd01097SEdward Tomasz Napierala 
308afd01097SEdward Tomasz Napierala 	/*
309afd01097SEdward Tomasz Napierala 	 * RFHIGHPID does not mess with the lastpid counter during boot.
310afd01097SEdward Tomasz Napierala 	 */
311afd01097SEdward Tomasz Napierala 	if (flags & RFHIGHPID)
312afd01097SEdward Tomasz Napierala 		pidchecked = 0;
313afd01097SEdward Tomasz Napierala 	else
314afd01097SEdward Tomasz Napierala 		lastpid = trypid;
315afd01097SEdward Tomasz Napierala 
316afd01097SEdward Tomasz Napierala 	return (trypid);
317afd01097SEdward Tomasz Napierala }
318afd01097SEdward Tomasz Napierala 
319afd01097SEdward Tomasz Napierala static int
3203e73ff1eSEdward Tomasz Napierala fork_norfproc(struct thread *td, int flags)
3211d845e86SEdward Tomasz Napierala {
3221d845e86SEdward Tomasz Napierala 	int error;
3231d845e86SEdward Tomasz Napierala 	struct proc *p1;
3241d845e86SEdward Tomasz Napierala 
325087bfb0eSEdward Tomasz Napierala 	KASSERT((flags & RFPROC) == 0,
326087bfb0eSEdward Tomasz Napierala 	    ("fork_norfproc called with RFPROC set"));
3271d845e86SEdward Tomasz Napierala 	p1 = td->td_proc;
3281d845e86SEdward Tomasz Napierala 
3291d845e86SEdward Tomasz Napierala 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
3301d845e86SEdward Tomasz Napierala 	    (flags & (RFCFDG | RFFDG))) {
3311d845e86SEdward Tomasz Napierala 		PROC_LOCK(p1);
3326ddcc233SKonstantin Belousov 		if (thread_single(p1, SINGLE_BOUNDARY)) {
3331d845e86SEdward Tomasz Napierala 			PROC_UNLOCK(p1);
3341d845e86SEdward Tomasz Napierala 			return (ERESTART);
3351d845e86SEdward Tomasz Napierala 		}
3361d845e86SEdward Tomasz Napierala 		PROC_UNLOCK(p1);
3371d845e86SEdward Tomasz Napierala 	}
3381d845e86SEdward Tomasz Napierala 
3391d845e86SEdward Tomasz Napierala 	error = vm_forkproc(td, NULL, NULL, NULL, flags);
3401d845e86SEdward Tomasz Napierala 	if (error)
3411d845e86SEdward Tomasz Napierala 		goto fail;
3421d845e86SEdward Tomasz Napierala 
3431d845e86SEdward Tomasz Napierala 	/*
3441d845e86SEdward Tomasz Napierala 	 * Close all file descriptors.
3451d845e86SEdward Tomasz Napierala 	 */
3461d845e86SEdward Tomasz Napierala 	if (flags & RFCFDG) {
3471d845e86SEdward Tomasz Napierala 		struct filedesc *fdtmp;
348eb48fbd9SMateusz Guzik 		fdtmp = fdinit(td->td_proc->p_fd, false);
3492609222aSPawel Jakub Dawidek 		fdescfree(td);
3501d845e86SEdward Tomasz Napierala 		p1->p_fd = fdtmp;
3511d845e86SEdward Tomasz Napierala 	}
3521d845e86SEdward Tomasz Napierala 
3531d845e86SEdward Tomasz Napierala 	/*
3541d845e86SEdward Tomasz Napierala 	 * Unshare file descriptors (from parent).
3551d845e86SEdward Tomasz Napierala 	 */
3561d845e86SEdward Tomasz Napierala 	if (flags & RFFDG)
357b9d32c36SMateusz Guzik 		fdunshare(td);
3581d845e86SEdward Tomasz Napierala 
3591d845e86SEdward Tomasz Napierala fail:
3601d845e86SEdward Tomasz Napierala 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
3611d845e86SEdward Tomasz Napierala 	    (flags & (RFCFDG | RFFDG))) {
3621d845e86SEdward Tomasz Napierala 		PROC_LOCK(p1);
3636ddcc233SKonstantin Belousov 		thread_single_end(p1, SINGLE_BOUNDARY);
3641d845e86SEdward Tomasz Napierala 		PROC_UNLOCK(p1);
3651d845e86SEdward Tomasz Napierala 	}
3661d845e86SEdward Tomasz Napierala 	return (error);
3671d845e86SEdward Tomasz Napierala }
3681d845e86SEdward Tomasz Napierala 
369afd01097SEdward Tomasz Napierala static void
370afd01097SEdward Tomasz Napierala do_fork(struct thread *td, int flags, struct proc *p2, struct thread *td2,
371cfb5f768SJonathan Anderson     struct vmspace *vm2, int pdflags)
372df8bae1dSRodney W. Grimes {
373afd01097SEdward Tomasz Napierala 	struct proc *p1, *pptr;
3746fa39a73SKonstantin Belousov 	int p2_held, trypid;
3755641ae5dSJohn Baldwin 	struct filedesc *fd;
376ad05d580STor Egge 	struct filedesc_to_leader *fdtol;
3773fc755c1SJohn Baldwin 	struct sigacts *newsigacts;
3785856e12eSJohn Dyson 
379afd01097SEdward Tomasz Napierala 	sx_assert(&proctree_lock, SX_SLOCKED);
380afd01097SEdward Tomasz Napierala 	sx_assert(&allproc_lock, SX_XLOCKED);
381df8bae1dSRodney W. Grimes 
3826fa39a73SKonstantin Belousov 	p2_held = 0;
38370fca427SJohn Baldwin 	p1 = td->td_proc;
38470fca427SJohn Baldwin 
385afd01097SEdward Tomasz Napierala 	trypid = fork_findpid(flags);
386df8bae1dSRodney W. Grimes 
3875ce2f678SJohn Baldwin 	sx_sunlock(&proctree_lock);
388df8bae1dSRodney W. Grimes 
389e602ba25SJulian Elischer 	p2->p_state = PRS_NEW;		/* protect against others */
390553629ebSJake Burkholder 	p2->p_pid = trypid;
39114961ba7SRobert Watson 	AUDIT_ARG_PID(p2->p_pid);
392553629ebSJake Burkholder 	LIST_INSERT_HEAD(&allproc, p2, p_list);
3936ddcc233SKonstantin Belousov 	allproc_gen++;
394553629ebSJake Burkholder 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
395cf7d9a8cSDavid Xu 	tidhash_add(td2);
3961ad9ee86SXin LI 	PROC_LOCK(p2);
3971ad9ee86SXin LI 	PROC_LOCK(p1);
3981ad9ee86SXin LI 
3991005a129SJohn Baldwin 	sx_xunlock(&allproc_lock);
400553629ebSJake Burkholder 
4011ad9ee86SXin LI 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
4021ad9ee86SXin LI 	    __rangeof(struct proc, p_startcopy, p_endcopy));
4038b4a2800SKonstantin Belousov 	pargs_hold(p2->p_args);
4046520495aSAdrian Chadd 
4051ad9ee86SXin LI 	PROC_UNLOCK(p1);
4061ad9ee86SXin LI 
4071ad9ee86SXin LI 	bzero(&p2->p_startzero,
4081ad9ee86SXin LI 	    __rangeof(struct proc, p_startzero, p_endzero));
4091ad9ee86SXin LI 
4100304c731SJamie Gritton 	/* Tell the prison that we exist. */
411413628a7SBjoern A. Zeeb 	prison_proc_hold(p2->p_ucred->cr_prison);
412413628a7SBjoern A. Zeeb 
4131ad9ee86SXin LI 	PROC_UNLOCK(p2);
4141ad9ee86SXin LI 
4150384fff8SJason Evans 	/*
4163fc755c1SJohn Baldwin 	 * Malloc things while we don't hold any locks.
4173fc755c1SJohn Baldwin 	 */
41890af4afaSJohn Baldwin 	if (flags & RFSIGSHARE)
4193fc755c1SJohn Baldwin 		newsigacts = NULL;
42090af4afaSJohn Baldwin 	else
42190af4afaSJohn Baldwin 		newsigacts = sigacts_alloc();
4223fc755c1SJohn Baldwin 
4233fc755c1SJohn Baldwin 	/*
4243fc755c1SJohn Baldwin 	 * Copy filedesc.
4253fc755c1SJohn Baldwin 	 */
426ad05d580STor Egge 	if (flags & RFCFDG) {
427eb48fbd9SMateusz Guzik 		fd = fdinit(p1->p_fd, false);
428ad05d580STor Egge 		fdtol = NULL;
429ad05d580STor Egge 	} else if (flags & RFFDG) {
430598b7ec8SPoul-Henning Kamp 		fd = fdcopy(p1->p_fd);
431ad05d580STor Egge 		fdtol = NULL;
432ad05d580STor Egge 	} else {
433c7f1c11bSAlfred Perlstein 		fd = fdshare(p1->p_fd);
434ad05d580STor Egge 		if (p1->p_fdtol == NULL)
4353e73ff1eSEdward Tomasz Napierala 			p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL,
436ad05d580STor Egge 			    p1->p_leader);
437ad05d580STor Egge 		if ((flags & RFTHREAD) != 0) {
438ad05d580STor Egge 			/*
4393e73ff1eSEdward Tomasz Napierala 			 * Shared file descriptor table, and shared
4403e73ff1eSEdward Tomasz Napierala 			 * process leaders.
441ad05d580STor Egge 			 */
442ad05d580STor Egge 			fdtol = p1->p_fdtol;
4435e3f7694SRobert Watson 			FILEDESC_XLOCK(p1->p_fd);
444ad05d580STor Egge 			fdtol->fdl_refcount++;
4455e3f7694SRobert Watson 			FILEDESC_XUNLOCK(p1->p_fd);
446ad05d580STor Egge 		} else {
447ad05d580STor Egge 			/*
4483e73ff1eSEdward Tomasz Napierala 			 * Shared file descriptor table, and different
4493e73ff1eSEdward Tomasz Napierala 			 * process leaders.
450ad05d580STor Egge 			 */
451ad05d580STor Egge 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
4523e73ff1eSEdward Tomasz Napierala 			    p1->p_fd, p2);
453ad05d580STor Egge 		}
454ad05d580STor Egge 	}
4553fc755c1SJohn Baldwin 	/*
456df8bae1dSRodney W. Grimes 	 * Make a proc table entry for the new process.
457df8bae1dSRodney W. Grimes 	 * Start by zeroing the section of proc that is zero-initialized,
458df8bae1dSRodney W. Grimes 	 * then copy the section that is copied directly from the parent.
459df8bae1dSRodney W. Grimes 	 */
460316ec49aSScott Long 
4617d447c95SJohn Baldwin 	PROC_LOCK(p2);
4627d447c95SJohn Baldwin 	PROC_LOCK(p1);
4637d447c95SJohn Baldwin 
464079b7badSJulian Elischer 	bzero(&td2->td_startzero,
4656db36923SDavid Schultz 	    __rangeof(struct thread, td_startzero, td_endzero));
466079b7badSJulian Elischer 
467079b7badSJulian Elischer 	bcopy(&td->td_startcopy, &td2->td_startcopy,
4686db36923SDavid Schultz 	    __rangeof(struct thread, td_startcopy, td_endcopy));
469df8bae1dSRodney W. Grimes 
4704b9322aeSJulian Elischer 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
471a30ec4b9SDavid Xu 	td2->td_sigstk = td->td_sigstk;
472b61ce5b0SJeff Roberson 	td2->td_flags = TDF_INMEM;
473acbe332aSDavid Xu 	td2->td_lend_user_pri = PRI_MAX;
474a30ec4b9SDavid Xu 
47521ca7b57SMarko Zec #ifdef VIMAGE
47621ca7b57SMarko Zec 	td2->td_vnet = NULL;
47721ca7b57SMarko Zec 	td2->td_vnet_lpush = NULL;
47821ca7b57SMarko Zec #endif
47921ca7b57SMarko Zec 
480df8bae1dSRodney W. Grimes 	/*
48122d19207SJohn Baldwin 	 * Allow the scheduler to initialize the child.
48222d19207SJohn Baldwin 	 */
48322d19207SJohn Baldwin 	thread_lock(td);
48422d19207SJohn Baldwin 	sched_fork(td, td2);
48522d19207SJohn Baldwin 	thread_unlock(td);
48622d19207SJohn Baldwin 
48722d19207SJohn Baldwin 	/*
488df8bae1dSRodney W. Grimes 	 * Duplicate sub-structures as needed.
489df8bae1dSRodney W. Grimes 	 * Increase reference counts on shared objects.
490df8bae1dSRodney W. Grimes 	 */
491b61ce5b0SJeff Roberson 	p2->p_flag = P_INMEM;
492677258f7SKonstantin Belousov 	p2->p_flag2 = p1->p_flag2 & (P2_NOTRACE | P2_NOTRACE_EXEC);
49354b0e65fSJeff Roberson 	p2->p_swtick = ticks;
4949752f794SJohn Baldwin 	if (p1->p_flag & P_PROFIL)
4959752f794SJohn Baldwin 		startprofclock(p2);
496b9df5231SPoul-Henning Kamp 
4976520495aSAdrian Chadd 	/*
4986520495aSAdrian Chadd 	 * Whilst the proc lock is held, copy the VM domain data out
4996520495aSAdrian Chadd 	 * using the VM domain method.
5006520495aSAdrian Chadd 	 */
5016520495aSAdrian Chadd 	vm_domain_policy_init(&p2->p_vm_dom_policy);
5026520495aSAdrian Chadd 	vm_domain_policy_localcopy(&p2->p_vm_dom_policy,
5036520495aSAdrian Chadd 	    &p1->p_vm_dom_policy);
5046520495aSAdrian Chadd 
5056626c604SJulian Elischer 	if (flags & RFSIGSHARE) {
50690af4afaSJohn Baldwin 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
5076626c604SJulian Elischer 	} else {
50890af4afaSJohn Baldwin 		sigacts_copy(newsigacts, p1->p_sigacts);
50990af4afaSJohn Baldwin 		p2->p_sigacts = newsigacts;
5106626c604SJulian Elischer 	}
511f49d8202SKonstantin Belousov 
512f49d8202SKonstantin Belousov 	if (flags & RFTSIGZMB)
513f49d8202SKonstantin Belousov 	        p2->p_sigparent = RFTSIGNUM(flags);
514f49d8202SKonstantin Belousov 	else if (flags & RFLINUXTHPN)
5156626c604SJulian Elischer 	        p2->p_sigparent = SIGUSR1;
5164ac9ae70SJulian Elischer 	else
5174ac9ae70SJulian Elischer 	        p2->p_sigparent = SIGCHLD;
51888c5ea45SJulian Elischer 
519df8bae1dSRodney W. Grimes 	p2->p_textvp = p1->p_textvp;
5205641ae5dSJohn Baldwin 	p2->p_fd = fd;
521ad05d580STor Egge 	p2->p_fdtol = fdtol;
522dabee6feSPeter Wemm 
52355648840SJohn Baldwin 	if (p1->p_flag2 & P2_INHERIT_PROTECTED) {
52455648840SJohn Baldwin 		p2->p_flag |= P_PROTECTED;
52555648840SJohn Baldwin 		p2->p_flag2 |= P2_INHERIT_PROTECTED;
52655648840SJohn Baldwin 	}
52755648840SJohn Baldwin 
528df8bae1dSRodney W. Grimes 	/*
529c8564ad4SBruce Evans 	 * p_limit is copy-on-write.  Bump its refcount.
530df8bae1dSRodney W. Grimes 	 */
5311c4bcd05SJeff Roberson 	lim_fork(p1, p2);
5328b059651SDavid Schultz 
5334ea6a9a2SMateusz Guzik 	thread_cow_get_proc(td2, p2);
5344ea6a9a2SMateusz Guzik 
5358b059651SDavid Schultz 	pstats_fork(p1->p_stats, p2->p_stats);
5368b059651SDavid Schultz 
537299bc736SDavid Schultz 	PROC_UNLOCK(p1);
538cda5aba4SDavid Schultz 	PROC_UNLOCK(p2);
539df8bae1dSRodney W. Grimes 
5403e73ff1eSEdward Tomasz Napierala 	/* Bump references to the text vnode (for procfs). */
541a69d88afSPeter Wemm 	if (p2->p_textvp)
542a69d88afSPeter Wemm 		vref(p2->p_textvp);
543a69d88afSPeter Wemm 
544c6544064SJohn Baldwin 	/*
545c8564ad4SBruce Evans 	 * Set up linkage for kernel based threading.
546c6544064SJohn Baldwin 	 */
547c6544064SJohn Baldwin 	if ((flags & RFTHREAD) != 0) {
548c6544064SJohn Baldwin 		mtx_lock(&ppeers_lock);
549c6544064SJohn Baldwin 		p2->p_peers = p1->p_peers;
550c6544064SJohn Baldwin 		p1->p_peers = p2;
551c6544064SJohn Baldwin 		p2->p_leader = p1->p_leader;
552c6544064SJohn Baldwin 		mtx_unlock(&ppeers_lock);
553c6544064SJohn Baldwin 		PROC_LOCK(p1->p_leader);
554c6544064SJohn Baldwin 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
555c6544064SJohn Baldwin 			PROC_UNLOCK(p1->p_leader);
556c6544064SJohn Baldwin 			/*
557c6544064SJohn Baldwin 			 * The task leader is exiting, so process p1 is
558c6544064SJohn Baldwin 			 * going to be killed shortly.  Since p1 obviously
559c6544064SJohn Baldwin 			 * isn't dead yet, we know that the leader is either
560c6544064SJohn Baldwin 			 * sending SIGKILL's to all the processes in this
561c6544064SJohn Baldwin 			 * task or is sleeping waiting for all the peers to
562c6544064SJohn Baldwin 			 * exit.  We let p1 complete the fork, but we need
563c6544064SJohn Baldwin 			 * to go ahead and kill the new process p2 since
564c6544064SJohn Baldwin 			 * the task leader may not get a chance to send
565c6544064SJohn Baldwin 			 * SIGKILL to it.  We leave it on the list so that
566c6544064SJohn Baldwin 			 * the task leader will wait for this new process
567c6544064SJohn Baldwin 			 * to commit suicide.
568c6544064SJohn Baldwin 			 */
569c6544064SJohn Baldwin 			PROC_LOCK(p2);
5708451d0ddSKip Macy 			kern_psignal(p2, SIGKILL);
571c6544064SJohn Baldwin 			PROC_UNLOCK(p2);
572293d2d22SRobert Watson 		} else
573293d2d22SRobert Watson 			PROC_UNLOCK(p1->p_leader);
574c6544064SJohn Baldwin 	} else {
575c6544064SJohn Baldwin 		p2->p_peers = NULL;
576c6544064SJohn Baldwin 		p2->p_leader = p2;
577c6544064SJohn Baldwin 	}
578c6544064SJohn Baldwin 
5793fc755c1SJohn Baldwin 	sx_xlock(&proctree_lock);
5803fc755c1SJohn Baldwin 	PGRP_LOCK(p1->p_pgrp);
5813fc755c1SJohn Baldwin 	PROC_LOCK(p2);
5823fc755c1SJohn Baldwin 	PROC_LOCK(p1);
5833fc755c1SJohn Baldwin 
58470e534e7SDavid Greenman 	/*
5859752f794SJohn Baldwin 	 * Preserve some more flags in subprocess.  P_PROFIL has already
586be67169aSBruce Evans 	 * been preserved.
58770e534e7SDavid Greenman 	 */
588a30ec4b9SDavid Xu 	p2->p_flag |= p1->p_flag & P_SUGID;
589*aff57357SEd Schouten 	td2->td_pflags |= (td->td_pflags & TDP_ALTSTACK) | TDP_FORKING;
590f591779bSSeigo Tanimura 	SESS_LOCK(p1->p_session);
591df8bae1dSRodney W. Grimes 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
592df8bae1dSRodney W. Grimes 		p2->p_flag |= P_CONTROLT;
593f591779bSSeigo Tanimura 	SESS_UNLOCK(p1->p_session);
5940e3eb7eeSSujal Patel 	if (flags & RFPPWAIT)
595df8bae1dSRodney W. Grimes 		p2->p_flag |= P_PPWAIT;
596be67169aSBruce Evans 
5975cded904SOlivier Houchard 	p2->p_pgrp = p1->p_pgrp;
598b75356e1SJeffrey Hsu 	LIST_INSERT_AFTER(p1, p2, p_pglist);
5992a60b9b9SSeigo Tanimura 	PGRP_UNLOCK(p1->p_pgrp);
600b75356e1SJeffrey Hsu 	LIST_INIT(&p2->p_children);
601dcd43281SKonstantin Belousov 	LIST_INIT(&p2->p_orphans);
602b75356e1SJeffrey Hsu 
603f7e50ea7SKonstantin Belousov 	callout_init_mtx(&p2->p_itcallout, &p2->p_mtx, 0);
6044f559836SJake Burkholder 
605df8bae1dSRodney W. Grimes 	/*
606df95311aSMatthew N. Dodd 	 * If PF_FORK is set, the child process inherits the
607df95311aSMatthew N. Dodd 	 * procfs ioctl flags from its parent.
608df95311aSMatthew N. Dodd 	 */
609df95311aSMatthew N. Dodd 	if (p1->p_pfsflags & PF_FORK) {
610df95311aSMatthew N. Dodd 		p2->p_stops = p1->p_stops;
611df95311aSMatthew N. Dodd 		p2->p_pfsflags = p1->p_pfsflags;
612df95311aSMatthew N. Dodd 	}
613df95311aSMatthew N. Dodd 
614df95311aSMatthew N. Dodd 	/*
615df8bae1dSRodney W. Grimes 	 * This begins the section where we must prevent the parent
616cda5aba4SDavid Schultz 	 * from being swapped.
617df8bae1dSRodney W. Grimes 	 */
618cda5aba4SDavid Schultz 	_PHOLD(p1);
61957934cd3SJohn Baldwin 	PROC_UNLOCK(p1);
6200d2afceeSDavid Greenman 
621df8bae1dSRodney W. Grimes 	/*
6223fc755c1SJohn Baldwin 	 * Attach the new process to its parent.
6233fc755c1SJohn Baldwin 	 *
6243fc755c1SJohn Baldwin 	 * If RFNOWAIT is set, the newly created process becomes a child
6253fc755c1SJohn Baldwin 	 * of init.  This effectively disassociates the child from the
6263fc755c1SJohn Baldwin 	 * parent.
6273fc755c1SJohn Baldwin 	 */
628237623b0SKonstantin Belousov 	if ((flags & RFNOWAIT) != 0) {
629237623b0SKonstantin Belousov 		pptr = p1->p_reaper;
630237623b0SKonstantin Belousov 		p2->p_reaper = pptr;
631237623b0SKonstantin Belousov 	} else {
632237623b0SKonstantin Belousov 		p2->p_reaper = (p1->p_treeflag & P_TREE_REAPER) != 0 ?
633237623b0SKonstantin Belousov 		    p1 : p1->p_reaper;
6343fc755c1SJohn Baldwin 		pptr = p1;
635237623b0SKonstantin Belousov 	}
6363fc755c1SJohn Baldwin 	p2->p_pptr = pptr;
6373fc755c1SJohn Baldwin 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
638237623b0SKonstantin Belousov 	LIST_INIT(&p2->p_reaplist);
639237623b0SKonstantin Belousov 	LIST_INSERT_HEAD(&p2->p_reaper->p_reaplist, p2, p_reapsibling);
640237623b0SKonstantin Belousov 	if (p2->p_reaper == p1)
641237623b0SKonstantin Belousov 		p2->p_reapsubtree = p2->p_pid;
6423fc755c1SJohn Baldwin 	sx_xunlock(&proctree_lock);
6433fc755c1SJohn Baldwin 
644bb0e8070SJohn Baldwin 	/* Inform accounting that we have forked. */
645bb0e8070SJohn Baldwin 	p2->p_acflag = AFORK;
646bb0e8070SJohn Baldwin 	PROC_UNLOCK(p2);
647bb0e8070SJohn Baldwin 
6487705d4b2SDmitry Chagin #ifdef KTRACE
6497705d4b2SDmitry Chagin 	ktrprocfork(p1, p2);
6507705d4b2SDmitry Chagin #endif
6517705d4b2SDmitry Chagin 
6523fc755c1SJohn Baldwin 	/*
653a2a1c95cSPeter Wemm 	 * Finish creating the child process.  It will return via a different
654a2a1c95cSPeter Wemm 	 * execution path later.  (ie: directly into user mode)
655dabee6feSPeter Wemm 	 */
65689b57fcfSKonstantin Belousov 	vm_forkproc(td, p2, td2, vm2, flags);
657df8bae1dSRodney W. Grimes 
6585d22597fSHajimu UMEMOTO 	if (flags == (RFFDG | RFPROC)) {
659393a081dSAttilio Rao 		PCPU_INC(cnt.v_forks);
660393a081dSAttilio Rao 		PCPU_ADD(cnt.v_forkpages, p2->p_vmspace->vm_dsize +
66194ddc707SAlan Cox 		    p2->p_vmspace->vm_ssize);
6625d22597fSHajimu UMEMOTO 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
663393a081dSAttilio Rao 		PCPU_INC(cnt.v_vforks);
664393a081dSAttilio Rao 		PCPU_ADD(cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
66594ddc707SAlan Cox 		    p2->p_vmspace->vm_ssize);
6665d22597fSHajimu UMEMOTO 	} else if (p1 == &proc0) {
667393a081dSAttilio Rao 		PCPU_INC(cnt.v_kthreads);
668393a081dSAttilio Rao 		PCPU_ADD(cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
66994ddc707SAlan Cox 		    p2->p_vmspace->vm_ssize);
6705d22597fSHajimu UMEMOTO 	} else {
671393a081dSAttilio Rao 		PCPU_INC(cnt.v_rforks);
672393a081dSAttilio Rao 		PCPU_ADD(cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
67394ddc707SAlan Cox 		    p2->p_vmspace->vm_ssize);
6745d22597fSHajimu UMEMOTO 	}
6755d22597fSHajimu UMEMOTO 
676cfb5f768SJonathan Anderson 	/*
677cfb5f768SJonathan Anderson 	 * Associate the process descriptor with the process before anything
678cfb5f768SJonathan Anderson 	 * can happen that might cause that process to need the descriptor.
679cfb5f768SJonathan Anderson 	 * However, don't do this until after fork(2) can no longer fail.
680cfb5f768SJonathan Anderson 	 */
681cfb5f768SJonathan Anderson 	if (flags & RFPROCDESC)
682cfb5f768SJonathan Anderson 		procdesc_new(p2, pdflags);
683cfb5f768SJonathan Anderson 
684df8bae1dSRodney W. Grimes 	/*
685e9189611SPeter Wemm 	 * Both processes are set up, now check if any loadable modules want
686e0d898b4SJulian Elischer 	 * to adjust anything.
687fed06968SJulian Elischer 	 */
68875b8b3b2SJohn Baldwin 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
689fed06968SJulian Elischer 
690fed06968SJulian Elischer 	/*
6914c3558aaSJohn Baldwin 	 * Set the child start time and mark the process as being complete.
6924c3558aaSJohn Baldwin 	 */
6938e6fa660SJohn Baldwin 	PROC_LOCK(p2);
6948e6fa660SJohn Baldwin 	PROC_LOCK(p1);
6954c3558aaSJohn Baldwin 	microuptime(&p2->p_stats->p_start);
69611bda9b8SJeff Roberson 	PROC_SLOCK(p2);
6974c3558aaSJohn Baldwin 	p2->p_state = PRS_NORMAL;
69811bda9b8SJeff Roberson 	PROC_SUNLOCK(p2);
6996fa39a73SKonstantin Belousov 
700d3555b6fSRui Paulo #ifdef KDTRACE_HOOKS
701d3555b6fSRui Paulo 	/*
7027159310fSMark Johnston 	 * Tell the DTrace fasttrap provider about the new process so that any
7037159310fSMark Johnston 	 * tracepoints inherited from the parent can be removed. We have to do
7047159310fSMark Johnston 	 * this only after p_state is PRS_NORMAL since the fasttrap module will
7057159310fSMark Johnston 	 * use pfind() later on.
706d3555b6fSRui Paulo 	 */
7077159310fSMark Johnston 	if ((flags & RFMEM) == 0 && dtrace_fasttrap_fork)
708d3555b6fSRui Paulo 		dtrace_fasttrap_fork(p1, p2);
709d3555b6fSRui Paulo #endif
7106fa39a73SKonstantin Belousov 	if ((p1->p_flag & (P_TRACED | P_FOLLOWFORK)) == (P_TRACED |
7116fa39a73SKonstantin Belousov 	    P_FOLLOWFORK)) {
7124c3558aaSJohn Baldwin 		/*
7136fa39a73SKonstantin Belousov 		 * Arrange for debugger to receive the fork event.
7146fa39a73SKonstantin Belousov 		 *
7156fa39a73SKonstantin Belousov 		 * We can report PL_FLAG_FORKED regardless of
7166fa39a73SKonstantin Belousov 		 * P_FOLLOWFORK settings, but it does not make a sense
7176fa39a73SKonstantin Belousov 		 * for runaway child.
718df8bae1dSRodney W. Grimes 		 */
7196fa39a73SKonstantin Belousov 		td->td_dbgflags |= TDB_FORK;
7206fa39a73SKonstantin Belousov 		td->td_dbg_forked = p2->p_pid;
7216fa39a73SKonstantin Belousov 		td2->td_dbgflags |= TDB_STOPATFORK;
7226fa39a73SKonstantin Belousov 		_PHOLD(p2);
7236fa39a73SKonstantin Belousov 		p2_held = 1;
7246fa39a73SKonstantin Belousov 	}
7251d7ca9bbSKonstantin Belousov 	if (flags & RFPPWAIT) {
7261d7ca9bbSKonstantin Belousov 		td->td_pflags |= TDP_RFPPWAIT;
7271d7ca9bbSKonstantin Belousov 		td->td_rfppwait_p = p2;
7281d7ca9bbSKonstantin Belousov 	}
7298e6fa660SJohn Baldwin 	PROC_UNLOCK(p2);
7300384fff8SJason Evans 	if ((flags & RFSTOPPED) == 0) {
7316fa39a73SKonstantin Belousov 		/*
7326fa39a73SKonstantin Belousov 		 * If RFSTOPPED not requested, make child runnable and
7336fa39a73SKonstantin Belousov 		 * add to run queue.
7346fa39a73SKonstantin Belousov 		 */
73511bda9b8SJeff Roberson 		thread_lock(td2);
73671fad9fdSJulian Elischer 		TD_SET_CAN_RUN(td2);
737f0393f06SJeff Roberson 		sched_add(td2, SRQ_BORING);
73811bda9b8SJeff Roberson 		thread_unlock(td2);
7390384fff8SJason Evans 	}
740df8bae1dSRodney W. Grimes 
741df8bae1dSRodney W. Grimes 	/*
742df8bae1dSRodney W. Grimes 	 * Now can be swapped.
743df8bae1dSRodney W. Grimes 	 */
74457934cd3SJohn Baldwin 	_PRELE(p1);
7457054ee4eSKonstantin Belousov 	PROC_UNLOCK(p1);
746df8bae1dSRodney W. Grimes 
747df8bae1dSRodney W. Grimes 	/*
74870fca427SJohn Baldwin 	 * Tell any interested parties about the new process.
749cb679c38SJonathan Lemon 	 */
7507054ee4eSKonstantin Belousov 	knote_fork(&p1->p_klist, p2->p_pid);
7512f2f522bSAndriy Gapon 	SDT_PROBE3(proc, kernel, , create, p2, p1, flags);
7525d217f17SJohn Birrell 
753cb679c38SJonathan Lemon 	/*
7546fa39a73SKonstantin Belousov 	 * Wait until debugger is attached to child.
7556fa39a73SKonstantin Belousov 	 */
7566fa39a73SKonstantin Belousov 	PROC_LOCK(p2);
7576fa39a73SKonstantin Belousov 	while ((td2->td_dbgflags & TDB_STOPATFORK) != 0)
7586fa39a73SKonstantin Belousov 		cv_wait(&p2->p_dbgwait, &p2->p_mtx);
7596fa39a73SKonstantin Belousov 	if (p2_held)
7606fa39a73SKonstantin Belousov 		_PRELE(p2);
76157934cd3SJohn Baldwin 	PROC_UNLOCK(p2);
762afd01097SEdward Tomasz Napierala }
763afd01097SEdward Tomasz Napierala 
764afd01097SEdward Tomasz Napierala int
765cfb5f768SJonathan Anderson fork1(struct thread *td, int flags, int pages, struct proc **procp,
766367a13f9SEd Schouten     int *procdescp, int pdflags, struct filecaps *fcaps)
767afd01097SEdward Tomasz Napierala {
7684b48959fSKonstantin Belousov 	struct proc *p1, *newproc;
769afd01097SEdward Tomasz Napierala 	struct thread *td2;
770afd01097SEdward Tomasz Napierala 	struct vmspace *vm2;
7714b48959fSKonstantin Belousov 	struct file *fp_procdesc;
772afd01097SEdward Tomasz Napierala 	vm_ooffset_t mem_charged;
7734b48959fSKonstantin Belousov 	int error, nprocs_new, ok;
774afd01097SEdward Tomasz Napierala 	static int curfail;
775afd01097SEdward Tomasz Napierala 	static struct timeval lastfail;
776afd01097SEdward Tomasz Napierala 
777f49d8202SKonstantin Belousov 	/* Check for the undefined or unimplemented flags. */
778f49d8202SKonstantin Belousov 	if ((flags & ~(RFFLAGS | RFTSIGFLAGS(RFTSIGMASK))) != 0)
779f49d8202SKonstantin Belousov 		return (EINVAL);
780f49d8202SKonstantin Belousov 
781f49d8202SKonstantin Belousov 	/* Signal value requires RFTSIGZMB. */
782f49d8202SKonstantin Belousov 	if ((flags & RFTSIGFLAGS(RFTSIGMASK)) != 0 && (flags & RFTSIGZMB) == 0)
783f49d8202SKonstantin Belousov 		return (EINVAL);
784f49d8202SKonstantin Belousov 
785afd01097SEdward Tomasz Napierala 	/* Can't copy and clear. */
786afd01097SEdward Tomasz Napierala 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
787afd01097SEdward Tomasz Napierala 		return (EINVAL);
788afd01097SEdward Tomasz Napierala 
789f49d8202SKonstantin Belousov 	/* Check the validity of the signal number. */
790f49d8202SKonstantin Belousov 	if ((flags & RFTSIGZMB) != 0 && (u_int)RFTSIGNUM(flags) > _SIG_MAXSIG)
791f49d8202SKonstantin Belousov 		return (EINVAL);
792f49d8202SKonstantin Belousov 
793cfb5f768SJonathan Anderson 	if ((flags & RFPROCDESC) != 0) {
794cfb5f768SJonathan Anderson 		/* Can't not create a process yet get a process descriptor. */
795cfb5f768SJonathan Anderson 		if ((flags & RFPROC) == 0)
796cfb5f768SJonathan Anderson 			return (EINVAL);
797cfb5f768SJonathan Anderson 
798cfb5f768SJonathan Anderson 		/* Must provide a place to put a procdesc if creating one. */
799cfb5f768SJonathan Anderson 		if (procdescp == NULL)
800cfb5f768SJonathan Anderson 			return (EINVAL);
801cfb5f768SJonathan Anderson 	}
802cfb5f768SJonathan Anderson 
803afd01097SEdward Tomasz Napierala 	p1 = td->td_proc;
804afd01097SEdward Tomasz Napierala 
805afd01097SEdward Tomasz Napierala 	/*
806afd01097SEdward Tomasz Napierala 	 * Here we don't create a new process, but we divorce
807afd01097SEdward Tomasz Napierala 	 * certain parts of a process from itself.
808afd01097SEdward Tomasz Napierala 	 */
8093e73ff1eSEdward Tomasz Napierala 	if ((flags & RFPROC) == 0) {
8103e73ff1eSEdward Tomasz Napierala 		*procp = NULL;
8113e73ff1eSEdward Tomasz Napierala 		return (fork_norfproc(td, flags));
8123e73ff1eSEdward Tomasz Napierala 	}
813afd01097SEdward Tomasz Napierala 
8144b48959fSKonstantin Belousov 	fp_procdesc = NULL;
8154b48959fSKonstantin Belousov 	newproc = NULL;
8164b48959fSKonstantin Belousov 	vm2 = NULL;
8174b48959fSKonstantin Belousov 
8184b48959fSKonstantin Belousov 	/*
8194b48959fSKonstantin Belousov 	 * Increment the nprocs resource before allocations occur.
8204b48959fSKonstantin Belousov 	 * Although process entries are dynamically created, we still
8214b48959fSKonstantin Belousov 	 * keep a global limit on the maximum number we will
8224b48959fSKonstantin Belousov 	 * create. There are hard-limits as to the number of processes
8234b48959fSKonstantin Belousov 	 * that can run, established by the KVA and memory usage for
8244b48959fSKonstantin Belousov 	 * the process data.
8254b48959fSKonstantin Belousov 	 *
8264b48959fSKonstantin Belousov 	 * Don't allow a nonprivileged user to use the last ten
8274b48959fSKonstantin Belousov 	 * processes; don't let root exceed the limit.
8284b48959fSKonstantin Belousov 	 */
8294b48959fSKonstantin Belousov 	nprocs_new = atomic_fetchadd_int(&nprocs, 1) + 1;
8304b48959fSKonstantin Belousov 	if ((nprocs_new >= maxproc - 10 && priv_check_cred(td->td_ucred,
8314b48959fSKonstantin Belousov 	    PRIV_MAXPROC, 0) != 0) || nprocs_new >= maxproc) {
8324b48959fSKonstantin Belousov 		error = EAGAIN;
8334b48959fSKonstantin Belousov 		sx_xlock(&allproc_lock);
8344b48959fSKonstantin Belousov 		if (ppsratecheck(&lastfail, &curfail, 1)) {
8354b48959fSKonstantin Belousov 			printf("maxproc limit exceeded by uid %u (pid %d); "
8364b48959fSKonstantin Belousov 			    "see tuning(7) and login.conf(5)\n",
8374b48959fSKonstantin Belousov 			    td->td_ucred->cr_ruid, p1->p_pid);
8384b48959fSKonstantin Belousov 		}
8394b48959fSKonstantin Belousov 		sx_xunlock(&allproc_lock);
8404b48959fSKonstantin Belousov 		goto fail2;
8414b48959fSKonstantin Belousov 	}
8424b48959fSKonstantin Belousov 
843cfb5f768SJonathan Anderson 	/*
844cfb5f768SJonathan Anderson 	 * If required, create a process descriptor in the parent first; we
845cfb5f768SJonathan Anderson 	 * will abandon it if something goes wrong. We don't finit() until
846cfb5f768SJonathan Anderson 	 * later.
847cfb5f768SJonathan Anderson 	 */
848cfb5f768SJonathan Anderson 	if (flags & RFPROCDESC) {
8496236e71bSEd Schouten 		error = falloc_caps(td, &fp_procdesc, procdescp, 0, fcaps);
850b38520f0SEdward Tomasz Napierala 		if (error != 0)
851d8f3dc78SKonstantin Belousov 			goto fail2;
852cfb5f768SJonathan Anderson 	}
853cfb5f768SJonathan Anderson 
854afd01097SEdward Tomasz Napierala 	mem_charged = 0;
855afd01097SEdward Tomasz Napierala 	if (pages == 0)
856edc82223SKonstantin Belousov 		pages = kstack_pages;
857afd01097SEdward Tomasz Napierala 	/* Allocate new proc. */
858afd01097SEdward Tomasz Napierala 	newproc = uma_zalloc(proc_zone, M_WAITOK);
859afd01097SEdward Tomasz Napierala 	td2 = FIRST_THREAD_IN_PROC(newproc);
860afd01097SEdward Tomasz Napierala 	if (td2 == NULL) {
861afd01097SEdward Tomasz Napierala 		td2 = thread_alloc(pages);
862afd01097SEdward Tomasz Napierala 		if (td2 == NULL) {
863afd01097SEdward Tomasz Napierala 			error = ENOMEM;
86412cec311SMateusz Guzik 			goto fail2;
865afd01097SEdward Tomasz Napierala 		}
866afd01097SEdward Tomasz Napierala 		proc_linkup(newproc, td2);
867afd01097SEdward Tomasz Napierala 	} else {
868afd01097SEdward Tomasz Napierala 		if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
869afd01097SEdward Tomasz Napierala 			if (td2->td_kstack != 0)
870afd01097SEdward Tomasz Napierala 				vm_thread_dispose(td2);
871afd01097SEdward Tomasz Napierala 			if (!thread_alloc_stack(td2, pages)) {
872afd01097SEdward Tomasz Napierala 				error = ENOMEM;
87312cec311SMateusz Guzik 				goto fail2;
874afd01097SEdward Tomasz Napierala 			}
875afd01097SEdward Tomasz Napierala 		}
876afd01097SEdward Tomasz Napierala 	}
877afd01097SEdward Tomasz Napierala 
878afd01097SEdward Tomasz Napierala 	if ((flags & RFMEM) == 0) {
879afd01097SEdward Tomasz Napierala 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
880afd01097SEdward Tomasz Napierala 		if (vm2 == NULL) {
881afd01097SEdward Tomasz Napierala 			error = ENOMEM;
88212cec311SMateusz Guzik 			goto fail2;
883afd01097SEdward Tomasz Napierala 		}
884afd01097SEdward Tomasz Napierala 		if (!swap_reserve(mem_charged)) {
885afd01097SEdward Tomasz Napierala 			/*
886afd01097SEdward Tomasz Napierala 			 * The swap reservation failed. The accounting
887afd01097SEdward Tomasz Napierala 			 * from the entries of the copied vm2 will be
888afd01097SEdward Tomasz Napierala 			 * substracted in vmspace_free(), so force the
889afd01097SEdward Tomasz Napierala 			 * reservation there.
890afd01097SEdward Tomasz Napierala 			 */
891afd01097SEdward Tomasz Napierala 			swap_reserve_force(mem_charged);
892afd01097SEdward Tomasz Napierala 			error = ENOMEM;
89312cec311SMateusz Guzik 			goto fail2;
894afd01097SEdward Tomasz Napierala 		}
895afd01097SEdward Tomasz Napierala 	} else
896afd01097SEdward Tomasz Napierala 		vm2 = NULL;
897afd01097SEdward Tomasz Napierala 
898097055e2SEdward Tomasz Napierala 	/*
899097055e2SEdward Tomasz Napierala 	 * XXX: This is ugly; when we copy resource usage, we need to bump
900097055e2SEdward Tomasz Napierala 	 *      per-cred resource counters.
901097055e2SEdward Tomasz Napierala 	 */
902ffb34484SMateusz Guzik 	proc_set_cred_init(newproc, crhold(td->td_ucred));
903097055e2SEdward Tomasz Napierala 
904097055e2SEdward Tomasz Napierala 	/*
905097055e2SEdward Tomasz Napierala 	 * Initialize resource accounting for the child process.
906097055e2SEdward Tomasz Napierala 	 */
907097055e2SEdward Tomasz Napierala 	error = racct_proc_fork(p1, newproc);
908097055e2SEdward Tomasz Napierala 	if (error != 0) {
909097055e2SEdward Tomasz Napierala 		error = EAGAIN;
910097055e2SEdward Tomasz Napierala 		goto fail1;
911097055e2SEdward Tomasz Napierala 	}
912097055e2SEdward Tomasz Napierala 
9131dbf9dccSEdward Tomasz Napierala #ifdef MAC
9141dbf9dccSEdward Tomasz Napierala 	mac_proc_init(newproc);
9151dbf9dccSEdward Tomasz Napierala #endif
9161dbf9dccSEdward Tomasz Napierala 	knlist_init_mtx(&newproc->p_klist, &newproc->p_mtx);
9171dbf9dccSEdward Tomasz Napierala 	STAILQ_INIT(&newproc->p_ktr);
9181dbf9dccSEdward Tomasz Napierala 
919afd01097SEdward Tomasz Napierala 	/* We have to lock the process tree while we look for a pid. */
920afd01097SEdward Tomasz Napierala 	sx_slock(&proctree_lock);
921afd01097SEdward Tomasz Napierala 	sx_xlock(&allproc_lock);
922afd01097SEdward Tomasz Napierala 
92358c77a9dSEdward Tomasz Napierala 	/*
924afd01097SEdward Tomasz Napierala 	 * Increment the count of procs running with this uid. Don't allow
925afd01097SEdward Tomasz Napierala 	 * a nonprivileged user to exceed their current limit.
926afd01097SEdward Tomasz Napierala 	 *
927afd01097SEdward Tomasz Napierala 	 * XXXRW: Can we avoid privilege here if it's not needed?
928afd01097SEdward Tomasz Napierala 	 */
929afd01097SEdward Tomasz Napierala 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
930afd01097SEdward Tomasz Napierala 	if (error == 0)
931afd01097SEdward Tomasz Napierala 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
932afd01097SEdward Tomasz Napierala 	else {
933afd01097SEdward Tomasz Napierala 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
934f6f6d240SMateusz Guzik 		    lim_cur(td, RLIMIT_NPROC));
935afd01097SEdward Tomasz Napierala 	}
936afd01097SEdward Tomasz Napierala 	if (ok) {
937cfb5f768SJonathan Anderson 		do_fork(td, flags, newproc, td2, vm2, pdflags);
938afd01097SEdward Tomasz Napierala 
93949539972SJulian Elischer 		/*
940df8abd0bSPeter Wemm 		 * Return child proc pointer to parent.
941df8bae1dSRodney W. Grimes 		 */
942afd01097SEdward Tomasz Napierala 		*procp = newproc;
9430a7007b9SPawel Jakub Dawidek 		if (flags & RFPROCDESC) {
944cfb5f768SJonathan Anderson 			procdesc_finit(newproc->p_procdesc, fp_procdesc);
9450a7007b9SPawel Jakub Dawidek 			fdrop(fp_procdesc, td);
9460a7007b9SPawel Jakub Dawidek 		}
94772a401d9SEdward Tomasz Napierala 		racct_proc_fork_done(newproc);
948df8bae1dSRodney W. Grimes 		return (0);
949afd01097SEdward Tomasz Napierala 	}
950afd01097SEdward Tomasz Napierala 
951afd01097SEdward Tomasz Napierala 	error = EAGAIN;
9525ce2f678SJohn Baldwin 	sx_sunlock(&proctree_lock);
953c6544064SJohn Baldwin 	sx_xunlock(&allproc_lock);
9546bea667fSRobert Watson #ifdef MAC
95530d239bcSRobert Watson 	mac_proc_destroy(newproc);
9566bea667fSRobert Watson #endif
9571dbf9dccSEdward Tomasz Napierala 	racct_proc_exit(newproc);
958ab27d5d8SEdward Tomasz Napierala fail1:
959edf1796dSMateusz Guzik 	crfree(newproc->p_ucred);
960edf1796dSMateusz Guzik 	newproc->p_ucred = NULL;
96112cec311SMateusz Guzik fail2:
96269aa768aSKonstantin Belousov 	if (vm2 != NULL)
96369aa768aSKonstantin Belousov 		vmspace_free(vm2);
964c6544064SJohn Baldwin 	uma_zfree(proc_zone, newproc);
965de265498SPawel Jakub Dawidek 	if ((flags & RFPROCDESC) != 0 && fp_procdesc != NULL) {
96690f54cbfSMateusz Guzik 		fdclose(td, fp_procdesc, *procdescp);
967cfb5f768SJonathan Anderson 		fdrop(fp_procdesc, td);
9680a7007b9SPawel Jakub Dawidek 	}
9694b48959fSKonstantin Belousov 	atomic_add_int(&nprocs, -1);
97084d37a46SJohn Baldwin 	pause("fork", hz / 2);
971c6544064SJohn Baldwin 	return (error);
972df8bae1dSRodney W. Grimes }
973fed06968SJulian Elischer 
974e0d898b4SJulian Elischer /*
975a7b124c3SJohn Baldwin  * Handle the return of a child process from fork1().  This function
976a7b124c3SJohn Baldwin  * is called from the MD fork_trampoline() entry point.
977a7b124c3SJohn Baldwin  */
978a7b124c3SJohn Baldwin void
9791d845e86SEdward Tomasz Napierala fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
9801d845e86SEdward Tomasz Napierala     struct trapframe *frame)
981a7b124c3SJohn Baldwin {
982696058c3SJulian Elischer 	struct proc *p;
98370fca427SJohn Baldwin 	struct thread *td;
984fe54587fSJeff Roberson 	struct thread *dtd;
98570fca427SJohn Baldwin 
9860047b9a9SBosko Milekic 	td = curthread;
9870047b9a9SBosko Milekic 	p = td->td_proc;
9880047b9a9SBosko Milekic 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
9890047b9a9SBosko Milekic 
9906617724cSJeff Roberson 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
991e01eafefSJulian Elischer 		td, td->td_sched, p->p_pid, td->td_name);
9920047b9a9SBosko Milekic 
99311bda9b8SJeff Roberson 	sched_fork_exit(td);
994a7b124c3SJohn Baldwin 	/*
995fe54587fSJeff Roberson 	* Processes normally resume in mi_switch() after being
996fe54587fSJeff Roberson 	* cpu_switch()'ed to, but when children start up they arrive here
997fe54587fSJeff Roberson 	* instead, so we must do much the same things as mi_switch() would.
998fe54587fSJeff Roberson 	*/
999fe54587fSJeff Roberson 	if ((dtd = PCPU_GET(deadthread))) {
1000fe54587fSJeff Roberson 		PCPU_SET(deadthread, NULL);
1001fe54587fSJeff Roberson 		thread_stash(dtd);
1002fe54587fSJeff Roberson 	}
1003fe54587fSJeff Roberson 	thread_unlock(td);
1004fe54587fSJeff Roberson 
1005fe54587fSJeff Roberson 	/*
1006a7b124c3SJohn Baldwin 	 * cpu_set_fork_handler intercepts this function call to
1007a7b124c3SJohn Baldwin 	 * have this call a non-return function to stay in kernel mode.
1008a7b124c3SJohn Baldwin 	 * initproc has its own fork handler, but it does return.
1009a7b124c3SJohn Baldwin 	 */
10105813dc03SJohn Baldwin 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
10118865286bSJohn Baldwin 	callout(arg, frame);
1012a7b124c3SJohn Baldwin 
1013a7b124c3SJohn Baldwin 	/*
1014a7b124c3SJohn Baldwin 	 * Check if a kernel thread misbehaved and returned from its main
1015a7b124c3SJohn Baldwin 	 * function.
1016a7b124c3SJohn Baldwin 	 */
1017a7b124c3SJohn Baldwin 	if (p->p_flag & P_KTHREAD) {
1018a7b124c3SJohn Baldwin 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
1019e01eafefSJulian Elischer 		    td->td_name, p->p_pid);
10203745c395SJulian Elischer 		kproc_exit(0);
1021a7b124c3SJohn Baldwin 	}
1022a7b124c3SJohn Baldwin 	mtx_assert(&Giant, MA_NOTOWNED);
1023993182e5SAlexander Leidinger 
1024e5d81ef1SDmitry Chagin 	if (p->p_sysent->sv_schedtail != NULL)
1025e5d81ef1SDmitry Chagin 		(p->p_sysent->sv_schedtail)(td);
1026*aff57357SEd Schouten 	td->td_pflags &= ~TDP_FORKING;
1027a7b124c3SJohn Baldwin }
1028a7b124c3SJohn Baldwin 
1029a7b124c3SJohn Baldwin /*
1030a7b124c3SJohn Baldwin  * Simplified back end of syscall(), used when returning from fork()
1031a7b124c3SJohn Baldwin  * directly into user mode.  Giant is not held on entry, and must not
1032a7b124c3SJohn Baldwin  * be held on return.  This function is passed in to fork_exit() as the
1033a7b124c3SJohn Baldwin  * first parameter and is called when returning to a new userland process.
1034a7b124c3SJohn Baldwin  */
1035a7b124c3SJohn Baldwin void
10361d845e86SEdward Tomasz Napierala fork_return(struct thread *td, struct trapframe *frame)
1037a7b124c3SJohn Baldwin {
10386fa39a73SKonstantin Belousov 	struct proc *p, *dbg;
10396fa39a73SKonstantin Belousov 
10406fa39a73SKonstantin Belousov 	p = td->td_proc;
1041189ac973SJohn Baldwin 	if (td->td_dbgflags & TDB_STOPATFORK) {
10426fa39a73SKonstantin Belousov 		sx_xlock(&proctree_lock);
10436fa39a73SKonstantin Belousov 		PROC_LOCK(p);
10446fa39a73SKonstantin Belousov 		if ((p->p_pptr->p_flag & (P_TRACED | P_FOLLOWFORK)) ==
10456fa39a73SKonstantin Belousov 		    (P_TRACED | P_FOLLOWFORK)) {
10466fa39a73SKonstantin Belousov 			/*
10476fa39a73SKonstantin Belousov 			 * If debugger still wants auto-attach for the
10486fa39a73SKonstantin Belousov 			 * parent's children, do it now.
10496fa39a73SKonstantin Belousov 			 */
10506fa39a73SKonstantin Belousov 			dbg = p->p_pptr->p_pptr;
10516fa39a73SKonstantin Belousov 			p->p_flag |= P_TRACED;
10526fa39a73SKonstantin Belousov 			p->p_oppid = p->p_pptr->p_pid;
1053515b7a0bSJohn Baldwin 			CTR2(KTR_PTRACE,
1054515b7a0bSJohn Baldwin 		    "fork_return: attaching to new child pid %d: oppid %d",
1055515b7a0bSJohn Baldwin 			    p->p_pid, p->p_oppid);
10566fa39a73SKonstantin Belousov 			proc_reparent(p, dbg);
10576fa39a73SKonstantin Belousov 			sx_xunlock(&proctree_lock);
1058189ac973SJohn Baldwin 			td->td_dbgflags |= TDB_CHILD | TDB_SCX;
10596fa39a73SKonstantin Belousov 			ptracestop(td, SIGSTOP);
1060189ac973SJohn Baldwin 			td->td_dbgflags &= ~(TDB_CHILD | TDB_SCX);
10616fa39a73SKonstantin Belousov 		} else {
10626fa39a73SKonstantin Belousov 			/*
10636fa39a73SKonstantin Belousov 			 * ... otherwise clear the request.
10646fa39a73SKonstantin Belousov 			 */
10656fa39a73SKonstantin Belousov 			sx_xunlock(&proctree_lock);
10666fa39a73SKonstantin Belousov 			td->td_dbgflags &= ~TDB_STOPATFORK;
10676fa39a73SKonstantin Belousov 			cv_broadcast(&p->p_dbgwait);
10686fa39a73SKonstantin Belousov 		}
10696fa39a73SKonstantin Belousov 		PROC_UNLOCK(p);
1070189ac973SJohn Baldwin 	} else if (p->p_flag & P_TRACED) {
1071189ac973SJohn Baldwin  		/*
1072189ac973SJohn Baldwin 		 * This is the start of a new thread in a traced
1073189ac973SJohn Baldwin 		 * process.  Report a system call exit event.
1074189ac973SJohn Baldwin 		 */
1075189ac973SJohn Baldwin 		PROC_LOCK(p);
1076189ac973SJohn Baldwin 		td->td_dbgflags |= TDB_SCX;
1077189ac973SJohn Baldwin 		_STOPEVENT(p, S_SCX, td->td_dbg_sc_code);
1078189ac973SJohn Baldwin 		if ((p->p_stops & S_PT_SCX) != 0)
1079189ac973SJohn Baldwin 			ptracestop(td, SIGTRAP);
1080189ac973SJohn Baldwin 		td->td_dbgflags &= ~TDB_SCX;
1081189ac973SJohn Baldwin 		PROC_UNLOCK(p);
10826fa39a73SKonstantin Belousov 	}
1083a7b124c3SJohn Baldwin 
1084eb2da9a5SPoul-Henning Kamp 	userret(td, frame);
10856fa39a73SKonstantin Belousov 
1086a7b124c3SJohn Baldwin #ifdef KTRACE
1087af300f23SJohn Baldwin 	if (KTRPOINT(td, KTR_SYSRET))
1088af300f23SJohn Baldwin 		ktrsysret(SYS_fork, 0, 0);
1089a7b124c3SJohn Baldwin #endif
1090a7b124c3SJohn Baldwin }
1091