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