xref: /freebsd/sys/kern/kern_fork.c (revision 729362425c09cf6b362366aabc6fb547eee8035a)
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 	if (p1->p_flag & P_THREADED) {
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 
297 	/*
298 	 * Although process entries are dynamically created, we still keep
299 	 * a global limit on the maximum number we will create.  Don't allow
300 	 * a nonprivileged user to use the last ten processes; don't let root
301 	 * exceed the limit. The variable nprocs is the current number of
302 	 * processes, maxproc is the limit.
303 	 */
304 	sx_xlock(&allproc_lock);
305 	uid = td->td_ucred->cr_ruid;
306 	if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) {
307 		error = EAGAIN;
308 		goto fail;
309 	}
310 
311 	/*
312 	 * Increment the count of procs running with this uid. Don't allow
313 	 * a nonprivileged user to exceed their current limit.
314 	 */
315 	PROC_LOCK(p1);
316 	ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
317 		(uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
318 	PROC_UNLOCK(p1);
319 	if (!ok) {
320 		error = EAGAIN;
321 		goto fail;
322 	}
323 
324 	/*
325 	 * Increment the nprocs resource before blocking can occur.  There
326 	 * are hard-limits as to the number of processes that can run.
327 	 */
328 	nprocs++;
329 
330 	/*
331 	 * Find an unused process ID.  We remember a range of unused IDs
332 	 * ready to use (from lastpid+1 through pidchecked-1).
333 	 *
334 	 * If RFHIGHPID is set (used during system boot), do not allocate
335 	 * low-numbered pids.
336 	 */
337 	trypid = lastpid + 1;
338 	if (flags & RFHIGHPID) {
339 		if (trypid < 10) {
340 			trypid = 10;
341 		}
342 	} else {
343 		if (randompid)
344 			trypid += arc4random() % randompid;
345 	}
346 retry:
347 	/*
348 	 * If the process ID prototype has wrapped around,
349 	 * restart somewhat above 0, as the low-numbered procs
350 	 * tend to include daemons that don't exit.
351 	 */
352 	if (trypid >= PID_MAX) {
353 		trypid = trypid % PID_MAX;
354 		if (trypid < 100)
355 			trypid += 100;
356 		pidchecked = 0;
357 	}
358 	if (trypid >= pidchecked) {
359 		int doingzomb = 0;
360 
361 		pidchecked = PID_MAX;
362 		/*
363 		 * Scan the active and zombie procs to check whether this pid
364 		 * is in use.  Remember the lowest pid that's greater
365 		 * than trypid, so we can avoid checking for a while.
366 		 */
367 		p2 = LIST_FIRST(&allproc);
368 again:
369 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
370 			PROC_LOCK(p2);
371 			while (p2->p_pid == trypid ||
372 			    p2->p_pgrp->pg_id == trypid ||
373 			    p2->p_session->s_sid == trypid) {
374 				trypid++;
375 				if (trypid >= pidchecked) {
376 					PROC_UNLOCK(p2);
377 					goto retry;
378 				}
379 			}
380 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
381 				pidchecked = p2->p_pid;
382 			if (p2->p_pgrp->pg_id > trypid &&
383 			    pidchecked > p2->p_pgrp->pg_id)
384 				pidchecked = p2->p_pgrp->pg_id;
385 			if (p2->p_session->s_sid > trypid &&
386 			    pidchecked > p2->p_session->s_sid)
387 				pidchecked = p2->p_session->s_sid;
388 			PROC_UNLOCK(p2);
389 		}
390 		if (!doingzomb) {
391 			doingzomb = 1;
392 			p2 = LIST_FIRST(&zombproc);
393 			goto again;
394 		}
395 	}
396 
397 	/*
398 	 * RFHIGHPID does not mess with the lastpid counter during boot.
399 	 */
400 	if (flags & RFHIGHPID)
401 		pidchecked = 0;
402 	else
403 		lastpid = trypid;
404 
405 	p2 = newproc;
406 	p2->p_state = PRS_NEW;		/* protect against others */
407 	p2->p_pid = trypid;
408 	LIST_INSERT_HEAD(&allproc, p2, p_list);
409 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
410 	sx_xunlock(&allproc_lock);
411 
412 	/*
413 	 * Malloc things while we don't hold any locks.
414 	 */
415 	if (flags & RFSIGSHARE) {
416 		MALLOC(newsigacts, struct sigacts *,
417 		    sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
418 		newprocsig = NULL;
419 	} else {
420 		newsigacts = NULL;
421 		MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
422 		    M_SUBPROC, M_WAITOK);
423 	}
424 
425 	/*
426 	 * Copy filedesc.
427 	 * XXX: This is busted.  fd*() need to not take proc
428 	 * arguments or something.
429 	 */
430 	if (flags & RFCFDG)
431 		fd = fdinit(td->td_proc->p_fd);
432 	else if (flags & RFFDG) {
433 		FILEDESC_LOCK(p1->p_fd);
434 		fd = fdcopy(td->td_proc->p_fd);
435 		FILEDESC_UNLOCK(p1->p_fd);
436 	} else
437 		fd = fdshare(p1->p_fd);
438 
439 	/*
440 	 * Make a proc table entry for the new process.
441 	 * Start by zeroing the section of proc that is zero-initialized,
442 	 * then copy the section that is copied directly from the parent.
443 	 */
444 	td2 = FIRST_THREAD_IN_PROC(p2);
445 	kg2 = FIRST_KSEGRP_IN_PROC(p2);
446 	ke2 = FIRST_KSE_IN_KSEGRP(kg2);
447 
448 	/* Allocate and switch to an alternate kstack if specified */
449 	if (pages != 0)
450 		pmap_new_altkstack(td2, pages);
451 
452 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
453 
454 	bzero(&p2->p_startzero,
455 	    (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
456 	bzero(&ke2->ke_startzero,
457 	    (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
458 	bzero(&td2->td_startzero,
459 	    (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
460 	bzero(&kg2->kg_startzero,
461 	    (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
462 
463 	mtx_init(&p2->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
464 	PROC_LOCK(p2);
465 	PROC_LOCK(p1);
466 
467 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
468 	    (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
469 	bcopy(&td->td_startcopy, &td2->td_startcopy,
470 	    (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
471 	bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
472 	    (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
473 #undef RANGEOF
474 
475 	/* Set up the thread as an active thread (as if runnable). */
476 	ke2->ke_state = KES_THREAD;
477 	ke2->ke_thread = td2;
478 	td2->td_kse = ke2;
479 
480 	/*
481 	 * Duplicate sub-structures as needed.
482 	 * Increase reference counts on shared objects.
483 	 * The p_stats and p_sigacts substructs are set in vm_forkproc.
484 	 */
485 	p2->p_flag = 0;
486 	mtx_lock_spin(&sched_lock);
487 	p2->p_sflag = PS_INMEM;
488 	if (p1->p_sflag & PS_PROFIL)
489 		startprofclock(p2);
490 	/*
491 	 * Allow the scheduler to adjust the priority of the child and
492 	 * parent while we hold the sched_lock.
493 	 */
494 	sched_fork(td->td_ksegrp, kg2);
495 
496 	mtx_unlock_spin(&sched_lock);
497 	p2->p_ucred = crhold(td->td_ucred);
498 	td2->td_ucred = crhold(p2->p_ucred);	/* XXXKSE */
499 
500 	pargs_hold(p2->p_args);
501 
502 	if (flags & RFSIGSHARE) {
503 		p2->p_procsig = p1->p_procsig;
504 		p2->p_procsig->ps_refcnt++;
505 		if (p1->p_sigacts == &p1->p_uarea->u_sigacts) {
506 			/*
507 			 * Set p_sigacts to the new shared structure.
508 			 * Note that this is updating p1->p_sigacts at the
509 			 * same time, since p_sigacts is just a pointer to
510 			 * the shared p_procsig->ps_sigacts.
511 			 */
512 			p2->p_sigacts  = newsigacts;
513 			newsigacts = NULL;
514 			*p2->p_sigacts = p1->p_uarea->u_sigacts;
515 		}
516 	} else {
517 		p2->p_procsig = newprocsig;
518 		newprocsig = NULL;
519 		bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
520 		p2->p_procsig->ps_refcnt = 1;
521 		p2->p_sigacts = NULL;	/* finished in vm_forkproc() */
522 	}
523 	if (flags & RFLINUXTHPN)
524 	        p2->p_sigparent = SIGUSR1;
525 	else
526 	        p2->p_sigparent = SIGCHLD;
527 
528 	/* Bump references to the text vnode (for procfs) */
529 	p2->p_textvp = p1->p_textvp;
530 	if (p2->p_textvp)
531 		VREF(p2->p_textvp);
532 	p2->p_fd = fd;
533 	PROC_UNLOCK(p1);
534 	PROC_UNLOCK(p2);
535 
536 	/*
537 	 * p_limit is copy-on-write, bump refcnt,
538 	 */
539 	p2->p_limit = p1->p_limit;
540 	p2->p_limit->p_refcnt++;
541 
542 	/*
543 	 * Setup linkage for kernel based threading
544 	 */
545 	if((flags & RFTHREAD) != 0) {
546 		mtx_lock(&ppeers_lock);
547 		p2->p_peers = p1->p_peers;
548 		p1->p_peers = p2;
549 		p2->p_leader = p1->p_leader;
550 		mtx_unlock(&ppeers_lock);
551 		PROC_LOCK(p1->p_leader);
552 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
553 			PROC_UNLOCK(p1->p_leader);
554 			/*
555 			 * The task leader is exiting, so process p1 is
556 			 * going to be killed shortly.  Since p1 obviously
557 			 * isn't dead yet, we know that the leader is either
558 			 * sending SIGKILL's to all the processes in this
559 			 * task or is sleeping waiting for all the peers to
560 			 * exit.  We let p1 complete the fork, but we need
561 			 * to go ahead and kill the new process p2 since
562 			 * the task leader may not get a chance to send
563 			 * SIGKILL to it.  We leave it on the list so that
564 			 * the task leader will wait for this new process
565 			 * to commit suicide.
566 			 */
567 			PROC_LOCK(p2);
568 			psignal(p2, SIGKILL);
569 			PROC_UNLOCK(p2);
570 		} else
571 			PROC_UNLOCK(p1->p_leader);
572 	} else {
573 		p2->p_peers = NULL;
574 		p2->p_leader = p2;
575 	}
576 
577 	sx_xlock(&proctree_lock);
578 	PGRP_LOCK(p1->p_pgrp);
579 	PROC_LOCK(p2);
580 	PROC_LOCK(p1);
581 
582 	/*
583 	 * Preserve some more flags in subprocess.  PS_PROFIL has already
584 	 * been preserved.
585 	 */
586 	p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
587 	SESS_LOCK(p1->p_session);
588 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
589 		p2->p_flag |= P_CONTROLT;
590 	SESS_UNLOCK(p1->p_session);
591 	if (flags & RFPPWAIT)
592 		p2->p_flag |= P_PPWAIT;
593 
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, 0);
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 	PROC_UNLOCK(p2);
648 	sx_xunlock(&proctree_lock);
649 
650 	KASSERT(newprocsig == NULL, ("unused newprocsig"));
651 	if (newsigacts != NULL)
652 		FREE(newsigacts, M_SUBPROC);
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 	microtime(&(p2->p_stats->p_start));
689 	p2->p_acflag = AFORK;
690 	if ((flags & RFSTOPPED) == 0) {
691 		mtx_lock_spin(&sched_lock);
692 		p2->p_state = PRS_NORMAL;
693 		TD_SET_CAN_RUN(td2);
694 		setrunqueue(td2);
695 		mtx_unlock_spin(&sched_lock);
696 	}
697 
698 	/*
699 	 * Now can be swapped.
700 	 */
701 	PROC_LOCK(p1);
702 	_PRELE(p1);
703 
704 	/*
705 	 * tell any interested parties about the new process
706 	 */
707 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
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_THREADED) {
724 		PROC_LOCK(p1);
725 		thread_single_end();
726 		PROC_UNLOCK(p1);
727 	}
728 
729 	/*
730 	 * Return child proc pointer to parent.
731 	 */
732 	*procp = p2;
733 	return (0);
734 fail:
735 	sx_xunlock(&allproc_lock);
736 	uma_zfree(proc_zone, newproc);
737 	if (p1->p_flag & P_THREADED) {
738 		PROC_LOCK(p1);
739 		thread_single_end();
740 		PROC_UNLOCK(p1);
741 	}
742 	tsleep(&forksleep, PUSER, "fork", hz / 2);
743 	return (error);
744 }
745 
746 /*
747  * Handle the return of a child process from fork1().  This function
748  * is called from the MD fork_trampoline() entry point.
749  */
750 void
751 fork_exit(callout, arg, frame)
752 	void (*callout)(void *, struct trapframe *);
753 	void *arg;
754 	struct trapframe *frame;
755 {
756 	struct thread *td;
757 	struct proc *p;
758 
759 	if ((td = PCPU_GET(deadthread))) {
760 		PCPU_SET(deadthread, NULL);
761 		thread_stash(td);
762 	}
763 	td = curthread;
764 	p = td->td_proc;
765 	td->td_kse->ke_oncpu = PCPU_GET(cpuid);
766 	p->p_state = PRS_NORMAL;
767 	/*
768 	 * Finish setting up thread glue.  We need to initialize
769 	 * the thread into a td_critnest=1 state.  Some platforms
770 	 * may have already partially or fully initialized td_critnest
771 	 * and/or td_md.md_savecrit (when applciable).
772 	 *
773 	 * see <arch>/<arch>/critical.c
774 	 */
775 	sched_lock.mtx_lock = (uintptr_t)td;
776 	sched_lock.mtx_recurse = 0;
777 	cpu_critical_fork_exit();
778 	CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
779 	    p->p_comm);
780 	if (PCPU_GET(switchtime.sec) == 0)
781 		binuptime(PCPU_PTR(switchtime));
782 	PCPU_SET(switchticks, ticks);
783 	mtx_unlock_spin(&sched_lock);
784 
785 	/*
786 	 * cpu_set_fork_handler intercepts this function call to
787          * have this call a non-return function to stay in kernel mode.
788          * initproc has its own fork handler, but it does return.
789          */
790 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
791 	callout(arg, frame);
792 
793 	/*
794 	 * Check if a kernel thread misbehaved and returned from its main
795 	 * function.
796 	 */
797 	PROC_LOCK(p);
798 	if (p->p_flag & P_KTHREAD) {
799 		PROC_UNLOCK(p);
800 		mtx_lock(&Giant);
801 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
802 		    p->p_comm, p->p_pid);
803 		kthread_exit(0);
804 	}
805 	PROC_UNLOCK(p);
806 #ifdef DIAGNOSTIC
807 	cred_free_thread(td);
808 #endif
809 	mtx_assert(&Giant, MA_NOTOWNED);
810 }
811 
812 /*
813  * Simplified back end of syscall(), used when returning from fork()
814  * directly into user mode.  Giant is not held on entry, and must not
815  * be held on return.  This function is passed in to fork_exit() as the
816  * first parameter and is called when returning to a new userland process.
817  */
818 void
819 fork_return(td, frame)
820 	struct thread *td;
821 	struct trapframe *frame;
822 {
823 
824 	userret(td, frame, 0);
825 #ifdef KTRACE
826 	if (KTRPOINT(td, KTR_SYSRET))
827 		ktrsysret(SYS_fork, 0, 0);
828 #endif
829 	mtx_assert(&Giant, MA_NOTOWNED);
830 }
831