xref: /freebsd/sys/kern/kern_fork.c (revision bd78cece5df2063d2e852bd6c895e05385eea931)
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 	/* mask kernel only flags out of the user flags */
164 	mtx_lock(&Giant);
165 	error = fork1(td, uap->flags & ~RFKERNELONLY, &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 
245 	GIANT_REQUIRED;
246 
247 	/* Can't copy and clear */
248 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
249 		return (EINVAL);
250 
251 	/*
252 	 * Here we don't create a new process, but we divorce
253 	 * certain parts of a process from itself.
254 	 */
255 	if ((flags & RFPROC) == 0) {
256 		vm_forkproc(td, 0, flags);
257 
258 		/*
259 		 * Close all file descriptors.
260 		 */
261 		if (flags & RFCFDG) {
262 			struct filedesc *fdtmp;
263 			fdtmp = fdinit(td);	/* XXXKSE */
264 			PROC_LOCK(p1);
265 			fdfree(td);		/* XXXKSE */
266 			p1->p_fd = fdtmp;
267 			PROC_UNLOCK(p1);
268 		}
269 
270 		/*
271 		 * Unshare file descriptors (from parent.)
272 		 */
273 		if (flags & RFFDG) {
274 			if (p1->p_fd->fd_refcnt > 1) {
275 				struct filedesc *newfd;
276 				newfd = fdcopy(td);
277 				PROC_LOCK(p1);
278 				fdfree(td);
279 				p1->p_fd = newfd;
280 				PROC_UNLOCK(p1);
281 			}
282 		}
283 		*procp = NULL;
284 		return (0);
285 	}
286 
287 	/*
288 	 * Although process entries are dynamically created, we still keep
289 	 * a global limit on the maximum number we will create.  Don't allow
290 	 * a nonprivileged user to use the last process; don't let root
291 	 * exceed the limit. The variable nprocs is the current number of
292 	 * processes, maxproc is the limit.
293 	 */
294 	uid = p1->p_ucred->cr_ruid;
295 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
296 		tablefull("proc");
297 		return (EAGAIN);
298 	}
299 	/*
300 	 * Increment the nprocs resource before blocking can occur.  There
301 	 * are hard-limits as to the number of processes that can run.
302 	 */
303 	nprocs++;
304 
305 	/*
306 	 * Increment the count of procs running with this uid. Don't allow
307 	 * a nonprivileged user to exceed their current limit.
308 	 */
309 	ok = chgproccnt(p1->p_ucred->cr_ruidinfo, 1,
310 		(uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
311 	if (!ok) {
312 		/*
313 		 * Back out the process count
314 		 */
315 		nprocs--;
316 		return (EAGAIN);
317 	}
318 
319 	/* Allocate new proc. */
320 	newproc = zalloc(proc_zone);
321 
322 	/*
323 	 * Setup linkage for kernel based threading
324 	 */
325 	if((flags & RFTHREAD) != 0) {
326 		newproc->p_peers = p1->p_peers;
327 		p1->p_peers = newproc;
328 		newproc->p_leader = p1->p_leader;
329 	} else {
330 		newproc->p_peers = NULL;
331 		newproc->p_leader = newproc;
332 	}
333 
334 	newproc->p_vmspace = NULL;
335 
336 	/*
337 	 * Find an unused process ID.  We remember a range of unused IDs
338 	 * ready to use (from lastpid+1 through pidchecked-1).
339 	 *
340 	 * If RFHIGHPID is set (used during system boot), do not allocate
341 	 * low-numbered pids.
342 	 */
343 	sx_xlock(&allproc_lock);
344 	trypid = lastpid + 1;
345 	if (flags & RFHIGHPID) {
346 		if (trypid < 10) {
347 			trypid = 10;
348 		}
349 	} else {
350 		if (randompid)
351 			trypid += arc4random() % randompid;
352 	}
353 retry:
354 	/*
355 	 * If the process ID prototype has wrapped around,
356 	 * restart somewhat above 0, as the low-numbered procs
357 	 * tend to include daemons that don't exit.
358 	 */
359 	if (trypid >= PID_MAX) {
360 		trypid = trypid % PID_MAX;
361 		if (trypid < 100)
362 			trypid += 100;
363 		pidchecked = 0;
364 	}
365 	if (trypid >= pidchecked) {
366 		int doingzomb = 0;
367 
368 		pidchecked = PID_MAX;
369 		/*
370 		 * Scan the active and zombie procs to check whether this pid
371 		 * is in use.  Remember the lowest pid that's greater
372 		 * than trypid, so we can avoid checking for a while.
373 		 */
374 		p2 = LIST_FIRST(&allproc);
375 again:
376 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
377 			while (p2->p_pid == trypid ||
378 			    p2->p_pgrp->pg_id == trypid ||
379 			    p2->p_session->s_sid == trypid) {
380 				trypid++;
381 				if (trypid >= pidchecked)
382 					goto retry;
383 			}
384 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
385 				pidchecked = p2->p_pid;
386 			if (p2->p_pgrp->pg_id > trypid &&
387 			    pidchecked > p2->p_pgrp->pg_id)
388 				pidchecked = p2->p_pgrp->pg_id;
389 			if (p2->p_session->s_sid > trypid &&
390 			    pidchecked > p2->p_session->s_sid)
391 				pidchecked = p2->p_session->s_sid;
392 		}
393 		if (!doingzomb) {
394 			doingzomb = 1;
395 			p2 = LIST_FIRST(&zombproc);
396 			goto again;
397 		}
398 	}
399 
400 	/*
401 	 * RFHIGHPID does not mess with the lastpid counter during boot.
402 	 */
403 	if (flags & RFHIGHPID)
404 		pidchecked = 0;
405 	else
406 		lastpid = trypid;
407 
408 	p2 = newproc;
409 	p2->p_stat = SIDL;			/* protect against others */
410 	p2->p_pid = trypid;
411 	LIST_INSERT_HEAD(&allproc, p2, p_list);
412 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
413 	sx_xunlock(&allproc_lock);
414 
415 	/*
416 	 * Make a proc table entry for the new process.
417 	 * Start by zeroing the section of proc that is zero-initialized,
418 	 * then copy the section that is copied directly from the parent.
419 	 */
420 	bzero(&p2->p_startzero,
421 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
422 	bzero(&p2->p_kse.ke_startzero,
423 	    (unsigned) ((caddr_t)&p2->p_kse.ke_endzero
424 			- (caddr_t)&p2->p_kse.ke_startzero));
425 	bzero(&p2->p_thread.td_startzero,
426 	    (unsigned) ((caddr_t)&p2->p_thread.td_endzero
427 			- (caddr_t)&p2->p_thread.td_startzero));
428 	bzero(&p2->p_ksegrp.kg_startzero,
429 	    (unsigned) ((caddr_t)&p2->p_ksegrp.kg_endzero
430 			- (caddr_t)&p2->p_ksegrp.kg_startzero));
431 	PROC_LOCK(p1);
432 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
433 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
434 
435 	bcopy(&p1->p_kse.ke_startcopy, &p2->p_kse.ke_startcopy,
436 	    (unsigned) ((caddr_t)&p2->p_kse.ke_endcopy
437 			- (caddr_t)&p2->p_kse.ke_startcopy));
438 
439 	bcopy(&p1->p_thread.td_startcopy, &p2->p_thread.td_startcopy,
440 	    (unsigned) ((caddr_t)&p2->p_thread.td_endcopy
441 			- (caddr_t)&p2->p_thread.td_startcopy));
442 
443 	bcopy(&p1->p_ksegrp.kg_startcopy, &p2->p_ksegrp.kg_startcopy,
444 	    (unsigned) ((caddr_t)&p2->p_ksegrp.kg_endcopy
445 			- (caddr_t)&p2->p_ksegrp.kg_startcopy));
446 	PROC_UNLOCK(p1);
447 
448 	/*
449 	 * XXXKSE Theoretically only the running thread would get copied
450 	 * Others in the kernel would be 'aborted' in the child.
451 	 * i.e return E*something*
452 	 */
453 	proc_linkup(p2);
454 
455 	mtx_init(&p2->p_mtx, "process lock", MTX_DEF);
456 	PROC_LOCK(p2);
457 	/* note.. XXXKSE no pcb or u-area yet */
458 
459 	/*
460 	 * Duplicate sub-structures as needed.
461 	 * Increase reference counts on shared objects.
462 	 * The p_stats and p_sigacts substructs are set in vm_forkproc.
463 	 */
464 	p2->p_flag = 0;
465 	mtx_lock_spin(&sched_lock);
466 	p2->p_sflag = PS_INMEM;
467 	if (p1->p_sflag & PS_PROFIL)
468 		startprofclock(p2);
469 	mtx_unlock_spin(&sched_lock);
470 	/*
471 	 * We start off holding one spinlock after fork: sched_lock.
472 	 */
473 	PROC_LOCK(p1);
474 	p2->p_ucred = crhold(p1->p_ucred);
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.
589 	 * If not inherited, these were zeroed above.
590 	 */
591 	if (p1->p_traceflag & KTRFAC_INHERIT) {
592 		p2->p_traceflag = p1->p_traceflag;
593 		if ((p2->p_tracep = p1->p_tracep) != NULL) {
594 			PROC_UNLOCK(p1);
595 			PROC_UNLOCK(p2);
596 			VREF(p2->p_tracep);
597 			PROC_LOCK(p2);
598 			PROC_LOCK(p1);
599 		}
600 	}
601 #endif
602 
603 	/*
604 	 * set priority of child to be that of parent
605 	 * XXXKSE hey! copying the estcpu seems dodgy.. should split it..
606 	 */
607 	mtx_lock_spin(&sched_lock);
608 	p2->p_ksegrp.kg_estcpu = p1->p_ksegrp.kg_estcpu;
609 	mtx_unlock_spin(&sched_lock);
610 
611 	/*
612 	 * This begins the section where we must prevent the parent
613 	 * from being swapped.
614 	 */
615 	_PHOLD(p1);
616 	PROC_UNLOCK(p1);
617 	PROC_UNLOCK(p2);
618 
619 	/*
620 	 * Finish creating the child process.  It will return via a different
621 	 * execution path later.  (ie: directly into user mode)
622 	 */
623 	vm_forkproc(td, p2, flags);
624 
625 	if (flags == (RFFDG | RFPROC)) {
626 		cnt.v_forks++;
627 		cnt.v_forkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
628 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
629 		cnt.v_vforks++;
630 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
631 	} else if (p1 == &proc0) {
632 		cnt.v_kthreads++;
633 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
634 	} else {
635 		cnt.v_rforks++;
636 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
637 	}
638 
639 	/*
640 	 * Both processes are set up, now check if any loadable modules want
641 	 * to adjust anything.
642 	 *   What if they have an error? XXX
643 	 */
644 	sx_slock(&fork_list_lock);
645 	TAILQ_FOREACH(ep, &fork_list, next) {
646 		(*ep->function)(p1, p2, flags);
647 	}
648 	sx_sunlock(&fork_list_lock);
649 
650 	/*
651 	 * If RFSTOPPED not requested, make child runnable and add to
652 	 * run queue.
653 	 */
654 	microtime(&(p2->p_stats->p_start));
655 	p2->p_acflag = AFORK;
656 	if ((flags & RFSTOPPED) == 0) {
657 		mtx_lock_spin(&sched_lock);
658 		p2->p_stat = SRUN;
659 		setrunqueue(&p2->p_thread);
660 		mtx_unlock_spin(&sched_lock);
661 	}
662 
663 	/*
664 	 * Now can be swapped.
665 	 */
666 	PROC_LOCK(p1);
667 	_PRELE(p1);
668 
669 	/*
670 	 * tell any interested parties about the new process
671 	 */
672 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
673 	PROC_UNLOCK(p1);
674 
675 	/*
676 	 * Preserve synchronization semantics of vfork.  If waiting for
677 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
678 	 * proc (in case of exit).
679 	 */
680 	PROC_LOCK(p2);
681 	while (p2->p_flag & P_PPWAIT)
682 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
683 	PROC_UNLOCK(p2);
684 
685 	/*
686 	 * Return child proc pointer to parent.
687 	 */
688 	*procp = p2;
689 	return (0);
690 }
691 
692 /*
693  * The next two functionms are general routines to handle adding/deleting
694  * items on the fork callout list.
695  *
696  * at_fork():
697  * Take the arguments given and put them onto the fork callout list,
698  * However first make sure that it's not already there.
699  * Returns 0 on success or a standard error number.
700  */
701 
702 int
703 at_fork(function)
704 	forklist_fn function;
705 {
706 	struct forklist *ep;
707 
708 #ifdef INVARIANTS
709 	/* let the programmer know if he's been stupid */
710 	if (rm_at_fork(function))
711 		printf("WARNING: fork callout entry (%p) already present\n",
712 		    function);
713 #endif
714 	ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
715 	if (ep == NULL)
716 		return (ENOMEM);
717 	ep->function = function;
718 	sx_xlock(&fork_list_lock);
719 	TAILQ_INSERT_TAIL(&fork_list, ep, next);
720 	sx_xunlock(&fork_list_lock);
721 	return (0);
722 }
723 
724 /*
725  * Scan the exit callout list for the given item and remove it..
726  * Returns the number of items removed (0 or 1)
727  */
728 
729 int
730 rm_at_fork(function)
731 	forklist_fn function;
732 {
733 	struct forklist *ep;
734 
735 	sx_xlock(&fork_list_lock);
736 	TAILQ_FOREACH(ep, &fork_list, next) {
737 		if (ep->function == function) {
738 			TAILQ_REMOVE(&fork_list, ep, next);
739 			sx_xunlock(&fork_list_lock);
740 			free(ep, M_ATFORK);
741 			return(1);
742 		}
743 	}
744 	sx_xunlock(&fork_list_lock);
745 	return (0);
746 }
747 
748 /*
749  * Handle the return of a child process from fork1().  This function
750  * is called from the MD fork_trampoline() entry point.
751  */
752 void
753 fork_exit(callout, arg, frame)
754 	void (*callout)(void *, struct trapframe *);
755 	void *arg;
756 	struct trapframe *frame;
757 {
758 	struct thread *td = curthread;
759 	struct proc *p = td->td_proc;
760 
761 	/*
762 	 * Setup the sched_lock state so that we can release it.
763 	 */
764 	sched_lock.mtx_lock = (uintptr_t)td;
765 	sched_lock.mtx_recurse = 0;
766 	/*
767 	 * XXX: We really shouldn't have to do this.
768 	 */
769 	mtx_intr_enable(&sched_lock);
770 	mtx_unlock_spin(&sched_lock);
771 
772 #ifdef SMP
773 	if (PCPU_GET(switchtime.tv_sec) == 0)
774 		microuptime(PCPU_PTR(switchtime));
775 	PCPU_SET(switchticks, ticks);
776 #endif
777 
778 	/*
779 	 * cpu_set_fork_handler intercepts this function call to
780          * have this call a non-return function to stay in kernel mode.
781          * initproc has its own fork handler, but it does return.
782          */
783 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
784 	callout(arg, frame);
785 
786 	/*
787 	 * Check if a kernel thread misbehaved and returned from its main
788 	 * function.
789 	 */
790 	PROC_LOCK(p);
791 	if (p->p_flag & P_KTHREAD) {
792 		PROC_UNLOCK(p);
793 		mtx_lock(&Giant);
794 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
795 		    p->p_comm, p->p_pid);
796 		kthread_exit(0);
797 	}
798 	PROC_UNLOCK(p);
799 	mtx_assert(&Giant, MA_NOTOWNED);
800 }
801 
802 /*
803  * Simplified back end of syscall(), used when returning from fork()
804  * directly into user mode.  Giant is not held on entry, and must not
805  * be held on return.  This function is passed in to fork_exit() as the
806  * first parameter and is called when returning to a new userland process.
807  */
808 void
809 fork_return(td, frame)
810 	struct thread *td;
811 	struct trapframe *frame;
812 {
813 
814 	userret(td, frame, 0);
815 #ifdef KTRACE
816 	if (KTRPOINT(td->td_proc, KTR_SYSRET)) {
817 		ktrsysret(td->td_proc->p_tracep, SYS_fork, 0, 0);
818 	}
819 #endif
820 	mtx_assert(&Giant, MA_NOTOWNED);
821 }
822