xref: /openbsd-src/sys/kern/kern_fork.c (revision 782ebdf8902fbe540cc1b971ad3ae76732171c58)
1 /*	$OpenBSD: kern_fork.c,v 1.176 2014/11/03 21:28:35 tedu Exp $	*/
2 /*	$NetBSD: kern_fork.c,v 1.29 1996/02/09 18:59:34 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/filedesc.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/mount.h>
46 #include <sys/proc.h>
47 #include <sys/exec.h>
48 #include <sys/resourcevar.h>
49 #include <sys/signalvar.h>
50 #include <sys/vnode.h>
51 #include <sys/vmmeter.h>
52 #include <sys/file.h>
53 #include <sys/acct.h>
54 #include <sys/ktrace.h>
55 #include <sys/sched.h>
56 #include <sys/sysctl.h>
57 #include <dev/rndvar.h>
58 #include <sys/pool.h>
59 #include <sys/mman.h>
60 #include <sys/ptrace.h>
61 #include <sys/atomic.h>
62 #include <sys/unistd.h>
63 
64 #include <sys/syscallargs.h>
65 
66 #include "systrace.h"
67 #include <dev/systrace.h>
68 
69 #include <uvm/uvm.h>
70 
71 #ifdef __HAVE_MD_TCB
72 # include <machine/tcb.h>
73 #endif
74 
75 int	nprocesses = 1;		/* process 0 */
76 int	nthreads = 1;		/* proc 0 */
77 int	randompid;		/* when set to 1, pid's go random */
78 struct	forkstat forkstat;
79 
80 void fork_return(void *);
81 void tfork_child_return(void *);
82 int pidtaken(pid_t);
83 
84 void process_new(struct proc *, struct process *, int);
85 
86 void
87 fork_return(void *arg)
88 {
89 	struct proc *p = (struct proc *)arg;
90 
91 	if (p->p_p->ps_flags & PS_TRACED)
92 		psignal(p, SIGTRAP);
93 
94 	child_return(p);
95 }
96 
97 /*ARGSUSED*/
98 int
99 sys_fork(struct proc *p, void *v, register_t *retval)
100 {
101 	int flags;
102 
103 	flags = FORK_FORK;
104 	if (p->p_p->ps_ptmask & PTRACE_FORK)
105 		flags |= FORK_PTRACE;
106 	return (fork1(p, flags, NULL, 0, fork_return, NULL, retval, NULL));
107 }
108 
109 /*ARGSUSED*/
110 int
111 sys_vfork(struct proc *p, void *v, register_t *retval)
112 {
113 	return (fork1(p, FORK_VFORK|FORK_PPWAIT, NULL, 0, NULL,
114 	    NULL, retval, NULL));
115 }
116 
117 int
118 sys___tfork(struct proc *p, void *v, register_t *retval)
119 {
120 	struct sys___tfork_args /* {
121 		syscallarg(const struct __tfork) *param;
122 		syscallarg(size_t) psize;
123 	} */ *uap = v;
124 	size_t psize = SCARG(uap, psize);
125 	struct __tfork param = { 0 };
126 	int flags;
127 	int error;
128 
129 	if (psize == 0 || psize > sizeof(param))
130 		return (EINVAL);
131 	if ((error = copyin(SCARG(uap, param), &param, psize)))
132 		return (error);
133 #ifdef KTRACE
134 	if (KTRPOINT(p, KTR_STRUCT))
135 		ktrstruct(p, "tfork", &param, sizeof(param));
136 #endif
137 
138 	flags = FORK_TFORK | FORK_THREAD | FORK_SIGHAND | FORK_SHAREVM
139 	    | FORK_SHAREFILES;
140 
141 	return (fork1(p, flags, param.tf_stack, param.tf_tid,
142 	    tfork_child_return, param.tf_tcb, retval, NULL));
143 }
144 
145 void
146 tfork_child_return(void *arg)
147 {
148 	struct proc *p = curproc;
149 
150 	TCB_SET(p, arg);
151 	child_return(p);
152 }
153 
154 /*
155  * Allocate and initialize a new process.
156  */
157 void
158 process_new(struct proc *p, struct process *parent, int flags)
159 {
160 	struct process *pr;
161 
162 	pr = pool_get(&process_pool, PR_WAITOK);
163 	pr->ps_mainproc = p;
164 
165 	TAILQ_INIT(&pr->ps_threads);
166 	TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
167 	pr->ps_pptr = parent;
168 	LIST_INIT(&pr->ps_children);
169 	pr->ps_refcnt = 1;
170 
171 	/*
172 	 * Make a process structure for the new process.
173 	 * Start by zeroing the section of proc that is zero-initialized,
174 	 * then copy the section that is copied directly from the parent.
175 	 */
176 	memset(&pr->ps_startzero, 0,
177 	    (caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero);
178 	memcpy(&pr->ps_startcopy, &parent->ps_startcopy,
179 	    (caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy);
180 
181 	/* post-copy fixups */
182 	pr->ps_ucred = p->p_ucred;
183 	crhold(pr->ps_ucred);
184 	KASSERT(p->p_ucred->cr_ref >= 3); /* fork thr, new thr, new process */
185 	pr->ps_limit->p_refcnt++;
186 
187 	/* bump references to the text vnode (for sysctl) */
188 	pr->ps_textvp = parent->ps_textvp;
189 	if (pr->ps_textvp)
190 		vref(pr->ps_textvp);
191 
192 	timeout_set(&pr->ps_realit_to, realitexpire, pr);
193 
194 	pr->ps_flags = parent->ps_flags & (PS_SUGID | PS_SUGIDEXEC);
195 	if (parent->ps_session->s_ttyvp != NULL)
196 		pr->ps_flags |= parent->ps_flags & PS_CONTROLT;
197 
198 	p->p_p = pr;
199 
200 	/*
201 	 * Duplicate sub-structures as needed.
202 	 * Increase reference counts on shared objects.
203 	 */
204 	if (flags & FORK_SHAREFILES)
205 		pr->ps_fd = fdshare(parent);
206 	else
207 		pr->ps_fd = fdcopy(parent);
208 	if (flags & FORK_SIGHAND)
209 		pr->ps_sigacts = sigactsshare(parent);
210 	else
211 		pr->ps_sigacts = sigactsinit(parent);
212 	if (flags & FORK_SHAREVM)
213 		pr->ps_vmspace = uvmspace_share(parent);
214 	else
215 		pr->ps_vmspace = uvmspace_fork(parent);
216 
217 	if (parent->ps_flags & PS_PROFIL)
218 		startprofclock(pr);
219 	if (flags & FORK_PTRACE)
220 		pr->ps_flags |= parent->ps_flags & PS_TRACED;
221 	if (flags & FORK_NOZOMBIE)
222 		pr->ps_flags |= PS_NOZOMBIE;
223 	if (flags & FORK_SYSTEM)
224 		pr->ps_flags |= PS_SYSTEM;
225 
226 	/* mark as embryo to protect against others */
227 	pr->ps_flags |= PS_EMBRYO;
228 
229 	/* Force visibility of all of the above changes */
230 	membar_producer();
231 
232 	/* it's sufficiently inited to be globally visible */
233 	LIST_INSERT_HEAD(&allprocess, pr, ps_list);
234 }
235 
236 /* print the 'table full' message once per 10 seconds */
237 struct timeval fork_tfmrate = { 10, 0 };
238 
239 int
240 fork1(struct proc *curp, int flags, void *stack, pid_t *tidptr,
241     void (*func)(void *), void *arg, register_t *retval,
242     struct proc **rnewprocp)
243 {
244 	struct process *curpr = curp->p_p;
245 	struct process *pr;
246 	struct proc *p;
247 	uid_t uid;
248 	struct vmspace *vm;
249 	int count;
250 	vaddr_t uaddr;
251 	int s;
252 	struct  ptrace_state *newptstat = NULL;
253 #if NSYSTRACE > 0
254 	void *newstrp = NULL;
255 #endif
256 
257 	/* sanity check some flag combinations */
258 	if (flags & FORK_THREAD) {
259 		if ((flags & FORK_SHAREFILES) == 0 ||
260 		    (flags & FORK_SIGHAND) == 0 ||
261 		    (flags & FORK_SYSTEM) != 0)
262 			return (EINVAL);
263 	}
264 	if (flags & FORK_SIGHAND && (flags & FORK_SHAREVM) == 0)
265 		return (EINVAL);
266 
267 	/*
268 	 * Although process entries are dynamically created, we still keep
269 	 * a global limit on the maximum number we will create. We reserve
270 	 * the last 5 processes to root. The variable nprocesses is the
271 	 * current number of processes, maxprocess is the limit.  Similar
272 	 * rules for threads (struct proc): we reserve the last 5 to root;
273 	 * the variable nthreads is the current number of procs, maxthread is
274 	 * the limit.
275 	 */
276 	uid = curp->p_ucred->cr_ruid;
277 	if ((nthreads >= maxthread - 5 && uid != 0) || nthreads >= maxthread) {
278 		static struct timeval lasttfm;
279 
280 		if (ratecheck(&lasttfm, &fork_tfmrate))
281 			tablefull("proc");
282 		return (EAGAIN);
283 	}
284 	nthreads++;
285 
286 	if ((flags & FORK_THREAD) == 0) {
287 		if ((nprocesses >= maxprocess - 5 && uid != 0) ||
288 		    nprocesses >= maxprocess) {
289 			static struct timeval lasttfm;
290 
291 			if (ratecheck(&lasttfm, &fork_tfmrate))
292 				tablefull("process");
293 			nthreads--;
294 			return (EAGAIN);
295 		}
296 		nprocesses++;
297 
298 		/*
299 		 * Increment the count of processes running with
300 		 * this uid.  Don't allow a nonprivileged user to
301 		 * exceed their current limit.
302 		 */
303 		count = chgproccnt(uid, 1);
304 		if (uid != 0 && count > curp->p_rlimit[RLIMIT_NPROC].rlim_cur) {
305 			(void)chgproccnt(uid, -1);
306 			nprocesses--;
307 			nthreads--;
308 			return (EAGAIN);
309 		}
310 	}
311 
312 	uaddr = uvm_uarea_alloc();
313 	if (uaddr == 0) {
314 		if ((flags & FORK_THREAD) == 0) {
315 			(void)chgproccnt(uid, -1);
316 			nprocesses--;
317 		}
318 		nthreads--;
319 		return (ENOMEM);
320 	}
321 
322 	/*
323 	 * From now on, we're committed to the fork and cannot fail.
324 	 */
325 
326 	/* Allocate new proc. */
327 	p = pool_get(&proc_pool, PR_WAITOK);
328 
329 	p->p_stat = SIDL;			/* protect against others */
330 	p->p_flag = 0;
331 
332 	/*
333 	 * Make a proc table entry for the new process.
334 	 * Start by zeroing the section of proc that is zero-initialized,
335 	 * then copy the section that is copied directly from the parent.
336 	 */
337 	memset(&p->p_startzero, 0,
338 	    (caddr_t)&p->p_endzero - (caddr_t)&p->p_startzero);
339 	memcpy(&p->p_startcopy, &curp->p_startcopy,
340 	    (caddr_t)&p->p_endcopy - (caddr_t)&p->p_startcopy);
341 	crhold(p->p_ucred);
342 
343 	/*
344 	 * Initialize the timeouts.
345 	 */
346 	timeout_set(&p->p_sleep_to, endtsleep, p);
347 
348 	if (flags & FORK_THREAD) {
349 		atomic_setbits_int(&p->p_flag, P_THREAD);
350 		p->p_p = pr = curpr;
351 		pr->ps_refcnt++;
352 	} else {
353 		process_new(p, curpr, flags);
354 		pr = p->p_p;
355 	}
356 	p->p_fd		= pr->ps_fd;
357 	p->p_vmspace	= pr->ps_vmspace;
358 	if (pr->ps_flags & PS_SYSTEM)
359 		atomic_setbits_int(&p->p_flag, P_SYSTEM);
360 
361 	if (flags & FORK_PPWAIT) {
362 		atomic_setbits_int(&pr->ps_flags, PS_PPWAIT);
363 		atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT);
364 	}
365 
366 #ifdef KTRACE
367 	/*
368 	 * Copy traceflag and tracefile if enabled.
369 	 * If not inherited, these were zeroed above.
370 	 */
371 	if ((flags & FORK_THREAD) == 0 && curpr->ps_traceflag & KTRFAC_INHERIT)
372 		ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp,
373 		    curpr->ps_tracecred);
374 #endif
375 
376 	/*
377 	 * set priority of child to be that of parent
378 	 * XXX should move p_estcpu into the region of struct proc which gets
379 	 * copied.
380 	 */
381 	scheduler_fork_hook(curp, p);
382 
383 	if (flags & FORK_THREAD)
384 		sigstkinit(&p->p_sigstk);
385 
386 	/*
387 	 * If emulation has thread fork hook, call it now.
388 	 */
389 	if (pr->ps_emul->e_proc_fork)
390 		(*pr->ps_emul->e_proc_fork)(p, curp);
391 
392 	p->p_addr = (struct user *)uaddr;
393 
394 	/*
395 	 * Finish creating the child thread.  cpu_fork() will copy
396 	 * and update the pcb and make the child ready to run.  If
397 	 * this is a normal user fork, the child will exit directly
398 	 * to user mode via child_return() on its first time slice
399 	 * and will not return here.  If this is a kernel thread,
400 	 * the specified entry point will be executed.
401 	 */
402 	cpu_fork(curp, p, stack, 0, func ? func : child_return, arg ? arg : p);
403 
404 	vm = pr->ps_vmspace;
405 
406 	if (flags & FORK_FORK) {
407 		forkstat.cntfork++;
408 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
409 	} else if (flags & FORK_VFORK) {
410 		forkstat.cntvfork++;
411 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
412 	} else if (flags & FORK_TFORK) {
413 		forkstat.cnttfork++;
414 	} else {
415 		forkstat.cntkthread++;
416 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
417 	}
418 
419 	if (pr->ps_flags & PS_TRACED && flags & FORK_FORK)
420 		newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK);
421 #if NSYSTRACE > 0
422 	if (ISSET(curp->p_flag, P_SYSTRACE))
423 		newstrp = systrace_getproc();
424 #endif
425 
426 	p->p_pid = allocpid();
427 
428 	LIST_INSERT_HEAD(&allproc, p, p_list);
429 	LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
430 	if ((flags & FORK_THREAD) == 0) {
431 		LIST_INSERT_AFTER(curpr, pr, ps_pglist);
432 		LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling);
433 
434 		if (pr->ps_flags & PS_TRACED) {
435 			pr->ps_oppid = curpr->ps_pid;
436 			if (pr->ps_pptr != curpr->ps_pptr)
437 				proc_reparent(pr, curpr->ps_pptr);
438 
439 			/*
440 			 * Set ptrace status.
441 			 */
442 			if (flags & FORK_FORK) {
443 				pr->ps_ptstat = newptstat;
444 				newptstat = NULL;
445 				curpr->ps_ptstat->pe_report_event = PTRACE_FORK;
446 				pr->ps_ptstat->pe_report_event = PTRACE_FORK;
447 				curpr->ps_ptstat->pe_other_pid = pr->ps_pid;
448 				pr->ps_ptstat->pe_other_pid = curpr->ps_pid;
449 			}
450 		}
451 	} else {
452 		TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
453 		/*
454 		 * if somebody else wants to take us to single threaded mode,
455 		 * count ourselves in.
456 		 */
457 		if (pr->ps_single) {
458 			curpr->ps_singlecount++;
459 			atomic_setbits_int(&p->p_flag, P_SUSPSINGLE);
460 		}
461 	}
462 
463 #if NSYSTRACE > 0
464 	if (newstrp)
465 		systrace_fork(curp, p, newstrp);
466 #endif
467 
468 	if (tidptr != NULL) {
469 		pid_t	pid = p->p_pid + THREAD_PID_OFFSET;
470 
471 		if (copyout(&pid, tidptr, sizeof(pid)))
472 			psignal(curp, SIGSEGV);
473 	}
474 
475 	/*
476 	 * For new processes, set accounting bits and mark as complete.
477 	 */
478 	if ((flags & FORK_THREAD) == 0) {
479 		getnanotime(&pr->ps_start);
480 		pr->ps_acflag = AFORK;
481 		atomic_clearbits_int(&pr->ps_flags, PS_EMBRYO);
482 	}
483 
484 	/*
485 	 * Make child runnable and add to run queue.
486 	 */
487 	if ((flags & FORK_IDLE) == 0) {
488 		SCHED_LOCK(s);
489 		p->p_stat = SRUN;
490 		p->p_cpu = sched_choosecpu_fork(curp, flags);
491 		setrunqueue(p);
492 		SCHED_UNLOCK(s);
493 	} else
494 		p->p_cpu = arg;
495 
496 	if (newptstat)
497 		free(newptstat, M_SUBPROC, sizeof(*newptstat));
498 
499 	/*
500 	 * Notify any interested parties about the new process.
501 	 */
502 	if ((flags & FORK_THREAD) == 0)
503 		KNOTE(&curpr->ps_klist, NOTE_FORK | p->p_pid);
504 
505 	/*
506 	 * Update stats now that we know the fork was successful.
507 	 */
508 	uvmexp.forks++;
509 	if (flags & FORK_PPWAIT)
510 		uvmexp.forks_ppwait++;
511 	if (flags & FORK_SHAREVM)
512 		uvmexp.forks_sharevm++;
513 
514 	/*
515 	 * Pass a pointer to the new process to the caller.
516 	 */
517 	if (rnewprocp != NULL)
518 		*rnewprocp = p;
519 
520 	/*
521 	 * Preserve synchronization semantics of vfork.  If waiting for
522 	 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT
523 	 * on ourselves, and sleep on our process for the latter flag
524 	 * to go away.
525 	 * XXX Need to stop other rthreads in the parent
526 	 */
527 	if (flags & FORK_PPWAIT)
528 		while (curpr->ps_flags & PS_ISPWAIT)
529 			tsleep(curpr, PWAIT, "ppwait", 0);
530 
531 	/*
532 	 * If we're tracing the child, alert the parent too.
533 	 */
534 	if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED))
535 		psignal(curp, SIGTRAP);
536 
537 	/*
538 	 * Return child pid to parent process,
539 	 * marking us as parent via retval[1].
540 	 */
541 	if (retval != NULL) {
542 		retval[0] = p->p_pid +
543 		    (flags & FORK_THREAD ? THREAD_PID_OFFSET : 0);
544 		retval[1] = 0;
545 	}
546 	return (0);
547 }
548 
549 /*
550  * Checks for current use of a pid, either as a pid or pgid.
551  */
552 pid_t oldpids[100];
553 int
554 ispidtaken(pid_t pid)
555 {
556 	uint32_t i;
557 	struct process *pr;
558 
559 	for (i = 0; i < nitems(oldpids); i++)
560 		if (pid == oldpids[i])
561 			return (1);
562 
563 	if (pfind(pid) != NULL)
564 		return (1);
565 	if (pgfind(pid) != NULL)
566 		return (1);
567 	LIST_FOREACH(pr, &zombprocess, ps_list) {
568 		if (pr->ps_pid == pid ||
569 		    (pr->ps_pgrp && pr->ps_pgrp->pg_id == pid))
570 			return (1);
571 	}
572 	return (0);
573 }
574 
575 /* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */
576 pid_t
577 allocpid(void)
578 {
579 	static pid_t lastpid;
580 	pid_t pid;
581 
582 	if (!randompid) {
583 		/* only used early on for system processes */
584 		pid = ++lastpid;
585 	} else {
586 		do {
587 			pid = 1 + arc4random_uniform(PID_MAX);
588 		} while (ispidtaken(pid));
589 	}
590 
591 	return pid;
592 }
593 
594 void
595 freepid(pid_t pid)
596 {
597 	static uint32_t idx;
598 
599 	oldpids[idx++ % nitems(oldpids)] = pid;
600 }
601 
602 #if defined(MULTIPROCESSOR)
603 /*
604  * XXX This is a slight hack to get newly-formed processes to
605  * XXX acquire the kernel lock as soon as they run.
606  */
607 void
608 proc_trampoline_mp(void)
609 {
610 	struct proc *p;
611 
612 	p = curproc;
613 
614 	SCHED_ASSERT_LOCKED();
615 	__mp_unlock(&sched_lock);
616 	spl0();
617 	SCHED_ASSERT_UNLOCKED();
618 	KERNEL_ASSERT_UNLOCKED();
619 
620 	KERNEL_LOCK();
621 }
622 #endif
623