xref: /freebsd/sys/kern/kern_fork.c (revision f0720ed5f83d956846b999aa395d4697503d21cd)
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 
480 	if (flags & RFTSIGZMB)
481 	        p2->p_sigparent = RFTSIGNUM(flags);
482 	else if (flags & RFLINUXTHPN)
483 	        p2->p_sigparent = SIGUSR1;
484 	else
485 	        p2->p_sigparent = SIGCHLD;
486 
487 	p2->p_textvp = p1->p_textvp;
488 	p2->p_fd = fd;
489 	p2->p_fdtol = fdtol;
490 
491 	/*
492 	 * p_limit is copy-on-write.  Bump its refcount.
493 	 */
494 	lim_fork(p1, p2);
495 
496 	pstats_fork(p1->p_stats, p2->p_stats);
497 
498 	PROC_UNLOCK(p1);
499 	PROC_UNLOCK(p2);
500 
501 	/* Bump references to the text vnode (for procfs). */
502 	if (p2->p_textvp)
503 		vref(p2->p_textvp);
504 
505 	/*
506 	 * Set up linkage for kernel based threading.
507 	 */
508 	if ((flags & RFTHREAD) != 0) {
509 		mtx_lock(&ppeers_lock);
510 		p2->p_peers = p1->p_peers;
511 		p1->p_peers = p2;
512 		p2->p_leader = p1->p_leader;
513 		mtx_unlock(&ppeers_lock);
514 		PROC_LOCK(p1->p_leader);
515 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
516 			PROC_UNLOCK(p1->p_leader);
517 			/*
518 			 * The task leader is exiting, so process p1 is
519 			 * going to be killed shortly.  Since p1 obviously
520 			 * isn't dead yet, we know that the leader is either
521 			 * sending SIGKILL's to all the processes in this
522 			 * task or is sleeping waiting for all the peers to
523 			 * exit.  We let p1 complete the fork, but we need
524 			 * to go ahead and kill the new process p2 since
525 			 * the task leader may not get a chance to send
526 			 * SIGKILL to it.  We leave it on the list so that
527 			 * the task leader will wait for this new process
528 			 * to commit suicide.
529 			 */
530 			PROC_LOCK(p2);
531 			psignal(p2, SIGKILL);
532 			PROC_UNLOCK(p2);
533 		} else
534 			PROC_UNLOCK(p1->p_leader);
535 	} else {
536 		p2->p_peers = NULL;
537 		p2->p_leader = p2;
538 	}
539 
540 	sx_xlock(&proctree_lock);
541 	PGRP_LOCK(p1->p_pgrp);
542 	PROC_LOCK(p2);
543 	PROC_LOCK(p1);
544 
545 	/*
546 	 * Preserve some more flags in subprocess.  P_PROFIL has already
547 	 * been preserved.
548 	 */
549 	p2->p_flag |= p1->p_flag & P_SUGID;
550 	td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
551 	SESS_LOCK(p1->p_session);
552 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
553 		p2->p_flag |= P_CONTROLT;
554 	SESS_UNLOCK(p1->p_session);
555 	if (flags & RFPPWAIT)
556 		p2->p_flag |= P_PPWAIT;
557 
558 	p2->p_pgrp = p1->p_pgrp;
559 	LIST_INSERT_AFTER(p1, p2, p_pglist);
560 	PGRP_UNLOCK(p1->p_pgrp);
561 	LIST_INIT(&p2->p_children);
562 
563 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
564 
565 	/*
566 	 * If PF_FORK is set, the child process inherits the
567 	 * procfs ioctl flags from its parent.
568 	 */
569 	if (p1->p_pfsflags & PF_FORK) {
570 		p2->p_stops = p1->p_stops;
571 		p2->p_pfsflags = p1->p_pfsflags;
572 	}
573 
574 	/*
575 	 * This begins the section where we must prevent the parent
576 	 * from being swapped.
577 	 */
578 	_PHOLD(p1);
579 	PROC_UNLOCK(p1);
580 
581 	/*
582 	 * Attach the new process to its parent.
583 	 *
584 	 * If RFNOWAIT is set, the newly created process becomes a child
585 	 * of init.  This effectively disassociates the child from the
586 	 * parent.
587 	 */
588 	if (flags & RFNOWAIT)
589 		pptr = initproc;
590 	else
591 		pptr = p1;
592 	p2->p_pptr = pptr;
593 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
594 	sx_xunlock(&proctree_lock);
595 
596 	/* Inform accounting that we have forked. */
597 	p2->p_acflag = AFORK;
598 	PROC_UNLOCK(p2);
599 
600 #ifdef KTRACE
601 	ktrprocfork(p1, p2);
602 #endif
603 
604 	/*
605 	 * Finish creating the child process.  It will return via a different
606 	 * execution path later.  (ie: directly into user mode)
607 	 */
608 	vm_forkproc(td, p2, td2, vm2, flags);
609 
610 	if (flags == (RFFDG | RFPROC)) {
611 		PCPU_INC(cnt.v_forks);
612 		PCPU_ADD(cnt.v_forkpages, p2->p_vmspace->vm_dsize +
613 		    p2->p_vmspace->vm_ssize);
614 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
615 		PCPU_INC(cnt.v_vforks);
616 		PCPU_ADD(cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
617 		    p2->p_vmspace->vm_ssize);
618 	} else if (p1 == &proc0) {
619 		PCPU_INC(cnt.v_kthreads);
620 		PCPU_ADD(cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
621 		    p2->p_vmspace->vm_ssize);
622 	} else {
623 		PCPU_INC(cnt.v_rforks);
624 		PCPU_ADD(cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
625 		    p2->p_vmspace->vm_ssize);
626 	}
627 
628 	/*
629 	 * Both processes are set up, now check if any loadable modules want
630 	 * to adjust anything.
631 	 */
632 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
633 
634 	/*
635 	 * Set the child start time and mark the process as being complete.
636 	 */
637 	PROC_LOCK(p2);
638 	PROC_LOCK(p1);
639 	microuptime(&p2->p_stats->p_start);
640 	PROC_SLOCK(p2);
641 	p2->p_state = PRS_NORMAL;
642 	PROC_SUNLOCK(p2);
643 
644 #ifdef KDTRACE_HOOKS
645 	/*
646 	 * Tell the DTrace fasttrap provider about the new process
647 	 * if it has registered an interest. We have to do this only after
648 	 * p_state is PRS_NORMAL since the fasttrap module will use pfind()
649 	 * later on.
650 	 */
651 	if (dtrace_fasttrap_fork)
652 		dtrace_fasttrap_fork(p1, p2);
653 #endif
654 	if ((p1->p_flag & (P_TRACED | P_FOLLOWFORK)) == (P_TRACED |
655 	    P_FOLLOWFORK)) {
656 		/*
657 		 * Arrange for debugger to receive the fork event.
658 		 *
659 		 * We can report PL_FLAG_FORKED regardless of
660 		 * P_FOLLOWFORK settings, but it does not make a sense
661 		 * for runaway child.
662 		 */
663 		td->td_dbgflags |= TDB_FORK;
664 		td->td_dbg_forked = p2->p_pid;
665 		td2->td_dbgflags |= TDB_STOPATFORK;
666 		_PHOLD(p2);
667 		p2_held = 1;
668 	}
669 	PROC_UNLOCK(p2);
670 	if ((flags & RFSTOPPED) == 0) {
671 		/*
672 		 * If RFSTOPPED not requested, make child runnable and
673 		 * add to run queue.
674 		 */
675 		thread_lock(td2);
676 		TD_SET_CAN_RUN(td2);
677 		sched_add(td2, SRQ_BORING);
678 		thread_unlock(td2);
679 	}
680 
681 	/*
682 	 * Now can be swapped.
683 	 */
684 	_PRELE(p1);
685 	PROC_UNLOCK(p1);
686 
687 	/*
688 	 * Tell any interested parties about the new process.
689 	 */
690 	knote_fork(&p1->p_klist, p2->p_pid);
691 	SDT_PROBE(proc, kernel, , create, p2, p1, flags, 0, 0);
692 
693 	/*
694 	 * Wait until debugger is attached to child.
695 	 */
696 	PROC_LOCK(p2);
697 	while ((td2->td_dbgflags & TDB_STOPATFORK) != 0)
698 		cv_wait(&p2->p_dbgwait, &p2->p_mtx);
699 	if (p2_held)
700 		_PRELE(p2);
701 
702 	/*
703 	 * Preserve synchronization semantics of vfork.  If waiting for
704 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
705 	 * proc (in case of exit).
706 	 */
707 	while (p2->p_flag & P_PPWAIT)
708 		cv_wait(&p2->p_pwait, &p2->p_mtx);
709 	PROC_UNLOCK(p2);
710 }
711 
712 int
713 fork1(struct thread *td, int flags, int pages, struct proc **procp)
714 {
715 	struct proc *p1;
716 	struct proc *newproc;
717 	int ok;
718 	struct thread *td2;
719 	struct vmspace *vm2;
720 	vm_ooffset_t mem_charged;
721 	int error;
722 	static int curfail;
723 	static struct timeval lastfail;
724 
725 	/* Check for the undefined or unimplemented flags. */
726 	if ((flags & ~(RFFLAGS | RFTSIGFLAGS(RFTSIGMASK))) != 0)
727 		return (EINVAL);
728 
729 	/* Signal value requires RFTSIGZMB. */
730 	if ((flags & RFTSIGFLAGS(RFTSIGMASK)) != 0 && (flags & RFTSIGZMB) == 0)
731 		return (EINVAL);
732 
733 	/* Can't copy and clear. */
734 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
735 		return (EINVAL);
736 
737 	/* Check the validity of the signal number. */
738 	if ((flags & RFTSIGZMB) != 0 && (u_int)RFTSIGNUM(flags) > _SIG_MAXSIG)
739 		return (EINVAL);
740 
741 	p1 = td->td_proc;
742 
743 	/*
744 	 * Here we don't create a new process, but we divorce
745 	 * certain parts of a process from itself.
746 	 */
747 	if ((flags & RFPROC) == 0) {
748 		*procp = NULL;
749 		return (fork_norfproc(td, flags));
750 	}
751 
752 #ifdef RACCT
753 	PROC_LOCK(p1);
754 	error = racct_add(p1, RACCT_NPROC, 1);
755 	PROC_UNLOCK(p1);
756 	if (error != 0)
757 		return (EAGAIN);
758 #endif
759 
760 	mem_charged = 0;
761 	vm2 = NULL;
762 	if (pages == 0)
763 		pages = KSTACK_PAGES;
764 	/* Allocate new proc. */
765 	newproc = uma_zalloc(proc_zone, M_WAITOK);
766 	td2 = FIRST_THREAD_IN_PROC(newproc);
767 	if (td2 == NULL) {
768 		td2 = thread_alloc(pages);
769 		if (td2 == NULL) {
770 			error = ENOMEM;
771 			goto fail1;
772 		}
773 		proc_linkup(newproc, td2);
774 	} else {
775 		if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
776 			if (td2->td_kstack != 0)
777 				vm_thread_dispose(td2);
778 			if (!thread_alloc_stack(td2, pages)) {
779 				error = ENOMEM;
780 				goto fail1;
781 			}
782 		}
783 	}
784 
785 	if ((flags & RFMEM) == 0) {
786 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
787 		if (vm2 == NULL) {
788 			error = ENOMEM;
789 			goto fail1;
790 		}
791 		if (!swap_reserve(mem_charged)) {
792 			/*
793 			 * The swap reservation failed. The accounting
794 			 * from the entries of the copied vm2 will be
795 			 * substracted in vmspace_free(), so force the
796 			 * reservation there.
797 			 */
798 			swap_reserve_force(mem_charged);
799 			error = ENOMEM;
800 			goto fail1;
801 		}
802 	} else
803 		vm2 = NULL;
804 #ifdef MAC
805 	mac_proc_init(newproc);
806 #endif
807 	knlist_init_mtx(&newproc->p_klist, &newproc->p_mtx);
808 	STAILQ_INIT(&newproc->p_ktr);
809 
810 	/*
811 	 * XXX: This is ugly; when we copy resource usage, we need to bump
812 	 *      per-cred resource counters.
813 	 */
814 	newproc->p_ucred = p1->p_ucred;
815 
816 	/*
817 	 * Initialize resource accounting for the child process.
818 	 */
819 	error = racct_proc_fork(p1, newproc);
820 	if (error != 0) {
821 		error = EAGAIN;
822 		goto fail1;
823 	}
824 
825 	/* We have to lock the process tree while we look for a pid. */
826 	sx_slock(&proctree_lock);
827 
828 	/*
829 	 * Although process entries are dynamically created, we still keep
830 	 * a global limit on the maximum number we will create.  Don't allow
831 	 * a nonprivileged user to use the last ten processes; don't let root
832 	 * exceed the limit. The variable nprocs is the current number of
833 	 * processes, maxproc is the limit.
834 	 */
835 	sx_xlock(&allproc_lock);
836 	if ((nprocs >= maxproc - 10 && priv_check_cred(td->td_ucred,
837 	    PRIV_MAXPROC, 0) != 0) || nprocs >= maxproc) {
838 		error = EAGAIN;
839 		goto fail;
840 	}
841 
842 #ifdef RACCT
843 	/*
844 	 * After fork, there is exactly one thread running.
845 	 */
846 	PROC_LOCK(newproc);
847 	error = racct_set(newproc, RACCT_NTHR, 1);
848 	PROC_UNLOCK(newproc);
849 	if (error != 0) {
850 		error = EAGAIN;
851 		goto fail;
852 	}
853 #endif
854 
855 	/*
856 	 * Increment the count of procs running with this uid. Don't allow
857 	 * a nonprivileged user to exceed their current limit.
858 	 *
859 	 * XXXRW: Can we avoid privilege here if it's not needed?
860 	 */
861 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
862 	if (error == 0)
863 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
864 	else {
865 		PROC_LOCK(p1);
866 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
867 		    lim_cur(p1, RLIMIT_NPROC));
868 		PROC_UNLOCK(p1);
869 	}
870 	if (ok) {
871 		do_fork(td, flags, newproc, td2, vm2);
872 
873 		/*
874 		 * Return child proc pointer to parent.
875 		 */
876 		*procp = newproc;
877 		return (0);
878 	}
879 
880 	error = EAGAIN;
881 fail:
882 	racct_proc_exit(newproc);
883 	sx_sunlock(&proctree_lock);
884 	if (ppsratecheck(&lastfail, &curfail, 1))
885 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
886 		    td->td_ucred->cr_ruid);
887 	sx_xunlock(&allproc_lock);
888 #ifdef MAC
889 	mac_proc_destroy(newproc);
890 #endif
891 fail1:
892 	if (vm2 != NULL)
893 		vmspace_free(vm2);
894 	uma_zfree(proc_zone, newproc);
895 	pause("fork", hz / 2);
896 #ifdef RACCT
897 	PROC_LOCK(p1);
898 	racct_sub(p1, RACCT_NPROC, 1);
899 	PROC_UNLOCK(p1);
900 #endif
901 	return (error);
902 }
903 
904 /*
905  * Handle the return of a child process from fork1().  This function
906  * is called from the MD fork_trampoline() entry point.
907  */
908 void
909 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
910     struct trapframe *frame)
911 {
912 	struct proc *p;
913 	struct thread *td;
914 	struct thread *dtd;
915 
916 	td = curthread;
917 	p = td->td_proc;
918 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
919 
920 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
921 		td, td->td_sched, p->p_pid, td->td_name);
922 
923 	sched_fork_exit(td);
924 	/*
925 	* Processes normally resume in mi_switch() after being
926 	* cpu_switch()'ed to, but when children start up they arrive here
927 	* instead, so we must do much the same things as mi_switch() would.
928 	*/
929 	if ((dtd = PCPU_GET(deadthread))) {
930 		PCPU_SET(deadthread, NULL);
931 		thread_stash(dtd);
932 	}
933 	thread_unlock(td);
934 
935 	/*
936 	 * cpu_set_fork_handler intercepts this function call to
937 	 * have this call a non-return function to stay in kernel mode.
938 	 * initproc has its own fork handler, but it does return.
939 	 */
940 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
941 	callout(arg, frame);
942 
943 	/*
944 	 * Check if a kernel thread misbehaved and returned from its main
945 	 * function.
946 	 */
947 	if (p->p_flag & P_KTHREAD) {
948 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
949 		    td->td_name, p->p_pid);
950 		kproc_exit(0);
951 	}
952 	mtx_assert(&Giant, MA_NOTOWNED);
953 
954 	if (p->p_sysent->sv_schedtail != NULL)
955 		(p->p_sysent->sv_schedtail)(td);
956 }
957 
958 /*
959  * Simplified back end of syscall(), used when returning from fork()
960  * directly into user mode.  Giant is not held on entry, and must not
961  * be held on return.  This function is passed in to fork_exit() as the
962  * first parameter and is called when returning to a new userland process.
963  */
964 void
965 fork_return(struct thread *td, struct trapframe *frame)
966 {
967 	struct proc *p, *dbg;
968 
969 	if (td->td_dbgflags & TDB_STOPATFORK) {
970 		p = td->td_proc;
971 		sx_xlock(&proctree_lock);
972 		PROC_LOCK(p);
973 		if ((p->p_pptr->p_flag & (P_TRACED | P_FOLLOWFORK)) ==
974 		    (P_TRACED | P_FOLLOWFORK)) {
975 			/*
976 			 * If debugger still wants auto-attach for the
977 			 * parent's children, do it now.
978 			 */
979 			dbg = p->p_pptr->p_pptr;
980 			p->p_flag |= P_TRACED;
981 			p->p_oppid = p->p_pptr->p_pid;
982 			proc_reparent(p, dbg);
983 			sx_xunlock(&proctree_lock);
984 			ptracestop(td, SIGSTOP);
985 		} else {
986 			/*
987 			 * ... otherwise clear the request.
988 			 */
989 			sx_xunlock(&proctree_lock);
990 			td->td_dbgflags &= ~TDB_STOPATFORK;
991 			cv_broadcast(&p->p_dbgwait);
992 		}
993 		PROC_UNLOCK(p);
994 	}
995 
996 	userret(td, frame);
997 
998 #ifdef KTRACE
999 	if (KTRPOINT(td, KTR_SYSRET))
1000 		ktrsysret(SYS_fork, 0, 0);
1001 #endif
1002 	mtx_assert(&Giant, MA_NOTOWNED);
1003 }
1004