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