Home | History | Annotate | Line # | Download | only in kern
      1 /*	$NetBSD: kern_fork.c,v 1.232 2025/07/16 19:14:13 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2001, 2004, 2006, 2007, 2008, 2019
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
     10  * NASA Ames Research Center, by Charles M. Hannum, and by Andrew Doran.
     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  *
     21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     31  * POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 /*
     35  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     36  *	The Regents of the University of California.  All rights reserved.
     37  * (c) UNIX System Laboratories, Inc.
     38  * All or some portions of this file are derived from material licensed
     39  * to the University of California by American Telephone and Telegraph
     40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     41  * the permission of UNIX System Laboratories, Inc.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. Neither the name of the University nor the names of its contributors
     52  *    may be used to endorse or promote products derived from this software
     53  *    without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  *
     67  *	@(#)kern_fork.c	8.8 (Berkeley) 2/14/95
     68  */
     69 
     70 #include <sys/cdefs.h>
     71 __KERNEL_RCSID(0, "$NetBSD: kern_fork.c,v 1.232 2025/07/16 19:14:13 kre Exp $");
     72 
     73 #include "opt_ktrace.h"
     74 #include "opt_dtrace.h"
     75 
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/filedesc.h>
     79 #include <sys/kernel.h>
     80 #include <sys/pool.h>
     81 #include <sys/mount.h>
     82 #include <sys/proc.h>
     83 #include <sys/ras.h>
     84 #include <sys/resourcevar.h>
     85 #include <sys/vnode.h>
     86 #include <sys/file.h>
     87 #include <sys/acct.h>
     88 #include <sys/ktrace.h>
     89 #include <sys/sched.h>
     90 #include <sys/signalvar.h>
     91 #include <sys/syscall.h>
     92 #include <sys/kauth.h>
     93 #include <sys/atomic.h>
     94 #include <sys/syscallargs.h>
     95 #include <sys/uidinfo.h>
     96 #include <sys/sdt.h>
     97 #include <sys/ptrace.h>
     98 
     99 /*
    100  * DTrace SDT provider definitions
    101  */
    102 SDT_PROVIDER_DECLARE(proc);
    103 SDT_PROBE_DEFINE3(proc, kernel, , create,
    104     "struct proc *", /* new process */
    105     "struct proc *", /* parent process */
    106     "int" /* flags */);
    107 
    108 u_int	nprocs __cacheline_aligned = 1;		/* process 0 */
    109 
    110 /*
    111  * Number of ticks to sleep if fork() would fail due to process hitting
    112  * limits. Exported in milliseconds to userland via sysctl.
    113  */
    114 int	forkfsleep = 0;
    115 
    116 int
    117 sys_fork(struct lwp *l, const void *v, register_t *retval)
    118 {
    119 
    120 	return fork1(l, 0, SIGCHLD, NULL, 0, NULL, NULL, retval);
    121 }
    122 
    123 /*
    124  * vfork(2) system call compatible with 4.4BSD (i.e. BSD with Mach VM).
    125  * Address space is not shared, but parent is blocked until child exit.
    126  */
    127 int
    128 sys_vfork(struct lwp *l, const void *v, register_t *retval)
    129 {
    130 
    131 	return fork1(l, FORK_PPWAIT, SIGCHLD, NULL, 0, NULL, NULL,
    132 	    retval);
    133 }
    134 
    135 /*
    136  * New vfork(2) system call for NetBSD, which implements original 3BSD vfork(2)
    137  * semantics.  Address space is shared, and parent is blocked until child exit.
    138  */
    139 int
    140 sys___vfork14(struct lwp *l, const void *v, register_t *retval)
    141 {
    142 
    143 	return fork1(l, FORK_PPWAIT|FORK_SHAREVM, SIGCHLD, NULL, 0,
    144 	    NULL, NULL, retval);
    145 }
    146 
    147 /*
    148  * Linux-compatible __clone(2) system call.
    149  */
    150 int
    151 sys___clone(struct lwp *l, const struct sys___clone_args *uap,
    152     register_t *retval)
    153 {
    154 	/* {
    155 		syscallarg(int) flags;
    156 		syscallarg(void *) stack;
    157 	} */
    158 	int flags, sig;
    159 
    160 	/*
    161 	 * We don't support the CLONE_PTRACE flag.
    162 	 */
    163 	if (SCARG(uap, flags) & (CLONE_PTRACE))
    164 		return EINVAL;
    165 
    166 	/*
    167 	 * Linux enforces CLONE_VM with CLONE_SIGHAND, do same.
    168 	 */
    169 	if (SCARG(uap, flags) & CLONE_SIGHAND
    170 	    && (SCARG(uap, flags) & CLONE_VM) == 0)
    171 		return EINVAL;
    172 
    173 	flags = 0;
    174 
    175 	if (SCARG(uap, flags) & CLONE_VM)
    176 		flags |= FORK_SHAREVM;
    177 	if (SCARG(uap, flags) & CLONE_FS)
    178 		flags |= FORK_SHARECWD;
    179 	if (SCARG(uap, flags) & CLONE_FILES)
    180 		flags |= FORK_SHAREFILES;
    181 	if (SCARG(uap, flags) & CLONE_SIGHAND)
    182 		flags |= FORK_SHARESIGS;
    183 	if (SCARG(uap, flags) & CLONE_VFORK)
    184 		flags |= FORK_PPWAIT;
    185 
    186 	sig = SCARG(uap, flags) & CLONE_CSIGNAL;
    187 	if (sig < 0 || sig >= _NSIG)
    188 		return EINVAL;
    189 
    190 	/*
    191 	 * Linux doesn't have close-on-fork yet, so we don't
    192 	 * know what they will do combining CLONE_FILES with
    193 	 * close-on-fork (which are not really compatible).
    194 	 * This might need to be changed in the future (another
    195 	 * option would be to just disable FORK_SHAREFILES)
    196 	 */
    197 	if ((flags & FORK_SHAREFILES) != 0) {
    198 		if (l->l_fd != NULL && l->l_fd->fd_foclose)
    199 			return EINVAL;
    200 	}
    201 
    202 	/*
    203 	 * Note that the Linux API does not provide a portable way of
    204 	 * specifying the stack area; the caller must know if the stack
    205 	 * grows up or down.  So, we pass a stack size of 0, so that the
    206 	 * code that makes this adjustment is a noop.
    207 	 */
    208 	return fork1(l, flags, sig, SCARG(uap, stack), 0,
    209 	    NULL, NULL, retval);
    210 }
    211 
    212 /*
    213  * Print the 'table full' message once per 10 seconds.
    214  */
    215 static struct timeval fork_tfmrate = { 10, 0 };
    216 
    217 /*
    218  * Check if a process is traced and shall inform about FORK events.
    219  */
    220 static inline bool
    221 tracefork(struct proc *p, int flags)
    222 {
    223 
    224 	return (p->p_slflag & (PSL_TRACEFORK|PSL_TRACED)) ==
    225 	    (PSL_TRACEFORK|PSL_TRACED) && (flags & FORK_PPWAIT) == 0;
    226 }
    227 
    228 /*
    229  * Check if a process is traced and shall inform about VFORK events.
    230  */
    231 static inline bool
    232 tracevfork(struct proc *p, int flags)
    233 {
    234 
    235 	return (p->p_slflag & (PSL_TRACEVFORK|PSL_TRACED)) ==
    236 	    (PSL_TRACEVFORK|PSL_TRACED) && (flags & FORK_PPWAIT) != 0;
    237 }
    238 
    239 /*
    240  * Check if a process is traced and shall inform about VFORK_DONE events.
    241  */
    242 static inline bool
    243 tracevforkdone(struct proc *p, int flags)
    244 {
    245 
    246 	return (p->p_slflag & (PSL_TRACEVFORK_DONE|PSL_TRACED)) ==
    247 	    (PSL_TRACEVFORK_DONE|PSL_TRACED) && (flags & FORK_PPWAIT);
    248 }
    249 
    250 /*
    251  * General fork call.  Note that another LWP in the process may call exec()
    252  * or exit() while we are forking.  It's safe to continue here, because
    253  * neither operation will complete until all LWPs have exited the process.
    254  */
    255 int
    256 fork1(struct lwp *l1, int flags, int exitsig, void *stack, size_t stacksize,
    257     void (*func)(void *), void *arg, register_t *retval)
    258 {
    259 	struct proc	*p1, *p2, *parent;
    260 	struct plimit   *p1_lim;
    261 	uid_t		uid;
    262 	struct lwp	*l2;
    263 	int		count;
    264 	vaddr_t		uaddr;
    265 	int		tnprocs;
    266 	int		error = 0;
    267 
    268 	p1 = l1->l_proc;
    269 	uid = kauth_cred_getuid(l1->l_cred);
    270 	tnprocs = atomic_inc_uint_nv(&nprocs);
    271 
    272 	/*
    273 	 * Although process entries are dynamically created, we still keep
    274 	 * a global limit on the maximum number we will create.
    275 	 */
    276 	if (__predict_false(tnprocs >= maxproc))
    277 		error = -1;
    278 	else
    279 		error = kauth_authorize_process(l1->l_cred,
    280 		    KAUTH_PROCESS_FORK, p1, KAUTH_ARG(tnprocs), NULL, NULL);
    281 
    282 	if (error) {
    283 		static struct timeval lasttfm;
    284 		atomic_dec_uint(&nprocs);
    285 		if (ratecheck(&lasttfm, &fork_tfmrate))
    286 			tablefull("proc", "increase kern.maxproc or NPROC");
    287 		if (forkfsleep)
    288 			kpause("forkmx", false, forkfsleep, NULL);
    289 		return EAGAIN;
    290 	}
    291 
    292 	/*
    293 	 * Enforce limits.
    294 	 */
    295 	count = chgproccnt(uid, 1);
    296 	if (__predict_false(count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
    297 		if (kauth_authorize_process(l1->l_cred, KAUTH_PROCESS_RLIMIT,
    298 		    p1, KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS),
    299 		    &p1->p_rlimit[RLIMIT_NPROC], KAUTH_ARG(RLIMIT_NPROC)) != 0) {
    300 			(void)chgproccnt(uid, -1);
    301 			atomic_dec_uint(&nprocs);
    302 			if (forkfsleep)
    303 				kpause("forkulim", false, forkfsleep, NULL);
    304 			return EAGAIN;
    305 		}
    306 	}
    307 
    308 	/*
    309 	 * Allocate virtual address space for the U-area now, while it
    310 	 * is still easy to abort the fork operation if we're out of
    311 	 * kernel virtual address space.
    312 	 */
    313 	uaddr = uvm_uarea_alloc();
    314 	if (__predict_false(uaddr == 0)) {
    315 		(void)chgproccnt(uid, -1);
    316 		atomic_dec_uint(&nprocs);
    317 		return ENOMEM;
    318 	}
    319 
    320 	/* Allocate new proc. */
    321 	p2 = proc_alloc();
    322 	if (p2 == NULL) {
    323 		/* We were unable to allocate a process ID. */
    324 		uvm_uarea_free(uaddr);
    325 		mutex_enter(p1->p_lock);
    326 		uid = kauth_cred_getuid(p1->p_cred);
    327 		(void)chgproccnt(uid, -1);
    328 		mutex_exit(p1->p_lock);
    329 		atomic_dec_uint(&nprocs);
    330 		return EAGAIN;
    331 	}
    332 
    333 	/*
    334 	 * We are now committed to the fork.  From here on, we may
    335 	 * block on resources, but resource allocation may NOT fail.
    336 	 */
    337 
    338 	/*
    339 	 * Make a proc table entry for the new process.
    340 	 * Start by zeroing the section of proc that is zero-initialized,
    341 	 * then copy the section that is copied directly from the parent.
    342 	 */
    343 	memset(&p2->p_startzero, 0,
    344 	    (unsigned) ((char *)&p2->p_endzero - (char *)&p2->p_startzero));
    345 	memcpy(&p2->p_startcopy, &p1->p_startcopy,
    346 	    (unsigned) ((char *)&p2->p_endcopy - (char *)&p2->p_startcopy));
    347 
    348 	TAILQ_INIT(&p2->p_sigpend.sp_info);
    349 
    350 	LIST_INIT(&p2->p_lwps);
    351 	LIST_INIT(&p2->p_sigwaiters);
    352 
    353 	/*
    354 	 * Duplicate sub-structures as needed.
    355 	 * Increase reference counts on shared objects.
    356 	 * Inherit flags we want to keep.  The flags related to SIGCHLD
    357 	 * handling are important in order to keep a consistent behaviour
    358 	 * for the child after the fork.  If we are a 32-bit process, the
    359 	 * child will be too.
    360 	 */
    361 	p2->p_flag =
    362 	    p1->p_flag & (PK_SUGID | PK_NOCLDWAIT | PK_CLDSIGIGN | PK_32);
    363 	p2->p_emul = p1->p_emul;
    364 	p2->p_execsw = p1->p_execsw;
    365 
    366 	if (flags & FORK_SYSTEM) {
    367 		/*
    368 		 * Mark it as a system process.  Set P_NOCLDWAIT so that
    369 		 * children are reparented to init(8) when they exit.
    370 		 * init(8) can easily wait them out for us.
    371 		 */
    372 		p2->p_flag |= (PK_SYSTEM | PK_NOCLDWAIT);
    373 	}
    374 
    375 	mutex_init(&p2->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
    376 	mutex_init(&p2->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
    377 	rw_init(&p2->p_reflock);
    378 	cv_init(&p2->p_waitcv, "wait");
    379 	cv_init(&p2->p_lwpcv, "lwpwait");
    380 
    381 	/*
    382 	 * Share a lock between the processes if they are to share signal
    383 	 * state: we must synchronize access to it.
    384 	 */
    385 	if (flags & FORK_SHARESIGS) {
    386 		p2->p_lock = p1->p_lock;
    387 		mutex_obj_hold(p1->p_lock);
    388 	} else
    389 		p2->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    390 
    391 	kauth_proc_fork(p1, p2);
    392 
    393 	p2->p_raslist = NULL;
    394 #if defined(__HAVE_RAS)
    395 	ras_fork(p1, p2);
    396 #endif
    397 
    398 	/* bump references to the text vnode (for procfs) */
    399 	p2->p_textvp = p1->p_textvp;
    400 	if (p2->p_textvp)
    401 		vref(p2->p_textvp);
    402 	if (p1->p_path)
    403 		p2->p_path = kmem_strdupsize(p1->p_path, NULL, KM_SLEEP);
    404 	else
    405 		p2->p_path = NULL;
    406 
    407 	if (flags & FORK_SHAREFILES)
    408 		fd_share(p2);
    409 	else if (flags & FORK_CLEANFILES)
    410 		p2->p_fd = fd_init(NULL);
    411 	else
    412 		p2->p_fd = fd_copy();
    413 
    414 	/* XXX racy */
    415 	p2->p_mqueue_cnt = p1->p_mqueue_cnt;
    416 
    417 	if (flags & FORK_SHARECWD)
    418 		cwdshare(p2);
    419 	else
    420 		p2->p_cwdi = cwdinit();
    421 
    422 	/*
    423 	 * Note: p_limit (rlimit stuff) is copy-on-write, so normally
    424 	 * we just need increase pl_refcnt.
    425 	 */
    426 	p1_lim = p1->p_limit;
    427 	if (!p1_lim->pl_writeable) {
    428 		lim_addref(p1_lim);
    429 		p2->p_limit = p1_lim;
    430 	} else {
    431 		p2->p_limit = lim_copy(p1_lim);
    432 	}
    433 
    434 	if (flags & FORK_PPWAIT) {
    435 		/* Mark ourselves as waiting for a child. */
    436 		p2->p_lflag = PL_PPWAIT;
    437 		l1->l_vforkwaiting = true;
    438 		p2->p_vforklwp = l1;
    439 	} else {
    440 		p2->p_lflag = 0;
    441 		l1->l_vforkwaiting = false;
    442 	}
    443 	p2->p_sflag = 0;
    444 	p2->p_slflag = 0;
    445 	parent = (flags & FORK_NOWAIT) ? initproc : p1;
    446 	p2->p_pptr = parent;
    447 	p2->p_ppid = parent->p_pid;
    448 	LIST_INIT(&p2->p_children);
    449 
    450 	p2->p_aio = NULL;
    451 
    452 #ifdef KTRACE
    453 	/*
    454 	 * Copy traceflag and tracefile if enabled.
    455 	 * If not inherited, these were zeroed above.
    456 	 */
    457 	if (p1->p_traceflag & KTRFAC_INHERIT) {
    458 		mutex_enter(&ktrace_lock);
    459 		p2->p_traceflag = p1->p_traceflag;
    460 		if ((p2->p_tracep = p1->p_tracep) != NULL)
    461 			ktradref(p2);
    462 		mutex_exit(&ktrace_lock);
    463 	}
    464 #endif
    465 
    466 	/*
    467 	 * Create signal actions for the child process.
    468 	 */
    469 	p2->p_sigacts = sigactsinit(p1, flags & FORK_SHARESIGS);
    470 	mutex_enter(p1->p_lock);
    471 	p2->p_sflag |=
    472 	    (p1->p_sflag & (PS_STOPFORK | PS_STOPEXEC | PS_NOCLDSTOP));
    473 	sched_proc_fork(p1, p2);
    474 	mutex_exit(p1->p_lock);
    475 
    476 	p2->p_stflag = p1->p_stflag;
    477 
    478 	/*
    479 	 * p_stats.
    480 	 * Copy parts of p_stats, and zero out the rest.
    481 	 */
    482 	p2->p_stats = pstatscopy(p1->p_stats);
    483 
    484 	/*
    485 	 * Set up the new process address space.
    486 	 */
    487 	uvm_proc_fork(p1, p2, (flags & FORK_SHAREVM) ? true : false);
    488 
    489 	/*
    490 	 * Finish creating the child process.
    491 	 * It will return through a different path later.
    492 	 */
    493 	lwp_create(l1, p2, uaddr, (flags & FORK_PPWAIT) ? LWP_VFORK : 0,
    494 	    stack, stacksize, (func != NULL) ? func : child_return, arg, &l2,
    495 	    l1->l_class, &l1->l_sigmask, &l1->l_sigstk);
    496 
    497 	/*
    498 	 * Inherit l_private from the parent.
    499 	 * Note that we cannot use lwp_setprivate() here since that
    500 	 * also sets the CPU TLS register, which is incorrect if the
    501 	 * process has changed that without letting the kernel know.
    502 	 */
    503 	l2->l_private = l1->l_private;
    504 
    505 	/*
    506 	 * If emulation has a process fork hook, call it now.
    507 	 */
    508 	if (p2->p_emul->e_proc_fork)
    509 		(*p2->p_emul->e_proc_fork)(p2, l1, flags);
    510 
    511 	/*
    512 	 * ...and finally, any other random fork hooks that subsystems
    513 	 * might have registered.
    514 	 */
    515 	doforkhooks(p2, p1);
    516 
    517 	SDT_PROBE(proc, kernel, , create, p2, p1, flags, 0, 0);
    518 
    519 	/*
    520 	 * It's now safe for the scheduler and other processes to see the
    521 	 * child process.
    522 	 */
    523 	mutex_enter(&proc_lock);
    524 
    525 	if (p1->p_session->s_ttyvp != NULL && p1->p_lflag & PL_CONTROLT)
    526 		p2->p_lflag |= PL_CONTROLT;
    527 
    528 	LIST_INSERT_HEAD(&parent->p_children, p2, p_sibling);
    529 	p2->p_exitsig = exitsig;		/* signal for parent on exit */
    530 
    531 	/*
    532 	 * Trace fork(2) and vfork(2)-like events on demand in a debugger.
    533 	 */
    534 	if (tracefork(p1, flags) || tracevfork(p1, flags)) {
    535 		proc_changeparent(p2, p1->p_pptr);
    536 		SET(p2->p_slflag, PSL_TRACEDCHILD);
    537 	}
    538 
    539 	p2->p_oppid = p1->p_pid; /* Remember the original parent id. */
    540 
    541 	LIST_INSERT_AFTER(p1, p2, p_pglist);
    542 	LIST_INSERT_HEAD(&allproc, p2, p_list);
    543 
    544 	p2->p_trace_enabled = trace_is_enabled(p2);
    545 #ifdef __HAVE_SYSCALL_INTERN
    546 	(*p2->p_emul->e_syscall_intern)(p2);
    547 #endif
    548 
    549 	/*
    550 	 * Update stats now that we know the fork was successful.
    551 	 */
    552 	KPREEMPT_DISABLE(l1);
    553 	CPU_COUNT(CPU_COUNT_FORKS, 1);
    554 	if (flags & FORK_PPWAIT)
    555 		CPU_COUNT(CPU_COUNT_FORKS_PPWAIT, 1);
    556 	if (flags & FORK_SHAREVM)
    557 		CPU_COUNT(CPU_COUNT_FORKS_SHAREVM, 1);
    558 	KPREEMPT_ENABLE(l1);
    559 
    560 	if (ktrpoint(KTR_EMUL))
    561 		p2->p_traceflag |= KTRFAC_TRC_EMUL;
    562 
    563 	/*
    564 	 * Notify any interested parties about the new process.
    565 	 */
    566 	if (!SLIST_EMPTY(&p1->p_klist)) {
    567 		mutex_exit(&proc_lock);
    568 		knote_proc_fork(p1, p2);
    569 		mutex_enter(&proc_lock);
    570 	}
    571 
    572 	/*
    573 	 * Make child runnable, set start time, and add to run queue except
    574 	 * if the parent requested the child to start in SSTOP state.
    575 	 */
    576 	mutex_enter(p2->p_lock);
    577 
    578 	/*
    579 	 * Start profiling.
    580 	 */
    581 	if ((p2->p_stflag & PST_PROFIL) != 0) {
    582 		mutex_spin_enter(&p2->p_stmutex);
    583 		startprofclock(p2);
    584 		mutex_spin_exit(&p2->p_stmutex);
    585 	}
    586 
    587 	getmicrotime(&p2->p_stats->p_start);
    588 	p2->p_acflag = AFORK;
    589 	lwp_lock(l2);
    590 	KASSERT(p2->p_nrlwps == 1);
    591 	KASSERT(l2->l_stat == LSIDL);
    592 	if (p2->p_sflag & PS_STOPFORK) {
    593 		p2->p_nrlwps = 0;
    594 		p2->p_stat = SSTOP;
    595 		p2->p_waited = 0;
    596 		p1->p_nstopchild++;
    597 		l2->l_stat = LSSTOP;
    598 		KASSERT(l2->l_wchan == NULL);
    599 		lwp_unlock(l2);
    600 	} else {
    601 		p2->p_nrlwps = 1;
    602 		p2->p_stat = SACTIVE;
    603 		setrunnable(l2);
    604 		/* LWP now unlocked */
    605 	}
    606 
    607 	/*
    608 	 * Return child pid to parent process,
    609 	 * marking us as parent via retval[1].
    610 	 */
    611 	if (retval != NULL) {
    612 		retval[0] = p2->p_pid;
    613 		retval[1] = 0;
    614 	}
    615 
    616 	mutex_exit(p2->p_lock);
    617 
    618 	/*
    619 	 * Let the parent know that we are tracing its child.
    620 	 */
    621 	if (tracefork(p1, flags) || tracevfork(p1, flags)) {
    622 		mutex_enter(p1->p_lock);
    623 		eventswitch(TRAP_CHLD,
    624 		    tracefork(p1, flags) ? PTRACE_FORK : PTRACE_VFORK,
    625 		    retval[0]);
    626 		mutex_enter(&proc_lock);
    627 	}
    628 
    629 	/*
    630 	 * Preserve synchronization semantics of vfork.  If waiting for
    631 	 * child to exec or exit, sleep until it clears p_vforkwaiting.
    632 	 */
    633 	while (l1->l_vforkwaiting)
    634 		cv_wait(&l1->l_waitcv, &proc_lock);
    635 
    636 	/*
    637 	 * Let the parent know that we are tracing its child.
    638 	 */
    639 	if (tracevforkdone(p1, flags)) {
    640 		mutex_enter(p1->p_lock);
    641 		eventswitch(TRAP_CHLD, PTRACE_VFORK_DONE, retval[0]);
    642 	} else
    643 		mutex_exit(&proc_lock);
    644 
    645 	return 0;
    646 }
    647 
    648 /*
    649  * MI code executed in each newly spawned process before returning to userland.
    650  */
    651 void
    652 child_return(void *arg)
    653 {
    654 	struct lwp *l = curlwp;
    655 	struct proc *p = l->l_proc;
    656 
    657 	if ((p->p_slflag & (PSL_TRACED|PSL_TRACEDCHILD)) ==
    658 	    (PSL_TRACED|PSL_TRACEDCHILD)) {
    659 		eventswitchchild(p, TRAP_CHLD,
    660 		    ISSET(p->p_lflag, PL_PPWAIT) ? PTRACE_VFORK : PTRACE_FORK);
    661 	}
    662 
    663 	md_child_return(l);
    664 
    665 	/*
    666 	 * Return SYS_fork for all fork types, including vfork(2) and clone(2).
    667 	 *
    668 	 * This approach simplifies the code and avoids extra locking.
    669 	 */
    670 	ktrsysret(SYS_fork, 0, 0);
    671 }
    672