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