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