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