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