xref: /freebsd/sys/kern/kern_fork.c (revision 9b48646ab366dcf6089fac653eef963331aa1169)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include "opt_ktrace.h"
38 #include "opt_kstack_pages.h"
39 
40 #define EXTERR_CATEGORY	EXTERR_CAT_FORK
41 #include <sys/systm.h>
42 #include <sys/acct.h>
43 #include <sys/bitstring.h>
44 #include <sys/eventhandler.h>
45 #include <sys/exterrvar.h>
46 #include <sys/fcntl.h>
47 #include <sys/filedesc.h>
48 #include <sys/jail.h>
49 #include <sys/kernel.h>
50 #include <sys/kthread.h>
51 #include <sys/ktr.h>
52 #include <sys/ktrace.h>
53 #include <sys/sysctl.h>
54 #include <sys/lock.h>
55 #include <sys/malloc.h>
56 #include <sys/msan.h>
57 #include <sys/mutex.h>
58 #include <sys/priv.h>
59 #include <sys/proc.h>
60 #include <sys/procdesc.h>
61 #include <sys/ptrace.h>
62 #include <sys/racct.h>
63 #include <sys/resourcevar.h>
64 #include <sys/sched.h>
65 #include <sys/sdt.h>
66 #include <sys/signalvar.h>
67 #include <sys/sx.h>
68 #include <sys/syscall.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/sysent.h>
71 #include <sys/sysproto.h>
72 #include <sys/vmmeter.h>
73 #include <sys/vnode.h>
74 #include <sys/unistd.h>
75 
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
78 
79 #include <vm/vm.h>
80 #include <vm/pmap.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_extern.h>
83 #include <vm/uma.h>
84 
85 #ifdef KDTRACE_HOOKS
86 #include <sys/dtrace_bsd.h>
87 dtrace_fork_func_t	dtrace_fasttrap_fork;
88 #endif
89 
90 SDT_PROVIDER_DECLARE(proc);
91 SDT_PROBE_DEFINE3(proc, , , create, "struct proc *", "struct proc *", "int");
92 
93 #ifndef _SYS_SYSPROTO_H_
94 struct fork_args {
95 	int     dummy;
96 };
97 #endif
98 
99 /* ARGSUSED */
100 int
101 sys_fork(struct thread *td, struct fork_args *uap)
102 {
103 	struct fork_req fr;
104 	int error, pid;
105 
106 	bzero(&fr, sizeof(fr));
107 	fr.fr_flags = RFFDG | RFPROC;
108 	fr.fr_pidp = &pid;
109 	error = fork1(td, &fr);
110 	if (error == 0) {
111 		td->td_retval[0] = pid;
112 		td->td_retval[1] = 0;
113 	}
114 	return (error);
115 }
116 
117 /* ARGUSED */
118 int
119 sys_pdfork(struct thread *td, struct pdfork_args *uap)
120 {
121 	struct fork_req fr;
122 	int error, fd, pid;
123 
124 	bzero(&fr, sizeof(fr));
125 	fr.fr_flags = RFFDG | RFPROC | RFPROCDESC;
126 	fr.fr_pidp = &pid;
127 	fr.fr_pd_fd = &fd;
128 	fr.fr_pd_flags = uap->flags;
129 	AUDIT_ARG_FFLAGS(uap->flags);
130 	/*
131 	 * It is necessary to return fd by reference because 0 is a valid file
132 	 * descriptor number, and the child needs to be able to distinguish
133 	 * itself from the parent using the return value.
134 	 */
135 	error = fork1(td, &fr);
136 	if (error == 0) {
137 		td->td_retval[0] = pid;
138 		td->td_retval[1] = 0;
139 		error = copyout(&fd, uap->fdp, sizeof(fd));
140 	}
141 	return (error);
142 }
143 
144 /* ARGSUSED */
145 int
146 sys_vfork(struct thread *td, struct vfork_args *uap)
147 {
148 	struct fork_req fr;
149 	int error, pid;
150 
151 	bzero(&fr, sizeof(fr));
152 	fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
153 	fr.fr_pidp = &pid;
154 	error = fork1(td, &fr);
155 	if (error == 0) {
156 		td->td_retval[0] = pid;
157 		td->td_retval[1] = 0;
158 	}
159 	return (error);
160 }
161 
162 int
163 sys_rfork(struct thread *td, struct rfork_args *uap)
164 {
165 	struct fork_req fr;
166 	int error, pid;
167 
168 	/* Don't allow kernel-only flags. */
169 	if ((uap->flags & RFKERNELONLY) != 0)
170 		return (EXTERROR(EINVAL, "Kernel-only flags %#jx", uap->flags));
171 	/* RFSPAWN must not appear with others */
172 	if ((uap->flags & RFSPAWN) != 0 && uap->flags != RFSPAWN)
173 		return (EXTERROR(EINVAL, "RFSPAWN must be the only flag %#jx",
174 		    uap->flags));
175 
176 	AUDIT_ARG_FFLAGS(uap->flags);
177 	bzero(&fr, sizeof(fr));
178 	if ((uap->flags & RFSPAWN) != 0) {
179 		fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
180 		fr.fr_flags2 = FR2_DROPSIG_CAUGHT;
181 	} else {
182 		fr.fr_flags = uap->flags;
183 	}
184 	fr.fr_pidp = &pid;
185 	error = fork1(td, &fr);
186 	if (error == 0) {
187 		td->td_retval[0] = pid;
188 		td->td_retval[1] = 0;
189 	}
190 	return (error);
191 }
192 
193 int
194 sys_pdrfork(struct thread *td, struct pdrfork_args *uap)
195 {
196 	struct fork_req fr;
197 	int error, fd, pid;
198 
199 	bzero(&fr, sizeof(fr));
200 	fd = -1;
201 
202 	AUDIT_ARG_FFLAGS(uap->pdflags);
203 	AUDIT_ARG_CMD(uap->rfflags);
204 
205 	if ((uap->rfflags & (RFSTOPPED | RFHIGHPID)) != 0)
206 		return (EXTERROR(EINVAL,
207 		    "Kernel-only flags %#jx", uap->rfflags));
208 
209 	/* RFSPAWN must not appear with others */
210 	if ((uap->rfflags & RFSPAWN) != 0) {
211 		if (uap->rfflags != RFSPAWN)
212 			return (EXTERROR(EINVAL,
213 			    "RFSPAWN must be the only flag %#jx",
214 			    uap->rfflags));
215 		fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM | RFPROCDESC;
216 		fr.fr_flags2 = FR2_DROPSIG_CAUGHT;
217 	} else {
218 		if ((uap->rfflags & (RFPROC | RFPROCDESC)) !=
219 		    (RFPROC | RFPROCDESC)) {
220 			return (EXTERROR(EINVAL,
221 			    "RFPROC|RFPROCDESC required %#jx", uap->rfflags));
222 		}
223 		fr.fr_flags = uap->rfflags;
224 	}
225 
226 	fr.fr_pidp = &pid;
227 	fr.fr_pd_fd = &fd;
228 	fr.fr_pd_flags = uap->pdflags;
229 	error = fork1(td, &fr);
230 	if (error == 0) {
231 		td->td_retval[0] = pid;
232 		td->td_retval[1] = 0;
233 		if ((fr.fr_flags & (RFPROC | RFPROCDESC)) ==
234 		    (RFPROC | RFPROCDESC) || uap->rfflags == RFSPAWN)
235 			error = copyout(&fd, uap->fdp, sizeof(fd));
236 	}
237 	return (error);
238 }
239 
240 int __exclusive_cache_line	nprocs = 1;		/* process 0 */
241 int	lastpid = 0;
242 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
243     "Last used PID");
244 
245 /*
246  * Random component to lastpid generation.  We mix in a random factor to make
247  * it a little harder to predict.  We sanity check the modulus value to avoid
248  * doing it in critical paths.  Don't let it be too small or we pointlessly
249  * waste randomness entropy, and don't let it be impossibly large.  Using a
250  * modulus that is too big causes a LOT more process table scans and slows
251  * down fork processing as the pidchecked caching is defeated.
252  */
253 static int randompid = 0;
254 
255 static int
256 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
257 {
258 	int error, pid;
259 
260 	error = sysctl_wire_old_buffer(req, sizeof(int));
261 	if (error != 0)
262 		return(error);
263 	sx_xlock(&allproc_lock);
264 	pid = randompid;
265 	error = sysctl_handle_int(oidp, &pid, 0, req);
266 	if (error == 0 && req->newptr != NULL) {
267 		if (pid == 0)
268 			randompid = 0;
269 		else if (pid == 1)
270 			/* generate a random PID modulus between 100 and 1123 */
271 			randompid = 100 + arc4random() % 1024;
272 		else if (pid < 0 || pid > pid_max - 100)
273 			/* out of range */
274 			randompid = pid_max - 100;
275 		else if (pid < 100)
276 			/* Make it reasonable */
277 			randompid = 100;
278 		else
279 			randompid = pid;
280 	}
281 	sx_xunlock(&allproc_lock);
282 	return (error);
283 }
284 
285 SYSCTL_PROC(_kern, OID_AUTO, randompid,
286     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
287     sysctl_kern_randompid, "I",
288     "Random PID modulus. Special values: 0: disable, 1: choose random value");
289 
290 extern bitstr_t proc_id_pidmap;
291 extern bitstr_t proc_id_grpidmap;
292 extern bitstr_t proc_id_sessidmap;
293 extern bitstr_t proc_id_reapmap;
294 
295 /*
296  * Find an unused process ID
297  *
298  * If RFHIGHPID is set (used during system boot), do not allocate
299  * low-numbered pids.
300  */
301 static int
302 fork_findpid(int flags)
303 {
304 	pid_t result;
305 	int trypid, random;
306 
307 	/*
308 	 * Avoid calling arc4random with procid_lock held.
309 	 */
310 	random = 0;
311 	if (__predict_false(randompid))
312 		random = arc4random() % randompid;
313 
314 	mtx_lock(&procid_lock);
315 
316 	trypid = lastpid + 1;
317 	if (flags & RFHIGHPID) {
318 		if (trypid < 10)
319 			trypid = 10;
320 	} else {
321 		trypid += random;
322 	}
323 retry:
324 	if (trypid >= pid_max)
325 		trypid = 2;
326 
327 	bit_ffc_at(&proc_id_pidmap, trypid, pid_max, &result);
328 	if (result == -1) {
329 		KASSERT(trypid != 2, ("unexpectedly ran out of IDs"));
330 		trypid = 2;
331 		goto retry;
332 	}
333 	if (bit_test(&proc_id_grpidmap, result) ||
334 	    bit_test(&proc_id_sessidmap, result) ||
335 	    bit_test(&proc_id_reapmap, result)) {
336 		trypid = result + 1;
337 		goto retry;
338 	}
339 
340 	/*
341 	 * RFHIGHPID does not mess with the lastpid counter during boot.
342 	 */
343 	if ((flags & RFHIGHPID) == 0)
344 		lastpid = result;
345 
346 	bit_set(&proc_id_pidmap, result);
347 	mtx_unlock(&procid_lock);
348 
349 	return (result);
350 }
351 
352 static int
353 fork_norfproc(struct thread *td, int flags)
354 {
355 	struct proc *p1;
356 	int error;
357 
358 	KASSERT((flags & RFPROC) == 0,
359 	    ("fork_norfproc called with RFPROC set"));
360 	p1 = td->td_proc;
361 
362 	/*
363 	 * Quiesce other threads if necessary.  If RFMEM is not specified we
364 	 * must ensure that other threads do not concurrently create a second
365 	 * process sharing the vmspace, see vmspace_unshare().
366 	 */
367 	if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS &&
368 	    ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) {
369 		PROC_LOCK(p1);
370 		if (thread_single(p1, SINGLE_BOUNDARY)) {
371 			PROC_UNLOCK(p1);
372 			return (ERESTART);
373 		}
374 		PROC_UNLOCK(p1);
375 	}
376 
377 	error = vm_forkproc(td, NULL, NULL, NULL, flags);
378 	if (error != 0)
379 		goto fail;
380 
381 	/*
382 	 * Close all file descriptors.
383 	 */
384 	if ((flags & RFCFDG) != 0) {
385 		struct filedesc *fdtmp;
386 		struct pwddesc *pdtmp;
387 
388 		pdtmp = pdinit(td->td_proc->p_pd, false);
389 		fdtmp = fdinit();
390 		pdescfree(td);
391 		fdescfree(td);
392 		p1->p_fd = fdtmp;
393 		p1->p_pd = pdtmp;
394 	}
395 
396 	/*
397 	 * Unshare file descriptors (from parent).
398 	 */
399 	if ((flags & RFFDG) != 0) {
400 		fdunshare(td);
401 		pdunshare(td);
402 	}
403 
404 fail:
405 	if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS &&
406 	    ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) {
407 		PROC_LOCK(p1);
408 		thread_single_end(p1, SINGLE_BOUNDARY);
409 		PROC_UNLOCK(p1);
410 	}
411 	return (error);
412 }
413 
414 static void
415 do_fork(struct thread *td, struct fork_req *fr, struct proc *p2, struct thread *td2,
416     struct vmspace *vm2, struct file *fp_procdesc)
417 {
418 	struct proc *p1, *pptr;
419 	struct filedesc *fd;
420 	struct filedesc_to_leader *fdtol;
421 	struct pwddesc *pd;
422 	struct sigacts *newsigacts;
423 
424 	p1 = td->td_proc;
425 
426 	PROC_LOCK(p1);
427 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
428 	    __rangeof(struct proc, p_startcopy, p_endcopy));
429 	pargs_hold(p2->p_args);
430 	PROC_UNLOCK(p1);
431 
432 	bzero(&p2->p_startzero,
433 	    __rangeof(struct proc, p_startzero, p_endzero));
434 
435 	/* Tell the prison that we exist. */
436 	prison_proc_hold(p2->p_ucred->cr_prison);
437 
438 	p2->p_state = PRS_NEW;		/* protect against others */
439 	p2->p_pid = fork_findpid(fr->fr_flags);
440 	AUDIT_ARG_PID(p2->p_pid);
441 	TSFORK(p2->p_pid, p1->p_pid);
442 
443 	sx_xlock(&allproc_lock);
444 	LIST_INSERT_HEAD(&allproc, p2, p_list);
445 	allproc_gen++;
446 	prison_proc_link(p2->p_ucred->cr_prison, p2);
447 	sx_xunlock(&allproc_lock);
448 
449 	sx_xlock(PIDHASHLOCK(p2->p_pid));
450 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
451 	sx_xunlock(PIDHASHLOCK(p2->p_pid));
452 
453 	tidhash_add(td2);
454 
455 	/*
456 	 * Malloc things while we don't hold any locks.
457 	 */
458 	if (fr->fr_flags & RFSIGSHARE)
459 		newsigacts = NULL;
460 	else
461 		newsigacts = sigacts_alloc();
462 
463 	/*
464 	 * Copy filedesc.
465 	 */
466 	if (fr->fr_flags & RFCFDG) {
467 		pd = pdinit(p1->p_pd, false);
468 		fd = fdinit();
469 		fdtol = NULL;
470 	} else if (fr->fr_flags & RFFDG) {
471 		if (fr->fr_flags2 & FR2_SHARE_PATHS)
472 			pd = pdshare(p1->p_pd);
473 		else
474 			pd = pdcopy(p1->p_pd);
475 		fd = fdcopy(p1->p_fd, p2);
476 		fdtol = NULL;
477 	} else {
478 		if (fr->fr_flags2 & FR2_SHARE_PATHS)
479 			pd = pdcopy(p1->p_pd);
480 		else
481 			pd = pdshare(p1->p_pd);
482 		fd = fdshare(p1->p_fd);
483 		if (p1->p_fdtol == NULL)
484 			p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL,
485 			    p1->p_leader);
486 		if ((fr->fr_flags & RFTHREAD) != 0) {
487 			/*
488 			 * Shared file descriptor table, and shared
489 			 * process leaders.
490 			 */
491 			fdtol = filedesc_to_leader_share(p1->p_fdtol, p1->p_fd);
492 		} else {
493 			/*
494 			 * Shared file descriptor table, and different
495 			 * process leaders.
496 			 */
497 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
498 			    p1->p_fd, p2);
499 		}
500 	}
501 	/*
502 	 * Make a proc table entry for the new process.
503 	 * Start by zeroing the section of proc that is zero-initialized,
504 	 * then copy the section that is copied directly from the parent.
505 	 */
506 
507 	PROC_LOCK(p2);
508 	PROC_LOCK(p1);
509 
510 	bzero(&td2->td_startzero,
511 	    __rangeof(struct thread, td_startzero, td_endzero));
512 
513 	bcopy(&td->td_startcopy, &td2->td_startcopy,
514 	    __rangeof(struct thread, td_startcopy, td_endcopy));
515 
516 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
517 	td2->td_sigstk = td->td_sigstk;
518 	td2->td_flags = TDF_INMEM;
519 	td2->td_lend_user_pri = PRI_MAX;
520 
521 #ifdef VIMAGE
522 	td2->td_vnet = NULL;
523 	td2->td_vnet_lpush = NULL;
524 #endif
525 
526 	/*
527 	 * Allow the scheduler to initialize the child.
528 	 */
529 	thread_lock(td);
530 	sched_fork(td, td2);
531 	/*
532 	 * Request AST to check for TDP_RFPPWAIT.  Do it here
533 	 * to avoid calling thread_lock() again.
534 	 */
535 	if ((fr->fr_flags & RFPPWAIT) != 0)
536 		ast_sched_locked(td, TDA_VFORK);
537 	thread_unlock(td);
538 
539 	/*
540 	 * Duplicate sub-structures as needed.
541 	 * Increase reference counts on shared objects.
542 	 */
543 	p2->p_flag = P_INMEM;
544 	p2->p_flag2 = p1->p_flag2 & (P2_ASLR_DISABLE | P2_ASLR_ENABLE |
545 	    P2_ASLR_IGNSTART | P2_NOTRACE | P2_NOTRACE_EXEC |
546 	    P2_PROTMAX_ENABLE | P2_PROTMAX_DISABLE | P2_TRAPCAP |
547 	    P2_STKGAP_DISABLE | P2_STKGAP_DISABLE_EXEC | P2_NO_NEW_PRIVS |
548 	    P2_WXORX_DISABLE | P2_WXORX_ENABLE_EXEC | P2_LOGSIGEXIT_CTL |
549 	    P2_LOGSIGEXIT_ENABLE);
550 	p2->p_swtick = ticks;
551 	if (p1->p_flag & P_PROFIL)
552 		startprofclock(p2);
553 
554 	if (fr->fr_flags & RFSIGSHARE) {
555 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
556 	} else {
557 		sigacts_copy(newsigacts, p1->p_sigacts);
558 		p2->p_sigacts = newsigacts;
559 		if ((fr->fr_flags2 & (FR2_DROPSIG_CAUGHT | FR2_KPROC)) != 0) {
560 			mtx_lock(&p2->p_sigacts->ps_mtx);
561 			if ((fr->fr_flags2 & FR2_DROPSIG_CAUGHT) != 0)
562 				sig_drop_caught(p2);
563 			if ((fr->fr_flags2 & FR2_KPROC) != 0)
564 				p2->p_sigacts->ps_flag |= PS_NOCLDWAIT;
565 			mtx_unlock(&p2->p_sigacts->ps_mtx);
566 		}
567 	}
568 
569 	if (fr->fr_flags & RFTSIGZMB)
570 	        p2->p_sigparent = RFTSIGNUM(fr->fr_flags);
571 	else if (fr->fr_flags & RFLINUXTHPN)
572 	        p2->p_sigparent = SIGUSR1;
573 	else
574 	        p2->p_sigparent = SIGCHLD;
575 
576 	if ((fr->fr_flags2 & FR2_KPROC) != 0) {
577 		p2->p_flag |= P_SYSTEM | P_KPROC;
578 		td2->td_pflags |= TDP_KTHREAD;
579 	}
580 
581 	p2->p_textvp = p1->p_textvp;
582 	p2->p_textdvp = p1->p_textdvp;
583 	p2->p_fd = fd;
584 	p2->p_fdtol = fdtol;
585 	p2->p_pd = pd;
586 
587 	if (p1->p_flag2 & P2_INHERIT_PROTECTED) {
588 		p2->p_flag |= P_PROTECTED;
589 		p2->p_flag2 |= P2_INHERIT_PROTECTED;
590 	}
591 
592 	/*
593 	 * p_limit is copy-on-write.  Bump its refcount.
594 	 */
595 	lim_fork(p1, p2);
596 
597 	thread_cow_get_proc(td2, p2);
598 
599 	pstats_fork(p1->p_stats, p2->p_stats);
600 
601 	PROC_UNLOCK(p1);
602 	PROC_UNLOCK(p2);
603 
604 	/*
605 	 * Bump references to the text vnode and directory, and copy
606 	 * the hardlink name.
607 	 */
608 	if (p2->p_textvp != NULL)
609 		vrefact(p2->p_textvp);
610 	if (p2->p_textdvp != NULL)
611 		vrefact(p2->p_textdvp);
612 	p2->p_binname = p1->p_binname == NULL ? NULL :
613 	    strdup(p1->p_binname, M_PARGS);
614 
615 	/*
616 	 * Set up linkage for kernel based threading.
617 	 */
618 	if ((fr->fr_flags & RFTHREAD) != 0) {
619 		mtx_lock(&ppeers_lock);
620 		p2->p_peers = p1->p_peers;
621 		p1->p_peers = p2;
622 		p2->p_leader = p1->p_leader;
623 		mtx_unlock(&ppeers_lock);
624 		PROC_LOCK(p1->p_leader);
625 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
626 			PROC_UNLOCK(p1->p_leader);
627 			/*
628 			 * The task leader is exiting, so process p1 is
629 			 * going to be killed shortly.  Since p1 obviously
630 			 * isn't dead yet, we know that the leader is either
631 			 * sending SIGKILL's to all the processes in this
632 			 * task or is sleeping waiting for all the peers to
633 			 * exit.  We let p1 complete the fork, but we need
634 			 * to go ahead and kill the new process p2 since
635 			 * the task leader may not get a chance to send
636 			 * SIGKILL to it.  We leave it on the list so that
637 			 * the task leader will wait for this new process
638 			 * to commit suicide.
639 			 */
640 			PROC_LOCK(p2);
641 			kern_psignal(p2, SIGKILL);
642 			PROC_UNLOCK(p2);
643 		} else
644 			PROC_UNLOCK(p1->p_leader);
645 	} else {
646 		p2->p_peers = NULL;
647 		p2->p_leader = p2;
648 	}
649 
650 	sx_xlock(&proctree_lock);
651 	PGRP_LOCK(p1->p_pgrp);
652 	PROC_LOCK(p2);
653 	PROC_LOCK(p1);
654 
655 	/*
656 	 * Preserve some more flags in subprocess.  P_PROFIL has already
657 	 * been preserved.
658 	 */
659 	p2->p_flag |= p1->p_flag & P_SUGID;
660 	td2->td_pflags |= td->td_pflags & (TDP_ALTSTACK | TDP_SIGFASTBLOCK);
661 	td2->td_pflags2 |= td->td_pflags2 & TDP2_UEXTERR;
662 	if (p1->p_flag & P_CONTROLT) {
663 		SESS_LOCK(p1->p_session);
664 		if (p1->p_session->s_ttyvp != NULL)
665 			p2->p_flag |= P_CONTROLT;
666 		SESS_UNLOCK(p1->p_session);
667 	}
668 	if (fr->fr_flags & RFPPWAIT)
669 		p2->p_flag |= P_PPWAIT;
670 
671 	p2->p_pgrp = p1->p_pgrp;
672 	LIST_INSERT_AFTER(p1, p2, p_pglist);
673 	PGRP_UNLOCK(p1->p_pgrp);
674 	LIST_INIT(&p2->p_children);
675 	LIST_INIT(&p2->p_orphans);
676 
677 	callout_init_mtx(&p2->p_itcallout, &p2->p_mtx, 0);
678 
679 	PROC_UNLOCK(p1);
680 
681 	/*
682 	 * Attach the new process to its parent.
683 	 *
684 	 * If RFNOWAIT is set, the newly created process becomes a child
685 	 * of init.  This effectively disassociates the child from the
686 	 * parent.
687 	 */
688 	if ((fr->fr_flags & RFNOWAIT) != 0) {
689 		pptr = p1->p_reaper;
690 		p2->p_reaper = pptr;
691 	} else {
692 		p2->p_reaper = (p1->p_treeflag & P_TREE_REAPER) != 0 ?
693 		    p1 : p1->p_reaper;
694 		pptr = p1;
695 	}
696 	p2->p_pptr = pptr;
697 	p2->p_oppid = pptr->p_pid;
698 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
699 	LIST_INIT(&p2->p_reaplist);
700 	LIST_INSERT_HEAD(&p2->p_reaper->p_reaplist, p2, p_reapsibling);
701 	if (p2->p_reaper == p1 && p1 != initproc) {
702 		p2->p_reapsubtree = p2->p_pid;
703 		proc_id_set_cond(PROC_ID_REAP, p2->p_pid);
704 	}
705 	sx_xunlock(&proctree_lock);
706 
707 	/* Inform accounting that we have forked. */
708 	p2->p_acflag = AFORK;
709 	PROC_UNLOCK(p2);
710 
711 #ifdef KTRACE
712 	ktrprocfork(p1, p2);
713 #endif
714 
715 	/*
716 	 * Finish creating the child process.  It will return via a different
717 	 * execution path later.  (ie: directly into user mode)
718 	 */
719 	vm_forkproc(td, p2, td2, vm2, fr->fr_flags);
720 
721 	if (fr->fr_flags == (RFFDG | RFPROC)) {
722 		VM_CNT_INC(v_forks);
723 		VM_CNT_ADD(v_forkpages, p2->p_vmspace->vm_dsize +
724 		    p2->p_vmspace->vm_ssize);
725 	} else if (fr->fr_flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
726 		VM_CNT_INC(v_vforks);
727 		VM_CNT_ADD(v_vforkpages, p2->p_vmspace->vm_dsize +
728 		    p2->p_vmspace->vm_ssize);
729 	} else if (p1 == &proc0) {
730 		VM_CNT_INC(v_kthreads);
731 		VM_CNT_ADD(v_kthreadpages, p2->p_vmspace->vm_dsize +
732 		    p2->p_vmspace->vm_ssize);
733 	} else {
734 		VM_CNT_INC(v_rforks);
735 		VM_CNT_ADD(v_rforkpages, p2->p_vmspace->vm_dsize +
736 		    p2->p_vmspace->vm_ssize);
737 	}
738 
739 	/*
740 	 * Associate the process descriptor with the process before anything
741 	 * can happen that might cause that process to need the descriptor.
742 	 * However, don't do this until after fork(2) can no longer fail.
743 	 */
744 	if (fr->fr_flags & RFPROCDESC)
745 		procdesc_new(p2, fr->fr_pd_flags);
746 
747 	/*
748 	 * Both processes are set up, now check if any loadable modules want
749 	 * to adjust anything.
750 	 */
751 	EVENTHANDLER_DIRECT_INVOKE(process_fork, p1, p2, fr->fr_flags);
752 
753 	/*
754 	 * Set the child start time and mark the process as being complete.
755 	 */
756 	PROC_LOCK(p2);
757 	PROC_LOCK(p1);
758 	microuptime(&p2->p_stats->p_start);
759 	PROC_SLOCK(p2);
760 	p2->p_state = PRS_NORMAL;
761 	PROC_SUNLOCK(p2);
762 
763 #ifdef KDTRACE_HOOKS
764 	/*
765 	 * Tell the DTrace fasttrap provider about the new process so that any
766 	 * tracepoints inherited from the parent can be removed. We have to do
767 	 * this only after p_state is PRS_NORMAL since the fasttrap module will
768 	 * use pfind() later on.
769 	 */
770 	if ((fr->fr_flags & RFMEM) == 0 && dtrace_fasttrap_fork)
771 		dtrace_fasttrap_fork(p1, p2);
772 #endif
773 	if (fr->fr_flags & RFPPWAIT) {
774 		td->td_pflags |= TDP_RFPPWAIT;
775 		td->td_rfppwait_p = p2;
776 		td->td_dbgflags |= TDB_VFORK;
777 	}
778 	PROC_UNLOCK(p2);
779 
780 	/*
781 	 * Tell any interested parties about the new process.
782 	 */
783 	knote_fork(p1->p_klist, p2->p_pid);
784 
785 	PROC_UNLOCK(p1);
786 	SDT_PROBE3(proc, , , create, p2, p1, fr->fr_flags);
787 
788 	if (fr->fr_flags & RFPROCDESC) {
789 		procdesc_finit(p2->p_procdesc, fp_procdesc);
790 		fdrop(fp_procdesc, td);
791 	}
792 
793 	/*
794 	 * Speculative check for PTRACE_FORK. PTRACE_FORK is not
795 	 * synced with forks in progress so it is OK if we miss it
796 	 * if being set atm.
797 	 */
798 	if ((p1->p_ptevents & PTRACE_FORK) != 0) {
799 		sx_xlock(&proctree_lock);
800 		PROC_LOCK(p2);
801 
802 		/*
803 		 * p1->p_ptevents & p1->p_pptr are protected by both
804 		 * process and proctree locks for modifications,
805 		 * so owning proctree_lock allows the race-free read.
806 		 */
807 		if ((p1->p_ptevents & PTRACE_FORK) != 0) {
808 			/*
809 			 * Arrange for debugger to receive the fork event.
810 			 *
811 			 * We can report PL_FLAG_FORKED regardless of
812 			 * P_FOLLOWFORK settings, but it does not make a sense
813 			 * for runaway child.
814 			 */
815 			td->td_dbgflags |= TDB_FORK;
816 			td->td_dbg_forked = p2->p_pid;
817 			td2->td_dbgflags |= TDB_STOPATFORK;
818 			proc_set_traced(p2, true);
819 			CTR2(KTR_PTRACE,
820 			    "do_fork: attaching to new child pid %d: oppid %d",
821 			    p2->p_pid, p2->p_oppid);
822 			proc_reparent(p2, p1->p_pptr, false);
823 		}
824 		PROC_UNLOCK(p2);
825 		sx_xunlock(&proctree_lock);
826 	}
827 
828 	racct_proc_fork_done(p2);
829 
830 	if ((fr->fr_flags & RFSTOPPED) == 0) {
831 		if (fr->fr_pidp != NULL)
832 			*fr->fr_pidp = p2->p_pid;
833 		/*
834 		 * If RFSTOPPED not requested, make child runnable and
835 		 * add to run queue.
836 		 */
837 		thread_lock(td2);
838 		TD_SET_CAN_RUN(td2);
839 		sched_add(td2, SRQ_BORING);
840 	} else {
841 		*fr->fr_procp = p2;
842 	}
843 }
844 
845 static void
846 ast_vfork(struct thread *td, int tda __unused)
847 {
848 	struct proc *p, *p2;
849 
850 	MPASS(td->td_pflags & TDP_RFPPWAIT);
851 
852 	p = td->td_proc;
853 	/*
854 	 * Preserve synchronization semantics of vfork.  If
855 	 * waiting for child to exec or exit, fork set
856 	 * P_PPWAIT on child, and there we sleep on our proc
857 	 * (in case of exit).
858 	 *
859 	 * Do it after the ptracestop() above is finished, to
860 	 * not block our debugger until child execs or exits
861 	 * to finish vfork wait.
862 	 */
863 	td->td_pflags &= ~TDP_RFPPWAIT;
864 	p2 = td->td_rfppwait_p;
865 again:
866 	PROC_LOCK(p2);
867 	while (p2->p_flag & P_PPWAIT) {
868 		PROC_LOCK(p);
869 		if (thread_suspend_check_needed()) {
870 			PROC_UNLOCK(p2);
871 			thread_suspend_check(0);
872 			PROC_UNLOCK(p);
873 			goto again;
874 		} else {
875 			PROC_UNLOCK(p);
876 		}
877 		cv_timedwait(&p2->p_pwait, &p2->p_mtx, hz);
878 	}
879 	PROC_UNLOCK(p2);
880 
881 	if (td->td_dbgflags & TDB_VFORK) {
882 		PROC_LOCK(p);
883 		if (p->p_ptevents & PTRACE_VFORK)
884 			ptracestop(td, SIGTRAP, NULL);
885 		td->td_dbgflags &= ~TDB_VFORK;
886 		PROC_UNLOCK(p);
887 	}
888 }
889 
890 int
891 fork1(struct thread *td, struct fork_req *fr)
892 {
893 	struct proc *p1, *newproc;
894 	struct thread *td2;
895 	struct vmspace *vm2;
896 	struct ucred *cred;
897 	struct file *fp_procdesc;
898 	struct pgrp *pg;
899 	vm_ooffset_t mem_charged;
900 	int error, nprocs_new;
901 	static int curfail;
902 	static struct timeval lastfail;
903 	int flags, pages;
904 	bool killsx_locked, singlethreaded;
905 
906 	flags = fr->fr_flags;
907 	pages = fr->fr_pages;
908 
909 	if ((flags & RFSTOPPED) != 0)
910 		MPASS(fr->fr_procp != NULL && fr->fr_pidp == NULL);
911 	else
912 		MPASS(fr->fr_procp == NULL);
913 
914 	if ((flags & ~(RFFLAGS | RFTSIGFLAGS(RFTSIGMASK))) != 0)
915 		return (EXTERROR(EINVAL,
916 		    "Undef or unimplemented flags %#jx", flags));
917 
918 	if ((flags & RFTSIGFLAGS(RFTSIGMASK)) != 0 && (flags & RFTSIGZMB) == 0)
919 		return (EXTERROR(EINVAL,
920 		    "Signal value requires RFTSIGZMB", flags));
921 
922 	if ((flags & (RFFDG | RFCFDG)) == (RFFDG | RFCFDG))
923 		return (EXTERROR(EINVAL, "Can not copy and clear"));
924 
925 	if ((flags & RFTSIGZMB) != 0 && (u_int)RFTSIGNUM(flags) > _SIG_MAXSIG)
926 		return (EXTERROR(EINVAL, "Invalid signal", RFTSIGNUM(flags)));
927 
928 	if ((flags & RFPROCDESC) != 0) {
929 		if ((flags & RFPROC) == 0)
930 			return (EXTERROR(EINVAL,
931 	    "Can not not create a process yet get a process descriptor"));
932 
933 		if (fr->fr_pd_fd == NULL)
934 			return (EXTERROR(EINVAL,
935 		    "Must provide a place to put a procdesc if creating one"));
936 
937 		if ((fr->fr_pd_flags & ~PD_ALLOWED_AT_FORK) != 0)
938 			return (EXTERROR(EINVAL,
939 			    "Invallid pdflags at fork %#jx", fr->fr_pd_flags));
940 	}
941 
942 	p1 = td->td_proc;
943 
944 	/*
945 	 * Here we don't create a new process, but we divorce
946 	 * certain parts of a process from itself.
947 	 */
948 	if ((flags & RFPROC) == 0) {
949 		if (fr->fr_procp != NULL)
950 			*fr->fr_procp = NULL;
951 		else if (fr->fr_pidp != NULL)
952 			*fr->fr_pidp = 0;
953 		return (fork_norfproc(td, flags));
954 	}
955 
956 	fp_procdesc = NULL;
957 	newproc = NULL;
958 	vm2 = NULL;
959 	killsx_locked = false;
960 	singlethreaded = false;
961 
962 	/*
963 	 * Increment the nprocs resource before allocations occur.
964 	 * Although process entries are dynamically created, we still
965 	 * keep a global limit on the maximum number we will
966 	 * create. There are hard-limits as to the number of processes
967 	 * that can run, established by the KVA and memory usage for
968 	 * the process data.
969 	 *
970 	 * Don't allow a nonprivileged user to use the last ten
971 	 * processes; don't let root exceed the limit.
972 	 */
973 	nprocs_new = atomic_fetchadd_int(&nprocs, 1) + 1;
974 	if (nprocs_new >= maxproc - 10) {
975 		if (priv_check_cred(td->td_ucred, PRIV_MAXPROC) != 0 ||
976 		    nprocs_new >= maxproc) {
977 			error = EAGAIN;
978 			sx_xlock(&allproc_lock);
979 			if (ppsratecheck(&lastfail, &curfail, 1)) {
980 				printf("maxproc limit exceeded by uid %u "
981 				    "(pid %d); see tuning(7) and "
982 				    "login.conf(5)\n",
983 				    td->td_ucred->cr_ruid, p1->p_pid);
984 			}
985 			sx_xunlock(&allproc_lock);
986 			goto fail2;
987 		}
988 	}
989 
990 	/*
991 	 * If we are possibly multi-threaded, and there is a process
992 	 * sending a signal to our group right now, ensure that our
993 	 * other threads cannot be chosen for the signal queueing.
994 	 * Otherwise, this might delay signal action, and make the new
995 	 * child escape the signaling.
996 	 */
997 	pg = p1->p_pgrp;
998 	if (p1->p_numthreads > 1) {
999 		if (sx_try_slock(&pg->pg_killsx) != 0) {
1000 			killsx_locked = true;
1001 		} else {
1002 			PROC_LOCK(p1);
1003 			if (thread_single(p1, SINGLE_BOUNDARY)) {
1004 				PROC_UNLOCK(p1);
1005 				error = ERESTART;
1006 				goto fail2;
1007 			}
1008 			PROC_UNLOCK(p1);
1009 			singlethreaded = true;
1010 		}
1011 	}
1012 
1013 	/*
1014 	 * Atomically check for signals and block processes from sending
1015 	 * a signal to our process group until the child is visible.
1016 	 */
1017 	if (!killsx_locked && sx_slock_sig(&pg->pg_killsx) != 0) {
1018 		error = ERESTART;
1019 		goto fail2;
1020 	}
1021 	if (__predict_false(p1->p_pgrp != pg || sig_intr() != 0)) {
1022 		/*
1023 		 * Either the process was moved to other process
1024 		 * group, or there is pending signal.  sx_slock_sig()
1025 		 * does not check for signals if not sleeping for the
1026 		 * lock.
1027 		 */
1028 		sx_sunlock(&pg->pg_killsx);
1029 		killsx_locked = false;
1030 		error = ERESTART;
1031 		goto fail2;
1032 	} else {
1033 		killsx_locked = true;
1034 	}
1035 
1036 	/*
1037 	 * If required, create a process descriptor in the parent first; we
1038 	 * will abandon it if something goes wrong. We don't finit() until
1039 	 * later.
1040 	 */
1041 	if (flags & RFPROCDESC) {
1042 		error = procdesc_falloc(td, &fp_procdesc, fr->fr_pd_fd,
1043 		    fr->fr_pd_flags, fr->fr_pd_fcaps);
1044 		if (error != 0)
1045 			goto fail2;
1046 		AUDIT_ARG_FD(*fr->fr_pd_fd);
1047 	}
1048 
1049 	mem_charged = 0;
1050 	if (pages == 0)
1051 		pages = kstack_pages;
1052 	/* Allocate new proc. */
1053 	newproc = uma_zalloc(proc_zone, M_WAITOK);
1054 	PROC_TREE_REF(newproc);
1055 	td2 = FIRST_THREAD_IN_PROC(newproc);
1056 	if (td2 == NULL) {
1057 		td2 = thread_alloc(pages);
1058 		if (td2 == NULL) {
1059 			error = ENOMEM;
1060 			goto fail2;
1061 		}
1062 		proc_linkup(newproc, td2);
1063 	} else {
1064 		error = thread_recycle(td2, pages);
1065 		if (error != 0)
1066 			goto fail2;
1067 	}
1068 
1069 	if ((flags & RFMEM) == 0) {
1070 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
1071 		if (vm2 == NULL) {
1072 			error = ENOMEM;
1073 			goto fail2;
1074 		}
1075 		if (!swap_reserve(mem_charged)) {
1076 			/*
1077 			 * The swap reservation failed. The accounting
1078 			 * from the entries of the copied vm2 will be
1079 			 * subtracted in vmspace_free(), so force the
1080 			 * reservation there.
1081 			 */
1082 			swap_reserve_force(mem_charged);
1083 			error = ENOMEM;
1084 			goto fail2;
1085 		}
1086 	} else
1087 		vm2 = NULL;
1088 
1089 	/*
1090 	 * XXX: This is ugly; when we copy resource usage, we need to bump
1091 	 *      per-cred resource counters.
1092 	 */
1093 	newproc->p_ucred = crcowget(td->td_ucred);
1094 
1095 	/*
1096 	 * Initialize resource accounting for the child process.
1097 	 */
1098 	error = racct_proc_fork(p1, newproc);
1099 	if (error != 0) {
1100 		error = EAGAIN;
1101 		goto fail1;
1102 	}
1103 
1104 #ifdef MAC
1105 	mac_proc_init(newproc);
1106 #endif
1107 
1108 	/*
1109 	 * Increment the count of procs running with this uid. Don't allow
1110 	 * a nonprivileged user to exceed their current limit.
1111 	 */
1112 	cred = td->td_ucred;
1113 	if (!chgproccnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_NPROC))) {
1114 		if (priv_check_cred(cred, PRIV_PROC_LIMIT) != 0)
1115 			goto fail0;
1116 		chgproccnt(cred->cr_ruidinfo, 1, 0);
1117 	}
1118 
1119 	newproc->p_klist = knlist_alloc(&newproc->p_mtx);
1120 
1121 	do_fork(td, fr, newproc, td2, vm2, fp_procdesc);
1122 	error = 0;
1123 	goto cleanup;
1124 fail0:
1125 	error = EAGAIN;
1126 #ifdef MAC
1127 	mac_proc_destroy(newproc);
1128 #endif
1129 	racct_proc_exit(newproc);
1130 fail1:
1131 	proc_unset_cred(newproc, false);
1132 fail2:
1133 	if (vm2 != NULL)
1134 		vmspace_free(vm2);
1135 	if (newproc != NULL)
1136 		PROC_TREE_UNREF(newproc);
1137 	if ((flags & RFPROCDESC) != 0 && fp_procdesc != NULL) {
1138 		fdclose(td, fp_procdesc, *fr->fr_pd_fd);
1139 		fdrop(fp_procdesc, td);
1140 	}
1141 	atomic_add_int(&nprocs, -1);
1142 cleanup:
1143 	if (killsx_locked)
1144 		sx_sunlock(&pg->pg_killsx);
1145 	if (singlethreaded) {
1146 		PROC_LOCK(p1);
1147 		thread_single_end(p1, SINGLE_BOUNDARY);
1148 		PROC_UNLOCK(p1);
1149 	}
1150 	if (error != 0)
1151 		pause("fork", hz / 2);
1152 	return (error);
1153 }
1154 
1155 /*
1156  * Handle the return of a child process from fork1().  This function
1157  * is called from the MD fork_trampoline() entry point.
1158  */
1159 void
1160 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
1161     struct trapframe *frame)
1162 {
1163 	struct proc *p;
1164 	struct thread *td;
1165 	struct thread *dtd;
1166 
1167 	kmsan_mark(frame, sizeof(*frame), KMSAN_STATE_INITED);
1168 
1169 	td = curthread;
1170 	p = td->td_proc;
1171 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
1172 
1173 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
1174 	    td, td_get_sched(td), p->p_pid, td->td_name);
1175 
1176 	sched_fork_exit(td);
1177 
1178 	/*
1179 	 * Processes normally resume in mi_switch() after being
1180 	 * cpu_switch()'ed to, but when children start up they arrive here
1181 	 * instead, so we must do much the same things as mi_switch() would.
1182 	 */
1183 	if ((dtd = PCPU_GET(deadthread))) {
1184 		PCPU_SET(deadthread, NULL);
1185 		thread_stash(dtd);
1186 	}
1187 	thread_unlock(td);
1188 
1189 	/*
1190 	 * cpu_fork_kthread_handler intercepts this function call to
1191 	 * have this call a non-return function to stay in kernel mode.
1192 	 * initproc has its own fork handler, but it does return.
1193 	 */
1194 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
1195 	callout(arg, frame);
1196 
1197 	/*
1198 	 * Check if a kernel thread misbehaved and returned from its main
1199 	 * function.
1200 	 */
1201 	if (p->p_flag & P_KPROC) {
1202 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
1203 		    td->td_name, p->p_pid);
1204 		kthread_exit();
1205 	}
1206 	mtx_assert(&Giant, MA_NOTOWNED);
1207 
1208 	/*
1209 	 * Now going to return to userland.
1210 	 */
1211 
1212 	if (p->p_sysent->sv_schedtail != NULL)
1213 		(p->p_sysent->sv_schedtail)(td);
1214 
1215 	userret(td, frame);
1216 }
1217 
1218 /*
1219  * Simplified back end of syscall(), used when returning from fork()
1220  * directly into user mode.  This function is passed in to fork_exit()
1221  * as the first parameter and is called when returning to a new
1222  * userland process.
1223  */
1224 void
1225 fork_return(struct thread *td, struct trapframe *frame)
1226 {
1227 	struct proc *p;
1228 
1229 	p = td->td_proc;
1230 	if (td->td_dbgflags & TDB_STOPATFORK) {
1231 		PROC_LOCK(p);
1232 		if ((p->p_flag & P_TRACED) != 0) {
1233 			/*
1234 			 * Inform the debugger if one is still present.
1235 			 */
1236 			td->td_dbgflags |= TDB_CHILD | TDB_SCX | TDB_FSTP;
1237 			ptracestop(td, SIGSTOP, NULL);
1238 			td->td_dbgflags &= ~(TDB_CHILD | TDB_SCX);
1239 		} else {
1240 			/*
1241 			 * ... otherwise clear the request.
1242 			 */
1243 			td->td_dbgflags &= ~TDB_STOPATFORK;
1244 		}
1245 		PROC_UNLOCK(p);
1246 	} else if (p->p_flag & P_TRACED) {
1247  		/*
1248 		 * This is the start of a new thread in a traced
1249 		 * process.  Report a system call exit event.
1250 		 */
1251 		PROC_LOCK(p);
1252 		td->td_dbgflags |= TDB_SCX;
1253 		if ((p->p_ptevents & PTRACE_SCX) != 0 ||
1254 		    (td->td_dbgflags & TDB_BORN) != 0)
1255 			ptracestop(td, SIGTRAP, NULL);
1256 		td->td_dbgflags &= ~(TDB_SCX | TDB_BORN);
1257 		PROC_UNLOCK(p);
1258 	}
1259 
1260 	/*
1261 	 * If the prison was killed mid-fork, die along with it.
1262 	 */
1263 	if (!prison_isalive(td->td_ucred->cr_prison))
1264 		kern_exit(td, 0, SIGKILL);
1265 
1266 #ifdef KTRACE
1267 	if (KTRPOINT(td, KTR_SYSRET))
1268 		ktrsysret(td->td_sa.code, 0, 0);
1269 #endif
1270 }
1271 
1272 static void
1273 fork_init(void *arg __unused)
1274 {
1275 	ast_register(TDA_VFORK, ASTR_ASTF_REQUIRED | ASTR_TDP, TDP_RFPPWAIT,
1276 	    ast_vfork);
1277 }
1278 SYSINIT(fork, SI_SUB_INTRINSIC, SI_ORDER_ANY, fork_init, NULL);
1279