The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_fork.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    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  * 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.
   21  *
   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
   32  * SUCH DAMAGE.
   33  *
   34  *      @(#)kern_fork.c 8.6 (Berkeley) 4/8/94
   35  */
   36 
   37 #include <sys/cdefs.h>
   38 __FBSDID("$FreeBSD: releng/6.1/sys/kern/kern_fork.c 158179 2006-04-30 16:44:43Z cvs2svn $");
   39 
   40 #include "opt_ktrace.h"
   41 #include "opt_mac.h"
   42 
   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>
   51 #include <sys/lock.h>
   52 #include <sys/malloc.h>
   53 #include <sys/mutex.h>
   54 #include <sys/proc.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>
   61 #include <sys/acct.h>
   62 #include <sys/mac.h>
   63 #include <sys/ktr.h>
   64 #include <sys/ktrace.h>
   65 #include <sys/unistd.h> 
   66 #include <sys/sx.h>
   67 #include <sys/signalvar.h>
   68 
   69 #include <vm/vm.h>
   70 #include <vm/pmap.h>
   71 #include <vm/vm_map.h>
   72 #include <vm/vm_extern.h>
   73 #include <vm/uma.h>
   74 
   75 
   76 #ifndef _SYS_SYSPROTO_H_
   77 struct fork_args {
   78         int     dummy;
   79 };
   80 #endif
   81 
   82 static int forksleep; /* Place for fork1() to sleep on. */
   83 
   84 /*
   85  * MPSAFE
   86  */
   87 /* ARGSUSED */
   88 int
   89 fork(td, uap)
   90         struct thread *td;
   91         struct fork_args *uap;
   92 {
   93         int error;
   94         struct proc *p2;
   95 
   96         error = fork1(td, RFFDG | RFPROC, 0, &p2);
   97         if (error == 0) {
   98                 td->td_retval[0] = p2->p_pid;
   99                 td->td_retval[1] = 0;
  100         }
  101         return (error);
  102 }
  103 
  104 /*
  105  * MPSAFE
  106  */
  107 /* ARGSUSED */
  108 int
  109 vfork(td, uap)
  110         struct thread *td;
  111         struct vfork_args *uap;
  112 {
  113         int error;
  114         struct proc *p2;
  115 
  116         error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, 0, &p2);
  117         if (error == 0) {
  118                 td->td_retval[0] = p2->p_pid;
  119                 td->td_retval[1] = 0;
  120         }
  121         return (error);
  122 }
  123 
  124 /*
  125  * MPSAFE
  126  */
  127 int
  128 rfork(td, uap)
  129         struct thread *td;
  130         struct rfork_args *uap;
  131 {
  132         struct proc *p2;
  133         int error;
  134 
  135         /* Don't allow kernel-only flags. */
  136         if ((uap->flags & RFKERNELONLY) != 0)
  137                 return (EINVAL);
  138 
  139         error = fork1(td, uap->flags, 0, &p2);
  140         if (error == 0) {
  141                 td->td_retval[0] = p2 ? p2->p_pid : 0;
  142                 td->td_retval[1] = 0;
  143         }
  144         return (error);
  145 }
  146 
  147 int     nprocs = 1;             /* process 0 */
  148 int     lastpid = 0;
  149 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0, 
  150     "Last used PID");
  151 
  152 /*
  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.
  159  */
  160 static int randompid = 0;
  161 
  162 static int
  163 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
  164 {
  165         int error, pid;
  166 
  167         error = sysctl_wire_old_buffer(req, sizeof(int));
  168         if (error != 0)
  169                 return(error);
  170         sx_xlock(&allproc_lock);
  171         pid = randompid;
  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 */
  175                         pid = PID_MAX - 100;
  176                 else if (pid < 2)                       /* NOP */
  177                         pid = 0;
  178                 else if (pid < 100)                     /* Make it reasonable */
  179                         pid = 100;
  180                 randompid = pid;
  181         }
  182         sx_xunlock(&allproc_lock);
  183         return (error);
  184 }
  185 
  186 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
  187     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
  188 
  189 int
  190 fork1(td, flags, pages, procp)
  191         struct thread *td;
  192         int flags;
  193         int pages;
  194         struct proc **procp;
  195 {
  196         struct proc *p1, *p2, *pptr;
  197         uid_t uid;
  198         struct proc *newproc;
  199         int ok, trypid;
  200         static int curfail, pidchecked = 0;
  201         static struct timeval lastfail;
  202         struct filedesc *fd;
  203         struct filedesc_to_leader *fdtol;
  204         struct thread *td2;
  205         struct ksegrp *kg2;
  206         struct sigacts *newsigacts;
  207         int error;
  208 
  209         /* Can't copy and clear. */
  210         if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
  211                 return (EINVAL);
  212 
  213         p1 = td->td_proc;
  214 
  215         /*
  216          * Here we don't create a new process, but we divorce
  217          * certain parts of a process from itself.
  218          */
  219         if ((flags & RFPROC) == 0) {
  220                 if ((p1->p_flag & P_HADTHREADS) &&
  221                     (flags & (RFCFDG | RFFDG))) {
  222                         PROC_LOCK(p1);
  223                         if (thread_single(SINGLE_BOUNDARY)) {
  224                                 PROC_UNLOCK(p1);
  225                                 return (ERESTART);
  226                         }
  227                         PROC_UNLOCK(p1);
  228                 }
  229 
  230                 vm_forkproc(td, NULL, NULL, flags);
  231                 /*
  232                  * Close all file descriptors.
  233                  */
  234                 if (flags & RFCFDG) {
  235                         struct filedesc *fdtmp;
  236                         fdtmp = fdinit(td->td_proc->p_fd);
  237                         fdfree(td);
  238                         p1->p_fd = fdtmp;
  239                 }
  240 
  241                 /*
  242                  * Unshare file descriptors (from parent).
  243                  */
  244                 if (flags & RFFDG) 
  245                         fdunshare(p1, td);
  246 
  247                 if ((p1->p_flag & P_HADTHREADS) &&
  248                     (flags & (RFCFDG | RFFDG))) {
  249                         PROC_LOCK(p1);
  250                         thread_single_end();
  251                         PROC_UNLOCK(p1);
  252                 }
  253                 *procp = NULL;
  254                 return (0);
  255         }
  256 
  257         /*
  258          * Note 1:1 allows for forking with one thread coming out on the
  259          * other side with the expectation that the process is about to
  260          * exec.
  261          */
  262         if (p1->p_flag & P_HADTHREADS) {
  263                 /*
  264                  * Idle the other threads for a second.
  265                  * Since the user space is copied, it must remain stable.
  266                  * In addition, all threads (from the user perspective)
  267                  * need to either be suspended or in the kernel,
  268                  * where they will try restart in the parent and will
  269                  * be aborted in the child.
  270                  */
  271                 PROC_LOCK(p1);
  272                 if (thread_single(SINGLE_NO_EXIT)) {
  273                         /* Abort. Someone else is single threading before us. */
  274                         PROC_UNLOCK(p1);
  275                         return (ERESTART);
  276                 }
  277                 PROC_UNLOCK(p1);
  278                 /*
  279                  * All other activity in this process
  280                  * is now suspended at the user boundary,
  281                  * (or other safe places if we think of any).
  282                  */
  283         }
  284 
  285         /* Allocate new proc. */
  286         newproc = uma_zalloc(proc_zone, M_WAITOK);
  287 #ifdef MAC
  288         mac_init_proc(newproc);
  289 #endif
  290         knlist_init(&newproc->p_klist, &newproc->p_mtx, NULL, NULL, NULL);
  291 
  292         /* We have to lock the process tree while we look for a pid. */
  293         sx_slock(&proctree_lock);
  294 
  295         /*
  296          * Although process entries are dynamically created, we still keep
  297          * a global limit on the maximum number we will create.  Don't allow
  298          * a nonprivileged user to use the last ten processes; don't let root
  299          * exceed the limit. The variable nprocs is the current number of
  300          * processes, maxproc is the limit.
  301          */
  302         sx_xlock(&allproc_lock);
  303         uid = td->td_ucred->cr_ruid;
  304         if ((nprocs >= maxproc - 10 &&
  305             suser_cred(td->td_ucred, SUSER_RUID) != 0) ||
  306             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) ? lim_cur(p1, RLIMIT_NPROC) : 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         } else {
  342                 if (randompid)
  343                         trypid += arc4random() % randompid;
  344         }
  345 retry:
  346         /*
  347          * If the process ID prototype has wrapped around,
  348          * restart somewhat above 0, as the low-numbered procs
  349          * tend to include daemons that don't exit.
  350          */
  351         if (trypid >= PID_MAX) {
  352                 trypid = trypid % PID_MAX;
  353                 if (trypid < 100)
  354                         trypid += 100;
  355                 pidchecked = 0;
  356         }
  357         if (trypid >= pidchecked) {
  358                 int doingzomb = 0;
  359 
  360                 pidchecked = PID_MAX;
  361                 /*
  362                  * Scan the active and zombie procs to check whether this pid
  363                  * is in use.  Remember the lowest pid that's greater
  364                  * than trypid, so we can avoid checking for a while.
  365                  */
  366                 p2 = LIST_FIRST(&allproc);
  367 again:
  368                 for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
  369                         PROC_LOCK(p2);
  370                         while (p2->p_pid == trypid ||
  371                             (p2->p_pgrp != NULL &&
  372                             (p2->p_pgrp->pg_id == trypid ||
  373                             (p2->p_session != NULL &&
  374                             p2->p_session->s_sid == trypid)))) {
  375                                 trypid++;
  376                                 if (trypid >= pidchecked) {
  377                                         PROC_UNLOCK(p2);
  378                                         goto retry;
  379                                 }
  380                         }
  381                         if (p2->p_pid > trypid && pidchecked > p2->p_pid)
  382                                 pidchecked = p2->p_pid;
  383                         if (p2->p_pgrp != NULL) {
  384                                 if (p2->p_pgrp->pg_id > trypid &&
  385                                     pidchecked > p2->p_pgrp->pg_id)
  386                                         pidchecked = p2->p_pgrp->pg_id;
  387                                 if (p2->p_session != NULL &&
  388                                     p2->p_session->s_sid > trypid &&
  389                                     pidchecked > p2->p_session->s_sid)
  390                                         pidchecked = p2->p_session->s_sid;
  391                         }
  392                         PROC_UNLOCK(p2);
  393                 }
  394                 if (!doingzomb) {
  395                         doingzomb = 1;
  396                         p2 = LIST_FIRST(&zombproc);
  397                         goto again;
  398                 }
  399         }
  400         sx_sunlock(&proctree_lock);
  401 
  402         /*
  403          * RFHIGHPID does not mess with the lastpid counter during boot.
  404          */
  405         if (flags & RFHIGHPID)
  406                 pidchecked = 0;
  407         else
  408                 lastpid = trypid;
  409 
  410         p2 = newproc;
  411         p2->p_state = PRS_NEW;          /* protect against others */
  412         p2->p_pid = trypid;
  413         LIST_INSERT_HEAD(&allproc, p2, p_list);
  414         LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
  415         sx_xunlock(&allproc_lock);
  416 
  417         /*
  418          * Malloc things while we don't hold any locks.
  419          */
  420         if (flags & RFSIGSHARE)
  421                 newsigacts = NULL;
  422         else
  423                 newsigacts = sigacts_alloc();
  424 
  425         /*
  426          * Copy filedesc.
  427          */
  428         if (flags & RFCFDG) {
  429                 fd = fdinit(p1->p_fd);
  430                 fdtol = NULL;
  431         } else if (flags & RFFDG) {
  432                 fd = fdcopy(p1->p_fd);
  433                 fdtol = NULL;
  434         } else {
  435                 fd = fdshare(p1->p_fd);
  436                 if (p1->p_fdtol == NULL)
  437                         p1->p_fdtol =
  438                                 filedesc_to_leader_alloc(NULL,
  439                                                          NULL,
  440                                                          p1->p_leader);
  441                 if ((flags & RFTHREAD) != 0) {
  442                         /*
  443                          * Shared file descriptor table and
  444                          * shared process leaders.
  445                          */
  446                         fdtol = p1->p_fdtol;
  447                         FILEDESC_LOCK_FAST(p1->p_fd);
  448                         fdtol->fdl_refcount++;
  449                         FILEDESC_UNLOCK_FAST(p1->p_fd);
  450                 } else {
  451                         /* 
  452                          * Shared file descriptor table, and
  453                          * different process leaders 
  454                          */
  455                         fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
  456                                                          p1->p_fd,
  457                                                          p2);
  458                 }
  459         }
  460         /*
  461          * Make a proc table entry for the new process.
  462          * Start by zeroing the section of proc that is zero-initialized,
  463          * then copy the section that is copied directly from the parent.
  464          */
  465         td2 = FIRST_THREAD_IN_PROC(p2);
  466         kg2 = FIRST_KSEGRP_IN_PROC(p2);
  467 
  468         /* Allocate and switch to an alternate kstack if specified. */
  469         if (pages != 0)
  470                 vm_thread_new_altkstack(td2, pages);
  471 
  472         PROC_LOCK(p2);
  473         PROC_LOCK(p1);
  474 
  475         bzero(&p2->p_startzero,
  476             __rangeof(struct proc, p_startzero, p_endzero));
  477         bzero(&td2->td_startzero,
  478             __rangeof(struct thread, td_startzero, td_endzero));
  479         bzero(&kg2->kg_startzero,
  480             __rangeof(struct ksegrp, kg_startzero, kg_endzero));
  481 
  482         bcopy(&p1->p_startcopy, &p2->p_startcopy,
  483             __rangeof(struct proc, p_startcopy, p_endcopy));
  484         bcopy(&td->td_startcopy, &td2->td_startcopy,
  485             __rangeof(struct thread, td_startcopy, td_endcopy));
  486         bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
  487             __rangeof(struct ksegrp, kg_startcopy, kg_endcopy));
  488 
  489         td2->td_sigstk = td->td_sigstk;
  490         td2->td_sigmask = td->td_sigmask;
  491 
  492         /*
  493          * Duplicate sub-structures as needed.
  494          * Increase reference counts on shared objects.
  495          */
  496         p2->p_flag = 0;
  497         if (p1->p_flag & P_PROFIL)
  498                 startprofclock(p2);
  499         mtx_lock_spin(&sched_lock);
  500         p2->p_sflag = PS_INMEM;
  501         /*
  502          * Allow the scheduler to adjust the priority of the child and
  503          * parent while we hold the sched_lock.
  504          */
  505         sched_fork(td, td2);
  506 
  507         mtx_unlock_spin(&sched_lock);
  508         p2->p_ucred = crhold(td->td_ucred);
  509         td2->td_ucred = crhold(p2->p_ucred);    /* XXXKSE */
  510 
  511         pargs_hold(p2->p_args);
  512 
  513         if (flags & RFSIGSHARE) {
  514                 p2->p_sigacts = sigacts_hold(p1->p_sigacts);
  515         } else {
  516                 sigacts_copy(newsigacts, p1->p_sigacts);
  517                 p2->p_sigacts = newsigacts;
  518         }
  519         if (flags & RFLINUXTHPN) 
  520                 p2->p_sigparent = SIGUSR1;
  521         else
  522                 p2->p_sigparent = SIGCHLD;
  523 
  524         p2->p_textvp = p1->p_textvp;
  525         p2->p_fd = fd;
  526         p2->p_fdtol = fdtol;
  527 
  528         /*
  529          * p_limit is copy-on-write.  Bump its refcount.
  530          */
  531         p2->p_limit = lim_hold(p1->p_limit);
  532 
  533         pstats_fork(p1->p_stats, p2->p_stats);
  534 
  535         PROC_UNLOCK(p1);
  536         PROC_UNLOCK(p2);
  537 
  538         /* Bump references to the text vnode (for procfs) */
  539         if (p2->p_textvp)
  540                 vref(p2->p_textvp);
  541 
  542         /*
  543          * Set up 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;
  587         td2->td_pflags |= td->td_pflags & TDP_ALTSTACK;
  588         SESS_LOCK(p1->p_session);
  589         if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
  590                 p2->p_flag |= P_CONTROLT;
  591         SESS_UNLOCK(p1->p_session);
  592         if (flags & RFPPWAIT)
  593                 p2->p_flag |= P_PPWAIT;
  594 
  595         p2->p_pgrp = p1->p_pgrp;
  596         LIST_INSERT_AFTER(p1, p2, p_pglist);
  597         PGRP_UNLOCK(p1->p_pgrp);
  598         LIST_INIT(&p2->p_children);
  599 
  600         callout_init(&p2->p_itcallout, CALLOUT_MPSAFE);
  601 
  602 #ifdef KTRACE
  603         /*
  604          * Copy traceflag and tracefile if enabled.
  605          */
  606         mtx_lock(&ktrace_mtx);
  607         KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
  608         if (p1->p_traceflag & KTRFAC_INHERIT) {
  609                 p2->p_traceflag = p1->p_traceflag;
  610                 if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
  611                         VREF(p2->p_tracevp);
  612                         KASSERT(p1->p_tracecred != NULL,
  613                             ("ktrace vnode with no cred"));
  614                         p2->p_tracecred = crhold(p1->p_tracecred);
  615                 }
  616         }
  617         mtx_unlock(&ktrace_mtx);
  618 #endif
  619 
  620         /*
  621          * If PF_FORK is set, the child process inherits the
  622          * procfs ioctl flags from its parent.
  623          */
  624         if (p1->p_pfsflags & PF_FORK) {
  625                 p2->p_stops = p1->p_stops;
  626                 p2->p_pfsflags = p1->p_pfsflags;
  627         }
  628 
  629         /*
  630          * This begins the section where we must prevent the parent
  631          * from being swapped.
  632          */
  633         _PHOLD(p1);
  634         PROC_UNLOCK(p1);
  635 
  636         /*
  637          * Attach the new process to its parent.
  638          *
  639          * If RFNOWAIT is set, the newly created process becomes a child
  640          * of init.  This effectively disassociates the child from the
  641          * parent.
  642          */
  643         if (flags & RFNOWAIT)
  644                 pptr = initproc;
  645         else
  646                 pptr = p1;
  647         p2->p_pptr = pptr;
  648         LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
  649         sx_xunlock(&proctree_lock);
  650 
  651         /* Inform accounting that we have forked. */
  652         p2->p_acflag = AFORK;
  653         PROC_UNLOCK(p2);
  654 
  655         /*
  656          * Finish creating the child process.  It will return via a different
  657          * execution path later.  (ie: directly into user mode)
  658          */
  659         vm_forkproc(td, p2, td2, flags);
  660 
  661         if (flags == (RFFDG | RFPROC)) {
  662                 atomic_add_int(&cnt.v_forks, 1);
  663                 atomic_add_int(&cnt.v_forkpages, p2->p_vmspace->vm_dsize +
  664                     p2->p_vmspace->vm_ssize);
  665         } else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
  666                 atomic_add_int(&cnt.v_vforks, 1);
  667                 atomic_add_int(&cnt.v_vforkpages, p2->p_vmspace->vm_dsize +
  668                     p2->p_vmspace->vm_ssize);
  669         } else if (p1 == &proc0) {
  670                 atomic_add_int(&cnt.v_kthreads, 1);
  671                 atomic_add_int(&cnt.v_kthreadpages, p2->p_vmspace->vm_dsize +
  672                     p2->p_vmspace->vm_ssize);
  673         } else {
  674                 atomic_add_int(&cnt.v_rforks, 1);
  675                 atomic_add_int(&cnt.v_rforkpages, p2->p_vmspace->vm_dsize +
  676                     p2->p_vmspace->vm_ssize);
  677         }
  678 
  679         /*
  680          * Both processes are set up, now check if any loadable modules want
  681          * to adjust anything.
  682          *   What if they have an error? XXX
  683          */
  684         EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
  685 
  686         /*
  687          * Set the child start time and mark the process as being complete.
  688          */
  689         microuptime(&p2->p_stats->p_start);
  690         mtx_lock_spin(&sched_lock);
  691         p2->p_state = PRS_NORMAL;
  692 
  693         /*
  694          * If RFSTOPPED not requested, make child runnable and add to
  695          * run queue.
  696          */
  697         if ((flags & RFSTOPPED) == 0) {
  698                 TD_SET_CAN_RUN(td2);
  699                 setrunqueue(td2, SRQ_BORING);
  700         }
  701         mtx_unlock_spin(&sched_lock);
  702 
  703         /*
  704          * Now can be swapped.
  705          */
  706         PROC_LOCK(p1);
  707         _PRELE(p1);
  708 
  709         /*
  710          * Tell any interested parties about the new process.
  711          */
  712         KNOTE_LOCKED(&p1->p_klist, NOTE_FORK | p2->p_pid);
  713 
  714         PROC_UNLOCK(p1);
  715 
  716         /*
  717          * Preserve synchronization semantics of vfork.  If waiting for
  718          * child to exec or exit, set P_PPWAIT on child, and sleep on our
  719          * proc (in case of exit).
  720          */
  721         PROC_LOCK(p2);
  722         while (p2->p_flag & P_PPWAIT)
  723                 msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
  724         PROC_UNLOCK(p2);
  725 
  726         /*
  727          * If other threads are waiting, let them continue now.
  728          */
  729         if (p1->p_flag & P_HADTHREADS) {
  730                 PROC_LOCK(p1);
  731                 thread_single_end();
  732                 PROC_UNLOCK(p1);
  733         }
  734 
  735         /*
  736          * Return child proc pointer to parent.
  737          */
  738         *procp = p2;
  739         return (0);
  740 fail:
  741         sx_sunlock(&proctree_lock);
  742         if (ppsratecheck(&lastfail, &curfail, 1))
  743                 printf("maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5).\n",
  744                         uid);
  745         sx_xunlock(&allproc_lock);
  746 #ifdef MAC
  747         mac_destroy_proc(newproc);
  748 #endif
  749         uma_zfree(proc_zone, newproc);
  750         if (p1->p_flag & P_HADTHREADS) {
  751                 PROC_LOCK(p1);
  752                 thread_single_end();
  753                 PROC_UNLOCK(p1);
  754         }
  755         tsleep(&forksleep, PUSER, "fork", hz / 2);
  756         return (error);
  757 }
  758 
  759 /*
  760  * Handle the return of a child process from fork1().  This function
  761  * is called from the MD fork_trampoline() entry point.
  762  */
  763 void
  764 fork_exit(callout, arg, frame)
  765         void (*callout)(void *, struct trapframe *);
  766         void *arg;
  767         struct trapframe *frame;
  768 {
  769         struct proc *p;
  770         struct thread *td;
  771 
  772         /*
  773          * Finish setting up thread glue so that it begins execution in a
  774          * non-nested critical section with sched_lock held but not recursed.
  775          */
  776         td = curthread;
  777         p = td->td_proc;
  778         td->td_oncpu = PCPU_GET(cpuid);
  779         KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
  780 
  781         sched_lock.mtx_lock = (uintptr_t)td;
  782         mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
  783         CTR4(KTR_PROC, "fork_exit: new thread %p (kse %p, pid %d, %s)",
  784                 td, td->td_sched, p->p_pid, p->p_comm);
  785 
  786         /*
  787          * Processes normally resume in mi_switch() after being
  788          * cpu_switch()'ed to, but when children start up they arrive here
  789          * instead, so we must do much the same things as mi_switch() would.
  790          */
  791 
  792         if ((td = PCPU_GET(deadthread))) {
  793                 PCPU_SET(deadthread, NULL);
  794                 thread_stash(td);
  795         }
  796         td = curthread;
  797         mtx_unlock_spin(&sched_lock);
  798 
  799         /*
  800          * cpu_set_fork_handler intercepts this function call to
  801          * have this call a non-return function to stay in kernel mode.
  802          * initproc has its own fork handler, but it does return.
  803          */
  804         KASSERT(callout != NULL, ("NULL callout in fork_exit"));
  805         callout(arg, frame);
  806 
  807         /*
  808          * Check if a kernel thread misbehaved and returned from its main
  809          * function.
  810          */
  811         PROC_LOCK(p);
  812         if (p->p_flag & P_KTHREAD) {
  813                 PROC_UNLOCK(p);
  814                 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
  815                     p->p_comm, p->p_pid);
  816                 kthread_exit(0);
  817         }
  818         PROC_UNLOCK(p);
  819         mtx_assert(&Giant, MA_NOTOWNED);
  820 }
  821 
  822 /*
  823  * Simplified back end of syscall(), used when returning from fork()
  824  * directly into user mode.  Giant is not held on entry, and must not
  825  * be held on return.  This function is passed in to fork_exit() as the
  826  * first parameter and is called when returning to a new userland process.
  827  */
  828 void
  829 fork_return(td, frame)
  830         struct thread *td;
  831         struct trapframe *frame;
  832 {
  833 
  834         userret(td, frame, 0);
  835 #ifdef KTRACE
  836         if (KTRPOINT(td, KTR_SYSRET))
  837                 ktrsysret(SYS_fork, 0, 0);
  838 #endif
  839         mtx_assert(&Giant, MA_NOTOWNED);
  840 }

Cache object: f4de9b208454ac4be1fca6e44cf5387d


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.