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