xref: /freebsd/sys/kern/kern_fork.c (revision 050570efa79efcc9cf5adeb545f1a679c8dc377b)
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(struct thread *td, struct vfork_args *uap)
116 {
117 	int error, flags;
118 	struct proc *p2;
119 
120 #ifdef XEN
121 	flags = RFFDG | RFPROC; /* validate that this is still an issue */
122 #else
123 	flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
124 #endif
125 	error = fork1(td, flags, 0, &p2);
126 	if (error == 0) {
127 		td->td_retval[0] = p2->p_pid;
128 		td->td_retval[1] = 0;
129 	}
130 	return (error);
131 }
132 
133 int
134 rfork(struct thread *td, struct rfork_args *uap)
135 {
136 	struct proc *p2;
137 	int error;
138 
139 	/* Don't allow kernel-only flags. */
140 	if ((uap->flags & RFKERNELONLY) != 0)
141 		return (EINVAL);
142 
143 	AUDIT_ARG_FFLAGS(uap->flags);
144 	error = fork1(td, uap->flags, 0, &p2);
145 	if (error == 0) {
146 		td->td_retval[0] = p2 ? p2->p_pid : 0;
147 		td->td_retval[1] = 0;
148 	}
149 	return (error);
150 }
151 
152 int	nprocs = 1;		/* process 0 */
153 int	lastpid = 0;
154 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
155     "Last used PID");
156 
157 /*
158  * Random component to lastpid generation.  We mix in a random factor to make
159  * it a little harder to predict.  We sanity check the modulus value to avoid
160  * doing it in critical paths.  Don't let it be too small or we pointlessly
161  * waste randomness entropy, and don't let it be impossibly large.  Using a
162  * modulus that is too big causes a LOT more process table scans and slows
163  * down fork processing as the pidchecked caching is defeated.
164  */
165 static int randompid = 0;
166 
167 static int
168 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
169 {
170 	int error, pid;
171 
172 	error = sysctl_wire_old_buffer(req, sizeof(int));
173 	if (error != 0)
174 		return(error);
175 	sx_xlock(&allproc_lock);
176 	pid = randompid;
177 	error = sysctl_handle_int(oidp, &pid, 0, req);
178 	if (error == 0 && req->newptr != NULL) {
179 		if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
180 			pid = PID_MAX - 100;
181 		else if (pid < 2)			/* NOP */
182 			pid = 0;
183 		else if (pid < 100)			/* Make it reasonable */
184 			pid = 100;
185 		randompid = pid;
186 	}
187 	sx_xunlock(&allproc_lock);
188 	return (error);
189 }
190 
191 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
192     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
193 
194 static int
195 fork_findpid(int flags)
196 {
197 	struct proc *p;
198 	int trypid;
199 	static int pidchecked = 0;
200 
201 	/*
202 	 * Requires allproc_lock in order to iterate over the list
203 	 * of processes, and proctree_lock to access p_pgrp.
204 	 */
205 	sx_assert(&allproc_lock, SX_LOCKED);
206 	sx_assert(&proctree_lock, SX_LOCKED);
207 
208 	/*
209 	 * Find an unused process ID.  We remember a range of unused IDs
210 	 * ready to use (from lastpid+1 through pidchecked-1).
211 	 *
212 	 * If RFHIGHPID is set (used during system boot), do not allocate
213 	 * low-numbered pids.
214 	 */
215 	trypid = lastpid + 1;
216 	if (flags & RFHIGHPID) {
217 		if (trypid < 10)
218 			trypid = 10;
219 	} else {
220 		if (randompid)
221 			trypid += arc4random() % randompid;
222 	}
223 retry:
224 	/*
225 	 * If the process ID prototype has wrapped around,
226 	 * restart somewhat above 0, as the low-numbered procs
227 	 * tend to include daemons that don't exit.
228 	 */
229 	if (trypid >= PID_MAX) {
230 		trypid = trypid % PID_MAX;
231 		if (trypid < 100)
232 			trypid += 100;
233 		pidchecked = 0;
234 	}
235 	if (trypid >= pidchecked) {
236 		int doingzomb = 0;
237 
238 		pidchecked = PID_MAX;
239 		/*
240 		 * Scan the active and zombie procs to check whether this pid
241 		 * is in use.  Remember the lowest pid that's greater
242 		 * than trypid, so we can avoid checking for a while.
243 		 */
244 		p = LIST_FIRST(&allproc);
245 again:
246 		for (; p != NULL; p = LIST_NEXT(p, p_list)) {
247 			while (p->p_pid == trypid ||
248 			    (p->p_pgrp != NULL &&
249 			    (p->p_pgrp->pg_id == trypid ||
250 			    (p->p_session != NULL &&
251 			    p->p_session->s_sid == trypid)))) {
252 				trypid++;
253 				if (trypid >= pidchecked)
254 					goto retry;
255 			}
256 			if (p->p_pid > trypid && pidchecked > p->p_pid)
257 				pidchecked = p->p_pid;
258 			if (p->p_pgrp != NULL) {
259 				if (p->p_pgrp->pg_id > trypid &&
260 				    pidchecked > p->p_pgrp->pg_id)
261 					pidchecked = p->p_pgrp->pg_id;
262 				if (p->p_session != NULL &&
263 				    p->p_session->s_sid > trypid &&
264 				    pidchecked > p->p_session->s_sid)
265 					pidchecked = p->p_session->s_sid;
266 			}
267 		}
268 		if (!doingzomb) {
269 			doingzomb = 1;
270 			p = LIST_FIRST(&zombproc);
271 			goto again;
272 		}
273 	}
274 
275 	/*
276 	 * RFHIGHPID does not mess with the lastpid counter during boot.
277 	 */
278 	if (flags & RFHIGHPID)
279 		pidchecked = 0;
280 	else
281 		lastpid = trypid;
282 
283 	return (trypid);
284 }
285 
286 static int
287 fork_norfproc(struct thread *td, int flags)
288 {
289 	int error;
290 	struct proc *p1;
291 
292 	KASSERT((flags & RFPROC) == 0,
293 	    ("fork_norfproc called with RFPROC set"));
294 	p1 = td->td_proc;
295 
296 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
297 	    (flags & (RFCFDG | RFFDG))) {
298 		PROC_LOCK(p1);
299 		if (thread_single(SINGLE_BOUNDARY)) {
300 			PROC_UNLOCK(p1);
301 			return (ERESTART);
302 		}
303 		PROC_UNLOCK(p1);
304 	}
305 
306 	error = vm_forkproc(td, NULL, NULL, NULL, flags);
307 	if (error)
308 		goto fail;
309 
310 	/*
311 	 * Close all file descriptors.
312 	 */
313 	if (flags & RFCFDG) {
314 		struct filedesc *fdtmp;
315 		fdtmp = fdinit(td->td_proc->p_fd);
316 		fdfree(td);
317 		p1->p_fd = fdtmp;
318 	}
319 
320 	/*
321 	 * Unshare file descriptors (from parent).
322 	 */
323 	if (flags & RFFDG)
324 		fdunshare(p1, td);
325 
326 fail:
327 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
328 	    (flags & (RFCFDG | RFFDG))) {
329 		PROC_LOCK(p1);
330 		thread_single_end();
331 		PROC_UNLOCK(p1);
332 	}
333 	return (error);
334 }
335 
336 static void
337 do_fork(struct thread *td, int flags, struct proc *p2, struct thread *td2,
338     struct vmspace *vm2)
339 {
340 	struct proc *p1, *pptr;
341 	int trypid;
342 	struct filedesc *fd;
343 	struct filedesc_to_leader *fdtol;
344 	struct sigacts *newsigacts;
345 
346 	sx_assert(&proctree_lock, SX_SLOCKED);
347 	sx_assert(&allproc_lock, SX_XLOCKED);
348 
349 	p1 = td->td_proc;
350 
351 	/*
352 	 * Increment the nprocs resource before blocking can occur.  There
353 	 * are hard-limits as to the number of processes that can run.
354 	 */
355 	nprocs++;
356 
357 	trypid = fork_findpid(flags);
358 
359 	sx_sunlock(&proctree_lock);
360 
361 	p2->p_state = PRS_NEW;		/* protect against others */
362 	p2->p_pid = trypid;
363 	AUDIT_ARG_PID(p2->p_pid);
364 	LIST_INSERT_HEAD(&allproc, p2, p_list);
365 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
366 	tidhash_add(td2);
367 	PROC_LOCK(p2);
368 	PROC_LOCK(p1);
369 
370 	sx_xunlock(&allproc_lock);
371 
372 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
373 	    __rangeof(struct proc, p_startcopy, p_endcopy));
374 	pargs_hold(p2->p_args);
375 	PROC_UNLOCK(p1);
376 
377 	bzero(&p2->p_startzero,
378 	    __rangeof(struct proc, p_startzero, p_endzero));
379 
380 	p2->p_ucred = crhold(td->td_ucred);
381 
382 	/* Tell the prison that we exist. */
383 	prison_proc_hold(p2->p_ucred->cr_prison);
384 
385 	PROC_UNLOCK(p2);
386 
387 	/*
388 	 * Malloc things while we don't hold any locks.
389 	 */
390 	if (flags & RFSIGSHARE)
391 		newsigacts = NULL;
392 	else
393 		newsigacts = sigacts_alloc();
394 
395 	/*
396 	 * Copy filedesc.
397 	 */
398 	if (flags & RFCFDG) {
399 		fd = fdinit(p1->p_fd);
400 		fdtol = NULL;
401 	} else if (flags & RFFDG) {
402 		fd = fdcopy(p1->p_fd);
403 		fdtol = NULL;
404 	} else {
405 		fd = fdshare(p1->p_fd);
406 		if (p1->p_fdtol == NULL)
407 			p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL,
408 			    p1->p_leader);
409 		if ((flags & RFTHREAD) != 0) {
410 			/*
411 			 * Shared file descriptor table, and shared
412 			 * process leaders.
413 			 */
414 			fdtol = p1->p_fdtol;
415 			FILEDESC_XLOCK(p1->p_fd);
416 			fdtol->fdl_refcount++;
417 			FILEDESC_XUNLOCK(p1->p_fd);
418 		} else {
419 			/*
420 			 * Shared file descriptor table, and different
421 			 * process leaders.
422 			 */
423 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
424 			    p1->p_fd, p2);
425 		}
426 	}
427 	/*
428 	 * Make a proc table entry for the new process.
429 	 * Start by zeroing the section of proc that is zero-initialized,
430 	 * then copy the section that is copied directly from the parent.
431 	 */
432 
433 	PROC_LOCK(p2);
434 	PROC_LOCK(p1);
435 
436 	bzero(&td2->td_startzero,
437 	    __rangeof(struct thread, td_startzero, td_endzero));
438 
439 	bcopy(&td->td_startcopy, &td2->td_startcopy,
440 	    __rangeof(struct thread, td_startcopy, td_endcopy));
441 
442 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
443 	td2->td_sigstk = td->td_sigstk;
444 	td2->td_sigmask = td->td_sigmask;
445 	td2->td_flags = TDF_INMEM;
446 	td2->td_lend_user_pri = PRI_MAX;
447 
448 #ifdef VIMAGE
449 	td2->td_vnet = NULL;
450 	td2->td_vnet_lpush = NULL;
451 #endif
452 
453 	/*
454 	 * Allow the scheduler to initialize the child.
455 	 */
456 	thread_lock(td);
457 	sched_fork(td, td2);
458 	thread_unlock(td);
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 	 */
626 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
627 
628 	/*
629 	 * Set the child start time and mark the process as being complete.
630 	 */
631 	microuptime(&p2->p_stats->p_start);
632 	PROC_SLOCK(p2);
633 	p2->p_state = PRS_NORMAL;
634 	PROC_SUNLOCK(p2);
635 #ifdef KDTRACE_HOOKS
636 	/*
637 	 * Tell the DTrace fasttrap provider about the new process
638 	 * if it has registered an interest. We have to do this only after
639 	 * p_state is PRS_NORMAL since the fasttrap module will use pfind()
640 	 * later on.
641 	 */
642 	if (dtrace_fasttrap_fork) {
643 		PROC_LOCK(p1);
644 		PROC_LOCK(p2);
645 		dtrace_fasttrap_fork(p1, p2);
646 		PROC_UNLOCK(p2);
647 		PROC_UNLOCK(p1);
648 	}
649 #endif
650 
651 	/*
652 	 * If RFSTOPPED not requested, make child runnable and add to
653 	 * run queue.
654 	 */
655 	if ((flags & RFSTOPPED) == 0) {
656 		thread_lock(td2);
657 		TD_SET_CAN_RUN(td2);
658 		sched_add(td2, SRQ_BORING);
659 		thread_unlock(td2);
660 	}
661 
662 	/*
663 	 * Now can be swapped.
664 	 */
665 	PROC_LOCK(p1);
666 	_PRELE(p1);
667 	PROC_UNLOCK(p1);
668 
669 	/*
670 	 * Tell any interested parties about the new process.
671 	 */
672 	knote_fork(&p1->p_klist, p2->p_pid);
673 	SDT_PROBE(proc, kernel, , create, p2, p1, flags, 0, 0);
674 
675 	/*
676 	 * Preserve synchronization semantics of vfork.  If waiting for
677 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
678 	 * proc (in case of exit).
679 	 */
680 	PROC_LOCK(p2);
681 	while (p2->p_flag & P_PPWAIT)
682 		cv_wait(&p2->p_pwait, &p2->p_mtx);
683 	PROC_UNLOCK(p2);
684 }
685 
686 int
687 fork1(struct thread *td, int flags, int pages, struct proc **procp)
688 {
689 	struct proc *p1;
690 	struct proc *newproc;
691 	int ok;
692 	struct thread *td2;
693 	struct vmspace *vm2;
694 	vm_ooffset_t mem_charged;
695 	int error;
696 	static int curfail;
697 	static struct timeval lastfail;
698 
699 	/* Can't copy and clear. */
700 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
701 		return (EINVAL);
702 
703 	p1 = td->td_proc;
704 
705 	/*
706 	 * Here we don't create a new process, but we divorce
707 	 * certain parts of a process from itself.
708 	 */
709 	if ((flags & RFPROC) == 0) {
710 		*procp = NULL;
711 		return (fork_norfproc(td, flags));
712 	}
713 
714 	mem_charged = 0;
715 	vm2 = NULL;
716 	if (pages == 0)
717 		pages = KSTACK_PAGES;
718 	/* Allocate new proc. */
719 	newproc = uma_zalloc(proc_zone, M_WAITOK);
720 	td2 = FIRST_THREAD_IN_PROC(newproc);
721 	if (td2 == NULL) {
722 		td2 = thread_alloc(pages);
723 		if (td2 == NULL) {
724 			error = ENOMEM;
725 			goto fail1;
726 		}
727 		proc_linkup(newproc, td2);
728 	} else {
729 		if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
730 			if (td2->td_kstack != 0)
731 				vm_thread_dispose(td2);
732 			if (!thread_alloc_stack(td2, pages)) {
733 				error = ENOMEM;
734 				goto fail1;
735 			}
736 		}
737 	}
738 
739 	if ((flags & RFMEM) == 0) {
740 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
741 		if (vm2 == NULL) {
742 			error = ENOMEM;
743 			goto fail1;
744 		}
745 		if (!swap_reserve(mem_charged)) {
746 			/*
747 			 * The swap reservation failed. The accounting
748 			 * from the entries of the copied vm2 will be
749 			 * substracted in vmspace_free(), so force the
750 			 * reservation there.
751 			 */
752 			swap_reserve_force(mem_charged);
753 			error = ENOMEM;
754 			goto fail1;
755 		}
756 	} else
757 		vm2 = NULL;
758 #ifdef MAC
759 	mac_proc_init(newproc);
760 #endif
761 	knlist_init_mtx(&newproc->p_klist, &newproc->p_mtx);
762 	STAILQ_INIT(&newproc->p_ktr);
763 
764 	/* We have to lock the process tree while we look for a pid. */
765 	sx_slock(&proctree_lock);
766 
767 	/*
768 	 * Although process entries are dynamically created, we still keep
769 	 * a global limit on the maximum number we will create.  Don't allow
770 	 * a nonprivileged user to use the last ten processes; don't let root
771 	 * exceed the limit. The variable nprocs is the current number of
772 	 * processes, maxproc is the limit.
773 	 */
774 	sx_xlock(&allproc_lock);
775 	if ((nprocs >= maxproc - 10 && priv_check_cred(td->td_ucred,
776 	    PRIV_MAXPROC, 0) != 0) || nprocs >= maxproc) {
777 		error = EAGAIN;
778 		goto fail;
779 	}
780 
781 	/*
782 	 * Increment the count of procs running with this uid. Don't allow
783 	 * a nonprivileged user to exceed their current limit.
784 	 *
785 	 * XXXRW: Can we avoid privilege here if it's not needed?
786 	 */
787 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
788 	if (error == 0)
789 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
790 	else {
791 		PROC_LOCK(p1);
792 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
793 		    lim_cur(p1, RLIMIT_NPROC));
794 		PROC_UNLOCK(p1);
795 	}
796 	if (ok) {
797 		do_fork(td, flags, newproc, td2, vm2);
798 
799 		/*
800 		 * Return child proc pointer to parent.
801 		 */
802 		*procp = newproc;
803 		return (0);
804 	}
805 
806 	error = EAGAIN;
807 fail:
808 	sx_sunlock(&proctree_lock);
809 	if (ppsratecheck(&lastfail, &curfail, 1))
810 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
811 		    td->td_ucred->cr_ruid);
812 	sx_xunlock(&allproc_lock);
813 #ifdef MAC
814 	mac_proc_destroy(newproc);
815 #endif
816 fail1:
817 	if (vm2 != NULL)
818 		vmspace_free(vm2);
819 	uma_zfree(proc_zone, newproc);
820 	pause("fork", hz / 2);
821 	return (error);
822 }
823 
824 /*
825  * Handle the return of a child process from fork1().  This function
826  * is called from the MD fork_trampoline() entry point.
827  */
828 void
829 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
830     struct trapframe *frame)
831 {
832 	struct proc *p;
833 	struct thread *td;
834 	struct thread *dtd;
835 
836 	td = curthread;
837 	p = td->td_proc;
838 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
839 
840 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
841 		td, td->td_sched, p->p_pid, td->td_name);
842 
843 	sched_fork_exit(td);
844 	/*
845 	* Processes normally resume in mi_switch() after being
846 	* cpu_switch()'ed to, but when children start up they arrive here
847 	* instead, so we must do much the same things as mi_switch() would.
848 	*/
849 	if ((dtd = PCPU_GET(deadthread))) {
850 		PCPU_SET(deadthread, NULL);
851 		thread_stash(dtd);
852 	}
853 	thread_unlock(td);
854 
855 	/*
856 	 * cpu_set_fork_handler intercepts this function call to
857 	 * have this call a non-return function to stay in kernel mode.
858 	 * initproc has its own fork handler, but it does return.
859 	 */
860 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
861 	callout(arg, frame);
862 
863 	/*
864 	 * Check if a kernel thread misbehaved and returned from its main
865 	 * function.
866 	 */
867 	if (p->p_flag & P_KTHREAD) {
868 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
869 		    td->td_name, p->p_pid);
870 		kproc_exit(0);
871 	}
872 	mtx_assert(&Giant, MA_NOTOWNED);
873 
874 	EVENTHANDLER_INVOKE(schedtail, p);
875 }
876 
877 /*
878  * Simplified back end of syscall(), used when returning from fork()
879  * directly into user mode.  Giant is not held on entry, and must not
880  * be held on return.  This function is passed in to fork_exit() as the
881  * first parameter and is called when returning to a new userland process.
882  */
883 void
884 fork_return(struct thread *td, struct trapframe *frame)
885 {
886 
887 	userret(td, frame);
888 #ifdef KTRACE
889 	if (KTRPOINT(td, KTR_SYSRET))
890 		ktrsysret(SYS_fork, 0, 0);
891 #endif
892 	mtx_assert(&Giant, MA_NOTOWNED);
893 }
894