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