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