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