xref: /openbsd-src/sys/kern/kern_fork.c (revision 8ef75ebff9897f37770a8c9470785199e7dcc7fd)
1 /*	$OpenBSD: kern_fork.c,v 1.43 2001/09/19 20:50:58 mickey 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/signalvar.h>
54 #include <sys/vnode.h>
55 #include <sys/file.h>
56 #include <sys/acct.h>
57 #include <sys/ktrace.h>
58 #include <sys/sched.h>
59 #include <dev/rndvar.h>
60 #include <sys/pool.h>
61 
62 #include <sys/syscallargs.h>
63 
64 #include <vm/vm.h>
65 #include <uvm/uvm_extern.h>
66 #include <uvm/uvm_map.h>
67 
68 int	nprocs = 1;		/* process 0 */
69 int	randompid;		/* when set to 1, pid's go random */
70 pid_t	lastpid;
71 struct	forkstat forkstat;
72 
73 
74 /*ARGSUSED*/
75 int
76 sys_fork(p, v, retval)
77 	struct proc *p;
78 	void *v;
79 	register_t *retval;
80 {
81 	return (fork1(p, SIGCHLD, FORK_FORK, NULL, 0, retval));
82 }
83 
84 /*ARGSUSED*/
85 int
86 sys_vfork(p, v, retval)
87 	struct proc *p;
88 	void *v;
89 	register_t *retval;
90 {
91 	return (fork1(p, SIGCHLD, FORK_VFORK|FORK_PPWAIT, NULL, 0, retval));
92 }
93 
94 int
95 sys_rfork(p, v, retval)
96 	struct proc *p;
97 	void *v;
98 	register_t *retval;
99 {
100 	struct sys_rfork_args /* {
101 		syscallarg(int) flags;
102 	} */ *uap = v;
103 
104 	int rforkflags;
105 	int flags;
106 
107 	flags = FORK_RFORK;
108 	rforkflags = SCARG(uap, flags);
109 
110 	if ((rforkflags & RFPROC) == 0)
111 		return (EINVAL);
112 
113 	switch(rforkflags & (RFFDG|RFCFDG)) {
114 	case (RFFDG|RFCFDG):
115 		return EINVAL;
116 	case RFCFDG:
117 		flags |= FORK_CLEANFILES;
118 		break;
119 	case RFFDG:
120 		break;
121 	default:
122 		flags |= FORK_SHAREFILES;
123 		break;
124 	}
125 
126 	if (rforkflags & RFNOWAIT)
127 		flags |= FORK_NOZOMBIE;
128 
129 	if (rforkflags & RFMEM)
130 		flags |= FORK_VMNOSTACK;
131 
132 	return (fork1(p, SIGCHLD, flags, NULL, 0, retval));
133 }
134 
135 int
136 fork1(p1, exitsig, flags, stack, stacksize, retval)
137 	register struct proc *p1;
138 	int exitsig;
139 	int flags;
140 	void *stack;
141 	size_t stacksize;
142 	register_t *retval;
143 {
144 	struct proc *p2;
145 	uid_t uid;
146 	struct proc *newproc;
147 	struct vmspace *vm;
148 	int count;
149 	static int pidchecked = 0;
150 	vaddr_t uaddr;
151 	int s;
152 	extern void endtsleep __P((void *));
153 	extern void realitexpire __P((void *));
154 
155 	/*
156 	 * Although process entries are dynamically created, we still keep
157 	 * a global limit on the maximum number we will create. We reserve
158 	 * the last 5 processes to root. The variable nprocs is the current
159 	 * number of processes, maxproc is the limit.
160 	 */
161 	uid = p1->p_cred->p_ruid;
162 	if ((nprocs >= maxproc - 5 && uid != 0) || nprocs >= maxproc) {
163 		tablefull("proc");
164 		return (EAGAIN);
165 	}
166 
167 	/*
168 	 * Increment the count of procs running with this uid. Don't allow
169 	 * a nonprivileged user to exceed their current limit.
170 	 */
171 	count = chgproccnt(uid, 1);
172 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
173 		(void)chgproccnt(uid, -1);
174 		return (EAGAIN);
175 	}
176 
177 	/*
178 	 * Allocate a pcb and kernel stack for the process
179 	 */
180 	uaddr = uvm_km_valloc(kernel_map, USPACE);
181 	if (uaddr == 0)
182 		return ENOMEM;
183 
184 	/* Allocate new proc. */
185 	newproc = pool_get(&proc_pool, PR_WAITOK);
186 
187 	lastpid++;
188 	if (randompid)
189 		lastpid = PID_MAX;
190 retry:
191 	/*
192 	 * If the process ID prototype has wrapped around,
193 	 * restart somewhat above 0, as the low-numbered procs
194 	 * tend to include daemons that don't exit.
195 	 */
196 	if (lastpid >= PID_MAX) {
197 		lastpid = arc4random() % PID_MAX;
198 		pidchecked = 0;
199 	}
200 	if (lastpid >= pidchecked) {
201 		int doingzomb = 0;
202 
203 		pidchecked = PID_MAX;
204 		/*
205 		 * Scan the active and zombie procs to check whether this pid
206 		 * is in use.  Remember the lowest pid that's greater
207 		 * than lastpid, so we can avoid checking for a while.
208 		 */
209 		p2 = LIST_FIRST(&allproc);
210 again:
211 		for (; p2 != 0; p2 = LIST_NEXT(p2, p_list)) {
212 			while (p2->p_pid == lastpid ||
213 			    p2->p_pgrp->pg_id == lastpid) {
214 				lastpid++;
215 				if (lastpid >= pidchecked)
216 					goto retry;
217 			}
218 			if (p2->p_pid > lastpid && pidchecked > p2->p_pid)
219 				pidchecked = p2->p_pid;
220 			if (p2->p_pgrp->pg_id > lastpid &&
221 			    pidchecked > p2->p_pgrp->pg_id)
222 				pidchecked = p2->p_pgrp->pg_id;
223 		}
224 		if (!doingzomb) {
225 			doingzomb = 1;
226 			p2 = LIST_FIRST(&zombproc);
227 			goto again;
228 		}
229 	}
230 
231 	nprocs++;
232 	p2 = newproc;
233 	p2->p_stat = SIDL;			/* protect against others */
234 	p2->p_pid = lastpid;
235 	p2->p_exitsig = exitsig;
236 	LIST_INSERT_HEAD(&allproc, p2, p_list);
237 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
238 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
239 
240 	/*
241 	 * Make a proc table entry for the new process.
242 	 * Start by zeroing the section of proc that is zero-initialized,
243 	 * then copy the section that is copied directly from the parent.
244 	 */
245 	bzero(&p2->p_startzero,
246 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
247 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
248 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
249 
250 	/*
251 	 * Initialize the timeouts.
252 	 */
253 	timeout_set(&p2->p_sleep_to, endtsleep, p2);
254 	timeout_set(&p2->p_realit_to, realitexpire, p2);
255 
256 	/*
257 	 * Duplicate sub-structures as needed.
258 	 * Increase reference counts on shared objects.
259 	 * The p_stats and p_sigacts substructs are set in vm_fork.
260 	 */
261 	p2->p_flag = P_INMEM;
262 	p2->p_emul = p1->p_emul;
263 	if (p1->p_flag & P_PROFIL)
264 		startprofclock(p2);
265 	p2->p_flag |= (p1->p_flag & (P_SUGID | P_SUGIDEXEC));
266 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
267 	    M_SUBPROC, M_WAITOK);
268 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
269 	p2->p_cred->p_refcnt = 1;
270 	crhold(p1->p_ucred);
271 
272 	/* bump references to the text vnode (for procfs) */
273 	p2->p_textvp = p1->p_textvp;
274 	if (p2->p_textvp)
275 		VREF(p2->p_textvp);
276 
277 	if (flags & FORK_CLEANFILES)
278 		p2->p_fd = fdinit(p1);
279 	else if (flags & FORK_SHAREFILES)
280 		p2->p_fd = fdshare(p1);
281 	else
282 		p2->p_fd = fdcopy(p1);
283 
284 	/*
285 	 * If p_limit is still copy-on-write, bump refcnt,
286 	 * otherwise get a copy that won't be modified.
287 	 * (If PL_SHAREMOD is clear, the structure is shared
288 	 * copy-on-write.)
289 	 */
290 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
291 		p2->p_limit = limcopy(p1->p_limit);
292 	else {
293 		p2->p_limit = p1->p_limit;
294 		p2->p_limit->p_refcnt++;
295 	}
296 
297 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
298 		p2->p_flag |= P_CONTROLT;
299 	if (flags & FORK_PPWAIT)
300 		p2->p_flag |= P_PPWAIT;
301 	LIST_INSERT_AFTER(p1, p2, p_pglist);
302 	p2->p_pptr = p1;
303 	if (flags & FORK_NOZOMBIE)
304 		p2->p_flag |= P_NOZOMBIE;
305 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
306 	LIST_INIT(&p2->p_children);
307 
308 #ifdef KTRACE
309 	/*
310 	 * Copy traceflag and tracefile if enabled.
311 	 * If not inherited, these were zeroed above.
312 	 */
313 	if (p1->p_traceflag & KTRFAC_INHERIT) {
314 		p2->p_traceflag = p1->p_traceflag;
315 		if ((p2->p_tracep = p1->p_tracep) != NULL)
316 			VREF(p2->p_tracep);
317 	}
318 #endif
319 
320 	/*
321 	 * set priority of child to be that of parent
322 	 * XXX should move p_estcpu into the region of struct proc which gets
323 	 * copied.
324 	 */
325 	scheduler_fork_hook(p1, p2);
326 
327 	/*
328 	 * Create signal actions for the child process.
329 	 */
330 	if (flags & FORK_SIGHAND)
331 		sigactsshare(p1, p2);
332 	else
333 		p2->p_sigacts = sigactsinit(p1);
334 
335 	/*
336 	 * This begins the section where we must prevent the parent
337 	 * from being swapped.
338 	 */
339 	PHOLD(p1);
340 
341 	if (flags & FORK_VMNOSTACK) {
342 		/* share as much address space as possible */
343 		(void) uvm_map_inherit(&p1->p_vmspace->vm_map,
344 		    VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS - MAXSSIZ,
345 		    VM_INHERIT_SHARE);
346 	}
347 
348 	p2->p_addr = (struct user *)uaddr;
349 
350 	/*
351 	 * Finish creating the child process.  It will return through a
352 	 * different path later.
353 	 */
354 	uvm_fork(p1, p2, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack,
355 	    stacksize);
356 
357 	vm = p2->p_vmspace;
358 
359 	if (flags & FORK_FORK) {
360 		forkstat.cntfork++;
361 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
362 	} else if (flags & FORK_VFORK) {
363 		forkstat.cntvfork++;
364 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
365 	} else if (flags & FORK_RFORK) {
366 		forkstat.cntrfork++;
367 		forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize;
368 	} else {
369 		forkstat.cntkthread++;
370 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
371 	}
372 
373 	/*
374 	 * Make child runnable, set start time, and add to run queue.
375 	 */
376 	s = splstatclock();
377 	p2->p_stats->p_start = time;
378 	p2->p_acflag = AFORK;
379 	p2->p_stat = SRUN;
380 	setrunqueue(p2);
381 	splx(s);
382 
383 	/*
384 	 * Now can be swapped.
385 	 */
386 	PRELE(p1);
387 
388 	uvmexp.forks++;
389 	if (flags & FORK_PPWAIT)
390 		uvmexp.forks_ppwait++;
391 	if (flags & FORK_SHAREVM)
392 		uvmexp.forks_sharevm++;
393 
394 	/*
395 	 * tell any interested parties about the new process
396 	 */
397 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
398 
399 	/*
400 	 * Preserve synchronization semantics of vfork.  If waiting for
401 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
402 	 * proc (in case of exit).
403 	 */
404 	if (flags & FORK_PPWAIT)
405 		while (p2->p_flag & P_PPWAIT)
406 			tsleep(p1, PWAIT, "ppwait", 0);
407 
408 	/*
409 	 * Return child pid to parent process,
410 	 * marking us as parent via retval[1].
411 	 */
412 	retval[0] = p2->p_pid;
413 	retval[1] = 0;
414 	return (0);
415 }
416 
417