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