xref: /netbsd-src/sys/kern/kern_fork.c (revision 5aefcfdc06931dd97e76246d2fe0302f7b3fe094)
1 /*	$NetBSD: kern_fork.c,v 1.81 2000/12/22 22:59:00 jdolecek Exp $	*/
2 
3 /*
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *	@(#)kern_fork.c	8.8 (Berkeley) 2/14/95
41  */
42 
43 #include "opt_ktrace.h"
44 #include "opt_multiprocessor.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/map.h>
49 #include <sys/filedesc.h>
50 #include <sys/kernel.h>
51 #include <sys/malloc.h>
52 #include <sys/pool.h>
53 #include <sys/mount.h>
54 #include <sys/proc.h>
55 #include <sys/resourcevar.h>
56 #include <sys/vnode.h>
57 #include <sys/file.h>
58 #include <sys/acct.h>
59 #include <sys/ktrace.h>
60 #include <sys/vmmeter.h>
61 #include <sys/sched.h>
62 #include <sys/signalvar.h>
63 
64 #include <sys/syscallargs.h>
65 
66 #include <uvm/uvm_extern.h>
67 
68 int	nprocs = 1;		/* process 0 */
69 
70 /*ARGSUSED*/
71 int
72 sys_fork(struct proc *p, void *v, register_t *retval)
73 {
74 
75 	return (fork1(p, 0, SIGCHLD, NULL, 0, NULL, NULL, retval, NULL));
76 }
77 
78 /*
79  * vfork(2) system call compatible with 4.4BSD (i.e. BSD with Mach VM).
80  * Address space is not shared, but parent is blocked until child exit.
81  */
82 /*ARGSUSED*/
83 int
84 sys_vfork(struct proc *p, void *v, register_t *retval)
85 {
86 
87 	return (fork1(p, FORK_PPWAIT, SIGCHLD, NULL, 0, NULL, NULL,
88 	    retval, NULL));
89 }
90 
91 /*
92  * New vfork(2) system call for NetBSD, which implements original 3BSD vfork(2)
93  * semantics.  Address space is shared, and parent is blocked until child exit.
94  */
95 /*ARGSUSED*/
96 int
97 sys___vfork14(struct proc *p, void *v, register_t *retval)
98 {
99 
100 	return (fork1(p, FORK_PPWAIT|FORK_SHAREVM, SIGCHLD, NULL, 0,
101 	    NULL, NULL, retval, NULL));
102 }
103 
104 int
105 fork1(struct proc *p1, int flags, int exitsig, void *stack, size_t stacksize,
106     void (*func)(void *), void *arg, register_t *retval,
107     struct proc **rnewprocp)
108 {
109 	struct proc *p2, *tp;
110 	uid_t uid;
111 	int count, s;
112 	vaddr_t uaddr;
113 	static int nextpid, pidchecked = 0;
114 
115 	/*
116 	 * Although process entries are dynamically created, we still keep
117 	 * a global limit on the maximum number we will create.  Don't allow
118 	 * a nonprivileged user to use the last process; don't let root
119 	 * exceed the limit. The variable nprocs is the current number of
120 	 * processes, maxproc is the limit.
121 	 */
122 	uid = p1->p_cred->p_ruid;
123 	if (__predict_false((nprocs >= maxproc - 1 && uid != 0) ||
124 			    nprocs >= maxproc)) {
125 		tablefull("proc", "increase kern.maxproc or NPROC");
126 		return (EAGAIN);
127 	}
128 	nprocs++;
129 
130 	/*
131 	 * Increment the count of procs running with this uid. Don't allow
132 	 * a nonprivileged user to exceed their current limit.
133 	 */
134 	count = chgproccnt(uid, 1);
135 	if (__predict_false(uid != 0 && count >
136 			    p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
137 		(void)chgproccnt(uid, -1);
138 		nprocs--;
139 		return (EAGAIN);
140 	}
141 
142 	/*
143 	 * Allocate virtual address space for the U-area now, while it
144 	 * is still easy to abort the fork operation if we're out of
145 	 * kernel virtual address space.  The actual U-area pages will
146 	 * be allocated and wired in vm_fork().
147 	 */
148 
149 #ifndef USPACE_ALIGN
150 #define USPACE_ALIGN	0
151 #endif
152 
153 	uaddr = uvm_km_valloc_align(kernel_map, USPACE, USPACE_ALIGN);
154 	if (__predict_false(uaddr == 0)) {
155 		(void)chgproccnt(uid, -1);
156 		nprocs--;
157 		return (ENOMEM);
158 	}
159 
160 	/*
161 	 * We are now committed to the fork.  From here on, we may
162 	 * block on resources, but resource allocation may NOT fail.
163 	 */
164 
165 	/* Allocate new proc. */
166 	p2 = pool_get(&proc_pool, PR_WAITOK);
167 
168 	/*
169 	 * Make a proc table entry for the new process.
170 	 * Start by zeroing the section of proc that is zero-initialized,
171 	 * then copy the section that is copied directly from the parent.
172 	 */
173 	memset(&p2->p_startzero, 0,
174 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
175 	memcpy(&p2->p_startcopy, &p1->p_startcopy,
176 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
177 
178 #if !defined(MULTIPROCESSOR)
179 	/*
180 	 * In the single-processor case, all processes will always run
181 	 * on the same CPU.  So, initialize the child's CPU to the parent's
182 	 * now.  In the multiprocessor case, the child's CPU will be
183 	 * initialized in the low-level context switch code when the
184 	 * process runs.
185 	 */
186 	p2->p_cpu = p1->p_cpu;
187 #else
188 	/*
189 	 * zero child's cpu pointer so we don't get trash.
190 	 */
191 	p2->p_cpu = NULL;
192 #endif /* ! MULTIPROCESSOR */
193 
194 	/*
195 	 * Duplicate sub-structures as needed.
196 	 * Increase reference counts on shared objects.
197 	 * The p_stats and p_sigacts substructs are set in uvm_fork().
198 	 */
199 	p2->p_flag = P_INMEM | (p1->p_flag & P_SUGID);
200 	p2->p_emul = p1->p_emul;
201 #ifdef __HAVE_SYSCALL_INTERN
202 	(*p2->p_emul->e_syscall_intern)(p2);
203 #endif
204 	if (p1->p_flag & P_PROFIL)
205 		startprofclock(p2);
206 	p2->p_cred = pool_get(&pcred_pool, PR_WAITOK);
207 	memcpy(p2->p_cred, p1->p_cred, sizeof(*p2->p_cred));
208 	p2->p_cred->p_refcnt = 1;
209 	crhold(p1->p_ucred);
210 
211 	/* bump references to the text vnode (for procfs) */
212 	p2->p_textvp = p1->p_textvp;
213 	if (p2->p_textvp)
214 		VREF(p2->p_textvp);
215 
216 	if (flags & FORK_SHAREFILES)
217 		fdshare(p1, p2);
218 	else
219 		p2->p_fd = fdcopy(p1);
220 
221 	if (flags & FORK_SHARECWD)
222 		cwdshare(p1, p2);
223 	else
224 		p2->p_cwdi = cwdinit(p1);
225 
226 	/*
227 	 * If p_limit is still copy-on-write, bump refcnt,
228 	 * otherwise get a copy that won't be modified.
229 	 * (If PL_SHAREMOD is clear, the structure is shared
230 	 * copy-on-write.)
231 	 */
232 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
233 		p2->p_limit = limcopy(p1->p_limit);
234 	else {
235 		p2->p_limit = p1->p_limit;
236 		p2->p_limit->p_refcnt++;
237 	}
238 
239 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
240 		p2->p_flag |= P_CONTROLT;
241 	if (flags & FORK_PPWAIT)
242 		p2->p_flag |= P_PPWAIT;
243 	LIST_INSERT_AFTER(p1, p2, p_pglist);
244 	p2->p_pptr = p1;
245 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
246 	LIST_INIT(&p2->p_children);
247 
248 	callout_init(&p2->p_realit_ch);
249 	callout_init(&p2->p_tsleep_ch);
250 
251 #ifdef KTRACE
252 	/*
253 	 * Copy traceflag and tracefile if enabled.
254 	 * If not inherited, these were zeroed above.
255 	 */
256 	if (p1->p_traceflag&KTRFAC_INHERIT) {
257 		p2->p_traceflag = p1->p_traceflag;
258 		if ((p2->p_tracep = p1->p_tracep) != NULL)
259 			ktradref(p2);
260 	}
261 #endif
262 	scheduler_fork_hook(p1, p2);
263 
264 	/*
265 	 * Create signal actions for the child process.
266 	 */
267 	sigactsinit(p2, p1, flags & FORK_SHARESIGS);
268 
269 	/*
270 	 * If emulation has process fork hook, call it now.
271 	 */
272 	if (p2->p_emul->e_proc_fork)
273 		(*p2->p_emul->e_proc_fork)(p2, p1);
274 
275 	/*
276 	 * This begins the section where we must prevent the parent
277 	 * from being swapped.
278 	 */
279 	PHOLD(p1);
280 
281 	/*
282 	 * Finish creating the child process.  It will return through a
283 	 * different path later.
284 	 */
285 	p2->p_addr = (struct user *)uaddr;
286 	uvm_fork(p1, p2, (flags & FORK_SHAREVM) ? TRUE : FALSE,
287 	    stack, stacksize,
288 	    (func != NULL) ? func : child_return,
289 	    (arg != NULL) ? arg : p2);
290 
291 	/*
292 	 * BEGIN PID ALLOCATION.
293 	 */
294 	s = proclist_lock_write();
295 
296 	/*
297 	 * Find an unused process ID.  We remember a range of unused IDs
298 	 * ready to use (from nextpid+1 through pidchecked-1).
299 	 */
300 	nextpid++;
301 retry:
302 	/*
303 	 * If the process ID prototype has wrapped around,
304 	 * restart somewhat above 0, as the low-numbered procs
305 	 * tend to include daemons that don't exit.
306 	 */
307 	if (nextpid >= PID_MAX) {
308 		nextpid = 100;
309 		pidchecked = 0;
310 	}
311 	if (nextpid >= pidchecked) {
312 		const struct proclist_desc *pd;
313 
314 		pidchecked = PID_MAX;
315 		/*
316 		 * Scan the process lists to check whether this pid
317 		 * is in use.  Remember the lowest pid that's greater
318 		 * than nextpid, so we can avoid checking for a while.
319 		 */
320 		pd = proclists;
321 again:
322 		LIST_FOREACH(tp, pd->pd_list, p_list) {
323 			while (tp->p_pid == nextpid ||
324 			    tp->p_pgrp->pg_id == nextpid ||
325 			    tp->p_session->s_sid == nextpid) {
326 				nextpid++;
327 				if (nextpid >= pidchecked)
328 					goto retry;
329 			}
330 			if (tp->p_pid > nextpid && pidchecked > tp->p_pid)
331 				pidchecked = tp->p_pid;
332 
333 			if (tp->p_pgrp->pg_id > nextpid &&
334 			    pidchecked > tp->p_pgrp->pg_id)
335 				pidchecked = tp->p_pgrp->pg_id;
336 
337 			if (tp->p_session->s_sid > nextpid &&
338 			    pidchecked > tp->p_session->s_sid)
339 				pidchecked = tp->p_session->s_sid;
340 		}
341 
342 		/*
343 		 * If there's another list, scan it.  If we have checked
344 		 * them all, we've found one!
345 		 */
346 		pd++;
347 		if (pd->pd_list != NULL)
348 			goto again;
349 	}
350 
351 	/* Record the pid we've allocated. */
352 	p2->p_pid = nextpid;
353 
354 	/* Record the signal to be delivered to the parent on exit. */
355 	p2->p_exitsig = exitsig;
356 
357 	/*
358 	 * Put the proc on allproc before unlocking PID allocation
359 	 * so that waiters won't grab it as soon as we unlock.
360 	 */
361 
362 	p2->p_stat = SIDL;			/* protect against others */
363 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
364 
365 	LIST_INSERT_HEAD(&allproc, p2, p_list);
366 
367 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
368 
369 	/*
370 	 * END PID ALLOCATION.
371 	 */
372 	proclist_unlock_write(s);
373 
374 	/*
375 	 * Make child runnable, set start time, and add to run queue.
376 	 */
377 	SCHED_LOCK(s);
378 	p2->p_stats->p_start = time;
379 	p2->p_acflag = AFORK;
380 	p2->p_stat = SRUN;
381 	setrunqueue(p2);
382 	SCHED_UNLOCK(s);
383 
384 	/*
385 	 * Now can be swapped.
386 	 */
387 	PRELE(p1);
388 
389 	/*
390 	 * Update stats now that we know the fork was successful.
391 	 */
392 	uvmexp.forks++;
393 	if (flags & FORK_PPWAIT)
394 		uvmexp.forks_ppwait++;
395 	if (flags & FORK_SHAREVM)
396 		uvmexp.forks_sharevm++;
397 
398 	/*
399 	 * Pass a pointer to the new process to the caller.
400 	 */
401 	if (rnewprocp != NULL)
402 		*rnewprocp = p2;
403 
404 #ifdef KTRACE
405 	if (KTRPOINT(p2, KTR_EMUL))
406 		ktremul(p2);
407 #endif
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 	if (retval != NULL) {
423 		retval[0] = p2->p_pid;
424 		retval[1] = 0;
425 	}
426 
427 	return (0);
428 }
429 
430 #if defined(MULTIPROCESSOR)
431 /*
432  * XXX This is a slight hack to get newly-formed processes to
433  * XXX acquire the kernel lock as soon as they run.
434  */
435 void
436 proc_trampoline_mp(void)
437 {
438 	struct proc *p = curproc;
439 
440 	SCHED_ASSERT_UNLOCKED();
441 	KERNEL_PROC_LOCK(p);
442 }
443 #endif
444