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