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