xref: /openbsd-src/sys/kern/kern_fork.c (revision 5bc652b1fc0fb53fbffea9975a1786d7967bb900)
1 /*	$OpenBSD: kern_fork.c,v 1.76 2005/05/29 03:20:41 deraadt 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. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/filedesc.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/mount.h>
46 #include <sys/proc.h>
47 #include <sys/exec.h>
48 #include <sys/resourcevar.h>
49 #include <sys/signalvar.h>
50 #include <sys/vnode.h>
51 #include <sys/file.h>
52 #include <sys/acct.h>
53 #include <sys/ktrace.h>
54 #include <sys/sched.h>
55 #include <dev/rndvar.h>
56 #include <sys/pool.h>
57 #include <sys/mman.h>
58 
59 #include <sys/syscallargs.h>
60 
61 #include "systrace.h"
62 #include <dev/systrace.h>
63 
64 #include <uvm/uvm_extern.h>
65 #include <uvm/uvm_map.h>
66 
67 int	nprocs = 1;		/* process 0 */
68 int	randompid;		/* when set to 1, pid's go random */
69 pid_t	lastpid;
70 struct	forkstat forkstat;
71 
72 int pidtaken(pid_t);
73 
74 /*ARGSUSED*/
75 int
76 sys_fork(struct proc *p, void *v, register_t *retval)
77 {
78 	return (fork1(p, SIGCHLD, FORK_FORK, NULL, 0, NULL,
79 	    NULL, retval, NULL));
80 }
81 
82 /*ARGSUSED*/
83 int
84 sys_vfork(struct proc *p, void *v, register_t *retval)
85 {
86 	return (fork1(p, SIGCHLD, FORK_VFORK|FORK_PPWAIT, NULL, 0, NULL,
87 	    NULL, retval, NULL));
88 }
89 
90 int
91 sys_rfork(struct proc *p, void *v, register_t *retval)
92 {
93 	struct sys_rfork_args /* {
94 		syscallarg(int) flags;
95 	} */ *uap = v;
96 
97 	int rforkflags;
98 	int flags;
99 
100 	flags = FORK_RFORK;
101 	rforkflags = SCARG(uap, flags);
102 
103 	if ((rforkflags & RFPROC) == 0)
104 		return (EINVAL);
105 
106 	switch(rforkflags & (RFFDG|RFCFDG)) {
107 	case (RFFDG|RFCFDG):
108 		return EINVAL;
109 	case RFCFDG:
110 		flags |= FORK_CLEANFILES;
111 		break;
112 	case RFFDG:
113 		break;
114 	default:
115 		flags |= FORK_SHAREFILES;
116 		break;
117 	}
118 
119 	if (rforkflags & RFNOWAIT)
120 		flags |= FORK_NOZOMBIE;
121 
122 	if (rforkflags & RFMEM)
123 		flags |= FORK_SHAREVM;
124 
125 	return (fork1(p, SIGCHLD, flags, NULL, 0, NULL, NULL, retval, NULL));
126 }
127 
128 /* print the 'table full' message once per 10 seconds */
129 struct timeval fork_tfmrate = { 10, 0 };
130 
131 int
132 fork1(struct proc *p1, int exitsig, int flags, void *stack, size_t stacksize,
133     void (*func)(void *), void *arg, register_t *retval,
134     struct proc **rnewprocp)
135 {
136 	struct proc *p2;
137 	uid_t uid;
138 	struct vmspace *vm;
139 	int count;
140 	vaddr_t uaddr;
141 	int s;
142 	extern void endtsleep(void *);
143 	extern void realitexpire(void *);
144 
145 	/*
146 	 * Although process entries are dynamically created, we still keep
147 	 * a global limit on the maximum number we will create. We reserve
148 	 * the last 5 processes to root. The variable nprocs is the current
149 	 * number of processes, maxproc is the limit.
150 	 */
151 	uid = p1->p_cred->p_ruid;
152 	if ((nprocs >= maxproc - 5 && uid != 0) || nprocs >= maxproc) {
153 		static struct timeval lasttfm;
154 
155 		if (ratecheck(&lasttfm, &fork_tfmrate))
156 			tablefull("proc");
157 		return (EAGAIN);
158 	}
159 	nprocs++;
160 
161 	/*
162 	 * Increment the count of procs running with this uid. Don't allow
163 	 * a nonprivileged user to exceed their current limit.
164 	 */
165 	count = chgproccnt(uid, 1);
166 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
167 		(void)chgproccnt(uid, -1);
168 		nprocs--;
169 		return (EAGAIN);
170 	}
171 
172 	/*
173 	 * Allocate a pcb and kernel stack for the process
174 	 */
175 	uaddr = uvm_km_valloc_align(kernel_map, USPACE, USPACE_ALIGN);
176 	if (uaddr == 0) {
177 		chgproccnt(uid, -1);
178 		nprocs--;
179 		return (ENOMEM);
180 	}
181 
182 	/*
183 	 * From now on, we're committed to the fork and cannot fail.
184 	 */
185 
186 	/* Allocate new proc. */
187 	p2 = pool_get(&proc_pool, PR_WAITOK);
188 
189 	p2->p_stat = SIDL;			/* protect against others */
190 	p2->p_exitsig = exitsig;
191 	p2->p_forw = p2->p_back = NULL;
192 
193 	/*
194 	 * Make a proc table entry for the new process.
195 	 * Start by zeroing the section of proc that is zero-initialized,
196 	 * then copy the section that is copied directly from the parent.
197 	 */
198 	bzero(&p2->p_startzero,
199 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
200 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
201 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
202 
203 	/*
204 	 * Initialize the timeouts.
205 	 */
206 	timeout_set(&p2->p_sleep_to, endtsleep, p2);
207 	timeout_set(&p2->p_realit_to, realitexpire, p2);
208 
209 #if defined(__HAVE_CPUINFO)
210 	p2->p_cpu = p1->p_cpu;
211 #endif
212 
213 	/*
214 	 * Duplicate sub-structures as needed.
215 	 * Increase reference counts on shared objects.
216 	 * The p_stats and p_sigacts substructs are set in vm_fork.
217 	 */
218 	p2->p_flag = P_INMEM;
219 	p2->p_emul = p1->p_emul;
220 	if (p1->p_flag & P_PROFIL)
221 		startprofclock(p2);
222 	p2->p_flag |= (p1->p_flag & (P_SUGID | P_SUGIDEXEC));
223 	p2->p_cred = pool_get(&pcred_pool, PR_WAITOK);
224 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
225 	p2->p_cred->p_refcnt = 1;
226 	crhold(p1->p_ucred);
227 
228 	/* bump references to the text vnode (for procfs) */
229 	p2->p_textvp = p1->p_textvp;
230 	if (p2->p_textvp)
231 		VREF(p2->p_textvp);
232 
233 	if (flags & FORK_CLEANFILES)
234 		p2->p_fd = fdinit(p1);
235 	else if (flags & FORK_SHAREFILES)
236 		p2->p_fd = fdshare(p1);
237 	else
238 		p2->p_fd = fdcopy(p1);
239 
240 	/*
241 	 * If p_limit is still copy-on-write, bump refcnt,
242 	 * otherwise get a copy that won't be modified.
243 	 * (If PL_SHAREMOD is clear, the structure is shared
244 	 * copy-on-write.)
245 	 */
246 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
247 		p2->p_limit = limcopy(p1->p_limit);
248 	else {
249 		p2->p_limit = p1->p_limit;
250 		p2->p_limit->p_refcnt++;
251 	}
252 
253 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
254 		p2->p_flag |= P_CONTROLT;
255 	if (flags & FORK_PPWAIT)
256 		p2->p_flag |= P_PPWAIT;
257 	LIST_INSERT_AFTER(p1, p2, p_pglist);
258 	p2->p_pptr = p1;
259 	if (flags & FORK_NOZOMBIE)
260 		p2->p_flag |= P_NOZOMBIE;
261 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
262 	LIST_INIT(&p2->p_children);
263 
264 #ifdef KTRACE
265 	/*
266 	 * Copy traceflag and tracefile if enabled.
267 	 * If not inherited, these were zeroed above.
268 	 */
269 	if (p1->p_traceflag & KTRFAC_INHERIT) {
270 		p2->p_traceflag = p1->p_traceflag;
271 		if ((p2->p_tracep = p1->p_tracep) != NULL)
272 			VREF(p2->p_tracep);
273 	}
274 #endif
275 
276 	/*
277 	 * set priority of child to be that of parent
278 	 * XXX should move p_estcpu into the region of struct proc which gets
279 	 * copied.
280 	 */
281 	scheduler_fork_hook(p1, p2);
282 
283 	/*
284 	 * Create signal actions for the child process.
285 	 */
286 	if (flags & FORK_SIGHAND)
287 		sigactsshare(p1, p2);
288 	else
289 		p2->p_sigacts = sigactsinit(p1);
290 
291 	/*
292 	 * If emulation has process fork hook, call it now.
293 	 */
294 	if (p2->p_emul->e_proc_fork)
295 		(*p2->p_emul->e_proc_fork)(p2, p1);
296 	/*
297 	 * This begins the section where we must prevent the parent
298 	 * from being swapped.
299 	 */
300 	PHOLD(p1);
301 
302 	p2->p_addr = (struct user *)uaddr;
303 
304 	/*
305 	 * Finish creating the child process.  It will return through a
306 	 * different path later.
307 	 */
308 	uvm_fork(p1, p2, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack,
309 	    stacksize, func ? func : child_return, arg ? arg : p2);
310 
311 	vm = p2->p_vmspace;
312 
313 	if (flags & FORK_FORK) {
314 		forkstat.cntfork++;
315 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
316 	} else if (flags & FORK_VFORK) {
317 		forkstat.cntvfork++;
318 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
319 	} else if (flags & FORK_RFORK) {
320 		forkstat.cntrfork++;
321 		forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize;
322 	} else {
323 		forkstat.cntkthread++;
324 		forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize;
325 	}
326 
327 	/* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */
328 	do {
329 		lastpid = 1 + (randompid ? arc4random() : lastpid) % PID_MAX;
330 	} while (pidtaken(lastpid));
331 	p2->p_pid = lastpid;
332 
333 	LIST_INSERT_HEAD(&allproc, p2, p_list);
334 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
335 
336 #if NSYSTRACE > 0
337 	if (ISSET(p1->p_flag, P_SYSTRACE))
338 		systrace_fork(p1, p2);
339 #endif
340 
341 	/*
342 	 * Make child runnable, set start time, and add to run queue.
343 	 */
344 	SCHED_LOCK(s);
345  	getmicrotime(&p2->p_stats->p_start);
346 	p2->p_acflag = AFORK;
347 	p2->p_stat = SRUN;
348 	setrunqueue(p2);
349 	SCHED_UNLOCK(s);
350 
351 	timeout_set(&p2->p_stats->p_virt_to, virttimer_trampoline, p2);
352 	timeout_set(&p2->p_stats->p_prof_to, proftimer_trampoline, p2);
353 
354 	/*
355 	 * Now can be swapped.
356 	 */
357 	PRELE(p1);
358 
359 	/*
360 	 * Notify any interested parties about the new process.
361 	 */
362 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
363 
364 	/*
365 	 * Update stats now that we know the fork was successfull.
366 	 */
367 	uvmexp.forks++;
368 	if (flags & FORK_PPWAIT)
369 		uvmexp.forks_ppwait++;
370 	if (flags & FORK_SHAREVM)
371 		uvmexp.forks_sharevm++;
372 
373 	/*
374 	 * Pass a pointer to the new process to the caller.
375 	 */
376 	if (rnewprocp != NULL)
377 		*rnewprocp = p2;
378 
379 	/*
380 	 * Preserve synchronization semantics of vfork.  If waiting for
381 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
382 	 * proc (in case of exit).
383 	 */
384 	if (flags & FORK_PPWAIT)
385 		while (p2->p_flag & P_PPWAIT)
386 			tsleep(p1, PWAIT, "ppwait", 0);
387 
388 	/*
389 	 * Return child pid to parent process,
390 	 * marking us as parent via retval[1].
391 	 */
392 	if (retval != NULL) {
393 		retval[0] = p2->p_pid;
394 		retval[1] = 0;
395 	}
396 	return (0);
397 }
398 
399 /*
400  * Checks for current use of a pid, either as a pid or pgid.
401  */
402 int
403 pidtaken(pid_t pid)
404 {
405 	struct proc *p;
406 
407 	if (pfind(pid) != NULL)
408 		return (1);
409 	if (pgfind(pid) != NULL)
410 		return (1);
411 	LIST_FOREACH(p, &zombproc, p_list)
412 		if (p->p_pid == pid || p->p_pgid == pid)
413 			return (1);
414 	return (0);
415 }
416 
417 #if defined(MULTIPROCESSOR)
418 /*
419  * XXX This is a slight hack to get newly-formed processes to
420  * XXX acquire the kernel lock as soon as they run.
421  */
422 void
423 proc_trampoline_mp(void)
424 {
425 	struct proc *p;
426 
427 	p = curproc;
428 
429 	SCHED_ASSERT_UNLOCKED();
430 	KERNEL_PROC_LOCK(p);
431 }
432 #endif
433