xref: /openbsd-src/sys/kern/kern_fork.c (revision 06494c7c7c814d5a02271bb8c7f55780c5f57216)
1 /*	$OpenBSD: kern_fork.c,v 1.152 2013/06/11 13:00:31 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/file.h>
52 #include <sys/acct.h>
53 #include <sys/ktrace.h>
54 #include <sys/sched.h>
55 #include <dev/rndvar.h>
56 #include <sys/pool.h>
57 #include <sys/mman.h>
58 #include <sys/ptrace.h>
59 
60 #include <sys/syscallargs.h>
61 
62 #include "systrace.h"
63 #include <dev/systrace.h>
64 
65 #include <uvm/uvm_extern.h>
66 #include <uvm/uvm_map.h>
67 
68 #ifdef __HAVE_MD_TCB
69 # include <machine/tcb.h>
70 #endif
71 
72 int	nprocesses = 1;		/* process 0 */
73 int	nthreads = 1;		/* proc 0 */
74 int	randompid;		/* when set to 1, pid's go random */
75 struct	forkstat forkstat;
76 
77 void fork_return(void *);
78 void tfork_child_return(void *);
79 int pidtaken(pid_t);
80 
81 void process_new(struct proc *, struct process *);
82 
83 void
84 fork_return(void *arg)
85 {
86 	struct proc *p = (struct proc *)arg;
87 
88 	if (p->p_p->ps_flags & PS_TRACED)
89 		psignal(p, SIGTRAP);
90 
91 	child_return(p);
92 }
93 
94 /*ARGSUSED*/
95 int
96 sys_fork(struct proc *p, void *v, register_t *retval)
97 {
98 	int flags;
99 
100 	flags = FORK_FORK;
101 	if (p->p_p->ps_ptmask & PTRACE_FORK)
102 		flags |= FORK_PTRACE;
103 	return (fork1(p, SIGCHLD, flags, NULL, 0,
104 	    fork_return, NULL, retval, NULL));
105 }
106 
107 /*ARGSUSED*/
108 int
109 sys_vfork(struct proc *p, void *v, register_t *retval)
110 {
111 	return (fork1(p, SIGCHLD, FORK_VFORK|FORK_PPWAIT, NULL, 0, NULL,
112 	    NULL, retval, NULL));
113 }
114 
115 int
116 sys___tfork(struct proc *p, void *v, register_t *retval)
117 {
118 	struct sys___tfork_args /* {
119 		syscallarg(const struct __tfork) *param;
120 		syscallarg(size_t) psize;
121 	} */ *uap = v;
122 	size_t psize = SCARG(uap, psize);
123 	struct __tfork param = { 0 };
124 	int flags;
125 	int error;
126 
127 	if (psize == 0 || psize > sizeof(param))
128 		return (EINVAL);
129 	if ((error = copyin(SCARG(uap, param), &param, psize)))
130 		return (error);
131 #ifdef KTRACE
132 	if (KTRPOINT(p, KTR_STRUCT))
133 		ktrstruct(p, "tfork", &param, sizeof(param));
134 #endif
135 
136 	flags = FORK_TFORK | FORK_THREAD | FORK_SIGHAND | FORK_SHAREVM
137 	    | FORK_NOZOMBIE | FORK_SHAREFILES;
138 
139 	return (fork1(p, 0, flags, param.tf_stack, param.tf_tid,
140 	    tfork_child_return, param.tf_tcb, retval, NULL));
141 }
142 
143 #ifdef COMPAT_O51
144 int
145 compat_o51_sys___tfork(struct proc *p, void *v, register_t *retval)
146 {
147 	struct compat_o51_sys___tfork_args /* {
148 		syscallarg(struct __tfork51) *param;
149 	} */ *uap = v;
150 	struct __tfork51 param;
151 	int flags;
152 	int error;
153 
154 	if ((error = copyin(SCARG(uap, param), &param, sizeof(param))))
155 		return (error);
156 
157 	if (param.tf_flags != 0)
158 		return (EINVAL);
159 
160 	flags = FORK_TFORK | FORK_THREAD | FORK_SIGHAND | FORK_SHAREVM
161 	    | FORK_NOZOMBIE | FORK_SHAREFILES;
162 
163 	return (fork1(p, 0, flags, NULL, param.tf_tid, tfork_child_return,
164 	    param.tf_tcb, retval, NULL));
165 }
166 #endif
167 
168 void
169 tfork_child_return(void *arg)
170 {
171 	struct proc *p = curproc;
172 
173 	TCB_SET(p, arg);
174 	child_return(p);
175 }
176 
177 /*
178  * Allocate and initialize a new process.
179  */
180 void
181 process_new(struct proc *p, struct process *parent)
182 {
183 	struct process *pr;
184 
185 	pr = pool_get(&process_pool, PR_WAITOK);
186 	pr->ps_mainproc = p;
187 
188 	TAILQ_INIT(&pr->ps_threads);
189 	TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
190 	pr->ps_pptr = parent;
191 	LIST_INIT(&pr->ps_children);
192 	pr->ps_refcnt = 1;
193 
194 	/*
195 	 * Make a process structure for the new process.
196 	 * Start by zeroing the section of proc that is zero-initialized,
197 	 * then copy the section that is copied directly from the parent.
198 	 */
199 	memset(&pr->ps_startzero, 0,
200 	    (caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero);
201 	memcpy(&pr->ps_startcopy, &parent->ps_startcopy,
202 	    (caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy);
203 
204 	/* post-copy fixups */
205 	pr->ps_cred = pool_get(&pcred_pool, PR_WAITOK);
206 	memcpy(pr->ps_cred, parent->ps_cred, sizeof(*pr->ps_cred));
207 	crhold(parent->ps_cred->pc_ucred);
208 	pr->ps_limit->p_refcnt++;
209 
210 	timeout_set(&pr->ps_realit_to, realitexpire, pr);
211 	timeout_set(&pr->ps_virt_to, virttimer_trampoline, pr);
212 	timeout_set(&pr->ps_prof_to, proftimer_trampoline, pr);
213 
214 	pr->ps_flags = parent->ps_flags & (PS_SUGID | PS_SUGIDEXEC);
215 	if (parent->ps_session->s_ttyvp != NULL &&
216 	    parent->ps_flags & PS_CONTROLT)
217 		atomic_setbits_int(&pr->ps_flags, PS_CONTROLT);
218 
219 	p->p_p = pr;
220 }
221 
222 /* print the 'table full' message once per 10 seconds */
223 struct timeval fork_tfmrate = { 10, 0 };
224 
225 int
226 fork1(struct proc *curp, int exitsig, int flags, void *stack, pid_t *tidptr,
227     void (*func)(void *), void *arg, register_t *retval,
228     struct proc **rnewprocp)
229 {
230 	struct process *curpr = curp->p_p;
231 	struct process *pr;
232 	struct proc *p;
233 	uid_t uid;
234 	struct vmspace *vm;
235 	int count;
236 	vaddr_t uaddr;
237 	int s;
238 	struct  ptrace_state *newptstat = NULL;
239 #if NSYSTRACE > 0
240 	void *newstrp = NULL;
241 #endif
242 
243 	/* sanity check some flag combinations */
244 	if (flags & FORK_THREAD) {
245 		if ((flags & (FORK_SIGHAND | FORK_NOZOMBIE)) !=
246 		    (FORK_SIGHAND | FORK_NOZOMBIE))
247 			return (EINVAL);
248 	}
249 	if (flags & FORK_SIGHAND && (flags & FORK_SHAREVM) == 0)
250 		return (EINVAL);
251 
252 	/*
253 	 * Although process entries are dynamically created, we still keep
254 	 * a global limit on the maximum number we will create. We reserve
255 	 * the last 5 processes to root. The variable nprocesses is the
256 	 * current number of processes, maxprocess is the limit.  Similar
257 	 * rules for threads (struct proc): we reserve the last 5 to root;
258 	 * the variable nthreads is the current number of procs, maxthread is
259 	 * the limit.
260 	 */
261 	uid = curp->p_cred->p_ruid;
262 	if ((nthreads >= maxthread - 5 && uid != 0) || nthreads >= maxthread) {
263 		static struct timeval lasttfm;
264 
265 		if (ratecheck(&lasttfm, &fork_tfmrate))
266 			tablefull("proc");
267 		return (EAGAIN);
268 	}
269 	nthreads++;
270 
271 	if ((flags & FORK_THREAD) == 0) {
272 		if ((nprocesses >= maxprocess - 5 && uid != 0) ||
273 		    nprocesses >= maxprocess) {
274 			static struct timeval lasttfm;
275 
276 			if (ratecheck(&lasttfm, &fork_tfmrate))
277 				tablefull("process");
278 			nthreads--;
279 			return (EAGAIN);
280 		}
281 		nprocesses++;
282 
283 		/*
284 		 * Increment the count of processes running with
285 		 * this uid.  Don't allow a nonprivileged user to
286 		 * exceed their current limit.
287 		 */
288 		count = chgproccnt(uid, 1);
289 		if (uid != 0 && count > curp->p_rlimit[RLIMIT_NPROC].rlim_cur) {
290 			(void)chgproccnt(uid, -1);
291 			nprocesses--;
292 			nthreads--;
293 			return (EAGAIN);
294 		}
295 	}
296 
297 	uaddr = uvm_km_kmemalloc_pla(kernel_map, uvm.kernel_object, USPACE,
298 	    USPACE_ALIGN, UVM_KMF_ZERO,
299 	    no_constraint.ucr_low, no_constraint.ucr_high,
300 	    0, 0, USPACE/PAGE_SIZE);
301 	if (uaddr == 0) {
302 		if ((flags & FORK_THREAD) == 0) {
303 			(void)chgproccnt(uid, -1);
304 			nprocesses--;
305 		}
306 		nthreads--;
307 		return (ENOMEM);
308 	}
309 
310 	/*
311 	 * From now on, we're committed to the fork and cannot fail.
312 	 */
313 
314 	/* Allocate new proc. */
315 	p = pool_get(&proc_pool, PR_WAITOK);
316 
317 	p->p_stat = SIDL;			/* protect against others */
318 	p->p_exitsig = exitsig;
319 	p->p_flag = 0;
320 	p->p_xstat = 0;
321 
322 	if (flags & FORK_THREAD) {
323 		atomic_setbits_int(&p->p_flag, P_THREAD);
324 		p->p_p = pr = curpr;
325 		pr->ps_refcnt++;
326 	} else {
327 		process_new(p, curpr);
328 		pr = p->p_p;
329 	}
330 
331 	/*
332 	 * Make a proc table entry for the new process.
333 	 * Start by zeroing the section of proc that is zero-initialized,
334 	 * then copy the section that is copied directly from the parent.
335 	 */
336 	memset(&p->p_startzero, 0,
337 	    (caddr_t)&p->p_endzero - (caddr_t)&p->p_startzero);
338 	memcpy(&p->p_startcopy, &curp->p_startcopy,
339 	    (caddr_t)&p->p_endcopy - (caddr_t)&p->p_startcopy);
340 
341 	/*
342 	 * Initialize the timeouts.
343 	 */
344 	timeout_set(&p->p_sleep_to, endtsleep, p);
345 
346 	/*
347 	 * Duplicate sub-structures as needed.
348 	 * Increase reference counts on shared objects.
349 	 */
350 	if ((flags & FORK_THREAD) == 0) {
351 		if (curpr->ps_flags & PS_PROFIL)
352 			startprofclock(pr);
353 		if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED))
354 			atomic_setbits_int(&pr->ps_flags, PS_TRACED);
355 	}
356 
357 	/* bump references to the text vnode (for procfs) */
358 	p->p_textvp = curp->p_textvp;
359 	if (p->p_textvp)
360 		vref(p->p_textvp);
361 
362 	if (flags & FORK_SHAREFILES)
363 		p->p_fd = fdshare(curp);
364 	else
365 		p->p_fd = fdcopy(curp);
366 
367 	if (flags & FORK_PPWAIT) {
368 		atomic_setbits_int(&pr->ps_flags, PS_PPWAIT);
369 		atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT);
370 	}
371 	if (flags & FORK_NOZOMBIE)
372 		atomic_setbits_int(&p->p_flag, P_NOZOMBIE);
373 
374 #ifdef KTRACE
375 	/*
376 	 * Copy traceflag and tracefile if enabled.
377 	 * If not inherited, these were zeroed above.
378 	 */
379 	if ((flags & FORK_THREAD) == 0 && curpr->ps_traceflag & KTRFAC_INHERIT)
380 		ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp,
381 		    curpr->ps_tracecred);
382 #endif
383 
384 	/*
385 	 * set priority of child to be that of parent
386 	 * XXX should move p_estcpu into the region of struct proc which gets
387 	 * copied.
388 	 */
389 	scheduler_fork_hook(curp, p);
390 
391 	/*
392 	 * Create signal actions for the child process.
393 	 */
394 	if (flags & FORK_SIGHAND)
395 		p->p_sigacts = sigactsshare(curp);
396 	else
397 		p->p_sigacts = sigactsinit(curp);
398 	if (flags & FORK_THREAD)
399 		sigstkinit(&p->p_sigstk);
400 
401 	/*
402 	 * If emulation has process fork hook, call it now.
403 	 */
404 	if (p->p_emul->e_proc_fork)
405 		(*p->p_emul->e_proc_fork)(p, curp);
406 
407 	p->p_addr = (struct user *)uaddr;
408 
409 	/*
410 	 * Finish creating the child process.  It will return through a
411 	 * different path later.
412 	 */
413 	uvm_fork(curp, p, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack,
414 	    0, func ? func : child_return, arg ? arg : p);
415 
416 	vm = p->p_vmspace;
417 
418 	if (flags & FORK_FORK) {
419 		forkstat.cntfork++;
420 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
421 	} else if (flags & FORK_VFORK) {
422 		forkstat.cntvfork++;
423 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
424 	} else if (flags & FORK_TFORK) {
425 		forkstat.cnttfork++;
426 	} else {
427 		forkstat.cntkthread++;
428 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
429 	}
430 
431 	if (pr->ps_flags & PS_TRACED && flags & FORK_FORK)
432 		newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK);
433 #if NSYSTRACE > 0
434 	if (ISSET(curp->p_flag, P_SYSTRACE))
435 		newstrp = systrace_getproc();
436 #endif
437 
438 	p->p_pid = allocpid();
439 
440 	LIST_INSERT_HEAD(&allproc, p, p_list);
441 	LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
442 	if ((flags & FORK_THREAD) == 0) {
443 		LIST_INSERT_AFTER(curpr, pr, ps_pglist);
444 		LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling);
445 
446 		if (pr->ps_flags & PS_TRACED) {
447 			pr->ps_oppid = curpr->ps_pid;
448 			if (pr->ps_pptr != curpr->ps_pptr)
449 				proc_reparent(pr, curpr->ps_pptr);
450 
451 			/*
452 			 * Set ptrace status.
453 			 */
454 			if (flags & FORK_FORK) {
455 				pr->ps_ptstat = newptstat;
456 				newptstat = NULL;
457 				curpr->ps_ptstat->pe_report_event = PTRACE_FORK;
458 				pr->ps_ptstat->pe_report_event = PTRACE_FORK;
459 				curpr->ps_ptstat->pe_other_pid = pr->ps_pid;
460 				pr->ps_ptstat->pe_other_pid = curpr->ps_pid;
461 			}
462 		}
463 	} else {
464 		TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
465 		/*
466 		 * if somebody else wants to take us to single threaded mode,
467 		 * count ourselves in.
468 		 */
469 		if (pr->ps_single) {
470 			curpr->ps_singlecount++;
471 			atomic_setbits_int(&p->p_flag, P_SUSPSINGLE);
472 		}
473 	}
474 
475 #if NSYSTRACE > 0
476 	if (newstrp)
477 		systrace_fork(curp, p, newstrp);
478 #endif
479 
480 	if (tidptr != NULL) {
481 		pid_t	pid = p->p_pid + THREAD_PID_OFFSET;
482 
483 		if (copyout(&pid, tidptr, sizeof(pid)))
484 			psignal(curp, SIGSEGV);
485 	}
486 
487 	/*
488 	 * For new processes, set accounting bits
489 	 */
490 	if ((flags & FORK_THREAD) == 0) {
491 		getnanotime(&pr->ps_start);
492 		pr->ps_acflag = AFORK;
493 	}
494 
495 	/*
496 	 * Make child runnable and add to run queue.
497 	 */
498 	if ((flags & FORK_IDLE) == 0) {
499 		SCHED_LOCK(s);
500 		p->p_stat = SRUN;
501 		p->p_cpu = sched_choosecpu_fork(curp, flags);
502 		setrunqueue(p);
503 		SCHED_UNLOCK(s);
504 	} else
505 		p->p_cpu = arg;
506 
507 	if (newptstat)
508 		free(newptstat, M_SUBPROC);
509 
510 	/*
511 	 * Notify any interested parties about the new process.
512 	 */
513 	if ((flags & FORK_THREAD) == 0)
514 		KNOTE(&curpr->ps_klist, NOTE_FORK | p->p_pid);
515 
516 	/*
517 	 * Update stats now that we know the fork was successful.
518 	 */
519 	uvmexp.forks++;
520 	if (flags & FORK_PPWAIT)
521 		uvmexp.forks_ppwait++;
522 	if (flags & FORK_SHAREVM)
523 		uvmexp.forks_sharevm++;
524 
525 	/*
526 	 * Pass a pointer to the new process to the caller.
527 	 */
528 	if (rnewprocp != NULL)
529 		*rnewprocp = p;
530 
531 	/*
532 	 * Preserve synchronization semantics of vfork.  If waiting for
533 	 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT
534 	 * on ourselves, and sleep on our process for the latter flag
535 	 * to go away.
536 	 * XXX Need to stop other rthreads in the parent
537 	 */
538 	if (flags & FORK_PPWAIT)
539 		while (curpr->ps_flags & PS_ISPWAIT)
540 			tsleep(curpr, PWAIT, "ppwait", 0);
541 
542 	/*
543 	 * If we're tracing the child, alert the parent too.
544 	 */
545 	if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED))
546 		psignal(curp, SIGTRAP);
547 
548 	/*
549 	 * Return child pid to parent process,
550 	 * marking us as parent via retval[1].
551 	 */
552 	if (retval != NULL) {
553 		retval[0] = p->p_pid +
554 		    (flags & FORK_THREAD ? THREAD_PID_OFFSET : 0);
555 		retval[1] = 0;
556 	}
557 	return (0);
558 }
559 
560 /*
561  * Checks for current use of a pid, either as a pid or pgid.
562  */
563 pid_t oldpids[100];
564 int
565 ispidtaken(pid_t pid)
566 {
567 	uint32_t i;
568 	struct proc *p;
569 
570 	for (i = 0; i < nitems(oldpids); i++)
571 		if (pid == oldpids[i])
572 			return (1);
573 
574 	if (pfind(pid) != NULL)
575 		return (1);
576 	if (pgfind(pid) != NULL)
577 		return (1);
578 	LIST_FOREACH(p, &zombproc, p_list) {
579 		if (p->p_pid == pid ||
580 		    (p->p_p->ps_pgrp && p->p_p->ps_pgrp->pg_id == pid))
581 			return (1);
582 	}
583 	return (0);
584 }
585 
586 /* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */
587 pid_t
588 allocpid(void)
589 {
590 	static pid_t lastpid;
591 	pid_t pid;
592 
593 	if (!randompid) {
594 		/* only used early on for system processes */
595 		pid = ++lastpid;
596 	} else {
597 		do {
598 			pid = 1 + arc4random_uniform(PID_MAX - 1);
599 		} while (ispidtaken(pid));
600 	}
601 
602 	return pid;
603 }
604 
605 void
606 freepid(pid_t pid)
607 {
608 	static uint32_t idx;
609 
610 	oldpids[idx++ % nitems(oldpids)] = pid;
611 }
612 
613 #if defined(MULTIPROCESSOR)
614 /*
615  * XXX This is a slight hack to get newly-formed processes to
616  * XXX acquire the kernel lock as soon as they run.
617  */
618 void
619 proc_trampoline_mp(void)
620 {
621 	struct proc *p;
622 
623 	p = curproc;
624 
625 	SCHED_ASSERT_LOCKED();
626 	__mp_unlock(&sched_lock);
627 	spl0();
628 	SCHED_ASSERT_UNLOCKED();
629 	KASSERT(__mp_lock_held(&kernel_lock) == 0);
630 
631 	KERNEL_LOCK();
632 }
633 #endif
634