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