kern_fork.c revision 1.67 1 /* $NetBSD: kern_fork.c,v 1.67 2000/06/26 14:21:14 mrg 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.8 (Berkeley) 2/14/95
41 */
42
43 #include "opt_ktrace.h"
44 #include "opt_multiprocessor.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/map.h>
49 #include <sys/filedesc.h>
50 #include <sys/kernel.h>
51 #include <sys/malloc.h>
52 #include <sys/pool.h>
53 #include <sys/mount.h>
54 #include <sys/proc.h>
55 #include <sys/resourcevar.h>
56 #include <sys/vnode.h>
57 #include <sys/file.h>
58 #include <sys/acct.h>
59 #include <sys/ktrace.h>
60 #include <sys/vmmeter.h>
61 #include <sys/sched.h>
62 #include <sys/signalvar.h>
63
64 #include <sys/syscallargs.h>
65
66 #include <vm/vm.h>
67
68 #include <uvm/uvm_extern.h>
69
70 int nprocs = 1; /* process 0 */
71
72 /*ARGSUSED*/
73 int
74 sys_fork(p, v, retval)
75 struct proc *p;
76 void *v;
77 register_t *retval;
78 {
79
80 return (fork1(p, 0, SIGCHLD, NULL, 0, NULL, NULL, retval, NULL));
81 }
82
83 /*
84 * vfork(2) system call compatible with 4.4BSD (i.e. BSD with Mach VM).
85 * Address space is not shared, but parent is blocked until child exit.
86 */
87 /*ARGSUSED*/
88 int
89 sys_vfork(p, v, retval)
90 struct proc *p;
91 void *v;
92 register_t *retval;
93 {
94
95 return (fork1(p, FORK_PPWAIT, SIGCHLD, NULL, 0, NULL, NULL,
96 retval, NULL));
97 }
98
99 /*
100 * New vfork(2) system call for NetBSD, which implements original 3BSD vfork(2)
101 * semantics. Address space is shared, and parent is blocked until child exit.
102 */
103 /*ARGSUSED*/
104 int
105 sys___vfork14(p, v, retval)
106 struct proc *p;
107 void *v;
108 register_t *retval;
109 {
110
111 return (fork1(p, FORK_PPWAIT|FORK_SHAREVM, SIGCHLD, NULL, 0,
112 NULL, NULL, retval, NULL));
113 }
114
115 int
116 fork1(p1, flags, exitsig, stack, stacksize, func, arg, retval, rnewprocp)
117 struct proc *p1;
118 int flags;
119 int exitsig;
120 void *stack;
121 size_t stacksize;
122 void (*func) __P((void *));
123 void *arg;
124 register_t *retval;
125 struct proc **rnewprocp;
126 {
127 struct proc *p2;
128 uid_t uid;
129 struct proc *newproc;
130 int count, s;
131 vaddr_t uaddr;
132 static int nextpid, pidchecked = 0;
133
134 /*
135 * Although process entries are dynamically created, we still keep
136 * a global limit on the maximum number we will create. Don't allow
137 * a nonprivileged user to use the last process; don't let root
138 * exceed the limit. The variable nprocs is the current number of
139 * processes, maxproc is the limit.
140 */
141 uid = p1->p_cred->p_ruid;
142 if (__predict_false((nprocs >= maxproc - 1 && uid != 0) ||
143 nprocs >= maxproc)) {
144 tablefull("proc");
145 return (EAGAIN);
146 }
147
148 /*
149 * Increment the count of procs running with this uid. Don't allow
150 * a nonprivileged user to exceed their current limit.
151 */
152 count = chgproccnt(uid, 1);
153 if (__predict_false(uid != 0 && count >
154 p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
155 (void)chgproccnt(uid, -1);
156 return (EAGAIN);
157 }
158
159 /*
160 * Allocate virtual address space for the U-area now, while it
161 * is still easy to abort the fork operation if we're out of
162 * kernel virtual address space. The actual U-area pages will
163 * be allocated and wired in vm_fork().
164 */
165 uaddr = uvm_km_valloc(kernel_map, USPACE);
166 if (__predict_false(uaddr == 0)) {
167 (void)chgproccnt(uid, -1);
168 return (ENOMEM);
169 }
170
171 /*
172 * We are now committed to the fork. From here on, we may
173 * block on resources, but resource allocation may NOT fail.
174 */
175
176 /* Allocate new proc. */
177 newproc = pool_get(&proc_pool, PR_WAITOK);
178
179 /*
180 * BEGIN PID ALLOCATION.
181 */
182 s = proclist_lock_write();
183
184 /*
185 * Find an unused process ID. We remember a range of unused IDs
186 * ready to use (from nextpid+1 through pidchecked-1).
187 */
188 nextpid++;
189 retry:
190 /*
191 * If the process ID prototype has wrapped around,
192 * restart somewhat above 0, as the low-numbered procs
193 * tend to include daemons that don't exit.
194 */
195 if (nextpid >= PID_MAX) {
196 nextpid = 100;
197 pidchecked = 0;
198 }
199 if (nextpid >= pidchecked) {
200 const struct proclist_desc *pd;
201
202 pidchecked = PID_MAX;
203 /*
204 * Scan the process lists to check whether this pid
205 * is in use. Remember the lowest pid that's greater
206 * than nextpid, so we can avoid checking for a while.
207 */
208 pd = proclists;
209 again:
210 for (p2 = LIST_FIRST(pd->pd_list); p2 != 0;
211 p2 = LIST_NEXT(p2, p_list)) {
212 while (p2->p_pid == nextpid ||
213 p2->p_pgrp->pg_id == nextpid ||
214 p2->p_session->s_sid == nextpid) {
215 nextpid++;
216 if (nextpid >= pidchecked)
217 goto retry;
218 }
219 if (p2->p_pid > nextpid && pidchecked > p2->p_pid)
220 pidchecked = p2->p_pid;
221
222 if (p2->p_pgrp->pg_id > nextpid &&
223 pidchecked > p2->p_pgrp->pg_id)
224 pidchecked = p2->p_pgrp->pg_id;
225
226 if (p2->p_session->s_sid > nextpid &&
227 pidchecked > p2->p_session->s_sid)
228 pidchecked = p2->p_session->s_sid;
229 }
230
231 /*
232 * If there's another list, scan it. If we have checked
233 * them all, we've found one!
234 */
235 pd++;
236 if (pd->pd_list != NULL)
237 goto again;
238 }
239
240 nprocs++;
241 p2 = newproc;
242
243 /* Record the pid we've allocated. */
244 p2->p_pid = nextpid;
245
246 /* Record the signal to be delivered to the parent on exit. */
247 p2->p_exitsig = exitsig;
248
249 /*
250 * Put the proc on allproc before unlocking PID allocation
251 * so that waiters won't grab it as soon as we unlock.
252 */
253
254 p2->p_stat = SIDL; /* protect against others */
255 p2->p_forw = p2->p_back = NULL; /* shouldn't be necessary */
256
257 LIST_INSERT_HEAD(&allproc, p2, p_list);
258
259 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
260
261 /*
262 * END PID ALLOCATION.
263 */
264 proclist_unlock_write(s);
265
266 /*
267 * Make a proc table entry for the new process.
268 * Start by zeroing the section of proc that is zero-initialized,
269 * then copy the section that is copied directly from the parent.
270 */
271 memset(&p2->p_startzero, 0,
272 (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
273 memcpy(&p2->p_startcopy, &p1->p_startcopy,
274 (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
275
276 #if !defined(MULTIPROCESSOR)
277 /*
278 * In the single-processor case, all processes will always run
279 * on the same CPU. So, initialize the child's CPU to the parent's
280 * now. In the multiprocessor case, the child's CPU will be
281 * initialized in the low-level context switch code when the
282 * process runs.
283 */
284 p2->p_cpu = p1->p_cpu;
285 #endif /* ! MULTIPROCESSOR */
286
287 /*
288 * Duplicate sub-structures as needed.
289 * Increase reference counts on shared objects.
290 * The p_stats and p_sigacts substructs are set in vm_fork.
291 */
292 p2->p_flag = P_INMEM | (p1->p_flag & P_SUGID);
293 p2->p_emul = p1->p_emul;
294 if (p1->p_flag & P_PROFIL)
295 startprofclock(p2);
296 p2->p_cred = pool_get(&pcred_pool, PR_WAITOK);
297 memcpy(p2->p_cred, p1->p_cred, sizeof(*p2->p_cred));
298 p2->p_cred->p_refcnt = 1;
299 crhold(p1->p_ucred);
300
301 /* bump references to the text vnode (for procfs) */
302 p2->p_textvp = p1->p_textvp;
303 if (p2->p_textvp)
304 VREF(p2->p_textvp);
305
306 if (flags & FORK_SHAREFILES)
307 fdshare(p1, p2);
308 else
309 p2->p_fd = fdcopy(p1);
310
311 if (flags & FORK_SHARECWD)
312 cwdshare(p1, p2);
313 else
314 p2->p_cwdi = cwdinit(p1);
315
316 /*
317 * If p_limit is still copy-on-write, bump refcnt,
318 * otherwise get a copy that won't be modified.
319 * (If PL_SHAREMOD is clear, the structure is shared
320 * copy-on-write.)
321 */
322 if (p1->p_limit->p_lflags & PL_SHAREMOD)
323 p2->p_limit = limcopy(p1->p_limit);
324 else {
325 p2->p_limit = p1->p_limit;
326 p2->p_limit->p_refcnt++;
327 }
328
329 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
330 p2->p_flag |= P_CONTROLT;
331 if (flags & FORK_PPWAIT)
332 p2->p_flag |= P_PPWAIT;
333 LIST_INSERT_AFTER(p1, p2, p_pglist);
334 p2->p_pptr = p1;
335 LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
336 LIST_INIT(&p2->p_children);
337
338 callout_init(&p2->p_realit_ch);
339 callout_init(&p2->p_tsleep_ch);
340
341 #ifdef KTRACE
342 /*
343 * Copy traceflag and tracefile if enabled.
344 * If not inherited, these were zeroed above.
345 */
346 if (p1->p_traceflag&KTRFAC_INHERIT) {
347 p2->p_traceflag = p1->p_traceflag;
348 if ((p2->p_tracep = p1->p_tracep) != NULL)
349 ktradref(p2);
350 }
351 #endif
352 scheduler_fork_hook(p1, p2);
353
354 /*
355 * Create signal actions for the child process.
356 */
357 if (flags & FORK_SHARESIGS)
358 sigactsshare(p1, p2);
359 else
360 p2->p_sigacts = sigactsinit(p1);
361
362 /*
363 * This begins the section where we must prevent the parent
364 * from being swapped.
365 */
366 PHOLD(p1);
367
368 /*
369 * Finish creating the child process. It will return through a
370 * different path later.
371 */
372 p2->p_addr = (struct user *)uaddr;
373 uvm_fork(p1, p2, (flags & FORK_SHAREVM) ? TRUE : FALSE,
374 stack, stacksize,
375 (func != NULL) ? func : child_return,
376 (arg != NULL) ? arg : p2);
377
378 /*
379 * Make child runnable, set start time, and add to run queue.
380 */
381 s = splstatclock();
382 p2->p_stats->p_start = time;
383 p2->p_acflag = AFORK;
384 p2->p_stat = SRUN;
385 setrunqueue(p2);
386 splx(s);
387
388 /*
389 * Now can be swapped.
390 */
391 PRELE(p1);
392
393 /*
394 * Update stats now that we know the fork was successful.
395 */
396 uvmexp.forks++;
397 if (flags & FORK_PPWAIT)
398 uvmexp.forks_ppwait++;
399 if (flags & FORK_SHAREVM)
400 uvmexp.forks_sharevm++;
401
402 /*
403 * Pass a pointer to the new process to the caller.
404 */
405 if (rnewprocp != NULL)
406 *rnewprocp = p2;
407
408 /*
409 * Preserve synchronization semantics of vfork. If waiting for
410 * child to exec or exit, set P_PPWAIT on child, and sleep on our
411 * proc (in case of exit).
412 */
413 if (flags & FORK_PPWAIT)
414 while (p2->p_flag & P_PPWAIT)
415 tsleep(p1, PWAIT, "ppwait", 0);
416
417 /*
418 * Return child pid to parent process,
419 * marking us as parent via retval[1].
420 */
421 if (retval != NULL) {
422 retval[0] = p2->p_pid;
423 retval[1] = 0;
424 }
425 return (0);
426 }
427