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