xref: /freebsd/sys/kern/kern_fork.c (revision f6a4109212fd8fbabc731f07b2dd5c7e07fbec33)
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) ? lim_cur(p1, RLIMIT_NPROC) : 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 
532 	/*
533 	 * p_limit is copy-on-write, bump refcnt,
534 	 */
535 	p2->p_limit = lim_hold(p1->p_limit);
536 	PROC_UNLOCK(p1);
537 	PROC_UNLOCK(p2);
538 
539 	/*
540 	 * Setup linkage for kernel based threading
541 	 */
542 	if((flags & RFTHREAD) != 0) {
543 		mtx_lock(&ppeers_lock);
544 		p2->p_peers = p1->p_peers;
545 		p1->p_peers = p2;
546 		p2->p_leader = p1->p_leader;
547 		mtx_unlock(&ppeers_lock);
548 		PROC_LOCK(p1->p_leader);
549 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
550 			PROC_UNLOCK(p1->p_leader);
551 			/*
552 			 * The task leader is exiting, so process p1 is
553 			 * going to be killed shortly.  Since p1 obviously
554 			 * isn't dead yet, we know that the leader is either
555 			 * sending SIGKILL's to all the processes in this
556 			 * task or is sleeping waiting for all the peers to
557 			 * exit.  We let p1 complete the fork, but we need
558 			 * to go ahead and kill the new process p2 since
559 			 * the task leader may not get a chance to send
560 			 * SIGKILL to it.  We leave it on the list so that
561 			 * the task leader will wait for this new process
562 			 * to commit suicide.
563 			 */
564 			PROC_LOCK(p2);
565 			psignal(p2, SIGKILL);
566 			PROC_UNLOCK(p2);
567 		} else
568 			PROC_UNLOCK(p1->p_leader);
569 	} else {
570 		p2->p_peers = NULL;
571 		p2->p_leader = p2;
572 	}
573 
574 	sx_xlock(&proctree_lock);
575 	PGRP_LOCK(p1->p_pgrp);
576 	PROC_LOCK(p2);
577 	PROC_LOCK(p1);
578 
579 	/*
580 	 * Preserve some more flags in subprocess.  P_PROFIL has already
581 	 * been preserved.
582 	 */
583 	p2->p_flag |= p1->p_flag & P_SUGID;
584 	td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
585 	SESS_LOCK(p1->p_session);
586 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
587 		p2->p_flag |= P_CONTROLT;
588 	SESS_UNLOCK(p1->p_session);
589 	if (flags & RFPPWAIT)
590 		p2->p_flag |= P_PPWAIT;
591 
592 	p2->p_pgrp = p1->p_pgrp;
593 	LIST_INSERT_AFTER(p1, p2, p_pglist);
594 	PGRP_UNLOCK(p1->p_pgrp);
595 	LIST_INIT(&p2->p_children);
596 
597 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
598 
599 #ifdef KTRACE
600 	/*
601 	 * Copy traceflag and tracefile if enabled.
602 	 */
603 	mtx_lock(&ktrace_mtx);
604 	KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
605 	if (p1->p_traceflag & KTRFAC_INHERIT) {
606 		p2->p_traceflag = p1->p_traceflag;
607 		if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
608 			VREF(p2->p_tracevp);
609 			KASSERT(p1->p_tracecred != NULL,
610 			    ("ktrace vnode with no cred"));
611 			p2->p_tracecred = crhold(p1->p_tracecred);
612 		}
613 	}
614 	mtx_unlock(&ktrace_mtx);
615 #endif
616 
617 	/*
618 	 * If PF_FORK is set, the child process inherits the
619 	 * procfs ioctl flags from its parent.
620 	 */
621 	if (p1->p_pfsflags & PF_FORK) {
622 		p2->p_stops = p1->p_stops;
623 		p2->p_pfsflags = p1->p_pfsflags;
624 	}
625 
626 	/*
627 	 * This begins the section where we must prevent the parent
628 	 * from being swapped.
629 	 */
630 	_PHOLD(p1);
631 	PROC_UNLOCK(p1);
632 
633 	/*
634 	 * Attach the new process to its parent.
635 	 *
636 	 * If RFNOWAIT is set, the newly created process becomes a child
637 	 * of init.  This effectively disassociates the child from the
638 	 * parent.
639 	 */
640 	if (flags & RFNOWAIT)
641 		pptr = initproc;
642 	else
643 		pptr = p1;
644 	p2->p_pptr = pptr;
645 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
646 	sx_xunlock(&proctree_lock);
647 
648 	/* Inform accounting that we have forked. */
649 	p2->p_acflag = AFORK;
650 	PROC_UNLOCK(p2);
651 
652 	/*
653 	 * Finish creating the child process.  It will return via a different
654 	 * execution path later.  (ie: directly into user mode)
655 	 */
656 	vm_forkproc(td, p2, td2, flags);
657 
658 	if (flags == (RFFDG | RFPROC)) {
659 		cnt.v_forks++;
660 		cnt.v_forkpages += p2->p_vmspace->vm_dsize +
661 		    p2->p_vmspace->vm_ssize;
662 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
663 		cnt.v_vforks++;
664 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize +
665 		    p2->p_vmspace->vm_ssize;
666 	} else if (p1 == &proc0) {
667 		cnt.v_kthreads++;
668 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize +
669 		    p2->p_vmspace->vm_ssize;
670 	} else {
671 		cnt.v_rforks++;
672 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize +
673 		    p2->p_vmspace->vm_ssize;
674 	}
675 
676 	/*
677 	 * Both processes are set up, now check if any loadable modules want
678 	 * to adjust anything.
679 	 *   What if they have an error? XXX
680 	 */
681 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
682 
683 	/*
684 	 * Set the child start time and mark the process as being complete.
685 	 */
686 	microuptime(&p2->p_stats->p_start);
687 	mtx_lock_spin(&sched_lock);
688 	p2->p_state = PRS_NORMAL;
689 
690 	/*
691 	 * If RFSTOPPED not requested, make child runnable and add to
692 	 * run queue.
693 	 */
694 	if ((flags & RFSTOPPED) == 0) {
695 		TD_SET_CAN_RUN(td2);
696 		setrunqueue(td2);
697 	}
698 	mtx_unlock_spin(&sched_lock);
699 
700 	/*
701 	 * Now can be swapped.
702 	 */
703 	PROC_LOCK(p1);
704 	_PRELE(p1);
705 
706 	/*
707 	 * Tell any interested parties about the new process.
708 	 */
709 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
710 
711 	PROC_UNLOCK(p1);
712 
713 	/*
714 	 * Preserve synchronization semantics of vfork.  If waiting for
715 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
716 	 * proc (in case of exit).
717 	 */
718 	PROC_LOCK(p2);
719 	while (p2->p_flag & P_PPWAIT)
720 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
721 	PROC_UNLOCK(p2);
722 
723 	/*
724 	 * If other threads are waiting, let them continue now
725 	 */
726 	if (p1->p_flag & P_SA) {
727 		PROC_LOCK(p1);
728 		thread_single_end();
729 		PROC_UNLOCK(p1);
730 	}
731 
732 	/*
733 	 * Return child proc pointer to parent.
734 	 */
735 	mtx_unlock(&Giant);
736 	*procp = p2;
737 	return (0);
738 fail:
739 	if (ppsratecheck(&lastfail, &curfail, 1))
740 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
741 			uid);
742 	sx_xunlock(&allproc_lock);
743 #ifdef MAC
744 	mac_destroy_proc(newproc);
745 #endif
746 	uma_zfree(proc_zone, newproc);
747 	if (p1->p_flag & P_SA) {
748 		PROC_LOCK(p1);
749 		thread_single_end();
750 		PROC_UNLOCK(p1);
751 	}
752 	tsleep(&forksleep, PUSER, "fork", hz / 2);
753 	mtx_unlock(&Giant);
754 	return (error);
755 }
756 
757 /*
758  * Handle the return of a child process from fork1().  This function
759  * is called from the MD fork_trampoline() entry point.
760  */
761 void
762 fork_exit(callout, arg, frame)
763 	void (*callout)(void *, struct trapframe *);
764 	void *arg;
765 	struct trapframe *frame;
766 {
767 	struct proc *p;
768 	struct thread *td;
769 
770 	/*
771 	 * Processes normally resume in mi_switch() after being
772 	 * cpu_switch()'ed to, but when children start up they arrive here
773 	 * instead, so we must do much the same things as mi_switch() would.
774 	 */
775 
776 	if ((td = PCPU_GET(deadthread))) {
777 		PCPU_SET(deadthread, NULL);
778 		thread_stash(td);
779 	}
780 	td = curthread;
781 	p = td->td_proc;
782 	td->td_oncpu = PCPU_GET(cpuid);
783 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
784 
785 	/*
786 	 * Finish setting up thread glue so that it begins execution in a
787 	 * non-nested critical section with sched_lock held but not recursed.
788 	 */
789 	sched_lock.mtx_lock = (uintptr_t)td;
790 	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
791 	cpu_critical_fork_exit();
792 	CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
793 	    p->p_comm);
794 	mtx_unlock_spin(&sched_lock);
795 
796 	/*
797 	 * cpu_set_fork_handler intercepts this function call to
798 	 * have this call a non-return function to stay in kernel mode.
799 	 * initproc has its own fork handler, but it does return.
800 	 */
801 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
802 	callout(arg, frame);
803 
804 	/*
805 	 * Check if a kernel thread misbehaved and returned from its main
806 	 * function.
807 	 */
808 	PROC_LOCK(p);
809 	if (p->p_flag & P_KTHREAD) {
810 		PROC_UNLOCK(p);
811 		mtx_lock(&Giant);
812 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
813 		    p->p_comm, p->p_pid);
814 		kthread_exit(0);
815 	}
816 	PROC_UNLOCK(p);
817 #ifdef DIAGNOSTIC
818 	cred_free_thread(td);
819 #endif
820 	mtx_assert(&Giant, MA_NOTOWNED);
821 }
822 
823 /*
824  * Simplified back end of syscall(), used when returning from fork()
825  * directly into user mode.  Giant is not held on entry, and must not
826  * be held on return.  This function is passed in to fork_exit() as the
827  * first parameter and is called when returning to a new userland process.
828  */
829 void
830 fork_return(td, frame)
831 	struct thread *td;
832 	struct trapframe *frame;
833 {
834 
835 	userret(td, frame, 0);
836 #ifdef KTRACE
837 	if (KTRPOINT(td, KTR_SYSRET))
838 		ktrsysret(SYS_fork, 0, 0);
839 #endif
840 	mtx_assert(&Giant, MA_NOTOWNED);
841 }
842