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_descrip.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_descrip.c      8.6 (Berkeley) 4/19/94
   35  */
   36 
   37 #include <sys/cdefs.h>
   38 __FBSDID("$FreeBSD: releng/6.4/sys/kern/kern_descrip.c 178459 2008-04-24 10:46:25Z dfr $");
   39 
   40 #include "opt_compat.h"
   41 #include "opt_ddb.h"
   42 
   43 #include <sys/param.h>
   44 #include <sys/systm.h>
   45 
   46 #include <sys/conf.h>
   47 #include <sys/fcntl.h>
   48 #include <sys/file.h>
   49 #include <sys/filedesc.h>
   50 #include <sys/filio.h>
   51 #include <sys/jail.h>
   52 #include <sys/kernel.h>
   53 #include <sys/limits.h>
   54 #include <sys/lock.h>
   55 #include <sys/malloc.h>
   56 #include <sys/mount.h>
   57 #include <sys/mutex.h>
   58 #include <sys/namei.h>
   59 #include <sys/proc.h>
   60 #include <sys/resourcevar.h>
   61 #include <sys/signalvar.h>
   62 #include <sys/socketvar.h>
   63 #include <sys/stat.h>
   64 #include <sys/sx.h>
   65 #include <sys/syscallsubr.h>
   66 #include <sys/sysctl.h>
   67 #include <sys/sysproto.h>
   68 #include <sys/unistd.h>
   69 #include <sys/vnode.h>
   70 
   71 #include <security/audit/audit.h>
   72 
   73 #include <vm/uma.h>
   74 
   75 #include <ddb/ddb.h>
   76 
   77 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
   78 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
   79                      "file desc to leader structures");
   80 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
   81 
   82 static uma_zone_t file_zone;
   83 
   84 
   85 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
   86 enum dup_type { DUP_VARIABLE, DUP_FIXED };
   87 
   88 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
   89     register_t *retval);
   90 static int      fd_first_free(struct filedesc *, int, int);
   91 static int      fd_last_used(struct filedesc *, int, int);
   92 static void     fdgrowtable(struct filedesc *, int);
   93 static int      fdrop_locked(struct file *fp, struct thread *td);
   94 static void     fdunused(struct filedesc *fdp, int fd);
   95 static void     fdused(struct filedesc *fdp, int fd);
   96 
   97 /*
   98  * A process is initially started out with NDFILE descriptors stored within
   99  * this structure, selected to be enough for typical applications based on
  100  * the historical limit of 20 open files (and the usage of descriptors by
  101  * shells).  If these descriptors are exhausted, a larger descriptor table
  102  * may be allocated, up to a process' resource limit; the internal arrays
  103  * are then unused.
  104  */
  105 #define NDFILE          20
  106 #define NDSLOTSIZE      sizeof(NDSLOTTYPE)
  107 #define NDENTRIES       (NDSLOTSIZE * __CHAR_BIT)
  108 #define NDSLOT(x)       ((x) / NDENTRIES)
  109 #define NDBIT(x)        ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
  110 #define NDSLOTS(x)      (((x) + NDENTRIES - 1) / NDENTRIES)
  111 
  112 /*
  113  * Storage required per open file descriptor.
  114  */
  115 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
  116 
  117 /*
  118  * Basic allocation of descriptors:
  119  * one of the above, plus arrays for NDFILE descriptors.
  120  */
  121 struct filedesc0 {
  122         struct  filedesc fd_fd;
  123         /*
  124          * These arrays are used when the number of open files is
  125          * <= NDFILE, and are then pointed to by the pointers above.
  126          */
  127         struct  file *fd_dfiles[NDFILE];
  128         char    fd_dfileflags[NDFILE];
  129         NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
  130 };
  131 
  132 /*
  133  * Descriptor management.
  134  */
  135 struct filelist filehead;       /* head of list of open files */
  136 int openfiles;                  /* actual number of open files */
  137 struct sx filelist_lock;        /* sx to protect filelist */
  138 struct mtx sigio_lock;          /* mtx to protect pointers to sigio */
  139 
  140 /* A mutex to protect the association between a proc and filedesc. */
  141 static struct mtx       fdesc_mtx;
  142 
  143 /*
  144  * Find the first zero bit in the given bitmap, starting at low and not
  145  * exceeding size - 1.
  146  */
  147 static int
  148 fd_first_free(struct filedesc *fdp, int low, int size)
  149 {
  150         NDSLOTTYPE *map = fdp->fd_map;
  151         NDSLOTTYPE mask;
  152         int off, maxoff;
  153 
  154         if (low >= size)
  155                 return (low);
  156 
  157         off = NDSLOT(low);
  158         if (low % NDENTRIES) {
  159                 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
  160                 if ((mask &= ~map[off]) != 0UL)
  161                         return (off * NDENTRIES + ffsl(mask) - 1);
  162                 ++off;
  163         }
  164         for (maxoff = NDSLOTS(size); off < maxoff; ++off)
  165                 if (map[off] != ~0UL)
  166                         return (off * NDENTRIES + ffsl(~map[off]) - 1);
  167         return (size);
  168 }
  169 
  170 /*
  171  * Find the highest non-zero bit in the given bitmap, starting at low and
  172  * not exceeding size - 1.
  173  */
  174 static int
  175 fd_last_used(struct filedesc *fdp, int low, int size)
  176 {
  177         NDSLOTTYPE *map = fdp->fd_map;
  178         NDSLOTTYPE mask;
  179         int off, minoff;
  180 
  181         if (low >= size)
  182                 return (-1);
  183 
  184         off = NDSLOT(size);
  185         if (size % NDENTRIES) {
  186                 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
  187                 if ((mask &= map[off]) != 0)
  188                         return (off * NDENTRIES + flsl(mask) - 1);
  189                 --off;
  190         }
  191         for (minoff = NDSLOT(low); off >= minoff; --off)
  192                 if (map[off] != 0)
  193                         return (off * NDENTRIES + flsl(map[off]) - 1);
  194         return (low - 1);
  195 }
  196 
  197 static int
  198 fdisused(struct filedesc *fdp, int fd)
  199 {
  200         KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
  201             ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
  202         return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
  203 }
  204 
  205 /*
  206  * Mark a file descriptor as used.
  207  */
  208 static void
  209 fdused(struct filedesc *fdp, int fd)
  210 {
  211         FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
  212         KASSERT(!fdisused(fdp, fd),
  213             ("fd already used"));
  214         fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
  215         if (fd > fdp->fd_lastfile)
  216                 fdp->fd_lastfile = fd;
  217         if (fd == fdp->fd_freefile)
  218                 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
  219 }
  220 
  221 /*
  222  * Mark a file descriptor as unused.
  223  */
  224 static void
  225 fdunused(struct filedesc *fdp, int fd)
  226 {
  227         FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
  228         KASSERT(fdisused(fdp, fd),
  229             ("fd is already unused"));
  230         KASSERT(fdp->fd_ofiles[fd] == NULL,
  231             ("fd is still in use"));
  232         fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
  233         if (fd < fdp->fd_freefile)
  234                 fdp->fd_freefile = fd;
  235         if (fd == fdp->fd_lastfile)
  236                 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
  237 }
  238 
  239 /*
  240  * System calls on descriptors.
  241  */
  242 #ifndef _SYS_SYSPROTO_H_
  243 struct getdtablesize_args {
  244         int     dummy;
  245 };
  246 #endif
  247 /*
  248  * MPSAFE
  249  */
  250 /* ARGSUSED */
  251 int
  252 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
  253 {
  254         struct proc *p = td->td_proc;
  255 
  256         PROC_LOCK(p);
  257         td->td_retval[0] =
  258             min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
  259         PROC_UNLOCK(p);
  260         return (0);
  261 }
  262 
  263 /*
  264  * Duplicate a file descriptor to a particular value.
  265  *
  266  * note: keep in mind that a potential race condition exists when closing
  267  * descriptors from a shared descriptor table (via rfork).
  268  */
  269 #ifndef _SYS_SYSPROTO_H_
  270 struct dup2_args {
  271         u_int   from;
  272         u_int   to;
  273 };
  274 #endif
  275 /*
  276  * MPSAFE
  277  */
  278 /* ARGSUSED */
  279 int
  280 dup2(struct thread *td, struct dup2_args *uap)
  281 {
  282 
  283         return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
  284                     td->td_retval));
  285 }
  286 
  287 /*
  288  * Duplicate a file descriptor.
  289  */
  290 #ifndef _SYS_SYSPROTO_H_
  291 struct dup_args {
  292         u_int   fd;
  293 };
  294 #endif
  295 /*
  296  * MPSAFE
  297  */
  298 /* ARGSUSED */
  299 int
  300 dup(struct thread *td, struct dup_args *uap)
  301 {
  302 
  303         return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
  304 }
  305 
  306 /*
  307  * The file control system call.
  308  */
  309 #ifndef _SYS_SYSPROTO_H_
  310 struct fcntl_args {
  311         int     fd;
  312         int     cmd;
  313         long    arg;
  314 };
  315 #endif
  316 /*
  317  * MPSAFE
  318  */
  319 /* ARGSUSED */
  320 int
  321 fcntl(struct thread *td, struct fcntl_args *uap)
  322 {
  323         struct flock fl;
  324         struct oflock ofl;
  325         intptr_t arg;
  326         int error;
  327         int cmd;
  328 
  329         error = 0;
  330         cmd = uap->cmd;
  331         switch (uap->cmd) {
  332         case F_OGETLK:
  333         case F_OSETLK:
  334         case F_OSETLKW:
  335                 /*
  336                  * Convert old flock structure to new.
  337                  */
  338                 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
  339                 fl.l_start = ofl.l_start;
  340                 fl.l_len = ofl.l_len;
  341                 fl.l_pid = ofl.l_pid;
  342                 fl.l_type = ofl.l_type;
  343                 fl.l_whence = ofl.l_whence;
  344                 fl.l_sysid = 0;
  345 
  346                 switch (uap->cmd) {
  347                 case F_OGETLK:
  348                     cmd = F_GETLK;
  349                     break;
  350                 case F_OSETLK:
  351                     cmd = F_SETLK;
  352                     break;
  353                 case F_OSETLKW:
  354                     cmd = F_SETLKW;
  355                     break;
  356                 }
  357                 arg = (intptr_t)&fl;
  358                 break;
  359         case F_GETLK:
  360         case F_SETLK:
  361         case F_SETLKW:
  362         case F_SETLK_REMOTE:
  363                 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
  364                 arg = (intptr_t)&fl;
  365                 break;
  366         default:
  367                 arg = uap->arg;
  368                 break;
  369         }
  370         if (error)
  371                 return (error);
  372         error = kern_fcntl(td, uap->fd, cmd, arg);
  373         if (error)
  374                 return (error);
  375         if (uap->cmd == F_OGETLK) {
  376                 ofl.l_start = fl.l_start;
  377                 ofl.l_len = fl.l_len;
  378                 ofl.l_pid = fl.l_pid;
  379                 ofl.l_type = fl.l_type;
  380                 ofl.l_whence = fl.l_whence;
  381                 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
  382         } else if (uap->cmd == F_GETLK) {
  383                 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
  384         }
  385         return (error);
  386 }
  387 
  388 int
  389 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
  390 {
  391         struct filedesc *fdp;
  392         struct flock *flp;
  393         struct file *fp;
  394         struct proc *p;
  395         char *pop;
  396         struct vnode *vp;
  397         u_int newmin;
  398         int error, flg, tmp;
  399         int giant_locked;
  400 
  401         /*
  402          * XXXRW: Some fcntl() calls require Giant -- others don't.  Try to
  403          * avoid grabbing Giant for calls we know don't need it.
  404          */
  405         switch (cmd) {
  406         case F_DUPFD:
  407         case F_GETFD:
  408         case F_SETFD:
  409         case F_GETFL:
  410                 giant_locked = 0;
  411                 break;
  412 
  413         default:
  414                 giant_locked = 1;
  415                 mtx_lock(&Giant);
  416         }
  417 
  418         error = 0;
  419         flg = F_POSIX;
  420         p = td->td_proc;
  421         fdp = p->p_fd;
  422         FILEDESC_LOCK(fdp);
  423         if ((unsigned)fd >= fdp->fd_nfiles ||
  424             (fp = fdp->fd_ofiles[fd]) == NULL) {
  425                 FILEDESC_UNLOCK(fdp);
  426                 error = EBADF;
  427                 goto done2;
  428         }
  429         pop = &fdp->fd_ofileflags[fd];
  430 
  431         switch (cmd) {
  432         case F_DUPFD:
  433                 /* mtx_assert(&Giant, MA_NOTOWNED); */
  434                 FILEDESC_UNLOCK(fdp);
  435                 newmin = arg;
  436                 PROC_LOCK(p);
  437                 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
  438                     newmin >= maxfilesperproc) {
  439                         PROC_UNLOCK(p);
  440                         error = EINVAL;
  441                         break;
  442                 }
  443                 PROC_UNLOCK(p);
  444                 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
  445                 break;
  446 
  447         case F_GETFD:
  448                 /* mtx_assert(&Giant, MA_NOTOWNED); */
  449                 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
  450                 FILEDESC_UNLOCK(fdp);
  451                 break;
  452 
  453         case F_SETFD:
  454                 /* mtx_assert(&Giant, MA_NOTOWNED); */
  455                 *pop = (*pop &~ UF_EXCLOSE) |
  456                     (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
  457                 FILEDESC_UNLOCK(fdp);
  458                 break;
  459 
  460         case F_GETFL:
  461                 /* mtx_assert(&Giant, MA_NOTOWNED); */
  462                 FILE_LOCK(fp);
  463                 td->td_retval[0] = OFLAGS(fp->f_flag);
  464                 FILE_UNLOCK(fp);
  465                 FILEDESC_UNLOCK(fdp);
  466                 break;
  467 
  468         case F_SETFL:
  469                 mtx_assert(&Giant, MA_OWNED);
  470                 FILE_LOCK(fp);
  471                 fhold_locked(fp);
  472                 fp->f_flag &= ~FCNTLFLAGS;
  473                 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
  474                 FILE_UNLOCK(fp);
  475                 FILEDESC_UNLOCK(fdp);
  476                 tmp = fp->f_flag & FNONBLOCK;
  477                 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
  478                 if (error) {
  479                         fdrop(fp, td);
  480                         break;
  481                 }
  482                 tmp = fp->f_flag & FASYNC;
  483                 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
  484                 if (error == 0) {
  485                         fdrop(fp, td);
  486                         break;
  487                 }
  488                 FILE_LOCK(fp);
  489                 fp->f_flag &= ~FNONBLOCK;
  490                 FILE_UNLOCK(fp);
  491                 tmp = 0;
  492                 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
  493                 fdrop(fp, td);
  494                 break;
  495 
  496         case F_GETOWN:
  497                 mtx_assert(&Giant, MA_OWNED);
  498                 fhold(fp);
  499                 FILEDESC_UNLOCK(fdp);
  500                 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
  501                 if (error == 0)
  502                         td->td_retval[0] = tmp;
  503                 fdrop(fp, td);
  504                 break;
  505 
  506         case F_SETOWN:
  507                 mtx_assert(&Giant, MA_OWNED);
  508                 fhold(fp);
  509                 FILEDESC_UNLOCK(fdp);
  510                 tmp = arg;
  511                 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
  512                 fdrop(fp, td);
  513                 break;
  514 
  515         case F_SETLK_REMOTE:
  516                 mtx_assert(&Giant, MA_OWNED);
  517                 error = suser(td);
  518                 if (error)
  519                         return (error);
  520                 flg = F_REMOTE;
  521                 goto do_setlk;
  522 
  523         case F_SETLKW:
  524                 mtx_assert(&Giant, MA_OWNED);
  525                 flg |= F_WAIT;
  526                 /* FALLTHROUGH F_SETLK */
  527 
  528         case F_SETLK:
  529         do_setlk:
  530                 mtx_assert(&Giant, MA_OWNED);
  531                 if (fp->f_type != DTYPE_VNODE) {
  532                         FILEDESC_UNLOCK(fdp);
  533                         error = EBADF;
  534                         break;
  535                 }
  536 
  537                 flp = (struct flock *)arg;
  538                 if (flp->l_whence == SEEK_CUR) {
  539                         if (fp->f_offset < 0 ||
  540                             (flp->l_start > 0 &&
  541                              fp->f_offset > OFF_MAX - flp->l_start)) {
  542                                 FILEDESC_UNLOCK(fdp);
  543                                 error = EOVERFLOW;
  544                                 break;
  545                         }
  546                         flp->l_start += fp->f_offset;
  547                 }
  548 
  549                 /*
  550                  * VOP_ADVLOCK() may block.
  551                  */
  552                 fhold(fp);
  553                 FILEDESC_UNLOCK(fdp);
  554                 vp = fp->f_vnode;
  555 
  556                 switch (flp->l_type) {
  557                 case F_RDLCK:
  558                         if ((fp->f_flag & FREAD) == 0) {
  559                                 error = EBADF;
  560                                 break;
  561                         }
  562                         PROC_LOCK(p->p_leader);
  563                         p->p_leader->p_flag |= P_ADVLOCK;
  564                         PROC_UNLOCK(p->p_leader);
  565                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
  566                             flp, flg);
  567                         break;
  568                 case F_WRLCK:
  569                         if ((fp->f_flag & FWRITE) == 0) {
  570                                 error = EBADF;
  571                                 break;
  572                         }
  573                         PROC_LOCK(p->p_leader);
  574                         p->p_leader->p_flag |= P_ADVLOCK;
  575                         PROC_UNLOCK(p->p_leader);
  576                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
  577                             flp, flg);
  578                         break;
  579                 case F_UNLCK:
  580                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
  581                             flp, flg);
  582                         break;
  583                 case F_UNLCKSYS:
  584                         /*
  585                          * Temporary api for testing remote lock
  586                          * infrastructure.
  587                          */
  588                         if (flg != F_REMOTE) {
  589                                 error = EINVAL;
  590                                 break;
  591                         }
  592                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
  593                             F_UNLCKSYS, flp, flg);
  594                         break;
  595                 default:
  596                         error = EINVAL;
  597                         break;
  598                 }
  599                 /* Check for race with close */
  600                 FILEDESC_LOCK_FAST(fdp);
  601                 if ((unsigned) fd >= fdp->fd_nfiles ||
  602                     fp != fdp->fd_ofiles[fd]) {
  603                         FILEDESC_UNLOCK_FAST(fdp);
  604                         flp->l_whence = SEEK_SET;
  605                         flp->l_start = 0;
  606                         flp->l_len = 0;
  607                         flp->l_type = F_UNLCK;
  608                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
  609                                            F_UNLCK, flp, F_POSIX);
  610                 } else
  611                         FILEDESC_UNLOCK_FAST(fdp);
  612                 fdrop(fp, td);
  613                 break;
  614 
  615         case F_GETLK:
  616                 mtx_assert(&Giant, MA_OWNED);
  617                 if (fp->f_type != DTYPE_VNODE) {
  618                         FILEDESC_UNLOCK(fdp);
  619                         error = EBADF;
  620                         break;
  621                 }
  622                 flp = (struct flock *)arg;
  623                 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
  624                     flp->l_type != F_UNLCK) {
  625                         FILEDESC_UNLOCK(fdp);
  626                         error = EINVAL;
  627                         break;
  628                 }
  629                 if (flp->l_whence == SEEK_CUR) {
  630                         if ((flp->l_start > 0 &&
  631                             fp->f_offset > OFF_MAX - flp->l_start) ||
  632                             (flp->l_start < 0 &&
  633                              fp->f_offset < OFF_MIN - flp->l_start)) {
  634                                 FILEDESC_UNLOCK(fdp);
  635                                 error = EOVERFLOW;
  636                                 break;
  637                         }
  638                         flp->l_start += fp->f_offset;
  639                 }
  640                 /*
  641                  * VOP_ADVLOCK() may block.
  642                  */
  643                 fhold(fp);
  644                 FILEDESC_UNLOCK(fdp);
  645                 vp = fp->f_vnode;
  646                 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
  647                     F_POSIX);
  648                 fdrop(fp, td);
  649                 break;
  650         default:
  651                 FILEDESC_UNLOCK(fdp);
  652                 error = EINVAL;
  653                 break;
  654         }
  655 done2:
  656         if (giant_locked)
  657                 mtx_unlock(&Giant);
  658         return (error);
  659 }
  660 
  661 /*
  662  * Common code for dup, dup2, and fcntl(F_DUPFD).
  663  */
  664 static int
  665 do_dup(struct thread *td, enum dup_type type, int old, int new, register_t *retval)
  666 {
  667         struct filedesc *fdp;
  668         struct proc *p;
  669         struct file *fp;
  670         struct file *delfp;
  671         int error, holdleaders, maxfd;
  672 
  673         KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
  674             ("invalid dup type %d", type));
  675 
  676         p = td->td_proc;
  677         fdp = p->p_fd;
  678 
  679         /*
  680          * Verify we have a valid descriptor to dup from and possibly to
  681          * dup to.
  682          */
  683         if (old < 0 || new < 0)
  684                 return (EBADF);
  685         PROC_LOCK(p);
  686         maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
  687         PROC_UNLOCK(p);
  688         if (new >= maxfd)
  689                 return (EMFILE);
  690 
  691         FILEDESC_LOCK(fdp);
  692         if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
  693                 FILEDESC_UNLOCK(fdp);
  694                 return (EBADF);
  695         }
  696         if (type == DUP_FIXED && old == new) {
  697                 *retval = new;
  698                 FILEDESC_UNLOCK(fdp);
  699                 return (0);
  700         }
  701         fp = fdp->fd_ofiles[old];
  702         fhold(fp);
  703 
  704         /*
  705          * If the caller specified a file descriptor, make sure the file
  706          * table is large enough to hold it, and grab it.  Otherwise, just
  707          * allocate a new descriptor the usual way.  Since the filedesc
  708          * lock may be temporarily dropped in the process, we have to look
  709          * out for a race.
  710          */
  711         if (type == DUP_FIXED) {
  712                 if (new >= fdp->fd_nfiles)
  713                         fdgrowtable(fdp, new + 1);
  714                 if (fdp->fd_ofiles[new] == NULL)
  715                         fdused(fdp, new);
  716         } else {
  717                 if ((error = fdalloc(td, new, &new)) != 0) {
  718                         FILEDESC_UNLOCK(fdp);
  719                         fdrop(fp, td);
  720                         return (error);
  721                 }
  722         }
  723 
  724         /*
  725          * If the old file changed out from under us then treat it as a
  726          * bad file descriptor.  Userland should do its own locking to
  727          * avoid this case.
  728          */
  729         if (fdp->fd_ofiles[old] != fp ||
  730             (fdp->fd_ofileflags[old] & UF_OPENING) != 0 ||
  731             (fdp->fd_ofileflags[new] & UF_OPENING) != 0) {
  732                 /* we've allocated a descriptor which we won't use */
  733                 if (fdp->fd_ofiles[new] == NULL)
  734                         fdunused(fdp, new);
  735                 FILEDESC_UNLOCK(fdp);
  736                 fdrop(fp, td);
  737                 return (EBADF);
  738         }
  739         KASSERT(old != new,
  740             ("new fd is same as old"));
  741 
  742         /*
  743          * Save info on the descriptor being overwritten.  We cannot close
  744          * it without introducing an ownership race for the slot, since we
  745          * need to drop the filedesc lock to call closef().
  746          *
  747          * XXX this duplicates parts of close().
  748          */
  749         delfp = fdp->fd_ofiles[new];
  750         holdleaders = 0;
  751         if (delfp != NULL) {
  752                 if (td->td_proc->p_fdtol != NULL) {
  753                         /*
  754                          * Ask fdfree() to sleep to ensure that all relevant
  755                          * process leaders can be traversed in closef().
  756                          */
  757                         fdp->fd_holdleaderscount++;
  758                         holdleaders = 1;
  759                 }
  760         }
  761 
  762         /*
  763          * Duplicate the source descriptor
  764          */
  765         fdp->fd_ofiles[new] = fp;
  766         fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
  767         if (new > fdp->fd_lastfile)
  768                 fdp->fd_lastfile = new;
  769         *retval = new;
  770 
  771         /*
  772          * If we dup'd over a valid file, we now own the reference to it
  773          * and must dispose of it using closef() semantics (as if a
  774          * close() were performed on it).
  775          *
  776          * XXX this duplicates parts of close().
  777          */
  778         if (delfp != NULL) {
  779                 knote_fdclose(td, new);
  780                 FILEDESC_UNLOCK(fdp);
  781                 (void) closef(delfp, td);
  782                 if (holdleaders) {
  783                         FILEDESC_LOCK_FAST(fdp);
  784                         fdp->fd_holdleaderscount--;
  785                         if (fdp->fd_holdleaderscount == 0 &&
  786                             fdp->fd_holdleaderswakeup != 0) {
  787                                 fdp->fd_holdleaderswakeup = 0;
  788                                 wakeup(&fdp->fd_holdleaderscount);
  789                         }
  790                         FILEDESC_UNLOCK_FAST(fdp);
  791                 }
  792         } else {
  793                 FILEDESC_UNLOCK(fdp);
  794         }
  795         return (0);
  796 }
  797 
  798 /*
  799  * If sigio is on the list associated with a process or process group,
  800  * disable signalling from the device, remove sigio from the list and
  801  * free sigio.
  802  */
  803 void
  804 funsetown(struct sigio **sigiop)
  805 {
  806         struct sigio *sigio;
  807 
  808         SIGIO_LOCK();
  809         sigio = *sigiop;
  810         if (sigio == NULL) {
  811                 SIGIO_UNLOCK();
  812                 return;
  813         }
  814         *(sigio->sio_myref) = NULL;
  815         if ((sigio)->sio_pgid < 0) {
  816                 struct pgrp *pg = (sigio)->sio_pgrp;
  817                 PGRP_LOCK(pg);
  818                 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
  819                              sigio, sio_pgsigio);
  820                 PGRP_UNLOCK(pg);
  821         } else {
  822                 struct proc *p = (sigio)->sio_proc;
  823                 PROC_LOCK(p);
  824                 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
  825                              sigio, sio_pgsigio);
  826                 PROC_UNLOCK(p);
  827         }
  828         SIGIO_UNLOCK();
  829         crfree(sigio->sio_ucred);
  830         FREE(sigio, M_SIGIO);
  831 }
  832 
  833 /*
  834  * Free a list of sigio structures.
  835  * We only need to lock the SIGIO_LOCK because we have made ourselves
  836  * inaccessible to callers of fsetown and therefore do not need to lock
  837  * the proc or pgrp struct for the list manipulation.
  838  */
  839 void
  840 funsetownlst(struct sigiolst *sigiolst)
  841 {
  842         struct proc *p;
  843         struct pgrp *pg;
  844         struct sigio *sigio;
  845 
  846         sigio = SLIST_FIRST(sigiolst);
  847         if (sigio == NULL)
  848                 return;
  849         p = NULL;
  850         pg = NULL;
  851 
  852         /*
  853          * Every entry of the list should belong
  854          * to a single proc or pgrp.
  855          */
  856         if (sigio->sio_pgid < 0) {
  857                 pg = sigio->sio_pgrp;
  858                 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
  859         } else /* if (sigio->sio_pgid > 0) */ {
  860                 p = sigio->sio_proc;
  861                 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
  862         }
  863 
  864         SIGIO_LOCK();
  865         while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
  866                 *(sigio->sio_myref) = NULL;
  867                 if (pg != NULL) {
  868                         KASSERT(sigio->sio_pgid < 0,
  869                             ("Proc sigio in pgrp sigio list"));
  870                         KASSERT(sigio->sio_pgrp == pg,
  871                             ("Bogus pgrp in sigio list"));
  872                         PGRP_LOCK(pg);
  873                         SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
  874                             sio_pgsigio);
  875                         PGRP_UNLOCK(pg);
  876                 } else /* if (p != NULL) */ {
  877                         KASSERT(sigio->sio_pgid > 0,
  878                             ("Pgrp sigio in proc sigio list"));
  879                         KASSERT(sigio->sio_proc == p,
  880                             ("Bogus proc in sigio list"));
  881                         PROC_LOCK(p);
  882                         SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
  883                             sio_pgsigio);
  884                         PROC_UNLOCK(p);
  885                 }
  886                 SIGIO_UNLOCK();
  887                 crfree(sigio->sio_ucred);
  888                 FREE(sigio, M_SIGIO);
  889                 SIGIO_LOCK();
  890         }
  891         SIGIO_UNLOCK();
  892 }
  893 
  894 /*
  895  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
  896  *
  897  * After permission checking, add a sigio structure to the sigio list for
  898  * the process or process group.
  899  */
  900 int
  901 fsetown(pid_t pgid, struct sigio **sigiop)
  902 {
  903         struct proc *proc;
  904         struct pgrp *pgrp;
  905         struct sigio *sigio;
  906         int ret;
  907 
  908         if (pgid == 0) {
  909                 funsetown(sigiop);
  910                 return (0);
  911         }
  912 
  913         ret = 0;
  914 
  915         /* Allocate and fill in the new sigio out of locks. */
  916         MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
  917         sigio->sio_pgid = pgid;
  918         sigio->sio_ucred = crhold(curthread->td_ucred);
  919         sigio->sio_myref = sigiop;
  920 
  921         sx_slock(&proctree_lock);
  922         if (pgid > 0) {
  923                 proc = pfind(pgid);
  924                 if (proc == NULL) {
  925                         ret = ESRCH;
  926                         goto fail;
  927                 }
  928 
  929                 /*
  930                  * Policy - Don't allow a process to FSETOWN a process
  931                  * in another session.
  932                  *
  933                  * Remove this test to allow maximum flexibility or
  934                  * restrict FSETOWN to the current process or process
  935                  * group for maximum safety.
  936                  */
  937                 PROC_UNLOCK(proc);
  938                 if (proc->p_session != curthread->td_proc->p_session) {
  939                         ret = EPERM;
  940                         goto fail;
  941                 }
  942 
  943                 pgrp = NULL;
  944         } else /* if (pgid < 0) */ {
  945                 pgrp = pgfind(-pgid);
  946                 if (pgrp == NULL) {
  947                         ret = ESRCH;
  948                         goto fail;
  949                 }
  950                 PGRP_UNLOCK(pgrp);
  951 
  952                 /*
  953                  * Policy - Don't allow a process to FSETOWN a process
  954                  * in another session.
  955                  *
  956                  * Remove this test to allow maximum flexibility or
  957                  * restrict FSETOWN to the current process or process
  958                  * group for maximum safety.
  959                  */
  960                 if (pgrp->pg_session != curthread->td_proc->p_session) {
  961                         ret = EPERM;
  962                         goto fail;
  963                 }
  964 
  965                 proc = NULL;
  966         }
  967         funsetown(sigiop);
  968         if (pgid > 0) {
  969                 PROC_LOCK(proc);
  970                 /*
  971                  * Since funsetownlst() is called without the proctree
  972                  * locked, we need to check for P_WEXIT.
  973                  * XXX: is ESRCH correct?
  974                  */
  975                 if ((proc->p_flag & P_WEXIT) != 0) {
  976                         PROC_UNLOCK(proc);
  977                         ret = ESRCH;
  978                         goto fail;
  979                 }
  980                 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
  981                 sigio->sio_proc = proc;
  982                 PROC_UNLOCK(proc);
  983         } else {
  984                 PGRP_LOCK(pgrp);
  985                 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
  986                 sigio->sio_pgrp = pgrp;
  987                 PGRP_UNLOCK(pgrp);
  988         }
  989         sx_sunlock(&proctree_lock);
  990         SIGIO_LOCK();
  991         *sigiop = sigio;
  992         SIGIO_UNLOCK();
  993         return (0);
  994 
  995 fail:
  996         sx_sunlock(&proctree_lock);
  997         crfree(sigio->sio_ucred);
  998         FREE(sigio, M_SIGIO);
  999         return (ret);
 1000 }
 1001 
 1002 /*
 1003  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
 1004  */
 1005 pid_t
 1006 fgetown(sigiop)
 1007         struct sigio **sigiop;
 1008 {
 1009         pid_t pgid;
 1010 
 1011         SIGIO_LOCK();
 1012         pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
 1013         SIGIO_UNLOCK();
 1014         return (pgid);
 1015 }
 1016 
 1017 /*
 1018  * Close a file descriptor.
 1019  */
 1020 #ifndef _SYS_SYSPROTO_H_
 1021 struct close_args {
 1022         int     fd;
 1023 };
 1024 #endif
 1025 /*
 1026  * MPSAFE
 1027  */
 1028 /* ARGSUSED */
 1029 int
 1030 close(td, uap)
 1031         struct thread *td;
 1032         struct close_args *uap;
 1033 {
 1034 
 1035         return (kern_close(td, uap->fd));
 1036 }
 1037 
 1038 int
 1039 kern_close(td, fd)
 1040         struct thread *td;
 1041         int fd;
 1042 {
 1043         struct filedesc *fdp;
 1044         struct file *fp;
 1045         int error;
 1046         int holdleaders;
 1047 
 1048         error = 0;
 1049         holdleaders = 0;
 1050         fdp = td->td_proc->p_fd;
 1051 
 1052         AUDIT_SYSCLOSE(td, fd);
 1053 
 1054         FILEDESC_LOCK(fdp);
 1055         if ((unsigned)fd >= fdp->fd_nfiles ||
 1056             (fp = fdp->fd_ofiles[fd]) == NULL ||
 1057             (fdp->fd_ofileflags[fd] & UF_OPENING) != 0) {
 1058                 FILEDESC_UNLOCK(fdp);
 1059                 return (EBADF);
 1060         }
 1061         fdp->fd_ofiles[fd] = NULL;
 1062         fdp->fd_ofileflags[fd] = 0;
 1063         fdunused(fdp, fd);
 1064         if (td->td_proc->p_fdtol != NULL) {
 1065                 /*
 1066                  * Ask fdfree() to sleep to ensure that all relevant
 1067                  * process leaders can be traversed in closef().
 1068                  */
 1069                 fdp->fd_holdleaderscount++;
 1070                 holdleaders = 1;
 1071         }
 1072 
 1073         /*
 1074          * We now hold the fp reference that used to be owned by the descriptor
 1075          * array.
 1076          * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
 1077          * race of the fd getting opened, a knote added, and deleteing a knote
 1078          * for the new fd.
 1079          */
 1080         knote_fdclose(td, fd);
 1081         FILEDESC_UNLOCK(fdp);
 1082 
 1083         error = closef(fp, td);
 1084         if (holdleaders) {
 1085                 FILEDESC_LOCK_FAST(fdp);
 1086                 fdp->fd_holdleaderscount--;
 1087                 if (fdp->fd_holdleaderscount == 0 &&
 1088                     fdp->fd_holdleaderswakeup != 0) {
 1089                         fdp->fd_holdleaderswakeup = 0;
 1090                         wakeup(&fdp->fd_holdleaderscount);
 1091                 }
 1092                 FILEDESC_UNLOCK_FAST(fdp);
 1093         }
 1094         return (error);
 1095 }
 1096 
 1097 #if defined(COMPAT_43)
 1098 /*
 1099  * Return status information about a file descriptor.
 1100  */
 1101 #ifndef _SYS_SYSPROTO_H_
 1102 struct ofstat_args {
 1103         int     fd;
 1104         struct  ostat *sb;
 1105 };
 1106 #endif
 1107 /*
 1108  * MPSAFE
 1109  */
 1110 /* ARGSUSED */
 1111 int
 1112 ofstat(struct thread *td, struct ofstat_args *uap)
 1113 {
 1114         struct ostat oub;
 1115         struct stat ub;
 1116         int error;
 1117 
 1118         error = kern_fstat(td, uap->fd, &ub);
 1119         if (error == 0) {
 1120                 cvtstat(&ub, &oub);
 1121                 error = copyout(&oub, uap->sb, sizeof(oub));
 1122         }
 1123         return (error);
 1124 }
 1125 #endif /* COMPAT_43 */
 1126 
 1127 /*
 1128  * Return status information about a file descriptor.
 1129  */
 1130 #ifndef _SYS_SYSPROTO_H_
 1131 struct fstat_args {
 1132         int     fd;
 1133         struct  stat *sb;
 1134 };
 1135 #endif
 1136 /*
 1137  * MPSAFE
 1138  */
 1139 /* ARGSUSED */
 1140 int
 1141 fstat(struct thread *td, struct fstat_args *uap)
 1142 {
 1143         struct stat ub;
 1144         int error;
 1145 
 1146         error = kern_fstat(td, uap->fd, &ub);
 1147         if (error == 0)
 1148                 error = copyout(&ub, uap->sb, sizeof(ub));
 1149         return (error);
 1150 }
 1151 
 1152 int
 1153 kern_fstat(struct thread *td, int fd, struct stat *sbp)
 1154 {
 1155         struct file *fp;
 1156         int error;
 1157 
 1158         AUDIT_ARG(fd, fd);
 1159 
 1160         if ((error = fget(td, fd, &fp)) != 0)
 1161                 return (error);
 1162 
 1163         AUDIT_ARG(file, td->td_proc, fp);
 1164 
 1165         error = fo_stat(fp, sbp, td->td_ucred, td);
 1166         fdrop(fp, td);
 1167         return (error);
 1168 }
 1169 
 1170 /*
 1171  * Return status information about a file descriptor.
 1172  */
 1173 #ifndef _SYS_SYSPROTO_H_
 1174 struct nfstat_args {
 1175         int     fd;
 1176         struct  nstat *sb;
 1177 };
 1178 #endif
 1179 /*
 1180  * MPSAFE
 1181  */
 1182 /* ARGSUSED */
 1183 int
 1184 nfstat(struct thread *td, struct nfstat_args *uap)
 1185 {
 1186         struct nstat nub;
 1187         struct stat ub;
 1188         int error;
 1189 
 1190         error = kern_fstat(td, uap->fd, &ub);
 1191         if (error == 0) {
 1192                 cvtnstat(&ub, &nub);
 1193                 error = copyout(&nub, uap->sb, sizeof(nub));
 1194         }
 1195         return (error);
 1196 }
 1197 
 1198 /*
 1199  * Return pathconf information about a file descriptor.
 1200  */
 1201 #ifndef _SYS_SYSPROTO_H_
 1202 struct fpathconf_args {
 1203         int     fd;
 1204         int     name;
 1205 };
 1206 #endif
 1207 /*
 1208  * MPSAFE
 1209  */
 1210 /* ARGSUSED */
 1211 int
 1212 fpathconf(struct thread *td, struct fpathconf_args *uap)
 1213 {
 1214         struct file *fp;
 1215         struct vnode *vp;
 1216         int error;
 1217 
 1218         if ((error = fget(td, uap->fd, &fp)) != 0)
 1219                 return (error);
 1220 
 1221         /* If asynchronous I/O is available, it works for all descriptors. */
 1222         if (uap->name == _PC_ASYNC_IO) {
 1223                 td->td_retval[0] = async_io_version;
 1224                 goto out;
 1225         }
 1226         vp = fp->f_vnode;
 1227         if (vp != NULL) {
 1228                 int vfslocked;
 1229                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 1230                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
 1231                 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
 1232                 VOP_UNLOCK(vp, 0, td);
 1233                 VFS_UNLOCK_GIANT(vfslocked);
 1234         } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
 1235                 if (uap->name != _PC_PIPE_BUF) {
 1236                         error = EINVAL;
 1237                 } else {
 1238                         td->td_retval[0] = PIPE_BUF;
 1239                 error = 0;
 1240                 }
 1241         } else {
 1242                 error = EOPNOTSUPP;
 1243         }
 1244 out:
 1245         fdrop(fp, td);
 1246         return (error);
 1247 }
 1248 
 1249 /*
 1250  * Grow the file table to accomodate (at least) nfd descriptors.  This may
 1251  * block and drop the filedesc lock, but it will reacquire it before
 1252  * returning.
 1253  */
 1254 static void
 1255 fdgrowtable(struct filedesc *fdp, int nfd)
 1256 {
 1257         struct file **ntable;
 1258         char *nfileflags;
 1259         int nnfiles, onfiles;
 1260         NDSLOTTYPE *nmap;
 1261 
 1262         FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
 1263 
 1264         KASSERT(fdp->fd_nfiles > 0,
 1265             ("zero-length file table"));
 1266 
 1267         /* compute the size of the new table */
 1268         onfiles = fdp->fd_nfiles;
 1269         nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
 1270         if (nnfiles <= onfiles)
 1271                 /* the table is already large enough */
 1272                 return;
 1273 
 1274         /* allocate a new table and (if required) new bitmaps */
 1275         FILEDESC_UNLOCK(fdp);
 1276         MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
 1277             M_FILEDESC, M_ZERO | M_WAITOK);
 1278         nfileflags = (char *)&ntable[nnfiles];
 1279         if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
 1280                 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
 1281                     M_FILEDESC, M_ZERO | M_WAITOK);
 1282         else
 1283                 nmap = NULL;
 1284         FILEDESC_LOCK(fdp);
 1285 
 1286         /*
 1287          * We now have new tables ready to go.  Since we dropped the
 1288          * filedesc lock to call malloc(), watch out for a race.
 1289          */
 1290         onfiles = fdp->fd_nfiles;
 1291         if (onfiles >= nnfiles) {
 1292                 /* we lost the race, but that's OK */
 1293                 free(ntable, M_FILEDESC);
 1294                 if (nmap != NULL)
 1295                         free(nmap, M_FILEDESC);
 1296                 return;
 1297         }
 1298         bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
 1299         bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
 1300         if (onfiles > NDFILE)
 1301                 free(fdp->fd_ofiles, M_FILEDESC);
 1302         fdp->fd_ofiles = ntable;
 1303         fdp->fd_ofileflags = nfileflags;
 1304         if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
 1305                 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
 1306                 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
 1307                         free(fdp->fd_map, M_FILEDESC);
 1308                 fdp->fd_map = nmap;
 1309         }
 1310         fdp->fd_nfiles = nnfiles;
 1311 }
 1312 
 1313 /*
 1314  * Allocate a file descriptor for the process.
 1315  */
 1316 int
 1317 fdalloc(struct thread *td, int minfd, int *result)
 1318 {
 1319         struct proc *p = td->td_proc;
 1320         struct filedesc *fdp = p->p_fd;
 1321         int fd = -1, maxfd;
 1322 
 1323         FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
 1324 
 1325         if (fdp->fd_freefile > minfd)
 1326                 minfd = fdp->fd_freefile;          
 1327 
 1328         PROC_LOCK(p);
 1329         maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
 1330         PROC_UNLOCK(p);
 1331 
 1332         /*
 1333          * Search the bitmap for a free descriptor.  If none is found, try
 1334          * to grow the file table.  Keep at it until we either get a file
 1335          * descriptor or run into process or system limits; fdgrowtable()
 1336          * may drop the filedesc lock, so we're in a race.
 1337          */
 1338         for (;;) {
 1339                 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
 1340                 if (fd >= maxfd)
 1341                         return (EMFILE);
 1342                 if (fd < fdp->fd_nfiles)
 1343                         break;
 1344                 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
 1345         }
 1346 
 1347         /*
 1348          * Perform some sanity checks, then mark the file descriptor as
 1349          * used and return it to the caller.
 1350          */
 1351         KASSERT(!fdisused(fdp, fd),
 1352             ("fd_first_free() returned non-free descriptor"));
 1353         KASSERT(fdp->fd_ofiles[fd] == NULL,
 1354             ("free descriptor isn't"));
 1355         fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
 1356         fdused(fdp, fd);
 1357         *result = fd;
 1358         return (0);
 1359 }
 1360 
 1361 /*
 1362  * Check to see whether n user file descriptors
 1363  * are available to the process p.
 1364  */
 1365 int
 1366 fdavail(struct thread *td, int n)
 1367 {
 1368         struct proc *p = td->td_proc;
 1369         struct filedesc *fdp = td->td_proc->p_fd;
 1370         struct file **fpp;
 1371         int i, lim, last;
 1372 
 1373         FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
 1374 
 1375         PROC_LOCK(p);
 1376         lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
 1377         PROC_UNLOCK(p);
 1378         if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
 1379                 return (1);
 1380         last = min(fdp->fd_nfiles, lim);
 1381         fpp = &fdp->fd_ofiles[fdp->fd_freefile];
 1382         for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
 1383                 if (*fpp == NULL && --n <= 0)
 1384                         return (1);
 1385         }
 1386         return (0);
 1387 }
 1388 
 1389 /*
 1390  * Create a new open file structure and allocate
 1391  * a file decriptor for the process that refers to it.
 1392  * We add one reference to the file for the descriptor table
 1393  * and one reference for resultfp. This is to prevent us being
 1394  * preempted and the entry in the descriptor table closed after
 1395  * we release the FILEDESC lock.
 1396  */
 1397 int
 1398 falloc(struct thread *td, struct file **resultfp, int *resultfd)
 1399 {
 1400         struct proc *p = td->td_proc;
 1401         struct file *fp, *fq;
 1402         int error, i;
 1403         int maxuserfiles = maxfiles - (maxfiles / 20);
 1404         static struct timeval lastfail;
 1405         static int curfail;
 1406 
 1407         fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
 1408         sx_xlock(&filelist_lock);
 1409 
 1410         if ((openfiles >= maxuserfiles &&
 1411              suser_cred(td->td_ucred, SUSER_RUID) != 0) ||
 1412             openfiles >= maxfiles) {
 1413                 if (ppsratecheck(&lastfail, &curfail, 1)) {
 1414                         printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
 1415                                 td->td_ucred->cr_ruid);
 1416                 }
 1417                 sx_xunlock(&filelist_lock);
 1418                 uma_zfree(file_zone, fp);
 1419                 return (ENFILE);
 1420         }
 1421         openfiles++;
 1422 
 1423         /*
 1424          * If the process has file descriptor zero open, add the new file
 1425          * descriptor to the list of open files at that point, otherwise
 1426          * put it at the front of the list of open files.
 1427          */
 1428         fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
 1429         fp->f_count = 1;
 1430         if (resultfp)
 1431                 fp->f_count++;
 1432         fp->f_cred = crhold(td->td_ucred);
 1433         fp->f_ops = &badfileops;
 1434         fp->f_data = NULL;
 1435         fp->f_vnode = NULL;
 1436         FILEDESC_LOCK(p->p_fd);
 1437         if ((fq = p->p_fd->fd_ofiles[0])) {
 1438                 LIST_INSERT_AFTER(fq, fp, f_list);
 1439         } else {
 1440                 LIST_INSERT_HEAD(&filehead, fp, f_list);
 1441         }
 1442         sx_xunlock(&filelist_lock);
 1443         if ((error = fdalloc(td, 0, &i))) {
 1444                 FILEDESC_UNLOCK(p->p_fd);
 1445                 fdrop(fp, td);
 1446                 if (resultfp)
 1447                         fdrop(fp, td);
 1448                 return (error);
 1449         }
 1450         p->p_fd->fd_ofiles[i] = fp;
 1451         FILEDESC_UNLOCK(p->p_fd);
 1452         if (resultfp)
 1453                 *resultfp = fp;
 1454         if (resultfd)
 1455                 *resultfd = i;
 1456         return (0);
 1457 }
 1458 
 1459 /*
 1460  * Build a new filedesc structure from another.
 1461  * Copy the current, root, and jail root vnode references.
 1462  */
 1463 struct filedesc *
 1464 fdinit(struct filedesc *fdp)
 1465 {
 1466         struct filedesc0 *newfdp;
 1467 
 1468         newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
 1469         mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
 1470         if (fdp != NULL) {
 1471                 FILEDESC_LOCK(fdp);
 1472                 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
 1473                 if (newfdp->fd_fd.fd_cdir)
 1474                         VREF(newfdp->fd_fd.fd_cdir);
 1475                 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
 1476                 if (newfdp->fd_fd.fd_rdir)
 1477                         VREF(newfdp->fd_fd.fd_rdir);
 1478                 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
 1479                 if (newfdp->fd_fd.fd_jdir)
 1480                         VREF(newfdp->fd_fd.fd_jdir);
 1481                 FILEDESC_UNLOCK(fdp);
 1482         }
 1483 
 1484         /* Create the file descriptor table. */
 1485         newfdp->fd_fd.fd_refcnt = 1;
 1486         newfdp->fd_fd.fd_holdcnt = 1;
 1487         newfdp->fd_fd.fd_cmask = CMASK;
 1488         newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
 1489         newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
 1490         newfdp->fd_fd.fd_nfiles = NDFILE;
 1491         newfdp->fd_fd.fd_map = newfdp->fd_dmap;
 1492         newfdp->fd_fd.fd_lastfile = -1;
 1493         return (&newfdp->fd_fd);
 1494 }
 1495 
 1496 static struct filedesc *
 1497 fdhold(struct proc *p)
 1498 {
 1499         struct filedesc *fdp;
 1500 
 1501         mtx_lock(&fdesc_mtx);
 1502         fdp = p->p_fd;
 1503         if (fdp != NULL)
 1504                 fdp->fd_holdcnt++;
 1505         mtx_unlock(&fdesc_mtx);
 1506         return (fdp);
 1507 }
 1508 
 1509 static void
 1510 fddrop(struct filedesc *fdp)
 1511 {
 1512         int i;
 1513 
 1514         mtx_lock(&fdesc_mtx);
 1515         i = --fdp->fd_holdcnt;
 1516         mtx_unlock(&fdesc_mtx);
 1517         if (i > 0)
 1518                 return;
 1519 
 1520         mtx_destroy(&fdp->fd_mtx);
 1521         FREE(fdp, M_FILEDESC);
 1522 }
 1523 
 1524 /*
 1525  * Share a filedesc structure.
 1526  */
 1527 struct filedesc *
 1528 fdshare(struct filedesc *fdp)
 1529 {
 1530         FILEDESC_LOCK_FAST(fdp);
 1531         fdp->fd_refcnt++;
 1532         FILEDESC_UNLOCK_FAST(fdp);
 1533         return (fdp);
 1534 }
 1535 
 1536 /*
 1537  * Unshare a filedesc structure, if necessary by making a copy
 1538  */
 1539 void
 1540 fdunshare(struct proc *p, struct thread *td)
 1541 {
 1542 
 1543         FILEDESC_LOCK_FAST(p->p_fd);
 1544         if (p->p_fd->fd_refcnt > 1) {
 1545                 struct filedesc *tmp;
 1546 
 1547                 FILEDESC_UNLOCK_FAST(p->p_fd);
 1548                 tmp = fdcopy(p->p_fd);
 1549                 fdfree(td);
 1550                 p->p_fd = tmp;
 1551         } else
 1552                 FILEDESC_UNLOCK_FAST(p->p_fd);
 1553 }
 1554 
 1555 /*
 1556  * Copy a filedesc structure.
 1557  * A NULL pointer in returns a NULL reference, this is to ease callers,
 1558  * not catch errors.
 1559  */
 1560 struct filedesc *
 1561 fdcopy(struct filedesc *fdp)
 1562 {
 1563         struct filedesc *newfdp;
 1564         int i;
 1565 
 1566         /* Certain daemons might not have file descriptors. */
 1567         if (fdp == NULL)
 1568                 return (NULL);
 1569 
 1570         newfdp = fdinit(fdp);
 1571         FILEDESC_LOCK_FAST(fdp);
 1572         while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
 1573                 FILEDESC_UNLOCK_FAST(fdp);
 1574                 FILEDESC_LOCK(newfdp);
 1575                 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
 1576                 FILEDESC_UNLOCK(newfdp);
 1577                 FILEDESC_LOCK_FAST(fdp);
 1578         }
 1579         /* copy everything except kqueue descriptors */
 1580         newfdp->fd_freefile = -1;
 1581         for (i = 0; i <= fdp->fd_lastfile; ++i) {
 1582                 if (fdisused(fdp, i) &&
 1583                     fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
 1584                     (fdp->fd_ofileflags[i] & UF_OPENING) == 0) {
 1585                         newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
 1586                         newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
 1587                         fhold(newfdp->fd_ofiles[i]);
 1588                         newfdp->fd_lastfile = i;
 1589                 } else {
 1590                         if (newfdp->fd_freefile == -1)
 1591                                 newfdp->fd_freefile = i;
 1592                 }
 1593         }
 1594         FILEDESC_UNLOCK_FAST(fdp);
 1595         FILEDESC_LOCK(newfdp);
 1596         for (i = 0; i <= newfdp->fd_lastfile; ++i)
 1597                 if (newfdp->fd_ofiles[i] != NULL)
 1598                         fdused(newfdp, i);
 1599         FILEDESC_UNLOCK(newfdp);
 1600         FILEDESC_LOCK_FAST(fdp);
 1601         if (newfdp->fd_freefile == -1)
 1602                 newfdp->fd_freefile = i;
 1603         newfdp->fd_cmask = fdp->fd_cmask;
 1604         FILEDESC_UNLOCK_FAST(fdp);
 1605         return (newfdp);
 1606 }
 1607 
 1608 /*
 1609  * Release a filedesc structure.
 1610  */
 1611 void
 1612 fdfree(struct thread *td)
 1613 {
 1614         struct filedesc *fdp;
 1615         struct file **fpp;
 1616         int i, locked;
 1617         struct filedesc_to_leader *fdtol;
 1618         struct file *fp;
 1619         struct vnode *cdir, *jdir, *rdir, *vp;
 1620         struct flock lf;
 1621 
 1622         /* Certain daemons might not have file descriptors. */
 1623         fdp = td->td_proc->p_fd;
 1624         if (fdp == NULL)
 1625                 return;
 1626 
 1627         /* Check for special need to clear POSIX style locks */
 1628         fdtol = td->td_proc->p_fdtol;
 1629         if (fdtol != NULL) {
 1630                 FILEDESC_LOCK(fdp);
 1631                 KASSERT(fdtol->fdl_refcount > 0,
 1632                         ("filedesc_to_refcount botch: fdl_refcount=%d",
 1633                          fdtol->fdl_refcount));
 1634                 if (fdtol->fdl_refcount == 1 &&
 1635                     (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1636                         for (i = 0, fpp = fdp->fd_ofiles;
 1637                              i <= fdp->fd_lastfile;
 1638                              i++, fpp++) {
 1639                                 if (*fpp == NULL ||
 1640                                     (*fpp)->f_type != DTYPE_VNODE)
 1641                                         continue;
 1642                                 fp = *fpp;
 1643                                 fhold(fp);
 1644                                 FILEDESC_UNLOCK(fdp);
 1645                                 lf.l_whence = SEEK_SET;
 1646                                 lf.l_start = 0;
 1647                                 lf.l_len = 0;
 1648                                 lf.l_type = F_UNLCK;
 1649                                 vp = fp->f_vnode;
 1650                                 locked = VFS_LOCK_GIANT(vp->v_mount);
 1651                                 (void) VOP_ADVLOCK(vp,
 1652                                                    (caddr_t)td->td_proc->
 1653                                                    p_leader,
 1654                                                    F_UNLCK,
 1655                                                    &lf,
 1656                                                    F_POSIX);
 1657                                 VFS_UNLOCK_GIANT(locked);
 1658                                 FILEDESC_LOCK(fdp);
 1659                                 fdrop(fp, td);
 1660                                 fpp = fdp->fd_ofiles + i;
 1661                         }
 1662                 }
 1663         retry:
 1664                 if (fdtol->fdl_refcount == 1) {
 1665                         if (fdp->fd_holdleaderscount > 0 &&
 1666                             (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1667                                 /*
 1668                                  * close() or do_dup() has cleared a reference
 1669                                  * in a shared file descriptor table.
 1670                                  */
 1671                                 fdp->fd_holdleaderswakeup = 1;
 1672                                 msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
 1673                                        PLOCK, "fdlhold", 0);
 1674                                 goto retry;
 1675                         }
 1676                         if (fdtol->fdl_holdcount > 0) {
 1677                                 /*
 1678                                  * Ensure that fdtol->fdl_leader
 1679                                  * remains valid in closef().
 1680                                  */
 1681                                 fdtol->fdl_wakeup = 1;
 1682                                 msleep(fdtol, &fdp->fd_mtx,
 1683                                        PLOCK, "fdlhold", 0);
 1684                                 goto retry;
 1685                         }
 1686                 }
 1687                 fdtol->fdl_refcount--;
 1688                 if (fdtol->fdl_refcount == 0 &&
 1689                     fdtol->fdl_holdcount == 0) {
 1690                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
 1691                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
 1692                 } else
 1693                         fdtol = NULL;
 1694                 td->td_proc->p_fdtol = NULL;
 1695                 FILEDESC_UNLOCK(fdp);
 1696                 if (fdtol != NULL)
 1697                         FREE(fdtol, M_FILEDESC_TO_LEADER);
 1698         }
 1699         FILEDESC_LOCK_FAST(fdp);
 1700         i = --fdp->fd_refcnt;
 1701         FILEDESC_UNLOCK_FAST(fdp);
 1702         if (i > 0)
 1703                 return;
 1704         /*
 1705          * We are the last reference to the structure, so we can
 1706          * safely assume it will not change out from under us.
 1707          */
 1708         fpp = fdp->fd_ofiles;
 1709         for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
 1710                 if (*fpp)
 1711                         (void) closef(*fpp, td);
 1712         }
 1713         FILEDESC_LOCK(fdp);
 1714 
 1715         /* XXX This should happen earlier. */
 1716         mtx_lock(&fdesc_mtx);
 1717         td->td_proc->p_fd = NULL;
 1718         mtx_unlock(&fdesc_mtx);
 1719 
 1720         if (fdp->fd_nfiles > NDFILE)
 1721                 FREE(fdp->fd_ofiles, M_FILEDESC);
 1722         if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
 1723                 FREE(fdp->fd_map, M_FILEDESC);
 1724 
 1725         fdp->fd_nfiles = 0;
 1726 
 1727         cdir = fdp->fd_cdir;
 1728         fdp->fd_cdir = NULL;
 1729         rdir = fdp->fd_rdir;
 1730         fdp->fd_rdir = NULL;
 1731         jdir = fdp->fd_jdir;
 1732         fdp->fd_jdir = NULL;
 1733         FILEDESC_UNLOCK(fdp);
 1734 
 1735         if (cdir) {
 1736                 locked = VFS_LOCK_GIANT(cdir->v_mount);
 1737                 vrele(cdir);
 1738                 VFS_UNLOCK_GIANT(locked);
 1739         }
 1740         if (rdir) {
 1741                 locked = VFS_LOCK_GIANT(rdir->v_mount);
 1742                 vrele(rdir);
 1743                 VFS_UNLOCK_GIANT(locked);
 1744         }
 1745         if (jdir) {
 1746                 locked = VFS_LOCK_GIANT(jdir->v_mount);
 1747                 vrele(jdir);
 1748                 VFS_UNLOCK_GIANT(locked);
 1749         }
 1750 
 1751         fddrop(fdp);
 1752 }
 1753 
 1754 /*
 1755  * For setugid programs, we don't want to people to use that setugidness
 1756  * to generate error messages which write to a file which otherwise would
 1757  * otherwise be off-limits to the process.  We check for filesystems where
 1758  * the vnode can change out from under us after execve (like [lin]procfs).
 1759  *
 1760  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
 1761  * sufficient.  We also don't check for setugidness since we know we are.
 1762  */
 1763 static int
 1764 is_unsafe(struct file *fp)
 1765 {
 1766         if (fp->f_type == DTYPE_VNODE) {
 1767                 struct vnode *vp = fp->f_vnode;
 1768 
 1769                 if ((vp->v_vflag & VV_PROCDEP) != 0)
 1770                         return (1);
 1771         }
 1772         return (0);
 1773 }
 1774 
 1775 /*
 1776  * Make this setguid thing safe, if at all possible.
 1777  */
 1778 void
 1779 setugidsafety(struct thread *td)
 1780 {
 1781         struct filedesc *fdp;
 1782         int i;
 1783 
 1784         /* Certain daemons might not have file descriptors. */
 1785         fdp = td->td_proc->p_fd;
 1786         if (fdp == NULL)
 1787                 return;
 1788 
 1789         /*
 1790          * Note: fdp->fd_ofiles may be reallocated out from under us while
 1791          * we are blocked in a close.  Be careful!
 1792          */
 1793         FILEDESC_LOCK(fdp);
 1794         for (i = 0; i <= fdp->fd_lastfile; i++) {
 1795                 if (i > 2)
 1796                         break;
 1797                 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
 1798                         struct file *fp;
 1799 
 1800                         knote_fdclose(td, i);
 1801                         /*
 1802                          * NULL-out descriptor prior to close to avoid
 1803                          * a race while close blocks.
 1804                          */
 1805                         fp = fdp->fd_ofiles[i];
 1806                         fdp->fd_ofiles[i] = NULL;
 1807                         fdp->fd_ofileflags[i] = 0;
 1808                         fdunused(fdp, i);
 1809                         FILEDESC_UNLOCK(fdp);
 1810                         (void) closef(fp, td);
 1811                         FILEDESC_LOCK(fdp);
 1812                 }
 1813         }
 1814         FILEDESC_UNLOCK(fdp);
 1815 }
 1816 
 1817 void
 1818 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
 1819 {
 1820 
 1821         FILEDESC_LOCK(fdp);
 1822         if (fdp->fd_ofiles[idx] == fp) {
 1823                 fdp->fd_ofiles[idx] = NULL;
 1824                 fdunused(fdp, idx);
 1825                 FILEDESC_UNLOCK(fdp);
 1826                 fdrop(fp, td);
 1827         } else {
 1828                 FILEDESC_UNLOCK(fdp);
 1829         }
 1830 }
 1831 
 1832 /*
 1833  * Close any files on exec?
 1834  */
 1835 void
 1836 fdcloseexec(struct thread *td)
 1837 {
 1838         struct filedesc *fdp;
 1839         int i;
 1840 
 1841         /* Certain daemons might not have file descriptors. */
 1842         fdp = td->td_proc->p_fd;
 1843         if (fdp == NULL)
 1844                 return;
 1845 
 1846         FILEDESC_LOCK(fdp);
 1847 
 1848         /*
 1849          * We cannot cache fd_ofiles or fd_ofileflags since operations
 1850          * may block and rip them out from under us.
 1851          */
 1852         for (i = 0; i <= fdp->fd_lastfile; i++) {
 1853                 if (fdp->fd_ofiles[i] != NULL &&
 1854                     (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
 1855                         struct file *fp;
 1856 
 1857                         knote_fdclose(td, i);
 1858                         /*
 1859                          * NULL-out descriptor prior to close to avoid
 1860                          * a race while close blocks.
 1861                          */
 1862                         fp = fdp->fd_ofiles[i];
 1863                         fdp->fd_ofiles[i] = NULL;
 1864                         fdp->fd_ofileflags[i] = 0;
 1865                         fdunused(fdp, i);
 1866                         FILEDESC_UNLOCK(fdp);
 1867                         (void) closef(fp, td);
 1868                         FILEDESC_LOCK(fdp);
 1869                 }
 1870         }
 1871         FILEDESC_UNLOCK(fdp);
 1872 }
 1873 
 1874 /*
 1875  * It is unsafe for set[ug]id processes to be started with file
 1876  * descriptors 0..2 closed, as these descriptors are given implicit
 1877  * significance in the Standard C library.  fdcheckstd() will create a
 1878  * descriptor referencing /dev/null for each of stdin, stdout, and
 1879  * stderr that is not already open.
 1880  */
 1881 int
 1882 fdcheckstd(struct thread *td)
 1883 {
 1884         struct filedesc *fdp;
 1885         register_t retval, save;
 1886         int i, error, devnull;
 1887 
 1888         fdp = td->td_proc->p_fd;
 1889         if (fdp == NULL)
 1890                 return (0);
 1891         KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
 1892         devnull = -1;
 1893         error = 0;
 1894         for (i = 0; i < 3; i++) {
 1895                 if (fdp->fd_ofiles[i] != NULL)
 1896                         continue;
 1897                 if (devnull < 0) {
 1898                         save = td->td_retval[0];
 1899                         error = kern_open(td, "/dev/null", UIO_SYSSPACE,
 1900                             O_RDWR, 0);
 1901                         devnull = td->td_retval[0];
 1902                         KASSERT(devnull == i, ("oof, we didn't get our fd"));
 1903                         td->td_retval[0] = save;
 1904                         if (error)
 1905                                 break;
 1906                 } else {
 1907                         error = do_dup(td, DUP_FIXED, devnull, i, &retval);
 1908                         if (error != 0)
 1909                                 break;
 1910                 }
 1911         }
 1912         return (error);
 1913 }
 1914 
 1915 /*
 1916  * Internal form of close.
 1917  * Decrement reference count on file structure.
 1918  * Note: td may be NULL when closing a file that was being passed in a
 1919  * message.
 1920  *
 1921  * XXXRW: Giant is not required for the caller, but often will be held; this
 1922  * makes it moderately likely the Giant will be recursed in the VFS case.
 1923  */
 1924 int
 1925 closef(struct file *fp, struct thread *td)
 1926 {
 1927         struct vnode *vp;
 1928         struct flock lf;
 1929         struct filedesc_to_leader *fdtol;
 1930         struct filedesc *fdp;
 1931 
 1932         /*
 1933          * POSIX record locking dictates that any close releases ALL
 1934          * locks owned by this process.  This is handled by setting
 1935          * a flag in the unlock to free ONLY locks obeying POSIX
 1936          * semantics, and not to free BSD-style file locks.
 1937          * If the descriptor was in a message, POSIX-style locks
 1938          * aren't passed with the descriptor, and the thread pointer
 1939          * will be NULL.  Callers should be careful only to pass a
 1940          * NULL thread pointer when there really is no owning
 1941          * context that might have locks, or the locks will be
 1942          * leaked.
 1943          */
 1944         if (fp->f_type == DTYPE_VNODE && td != NULL) {
 1945                 int vfslocked;
 1946 
 1947                 vp = fp->f_vnode;
 1948                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 1949                 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1950                         lf.l_whence = SEEK_SET;
 1951                         lf.l_start = 0;
 1952                         lf.l_len = 0;
 1953                         lf.l_type = F_UNLCK;
 1954                         (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
 1955                                            F_UNLCK, &lf, F_POSIX);
 1956                 }
 1957                 fdtol = td->td_proc->p_fdtol;
 1958                 if (fdtol != NULL) {
 1959                         /*
 1960                          * Handle special case where file descriptor table
 1961                          * is shared between multiple process leaders.
 1962                          */
 1963                         fdp = td->td_proc->p_fd;
 1964                         FILEDESC_LOCK(fdp);
 1965                         for (fdtol = fdtol->fdl_next;
 1966                              fdtol != td->td_proc->p_fdtol;
 1967                              fdtol = fdtol->fdl_next) {
 1968                                 if ((fdtol->fdl_leader->p_flag &
 1969                                      P_ADVLOCK) == 0)
 1970                                         continue;
 1971                                 fdtol->fdl_holdcount++;
 1972                                 FILEDESC_UNLOCK(fdp);
 1973                                 lf.l_whence = SEEK_SET;
 1974                                 lf.l_start = 0;
 1975                                 lf.l_len = 0;
 1976                                 lf.l_type = F_UNLCK;
 1977                                 vp = fp->f_vnode;
 1978                                 (void) VOP_ADVLOCK(vp,
 1979                                                    (caddr_t)fdtol->fdl_leader,
 1980                                                    F_UNLCK, &lf, F_POSIX);
 1981                                 FILEDESC_LOCK(fdp);
 1982                                 fdtol->fdl_holdcount--;
 1983                                 if (fdtol->fdl_holdcount == 0 &&
 1984                                     fdtol->fdl_wakeup != 0) {
 1985                                         fdtol->fdl_wakeup = 0;
 1986                                         wakeup(fdtol);
 1987                                 }
 1988                         }
 1989                         FILEDESC_UNLOCK(fdp);
 1990                 }
 1991                 VFS_UNLOCK_GIANT(vfslocked);
 1992         }
 1993         return (fdrop(fp, td));
 1994 }
 1995 
 1996 /*
 1997  * Extract the file pointer associated with the specified descriptor for
 1998  * the current user process.
 1999  *
 2000  * If the descriptor doesn't exist, EBADF is returned.
 2001  *
 2002  * If the descriptor exists but doesn't match 'flags' then
 2003  * return EBADF for read attempts and EINVAL for write attempts.
 2004  *
 2005  * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
 2006  * It should be dropped with fdrop().
 2007  * If it is not set, then the refcount will not be bumped however the
 2008  * thread's filedesc struct will be returned locked (for fgetsock).
 2009  *
 2010  * If an error occured the non-zero error is returned and *fpp is set to NULL.
 2011  * Otherwise *fpp is set and zero is returned.
 2012  */
 2013 static __inline int
 2014 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
 2015 {
 2016         struct filedesc *fdp;
 2017         struct file *fp;
 2018 
 2019         *fpp = NULL;
 2020         if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
 2021                 return (EBADF);
 2022         FILEDESC_LOCK(fdp);
 2023         if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
 2024                 FILEDESC_UNLOCK(fdp);
 2025                 return (EBADF);
 2026         }
 2027 
 2028         /*
 2029          * Note: FREAD failure returns EBADF to maintain backwards
 2030          * compatibility with what routines returned before.
 2031          *
 2032          * Only one flag, or 0, may be specified.
 2033          */
 2034         if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
 2035                 FILEDESC_UNLOCK(fdp);
 2036                 return (EBADF);
 2037         }
 2038         if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
 2039                 FILEDESC_UNLOCK(fdp);
 2040                 return (EINVAL);
 2041         }
 2042         if (hold) {
 2043                 fhold(fp);
 2044                 FILEDESC_UNLOCK(fdp);
 2045         }
 2046         *fpp = fp;
 2047         return (0);
 2048 }
 2049 
 2050 int
 2051 fget(struct thread *td, int fd, struct file **fpp)
 2052 {
 2053 
 2054         return(_fget(td, fd, fpp, 0, 1));
 2055 }
 2056 
 2057 int
 2058 fget_read(struct thread *td, int fd, struct file **fpp)
 2059 {
 2060 
 2061         return(_fget(td, fd, fpp, FREAD, 1));
 2062 }
 2063 
 2064 int
 2065 fget_write(struct thread *td, int fd, struct file **fpp)
 2066 {
 2067 
 2068         return(_fget(td, fd, fpp, FWRITE, 1));
 2069 }
 2070 
 2071 /*
 2072  * Like fget() but loads the underlying vnode, or returns an error if
 2073  * the descriptor does not represent a vnode.  Note that pipes use vnodes
 2074  * but never have VM objects.  The returned vnode will be vref()d.
 2075  *
 2076  * XXX: what about the unused flags ?
 2077  */
 2078 static __inline int
 2079 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
 2080 {
 2081         struct file *fp;
 2082         int error;
 2083 
 2084         *vpp = NULL;
 2085         if ((error = _fget(td, fd, &fp, flags, 0)) != 0)
 2086                 return (error);
 2087         if (fp->f_vnode == NULL) {
 2088                 error = EINVAL;
 2089         } else {
 2090                 *vpp = fp->f_vnode;
 2091                 vref(*vpp);
 2092         }
 2093         FILEDESC_UNLOCK(td->td_proc->p_fd);
 2094         return (error);
 2095 }
 2096 
 2097 int
 2098 fgetvp(struct thread *td, int fd, struct vnode **vpp)
 2099 {
 2100 
 2101         return (_fgetvp(td, fd, vpp, 0));
 2102 }
 2103 
 2104 int
 2105 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
 2106 {
 2107 
 2108         return (_fgetvp(td, fd, vpp, FREAD));
 2109 }
 2110 
 2111 #ifdef notyet
 2112 int
 2113 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
 2114 {
 2115 
 2116         return (_fgetvp(td, fd, vpp, FWRITE));
 2117 }
 2118 #endif
 2119 
 2120 /*
 2121  * Like fget() but loads the underlying socket, or returns an error if
 2122  * the descriptor does not represent a socket.
 2123  *
 2124  * We bump the ref count on the returned socket.  XXX Also obtain the SX
 2125  * lock in the future.
 2126  */
 2127 int
 2128 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
 2129 {
 2130         struct file *fp;
 2131         int error;
 2132 
 2133         NET_ASSERT_GIANT();
 2134 
 2135         *spp = NULL;
 2136         if (fflagp != NULL)
 2137                 *fflagp = 0;
 2138         if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
 2139                 return (error);
 2140         if (fp->f_type != DTYPE_SOCKET) {
 2141                 error = ENOTSOCK;
 2142         } else {
 2143                 *spp = fp->f_data;
 2144                 if (fflagp)
 2145                         *fflagp = fp->f_flag;
 2146                 SOCK_LOCK(*spp);
 2147                 soref(*spp);
 2148                 SOCK_UNLOCK(*spp);
 2149         }
 2150         FILEDESC_UNLOCK(td->td_proc->p_fd);
 2151         return (error);
 2152 }
 2153 
 2154 /*
 2155  * Drop the reference count on the socket and XXX release the SX lock in
 2156  * the future.  The last reference closes the socket.
 2157  */
 2158 void
 2159 fputsock(struct socket *so)
 2160 {
 2161 
 2162         NET_ASSERT_GIANT();
 2163         ACCEPT_LOCK();
 2164         SOCK_LOCK(so);
 2165         sorele(so);
 2166 }
 2167 
 2168 int
 2169 fdrop(struct file *fp, struct thread *td)
 2170 {
 2171 
 2172         FILE_LOCK(fp);
 2173         return (fdrop_locked(fp, td));
 2174 }
 2175 
 2176 /*
 2177  * Drop reference on struct file passed in, may call closef if the
 2178  * reference hits zero.
 2179  * Expects struct file locked, and will unlock it.
 2180  */
 2181 static int
 2182 fdrop_locked(struct file *fp, struct thread *td)
 2183 {
 2184         int error;
 2185 
 2186         FILE_LOCK_ASSERT(fp, MA_OWNED);
 2187 
 2188         if (--fp->f_count > 0) {
 2189                 FILE_UNLOCK(fp);
 2190                 return (0);
 2191         }
 2192 
 2193         /*
 2194          * We might have just dropped the last reference to a file
 2195          * object that is for a UNIX domain socket whose message
 2196          * buffers are being examined in unp_gc().  If that is the
 2197          * case, FWAIT will be set in f_gcflag and we need to wait for
 2198          * unp_gc() to finish its scan.
 2199          */
 2200         while (fp->f_gcflag & FWAIT)
 2201                 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
 2202 
 2203         /* We have the last ref so we can proceed without the file lock. */
 2204         FILE_UNLOCK(fp);
 2205         if (fp->f_count < 0)
 2206                 panic("fdrop: count < 0");
 2207         if (fp->f_ops != &badfileops)
 2208                 error = fo_close(fp, td);
 2209         else
 2210                 error = 0;
 2211 
 2212         sx_xlock(&filelist_lock);
 2213         LIST_REMOVE(fp, f_list);
 2214         openfiles--;
 2215         sx_xunlock(&filelist_lock);
 2216         crfree(fp->f_cred);
 2217         uma_zfree(file_zone, fp);
 2218 
 2219         return (error);
 2220 }
 2221 
 2222 /*
 2223  * Apply an advisory lock on a file descriptor.
 2224  *
 2225  * Just attempt to get a record lock of the requested type on
 2226  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
 2227  */
 2228 #ifndef _SYS_SYSPROTO_H_
 2229 struct flock_args {
 2230         int     fd;
 2231         int     how;
 2232 };
 2233 #endif
 2234 /*
 2235  * MPSAFE
 2236  */
 2237 /* ARGSUSED */
 2238 int
 2239 flock(struct thread *td, struct flock_args *uap)
 2240 {
 2241         struct file *fp;
 2242         struct vnode *vp;
 2243         struct flock lf;
 2244         int error;
 2245 
 2246         if ((error = fget(td, uap->fd, &fp)) != 0)
 2247                 return (error);
 2248         if (fp->f_type != DTYPE_VNODE) {
 2249                 fdrop(fp, td);
 2250                 return (EOPNOTSUPP);
 2251         }
 2252 
 2253         mtx_lock(&Giant);
 2254         vp = fp->f_vnode;
 2255         lf.l_whence = SEEK_SET;
 2256         lf.l_start = 0;
 2257         lf.l_len = 0;
 2258         if (uap->how & LOCK_UN) {
 2259                 lf.l_type = F_UNLCK;
 2260                 FILE_LOCK(fp);
 2261                 fp->f_flag &= ~FHASLOCK;
 2262                 FILE_UNLOCK(fp);
 2263                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
 2264                 goto done2;
 2265         }
 2266         if (uap->how & LOCK_EX)
 2267                 lf.l_type = F_WRLCK;
 2268         else if (uap->how & LOCK_SH)
 2269                 lf.l_type = F_RDLCK;
 2270         else {
 2271                 error = EBADF;
 2272                 goto done2;
 2273         }
 2274         FILE_LOCK(fp);
 2275         fp->f_flag |= FHASLOCK;
 2276         FILE_UNLOCK(fp);
 2277         error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
 2278             (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
 2279 done2:
 2280         fdrop(fp, td);
 2281         mtx_unlock(&Giant);
 2282         return (error);
 2283 }
 2284 /*
 2285  * Duplicate the specified descriptor to a free descriptor.
 2286  */
 2287 int
 2288 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
 2289 {
 2290         struct file *wfp;
 2291         struct file *fp;
 2292 
 2293         /*
 2294          * If the to-be-dup'd fd number is greater than the allowed number
 2295          * of file descriptors, or the fd to be dup'd has already been
 2296          * closed, then reject.
 2297          */
 2298         FILEDESC_LOCK(fdp);
 2299         if (dfd < 0 || dfd >= fdp->fd_nfiles ||
 2300             (wfp = fdp->fd_ofiles[dfd]) == NULL) {
 2301                 FILEDESC_UNLOCK(fdp);
 2302                 return (EBADF);
 2303         }
 2304 
 2305         /*
 2306          * There are two cases of interest here.
 2307          *
 2308          * For ENODEV simply dup (dfd) to file descriptor
 2309          * (indx) and return.
 2310          *
 2311          * For ENXIO steal away the file structure from (dfd) and
 2312          * store it in (indx).  (dfd) is effectively closed by
 2313          * this operation.
 2314          *
 2315          * Any other error code is just returned.
 2316          */
 2317         switch (error) {
 2318         case ENODEV:
 2319                 /*
 2320                  * Check that the mode the file is being opened for is a
 2321                  * subset of the mode of the existing descriptor.
 2322                  */
 2323                 FILE_LOCK(wfp);
 2324                 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
 2325                         FILE_UNLOCK(wfp);
 2326                         FILEDESC_UNLOCK(fdp);
 2327                         return (EACCES);
 2328                 }
 2329                 fp = fdp->fd_ofiles[indx];
 2330                 fdp->fd_ofiles[indx] = wfp;
 2331                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
 2332                 if (fp == NULL)
 2333                         fdused(fdp, indx);
 2334                 fhold_locked(wfp);
 2335                 FILE_UNLOCK(wfp);
 2336                 FILEDESC_UNLOCK(fdp);
 2337                 if (fp != NULL) {
 2338                         /*
 2339                          * We now own the reference to fp that the ofiles[]
 2340                          * array used to own.  Release it.
 2341                          */
 2342                         FILE_LOCK(fp);
 2343                         fdrop_locked(fp, td);
 2344                 }
 2345                 return (0);
 2346 
 2347         case ENXIO:
 2348                 /*
 2349                  * Steal away the file pointer from dfd and stuff it into indx.
 2350                  */
 2351                 fp = fdp->fd_ofiles[indx];
 2352                 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
 2353                 fdp->fd_ofiles[dfd] = NULL;
 2354                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
 2355                 fdp->fd_ofileflags[dfd] = 0;
 2356                 fdunused(fdp, dfd);
 2357                 if (fp == NULL)
 2358                         fdused(fdp, indx);
 2359                 if (fp != NULL)
 2360                         FILE_LOCK(fp);
 2361 
 2362                 /*
 2363                  * We now own the reference to fp that the ofiles[] array
 2364                  * used to own.  Release it.
 2365                  */
 2366                 if (fp != NULL)
 2367                         fdrop_locked(fp, td);
 2368 
 2369                 FILEDESC_UNLOCK(fdp);
 2370 
 2371                 return (0);
 2372 
 2373         default:
 2374                 FILEDESC_UNLOCK(fdp);
 2375                 return (error);
 2376         }
 2377         /* NOTREACHED */
 2378 }
 2379 
 2380 /*
 2381  * Scan all active processes to see if any of them have a current
 2382  * or root directory of `olddp'. If so, replace them with the new
 2383  * mount point.
 2384  */
 2385 void
 2386 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
 2387 {
 2388         struct filedesc *fdp;
 2389         struct proc *p;
 2390         int nrele;
 2391 
 2392         if (vrefcnt(olddp) == 1)
 2393                 return;
 2394         sx_slock(&allproc_lock);
 2395         LIST_FOREACH(p, &allproc, p_list) {
 2396                 fdp = fdhold(p);
 2397                 if (fdp == NULL)
 2398                         continue;
 2399                 nrele = 0;
 2400                 FILEDESC_LOCK_FAST(fdp);
 2401                 if (fdp->fd_cdir == olddp) {
 2402                         vref(newdp);
 2403                         fdp->fd_cdir = newdp;
 2404                         nrele++;
 2405                 }
 2406                 if (fdp->fd_rdir == olddp) {
 2407                         vref(newdp);
 2408                         fdp->fd_rdir = newdp;
 2409                         nrele++;
 2410                 }
 2411                 FILEDESC_UNLOCK_FAST(fdp);
 2412                 fddrop(fdp);
 2413                 while (nrele--)
 2414                         vrele(olddp);
 2415         }
 2416         sx_sunlock(&allproc_lock);
 2417         if (rootvnode == olddp) {
 2418                 vrele(rootvnode);
 2419                 vref(newdp);
 2420                 rootvnode = newdp;
 2421         }
 2422 }
 2423 
 2424 struct filedesc_to_leader *
 2425 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
 2426 {
 2427         struct filedesc_to_leader *fdtol;
 2428 
 2429         MALLOC(fdtol, struct filedesc_to_leader *,
 2430                sizeof(struct filedesc_to_leader),
 2431                M_FILEDESC_TO_LEADER,
 2432                M_WAITOK);
 2433         fdtol->fdl_refcount = 1;
 2434         fdtol->fdl_holdcount = 0;
 2435         fdtol->fdl_wakeup = 0;
 2436         fdtol->fdl_leader = leader;
 2437         if (old != NULL) {
 2438                 FILEDESC_LOCK(fdp);
 2439                 fdtol->fdl_next = old->fdl_next;
 2440                 fdtol->fdl_prev = old;
 2441                 old->fdl_next = fdtol;
 2442                 fdtol->fdl_next->fdl_prev = fdtol;
 2443                 FILEDESC_UNLOCK(fdp);
 2444         } else {
 2445                 fdtol->fdl_next = fdtol;
 2446                 fdtol->fdl_prev = fdtol;
 2447         }
 2448         return (fdtol);
 2449 }
 2450 
 2451 /*
 2452  * Get file structures.
 2453  */
 2454 static int
 2455 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
 2456 {
 2457         struct xfile xf;
 2458         struct filedesc *fdp;
 2459         struct file *fp;
 2460         struct proc *p;
 2461         int error, n;
 2462 
 2463         /*
 2464          * Note: because the number of file descriptors is calculated
 2465          * in different ways for sizing vs returning the data,
 2466          * there is information leakage from the first loop.  However,
 2467          * it is of a similar order of magnitude to the leakage from
 2468          * global system statistics such as kern.openfiles.
 2469          */
 2470         error = sysctl_wire_old_buffer(req, 0);
 2471         if (error != 0)
 2472                 return (error);
 2473         if (req->oldptr == NULL) {
 2474                 n = 16;         /* A slight overestimate. */
 2475                 sx_slock(&filelist_lock);
 2476                 LIST_FOREACH(fp, &filehead, f_list) {
 2477                         /*
 2478                          * We should grab the lock, but this is an
 2479                          * estimate, so does it really matter?
 2480                          */
 2481                         /* mtx_lock(fp->f_mtxp); */
 2482                         n += fp->f_count;
 2483                         /* mtx_unlock(f->f_mtxp); */
 2484                 }
 2485                 sx_sunlock(&filelist_lock);
 2486                 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
 2487         }
 2488         error = 0;
 2489         bzero(&xf, sizeof(xf));
 2490         xf.xf_size = sizeof(xf);
 2491         sx_slock(&allproc_lock);
 2492         LIST_FOREACH(p, &allproc, p_list) {
 2493                 if (p->p_state == PRS_NEW)
 2494                         continue;
 2495                 PROC_LOCK(p);
 2496                 if (p_cansee(req->td, p) != 0) {
 2497                         PROC_UNLOCK(p);
 2498                         continue;
 2499                 }
 2500                 xf.xf_pid = p->p_pid;
 2501                 xf.xf_uid = p->p_ucred->cr_uid;
 2502                 PROC_UNLOCK(p);
 2503                 fdp = fdhold(p);
 2504                 if (fdp == NULL)
 2505                         continue;
 2506                 FILEDESC_LOCK_FAST(fdp);
 2507                 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
 2508                         if ((fp = fdp->fd_ofiles[n]) == NULL)
 2509                                 continue;
 2510                         xf.xf_fd = n;
 2511                         xf.xf_file = fp;
 2512                         xf.xf_data = fp->f_data;
 2513                         xf.xf_vnode = fp->f_vnode;
 2514                         xf.xf_type = fp->f_type;
 2515                         xf.xf_count = fp->f_count;
 2516                         xf.xf_msgcount = fp->f_msgcount;
 2517                         xf.xf_offset = fp->f_offset;
 2518                         xf.xf_flag = fp->f_flag;
 2519                         error = SYSCTL_OUT(req, &xf, sizeof(xf));
 2520                         if (error)
 2521                                 break;
 2522                 }
 2523                 FILEDESC_UNLOCK_FAST(fdp);
 2524                 fddrop(fdp);
 2525                 if (error)
 2526                         break;
 2527         }
 2528         sx_sunlock(&allproc_lock);
 2529         return (error);
 2530 }
 2531 
 2532 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
 2533     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
 2534 
 2535 #ifdef DDB
 2536 /*
 2537  * For the purposes of debugging, generate a human-readable string for the
 2538  * file type.
 2539  */
 2540 static const char *
 2541 file_type_to_name(short type)
 2542 {
 2543 
 2544         switch (type) {
 2545         case 0:
 2546                 return ("zero");
 2547         case DTYPE_VNODE:
 2548                 return ("vnod");
 2549         case DTYPE_SOCKET:
 2550                 return ("sock");
 2551         case DTYPE_PIPE:
 2552                 return ("pipe");
 2553         case DTYPE_FIFO:
 2554                 return ("fifo");
 2555         case DTYPE_CRYPTO:
 2556                 return ("crpt");
 2557         default:
 2558                 return ("unkn");
 2559         }
 2560 }
 2561 
 2562 /*
 2563  * For the purposes of debugging, identify a process (if any, perhaps one of
 2564  * many) that references the passed file in its file descriptor array. Return
 2565  * NULL if none.
 2566  */
 2567 static struct proc *
 2568 file_to_first_proc(struct file *fp)
 2569 {
 2570         struct filedesc *fdp;
 2571         struct proc *p;
 2572         int n;
 2573 
 2574         LIST_FOREACH(p, &allproc, p_list) {
 2575                 if (p->p_state == PRS_NEW)
 2576                         continue;
 2577                 fdp = p->p_fd;
 2578                 if (fdp == NULL)
 2579                         continue;
 2580                 for (n = 0; n < fdp->fd_nfiles; n++) {
 2581                         if (fp == fdp->fd_ofiles[n])
 2582                                 return (p);
 2583                 }
 2584         }
 2585         return (NULL);
 2586 }
 2587 
 2588 DB_SHOW_COMMAND(files, db_show_files)
 2589 {
 2590         struct file *fp;
 2591         struct proc *p;
 2592 
 2593         db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n", "File",
 2594             "Type", "Data", "Flag", "GCFl", "Count", "MCount", "Vnode",
 2595             "FPID", "FCmd");
 2596         LIST_FOREACH(fp, &filehead, f_list) {
 2597                 p = file_to_first_proc(fp);
 2598                 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
 2599                     file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
 2600                     fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
 2601                     p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
 2602         }
 2603 }
 2604 #endif
 2605 
 2606 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
 2607     &maxfilesperproc, 0, "Maximum files allowed open per process");
 2608 
 2609 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
 2610     &maxfiles, 0, "Maximum number of files");
 2611 
 2612 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
 2613     &openfiles, 0, "System-wide number of open files");
 2614 
 2615 /* ARGSUSED*/
 2616 static void
 2617 filelistinit(void *dummy)
 2618 {
 2619 
 2620         file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
 2621             NULL, NULL, UMA_ALIGN_PTR, 0);
 2622         sx_init(&filelist_lock, "filelist lock");
 2623         mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
 2624         mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
 2625 }
 2626 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
 2627 
 2628 /*-------------------------------------------------------------------*/
 2629 
 2630 static int
 2631 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
 2632 {
 2633 
 2634         return (EBADF);
 2635 }
 2636 
 2637 static int
 2638 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
 2639 {
 2640 
 2641         return (EBADF);
 2642 }
 2643 
 2644 static int
 2645 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
 2646 {
 2647 
 2648         return (0);
 2649 }
 2650 
 2651 static int
 2652 badfo_kqfilter(struct file *fp, struct knote *kn)
 2653 {
 2654 
 2655         return (EBADF);
 2656 }
 2657 
 2658 static int
 2659 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
 2660 {
 2661 
 2662         return (EBADF);
 2663 }
 2664 
 2665 static int
 2666 badfo_close(struct file *fp, struct thread *td)
 2667 {
 2668 
 2669         return (EBADF);
 2670 }
 2671 
 2672 struct fileops badfileops = {
 2673         .fo_read = badfo_readwrite,
 2674         .fo_write = badfo_readwrite,
 2675         .fo_ioctl = badfo_ioctl,
 2676         .fo_poll = badfo_poll,
 2677         .fo_kqfilter = badfo_kqfilter,
 2678         .fo_stat = badfo_stat,
 2679         .fo_close = badfo_close,
 2680 };
 2681 
 2682 
 2683 /*-------------------------------------------------------------------*/
 2684 
 2685 /*
 2686  * File Descriptor pseudo-device driver (/dev/fd/).
 2687  *
 2688  * Opening minor device N dup()s the file (if any) connected to file
 2689  * descriptor N belonging to the calling process.  Note that this driver
 2690  * consists of only the ``open()'' routine, because all subsequent
 2691  * references to this file will be direct to the other driver.
 2692  *
 2693  * XXX: we could give this one a cloning event handler if necessary.
 2694  */
 2695 
 2696 /* ARGSUSED */
 2697 static int
 2698 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
 2699 {
 2700 
 2701         /*
 2702          * XXX Kludge: set curthread->td_dupfd to contain the value of the
 2703          * the file descriptor being sought for duplication. The error
 2704          * return ensures that the vnode for this device will be released
 2705          * by vn_open. Open will detect this special error and take the
 2706          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
 2707          * will simply report the error.
 2708          */
 2709         td->td_dupfd = dev2unit(dev);
 2710         return (ENODEV);
 2711 }
 2712 
 2713 static struct cdevsw fildesc_cdevsw = {
 2714         .d_version =    D_VERSION,
 2715         .d_flags =      D_NEEDGIANT,
 2716         .d_open =       fdopen,
 2717         .d_name =       "FD",
 2718 };
 2719 
 2720 static void
 2721 fildesc_drvinit(void *unused)
 2722 {
 2723         struct cdev *dev;
 2724 
 2725         dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
 2726         make_dev_alias(dev, "stdin");
 2727         dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
 2728         make_dev_alias(dev, "stdout");
 2729         dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
 2730         make_dev_alias(dev, "stderr");
 2731 }
 2732 
 2733 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)

Cache object: 6827c6742f096ffab3d400632c0d7119


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