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