xref: /freebsd/sys/kern/kern_fork.c (revision 7bd6fde3)
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_mac.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/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/kthread.h>
50 #include <sys/sysctl.h>
51 #include <sys/lock.h>
52 #include <sys/malloc.h>
53 #include <sys/mutex.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/pioctl.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sched.h>
59 #include <sys/syscall.h>
60 #include <sys/vmmeter.h>
61 #include <sys/vnode.h>
62 #include <sys/acct.h>
63 #include <sys/ktr.h>
64 #include <sys/ktrace.h>
65 #include <sys/unistd.h>
66 #include <sys/sx.h>
67 #include <sys/signalvar.h>
68 
69 #include <security/audit/audit.h>
70 #include <security/mac/mac_framework.h>
71 
72 #include <vm/vm.h>
73 #include <vm/pmap.h>
74 #include <vm/vm_map.h>
75 #include <vm/vm_extern.h>
76 #include <vm/uma.h>
77 
78 
79 #ifndef _SYS_SYSPROTO_H_
80 struct fork_args {
81 	int     dummy;
82 };
83 #endif
84 
85 /*
86  * MPSAFE
87  */
88 /* ARGSUSED */
89 int
90 fork(td, uap)
91 	struct thread *td;
92 	struct fork_args *uap;
93 {
94 	int error;
95 	struct proc *p2;
96 
97 	error = fork1(td, RFFDG | RFPROC, 0, &p2);
98 	if (error == 0) {
99 		td->td_retval[0] = p2->p_pid;
100 		td->td_retval[1] = 0;
101 	}
102 	return (error);
103 }
104 
105 /*
106  * MPSAFE
107  */
108 /* ARGSUSED */
109 int
110 vfork(td, uap)
111 	struct thread *td;
112 	struct vfork_args *uap;
113 {
114 	int error;
115 	struct proc *p2;
116 
117 	error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
118 	if (error == 0) {
119 		td->td_retval[0] = p2->p_pid;
120 		td->td_retval[1] = 0;
121 	}
122 	return (error);
123 }
124 
125 /*
126  * MPSAFE
127  */
128 int
129 rfork(td, uap)
130 	struct thread *td;
131 	struct rfork_args *uap;
132 {
133 	struct proc *p2;
134 	int error;
135 
136 	/* Don't allow kernel-only flags. */
137 	if ((uap->flags & RFKERNELONLY) != 0)
138 		return (EINVAL);
139 
140 	AUDIT_ARG(fflags, uap->flags);
141 	error = fork1(td, uap->flags, 0, &p2);
142 	if (error == 0) {
143 		td->td_retval[0] = p2 ? p2->p_pid : 0;
144 		td->td_retval[1] = 0;
145 	}
146 	return (error);
147 }
148 
149 int	nprocs = 1;		/* process 0 */
150 int	lastpid = 0;
151 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
152     "Last used PID");
153 
154 /*
155  * Random component to lastpid generation.  We mix in a random factor to make
156  * it a little harder to predict.  We sanity check the modulus value to avoid
157  * doing it in critical paths.  Don't let it be too small or we pointlessly
158  * waste randomness entropy, and don't let it be impossibly large.  Using a
159  * modulus that is too big causes a LOT more process table scans and slows
160  * down fork processing as the pidchecked caching is defeated.
161  */
162 static int randompid = 0;
163 
164 static int
165 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
166 {
167 	int error, pid;
168 
169 	error = sysctl_wire_old_buffer(req, sizeof(int));
170 	if (error != 0)
171 		return(error);
172 	sx_xlock(&allproc_lock);
173 	pid = randompid;
174 	error = sysctl_handle_int(oidp, &pid, 0, req);
175 	if (error == 0 && req->newptr != NULL) {
176 		if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
177 			pid = PID_MAX - 100;
178 		else if (pid < 2)			/* NOP */
179 			pid = 0;
180 		else if (pid < 100)			/* Make it reasonable */
181 			pid = 100;
182 		randompid = pid;
183 	}
184 	sx_xunlock(&allproc_lock);
185 	return (error);
186 }
187 
188 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
189     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
190 
191 int
192 fork1(td, flags, pages, procp)
193 	struct thread *td;
194 	int flags;
195 	int pages;
196 	struct proc **procp;
197 {
198 	struct proc *p1, *p2, *pptr;
199 	struct proc *newproc;
200 	int ok, trypid;
201 	static int curfail, pidchecked = 0;
202 	static struct timeval lastfail;
203 	struct filedesc *fd;
204 	struct filedesc_to_leader *fdtol;
205 	struct thread *td2;
206 	struct sigacts *newsigacts;
207 	int error;
208 
209 	/* Can't copy and clear. */
210 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
211 		return (EINVAL);
212 
213 	p1 = td->td_proc;
214 
215 	/*
216 	 * Here we don't create a new process, but we divorce
217 	 * certain parts of a process from itself.
218 	 */
219 	if ((flags & RFPROC) == 0) {
220 		if ((p1->p_flag & P_HADTHREADS) &&
221 		    (flags & (RFCFDG | RFFDG))) {
222 			PROC_LOCK(p1);
223 			if (thread_single(SINGLE_BOUNDARY)) {
224 				PROC_UNLOCK(p1);
225 				return (ERESTART);
226 			}
227 			PROC_UNLOCK(p1);
228 		}
229 
230 		vm_forkproc(td, NULL, NULL, flags);
231 
232 		/*
233 		 * Close all file descriptors.
234 		 */
235 		if (flags & RFCFDG) {
236 			struct filedesc *fdtmp;
237 			fdtmp = fdinit(td->td_proc->p_fd);
238 			fdfree(td);
239 			p1->p_fd = fdtmp;
240 		}
241 
242 		/*
243 		 * Unshare file descriptors (from parent).
244 		 */
245 		if (flags & RFFDG)
246 			fdunshare(p1, td);
247 
248 		if ((p1->p_flag & P_HADTHREADS) &&
249 		    (flags & (RFCFDG | RFFDG))) {
250 			PROC_LOCK(p1);
251 			thread_single_end();
252 			PROC_UNLOCK(p1);
253 		}
254 		*procp = NULL;
255 		return (0);
256 	}
257 
258 	/*
259 	 * Note 1:1 allows for forking with one thread coming out on the
260 	 * other side with the expectation that the process is about to
261 	 * exec.
262 	 */
263 	if (p1->p_flag & P_HADTHREADS) {
264 		/*
265 		 * Idle the other threads for a second.
266 		 * Since the user space is copied, it must remain stable.
267 		 * In addition, all threads (from the user perspective)
268 		 * need to either be suspended or in the kernel,
269 		 * where they will try restart in the parent and will
270 		 * be aborted in the child.
271 		 */
272 		PROC_LOCK(p1);
273 		if (thread_single(SINGLE_NO_EXIT)) {
274 			/* Abort. Someone else is single threading before us. */
275 			PROC_UNLOCK(p1);
276 			return (ERESTART);
277 		}
278 		PROC_UNLOCK(p1);
279 		/*
280 		 * All other activity in this process
281 		 * is now suspended at the user boundary,
282 		 * (or other safe places if we think of any).
283 		 */
284 	}
285 
286 	/* Allocate new proc. */
287 	newproc = uma_zalloc(proc_zone, M_WAITOK);
288 #ifdef MAC
289 	mac_init_proc(newproc);
290 #endif
291 #ifdef AUDIT
292 	audit_proc_alloc(newproc);
293 #endif
294 	knlist_init(&newproc->p_klist, &newproc->p_mtx, NULL, NULL, NULL);
295 	STAILQ_INIT(&newproc->p_ktr);
296 
297 	/* We have to lock the process tree while we look for a pid. */
298 	sx_slock(&proctree_lock);
299 
300 	/*
301 	 * Although process entries are dynamically created, we still keep
302 	 * a global limit on the maximum number we will create.  Don't allow
303 	 * a nonprivileged user to use the last ten processes; don't let root
304 	 * exceed the limit. The variable nprocs is the current number of
305 	 * processes, maxproc is the limit.
306 	 */
307 	sx_xlock(&allproc_lock);
308 	if ((nprocs >= maxproc - 10 &&
309 	    priv_check_cred(td->td_ucred, PRIV_MAXPROC, SUSER_RUID) != 0) ||
310 	    nprocs >= maxproc) {
311 		error = EAGAIN;
312 		goto fail;
313 	}
314 
315 	/*
316 	 * Increment the count of procs running with this uid. Don't allow
317 	 * a nonprivileged user to exceed their current limit.
318 	 *
319 	 * XXXRW: Can we avoid privilege here if it's not needed?
320 	 */
321 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, SUSER_RUID |
322 	    SUSER_ALLOWJAIL);
323 	if (error == 0)
324 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
325 	else {
326 		PROC_LOCK(p1);
327 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
328 		    lim_cur(p1, RLIMIT_NPROC));
329 		PROC_UNLOCK(p1);
330 	}
331 	if (!ok) {
332 		error = EAGAIN;
333 		goto fail;
334 	}
335 
336 	/*
337 	 * Increment the nprocs resource before blocking can occur.  There
338 	 * are hard-limits as to the number of processes that can run.
339 	 */
340 	nprocs++;
341 
342 	/*
343 	 * Find an unused process ID.  We remember a range of unused IDs
344 	 * ready to use (from lastpid+1 through pidchecked-1).
345 	 *
346 	 * If RFHIGHPID is set (used during system boot), do not allocate
347 	 * low-numbered pids.
348 	 */
349 	trypid = lastpid + 1;
350 	if (flags & RFHIGHPID) {
351 		if (trypid < 10)
352 			trypid = 10;
353 	} else {
354 		if (randompid)
355 			trypid += arc4random() % randompid;
356 	}
357 retry:
358 	/*
359 	 * If the process ID prototype has wrapped around,
360 	 * restart somewhat above 0, as the low-numbered procs
361 	 * tend to include daemons that don't exit.
362 	 */
363 	if (trypid >= PID_MAX) {
364 		trypid = trypid % PID_MAX;
365 		if (trypid < 100)
366 			trypid += 100;
367 		pidchecked = 0;
368 	}
369 	if (trypid >= pidchecked) {
370 		int doingzomb = 0;
371 
372 		pidchecked = PID_MAX;
373 		/*
374 		 * Scan the active and zombie procs to check whether this pid
375 		 * is in use.  Remember the lowest pid that's greater
376 		 * than trypid, so we can avoid checking for a while.
377 		 */
378 		p2 = LIST_FIRST(&allproc);
379 again:
380 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
381 			while (p2->p_pid == trypid ||
382 			    (p2->p_pgrp != NULL &&
383 			    (p2->p_pgrp->pg_id == trypid ||
384 			    (p2->p_session != NULL &&
385 			    p2->p_session->s_sid == trypid)))) {
386 				trypid++;
387 				if (trypid >= pidchecked)
388 					goto retry;
389 			}
390 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
391 				pidchecked = p2->p_pid;
392 			if (p2->p_pgrp != NULL) {
393 				if (p2->p_pgrp->pg_id > trypid &&
394 				    pidchecked > p2->p_pgrp->pg_id)
395 					pidchecked = p2->p_pgrp->pg_id;
396 				if (p2->p_session != NULL &&
397 				    p2->p_session->s_sid > trypid &&
398 				    pidchecked > p2->p_session->s_sid)
399 					pidchecked = p2->p_session->s_sid;
400 			}
401 		}
402 		if (!doingzomb) {
403 			doingzomb = 1;
404 			p2 = LIST_FIRST(&zombproc);
405 			goto again;
406 		}
407 	}
408 	sx_sunlock(&proctree_lock);
409 
410 	/*
411 	 * RFHIGHPID does not mess with the lastpid counter during boot.
412 	 */
413 	if (flags & RFHIGHPID)
414 		pidchecked = 0;
415 	else
416 		lastpid = trypid;
417 
418 	p2 = newproc;
419 	p2->p_state = PRS_NEW;		/* protect against others */
420 	p2->p_pid = trypid;
421 	AUDIT_ARG(pid, p2->p_pid);
422 	LIST_INSERT_HEAD(&allproc, p2, p_list);
423 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
424 
425 	PROC_LOCK(p2);
426 	PROC_LOCK(p1);
427 
428 	sx_xunlock(&allproc_lock);
429 
430 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
431 	    __rangeof(struct proc, p_startcopy, p_endcopy));
432 	PROC_UNLOCK(p1);
433 
434 	bzero(&p2->p_startzero,
435 	    __rangeof(struct proc, p_startzero, p_endzero));
436 
437 	p2->p_ucred = crhold(td->td_ucred);
438 	PROC_UNLOCK(p2);
439 
440 	/*
441 	 * Malloc things while we don't hold any locks.
442 	 */
443 	if (flags & RFSIGSHARE)
444 		newsigacts = NULL;
445 	else
446 		newsigacts = sigacts_alloc();
447 
448 	/*
449 	 * Copy filedesc.
450 	 */
451 	if (flags & RFCFDG) {
452 		fd = fdinit(p1->p_fd);
453 		fdtol = NULL;
454 	} else if (flags & RFFDG) {
455 		fd = fdcopy(p1->p_fd);
456 		fdtol = NULL;
457 	} else {
458 		fd = fdshare(p1->p_fd);
459 		if (p1->p_fdtol == NULL)
460 			p1->p_fdtol =
461 				filedesc_to_leader_alloc(NULL,
462 							 NULL,
463 							 p1->p_leader);
464 		if ((flags & RFTHREAD) != 0) {
465 			/*
466 			 * Shared file descriptor table and
467 			 * shared process leaders.
468 			 */
469 			fdtol = p1->p_fdtol;
470 			FILEDESC_LOCK_FAST(p1->p_fd);
471 			fdtol->fdl_refcount++;
472 			FILEDESC_UNLOCK_FAST(p1->p_fd);
473 		} else {
474 			/*
475 			 * Shared file descriptor table, and
476 			 * different process leaders
477 			 */
478 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
479 							 p1->p_fd,
480 							 p2);
481 		}
482 	}
483 	/*
484 	 * Make a proc table entry for the new process.
485 	 * Start by zeroing the section of proc that is zero-initialized,
486 	 * then copy the section that is copied directly from the parent.
487 	 */
488 	td2 = FIRST_THREAD_IN_PROC(p2);
489 
490 	/* Allocate and switch to an alternate kstack if specified. */
491 	if (pages != 0)
492 		vm_thread_new_altkstack(td2, pages);
493 
494 	PROC_LOCK(p2);
495 	PROC_LOCK(p1);
496 
497 	bzero(&td2->td_startzero,
498 	    __rangeof(struct thread, td_startzero, td_endzero));
499 
500 	bcopy(&td->td_startcopy, &td2->td_startcopy,
501 	    __rangeof(struct thread, td_startcopy, td_endcopy));
502 
503 	td2->td_sigstk = td->td_sigstk;
504 	td2->td_sigmask = td->td_sigmask;
505 
506 	/*
507 	 * Duplicate sub-structures as needed.
508 	 * Increase reference counts on shared objects.
509 	 */
510 	p2->p_flag = 0;
511 	if (p1->p_flag & P_PROFIL)
512 		startprofclock(p2);
513 	mtx_lock_spin(&sched_lock);
514 	p2->p_sflag = PS_INMEM;
515 	/*
516 	 * Allow the scheduler to adjust the priority of the child and
517 	 * parent while we hold the sched_lock.
518 	 */
519 	sched_fork(td, td2);
520 
521 	mtx_unlock_spin(&sched_lock);
522 	td2->td_ucred = crhold(p2->p_ucred);
523 #ifdef AUDIT
524 	audit_proc_fork(p1, p2);
525 #endif
526 	pargs_hold(p2->p_args);
527 
528 	if (flags & RFSIGSHARE) {
529 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
530 	} else {
531 		sigacts_copy(newsigacts, p1->p_sigacts);
532 		p2->p_sigacts = newsigacts;
533 	}
534 	if (flags & RFLINUXTHPN)
535 	        p2->p_sigparent = SIGUSR1;
536 	else
537 	        p2->p_sigparent = SIGCHLD;
538 
539 	p2->p_textvp = p1->p_textvp;
540 	p2->p_fd = fd;
541 	p2->p_fdtol = fdtol;
542 
543 	/*
544 	 * p_limit is copy-on-write.  Bump its refcount.
545 	 */
546 	p2->p_limit = lim_hold(p1->p_limit);
547 
548 	pstats_fork(p1->p_stats, p2->p_stats);
549 
550 	PROC_UNLOCK(p1);
551 	PROC_UNLOCK(p2);
552 
553 	/* Bump references to the text vnode (for procfs) */
554 	if (p2->p_textvp)
555 		vref(p2->p_textvp);
556 
557 	/*
558 	 * Set up linkage for kernel based threading.
559 	 */
560 	if ((flags & RFTHREAD) != 0) {
561 		mtx_lock(&ppeers_lock);
562 		p2->p_peers = p1->p_peers;
563 		p1->p_peers = p2;
564 		p2->p_leader = p1->p_leader;
565 		mtx_unlock(&ppeers_lock);
566 		PROC_LOCK(p1->p_leader);
567 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
568 			PROC_UNLOCK(p1->p_leader);
569 			/*
570 			 * The task leader is exiting, so process p1 is
571 			 * going to be killed shortly.  Since p1 obviously
572 			 * isn't dead yet, we know that the leader is either
573 			 * sending SIGKILL's to all the processes in this
574 			 * task or is sleeping waiting for all the peers to
575 			 * exit.  We let p1 complete the fork, but we need
576 			 * to go ahead and kill the new process p2 since
577 			 * the task leader may not get a chance to send
578 			 * SIGKILL to it.  We leave it on the list so that
579 			 * the task leader will wait for this new process
580 			 * to commit suicide.
581 			 */
582 			PROC_LOCK(p2);
583 			psignal(p2, SIGKILL);
584 			PROC_UNLOCK(p2);
585 		} else
586 			PROC_UNLOCK(p1->p_leader);
587 	} else {
588 		p2->p_peers = NULL;
589 		p2->p_leader = p2;
590 	}
591 
592 	sx_xlock(&proctree_lock);
593 	PGRP_LOCK(p1->p_pgrp);
594 	PROC_LOCK(p2);
595 	PROC_LOCK(p1);
596 
597 	/*
598 	 * Preserve some more flags in subprocess.  P_PROFIL has already
599 	 * been preserved.
600 	 */
601 	p2->p_flag |= p1->p_flag & P_SUGID;
602 	td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
603 	SESS_LOCK(p1->p_session);
604 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
605 		p2->p_flag |= P_CONTROLT;
606 	SESS_UNLOCK(p1->p_session);
607 	if (flags & RFPPWAIT)
608 		p2->p_flag |= P_PPWAIT;
609 
610 	p2->p_pgrp = p1->p_pgrp;
611 	LIST_INSERT_AFTER(p1, p2, p_pglist);
612 	PGRP_UNLOCK(p1->p_pgrp);
613 	LIST_INIT(&p2->p_children);
614 
615 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
616 
617 #ifdef KTRACE
618 	/*
619 	 * Copy traceflag and tracefile if enabled.
620 	 */
621 	mtx_lock(&ktrace_mtx);
622 	KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
623 	if (p1->p_traceflag & KTRFAC_INHERIT) {
624 		p2->p_traceflag = p1->p_traceflag;
625 		if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
626 			VREF(p2->p_tracevp);
627 			KASSERT(p1->p_tracecred != NULL,
628 			    ("ktrace vnode with no cred"));
629 			p2->p_tracecred = crhold(p1->p_tracecred);
630 		}
631 	}
632 	mtx_unlock(&ktrace_mtx);
633 #endif
634 
635 	/*
636 	 * If PF_FORK is set, the child process inherits the
637 	 * procfs ioctl flags from its parent.
638 	 */
639 	if (p1->p_pfsflags & PF_FORK) {
640 		p2->p_stops = p1->p_stops;
641 		p2->p_pfsflags = p1->p_pfsflags;
642 	}
643 
644 	/*
645 	 * This begins the section where we must prevent the parent
646 	 * from being swapped.
647 	 */
648 	_PHOLD(p1);
649 	PROC_UNLOCK(p1);
650 
651 	/*
652 	 * Attach the new process to its parent.
653 	 *
654 	 * If RFNOWAIT is set, the newly created process becomes a child
655 	 * of init.  This effectively disassociates the child from the
656 	 * parent.
657 	 */
658 	if (flags & RFNOWAIT)
659 		pptr = initproc;
660 	else
661 		pptr = p1;
662 	p2->p_pptr = pptr;
663 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
664 	sx_xunlock(&proctree_lock);
665 
666 	/* Inform accounting that we have forked. */
667 	p2->p_acflag = AFORK;
668 	PROC_UNLOCK(p2);
669 
670 	/*
671 	 * Finish creating the child process.  It will return via a different
672 	 * execution path later.  (ie: directly into user mode)
673 	 */
674 	vm_forkproc(td, p2, td2, flags);
675 
676 	if (flags == (RFFDG | RFPROC)) {
677 		atomic_add_int(&cnt.v_forks, 1);
678 		atomic_add_int(&cnt.v_forkpages, p2->p_vmspace->vm_dsize +
679 		    p2->p_vmspace->vm_ssize);
680 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
681 		atomic_add_int(&cnt.v_vforks, 1);
682 		atomic_add_int(&cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
683 		    p2->p_vmspace->vm_ssize);
684 	} else if (p1 == &proc0) {
685 		atomic_add_int(&cnt.v_kthreads, 1);
686 		atomic_add_int(&cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
687 		    p2->p_vmspace->vm_ssize);
688 	} else {
689 		atomic_add_int(&cnt.v_rforks, 1);
690 		atomic_add_int(&cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
691 		    p2->p_vmspace->vm_ssize);
692 	}
693 
694 	/*
695 	 * Both processes are set up, now check if any loadable modules want
696 	 * to adjust anything.
697 	 *   What if they have an error? XXX
698 	 */
699 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
700 
701 	/*
702 	 * Set the child start time and mark the process as being complete.
703 	 */
704 	microuptime(&p2->p_stats->p_start);
705 	mtx_lock_spin(&sched_lock);
706 	p2->p_state = PRS_NORMAL;
707 
708 	/*
709 	 * If RFSTOPPED not requested, make child runnable and add to
710 	 * run queue.
711 	 */
712 	if ((flags & RFSTOPPED) == 0) {
713 		TD_SET_CAN_RUN(td2);
714 		sched_add(td2, SRQ_BORING);
715 	}
716 	mtx_unlock_spin(&sched_lock);
717 
718 	/*
719 	 * Now can be swapped.
720 	 */
721 	PROC_LOCK(p1);
722 	_PRELE(p1);
723 
724 	/*
725 	 * Tell any interested parties about the new process.
726 	 */
727 	KNOTE_LOCKED(&p1->p_klist, NOTE_FORK | p2->p_pid);
728 
729 	PROC_UNLOCK(p1);
730 
731 	/*
732 	 * Preserve synchronization semantics of vfork.  If waiting for
733 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
734 	 * proc (in case of exit).
735 	 */
736 	PROC_LOCK(p2);
737 	while (p2->p_flag & P_PPWAIT)
738 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
739 	PROC_UNLOCK(p2);
740 
741 	/*
742 	 * If other threads are waiting, let them continue now.
743 	 */
744 	if (p1->p_flag & P_HADTHREADS) {
745 		PROC_LOCK(p1);
746 		thread_single_end();
747 		PROC_UNLOCK(p1);
748 	}
749 
750 	/*
751 	 * Return child proc pointer to parent.
752 	 */
753 	*procp = p2;
754 	return (0);
755 fail:
756 	sx_sunlock(&proctree_lock);
757 	if (ppsratecheck(&lastfail, &curfail, 1))
758 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
759 		    td->td_ucred->cr_ruid);
760 	sx_xunlock(&allproc_lock);
761 #ifdef MAC
762 	mac_destroy_proc(newproc);
763 #endif
764 #ifdef AUDIT
765 	audit_proc_free(newproc);
766 #endif
767 	uma_zfree(proc_zone, newproc);
768 	if (p1->p_flag & P_HADTHREADS) {
769 		PROC_LOCK(p1);
770 		thread_single_end();
771 		PROC_UNLOCK(p1);
772 	}
773 	pause("fork", hz / 2);
774 	return (error);
775 }
776 
777 /*
778  * Handle the return of a child process from fork1().  This function
779  * is called from the MD fork_trampoline() entry point.
780  */
781 void
782 fork_exit(callout, arg, frame)
783 	void (*callout)(void *, struct trapframe *);
784 	void *arg;
785 	struct trapframe *frame;
786 {
787 	struct proc *p;
788 	struct thread *td;
789 
790 	/*
791 	 * Finish setting up thread glue so that it begins execution in a
792 	 * non-nested critical section with sched_lock held but not recursed.
793 	 */
794 	td = curthread;
795 	p = td->td_proc;
796 	td->td_oncpu = PCPU_GET(cpuid);
797 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
798 
799 	sched_lock.mtx_lock = (uintptr_t)td;
800 	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
801 	CTR4(KTR_PROC, "fork_exit: new thread %p (kse %p, pid %d, %s)",
802 		td, td->td_sched, p->p_pid, p->p_comm);
803 
804 	/*
805 	 * Processes normally resume in mi_switch() after being
806 	 * cpu_switch()'ed to, but when children start up they arrive here
807 	 * instead, so we must do much the same things as mi_switch() would.
808 	 */
809 
810 	if ((td = PCPU_GET(deadthread))) {
811 		PCPU_SET(deadthread, NULL);
812 		thread_stash(td);
813 	}
814 	td = curthread;
815 	mtx_unlock_spin(&sched_lock);
816 
817 	/*
818 	 * cpu_set_fork_handler intercepts this function call to
819 	 * have this call a non-return function to stay in kernel mode.
820 	 * initproc has its own fork handler, but it does return.
821 	 */
822 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
823 	callout(arg, frame);
824 
825 	/*
826 	 * Check if a kernel thread misbehaved and returned from its main
827 	 * function.
828 	 */
829 	if (p->p_flag & P_KTHREAD) {
830 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
831 		    p->p_comm, p->p_pid);
832 		kthread_exit(0);
833 	}
834 	mtx_assert(&Giant, MA_NOTOWNED);
835 
836 	EVENTHANDLER_INVOKE(schedtail, p);
837 }
838 
839 /*
840  * Simplified back end of syscall(), used when returning from fork()
841  * directly into user mode.  Giant is not held on entry, and must not
842  * be held on return.  This function is passed in to fork_exit() as the
843  * first parameter and is called when returning to a new userland process.
844  */
845 void
846 fork_return(td, frame)
847 	struct thread *td;
848 	struct trapframe *frame;
849 {
850 
851 	userret(td, frame);
852 #ifdef KTRACE
853 	if (KTRPOINT(td, KTR_SYSRET))
854 		ktrsysret(SYS_fork, 0, 0);
855 #endif
856 	mtx_assert(&Giant, MA_NOTOWNED);
857 }
858