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