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