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