FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_fork.c
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/sysctl.h>
50 #include <sys/malloc.h>
51 #include <sys/proc.h>
52 #include <sys/resourcevar.h>
53 #include <sys/vnode.h>
54 #include <sys/acct.h>
55 #include <sys/ktrace.h>
56 #include <sys/unistd.h>
57
58 #include <vm/vm.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_zone.h>
64
65 #include <machine/frame.h>
66 #include <sys/user.h>
67
68 #ifdef SMP
69 static int fast_vfork = 0; /* Doesn't work on SMP yet. */
70 #else
71 static int fast_vfork = 1;
72 #endif
73 SYSCTL_INT(_kern, OID_AUTO, fast_vfork, CTLFLAG_RW, &fast_vfork, 0, "");
74
75 /*
76 * These are the stuctures used to create a callout list for things to do
77 * when forking a process
78 */
79 typedef struct fork_list_element {
80 struct fork_list_element *next;
81 forklist_fn function;
82 } *fle_p;
83
84 static fle_p fork_list;
85
86 #ifndef _SYS_SYSPROTO_H_
87 struct fork_args {
88 int dummy;
89 };
90 #endif
91
92 /* ARGSUSED */
93 int
94 fork(p, uap)
95 struct proc *p;
96 struct fork_args *uap;
97 {
98
99 return (fork1(p, RFFDG | RFPROC));
100 }
101
102 /* ARGSUSED */
103 int
104 vfork(p, uap)
105 struct proc *p;
106 struct vfork_args *uap;
107 {
108
109 return (fork1(p, RFFDG | RFPROC | RFPPWAIT | (fast_vfork ? RFMEM : 0)));
110 }
111
112 /* ARGSUSED */
113 int
114 rfork(p, uap)
115 struct proc *p;
116 struct rfork_args *uap;
117 {
118
119 return (fork1(p, uap->flags));
120 }
121
122
123 int nprocs = 1; /* process 0 */
124 static int nextpid = 0;
125
126 int
127 fork1(p1, flags)
128 register struct proc *p1;
129 int flags;
130 {
131 register struct proc *p2, *pptr;
132 register uid_t uid;
133 struct proc *newproc;
134 int count;
135 static int pidchecked = 0;
136 fle_p ep ;
137
138 ep = fork_list;
139
140 if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
141 return (EINVAL);
142
143 #ifdef SMP
144 /*
145 * FATAL now, we cannot have the same PTD on both cpus, the PTD
146 * needs to move out of PTmap and be per-process, even for shared
147 * page table processes. Unfortunately, this means either removing
148 * PTD[] as a fixed virtual address, or move it to the per-cpu map
149 * area for SMP mode. Both cases require seperate management of
150 * the per-process-even-if-PTmap-is-shared PTD.
151 */
152 if (flags & RFMEM) {
153 printf("shared address space fork attempted: pid: %d\n",
154 p1->p_pid);
155 return (EOPNOTSUPP);
156 }
157 #endif
158
159 /*
160 * Here we don't create a new process, but we divorce
161 * certain parts of a process from itself.
162 */
163 if ((flags & RFPROC) == 0) {
164
165 /*
166 * Divorce the memory, if it is shared, essentially
167 * this changes shared memory amongst threads, into
168 * COW locally.
169 */
170 if ((flags & RFMEM) == 0) {
171 if (p1->p_vmspace->vm_refcnt > 1) {
172 vmspace_unshare(p1);
173 }
174 }
175
176 /*
177 * Close all file descriptors.
178 */
179 if (flags & RFCFDG) {
180 struct filedesc *fdtmp;
181 fdtmp = fdinit(p1);
182 fdfree(p1);
183 p1->p_fd = fdtmp;
184 }
185
186 /*
187 * Unshare file descriptors (from parent.)
188 */
189 if (flags & RFFDG) {
190 if (p1->p_fd->fd_refcnt > 1) {
191 struct filedesc *newfd;
192 newfd = fdcopy(p1);
193 fdfree(p1);
194 p1->p_fd = newfd;
195 }
196 }
197 return (0);
198 }
199
200 /*
201 * Although process entries are dynamically created, we still keep
202 * a global limit on the maximum number we will create. Don't allow
203 * a nonprivileged user to use the last process; don't let root
204 * exceed the limit. The variable nprocs is the current number of
205 * processes, maxproc is the limit.
206 */
207 uid = p1->p_cred->p_ruid;
208 if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
209 tablefull("proc");
210 return (EAGAIN);
211 }
212 /*
213 * Increment the nprocs resource before blocking can occur. There
214 * are hard-limits as to the number of processes that can run.
215 */
216 nprocs++;
217
218 /*
219 * Increment the count of procs running with this uid. Don't allow
220 * a nonprivileged user to exceed their current limit.
221 */
222 count = chgproccnt(uid, 1);
223 if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) {
224 (void)chgproccnt(uid, -1);
225 /*
226 * Back out the process count
227 */
228 nprocs--;
229 return (EAGAIN);
230 }
231
232 /* Allocate new proc. */
233 newproc = zalloc(proc_zone);
234
235 /*
236 * Setup linkage for kernel based threading
237 */
238 if((flags & RFTHREAD) != 0) {
239 newproc->p_peers = p1->p_peers;
240 p1->p_peers = newproc;
241 newproc->p_leader = p1->p_leader;
242 } else {
243 newproc->p_peers = 0;
244 newproc->p_leader = newproc;
245 }
246
247 newproc->p_wakeup = 0;
248
249 newproc->p_vmspace = NULL;
250
251 /*
252 * Find an unused process ID. We remember a range of unused IDs
253 * ready to use (from nextpid+1 through pidchecked-1).
254 */
255 nextpid++;
256 retry:
257 /*
258 * If the process ID prototype has wrapped around,
259 * restart somewhat above 0, as the low-numbered procs
260 * tend to include daemons that don't exit.
261 */
262 if (nextpid >= PID_MAX) {
263 nextpid = 100;
264 pidchecked = 0;
265 }
266 if (nextpid >= pidchecked) {
267 int doingzomb = 0;
268
269 pidchecked = PID_MAX;
270 /*
271 * Scan the active and zombie procs to check whether this pid
272 * is in use. Remember the lowest pid that's greater
273 * than nextpid, so we can avoid checking for a while.
274 */
275 p2 = allproc.lh_first;
276 again:
277 for (; p2 != 0; p2 = p2->p_list.le_next) {
278 while (p2->p_pid == nextpid ||
279 p2->p_pgrp->pg_id == nextpid ||
280 p2->p_session->s_sid == nextpid) {
281 nextpid++;
282 if (nextpid >= pidchecked)
283 goto retry;
284 }
285 if (p2->p_pid > nextpid && pidchecked > p2->p_pid)
286 pidchecked = p2->p_pid;
287 if (p2->p_pgrp->pg_id > nextpid &&
288 pidchecked > p2->p_pgrp->pg_id)
289 pidchecked = p2->p_pgrp->pg_id;
290 if (p2->p_session->s_sid > nextpid &&
291 pidchecked > p2->p_session->s_sid)
292 pidchecked = p2->p_session->s_sid;
293 }
294 if (!doingzomb) {
295 doingzomb = 1;
296 p2 = zombproc.lh_first;
297 goto again;
298 }
299 }
300
301 p2 = newproc;
302 p2->p_stat = SIDL; /* protect against others */
303 p2->p_pid = nextpid;
304 LIST_INSERT_HEAD(&allproc, p2, p_list);
305 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
306
307 /*
308 * Make a proc table entry for the new process.
309 * Start by zeroing the section of proc that is zero-initialized,
310 * then copy the section that is copied directly from the parent.
311 */
312 bzero(&p2->p_startzero,
313 (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
314 bcopy(&p1->p_startcopy, &p2->p_startcopy,
315 (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
316
317 p2->p_aioinfo = NULL;
318
319 /*
320 * Duplicate sub-structures as needed.
321 * Increase reference counts on shared objects.
322 * The p_stats and p_sigacts substructs are set in vm_fork.
323 */
324 p2->p_flag = P_INMEM;
325 if (p1->p_flag & P_PROFIL)
326 startprofclock(p2);
327 MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
328 M_SUBPROC, M_WAITOK);
329 bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
330 p2->p_cred->p_refcnt = 1;
331 crhold(p1->p_ucred);
332
333 if (flags & RFSIGSHARE) {
334 p2->p_procsig = p1->p_procsig;
335 p2->p_procsig->ps_refcnt++;
336 if (p1->p_sigacts == &p1->p_addr->u_sigacts) {
337 struct sigacts *newsigacts;
338 int s;
339
340 if (p2->p_procsig->ps_refcnt != 2)
341 printf ("PID:%d Creating shared sigacts with procsig->ps_refcnt %d\n",
342 p2->p_pid, p2->p_procsig->ps_refcnt);
343 /* Create the shared sigacts structure */
344 MALLOC (newsigacts, struct sigacts *, sizeof (struct sigacts),
345 M_SUBPROC, M_WAITOK);
346 s = splhigh();
347 /* Set p_sigacts to the new shared structure. Note that this
348 * is updating p1->p_sigacts at the same time, since p_sigacts
349 * is just a pointer to the shared p_procsig->ps_sigacts.
350 */
351 p2->p_sigacts = newsigacts;
352 /* Copy in the values from the u area */
353 *p2->p_sigacts = p1->p_addr->u_sigacts;
354 splx (s);
355 }
356 } else {
357 MALLOC (p2->p_procsig, struct procsig *, sizeof(struct procsig),
358 M_SUBPROC, M_WAITOK);
359 bcopy(&p1->p_procsig->ps_begincopy, &p2->p_procsig->ps_begincopy,
360 (unsigned)&p1->p_procsig->ps_endcopy -
361 (unsigned)&p1->p_procsig->ps_begincopy);
362 p2->p_procsig->ps_refcnt = 1;
363 /* Note that we fill in the values of sigacts in vm_fork */
364 p2->p_sigacts = NULL;
365 }
366 if (flags & RFLINUXTHPN)
367 p2->p_sigparent = SIGUSR1;
368 else
369 p2->p_sigparent = SIGCHLD;
370
371 /* bump references to the text vnode (for procfs) */
372 p2->p_textvp = p1->p_textvp;
373 if (p2->p_textvp)
374 VREF(p2->p_textvp);
375
376 if (flags & RFCFDG)
377 p2->p_fd = fdinit(p1);
378 else if (flags & RFFDG)
379 p2->p_fd = fdcopy(p1);
380 else
381 p2->p_fd = fdshare(p1);
382
383 /*
384 * If p_limit is still copy-on-write, bump refcnt,
385 * otherwise get a copy that won't be modified.
386 * (If PL_SHAREMOD is clear, the structure is shared
387 * copy-on-write.)
388 */
389 if (p1->p_limit->p_lflags & PL_SHAREMOD)
390 p2->p_limit = limcopy(p1->p_limit);
391 else {
392 p2->p_limit = p1->p_limit;
393 p2->p_limit->p_refcnt++;
394 }
395
396 /*
397 * Preserve some more flags in subprocess. P_PROFIL has already
398 * been preserved.
399 */
400 p2->p_flag |= p1->p_flag & P_SUGID;
401 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
402 p2->p_flag |= P_CONTROLT;
403 if (flags & RFPPWAIT)
404 p2->p_flag |= P_PPWAIT;
405
406 LIST_INSERT_AFTER(p1, p2, p_pglist);
407
408 /*
409 * Attach the new process to its parent.
410 *
411 * If RFNOWAIT is set, the newly created process becomes a child
412 * of init. This effectively disassociates the child from the
413 * parent.
414 */
415 if (flags & RFNOWAIT)
416 pptr = initproc;
417 else
418 pptr = p1;
419 p2->p_pptr = pptr;
420 LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
421 LIST_INIT(&p2->p_children);
422
423 #ifdef KTRACE
424 /*
425 * Copy traceflag and tracefile if enabled.
426 * If not inherited, these were zeroed above.
427 */
428 if (p1->p_traceflag&KTRFAC_INHERIT) {
429 p2->p_traceflag = p1->p_traceflag;
430 if ((p2->p_tracep = p1->p_tracep) != NULL)
431 VREF(p2->p_tracep);
432 }
433 #endif
434
435 /*
436 * set priority of child to be that of parent
437 */
438 p2->p_estcpu = p1->p_estcpu;
439
440 /*
441 * This begins the section where we must prevent the parent
442 * from being swapped.
443 */
444 p1->p_flag |= P_NOSWAP;
445
446 /*
447 * Finish creating the child process. It will return via a different
448 * execution path later. (ie: directly into user mode)
449 */
450 vm_fork(p1, p2, flags);
451
452 /*
453 * Both processes are set up, now check if any LKMs want
454 * to adjust anything.
455 * What if they have an error? XXX
456 */
457 while (ep) {
458 (*ep->function)(p1, p2, flags);
459 ep = ep->next;
460 }
461
462 /*
463 * Make child runnable and add to run queue.
464 */
465 microtime(&(p2->p_stats->p_start));
466 p2->p_acflag = AFORK;
467 (void) splhigh();
468 p2->p_stat = SRUN;
469 setrunqueue(p2);
470 (void) spl0();
471
472 /*
473 * Now can be swapped.
474 */
475 p1->p_flag &= ~P_NOSWAP;
476
477 /*
478 * Preserve synchronization semantics of vfork. If waiting for
479 * child to exec or exit, set P_PPWAIT on child, and sleep on our
480 * proc (in case of exit).
481 */
482 while (p2->p_flag & P_PPWAIT)
483 tsleep(p1, PWAIT, "ppwait", 0);
484
485 /*
486 * Return child pid to parent process,
487 * marking us as parent via p1->p_retval[1].
488 */
489 p1->p_retval[0] = p2->p_pid;
490 p1->p_retval[1] = 0;
491 return (0);
492 }
493
494 /*
495 * The next two functionms are general routines to handle adding/deleting
496 * items on the fork callout list.
497 *
498 * at_fork():
499 * Take the arguments given and put them onto the fork callout list,
500 * However first make sure that it's not already there.
501 * Returns 0 on success or a standard error number.
502 */
503 int
504 at_fork(function)
505 forklist_fn function;
506 {
507 fle_p ep;
508
509 /* let the programmer know if he's been stupid */
510 if (rm_at_fork(function))
511 printf("fork callout entry already present\n");
512 ep = malloc(sizeof(*ep), M_TEMP, M_NOWAIT);
513 if (ep == NULL)
514 return (ENOMEM);
515 ep->next = fork_list;
516 ep->function = function;
517 fork_list = ep;
518 return (0);
519 }
520
521 /*
522 * Scan the exit callout list for the given items and remove them.
523 * Returns the number of items removed.
524 * Theoretically this value can only be 0 or 1.
525 */
526 int
527 rm_at_fork(function)
528 forklist_fn function;
529 {
530 fle_p *epp, ep;
531 int count;
532
533 count= 0;
534 epp = &fork_list;
535 ep = *epp;
536 while (ep) {
537 if (ep->function == function) {
538 *epp = ep->next;
539 free(ep, M_TEMP);
540 count++;
541 } else {
542 epp = &ep->next;
543 }
544 ep = *epp;
545 }
546 return (count);
547 }
Cache object: 1c232f9ff4d0491e6fbc4e1b588e603f
|