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