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