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