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