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