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