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