xref: /openbsd-src/sys/kern/kern_fork.c (revision b866a8e96c715c31ae90169e6776b208f97d80cd)
1 /*	$OpenBSD: kern_fork.c,v 1.6 1996/09/02 01:22:05 tholo 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 pid_t	lastpid;
64 
65 #define	ISFORK	0
66 #define	ISVFORK	1
67 #define	ISRFORK	2
68 
69 int fork1 __P((struct proc *, int, int, register_t *));
70 
71 /*ARGSUSED*/
72 int
73 sys_fork(p, v, retval)
74 	struct proc *p;
75 	void *v;
76 	register_t *retval;
77 {
78 	return (fork1(p, ISFORK, 0, retval));
79 }
80 
81 /*ARGSUSED*/
82 int
83 sys_vfork(p, v, retval)
84 	struct proc *p;
85 	void *v;
86 	register_t *retval;
87 {
88 	return (fork1(p, ISVFORK, 0, retval));
89 }
90 
91 int
92 sys_rfork(p, v, retval)
93 	struct proc *p;
94 	void *v;
95 	register_t *retval;
96 {
97 	struct sys_rfork_args /* {
98 		syscallarg(int) flags;
99 	} */ *uap = v;
100 
101 	return (fork1(p, ISRFORK, SCARG(uap, flags), retval));
102 }
103 
104 int
105 fork1(p1, forktype, rforkflags, retval)
106 	register struct proc *p1;
107 	int forktype;
108 	int rforkflags;
109 	register_t *retval;
110 {
111 	register struct proc *p2;
112 	register uid_t uid;
113 	struct proc *newproc;
114 	int count;
115 	static int pidchecked = 0;
116 	int dupfd = 1, cleanfd = 0;
117 
118 	if (forktype == ISRFORK) {
119 		dupfd = 0;
120 		if ((rforkflags & RFPROC) == 0)
121 			return (EINVAL);
122 		if ((rforkflags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
123 			return (EINVAL);
124 		if (rforkflags & RFFDG)
125 			dupfd = 1;
126 		if (rforkflags & RFNOWAIT)
127 			return (EINVAL);	/* XXX unimplimented */
128 		if (rforkflags & RFCFDG)
129 			cleanfd = 1;
130 	}
131 
132 	/*
133 	 * Although process entries are dynamically created, we still keep
134 	 * a global limit on the maximum number we will create.  Don't allow
135 	 * a nonprivileged user to use the last process; don't let root
136 	 * exceed the limit. The variable nprocs is the current number of
137 	 * processes, maxproc is the limit.
138 	 */
139 	uid = p1->p_cred->p_ruid;
140 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
141 		tablefull("proc");
142 		return (EAGAIN);
143 	}
144 
145 	/*
146 	 * Increment the count of procs running with this uid. Don't allow
147 	 * a nonprivileged user to exceed their current limit.
148 	 */
149 	count = chgproccnt(uid, 1);
150 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
151 		(void)chgproccnt(uid, -1);
152 		return (EAGAIN);
153 	}
154 
155 	/* Allocate new proc. */
156 	MALLOC(newproc, struct proc *, sizeof(struct proc), M_PROC, M_WAITOK);
157 
158 	/*
159 	 * Find an unused process ID.  We remember a range of unused IDs
160 	 * ready to use (from lastpid+1 through pidchecked-1).
161 	 */
162 	lastpid++;
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 = 100;
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 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
232 	    M_SUBPROC, M_WAITOK);
233 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
234 	p2->p_cred->p_refcnt = 1;
235 	crhold(p1->p_ucred);
236 
237 	/* bump references to the text vnode (for procfs) */
238 	p2->p_textvp = p1->p_textvp;
239 	if (p2->p_textvp)
240 		VREF(p2->p_textvp);
241 
242 	if (cleanfd)
243 		p2->p_fd = fdinit(p1);
244 	else if (dupfd)
245 		p2->p_fd = fdcopy(p1);
246 	else
247 		p2->p_fd = fdshare(p1);
248 
249 	/*
250 	 * If p_limit is still copy-on-write, bump refcnt,
251 	 * otherwise get a copy that won't be modified.
252 	 * (If PL_SHAREMOD is clear, the structure is shared
253 	 * copy-on-write.)
254 	 */
255 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
256 		p2->p_limit = limcopy(p1->p_limit);
257 	else {
258 		p2->p_limit = p1->p_limit;
259 		p2->p_limit->p_refcnt++;
260 	}
261 
262 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
263 		p2->p_flag |= P_CONTROLT;
264 	if (forktype == ISVFORK)
265 		p2->p_flag |= P_PPWAIT;
266 	LIST_INSERT_AFTER(p1, p2, p_pglist);
267 	p2->p_pptr = p1;
268 	if (rforkflags & RFNOWAIT) {
269 		/* XXX should we do anything? */
270 	} else {
271 		LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
272 	}
273 	LIST_INIT(&p2->p_children);
274 
275 #ifdef KTRACE
276 	/*
277 	 * Copy traceflag and tracefile if enabled.
278 	 * If not inherited, these were zeroed above.
279 	 */
280 	if (p1->p_traceflag&KTRFAC_INHERIT) {
281 		p2->p_traceflag = p1->p_traceflag;
282 		if ((p2->p_tracep = p1->p_tracep) != NULL)
283 			VREF(p2->p_tracep);
284 	}
285 #endif
286 
287 	/*
288 	 * This begins the section where we must prevent the parent
289 	 * from being swapped.
290 	 */
291 	p1->p_holdcnt++;
292 
293 	if (forktype == ISRFORK && (rforkflags & RFMEM)) {
294 		/* share as much address space as possible */
295 		(void) vm_map_inherit(&p1->p_vmspace->vm_map,
296 		    VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS - MAXSSIZ,
297 		    VM_INHERIT_SHARE);
298 	}
299 
300 #ifdef __FORK_BRAINDAMAGE
301 	/*
302 	 * Set return values for child before vm_fork,
303 	 * so they can be copied to child stack.
304 	 * We return 0, rather than the traditional behaviour of modifying the
305 	 * return value in the system call stub.
306 	 * NOTE: the kernel stack may be at a different location in the child
307 	 * process, and thus addresses of automatic variables (including retval)
308 	 * may be invalid after vm_fork returns in the child process.
309 	 */
310 	retval[0] = 0;
311 	retval[1] = 1;
312 	if (vm_fork(p1, p2))
313 		return (0);
314 #else
315 	/*
316 	 * Finish creating the child process.  It will return through a
317 	 * different path later.
318 	 */
319 	vm_fork(p1, p2);
320 #endif
321 
322 	switch (forktype) {
323 		case ISFORK:
324 			forkstat.cntfork++;
325 			break;
326 		case ISVFORK:
327 			forkstat.cntvfork++;
328 			break;
329 		case ISRFORK:
330 			forkstat.cntrfork++;
331 			break;
332 	}
333 
334 	/*
335 	 * Make child runnable, set start time, and add to run queue.
336 	 */
337 	(void) splstatclock();
338 	p2->p_stats->p_start = time;
339 	p2->p_acflag = AFORK;
340 	p2->p_stat = SRUN;
341 	setrunqueue(p2);
342 	(void) spl0();
343 
344 	/*
345 	 * Now can be swapped.
346 	 */
347 	p1->p_holdcnt--;
348 
349 	/*
350 	 * Preserve synchronization semantics of vfork.  If waiting for
351 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
352 	 * proc (in case of exit).
353 	 */
354 	if (forktype == ISVFORK)
355 		while (p2->p_flag & P_PPWAIT)
356 			tsleep(p1, PWAIT, "ppwait", 0);
357 
358 	/*
359 	 * Return child pid to parent process,
360 	 * marking us as parent via retval[1].
361 	 */
362 	retval[0] = p2->p_pid;
363 	retval[1] = 0;
364 	return (0);
365 }
366