xref: /freebsd/sys/kern/kern_fork.c (revision ef5d438ed4bc17ad7ece3e40fe4d1f9baf3aadf7)
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  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
39  * $Id: kern_fork.c,v 1.16 1996/01/03 21:42:02 wollman Exp $
40  */
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/malloc.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 
57 #include <vm/vm.h>
58 #include <vm/vm_param.h>
59 #include <vm/lock.h>
60 #include <vm/pmap.h>
61 #include <vm/vm_map.h>
62 #include <vm/vm_extern.h>
63 #include <vm/vm_inherit.h>
64 
65 static int fork1(struct proc *p, int forktype, int rforkflags, int *retval);
66 
67 #define	ISFORK	0
68 #define	ISVFORK	1
69 #define	ISRFORK	2
70 
71 #ifndef _SYS_SYSPROTO_H_
72 struct fork_args {
73         int     dummy;
74 };
75 #endif
76 
77 /* ARGSUSED */
78 int
79 fork(p, uap, retval)
80 	struct proc *p;
81 	struct fork_args *uap;
82 	int retval[];
83 {
84 	return (fork1(p, ISFORK, 0, retval));
85 }
86 
87 /* ARGSUSED */
88 int
89 vfork(p, uap, retval)
90 	struct proc *p;
91 	struct vfork_args *uap;
92 	int retval[];
93 {
94 	return (fork1(p, ISVFORK, 0, retval));
95 }
96 
97 /* ARGSUSED */
98 int
99 rfork(p, uap, retval)
100 	struct proc *p;
101 	struct rfork_args *uap;
102 	int retval[];
103 {
104 	return (fork1(p, ISRFORK, uap->flags, retval));
105 }
106 
107 
108 int	nprocs = 1;		/* process 0 */
109 
110 static int
111 fork1(p1, forktype, rforkflags, retval)
112 	register struct proc *p1;
113 	int forktype;
114 	int rforkflags;
115 	int retval[];
116 {
117 	register struct proc *p2;
118 	register uid_t uid;
119 	struct proc *newproc;
120 	struct proc **hash;
121 	int count;
122 	static int nextpid, pidchecked = 0;
123 	int dupfd = 1, cleanfd = 0;
124 
125 	if (forktype == ISRFORK) {
126 		dupfd = 0;
127 		if ((rforkflags & RFPROC) == 0)
128 			return (EINVAL);
129 		if ((rforkflags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
130 			return (EINVAL);
131 		if (rforkflags & RFFDG)
132 			dupfd = 1;
133 		if (rforkflags & RFNOWAIT)
134 			return (EINVAL);	/* XXX unimplimented */
135 		if (rforkflags & RFCFDG)
136 			cleanfd = 1;
137 	}
138 
139 	/*
140 	 * Although process entries are dynamically created, we still keep
141 	 * a global limit on the maximum number we will create.  Don't allow
142 	 * a nonprivileged user to use the last process; don't let root
143 	 * exceed the limit. The variable nprocs is the current number of
144 	 * processes, maxproc is the limit.
145 	 */
146 	uid = p1->p_cred->p_ruid;
147 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
148 		tablefull("proc");
149 		return (EAGAIN);
150 	}
151 	/*
152 	 * Increment the count of procs running with this uid. Don't allow
153 	 * a nonprivileged user to exceed their current limit.
154 	 */
155 	count = chgproccnt(uid, 1);
156 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
157 		(void)chgproccnt(uid, -1);
158 		return (EAGAIN);
159 	}
160 
161 	/* Allocate new proc. */
162 	MALLOC(newproc, struct proc *, sizeof(struct proc), M_PROC, M_WAITOK);
163 
164 	/*
165 	 * Find an unused process ID.  We remember a range of unused IDs
166 	 * ready to use (from nextpid+1 through pidchecked-1).
167 	 */
168 	nextpid++;
169 retry:
170 	/*
171 	 * If the process ID prototype has wrapped around,
172 	 * restart somewhat above 0, as the low-numbered procs
173 	 * tend to include daemons that don't exit.
174 	 */
175 	if (nextpid >= PID_MAX) {
176 		nextpid = 100;
177 		pidchecked = 0;
178 	}
179 	if (nextpid >= pidchecked) {
180 		int doingzomb = 0;
181 
182 		pidchecked = PID_MAX;
183 		/*
184 		 * Scan the active and zombie procs to check whether this pid
185 		 * is in use.  Remember the lowest pid that's greater
186 		 * than nextpid, so we can avoid checking for a while.
187 		 */
188 		p2 = (struct proc *)allproc;
189 again:
190 		for (; p2 != NULL; p2 = p2->p_next) {
191 			while (p2->p_pid == nextpid ||
192 			    p2->p_pgrp->pg_id == nextpid) {
193 				nextpid++;
194 				if (nextpid >= pidchecked)
195 					goto retry;
196 			}
197 			if (p2->p_pid > nextpid && pidchecked > p2->p_pid)
198 				pidchecked = p2->p_pid;
199 			if (p2->p_pgrp->pg_id > nextpid &&
200 			    pidchecked > p2->p_pgrp->pg_id)
201 				pidchecked = p2->p_pgrp->pg_id;
202 		}
203 		if (!doingzomb) {
204 			doingzomb = 1;
205 			p2 = zombproc;
206 			goto again;
207 		}
208 	}
209 
210 
211 	/*
212 	 * Link onto allproc (this should probably be delayed).
213 	 * Heavy use of volatile here to prevent the compiler from
214 	 * rearranging code.  Yes, it *is* terribly ugly, but at least
215 	 * it works.
216 	 */
217 	nprocs++;
218 	p2 = newproc;
219 #define	Vp2 ((volatile struct proc *)p2)
220 	Vp2->p_stat = SIDL;			/* protect against others */
221 	Vp2->p_pid = nextpid;
222 	/*
223 	 * This is really:
224 	 *	p2->p_next = allproc;
225 	 *	allproc->p_prev = &p2->p_next;
226 	 *	p2->p_prev = &allproc;
227 	 *	allproc = p2;
228 	 * The assignment via allproc is legal since it is never NULL.
229 	 */
230 	*(volatile struct proc **)&Vp2->p_next = allproc;
231 	*(volatile struct proc ***)&allproc->p_prev =
232 	    (volatile struct proc **)&Vp2->p_next;
233 	*(volatile struct proc ***)&Vp2->p_prev = &allproc;
234 	allproc = Vp2;
235 #undef Vp2
236 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
237 
238 	/* Insert on the hash chain. */
239 	hash = &pidhash[PIDHASH(p2->p_pid)];
240 	p2->p_hash = *hash;
241 	*hash = p2;
242 
243 	/*
244 	 * Make a proc table entry for the new process.
245 	 * Start by zeroing the section of proc that is zero-initialized,
246 	 * then copy the section that is copied directly from the parent.
247 	 */
248 	bzero(&p2->p_startzero,
249 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
250 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
251 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
252 
253 	/*
254 	 * Duplicate sub-structures as needed.
255 	 * Increase reference counts on shared objects.
256 	 * The p_stats and p_sigacts substructs are set in vm_fork.
257 	 */
258 	p2->p_flag = P_INMEM;
259 	if (p1->p_flag & P_PROFIL)
260 		startprofclock(p2);
261 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
262 	    M_SUBPROC, M_WAITOK);
263 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
264 	p2->p_cred->p_refcnt = 1;
265 	crhold(p1->p_ucred);
266 
267 	/* bump references to the text vnode (for procfs) */
268 	p2->p_textvp = p1->p_textvp;
269 	if (p2->p_textvp)
270 		VREF(p2->p_textvp);
271 
272 	if (cleanfd)
273 		p2->p_fd = fdinit(p1);
274 	else if (dupfd)
275 		p2->p_fd = fdcopy(p1);
276 	else
277 		p2->p_fd = fdshare(p1);
278 
279 	/*
280 	 * If p_limit is still copy-on-write, bump refcnt,
281 	 * otherwise get a copy that won't be modified.
282 	 * (If PL_SHAREMOD is clear, the structure is shared
283 	 * copy-on-write.)
284 	 */
285 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
286 		p2->p_limit = limcopy(p1->p_limit);
287 	else {
288 		p2->p_limit = p1->p_limit;
289 		p2->p_limit->p_refcnt++;
290 	}
291 
292 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
293 		p2->p_flag |= P_CONTROLT;
294 	if (forktype == ISVFORK)
295 		p2->p_flag |= P_PPWAIT;
296 	p2->p_pgrpnxt = p1->p_pgrpnxt;
297 	p1->p_pgrpnxt = p2;
298 	p2->p_pptr = p1;
299 	p2->p_osptr = p1->p_cptr;
300 	if (p1->p_cptr)
301 		p1->p_cptr->p_ysptr = p2;
302 	p1->p_cptr = p2;
303 #ifdef KTRACE
304 	/*
305 	 * Copy traceflag and tracefile if enabled.
306 	 * If not inherited, these were zeroed above.
307 	 */
308 	if (p1->p_traceflag&KTRFAC_INHERIT) {
309 		p2->p_traceflag = p1->p_traceflag;
310 		if ((p2->p_tracep = p1->p_tracep) != NULL)
311 			VREF(p2->p_tracep);
312 	}
313 #endif
314 
315 	/*
316 	 * set priority of child to be that of parent
317 	 */
318 	p2->p_estcpu = p1->p_estcpu;
319 
320 	/*
321 	 * This begins the section where we must prevent the parent
322 	 * from being swapped.
323 	 */
324 	p1->p_flag |= P_NOSWAP;
325 
326 	/*
327 	 * share as much address space as possible
328 	 */
329 	if (forktype == ISRFORK && (rforkflags & RFMEM)) {
330 		(void) vm_map_inherit(&p1->p_vmspace->vm_map,
331 		    VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS - MAXSSIZ,
332 		    VM_INHERIT_SHARE);
333 	}
334 
335 	/*
336 	 * Set return values for child before vm_fork,
337 	 * so they can be copied to child stack.
338 	 * We return parent pid, and mark as child in retval[1].
339 	 * NOTE: the kernel stack may be at a different location in the child
340 	 * process, and thus addresses of automatic variables (including retval)
341 	 * may be invalid after vm_fork returns in the child process.
342 	 */
343 	retval[0] = p1->p_pid;
344 	retval[1] = 1;
345 	if (vm_fork(p1, p2)) {
346 		/*
347 		 * Child process.  Set start time and get to work.
348 		 */
349 		microtime(&runtime);
350 		p2->p_stats->p_start = runtime;
351 		p2->p_acflag = AFORK;
352 		return (0);
353 	}
354 
355 	/*
356 	 * Make child runnable and add to run queue.
357 	 */
358 	(void) splhigh();
359 	p2->p_stat = SRUN;
360 	setrunqueue(p2);
361 	(void) spl0();
362 
363 	/*
364 	 * Now can be swapped.
365 	 */
366 	p1->p_flag &= ~P_NOSWAP;
367 
368 	/*
369 	 * Preserve synchronization semantics of vfork.  If waiting for
370 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
371 	 * proc (in case of exit).
372 	 */
373 	if (forktype == ISVFORK)
374 		while (p2->p_flag & P_PPWAIT)
375 			tsleep(p1, PWAIT, "ppwait", 0);
376 
377 	/*
378 	 * Return child pid to parent process,
379 	 * marking us as parent via retval[1].
380 	 */
381 	retval[0] = p2->p_pid;
382 	retval[1] = 0;
383 	return (0);
384 }
385