xref: /freebsd/sys/kern/kern_fork.c (revision aa0a1e58f0189b0fde359a8bda032887e72057fa)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_kdtrace.h"
41 #include "opt_ktrace.h"
42 #include "opt_kstack_pages.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/eventhandler.h>
48 #include <sys/filedesc.h>
49 #include <sys/jail.h>
50 #include <sys/kernel.h>
51 #include <sys/kthread.h>
52 #include <sys/sysctl.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mutex.h>
56 #include <sys/priv.h>
57 #include <sys/proc.h>
58 #include <sys/pioctl.h>
59 #include <sys/resourcevar.h>
60 #include <sys/sched.h>
61 #include <sys/syscall.h>
62 #include <sys/vmmeter.h>
63 #include <sys/vnode.h>
64 #include <sys/acct.h>
65 #include <sys/ktr.h>
66 #include <sys/ktrace.h>
67 #include <sys/unistd.h>
68 #include <sys/sdt.h>
69 #include <sys/sx.h>
70 #include <sys/sysent.h>
71 #include <sys/signalvar.h>
72 
73 #include <security/audit/audit.h>
74 #include <security/mac/mac_framework.h>
75 
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_extern.h>
80 #include <vm/uma.h>
81 
82 #ifdef KDTRACE_HOOKS
83 #include <sys/dtrace_bsd.h>
84 dtrace_fork_func_t	dtrace_fasttrap_fork;
85 #endif
86 
87 SDT_PROVIDER_DECLARE(proc);
88 SDT_PROBE_DEFINE(proc, kernel, , create, create);
89 SDT_PROBE_ARGTYPE(proc, kernel, , create, 0, "struct proc *");
90 SDT_PROBE_ARGTYPE(proc, kernel, , create, 1, "struct proc *");
91 SDT_PROBE_ARGTYPE(proc, kernel, , create, 2, "int");
92 
93 #ifndef _SYS_SYSPROTO_H_
94 struct fork_args {
95 	int     dummy;
96 };
97 #endif
98 
99 /* ARGSUSED */
100 int
101 fork(struct thread *td, struct fork_args *uap)
102 {
103 	int error;
104 	struct proc *p2;
105 
106 	error = fork1(td, RFFDG | RFPROC, 0, &p2);
107 	if (error == 0) {
108 		td->td_retval[0] = p2->p_pid;
109 		td->td_retval[1] = 0;
110 	}
111 	return (error);
112 }
113 
114 /* ARGSUSED */
115 int
116 vfork(struct thread *td, struct vfork_args *uap)
117 {
118 	int error, flags;
119 	struct proc *p2;
120 
121 #ifdef XEN
122 	flags = RFFDG | RFPROC; /* validate that this is still an issue */
123 #else
124 	flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
125 #endif
126 	error = fork1(td, flags, 0, &p2);
127 	if (error == 0) {
128 		td->td_retval[0] = p2->p_pid;
129 		td->td_retval[1] = 0;
130 	}
131 	return (error);
132 }
133 
134 int
135 rfork(struct thread *td, 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 	AUDIT_ARG_FFLAGS(uap->flags);
145 	error = fork1(td, uap->flags, 0, &p2);
146 	if (error == 0) {
147 		td->td_retval[0] = p2 ? p2->p_pid : 0;
148 		td->td_retval[1] = 0;
149 	}
150 	return (error);
151 }
152 
153 int	nprocs = 1;		/* process 0 */
154 int	lastpid = 0;
155 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
156     "Last used PID");
157 
158 /*
159  * Random component to lastpid generation.  We mix in a random factor to make
160  * it a little harder to predict.  We sanity check the modulus value to avoid
161  * doing it in critical paths.  Don't let it be too small or we pointlessly
162  * waste randomness entropy, and don't let it be impossibly large.  Using a
163  * modulus that is too big causes a LOT more process table scans and slows
164  * down fork processing as the pidchecked caching is defeated.
165  */
166 static int randompid = 0;
167 
168 static int
169 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
170 {
171 	int error, pid;
172 
173 	error = sysctl_wire_old_buffer(req, sizeof(int));
174 	if (error != 0)
175 		return(error);
176 	sx_xlock(&allproc_lock);
177 	pid = randompid;
178 	error = sysctl_handle_int(oidp, &pid, 0, req);
179 	if (error == 0 && req->newptr != NULL) {
180 		if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
181 			pid = PID_MAX - 100;
182 		else if (pid < 2)			/* NOP */
183 			pid = 0;
184 		else if (pid < 100)			/* Make it reasonable */
185 			pid = 100;
186 		randompid = pid;
187 	}
188 	sx_xunlock(&allproc_lock);
189 	return (error);
190 }
191 
192 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
193     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
194 
195 static int
196 fork_findpid(int flags)
197 {
198 	struct proc *p;
199 	int trypid;
200 	static int pidchecked = 0;
201 
202 	/*
203 	 * Requires allproc_lock in order to iterate over the list
204 	 * of processes, and proctree_lock to access p_pgrp.
205 	 */
206 	sx_assert(&allproc_lock, SX_LOCKED);
207 	sx_assert(&proctree_lock, SX_LOCKED);
208 
209 	/*
210 	 * Find an unused process ID.  We remember a range of unused IDs
211 	 * ready to use (from lastpid+1 through pidchecked-1).
212 	 *
213 	 * If RFHIGHPID is set (used during system boot), do not allocate
214 	 * low-numbered pids.
215 	 */
216 	trypid = lastpid + 1;
217 	if (flags & RFHIGHPID) {
218 		if (trypid < 10)
219 			trypid = 10;
220 	} else {
221 		if (randompid)
222 			trypid += arc4random() % randompid;
223 	}
224 retry:
225 	/*
226 	 * If the process ID prototype has wrapped around,
227 	 * restart somewhat above 0, as the low-numbered procs
228 	 * tend to include daemons that don't exit.
229 	 */
230 	if (trypid >= PID_MAX) {
231 		trypid = trypid % PID_MAX;
232 		if (trypid < 100)
233 			trypid += 100;
234 		pidchecked = 0;
235 	}
236 	if (trypid >= pidchecked) {
237 		int doingzomb = 0;
238 
239 		pidchecked = PID_MAX;
240 		/*
241 		 * Scan the active and zombie procs to check whether this pid
242 		 * is in use.  Remember the lowest pid that's greater
243 		 * than trypid, so we can avoid checking for a while.
244 		 */
245 		p = LIST_FIRST(&allproc);
246 again:
247 		for (; p != NULL; p = LIST_NEXT(p, p_list)) {
248 			while (p->p_pid == trypid ||
249 			    (p->p_pgrp != NULL &&
250 			    (p->p_pgrp->pg_id == trypid ||
251 			    (p->p_session != NULL &&
252 			    p->p_session->s_sid == trypid)))) {
253 				trypid++;
254 				if (trypid >= pidchecked)
255 					goto retry;
256 			}
257 			if (p->p_pid > trypid && pidchecked > p->p_pid)
258 				pidchecked = p->p_pid;
259 			if (p->p_pgrp != NULL) {
260 				if (p->p_pgrp->pg_id > trypid &&
261 				    pidchecked > p->p_pgrp->pg_id)
262 					pidchecked = p->p_pgrp->pg_id;
263 				if (p->p_session != NULL &&
264 				    p->p_session->s_sid > trypid &&
265 				    pidchecked > p->p_session->s_sid)
266 					pidchecked = p->p_session->s_sid;
267 			}
268 		}
269 		if (!doingzomb) {
270 			doingzomb = 1;
271 			p = LIST_FIRST(&zombproc);
272 			goto again;
273 		}
274 	}
275 
276 	/*
277 	 * RFHIGHPID does not mess with the lastpid counter during boot.
278 	 */
279 	if (flags & RFHIGHPID)
280 		pidchecked = 0;
281 	else
282 		lastpid = trypid;
283 
284 	return (trypid);
285 }
286 
287 static int
288 fork_norfproc(struct thread *td, int flags)
289 {
290 	int error;
291 	struct proc *p1;
292 
293 	KASSERT((flags & RFPROC) == 0,
294 	    ("fork_norfproc called with RFPROC set"));
295 	p1 = td->td_proc;
296 
297 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
298 	    (flags & (RFCFDG | RFFDG))) {
299 		PROC_LOCK(p1);
300 		if (thread_single(SINGLE_BOUNDARY)) {
301 			PROC_UNLOCK(p1);
302 			return (ERESTART);
303 		}
304 		PROC_UNLOCK(p1);
305 	}
306 
307 	error = vm_forkproc(td, NULL, NULL, NULL, flags);
308 	if (error)
309 		goto fail;
310 
311 	/*
312 	 * Close all file descriptors.
313 	 */
314 	if (flags & RFCFDG) {
315 		struct filedesc *fdtmp;
316 		fdtmp = fdinit(td->td_proc->p_fd);
317 		fdfree(td);
318 		p1->p_fd = fdtmp;
319 	}
320 
321 	/*
322 	 * Unshare file descriptors (from parent).
323 	 */
324 	if (flags & RFFDG)
325 		fdunshare(p1, td);
326 
327 fail:
328 	if (((p1->p_flag & (P_HADTHREADS|P_SYSTEM)) == P_HADTHREADS) &&
329 	    (flags & (RFCFDG | RFFDG))) {
330 		PROC_LOCK(p1);
331 		thread_single_end();
332 		PROC_UNLOCK(p1);
333 	}
334 	return (error);
335 }
336 
337 static void
338 do_fork(struct thread *td, int flags, struct proc *p2, struct thread *td2,
339     struct vmspace *vm2)
340 {
341 	struct proc *p1, *pptr;
342 	int p2_held, trypid;
343 	struct filedesc *fd;
344 	struct filedesc_to_leader *fdtol;
345 	struct sigacts *newsigacts;
346 
347 	sx_assert(&proctree_lock, SX_SLOCKED);
348 	sx_assert(&allproc_lock, SX_XLOCKED);
349 
350 	p2_held = 0;
351 	p1 = td->td_proc;
352 
353 	/*
354 	 * Increment the nprocs resource before blocking can occur.  There
355 	 * are hard-limits as to the number of processes that can run.
356 	 */
357 	nprocs++;
358 
359 	trypid = fork_findpid(flags);
360 
361 	sx_sunlock(&proctree_lock);
362 
363 	p2->p_state = PRS_NEW;		/* protect against others */
364 	p2->p_pid = trypid;
365 	AUDIT_ARG_PID(p2->p_pid);
366 	LIST_INSERT_HEAD(&allproc, p2, p_list);
367 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
368 	tidhash_add(td2);
369 	PROC_LOCK(p2);
370 	PROC_LOCK(p1);
371 
372 	sx_xunlock(&allproc_lock);
373 
374 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
375 	    __rangeof(struct proc, p_startcopy, p_endcopy));
376 	pargs_hold(p2->p_args);
377 	PROC_UNLOCK(p1);
378 
379 	bzero(&p2->p_startzero,
380 	    __rangeof(struct proc, p_startzero, p_endzero));
381 
382 	p2->p_ucred = crhold(td->td_ucred);
383 
384 	/* Tell the prison that we exist. */
385 	prison_proc_hold(p2->p_ucred->cr_prison);
386 
387 	PROC_UNLOCK(p2);
388 
389 	/*
390 	 * Malloc things while we don't hold any locks.
391 	 */
392 	if (flags & RFSIGSHARE)
393 		newsigacts = NULL;
394 	else
395 		newsigacts = sigacts_alloc();
396 
397 	/*
398 	 * Copy filedesc.
399 	 */
400 	if (flags & RFCFDG) {
401 		fd = fdinit(p1->p_fd);
402 		fdtol = NULL;
403 	} else if (flags & RFFDG) {
404 		fd = fdcopy(p1->p_fd);
405 		fdtol = NULL;
406 	} else {
407 		fd = fdshare(p1->p_fd);
408 		if (p1->p_fdtol == NULL)
409 			p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL,
410 			    p1->p_leader);
411 		if ((flags & RFTHREAD) != 0) {
412 			/*
413 			 * Shared file descriptor table, and shared
414 			 * process leaders.
415 			 */
416 			fdtol = p1->p_fdtol;
417 			FILEDESC_XLOCK(p1->p_fd);
418 			fdtol->fdl_refcount++;
419 			FILEDESC_XUNLOCK(p1->p_fd);
420 		} else {
421 			/*
422 			 * Shared file descriptor table, and different
423 			 * process leaders.
424 			 */
425 			fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
426 			    p1->p_fd, p2);
427 		}
428 	}
429 	/*
430 	 * Make a proc table entry for the new process.
431 	 * Start by zeroing the section of proc that is zero-initialized,
432 	 * then copy the section that is copied directly from the parent.
433 	 */
434 
435 	PROC_LOCK(p2);
436 	PROC_LOCK(p1);
437 
438 	bzero(&td2->td_startzero,
439 	    __rangeof(struct thread, td_startzero, td_endzero));
440 
441 	bcopy(&td->td_startcopy, &td2->td_startcopy,
442 	    __rangeof(struct thread, td_startcopy, td_endcopy));
443 
444 	bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
445 	td2->td_sigstk = td->td_sigstk;
446 	td2->td_sigmask = td->td_sigmask;
447 	td2->td_flags = TDF_INMEM;
448 	td2->td_lend_user_pri = PRI_MAX;
449 
450 #ifdef VIMAGE
451 	td2->td_vnet = NULL;
452 	td2->td_vnet_lpush = NULL;
453 #endif
454 
455 	/*
456 	 * Allow the scheduler to initialize the child.
457 	 */
458 	thread_lock(td);
459 	sched_fork(td, td2);
460 	thread_unlock(td);
461 
462 	/*
463 	 * Duplicate sub-structures as needed.
464 	 * Increase reference counts on shared objects.
465 	 */
466 	p2->p_flag = P_INMEM;
467 	p2->p_swtick = ticks;
468 	if (p1->p_flag & P_PROFIL)
469 		startprofclock(p2);
470 	td2->td_ucred = crhold(p2->p_ucred);
471 
472 	if (flags & RFSIGSHARE) {
473 		p2->p_sigacts = sigacts_hold(p1->p_sigacts);
474 	} else {
475 		sigacts_copy(newsigacts, p1->p_sigacts);
476 		p2->p_sigacts = newsigacts;
477 	}
478 	if (flags & RFLINUXTHPN)
479 	        p2->p_sigparent = SIGUSR1;
480 	else
481 	        p2->p_sigparent = SIGCHLD;
482 
483 	p2->p_textvp = p1->p_textvp;
484 	p2->p_fd = fd;
485 	p2->p_fdtol = fdtol;
486 
487 	/*
488 	 * p_limit is copy-on-write.  Bump its refcount.
489 	 */
490 	lim_fork(p1, p2);
491 
492 	pstats_fork(p1->p_stats, p2->p_stats);
493 
494 	PROC_UNLOCK(p1);
495 	PROC_UNLOCK(p2);
496 
497 	/* Bump references to the text vnode (for procfs). */
498 	if (p2->p_textvp)
499 		vref(p2->p_textvp);
500 
501 	/*
502 	 * Set up linkage for kernel based threading.
503 	 */
504 	if ((flags & RFTHREAD) != 0) {
505 		mtx_lock(&ppeers_lock);
506 		p2->p_peers = p1->p_peers;
507 		p1->p_peers = p2;
508 		p2->p_leader = p1->p_leader;
509 		mtx_unlock(&ppeers_lock);
510 		PROC_LOCK(p1->p_leader);
511 		if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
512 			PROC_UNLOCK(p1->p_leader);
513 			/*
514 			 * The task leader is exiting, so process p1 is
515 			 * going to be killed shortly.  Since p1 obviously
516 			 * isn't dead yet, we know that the leader is either
517 			 * sending SIGKILL's to all the processes in this
518 			 * task or is sleeping waiting for all the peers to
519 			 * exit.  We let p1 complete the fork, but we need
520 			 * to go ahead and kill the new process p2 since
521 			 * the task leader may not get a chance to send
522 			 * SIGKILL to it.  We leave it on the list so that
523 			 * the task leader will wait for this new process
524 			 * to commit suicide.
525 			 */
526 			PROC_LOCK(p2);
527 			psignal(p2, SIGKILL);
528 			PROC_UNLOCK(p2);
529 		} else
530 			PROC_UNLOCK(p1->p_leader);
531 	} else {
532 		p2->p_peers = NULL;
533 		p2->p_leader = p2;
534 	}
535 
536 	sx_xlock(&proctree_lock);
537 	PGRP_LOCK(p1->p_pgrp);
538 	PROC_LOCK(p2);
539 	PROC_LOCK(p1);
540 
541 	/*
542 	 * Preserve some more flags in subprocess.  P_PROFIL has already
543 	 * been preserved.
544 	 */
545 	p2->p_flag |= p1->p_flag & P_SUGID;
546 	td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
547 	SESS_LOCK(p1->p_session);
548 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
549 		p2->p_flag |= P_CONTROLT;
550 	SESS_UNLOCK(p1->p_session);
551 	if (flags & RFPPWAIT)
552 		p2->p_flag |= P_PPWAIT;
553 
554 	p2->p_pgrp = p1->p_pgrp;
555 	LIST_INSERT_AFTER(p1, p2, p_pglist);
556 	PGRP_UNLOCK(p1->p_pgrp);
557 	LIST_INIT(&p2->p_children);
558 
559 	callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
560 
561 	/*
562 	 * If PF_FORK is set, the child process inherits the
563 	 * procfs ioctl flags from its parent.
564 	 */
565 	if (p1->p_pfsflags & PF_FORK) {
566 		p2->p_stops = p1->p_stops;
567 		p2->p_pfsflags = p1->p_pfsflags;
568 	}
569 
570 	/*
571 	 * This begins the section where we must prevent the parent
572 	 * from being swapped.
573 	 */
574 	_PHOLD(p1);
575 	PROC_UNLOCK(p1);
576 
577 	/*
578 	 * Attach the new process to its parent.
579 	 *
580 	 * If RFNOWAIT is set, the newly created process becomes a child
581 	 * of init.  This effectively disassociates the child from the
582 	 * parent.
583 	 */
584 	if (flags & RFNOWAIT)
585 		pptr = initproc;
586 	else
587 		pptr = p1;
588 	p2->p_pptr = pptr;
589 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
590 	sx_xunlock(&proctree_lock);
591 
592 	/* Inform accounting that we have forked. */
593 	p2->p_acflag = AFORK;
594 	PROC_UNLOCK(p2);
595 
596 #ifdef KTRACE
597 	ktrprocfork(p1, p2);
598 #endif
599 
600 	/*
601 	 * Finish creating the child process.  It will return via a different
602 	 * execution path later.  (ie: directly into user mode)
603 	 */
604 	vm_forkproc(td, p2, td2, vm2, flags);
605 
606 	if (flags == (RFFDG | RFPROC)) {
607 		PCPU_INC(cnt.v_forks);
608 		PCPU_ADD(cnt.v_forkpages, p2->p_vmspace->vm_dsize +
609 		    p2->p_vmspace->vm_ssize);
610 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
611 		PCPU_INC(cnt.v_vforks);
612 		PCPU_ADD(cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
613 		    p2->p_vmspace->vm_ssize);
614 	} else if (p1 == &proc0) {
615 		PCPU_INC(cnt.v_kthreads);
616 		PCPU_ADD(cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
617 		    p2->p_vmspace->vm_ssize);
618 	} else {
619 		PCPU_INC(cnt.v_rforks);
620 		PCPU_ADD(cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
621 		    p2->p_vmspace->vm_ssize);
622 	}
623 
624 	/*
625 	 * Both processes are set up, now check if any loadable modules want
626 	 * to adjust anything.
627 	 */
628 	EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
629 
630 	/*
631 	 * Set the child start time and mark the process as being complete.
632 	 */
633 	microuptime(&p2->p_stats->p_start);
634 	PROC_SLOCK(p2);
635 	p2->p_state = PRS_NORMAL;
636 	PROC_SUNLOCK(p2);
637 
638 	PROC_LOCK(p1);
639 #ifdef KDTRACE_HOOKS
640 	/*
641 	 * Tell the DTrace fasttrap provider about the new process
642 	 * if it has registered an interest. We have to do this only after
643 	 * p_state is PRS_NORMAL since the fasttrap module will use pfind()
644 	 * later on.
645 	 */
646 	if (dtrace_fasttrap_fork) {
647 		PROC_LOCK(p2);
648 		dtrace_fasttrap_fork(p1, p2);
649 		PROC_UNLOCK(p2);
650 	}
651 #endif
652 	if ((p1->p_flag & (P_TRACED | P_FOLLOWFORK)) == (P_TRACED |
653 	    P_FOLLOWFORK)) {
654 		/*
655 		 * Arrange for debugger to receive the fork event.
656 		 *
657 		 * We can report PL_FLAG_FORKED regardless of
658 		 * P_FOLLOWFORK settings, but it does not make a sense
659 		 * for runaway child.
660 		 */
661 		td->td_dbgflags |= TDB_FORK;
662 		td->td_dbg_forked = p2->p_pid;
663 		PROC_LOCK(p2);
664 		td2->td_dbgflags |= TDB_STOPATFORK;
665 		_PHOLD(p2);
666 		p2_held = 1;
667 		PROC_UNLOCK(p2);
668 	}
669 	if ((flags & RFSTOPPED) == 0) {
670 		/*
671 		 * If RFSTOPPED not requested, make child runnable and
672 		 * add to run queue.
673 		 */
674 		thread_lock(td2);
675 		TD_SET_CAN_RUN(td2);
676 		sched_add(td2, SRQ_BORING);
677 		thread_unlock(td2);
678 	}
679 
680 	/*
681 	 * Now can be swapped.
682 	 */
683 	_PRELE(p1);
684 	PROC_UNLOCK(p1);
685 
686 	/*
687 	 * Tell any interested parties about the new process.
688 	 */
689 	knote_fork(&p1->p_klist, p2->p_pid);
690 	SDT_PROBE(proc, kernel, , create, p2, p1, flags, 0, 0);
691 
692 	/*
693 	 * Wait until debugger is attached to child.
694 	 */
695 	PROC_LOCK(p2);
696 	while ((td2->td_dbgflags & TDB_STOPATFORK) != 0)
697 		cv_wait(&p2->p_dbgwait, &p2->p_mtx);
698 	if (p2_held)
699 		_PRELE(p2);
700 
701 	/*
702 	 * Preserve synchronization semantics of vfork.  If waiting for
703 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
704 	 * proc (in case of exit).
705 	 */
706 	while (p2->p_flag & P_PPWAIT)
707 		cv_wait(&p2->p_pwait, &p2->p_mtx);
708 	PROC_UNLOCK(p2);
709 }
710 
711 int
712 fork1(struct thread *td, int flags, int pages, struct proc **procp)
713 {
714 	struct proc *p1;
715 	struct proc *newproc;
716 	int ok;
717 	struct thread *td2;
718 	struct vmspace *vm2;
719 	vm_ooffset_t mem_charged;
720 	int error;
721 	static int curfail;
722 	static struct timeval lastfail;
723 
724 	/* Can't copy and clear. */
725 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
726 		return (EINVAL);
727 
728 	p1 = td->td_proc;
729 
730 	/*
731 	 * Here we don't create a new process, but we divorce
732 	 * certain parts of a process from itself.
733 	 */
734 	if ((flags & RFPROC) == 0) {
735 		*procp = NULL;
736 		return (fork_norfproc(td, flags));
737 	}
738 
739 	mem_charged = 0;
740 	vm2 = NULL;
741 	if (pages == 0)
742 		pages = KSTACK_PAGES;
743 	/* Allocate new proc. */
744 	newproc = uma_zalloc(proc_zone, M_WAITOK);
745 	td2 = FIRST_THREAD_IN_PROC(newproc);
746 	if (td2 == NULL) {
747 		td2 = thread_alloc(pages);
748 		if (td2 == NULL) {
749 			error = ENOMEM;
750 			goto fail1;
751 		}
752 		proc_linkup(newproc, td2);
753 	} else {
754 		if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
755 			if (td2->td_kstack != 0)
756 				vm_thread_dispose(td2);
757 			if (!thread_alloc_stack(td2, pages)) {
758 				error = ENOMEM;
759 				goto fail1;
760 			}
761 		}
762 	}
763 
764 	if ((flags & RFMEM) == 0) {
765 		vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
766 		if (vm2 == NULL) {
767 			error = ENOMEM;
768 			goto fail1;
769 		}
770 		if (!swap_reserve(mem_charged)) {
771 			/*
772 			 * The swap reservation failed. The accounting
773 			 * from the entries of the copied vm2 will be
774 			 * substracted in vmspace_free(), so force the
775 			 * reservation there.
776 			 */
777 			swap_reserve_force(mem_charged);
778 			error = ENOMEM;
779 			goto fail1;
780 		}
781 	} else
782 		vm2 = NULL;
783 #ifdef MAC
784 	mac_proc_init(newproc);
785 #endif
786 	knlist_init_mtx(&newproc->p_klist, &newproc->p_mtx);
787 	STAILQ_INIT(&newproc->p_ktr);
788 
789 	/* We have to lock the process tree while we look for a pid. */
790 	sx_slock(&proctree_lock);
791 
792 	/*
793 	 * Although process entries are dynamically created, we still keep
794 	 * a global limit on the maximum number we will create.  Don't allow
795 	 * a nonprivileged user to use the last ten processes; don't let root
796 	 * exceed the limit. The variable nprocs is the current number of
797 	 * processes, maxproc is the limit.
798 	 */
799 	sx_xlock(&allproc_lock);
800 	if ((nprocs >= maxproc - 10 && priv_check_cred(td->td_ucred,
801 	    PRIV_MAXPROC, 0) != 0) || nprocs >= maxproc) {
802 		error = EAGAIN;
803 		goto fail;
804 	}
805 
806 	/*
807 	 * Increment the count of procs running with this uid. Don't allow
808 	 * a nonprivileged user to exceed their current limit.
809 	 *
810 	 * XXXRW: Can we avoid privilege here if it's not needed?
811 	 */
812 	error = priv_check_cred(td->td_ucred, PRIV_PROC_LIMIT, 0);
813 	if (error == 0)
814 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 0);
815 	else {
816 		PROC_LOCK(p1);
817 		ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
818 		    lim_cur(p1, RLIMIT_NPROC));
819 		PROC_UNLOCK(p1);
820 	}
821 	if (ok) {
822 		do_fork(td, flags, newproc, td2, vm2);
823 
824 		/*
825 		 * Return child proc pointer to parent.
826 		 */
827 		*procp = newproc;
828 		return (0);
829 	}
830 
831 	error = EAGAIN;
832 fail:
833 	sx_sunlock(&proctree_lock);
834 	if (ppsratecheck(&lastfail, &curfail, 1))
835 		printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
836 		    td->td_ucred->cr_ruid);
837 	sx_xunlock(&allproc_lock);
838 #ifdef MAC
839 	mac_proc_destroy(newproc);
840 #endif
841 fail1:
842 	if (vm2 != NULL)
843 		vmspace_free(vm2);
844 	uma_zfree(proc_zone, newproc);
845 	pause("fork", hz / 2);
846 	return (error);
847 }
848 
849 /*
850  * Handle the return of a child process from fork1().  This function
851  * is called from the MD fork_trampoline() entry point.
852  */
853 void
854 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
855     struct trapframe *frame)
856 {
857 	struct proc *p;
858 	struct thread *td;
859 	struct thread *dtd;
860 
861 	td = curthread;
862 	p = td->td_proc;
863 	KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
864 
865 	CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
866 		td, td->td_sched, p->p_pid, td->td_name);
867 
868 	sched_fork_exit(td);
869 	/*
870 	* Processes normally resume in mi_switch() after being
871 	* cpu_switch()'ed to, but when children start up they arrive here
872 	* instead, so we must do much the same things as mi_switch() would.
873 	*/
874 	if ((dtd = PCPU_GET(deadthread))) {
875 		PCPU_SET(deadthread, NULL);
876 		thread_stash(dtd);
877 	}
878 	thread_unlock(td);
879 
880 	/*
881 	 * cpu_set_fork_handler intercepts this function call to
882 	 * have this call a non-return function to stay in kernel mode.
883 	 * initproc has its own fork handler, but it does return.
884 	 */
885 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
886 	callout(arg, frame);
887 
888 	/*
889 	 * Check if a kernel thread misbehaved and returned from its main
890 	 * function.
891 	 */
892 	if (p->p_flag & P_KTHREAD) {
893 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
894 		    td->td_name, p->p_pid);
895 		kproc_exit(0);
896 	}
897 	mtx_assert(&Giant, MA_NOTOWNED);
898 
899 	if (p->p_sysent->sv_schedtail != NULL)
900 		(p->p_sysent->sv_schedtail)(td);
901 }
902 
903 /*
904  * Simplified back end of syscall(), used when returning from fork()
905  * directly into user mode.  Giant is not held on entry, and must not
906  * be held on return.  This function is passed in to fork_exit() as the
907  * first parameter and is called when returning to a new userland process.
908  */
909 void
910 fork_return(struct thread *td, struct trapframe *frame)
911 {
912 	struct proc *p, *dbg;
913 
914 	if (td->td_dbgflags & TDB_STOPATFORK) {
915 		p = td->td_proc;
916 		sx_xlock(&proctree_lock);
917 		PROC_LOCK(p);
918 		if ((p->p_pptr->p_flag & (P_TRACED | P_FOLLOWFORK)) ==
919 		    (P_TRACED | P_FOLLOWFORK)) {
920 			/*
921 			 * If debugger still wants auto-attach for the
922 			 * parent's children, do it now.
923 			 */
924 			dbg = p->p_pptr->p_pptr;
925 			p->p_flag |= P_TRACED;
926 			p->p_oppid = p->p_pptr->p_pid;
927 			proc_reparent(p, dbg);
928 			sx_xunlock(&proctree_lock);
929 			ptracestop(td, SIGSTOP);
930 		} else {
931 			/*
932 			 * ... otherwise clear the request.
933 			 */
934 			sx_xunlock(&proctree_lock);
935 			td->td_dbgflags &= ~TDB_STOPATFORK;
936 			cv_broadcast(&p->p_dbgwait);
937 		}
938 		PROC_UNLOCK(p);
939 	}
940 
941 	userret(td, frame);
942 
943 #ifdef KTRACE
944 	if (KTRPOINT(td, KTR_SYSRET))
945 		ktrsysret(SYS_fork, 0, 0);
946 #endif
947 	mtx_assert(&Giant, MA_NOTOWNED);
948 }
949