xref: /openbsd-src/sys/kern/kern_fork.c (revision 1a12e8a7ab11e47f6fb18cdbc03b05e8885dfcad)
1 /*	$OpenBSD: kern_fork.c,v 1.36 2000/11/16 20:02:17 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/map.h>
47 #include <sys/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
51 #include <sys/proc.h>
52 #include <sys/resourcevar.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 
60 #include <sys/syscallargs.h>
61 
62 #include <vm/vm.h>
63 #include <vm/vm_kern.h>
64 
65 #if defined(UVM)
66 #include <uvm/uvm_extern.h>
67 #include <uvm/uvm_map.h>
68 #endif
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 
76 /*ARGSUSED*/
77 int
78 sys_fork(p, v, retval)
79 	struct proc *p;
80 	void *v;
81 	register_t *retval;
82 {
83 	return (fork1(p, FORK_FORK, NULL, 0, retval));
84 }
85 
86 /*ARGSUSED*/
87 int
88 sys_vfork(p, v, retval)
89 	struct proc *p;
90 	void *v;
91 	register_t *retval;
92 {
93 	return (fork1(p, FORK_VFORK|FORK_PPWAIT, NULL, 0, retval));
94 }
95 
96 int
97 sys_rfork(p, v, retval)
98 	struct proc *p;
99 	void *v;
100 	register_t *retval;
101 {
102 	struct sys_rfork_args /* {
103 		syscallarg(int) flags;
104 	} */ *uap = v;
105 	int rforkflags;
106 	int flags;
107 
108 	flags = FORK_RFORK;
109 	rforkflags = SCARG(uap, flags);
110 
111 	if ((rforkflags & RFPROC) == 0)
112 		return (EINVAL);
113 
114 	switch(rforkflags & (RFFDG|RFCFDG)) {
115 	case (RFFDG|RFCFDG):
116 		return EINVAL;
117 	case RFCFDG:
118 		flags |= FORK_CLEANFILES;
119 		break;
120 	case RFFDG:
121 		break;
122 	default:
123 		flags |= FORK_SHAREFILES;
124 		break;
125 	}
126 
127 	if (rforkflags & RFNOWAIT)
128 		flags |= FORK_NOZOMBIE;
129 
130 	if (rforkflags & RFMEM)
131 		flags |= FORK_VMNOSTACK;
132 
133 	return (fork1(p, flags, NULL, 0, retval));
134 }
135 
136 int
137 fork1(p1, flags, stack, stacksize, retval)
138 	register struct proc *p1;
139 	int flags;
140 	void *stack;
141 	size_t stacksize;
142 	register_t *retval;
143 {
144 	struct proc *p2;
145 	uid_t uid;
146 	struct proc *newproc;
147 	struct vmspace *vm;
148 	int count;
149 	static int pidchecked = 0;
150 	vaddr_t uaddr;
151 	extern void endtsleep __P((void *));
152 	extern void realitexpire __P((void *));
153 
154 	/*
155 	 * Although process entries are dynamically created, we still keep
156 	 * a global limit on the maximum number we will create. We reserve
157 	 * the last 5 processes to root. The variable nprocs is the current
158 	 * number of processes, maxproc is the limit.
159 	 */
160 	uid = p1->p_cred->p_ruid;
161 	if ((nprocs >= maxproc - 5 && uid != 0) || nprocs >= maxproc) {
162 		tablefull("proc");
163 		return (EAGAIN);
164 	}
165 
166 #if !defined(UVM)
167 	if (flags & FORK_SHAREVM)
168 		return (EINVAL);
169 #endif
170 
171 	/*
172 	 * Increment the count of procs running with this uid. Don't allow
173 	 * a nonprivileged user to exceed their current limit.
174 	 */
175 	count = chgproccnt(uid, 1);
176 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
177 		(void)chgproccnt(uid, -1);
178 		return (EAGAIN);
179 	}
180 
181 	/*
182 	 * Allocate a pcb and kernel stack for the process
183 	 */
184 #if defined(arc) || defined(mips_cachealias)
185 	uaddr = kmem_alloc_upage(kernel_map, USPACE);
186 #else
187 #if defined(UVM)
188 	uaddr = uvm_km_valloc(kernel_map, USPACE);
189 #else
190 	uaddr = kmem_alloc_pageable(kernel_map, USPACE);
191 #endif
192 #endif
193 	if (uaddr == 0)
194 		return ENOMEM;
195 
196 	/* Allocate new proc. */
197 	MALLOC(newproc, struct proc *, sizeof(struct proc), M_PROC, M_WAITOK);
198 
199 	lastpid++;
200 	if (randompid)
201 		lastpid = PID_MAX;
202 retry:
203 	/*
204 	 * If the process ID prototype has wrapped around,
205 	 * restart somewhat above 0, as the low-numbered procs
206 	 * tend to include daemons that don't exit.
207 	 */
208 	if (lastpid >= PID_MAX) {
209 		lastpid = arc4random() % PID_MAX;
210 		pidchecked = 0;
211 	}
212 	if (lastpid >= pidchecked) {
213 		int doingzomb = 0;
214 
215 		pidchecked = PID_MAX;
216 		/*
217 		 * Scan the active and zombie procs to check whether this pid
218 		 * is in use.  Remember the lowest pid that's greater
219 		 * than lastpid, so we can avoid checking for a while.
220 		 */
221 		p2 = LIST_FIRST(&allproc);
222 again:
223 		for (; p2 != 0; p2 = LIST_NEXT(p2, p_list)) {
224 			while (p2->p_pid == lastpid ||
225 			    p2->p_pgrp->pg_id == lastpid) {
226 				lastpid++;
227 				if (lastpid >= pidchecked)
228 					goto retry;
229 			}
230 			if (p2->p_pid > lastpid && pidchecked > p2->p_pid)
231 				pidchecked = p2->p_pid;
232 			if (p2->p_pgrp->pg_id > lastpid &&
233 			    pidchecked > p2->p_pgrp->pg_id)
234 				pidchecked = p2->p_pgrp->pg_id;
235 		}
236 		if (!doingzomb) {
237 			doingzomb = 1;
238 			p2 = LIST_FIRST(&zombproc);
239 			goto again;
240 		}
241 	}
242 
243 	nprocs++;
244 	p2 = newproc;
245 	p2->p_stat = SIDL;			/* protect against others */
246 	p2->p_pid = lastpid;
247 	LIST_INSERT_HEAD(&allproc, p2, p_list);
248 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
249 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
250 
251 	/*
252 	 * Make a proc table entry for the new process.
253 	 * Start by zeroing the section of proc that is zero-initialized,
254 	 * then copy the section that is copied directly from the parent.
255 	 */
256 	bzero(&p2->p_startzero,
257 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
258 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
259 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
260 
261 	/*
262 	 * Initialize the timeouts.
263 	 */
264 	timeout_set(&p2->p_sleep_to, endtsleep, p2);
265 	timeout_set(&p2->p_realit_to, realitexpire, p2);
266 
267 	/*
268 	 * Duplicate sub-structures as needed.
269 	 * Increase reference counts on shared objects.
270 	 * The p_stats and p_sigacts substructs are set in vm_fork.
271 	 */
272 	p2->p_flag = P_INMEM;
273 	p2->p_emul = p1->p_emul;
274 	if (p1->p_flag & P_PROFIL)
275 		startprofclock(p2);
276 	p2->p_flag |= (p1->p_flag & (P_SUGID | P_SUGIDEXEC));
277 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
278 	    M_SUBPROC, M_WAITOK);
279 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
280 	p2->p_cred->p_refcnt = 1;
281 	crhold(p1->p_ucred);
282 
283 	/* bump references to the text vnode (for procfs) */
284 	p2->p_textvp = p1->p_textvp;
285 	if (p2->p_textvp)
286 		VREF(p2->p_textvp);
287 
288 	if (flags & FORK_CLEANFILES)
289 		p2->p_fd = fdinit(p1);
290 	else if (flags & FORK_SHAREFILES)
291 		p2->p_fd = fdshare(p1);
292 	else
293 		p2->p_fd = fdcopy(p1);
294 
295 	/*
296 	 * If p_limit is still copy-on-write, bump refcnt,
297 	 * otherwise get a copy that won't be modified.
298 	 * (If PL_SHAREMOD is clear, the structure is shared
299 	 * copy-on-write.)
300 	 */
301 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
302 		p2->p_limit = limcopy(p1->p_limit);
303 	else {
304 		p2->p_limit = p1->p_limit;
305 		p2->p_limit->p_refcnt++;
306 	}
307 
308 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
309 		p2->p_flag |= P_CONTROLT;
310 	if (flags & FORK_PPWAIT)
311 		p2->p_flag |= P_PPWAIT;
312 	LIST_INSERT_AFTER(p1, p2, p_pglist);
313 	p2->p_pptr = p1;
314 	if (flags & FORK_NOZOMBIE)
315 		p2->p_flag |= P_NOZOMBIE;
316 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
317 	LIST_INIT(&p2->p_children);
318 
319 #ifdef KTRACE
320 	/*
321 	 * Copy traceflag and tracefile if enabled.
322 	 * If not inherited, these were zeroed above.
323 	 */
324 	if (p1->p_traceflag & KTRFAC_INHERIT) {
325 		p2->p_traceflag = p1->p_traceflag;
326 		if ((p2->p_tracep = p1->p_tracep) != NULL)
327 			VREF(p2->p_tracep);
328 	}
329 #endif
330 
331 	/*
332 	 * set priority of child to be that of parent
333 	 * XXX should move p_estcpu into the region of struct proc which gets
334 	 * copied.
335 	 */
336 	scheduler_fork_hook(p1, p2);
337 
338 	/*
339 	 * This begins the section where we must prevent the parent
340 	 * from being swapped.
341 	 */
342 	PHOLD(p1);
343 
344 #if defined(UVM)
345 	if (flags & FORK_VMNOSTACK) {
346 		/* share as much address space as possible */
347 		(void) uvm_map_inherit(&p1->p_vmspace->vm_map,
348 		    VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS - MAXSSIZ,
349 		    VM_INHERIT_SHARE);
350 	}
351 #else
352 	if (flags & FORK_VMNOSTACK) {
353 		/* share as much address space as possible */
354 		(void) vm_map_inherit(&p1->p_vmspace->vm_map,
355 		    VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS - MAXSSIZ,
356 		    VM_INHERIT_SHARE);
357 	}
358 #endif
359 
360 	p2->p_addr = (struct user *)uaddr;
361 
362 #ifdef __FORK_BRAINDAMAGE
363 	/*
364 	 * Set return values for child before vm_fork,
365 	 * so they can be copied to child stack.
366 	 * We return 0, rather than the traditional behaviour of modifying the
367 	 * return value in the system call stub.
368 	 * NOTE: the kernel stack may be at a different location in the child
369 	 * process, and thus addresses of automatic variables (including retval)
370 	 * may be invalid after vm_fork returns in the child process.
371 	 */
372 	retval[0] = 0;
373 	retval[1] = 1;
374 	if (vm_fork(p1, p2, stack, stacksize))
375 		return (0);
376 #else
377 	/*
378 	 * Finish creating the child process.  It will return through a
379 	 * different path later.
380 	 */
381 #if defined(UVM)
382 	uvm_fork(p1, p2, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack,
383 		 stacksize);
384 #else /* UVM */
385 	vm_fork(p1, p2, stack, stacksize);
386 #endif /* UVM */
387 #endif
388 	vm = p2->p_vmspace;
389 
390 	if (flags & FORK_FORK) {
391 		forkstat.cntfork++;
392 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
393 	} else if (flags & FORK_VFORK) {
394 		forkstat.cntvfork++;
395 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
396 	} else if (flags & FORK_RFORK) {
397 		forkstat.cntrfork++;
398 		forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize;
399 	} else {
400 		forkstat.cntkthread++;
401 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
402 	}
403 
404 	/*
405 	 * Make child runnable, set start time, and add to run queue.
406 	 */
407 	(void) splstatclock();
408 	p2->p_stats->p_start = time;
409 	p2->p_acflag = AFORK;
410 	p2->p_stat = SRUN;
411 	setrunqueue(p2);
412 	(void) spl0();
413 
414 	/*
415 	 * Now can be swapped.
416 	 */
417 	PRELE(p1);
418 
419 #if defined(UVM)
420 	uvmexp.forks++;
421 	if (flags & FORK_PPWAIT)
422 		uvmexp.forks_ppwait++;
423 	if (flags & FORK_SHAREVM)
424 		uvmexp.forks_sharevm++;
425 #endif
426 
427 	/*
428 	 * tell any interested parties about the new process
429 	 */
430 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
431 
432 	/*
433 	 * Preserve synchronization semantics of vfork.  If waiting for
434 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
435 	 * proc (in case of exit).
436 	 */
437 	if (flags & FORK_PPWAIT)
438 		while (p2->p_flag & P_PPWAIT)
439 			tsleep(p1, PWAIT, "ppwait", 0);
440 
441 	/*
442 	 * Return child pid to parent process,
443 	 * marking us as parent via retval[1].
444 	 */
445 	retval[0] = p2->p_pid;
446 	retval[1] = 0;
447 	return (0);
448 }
449 
450