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