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