xref: /openbsd-src/sys/kern/kern_fork.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
1 /*	$OpenBSD: kern_fork.c,v 1.62 2003/07/02 00:07:42 avsm 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/resourcevar.h>
48 #include <sys/signalvar.h>
49 #include <sys/vnode.h>
50 #include <sys/file.h>
51 #include <sys/acct.h>
52 #include <sys/ktrace.h>
53 #include <sys/sched.h>
54 #include <dev/rndvar.h>
55 #include <sys/pool.h>
56 #include <sys/mman.h>
57 
58 #include <sys/syscallargs.h>
59 
60 #include "systrace.h"
61 #include <dev/systrace.h>
62 
63 #include <uvm/uvm_extern.h>
64 #include <uvm/uvm_map.h>
65 
66 int	nprocs = 1;		/* process 0 */
67 int	randompid;		/* when set to 1, pid's go random */
68 pid_t	lastpid;
69 struct	forkstat forkstat;
70 
71 int pidtaken(pid_t);
72 
73 /*ARGSUSED*/
74 int
75 sys_fork(struct proc *p, void *v, register_t *retval)
76 {
77 	return (fork1(p, SIGCHLD, FORK_FORK, NULL, 0, NULL, NULL, retval));
78 }
79 
80 /*ARGSUSED*/
81 int
82 sys_vfork(struct proc *p, void *v, register_t *retval)
83 {
84 	return (fork1(p, SIGCHLD, FORK_VFORK|FORK_PPWAIT, NULL, 0, NULL,
85 	    NULL, retval));
86 }
87 
88 int
89 sys_rfork(struct proc *p, void *v, register_t *retval)
90 {
91 	struct sys_rfork_args /* {
92 		syscallarg(int) flags;
93 	} */ *uap = v;
94 
95 	int rforkflags;
96 	int flags;
97 
98 	flags = FORK_RFORK;
99 	rforkflags = SCARG(uap, flags);
100 
101 	if ((rforkflags & RFPROC) == 0)
102 		return (EINVAL);
103 
104 	switch(rforkflags & (RFFDG|RFCFDG)) {
105 	case (RFFDG|RFCFDG):
106 		return EINVAL;
107 	case RFCFDG:
108 		flags |= FORK_CLEANFILES;
109 		break;
110 	case RFFDG:
111 		break;
112 	default:
113 		flags |= FORK_SHAREFILES;
114 		break;
115 	}
116 
117 	if (rforkflags & RFNOWAIT)
118 		flags |= FORK_NOZOMBIE;
119 
120 	if (rforkflags & RFMEM)
121 		flags |= FORK_VMNOSTACK;
122 
123 	return (fork1(p, SIGCHLD, flags, NULL, 0, NULL, NULL, retval));
124 }
125 
126 int
127 fork1(struct proc *p1, int exitsig, int flags, void *stack, size_t stacksize,
128     void (*func)(void *), void *arg, register_t *retval)
129 {
130 	struct proc *p2;
131 	uid_t uid;
132 	struct vmspace *vm;
133 	int count;
134 	vaddr_t uaddr;
135 	int s;
136 	extern void endtsleep(void *);
137 	extern void realitexpire(void *);
138 
139 	/*
140 	 * Although process entries are dynamically created, we still keep
141 	 * a global limit on the maximum number we will create. We reserve
142 	 * the last 5 processes to root. The variable nprocs is the current
143 	 * number of processes, maxproc is the limit.
144 	 */
145 	uid = p1->p_cred->p_ruid;
146 	if ((nprocs >= maxproc - 5 && uid != 0) || nprocs >= maxproc) {
147 		tablefull("proc");
148 		return (EAGAIN);
149 	}
150 	nprocs++;
151 
152 	/*
153 	 * Increment the count of procs running with this uid. Don't allow
154 	 * a nonprivileged user to exceed their current limit.
155 	 */
156 	count = chgproccnt(uid, 1);
157 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
158 		(void)chgproccnt(uid, -1);
159 		nprocs--;
160 		return (EAGAIN);
161 	}
162 
163 	/*
164 	 * Allocate a pcb and kernel stack for the process
165 	 */
166 	uaddr = uvm_km_valloc(kernel_map, USPACE);
167 	if (uaddr == 0) {
168 		chgproccnt(uid, -1);
169 		nprocs--;
170 		return (ENOMEM);
171 	}
172 
173 	/*
174 	 * From now on, we're committed to the fork and cannot fail.
175 	 */
176 
177 	/* Allocate new proc. */
178 	p2 = pool_get(&proc_pool, PR_WAITOK);
179 
180 	p2->p_stat = SIDL;			/* protect against others */
181 	p2->p_exitsig = exitsig;
182 	p2->p_forw = p2->p_back = NULL;
183 
184 	/*
185 	 * Make a proc table entry for the new process.
186 	 * Start by zeroing the section of proc that is zero-initialized,
187 	 * then copy the section that is copied directly from the parent.
188 	 */
189 	bzero(&p2->p_startzero,
190 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
191 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
192 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
193 
194 	/*
195 	 * Initialize the timeouts.
196 	 */
197 	timeout_set(&p2->p_sleep_to, endtsleep, p2);
198 	timeout_set(&p2->p_realit_to, realitexpire, p2);
199 
200 	/*
201 	 * Duplicate sub-structures as needed.
202 	 * Increase reference counts on shared objects.
203 	 * The p_stats and p_sigacts substructs are set in vm_fork.
204 	 */
205 	p2->p_flag = P_INMEM;
206 	p2->p_emul = p1->p_emul;
207 	if (p1->p_flag & P_PROFIL)
208 		startprofclock(p2);
209 	p2->p_flag |= (p1->p_flag & (P_SUGID | P_SUGIDEXEC));
210 	p2->p_cred = pool_get(&pcred_pool, PR_WAITOK);
211 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
212 	p2->p_cred->p_refcnt = 1;
213 	crhold(p1->p_ucred);
214 
215 	/* bump references to the text vnode (for procfs) */
216 	p2->p_textvp = p1->p_textvp;
217 	if (p2->p_textvp)
218 		VREF(p2->p_textvp);
219 
220 	if (flags & FORK_CLEANFILES)
221 		p2->p_fd = fdinit(p1);
222 	else if (flags & FORK_SHAREFILES)
223 		p2->p_fd = fdshare(p1);
224 	else
225 		p2->p_fd = fdcopy(p1);
226 
227 	/*
228 	 * If p_limit is still copy-on-write, bump refcnt,
229 	 * otherwise get a copy that won't be modified.
230 	 * (If PL_SHAREMOD is clear, the structure is shared
231 	 * copy-on-write.)
232 	 */
233 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
234 		p2->p_limit = limcopy(p1->p_limit);
235 	else {
236 		p2->p_limit = p1->p_limit;
237 		p2->p_limit->p_refcnt++;
238 	}
239 
240 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
241 		p2->p_flag |= P_CONTROLT;
242 	if (flags & FORK_PPWAIT)
243 		p2->p_flag |= P_PPWAIT;
244 	LIST_INSERT_AFTER(p1, p2, p_pglist);
245 	p2->p_pptr = p1;
246 	if (flags & FORK_NOZOMBIE)
247 		p2->p_flag |= P_NOZOMBIE;
248 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
249 	LIST_INIT(&p2->p_children);
250 
251 #ifdef KTRACE
252 	/*
253 	 * Copy traceflag and tracefile if enabled.
254 	 * If not inherited, these were zeroed above.
255 	 */
256 	if (p1->p_traceflag & KTRFAC_INHERIT) {
257 		p2->p_traceflag = p1->p_traceflag;
258 		if ((p2->p_tracep = p1->p_tracep) != NULL)
259 			VREF(p2->p_tracep);
260 	}
261 #endif
262 
263 	/*
264 	 * set priority of child to be that of parent
265 	 * XXX should move p_estcpu into the region of struct proc which gets
266 	 * copied.
267 	 */
268 	scheduler_fork_hook(p1, p2);
269 
270 	/*
271 	 * Create signal actions for the child process.
272 	 */
273 	if (flags & FORK_SIGHAND)
274 		sigactsshare(p1, p2);
275 	else
276 		p2->p_sigacts = sigactsinit(p1);
277 
278 	/*
279 	 * If emulation has process fork hook, call it now.
280 	 */
281 	if (p2->p_emul->e_proc_fork)
282 		(*p2->p_emul->e_proc_fork)(p2, p1);
283 	/*
284 	 * This begins the section where we must prevent the parent
285 	 * from being swapped.
286 	 */
287 	PHOLD(p1);
288 
289 	if (flags & FORK_VMNOSTACK) {
290 		/* share everything, but ... */
291 		uvm_map_inherit(&p1->p_vmspace->vm_map,
292 		    VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS,
293 		    MAP_INHERIT_SHARE);
294 		/* ... don't share stack */
295 #ifdef MACHINE_STACK_GROWS_UP
296 		uvm_map_inherit(&p1->p_vmspace->vm_map,
297 		    USRSTACK, USRSTACK + MAXSSIZ,
298 		    MAP_INHERIT_COPY);
299 #else
300 		uvm_map_inherit(&p1->p_vmspace->vm_map,
301 		    USRSTACK - MAXSSIZ, USRSTACK,
302 		    MAP_INHERIT_COPY);
303 #endif
304 	}
305 
306 	p2->p_addr = (struct user *)uaddr;
307 
308 	/*
309 	 * Finish creating the child process.  It will return through a
310 	 * different path later.
311 	 */
312 	uvm_fork(p1, p2, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack,
313 	    stacksize, func ? func : child_return, arg ? arg : p2);
314 
315 	vm = p2->p_vmspace;
316 
317 	if (flags & FORK_FORK) {
318 		forkstat.cntfork++;
319 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
320 	} else if (flags & FORK_VFORK) {
321 		forkstat.cntvfork++;
322 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
323 	} else if (flags & FORK_RFORK) {
324 		forkstat.cntrfork++;
325 		forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize;
326 	} else {
327 		forkstat.cntkthread++;
328 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
329 	}
330 
331 	/* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */
332 	do {
333 		lastpid = 1 + (randompid ? arc4random() : lastpid) % PID_MAX;
334 	} while (pidtaken(lastpid));
335 	p2->p_pid = lastpid;
336 
337 	LIST_INSERT_HEAD(&allproc, p2, p_list);
338 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
339 
340 #if NSYSTRACE > 0
341 	if (ISSET(p1->p_flag, P_SYSTRACE))
342 		systrace_fork(p1, p2);
343 #endif
344 
345 	/*
346 	 * Make child runnable, set start time, and add to run queue.
347 	 */
348 	s = splstatclock();
349 	p2->p_stats->p_start = time;
350 	p2->p_acflag = AFORK;
351 	p2->p_stat = SRUN;
352 	setrunqueue(p2);
353 	splx(s);
354 
355 	/*
356 	 * Now can be swapped.
357 	 */
358 	PRELE(p1);
359 
360 	uvmexp.forks++;
361 	if (flags & FORK_PPWAIT)
362 		uvmexp.forks_ppwait++;
363 	if (flags & FORK_SHAREVM)
364 		uvmexp.forks_sharevm++;
365 
366 	/*
367 	 * tell any interested parties about the new process
368 	 */
369 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
370 
371 	/*
372 	 * Preserve synchronization semantics of vfork.  If waiting for
373 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
374 	 * proc (in case of exit).
375 	 */
376 	if (flags & FORK_PPWAIT)
377 		while (p2->p_flag & P_PPWAIT)
378 			tsleep(p1, PWAIT, "ppwait", 0);
379 
380 	/*
381 	 * Return child pid to parent process,
382 	 * marking us as parent via retval[1].
383 	 */
384 	retval[0] = p2->p_pid;
385 	retval[1] = 0;
386 	return (0);
387 }
388 
389 /*
390  * Checks for current use of a pid, either as a pid or pgid.
391  */
392 int
393 pidtaken(pid_t pid)
394 {
395 	struct proc *p;
396 
397 	if (pfind(pid) != NULL)
398 		return (1);
399 	if (pgfind(pid) != NULL)
400 		return (1);
401 	LIST_FOREACH(p, &zombproc, p_list)
402 		if (p->p_pid == pid || p->p_pgid == pid)
403 			return (1);
404 	return (0);
405 }
406