xref: /freebsd/sys/kern/kern_fork.c (revision 218a01e0624b8b439277a5e0f5b52a529840121e)
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 #include "opt_mac.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/filedesc.h>
49 #include <sys/kernel.h>
50 #include <sys/sysctl.h>
51 #include <sys/lock.h>
52 #include <sys/malloc.h>
53 #include <sys/mutex.h>
54 #include <sys/proc.h>
55 #include <sys/pioctl.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sched.h>
58 #include <sys/syscall.h>
59 #include <sys/vnode.h>
60 #include <sys/acct.h>
61 #include <sys/mac.h>
62 #include <sys/ktr.h>
63 #include <sys/ktrace.h>
64 #include <sys/kthread.h>
65 #include <sys/unistd.h>
66 #include <sys/jail.h>
67 #include <sys/sx.h>
68 
69 #include <vm/vm.h>
70 #include <vm/pmap.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_extern.h>
73 #include <vm/uma.h>
74 
75 #include <sys/vmmeter.h>
76 #include <sys/user.h>
77 #include <machine/critical.h>
78 
79 static MALLOC_DEFINE(M_ATFORK, "atfork", "atfork callback");
80 
81 /*
82  * These are the stuctures used to create a callout list for things to do
83  * when forking a process
84  */
85 struct forklist {
86 	forklist_fn function;
87 	TAILQ_ENTRY(forklist) next;
88 };
89 
90 static struct sx fork_list_lock;
91 
92 TAILQ_HEAD(forklist_head, forklist);
93 static struct forklist_head fork_list = TAILQ_HEAD_INITIALIZER(fork_list);
94 
95 #ifndef _SYS_SYSPROTO_H_
96 struct fork_args {
97 	int     dummy;
98 };
99 #endif
100 
101 int forksleep; /* Place for fork1() to sleep on. */
102 
103 static void
104 init_fork_list(void *data __unused)
105 {
106 
107 	sx_init(&fork_list_lock, "fork list");
108 }
109 SYSINIT(fork_list, SI_SUB_INTRINSIC, SI_ORDER_ANY, init_fork_list, NULL);
110 
111 /*
112  * MPSAFE
113  */
114 /* ARGSUSED */
115 int
116 fork(td, uap)
117 	struct thread *td;
118 	struct fork_args *uap;
119 {
120 	int error;
121 	struct proc *p2;
122 
123 	mtx_lock(&Giant);
124 	error = fork1(td, RFFDG | RFPROC, 0, &p2);
125 	if (error == 0) {
126 		td->td_retval[0] = p2->p_pid;
127 		td->td_retval[1] = 0;
128 	}
129 	mtx_unlock(&Giant);
130 	return error;
131 }
132 
133 /*
134  * MPSAFE
135  */
136 /* ARGSUSED */
137 int
138 vfork(td, uap)
139 	struct thread *td;
140 	struct vfork_args *uap;
141 {
142 	int error;
143 	struct proc *p2;
144 
145 	mtx_lock(&Giant);
146 	error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
147 	if (error == 0) {
148 		td->td_retval[0] = p2->p_pid;
149 		td->td_retval[1] = 0;
150 	}
151 	mtx_unlock(&Giant);
152 	return error;
153 }
154 
155 /*
156  * MPSAFE
157  */
158 int
159 rfork(td, uap)
160 	struct thread *td;
161 	struct rfork_args *uap;
162 {
163 	int error;
164 	struct proc *p2;
165 
166 	/* Don't allow kernel only flags. */
167 	if ((uap->flags & RFKERNELONLY) != 0)
168 		return (EINVAL);
169 	/*
170 	 * Don't allow sharing of file descriptor table unless
171 	 * RFTHREAD flag is supplied
172 	 */
173 	if ((uap->flags & (RFPROC | RFTHREAD | RFFDG | RFCFDG)) ==
174 	    RFPROC)
175 		return(EINVAL);
176 	mtx_lock(&Giant);
177 	error = fork1(td, uap->flags, 0, &p2);
178 	if (error == 0) {
179 		td->td_retval[0] = p2 ? p2->p_pid : 0;
180 		td->td_retval[1] = 0;
181 	}
182 	mtx_unlock(&Giant);
183 	return error;
184 }
185 
186 
187 int	nprocs = 1;				/* process 0 */
188 int	lastpid = 0;
189 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
190     "Last used PID");
191 
192 /*
193  * Random component to lastpid generation.  We mix in a random factor to make
194  * it a little harder to predict.  We sanity check the modulus value to avoid
195  * doing it in critical paths.  Don't let it be too small or we pointlessly
196  * waste randomness entropy, and don't let it be impossibly large.  Using a
197  * modulus that is too big causes a LOT more process table scans and slows
198  * down fork processing as the pidchecked caching is defeated.
199  */
200 static int randompid = 0;
201 
202 static int
203 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
204 {
205 	int error, pid;
206 
207 	sysctl_wire_old_buffer(req, sizeof(int));
208 	sx_xlock(&allproc_lock);
209 	pid = randompid;
210 	error = sysctl_handle_int(oidp, &pid, 0, req);
211 	if (error == 0 && req->newptr != NULL) {
212 		if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
213 			pid = PID_MAX - 100;
214 		else if (pid < 2)			/* NOP */
215 			pid = 0;
216 		else if (pid < 100)			/* Make it reasonable */
217 			pid = 100;
218 		randompid = pid;
219 	}
220 	sx_xunlock(&allproc_lock);
221 	return (error);
222 }
223 
224 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
225     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
226 
227 int
228 fork1(td, flags, pages, procp)
229 	struct thread *td;			/* parent proc */
230 	int flags;
231 	int pages;
232 	struct proc **procp;			/* child proc */
233 {
234 	struct proc *p2, *pptr;
235 	uid_t uid;
236 	struct proc *newproc;
237 	int trypid;
238 	int ok;
239 	static int pidchecked = 0;
240 	struct forklist *ep;
241 	struct filedesc *fd;
242 	struct proc *p1 = td->td_proc;
243 	struct thread *td2;
244 	struct kse *ke2;
245 	struct ksegrp *kg2;
246 	struct sigacts *newsigacts;
247 	struct procsig *newprocsig;
248 	int error;
249 
250 	GIANT_REQUIRED;
251 
252 	/* Can't copy and clear */
253 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
254 		return (EINVAL);
255 
256 	/*
257 	 * Here we don't create a new process, but we divorce
258 	 * certain parts of a process from itself.
259 	 */
260 	if ((flags & RFPROC) == 0) {
261 		vm_forkproc(td, NULL, NULL, flags);
262 
263 		/*
264 		 * Close all file descriptors.
265 		 */
266 		if (flags & RFCFDG) {
267 			struct filedesc *fdtmp;
268 			fdtmp = fdinit(td->td_proc->p_fd);
269 			fdfree(td);
270 			p1->p_fd = fdtmp;
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->td_proc->p_fd);
282 				FILEDESC_UNLOCK(p1->p_fd);
283 				fdfree(td);
284 				p1->p_fd = newfd;
285 			} else
286 				FILEDESC_UNLOCK(p1->p_fd);
287 		}
288 		*procp = NULL;
289 		return (0);
290 	}
291 
292 	if (p1->p_flag & P_KSES) {
293 		/*
294 		 * Idle the other threads for a second.
295 		 * Since the user space is copied, it must remain stable.
296 		 * In addition, all threads (from the user perspective)
297 		 * need to either be suspended or in the kernel,
298 		 * where they will try restart in the parent and will
299 		 * be aborted in the child.
300 		 */
301 		PROC_LOCK(p1);
302 		if (thread_single(SINGLE_NO_EXIT)) {
303 			/* Abort.. someone else is single threading before us */
304 			PROC_UNLOCK(p1);
305 			return (ERESTART);
306 		}
307 		PROC_UNLOCK(p1);
308 		/*
309 		 * All other activity in this process
310 		 * is now suspended at the user boundary,
311 		 * (or other safe places if we think of any).
312 		 */
313 	}
314 
315 	/* Allocate new proc. */
316 	newproc = uma_zalloc(proc_zone, 0);
317 #ifdef MAC
318 	mac_init_proc(newproc);
319 #endif
320 
321 	/*
322 	 * Although process entries are dynamically created, we still keep
323 	 * a global limit on the maximum number we will create.  Don't allow
324 	 * a nonprivileged user to use the last ten processes; don't let root
325 	 * exceed the limit. The variable nprocs is the current number of
326 	 * processes, maxproc is the limit.
327 	 */
328 	sx_xlock(&allproc_lock);
329 	uid = td->td_ucred->cr_ruid;
330 	if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) {
331 		error = EAGAIN;
332 		goto fail;
333 	}
334 
335 	/*
336 	 * Increment the count of procs running with this uid. Don't allow
337 	 * a nonprivileged user to exceed their current limit.
338 	 */
339 	PROC_LOCK(p1);
340 	ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
341 		(uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
342 	PROC_UNLOCK(p1);
343 	if (!ok) {
344 		error = EAGAIN;
345 		goto fail;
346 	}
347 
348 	/*
349 	 * Increment the nprocs resource before blocking can occur.  There
350 	 * are hard-limits as to the number of processes that can run.
351 	 */
352 	nprocs++;
353 
354 	/*
355 	 * Find an unused process ID.  We remember a range of unused IDs
356 	 * ready to use (from lastpid+1 through pidchecked-1).
357 	 *
358 	 * If RFHIGHPID is set (used during system boot), do not allocate
359 	 * low-numbered pids.
360 	 */
361 	trypid = lastpid + 1;
362 	if (flags & RFHIGHPID) {
363 		if (trypid < 10) {
364 			trypid = 10;
365 		}
366 	} else {
367 		if (randompid)
368 			trypid += arc4random() % randompid;
369 	}
370 retry:
371 	/*
372 	 * If the process ID prototype has wrapped around,
373 	 * restart somewhat above 0, as the low-numbered procs
374 	 * tend to include daemons that don't exit.
375 	 */
376 	if (trypid >= PID_MAX) {
377 		trypid = trypid % PID_MAX;
378 		if (trypid < 100)
379 			trypid += 100;
380 		pidchecked = 0;
381 	}
382 	if (trypid >= pidchecked) {
383 		int doingzomb = 0;
384 
385 		pidchecked = PID_MAX;
386 		/*
387 		 * Scan the active and zombie procs to check whether this pid
388 		 * is in use.  Remember the lowest pid that's greater
389 		 * than trypid, so we can avoid checking for a while.
390 		 */
391 		p2 = LIST_FIRST(&allproc);
392 again:
393 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
394 			PROC_LOCK(p2);
395 			while (p2->p_pid == trypid ||
396 			    p2->p_pgrp->pg_id == trypid ||
397 			    p2->p_session->s_sid == trypid) {
398 				trypid++;
399 				if (trypid >= pidchecked) {
400 					PROC_UNLOCK(p2);
401 					goto retry;
402 				}
403 			}
404 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
405 				pidchecked = p2->p_pid;
406 			if (p2->p_pgrp->pg_id > trypid &&
407 			    pidchecked > p2->p_pgrp->pg_id)
408 				pidchecked = p2->p_pgrp->pg_id;
409 			if (p2->p_session->s_sid > trypid &&
410 			    pidchecked > p2->p_session->s_sid)
411 				pidchecked = p2->p_session->s_sid;
412 			PROC_UNLOCK(p2);
413 		}
414 		if (!doingzomb) {
415 			doingzomb = 1;
416 			p2 = LIST_FIRST(&zombproc);
417 			goto again;
418 		}
419 	}
420 
421 	/*
422 	 * RFHIGHPID does not mess with the lastpid counter during boot.
423 	 */
424 	if (flags & RFHIGHPID)
425 		pidchecked = 0;
426 	else
427 		lastpid = trypid;
428 
429 	p2 = newproc;
430 	p2->p_state = PRS_NEW;		/* protect against others */
431 	p2->p_pid = trypid;
432 	LIST_INSERT_HEAD(&allproc, p2, p_list);
433 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
434 	sx_xunlock(&allproc_lock);
435 
436 	/*
437 	 * Malloc things while we don't hold any locks.
438 	 */
439 	if (flags & RFSIGSHARE) {
440 		MALLOC(newsigacts, struct sigacts *,
441 		    sizeof(struct sigacts), M_SUBPROC, 0);
442 		newprocsig = NULL;
443 	} else {
444 		newsigacts = NULL;
445 		MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
446 		    M_SUBPROC, 0);
447 	}
448 
449 	/*
450 	 * Copy filedesc.
451 	 * XXX: This is busted.  fd*() need to not take proc
452 	 * arguments or something.
453 	 */
454 	if (flags & RFCFDG)
455 		fd = fdinit(td->td_proc->p_fd);
456 	else if (flags & RFFDG) {
457 		FILEDESC_LOCK(p1->p_fd);
458 		fd = fdcopy(td->td_proc->p_fd);
459 		FILEDESC_UNLOCK(p1->p_fd);
460 	} else
461 		fd = fdshare(p1->p_fd);
462 
463 	/*
464 	 * Make a proc table entry for the new process.
465 	 * Start by zeroing the section of proc that is zero-initialized,
466 	 * then copy the section that is copied directly from the parent.
467 	 */
468 	td2 = FIRST_THREAD_IN_PROC(p2);
469 	kg2 = FIRST_KSEGRP_IN_PROC(p2);
470 	ke2 = FIRST_KSE_IN_KSEGRP(kg2);
471 
472 	/* Allocate and switch to an alternate kstack if specified */
473 	if (pages != 0)
474 		pmap_new_altkstack(td2, pages);
475 
476 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
477 
478 	bzero(&p2->p_startzero,
479 	    (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
480 	bzero(&ke2->ke_startzero,
481 	    (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
482 	bzero(&td2->td_startzero,
483 	    (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
484 	bzero(&kg2->kg_startzero,
485 	    (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
486 
487 	mtx_init(&p2->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
488 	PROC_LOCK(p2);
489 	PROC_LOCK(p1);
490 
491 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
492 	    (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
493 	bcopy(&td->td_startcopy, &td2->td_startcopy,
494 	    (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
495 	bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
496 	    (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
497 #undef RANGEOF
498 
499 	/* Set up the thread as an active thread (as if runnable). */
500 	ke2->ke_state = KES_THREAD;
501 	ke2->ke_thread = td2;
502 	ke2->ke_owner = td2;
503 	td2->td_kse = ke2;
504 	td2->td_flags &= ~TDF_UNBOUND; /* For the rest of this syscall. */
505 
506 	/*
507 	 * Duplicate sub-structures as needed.
508 	 * Increase reference counts on shared objects.
509 	 * The p_stats and p_sigacts substructs are set in vm_forkproc.
510 	 */
511 	p2->p_flag = 0;
512 	mtx_lock_spin(&sched_lock);
513 	p2->p_sflag = PS_INMEM;
514 	if (p1->p_sflag & PS_PROFIL)
515 		startprofclock(p2);
516 	/*
517 	 * Allow the scheduler to adjust the priority of the child and
518 	 * parent while we hold the sched_lock.
519 	 */
520 	sched_fork(td->td_ksegrp, kg2);
521 
522 	mtx_unlock_spin(&sched_lock);
523 	p2->p_ucred = crhold(td->td_ucred);
524 	td2->td_ucred = crhold(p2->p_ucred);	/* XXXKSE */
525 
526 	pargs_hold(p2->p_args);
527 
528 	if (flags & RFSIGSHARE) {
529 		p2->p_procsig = p1->p_procsig;
530 		p2->p_procsig->ps_refcnt++;
531 		if (p1->p_sigacts == &p1->p_uarea->u_sigacts) {
532 			/*
533 			 * Set p_sigacts to the new shared structure.
534 			 * Note that this is updating p1->p_sigacts at the
535 			 * same time, since p_sigacts is just a pointer to
536 			 * the shared p_procsig->ps_sigacts.
537 			 */
538 			p2->p_sigacts  = newsigacts;
539 			newsigacts = NULL;
540 			*p2->p_sigacts = p1->p_uarea->u_sigacts;
541 		}
542 	} else {
543 		p2->p_procsig = newprocsig;
544 		newprocsig = NULL;
545 		bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
546 		p2->p_procsig->ps_refcnt = 1;
547 		p2->p_sigacts = NULL;	/* finished in vm_forkproc() */
548 	}
549 	if (flags & RFLINUXTHPN)
550 	        p2->p_sigparent = SIGUSR1;
551 	else
552 	        p2->p_sigparent = SIGCHLD;
553 
554 	/* Bump references to the text vnode (for procfs) */
555 	p2->p_textvp = p1->p_textvp;
556 	if (p2->p_textvp)
557 		VREF(p2->p_textvp);
558 	p2->p_fd = fd;
559 	PROC_UNLOCK(p1);
560 	PROC_UNLOCK(p2);
561 
562 	/*
563 	 * If p_limit is still copy-on-write, bump refcnt,
564 	 * otherwise get a copy that won't be modified.
565 	 * (If PL_SHAREMOD is clear, the structure is shared
566 	 * copy-on-write.)
567 	 */
568 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
569 		p2->p_limit = limcopy(p1->p_limit);
570 	else {
571 		p2->p_limit = p1->p_limit;
572 		p2->p_limit->p_refcnt++;
573 	}
574 
575 	/*
576 	 * Setup linkage for kernel based threading
577 	 */
578 	if((flags & RFTHREAD) != 0) {
579 		mtx_lock(&ppeers_lock);
580 		p2->p_peers = p1->p_peers;
581 		p1->p_peers = p2;
582 		p2->p_leader = p1->p_leader;
583 		mtx_unlock(&ppeers_lock);
584 		PROC_LOCK(p1->p_leader);
585 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
586 			PROC_UNLOCK(p1->p_leader);
587 			/*
588 			 * The task leader is exiting, so process p1 is
589 			 * going to be killed shortly.  Since p1 obviously
590 			 * isn't dead yet, we know that the leader is either
591 			 * sending SIGKILL's to all the processes in this
592 			 * task or is sleeping waiting for all the peers to
593 			 * exit.  We let p1 complete the fork, but we need
594 			 * to go ahead and kill the new process p2 since
595 			 * the task leader may not get a chance to send
596 			 * SIGKILL to it.  We leave it on the list so that
597 			 * the task leader will wait for this new process
598 			 * to commit suicide.
599 			 */
600 			PROC_LOCK(p2);
601 			psignal(p2, SIGKILL);
602 			PROC_UNLOCK(p2);
603 		} else
604 			PROC_UNLOCK(p1->p_leader);
605 	} else {
606 		p2->p_peers = NULL;
607 		p2->p_leader = p2;
608 	}
609 
610 	sx_xlock(&proctree_lock);
611 	PGRP_LOCK(p1->p_pgrp);
612 	PROC_LOCK(p2);
613 	PROC_LOCK(p1);
614 
615 	/*
616 	 * Preserve some more flags in subprocess.  PS_PROFIL has already
617 	 * been preserved.
618 	 */
619 	p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
620 	SESS_LOCK(p1->p_session);
621 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
622 		p2->p_flag |= P_CONTROLT;
623 	SESS_UNLOCK(p1->p_session);
624 	if (flags & RFPPWAIT)
625 		p2->p_flag |= P_PPWAIT;
626 
627 	LIST_INSERT_AFTER(p1, p2, p_pglist);
628 	PGRP_UNLOCK(p1->p_pgrp);
629 	LIST_INIT(&p2->p_children);
630 
631 	callout_init(&p2->p_itcallout, 0);
632 
633 #ifdef KTRACE
634 	/*
635 	 * Copy traceflag and tracefile if enabled.
636 	 */
637 	mtx_lock(&ktrace_mtx);
638 	KASSERT(p2->p_tracep == NULL, ("new process has a ktrace vnode"));
639 	if (p1->p_traceflag & KTRFAC_INHERIT) {
640 		p2->p_traceflag = p1->p_traceflag;
641 		if ((p2->p_tracep = p1->p_tracep) != NULL)
642 			VREF(p2->p_tracep);
643 	}
644 	mtx_unlock(&ktrace_mtx);
645 #endif
646 
647 	/*
648 	 * If PF_FORK is set, the child process inherits the
649 	 * procfs ioctl flags from its parent.
650 	 */
651 	if (p1->p_pfsflags & PF_FORK) {
652 		p2->p_stops = p1->p_stops;
653 		p2->p_pfsflags = p1->p_pfsflags;
654 	}
655 
656 	/*
657 	 * This begins the section where we must prevent the parent
658 	 * from being swapped.
659 	 */
660 	_PHOLD(p1);
661 	PROC_UNLOCK(p1);
662 
663 	/*
664 	 * Attach the new process to its parent.
665 	 *
666 	 * If RFNOWAIT is set, the newly created process becomes a child
667 	 * of init.  This effectively disassociates the child from the
668 	 * parent.
669 	 */
670 	if (flags & RFNOWAIT)
671 		pptr = initproc;
672 	else
673 		pptr = p1;
674 	p2->p_pptr = pptr;
675 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
676 	PROC_UNLOCK(p2);
677 	sx_xunlock(&proctree_lock);
678 
679 	KASSERT(newprocsig == NULL, ("unused newprocsig"));
680 	if (newsigacts != NULL)
681 		FREE(newsigacts, M_SUBPROC);
682 	/*
683 	 * Finish creating the child process.  It will return via a different
684 	 * execution path later.  (ie: directly into user mode)
685 	 */
686 	vm_forkproc(td, p2, td2, flags);
687 
688 	if (flags == (RFFDG | RFPROC)) {
689 		cnt.v_forks++;
690 		cnt.v_forkpages += p2->p_vmspace->vm_dsize +
691 		    p2->p_vmspace->vm_ssize;
692 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
693 		cnt.v_vforks++;
694 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize +
695 		    p2->p_vmspace->vm_ssize;
696 	} else if (p1 == &proc0) {
697 		cnt.v_kthreads++;
698 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize +
699 		    p2->p_vmspace->vm_ssize;
700 	} else {
701 		cnt.v_rforks++;
702 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize +
703 		    p2->p_vmspace->vm_ssize;
704 	}
705 
706 	/*
707 	 * Both processes are set up, now check if any loadable modules want
708 	 * to adjust anything.
709 	 *   What if they have an error? XXX
710 	 */
711 	sx_slock(&fork_list_lock);
712 	TAILQ_FOREACH(ep, &fork_list, next) {
713 		(*ep->function)(p1, p2, flags);
714 	}
715 	sx_sunlock(&fork_list_lock);
716 
717 	/*
718 	 * If RFSTOPPED not requested, make child runnable and add to
719 	 * run queue.
720 	 */
721 	microtime(&(p2->p_stats->p_start));
722 	p2->p_acflag = AFORK;
723 	if ((flags & RFSTOPPED) == 0) {
724 		mtx_lock_spin(&sched_lock);
725 		p2->p_state = PRS_NORMAL;
726 		TD_SET_CAN_RUN(td2);
727 		setrunqueue(td2);
728 		mtx_unlock_spin(&sched_lock);
729 	}
730 
731 	/*
732 	 * Now can be swapped.
733 	 */
734 	PROC_LOCK(p1);
735 	_PRELE(p1);
736 
737 	/*
738 	 * tell any interested parties about the new process
739 	 */
740 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
741 	PROC_UNLOCK(p1);
742 
743 	/*
744 	 * Preserve synchronization semantics of vfork.  If waiting for
745 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
746 	 * proc (in case of exit).
747 	 */
748 	PROC_LOCK(p2);
749 	while (p2->p_flag & P_PPWAIT)
750 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
751 	PROC_UNLOCK(p2);
752 
753 	/*
754 	 * If other threads are waiting, let them continue now
755 	 */
756 	if (p1->p_flag & P_KSES) {
757 		PROC_LOCK(p1);
758 		thread_single_end();
759 		PROC_UNLOCK(p1);
760 	}
761 
762 	/*
763 	 * Return child proc pointer to parent.
764 	 */
765 	*procp = p2;
766 	return (0);
767 fail:
768 	sx_xunlock(&allproc_lock);
769 	uma_zfree(proc_zone, newproc);
770 	if (p1->p_flag & P_KSES) {
771 		PROC_LOCK(p1);
772 		thread_single_end();
773 		PROC_UNLOCK(p1);
774 	}
775 	tsleep(&forksleep, PUSER, "fork", hz / 2);
776 	return (error);
777 }
778 
779 /*
780  * The next two functionms are general routines to handle adding/deleting
781  * items on the fork callout list.
782  *
783  * at_fork():
784  * Take the arguments given and put them onto the fork callout list,
785  * However first make sure that it's not already there.
786  * Returns 0 on success or a standard error number.
787  */
788 
789 int
790 at_fork(function)
791 	forklist_fn function;
792 {
793 	struct forklist *ep;
794 
795 #ifdef INVARIANTS
796 	/* let the programmer know if he's been stupid */
797 	if (rm_at_fork(function))
798 		printf("WARNING: fork callout entry (%p) already present\n",
799 		    function);
800 #endif
801 	ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
802 	if (ep == NULL)
803 		return (ENOMEM);
804 	ep->function = function;
805 	sx_xlock(&fork_list_lock);
806 	TAILQ_INSERT_TAIL(&fork_list, ep, next);
807 	sx_xunlock(&fork_list_lock);
808 	return (0);
809 }
810 
811 /*
812  * Scan the exit callout list for the given item and remove it..
813  * Returns the number of items removed (0 or 1)
814  */
815 
816 int
817 rm_at_fork(function)
818 	forklist_fn function;
819 {
820 	struct forklist *ep;
821 
822 	sx_xlock(&fork_list_lock);
823 	TAILQ_FOREACH(ep, &fork_list, next) {
824 		if (ep->function == function) {
825 			TAILQ_REMOVE(&fork_list, ep, next);
826 			sx_xunlock(&fork_list_lock);
827 			free(ep, M_ATFORK);
828 			return(1);
829 		}
830 	}
831 	sx_xunlock(&fork_list_lock);
832 	return (0);
833 }
834 
835 /*
836  * Handle the return of a child process from fork1().  This function
837  * is called from the MD fork_trampoline() entry point.
838  */
839 void
840 fork_exit(callout, arg, frame)
841 	void (*callout)(void *, struct trapframe *);
842 	void *arg;
843 	struct trapframe *frame;
844 {
845 	struct thread *td;
846 	struct proc *p;
847 
848 	if ((td = PCPU_GET(deadthread))) {
849 		PCPU_SET(deadthread, NULL);
850 		thread_stash(td);
851 	}
852 	td = curthread;
853 	p = td->td_proc;
854 	td->td_kse->ke_oncpu = PCPU_GET(cpuid);
855 	p->p_state = PRS_NORMAL;
856 	/*
857 	 * Finish setting up thread glue.  We need to initialize
858 	 * the thread into a td_critnest=1 state.  Some platforms
859 	 * may have already partially or fully initialized td_critnest
860 	 * and/or td_md.md_savecrit (when applciable).
861 	 *
862 	 * see <arch>/<arch>/critical.c
863 	 */
864 	sched_lock.mtx_lock = (uintptr_t)td;
865 	sched_lock.mtx_recurse = 0;
866 	cpu_critical_fork_exit();
867 	CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
868 	    p->p_comm);
869 	if (PCPU_GET(switchtime.sec) == 0)
870 		binuptime(PCPU_PTR(switchtime));
871 	PCPU_SET(switchticks, ticks);
872 	mtx_unlock_spin(&sched_lock);
873 
874 	/*
875 	 * cpu_set_fork_handler intercepts this function call to
876          * have this call a non-return function to stay in kernel mode.
877          * initproc has its own fork handler, but it does return.
878          */
879 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
880 	callout(arg, frame);
881 
882 	/*
883 	 * Check if a kernel thread misbehaved and returned from its main
884 	 * function.
885 	 */
886 	PROC_LOCK(p);
887 	if (p->p_flag & P_KTHREAD) {
888 		PROC_UNLOCK(p);
889 		mtx_lock(&Giant);
890 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
891 		    p->p_comm, p->p_pid);
892 		kthread_exit(0);
893 	}
894 	PROC_UNLOCK(p);
895 #ifdef DIAGNOSTIC
896 	cred_free_thread(td);
897 #endif
898 	mtx_assert(&Giant, MA_NOTOWNED);
899 }
900 
901 /*
902  * Simplified back end of syscall(), used when returning from fork()
903  * directly into user mode.  Giant is not held on entry, and must not
904  * be held on return.  This function is passed in to fork_exit() as the
905  * first parameter and is called when returning to a new userland process.
906  */
907 void
908 fork_return(td, frame)
909 	struct thread *td;
910 	struct trapframe *frame;
911 {
912 
913 	userret(td, frame, 0);
914 #ifdef KTRACE
915 	if (KTRPOINT(td, KTR_SYSRET))
916 		ktrsysret(SYS_fork, 0, 0);
917 #endif
918 	mtx_assert(&Giant, MA_NOTOWNED);
919 }
920