xref: /freebsd/sys/kern/kern_fork.c (revision 3e0f6b97b257a96f7275e4442204263e44b16686)
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  * $FreeBSD$
40  */
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/malloc.h>
50 #include <sys/proc.h>
51 #include <sys/resourcevar.h>
52 #include <sys/vnode.h>
53 #include <sys/acct.h>
54 #include <sys/ktrace.h>
55 #include <sys/unistd.h>
56 
57 #include <vm/vm.h>
58 #include <vm/vm_param.h>
59 #include <sys/lock.h>
60 #include <vm/pmap.h>
61 #include <vm/vm_map.h>
62 #include <vm/vm_extern.h>
63 #include <vm/vm_inherit.h>
64 
65 static int fork1 __P((struct proc *p, int flags, int *retval));
66 
67 /*
68  * These are the stuctures used to create a callout list for things to do
69  * when forking a process
70  */
71 typedef struct fork_list_element {
72 	struct fork_list_element *next;
73 	forklist_fn function;
74 } *fle_p;
75 
76 static fle_p	fork_list;
77 
78 #ifndef _SYS_SYSPROTO_H_
79 struct fork_args {
80 	int     dummy;
81 };
82 #endif
83 
84 /* ARGSUSED */
85 int
86 fork(p, uap, retval)
87 	struct proc *p;
88 	struct fork_args *uap;
89 	int retval[];
90 {
91 	return (fork1(p, (RFFDG|RFPROC), retval));
92 }
93 
94 /* ARGSUSED */
95 int
96 vfork(p, uap, retval)
97 	struct proc *p;
98 	struct vfork_args *uap;
99 	int retval[];
100 {
101 	return (fork1(p, (RFFDG|RFPROC|RFPPWAIT), retval));
102 }
103 
104 /* ARGSUSED */
105 int
106 rfork(p, uap, retval)
107 	struct proc *p;
108 	struct rfork_args *uap;
109 	int retval[];
110 {
111 	return (fork1(p, uap->flags, retval));
112 }
113 
114 
115 int	nprocs = 1;		/* process 0 */
116 static int nextpid = 0;
117 
118 static int
119 fork1(p1, flags, retval)
120 	register struct proc *p1;
121 	int flags;
122 	int retval[];
123 {
124 	register struct proc *p2, *pptr;
125 	register uid_t uid;
126 	struct proc *newproc;
127 	int count;
128 	static int pidchecked = 0;
129 	fle_p ep ;
130 
131 	ep = fork_list;
132 	if ((flags & RFPROC) == 0)
133 		return (EINVAL);
134 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
135 		return (EINVAL);
136 
137 	/*
138 	 * Although process entries are dynamically created, we still keep
139 	 * a global limit on the maximum number we will create.  Don't allow
140 	 * a nonprivileged user to use the last process; don't let root
141 	 * exceed the limit. The variable nprocs is the current number of
142 	 * processes, maxproc is the limit.
143 	 */
144 	uid = p1->p_cred->p_ruid;
145 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
146 		tablefull("proc");
147 		return (EAGAIN);
148 	}
149 	/*
150 	 * Increment the nprocs resource before blocking can occur.  There
151 	 * are hard-limits as to the number of processes that can run.
152 	 */
153 	nprocs++;
154 
155 	/*
156 	 * Increment the count of procs running with this uid. Don't allow
157 	 * a nonprivileged user to exceed their current limit.
158 	 */
159 	count = chgproccnt(uid, 1);
160 	if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
161 		(void)chgproccnt(uid, -1);
162 		/*
163 		 * Back out the process count
164 		 */
165 		nprocs--;
166 		return (EAGAIN);
167 	}
168 
169 	/* Allocate new proc. */
170 	MALLOC(newproc, struct proc *, sizeof(struct proc), M_PROC, M_WAITOK);
171 
172 	/*
173 	 * Find an unused process ID.  We remember a range of unused IDs
174 	 * ready to use (from nextpid+1 through pidchecked-1).
175 	 */
176 	nextpid++;
177 retry:
178 	/*
179 	 * If the process ID prototype has wrapped around,
180 	 * restart somewhat above 0, as the low-numbered procs
181 	 * tend to include daemons that don't exit.
182 	 */
183 	if (nextpid >= PID_MAX) {
184 		nextpid = 100;
185 		pidchecked = 0;
186 	}
187 	if (nextpid >= pidchecked) {
188 		int doingzomb = 0;
189 
190 		pidchecked = PID_MAX;
191 		/*
192 		 * Scan the active and zombie procs to check whether this pid
193 		 * is in use.  Remember the lowest pid that's greater
194 		 * than nextpid, so we can avoid checking for a while.
195 		 */
196 		p2 = allproc.lh_first;
197 again:
198 		for (; p2 != 0; p2 = p2->p_list.le_next) {
199 			while (p2->p_pid == nextpid ||
200 			    p2->p_pgrp->pg_id == nextpid) {
201 				nextpid++;
202 				if (nextpid >= pidchecked)
203 					goto retry;
204 			}
205 			if (p2->p_pid > nextpid && pidchecked > p2->p_pid)
206 				pidchecked = p2->p_pid;
207 			if (p2->p_pgrp->pg_id > nextpid &&
208 			    pidchecked > p2->p_pgrp->pg_id)
209 				pidchecked = p2->p_pgrp->pg_id;
210 		}
211 		if (!doingzomb) {
212 			doingzomb = 1;
213 			p2 = zombproc.lh_first;
214 			goto again;
215 		}
216 	}
217 
218 	p2 = newproc;
219 	p2->p_stat = SIDL;			/* protect against others */
220 	p2->p_pid = nextpid;
221 	LIST_INSERT_HEAD(&allproc, p2, p_list);
222 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
223 
224 	/*
225 	 * Make a proc table entry for the new process.
226 	 * Start by zeroing the section of proc that is zero-initialized,
227 	 * then copy the section that is copied directly from the parent.
228 	 */
229 	bzero(&p2->p_startzero,
230 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
231 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
232 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
233 
234 	/*
235 	 * XXX: this should be done as part of the startzero above
236 	 */
237 	p2->p_vmspace = 0;		/* XXX */
238 
239 	/*
240 	 * Duplicate sub-structures as needed.
241 	 * Increase reference counts on shared objects.
242 	 * The p_stats and p_sigacts substructs are set in vm_fork.
243 	 */
244 	p2->p_flag = P_INMEM;
245 	if (p1->p_flag & P_PROFIL)
246 		startprofclock(p2);
247 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
248 	    M_SUBPROC, M_WAITOK);
249 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
250 	p2->p_cred->p_refcnt = 1;
251 	crhold(p1->p_ucred);
252 
253 	/* bump references to the text vnode (for procfs) */
254 	p2->p_textvp = p1->p_textvp;
255 	if (p2->p_textvp)
256 		VREF(p2->p_textvp);
257 
258 	if (flags & RFCFDG)
259 		p2->p_fd = fdinit(p1);
260 	else if (flags & RFFDG)
261 		p2->p_fd = fdcopy(p1);
262 	else
263 		p2->p_fd = fdshare(p1);
264 
265 	/*
266 	 * If p_limit is still copy-on-write, bump refcnt,
267 	 * otherwise get a copy that won't be modified.
268 	 * (If PL_SHAREMOD is clear, the structure is shared
269 	 * copy-on-write.)
270 	 */
271 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
272 		p2->p_limit = limcopy(p1->p_limit);
273 	else {
274 		p2->p_limit = p1->p_limit;
275 		p2->p_limit->p_refcnt++;
276 	}
277 
278 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
279 		p2->p_flag |= P_CONTROLT;
280 	if (flags & RFPPWAIT)
281 		p2->p_flag |= P_PPWAIT;
282 	LIST_INSERT_AFTER(p1, p2, p_pglist);
283 
284 	/*
285 	 * Attach the new process to its parent.
286 	 *
287 	 * If RFNOWAIT is set, the newly created process becomes a child
288 	 * of init.  This effectively disassociates the child from the
289 	 * parent.
290 	 */
291 	if (flags & RFNOWAIT)
292 		pptr = initproc;
293 	else
294 		pptr = p1;
295 	p2->p_pptr = pptr;
296 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
297 	LIST_INIT(&p2->p_children);
298 
299 #ifdef KTRACE
300 	/*
301 	 * Copy traceflag and tracefile if enabled.
302 	 * If not inherited, these were zeroed above.
303 	 */
304 	if (p1->p_traceflag&KTRFAC_INHERIT) {
305 		p2->p_traceflag = p1->p_traceflag;
306 		if ((p2->p_tracep = p1->p_tracep) != NULL)
307 			VREF(p2->p_tracep);
308 	}
309 #endif
310 
311 	/*
312 	 * set priority of child to be that of parent
313 	 */
314 	p2->p_estcpu = p1->p_estcpu;
315 
316 	/*
317 	 * This begins the section where we must prevent the parent
318 	 * from being swapped.
319 	 */
320 	p1->p_flag |= P_NOSWAP;
321 
322 	/*
323 	 * share as much address space as possible
324 	 * XXX this should probably go in vm_fork()
325 	 */
326 	if (flags & RFMEM)
327 		(void) vm_map_inherit(&p1->p_vmspace->vm_map,
328 		    VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS - MAXSSIZ,
329 		    VM_INHERIT_SHARE);
330 
331 	/*
332 	 * Set return values for child before vm_fork,
333 	 * so they can be copied to child stack.
334 	 * We return parent pid, and mark as child in retval[1].
335 	 * NOTE: the kernel stack may be at a different location in the child
336 	 * process, and thus addresses of automatic variables (including retval)
337 	 * may be invalid after vm_fork returns in the child process.
338 	 */
339 	retval[0] = p1->p_pid;
340 	retval[1] = 1;
341 	if (vm_fork(p1, p2)) {
342 		/*
343 		 * Child process.  Set start time and get to work.
344 		 */
345 		microtime(&runtime);
346 		(void) spl0();
347 		p2->p_stats->p_start = runtime;
348 		p2->p_acflag = AFORK;
349 		return (0);
350 	}
351 
352 	/*
353 	 * Both processes are set up, now check if any LKMs want
354 	 * to adjust anything.
355 	 *   What if they have an error? XXX
356 	 */
357 	while (ep) {
358 		(*ep->function)(p1, p2, flags);
359 		ep = ep->next;
360 	}
361 
362 	/*
363 	 * Make child runnable and add to run queue.
364 	 */
365 	(void) splhigh();
366 	p2->p_stat = SRUN;
367 	setrunqueue(p2);
368 	(void) spl0();
369 
370 	/*
371 	 * Now can be swapped.
372 	 */
373 	p1->p_flag &= ~P_NOSWAP;
374 
375 	/*
376 	 * Preserve synchronization semantics of vfork.  If waiting for
377 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
378 	 * proc (in case of exit).
379 	 */
380 	while (p2->p_flag & P_PPWAIT)
381 		tsleep(p1, PWAIT, "ppwait", 0);
382 
383 	/*
384 	 * Return child pid to parent process,
385 	 * marking us as parent via retval[1].
386 	 */
387 	retval[0] = p2->p_pid;
388 	retval[1] = 0;
389 	return (0);
390 }
391 
392 /*
393  * The next two functionms are general routines to handle adding/deleting
394  * items on the fork callout list.
395  *
396  * at_fork():
397  * Take the arguments given and put them onto the fork callout list,
398  * However first make sure that it's not already there.
399  * Returns 0 on success or a standard error number.
400  */
401 int
402 at_fork(forklist_fn function)
403 {
404 	fle_p ep;
405 
406 	/* let the programmer know if he's been stupid */
407 	if (rm_at_fork(function))
408 		printf("fork callout entry already present\n");
409 	ep = malloc(sizeof(*ep), M_TEMP, M_NOWAIT);
410 	if (ep == NULL)
411 		return (ENOMEM);
412 	ep->next = fork_list;
413 	ep->function = function;
414 	fork_list = ep;
415 	return (0);
416 }
417 
418 /*
419  * Scan the exit callout list for the given items and remove them.
420  * Returns the number of items removed.
421  * Theoretically this value can only be 0 or 1.
422  */
423 int
424 rm_at_fork(forklist_fn function)
425 {
426 	fle_p *epp, ep;
427 	int count;
428 
429 	count= 0;
430 	epp = &fork_list;
431 	ep = *epp;
432 	while (ep) {
433 		if (ep->function == function) {
434 			*epp = ep->next;
435 			free(ep, M_TEMP);
436 			count++;
437 		} else {
438 			epp = &ep->next;
439 		}
440 		ep = *epp;
441 	}
442 	return (count);
443 }
444 
445 
446