xref: /freebsd/sys/kern/kern_fork.c (revision d2387d42b8da231a5b95cbc313825fb2aadf26f6)
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_ktrace.h"
45 #include "opt_mac.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/sysproto.h>
50 #include <sys/eventhandler.h>
51 #include <sys/filedesc.h>
52 #include <sys/kernel.h>
53 #include <sys/kthread.h>
54 #include <sys/sysctl.h>
55 #include <sys/lock.h>
56 #include <sys/malloc.h>
57 #include <sys/mutex.h>
58 #include <sys/proc.h>
59 #include <sys/pioctl.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/mac.h>
67 #include <sys/ktr.h>
68 #include <sys/ktrace.h>
69 #include <sys/unistd.h>
70 #include <sys/sx.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 #include <sys/user.h>
79 #include <machine/critical.h>
80 
81 #ifndef _SYS_SYSPROTO_H_
82 struct fork_args {
83 	int     dummy;
84 };
85 #endif
86 
87 static int forksleep; /* Place for fork1() to sleep on. */
88 
89 /*
90  * MPSAFE
91  */
92 /* ARGSUSED */
93 int
94 fork(td, uap)
95 	struct thread *td;
96 	struct fork_args *uap;
97 {
98 	int error;
99 	struct proc *p2;
100 
101 	error = fork1(td, RFFDG | RFPROC, 0, &p2);
102 	if (error == 0) {
103 		td->td_retval[0] = p2->p_pid;
104 		td->td_retval[1] = 0;
105 	}
106 	return (error);
107 }
108 
109 /*
110  * MPSAFE
111  */
112 /* ARGSUSED */
113 int
114 vfork(td, uap)
115 	struct thread *td;
116 	struct vfork_args *uap;
117 {
118 	int error;
119 	struct proc *p2;
120 
121 	error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
122 	if (error == 0) {
123 		td->td_retval[0] = p2->p_pid;
124 		td->td_retval[1] = 0;
125 	}
126 	return (error);
127 }
128 
129 /*
130  * MPSAFE
131  */
132 int
133 rfork(td, uap)
134 	struct thread *td;
135 	struct rfork_args *uap;
136 {
137 	struct proc *p2;
138 	int error;
139 
140 	/* Don't allow kernel-only flags. */
141 	if ((uap->flags & RFKERNELONLY) != 0)
142 		return (EINVAL);
143 
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 int
195 fork1(td, flags, pages, procp)
196 	struct thread *td;
197 	int flags;
198 	int pages;
199 	struct proc **procp;
200 {
201 	struct proc *p1, *p2, *pptr;
202 	uid_t uid;
203 	struct proc *newproc;
204 	int ok, trypid;
205 	static int curfail, pidchecked = 0;
206 	static struct timeval lastfail;
207 	struct filedesc *fd;
208 	struct filedesc_to_leader *fdtol;
209 	struct thread *td2;
210 	struct kse *ke2;
211 	struct ksegrp *kg2;
212 	struct sigacts *newsigacts;
213 	int error;
214 
215 	/* Can't copy and clear. */
216 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
217 		return (EINVAL);
218 
219 	p1 = td->td_proc;
220 
221 	/*
222 	 * Here we don't create a new process, but we divorce
223 	 * certain parts of a process from itself.
224 	 */
225 	if ((flags & RFPROC) == 0) {
226 		mtx_lock(&Giant);
227 		vm_forkproc(td, NULL, NULL, flags);
228 		mtx_unlock(&Giant);
229 
230 		/*
231 		 * Close all file descriptors.
232 		 */
233 		if (flags & RFCFDG) {
234 			struct filedesc *fdtmp;
235 			FILEDESC_LOCK(td->td_proc->p_fd);
236 			fdtmp = fdinit(td->td_proc->p_fd);
237 			FILEDESC_UNLOCK(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 			FILEDESC_LOCK(p1->p_fd);
247 			if (p1->p_fd->fd_refcnt > 1) {
248 				struct filedesc *newfd;
249 
250 				newfd = fdcopy(td->td_proc->p_fd);
251 				FILEDESC_UNLOCK(p1->p_fd);
252 				fdfree(td);
253 				p1->p_fd = newfd;
254 			} else
255 				FILEDESC_UNLOCK(p1->p_fd);
256 		}
257 		*procp = NULL;
258 		return (0);
259 	}
260 
261 	/*
262 	 * Note 1:1 allows for forking with one thread coming out on the
263 	 * other side with the expectation that the process is about to
264 	 * exec.
265 	 */
266 	if (p1->p_flag & P_SA) {
267 		/*
268 		 * Idle the other threads for a second.
269 		 * Since the user space is copied, it must remain stable.
270 		 * In addition, all threads (from the user perspective)
271 		 * need to either be suspended or in the kernel,
272 		 * where they will try restart in the parent and will
273 		 * be aborted in the child.
274 		 */
275 		PROC_LOCK(p1);
276 		if (thread_single(SINGLE_NO_EXIT)) {
277 			/* Abort. Someone else is single threading before us. */
278 			PROC_UNLOCK(p1);
279 			return (ERESTART);
280 		}
281 		PROC_UNLOCK(p1);
282 		/*
283 		 * All other activity in this process
284 		 * is now suspended at the user boundary,
285 		 * (or other safe places if we think of any).
286 		 */
287 	}
288 
289 	/* Allocate new proc. */
290 	newproc = uma_zalloc(proc_zone, M_WAITOK);
291 #ifdef MAC
292 	mac_init_proc(newproc);
293 #endif
294 
295 	/* We have to lock the process tree while we look for a pid. */
296 	sx_slock(&proctree_lock);
297 
298 	/*
299 	 * Although process entries are dynamically created, we still keep
300 	 * a global limit on the maximum number we will create.  Don't allow
301 	 * a nonprivileged user to use the last ten processes; don't let root
302 	 * exceed the limit. The variable nprocs is the current number of
303 	 * processes, maxproc is the limit.
304 	 */
305 	sx_xlock(&allproc_lock);
306 	uid = td->td_ucred->cr_ruid;
307 	if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) {
308 		error = EAGAIN;
309 		goto fail;
310 	}
311 
312 	/*
313 	 * Increment the count of procs running with this uid. Don't allow
314 	 * a nonprivileged user to exceed their current limit.
315 	 */
316 	PROC_LOCK(p1);
317 	ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
318 		(uid != 0) ? lim_cur(p1, RLIMIT_NPROC) : 0);
319 	PROC_UNLOCK(p1);
320 	if (!ok) {
321 		error = EAGAIN;
322 		goto fail;
323 	}
324 
325 	/*
326 	 * Increment the nprocs resource before blocking can occur.  There
327 	 * are hard-limits as to the number of processes that can run.
328 	 */
329 	nprocs++;
330 
331 	/*
332 	 * Find an unused process ID.  We remember a range of unused IDs
333 	 * ready to use (from lastpid+1 through pidchecked-1).
334 	 *
335 	 * If RFHIGHPID is set (used during system boot), do not allocate
336 	 * low-numbered pids.
337 	 */
338 	trypid = lastpid + 1;
339 	if (flags & RFHIGHPID) {
340 		if (trypid < 10)
341 			trypid = 10;
342 	} else {
343 		if (randompid)
344 			trypid += arc4random() % randompid;
345 	}
346 retry:
347 	/*
348 	 * If the process ID prototype has wrapped around,
349 	 * restart somewhat above 0, as the low-numbered procs
350 	 * tend to include daemons that don't exit.
351 	 */
352 	if (trypid >= PID_MAX) {
353 		trypid = trypid % PID_MAX;
354 		if (trypid < 100)
355 			trypid += 100;
356 		pidchecked = 0;
357 	}
358 	if (trypid >= pidchecked) {
359 		int doingzomb = 0;
360 
361 		pidchecked = PID_MAX;
362 		/*
363 		 * Scan the active and zombie procs to check whether this pid
364 		 * is in use.  Remember the lowest pid that's greater
365 		 * than trypid, so we can avoid checking for a while.
366 		 */
367 		p2 = LIST_FIRST(&allproc);
368 again:
369 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
370 			PROC_LOCK(p2);
371 			while (p2->p_pid == trypid ||
372 			    (p2->p_pgrp != NULL &&
373 			    (p2->p_pgrp->pg_id == trypid ||
374 			    (p2->p_session != NULL &&
375 			    p2->p_session->s_sid == trypid)))) {
376 				trypid++;
377 				if (trypid >= pidchecked) {
378 					PROC_UNLOCK(p2);
379 					goto retry;
380 				}
381 			}
382 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
383 				pidchecked = p2->p_pid;
384 			if (p2->p_pgrp != NULL) {
385 				if (p2->p_pgrp->pg_id > trypid &&
386 				    pidchecked > p2->p_pgrp->pg_id)
387 					pidchecked = p2->p_pgrp->pg_id;
388 				if (p2->p_session != NULL &&
389 				    p2->p_session->s_sid > trypid &&
390 				    pidchecked > p2->p_session->s_sid)
391 					pidchecked = p2->p_session->s_sid;
392 			}
393 			PROC_UNLOCK(p2);
394 		}
395 		if (!doingzomb) {
396 			doingzomb = 1;
397 			p2 = LIST_FIRST(&zombproc);
398 			goto again;
399 		}
400 	}
401 	sx_sunlock(&proctree_lock);
402 
403 	/*
404 	 * RFHIGHPID does not mess with the lastpid counter during boot.
405 	 */
406 	if (flags & RFHIGHPID)
407 		pidchecked = 0;
408 	else
409 		lastpid = trypid;
410 
411 	p2 = newproc;
412 	p2->p_state = PRS_NEW;		/* protect against others */
413 	p2->p_pid = trypid;
414 	LIST_INSERT_HEAD(&allproc, p2, p_list);
415 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
416 	sx_xunlock(&allproc_lock);
417 
418 	/*
419 	 * Malloc things while we don't hold any locks.
420 	 */
421 	if (flags & RFSIGSHARE)
422 		newsigacts = NULL;
423 	else
424 		newsigacts = sigacts_alloc();
425 
426 	/*
427 	 * Copy filedesc.
428 	 */
429 	if (flags & RFCFDG) {
430 		FILEDESC_LOCK(td->td_proc->p_fd);
431 		fd = fdinit(td->td_proc->p_fd);
432 		FILEDESC_UNLOCK(td->td_proc->p_fd);
433 		fdtol = NULL;
434 	} else if (flags & RFFDG) {
435 		FILEDESC_LOCK(p1->p_fd);
436 		fd = fdcopy(td->td_proc->p_fd);
437 		FILEDESC_UNLOCK(p1->p_fd);
438 		fdtol = NULL;
439 	} else {
440 		fd = fdshare(p1->p_fd);
441 		if (p1->p_fdtol == NULL)
442 			p1->p_fdtol =
443 				filedesc_to_leader_alloc(NULL,
444 							 NULL,
445 							 p1->p_leader);
446 		if ((flags & RFTHREAD) != 0) {
447 			/*
448 			 * Shared file descriptor table and
449 			 * shared process leaders.
450 			 */
451 			fdtol = p1->p_fdtol;
452 			FILEDESC_LOCK(p1->p_fd);
453 			fdtol->fdl_refcount++;
454 			FILEDESC_UNLOCK(p1->p_fd);
455 		} else {
456 			/*
457 			 * Shared file descriptor table, and
458 			 * different process leaders
459 			 */
460 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
461 							 p1->p_fd,
462 							 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 	td2 = FIRST_THREAD_IN_PROC(p2);
471 	kg2 = FIRST_KSEGRP_IN_PROC(p2);
472 	ke2 = FIRST_KSE_IN_KSEGRP(kg2);
473 
474 	/* Allocate and switch to an alternate kstack if specified. */
475 	if (pages != 0)
476 		vm_thread_new_altkstack(td2, pages);
477 
478 	PROC_LOCK(p2);
479 	PROC_LOCK(p1);
480 
481 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
482 
483 	bzero(&p2->p_startzero,
484 	    (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
485 	bzero(&ke2->ke_startzero,
486 	    (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
487 	bzero(&td2->td_startzero,
488 	    (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
489 	bzero(&kg2->kg_startzero,
490 	    (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
491 
492 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
493 	    (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
494 	bcopy(&td->td_startcopy, &td2->td_startcopy,
495 	    (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
496 	bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
497 	    (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
498 #undef RANGEOF
499 
500 	td2->td_tid = p2->p_pid;
501 	td2->td_sigstk = td->td_sigstk;
502 
503 	/* Set up the thread as an active thread (as if runnable). */
504 	ke2->ke_state = KES_THREAD;
505 	ke2->ke_thread = td2;
506 	td2->td_kse = ke2;
507 
508 	/*
509 	 * Duplicate sub-structures as needed.
510 	 * Increase reference counts on shared objects.
511 	 * The p_stats substruct is set in vm_forkproc.
512 	 */
513 	p2->p_flag = 0;
514 	if (p1->p_flag & P_PROFIL)
515 		startprofclock(p2);
516 	mtx_lock_spin(&sched_lock);
517 	p2->p_sflag = PS_INMEM;
518 	/*
519 	 * Allow the scheduler to adjust the priority of the child and
520 	 * parent while we hold the sched_lock.
521 	 */
522 	sched_fork(p1, p2);
523 
524 	mtx_unlock_spin(&sched_lock);
525 	p2->p_ucred = crhold(td->td_ucred);
526 	td2->td_ucred = crhold(p2->p_ucred);	/* XXXKSE */
527 
528 	pargs_hold(p2->p_args);
529 
530 	if (flags & RFSIGSHARE) {
531 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
532 	} else {
533 		sigacts_copy(newsigacts, p1->p_sigacts);
534 		p2->p_sigacts = newsigacts;
535 	}
536 	if (flags & RFLINUXTHPN)
537 	        p2->p_sigparent = SIGUSR1;
538 	else
539 	        p2->p_sigparent = SIGCHLD;
540 
541 	p2->p_textvp = p1->p_textvp;
542 	p2->p_fd = fd;
543 	p2->p_fdtol = fdtol;
544 
545 	/*
546 	 * p_limit is copy-on-write.  Bump its refcount.
547 	 */
548 	p2->p_limit = lim_hold(p1->p_limit);
549 	PROC_UNLOCK(p1);
550 	PROC_UNLOCK(p2);
551 
552 	/* Bump references to the text vnode (for procfs) */
553 	if (p2->p_textvp)
554 		vref(p2->p_textvp);
555 
556 	/*
557 	 * Set up linkage for kernel based threading.
558 	 */
559 	if ((flags & RFTHREAD) != 0) {
560 		mtx_lock(&ppeers_lock);
561 		p2->p_peers = p1->p_peers;
562 		p1->p_peers = p2;
563 		p2->p_leader = p1->p_leader;
564 		mtx_unlock(&ppeers_lock);
565 		PROC_LOCK(p1->p_leader);
566 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
567 			PROC_UNLOCK(p1->p_leader);
568 			/*
569 			 * The task leader is exiting, so process p1 is
570 			 * going to be killed shortly.  Since p1 obviously
571 			 * isn't dead yet, we know that the leader is either
572 			 * sending SIGKILL's to all the processes in this
573 			 * task or is sleeping waiting for all the peers to
574 			 * exit.  We let p1 complete the fork, but we need
575 			 * to go ahead and kill the new process p2 since
576 			 * the task leader may not get a chance to send
577 			 * SIGKILL to it.  We leave it on the list so that
578 			 * the task leader will wait for this new process
579 			 * to commit suicide.
580 			 */
581 			PROC_LOCK(p2);
582 			psignal(p2, SIGKILL);
583 			PROC_UNLOCK(p2);
584 		} else
585 			PROC_UNLOCK(p1->p_leader);
586 	} else {
587 		p2->p_peers = NULL;
588 		p2->p_leader = p2;
589 	}
590 
591 	sx_xlock(&proctree_lock);
592 	PGRP_LOCK(p1->p_pgrp);
593 	PROC_LOCK(p2);
594 	PROC_LOCK(p1);
595 
596 	/*
597 	 * Preserve some more flags in subprocess.  P_PROFIL has already
598 	 * been preserved.
599 	 */
600 	p2->p_flag |= p1->p_flag & P_SUGID;
601 	td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
602 	SESS_LOCK(p1->p_session);
603 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
604 		p2->p_flag |= P_CONTROLT;
605 	SESS_UNLOCK(p1->p_session);
606 	if (flags & RFPPWAIT)
607 		p2->p_flag |= P_PPWAIT;
608 
609 	p2->p_pgrp = p1->p_pgrp;
610 	LIST_INSERT_AFTER(p1, p2, p_pglist);
611 	PGRP_UNLOCK(p1->p_pgrp);
612 	LIST_INIT(&p2->p_children);
613 
614 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
615 
616 #ifdef KTRACE
617 	/*
618 	 * Copy traceflag and tracefile if enabled.
619 	 */
620 	mtx_lock(&ktrace_mtx);
621 	KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
622 	if (p1->p_traceflag & KTRFAC_INHERIT) {
623 		p2->p_traceflag = p1->p_traceflag;
624 		if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
625 			VREF(p2->p_tracevp);
626 			KASSERT(p1->p_tracecred != NULL,
627 			    ("ktrace vnode with no cred"));
628 			p2->p_tracecred = crhold(p1->p_tracecred);
629 		}
630 	}
631 	mtx_unlock(&ktrace_mtx);
632 #endif
633 
634 	/*
635 	 * If PF_FORK is set, the child process inherits the
636 	 * procfs ioctl flags from its parent.
637 	 */
638 	if (p1->p_pfsflags & PF_FORK) {
639 		p2->p_stops = p1->p_stops;
640 		p2->p_pfsflags = p1->p_pfsflags;
641 	}
642 
643 	/*
644 	 * This begins the section where we must prevent the parent
645 	 * from being swapped.
646 	 */
647 	_PHOLD(p1);
648 	PROC_UNLOCK(p1);
649 
650 	/*
651 	 * Attach the new process to its parent.
652 	 *
653 	 * If RFNOWAIT is set, the newly created process becomes a child
654 	 * of init.  This effectively disassociates the child from the
655 	 * parent.
656 	 */
657 	if (flags & RFNOWAIT)
658 		pptr = initproc;
659 	else
660 		pptr = p1;
661 	p2->p_pptr = pptr;
662 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
663 	sx_xunlock(&proctree_lock);
664 
665 	/* Inform accounting that we have forked. */
666 	p2->p_acflag = AFORK;
667 	PROC_UNLOCK(p2);
668 
669 	/*
670 	 * Finish creating the child process.  It will return via a different
671 	 * execution path later.  (ie: directly into user mode)
672 	 */
673 	mtx_lock(&Giant);
674 	vm_forkproc(td, p2, td2, flags);
675 
676 	if (flags == (RFFDG | RFPROC)) {
677 		cnt.v_forks++;
678 		cnt.v_forkpages += p2->p_vmspace->vm_dsize +
679 		    p2->p_vmspace->vm_ssize;
680 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
681 		cnt.v_vforks++;
682 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize +
683 		    p2->p_vmspace->vm_ssize;
684 	} else if (p1 == &proc0) {
685 		cnt.v_kthreads++;
686 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize +
687 		    p2->p_vmspace->vm_ssize;
688 	} else {
689 		cnt.v_rforks++;
690 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize +
691 		    p2->p_vmspace->vm_ssize;
692 	}
693 	mtx_unlock(&Giant);
694 
695 	/*
696 	 * Both processes are set up, now check if any loadable modules want
697 	 * to adjust anything.
698 	 *   What if they have an error? XXX
699 	 */
700 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
701 
702 	/*
703 	 * Set the child start time and mark the process as being complete.
704 	 */
705 	microuptime(&p2->p_stats->p_start);
706 	mtx_lock_spin(&sched_lock);
707 	p2->p_state = PRS_NORMAL;
708 
709 	/*
710 	 * If RFSTOPPED not requested, make child runnable and add to
711 	 * run queue.
712 	 */
713 	if ((flags & RFSTOPPED) == 0) {
714 		TD_SET_CAN_RUN(td2);
715 		setrunqueue(td2);
716 	}
717 	mtx_unlock_spin(&sched_lock);
718 
719 	/*
720 	 * Now can be swapped.
721 	 */
722 	PROC_LOCK(p1);
723 	_PRELE(p1);
724 
725 	/*
726 	 * Tell any interested parties about the new process.
727 	 */
728 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
729 
730 	PROC_UNLOCK(p1);
731 
732 	/*
733 	 * Preserve synchronization semantics of vfork.  If waiting for
734 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
735 	 * proc (in case of exit).
736 	 */
737 	PROC_LOCK(p2);
738 	while (p2->p_flag & P_PPWAIT)
739 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
740 	PROC_UNLOCK(p2);
741 
742 	/*
743 	 * If other threads are waiting, let them continue now.
744 	 */
745 	if (p1->p_flag & P_SA) {
746 		PROC_LOCK(p1);
747 		thread_single_end();
748 		PROC_UNLOCK(p1);
749 	}
750 
751 	/*
752 	 * Return child proc pointer to parent.
753 	 */
754 	*procp = p2;
755 	return (0);
756 fail:
757 	sx_sunlock(&proctree_lock);
758 	if (ppsratecheck(&lastfail, &curfail, 1))
759 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
760 			uid);
761 	sx_xunlock(&allproc_lock);
762 #ifdef MAC
763 	mac_destroy_proc(newproc);
764 #endif
765 	uma_zfree(proc_zone, newproc);
766 	if (p1->p_flag & P_SA) {
767 		PROC_LOCK(p1);
768 		thread_single_end();
769 		PROC_UNLOCK(p1);
770 	}
771 	tsleep(&forksleep, PUSER, "fork", hz / 2);
772 	return (error);
773 }
774 
775 /*
776  * Handle the return of a child process from fork1().  This function
777  * is called from the MD fork_trampoline() entry point.
778  */
779 void
780 fork_exit(callout, arg, frame)
781 	void (*callout)(void *, struct trapframe *);
782 	void *arg;
783 	struct trapframe *frame;
784 {
785 	struct proc *p;
786 	struct thread *td;
787 
788 	/*
789 	 * Processes normally resume in mi_switch() after being
790 	 * cpu_switch()'ed to, but when children start up they arrive here
791 	 * instead, so we must do much the same things as mi_switch() would.
792 	 */
793 
794 	if ((td = PCPU_GET(deadthread))) {
795 		PCPU_SET(deadthread, NULL);
796 		thread_stash(td);
797 	}
798 	td = curthread;
799 	p = td->td_proc;
800 	td->td_oncpu = PCPU_GET(cpuid);
801 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
802 
803 	/*
804 	 * Finish setting up thread glue so that it begins execution in a
805 	 * non-nested critical section with sched_lock held but not recursed.
806 	 */
807 	sched_lock.mtx_lock = (uintptr_t)td;
808 	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
809 	cpu_critical_fork_exit();
810 	CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
811 	    p->p_comm);
812 	mtx_unlock_spin(&sched_lock);
813 
814 	/*
815 	 * cpu_set_fork_handler intercepts this function call to
816 	 * have this call a non-return function to stay in kernel mode.
817 	 * initproc has its own fork handler, but it does return.
818 	 */
819 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
820 	callout(arg, frame);
821 
822 	/*
823 	 * Check if a kernel thread misbehaved and returned from its main
824 	 * function.
825 	 */
826 	PROC_LOCK(p);
827 	if (p->p_flag & P_KTHREAD) {
828 		PROC_UNLOCK(p);
829 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
830 		    p->p_comm, p->p_pid);
831 		kthread_exit(0);
832 	}
833 	PROC_UNLOCK(p);
834 #ifdef DIAGNOSTIC
835 	cred_free_thread(td);
836 #endif
837 	mtx_assert(&Giant, MA_NOTOWNED);
838 }
839 
840 /*
841  * Simplified back end of syscall(), used when returning from fork()
842  * directly into user mode.  Giant is not held on entry, and must not
843  * be held on return.  This function is passed in to fork_exit() as the
844  * first parameter and is called when returning to a new userland process.
845  */
846 void
847 fork_return(td, frame)
848 	struct thread *td;
849 	struct trapframe *frame;
850 {
851 
852 	userret(td, frame, 0);
853 #ifdef KTRACE
854 	if (KTRPOINT(td, KTR_SYSRET))
855 		ktrsysret(SYS_fork, 0, 0);
856 #endif
857 	mtx_assert(&Giant, MA_NOTOWNED);
858 }
859