xref: /netbsd-src/sys/kern/kern_fork.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: kern_fork.c,v 1.30 1996/10/09 00:04:39 mycroft Exp $	*/
2 
3 /*
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
41  */
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/map.h>
46 #include <sys/filedesc.h>
47 #include <sys/kernel.h>
48 #include <sys/malloc.h>
49 #include <sys/mount.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 <sys/syscallargs.h>
58 
59 #include <vm/vm.h>
60 
61 int	nprocs = 1;		/* process 0 */
62 
63 int fork1 __P((struct proc *, int, register_t *));
64 
65 /*ARGSUSED*/
66 int
67 sys_fork(p, v, retval)
68 	struct proc *p;
69 	void *v;
70 	register_t *retval;
71 {
72 
73 	return (fork1(p, 0, retval));
74 }
75 
76 /*ARGSUSED*/
77 int
78 sys_vfork(p, v, retval)
79 	struct proc *p;
80 	void *v;
81 	register_t *retval;
82 {
83 
84 	return (fork1(p, 1, retval));
85 }
86 
87 int
88 fork1(p1, isvfork, retval)
89 	register struct proc *p1;
90 	int isvfork;
91 	register_t *retval;
92 {
93 	register struct proc *p2;
94 	register uid_t uid;
95 	struct proc *newproc;
96 	int count;
97 	static int nextpid, pidchecked = 0;
98 
99 	/*
100 	 * Although process entries are dynamically created, we still keep
101 	 * a global limit on the maximum number we will create.  Don't allow
102 	 * a nonprivileged user to use the last process; don't let root
103 	 * exceed the limit. The variable nprocs is the current number of
104 	 * processes, maxproc is the limit.
105 	 */
106 	uid = p1->p_cred->p_ruid;
107 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
108 		tablefull("proc");
109 		return (EAGAIN);
110 	}
111 
112 	/*
113 	 * Increment the count of procs running with this uid. Don't allow
114 	 * a nonprivileged user to exceed their current limit.
115 	 */
116 	count = chgproccnt(uid, 1);
117 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
118 		(void)chgproccnt(uid, -1);
119 		return (EAGAIN);
120 	}
121 
122 	/* Allocate new proc. */
123 	MALLOC(newproc, struct proc *, sizeof(struct proc), M_PROC, M_WAITOK);
124 
125 	/*
126 	 * Find an unused process ID.  We remember a range of unused IDs
127 	 * ready to use (from nextpid+1 through pidchecked-1).
128 	 */
129 	nextpid++;
130 retry:
131 	/*
132 	 * If the process ID prototype has wrapped around,
133 	 * restart somewhat above 0, as the low-numbered procs
134 	 * tend to include daemons that don't exit.
135 	 */
136 	if (nextpid >= PID_MAX) {
137 		nextpid = 100;
138 		pidchecked = 0;
139 	}
140 	if (nextpid >= pidchecked) {
141 		int doingzomb = 0;
142 
143 		pidchecked = PID_MAX;
144 		/*
145 		 * Scan the active and zombie procs to check whether this pid
146 		 * is in use.  Remember the lowest pid that's greater
147 		 * than nextpid, so we can avoid checking for a while.
148 		 */
149 		p2 = allproc.lh_first;
150 again:
151 		for (; p2 != 0; p2 = p2->p_list.le_next) {
152 			while (p2->p_pid == nextpid ||
153 			    p2->p_pgrp->pg_id == nextpid) {
154 				nextpid++;
155 				if (nextpid >= pidchecked)
156 					goto retry;
157 			}
158 			if (p2->p_pid > nextpid && pidchecked > p2->p_pid)
159 				pidchecked = p2->p_pid;
160 			if (p2->p_pgrp->pg_id > nextpid &&
161 			    pidchecked > p2->p_pgrp->pg_id)
162 				pidchecked = p2->p_pgrp->pg_id;
163 		}
164 		if (!doingzomb) {
165 			doingzomb = 1;
166 			p2 = zombproc.lh_first;
167 			goto again;
168 		}
169 	}
170 
171 	nprocs++;
172 	p2 = newproc;
173 	p2->p_stat = SIDL;			/* protect against others */
174 	p2->p_pid = nextpid;
175 	LIST_INSERT_HEAD(&allproc, p2, p_list);
176 	p2->p_forw = p2->p_back = NULL;		/* shouldn't be necessary */
177 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
178 
179 	/*
180 	 * Make a proc table entry for the new process.
181 	 * Start by zeroing the section of proc that is zero-initialized,
182 	 * then copy the section that is copied directly from the parent.
183 	 */
184 	bzero(&p2->p_startzero,
185 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
186 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
187 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
188 
189 	/*
190 	 * Duplicate sub-structures as needed.
191 	 * Increase reference counts on shared objects.
192 	 * The p_stats and p_sigacts substructs are set in vm_fork.
193 	 */
194 	p2->p_flag = P_INMEM;
195 	p2->p_emul = p1->p_emul;
196 	if (p1->p_flag & P_PROFIL)
197 		startprofclock(p2);
198 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
199 	    M_SUBPROC, M_WAITOK);
200 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
201 	p2->p_cred->p_refcnt = 1;
202 	crhold(p1->p_ucred);
203 
204 	/* bump references to the text vnode (for procfs) */
205 	p2->p_textvp = p1->p_textvp;
206 	if (p2->p_textvp)
207 		VREF(p2->p_textvp);
208 
209 	p2->p_fd = fdcopy(p1);
210 	/*
211 	 * If p_limit is still copy-on-write, bump refcnt,
212 	 * otherwise get a copy that won't be modified.
213 	 * (If PL_SHAREMOD is clear, the structure is shared
214 	 * copy-on-write.)
215 	 */
216 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
217 		p2->p_limit = limcopy(p1->p_limit);
218 	else {
219 		p2->p_limit = p1->p_limit;
220 		p2->p_limit->p_refcnt++;
221 	}
222 
223 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
224 		p2->p_flag |= P_CONTROLT;
225 	if (isvfork)
226 		p2->p_flag |= P_PPWAIT;
227 	LIST_INSERT_AFTER(p1, p2, p_pglist);
228 	p2->p_pptr = p1;
229 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
230 	LIST_INIT(&p2->p_children);
231 
232 #ifdef KTRACE
233 	/*
234 	 * Copy traceflag and tracefile if enabled.
235 	 * If not inherited, these were zeroed above.
236 	 */
237 	if (p1->p_traceflag&KTRFAC_INHERIT) {
238 		p2->p_traceflag = p1->p_traceflag;
239 		if ((p2->p_tracep = p1->p_tracep) != NULL)
240 			VREF(p2->p_tracep);
241 	}
242 #endif
243 
244 	/*
245 	 * This begins the section where we must prevent the parent
246 	 * from being swapped.
247 	 */
248 	PHOLD(p1);
249 
250 #ifdef __FORK_BRAINDAMAGE
251 	/*
252 	 * Set return values for child before vm_fork,
253 	 * so they can be copied to child stack.
254 	 * We return 0, rather than the traditional behaviour of modifying the
255 	 * return value in the system call stub.
256 	 * NOTE: the kernel stack may be at a different location in the child
257 	 * process, and thus addresses of automatic variables (including retval)
258 	 * may be invalid after vm_fork returns in the child process.
259 	 */
260 	retval[0] = 0;
261 	retval[1] = 1;
262 	if (vm_fork(p1, p2))
263 		return (0);
264 #else
265 	/*
266 	 * Finish creating the child process.  It will return through a
267 	 * different path later.
268 	 */
269 	vm_fork(p1, p2);
270 #endif
271 
272 	/*
273 	 * Make child runnable, set start time, and add to run queue.
274 	 */
275 	(void) splstatclock();
276 	p2->p_stats->p_start = time;
277 	p2->p_acflag = AFORK;
278 	p2->p_stat = SRUN;
279 	setrunqueue(p2);
280 	(void) spl0();
281 
282 	/*
283 	 * Now can be swapped.
284 	 */
285 	PRELE(p1);
286 
287 	/*
288 	 * Preserve synchronization semantics of vfork.  If waiting for
289 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
290 	 * proc (in case of exit).
291 	 */
292 	if (isvfork)
293 		while (p2->p_flag & P_PPWAIT)
294 			tsleep(p1, PWAIT, "ppwait", 0);
295 
296 	/*
297 	 * Return child pid to parent process,
298 	 * marking us as parent via retval[1].
299 	 */
300 	retval[0] = p2->p_pid;
301 	retval[1] = 0;
302 	return (0);
303 }
304