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