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