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