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