xref: /freebsd/sys/kern/kern_fork.c (revision 8899023f664718b49e85db30bfc35f79481fce32)
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 
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 = uma_zalloc(proc_zone, M_WAITOK);
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 			PROC_LOCK(p2);
386 			while (p2->p_pid == trypid ||
387 			    p2->p_pgrp->pg_id == trypid ||
388 			    p2->p_session->s_sid == trypid) {
389 				trypid++;
390 				if (trypid >= pidchecked) {
391 					PROC_UNLOCK(p2);
392 					goto retry;
393 				}
394 			}
395 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
396 				pidchecked = p2->p_pid;
397 			if (p2->p_pgrp->pg_id > trypid &&
398 			    pidchecked > p2->p_pgrp->pg_id)
399 				pidchecked = p2->p_pgrp->pg_id;
400 			if (p2->p_session->s_sid > trypid &&
401 			    pidchecked > p2->p_session->s_sid)
402 				pidchecked = p2->p_session->s_sid;
403 			PROC_UNLOCK(p2);
404 		}
405 		if (!doingzomb) {
406 			doingzomb = 1;
407 			p2 = LIST_FIRST(&zombproc);
408 			goto again;
409 		}
410 	}
411 
412 	/*
413 	 * RFHIGHPID does not mess with the lastpid counter during boot.
414 	 */
415 	if (flags & RFHIGHPID)
416 		pidchecked = 0;
417 	else
418 		lastpid = trypid;
419 
420 	p2 = newproc;
421 	p2->p_stat = SIDL;			/* protect against others */
422 	p2->p_pid = trypid;
423 	LIST_INSERT_HEAD(&allproc, p2, p_list);
424 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
425 	sx_xunlock(&allproc_lock);
426 
427 	/*
428 	 * Make a proc table entry for the new process.
429 	 * Start by zeroing the section of proc that is zero-initialized,
430 	 * then copy the section that is copied directly from the parent.
431 	 */
432 	td2 = thread_get(p2);
433 	ke2 = &p2->p_kse;
434 	kg2 = &p2->p_ksegrp;
435 
436 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
437 
438 	bzero(&p2->p_startzero,
439 	    (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
440 	bzero(&ke2->ke_startzero,
441 	    (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
442 	bzero(&td2->td_startzero,
443 	    (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
444 	bzero(&kg2->kg_startzero,
445 	    (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
446 
447 	PROC_LOCK(p1);
448 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
449 	    (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
450 	bcopy(&td->td_kse->ke_startcopy, &ke2->ke_startcopy,
451 	    (unsigned) RANGEOF(struct kse, ke_startcopy, ke_endcopy));
452 	bcopy(&td->td_startcopy, &td2->td_startcopy,
453 	    (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
454 	bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
455 	    (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
456 #undef RANGEOF
457 	PROC_UNLOCK(p1);
458 
459 	/*
460 	 * XXXKSE Theoretically only the running thread would get copied
461 	 * Others in the kernel would be 'aborted' in the child.
462 	 * i.e return E*something*
463 	 */
464 	proc_linkup(p2, kg2, ke2, td2);
465 
466 	mtx_init(&p2->p_mtx, "process lock", MTX_DEF|MTX_DUPOK);
467 	PROC_LOCK(p2);
468 	/* note.. XXXKSE no pcb or u-area yet */
469 
470 	/*
471 	 * Duplicate sub-structures as needed.
472 	 * Increase reference counts on shared objects.
473 	 * The p_stats and p_sigacts substructs are set in vm_forkproc.
474 	 */
475 	p2->p_flag = 0;
476 	mtx_lock_spin(&sched_lock);
477 	p2->p_sflag = PS_INMEM;
478 	if (p1->p_sflag & PS_PROFIL)
479 		startprofclock(p2);
480 	mtx_unlock_spin(&sched_lock);
481 	PROC_LOCK(p1);
482 	p2->p_ucred = crhold(p1->p_ucred);
483 	td2->td_ucred = crhold(p2->p_ucred);	/* XXXKSE */
484 
485 	pargs_hold(p2->p_args);
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 	SESS_LOCK(p1->p_session);
563 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
564 		p2->p_flag |= P_CONTROLT;
565 	SESS_UNLOCK(p1->p_session);
566 	if (flags & RFPPWAIT)
567 		p2->p_flag |= P_PPWAIT;
568 
569 	LIST_INSERT_AFTER(p1, p2, p_pglist);
570 	PROC_UNLOCK(p1);
571 	PROC_UNLOCK(p2);
572 
573 	/*
574 	 * Attach the new process to its parent.
575 	 *
576 	 * If RFNOWAIT is set, the newly created process becomes a child
577 	 * of init.  This effectively disassociates the child from the
578 	 * parent.
579 	 */
580 	if (flags & RFNOWAIT)
581 		pptr = initproc;
582 	else
583 		pptr = p1;
584 	sx_xlock(&proctree_lock);
585 	PROC_LOCK(p2);
586 	p2->p_pptr = pptr;
587 	PROC_UNLOCK(p2);
588 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
589 	sx_xunlock(&proctree_lock);
590 	PROC_LOCK(p2);
591 	LIST_INIT(&p2->p_children);
592 	LIST_INIT(&td2->td_contested); /* XXXKSE only 1 thread? */
593 
594 	callout_init(&p2->p_itcallout, 0);
595 	callout_init(&td2->td_slpcallout, 1); /* XXXKSE */
596 
597 	PROC_LOCK(p1);
598 #ifdef KTRACE
599 	/*
600 	 * Copy traceflag and tracefile if enabled.  If not inherited,
601 	 * these were zeroed above but we still could have a trace race
602 	 * so make sure p2's p_tracep is NULL.
603 	 */
604 	if ((p1->p_traceflag & KTRFAC_INHERIT) && p2->p_tracep == NULL) {
605 		p2->p_traceflag = p1->p_traceflag;
606 		if ((p2->p_tracep = p1->p_tracep) != NULL) {
607 			PROC_UNLOCK(p1);
608 			PROC_UNLOCK(p2);
609 			VREF(p2->p_tracep);
610 			PROC_LOCK(p2);
611 			PROC_LOCK(p1);
612 		}
613 	}
614 #endif
615 
616 	/*
617 	 * set priority of child to be that of parent
618 	 * XXXKSE hey! copying the estcpu seems dodgy.. should split it..
619 	 */
620 	mtx_lock_spin(&sched_lock);
621 	p2->p_ksegrp.kg_estcpu = p1->p_ksegrp.kg_estcpu;
622 	mtx_unlock_spin(&sched_lock);
623 
624 	/*
625 	 * This begins the section where we must prevent the parent
626 	 * from being swapped.
627 	 */
628 	_PHOLD(p1);
629 	PROC_UNLOCK(p1);
630 	PROC_UNLOCK(p2);
631 
632 	/*
633 	 * Finish creating the child process.  It will return via a different
634 	 * execution path later.  (ie: directly into user mode)
635 	 */
636 	vm_forkproc(td, p2, td2, flags);
637 
638 	if (flags == (RFFDG | RFPROC)) {
639 		cnt.v_forks++;
640 		cnt.v_forkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
641 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
642 		cnt.v_vforks++;
643 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
644 	} else if (p1 == &proc0) {
645 		cnt.v_kthreads++;
646 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
647 	} else {
648 		cnt.v_rforks++;
649 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
650 	}
651 
652 	/*
653 	 * Both processes are set up, now check if any loadable modules want
654 	 * to adjust anything.
655 	 *   What if they have an error? XXX
656 	 */
657 	sx_slock(&fork_list_lock);
658 	TAILQ_FOREACH(ep, &fork_list, next) {
659 		(*ep->function)(p1, p2, flags);
660 	}
661 	sx_sunlock(&fork_list_lock);
662 
663 	/*
664 	 * If RFSTOPPED not requested, make child runnable and add to
665 	 * run queue.
666 	 */
667 	microtime(&(p2->p_stats->p_start));
668 	p2->p_acflag = AFORK;
669 	if ((flags & RFSTOPPED) == 0) {
670 		mtx_lock_spin(&sched_lock);
671 		p2->p_stat = SRUN;
672 		setrunqueue(td2);
673 		mtx_unlock_spin(&sched_lock);
674 	}
675 
676 	/*
677 	 * Now can be swapped.
678 	 */
679 	PROC_LOCK(p1);
680 	_PRELE(p1);
681 
682 	/*
683 	 * tell any interested parties about the new process
684 	 */
685 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
686 	PROC_UNLOCK(p1);
687 
688 	/*
689 	 * Preserve synchronization semantics of vfork.  If waiting for
690 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
691 	 * proc (in case of exit).
692 	 */
693 	PROC_LOCK(p2);
694 	while (p2->p_flag & P_PPWAIT)
695 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
696 	PROC_UNLOCK(p2);
697 
698 	/*
699 	 * Return child proc pointer to parent.
700 	 */
701 	*procp = p2;
702 	return (0);
703 }
704 
705 /*
706  * The next two functionms are general routines to handle adding/deleting
707  * items on the fork callout list.
708  *
709  * at_fork():
710  * Take the arguments given and put them onto the fork callout list,
711  * However first make sure that it's not already there.
712  * Returns 0 on success or a standard error number.
713  */
714 
715 int
716 at_fork(function)
717 	forklist_fn function;
718 {
719 	struct forklist *ep;
720 
721 #ifdef INVARIANTS
722 	/* let the programmer know if he's been stupid */
723 	if (rm_at_fork(function))
724 		printf("WARNING: fork callout entry (%p) already present\n",
725 		    function);
726 #endif
727 	ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
728 	if (ep == NULL)
729 		return (ENOMEM);
730 	ep->function = function;
731 	sx_xlock(&fork_list_lock);
732 	TAILQ_INSERT_TAIL(&fork_list, ep, next);
733 	sx_xunlock(&fork_list_lock);
734 	return (0);
735 }
736 
737 /*
738  * Scan the exit callout list for the given item and remove it..
739  * Returns the number of items removed (0 or 1)
740  */
741 
742 int
743 rm_at_fork(function)
744 	forklist_fn function;
745 {
746 	struct forklist *ep;
747 
748 	sx_xlock(&fork_list_lock);
749 	TAILQ_FOREACH(ep, &fork_list, next) {
750 		if (ep->function == function) {
751 			TAILQ_REMOVE(&fork_list, ep, next);
752 			sx_xunlock(&fork_list_lock);
753 			free(ep, M_ATFORK);
754 			return(1);
755 		}
756 	}
757 	sx_xunlock(&fork_list_lock);
758 	return (0);
759 }
760 
761 /*
762  * Handle the return of a child process from fork1().  This function
763  * is called from the MD fork_trampoline() entry point.
764  */
765 void
766 fork_exit(callout, arg, frame)
767 	void (*callout)(void *, struct trapframe *);
768 	void *arg;
769 	struct trapframe *frame;
770 {
771 	struct thread *td = curthread;
772 	struct proc *p = td->td_proc;
773 
774 	td->td_kse->ke_oncpu = PCPU_GET(cpuid);
775 	/*
776 	 * Finish setting up thread glue.  We need to initialize
777 	 * the thread into a td_critnest=1 state.  Some platforms
778 	 * may have already partially or fully initialized td_critnest
779 	 * and/or td_md.md_savecrit (when applciable).
780 	 *
781 	 * see <arch>/<arch>/critical.c
782 	 */
783 	sched_lock.mtx_lock = (uintptr_t)td;
784 	sched_lock.mtx_recurse = 0;
785 	cpu_critical_fork_exit();
786 	CTR3(KTR_PROC, "fork_exit: new proc %p (pid %d, %s)", p, p->p_pid,
787 	    p->p_comm);
788 	if (PCPU_GET(switchtime.sec) == 0)
789 		binuptime(PCPU_PTR(switchtime));
790 	PCPU_SET(switchticks, ticks);
791 	mtx_unlock_spin(&sched_lock);
792 
793 	/*
794 	 * cpu_set_fork_handler intercepts this function call to
795          * have this call a non-return function to stay in kernel mode.
796          * initproc has its own fork handler, but it does return.
797          */
798 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
799 	callout(arg, frame);
800 
801 	/*
802 	 * Check if a kernel thread misbehaved and returned from its main
803 	 * function.
804 	 */
805 	PROC_LOCK(p);
806 	if (p->p_flag & P_KTHREAD) {
807 		PROC_UNLOCK(p);
808 		mtx_lock(&Giant);
809 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
810 		    p->p_comm, p->p_pid);
811 		kthread_exit(0);
812 	}
813 	PROC_UNLOCK(p);
814 #ifdef DIAGNOSTIC
815 	cred_free_thread(td);
816 #endif
817 	mtx_assert(&Giant, MA_NOTOWNED);
818 }
819 
820 /*
821  * Simplified back end of syscall(), used when returning from fork()
822  * directly into user mode.  Giant is not held on entry, and must not
823  * be held on return.  This function is passed in to fork_exit() as the
824  * first parameter and is called when returning to a new userland process.
825  */
826 void
827 fork_return(td, frame)
828 	struct thread *td;
829 	struct trapframe *frame;
830 {
831 
832 	userret(td, frame, 0);
833 #ifdef KTRACE
834 	if (KTRPOINT(td->td_proc, KTR_SYSRET)) {
835 		ktrsysret(td->td_proc->p_tracep, SYS_fork, 0, 0);
836 	}
837 #endif
838 	mtx_assert(&Giant, MA_NOTOWNED);
839 }
840