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