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