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  * 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: releng/5.1/sys/kern/kern_fork.c 114983 2003-05-13 20:36:02Z jhb $
   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_
   81 struct fork_args {
   82         int     dummy;
   83 };
   84 #endif
   85 
   86 static int forksleep; /* Place for fork1() to sleep on. */
   87 
   88 /*
   89  * MPSAFE
   90  */
   91 /* ARGSUSED */
   92 int
   93 fork(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 */
  112 int
  113 vfork(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  */
  131 int
  132 rfork(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 
  158 int     nprocs = 1;                             /* process 0 */
  159 int     lastpid = 0;
  160 SYSCTL_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  */
  171 static int randompid = 0;
  172 
  173 static int
  174 sysctl_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 
  195 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
  196     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
  197 
  198 int
  199 fork1(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         int error;
  218 
  219         /* Can't copy and clear */
  220         if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
  221                 return (EINVAL);
  222 
  223         mtx_lock(&Giant);
  224         /*
  225          * Here we don't create a new process, but we divorce
  226          * certain parts of a process from itself.
  227          */
  228         if ((flags & RFPROC) == 0) {
  229                 vm_forkproc(td, NULL, NULL, flags);
  230 
  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                         FILEDESC_LOCK(p1->p_fd);
  246                         if (p1->p_fd->fd_refcnt > 1) {
  247                                 struct filedesc *newfd;
  248 
  249                                 newfd = fdcopy(td->td_proc->p_fd);
  250                                 FILEDESC_UNLOCK(p1->p_fd);
  251                                 fdfree(td);
  252                                 p1->p_fd = newfd;
  253                         } else
  254                                 FILEDESC_UNLOCK(p1->p_fd);
  255                 }
  256                 mtx_unlock(&Giant);
  257                 *procp = NULL;
  258                 return (0);
  259         }
  260 
  261         /*
  262          * Note 1:1 allows for forking with one thread coming out on the
  263          * other side with the expectation that the process is about to
  264          * exec.
  265          */
  266         if (p1->p_flag & P_THREADED) {
  267                 /*
  268                  * Idle the other threads for a second.
  269                  * Since the user space is copied, it must remain stable.
  270                  * In addition, all threads (from the user perspective)
  271                  * need to either be suspended or in the kernel,
  272                  * where they will try restart in the parent and will
  273                  * be aborted in the child.
  274                  */
  275                 PROC_LOCK(p1);
  276                 if (thread_single(SINGLE_NO_EXIT)) {
  277                         /* Abort.. someone else is single threading before us */
  278                         PROC_UNLOCK(p1);
  279                         mtx_unlock(&Giant);
  280                         return (ERESTART);
  281                 }
  282                 PROC_UNLOCK(p1);
  283                 /*
  284                  * All other activity in this process
  285                  * is now suspended at the user boundary,
  286                  * (or other safe places if we think of any).
  287                  */
  288         }
  289 
  290         /* Allocate new proc. */
  291         newproc = uma_zalloc(proc_zone, M_WAITOK);
  292 #ifdef MAC
  293         mac_init_proc(newproc);
  294 #endif
  295 
  296         /*
  297          * Although process entries are dynamically created, we still keep
  298          * a global limit on the maximum number we will create.  Don't allow
  299          * a nonprivileged user to use the last ten processes; don't let root
  300          * exceed the limit. The variable nprocs is the current number of
  301          * processes, maxproc is the limit.
  302          */
  303         sx_xlock(&allproc_lock);
  304         uid = td->td_ucred->cr_ruid;
  305         if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) {
  306                 error = EAGAIN;
  307                 goto fail;
  308         }
  309 
  310         /*
  311          * Increment the count of procs running with this uid. Don't allow
  312          * a nonprivileged user to exceed their current limit.
  313          */
  314         PROC_LOCK(p1);
  315         ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1,
  316                 (uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
  317         PROC_UNLOCK(p1);
  318         if (!ok) {
  319                 error = EAGAIN;
  320                 goto fail;
  321         }
  322 
  323         /*
  324          * Increment the nprocs resource before blocking can occur.  There
  325          * are hard-limits as to the number of processes that can run.
  326          */
  327         nprocs++;
  328 
  329         /*
  330          * Find an unused process ID.  We remember a range of unused IDs
  331          * ready to use (from lastpid+1 through pidchecked-1).
  332          *
  333          * If RFHIGHPID is set (used during system boot), do not allocate
  334          * low-numbered pids.
  335          */
  336         trypid = lastpid + 1;
  337         if (flags & RFHIGHPID) {
  338                 if (trypid < 10) {
  339                         trypid = 10;
  340                 }
  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->pg_id == trypid ||
  372                             p2->p_session->s_sid == trypid) {
  373                                 trypid++;
  374                                 if (trypid >= pidchecked) {
  375                                         PROC_UNLOCK(p2);
  376                                         goto retry;
  377                                 }
  378                         }
  379                         if (p2->p_pid > trypid && pidchecked > p2->p_pid)
  380                                 pidchecked = p2->p_pid;
  381                         if (p2->p_pgrp->pg_id > trypid &&
  382                             pidchecked > p2->p_pgrp->pg_id)
  383                                 pidchecked = p2->p_pgrp->pg_id;
  384                         if (p2->p_session->s_sid > trypid &&
  385                             pidchecked > p2->p_session->s_sid)
  386                                 pidchecked = p2->p_session->s_sid;
  387                         PROC_UNLOCK(p2);
  388                 }
  389                 if (!doingzomb) {
  390                         doingzomb = 1;
  391                         p2 = LIST_FIRST(&zombproc);
  392                         goto again;
  393                 }
  394         }
  395 
  396         /*
  397          * RFHIGHPID does not mess with the lastpid counter during boot.
  398          */
  399         if (flags & RFHIGHPID)
  400                 pidchecked = 0;
  401         else
  402                 lastpid = trypid;
  403 
  404         p2 = newproc;
  405         p2->p_state = PRS_NEW;          /* protect against others */
  406         p2->p_pid = trypid;
  407         LIST_INSERT_HEAD(&allproc, p2, p_list);
  408         LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
  409         sx_xunlock(&allproc_lock);
  410 
  411         /*
  412          * Malloc things while we don't hold any locks.
  413          */
  414         if (flags & RFSIGSHARE)
  415                 newsigacts = NULL;
  416         else
  417                 newsigacts = sigacts_alloc();
  418 
  419         /*
  420          * Copy filedesc.
  421          */
  422         if (flags & RFCFDG)
  423                 fd = fdinit(td->td_proc->p_fd);
  424         else if (flags & RFFDG) {
  425                 FILEDESC_LOCK(p1->p_fd);
  426                 fd = fdcopy(td->td_proc->p_fd);
  427                 FILEDESC_UNLOCK(p1->p_fd);
  428         } else
  429                 fd = fdshare(p1->p_fd);
  430 
  431         /*
  432          * Make a proc table entry for the new process.
  433          * Start by zeroing the section of proc that is zero-initialized,
  434          * then copy the section that is copied directly from the parent.
  435          */
  436         td2 = FIRST_THREAD_IN_PROC(p2);
  437         kg2 = FIRST_KSEGRP_IN_PROC(p2);
  438         ke2 = FIRST_KSE_IN_KSEGRP(kg2);
  439 
  440         /* Allocate and switch to an alternate kstack if specified */
  441         if (pages != 0)
  442                 pmap_new_altkstack(td2, pages);
  443 
  444         PROC_LOCK(p2);
  445         PROC_LOCK(p1);
  446 
  447 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
  448 
  449         bzero(&p2->p_startzero,
  450             (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
  451         bzero(&ke2->ke_startzero,
  452             (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
  453         bzero(&td2->td_startzero,
  454             (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
  455         bzero(&kg2->kg_startzero,
  456             (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
  457 
  458         bcopy(&p1->p_startcopy, &p2->p_startcopy,
  459             (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
  460         bcopy(&td->td_startcopy, &td2->td_startcopy,
  461             (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
  462         bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
  463             (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
  464 #undef RANGEOF
  465 
  466         /* Set up the thread as an active thread (as if runnable). */
  467         ke2->ke_state = KES_THREAD;
  468         ke2->ke_thread = td2;
  469         td2->td_kse = ke2;
  470 
  471         /*
  472          * Duplicate sub-structures as needed.
  473          * Increase reference counts on shared objects.
  474          * The p_stats substruct is set in vm_forkproc.
  475          */
  476         p2->p_flag = 0;
  477         if (p1->p_flag & P_PROFIL)
  478                 startprofclock(p2);
  479         mtx_lock_spin(&sched_lock);
  480         p2->p_sflag = PS_INMEM;
  481         /*
  482          * Allow the scheduler to adjust the priority of the child and
  483          * parent while we hold the sched_lock.
  484          */
  485         sched_fork(p1, p2);
  486 
  487         mtx_unlock_spin(&sched_lock);
  488         p2->p_ucred = crhold(td->td_ucred);
  489         td2->td_ucred = crhold(p2->p_ucred);    /* XXXKSE */
  490 
  491         pargs_hold(p2->p_args);
  492 
  493         if (flags & RFSIGSHARE) {
  494                 p2->p_sigacts = sigacts_hold(p1->p_sigacts);
  495         } else {
  496                 sigacts_copy(newsigacts, p1->p_sigacts);
  497                 p2->p_sigacts = newsigacts;
  498         }
  499         if (flags & RFLINUXTHPN) 
  500                 p2->p_sigparent = SIGUSR1;
  501         else
  502                 p2->p_sigparent = SIGCHLD;
  503 
  504         /* Bump references to the text vnode (for procfs) */
  505         p2->p_textvp = p1->p_textvp;
  506         if (p2->p_textvp)
  507                 VREF(p2->p_textvp);
  508         p2->p_fd = fd;
  509         PROC_UNLOCK(p1);
  510         PROC_UNLOCK(p2);
  511 
  512         /*
  513          * p_limit is copy-on-write, bump refcnt,
  514          */
  515         p2->p_limit = p1->p_limit;
  516         p2->p_limit->p_refcnt++;
  517 
  518         /*
  519          * Setup linkage for kernel based threading
  520          */
  521         if((flags & RFTHREAD) != 0) {
  522                 mtx_lock(&ppeers_lock);
  523                 p2->p_peers = p1->p_peers;
  524                 p1->p_peers = p2;
  525                 p2->p_leader = p1->p_leader;
  526                 mtx_unlock(&ppeers_lock);
  527                 PROC_LOCK(p1->p_leader);
  528                 if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
  529                         PROC_UNLOCK(p1->p_leader);
  530                         /*
  531                          * The task leader is exiting, so process p1 is
  532                          * going to be killed shortly.  Since p1 obviously
  533                          * isn't dead yet, we know that the leader is either
  534                          * sending SIGKILL's to all the processes in this
  535                          * task or is sleeping waiting for all the peers to
  536                          * exit.  We let p1 complete the fork, but we need
  537                          * to go ahead and kill the new process p2 since
  538                          * the task leader may not get a chance to send
  539                          * SIGKILL to it.  We leave it on the list so that
  540                          * the task leader will wait for this new process
  541                          * to commit suicide.
  542                          */
  543                         PROC_LOCK(p2);
  544                         psignal(p2, SIGKILL);
  545                         PROC_UNLOCK(p2);
  546                 } else
  547                         PROC_UNLOCK(p1->p_leader);
  548         } else {
  549                 p2->p_peers = NULL;
  550                 p2->p_leader = p2;
  551         }
  552 
  553         sx_xlock(&proctree_lock);
  554         PGRP_LOCK(p1->p_pgrp);
  555         PROC_LOCK(p2);
  556         PROC_LOCK(p1);
  557 
  558         /*
  559          * Preserve some more flags in subprocess.  P_PROFIL has already
  560          * been preserved.
  561          */
  562         p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
  563         SESS_LOCK(p1->p_session);
  564         if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
  565                 p2->p_flag |= P_CONTROLT;
  566         SESS_UNLOCK(p1->p_session);
  567         if (flags & RFPPWAIT)
  568                 p2->p_flag |= P_PPWAIT;
  569 
  570         LIST_INSERT_AFTER(p1, p2, p_pglist);
  571         PGRP_UNLOCK(p1->p_pgrp);
  572         LIST_INIT(&p2->p_children);
  573 
  574         callout_init(&p2->p_itcallout, 1);
  575 
  576 #ifdef KTRACE
  577         /*
  578          * Copy traceflag and tracefile if enabled.
  579          */
  580         mtx_lock(&ktrace_mtx);
  581         KASSERT(p2->p_tracevp == NULL, ("new process has a ktrace vnode"));
  582         if (p1->p_traceflag & KTRFAC_INHERIT) {
  583                 p2->p_traceflag = p1->p_traceflag;
  584                 if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
  585                         VREF(p2->p_tracevp);
  586                         KASSERT(p1->p_tracecred != NULL,
  587                             ("ktrace vnode with no cred"));
  588                         p2->p_tracecred = crhold(p1->p_tracecred);
  589                 }
  590         }
  591         mtx_unlock(&ktrace_mtx);
  592 #endif
  593 
  594         /*
  595          * If PF_FORK is set, the child process inherits the
  596          * procfs ioctl flags from its parent.
  597          */
  598         if (p1->p_pfsflags & PF_FORK) {
  599                 p2->p_stops = p1->p_stops;
  600                 p2->p_pfsflags = p1->p_pfsflags;
  601         }
  602 
  603         /*
  604          * This begins the section where we must prevent the parent
  605          * from being swapped.
  606          */
  607         _PHOLD(p1);
  608         PROC_UNLOCK(p1);
  609 
  610         /*
  611          * Attach the new process to its parent.
  612          *
  613          * If RFNOWAIT is set, the newly created process becomes a child
  614          * of init.  This effectively disassociates the child from the
  615          * parent.
  616          */
  617         if (flags & RFNOWAIT)
  618                 pptr = initproc;
  619         else
  620                 pptr = p1;
  621         p2->p_pptr = pptr;
  622         LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
  623         sx_xunlock(&proctree_lock);
  624 
  625         /* Inform accounting that we have forked. */
  626         p2->p_acflag = AFORK;
  627         PROC_UNLOCK(p2);
  628 
  629         /*
  630          * Finish creating the child process.  It will return via a different
  631          * execution path later.  (ie: directly into user mode)
  632          */
  633         vm_forkproc(td, p2, td2, flags);
  634 
  635         if (flags == (RFFDG | RFPROC)) {
  636                 cnt.v_forks++;
  637                 cnt.v_forkpages += p2->p_vmspace->vm_dsize +
  638                     p2->p_vmspace->vm_ssize;
  639         } else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
  640                 cnt.v_vforks++;
  641                 cnt.v_vforkpages += p2->p_vmspace->vm_dsize +
  642                     p2->p_vmspace->vm_ssize;
  643         } else if (p1 == &proc0) {
  644                 cnt.v_kthreads++;
  645                 cnt.v_kthreadpages += p2->p_vmspace->vm_dsize +
  646                     p2->p_vmspace->vm_ssize;
  647         } else {
  648                 cnt.v_rforks++;
  649                 cnt.v_rforkpages += p2->p_vmspace->vm_dsize +
  650                     p2->p_vmspace->vm_ssize;
  651         }
  652 
  653         /*
  654          * Both processes are set up, now check if any loadable modules want
  655          * to adjust anything.
  656          *   What if they have an error? XXX
  657          */
  658         EVENTHANDLER_INVOKE(process_fork, p1, p2, flags);
  659 
  660         /*
  661          * If RFSTOPPED not requested, make child runnable and add to
  662          * run queue.
  663          */
  664         microuptime(&p2->p_stats->p_start);
  665         if ((flags & RFSTOPPED) == 0) {
  666                 mtx_lock_spin(&sched_lock);
  667                 p2->p_state = PRS_NORMAL;
  668                 TD_SET_CAN_RUN(td2);
  669                 setrunqueue(td2);
  670                 mtx_unlock_spin(&sched_lock);
  671         }
  672 
  673         /*
  674          * Now can be swapped.
  675          */
  676         PROC_LOCK(p1);
  677         _PRELE(p1);
  678 
  679         /*
  680          * tell any interested parties about the new process
  681          */
  682         KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
  683         PROC_UNLOCK(p1);
  684 
  685         /*
  686          * Preserve synchronization semantics of vfork.  If waiting for
  687          * child to exec or exit, set P_PPWAIT on child, and sleep on our
  688          * proc (in case of exit).
  689          */
  690         PROC_LOCK(p2);
  691         while (p2->p_flag & P_PPWAIT)
  692                 msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
  693         PROC_UNLOCK(p2);
  694 
  695         /*
  696          * If other threads are waiting, let them continue now
  697          */
  698         if (p1->p_flag & P_THREADED) {
  699                 PROC_LOCK(p1);
  700                 thread_single_end();
  701                 PROC_UNLOCK(p1);
  702         }
  703 
  704         /*
  705          * Return child proc pointer to parent.
  706          */
  707         mtx_unlock(&Giant);
  708         *procp = p2;
  709         return (0);
  710 fail:
  711         sx_xunlock(&allproc_lock);
  712         uma_zfree(proc_zone, newproc);
  713         if (p1->p_flag & P_THREADED) {
  714                 PROC_LOCK(p1);
  715                 thread_single_end();
  716                 PROC_UNLOCK(p1);
  717         }
  718         tsleep(&forksleep, PUSER, "fork", hz / 2);
  719         mtx_unlock(&Giant);
  720         return (error);
  721 }
  722 
  723 /*
  724  * Handle the return of a child process from fork1().  This function
  725  * is called from the MD fork_trampoline() entry point.
  726  */
  727 void
  728 fork_exit(callout, arg, frame)
  729         void (*callout)(void *, struct trapframe *);
  730         void *arg;
  731         struct trapframe *frame;
  732 {
  733         struct thread *td;
  734         struct proc *p;
  735 
  736         if ((td = PCPU_GET(deadthread))) {
  737                 PCPU_SET(deadthread, NULL);
  738                 thread_stash(td);
  739         }
  740         td = curthread;
  741         p = td->td_proc;
  742         td->td_oncpu = PCPU_GET(cpuid);
  743         p->p_state = PRS_NORMAL;
  744         /*
  745          * Finish setting up thread glue.  We need to initialize
  746          * the thread into a td_critnest=1 state.  Some platforms
  747          * may have already partially or fully initialized td_critnest
  748          * and/or td_md.md_savecrit (when applciable).
  749          *
  750          * see <arch>/<arch>/critical.c
  751          */
  752         sched_lock.mtx_lock = (uintptr_t)td;
  753         sched_lock.mtx_recurse = 0;
  754         cpu_critical_fork_exit();
  755         CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid,
  756             p->p_comm);
  757         if (PCPU_GET(switchtime.sec) == 0)
  758                 binuptime(PCPU_PTR(switchtime));
  759         PCPU_SET(switchticks, ticks);
  760         mtx_unlock_spin(&sched_lock);
  761 
  762         /*
  763          * cpu_set_fork_handler intercepts this function call to
  764          * have this call a non-return function to stay in kernel mode.
  765          * initproc has its own fork handler, but it does return.
  766          */
  767         KASSERT(callout != NULL, ("NULL callout in fork_exit"));
  768         callout(arg, frame);
  769 
  770         /*
  771          * Check if a kernel thread misbehaved and returned from its main
  772          * function.
  773          */
  774         PROC_LOCK(p);
  775         if (p->p_flag & P_KTHREAD) {
  776                 PROC_UNLOCK(p);
  777                 mtx_lock(&Giant);
  778                 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
  779                     p->p_comm, p->p_pid);
  780                 kthread_exit(0);
  781         }
  782         PROC_UNLOCK(p);
  783 #ifdef DIAGNOSTIC
  784         cred_free_thread(td);
  785 #endif
  786         mtx_assert(&Giant, MA_NOTOWNED);
  787 }
  788 
  789 /*
  790  * Simplified back end of syscall(), used when returning from fork()
  791  * directly into user mode.  Giant is not held on entry, and must not
  792  * be held on return.  This function is passed in to fork_exit() as the
  793  * first parameter and is called when returning to a new userland process.
  794  */
  795 void
  796 fork_return(td, frame)
  797         struct thread *td;
  798         struct trapframe *frame;
  799 {
  800 
  801         userret(td, frame, 0);
  802 #ifdef KTRACE
  803         if (KTRPOINT(td, KTR_SYSRET))
  804                 ktrsysret(SYS_fork, 0, 0);
  805 #endif
  806         mtx_assert(&Giant, MA_NOTOWNED);
  807 }

Cache object: 3a252b69ecbadf983bdd1e2f8919d53b


[ 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.