Deleted Added
full compact
kern_fork.c (113874) kern_fork.c (114293)
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
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: head/sys/kern/kern_fork.c 113874 2003-04-22 20:54:04Z jhb $
39 * $FreeBSD: head/sys/kern/kern_fork.c 114293 2003-04-30 12:57:40Z markm $
40 */
41
42#include "opt_ktrace.h"
43#include "opt_mac.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/sysproto.h>
48#include <sys/eventhandler.h>
49#include <sys/filedesc.h>
50#include <sys/kernel.h>
51#include <sys/sysctl.h>
52#include <sys/lock.h>
53#include <sys/malloc.h>
54#include <sys/mutex.h>
55#include <sys/proc.h>
56#include <sys/pioctl.h>
57#include <sys/resourcevar.h>
58#include <sys/sched.h>
59#include <sys/syscall.h>
60#include <sys/vnode.h>
61#include <sys/acct.h>
62#include <sys/mac.h>
63#include <sys/ktr.h>
64#include <sys/ktrace.h>
65#include <sys/kthread.h>
66#include <sys/unistd.h>
67#include <sys/jail.h>
68#include <sys/sx.h>
69
70#include <vm/vm.h>
71#include <vm/pmap.h>
72#include <vm/vm_map.h>
73#include <vm/vm_extern.h>
74#include <vm/uma.h>
75
76#include <sys/vmmeter.h>
77#include <sys/user.h>
78#include <machine/critical.h>
79
80#ifndef _SYS_SYSPROTO_H_
81struct fork_args {
82 int dummy;
83};
84#endif
85
40 */
41
42#include "opt_ktrace.h"
43#include "opt_mac.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/sysproto.h>
48#include <sys/eventhandler.h>
49#include <sys/filedesc.h>
50#include <sys/kernel.h>
51#include <sys/sysctl.h>
52#include <sys/lock.h>
53#include <sys/malloc.h>
54#include <sys/mutex.h>
55#include <sys/proc.h>
56#include <sys/pioctl.h>
57#include <sys/resourcevar.h>
58#include <sys/sched.h>
59#include <sys/syscall.h>
60#include <sys/vnode.h>
61#include <sys/acct.h>
62#include <sys/mac.h>
63#include <sys/ktr.h>
64#include <sys/ktrace.h>
65#include <sys/kthread.h>
66#include <sys/unistd.h>
67#include <sys/jail.h>
68#include <sys/sx.h>
69
70#include <vm/vm.h>
71#include <vm/pmap.h>
72#include <vm/vm_map.h>
73#include <vm/vm_extern.h>
74#include <vm/uma.h>
75
76#include <sys/vmmeter.h>
77#include <sys/user.h>
78#include <machine/critical.h>
79
80#ifndef _SYS_SYSPROTO_H_
81struct fork_args {
82 int dummy;
83};
84#endif
85
86int forksleep; /* Place for fork1() to sleep on. */
86static int forksleep; /* Place for fork1() to sleep on. */
87
88/*
89 * MPSAFE
90 */
91/* ARGSUSED */
92int
93fork(td, uap)
94 struct thread *td;
95 struct fork_args *uap;
96{
97 int error;
98 struct proc *p2;
99
100 error = fork1(td, RFFDG | RFPROC, 0, &p2);
101 if (error == 0) {
102 td->td_retval[0] = p2->p_pid;
103 td->td_retval[1] = 0;
104 }
105 return error;
106}
107
108/*
109 * MPSAFE
110 */
111/* ARGSUSED */
112int
113vfork(td, uap)
114 struct thread *td;
115 struct vfork_args *uap;
116{
117 int error;
118 struct proc *p2;
119
120 error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
121 if (error == 0) {
122 td->td_retval[0] = p2->p_pid;
123 td->td_retval[1] = 0;
124 }
125 return error;
126}
127
128/*
129 * MPSAFE
130 */
131int
132rfork(td, uap)
133 struct thread *td;
134 struct rfork_args *uap;
135{
136 int error;
137 struct proc *p2;
138
139 /* Don't allow kernel only flags. */
140 if ((uap->flags & RFKERNELONLY) != 0)
141 return (EINVAL);
142 /*
143 * Don't allow sharing of file descriptor table unless
144 * RFTHREAD flag is supplied
145 */
146 if ((uap->flags & (RFPROC | RFTHREAD | RFFDG | RFCFDG)) ==
147 RFPROC)
148 return(EINVAL);
149 error = fork1(td, uap->flags, 0, &p2);
150 if (error == 0) {
151 td->td_retval[0] = p2 ? p2->p_pid : 0;
152 td->td_retval[1] = 0;
153 }
154 return error;
155}
156
157
158int nprocs = 1; /* process 0 */
159int lastpid = 0;
160SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
161 "Last used PID");
162
163/*
164 * Random component to lastpid generation. We mix in a random factor to make
165 * it a little harder to predict. We sanity check the modulus value to avoid
166 * doing it in critical paths. Don't let it be too small or we pointlessly
167 * waste randomness entropy, and don't let it be impossibly large. Using a
168 * modulus that is too big causes a LOT more process table scans and slows
169 * down fork processing as the pidchecked caching is defeated.
170 */
171static int randompid = 0;
172
173static int
174sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
175{
176 int error, pid;
177
178 sysctl_wire_old_buffer(req, sizeof(int));
179 sx_xlock(&allproc_lock);
180 pid = randompid;
181 error = sysctl_handle_int(oidp, &pid, 0, req);
182 if (error == 0 && req->newptr != NULL) {
183 if (pid < 0 || pid > PID_MAX - 100) /* out of range */
184 pid = PID_MAX - 100;
185 else if (pid < 2) /* NOP */
186 pid = 0;
187 else if (pid < 100) /* Make it reasonable */
188 pid = 100;
189 randompid = pid;
190 }
191 sx_xunlock(&allproc_lock);
192 return (error);
193}
194
195SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
196 0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
197
198int
199fork1(td, flags, pages, procp)
200 struct thread *td; /* parent proc */
201 int flags;
202 int pages;
203 struct proc **procp; /* child proc */
204{
205 struct proc *p2, *pptr;
206 uid_t uid;
207 struct proc *newproc;
208 int trypid;
209 int ok;
210 static int pidchecked = 0;
211 struct filedesc *fd;
212 struct proc *p1 = td->td_proc;
213 struct thread *td2;
214 struct kse *ke2;
215 struct ksegrp *kg2;
216 struct sigacts *newsigacts;
217 struct procsig *newprocsig;
218 int error;
219
220 /* Can't copy and clear */
221 if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
222 return (EINVAL);
223
224 mtx_lock(&Giant);
225 /*
226 * Here we don't create a new process, but we divorce
227 * certain parts of a process from itself.
228 */
229 if ((flags & RFPROC) == 0) {
230 vm_forkproc(td, NULL, NULL, flags);
231
232 /*
233 * Close all file descriptors.
234 */
235 if (flags & RFCFDG) {
236 struct filedesc *fdtmp;
237 fdtmp = fdinit(td->td_proc->p_fd);
238 fdfree(td);
239 p1->p_fd = fdtmp;
240 }
241
242 /*
243 * Unshare file descriptors (from parent.)
244 */
245 if (flags & RFFDG) {
246 FILEDESC_LOCK(p1->p_fd);
247 if (p1->p_fd->fd_refcnt > 1) {
248 struct filedesc *newfd;
249
250 newfd = fdcopy(td->td_proc->p_fd);
251 FILEDESC_UNLOCK(p1->p_fd);
252 fdfree(td);
253 p1->p_fd = newfd;
254 } else
255 FILEDESC_UNLOCK(p1->p_fd);
256 }
257 mtx_unlock(&Giant);
258 *procp = NULL;
259 return (0);
260 }
261
262 /*
263 * Note 1:1 allows for forking with one thread coming out on the
264 * other side with the expectation that the process is about to
265 * exec.
266 */
267 if (p1->p_flag & P_THREADED) {
268 /*
269 * Idle the other threads for a second.
270 * Since the user space is copied, it must remain stable.
271 * In addition, all threads (from the user perspective)
272 * need to either be suspended or in the kernel,
273 * where they will try restart in the parent and will
274 * be aborted in the child.
275 */
276 PROC_LOCK(p1);
277 if (thread_single(SINGLE_NO_EXIT)) {
278 /* Abort.. someone else is single threading before us */
279 PROC_UNLOCK(p1);
280 mtx_unlock(&Giant);
281 return (ERESTART);
282 }
283 PROC_UNLOCK(p1);
284 /*
285 * All other activity in this process
286 * is now suspended at the user boundary,
287 * (or other safe places if we think of any).
288 */
289 }
290
291 /* Allocate new proc. */
292 newproc = uma_zalloc(proc_zone, M_WAITOK);
293#ifdef MAC
294 mac_init_proc(newproc);
295#endif
296
297 /*
298 * Although process entries are dynamically created, we still keep
299 * a global limit on the maximum number we will create. Don't allow
300 * a nonprivileged user to use the last ten processes; don't let root
301 * exceed the limit. The variable nprocs is the current number of
302 * processes, maxproc is the limit.
303 */
304 sx_xlock(&allproc_lock);
305 uid = td->td_ucred->cr_ruid;
306 if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) {
307 error = EAGAIN;
308 goto fail;
309 }
310
311 /*
312 * Increment the count of procs running with this uid. Don't allow
313 * a nonprivileged user to exceed their current limit.
314 */
315 PROC_LOCK(p1);
316 ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
317 (uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
318 PROC_UNLOCK(p1);
319 if (!ok) {
320 error = EAGAIN;
321 goto fail;
322 }
323
324 /*
325 * Increment the nprocs resource before blocking can occur. There
326 * are hard-limits as to the number of processes that can run.
327 */
328 nprocs++;
329
330 /*
331 * Find an unused process ID. We remember a range of unused IDs
332 * ready to use (from lastpid+1 through pidchecked-1).
333 *
334 * If RFHIGHPID is set (used during system boot), do not allocate
335 * low-numbered pids.
336 */
337 trypid = lastpid + 1;
338 if (flags & RFHIGHPID) {
339 if (trypid < 10) {
340 trypid = 10;
341 }
342 } else {
343 if (randompid)
344 trypid += arc4random() % randompid;
345 }
346retry:
347 /*
348 * If the process ID prototype has wrapped around,
349 * restart somewhat above 0, as the low-numbered procs
350 * tend to include daemons that don't exit.
351 */
352 if (trypid >= PID_MAX) {
353 trypid = trypid % PID_MAX;
354 if (trypid < 100)
355 trypid += 100;
356 pidchecked = 0;
357 }
358 if (trypid >= pidchecked) {
359 int doingzomb = 0;
360
361 pidchecked = PID_MAX;
362 /*
363 * Scan the active and zombie procs to check whether this pid
364 * is in use. Remember the lowest pid that's greater
365 * than trypid, so we can avoid checking for a while.
366 */
367 p2 = LIST_FIRST(&allproc);
368again:
369 for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
370 PROC_LOCK(p2);
371 while (p2->p_pid == trypid ||
372 p2->p_pgrp->pg_id == trypid ||
373 p2->p_session->s_sid == trypid) {
374 trypid++;
375 if (trypid >= pidchecked) {
376 PROC_UNLOCK(p2);
377 goto retry;
378 }
379 }
380 if (p2->p_pid > trypid && pidchecked > p2->p_pid)
381 pidchecked = p2->p_pid;
382 if (p2->p_pgrp->pg_id > trypid &&
383 pidchecked > p2->p_pgrp->pg_id)
384 pidchecked = p2->p_pgrp->pg_id;
385 if (p2->p_session->s_sid > trypid &&
386 pidchecked > p2->p_session->s_sid)
387 pidchecked = p2->p_session->s_sid;
388 PROC_UNLOCK(p2);
389 }
390 if (!doingzomb) {
391 doingzomb = 1;
392 p2 = LIST_FIRST(&zombproc);
393 goto again;
394 }
395 }
396
397 /*
398 * RFHIGHPID does not mess with the lastpid counter during boot.
399 */
400 if (flags & RFHIGHPID)
401 pidchecked = 0;
402 else
403 lastpid = trypid;
404
405 p2 = newproc;
406 p2->p_state = PRS_NEW; /* protect against others */
407 p2->p_pid = trypid;
408 LIST_INSERT_HEAD(&allproc, p2, p_list);
409 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
410 sx_xunlock(&allproc_lock);
411
412 /*
413 * Malloc things while we don't hold any locks.
414 */
415 if (flags & RFSIGSHARE) {
416 MALLOC(newsigacts, struct sigacts *,
417 sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
418 newprocsig = NULL;
419 } else {
420 newsigacts = NULL;
421 MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
422 M_SUBPROC, M_WAITOK);
423 }
424
425 /*
426 * Copy filedesc.
427 * XXX: This is busted. fd*() need to not take proc
428 * arguments or something.
429 */
430 if (flags & RFCFDG)
431 fd = fdinit(td->td_proc->p_fd);
432 else if (flags & RFFDG) {
433 FILEDESC_LOCK(p1->p_fd);
434 fd = fdcopy(td->td_proc->p_fd);
435 FILEDESC_UNLOCK(p1->p_fd);
436 } else
437 fd = fdshare(p1->p_fd);
438
439 /*
440 * Make a proc table entry for the new process.
441 * Start by zeroing the section of proc that is zero-initialized,
442 * then copy the section that is copied directly from the parent.
443 */
444 td2 = FIRST_THREAD_IN_PROC(p2);
445 kg2 = FIRST_KSEGRP_IN_PROC(p2);
446 ke2 = FIRST_KSE_IN_KSEGRP(kg2);
447
448 /* Allocate and switch to an alternate kstack if specified */
449 if (pages != 0)
450 pmap_new_altkstack(td2, pages);
451
452#define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
453
454 bzero(&p2->p_startzero,
455 (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
456 bzero(&ke2->ke_startzero,
457 (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
458 bzero(&td2->td_startzero,
459 (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
460 bzero(&kg2->kg_startzero,
461 (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
462
463 mtx_init(&p2->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
464 PROC_LOCK(p2);
465 PROC_LOCK(p1);
466
467 bcopy(&p1->p_startcopy, &p2->p_startcopy,
468 (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
469 bcopy(&td->td_startcopy, &td2->td_startcopy,
470 (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
471 bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
472 (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
473#undef RANGEOF
474
475 /* Set up the thread as an active thread (as if runnable). */
476 ke2->ke_state = KES_THREAD;
477 ke2->ke_thread = td2;
478 td2->td_kse = ke2;
479
480 /*
481 * Duplicate sub-structures as needed.
482 * Increase reference counts on shared objects.
483 * The p_stats and p_sigacts substructs are set in vm_forkproc.
484 */
485 p2->p_flag = 0;
486 if (p1->p_flag & P_PROFIL)
487 startprofclock(p2);
488 mtx_lock_spin(&sched_lock);
489 p2->p_sflag = PS_INMEM;
490 /*
491 * Allow the scheduler to adjust the priority of the child and
492 * parent while we hold the sched_lock.
493 */
494 sched_fork(p1, p2);
495
496 mtx_unlock_spin(&sched_lock);
497 p2->p_ucred = crhold(td->td_ucred);
498 td2->td_ucred = crhold(p2->p_ucred); /* XXXKSE */
499
500 pargs_hold(p2->p_args);
501
502 if (flags & RFSIGSHARE) {
503 p2->p_procsig = p1->p_procsig;
504 p2->p_procsig->ps_refcnt++;
505 if (p1->p_sigacts == &p1->p_uarea->u_sigacts) {
506 /*
507 * Set p_sigacts to the new shared structure.
508 * Note that this is updating p1->p_sigacts at the
509 * same time, since p_sigacts is just a pointer to
510 * the shared p_procsig->ps_sigacts.
511 */
512 p2->p_sigacts = newsigacts;
513 newsigacts = NULL;
514 *p2->p_sigacts = p1->p_uarea->u_sigacts;
515 }
516 } else {
517 p2->p_procsig = newprocsig;
518 newprocsig = NULL;
519 bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
520 p2->p_procsig->ps_refcnt = 1;
521 p2->p_sigacts = NULL; /* finished in vm_forkproc() */
522 }
523 if (flags & RFLINUXTHPN)
524 p2->p_sigparent = SIGUSR1;
525 else
526 p2->p_sigparent = SIGCHLD;
527
528 /* Bump references to the text vnode (for procfs) */
529 p2->p_textvp = p1->p_textvp;
530 if (p2->p_textvp)
531 VREF(p2->p_textvp);
532 p2->p_fd = fd;
533 PROC_UNLOCK(p1);
534 PROC_UNLOCK(p2);
535
536 /*
537 * p_limit is copy-on-write, bump refcnt,
538 */
539 p2->p_limit = p1->p_limit;
540 p2->p_limit->p_refcnt++;
541
542 /*
543 * Setup linkage for kernel based threading
544 */
545 if((flags & RFTHREAD) != 0) {
546 mtx_lock(&ppeers_lock);
547 p2->p_peers = p1->p_peers;
548 p1->p_peers = p2;
549 p2->p_leader = p1->p_leader;
550 mtx_unlock(&ppeers_lock);
551 PROC_LOCK(p1->p_leader);
552 if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
553 PROC_UNLOCK(p1->p_leader);
554 /*
555 * The task leader is exiting, so process p1 is
556 * going to be killed shortly. Since p1 obviously
557 * isn't dead yet, we know that the leader is either
558 * sending SIGKILL's to all the processes in this
559 * task or is sleeping waiting for all the peers to
560 * exit. We let p1 complete the fork, but we need
561 * to go ahead and kill the new process p2 since
562 * the task leader may not get a chance to send
563 * SIGKILL to it. We leave it on the list so that
564 * the task leader will wait for this new process
565 * to commit suicide.
566 */
567 PROC_LOCK(p2);
568 psignal(p2, SIGKILL);
569 PROC_UNLOCK(p2);
570 } else
571 PROC_UNLOCK(p1->p_leader);
572 } else {
573 p2->p_peers = NULL;
574 p2->p_leader = p2;
575 }
576
577 sx_xlock(&proctree_lock);
578 PGRP_LOCK(p1->p_pgrp);
579 PROC_LOCK(p2);
580 PROC_LOCK(p1);
581
582 /*
583 * Preserve some more flags in subprocess. P_PROFIL has already
584 * been preserved.
585 */
586 p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
587 SESS_LOCK(p1->p_session);
588 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
589 p2->p_flag |= P_CONTROLT;
590 SESS_UNLOCK(p1->p_session);
591 if (flags & RFPPWAIT)
592 p2->p_flag |= P_PPWAIT;
593
594 LIST_INSERT_AFTER(p1, p2, p_pglist);
595 PGRP_UNLOCK(p1->p_pgrp);
596 LIST_INIT(&p2->p_children);
597
598 callout_init(&p2->p_itcallout, 1);
599
600#ifdef KTRACE
601 /*
602 * Copy traceflag and tracefile if enabled.
603 */
604 mtx_lock(&ktrace_mtx);
605 KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
606 if (p1->p_traceflag & KTRFAC_INHERIT) {
607 p2->p_traceflag = p1->p_traceflag;
608 if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
609 VREF(p2->p_tracevp);
610 KASSERT(p1->p_tracecred != NULL,
611 ("ktrace vnode with no cred"));
612 p2->p_tracecred = crhold(p1->p_tracecred);
613 }
614 }
615 mtx_unlock(&ktrace_mtx);
616#endif
617
618 /*
619 * If PF_FORK is set, the child process inherits the
620 * procfs ioctl flags from its parent.
621 */
622 if (p1->p_pfsflags & PF_FORK) {
623 p2->p_stops = p1->p_stops;
624 p2->p_pfsflags = p1->p_pfsflags;
625 }
626
627 /*
628 * This begins the section where we must prevent the parent
629 * from being swapped.
630 */
631 _PHOLD(p1);
632 PROC_UNLOCK(p1);
633
634 /*
635 * Attach the new process to its parent.
636 *
637 * If RFNOWAIT is set, the newly created process becomes a child
638 * of init. This effectively disassociates the child from the
639 * parent.
640 */
641 if (flags & RFNOWAIT)
642 pptr = initproc;
643 else
644 pptr = p1;
645 p2->p_pptr = pptr;
646 LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
647 sx_xunlock(&proctree_lock);
648
649 /* Inform accounting that we have forked. */
650 p2->p_acflag = AFORK;
651 PROC_UNLOCK(p2);
652
653 KASSERT(newprocsig == NULL, ("unused newprocsig"));
654 if (newsigacts != NULL)
655 FREE(newsigacts, M_SUBPROC);
656 /*
657 * Finish creating the child process. It will return via a different
658 * execution path later. (ie: directly into user mode)
659 */
660 vm_forkproc(td, p2, td2, flags);
661
662 if (flags == (RFFDG | RFPROC)) {
663 cnt.v_forks++;
664 cnt.v_forkpages += p2->p_vmspace->vm_dsize +
665 p2->p_vmspace->vm_ssize;
666 } else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
667 cnt.v_vforks++;
668 cnt.v_vforkpages += p2->p_vmspace->vm_dsize +
669 p2->p_vmspace->vm_ssize;
670 } else if (p1 == &proc0) {
671 cnt.v_kthreads++;
672 cnt.v_kthreadpages += p2->p_vmspace->vm_dsize +
673 p2->p_vmspace->vm_ssize;
674 } else {
675 cnt.v_rforks++;
676 cnt.v_rforkpages += p2->p_vmspace->vm_dsize +
677 p2->p_vmspace->vm_ssize;
678 }
679
680 /*
681 * Both processes are set up, now check if any loadable modules want
682 * to adjust anything.
683 * What if they have an error? XXX
684 */
685 EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
686
687 /*
688 * If RFSTOPPED not requested, make child runnable and add to
689 * run queue.
690 */
691 microtime(&(p2->p_stats->p_start));
692 if ((flags & RFSTOPPED) == 0) {
693 mtx_lock_spin(&sched_lock);
694 p2->p_state = PRS_NORMAL;
695 TD_SET_CAN_RUN(td2);
696 setrunqueue(td2);
697 mtx_unlock_spin(&sched_lock);
698 }
699
700 /*
701 * Now can be swapped.
702 */
703 PROC_LOCK(p1);
704 _PRELE(p1);
705
706 /*
707 * tell any interested parties about the new process
708 */
709 KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
710 PROC_UNLOCK(p1);
711
712 /*
713 * Preserve synchronization semantics of vfork. If waiting for
714 * child to exec or exit, set P_PPWAIT on child, and sleep on our
715 * proc (in case of exit).
716 */
717 PROC_LOCK(p2);
718 while (p2->p_flag & P_PPWAIT)
719 msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
720 PROC_UNLOCK(p2);
721
722 /*
723 * If other threads are waiting, let them continue now
724 */
725 if (p1->p_flag & P_THREADED) {
726 PROC_LOCK(p1);
727 thread_single_end();
728 PROC_UNLOCK(p1);
729 }
730
731 /*
732 * Return child proc pointer to parent.
733 */
734 mtx_unlock(&Giant);
735 *procp = p2;
736 return (0);
737fail:
738 sx_xunlock(&allproc_lock);
739 uma_zfree(proc_zone, newproc);
740 if (p1->p_flag & P_THREADED) {
741 PROC_LOCK(p1);
742 thread_single_end();
743 PROC_UNLOCK(p1);
744 }
745 tsleep(&forksleep, PUSER, "fork", hz / 2);
746 mtx_unlock(&Giant);
747 return (error);
748}
749
750/*
751 * Handle the return of a child process from fork1(). This function
752 * is called from the MD fork_trampoline() entry point.
753 */
754void
755fork_exit(callout, arg, frame)
756 void (*callout)(void *, struct trapframe *);
757 void *arg;
758 struct trapframe *frame;
759{
760 struct thread *td;
761 struct proc *p;
762
763 if ((td = PCPU_GET(deadthread))) {
764 PCPU_SET(deadthread, NULL);
765 thread_stash(td);
766 }
767 td = curthread;
768 p = td->td_proc;
769 td->td_oncpu = PCPU_GET(cpuid);
770 p->p_state = PRS_NORMAL;
771 /*
772 * Finish setting up thread glue. We need to initialize
773 * the thread into a td_critnest=1 state. Some platforms
774 * may have already partially or fully initialized td_critnest
775 * and/or td_md.md_savecrit (when applciable).
776 *
777 * see <arch>/<arch>/critical.c
778 */
779 sched_lock.mtx_lock = (uintptr_t)td;
780 sched_lock.mtx_recurse = 0;
781 cpu_critical_fork_exit();
782 CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
783 p->p_comm);
784 if (PCPU_GET(switchtime.sec) == 0)
785 binuptime(PCPU_PTR(switchtime));
786 PCPU_SET(switchticks, ticks);
787 mtx_unlock_spin(&sched_lock);
788
789 /*
790 * cpu_set_fork_handler intercepts this function call to
791 * have this call a non-return function to stay in kernel mode.
792 * initproc has its own fork handler, but it does return.
793 */
794 KASSERT(callout != NULL, ("NULL callout in fork_exit"));
795 callout(arg, frame);
796
797 /*
798 * Check if a kernel thread misbehaved and returned from its main
799 * function.
800 */
801 PROC_LOCK(p);
802 if (p->p_flag & P_KTHREAD) {
803 PROC_UNLOCK(p);
804 mtx_lock(&Giant);
805 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
806 p->p_comm, p->p_pid);
807 kthread_exit(0);
808 }
809 PROC_UNLOCK(p);
810#ifdef DIAGNOSTIC
811 cred_free_thread(td);
812#endif
813 mtx_assert(&Giant, MA_NOTOWNED);
814}
815
816/*
817 * Simplified back end of syscall(), used when returning from fork()
818 * directly into user mode. Giant is not held on entry, and must not
819 * be held on return. This function is passed in to fork_exit() as the
820 * first parameter and is called when returning to a new userland process.
821 */
822void
823fork_return(td, frame)
824 struct thread *td;
825 struct trapframe *frame;
826{
827
828 userret(td, frame, 0);
829#ifdef KTRACE
830 if (KTRPOINT(td, KTR_SYSRET))
831 ktrsysret(SYS_fork, 0, 0);
832#endif
833 mtx_assert(&Giant, MA_NOTOWNED);
834}
87
88/*
89 * MPSAFE
90 */
91/* ARGSUSED */
92int
93fork(td, uap)
94 struct thread *td;
95 struct fork_args *uap;
96{
97 int error;
98 struct proc *p2;
99
100 error = fork1(td, RFFDG | RFPROC, 0, &p2);
101 if (error == 0) {
102 td->td_retval[0] = p2->p_pid;
103 td->td_retval[1] = 0;
104 }
105 return error;
106}
107
108/*
109 * MPSAFE
110 */
111/* ARGSUSED */
112int
113vfork(td, uap)
114 struct thread *td;
115 struct vfork_args *uap;
116{
117 int error;
118 struct proc *p2;
119
120 error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
121 if (error == 0) {
122 td->td_retval[0] = p2->p_pid;
123 td->td_retval[1] = 0;
124 }
125 return error;
126}
127
128/*
129 * MPSAFE
130 */
131int
132rfork(td, uap)
133 struct thread *td;
134 struct rfork_args *uap;
135{
136 int error;
137 struct proc *p2;
138
139 /* Don't allow kernel only flags. */
140 if ((uap->flags & RFKERNELONLY) != 0)
141 return (EINVAL);
142 /*
143 * Don't allow sharing of file descriptor table unless
144 * RFTHREAD flag is supplied
145 */
146 if ((uap->flags & (RFPROC | RFTHREAD | RFFDG | RFCFDG)) ==
147 RFPROC)
148 return(EINVAL);
149 error = fork1(td, uap->flags, 0, &p2);
150 if (error == 0) {
151 td->td_retval[0] = p2 ? p2->p_pid : 0;
152 td->td_retval[1] = 0;
153 }
154 return error;
155}
156
157
158int nprocs = 1; /* process 0 */
159int lastpid = 0;
160SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
161 "Last used PID");
162
163/*
164 * Random component to lastpid generation. We mix in a random factor to make
165 * it a little harder to predict. We sanity check the modulus value to avoid
166 * doing it in critical paths. Don't let it be too small or we pointlessly
167 * waste randomness entropy, and don't let it be impossibly large. Using a
168 * modulus that is too big causes a LOT more process table scans and slows
169 * down fork processing as the pidchecked caching is defeated.
170 */
171static int randompid = 0;
172
173static int
174sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
175{
176 int error, pid;
177
178 sysctl_wire_old_buffer(req, sizeof(int));
179 sx_xlock(&allproc_lock);
180 pid = randompid;
181 error = sysctl_handle_int(oidp, &pid, 0, req);
182 if (error == 0 && req->newptr != NULL) {
183 if (pid < 0 || pid > PID_MAX - 100) /* out of range */
184 pid = PID_MAX - 100;
185 else if (pid < 2) /* NOP */
186 pid = 0;
187 else if (pid < 100) /* Make it reasonable */
188 pid = 100;
189 randompid = pid;
190 }
191 sx_xunlock(&allproc_lock);
192 return (error);
193}
194
195SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
196 0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
197
198int
199fork1(td, flags, pages, procp)
200 struct thread *td; /* parent proc */
201 int flags;
202 int pages;
203 struct proc **procp; /* child proc */
204{
205 struct proc *p2, *pptr;
206 uid_t uid;
207 struct proc *newproc;
208 int trypid;
209 int ok;
210 static int pidchecked = 0;
211 struct filedesc *fd;
212 struct proc *p1 = td->td_proc;
213 struct thread *td2;
214 struct kse *ke2;
215 struct ksegrp *kg2;
216 struct sigacts *newsigacts;
217 struct procsig *newprocsig;
218 int error;
219
220 /* Can't copy and clear */
221 if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
222 return (EINVAL);
223
224 mtx_lock(&Giant);
225 /*
226 * Here we don't create a new process, but we divorce
227 * certain parts of a process from itself.
228 */
229 if ((flags & RFPROC) == 0) {
230 vm_forkproc(td, NULL, NULL, flags);
231
232 /*
233 * Close all file descriptors.
234 */
235 if (flags & RFCFDG) {
236 struct filedesc *fdtmp;
237 fdtmp = fdinit(td->td_proc->p_fd);
238 fdfree(td);
239 p1->p_fd = fdtmp;
240 }
241
242 /*
243 * Unshare file descriptors (from parent.)
244 */
245 if (flags & RFFDG) {
246 FILEDESC_LOCK(p1->p_fd);
247 if (p1->p_fd->fd_refcnt > 1) {
248 struct filedesc *newfd;
249
250 newfd = fdcopy(td->td_proc->p_fd);
251 FILEDESC_UNLOCK(p1->p_fd);
252 fdfree(td);
253 p1->p_fd = newfd;
254 } else
255 FILEDESC_UNLOCK(p1->p_fd);
256 }
257 mtx_unlock(&Giant);
258 *procp = NULL;
259 return (0);
260 }
261
262 /*
263 * Note 1:1 allows for forking with one thread coming out on the
264 * other side with the expectation that the process is about to
265 * exec.
266 */
267 if (p1->p_flag & P_THREADED) {
268 /*
269 * Idle the other threads for a second.
270 * Since the user space is copied, it must remain stable.
271 * In addition, all threads (from the user perspective)
272 * need to either be suspended or in the kernel,
273 * where they will try restart in the parent and will
274 * be aborted in the child.
275 */
276 PROC_LOCK(p1);
277 if (thread_single(SINGLE_NO_EXIT)) {
278 /* Abort.. someone else is single threading before us */
279 PROC_UNLOCK(p1);
280 mtx_unlock(&Giant);
281 return (ERESTART);
282 }
283 PROC_UNLOCK(p1);
284 /*
285 * All other activity in this process
286 * is now suspended at the user boundary,
287 * (or other safe places if we think of any).
288 */
289 }
290
291 /* Allocate new proc. */
292 newproc = uma_zalloc(proc_zone, M_WAITOK);
293#ifdef MAC
294 mac_init_proc(newproc);
295#endif
296
297 /*
298 * Although process entries are dynamically created, we still keep
299 * a global limit on the maximum number we will create. Don't allow
300 * a nonprivileged user to use the last ten processes; don't let root
301 * exceed the limit. The variable nprocs is the current number of
302 * processes, maxproc is the limit.
303 */
304 sx_xlock(&allproc_lock);
305 uid = td->td_ucred->cr_ruid;
306 if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) {
307 error = EAGAIN;
308 goto fail;
309 }
310
311 /*
312 * Increment the count of procs running with this uid. Don't allow
313 * a nonprivileged user to exceed their current limit.
314 */
315 PROC_LOCK(p1);
316 ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
317 (uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
318 PROC_UNLOCK(p1);
319 if (!ok) {
320 error = EAGAIN;
321 goto fail;
322 }
323
324 /*
325 * Increment the nprocs resource before blocking can occur. There
326 * are hard-limits as to the number of processes that can run.
327 */
328 nprocs++;
329
330 /*
331 * Find an unused process ID. We remember a range of unused IDs
332 * ready to use (from lastpid+1 through pidchecked-1).
333 *
334 * If RFHIGHPID is set (used during system boot), do not allocate
335 * low-numbered pids.
336 */
337 trypid = lastpid + 1;
338 if (flags & RFHIGHPID) {
339 if (trypid < 10) {
340 trypid = 10;
341 }
342 } else {
343 if (randompid)
344 trypid += arc4random() % randompid;
345 }
346retry:
347 /*
348 * If the process ID prototype has wrapped around,
349 * restart somewhat above 0, as the low-numbered procs
350 * tend to include daemons that don't exit.
351 */
352 if (trypid >= PID_MAX) {
353 trypid = trypid % PID_MAX;
354 if (trypid < 100)
355 trypid += 100;
356 pidchecked = 0;
357 }
358 if (trypid >= pidchecked) {
359 int doingzomb = 0;
360
361 pidchecked = PID_MAX;
362 /*
363 * Scan the active and zombie procs to check whether this pid
364 * is in use. Remember the lowest pid that's greater
365 * than trypid, so we can avoid checking for a while.
366 */
367 p2 = LIST_FIRST(&allproc);
368again:
369 for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
370 PROC_LOCK(p2);
371 while (p2->p_pid == trypid ||
372 p2->p_pgrp->pg_id == trypid ||
373 p2->p_session->s_sid == trypid) {
374 trypid++;
375 if (trypid >= pidchecked) {
376 PROC_UNLOCK(p2);
377 goto retry;
378 }
379 }
380 if (p2->p_pid > trypid && pidchecked > p2->p_pid)
381 pidchecked = p2->p_pid;
382 if (p2->p_pgrp->pg_id > trypid &&
383 pidchecked > p2->p_pgrp->pg_id)
384 pidchecked = p2->p_pgrp->pg_id;
385 if (p2->p_session->s_sid > trypid &&
386 pidchecked > p2->p_session->s_sid)
387 pidchecked = p2->p_session->s_sid;
388 PROC_UNLOCK(p2);
389 }
390 if (!doingzomb) {
391 doingzomb = 1;
392 p2 = LIST_FIRST(&zombproc);
393 goto again;
394 }
395 }
396
397 /*
398 * RFHIGHPID does not mess with the lastpid counter during boot.
399 */
400 if (flags & RFHIGHPID)
401 pidchecked = 0;
402 else
403 lastpid = trypid;
404
405 p2 = newproc;
406 p2->p_state = PRS_NEW; /* protect against others */
407 p2->p_pid = trypid;
408 LIST_INSERT_HEAD(&allproc, p2, p_list);
409 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
410 sx_xunlock(&allproc_lock);
411
412 /*
413 * Malloc things while we don't hold any locks.
414 */
415 if (flags & RFSIGSHARE) {
416 MALLOC(newsigacts, struct sigacts *,
417 sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
418 newprocsig = NULL;
419 } else {
420 newsigacts = NULL;
421 MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
422 M_SUBPROC, M_WAITOK);
423 }
424
425 /*
426 * Copy filedesc.
427 * XXX: This is busted. fd*() need to not take proc
428 * arguments or something.
429 */
430 if (flags & RFCFDG)
431 fd = fdinit(td->td_proc->p_fd);
432 else if (flags & RFFDG) {
433 FILEDESC_LOCK(p1->p_fd);
434 fd = fdcopy(td->td_proc->p_fd);
435 FILEDESC_UNLOCK(p1->p_fd);
436 } else
437 fd = fdshare(p1->p_fd);
438
439 /*
440 * Make a proc table entry for the new process.
441 * Start by zeroing the section of proc that is zero-initialized,
442 * then copy the section that is copied directly from the parent.
443 */
444 td2 = FIRST_THREAD_IN_PROC(p2);
445 kg2 = FIRST_KSEGRP_IN_PROC(p2);
446 ke2 = FIRST_KSE_IN_KSEGRP(kg2);
447
448 /* Allocate and switch to an alternate kstack if specified */
449 if (pages != 0)
450 pmap_new_altkstack(td2, pages);
451
452#define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
453
454 bzero(&p2->p_startzero,
455 (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
456 bzero(&ke2->ke_startzero,
457 (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
458 bzero(&td2->td_startzero,
459 (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
460 bzero(&kg2->kg_startzero,
461 (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
462
463 mtx_init(&p2->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
464 PROC_LOCK(p2);
465 PROC_LOCK(p1);
466
467 bcopy(&p1->p_startcopy, &p2->p_startcopy,
468 (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
469 bcopy(&td->td_startcopy, &td2->td_startcopy,
470 (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
471 bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
472 (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
473#undef RANGEOF
474
475 /* Set up the thread as an active thread (as if runnable). */
476 ke2->ke_state = KES_THREAD;
477 ke2->ke_thread = td2;
478 td2->td_kse = ke2;
479
480 /*
481 * Duplicate sub-structures as needed.
482 * Increase reference counts on shared objects.
483 * The p_stats and p_sigacts substructs are set in vm_forkproc.
484 */
485 p2->p_flag = 0;
486 if (p1->p_flag & P_PROFIL)
487 startprofclock(p2);
488 mtx_lock_spin(&sched_lock);
489 p2->p_sflag = PS_INMEM;
490 /*
491 * Allow the scheduler to adjust the priority of the child and
492 * parent while we hold the sched_lock.
493 */
494 sched_fork(p1, p2);
495
496 mtx_unlock_spin(&sched_lock);
497 p2->p_ucred = crhold(td->td_ucred);
498 td2->td_ucred = crhold(p2->p_ucred); /* XXXKSE */
499
500 pargs_hold(p2->p_args);
501
502 if (flags & RFSIGSHARE) {
503 p2->p_procsig = p1->p_procsig;
504 p2->p_procsig->ps_refcnt++;
505 if (p1->p_sigacts == &p1->p_uarea->u_sigacts) {
506 /*
507 * Set p_sigacts to the new shared structure.
508 * Note that this is updating p1->p_sigacts at the
509 * same time, since p_sigacts is just a pointer to
510 * the shared p_procsig->ps_sigacts.
511 */
512 p2->p_sigacts = newsigacts;
513 newsigacts = NULL;
514 *p2->p_sigacts = p1->p_uarea->u_sigacts;
515 }
516 } else {
517 p2->p_procsig = newprocsig;
518 newprocsig = NULL;
519 bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
520 p2->p_procsig->ps_refcnt = 1;
521 p2->p_sigacts = NULL; /* finished in vm_forkproc() */
522 }
523 if (flags & RFLINUXTHPN)
524 p2->p_sigparent = SIGUSR1;
525 else
526 p2->p_sigparent = SIGCHLD;
527
528 /* Bump references to the text vnode (for procfs) */
529 p2->p_textvp = p1->p_textvp;
530 if (p2->p_textvp)
531 VREF(p2->p_textvp);
532 p2->p_fd = fd;
533 PROC_UNLOCK(p1);
534 PROC_UNLOCK(p2);
535
536 /*
537 * p_limit is copy-on-write, bump refcnt,
538 */
539 p2->p_limit = p1->p_limit;
540 p2->p_limit->p_refcnt++;
541
542 /*
543 * Setup linkage for kernel based threading
544 */
545 if((flags & RFTHREAD) != 0) {
546 mtx_lock(&ppeers_lock);
547 p2->p_peers = p1->p_peers;
548 p1->p_peers = p2;
549 p2->p_leader = p1->p_leader;
550 mtx_unlock(&ppeers_lock);
551 PROC_LOCK(p1->p_leader);
552 if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
553 PROC_UNLOCK(p1->p_leader);
554 /*
555 * The task leader is exiting, so process p1 is
556 * going to be killed shortly. Since p1 obviously
557 * isn't dead yet, we know that the leader is either
558 * sending SIGKILL's to all the processes in this
559 * task or is sleeping waiting for all the peers to
560 * exit. We let p1 complete the fork, but we need
561 * to go ahead and kill the new process p2 since
562 * the task leader may not get a chance to send
563 * SIGKILL to it. We leave it on the list so that
564 * the task leader will wait for this new process
565 * to commit suicide.
566 */
567 PROC_LOCK(p2);
568 psignal(p2, SIGKILL);
569 PROC_UNLOCK(p2);
570 } else
571 PROC_UNLOCK(p1->p_leader);
572 } else {
573 p2->p_peers = NULL;
574 p2->p_leader = p2;
575 }
576
577 sx_xlock(&proctree_lock);
578 PGRP_LOCK(p1->p_pgrp);
579 PROC_LOCK(p2);
580 PROC_LOCK(p1);
581
582 /*
583 * Preserve some more flags in subprocess. P_PROFIL has already
584 * been preserved.
585 */
586 p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
587 SESS_LOCK(p1->p_session);
588 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
589 p2->p_flag |= P_CONTROLT;
590 SESS_UNLOCK(p1->p_session);
591 if (flags & RFPPWAIT)
592 p2->p_flag |= P_PPWAIT;
593
594 LIST_INSERT_AFTER(p1, p2, p_pglist);
595 PGRP_UNLOCK(p1->p_pgrp);
596 LIST_INIT(&p2->p_children);
597
598 callout_init(&p2->p_itcallout, 1);
599
600#ifdef KTRACE
601 /*
602 * Copy traceflag and tracefile if enabled.
603 */
604 mtx_lock(&ktrace_mtx);
605 KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
606 if (p1->p_traceflag & KTRFAC_INHERIT) {
607 p2->p_traceflag = p1->p_traceflag;
608 if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
609 VREF(p2->p_tracevp);
610 KASSERT(p1->p_tracecred != NULL,
611 ("ktrace vnode with no cred"));
612 p2->p_tracecred = crhold(p1->p_tracecred);
613 }
614 }
615 mtx_unlock(&ktrace_mtx);
616#endif
617
618 /*
619 * If PF_FORK is set, the child process inherits the
620 * procfs ioctl flags from its parent.
621 */
622 if (p1->p_pfsflags & PF_FORK) {
623 p2->p_stops = p1->p_stops;
624 p2->p_pfsflags = p1->p_pfsflags;
625 }
626
627 /*
628 * This begins the section where we must prevent the parent
629 * from being swapped.
630 */
631 _PHOLD(p1);
632 PROC_UNLOCK(p1);
633
634 /*
635 * Attach the new process to its parent.
636 *
637 * If RFNOWAIT is set, the newly created process becomes a child
638 * of init. This effectively disassociates the child from the
639 * parent.
640 */
641 if (flags & RFNOWAIT)
642 pptr = initproc;
643 else
644 pptr = p1;
645 p2->p_pptr = pptr;
646 LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
647 sx_xunlock(&proctree_lock);
648
649 /* Inform accounting that we have forked. */
650 p2->p_acflag = AFORK;
651 PROC_UNLOCK(p2);
652
653 KASSERT(newprocsig == NULL, ("unused newprocsig"));
654 if (newsigacts != NULL)
655 FREE(newsigacts, M_SUBPROC);
656 /*
657 * Finish creating the child process. It will return via a different
658 * execution path later. (ie: directly into user mode)
659 */
660 vm_forkproc(td, p2, td2, flags);
661
662 if (flags == (RFFDG | RFPROC)) {
663 cnt.v_forks++;
664 cnt.v_forkpages += p2->p_vmspace->vm_dsize +
665 p2->p_vmspace->vm_ssize;
666 } else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
667 cnt.v_vforks++;
668 cnt.v_vforkpages += p2->p_vmspace->vm_dsize +
669 p2->p_vmspace->vm_ssize;
670 } else if (p1 == &proc0) {
671 cnt.v_kthreads++;
672 cnt.v_kthreadpages += p2->p_vmspace->vm_dsize +
673 p2->p_vmspace->vm_ssize;
674 } else {
675 cnt.v_rforks++;
676 cnt.v_rforkpages += p2->p_vmspace->vm_dsize +
677 p2->p_vmspace->vm_ssize;
678 }
679
680 /*
681 * Both processes are set up, now check if any loadable modules want
682 * to adjust anything.
683 * What if they have an error? XXX
684 */
685 EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
686
687 /*
688 * If RFSTOPPED not requested, make child runnable and add to
689 * run queue.
690 */
691 microtime(&(p2->p_stats->p_start));
692 if ((flags & RFSTOPPED) == 0) {
693 mtx_lock_spin(&sched_lock);
694 p2->p_state = PRS_NORMAL;
695 TD_SET_CAN_RUN(td2);
696 setrunqueue(td2);
697 mtx_unlock_spin(&sched_lock);
698 }
699
700 /*
701 * Now can be swapped.
702 */
703 PROC_LOCK(p1);
704 _PRELE(p1);
705
706 /*
707 * tell any interested parties about the new process
708 */
709 KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
710 PROC_UNLOCK(p1);
711
712 /*
713 * Preserve synchronization semantics of vfork. If waiting for
714 * child to exec or exit, set P_PPWAIT on child, and sleep on our
715 * proc (in case of exit).
716 */
717 PROC_LOCK(p2);
718 while (p2->p_flag & P_PPWAIT)
719 msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
720 PROC_UNLOCK(p2);
721
722 /*
723 * If other threads are waiting, let them continue now
724 */
725 if (p1->p_flag & P_THREADED) {
726 PROC_LOCK(p1);
727 thread_single_end();
728 PROC_UNLOCK(p1);
729 }
730
731 /*
732 * Return child proc pointer to parent.
733 */
734 mtx_unlock(&Giant);
735 *procp = p2;
736 return (0);
737fail:
738 sx_xunlock(&allproc_lock);
739 uma_zfree(proc_zone, newproc);
740 if (p1->p_flag & P_THREADED) {
741 PROC_LOCK(p1);
742 thread_single_end();
743 PROC_UNLOCK(p1);
744 }
745 tsleep(&forksleep, PUSER, "fork", hz / 2);
746 mtx_unlock(&Giant);
747 return (error);
748}
749
750/*
751 * Handle the return of a child process from fork1(). This function
752 * is called from the MD fork_trampoline() entry point.
753 */
754void
755fork_exit(callout, arg, frame)
756 void (*callout)(void *, struct trapframe *);
757 void *arg;
758 struct trapframe *frame;
759{
760 struct thread *td;
761 struct proc *p;
762
763 if ((td = PCPU_GET(deadthread))) {
764 PCPU_SET(deadthread, NULL);
765 thread_stash(td);
766 }
767 td = curthread;
768 p = td->td_proc;
769 td->td_oncpu = PCPU_GET(cpuid);
770 p->p_state = PRS_NORMAL;
771 /*
772 * Finish setting up thread glue. We need to initialize
773 * the thread into a td_critnest=1 state. Some platforms
774 * may have already partially or fully initialized td_critnest
775 * and/or td_md.md_savecrit (when applciable).
776 *
777 * see <arch>/<arch>/critical.c
778 */
779 sched_lock.mtx_lock = (uintptr_t)td;
780 sched_lock.mtx_recurse = 0;
781 cpu_critical_fork_exit();
782 CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
783 p->p_comm);
784 if (PCPU_GET(switchtime.sec) == 0)
785 binuptime(PCPU_PTR(switchtime));
786 PCPU_SET(switchticks, ticks);
787 mtx_unlock_spin(&sched_lock);
788
789 /*
790 * cpu_set_fork_handler intercepts this function call to
791 * have this call a non-return function to stay in kernel mode.
792 * initproc has its own fork handler, but it does return.
793 */
794 KASSERT(callout != NULL, ("NULL callout in fork_exit"));
795 callout(arg, frame);
796
797 /*
798 * Check if a kernel thread misbehaved and returned from its main
799 * function.
800 */
801 PROC_LOCK(p);
802 if (p->p_flag & P_KTHREAD) {
803 PROC_UNLOCK(p);
804 mtx_lock(&Giant);
805 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
806 p->p_comm, p->p_pid);
807 kthread_exit(0);
808 }
809 PROC_UNLOCK(p);
810#ifdef DIAGNOSTIC
811 cred_free_thread(td);
812#endif
813 mtx_assert(&Giant, MA_NOTOWNED);
814}
815
816/*
817 * Simplified back end of syscall(), used when returning from fork()
818 * directly into user mode. Giant is not held on entry, and must not
819 * be held on return. This function is passed in to fork_exit() as the
820 * first parameter and is called when returning to a new userland process.
821 */
822void
823fork_return(td, frame)
824 struct thread *td;
825 struct trapframe *frame;
826{
827
828 userret(td, frame, 0);
829#ifdef KTRACE
830 if (KTRPOINT(td, KTR_SYSRET))
831 ktrsysret(SYS_fork, 0, 0);
832#endif
833 mtx_assert(&Giant, MA_NOTOWNED);
834}