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