xref: /freebsd/sys/kern/kern_fork.c (revision f4f33ea0c752ff0f9bfad34991d5bbb54e71133d)
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  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_ktrace.h"
43 #include "opt_kstack_pages.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/eventhandler.h>
49 #include <sys/fcntl.h>
50 #include <sys/filedesc.h>
51 #include <sys/jail.h>
52 #include <sys/kernel.h>
53 #include <sys/kthread.h>
54 #include <sys/sysctl.h>
55 #include <sys/lock.h>
56 #include <sys/malloc.h>
57 #include <sys/mutex.h>
58 #include <sys/priv.h>
59 #include <sys/proc.h>
60 #include <sys/procdesc.h>
61 #include <sys/pioctl.h>
62 #include <sys/ptrace.h>
63 #include <sys/racct.h>
64 #include <sys/resourcevar.h>
65 #include <sys/sched.h>
66 #include <sys/syscall.h>
67 #include <sys/vmmeter.h>
68 #include <sys/vnode.h>
69 #include <sys/acct.h>
70 #include <sys/ktr.h>
71 #include <sys/ktrace.h>
72 #include <sys/unistd.h>
73 #include <sys/sdt.h>
74 #include <sys/sx.h>
75 #include <sys/sysent.h>
76 #include <sys/signalvar.h>
77 
78 #include <security/audit/audit.h>
79 #include <security/mac/mac_framework.h>
80 
81 #include <vm/vm.h>
82 #include <vm/pmap.h>
83 #include <vm/vm_map.h>
84 #include <vm/vm_extern.h>
85 #include <vm/uma.h>
86 
87 #ifdef KDTRACE_HOOKS
88 #include <sys/dtrace_bsd.h>
89 dtrace_fork_func_t	dtrace_fasttrap_fork;
90 #endif
91 
92 SDT_PROVIDER_DECLARE(proc);
93 SDT_PROBE_DEFINE3(proc, , , create, "struct proc *", "struct proc *", "int");
94 
95 #ifndef _SYS_SYSPROTO_H_
96 struct fork_args {
97 	int     dummy;
98 };
99 #endif
100 
101 EVENTHANDLER_LIST_DECLARE(process_fork);
102 
103 /* ARGSUSED */
104 int
105 sys_fork(struct thread *td, struct fork_args *uap)
106 {
107 	struct fork_req fr;
108 	int error, pid;
109 
110 	bzero(&fr, sizeof(fr));
111 	fr.fr_flags = RFFDG | RFPROC;
112 	fr.fr_pidp = &pid;
113 	error = fork1(td, &fr);
114 	if (error == 0) {
115 		td->td_retval[0] = pid;
116 		td->td_retval[1] = 0;
117 	}
118 	return (error);
119 }
120 
121 /* ARGUSED */
122 int
123 sys_pdfork(struct thread *td, struct pdfork_args *uap)
124 {
125 	struct fork_req fr;
126 	int error, fd, pid;
127 
128 	bzero(&fr, sizeof(fr));
129 	fr.fr_flags = RFFDG | RFPROC | RFPROCDESC;
130 	fr.fr_pidp = &pid;
131 	fr.fr_pd_fd = &fd;
132 	fr.fr_pd_flags = uap->flags;
133 	/*
134 	 * It is necessary to return fd by reference because 0 is a valid file
135 	 * descriptor number, and the child needs to be able to distinguish
136 	 * itself from the parent using the return value.
137 	 */
138 	error = fork1(td, &fr);
139 	if (error == 0) {
140 		td->td_retval[0] = pid;
141 		td->td_retval[1] = 0;
142 		error = copyout(&fd, uap->fdp, sizeof(fd));
143 	}
144 	return (error);
145 }
146 
147 /* ARGSUSED */
148 int
149 sys_vfork(struct thread *td, struct vfork_args *uap)
150 {
151 	struct fork_req fr;
152 	int error, pid;
153 
154 	bzero(&fr, sizeof(fr));
155 	fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
156 	fr.fr_pidp = &pid;
157 	error = fork1(td, &fr);
158 	if (error == 0) {
159 		td->td_retval[0] = pid;
160 		td->td_retval[1] = 0;
161 	}
162 	return (error);
163 }
164 
165 int
166 sys_rfork(struct thread *td, struct rfork_args *uap)
167 {
168 	struct fork_req fr;
169 	int error, pid;
170 
171 	/* Don't allow kernel-only flags. */
172 	if ((uap->flags & RFKERNELONLY) != 0)
173 		return (EINVAL);
174 
175 	AUDIT_ARG_FFLAGS(uap->flags);
176 	bzero(&fr, sizeof(fr));
177 	fr.fr_flags = uap->flags;
178 	fr.fr_pidp = &pid;
179 	error = fork1(td, &fr);
180 	if (error == 0) {
181 		td->td_retval[0] = pid;
182 		td->td_retval[1] = 0;
183 	}
184 	return (error);
185 }
186 
187 int	nprocs = 1;		/* process 0 */
188 int	lastpid = 0;
189 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
190     "Last used PID");
191 
192 /*
193  * Random component to lastpid generation.  We mix in a random factor to make
194  * it a little harder to predict.  We sanity check the modulus value to avoid
195  * doing it in critical paths.  Don't let it be too small or we pointlessly
196  * waste randomness entropy, and don't let it be impossibly large.  Using a
197  * modulus that is too big causes a LOT more process table scans and slows
198  * down fork processing as the pidchecked caching is defeated.
199  */
200 static int randompid = 0;
201 
202 static int
203 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
204 {
205 	int error, pid;
206 
207 	error = sysctl_wire_old_buffer(req, sizeof(int));
208 	if (error != 0)
209 		return(error);
210 	sx_xlock(&allproc_lock);
211 	pid = randompid;
212 	error = sysctl_handle_int(oidp, &pid, 0, req);
213 	if (error == 0 && req->newptr != NULL) {
214 		if (pid == 0)
215 			randompid = 0;
216 		else if (pid == 1)
217 			/* generate a random PID modulus between 100 and 1123 */
218 			randompid = 100 + arc4random() % 1024;
219 		else if (pid < 0 || pid > pid_max - 100)
220 			/* out of range */
221 			randompid = pid_max - 100;
222 		else if (pid < 100)
223 			/* Make it reasonable */
224 			randompid = 100;
225 		else
226 			randompid = pid;
227 	}
228 	sx_xunlock(&allproc_lock);
229 	return (error);
230 }
231 
232 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
233     0, 0, sysctl_kern_randompid, "I", "Random PID modulus. Special values: 0: disable, 1: choose random value");
234 
235 static int
236 fork_findpid(int flags)
237 {
238 	struct proc *p;
239 	int trypid;
240 	static int pidchecked = 0;
241 
242 	/*
243 	 * Requires allproc_lock in order to iterate over the list
244 	 * of processes, and proctree_lock to access p_pgrp.
245 	 */
246 	sx_assert(&allproc_lock, SX_LOCKED);
247 	sx_assert(&proctree_lock, SX_LOCKED);
248 
249 	/*
250 	 * Find an unused process ID.  We remember a range of unused IDs
251 	 * ready to use (from lastpid+1 through pidchecked-1).
252 	 *
253 	 * If RFHIGHPID is set (used during system boot), do not allocate
254 	 * low-numbered pids.
255 	 */
256 	trypid = lastpid + 1;
257 	if (flags & RFHIGHPID) {
258 		if (trypid < 10)
259 			trypid = 10;
260 	} else {
261 		if (randompid)
262 			trypid += arc4random() % randompid;
263 	}
264 retry:
265 	/*
266 	 * If the process ID prototype has wrapped around,
267 	 * restart somewhat above 0, as the low-numbered procs
268 	 * tend to include daemons that don't exit.
269 	 */
270 	if (trypid >= pid_max) {
271 		trypid = trypid % pid_max;
272 		if (trypid < 100)
273 			trypid += 100;
274 		pidchecked = 0;
275 	}
276 	if (trypid >= pidchecked) {
277 		int doingzomb = 0;
278 
279 		pidchecked = PID_MAX;
280 		/*
281 		 * Scan the active and zombie procs to check whether this pid
282 		 * is in use.  Remember the lowest pid that's greater
283 		 * than trypid, so we can avoid checking for a while.
284 		 *
285 		 * Avoid reuse of the process group id, session id or
286 		 * the reaper subtree id.  Note that for process group
287 		 * and sessions, the amount of reserved pids is
288 		 * limited by process limit.  For the subtree ids, the
289 		 * id is kept reserved only while there is a
290 		 * non-reaped process in the subtree, so amount of
291 		 * reserved pids is limited by process limit times
292 		 * two.
293 		 */
294 		p = LIST_FIRST(&allproc);
295 again:
296 		for (; p != NULL; p = LIST_NEXT(p, p_list)) {
297 			while (p->p_pid == trypid ||
298 			    p->p_reapsubtree == trypid ||
299 			    (p->p_pgrp != NULL &&
300 			    (p->p_pgrp->pg_id == trypid ||
301 			    (p->p_session != NULL &&
302 			    p->p_session->s_sid == trypid)))) {
303 				trypid++;
304 				if (trypid >= pidchecked)
305 					goto retry;
306 			}
307 			if (p->p_pid > trypid && pidchecked > p->p_pid)
308 				pidchecked = p->p_pid;
309 			if (p->p_pgrp != NULL) {
310 				if (p->p_pgrp->pg_id > trypid &&
311 				    pidchecked > p->p_pgrp->pg_id)
312 					pidchecked = p->p_pgrp->pg_id;
313 				if (p->p_session != NULL &&
314 				    p->p_session->s_sid > trypid &&
315 				    pidchecked > p->p_session->s_sid)
316 					pidchecked = p->p_session->s_sid;
317 			}
318 		}
319 		if (!doingzomb) {
320 			doingzomb = 1;
321 			p = LIST_FIRST(&zombproc);
322 			goto again;
323 		}
324 	}
325 
326 	/*
327 	 * RFHIGHPID does not mess with the lastpid counter during boot.
328 	 */
329 	if (flags & RFHIGHPID)
330 		pidchecked = 0;
331 	else
332 		lastpid = trypid;
333 
334 	return (trypid);
335 }
336 
337 static int
338 fork_norfproc(struct thread *td, int flags)
339 {
340 	int error;
341 	struct proc *p1;
342 
343 	KASSERT((flags & RFPROC) == 0,
344 	    ("fork_norfproc called with RFPROC set"));
345 	p1 = td->td_proc;
346 
347 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
348 	    (flags & (RFCFDG | RFFDG))) {
349 		PROC_LOCK(p1);
350 		if (thread_single(p1, SINGLE_BOUNDARY)) {
351 			PROC_UNLOCK(p1);
352 			return (ERESTART);
353 		}
354 		PROC_UNLOCK(p1);
355 	}
356 
357 	error = vm_forkproc(td, NULL, NULL, NULL, flags);
358 	if (error)
359 		goto fail;
360 
361 	/*
362 	 * Close all file descriptors.
363 	 */
364 	if (flags & RFCFDG) {
365 		struct filedesc *fdtmp;
366 		fdtmp = fdinit(td->td_proc->p_fd, false);
367 		fdescfree(td);
368 		p1->p_fd = fdtmp;
369 	}
370 
371 	/*
372 	 * Unshare file descriptors (from parent).
373 	 */
374 	if (flags & RFFDG)
375 		fdunshare(td);
376 
377 fail:
378 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
379 	    (flags & (RFCFDG | RFFDG))) {
380 		PROC_LOCK(p1);
381 		thread_single_end(p1, SINGLE_BOUNDARY);
382 		PROC_UNLOCK(p1);
383 	}
384 	return (error);
385 }
386 
387 static void
388 do_fork(struct thread *td, struct fork_req *fr, struct proc *p2, struct thread *td2,
389     struct vmspace *vm2, struct file *fp_procdesc)
390 {
391 	struct proc *p1, *pptr;
392 	int trypid;
393 	struct filedesc *fd;
394 	struct filedesc_to_leader *fdtol;
395 	struct sigacts *newsigacts;
396 
397 	sx_assert(&proctree_lock, SX_LOCKED);
398 	sx_assert(&allproc_lock, SX_XLOCKED);
399 
400 	p1 = td->td_proc;
401 
402 	trypid = fork_findpid(fr->fr_flags);
403 
404 	p2->p_state = PRS_NEW;		/* protect against others */
405 	p2->p_pid = trypid;
406 	AUDIT_ARG_PID(p2->p_pid);
407 	LIST_INSERT_HEAD(&allproc, p2, p_list);
408 	allproc_gen++;
409 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
410 	PROC_LOCK(p2);
411 	PROC_LOCK(p1);
412 
413 	sx_xunlock(&allproc_lock);
414 	sx_xunlock(&proctree_lock);
415 
416 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
417 	    __rangeof(struct proc, p_startcopy, p_endcopy));
418 	pargs_hold(p2->p_args);
419 
420 	PROC_UNLOCK(p1);
421 
422 	bzero(&p2->p_startzero,
423 	    __rangeof(struct proc, p_startzero, p_endzero));
424 
425 	/* Tell the prison that we exist. */
426 	prison_proc_hold(p2->p_ucred->cr_prison);
427 
428 	PROC_UNLOCK(p2);
429 
430 	tidhash_add(td2);
431 
432 	/*
433 	 * Malloc things while we don't hold any locks.
434 	 */
435 	if (fr->fr_flags & RFSIGSHARE)
436 		newsigacts = NULL;
437 	else
438 		newsigacts = sigacts_alloc();
439 
440 	/*
441 	 * Copy filedesc.
442 	 */
443 	if (fr->fr_flags & RFCFDG) {
444 		fd = fdinit(p1->p_fd, false);
445 		fdtol = NULL;
446 	} else if (fr->fr_flags & RFFDG) {
447 		fd = fdcopy(p1->p_fd);
448 		fdtol = NULL;
449 	} else {
450 		fd = fdshare(p1->p_fd);
451 		if (p1->p_fdtol == NULL)
452 			p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL,
453 			    p1->p_leader);
454 		if ((fr->fr_flags & RFTHREAD) != 0) {
455 			/*
456 			 * Shared file descriptor table, and shared
457 			 * process leaders.
458 			 */
459 			fdtol = p1->p_fdtol;
460 			FILEDESC_XLOCK(p1->p_fd);
461 			fdtol->fdl_refcount++;
462 			FILEDESC_XUNLOCK(p1->p_fd);
463 		} else {
464 			/*
465 			 * Shared file descriptor table, and different
466 			 * process leaders.
467 			 */
468 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
469 			    p1->p_fd, p2);
470 		}
471 	}
472 	/*
473 	 * Make a proc table entry for the new process.
474 	 * Start by zeroing the section of proc that is zero-initialized,
475 	 * then copy the section that is copied directly from the parent.
476 	 */
477 
478 	PROC_LOCK(p2);
479 	PROC_LOCK(p1);
480 
481 	bzero(&td2->td_startzero,
482 	    __rangeof(struct thread, td_startzero, td_endzero));
483 
484 	bcopy(&td->td_startcopy, &td2->td_startcopy,
485 	    __rangeof(struct thread, td_startcopy, td_endcopy));
486 
487 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
488 	td2->td_sigstk = td->td_sigstk;
489 	td2->td_flags = TDF_INMEM;
490 	td2->td_lend_user_pri = PRI_MAX;
491 
492 #ifdef VIMAGE
493 	td2->td_vnet = NULL;
494 	td2->td_vnet_lpush = NULL;
495 #endif
496 
497 	/*
498 	 * Allow the scheduler to initialize the child.
499 	 */
500 	thread_lock(td);
501 	sched_fork(td, td2);
502 	thread_unlock(td);
503 
504 	/*
505 	 * Duplicate sub-structures as needed.
506 	 * Increase reference counts on shared objects.
507 	 */
508 	p2->p_flag = P_INMEM;
509 	p2->p_flag2 = p1->p_flag2 & (P2_NOTRACE | P2_NOTRACE_EXEC | P2_TRAPCAP);
510 	p2->p_swtick = ticks;
511 	if (p1->p_flag & P_PROFIL)
512 		startprofclock(p2);
513 
514 	if (fr->fr_flags & RFSIGSHARE) {
515 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
516 	} else {
517 		sigacts_copy(newsigacts, p1->p_sigacts);
518 		p2->p_sigacts = newsigacts;
519 	}
520 
521 	if (fr->fr_flags & RFTSIGZMB)
522 	        p2->p_sigparent = RFTSIGNUM(fr->fr_flags);
523 	else if (fr->fr_flags & RFLINUXTHPN)
524 	        p2->p_sigparent = SIGUSR1;
525 	else
526 	        p2->p_sigparent = SIGCHLD;
527 
528 	p2->p_textvp = p1->p_textvp;
529 	p2->p_fd = fd;
530 	p2->p_fdtol = fdtol;
531 
532 	if (p1->p_flag2 & P2_INHERIT_PROTECTED) {
533 		p2->p_flag |= P_PROTECTED;
534 		p2->p_flag2 |= P2_INHERIT_PROTECTED;
535 	}
536 
537 	/*
538 	 * p_limit is copy-on-write.  Bump its refcount.
539 	 */
540 	lim_fork(p1, p2);
541 
542 	thread_cow_get_proc(td2, p2);
543 
544 	pstats_fork(p1->p_stats, p2->p_stats);
545 
546 	PROC_UNLOCK(p1);
547 	PROC_UNLOCK(p2);
548 
549 	/* Bump references to the text vnode (for procfs). */
550 	if (p2->p_textvp)
551 		vrefact(p2->p_textvp);
552 
553 	/*
554 	 * Set up linkage for kernel based threading.
555 	 */
556 	if ((fr->fr_flags & RFTHREAD) != 0) {
557 		mtx_lock(&ppeers_lock);
558 		p2->p_peers = p1->p_peers;
559 		p1->p_peers = p2;
560 		p2->p_leader = p1->p_leader;
561 		mtx_unlock(&ppeers_lock);
562 		PROC_LOCK(p1->p_leader);
563 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
564 			PROC_UNLOCK(p1->p_leader);
565 			/*
566 			 * The task leader is exiting, so process p1 is
567 			 * going to be killed shortly.  Since p1 obviously
568 			 * isn't dead yet, we know that the leader is either
569 			 * sending SIGKILL's to all the processes in this
570 			 * task or is sleeping waiting for all the peers to
571 			 * exit.  We let p1 complete the fork, but we need
572 			 * to go ahead and kill the new process p2 since
573 			 * the task leader may not get a chance to send
574 			 * SIGKILL to it.  We leave it on the list so that
575 			 * the task leader will wait for this new process
576 			 * to commit suicide.
577 			 */
578 			PROC_LOCK(p2);
579 			kern_psignal(p2, SIGKILL);
580 			PROC_UNLOCK(p2);
581 		} else
582 			PROC_UNLOCK(p1->p_leader);
583 	} else {
584 		p2->p_peers = NULL;
585 		p2->p_leader = p2;
586 	}
587 
588 	sx_xlock(&proctree_lock);
589 	PGRP_LOCK(p1->p_pgrp);
590 	PROC_LOCK(p2);
591 	PROC_LOCK(p1);
592 
593 	/*
594 	 * Preserve some more flags in subprocess.  P_PROFIL has already
595 	 * been preserved.
596 	 */
597 	p2->p_flag |= p1->p_flag & P_SUGID;
598 	td2->td_pflags |= (td->td_pflags & TDP_ALTSTACK) | TDP_FORKING;
599 	SESS_LOCK(p1->p_session);
600 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
601 		p2->p_flag |= P_CONTROLT;
602 	SESS_UNLOCK(p1->p_session);
603 	if (fr->fr_flags & RFPPWAIT)
604 		p2->p_flag |= P_PPWAIT;
605 
606 	p2->p_pgrp = p1->p_pgrp;
607 	LIST_INSERT_AFTER(p1, p2, p_pglist);
608 	PGRP_UNLOCK(p1->p_pgrp);
609 	LIST_INIT(&p2->p_children);
610 	LIST_INIT(&p2->p_orphans);
611 
612 	callout_init_mtx(&p2->p_itcallout, &p2->p_mtx, 0);
613 
614 	/*
615 	 * If PF_FORK is set, the child process inherits the
616 	 * procfs ioctl flags from its parent.
617 	 */
618 	if (p1->p_pfsflags & PF_FORK) {
619 		p2->p_stops = p1->p_stops;
620 		p2->p_pfsflags = p1->p_pfsflags;
621 	}
622 
623 	/*
624 	 * This begins the section where we must prevent the parent
625 	 * from being swapped.
626 	 */
627 	_PHOLD(p1);
628 	PROC_UNLOCK(p1);
629 
630 	/*
631 	 * Attach the new process to its parent.
632 	 *
633 	 * If RFNOWAIT is set, the newly created process becomes a child
634 	 * of init.  This effectively disassociates the child from the
635 	 * parent.
636 	 */
637 	if ((fr->fr_flags & RFNOWAIT) != 0) {
638 		pptr = p1->p_reaper;
639 		p2->p_reaper = pptr;
640 	} else {
641 		p2->p_reaper = (p1->p_treeflag & P_TREE_REAPER) != 0 ?
642 		    p1 : p1->p_reaper;
643 		pptr = p1;
644 	}
645 	p2->p_pptr = pptr;
646 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
647 	LIST_INIT(&p2->p_reaplist);
648 	LIST_INSERT_HEAD(&p2->p_reaper->p_reaplist, p2, p_reapsibling);
649 	if (p2->p_reaper == p1)
650 		p2->p_reapsubtree = p2->p_pid;
651 	sx_xunlock(&proctree_lock);
652 
653 	/* Inform accounting that we have forked. */
654 	p2->p_acflag = AFORK;
655 	PROC_UNLOCK(p2);
656 
657 #ifdef KTRACE
658 	ktrprocfork(p1, p2);
659 #endif
660 
661 	/*
662 	 * Finish creating the child process.  It will return via a different
663 	 * execution path later.  (ie: directly into user mode)
664 	 */
665 	vm_forkproc(td, p2, td2, vm2, fr->fr_flags);
666 
667 	if (fr->fr_flags == (RFFDG | RFPROC)) {
668 		VM_CNT_INC(v_forks);
669 		VM_CNT_ADD(v_forkpages, p2->p_vmspace->vm_dsize +
670 		    p2->p_vmspace->vm_ssize);
671 	} else if (fr->fr_flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
672 		VM_CNT_INC(v_vforks);
673 		VM_CNT_ADD(v_vforkpages, p2->p_vmspace->vm_dsize +
674 		    p2->p_vmspace->vm_ssize);
675 	} else if (p1 == &proc0) {
676 		VM_CNT_INC(v_kthreads);
677 		VM_CNT_ADD(v_kthreadpages, p2->p_vmspace->vm_dsize +
678 		    p2->p_vmspace->vm_ssize);
679 	} else {
680 		VM_CNT_INC(v_rforks);
681 		VM_CNT_ADD(v_rforkpages, p2->p_vmspace->vm_dsize +
682 		    p2->p_vmspace->vm_ssize);
683 	}
684 
685 	/*
686 	 * Associate the process descriptor with the process before anything
687 	 * can happen that might cause that process to need the descriptor.
688 	 * However, don't do this until after fork(2) can no longer fail.
689 	 */
690 	if (fr->fr_flags & RFPROCDESC)
691 		procdesc_new(p2, fr->fr_pd_flags);
692 
693 	/*
694 	 * Both processes are set up, now check if any loadable modules want
695 	 * to adjust anything.
696 	 */
697 	EVENTHANDLER_DIRECT_INVOKE(process_fork, p1, p2, fr->fr_flags);
698 
699 	/*
700 	 * Set the child start time and mark the process as being complete.
701 	 */
702 	PROC_LOCK(p2);
703 	PROC_LOCK(p1);
704 	microuptime(&p2->p_stats->p_start);
705 	PROC_SLOCK(p2);
706 	p2->p_state = PRS_NORMAL;
707 	PROC_SUNLOCK(p2);
708 
709 #ifdef KDTRACE_HOOKS
710 	/*
711 	 * Tell the DTrace fasttrap provider about the new process so that any
712 	 * tracepoints inherited from the parent can be removed. We have to do
713 	 * this only after p_state is PRS_NORMAL since the fasttrap module will
714 	 * use pfind() later on.
715 	 */
716 	if ((fr->fr_flags & RFMEM) == 0 && dtrace_fasttrap_fork)
717 		dtrace_fasttrap_fork(p1, p2);
718 #endif
719 	/*
720 	 * Hold the process so that it cannot exit after we make it runnable,
721 	 * but before we wait for the debugger.
722 	 */
723 	_PHOLD(p2);
724 	if (fr->fr_flags & RFPPWAIT) {
725 		td->td_pflags |= TDP_RFPPWAIT;
726 		td->td_rfppwait_p = p2;
727 		td->td_dbgflags |= TDB_VFORK;
728 	}
729 	PROC_UNLOCK(p2);
730 
731 	/*
732 	 * Now can be swapped.
733 	 */
734 	_PRELE(p1);
735 	PROC_UNLOCK(p1);
736 
737 	/*
738 	 * Tell any interested parties about the new process.
739 	 */
740 	knote_fork(p1->p_klist, p2->p_pid);
741 	SDT_PROBE3(proc, , , create, p2, p1, fr->fr_flags);
742 
743 	if (fr->fr_flags & RFPROCDESC) {
744 		procdesc_finit(p2->p_procdesc, fp_procdesc);
745 		fdrop(fp_procdesc, td);
746 	}
747 
748 	/*
749 	 * Speculative check for PTRACE_FORK. PTRACE_FORK is not
750 	 * synced with forks in progress so it is OK if we miss it
751 	 * if being set atm.
752 	 */
753 	if ((p1->p_ptevents & PTRACE_FORK) != 0) {
754 		sx_xlock(&proctree_lock);
755 		PROC_LOCK(p2);
756 
757 		/*
758 		 * p1->p_ptevents & p1->p_pptr are protected by both
759 		 * process and proctree locks for modifications,
760 		 * so owning proctree_lock allows the race-free read.
761 		 */
762 		if ((p1->p_ptevents & PTRACE_FORK) != 0) {
763 			/*
764 			 * Arrange for debugger to receive the fork event.
765 			 *
766 			 * We can report PL_FLAG_FORKED regardless of
767 			 * P_FOLLOWFORK settings, but it does not make a sense
768 			 * for runaway child.
769 			 */
770 			td->td_dbgflags |= TDB_FORK;
771 			td->td_dbg_forked = p2->p_pid;
772 			td2->td_dbgflags |= TDB_STOPATFORK;
773 			proc_set_traced(p2, true);
774 			CTR2(KTR_PTRACE,
775 			    "do_fork: attaching to new child pid %d: oppid %d",
776 			    p2->p_pid, p2->p_oppid);
777 			proc_reparent(p2, p1->p_pptr);
778 		}
779 		PROC_UNLOCK(p2);
780 		sx_xunlock(&proctree_lock);
781 	}
782 
783 	if ((fr->fr_flags & RFSTOPPED) == 0) {
784 		/*
785 		 * If RFSTOPPED not requested, make child runnable and
786 		 * add to run queue.
787 		 */
788 		thread_lock(td2);
789 		TD_SET_CAN_RUN(td2);
790 		sched_add(td2, SRQ_BORING);
791 		thread_unlock(td2);
792 		if (fr->fr_pidp != NULL)
793 			*fr->fr_pidp = p2->p_pid;
794 	} else {
795 		*fr->fr_procp = p2;
796 	}
797 
798 	PROC_LOCK(p2);
799 	_PRELE(p2);
800 	racct_proc_fork_done(p2);
801 	PROC_UNLOCK(p2);
802 }
803 
804 int
805 fork1(struct thread *td, struct fork_req *fr)
806 {
807 	struct proc *p1, *newproc;
808 	struct thread *td2;
809 	struct vmspace *vm2;
810 	struct file *fp_procdesc;
811 	vm_ooffset_t mem_charged;
812 	int error, nprocs_new, ok;
813 	static int curfail;
814 	static struct timeval lastfail;
815 	int flags, pages;
816 
817 	flags = fr->fr_flags;
818 	pages = fr->fr_pages;
819 
820 	if ((flags & RFSTOPPED) != 0)
821 		MPASS(fr->fr_procp != NULL && fr->fr_pidp == NULL);
822 	else
823 		MPASS(fr->fr_procp == NULL);
824 
825 	/* Check for the undefined or unimplemented flags. */
826 	if ((flags & ~(RFFLAGS | RFTSIGFLAGS(RFTSIGMASK))) != 0)
827 		return (EINVAL);
828 
829 	/* Signal value requires RFTSIGZMB. */
830 	if ((flags & RFTSIGFLAGS(RFTSIGMASK)) != 0 && (flags & RFTSIGZMB) == 0)
831 		return (EINVAL);
832 
833 	/* Can't copy and clear. */
834 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
835 		return (EINVAL);
836 
837 	/* Check the validity of the signal number. */
838 	if ((flags & RFTSIGZMB) != 0 && (u_int)RFTSIGNUM(flags) > _SIG_MAXSIG)
839 		return (EINVAL);
840 
841 	if ((flags & RFPROCDESC) != 0) {
842 		/* Can't not create a process yet get a process descriptor. */
843 		if ((flags & RFPROC) == 0)
844 			return (EINVAL);
845 
846 		/* Must provide a place to put a procdesc if creating one. */
847 		if (fr->fr_pd_fd == NULL)
848 			return (EINVAL);
849 
850 		/* Check if we are using supported flags. */
851 		if ((fr->fr_pd_flags & ~PD_ALLOWED_AT_FORK) != 0)
852 			return (EINVAL);
853 	}
854 
855 	p1 = td->td_proc;
856 
857 	/*
858 	 * Here we don't create a new process, but we divorce
859 	 * certain parts of a process from itself.
860 	 */
861 	if ((flags & RFPROC) == 0) {
862 		if (fr->fr_procp != NULL)
863 			*fr->fr_procp = NULL;
864 		else if (fr->fr_pidp != NULL)
865 			*fr->fr_pidp = 0;
866 		return (fork_norfproc(td, flags));
867 	}
868 
869 	fp_procdesc = NULL;
870 	newproc = NULL;
871 	vm2 = NULL;
872 
873 	/*
874 	 * Increment the nprocs resource before allocations occur.
875 	 * Although process entries are dynamically created, we still
876 	 * keep a global limit on the maximum number we will
877 	 * create. There are hard-limits as to the number of processes
878 	 * that can run, established by the KVA and memory usage for
879 	 * the process data.
880 	 *
881 	 * Don't allow a nonprivileged user to use the last ten
882 	 * processes; don't let root exceed the limit.
883 	 */
884 	nprocs_new = atomic_fetchadd_int(&nprocs, 1) + 1;
885 	if ((nprocs_new >= maxproc - 10 && priv_check_cred(td->td_ucred,
886 	    PRIV_MAXPROC, 0) != 0) || nprocs_new >= maxproc) {
887 		error = EAGAIN;
888 		sx_xlock(&allproc_lock);
889 		if (ppsratecheck(&lastfail, &curfail, 1)) {
890 			printf("maxproc limit exceeded by uid %u (pid %d); "
891 			    "see tuning(7) and login.conf(5)\n",
892 			    td->td_ucred->cr_ruid, p1->p_pid);
893 		}
894 		sx_xunlock(&allproc_lock);
895 		goto fail2;
896 	}
897 
898 	/*
899 	 * If required, create a process descriptor in the parent first; we
900 	 * will abandon it if something goes wrong. We don't finit() until
901 	 * later.
902 	 */
903 	if (flags & RFPROCDESC) {
904 		error = procdesc_falloc(td, &fp_procdesc, fr->fr_pd_fd,
905 		    fr->fr_pd_flags, fr->fr_pd_fcaps);
906 		if (error != 0)
907 			goto fail2;
908 	}
909 
910 	mem_charged = 0;
911 	if (pages == 0)
912 		pages = kstack_pages;
913 	/* Allocate new proc. */
914 	newproc = uma_zalloc(proc_zone, M_WAITOK);
915 	td2 = FIRST_THREAD_IN_PROC(newproc);
916 	if (td2 == NULL) {
917 		td2 = thread_alloc(pages);
918 		if (td2 == NULL) {
919 			error = ENOMEM;
920 			goto fail2;
921 		}
922 		proc_linkup(newproc, td2);
923 	} else {
924 		if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
925 			if (td2->td_kstack != 0)
926 				vm_thread_dispose(td2);
927 			if (!thread_alloc_stack(td2, pages)) {
928 				error = ENOMEM;
929 				goto fail2;
930 			}
931 		}
932 	}
933 
934 	if ((flags & RFMEM) == 0) {
935 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
936 		if (vm2 == NULL) {
937 			error = ENOMEM;
938 			goto fail2;
939 		}
940 		if (!swap_reserve(mem_charged)) {
941 			/*
942 			 * The swap reservation failed. The accounting
943 			 * from the entries of the copied vm2 will be
944 			 * subtracted in vmspace_free(), so force the
945 			 * reservation there.
946 			 */
947 			swap_reserve_force(mem_charged);
948 			error = ENOMEM;
949 			goto fail2;
950 		}
951 	} else
952 		vm2 = NULL;
953 
954 	/*
955 	 * XXX: This is ugly; when we copy resource usage, we need to bump
956 	 *      per-cred resource counters.
957 	 */
958 	proc_set_cred_init(newproc, crhold(td->td_ucred));
959 
960 	/*
961 	 * Initialize resource accounting for the child process.
962 	 */
963 	error = racct_proc_fork(p1, newproc);
964 	if (error != 0) {
965 		error = EAGAIN;
966 		goto fail1;
967 	}
968 
969 #ifdef MAC
970 	mac_proc_init(newproc);
971 #endif
972 	newproc->p_klist = knlist_alloc(&newproc->p_mtx);
973 	STAILQ_INIT(&newproc->p_ktr);
974 
975 	/* We have to lock the process tree while we look for a pid. */
976 	sx_xlock(&proctree_lock);
977 	sx_xlock(&allproc_lock);
978 
979 	/*
980 	 * Increment the count of procs running with this uid. Don't allow
981 	 * a nonprivileged user to exceed their current limit.
982 	 *
983 	 * XXXRW: Can we avoid privilege here if it's not needed?
984 	 */
985 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
986 	if (error == 0)
987 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
988 	else {
989 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
990 		    lim_cur(td, RLIMIT_NPROC));
991 	}
992 	if (ok) {
993 		do_fork(td, fr, newproc, td2, vm2, fp_procdesc);
994 		return (0);
995 	}
996 
997 	error = EAGAIN;
998 	sx_xunlock(&allproc_lock);
999 	sx_xunlock(&proctree_lock);
1000 #ifdef MAC
1001 	mac_proc_destroy(newproc);
1002 #endif
1003 	racct_proc_exit(newproc);
1004 fail1:
1005 	crfree(newproc->p_ucred);
1006 	newproc->p_ucred = NULL;
1007 fail2:
1008 	if (vm2 != NULL)
1009 		vmspace_free(vm2);
1010 	uma_zfree(proc_zone, newproc);
1011 	if ((flags & RFPROCDESC) != 0 && fp_procdesc != NULL) {
1012 		fdclose(td, fp_procdesc, *fr->fr_pd_fd);
1013 		fdrop(fp_procdesc, td);
1014 	}
1015 	atomic_add_int(&nprocs, -1);
1016 	pause("fork", hz / 2);
1017 	return (error);
1018 }
1019 
1020 /*
1021  * Handle the return of a child process from fork1().  This function
1022  * is called from the MD fork_trampoline() entry point.
1023  */
1024 void
1025 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
1026     struct trapframe *frame)
1027 {
1028 	struct proc *p;
1029 	struct thread *td;
1030 	struct thread *dtd;
1031 
1032 	td = curthread;
1033 	p = td->td_proc;
1034 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
1035 
1036 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
1037 	    td, td_get_sched(td), p->p_pid, td->td_name);
1038 
1039 	sched_fork_exit(td);
1040 	/*
1041 	* Processes normally resume in mi_switch() after being
1042 	* cpu_switch()'ed to, but when children start up they arrive here
1043 	* instead, so we must do much the same things as mi_switch() would.
1044 	*/
1045 	if ((dtd = PCPU_GET(deadthread))) {
1046 		PCPU_SET(deadthread, NULL);
1047 		thread_stash(dtd);
1048 	}
1049 	thread_unlock(td);
1050 
1051 	/*
1052 	 * cpu_fork_kthread_handler intercepts this function call to
1053 	 * have this call a non-return function to stay in kernel mode.
1054 	 * initproc has its own fork handler, but it does return.
1055 	 */
1056 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
1057 	callout(arg, frame);
1058 
1059 	/*
1060 	 * Check if a kernel thread misbehaved and returned from its main
1061 	 * function.
1062 	 */
1063 	if (p->p_flag & P_KPROC) {
1064 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
1065 		    td->td_name, p->p_pid);
1066 		kthread_exit();
1067 	}
1068 	mtx_assert(&Giant, MA_NOTOWNED);
1069 
1070 	if (p->p_sysent->sv_schedtail != NULL)
1071 		(p->p_sysent->sv_schedtail)(td);
1072 	td->td_pflags &= ~TDP_FORKING;
1073 }
1074 
1075 /*
1076  * Simplified back end of syscall(), used when returning from fork()
1077  * directly into user mode.  This function is passed in to fork_exit()
1078  * as the first parameter and is called when returning to a new
1079  * userland process.
1080  */
1081 void
1082 fork_return(struct thread *td, struct trapframe *frame)
1083 {
1084 	struct proc *p;
1085 
1086 	p = td->td_proc;
1087 	if (td->td_dbgflags & TDB_STOPATFORK) {
1088 		PROC_LOCK(p);
1089 		if ((p->p_flag & P_TRACED) != 0) {
1090 			/*
1091 			 * Inform the debugger if one is still present.
1092 			 */
1093 			td->td_dbgflags |= TDB_CHILD | TDB_SCX | TDB_FSTP;
1094 			ptracestop(td, SIGSTOP, NULL);
1095 			td->td_dbgflags &= ~(TDB_CHILD | TDB_SCX);
1096 		} else {
1097 			/*
1098 			 * ... otherwise clear the request.
1099 			 */
1100 			td->td_dbgflags &= ~TDB_STOPATFORK;
1101 		}
1102 		PROC_UNLOCK(p);
1103 	} else if (p->p_flag & P_TRACED || td->td_dbgflags & TDB_BORN) {
1104  		/*
1105 		 * This is the start of a new thread in a traced
1106 		 * process.  Report a system call exit event.
1107 		 */
1108 		PROC_LOCK(p);
1109 		td->td_dbgflags |= TDB_SCX;
1110 		_STOPEVENT(p, S_SCX, td->td_sa.code);
1111 		if ((p->p_ptevents & PTRACE_SCX) != 0 ||
1112 		    (td->td_dbgflags & TDB_BORN) != 0)
1113 			ptracestop(td, SIGTRAP, NULL);
1114 		td->td_dbgflags &= ~(TDB_SCX | TDB_BORN);
1115 		PROC_UNLOCK(p);
1116 	}
1117 
1118 	userret(td, frame);
1119 
1120 #ifdef KTRACE
1121 	if (KTRPOINT(td, KTR_SYSRET))
1122 		ktrsysret(SYS_fork, 0, 0);
1123 #endif
1124 }
1125