xref: /netbsd-src/sys/kern/kern_fork.c (revision 7c7c171d130af9949261bc7dce2150a03c3d239c)
1 /*	$NetBSD: kern_fork.c,v 1.41 1998/04/09 00:23:38 thorpej 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_uvm.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/map.h>
48 #include <sys/filedesc.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/mount.h>
52 #include <sys/proc.h>
53 #include <sys/resourcevar.h>
54 #include <sys/vnode.h>
55 #include <sys/file.h>
56 #include <sys/acct.h>
57 #include <sys/ktrace.h>
58 #include <sys/vmmeter.h>
59 
60 #include <sys/syscallargs.h>
61 
62 #include <vm/vm.h>
63 #include <vm/vm_kern.h>
64 
65 #if defined(UVM)
66 #include <uvm/uvm_extern.h>
67 #endif
68 
69 int	nprocs = 1;		/* process 0 */
70 
71 /*ARGSUSED*/
72 int
73 sys_fork(p, v, retval)
74 	struct proc *p;
75 	void *v;
76 	register_t *retval;
77 {
78 
79 	return (fork1(p, 0, retval, NULL));
80 }
81 
82 /*
83  * vfork(2) system call compatible with 4.4BSD (i.e. BSD with Mach VM).
84  * Address space is not shared, but parent is blocked until child exit.
85  */
86 /*ARGSUSED*/
87 int
88 sys_vfork(p, v, retval)
89 	struct proc *p;
90 	void *v;
91 	register_t *retval;
92 {
93 
94 	return (fork1(p, FORK_PPWAIT, retval, NULL));
95 }
96 
97 /*
98  * New vfork(2) system call for NetBSD, which implements original 3BSD vfork(2)
99  * semantics.  Address space is shared, and parent is blocked until child exit.
100  */
101 /*ARGSUSED*/
102 int
103 sys___vfork14(p, v, retval)
104 	struct proc *p;
105 	void *v;
106 	register_t *retval;
107 {
108 
109 	return (fork1(p, FORK_PPWAIT|FORK_SHAREVM, retval, NULL));
110 }
111 
112 int
113 fork1(p1, flags, retval, rnewprocp)
114 	register struct proc *p1;
115 	int flags;
116 	register_t *retval;
117 	struct proc **rnewprocp;
118 {
119 	register struct proc *p2;
120 	register uid_t uid;
121 	struct proc *newproc;
122 	int count;
123 	vm_offset_t uaddr;
124 	static int nextpid, pidchecked = 0;
125 
126 	/*
127 	 * Although process entries are dynamically created, we still keep
128 	 * a global limit on the maximum number we will create.  Don't allow
129 	 * a nonprivileged user to use the last process; don't let root
130 	 * exceed the limit. The variable nprocs is the current number of
131 	 * processes, maxproc is the limit.
132 	 */
133 	uid = p1->p_cred->p_ruid;
134 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
135 		tablefull("proc");
136 		return (EAGAIN);
137 	}
138 
139 	/*
140 	 * Increment the count of procs running with this uid. Don't allow
141 	 * a nonprivileged user to exceed their current limit.
142 	 */
143 	count = chgproccnt(uid, 1);
144 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
145 		(void)chgproccnt(uid, -1);
146 		return (EAGAIN);
147 	}
148 
149 	/*
150 	 * Allocate virtual address space for the U-area now, while it
151 	 * is still easy to abort the fork operation if we're out of
152 	 * kernel virtual address space.  The actual U-area pages will
153 	 * be allocated and wired in vm_fork().
154 	 */
155 #if defined(UVM)
156 	uaddr = uvm_km_valloc(kernel_map, USPACE);
157 #else
158 	uaddr = kmem_alloc_pageable(kernel_map, USPACE);
159 #endif
160 	if (uaddr == 0) {
161 		(void)chgproccnt(uid, -1);
162 		return (ENOMEM);
163 	}
164 
165 	/*
166 	 * We are now committed to the fork.  From here on, we may
167 	 * block on resources, but resource allocation may NOT fail.
168 	 */
169 
170 	/* Allocate new proc. */
171 	MALLOC(newproc, struct proc *, sizeof(struct proc), M_PROC, M_WAITOK);
172 
173 	/*
174 	 * Find an unused process ID.  We remember a range of unused IDs
175 	 * ready to use (from nextpid+1 through pidchecked-1).
176 	 */
177 	nextpid++;
178 retry:
179 	/*
180 	 * If the process ID prototype has wrapped around,
181 	 * restart somewhat above 0, as the low-numbered procs
182 	 * tend to include daemons that don't exit.
183 	 */
184 	if (nextpid >= PID_MAX) {
185 		nextpid = 100;
186 		pidchecked = 0;
187 	}
188 	if (nextpid >= pidchecked) {
189 		int doingzomb = 0;
190 
191 		pidchecked = PID_MAX;
192 		/*
193 		 * Scan the active and zombie procs to check whether this pid
194 		 * is in use.  Remember the lowest pid that's greater
195 		 * than nextpid, so we can avoid checking for a while.
196 		 */
197 		p2 = allproc.lh_first;
198 again:
199 		for (; p2 != 0; p2 = p2->p_list.le_next) {
200 			while (p2->p_pid == nextpid ||
201 			    p2->p_pgrp->pg_id == nextpid ||
202 			    p2->p_session->s_sid == nextpid) {
203 				nextpid++;
204 				if (nextpid >= pidchecked)
205 					goto retry;
206 			}
207 			if (p2->p_pid > nextpid && pidchecked > p2->p_pid)
208 				pidchecked = p2->p_pid;
209 
210 			if (p2->p_pgrp->pg_id > nextpid &&
211 			    pidchecked > p2->p_pgrp->pg_id)
212 				pidchecked = p2->p_pgrp->pg_id;
213 
214 			if (p2->p_session->s_sid > nextpid &&
215 			    pidchecked > p2->p_session->s_sid)
216 				pidchecked = p2->p_session->s_sid;
217 		}
218 		if (!doingzomb) {
219 			doingzomb = 1;
220 			p2 = zombproc.lh_first;
221 			goto again;
222 		}
223 	}
224 
225 	nprocs++;
226 	p2 = newproc;
227 	p2->p_stat = SIDL;			/* protect against others */
228 	p2->p_pid = nextpid;
229 	LIST_INSERT_HEAD(&allproc, p2, p_list);
230 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
231 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
232 
233 	/*
234 	 * Make a proc table entry for the new process.
235 	 * Start by zeroing the section of proc that is zero-initialized,
236 	 * then copy the section that is copied directly from the parent.
237 	 */
238 	bzero(&p2->p_startzero,
239 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
240 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
241 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
242 
243 	/*
244 	 * Duplicate sub-structures as needed.
245 	 * Increase reference counts on shared objects.
246 	 * The p_stats and p_sigacts substructs are set in vm_fork.
247 	 */
248 	p2->p_flag = P_INMEM | (p1->p_flag & P_SUGID);
249 	p2->p_emul = p1->p_emul;
250 	if (p1->p_flag & P_PROFIL)
251 		startprofclock(p2);
252 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
253 	    M_SUBPROC, M_WAITOK);
254 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
255 	p2->p_cred->p_refcnt = 1;
256 	crhold(p1->p_ucred);
257 
258 	/* bump references to the text vnode (for procfs) */
259 	p2->p_textvp = p1->p_textvp;
260 	if (p2->p_textvp)
261 		VREF(p2->p_textvp);
262 
263 	p2->p_fd = fdcopy(p1);
264 	/*
265 	 * If p_limit is still copy-on-write, bump refcnt,
266 	 * otherwise get a copy that won't be modified.
267 	 * (If PL_SHAREMOD is clear, the structure is shared
268 	 * copy-on-write.)
269 	 */
270 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
271 		p2->p_limit = limcopy(p1->p_limit);
272 	else {
273 		p2->p_limit = p1->p_limit;
274 		p2->p_limit->p_refcnt++;
275 	}
276 
277 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
278 		p2->p_flag |= P_CONTROLT;
279 	if (flags & FORK_PPWAIT)
280 		p2->p_flag |= P_PPWAIT;
281 	LIST_INSERT_AFTER(p1, p2, p_pglist);
282 	p2->p_pptr = p1;
283 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
284 	LIST_INIT(&p2->p_children);
285 
286 #ifdef KTRACE
287 	/*
288 	 * Copy traceflag and tracefile if enabled.
289 	 * If not inherited, these were zeroed above.
290 	 */
291 	if (p1->p_traceflag&KTRFAC_INHERIT) {
292 		p2->p_traceflag = p1->p_traceflag;
293 		if ((p2->p_tracep = p1->p_tracep) != NULL)
294 			VREF(p2->p_tracep);
295 	}
296 #endif
297 
298 	/*
299 	 * This begins the section where we must prevent the parent
300 	 * from being swapped.
301 	 */
302 	PHOLD(p1);
303 
304 	/*
305 	 * Finish creating the child process.  It will return through a
306 	 * different path later.
307 	 */
308 	p2->p_addr = (struct user *)uaddr;
309 #if defined(UVM)
310 	uvm_fork(p1, p2, (flags & FORK_SHAREVM) ? TRUE : FALSE);
311 #else
312 	vm_fork(p1, p2, (flags & FORK_SHAREVM) ? TRUE : FALSE);
313 #endif
314 
315 	/*
316 	 * Make child runnable, set start time, and add to run queue.
317 	 */
318 	(void) splstatclock();
319 	p2->p_stats->p_start = time;
320 	p2->p_acflag = AFORK;
321 	p2->p_stat = SRUN;
322 	setrunqueue(p2);
323 	(void) spl0();
324 
325 	/*
326 	 * Now can be swapped.
327 	 */
328 	PRELE(p1);
329 
330 	/*
331 	 * Update stats now that we know the fork was successful.
332 	 */
333 #if defined(UVM)
334 	uvmexp.forks++;
335 	if (flags & FORK_PPWAIT)
336 		uvmexp.forks_ppwait++;
337 	if (flags & FORK_SHAREVM)
338 		uvmexp.forks_sharevm++;
339 #else
340 	cnt.v_forks++;
341 	if (flags & FORK_PPWAIT)
342 		cnt.v_forks_ppwait++;
343 	if (flags & FORK_SHAREVM)
344 		cnt.v_forks_sharevm++;
345 #endif
346 
347 	/*
348 	 * Pass a pointer to the new process to the caller.
349 	 */
350 	if (rnewprocp != NULL)
351 		*rnewprocp = p2;
352 
353 	/*
354 	 * Preserve synchronization semantics of vfork.  If waiting for
355 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
356 	 * proc (in case of exit).
357 	 */
358 	if (flags & FORK_PPWAIT)
359 		while (p2->p_flag & P_PPWAIT)
360 			tsleep(p1, PWAIT, "ppwait", 0);
361 
362 	/*
363 	 * Return child pid to parent process,
364 	 * marking us as parent via retval[1].
365 	 */
366 	if (retval != NULL) {
367 		retval[0] = p2->p_pid;
368 		retval[1] = 0;
369 	}
370 	return (0);
371 }
372