xref: /openbsd-src/sys/kern/kern_fork.c (revision f07e72ced5291792cbe72a84ad9c7397a32e1093)
1 /*	$OpenBSD: kern_fork.c,v 1.88 2007/03/24 16:01:22 art 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 int	nprocs = 1;		/* process 0 */
69 int	randompid;		/* when set to 1, pid's go random */
70 pid_t	lastpid;
71 struct	forkstat forkstat;
72 
73 void fork_return(void *);
74 int pidtaken(pid_t);
75 
76 void
77 fork_return(void *arg)
78 {
79 	struct proc *p = (struct proc *)arg;
80 
81 	if (p->p_flag & P_TRACED)
82 		psignal(p, SIGTRAP);
83 
84 	child_return(p);
85 }
86 
87 /*ARGSUSED*/
88 int
89 sys_fork(struct proc *p, void *v, register_t *retval)
90 {
91 	int flags;
92 
93 	flags = FORK_FORK;
94 	if (p->p_ptmask & PTRACE_FORK)
95 		flags |= FORK_PTRACE;
96 	return (fork1(p, SIGCHLD, flags, NULL, 0,
97 	    fork_return, NULL, retval, NULL));
98 }
99 
100 /*ARGSUSED*/
101 int
102 sys_vfork(struct proc *p, void *v, register_t *retval)
103 {
104 	return (fork1(p, SIGCHLD, FORK_VFORK|FORK_PPWAIT, NULL, 0, NULL,
105 	    NULL, retval, NULL));
106 }
107 
108 int
109 sys_rfork(struct proc *p, void *v, register_t *retval)
110 {
111 	struct sys_rfork_args /* {
112 		syscallarg(int) flags;
113 	} */ *uap = v;
114 
115 	int rforkflags;
116 	int flags;
117 
118 	flags = FORK_RFORK;
119 	rforkflags = SCARG(uap, flags);
120 
121 	if ((rforkflags & RFPROC) == 0)
122 		return (EINVAL);
123 
124 	switch(rforkflags & (RFFDG|RFCFDG)) {
125 	case (RFFDG|RFCFDG):
126 		return EINVAL;
127 	case RFCFDG:
128 		flags |= FORK_CLEANFILES;
129 		break;
130 	case RFFDG:
131 		break;
132 	default:
133 		flags |= FORK_SHAREFILES;
134 		break;
135 	}
136 
137 	if (rforkflags & RFNOWAIT)
138 		flags |= FORK_NOZOMBIE;
139 
140 	if (rforkflags & RFMEM)
141 		flags |= FORK_SHAREVM;
142 #ifdef RTHREADS
143 	if (rforkflags & RFTHREAD)
144 		flags |= FORK_THREAD;
145 #endif
146 
147 	return (fork1(p, SIGCHLD, flags, NULL, 0, NULL, NULL, retval, NULL));
148 }
149 
150 /* print the 'table full' message once per 10 seconds */
151 struct timeval fork_tfmrate = { 10, 0 };
152 
153 int
154 fork1(struct proc *p1, int exitsig, int flags, void *stack, size_t stacksize,
155     void (*func)(void *), void *arg, register_t *retval,
156     struct proc **rnewprocp)
157 {
158 	struct proc *p2;
159 	uid_t uid;
160 	struct vmspace *vm;
161 	int count;
162 	vaddr_t uaddr;
163 	int s;
164 	extern void endtsleep(void *);
165 	extern void realitexpire(void *);
166 
167 	/*
168 	 * Although process entries are dynamically created, we still keep
169 	 * a global limit on the maximum number we will create. We reserve
170 	 * the last 5 processes to root. The variable nprocs is the current
171 	 * number of processes, maxproc is the limit.
172 	 */
173 	uid = p1->p_cred->p_ruid;
174 	if ((nprocs >= maxproc - 5 && uid != 0) || nprocs >= maxproc) {
175 		static struct timeval lasttfm;
176 
177 		if (ratecheck(&lasttfm, &fork_tfmrate))
178 			tablefull("proc");
179 		return (EAGAIN);
180 	}
181 	nprocs++;
182 
183 	/*
184 	 * Increment the count of procs running with this uid. Don't allow
185 	 * a nonprivileged user to exceed their current limit.
186 	 */
187 	count = chgproccnt(uid, 1);
188 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
189 		(void)chgproccnt(uid, -1);
190 		nprocs--;
191 		return (EAGAIN);
192 	}
193 
194 	uaddr = uvm_km_alloc1(kernel_map, USPACE, USPACE_ALIGN, 1);
195 	if (uaddr == 0) {
196 		chgproccnt(uid, -1);
197 		nprocs--;
198 		return (ENOMEM);
199 	}
200 
201 	/*
202 	 * From now on, we're committed to the fork and cannot fail.
203 	 */
204 
205 	/* Allocate new proc. */
206 	p2 = pool_get(&proc_pool, PR_WAITOK);
207 
208 	p2->p_stat = SIDL;			/* protect against others */
209 	p2->p_exitsig = exitsig;
210 	p2->p_forw = p2->p_back = NULL;
211 
212 	/*
213 	 * Make a proc table entry for the new process.
214 	 * Start by zeroing the section of proc that is zero-initialized,
215 	 * then copy the section that is copied directly from the parent.
216 	 */
217 	bzero(&p2->p_startzero,
218 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
219 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
220 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
221 
222 	/*
223 	 * Initialize the timeouts.
224 	 */
225 	timeout_set(&p2->p_sleep_to, endtsleep, p2);
226 	timeout_set(&p2->p_realit_to, realitexpire, p2);
227 
228 #if defined(__HAVE_CPUINFO)
229 	p2->p_cpu = p1->p_cpu;
230 #endif
231 
232 	/*
233 	 * Duplicate sub-structures as needed.
234 	 * Increase reference counts on shared objects.
235 	 * The p_stats and p_sigacts substructs are set in vm_fork.
236 	 */
237 	p2->p_flag = 0;
238 	p2->p_emul = p1->p_emul;
239 	if (p1->p_flag & P_PROFIL)
240 		startprofclock(p2);
241 	atomic_setbits_int(&p2->p_flag, p1->p_flag & (P_SUGID | P_SUGIDEXEC));
242 	if (flags & FORK_PTRACE)
243 		atomic_setbits_int(&p2->p_flag, p1->p_flag & P_TRACED);
244 	p2->p_cred = pool_get(&pcred_pool, PR_WAITOK);
245 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
246 	p2->p_cred->p_refcnt = 1;
247 	crhold(p1->p_ucred);
248 
249 	TAILQ_INIT(&p2->p_selects);
250 
251 	/* bump references to the text vnode (for procfs) */
252 	p2->p_textvp = p1->p_textvp;
253 	if (p2->p_textvp)
254 		VREF(p2->p_textvp);
255 
256 	if (flags & FORK_CLEANFILES)
257 		p2->p_fd = fdinit(p1);
258 	else if (flags & FORK_SHAREFILES)
259 		p2->p_fd = fdshare(p1);
260 	else
261 		p2->p_fd = fdcopy(p1);
262 
263 	/*
264 	 * If p_limit is still copy-on-write, bump refcnt,
265 	 * otherwise get a copy that won't be modified.
266 	 * (If PL_SHAREMOD is clear, the structure is shared
267 	 * copy-on-write.)
268 	 */
269 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
270 		p2->p_limit = limcopy(p1->p_limit);
271 	else {
272 		p2->p_limit = p1->p_limit;
273 		p2->p_limit->p_refcnt++;
274 	}
275 
276 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
277 		atomic_setbits_int(&p2->p_flag, P_CONTROLT);
278 	if (flags & FORK_PPWAIT)
279 		atomic_setbits_int(&p2->p_flag, P_PPWAIT);
280 	p2->p_pptr = p1;
281 	if (flags & FORK_NOZOMBIE)
282 		atomic_setbits_int(&p2->p_flag, P_NOZOMBIE);
283 	LIST_INIT(&p2->p_children);
284 
285 #ifdef RTHREADS
286 	if (flags & FORK_THREAD) {
287 		atomic_setbits_int(&p2->p_flag, P_THREAD);
288 		p2->p_thrparent = p1->p_thrparent;
289 	} else {
290 		p2->p_thrparent = p2;
291 	}
292 #else
293 	p2->p_thrparent = p2;
294 #endif
295 
296 	LIST_INIT(&p2->p_thrchildren);
297 
298 #ifdef KTRACE
299 	/*
300 	 * Copy traceflag and tracefile if enabled.
301 	 * If not inherited, these were zeroed above.
302 	 */
303 	if (p1->p_traceflag & KTRFAC_INHERIT) {
304 		p2->p_traceflag = p1->p_traceflag;
305 		if ((p2->p_tracep = p1->p_tracep) != NULL)
306 			VREF(p2->p_tracep);
307 	}
308 #endif
309 
310 	/*
311 	 * set priority of child to be that of parent
312 	 * XXX should move p_estcpu into the region of struct proc which gets
313 	 * copied.
314 	 */
315 	scheduler_fork_hook(p1, p2);
316 
317 	/*
318 	 * Create signal actions for the child process.
319 	 */
320 	if (flags & FORK_SIGHAND)
321 		sigactsshare(p1, p2);
322 	else
323 		p2->p_sigacts = sigactsinit(p1);
324 
325 	/*
326 	 * If emulation has process fork hook, call it now.
327 	 */
328 	if (p2->p_emul->e_proc_fork)
329 		(*p2->p_emul->e_proc_fork)(p2, p1);
330 
331 	p2->p_addr = (struct user *)uaddr;
332 
333 	/*
334 	 * Finish creating the child process.  It will return through a
335 	 * different path later.
336 	 */
337 	uvm_fork(p1, p2, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack,
338 	    stacksize, func ? func : child_return, arg ? arg : p2);
339 
340 	timeout_set(&p2->p_stats->p_virt_to, virttimer_trampoline, p2);
341 	timeout_set(&p2->p_stats->p_prof_to, proftimer_trampoline, p2);
342 
343 	vm = p2->p_vmspace;
344 
345 	if (flags & FORK_FORK) {
346 		forkstat.cntfork++;
347 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
348 	} else if (flags & FORK_VFORK) {
349 		forkstat.cntvfork++;
350 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
351 	} else if (flags & FORK_RFORK) {
352 		forkstat.cntrfork++;
353 		forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize;
354 	} else {
355 		forkstat.cntkthread++;
356 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
357 	}
358 
359 	/* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */
360 	do {
361 		lastpid = 1 + (randompid ? arc4random() : lastpid) % PID_MAX;
362 	} while (pidtaken(lastpid));
363 	p2->p_pid = lastpid;
364 
365 	LIST_INSERT_HEAD(&allproc, p2, p_list);
366 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
367 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
368 	LIST_INSERT_AFTER(p1, p2, p_pglist);
369 #ifdef RTHREADS
370 	if (flags & FORK_THREAD)
371 		LIST_INSERT_HEAD(&p1->p_thrparent->p_thrchildren, p2, p_thrsib);
372 #endif
373 	if (p2->p_flag & P_TRACED) {
374 		p2->p_oppid = p1->p_pid;
375 		if (p2->p_pptr != p1->p_pptr)
376 			proc_reparent(p2, p1->p_pptr);
377 
378 		/*
379 		 * Set ptrace status.
380 		 */
381 		if (flags & FORK_FORK) {
382 			p2->p_ptstat = malloc(sizeof(*p2->p_ptstat),
383 			    M_SUBPROC, M_WAITOK);
384 			p1->p_ptstat->pe_report_event = PTRACE_FORK;
385 			p2->p_ptstat->pe_report_event = PTRACE_FORK;
386 			p1->p_ptstat->pe_other_pid = p2->p_pid;
387 			p2->p_ptstat->pe_other_pid = p1->p_pid;
388 		}
389 	}
390 
391 #if NSYSTRACE > 0
392 	if (ISSET(p1->p_flag, P_SYSTRACE))
393 		systrace_fork(p1, p2);
394 #endif
395 
396 	/*
397 	 * Make child runnable, set start time, and add to run queue.
398 	 */
399 	SCHED_LOCK(s);
400  	getmicrotime(&p2->p_stats->p_start);
401 	p2->p_acflag = AFORK;
402 	p2->p_stat = SRUN;
403 	setrunqueue(p2);
404 	SCHED_UNLOCK(s);
405 
406 	/*
407 	 * Notify any interested parties about the new process.
408 	 */
409 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
410 
411 	/*
412 	 * Update stats now that we know the fork was successfull.
413 	 */
414 	uvmexp.forks++;
415 	if (flags & FORK_PPWAIT)
416 		uvmexp.forks_ppwait++;
417 	if (flags & FORK_SHAREVM)
418 		uvmexp.forks_sharevm++;
419 
420 	/*
421 	 * Pass a pointer to the new process to the caller.
422 	 */
423 	if (rnewprocp != NULL)
424 		*rnewprocp = p2;
425 
426 	/*
427 	 * Preserve synchronization semantics of vfork.  If waiting for
428 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
429 	 * proc (in case of exit).
430 	 */
431 	if (flags & FORK_PPWAIT)
432 		while (p2->p_flag & P_PPWAIT)
433 			tsleep(p1, PWAIT, "ppwait", 0);
434 
435 	/*
436 	 * If we're tracing the child, alert the parent too.
437 	 */
438 	if ((flags & FORK_PTRACE) && (p1->p_flag & P_TRACED))
439 		psignal(p1, SIGTRAP);
440 
441 	/*
442 	 * Return child pid to parent process,
443 	 * marking us as parent via retval[1].
444 	 */
445 	if (retval != NULL) {
446 		retval[0] = p2->p_pid;
447 		retval[1] = 0;
448 	}
449 	return (0);
450 }
451 
452 /*
453  * Checks for current use of a pid, either as a pid or pgid.
454  */
455 int
456 pidtaken(pid_t pid)
457 {
458 	struct proc *p;
459 
460 	if (pfind(pid) != NULL)
461 		return (1);
462 	if (pgfind(pid) != NULL)
463 		return (1);
464 	LIST_FOREACH(p, &zombproc, p_list)
465 		if (p->p_pid == pid || p->p_pgid == pid)
466 			return (1);
467 	return (0);
468 }
469 
470 #if defined(MULTIPROCESSOR)
471 /*
472  * XXX This is a slight hack to get newly-formed processes to
473  * XXX acquire the kernel lock as soon as they run.
474  */
475 void
476 proc_trampoline_mp(void)
477 {
478 	struct proc *p;
479 
480 	p = curproc;
481 
482 	SCHED_ASSERT_UNLOCKED();
483 	KERNEL_PROC_LOCK(p);
484 }
485 #endif
486