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