xref: /freebsd/sys/kern/kern_fork.c (revision 6d4b97158fa99be390dba1c61c1d1f547852aef6)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_kdtrace.h"
41 #include "opt_ktrace.h"
42 #include "opt_kstack_pages.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/eventhandler.h>
48 #include <sys/filedesc.h>
49 #include <sys/jail.h>
50 #include <sys/kernel.h>
51 #include <sys/kthread.h>
52 #include <sys/sysctl.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mutex.h>
56 #include <sys/priv.h>
57 #include <sys/proc.h>
58 #include <sys/pioctl.h>
59 #include <sys/resourcevar.h>
60 #include <sys/sched.h>
61 #include <sys/syscall.h>
62 #include <sys/vmmeter.h>
63 #include <sys/vnode.h>
64 #include <sys/acct.h>
65 #include <sys/ktr.h>
66 #include <sys/ktrace.h>
67 #include <sys/unistd.h>
68 #include <sys/sdt.h>
69 #include <sys/sx.h>
70 #include <sys/signalvar.h>
71 
72 #include <security/audit/audit.h>
73 #include <security/mac/mac_framework.h>
74 
75 #include <vm/vm.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_extern.h>
79 #include <vm/uma.h>
80 
81 #ifdef KDTRACE_HOOKS
82 #include <sys/dtrace_bsd.h>
83 dtrace_fork_func_t	dtrace_fasttrap_fork;
84 #endif
85 
86 SDT_PROVIDER_DECLARE(proc);
87 SDT_PROBE_DEFINE(proc, kernel, , create, create);
88 SDT_PROBE_ARGTYPE(proc, kernel, , create, 0, "struct proc *");
89 SDT_PROBE_ARGTYPE(proc, kernel, , create, 1, "struct proc *");
90 SDT_PROBE_ARGTYPE(proc, kernel, , create, 2, "int");
91 
92 #ifndef _SYS_SYSPROTO_H_
93 struct fork_args {
94 	int     dummy;
95 };
96 #endif
97 
98 /* ARGSUSED */
99 int
100 fork(struct thread *td, struct fork_args *uap)
101 {
102 	int error;
103 	struct proc *p2;
104 
105 	error = fork1(td, RFFDG | RFPROC, 0, &p2);
106 	if (error == 0) {
107 		td->td_retval[0] = p2->p_pid;
108 		td->td_retval[1] = 0;
109 	}
110 	return (error);
111 }
112 
113 /* ARGSUSED */
114 int
115 vfork(td, uap)
116 	struct thread *td;
117 	struct vfork_args *uap;
118 {
119 	int error, flags;
120 	struct proc *p2;
121 
122 #ifdef XEN
123 	flags = RFFDG | RFPROC; /* validate that this is still an issue */
124 #else
125 	flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
126 #endif
127 	error = fork1(td, flags, 0, &p2);
128 	if (error == 0) {
129 		td->td_retval[0] = p2->p_pid;
130 		td->td_retval[1] = 0;
131 	}
132 	return (error);
133 }
134 
135 int
136 rfork(struct thread *td, struct rfork_args *uap)
137 {
138 	struct proc *p2;
139 	int error;
140 
141 	/* Don't allow kernel-only flags. */
142 	if ((uap->flags & RFKERNELONLY) != 0)
143 		return (EINVAL);
144 
145 	AUDIT_ARG_FFLAGS(uap->flags);
146 	error = fork1(td, uap->flags, 0, &p2);
147 	if (error == 0) {
148 		td->td_retval[0] = p2 ? p2->p_pid : 0;
149 		td->td_retval[1] = 0;
150 	}
151 	return (error);
152 }
153 
154 int	nprocs = 1;		/* process 0 */
155 int	lastpid = 0;
156 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
157     "Last used PID");
158 
159 /*
160  * Random component to lastpid generation.  We mix in a random factor to make
161  * it a little harder to predict.  We sanity check the modulus value to avoid
162  * doing it in critical paths.  Don't let it be too small or we pointlessly
163  * waste randomness entropy, and don't let it be impossibly large.  Using a
164  * modulus that is too big causes a LOT more process table scans and slows
165  * down fork processing as the pidchecked caching is defeated.
166  */
167 static int randompid = 0;
168 
169 static int
170 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
171 {
172 	int error, pid;
173 
174 	error = sysctl_wire_old_buffer(req, sizeof(int));
175 	if (error != 0)
176 		return(error);
177 	sx_xlock(&allproc_lock);
178 	pid = randompid;
179 	error = sysctl_handle_int(oidp, &pid, 0, req);
180 	if (error == 0 && req->newptr != NULL) {
181 		if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
182 			pid = PID_MAX - 100;
183 		else if (pid < 2)			/* NOP */
184 			pid = 0;
185 		else if (pid < 100)			/* Make it reasonable */
186 			pid = 100;
187 		randompid = pid;
188 	}
189 	sx_xunlock(&allproc_lock);
190 	return (error);
191 }
192 
193 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
194     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
195 
196 static int
197 fork_norfproc(struct thread *td, int flags, struct proc **procp)
198 {
199 	int error;
200 	struct proc *p1;
201 
202 	KASSERT((flags & RFPROC) == 0,
203 	    ("fork_norfproc called with RFPROC set"));
204 	p1 = td->td_proc;
205 	*procp = NULL;
206 
207 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
208 	    (flags & (RFCFDG | RFFDG))) {
209 		PROC_LOCK(p1);
210 		if (thread_single(SINGLE_BOUNDARY)) {
211 			PROC_UNLOCK(p1);
212 			return (ERESTART);
213 		}
214 		PROC_UNLOCK(p1);
215 	}
216 
217 	error = vm_forkproc(td, NULL, NULL, NULL, flags);
218 	if (error)
219 		goto fail;
220 
221 	/*
222 	 * Close all file descriptors.
223 	 */
224 	if (flags & RFCFDG) {
225 		struct filedesc *fdtmp;
226 		fdtmp = fdinit(td->td_proc->p_fd);
227 		fdfree(td);
228 		p1->p_fd = fdtmp;
229 	}
230 
231 	/*
232 	 * Unshare file descriptors (from parent).
233 	 */
234 	if (flags & RFFDG)
235 		fdunshare(p1, td);
236 
237 fail:
238 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
239 	    (flags & (RFCFDG | RFFDG))) {
240 		PROC_LOCK(p1);
241 		thread_single_end();
242 		PROC_UNLOCK(p1);
243 	}
244 	return (error);
245 }
246 
247 int
248 fork1(struct thread *td, int flags, int pages, struct proc **procp)
249 {
250 	struct proc *p1, *p2, *pptr;
251 	struct proc *newproc;
252 	int ok, trypid;
253 	static int curfail, pidchecked = 0;
254 	static struct timeval lastfail;
255 	struct filedesc *fd;
256 	struct filedesc_to_leader *fdtol;
257 	struct thread *td2;
258 	struct sigacts *newsigacts;
259 	struct vmspace *vm2;
260 	vm_ooffset_t mem_charged;
261 	int error;
262 
263 	/* Can't copy and clear. */
264 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
265 		return (EINVAL);
266 
267 	p1 = td->td_proc;
268 
269 	/*
270 	 * Here we don't create a new process, but we divorce
271 	 * certain parts of a process from itself.
272 	 */
273 	if ((flags & RFPROC) == 0)
274 		return (fork_norfproc(td, flags, procp));
275 
276 	/*
277 	 * XXX
278 	 * We did have single-threading code here
279 	 * however it proved un-needed and caused problems
280 	 */
281 
282 	mem_charged = 0;
283 	vm2 = NULL;
284 	if (pages == 0)
285 		pages = KSTACK_PAGES;
286 	/* Allocate new proc. */
287 	newproc = uma_zalloc(proc_zone, M_WAITOK);
288 	td2 = FIRST_THREAD_IN_PROC(newproc);
289 	if (td2 == NULL) {
290 		td2 = thread_alloc(pages);
291 		if (td2 == NULL) {
292 			error = ENOMEM;
293 			goto fail1;
294 		}
295 		proc_linkup(newproc, td2);
296 	} else {
297 		if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
298 			if (td2->td_kstack != 0)
299 				vm_thread_dispose(td2);
300 			if (!thread_alloc_stack(td2, pages)) {
301 				error = ENOMEM;
302 				goto fail1;
303 			}
304 		}
305 	}
306 
307 	if ((flags & RFMEM) == 0) {
308 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
309 		if (vm2 == NULL) {
310 			error = ENOMEM;
311 			goto fail1;
312 		}
313 		if (!swap_reserve(mem_charged)) {
314 			/*
315 			 * The swap reservation failed. The accounting
316 			 * from the entries of the copied vm2 will be
317 			 * substracted in vmspace_free(), so force the
318 			 * reservation there.
319 			 */
320 			swap_reserve_force(mem_charged);
321 			error = ENOMEM;
322 			goto fail1;
323 		}
324 	} else
325 		vm2 = NULL;
326 #ifdef MAC
327 	mac_proc_init(newproc);
328 #endif
329 	knlist_init_mtx(&newproc->p_klist, &newproc->p_mtx);
330 	STAILQ_INIT(&newproc->p_ktr);
331 
332 	/* We have to lock the process tree while we look for a pid. */
333 	sx_slock(&proctree_lock);
334 
335 	/*
336 	 * Although process entries are dynamically created, we still keep
337 	 * a global limit on the maximum number we will create.  Don't allow
338 	 * a nonprivileged user to use the last ten processes; don't let root
339 	 * exceed the limit. The variable nprocs is the current number of
340 	 * processes, maxproc is the limit.
341 	 */
342 	sx_xlock(&allproc_lock);
343 	if ((nprocs >= maxproc - 10 && priv_check_cred(td->td_ucred,
344 	    PRIV_MAXPROC, 0) != 0) || nprocs >= maxproc) {
345 		error = EAGAIN;
346 		goto fail;
347 	}
348 
349 	/*
350 	 * Increment the count of procs running with this uid. Don't allow
351 	 * a nonprivileged user to exceed their current limit.
352 	 *
353 	 * XXXRW: Can we avoid privilege here if it's not needed?
354 	 */
355 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
356 	if (error == 0)
357 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
358 	else {
359 		PROC_LOCK(p1);
360 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
361 		    lim_cur(p1, RLIMIT_NPROC));
362 		PROC_UNLOCK(p1);
363 	}
364 	if (!ok) {
365 		error = EAGAIN;
366 		goto fail;
367 	}
368 
369 	/*
370 	 * Increment the nprocs resource before blocking can occur.  There
371 	 * are hard-limits as to the number of processes that can run.
372 	 */
373 	nprocs++;
374 
375 	/*
376 	 * Find an unused process ID.  We remember a range of unused IDs
377 	 * ready to use (from lastpid+1 through pidchecked-1).
378 	 *
379 	 * If RFHIGHPID is set (used during system boot), do not allocate
380 	 * low-numbered pids.
381 	 */
382 	trypid = lastpid + 1;
383 	if (flags & RFHIGHPID) {
384 		if (trypid < 10)
385 			trypid = 10;
386 	} else {
387 		if (randompid)
388 			trypid += arc4random() % randompid;
389 	}
390 retry:
391 	/*
392 	 * If the process ID prototype has wrapped around,
393 	 * restart somewhat above 0, as the low-numbered procs
394 	 * tend to include daemons that don't exit.
395 	 */
396 	if (trypid >= PID_MAX) {
397 		trypid = trypid % PID_MAX;
398 		if (trypid < 100)
399 			trypid += 100;
400 		pidchecked = 0;
401 	}
402 	if (trypid >= pidchecked) {
403 		int doingzomb = 0;
404 
405 		pidchecked = PID_MAX;
406 		/*
407 		 * Scan the active and zombie procs to check whether this pid
408 		 * is in use.  Remember the lowest pid that's greater
409 		 * than trypid, so we can avoid checking for a while.
410 		 */
411 		p2 = LIST_FIRST(&allproc);
412 again:
413 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
414 			while (p2->p_pid == trypid ||
415 			    (p2->p_pgrp != NULL &&
416 			    (p2->p_pgrp->pg_id == trypid ||
417 			    (p2->p_session != NULL &&
418 			    p2->p_session->s_sid == trypid)))) {
419 				trypid++;
420 				if (trypid >= pidchecked)
421 					goto retry;
422 			}
423 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
424 				pidchecked = p2->p_pid;
425 			if (p2->p_pgrp != NULL) {
426 				if (p2->p_pgrp->pg_id > trypid &&
427 				    pidchecked > p2->p_pgrp->pg_id)
428 					pidchecked = p2->p_pgrp->pg_id;
429 				if (p2->p_session != NULL &&
430 				    p2->p_session->s_sid > trypid &&
431 				    pidchecked > p2->p_session->s_sid)
432 					pidchecked = p2->p_session->s_sid;
433 			}
434 		}
435 		if (!doingzomb) {
436 			doingzomb = 1;
437 			p2 = LIST_FIRST(&zombproc);
438 			goto again;
439 		}
440 	}
441 	sx_sunlock(&proctree_lock);
442 
443 	/*
444 	 * RFHIGHPID does not mess with the lastpid counter during boot.
445 	 */
446 	if (flags & RFHIGHPID)
447 		pidchecked = 0;
448 	else
449 		lastpid = trypid;
450 
451 	p2 = newproc;
452 	p2->p_state = PRS_NEW;		/* protect against others */
453 	p2->p_pid = trypid;
454 	/*
455 	 * Allow the scheduler to initialize the child.
456 	 */
457 	thread_lock(td);
458 	sched_fork(td, td2);
459 	thread_unlock(td);
460 	AUDIT_ARG_PID(p2->p_pid);
461 	LIST_INSERT_HEAD(&allproc, p2, p_list);
462 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
463 	tidhash_add(td2);
464 	PROC_LOCK(p2);
465 	PROC_LOCK(p1);
466 
467 	sx_xunlock(&allproc_lock);
468 
469 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
470 	    __rangeof(struct proc, p_startcopy, p_endcopy));
471 	pargs_hold(p2->p_args);
472 	PROC_UNLOCK(p1);
473 
474 	bzero(&p2->p_startzero,
475 	    __rangeof(struct proc, p_startzero, p_endzero));
476 
477 	p2->p_ucred = crhold(td->td_ucred);
478 
479 	/* Tell the prison that we exist. */
480 	prison_proc_hold(p2->p_ucred->cr_prison);
481 
482 	PROC_UNLOCK(p2);
483 
484 	/*
485 	 * Malloc things while we don't hold any locks.
486 	 */
487 	if (flags & RFSIGSHARE)
488 		newsigacts = NULL;
489 	else
490 		newsigacts = sigacts_alloc();
491 
492 	/*
493 	 * Copy filedesc.
494 	 */
495 	if (flags & RFCFDG) {
496 		fd = fdinit(p1->p_fd);
497 		fdtol = NULL;
498 	} else if (flags & RFFDG) {
499 		fd = fdcopy(p1->p_fd);
500 		fdtol = NULL;
501 	} else {
502 		fd = fdshare(p1->p_fd);
503 		if (p1->p_fdtol == NULL)
504 			p1->p_fdtol =
505 				filedesc_to_leader_alloc(NULL,
506 							 NULL,
507 							 p1->p_leader);
508 		if ((flags & RFTHREAD) != 0) {
509 			/*
510 			 * Shared file descriptor table and
511 			 * shared process leaders.
512 			 */
513 			fdtol = p1->p_fdtol;
514 			FILEDESC_XLOCK(p1->p_fd);
515 			fdtol->fdl_refcount++;
516 			FILEDESC_XUNLOCK(p1->p_fd);
517 		} else {
518 			/*
519 			 * Shared file descriptor table, and
520 			 * different process leaders
521 			 */
522 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
523 							 p1->p_fd,
524 							 p2);
525 		}
526 	}
527 	/*
528 	 * Make a proc table entry for the new process.
529 	 * Start by zeroing the section of proc that is zero-initialized,
530 	 * then copy the section that is copied directly from the parent.
531 	 */
532 
533 	PROC_LOCK(p2);
534 	PROC_LOCK(p1);
535 
536 	bzero(&td2->td_startzero,
537 	    __rangeof(struct thread, td_startzero, td_endzero));
538 
539 	bcopy(&td->td_startcopy, &td2->td_startcopy,
540 	    __rangeof(struct thread, td_startcopy, td_endcopy));
541 
542 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
543 	td2->td_sigstk = td->td_sigstk;
544 	td2->td_sigmask = td->td_sigmask;
545 	td2->td_flags = TDF_INMEM;
546 	td2->td_lend_user_pri = PRI_MAX;
547 
548 #ifdef VIMAGE
549 	td2->td_vnet = NULL;
550 	td2->td_vnet_lpush = NULL;
551 #endif
552 
553 	/*
554 	 * Duplicate sub-structures as needed.
555 	 * Increase reference counts on shared objects.
556 	 */
557 	p2->p_flag = P_INMEM;
558 	p2->p_swtick = ticks;
559 	if (p1->p_flag & P_PROFIL)
560 		startprofclock(p2);
561 	td2->td_ucred = crhold(p2->p_ucred);
562 
563 	if (flags & RFSIGSHARE) {
564 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
565 	} else {
566 		sigacts_copy(newsigacts, p1->p_sigacts);
567 		p2->p_sigacts = newsigacts;
568 	}
569 	if (flags & RFLINUXTHPN)
570 	        p2->p_sigparent = SIGUSR1;
571 	else
572 	        p2->p_sigparent = SIGCHLD;
573 
574 	p2->p_textvp = p1->p_textvp;
575 	p2->p_fd = fd;
576 	p2->p_fdtol = fdtol;
577 
578 	/*
579 	 * p_limit is copy-on-write.  Bump its refcount.
580 	 */
581 	lim_fork(p1, p2);
582 
583 	pstats_fork(p1->p_stats, p2->p_stats);
584 
585 	PROC_UNLOCK(p1);
586 	PROC_UNLOCK(p2);
587 
588 	/* Bump references to the text vnode (for procfs) */
589 	if (p2->p_textvp)
590 		vref(p2->p_textvp);
591 
592 	/*
593 	 * Set up linkage for kernel based threading.
594 	 */
595 	if ((flags & RFTHREAD) != 0) {
596 		mtx_lock(&ppeers_lock);
597 		p2->p_peers = p1->p_peers;
598 		p1->p_peers = p2;
599 		p2->p_leader = p1->p_leader;
600 		mtx_unlock(&ppeers_lock);
601 		PROC_LOCK(p1->p_leader);
602 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
603 			PROC_UNLOCK(p1->p_leader);
604 			/*
605 			 * The task leader is exiting, so process p1 is
606 			 * going to be killed shortly.  Since p1 obviously
607 			 * isn't dead yet, we know that the leader is either
608 			 * sending SIGKILL's to all the processes in this
609 			 * task or is sleeping waiting for all the peers to
610 			 * exit.  We let p1 complete the fork, but we need
611 			 * to go ahead and kill the new process p2 since
612 			 * the task leader may not get a chance to send
613 			 * SIGKILL to it.  We leave it on the list so that
614 			 * the task leader will wait for this new process
615 			 * to commit suicide.
616 			 */
617 			PROC_LOCK(p2);
618 			psignal(p2, SIGKILL);
619 			PROC_UNLOCK(p2);
620 		} else
621 			PROC_UNLOCK(p1->p_leader);
622 	} else {
623 		p2->p_peers = NULL;
624 		p2->p_leader = p2;
625 	}
626 
627 	sx_xlock(&proctree_lock);
628 	PGRP_LOCK(p1->p_pgrp);
629 	PROC_LOCK(p2);
630 	PROC_LOCK(p1);
631 
632 	/*
633 	 * Preserve some more flags in subprocess.  P_PROFIL has already
634 	 * been preserved.
635 	 */
636 	p2->p_flag |= p1->p_flag & P_SUGID;
637 	td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
638 	SESS_LOCK(p1->p_session);
639 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
640 		p2->p_flag |= P_CONTROLT;
641 	SESS_UNLOCK(p1->p_session);
642 	if (flags & RFPPWAIT)
643 		p2->p_flag |= P_PPWAIT;
644 
645 	p2->p_pgrp = p1->p_pgrp;
646 	LIST_INSERT_AFTER(p1, p2, p_pglist);
647 	PGRP_UNLOCK(p1->p_pgrp);
648 	LIST_INIT(&p2->p_children);
649 
650 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
651 
652 #ifdef KTRACE
653 	ktrprocfork(p1, p2);
654 #endif
655 
656 	/*
657 	 * If PF_FORK is set, the child process inherits the
658 	 * procfs ioctl flags from its parent.
659 	 */
660 	if (p1->p_pfsflags & PF_FORK) {
661 		p2->p_stops = p1->p_stops;
662 		p2->p_pfsflags = p1->p_pfsflags;
663 	}
664 
665 	/*
666 	 * This begins the section where we must prevent the parent
667 	 * from being swapped.
668 	 */
669 	_PHOLD(p1);
670 	PROC_UNLOCK(p1);
671 
672 	/*
673 	 * Attach the new process to its parent.
674 	 *
675 	 * If RFNOWAIT is set, the newly created process becomes a child
676 	 * of init.  This effectively disassociates the child from the
677 	 * parent.
678 	 */
679 	if (flags & RFNOWAIT)
680 		pptr = initproc;
681 	else
682 		pptr = p1;
683 	p2->p_pptr = pptr;
684 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
685 	sx_xunlock(&proctree_lock);
686 
687 	/* Inform accounting that we have forked. */
688 	p2->p_acflag = AFORK;
689 	PROC_UNLOCK(p2);
690 
691 	/*
692 	 * Finish creating the child process.  It will return via a different
693 	 * execution path later.  (ie: directly into user mode)
694 	 */
695 	vm_forkproc(td, p2, td2, vm2, flags);
696 
697 	if (flags == (RFFDG | RFPROC)) {
698 		PCPU_INC(cnt.v_forks);
699 		PCPU_ADD(cnt.v_forkpages, p2->p_vmspace->vm_dsize +
700 		    p2->p_vmspace->vm_ssize);
701 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
702 		PCPU_INC(cnt.v_vforks);
703 		PCPU_ADD(cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
704 		    p2->p_vmspace->vm_ssize);
705 	} else if (p1 == &proc0) {
706 		PCPU_INC(cnt.v_kthreads);
707 		PCPU_ADD(cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
708 		    p2->p_vmspace->vm_ssize);
709 	} else {
710 		PCPU_INC(cnt.v_rforks);
711 		PCPU_ADD(cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
712 		    p2->p_vmspace->vm_ssize);
713 	}
714 
715 	/*
716 	 * Both processes are set up, now check if any loadable modules want
717 	 * to adjust anything.
718 	 *   What if they have an error? XXX
719 	 */
720 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
721 
722 	/*
723 	 * Set the child start time and mark the process as being complete.
724 	 */
725 	microuptime(&p2->p_stats->p_start);
726 	PROC_SLOCK(p2);
727 	p2->p_state = PRS_NORMAL;
728 	PROC_SUNLOCK(p2);
729 #ifdef KDTRACE_HOOKS
730 	/*
731 	 * Tell the DTrace fasttrap provider about the new process
732 	 * if it has registered an interest. We have to do this only after
733 	 * p_state is PRS_NORMAL since the fasttrap module will use pfind()
734 	 * later on.
735 	 */
736 	if (dtrace_fasttrap_fork) {
737 		PROC_LOCK(p1);
738 		PROC_LOCK(p2);
739 		dtrace_fasttrap_fork(p1, p2);
740 		PROC_UNLOCK(p2);
741 		PROC_UNLOCK(p1);
742 	}
743 #endif
744 
745 	/*
746 	 * If RFSTOPPED not requested, make child runnable and add to
747 	 * run queue.
748 	 */
749 	if ((flags & RFSTOPPED) == 0) {
750 		thread_lock(td2);
751 		TD_SET_CAN_RUN(td2);
752 		sched_add(td2, SRQ_BORING);
753 		thread_unlock(td2);
754 	}
755 
756 	/*
757 	 * Now can be swapped.
758 	 */
759 	PROC_LOCK(p1);
760 	_PRELE(p1);
761 	PROC_UNLOCK(p1);
762 
763 	/*
764 	 * Tell any interested parties about the new process.
765 	 */
766 	knote_fork(&p1->p_klist, p2->p_pid);
767 	SDT_PROBE(proc, kernel, , create, p2, p1, flags, 0, 0);
768 
769 	/*
770 	 * Preserve synchronization semantics of vfork.  If waiting for
771 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
772 	 * proc (in case of exit).
773 	 */
774 	PROC_LOCK(p2);
775 	while (p2->p_flag & P_PPWAIT)
776 		cv_wait(&p2->p_pwait, &p2->p_mtx);
777 	PROC_UNLOCK(p2);
778 
779 	/*
780 	 * Return child proc pointer to parent.
781 	 */
782 	*procp = p2;
783 	return (0);
784 fail:
785 	sx_sunlock(&proctree_lock);
786 	if (ppsratecheck(&lastfail, &curfail, 1))
787 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
788 		    td->td_ucred->cr_ruid);
789 	sx_xunlock(&allproc_lock);
790 #ifdef MAC
791 	mac_proc_destroy(newproc);
792 #endif
793 fail1:
794 	if (vm2 != NULL)
795 		vmspace_free(vm2);
796 	uma_zfree(proc_zone, newproc);
797 	pause("fork", hz / 2);
798 	return (error);
799 }
800 
801 /*
802  * Handle the return of a child process from fork1().  This function
803  * is called from the MD fork_trampoline() entry point.
804  */
805 void
806 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
807     struct trapframe *frame)
808 {
809 	struct proc *p;
810 	struct thread *td;
811 	struct thread *dtd;
812 
813 	td = curthread;
814 	p = td->td_proc;
815 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
816 
817 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
818 		td, td->td_sched, p->p_pid, td->td_name);
819 
820 	sched_fork_exit(td);
821 	/*
822 	* Processes normally resume in mi_switch() after being
823 	* cpu_switch()'ed to, but when children start up they arrive here
824 	* instead, so we must do much the same things as mi_switch() would.
825 	*/
826 	if ((dtd = PCPU_GET(deadthread))) {
827 		PCPU_SET(deadthread, NULL);
828 		thread_stash(dtd);
829 	}
830 	thread_unlock(td);
831 
832 	/*
833 	 * cpu_set_fork_handler intercepts this function call to
834 	 * have this call a non-return function to stay in kernel mode.
835 	 * initproc has its own fork handler, but it does return.
836 	 */
837 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
838 	callout(arg, frame);
839 
840 	/*
841 	 * Check if a kernel thread misbehaved and returned from its main
842 	 * function.
843 	 */
844 	if (p->p_flag & P_KTHREAD) {
845 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
846 		    td->td_name, p->p_pid);
847 		kproc_exit(0);
848 	}
849 	mtx_assert(&Giant, MA_NOTOWNED);
850 
851 	EVENTHANDLER_INVOKE(schedtail, p);
852 }
853 
854 /*
855  * Simplified back end of syscall(), used when returning from fork()
856  * directly into user mode.  Giant is not held on entry, and must not
857  * be held on return.  This function is passed in to fork_exit() as the
858  * first parameter and is called when returning to a new userland process.
859  */
860 void
861 fork_return(struct thread *td, struct trapframe *frame)
862 {
863 
864 	userret(td, frame);
865 #ifdef KTRACE
866 	if (KTRPOINT(td, KTR_SYSRET))
867 		ktrsysret(SYS_fork, 0, 0);
868 #endif
869 	mtx_assert(&Giant, MA_NOTOWNED);
870 }
871