xref: /freebsd/sys/kern/kern_fork.c (revision c17d43407fe04133a94055b0dbc7ea8965654a9f)
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);
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 	if (p2->p_args)
486 		p2->p_args->ar_ref++;
487 
488 	if (flags & RFSIGSHARE) {
489 		p2->p_procsig = p1->p_procsig;
490 		p2->p_procsig->ps_refcnt++;
491 		if (p1->p_sigacts == &p1->p_uarea->u_sigacts) {
492 			struct sigacts *newsigacts;
493 
494 			PROC_UNLOCK(p1);
495 			PROC_UNLOCK(p2);
496 			/* Create the shared sigacts structure */
497 			MALLOC(newsigacts, struct sigacts *,
498 			    sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
499 			PROC_LOCK(p2);
500 			PROC_LOCK(p1);
501 			/*
502 			 * Set p_sigacts to the new shared structure.
503 			 * Note that this is updating p1->p_sigacts at the
504 			 * same time, since p_sigacts is just a pointer to
505 			 * the shared p_procsig->ps_sigacts.
506 			 */
507 			p2->p_sigacts  = newsigacts;
508 			*p2->p_sigacts = p1->p_uarea->u_sigacts;
509 		}
510 	} else {
511 		PROC_UNLOCK(p1);
512 		PROC_UNLOCK(p2);
513 		MALLOC(p2->p_procsig, struct procsig *, sizeof(struct procsig),
514 		    M_SUBPROC, M_WAITOK);
515 		PROC_LOCK(p2);
516 		PROC_LOCK(p1);
517 		bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
518 		p2->p_procsig->ps_refcnt = 1;
519 		p2->p_sigacts = NULL;	/* finished in vm_forkproc() */
520 	}
521 	if (flags & RFLINUXTHPN)
522 	        p2->p_sigparent = SIGUSR1;
523 	else
524 	        p2->p_sigparent = SIGCHLD;
525 
526 	/* bump references to the text vnode (for procfs) */
527 	p2->p_textvp = p1->p_textvp;
528 	PROC_UNLOCK(p1);
529 	PROC_UNLOCK(p2);
530 	if (p2->p_textvp)
531 		VREF(p2->p_textvp);
532 
533 	if (flags & RFCFDG)
534 		fd = fdinit(td);
535 	else if (flags & RFFDG) {
536 		FILEDESC_LOCK(p1->p_fd);
537 		fd = fdcopy(td);
538 		FILEDESC_UNLOCK(p1->p_fd);
539 	} else
540 		fd = fdshare(p1);
541 	PROC_LOCK(p2);
542 	p2->p_fd = fd;
543 
544 	/*
545 	 * If p_limit is still copy-on-write, bump refcnt,
546 	 * otherwise get a copy that won't be modified.
547 	 * (If PL_SHAREMOD is clear, the structure is shared
548 	 * copy-on-write.)
549 	 */
550 	PROC_LOCK(p1);
551 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
552 		p2->p_limit = limcopy(p1->p_limit);
553 	else {
554 		p2->p_limit = p1->p_limit;
555 		p2->p_limit->p_refcnt++;
556 	}
557 
558 	/*
559 	 * Preserve some more flags in subprocess.  PS_PROFIL has already
560 	 * been preserved.
561 	 */
562 	p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
563 	SESS_LOCK(p1->p_session);
564 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
565 		p2->p_flag |= P_CONTROLT;
566 	SESS_UNLOCK(p1->p_session);
567 	if (flags & RFPPWAIT)
568 		p2->p_flag |= P_PPWAIT;
569 
570 	LIST_INSERT_AFTER(p1, p2, p_pglist);
571 	PROC_UNLOCK(p1);
572 	PROC_UNLOCK(p2);
573 
574 	/*
575 	 * Attach the new process to its parent.
576 	 *
577 	 * If RFNOWAIT is set, the newly created process becomes a child
578 	 * of init.  This effectively disassociates the child from the
579 	 * parent.
580 	 */
581 	if (flags & RFNOWAIT)
582 		pptr = initproc;
583 	else
584 		pptr = p1;
585 	sx_xlock(&proctree_lock);
586 	PROC_LOCK(p2);
587 	p2->p_pptr = pptr;
588 	PROC_UNLOCK(p2);
589 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
590 	sx_xunlock(&proctree_lock);
591 	PROC_LOCK(p2);
592 	LIST_INIT(&p2->p_children);
593 	LIST_INIT(&td2->td_contested); /* XXXKSE only 1 thread? */
594 
595 	callout_init(&p2->p_itcallout, 0);
596 	callout_init(&td2->td_slpcallout, 1); /* XXXKSE */
597 
598 	PROC_LOCK(p1);
599 #ifdef KTRACE
600 	/*
601 	 * Copy traceflag and tracefile if enabled.  If not inherited,
602 	 * these were zeroed above but we still could have a trace race
603 	 * so make sure p2's p_tracep is NULL.
604 	 */
605 	if ((p1->p_traceflag & KTRFAC_INHERIT) && p2->p_tracep == NULL) {
606 		p2->p_traceflag = p1->p_traceflag;
607 		if ((p2->p_tracep = p1->p_tracep) != NULL) {
608 			PROC_UNLOCK(p1);
609 			PROC_UNLOCK(p2);
610 			VREF(p2->p_tracep);
611 			PROC_LOCK(p2);
612 			PROC_LOCK(p1);
613 		}
614 	}
615 #endif
616 
617 	/*
618 	 * set priority of child to be that of parent
619 	 * XXXKSE hey! copying the estcpu seems dodgy.. should split it..
620 	 */
621 	mtx_lock_spin(&sched_lock);
622 	p2->p_ksegrp.kg_estcpu = p1->p_ksegrp.kg_estcpu;
623 	mtx_unlock_spin(&sched_lock);
624 
625 	/*
626 	 * This begins the section where we must prevent the parent
627 	 * from being swapped.
628 	 */
629 	_PHOLD(p1);
630 	PROC_UNLOCK(p1);
631 	PROC_UNLOCK(p2);
632 
633 	/*
634 	 * Finish creating the child process.  It will return via a different
635 	 * execution path later.  (ie: directly into user mode)
636 	 */
637 	vm_forkproc(td, p2, td2, flags);
638 
639 	if (flags == (RFFDG | RFPROC)) {
640 		cnt.v_forks++;
641 		cnt.v_forkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
642 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
643 		cnt.v_vforks++;
644 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
645 	} else if (p1 == &proc0) {
646 		cnt.v_kthreads++;
647 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
648 	} else {
649 		cnt.v_rforks++;
650 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
651 	}
652 
653 	/*
654 	 * Both processes are set up, now check if any loadable modules want
655 	 * to adjust anything.
656 	 *   What if they have an error? XXX
657 	 */
658 	sx_slock(&fork_list_lock);
659 	TAILQ_FOREACH(ep, &fork_list, next) {
660 		(*ep->function)(p1, p2, flags);
661 	}
662 	sx_sunlock(&fork_list_lock);
663 
664 	/*
665 	 * If RFSTOPPED not requested, make child runnable and add to
666 	 * run queue.
667 	 */
668 	microtime(&(p2->p_stats->p_start));
669 	p2->p_acflag = AFORK;
670 	if ((flags & RFSTOPPED) == 0) {
671 		mtx_lock_spin(&sched_lock);
672 		p2->p_stat = SRUN;
673 		setrunqueue(td2);
674 		mtx_unlock_spin(&sched_lock);
675 	}
676 
677 	/*
678 	 * Now can be swapped.
679 	 */
680 	PROC_LOCK(p1);
681 	_PRELE(p1);
682 
683 	/*
684 	 * tell any interested parties about the new process
685 	 */
686 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
687 	PROC_UNLOCK(p1);
688 
689 	/*
690 	 * Preserve synchronization semantics of vfork.  If waiting for
691 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
692 	 * proc (in case of exit).
693 	 */
694 	PROC_LOCK(p2);
695 	while (p2->p_flag & P_PPWAIT)
696 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
697 	PROC_UNLOCK(p2);
698 
699 	/*
700 	 * Return child proc pointer to parent.
701 	 */
702 	*procp = p2;
703 	return (0);
704 }
705 
706 /*
707  * The next two functionms are general routines to handle adding/deleting
708  * items on the fork callout list.
709  *
710  * at_fork():
711  * Take the arguments given and put them onto the fork callout list,
712  * However first make sure that it's not already there.
713  * Returns 0 on success or a standard error number.
714  */
715 
716 int
717 at_fork(function)
718 	forklist_fn function;
719 {
720 	struct forklist *ep;
721 
722 #ifdef INVARIANTS
723 	/* let the programmer know if he's been stupid */
724 	if (rm_at_fork(function))
725 		printf("WARNING: fork callout entry (%p) already present\n",
726 		    function);
727 #endif
728 	ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
729 	if (ep == NULL)
730 		return (ENOMEM);
731 	ep->function = function;
732 	sx_xlock(&fork_list_lock);
733 	TAILQ_INSERT_TAIL(&fork_list, ep, next);
734 	sx_xunlock(&fork_list_lock);
735 	return (0);
736 }
737 
738 /*
739  * Scan the exit callout list for the given item and remove it..
740  * Returns the number of items removed (0 or 1)
741  */
742 
743 int
744 rm_at_fork(function)
745 	forklist_fn function;
746 {
747 	struct forklist *ep;
748 
749 	sx_xlock(&fork_list_lock);
750 	TAILQ_FOREACH(ep, &fork_list, next) {
751 		if (ep->function == function) {
752 			TAILQ_REMOVE(&fork_list, ep, next);
753 			sx_xunlock(&fork_list_lock);
754 			free(ep, M_ATFORK);
755 			return(1);
756 		}
757 	}
758 	sx_xunlock(&fork_list_lock);
759 	return (0);
760 }
761 
762 /*
763  * Handle the return of a child process from fork1().  This function
764  * is called from the MD fork_trampoline() entry point.
765  */
766 void
767 fork_exit(callout, arg, frame)
768 	void (*callout)(void *, struct trapframe *);
769 	void *arg;
770 	struct trapframe *frame;
771 {
772 	struct thread *td = curthread;
773 	struct proc *p = td->td_proc;
774 
775 	td->td_kse->ke_oncpu = PCPU_GET(cpuid);
776 	/*
777 	 * Setup the sched_lock state so that we can release it.
778 	 */
779 	sched_lock.mtx_lock = (uintptr_t)td;
780 	sched_lock.mtx_recurse = 0;
781 	td->td_critnest = 1;
782 	td->td_savecrit = CRITICAL_FORK;
783 	CTR3(KTR_PROC, "fork_exit: new proc %p (pid %d, %s)", p, p->p_pid,
784 	    p->p_comm);
785 	if (PCPU_GET(switchtime.sec) == 0)
786 		binuptime(PCPU_PTR(switchtime));
787 	PCPU_SET(switchticks, ticks);
788 	mtx_unlock_spin(&sched_lock);
789 
790 	/*
791 	 * cpu_set_fork_handler intercepts this function call to
792          * have this call a non-return function to stay in kernel mode.
793          * initproc has its own fork handler, but it does return.
794          */
795 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
796 	callout(arg, frame);
797 
798 	/*
799 	 * Check if a kernel thread misbehaved and returned from its main
800 	 * function.
801 	 */
802 	PROC_LOCK(p);
803 	if (p->p_flag & P_KTHREAD) {
804 		PROC_UNLOCK(p);
805 		mtx_lock(&Giant);
806 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
807 		    p->p_comm, p->p_pid);
808 		kthread_exit(0);
809 	}
810 	PROC_UNLOCK(p);
811 #ifdef DIAGNOSTIC
812 	cred_free_thread(td);
813 #endif
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