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