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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_fork.c 8.6 (Berkeley) 4/8/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_ktrace.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/sysproto.h>
46 #include <sys/eventhandler.h>
47 #include <sys/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/kthread.h>
50 #include <sys/sysctl.h>
52 #include <sys/malloc.h>
53 #include <sys/mutex.h>
55 #include <sys/pioctl.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sched.h>
58 #include <sys/syscall.h>
59 #include <sys/vmmeter.h>
60 #include <sys/vnode.h>
64 #include <sys/ktrace.h>
65 #include <sys/unistd.h>
67 #include <sys/signalvar.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_extern.h>
76 #ifndef _SYS_SYSPROTO_H_
82 static int forksleep; /* Place for fork1() to sleep on. */
91 struct fork_args *uap;
96 error = fork1(td, RFFDG | RFPROC, 0, &p2);
98 td->td_retval[0] = p2->p_pid;
111 struct vfork_args *uap;
116 error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
118 td->td_retval[0] = p2->p_pid;
119 td->td_retval[1] = 0;
130 struct rfork_args *uap;
135 /* Don't allow kernel-only flags. */
136 if ((uap->flags & RFKERNELONLY) != 0)
139 error = fork1(td, uap->flags, 0, &p2);
141 td->td_retval[0] = p2 ? p2->p_pid : 0;
142 td->td_retval[1] = 0;
147 int nprocs = 1; /* process 0 */
149 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
153 * Random component to lastpid generation. We mix in a random factor to make
154 * it a little harder to predict. We sanity check the modulus value to avoid
155 * doing it in critical paths. Don't let it be too small or we pointlessly
156 * waste randomness entropy, and don't let it be impossibly large. Using a
157 * modulus that is too big causes a LOT more process table scans and slows
158 * down fork processing as the pidchecked caching is defeated.
160 static int randompid = 0;
163 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
167 error = sysctl_wire_old_buffer(req, sizeof(int));
170 sx_xlock(&allproc_lock);
172 error = sysctl_handle_int(oidp, &pid, 0, req);
173 if (error == 0 && req->newptr != NULL) {
174 if (pid < 0 || pid > PID_MAX - 100) /* out of range */
176 else if (pid < 2) /* NOP */
178 else if (pid < 100) /* Make it reasonable */
182 sx_xunlock(&allproc_lock);
186 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
187 0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
190 fork1(td, flags, pages, procp)
196 struct proc *p1, *p2, *pptr;
198 struct proc *newproc;
200 static int curfail, pidchecked = 0;
201 static struct timeval lastfail;
203 struct filedesc_to_leader *fdtol;
206 struct sigacts *newsigacts;
209 /* Can't copy and clear. */
210 if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
216 * Here we don't create a new process, but we divorce
217 * certain parts of a process from itself.
219 if ((flags & RFPROC) == 0) {
220 vm_forkproc(td, NULL, NULL, flags);
223 * Close all file descriptors.
225 if (flags & RFCFDG) {
226 struct filedesc *fdtmp;
227 fdtmp = fdinit(td->td_proc->p_fd);
233 * Unshare file descriptors (from parent).
242 * Note 1:1 allows for forking with one thread coming out on the
243 * other side with the expectation that the process is about to
246 if (p1->p_flag & P_HADTHREADS) {
248 * Idle the other threads for a second.
249 * Since the user space is copied, it must remain stable.
250 * In addition, all threads (from the user perspective)
251 * need to either be suspended or in the kernel,
252 * where they will try restart in the parent and will
253 * be aborted in the child.
256 if (thread_single(SINGLE_NO_EXIT)) {
257 /* Abort. Someone else is single threading before us. */
263 * All other activity in this process
264 * is now suspended at the user boundary,
265 * (or other safe places if we think of any).
269 /* Allocate new proc. */
270 newproc = uma_zalloc(proc_zone, M_WAITOK);
272 mac_init_proc(newproc);
274 knlist_init(&newproc->p_klist, &newproc->p_mtx, NULL, NULL, NULL);
276 /* We have to lock the process tree while we look for a pid. */
277 sx_slock(&proctree_lock);
280 * Although process entries are dynamically created, we still keep
281 * a global limit on the maximum number we will create. Don't allow
282 * a nonprivileged user to use the last ten processes; don't let root
283 * exceed the limit. The variable nprocs is the current number of
284 * processes, maxproc is the limit.
286 sx_xlock(&allproc_lock);
287 uid = td->td_ucred->cr_ruid;
288 if ((nprocs >= maxproc - 10 &&
289 suser_cred(td->td_ucred, SUSER_RUID) != 0) ||
296 * Increment the count of procs running with this uid. Don't allow
297 * a nonprivileged user to exceed their current limit.
300 ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
301 (uid != 0) ? lim_cur(p1, RLIMIT_NPROC) : 0);
309 * Increment the nprocs resource before blocking can occur. There
310 * are hard-limits as to the number of processes that can run.
315 * Find an unused process ID. We remember a range of unused IDs
316 * ready to use (from lastpid+1 through pidchecked-1).
318 * If RFHIGHPID is set (used during system boot), do not allocate
321 trypid = lastpid + 1;
322 if (flags & RFHIGHPID) {
327 trypid += arc4random() % randompid;
331 * If the process ID prototype has wrapped around,
332 * restart somewhat above 0, as the low-numbered procs
333 * tend to include daemons that don't exit.
335 if (trypid >= PID_MAX) {
336 trypid = trypid % PID_MAX;
341 if (trypid >= pidchecked) {
344 pidchecked = PID_MAX;
346 * Scan the active and zombie procs to check whether this pid
347 * is in use. Remember the lowest pid that's greater
348 * than trypid, so we can avoid checking for a while.
350 p2 = LIST_FIRST(&allproc);
352 for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
354 while (p2->p_pid == trypid ||
355 (p2->p_pgrp != NULL &&
356 (p2->p_pgrp->pg_id == trypid ||
357 (p2->p_session != NULL &&
358 p2->p_session->s_sid == trypid)))) {
360 if (trypid >= pidchecked) {
365 if (p2->p_pid > trypid && pidchecked > p2->p_pid)
366 pidchecked = p2->p_pid;
367 if (p2->p_pgrp != NULL) {
368 if (p2->p_pgrp->pg_id > trypid &&
369 pidchecked > p2->p_pgrp->pg_id)
370 pidchecked = p2->p_pgrp->pg_id;
371 if (p2->p_session != NULL &&
372 p2->p_session->s_sid > trypid &&
373 pidchecked > p2->p_session->s_sid)
374 pidchecked = p2->p_session->s_sid;
380 p2 = LIST_FIRST(&zombproc);
384 sx_sunlock(&proctree_lock);
387 * RFHIGHPID does not mess with the lastpid counter during boot.
389 if (flags & RFHIGHPID)
395 p2->p_state = PRS_NEW; /* protect against others */
397 LIST_INSERT_HEAD(&allproc, p2, p_list);
398 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
399 sx_xunlock(&allproc_lock);
402 * Malloc things while we don't hold any locks.
404 if (flags & RFSIGSHARE)
407 newsigacts = sigacts_alloc();
412 if (flags & RFCFDG) {
413 fd = fdinit(p1->p_fd);
415 } else if (flags & RFFDG) {
416 fd = fdcopy(p1->p_fd);
419 fd = fdshare(p1->p_fd);
420 if (p1->p_fdtol == NULL)
422 filedesc_to_leader_alloc(NULL,
425 if ((flags & RFTHREAD) != 0) {
427 * Shared file descriptor table and
428 * shared process leaders.
431 FILEDESC_LOCK_FAST(p1->p_fd);
432 fdtol->fdl_refcount++;
433 FILEDESC_UNLOCK_FAST(p1->p_fd);
436 * Shared file descriptor table, and
437 * different process leaders
439 fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
445 * Make a proc table entry for the new process.
446 * Start by zeroing the section of proc that is zero-initialized,
447 * then copy the section that is copied directly from the parent.
449 td2 = FIRST_THREAD_IN_PROC(p2);
450 kg2 = FIRST_KSEGRP_IN_PROC(p2);
452 /* Allocate and switch to an alternate kstack if specified. */
454 vm_thread_new_altkstack(td2, pages);
459 bzero(&p2->p_startzero,
460 __rangeof(struct proc, p_startzero, p_endzero));
461 bzero(&td2->td_startzero,
462 __rangeof(struct thread, td_startzero, td_endzero));
463 bzero(&kg2->kg_startzero,
464 __rangeof(struct ksegrp, kg_startzero, kg_endzero));
466 bcopy(&p1->p_startcopy, &p2->p_startcopy,
467 __rangeof(struct proc, p_startcopy, p_endcopy));
468 bcopy(&td->td_startcopy, &td2->td_startcopy,
469 __rangeof(struct thread, td_startcopy, td_endcopy));
470 bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
471 __rangeof(struct ksegrp, kg_startcopy, kg_endcopy));
473 td2->td_sigstk = td->td_sigstk;
474 td2->td_sigmask = td->td_sigmask;
477 * Duplicate sub-structures as needed.
478 * Increase reference counts on shared objects.
481 if (p1->p_flag & P_PROFIL)
483 mtx_lock_spin(&sched_lock);
484 p2->p_sflag = PS_INMEM;
486 * Allow the scheduler to adjust the priority of the child and
487 * parent while we hold the sched_lock.
491 mtx_unlock_spin(&sched_lock);
492 p2->p_ucred = crhold(td->td_ucred);
493 td2->td_ucred = crhold(p2->p_ucred); /* XXXKSE */
495 pargs_hold(p2->p_args);
497 if (flags & RFSIGSHARE) {
498 p2->p_sigacts = sigacts_hold(p1->p_sigacts);
500 sigacts_copy(newsigacts, p1->p_sigacts);
501 p2->p_sigacts = newsigacts;
503 if (flags & RFLINUXTHPN)
504 p2->p_sigparent = SIGUSR1;
506 p2->p_sigparent = SIGCHLD;
508 p2->p_textvp = p1->p_textvp;
513 * p_limit is copy-on-write. Bump its refcount.
515 p2->p_limit = lim_hold(p1->p_limit);
517 pstats_fork(p1->p_stats, p2->p_stats);
522 /* Bump references to the text vnode (for procfs) */
527 * Set up linkage for kernel based threading.
529 if ((flags & RFTHREAD) != 0) {
530 mtx_lock(&ppeers_lock);
531 p2->p_peers = p1->p_peers;
533 p2->p_leader = p1->p_leader;
534 mtx_unlock(&ppeers_lock);
535 PROC_LOCK(p1->p_leader);
536 if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
537 PROC_UNLOCK(p1->p_leader);
539 * The task leader is exiting, so process p1 is
540 * going to be killed shortly. Since p1 obviously
541 * isn't dead yet, we know that the leader is either
542 * sending SIGKILL's to all the processes in this
543 * task or is sleeping waiting for all the peers to
544 * exit. We let p1 complete the fork, but we need
545 * to go ahead and kill the new process p2 since
546 * the task leader may not get a chance to send
547 * SIGKILL to it. We leave it on the list so that
548 * the task leader will wait for this new process
552 psignal(p2, SIGKILL);
555 PROC_UNLOCK(p1->p_leader);
561 sx_xlock(&proctree_lock);
562 PGRP_LOCK(p1->p_pgrp);
567 * Preserve some more flags in subprocess. P_PROFIL has already
570 p2->p_flag |= p1->p_flag & P_SUGID;
571 td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
572 SESS_LOCK(p1->p_session);
573 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
574 p2->p_flag |= P_CONTROLT;
575 SESS_UNLOCK(p1->p_session);
576 if (flags & RFPPWAIT)
577 p2->p_flag |= P_PPWAIT;
579 p2->p_pgrp = p1->p_pgrp;
580 LIST_INSERT_AFTER(p1, p2, p_pglist);
581 PGRP_UNLOCK(p1->p_pgrp);
582 LIST_INIT(&p2->p_children);
584 callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
588 * Copy traceflag and tracefile if enabled.
590 mtx_lock(&ktrace_mtx);
591 KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
592 if (p1->p_traceflag & KTRFAC_INHERIT) {
593 p2->p_traceflag = p1->p_traceflag;
594 if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
596 KASSERT(p1->p_tracecred != NULL,
597 ("ktrace vnode with no cred"));
598 p2->p_tracecred = crhold(p1->p_tracecred);
601 mtx_unlock(&ktrace_mtx);
605 * If PF_FORK is set, the child process inherits the
606 * procfs ioctl flags from its parent.
608 if (p1->p_pfsflags & PF_FORK) {
609 p2->p_stops = p1->p_stops;
610 p2->p_pfsflags = p1->p_pfsflags;
614 * This begins the section where we must prevent the parent
615 * from being swapped.
621 * Attach the new process to its parent.
623 * If RFNOWAIT is set, the newly created process becomes a child
624 * of init. This effectively disassociates the child from the
627 if (flags & RFNOWAIT)
632 LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
633 sx_xunlock(&proctree_lock);
635 /* Inform accounting that we have forked. */
636 p2->p_acflag = AFORK;
640 * Finish creating the child process. It will return via a different
641 * execution path later. (ie: directly into user mode)
643 vm_forkproc(td, p2, td2, flags);
645 if (flags == (RFFDG | RFPROC)) {
646 atomic_add_int(&cnt.v_forks, 1);
647 atomic_add_int(&cnt.v_forkpages, p2->p_vmspace->vm_dsize +
648 p2->p_vmspace->vm_ssize);
649 } else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
650 atomic_add_int(&cnt.v_vforks, 1);
651 atomic_add_int(&cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
652 p2->p_vmspace->vm_ssize);
653 } else if (p1 == &proc0) {
654 atomic_add_int(&cnt.v_kthreads, 1);
655 atomic_add_int(&cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
656 p2->p_vmspace->vm_ssize);
658 atomic_add_int(&cnt.v_rforks, 1);
659 atomic_add_int(&cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
660 p2->p_vmspace->vm_ssize);
664 * Both processes are set up, now check if any loadable modules want
665 * to adjust anything.
666 * What if they have an error? XXX
668 EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
671 * Set the child start time and mark the process as being complete.
673 microuptime(&p2->p_stats->p_start);
674 mtx_lock_spin(&sched_lock);
675 p2->p_state = PRS_NORMAL;
678 * If RFSTOPPED not requested, make child runnable and add to
681 if ((flags & RFSTOPPED) == 0) {
683 setrunqueue(td2, SRQ_BORING);
685 mtx_unlock_spin(&sched_lock);
688 * Now can be swapped.
694 * Tell any interested parties about the new process.
696 KNOTE_LOCKED(&p1->p_klist, NOTE_FORK | p2->p_pid);
701 * Preserve synchronization semantics of vfork. If waiting for
702 * child to exec or exit, set P_PPWAIT on child, and sleep on our
703 * proc (in case of exit).
706 while (p2->p_flag & P_PPWAIT)
707 msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
711 * If other threads are waiting, let them continue now.
713 if (p1->p_flag & P_HADTHREADS) {
720 * Return child proc pointer to parent.
725 sx_sunlock(&proctree_lock);
726 if (ppsratecheck(&lastfail, &curfail, 1))
727 printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
729 sx_xunlock(&allproc_lock);
731 mac_destroy_proc(newproc);
733 uma_zfree(proc_zone, newproc);
734 if (p1->p_flag & P_HADTHREADS) {
739 tsleep(&forksleep, PUSER, "fork", hz / 2);
744 * Handle the return of a child process from fork1(). This function
745 * is called from the MD fork_trampoline() entry point.
748 fork_exit(callout, arg, frame)
749 void (*callout)(void *, struct trapframe *);
751 struct trapframe *frame;
757 * Finish setting up thread glue so that it begins execution in a
758 * non-nested critical section with sched_lock held but not recursed.
762 td->td_oncpu = PCPU_GET(cpuid);
763 KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
765 sched_lock.mtx_lock = (uintptr_t)td;
766 mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
767 CTR4(KTR_PROC, "fork_exit: new thread %p (kse %p, pid %d, %s)",
768 td, td->td_sched, p->p_pid, p->p_comm);
771 * Processes normally resume in mi_switch() after being
772 * cpu_switch()'ed to, but when children start up they arrive here
773 * instead, so we must do much the same things as mi_switch() would.
776 if ((td = PCPU_GET(deadthread))) {
777 PCPU_SET(deadthread, NULL);
781 mtx_unlock_spin(&sched_lock);
784 * cpu_set_fork_handler intercepts this function call to
785 * have this call a non-return function to stay in kernel mode.
786 * initproc has its own fork handler, but it does return.
788 KASSERT(callout != NULL, ("NULL callout in fork_exit"));
792 * Check if a kernel thread misbehaved and returned from its main
796 if (p->p_flag & P_KTHREAD) {
798 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
799 p->p_comm, p->p_pid);
803 mtx_assert(&Giant, MA_NOTOWNED);
807 * Simplified back end of syscall(), used when returning from fork()
808 * directly into user mode. Giant is not held on entry, and must not
809 * be held on return. This function is passed in to fork_exit() as the
810 * first parameter and is called when returning to a new userland process.
813 fork_return(td, frame)
815 struct trapframe *frame;
818 userret(td, frame, 0);
820 if (KTRPOINT(td, KTR_SYSRET))
821 ktrsysret(SYS_fork, 0, 0);
823 mtx_assert(&Giant, MA_NOTOWNED);