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