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