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