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