xref: /freebsd/sys/kern/kern_fork.c (revision 10b9d77bf1ccf2f3affafa6261692cb92cf7e992)
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 p2_held, 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 	p2_held = 0;
350 	p1 = td->td_proc;
351 
352 	/*
353 	 * Increment the nprocs resource before blocking can occur.  There
354 	 * are hard-limits as to the number of processes that can run.
355 	 */
356 	nprocs++;
357 
358 	trypid = fork_findpid(flags);
359 
360 	sx_sunlock(&proctree_lock);
361 
362 	p2->p_state = PRS_NEW;		/* protect against others */
363 	p2->p_pid = trypid;
364 	AUDIT_ARG_PID(p2->p_pid);
365 	LIST_INSERT_HEAD(&allproc, p2, p_list);
366 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
367 	tidhash_add(td2);
368 	PROC_LOCK(p2);
369 	PROC_LOCK(p1);
370 
371 	sx_xunlock(&allproc_lock);
372 
373 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
374 	    __rangeof(struct proc, p_startcopy, p_endcopy));
375 	pargs_hold(p2->p_args);
376 	PROC_UNLOCK(p1);
377 
378 	bzero(&p2->p_startzero,
379 	    __rangeof(struct proc, p_startzero, p_endzero));
380 
381 	p2->p_ucred = crhold(td->td_ucred);
382 
383 	/* Tell the prison that we exist. */
384 	prison_proc_hold(p2->p_ucred->cr_prison);
385 
386 	PROC_UNLOCK(p2);
387 
388 	/*
389 	 * Malloc things while we don't hold any locks.
390 	 */
391 	if (flags & RFSIGSHARE)
392 		newsigacts = NULL;
393 	else
394 		newsigacts = sigacts_alloc();
395 
396 	/*
397 	 * Copy filedesc.
398 	 */
399 	if (flags & RFCFDG) {
400 		fd = fdinit(p1->p_fd);
401 		fdtol = NULL;
402 	} else if (flags & RFFDG) {
403 		fd = fdcopy(p1->p_fd);
404 		fdtol = NULL;
405 	} else {
406 		fd = fdshare(p1->p_fd);
407 		if (p1->p_fdtol == NULL)
408 			p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL,
409 			    p1->p_leader);
410 		if ((flags & RFTHREAD) != 0) {
411 			/*
412 			 * Shared file descriptor table, and shared
413 			 * process leaders.
414 			 */
415 			fdtol = p1->p_fdtol;
416 			FILEDESC_XLOCK(p1->p_fd);
417 			fdtol->fdl_refcount++;
418 			FILEDESC_XUNLOCK(p1->p_fd);
419 		} else {
420 			/*
421 			 * Shared file descriptor table, and different
422 			 * process leaders.
423 			 */
424 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
425 			    p1->p_fd, p2);
426 		}
427 	}
428 	/*
429 	 * Make a proc table entry for the new process.
430 	 * Start by zeroing the section of proc that is zero-initialized,
431 	 * then copy the section that is copied directly from the parent.
432 	 */
433 
434 	PROC_LOCK(p2);
435 	PROC_LOCK(p1);
436 
437 	bzero(&td2->td_startzero,
438 	    __rangeof(struct thread, td_startzero, td_endzero));
439 
440 	bcopy(&td->td_startcopy, &td2->td_startcopy,
441 	    __rangeof(struct thread, td_startcopy, td_endcopy));
442 
443 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
444 	td2->td_sigstk = td->td_sigstk;
445 	td2->td_sigmask = td->td_sigmask;
446 	td2->td_flags = TDF_INMEM;
447 	td2->td_lend_user_pri = PRI_MAX;
448 
449 #ifdef VIMAGE
450 	td2->td_vnet = NULL;
451 	td2->td_vnet_lpush = NULL;
452 #endif
453 
454 	/*
455 	 * Allow the scheduler to initialize the child.
456 	 */
457 	thread_lock(td);
458 	sched_fork(td, td2);
459 	thread_unlock(td);
460 
461 	/*
462 	 * Duplicate sub-structures as needed.
463 	 * Increase reference counts on shared objects.
464 	 */
465 	p2->p_flag = P_INMEM;
466 	p2->p_swtick = ticks;
467 	if (p1->p_flag & P_PROFIL)
468 		startprofclock(p2);
469 	td2->td_ucred = crhold(p2->p_ucred);
470 
471 	if (flags & RFSIGSHARE) {
472 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
473 	} else {
474 		sigacts_copy(newsigacts, p1->p_sigacts);
475 		p2->p_sigacts = newsigacts;
476 	}
477 	if (flags & RFLINUXTHPN)
478 	        p2->p_sigparent = SIGUSR1;
479 	else
480 	        p2->p_sigparent = SIGCHLD;
481 
482 	p2->p_textvp = p1->p_textvp;
483 	p2->p_fd = fd;
484 	p2->p_fdtol = fdtol;
485 
486 	/*
487 	 * p_limit is copy-on-write.  Bump its refcount.
488 	 */
489 	lim_fork(p1, p2);
490 
491 	pstats_fork(p1->p_stats, p2->p_stats);
492 
493 	PROC_UNLOCK(p1);
494 	PROC_UNLOCK(p2);
495 
496 	/* Bump references to the text vnode (for procfs). */
497 	if (p2->p_textvp)
498 		vref(p2->p_textvp);
499 
500 	/*
501 	 * Set up linkage for kernel based threading.
502 	 */
503 	if ((flags & RFTHREAD) != 0) {
504 		mtx_lock(&ppeers_lock);
505 		p2->p_peers = p1->p_peers;
506 		p1->p_peers = p2;
507 		p2->p_leader = p1->p_leader;
508 		mtx_unlock(&ppeers_lock);
509 		PROC_LOCK(p1->p_leader);
510 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
511 			PROC_UNLOCK(p1->p_leader);
512 			/*
513 			 * The task leader is exiting, so process p1 is
514 			 * going to be killed shortly.  Since p1 obviously
515 			 * isn't dead yet, we know that the leader is either
516 			 * sending SIGKILL's to all the processes in this
517 			 * task or is sleeping waiting for all the peers to
518 			 * exit.  We let p1 complete the fork, but we need
519 			 * to go ahead and kill the new process p2 since
520 			 * the task leader may not get a chance to send
521 			 * SIGKILL to it.  We leave it on the list so that
522 			 * the task leader will wait for this new process
523 			 * to commit suicide.
524 			 */
525 			PROC_LOCK(p2);
526 			psignal(p2, SIGKILL);
527 			PROC_UNLOCK(p2);
528 		} else
529 			PROC_UNLOCK(p1->p_leader);
530 	} else {
531 		p2->p_peers = NULL;
532 		p2->p_leader = p2;
533 	}
534 
535 	sx_xlock(&proctree_lock);
536 	PGRP_LOCK(p1->p_pgrp);
537 	PROC_LOCK(p2);
538 	PROC_LOCK(p1);
539 
540 	/*
541 	 * Preserve some more flags in subprocess.  P_PROFIL has already
542 	 * been preserved.
543 	 */
544 	p2->p_flag |= p1->p_flag & P_SUGID;
545 	td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
546 	SESS_LOCK(p1->p_session);
547 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
548 		p2->p_flag |= P_CONTROLT;
549 	SESS_UNLOCK(p1->p_session);
550 	if (flags & RFPPWAIT)
551 		p2->p_flag |= P_PPWAIT;
552 
553 	p2->p_pgrp = p1->p_pgrp;
554 	LIST_INSERT_AFTER(p1, p2, p_pglist);
555 	PGRP_UNLOCK(p1->p_pgrp);
556 	LIST_INIT(&p2->p_children);
557 
558 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
559 
560 	/*
561 	 * If PF_FORK is set, the child process inherits the
562 	 * procfs ioctl flags from its parent.
563 	 */
564 	if (p1->p_pfsflags & PF_FORK) {
565 		p2->p_stops = p1->p_stops;
566 		p2->p_pfsflags = p1->p_pfsflags;
567 	}
568 
569 	/*
570 	 * This begins the section where we must prevent the parent
571 	 * from being swapped.
572 	 */
573 	_PHOLD(p1);
574 	PROC_UNLOCK(p1);
575 
576 	/*
577 	 * Attach the new process to its parent.
578 	 *
579 	 * If RFNOWAIT is set, the newly created process becomes a child
580 	 * of init.  This effectively disassociates the child from the
581 	 * parent.
582 	 */
583 	if (flags & RFNOWAIT)
584 		pptr = initproc;
585 	else
586 		pptr = p1;
587 	p2->p_pptr = pptr;
588 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
589 	sx_xunlock(&proctree_lock);
590 
591 	/* Inform accounting that we have forked. */
592 	p2->p_acflag = AFORK;
593 	PROC_UNLOCK(p2);
594 
595 #ifdef KTRACE
596 	ktrprocfork(p1, p2);
597 #endif
598 
599 	/*
600 	 * Finish creating the child process.  It will return via a different
601 	 * execution path later.  (ie: directly into user mode)
602 	 */
603 	vm_forkproc(td, p2, td2, vm2, flags);
604 
605 	if (flags == (RFFDG | RFPROC)) {
606 		PCPU_INC(cnt.v_forks);
607 		PCPU_ADD(cnt.v_forkpages, p2->p_vmspace->vm_dsize +
608 		    p2->p_vmspace->vm_ssize);
609 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
610 		PCPU_INC(cnt.v_vforks);
611 		PCPU_ADD(cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
612 		    p2->p_vmspace->vm_ssize);
613 	} else if (p1 == &proc0) {
614 		PCPU_INC(cnt.v_kthreads);
615 		PCPU_ADD(cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
616 		    p2->p_vmspace->vm_ssize);
617 	} else {
618 		PCPU_INC(cnt.v_rforks);
619 		PCPU_ADD(cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
620 		    p2->p_vmspace->vm_ssize);
621 	}
622 
623 	/*
624 	 * Both processes are set up, now check if any loadable modules want
625 	 * to adjust anything.
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 
637 	PROC_LOCK(p1);
638 #ifdef KDTRACE_HOOKS
639 	/*
640 	 * Tell the DTrace fasttrap provider about the new process
641 	 * if it has registered an interest. We have to do this only after
642 	 * p_state is PRS_NORMAL since the fasttrap module will use pfind()
643 	 * later on.
644 	 */
645 	if (dtrace_fasttrap_fork) {
646 		PROC_LOCK(p2);
647 		dtrace_fasttrap_fork(p1, p2);
648 		PROC_UNLOCK(p2);
649 	}
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 		PROC_LOCK(p2);
663 		td2->td_dbgflags |= TDB_STOPATFORK;
664 		_PHOLD(p2);
665 		p2_held = 1;
666 		PROC_UNLOCK(p2);
667 	}
668 	if ((flags & RFSTOPPED) == 0) {
669 		/*
670 		 * If RFSTOPPED not requested, make child runnable and
671 		 * add to run queue.
672 		 */
673 		thread_lock(td2);
674 		TD_SET_CAN_RUN(td2);
675 		sched_add(td2, SRQ_BORING);
676 		thread_unlock(td2);
677 	}
678 
679 	/*
680 	 * Now can be swapped.
681 	 */
682 	_PRELE(p1);
683 	PROC_UNLOCK(p1);
684 
685 	/*
686 	 * Tell any interested parties about the new process.
687 	 */
688 	knote_fork(&p1->p_klist, p2->p_pid);
689 	SDT_PROBE(proc, kernel, , create, p2, p1, flags, 0, 0);
690 
691 	/*
692 	 * Wait until debugger is attached to child.
693 	 */
694 	PROC_LOCK(p2);
695 	while ((td2->td_dbgflags & TDB_STOPATFORK) != 0)
696 		cv_wait(&p2->p_dbgwait, &p2->p_mtx);
697 	if (p2_held)
698 		_PRELE(p2);
699 
700 	/*
701 	 * Preserve synchronization semantics of vfork.  If waiting for
702 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
703 	 * proc (in case of exit).
704 	 */
705 	while (p2->p_flag & P_PPWAIT)
706 		cv_wait(&p2->p_pwait, &p2->p_mtx);
707 	PROC_UNLOCK(p2);
708 }
709 
710 int
711 fork1(struct thread *td, int flags, int pages, struct proc **procp)
712 {
713 	struct proc *p1;
714 	struct proc *newproc;
715 	int ok;
716 	struct thread *td2;
717 	struct vmspace *vm2;
718 	vm_ooffset_t mem_charged;
719 	int error;
720 	static int curfail;
721 	static struct timeval lastfail;
722 
723 	/* Can't copy and clear. */
724 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
725 		return (EINVAL);
726 
727 	p1 = td->td_proc;
728 
729 	/*
730 	 * Here we don't create a new process, but we divorce
731 	 * certain parts of a process from itself.
732 	 */
733 	if ((flags & RFPROC) == 0) {
734 		*procp = NULL;
735 		return (fork_norfproc(td, flags));
736 	}
737 
738 	mem_charged = 0;
739 	vm2 = NULL;
740 	if (pages == 0)
741 		pages = KSTACK_PAGES;
742 	/* Allocate new proc. */
743 	newproc = uma_zalloc(proc_zone, M_WAITOK);
744 	td2 = FIRST_THREAD_IN_PROC(newproc);
745 	if (td2 == NULL) {
746 		td2 = thread_alloc(pages);
747 		if (td2 == NULL) {
748 			error = ENOMEM;
749 			goto fail1;
750 		}
751 		proc_linkup(newproc, td2);
752 	} else {
753 		if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
754 			if (td2->td_kstack != 0)
755 				vm_thread_dispose(td2);
756 			if (!thread_alloc_stack(td2, pages)) {
757 				error = ENOMEM;
758 				goto fail1;
759 			}
760 		}
761 	}
762 
763 	if ((flags & RFMEM) == 0) {
764 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
765 		if (vm2 == NULL) {
766 			error = ENOMEM;
767 			goto fail1;
768 		}
769 		if (!swap_reserve(mem_charged)) {
770 			/*
771 			 * The swap reservation failed. The accounting
772 			 * from the entries of the copied vm2 will be
773 			 * substracted in vmspace_free(), so force the
774 			 * reservation there.
775 			 */
776 			swap_reserve_force(mem_charged);
777 			error = ENOMEM;
778 			goto fail1;
779 		}
780 	} else
781 		vm2 = NULL;
782 #ifdef MAC
783 	mac_proc_init(newproc);
784 #endif
785 	knlist_init_mtx(&newproc->p_klist, &newproc->p_mtx);
786 	STAILQ_INIT(&newproc->p_ktr);
787 
788 	/* We have to lock the process tree while we look for a pid. */
789 	sx_slock(&proctree_lock);
790 
791 	/*
792 	 * Although process entries are dynamically created, we still keep
793 	 * a global limit on the maximum number we will create.  Don't allow
794 	 * a nonprivileged user to use the last ten processes; don't let root
795 	 * exceed the limit. The variable nprocs is the current number of
796 	 * processes, maxproc is the limit.
797 	 */
798 	sx_xlock(&allproc_lock);
799 	if ((nprocs >= maxproc - 10 && priv_check_cred(td->td_ucred,
800 	    PRIV_MAXPROC, 0) != 0) || nprocs >= maxproc) {
801 		error = EAGAIN;
802 		goto fail;
803 	}
804 
805 	/*
806 	 * Increment the count of procs running with this uid. Don't allow
807 	 * a nonprivileged user to exceed their current limit.
808 	 *
809 	 * XXXRW: Can we avoid privilege here if it's not needed?
810 	 */
811 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
812 	if (error == 0)
813 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
814 	else {
815 		PROC_LOCK(p1);
816 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
817 		    lim_cur(p1, RLIMIT_NPROC));
818 		PROC_UNLOCK(p1);
819 	}
820 	if (ok) {
821 		do_fork(td, flags, newproc, td2, vm2);
822 
823 		/*
824 		 * Return child proc pointer to parent.
825 		 */
826 		*procp = newproc;
827 		return (0);
828 	}
829 
830 	error = EAGAIN;
831 fail:
832 	sx_sunlock(&proctree_lock);
833 	if (ppsratecheck(&lastfail, &curfail, 1))
834 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
835 		    td->td_ucred->cr_ruid);
836 	sx_xunlock(&allproc_lock);
837 #ifdef MAC
838 	mac_proc_destroy(newproc);
839 #endif
840 fail1:
841 	if (vm2 != NULL)
842 		vmspace_free(vm2);
843 	uma_zfree(proc_zone, newproc);
844 	pause("fork", hz / 2);
845 	return (error);
846 }
847 
848 /*
849  * Handle the return of a child process from fork1().  This function
850  * is called from the MD fork_trampoline() entry point.
851  */
852 void
853 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
854     struct trapframe *frame)
855 {
856 	struct proc *p;
857 	struct thread *td;
858 	struct thread *dtd;
859 
860 	td = curthread;
861 	p = td->td_proc;
862 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
863 
864 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
865 		td, td->td_sched, p->p_pid, td->td_name);
866 
867 	sched_fork_exit(td);
868 	/*
869 	* Processes normally resume in mi_switch() after being
870 	* cpu_switch()'ed to, but when children start up they arrive here
871 	* instead, so we must do much the same things as mi_switch() would.
872 	*/
873 	if ((dtd = PCPU_GET(deadthread))) {
874 		PCPU_SET(deadthread, NULL);
875 		thread_stash(dtd);
876 	}
877 	thread_unlock(td);
878 
879 	/*
880 	 * cpu_set_fork_handler intercepts this function call to
881 	 * have this call a non-return function to stay in kernel mode.
882 	 * initproc has its own fork handler, but it does return.
883 	 */
884 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
885 	callout(arg, frame);
886 
887 	/*
888 	 * Check if a kernel thread misbehaved and returned from its main
889 	 * function.
890 	 */
891 	if (p->p_flag & P_KTHREAD) {
892 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
893 		    td->td_name, p->p_pid);
894 		kproc_exit(0);
895 	}
896 	mtx_assert(&Giant, MA_NOTOWNED);
897 
898 	EVENTHANDLER_INVOKE(schedtail, p);
899 }
900 
901 /*
902  * Simplified back end of syscall(), used when returning from fork()
903  * directly into user mode.  Giant is not held on entry, and must not
904  * be held on return.  This function is passed in to fork_exit() as the
905  * first parameter and is called when returning to a new userland process.
906  */
907 void
908 fork_return(struct thread *td, struct trapframe *frame)
909 {
910 	struct proc *p, *dbg;
911 
912 	if (td->td_dbgflags & TDB_STOPATFORK) {
913 		p = td->td_proc;
914 		sx_xlock(&proctree_lock);
915 		PROC_LOCK(p);
916 		if ((p->p_pptr->p_flag & (P_TRACED | P_FOLLOWFORK)) ==
917 		    (P_TRACED | P_FOLLOWFORK)) {
918 			/*
919 			 * If debugger still wants auto-attach for the
920 			 * parent's children, do it now.
921 			 */
922 			dbg = p->p_pptr->p_pptr;
923 			p->p_flag |= P_TRACED;
924 			p->p_oppid = p->p_pptr->p_pid;
925 			proc_reparent(p, dbg);
926 			sx_xunlock(&proctree_lock);
927 			ptracestop(td, SIGSTOP);
928 		} else {
929 			/*
930 			 * ... otherwise clear the request.
931 			 */
932 			sx_xunlock(&proctree_lock);
933 			td->td_dbgflags &= ~TDB_STOPATFORK;
934 			cv_broadcast(&p->p_dbgwait);
935 		}
936 		PROC_UNLOCK(p);
937 	}
938 
939 	userret(td, frame);
940 
941 #ifdef KTRACE
942 	if (KTRPOINT(td, KTR_SYSRET))
943 		ktrsysret(SYS_fork, 0, 0);
944 #endif
945 	mtx_assert(&Giant, MA_NOTOWNED);
946 }
947