xref: /openbsd-src/sys/kern/kern_fork.c (revision a2e04e14c7bba4f83f5db2cc788417da45b260c4)
1 /*	$OpenBSD: kern_fork.c,v 1.133 2011/12/14 07:32:16 guenther 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	nprocs = 1;		/* process 0 */
73 int	randompid;		/* when set to 1, pid's go random */
74 pid_t	lastpid;
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_flag & P_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_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_rfork(struct proc *p, void *v, register_t *retval)
117 {
118 	struct sys_rfork_args /* {
119 		syscallarg(int) flags;
120 	} */ *uap = v;
121 
122 	int rforkflags;
123 	int flags;
124 
125 	flags = FORK_RFORK;
126 	rforkflags = SCARG(uap, flags);
127 
128 	if ((rforkflags & RFPROC) == 0)
129 		return (EINVAL);
130 
131 	switch(rforkflags & (RFFDG|RFCFDG)) {
132 	case (RFFDG|RFCFDG):
133 		return EINVAL;
134 	case RFCFDG:
135 		flags |= FORK_CLEANFILES;
136 		break;
137 	case RFFDG:
138 		break;
139 	default:
140 		flags |= FORK_SHAREFILES;
141 		break;
142 	}
143 
144 	if (rforkflags & RFNOWAIT)
145 		flags |= FORK_NOZOMBIE;
146 
147 	if (rforkflags & RFMEM)
148 		flags |= FORK_SHAREVM;
149 
150 	if (rforkflags & RFTHREAD)
151 		flags |= FORK_THREAD | FORK_SIGHAND | FORK_NOZOMBIE;
152 
153 	return (fork1(p, SIGCHLD, flags, NULL, 0, NULL, NULL, retval, NULL));
154 }
155 
156 int
157 sys___tfork(struct proc *p, void *v, register_t *retval)
158 {
159 	struct sys___tfork_args /* {
160 		syscallarg(struct __tfork) *param;
161 	} */ *uap = v;
162 	struct __tfork param;
163 	int flags;
164 	int error;
165 
166 	if ((error = copyin(SCARG(uap, param), &param, sizeof(param))))
167 		return (error);
168 
169 	/* XXX will supersede rfork at some point... */
170 	if (param.tf_flags != 0)
171 		return (EINVAL);
172 
173 	flags = FORK_TFORK | FORK_THREAD | FORK_SIGHAND | FORK_SHAREVM
174 	    | FORK_NOZOMBIE | FORK_SHAREFILES;
175 
176 	return (fork1(p, 0, flags, NULL, param.tf_tid, tfork_child_return,
177 	    param.tf_tcb, retval, NULL));
178 }
179 
180 void
181 tfork_child_return(void *arg)
182 {
183 	struct proc *p = curproc;
184 
185 	TCB_SET(p, arg);
186 	child_return(p);
187 }
188 
189 /*
190  * Allocate and initialize a new process.
191  */
192 void
193 process_new(struct proc *p, struct process *parent)
194 {
195 	struct process *pr;
196 
197 	pr = pool_get(&process_pool, PR_WAITOK);
198 	pr->ps_mainproc = p;
199 
200 	TAILQ_INIT(&pr->ps_threads);
201 	TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
202 	pr->ps_pptr = parent;
203 	LIST_INIT(&pr->ps_children);
204 	pr->ps_refcnt = 1;
205 
206 	/*
207 	 * Make a process structure for the new process.
208 	 * Start by zeroing the section of proc that is zero-initialized,
209 	 * then copy the section that is copied directly from the parent.
210 	 */
211 	bzero(&pr->ps_startzero,
212 	    (unsigned) ((caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero));
213 	bcopy(&parent->ps_startcopy, &pr->ps_startcopy,
214 	    (unsigned) ((caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy));
215 
216 	/* post-copy fixups */
217 	pr->ps_cred = pool_get(&pcred_pool, PR_WAITOK);
218 	bcopy(parent->ps_cred, pr->ps_cred, sizeof(*pr->ps_cred));
219 	crhold(parent->ps_cred->pc_ucred);
220 	pr->ps_limit->p_refcnt++;
221 
222 	pr->ps_flags = parent->ps_flags & (PS_SUGID | PS_SUGIDEXEC);
223 	if (parent->ps_session->s_ttyvp != NULL &&
224 	    parent->ps_flags & PS_CONTROLT)
225 		atomic_setbits_int(&pr->ps_flags, PS_CONTROLT);
226 
227 	p->p_p = pr;
228 }
229 
230 /* print the 'table full' message once per 10 seconds */
231 struct timeval fork_tfmrate = { 10, 0 };
232 
233 int
234 fork1(struct proc *curp, int exitsig, int flags, void *stack, pid_t *tidptr,
235     void (*func)(void *), void *arg, register_t *retval,
236     struct proc **rnewprocp)
237 {
238 	struct process *curpr = curp->p_p;
239 	struct process *pr;
240 	struct proc *p;
241 	uid_t uid;
242 	struct vmspace *vm;
243 	int count;
244 	vaddr_t uaddr;
245 	int s;
246 	struct  ptrace_state *newptstat = NULL;
247 #if NSYSTRACE > 0
248 	void *newstrp = NULL;
249 #endif
250 
251 	/* sanity check some flag combinations */
252 	if (flags & FORK_THREAD) {
253 		if (!rthreads_enabled)
254 			return (ENOTSUP);
255 		if ((flags & (FORK_SIGHAND | FORK_NOZOMBIE)) !=
256 		    (FORK_SIGHAND | FORK_NOZOMBIE))
257 			return (EINVAL);
258 	}
259 	if (flags & FORK_SIGHAND && (flags & FORK_SHAREVM) == 0)
260 		return (EINVAL);
261 
262 	/*
263 	 * Although process entries are dynamically created, we still keep
264 	 * a global limit on the maximum number we will create. We reserve
265 	 * the last 5 processes to root. The variable nprocs is the current
266 	 * number of processes, maxproc is the limit.
267 	 */
268 	uid = curp->p_cred->p_ruid;
269 	if ((nprocs >= maxproc - 5 && uid != 0) || nprocs >= maxproc) {
270 		static struct timeval lasttfm;
271 
272 		if (ratecheck(&lasttfm, &fork_tfmrate))
273 			tablefull("proc");
274 		return (EAGAIN);
275 	}
276 	nprocs++;
277 
278 	/*
279 	 * Increment the count of procs running with this uid. Don't allow
280 	 * a nonprivileged user to exceed their current limit.
281 	 */
282 	count = chgproccnt(uid, 1);
283 	if (uid != 0 && count > curp->p_rlimit[RLIMIT_NPROC].rlim_cur) {
284 		(void)chgproccnt(uid, -1);
285 		nprocs--;
286 		return (EAGAIN);
287 	}
288 
289 	uaddr = uvm_km_kmemalloc_pla(kernel_map, uvm.kernel_object, USPACE,
290 	    USPACE_ALIGN, UVM_KMF_ZERO,
291 	    no_constraint.ucr_low, no_constraint.ucr_high,
292 	    0, 0, USPACE/PAGE_SIZE);
293 	if (uaddr == 0) {
294 		chgproccnt(uid, -1);
295 		nprocs--;
296 		return (ENOMEM);
297 	}
298 
299 	/*
300 	 * From now on, we're committed to the fork and cannot fail.
301 	 */
302 
303 	/* Allocate new proc. */
304 	p = pool_get(&proc_pool, PR_WAITOK);
305 
306 	p->p_stat = SIDL;			/* protect against others */
307 	p->p_exitsig = exitsig;
308 	p->p_flag = 0;
309 
310 	if (flags & FORK_THREAD) {
311 		atomic_setbits_int(&p->p_flag, P_THREAD);
312 		p->p_p = pr = curpr;
313 		TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
314 		pr->ps_refcnt++;
315 	} else {
316 		process_new(p, curpr);
317 		pr = p->p_p;
318 	}
319 
320 	/*
321 	 * Make a proc table entry for the new process.
322 	 * Start by zeroing the section of proc that is zero-initialized,
323 	 * then copy the section that is copied directly from the parent.
324 	 */
325 	bzero(&p->p_startzero,
326 	    (unsigned) ((caddr_t)&p->p_endzero - (caddr_t)&p->p_startzero));
327 	bcopy(&curp->p_startcopy, &p->p_startcopy,
328 	    (unsigned) ((caddr_t)&p->p_endcopy - (caddr_t)&p->p_startcopy));
329 
330 	/*
331 	 * Initialize the timeouts.
332 	 */
333 	timeout_set(&p->p_sleep_to, endtsleep, p);
334 	timeout_set(&p->p_realit_to, realitexpire, p);
335 
336 	/*
337 	 * Duplicate sub-structures as needed.
338 	 * Increase reference counts on shared objects.
339 	 * The p_stats and p_sigacts substructs are set in vm_fork.
340 	 */
341 	if (curp->p_flag & P_PROFIL)
342 		startprofclock(p);
343 	if (flags & FORK_PTRACE)
344 		atomic_setbits_int(&p->p_flag, curp->p_flag & P_TRACED);
345 
346 	/* bump references to the text vnode (for procfs) */
347 	p->p_textvp = curp->p_textvp;
348 	if (p->p_textvp)
349 		vref(p->p_textvp);
350 
351 	if (flags & FORK_CLEANFILES)
352 		p->p_fd = fdinit(curp);
353 	else if (flags & FORK_SHAREFILES)
354 		p->p_fd = fdshare(curp);
355 	else
356 		p->p_fd = fdcopy(curp);
357 
358 	if (flags & FORK_PPWAIT) {
359 		atomic_setbits_int(&pr->ps_flags, PS_PPWAIT);
360 		atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT);
361 	}
362 	if (flags & FORK_NOZOMBIE)
363 		atomic_setbits_int(&p->p_flag, P_NOZOMBIE);
364 
365 #ifdef KTRACE
366 	/*
367 	 * Copy traceflag and tracefile if enabled.
368 	 * If not inherited, these were zeroed above.
369 	 */
370 	if ((flags & FORK_THREAD) == 0 && curpr->ps_traceflag & KTRFAC_INHERIT)
371 		ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp,
372 		    curpr->ps_tracecred);
373 #endif
374 
375 	/*
376 	 * set priority of child to be that of parent
377 	 * XXX should move p_estcpu into the region of struct proc which gets
378 	 * copied.
379 	 */
380 	scheduler_fork_hook(curp, p);
381 
382 	/*
383 	 * Create signal actions for the child process.
384 	 */
385 	if (flags & FORK_SIGHAND)
386 		p->p_sigacts = sigactsshare(curp);
387 	else
388 		p->p_sigacts = sigactsinit(curp);
389 	if (flags & FORK_THREAD)
390 		sigstkinit(&p->p_sigstk);
391 
392 	/*
393 	 * If emulation has process fork hook, call it now.
394 	 */
395 	if (p->p_emul->e_proc_fork)
396 		(*p->p_emul->e_proc_fork)(p, curp);
397 
398 	p->p_addr = (struct user *)uaddr;
399 
400 	/*
401 	 * Finish creating the child process.  It will return through a
402 	 * different path later.
403 	 */
404 	uvm_fork(curp, p, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack,
405 	    0, func ? func : child_return, arg ? arg : p);
406 
407 	timeout_set(&p->p_stats->p_virt_to, virttimer_trampoline, p);
408 	timeout_set(&p->p_stats->p_prof_to, proftimer_trampoline, p);
409 
410 	vm = p->p_vmspace;
411 
412 	if (flags & FORK_FORK) {
413 		forkstat.cntfork++;
414 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
415 	} else if (flags & FORK_VFORK) {
416 		forkstat.cntvfork++;
417 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
418 #if 0
419 	} else if (flags & FORK_TFORK) {
420 		forkstat.cnttfork++;
421 #endif
422 	} else if (flags & FORK_RFORK) {
423 		forkstat.cntrfork++;
424 		forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize;
425 	} else {
426 		forkstat.cntkthread++;
427 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
428 	}
429 
430 	if (p->p_flag & P_TRACED && flags & FORK_FORK)
431 		newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK);
432 #if NSYSTRACE > 0
433 	if (ISSET(curp->p_flag, P_SYSTRACE))
434 		newstrp = systrace_getproc();
435 #endif
436 
437 	/* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */
438 	do {
439 		lastpid = 1 + (randompid ? arc4random() : lastpid) % PID_MAX;
440 	} while (pidtaken(lastpid));
441 	p->p_pid = lastpid;
442 
443 	LIST_INSERT_HEAD(&allproc, p, p_list);
444 	LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
445 	if ((flags & FORK_THREAD) == 0) {
446 		LIST_INSERT_AFTER(curpr, pr, ps_pglist);
447 		LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling);
448 	}
449 
450 	if (p->p_flag & P_TRACED) {
451 		p->p_oppid = curp->p_pid;
452 		if ((flags & FORK_THREAD) == 0 &&
453 		    pr->ps_pptr != curpr->ps_pptr)
454 			proc_reparent(pr, curpr->ps_pptr);
455 
456 		/*
457 		 * Set ptrace status.
458 		 */
459 		if (flags & FORK_FORK) {
460 			p->p_ptstat = newptstat;
461 			newptstat = NULL;
462 			curp->p_ptstat->pe_report_event = PTRACE_FORK;
463 			p->p_ptstat->pe_report_event = PTRACE_FORK;
464 			curp->p_ptstat->pe_other_pid = p->p_pid;
465 			p->p_ptstat->pe_other_pid = curp->p_pid;
466 		}
467 	}
468 
469 #if NSYSTRACE > 0
470 	if (newstrp)
471 		systrace_fork(curp, p, newstrp);
472 #endif
473 
474 	if (tidptr != NULL) {
475 		pid_t	pid = p->p_pid + THREAD_PID_OFFSET;
476 
477 		if (copyout(&pid, tidptr, sizeof(pid)))
478 			psignal(curp, SIGSEGV);
479 	}
480 
481 	/*
482 	 * Make child runnable, set start time, and add to run queue.
483 	 */
484 	SCHED_LOCK(s);
485  	getmicrotime(&p->p_stats->p_start);
486 	p->p_acflag = AFORK;
487 	p->p_stat = SRUN;
488 	p->p_cpu = sched_choosecpu_fork(curp, flags);
489 	setrunqueue(p);
490 	SCHED_UNLOCK(s);
491 
492 	if (newptstat)
493 		free(newptstat, M_SUBPROC);
494 
495 	/*
496 	 * Notify any interested parties about the new process.
497 	 */
498 	if ((flags & FORK_THREAD) == 0)
499 		KNOTE(&curpr->ps_klist, NOTE_FORK | p->p_pid);
500 
501 	/*
502 	 * Update stats now that we know the fork was successful.
503 	 */
504 	uvmexp.forks++;
505 	if (flags & FORK_PPWAIT)
506 		uvmexp.forks_ppwait++;
507 	if (flags & FORK_SHAREVM)
508 		uvmexp.forks_sharevm++;
509 
510 	/*
511 	 * Pass a pointer to the new process to the caller.
512 	 */
513 	if (rnewprocp != NULL)
514 		*rnewprocp = p;
515 
516 	/*
517 	 * Preserve synchronization semantics of vfork.  If waiting for
518 	 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT
519 	 * on ourselves, and sleep on our process for the latter flag
520 	 * to go away.
521 	 * XXX Need to stop other rthreads in the parent
522 	 */
523 	if (flags & FORK_PPWAIT)
524 		while (curpr->ps_flags & PS_ISPWAIT)
525 			tsleep(curpr, PWAIT, "ppwait", 0);
526 
527 	/*
528 	 * If we're tracing the child, alert the parent too.
529 	 */
530 	if ((flags & FORK_PTRACE) && (curp->p_flag & P_TRACED))
531 		psignal(curp, SIGTRAP);
532 
533 	/*
534 	 * Return child pid to parent process,
535 	 * marking us as parent via retval[1].
536 	 */
537 	if (retval != NULL) {
538 		retval[0] = p->p_pid +
539 		    (flags & FORK_THREAD ? THREAD_PID_OFFSET : 0);
540 		retval[1] = 0;
541 	}
542 	return (0);
543 }
544 
545 /*
546  * Checks for current use of a pid, either as a pid or pgid.
547  */
548 int
549 pidtaken(pid_t pid)
550 {
551 	struct proc *p;
552 
553 	if (pfind(pid) != NULL)
554 		return (1);
555 	if (pgfind(pid) != NULL)
556 		return (1);
557 	LIST_FOREACH(p, &zombproc, p_list) {
558 		if (p->p_pid == pid || (p->p_p->ps_pgrp && p->p_p->ps_pgrp->pg_id == pid))
559 			return (1);
560 	}
561 	return (0);
562 }
563 
564 #if defined(MULTIPROCESSOR)
565 /*
566  * XXX This is a slight hack to get newly-formed processes to
567  * XXX acquire the kernel lock as soon as they run.
568  */
569 void
570 proc_trampoline_mp(void)
571 {
572 	struct proc *p;
573 
574 	p = curproc;
575 
576 	SCHED_ASSERT_LOCKED();
577 	__mp_unlock(&sched_lock);
578 	spl0();
579 	SCHED_ASSERT_UNLOCKED();
580 	KASSERT(__mp_lock_held(&kernel_lock) == 0);
581 
582 	KERNEL_LOCK();
583 }
584 #endif
585