xref: /freebsd/sys/kern/kern_fork.c (revision 82431678fce5c893ef9c7418ad6d998ad4187de6)
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_kdtrace.h"
41 #include "opt_ktrace.h"
42 #include "opt_mac.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/eventhandler.h>
48 #include <sys/filedesc.h>
49 #include <sys/kernel.h>
50 #include <sys/kthread.h>
51 #include <sys/sysctl.h>
52 #include <sys/lock.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
55 #include <sys/priv.h>
56 #include <sys/proc.h>
57 #include <sys/jail.h>
58 #include <sys/pioctl.h>
59 #include <sys/resourcevar.h>
60 #include <sys/sched.h>
61 #include <sys/syscall.h>
62 #include <sys/vmmeter.h>
63 #include <sys/vnode.h>
64 #include <sys/acct.h>
65 #include <sys/ktr.h>
66 #include <sys/ktrace.h>
67 #include <sys/unistd.h>
68 #include <sys/sdt.h>
69 #include <sys/sx.h>
70 #include <sys/signalvar.h>
71 #include <sys/vimage.h>
72 
73 #include <security/audit/audit.h>
74 #include <security/mac/mac_framework.h>
75 
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_extern.h>
80 #include <vm/uma.h>
81 
82 #ifdef KDTRACE_HOOKS
83 #include <sys/dtrace_bsd.h>
84 dtrace_fork_func_t	dtrace_fasttrap_fork;
85 #endif
86 
87 SDT_PROVIDER_DECLARE(proc);
88 SDT_PROBE_DEFINE(proc, kernel, , create);
89 SDT_PROBE_ARGTYPE(proc, kernel, , create, 0, "struct proc *");
90 SDT_PROBE_ARGTYPE(proc, kernel, , create, 1, "struct proc *");
91 SDT_PROBE_ARGTYPE(proc, kernel, , create, 2, "int");
92 
93 #ifndef _SYS_SYSPROTO_H_
94 struct fork_args {
95 	int     dummy;
96 };
97 #endif
98 
99 /* ARGSUSED */
100 int
101 fork(td, uap)
102 	struct thread *td;
103 	struct fork_args *uap;
104 {
105 	int error;
106 	struct proc *p2;
107 
108 	error = fork1(td, RFFDG | RFPROC, 0, &p2);
109 	if (error == 0) {
110 		td->td_retval[0] = p2->p_pid;
111 		td->td_retval[1] = 0;
112 	}
113 	return (error);
114 }
115 
116 /* ARGSUSED */
117 int
118 vfork(td, uap)
119 	struct thread *td;
120 	struct vfork_args *uap;
121 {
122 	int error, flags;
123 	struct proc *p2;
124 
125 #ifdef XEN
126 	flags = RFFDG | RFPROC; /* validate that this is still an issue */
127 #else
128 	flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
129 #endif
130 	error = fork1(td, flags, 0, &p2);
131 	if (error == 0) {
132 		td->td_retval[0] = p2->p_pid;
133 		td->td_retval[1] = 0;
134 	}
135 	return (error);
136 }
137 
138 int
139 rfork(td, uap)
140 	struct thread *td;
141 	struct rfork_args *uap;
142 {
143 	struct proc *p2;
144 	int error;
145 
146 	/* Don't allow kernel-only flags. */
147 	if ((uap->flags & RFKERNELONLY) != 0)
148 		return (EINVAL);
149 
150 	AUDIT_ARG(fflags, uap->flags);
151 	error = fork1(td, uap->flags, 0, &p2);
152 	if (error == 0) {
153 		td->td_retval[0] = p2 ? p2->p_pid : 0;
154 		td->td_retval[1] = 0;
155 	}
156 	return (error);
157 }
158 
159 int	nprocs = 1;		/* process 0 */
160 int	lastpid = 0;
161 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
162     "Last used PID");
163 
164 /*
165  * Random component to lastpid generation.  We mix in a random factor to make
166  * it a little harder to predict.  We sanity check the modulus value to avoid
167  * doing it in critical paths.  Don't let it be too small or we pointlessly
168  * waste randomness entropy, and don't let it be impossibly large.  Using a
169  * modulus that is too big causes a LOT more process table scans and slows
170  * down fork processing as the pidchecked caching is defeated.
171  */
172 static int randompid = 0;
173 
174 static int
175 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
176 {
177 	int error, pid;
178 
179 	error = sysctl_wire_old_buffer(req, sizeof(int));
180 	if (error != 0)
181 		return(error);
182 	sx_xlock(&allproc_lock);
183 	pid = randompid;
184 	error = sysctl_handle_int(oidp, &pid, 0, req);
185 	if (error == 0 && req->newptr != NULL) {
186 		if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
187 			pid = PID_MAX - 100;
188 		else if (pid < 2)			/* NOP */
189 			pid = 0;
190 		else if (pid < 100)			/* Make it reasonable */
191 			pid = 100;
192 		randompid = pid;
193 	}
194 	sx_xunlock(&allproc_lock);
195 	return (error);
196 }
197 
198 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
199     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
200 
201 int
202 fork1(td, flags, pages, procp)
203 	struct thread *td;
204 	int flags;
205 	int pages;
206 	struct proc **procp;
207 {
208 	struct proc *p1, *p2, *pptr;
209 	struct proc *newproc;
210 	int ok, trypid;
211 	static int curfail, pidchecked = 0;
212 	static struct timeval lastfail;
213 	struct filedesc *fd;
214 	struct filedesc_to_leader *fdtol;
215 	struct thread *td2;
216 	struct sigacts *newsigacts;
217 	struct vmspace *vm2;
218 	int error;
219 
220 	/* Can't copy and clear. */
221 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
222 		return (EINVAL);
223 
224 	p1 = td->td_proc;
225 
226 	/*
227 	 * Here we don't create a new process, but we divorce
228 	 * certain parts of a process from itself.
229 	 */
230 	if ((flags & RFPROC) == 0) {
231 		if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
232 		    (flags & (RFCFDG | RFFDG))) {
233 			PROC_LOCK(p1);
234 			if (thread_single(SINGLE_BOUNDARY)) {
235 				PROC_UNLOCK(p1);
236 				return (ERESTART);
237 			}
238 			PROC_UNLOCK(p1);
239 		}
240 
241 		error = vm_forkproc(td, NULL, NULL, NULL, flags);
242 		if (error)
243 			goto norfproc_fail;
244 
245 		/*
246 		 * Close all file descriptors.
247 		 */
248 		if (flags & RFCFDG) {
249 			struct filedesc *fdtmp;
250 			fdtmp = fdinit(td->td_proc->p_fd);
251 			fdfree(td);
252 			p1->p_fd = fdtmp;
253 		}
254 
255 		/*
256 		 * Unshare file descriptors (from parent).
257 		 */
258 		if (flags & RFFDG)
259 			fdunshare(p1, td);
260 
261 norfproc_fail:
262 		if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
263 		    (flags & (RFCFDG | RFFDG))) {
264 			PROC_LOCK(p1);
265 			thread_single_end();
266 			PROC_UNLOCK(p1);
267 		}
268 		*procp = NULL;
269 		return (error);
270 	}
271 
272 	/*
273 	 * XXX
274 	 * We did have single-threading code here
275 	 * however it proved un-needed and caused problems
276 	 */
277 
278 	vm2 = NULL;
279 	/* Allocate new proc. */
280 	newproc = uma_zalloc(proc_zone, M_WAITOK);
281 	if (TAILQ_EMPTY(&newproc->p_threads)) {
282 		td2 = thread_alloc();
283 		if (td2 == NULL) {
284 			error = ENOMEM;
285 			goto fail1;
286 		}
287 		proc_linkup(newproc, td2);
288 	} else
289 		td2 = FIRST_THREAD_IN_PROC(newproc);
290 
291 	/* Allocate and switch to an alternate kstack if specified. */
292 	if (pages != 0) {
293 		if (!vm_thread_new_altkstack(td2, pages)) {
294 			error = ENOMEM;
295 			goto fail1;
296 		}
297 	}
298 	if ((flags & RFMEM) == 0) {
299 		vm2 = vmspace_fork(p1->p_vmspace);
300 		if (vm2 == NULL) {
301 			error = ENOMEM;
302 			goto fail1;
303 		}
304 	}
305 #ifdef MAC
306 	mac_proc_init(newproc);
307 #endif
308 	knlist_init(&newproc->p_klist, &newproc->p_mtx, NULL, NULL, NULL);
309 	STAILQ_INIT(&newproc->p_ktr);
310 
311 	/* We have to lock the process tree while we look for a pid. */
312 	sx_slock(&proctree_lock);
313 
314 	/*
315 	 * Although process entries are dynamically created, we still keep
316 	 * a global limit on the maximum number we will create.  Don't allow
317 	 * a nonprivileged user to use the last ten processes; don't let root
318 	 * exceed the limit. The variable nprocs is the current number of
319 	 * processes, maxproc is the limit.
320 	 */
321 	sx_xlock(&allproc_lock);
322 	if ((nprocs >= maxproc - 10 && priv_check_cred(td->td_ucred,
323 	    PRIV_MAXPROC, 0) != 0) || nprocs >= maxproc) {
324 		error = EAGAIN;
325 		goto fail;
326 	}
327 
328 	/*
329 	 * Increment the count of procs running with this uid. Don't allow
330 	 * a nonprivileged user to exceed their current limit.
331 	 *
332 	 * XXXRW: Can we avoid privilege here if it's not needed?
333 	 */
334 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
335 	if (error == 0)
336 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
337 	else {
338 		PROC_LOCK(p1);
339 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
340 		    lim_cur(p1, RLIMIT_NPROC));
341 		PROC_UNLOCK(p1);
342 	}
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 #ifdef VIMAGE
354 	P_TO_VPROCG(p1)->nprocs++;
355 #endif
356 
357 	/*
358 	 * Find an unused process ID.  We remember a range of unused IDs
359 	 * ready to use (from lastpid+1 through pidchecked-1).
360 	 *
361 	 * If RFHIGHPID is set (used during system boot), do not allocate
362 	 * low-numbered pids.
363 	 */
364 	trypid = lastpid + 1;
365 	if (flags & RFHIGHPID) {
366 		if (trypid < 10)
367 			trypid = 10;
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 			while (p2->p_pid == trypid ||
397 			    (p2->p_pgrp != NULL &&
398 			    (p2->p_pgrp->pg_id == trypid ||
399 			    (p2->p_session != NULL &&
400 			    p2->p_session->s_sid == trypid)))) {
401 				trypid++;
402 				if (trypid >= pidchecked)
403 					goto retry;
404 			}
405 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
406 				pidchecked = p2->p_pid;
407 			if (p2->p_pgrp != NULL) {
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 != NULL &&
412 				    p2->p_session->s_sid > trypid &&
413 				    pidchecked > p2->p_session->s_sid)
414 					pidchecked = p2->p_session->s_sid;
415 			}
416 		}
417 		if (!doingzomb) {
418 			doingzomb = 1;
419 			p2 = LIST_FIRST(&zombproc);
420 			goto again;
421 		}
422 	}
423 	sx_sunlock(&proctree_lock);
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 	/*
437 	 * Allow the scheduler to initialize the child.
438 	 */
439 	thread_lock(td);
440 	sched_fork(td, td2);
441 	thread_unlock(td);
442 	AUDIT_ARG(pid, p2->p_pid);
443 	LIST_INSERT_HEAD(&allproc, p2, p_list);
444 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
445 
446 	PROC_LOCK(p2);
447 	PROC_LOCK(p1);
448 
449 	sx_xunlock(&allproc_lock);
450 
451 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
452 	    __rangeof(struct proc, p_startcopy, p_endcopy));
453 	pargs_hold(p2->p_args);
454 	PROC_UNLOCK(p1);
455 
456 	bzero(&p2->p_startzero,
457 	    __rangeof(struct proc, p_startzero, p_endzero));
458 
459 	p2->p_ucred = crhold(td->td_ucred);
460 
461 	/* In case we are jailed tell the prison that we exist. */
462 	if (jailed(p2->p_ucred))
463 		prison_proc_hold(p2->p_ucred->cr_prison);
464 
465 	PROC_UNLOCK(p2);
466 
467 	/*
468 	 * Malloc things while we don't hold any locks.
469 	 */
470 	if (flags & RFSIGSHARE)
471 		newsigacts = NULL;
472 	else
473 		newsigacts = sigacts_alloc();
474 
475 	/*
476 	 * Copy filedesc.
477 	 */
478 	if (flags & RFCFDG) {
479 		fd = fdinit(p1->p_fd);
480 		fdtol = NULL;
481 	} else if (flags & RFFDG) {
482 		fd = fdcopy(p1->p_fd);
483 		fdtol = NULL;
484 	} else {
485 		fd = fdshare(p1->p_fd);
486 		if (p1->p_fdtol == NULL)
487 			p1->p_fdtol =
488 				filedesc_to_leader_alloc(NULL,
489 							 NULL,
490 							 p1->p_leader);
491 		if ((flags & RFTHREAD) != 0) {
492 			/*
493 			 * Shared file descriptor table and
494 			 * shared process leaders.
495 			 */
496 			fdtol = p1->p_fdtol;
497 			FILEDESC_XLOCK(p1->p_fd);
498 			fdtol->fdl_refcount++;
499 			FILEDESC_XUNLOCK(p1->p_fd);
500 		} else {
501 			/*
502 			 * Shared file descriptor table, and
503 			 * different process leaders
504 			 */
505 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
506 							 p1->p_fd,
507 							 p2);
508 		}
509 	}
510 	/*
511 	 * Make a proc table entry for the new process.
512 	 * Start by zeroing the section of proc that is zero-initialized,
513 	 * then copy the section that is copied directly from the parent.
514 	 */
515 
516 	PROC_LOCK(p2);
517 	PROC_LOCK(p1);
518 
519 	bzero(&td2->td_startzero,
520 	    __rangeof(struct thread, td_startzero, td_endzero));
521 
522 	bcopy(&td->td_startcopy, &td2->td_startcopy,
523 	    __rangeof(struct thread, td_startcopy, td_endcopy));
524 
525 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
526 	td2->td_sigstk = td->td_sigstk;
527 	td2->td_sigmask = td->td_sigmask;
528 	td2->td_flags = TDF_INMEM;
529 
530 #ifdef VIMAGE
531 	td2->td_vnet = NULL;
532 	td2->td_vnet_lpush = NULL;
533 #endif
534 
535 	/*
536 	 * Duplicate sub-structures as needed.
537 	 * Increase reference counts on shared objects.
538 	 */
539 	p2->p_flag = P_INMEM;
540 	p2->p_swtick = ticks;
541 	if (p1->p_flag & P_PROFIL)
542 		startprofclock(p2);
543 	td2->td_ucred = crhold(p2->p_ucred);
544 
545 	if (flags & RFSIGSHARE) {
546 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
547 	} else {
548 		sigacts_copy(newsigacts, p1->p_sigacts);
549 		p2->p_sigacts = newsigacts;
550 	}
551 	if (flags & RFLINUXTHPN)
552 	        p2->p_sigparent = SIGUSR1;
553 	else
554 	        p2->p_sigparent = SIGCHLD;
555 
556 	p2->p_textvp = p1->p_textvp;
557 	p2->p_fd = fd;
558 	p2->p_fdtol = fdtol;
559 
560 	/*
561 	 * p_limit is copy-on-write.  Bump its refcount.
562 	 */
563 	lim_fork(p1, p2);
564 
565 	pstats_fork(p1->p_stats, p2->p_stats);
566 
567 	PROC_UNLOCK(p1);
568 	PROC_UNLOCK(p2);
569 
570 	/* Bump references to the text vnode (for procfs) */
571 	if (p2->p_textvp)
572 		vref(p2->p_textvp);
573 
574 	/*
575 	 * Set up linkage for kernel based threading.
576 	 */
577 	if ((flags & RFTHREAD) != 0) {
578 		mtx_lock(&ppeers_lock);
579 		p2->p_peers = p1->p_peers;
580 		p1->p_peers = p2;
581 		p2->p_leader = p1->p_leader;
582 		mtx_unlock(&ppeers_lock);
583 		PROC_LOCK(p1->p_leader);
584 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
585 			PROC_UNLOCK(p1->p_leader);
586 			/*
587 			 * The task leader is exiting, so process p1 is
588 			 * going to be killed shortly.  Since p1 obviously
589 			 * isn't dead yet, we know that the leader is either
590 			 * sending SIGKILL's to all the processes in this
591 			 * task or is sleeping waiting for all the peers to
592 			 * exit.  We let p1 complete the fork, but we need
593 			 * to go ahead and kill the new process p2 since
594 			 * the task leader may not get a chance to send
595 			 * SIGKILL to it.  We leave it on the list so that
596 			 * the task leader will wait for this new process
597 			 * to commit suicide.
598 			 */
599 			PROC_LOCK(p2);
600 			psignal(p2, SIGKILL);
601 			PROC_UNLOCK(p2);
602 		} else
603 			PROC_UNLOCK(p1->p_leader);
604 	} else {
605 		p2->p_peers = NULL;
606 		p2->p_leader = p2;
607 	}
608 
609 	sx_xlock(&proctree_lock);
610 	PGRP_LOCK(p1->p_pgrp);
611 	PROC_LOCK(p2);
612 	PROC_LOCK(p1);
613 
614 	/*
615 	 * Preserve some more flags in subprocess.  P_PROFIL has already
616 	 * been preserved.
617 	 */
618 	p2->p_flag |= p1->p_flag & P_SUGID;
619 	td2->td_pflags |= td->td_pflags & TDP_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 	p2->p_pgrp = p1->p_pgrp;
628 	LIST_INSERT_AFTER(p1, p2, p_pglist);
629 	PGRP_UNLOCK(p1->p_pgrp);
630 	LIST_INIT(&p2->p_children);
631 
632 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
633 
634 #ifdef KTRACE
635 	/*
636 	 * Copy traceflag and tracefile if enabled.
637 	 */
638 	mtx_lock(&ktrace_mtx);
639 	KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
640 	if (p1->p_traceflag & KTRFAC_INHERIT) {
641 		p2->p_traceflag = p1->p_traceflag;
642 		if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
643 			VREF(p2->p_tracevp);
644 			KASSERT(p1->p_tracecred != NULL,
645 			    ("ktrace vnode with no cred"));
646 			p2->p_tracecred = crhold(p1->p_tracecred);
647 		}
648 	}
649 	mtx_unlock(&ktrace_mtx);
650 #endif
651 
652 	/*
653 	 * If PF_FORK is set, the child process inherits the
654 	 * procfs ioctl flags from its parent.
655 	 */
656 	if (p1->p_pfsflags & PF_FORK) {
657 		p2->p_stops = p1->p_stops;
658 		p2->p_pfsflags = p1->p_pfsflags;
659 	}
660 
661 #ifdef KDTRACE_HOOKS
662 	/*
663 	 * Tell the DTrace fasttrap provider about the new process
664 	 * if it has registered an interest.
665 	 */
666 	if (dtrace_fasttrap_fork)
667 		dtrace_fasttrap_fork(p1, p2);
668 #endif
669 
670 	/*
671 	 * This begins the section where we must prevent the parent
672 	 * from being swapped.
673 	 */
674 	_PHOLD(p1);
675 	PROC_UNLOCK(p1);
676 
677 	/*
678 	 * Attach the new process to its parent.
679 	 *
680 	 * If RFNOWAIT is set, the newly created process becomes a child
681 	 * of init.  This effectively disassociates the child from the
682 	 * parent.
683 	 */
684 	if (flags & RFNOWAIT)
685 		pptr = initproc;
686 	else
687 		pptr = p1;
688 	p2->p_pptr = pptr;
689 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
690 	sx_xunlock(&proctree_lock);
691 
692 	/* Inform accounting that we have forked. */
693 	p2->p_acflag = AFORK;
694 	PROC_UNLOCK(p2);
695 
696 	/*
697 	 * Finish creating the child process.  It will return via a different
698 	 * execution path later.  (ie: directly into user mode)
699 	 */
700 	vm_forkproc(td, p2, td2, vm2, flags);
701 
702 	if (flags == (RFFDG | RFPROC)) {
703 		PCPU_INC(cnt.v_forks);
704 		PCPU_ADD(cnt.v_forkpages, p2->p_vmspace->vm_dsize +
705 		    p2->p_vmspace->vm_ssize);
706 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
707 		PCPU_INC(cnt.v_vforks);
708 		PCPU_ADD(cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
709 		    p2->p_vmspace->vm_ssize);
710 	} else if (p1 == &proc0) {
711 		PCPU_INC(cnt.v_kthreads);
712 		PCPU_ADD(cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
713 		    p2->p_vmspace->vm_ssize);
714 	} else {
715 		PCPU_INC(cnt.v_rforks);
716 		PCPU_ADD(cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
717 		    p2->p_vmspace->vm_ssize);
718 	}
719 
720 	/*
721 	 * Both processes are set up, now check if any loadable modules want
722 	 * to adjust anything.
723 	 *   What if they have an error? XXX
724 	 */
725 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
726 
727 	/*
728 	 * Set the child start time and mark the process as being complete.
729 	 */
730 	microuptime(&p2->p_stats->p_start);
731 	PROC_SLOCK(p2);
732 	p2->p_state = PRS_NORMAL;
733 	PROC_SUNLOCK(p2);
734 
735 	/*
736 	 * If RFSTOPPED not requested, make child runnable and add to
737 	 * run queue.
738 	 */
739 	if ((flags & RFSTOPPED) == 0) {
740 		thread_lock(td2);
741 		TD_SET_CAN_RUN(td2);
742 		sched_add(td2, SRQ_BORING);
743 		thread_unlock(td2);
744 	}
745 
746 	/*
747 	 * Now can be swapped.
748 	 */
749 	PROC_LOCK(p1);
750 	_PRELE(p1);
751 	PROC_UNLOCK(p1);
752 
753 	/*
754 	 * Tell any interested parties about the new process.
755 	 */
756 	knote_fork(&p1->p_klist, p2->p_pid);
757 	SDT_PROBE(proc, kernel, , create, p2, p1, flags, 0, 0);
758 
759 	/*
760 	 * Preserve synchronization semantics of vfork.  If waiting for
761 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
762 	 * proc (in case of exit).
763 	 */
764 	PROC_LOCK(p2);
765 	while (p2->p_flag & P_PPWAIT)
766 		cv_wait(&p2->p_pwait, &p2->p_mtx);
767 	PROC_UNLOCK(p2);
768 
769 	/*
770 	 * Return child proc pointer to parent.
771 	 */
772 	*procp = p2;
773 	return (0);
774 fail:
775 	sx_sunlock(&proctree_lock);
776 	if (ppsratecheck(&lastfail, &curfail, 1))
777 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
778 		    td->td_ucred->cr_ruid);
779 	sx_xunlock(&allproc_lock);
780 #ifdef MAC
781 	mac_proc_destroy(newproc);
782 #endif
783 fail1:
784 	if (vm2 != NULL)
785 		vmspace_free(vm2);
786 	uma_zfree(proc_zone, newproc);
787 	pause("fork", hz / 2);
788 	return (error);
789 }
790 
791 /*
792  * Handle the return of a child process from fork1().  This function
793  * is called from the MD fork_trampoline() entry point.
794  */
795 void
796 fork_exit(callout, arg, frame)
797 	void (*callout)(void *, struct trapframe *);
798 	void *arg;
799 	struct trapframe *frame;
800 {
801 	struct proc *p;
802 	struct thread *td;
803 	struct thread *dtd;
804 
805 	td = curthread;
806 	p = td->td_proc;
807 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
808 
809 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
810 		td, td->td_sched, p->p_pid, td->td_name);
811 
812 	sched_fork_exit(td);
813 	/*
814 	* Processes normally resume in mi_switch() after being
815 	* cpu_switch()'ed to, but when children start up they arrive here
816 	* instead, so we must do much the same things as mi_switch() would.
817 	*/
818 	if ((dtd = PCPU_GET(deadthread))) {
819 		PCPU_SET(deadthread, NULL);
820 		thread_stash(dtd);
821 	}
822 	thread_unlock(td);
823 
824 	/*
825 	 * cpu_set_fork_handler intercepts this function call to
826 	 * have this call a non-return function to stay in kernel mode.
827 	 * initproc has its own fork handler, but it does return.
828 	 */
829 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
830 	callout(arg, frame);
831 
832 	/*
833 	 * Check if a kernel thread misbehaved and returned from its main
834 	 * function.
835 	 */
836 	if (p->p_flag & P_KTHREAD) {
837 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
838 		    td->td_name, p->p_pid);
839 		kproc_exit(0);
840 	}
841 	mtx_assert(&Giant, MA_NOTOWNED);
842 
843 	EVENTHANDLER_INVOKE(schedtail, p);
844 }
845 
846 /*
847  * Simplified back end of syscall(), used when returning from fork()
848  * directly into user mode.  Giant is not held on entry, and must not
849  * be held on return.  This function is passed in to fork_exit() as the
850  * first parameter and is called when returning to a new userland process.
851  */
852 void
853 fork_return(td, frame)
854 	struct thread *td;
855 	struct trapframe *frame;
856 {
857 
858 	userret(td, frame);
859 #ifdef KTRACE
860 	if (KTRPOINT(td, KTR_SYSRET))
861 		ktrsysret(SYS_fork, 0, 0);
862 #endif
863 	mtx_assert(&Giant, MA_NOTOWNED);
864 }
865