xref: /netbsd-src/sys/kern/kern_fork.c (revision d9158b13b5dfe46201430699a3f7a235ecf28df3)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	from: @(#)kern_fork.c	8.6 (Berkeley) 4/8/94
39  *	$Id: kern_fork.c,v 1.18 1994/06/15 19:59:21 mycroft Exp $
40  */
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/map.h>
45 #include <sys/filedesc.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/proc.h>
49 #include <sys/resourcevar.h>
50 #include <sys/vnode.h>
51 #include <sys/file.h>
52 #include <sys/acct.h>
53 #include <sys/ktrace.h>
54 
55 /* ARGSUSED */
56 fork(p, uap, retval)
57 	struct proc *p;
58 	void *uap;
59 	int retval[];
60 {
61 
62 	return (fork1(p, 0, retval));
63 }
64 
65 /* ARGSUSED */
66 vfork(p, uap, retval)
67 	struct proc *p;
68 	void *uap;
69 	int retval[];
70 {
71 
72 	return (fork1(p, 1, retval));
73 }
74 
75 int	nprocs = 1;		/* process 0 */
76 
77 fork1(p1, isvfork, retval)
78 	register struct proc *p1;
79 	int isvfork, retval[];
80 {
81 	register struct proc *p2;
82 	register uid_t uid;
83 	struct proc *newproc;
84 	struct proc **hash;
85 	int count;
86 	static int nextpid, pidchecked = 0;
87 
88 	/*
89 	 * Although process entries are dynamically created, we still keep
90 	 * a global limit on the maximum number we will create.  Don't allow
91 	 * a nonprivileged user to use the last process; don't let root
92 	 * exceed the limit. The variable nprocs is the current number of
93 	 * processes, maxproc is the limit.
94 	 */
95 	uid = p1->p_cred->p_ruid;
96 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
97 		tablefull("proc");
98 		return (EAGAIN);
99 	}
100 	/*
101 	 * Increment the count of procs running with this uid. Don't allow
102 	 * a nonprivileged user to exceed their current limit.
103 	 */
104 	count = chgproccnt(uid, 1);
105 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
106 		(void)chgproccnt(uid, -1);
107 		return (EAGAIN);
108 	}
109 
110 	/* Allocate new proc. */
111 	MALLOC(newproc, struct proc *, sizeof(struct proc), M_PROC, M_WAITOK);
112 
113 	/*
114 	 * Find an unused process ID.  We remember a range of unused IDs
115 	 * ready to use (from nextpid+1 through pidchecked-1).
116 	 */
117 	nextpid++;
118 retry:
119 	/*
120 	 * If the process ID prototype has wrapped around,
121 	 * restart somewhat above 0, as the low-numbered procs
122 	 * tend to include daemons that don't exit.
123 	 */
124 	if (nextpid >= PID_MAX) {
125 		nextpid = 100;
126 		pidchecked = 0;
127 	}
128 	if (nextpid >= pidchecked) {
129 		int doingzomb = 0;
130 
131 		pidchecked = PID_MAX;
132 		/*
133 		 * Scan the active and zombie procs to check whether this pid
134 		 * is in use.  Remember the lowest pid that's greater
135 		 * than nextpid, so we can avoid checking for a while.
136 		 */
137 		p2 = (struct proc *)allproc;
138 again:
139 		for (; p2 != NULL; p2 = p2->p_next) {
140 			while (p2->p_pid == nextpid ||
141 			    p2->p_pgrp->pg_id == nextpid) {
142 				nextpid++;
143 				if (nextpid >= pidchecked)
144 					goto retry;
145 			}
146 			if (p2->p_pid > nextpid && pidchecked > p2->p_pid)
147 				pidchecked = p2->p_pid;
148 			if (p2->p_pgrp->pg_id > nextpid &&
149 			    pidchecked > p2->p_pgrp->pg_id)
150 				pidchecked = p2->p_pgrp->pg_id;
151 		}
152 		if (!doingzomb) {
153 			doingzomb = 1;
154 			p2 = zombproc;
155 			goto again;
156 		}
157 	}
158 
159 
160 	/*
161 	 * Link onto allproc (this should probably be delayed).
162 	 * Heavy use of volatile here to prevent the compiler from
163 	 * rearranging code.  Yes, it *is* terribly ugly, but at least
164 	 * it works.
165 	 */
166 	nprocs++;
167 	p2 = newproc;
168 #define	Vp2 ((volatile struct proc *)p2)
169 	Vp2->p_stat = SIDL;			/* protect against others */
170 	Vp2->p_pid = nextpid;
171 	/*
172 	 * This is really:
173 	 *	p2->p_next = allproc;
174 	 *	allproc->p_prev = &p2->p_next;
175 	 *	p2->p_prev = &allproc;
176 	 *	allproc = p2;
177 	 * The assignment via allproc is legal since it is never NULL.
178 	 */
179 	*(volatile struct proc **)&Vp2->p_next = allproc;
180 	*(volatile struct proc ***)&allproc->p_prev =
181 	    (volatile struct proc **)&Vp2->p_next;
182 	*(volatile struct proc ***)&Vp2->p_prev = &allproc;
183 	allproc = Vp2;
184 #undef Vp2
185 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
186 
187 	/* Insert on the hash chain. */
188 	hash = &pidhash[PIDHASH(p2->p_pid)];
189 	p2->p_hash = *hash;
190 	*hash = p2;
191 
192 	/*
193 	 * Make a proc table entry for the new process.
194 	 * Start by zeroing the section of proc that is zero-initialized,
195 	 * then copy the section that is copied directly from the parent.
196 	 */
197 	bzero(&p2->p_startzero,
198 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
199 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
200 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
201 
202 	/*
203 	 * Duplicate sub-structures as needed.
204 	 * Increase reference counts on shared objects.
205 	 * The p_stats and p_sigacts substructs are set in vm_fork.
206 	 */
207 	p2->p_flag = P_INMEM;
208 	if (p1->p_flag & P_PROFIL)
209 		startprofclock(p2);
210 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
211 	    M_SUBPROC, M_WAITOK);
212 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
213 	p2->p_cred->p_refcnt = 1;
214 	crhold(p1->p_ucred);
215 
216 	/* bump references to the text vnode (for procfs) */
217 	p2->p_textvp = p1->p_textvp;
218 	if (p2->p_textvp)
219 		VREF(p2->p_textvp);
220 
221 	p2->p_fd = fdcopy(p1);
222 	/*
223 	 * If p_limit is still copy-on-write, bump refcnt,
224 	 * otherwise get a copy that won't be modified.
225 	 * (If PL_SHAREMOD is clear, the structure is shared
226 	 * copy-on-write.)
227 	 */
228 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
229 		p2->p_limit = limcopy(p1->p_limit);
230 	else {
231 		p2->p_limit = p1->p_limit;
232 		p2->p_limit->p_refcnt++;
233 	}
234 
235 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
236 		p2->p_flag |= P_CONTROLT;
237 	if (isvfork)
238 		p2->p_flag |= P_PPWAIT;
239 	p2->p_pgrpnxt = p1->p_pgrpnxt;
240 	p1->p_pgrpnxt = p2;
241 	p2->p_pptr = p1;
242 	p2->p_osptr = p1->p_cptr;
243 	if (p1->p_cptr)
244 		p1->p_cptr->p_ysptr = p2;
245 	p1->p_cptr = p2;
246 #ifdef KTRACE
247 	/*
248 	 * Copy traceflag and tracefile if enabled.
249 	 * If not inherited, these were zeroed above.
250 	 */
251 	if (p1->p_traceflag&KTRFAC_INHERIT) {
252 		p2->p_traceflag = p1->p_traceflag;
253 		if ((p2->p_tracep = p1->p_tracep) != NULL)
254 			VREF(p2->p_tracep);
255 	}
256 #endif
257 
258 	/*
259 	 * This begins the section where we must prevent the parent
260 	 * from being swapped.
261 	 */
262 	p1->p_holdcnt++;
263 	/*
264 	 * Set return values for child before vm_fork,
265 	 * so they can be copied to child stack.
266 	 * We return parent pid, and mark as child in retval[1].
267 	 * NOTE: the kernel stack may be at a different location in the child
268 	 * process, and thus addresses of automatic variables (including retval)
269 	 * may be invalid after vm_fork returns in the child process.
270 	 */
271 	retval[0] = p1->p_pid;
272 	retval[1] = 1;
273 	if (vm_fork(p1, p2, isvfork)) {
274 		/*
275 		 * Child process.  Set start time and get to work.
276 		 */
277 		(void) splclock();
278 		p2->p_stats->p_start = time;
279 		(void) spl0();
280 		p2->p_acflag = AFORK;
281 		return (0);
282 	}
283 
284 	/*
285 	 * Make child runnable and add to run queue.
286 	 */
287 	(void) splhigh();
288 	p2->p_stat = SRUN;
289 	setrunqueue(p2);
290 	(void) spl0();
291 
292 	/*
293 	 * Now can be swapped.
294 	 */
295 	p1->p_holdcnt--;
296 
297 	/*
298 	 * Preserve synchronization semantics of vfork.  If waiting for
299 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
300 	 * proc (in case of exit).
301 	 */
302 	if (isvfork)
303 		while (p2->p_flag & P_PPWAIT)
304 			tsleep(p1, PWAIT, "ppwait", 0);
305 
306 	/*
307 	 * Return child pid to parent process,
308 	 * marking us as parent via retval[1].
309 	 */
310 	retval[0] = p2->p_pid;
311 	retval[1] = 0;
312 	return (0);
313 }
314