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$");
   39 
   40 #include "opt_compat.h"
   41 #include "opt_ddb.h"
   42 #include "opt_ktrace.h"
   43 
   44 #include <sys/param.h>
   45 #include <sys/systm.h>
   46 
   47 #include <sys/conf.h>
   48 #include <sys/domain.h>
   49 #include <sys/fcntl.h>
   50 #include <sys/file.h>
   51 #include <sys/filedesc.h>
   52 #include <sys/filio.h>
   53 #include <sys/jail.h>
   54 #include <sys/kernel.h>
   55 #include <sys/ksem.h>
   56 #include <sys/limits.h>
   57 #include <sys/lock.h>
   58 #include <sys/malloc.h>
   59 #include <sys/mman.h>
   60 #include <sys/mount.h>
   61 #include <sys/mqueue.h>
   62 #include <sys/mutex.h>
   63 #include <sys/namei.h>
   64 #include <sys/priv.h>
   65 #include <sys/proc.h>
   66 #include <sys/protosw.h>
   67 #include <sys/resourcevar.h>
   68 #include <sys/signalvar.h>
   69 #include <sys/socketvar.h>
   70 #include <sys/stat.h>
   71 #include <sys/sx.h>
   72 #include <sys/syscallsubr.h>
   73 #include <sys/sysctl.h>
   74 #include <sys/sysproto.h>
   75 #include <sys/tty.h>
   76 #include <sys/unistd.h>
   77 #include <sys/user.h>
   78 #include <sys/vnode.h>
   79 #ifdef KTRACE
   80 #include <sys/ktrace.h>
   81 #endif
   82 
   83 #include <net/vnet.h>
   84 
   85 #include <security/audit/audit.h>
   86 
   87 #include <vm/uma.h>
   88 
   89 #include <ddb/ddb.h>
   90 
   91 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
   92 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
   93                      "file desc to leader structures");
   94 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
   95 
   96 MALLOC_DECLARE(M_FADVISE);
   97 
   98 static uma_zone_t file_zone;
   99 
  100 void    (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
  101 
  102 /* Flags for do_dup() */
  103 #define DUP_FIXED       0x1     /* Force fixed allocation */
  104 #define DUP_FCNTL       0x2     /* fcntl()-style errors */
  105 #define DUP_CLOEXEC     0x4     /* Atomically set FD_CLOEXEC. */
  106 
  107 static int do_dup(struct thread *td, int flags, int old, int new,
  108     register_t *retval);
  109 static int      fd_first_free(struct filedesc *, int, int);
  110 static int      fd_last_used(struct filedesc *, int, int);
  111 static void     fdgrowtable(struct filedesc *, int);
  112 static void     fdunused(struct filedesc *fdp, int fd);
  113 static void     fdused(struct filedesc *fdp, int fd);
  114 
  115 /*
  116  * A process is initially started out with NDFILE descriptors stored within
  117  * this structure, selected to be enough for typical applications based on
  118  * the historical limit of 20 open files (and the usage of descriptors by
  119  * shells).  If these descriptors are exhausted, a larger descriptor table
  120  * may be allocated, up to a process' resource limit; the internal arrays
  121  * are then unused.
  122  */
  123 #define NDFILE          20
  124 #define NDSLOTSIZE      sizeof(NDSLOTTYPE)
  125 #define NDENTRIES       (NDSLOTSIZE * __CHAR_BIT)
  126 #define NDSLOT(x)       ((x) / NDENTRIES)
  127 #define NDBIT(x)        ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
  128 #define NDSLOTS(x)      (((x) + NDENTRIES - 1) / NDENTRIES)
  129 
  130 /*
  131  * Storage required per open file descriptor.
  132  */
  133 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
  134 
  135 /*
  136  * Storage to hold unused ofiles that need to be reclaimed.
  137  */
  138 struct freetable {
  139         struct file     **ft_table;
  140         SLIST_ENTRY(freetable) ft_next;
  141 };
  142 
  143 /*
  144  * Basic allocation of descriptors:
  145  * one of the above, plus arrays for NDFILE descriptors.
  146  */
  147 struct filedesc0 {
  148         struct  filedesc fd_fd;
  149         /*
  150          * ofiles which need to be reclaimed on free.
  151          */
  152         SLIST_HEAD(,freetable) fd_free;
  153         /*
  154          * These arrays are used when the number of open files is
  155          * <= NDFILE, and are then pointed to by the pointers above.
  156          */
  157         struct  file *fd_dfiles[NDFILE];
  158         char    fd_dfileflags[NDFILE];
  159         NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
  160 };
  161 
  162 /*
  163  * Descriptor management.
  164  */
  165 volatile int openfiles;                 /* actual number of open files */
  166 struct mtx sigio_lock;          /* mtx to protect pointers to sigio */
  167 void    (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
  168 
  169 /* A mutex to protect the association between a proc and filedesc. */
  170 static struct mtx       fdesc_mtx;
  171 
  172 /*
  173  * Find the first zero bit in the given bitmap, starting at low and not
  174  * exceeding size - 1.
  175  */
  176 static int
  177 fd_first_free(struct filedesc *fdp, int low, int size)
  178 {
  179         NDSLOTTYPE *map = fdp->fd_map;
  180         NDSLOTTYPE mask;
  181         int off, maxoff;
  182 
  183         if (low >= size)
  184                 return (low);
  185 
  186         off = NDSLOT(low);
  187         if (low % NDENTRIES) {
  188                 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
  189                 if ((mask &= ~map[off]) != 0UL)
  190                         return (off * NDENTRIES + ffsl(mask) - 1);
  191                 ++off;
  192         }
  193         for (maxoff = NDSLOTS(size); off < maxoff; ++off)
  194                 if (map[off] != ~0UL)
  195                         return (off * NDENTRIES + ffsl(~map[off]) - 1);
  196         return (size);
  197 }
  198 
  199 /*
  200  * Find the highest non-zero bit in the given bitmap, starting at low and
  201  * not exceeding size - 1.
  202  */
  203 static int
  204 fd_last_used(struct filedesc *fdp, int low, int size)
  205 {
  206         NDSLOTTYPE *map = fdp->fd_map;
  207         NDSLOTTYPE mask;
  208         int off, minoff;
  209 
  210         if (low >= size)
  211                 return (-1);
  212 
  213         off = NDSLOT(size);
  214         if (size % NDENTRIES) {
  215                 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
  216                 if ((mask &= map[off]) != 0)
  217                         return (off * NDENTRIES + flsl(mask) - 1);
  218                 --off;
  219         }
  220         for (minoff = NDSLOT(low); off >= minoff; --off)
  221                 if (map[off] != 0)
  222                         return (off * NDENTRIES + flsl(map[off]) - 1);
  223         return (low - 1);
  224 }
  225 
  226 static int
  227 fdisused(struct filedesc *fdp, int fd)
  228 {
  229         KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
  230             ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
  231         return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
  232 }
  233 
  234 /*
  235  * Mark a file descriptor as used.
  236  */
  237 static void
  238 fdused(struct filedesc *fdp, int fd)
  239 {
  240 
  241         FILEDESC_XLOCK_ASSERT(fdp);
  242         KASSERT(!fdisused(fdp, fd),
  243             ("fd already used"));
  244 
  245         fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
  246         if (fd > fdp->fd_lastfile)
  247                 fdp->fd_lastfile = fd;
  248         if (fd == fdp->fd_freefile)
  249                 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
  250 }
  251 
  252 /*
  253  * Mark a file descriptor as unused.
  254  */
  255 static void
  256 fdunused(struct filedesc *fdp, int fd)
  257 {
  258 
  259         FILEDESC_XLOCK_ASSERT(fdp);
  260         KASSERT(fdisused(fdp, fd),
  261             ("fd is already unused"));
  262         KASSERT(fdp->fd_ofiles[fd] == NULL,
  263             ("fd is still in use"));
  264 
  265         fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
  266         if (fd < fdp->fd_freefile)
  267                 fdp->fd_freefile = fd;
  268         if (fd == fdp->fd_lastfile)
  269                 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
  270 }
  271 
  272 /*
  273  * System calls on descriptors.
  274  */
  275 #ifndef _SYS_SYSPROTO_H_
  276 struct getdtablesize_args {
  277         int     dummy;
  278 };
  279 #endif
  280 /* ARGSUSED */
  281 int
  282 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
  283 {
  284         struct proc *p = td->td_proc;
  285 
  286         PROC_LOCK(p);
  287         td->td_retval[0] =
  288             min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
  289         PROC_UNLOCK(p);
  290         return (0);
  291 }
  292 
  293 /*
  294  * Duplicate a file descriptor to a particular value.
  295  *
  296  * Note: keep in mind that a potential race condition exists when closing
  297  * descriptors from a shared descriptor table (via rfork).
  298  */
  299 #ifndef _SYS_SYSPROTO_H_
  300 struct dup2_args {
  301         u_int   from;
  302         u_int   to;
  303 };
  304 #endif
  305 /* ARGSUSED */
  306 int
  307 dup2(struct thread *td, struct dup2_args *uap)
  308 {
  309 
  310         return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
  311                     td->td_retval));
  312 }
  313 
  314 /*
  315  * Duplicate a file descriptor.
  316  */
  317 #ifndef _SYS_SYSPROTO_H_
  318 struct dup_args {
  319         u_int   fd;
  320 };
  321 #endif
  322 /* ARGSUSED */
  323 int
  324 dup(struct thread *td, struct dup_args *uap)
  325 {
  326 
  327         return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
  328 }
  329 
  330 /*
  331  * The file control system call.
  332  */
  333 #ifndef _SYS_SYSPROTO_H_
  334 struct fcntl_args {
  335         int     fd;
  336         int     cmd;
  337         long    arg;
  338 };
  339 #endif
  340 /* ARGSUSED */
  341 int
  342 fcntl(struct thread *td, struct fcntl_args *uap)
  343 {
  344         struct flock fl;
  345         struct oflock ofl;
  346         intptr_t arg;
  347         int error;
  348         int cmd;
  349 
  350         error = 0;
  351         cmd = uap->cmd;
  352         switch (uap->cmd) {
  353         case F_OGETLK:
  354         case F_OSETLK:
  355         case F_OSETLKW:
  356                 /*
  357                  * Convert old flock structure to new.
  358                  */
  359                 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
  360                 fl.l_start = ofl.l_start;
  361                 fl.l_len = ofl.l_len;
  362                 fl.l_pid = ofl.l_pid;
  363                 fl.l_type = ofl.l_type;
  364                 fl.l_whence = ofl.l_whence;
  365                 fl.l_sysid = 0;
  366 
  367                 switch (uap->cmd) {
  368                 case F_OGETLK:
  369                     cmd = F_GETLK;
  370                     break;
  371                 case F_OSETLK:
  372                     cmd = F_SETLK;
  373                     break;
  374                 case F_OSETLKW:
  375                     cmd = F_SETLKW;
  376                     break;
  377                 }
  378                 arg = (intptr_t)&fl;
  379                 break;
  380         case F_GETLK:
  381         case F_SETLK:
  382         case F_SETLKW:
  383         case F_SETLK_REMOTE:
  384                 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
  385                 arg = (intptr_t)&fl;
  386                 break;
  387         default:
  388                 arg = uap->arg;
  389                 break;
  390         }
  391         if (error)
  392                 return (error);
  393         error = kern_fcntl(td, uap->fd, cmd, arg);
  394         if (error)
  395                 return (error);
  396         if (uap->cmd == F_OGETLK) {
  397                 ofl.l_start = fl.l_start;
  398                 ofl.l_len = fl.l_len;
  399                 ofl.l_pid = fl.l_pid;
  400                 ofl.l_type = fl.l_type;
  401                 ofl.l_whence = fl.l_whence;
  402                 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
  403         } else if (uap->cmd == F_GETLK) {
  404                 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
  405         }
  406         return (error);
  407 }
  408 
  409 static inline struct file *
  410 fdtofp(int fd, struct filedesc *fdp)
  411 {
  412         struct file *fp;
  413 
  414         FILEDESC_LOCK_ASSERT(fdp);
  415         if ((unsigned)fd >= fdp->fd_nfiles ||
  416             (fp = fdp->fd_ofiles[fd]) == NULL)
  417                 return (NULL);
  418         return (fp);
  419 }
  420 
  421 int
  422 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
  423 {
  424         struct filedesc *fdp;
  425         struct flock *flp;
  426         struct file *fp;
  427         struct proc *p;
  428         char *pop;
  429         struct vnode *vp;
  430         int error, flg, tmp;
  431         int vfslocked;
  432         u_int old, new;
  433         uint64_t bsize;
  434 
  435         vfslocked = 0;
  436         error = 0;
  437         flg = F_POSIX;
  438         p = td->td_proc;
  439         fdp = p->p_fd;
  440 
  441         switch (cmd) {
  442         case F_DUPFD:
  443                 tmp = arg;
  444                 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
  445                 break;
  446 
  447         case F_DUPFD_CLOEXEC:
  448                 tmp = arg;
  449                 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
  450                     td->td_retval);
  451                 break;
  452 
  453         case F_DUP2FD:
  454                 tmp = arg;
  455                 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
  456                 break;
  457 
  458         case F_DUP2FD_CLOEXEC:
  459                 tmp = arg;
  460                 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
  461                     td->td_retval);
  462                 break;
  463 
  464         case F_GETFD:
  465                 FILEDESC_SLOCK(fdp);
  466                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  467                         FILEDESC_SUNLOCK(fdp);
  468                         error = EBADF;
  469                         break;
  470                 }
  471                 pop = &fdp->fd_ofileflags[fd];
  472                 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
  473                 FILEDESC_SUNLOCK(fdp);
  474                 break;
  475 
  476         case F_SETFD:
  477                 FILEDESC_XLOCK(fdp);
  478                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  479                         FILEDESC_XUNLOCK(fdp);
  480                         error = EBADF;
  481                         break;
  482                 }
  483                 pop = &fdp->fd_ofileflags[fd];
  484                 *pop = (*pop &~ UF_EXCLOSE) |
  485                     (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
  486                 FILEDESC_XUNLOCK(fdp);
  487                 break;
  488 
  489         case F_GETFL:
  490                 FILEDESC_SLOCK(fdp);
  491                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  492                         FILEDESC_SUNLOCK(fdp);
  493                         error = EBADF;
  494                         break;
  495                 }
  496                 td->td_retval[0] = OFLAGS(fp->f_flag);
  497                 FILEDESC_SUNLOCK(fdp);
  498                 break;
  499 
  500         case F_SETFL:
  501                 FILEDESC_SLOCK(fdp);
  502                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  503                         FILEDESC_SUNLOCK(fdp);
  504                         error = EBADF;
  505                         break;
  506                 }
  507                 fhold(fp);
  508                 FILEDESC_SUNLOCK(fdp);
  509                 do {
  510                         tmp = flg = fp->f_flag;
  511                         tmp &= ~FCNTLFLAGS;
  512                         tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
  513                 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
  514                 tmp = fp->f_flag & FNONBLOCK;
  515                 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
  516                 if (error) {
  517                         fdrop(fp, td);
  518                         break;
  519                 }
  520                 tmp = fp->f_flag & FASYNC;
  521                 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
  522                 if (error == 0) {
  523                         fdrop(fp, td);
  524                         break;
  525                 }
  526                 atomic_clear_int(&fp->f_flag, FNONBLOCK);
  527                 tmp = 0;
  528                 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
  529                 fdrop(fp, td);
  530                 break;
  531 
  532         case F_GETOWN:
  533                 FILEDESC_SLOCK(fdp);
  534                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  535                         FILEDESC_SUNLOCK(fdp);
  536                         error = EBADF;
  537                         break;
  538                 }
  539                 fhold(fp);
  540                 FILEDESC_SUNLOCK(fdp);
  541                 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
  542                 if (error == 0)
  543                         td->td_retval[0] = tmp;
  544                 fdrop(fp, td);
  545                 break;
  546 
  547         case F_SETOWN:
  548                 FILEDESC_SLOCK(fdp);
  549                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  550                         FILEDESC_SUNLOCK(fdp);
  551                         error = EBADF;
  552                         break;
  553                 }
  554                 fhold(fp);
  555                 FILEDESC_SUNLOCK(fdp);
  556                 tmp = arg;
  557                 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
  558                 fdrop(fp, td);
  559                 break;
  560 
  561         case F_SETLK_REMOTE:
  562                 error = priv_check(td, PRIV_NFS_LOCKD);
  563                 if (error)
  564                         return (error);
  565                 flg = F_REMOTE;
  566                 goto do_setlk;
  567 
  568         case F_SETLKW:
  569                 flg |= F_WAIT;
  570                 /* FALLTHROUGH F_SETLK */
  571 
  572         case F_SETLK:
  573         do_setlk:
  574                 FILEDESC_SLOCK(fdp);
  575                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  576                         FILEDESC_SUNLOCK(fdp);
  577                         error = EBADF;
  578                         break;
  579                 }
  580                 if (fp->f_type != DTYPE_VNODE) {
  581                         FILEDESC_SUNLOCK(fdp);
  582                         error = EBADF;
  583                         break;
  584                 }
  585                 flp = (struct flock *)arg;
  586                 if (flp->l_whence == SEEK_CUR) {
  587                         if (fp->f_offset < 0 ||
  588                             (flp->l_start > 0 &&
  589                              fp->f_offset > OFF_MAX - flp->l_start)) {
  590                                 FILEDESC_SUNLOCK(fdp);
  591                                 error = EOVERFLOW;
  592                                 break;
  593                         }
  594                         flp->l_start += fp->f_offset;
  595                 }
  596 
  597                 /*
  598                  * VOP_ADVLOCK() may block.
  599                  */
  600                 fhold(fp);
  601                 FILEDESC_SUNLOCK(fdp);
  602                 vp = fp->f_vnode;
  603                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
  604                 switch (flp->l_type) {
  605                 case F_RDLCK:
  606                         if ((fp->f_flag & FREAD) == 0) {
  607                                 error = EBADF;
  608                                 break;
  609                         }
  610                         PROC_LOCK(p->p_leader);
  611                         p->p_leader->p_flag |= P_ADVLOCK;
  612                         PROC_UNLOCK(p->p_leader);
  613                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
  614                             flp, flg);
  615                         break;
  616                 case F_WRLCK:
  617                         if ((fp->f_flag & FWRITE) == 0) {
  618                                 error = EBADF;
  619                                 break;
  620                         }
  621                         PROC_LOCK(p->p_leader);
  622                         p->p_leader->p_flag |= P_ADVLOCK;
  623                         PROC_UNLOCK(p->p_leader);
  624                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
  625                             flp, flg);
  626                         break;
  627                 case F_UNLCK:
  628                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
  629                             flp, flg);
  630                         break;
  631                 case F_UNLCKSYS:
  632                         /*
  633                          * Temporary api for testing remote lock
  634                          * infrastructure.
  635                          */
  636                         if (flg != F_REMOTE) {
  637                                 error = EINVAL;
  638                                 break;
  639                         }
  640                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
  641                             F_UNLCKSYS, flp, flg);
  642                         break;
  643                 default:
  644                         error = EINVAL;
  645                         break;
  646                 }
  647                 VFS_UNLOCK_GIANT(vfslocked);
  648                 vfslocked = 0;
  649                 /* Check for race with close */
  650                 FILEDESC_SLOCK(fdp);
  651                 if ((unsigned) fd >= fdp->fd_nfiles ||
  652                     fp != fdp->fd_ofiles[fd]) {
  653                         FILEDESC_SUNLOCK(fdp);
  654                         flp->l_whence = SEEK_SET;
  655                         flp->l_start = 0;
  656                         flp->l_len = 0;
  657                         flp->l_type = F_UNLCK;
  658                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
  659                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
  660                                            F_UNLCK, flp, F_POSIX);
  661                         VFS_UNLOCK_GIANT(vfslocked);
  662                         vfslocked = 0;
  663                 } else
  664                         FILEDESC_SUNLOCK(fdp);
  665                 fdrop(fp, td);
  666                 break;
  667 
  668         case F_GETLK:
  669                 FILEDESC_SLOCK(fdp);
  670                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  671                         FILEDESC_SUNLOCK(fdp);
  672                         error = EBADF;
  673                         break;
  674                 }
  675                 if (fp->f_type != DTYPE_VNODE) {
  676                         FILEDESC_SUNLOCK(fdp);
  677                         error = EBADF;
  678                         break;
  679                 }
  680                 flp = (struct flock *)arg;
  681                 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
  682                     flp->l_type != F_UNLCK) {
  683                         FILEDESC_SUNLOCK(fdp);
  684                         error = EINVAL;
  685                         break;
  686                 }
  687                 if (flp->l_whence == SEEK_CUR) {
  688                         if ((flp->l_start > 0 &&
  689                             fp->f_offset > OFF_MAX - flp->l_start) ||
  690                             (flp->l_start < 0 &&
  691                              fp->f_offset < OFF_MIN - flp->l_start)) {
  692                                 FILEDESC_SUNLOCK(fdp);
  693                                 error = EOVERFLOW;
  694                                 break;
  695                         }
  696                         flp->l_start += fp->f_offset;
  697                 }
  698                 /*
  699                  * VOP_ADVLOCK() may block.
  700                  */
  701                 fhold(fp);
  702                 FILEDESC_SUNLOCK(fdp);
  703                 vp = fp->f_vnode;
  704                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
  705                 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
  706                     F_POSIX);
  707                 VFS_UNLOCK_GIANT(vfslocked);
  708                 vfslocked = 0;
  709                 fdrop(fp, td);
  710                 break;
  711 
  712         case F_RDAHEAD:
  713                 arg = arg ? 128 * 1024: 0;
  714                 /* FALLTHROUGH */
  715         case F_READAHEAD:
  716                 FILEDESC_SLOCK(fdp);
  717                 if ((fp = fdtofp(fd, fdp)) == NULL) {
  718                         FILEDESC_SUNLOCK(fdp);
  719                         error = EBADF;
  720                         break;
  721                 }
  722                 if (fp->f_type != DTYPE_VNODE) {
  723                         FILEDESC_SUNLOCK(fdp);
  724                         error = EBADF;
  725                         break;
  726                 }
  727                 fhold(fp);
  728                 FILEDESC_SUNLOCK(fdp);
  729                 if (arg != 0) {
  730                         vp = fp->f_vnode;
  731                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
  732                         error = vn_lock(vp, LK_SHARED);
  733                         if (error != 0)
  734                                 goto readahead_vnlock_fail;
  735                         bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
  736                         VOP_UNLOCK(vp, 0);
  737                         fp->f_seqcount = (arg + bsize - 1) / bsize;
  738                         do {
  739                                 new = old = fp->f_flag;
  740                                 new |= FRDAHEAD;
  741                         } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
  742 readahead_vnlock_fail:
  743                         VFS_UNLOCK_GIANT(vfslocked);
  744                         vfslocked = 0;
  745                 } else {
  746                         do {
  747                                 new = old = fp->f_flag;
  748                                 new &= ~FRDAHEAD;
  749                         } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
  750                 }
  751                 fdrop(fp, td);
  752                 break;
  753 
  754         default:
  755                 error = EINVAL;
  756                 break;
  757         }
  758         VFS_UNLOCK_GIANT(vfslocked);
  759         return (error);
  760 }
  761 
  762 /*
  763  * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
  764  */
  765 static int
  766 do_dup(struct thread *td, int flags, int old, int new,
  767     register_t *retval)
  768 {
  769         struct filedesc *fdp;
  770         struct proc *p;
  771         struct file *fp;
  772         struct file *delfp;
  773         int error, holdleaders, maxfd;
  774 
  775         p = td->td_proc;
  776         fdp = p->p_fd;
  777 
  778         /*
  779          * Verify we have a valid descriptor to dup from and possibly to
  780          * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
  781          * return EINVAL when the new descriptor is out of bounds.
  782          */
  783         if (old < 0)
  784                 return (EBADF);
  785         if (new < 0)
  786                 return (flags & DUP_FCNTL ? EINVAL : EBADF);
  787         PROC_LOCK(p);
  788         maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
  789         PROC_UNLOCK(p);
  790         if (new >= maxfd)
  791                 return (flags & DUP_FCNTL ? EINVAL : EBADF);
  792 
  793         FILEDESC_XLOCK(fdp);
  794         if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
  795                 FILEDESC_XUNLOCK(fdp);
  796                 return (EBADF);
  797         }
  798         if (flags & DUP_FIXED && old == new) {
  799                 *retval = new;
  800                 if (flags & DUP_CLOEXEC)
  801                         fdp->fd_ofileflags[new] |= UF_EXCLOSE;
  802                 FILEDESC_XUNLOCK(fdp);
  803                 return (0);
  804         }
  805         fp = fdp->fd_ofiles[old];
  806         fhold(fp);
  807 
  808         /*
  809          * If the caller specified a file descriptor, make sure the file
  810          * table is large enough to hold it, and grab it.  Otherwise, just
  811          * allocate a new descriptor the usual way.  Since the filedesc
  812          * lock may be temporarily dropped in the process, we have to look
  813          * out for a race.
  814          */
  815         if (flags & DUP_FIXED) {
  816                 if (new >= fdp->fd_nfiles)
  817                         fdgrowtable(fdp, new + 1);
  818                 if (fdp->fd_ofiles[new] == NULL)
  819                         fdused(fdp, new);
  820         } else {
  821                 if ((error = fdalloc(td, new, &new)) != 0) {
  822                         FILEDESC_XUNLOCK(fdp);
  823                         fdrop(fp, td);
  824                         return (error);
  825                 }
  826         }
  827 
  828         /*
  829          * If the old file changed out from under us then treat it as a
  830          * bad file descriptor.  Userland should do its own locking to
  831          * avoid this case.
  832          */
  833         if (fdp->fd_ofiles[old] != fp) {
  834                 /* we've allocated a descriptor which we won't use */
  835                 if (fdp->fd_ofiles[new] == NULL)
  836                         fdunused(fdp, new);
  837                 FILEDESC_XUNLOCK(fdp);
  838                 fdrop(fp, td);
  839                 return (EBADF);
  840         }
  841         KASSERT(old != new,
  842             ("new fd is same as old"));
  843 
  844         /*
  845          * Save info on the descriptor being overwritten.  We cannot close
  846          * it without introducing an ownership race for the slot, since we
  847          * need to drop the filedesc lock to call closef().
  848          *
  849          * XXX this duplicates parts of close().
  850          */
  851         delfp = fdp->fd_ofiles[new];
  852         holdleaders = 0;
  853         if (delfp != NULL) {
  854                 if (td->td_proc->p_fdtol != NULL) {
  855                         /*
  856                          * Ask fdfree() to sleep to ensure that all relevant
  857                          * process leaders can be traversed in closef().
  858                          */
  859                         fdp->fd_holdleaderscount++;
  860                         holdleaders = 1;
  861                 }
  862         }
  863 
  864         /*
  865          * Duplicate the source descriptor
  866          */
  867         fdp->fd_ofiles[new] = fp;
  868         if ((flags & DUP_CLOEXEC) != 0)
  869                 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
  870         else
  871                 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
  872         if (new > fdp->fd_lastfile)
  873                 fdp->fd_lastfile = new;
  874         *retval = new;
  875 
  876         /*
  877          * If we dup'd over a valid file, we now own the reference to it
  878          * and must dispose of it using closef() semantics (as if a
  879          * close() were performed on it).
  880          *
  881          * XXX this duplicates parts of close().
  882          */
  883         if (delfp != NULL) {
  884                 knote_fdclose(td, new);
  885                 if (delfp->f_type == DTYPE_MQUEUE)
  886                         mq_fdclose(td, new, delfp);
  887                 FILEDESC_XUNLOCK(fdp);
  888                 (void) closef(delfp, td);
  889                 if (holdleaders) {
  890                         FILEDESC_XLOCK(fdp);
  891                         fdp->fd_holdleaderscount--;
  892                         if (fdp->fd_holdleaderscount == 0 &&
  893                             fdp->fd_holdleaderswakeup != 0) {
  894                                 fdp->fd_holdleaderswakeup = 0;
  895                                 wakeup(&fdp->fd_holdleaderscount);
  896                         }
  897                         FILEDESC_XUNLOCK(fdp);
  898                 }
  899         } else {
  900                 FILEDESC_XUNLOCK(fdp);
  901         }
  902         return (0);
  903 }
  904 
  905 /*
  906  * If sigio is on the list associated with a process or process group,
  907  * disable signalling from the device, remove sigio from the list and
  908  * free sigio.
  909  */
  910 void
  911 funsetown(struct sigio **sigiop)
  912 {
  913         struct sigio *sigio;
  914 
  915         SIGIO_LOCK();
  916         sigio = *sigiop;
  917         if (sigio == NULL) {
  918                 SIGIO_UNLOCK();
  919                 return;
  920         }
  921         *(sigio->sio_myref) = NULL;
  922         if ((sigio)->sio_pgid < 0) {
  923                 struct pgrp *pg = (sigio)->sio_pgrp;
  924                 PGRP_LOCK(pg);
  925                 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
  926                              sigio, sio_pgsigio);
  927                 PGRP_UNLOCK(pg);
  928         } else {
  929                 struct proc *p = (sigio)->sio_proc;
  930                 PROC_LOCK(p);
  931                 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
  932                              sigio, sio_pgsigio);
  933                 PROC_UNLOCK(p);
  934         }
  935         SIGIO_UNLOCK();
  936         crfree(sigio->sio_ucred);
  937         free(sigio, M_SIGIO);
  938 }
  939 
  940 /*
  941  * Free a list of sigio structures.
  942  * We only need to lock the SIGIO_LOCK because we have made ourselves
  943  * inaccessible to callers of fsetown and therefore do not need to lock
  944  * the proc or pgrp struct for the list manipulation.
  945  */
  946 void
  947 funsetownlst(struct sigiolst *sigiolst)
  948 {
  949         struct proc *p;
  950         struct pgrp *pg;
  951         struct sigio *sigio;
  952 
  953         sigio = SLIST_FIRST(sigiolst);
  954         if (sigio == NULL)
  955                 return;
  956         p = NULL;
  957         pg = NULL;
  958 
  959         /*
  960          * Every entry of the list should belong
  961          * to a single proc or pgrp.
  962          */
  963         if (sigio->sio_pgid < 0) {
  964                 pg = sigio->sio_pgrp;
  965                 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
  966         } else /* if (sigio->sio_pgid > 0) */ {
  967                 p = sigio->sio_proc;
  968                 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
  969         }
  970 
  971         SIGIO_LOCK();
  972         while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
  973                 *(sigio->sio_myref) = NULL;
  974                 if (pg != NULL) {
  975                         KASSERT(sigio->sio_pgid < 0,
  976                             ("Proc sigio in pgrp sigio list"));
  977                         KASSERT(sigio->sio_pgrp == pg,
  978                             ("Bogus pgrp in sigio list"));
  979                         PGRP_LOCK(pg);
  980                         SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
  981                             sio_pgsigio);
  982                         PGRP_UNLOCK(pg);
  983                 } else /* if (p != NULL) */ {
  984                         KASSERT(sigio->sio_pgid > 0,
  985                             ("Pgrp sigio in proc sigio list"));
  986                         KASSERT(sigio->sio_proc == p,
  987                             ("Bogus proc in sigio list"));
  988                         PROC_LOCK(p);
  989                         SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
  990                             sio_pgsigio);
  991                         PROC_UNLOCK(p);
  992                 }
  993                 SIGIO_UNLOCK();
  994                 crfree(sigio->sio_ucred);
  995                 free(sigio, M_SIGIO);
  996                 SIGIO_LOCK();
  997         }
  998         SIGIO_UNLOCK();
  999 }
 1000 
 1001 /*
 1002  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
 1003  *
 1004  * After permission checking, add a sigio structure to the sigio list for
 1005  * the process or process group.
 1006  */
 1007 int
 1008 fsetown(pid_t pgid, struct sigio **sigiop)
 1009 {
 1010         struct proc *proc;
 1011         struct pgrp *pgrp;
 1012         struct sigio *sigio;
 1013         int ret;
 1014 
 1015         if (pgid == 0) {
 1016                 funsetown(sigiop);
 1017                 return (0);
 1018         }
 1019 
 1020         ret = 0;
 1021 
 1022         /* Allocate and fill in the new sigio out of locks. */
 1023         sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
 1024         sigio->sio_pgid = pgid;
 1025         sigio->sio_ucred = crhold(curthread->td_ucred);
 1026         sigio->sio_myref = sigiop;
 1027 
 1028         sx_slock(&proctree_lock);
 1029         if (pgid > 0) {
 1030                 proc = pfind(pgid);
 1031                 if (proc == NULL) {
 1032                         ret = ESRCH;
 1033                         goto fail;
 1034                 }
 1035 
 1036                 /*
 1037                  * Policy - Don't allow a process to FSETOWN a process
 1038                  * in another session.
 1039                  *
 1040                  * Remove this test to allow maximum flexibility or
 1041                  * restrict FSETOWN to the current process or process
 1042                  * group for maximum safety.
 1043                  */
 1044                 PROC_UNLOCK(proc);
 1045                 if (proc->p_session != curthread->td_proc->p_session) {
 1046                         ret = EPERM;
 1047                         goto fail;
 1048                 }
 1049 
 1050                 pgrp = NULL;
 1051         } else /* if (pgid < 0) */ {
 1052                 pgrp = pgfind(-pgid);
 1053                 if (pgrp == NULL) {
 1054                         ret = ESRCH;
 1055                         goto fail;
 1056                 }
 1057                 PGRP_UNLOCK(pgrp);
 1058 
 1059                 /*
 1060                  * Policy - Don't allow a process to FSETOWN a process
 1061                  * in another session.
 1062                  *
 1063                  * Remove this test to allow maximum flexibility or
 1064                  * restrict FSETOWN to the current process or process
 1065                  * group for maximum safety.
 1066                  */
 1067                 if (pgrp->pg_session != curthread->td_proc->p_session) {
 1068                         ret = EPERM;
 1069                         goto fail;
 1070                 }
 1071 
 1072                 proc = NULL;
 1073         }
 1074         funsetown(sigiop);
 1075         if (pgid > 0) {
 1076                 PROC_LOCK(proc);
 1077                 /*
 1078                  * Since funsetownlst() is called without the proctree
 1079                  * locked, we need to check for P_WEXIT.
 1080                  * XXX: is ESRCH correct?
 1081                  */
 1082                 if ((proc->p_flag & P_WEXIT) != 0) {
 1083                         PROC_UNLOCK(proc);
 1084                         ret = ESRCH;
 1085                         goto fail;
 1086                 }
 1087                 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
 1088                 sigio->sio_proc = proc;
 1089                 PROC_UNLOCK(proc);
 1090         } else {
 1091                 PGRP_LOCK(pgrp);
 1092                 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
 1093                 sigio->sio_pgrp = pgrp;
 1094                 PGRP_UNLOCK(pgrp);
 1095         }
 1096         sx_sunlock(&proctree_lock);
 1097         SIGIO_LOCK();
 1098         *sigiop = sigio;
 1099         SIGIO_UNLOCK();
 1100         return (0);
 1101 
 1102 fail:
 1103         sx_sunlock(&proctree_lock);
 1104         crfree(sigio->sio_ucred);
 1105         free(sigio, M_SIGIO);
 1106         return (ret);
 1107 }
 1108 
 1109 /*
 1110  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
 1111  */
 1112 pid_t
 1113 fgetown(sigiop)
 1114         struct sigio **sigiop;
 1115 {
 1116         pid_t pgid;
 1117 
 1118         SIGIO_LOCK();
 1119         pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
 1120         SIGIO_UNLOCK();
 1121         return (pgid);
 1122 }
 1123 
 1124 /*
 1125  * Close a file descriptor.
 1126  */
 1127 #ifndef _SYS_SYSPROTO_H_
 1128 struct close_args {
 1129         int     fd;
 1130 };
 1131 #endif
 1132 /* ARGSUSED */
 1133 int
 1134 close(td, uap)
 1135         struct thread *td;
 1136         struct close_args *uap;
 1137 {
 1138 
 1139         return (kern_close(td, uap->fd));
 1140 }
 1141 
 1142 int
 1143 kern_close(td, fd)
 1144         struct thread *td;
 1145         int fd;
 1146 {
 1147         struct filedesc *fdp;
 1148         struct file *fp;
 1149         int error;
 1150         int holdleaders;
 1151 
 1152         error = 0;
 1153         holdleaders = 0;
 1154         fdp = td->td_proc->p_fd;
 1155 
 1156         AUDIT_SYSCLOSE(td, fd);
 1157 
 1158         FILEDESC_XLOCK(fdp);
 1159         if ((unsigned)fd >= fdp->fd_nfiles ||
 1160             (fp = fdp->fd_ofiles[fd]) == NULL) {
 1161                 FILEDESC_XUNLOCK(fdp);
 1162                 return (EBADF);
 1163         }
 1164         fdp->fd_ofiles[fd] = NULL;
 1165         fdp->fd_ofileflags[fd] = 0;
 1166         fdunused(fdp, fd);
 1167         if (td->td_proc->p_fdtol != NULL) {
 1168                 /*
 1169                  * Ask fdfree() to sleep to ensure that all relevant
 1170                  * process leaders can be traversed in closef().
 1171                  */
 1172                 fdp->fd_holdleaderscount++;
 1173                 holdleaders = 1;
 1174         }
 1175 
 1176         /*
 1177          * We now hold the fp reference that used to be owned by the
 1178          * descriptor array.  We have to unlock the FILEDESC *AFTER*
 1179          * knote_fdclose to prevent a race of the fd getting opened, a knote
 1180          * added, and deleteing a knote for the new fd.
 1181          */
 1182         knote_fdclose(td, fd);
 1183         if (fp->f_type == DTYPE_MQUEUE)
 1184                 mq_fdclose(td, fd, fp);
 1185         FILEDESC_XUNLOCK(fdp);
 1186 
 1187         error = closef(fp, td);
 1188         if (holdleaders) {
 1189                 FILEDESC_XLOCK(fdp);
 1190                 fdp->fd_holdleaderscount--;
 1191                 if (fdp->fd_holdleaderscount == 0 &&
 1192                     fdp->fd_holdleaderswakeup != 0) {
 1193                         fdp->fd_holdleaderswakeup = 0;
 1194                         wakeup(&fdp->fd_holdleaderscount);
 1195                 }
 1196                 FILEDESC_XUNLOCK(fdp);
 1197         }
 1198         return (error);
 1199 }
 1200 
 1201 /*
 1202  * Close open file descriptors.
 1203  */
 1204 #ifndef _SYS_SYSPROTO_H_
 1205 struct closefrom_args {
 1206         int     lowfd;
 1207 };
 1208 #endif
 1209 /* ARGSUSED */
 1210 int
 1211 closefrom(struct thread *td, struct closefrom_args *uap)
 1212 {
 1213         struct filedesc *fdp;
 1214         int fd;
 1215 
 1216         fdp = td->td_proc->p_fd;
 1217         AUDIT_ARG_FD(uap->lowfd);
 1218 
 1219         /*
 1220          * Treat negative starting file descriptor values identical to
 1221          * closefrom(0) which closes all files.
 1222          */
 1223         if (uap->lowfd < 0)
 1224                 uap->lowfd = 0;
 1225         FILEDESC_SLOCK(fdp);
 1226         for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
 1227                 if (fdp->fd_ofiles[fd] != NULL) {
 1228                         FILEDESC_SUNLOCK(fdp);
 1229                         (void)kern_close(td, fd);
 1230                         FILEDESC_SLOCK(fdp);
 1231                 }
 1232         }
 1233         FILEDESC_SUNLOCK(fdp);
 1234         return (0);
 1235 }
 1236 
 1237 #if defined(COMPAT_43)
 1238 /*
 1239  * Return status information about a file descriptor.
 1240  */
 1241 #ifndef _SYS_SYSPROTO_H_
 1242 struct ofstat_args {
 1243         int     fd;
 1244         struct  ostat *sb;
 1245 };
 1246 #endif
 1247 /* ARGSUSED */
 1248 int
 1249 ofstat(struct thread *td, struct ofstat_args *uap)
 1250 {
 1251         struct ostat oub;
 1252         struct stat ub;
 1253         int error;
 1254 
 1255         error = kern_fstat(td, uap->fd, &ub);
 1256         if (error == 0) {
 1257                 cvtstat(&ub, &oub);
 1258                 error = copyout(&oub, uap->sb, sizeof(oub));
 1259         }
 1260         return (error);
 1261 }
 1262 #endif /* COMPAT_43 */
 1263 
 1264 /*
 1265  * Return status information about a file descriptor.
 1266  */
 1267 #ifndef _SYS_SYSPROTO_H_
 1268 struct fstat_args {
 1269         int     fd;
 1270         struct  stat *sb;
 1271 };
 1272 #endif
 1273 /* ARGSUSED */
 1274 int
 1275 fstat(struct thread *td, struct fstat_args *uap)
 1276 {
 1277         struct stat ub;
 1278         int error;
 1279 
 1280         error = kern_fstat(td, uap->fd, &ub);
 1281         if (error == 0)
 1282                 error = copyout(&ub, uap->sb, sizeof(ub));
 1283         return (error);
 1284 }
 1285 
 1286 int
 1287 kern_fstat(struct thread *td, int fd, struct stat *sbp)
 1288 {
 1289         struct file *fp;
 1290         int error;
 1291 
 1292         AUDIT_ARG_FD(fd);
 1293 
 1294         if ((error = fget(td, fd, &fp)) != 0)
 1295                 return (error);
 1296 
 1297         AUDIT_ARG_FILE(td->td_proc, fp);
 1298 
 1299         error = fo_stat(fp, sbp, td->td_ucred, td);
 1300         fdrop(fp, td);
 1301 #ifdef KTRACE
 1302         if (error == 0 && KTRPOINT(td, KTR_STRUCT))
 1303                 ktrstat(sbp);
 1304 #endif
 1305         return (error);
 1306 }
 1307 
 1308 /*
 1309  * Return status information about a file descriptor.
 1310  */
 1311 #ifndef _SYS_SYSPROTO_H_
 1312 struct nfstat_args {
 1313         int     fd;
 1314         struct  nstat *sb;
 1315 };
 1316 #endif
 1317 /* ARGSUSED */
 1318 int
 1319 nfstat(struct thread *td, struct nfstat_args *uap)
 1320 {
 1321         struct nstat nub;
 1322         struct stat ub;
 1323         int error;
 1324 
 1325         error = kern_fstat(td, uap->fd, &ub);
 1326         if (error == 0) {
 1327                 cvtnstat(&ub, &nub);
 1328                 error = copyout(&nub, uap->sb, sizeof(nub));
 1329         }
 1330         return (error);
 1331 }
 1332 
 1333 /*
 1334  * Return pathconf information about a file descriptor.
 1335  */
 1336 #ifndef _SYS_SYSPROTO_H_
 1337 struct fpathconf_args {
 1338         int     fd;
 1339         int     name;
 1340 };
 1341 #endif
 1342 /* ARGSUSED */
 1343 int
 1344 fpathconf(struct thread *td, struct fpathconf_args *uap)
 1345 {
 1346         struct file *fp;
 1347         struct vnode *vp;
 1348         int error;
 1349 
 1350         if ((error = fget(td, uap->fd, &fp)) != 0)
 1351                 return (error);
 1352 
 1353         /* If asynchronous I/O is available, it works for all descriptors. */
 1354         if (uap->name == _PC_ASYNC_IO) {
 1355                 td->td_retval[0] = async_io_version;
 1356                 goto out;
 1357         }
 1358         vp = fp->f_vnode;
 1359         if (vp != NULL) {
 1360                 int vfslocked;
 1361                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 1362                 vn_lock(vp, LK_SHARED | LK_RETRY);
 1363                 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
 1364                 VOP_UNLOCK(vp, 0);
 1365                 VFS_UNLOCK_GIANT(vfslocked);
 1366         } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
 1367                 if (uap->name != _PC_PIPE_BUF) {
 1368                         error = EINVAL;
 1369                 } else {
 1370                         td->td_retval[0] = PIPE_BUF;
 1371                 error = 0;
 1372                 }
 1373         } else {
 1374                 error = EOPNOTSUPP;
 1375         }
 1376 out:
 1377         fdrop(fp, td);
 1378         return (error);
 1379 }
 1380 
 1381 /*
 1382  * Grow the file table to accomodate (at least) nfd descriptors.  This may
 1383  * block and drop the filedesc lock, but it will reacquire it before
 1384  * returning.
 1385  */
 1386 static void
 1387 fdgrowtable(struct filedesc *fdp, int nfd)
 1388 {
 1389         struct filedesc0 *fdp0;
 1390         struct freetable *fo;
 1391         struct file **ntable;
 1392         struct file **otable;
 1393         char *nfileflags;
 1394         int nnfiles, onfiles;
 1395         NDSLOTTYPE *nmap;
 1396 
 1397         FILEDESC_XLOCK_ASSERT(fdp);
 1398 
 1399         KASSERT(fdp->fd_nfiles > 0,
 1400             ("zero-length file table"));
 1401 
 1402         /* compute the size of the new table */
 1403         onfiles = fdp->fd_nfiles;
 1404         nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
 1405         if (nnfiles <= onfiles)
 1406                 /* the table is already large enough */
 1407                 return;
 1408 
 1409         /* allocate a new table and (if required) new bitmaps */
 1410         FILEDESC_XUNLOCK(fdp);
 1411         ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
 1412             M_FILEDESC, M_ZERO | M_WAITOK);
 1413         nfileflags = (char *)&ntable[nnfiles];
 1414         if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
 1415                 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
 1416                     M_FILEDESC, M_ZERO | M_WAITOK);
 1417         else
 1418                 nmap = NULL;
 1419         FILEDESC_XLOCK(fdp);
 1420 
 1421         /*
 1422          * We now have new tables ready to go.  Since we dropped the
 1423          * filedesc lock to call malloc(), watch out for a race.
 1424          */
 1425         onfiles = fdp->fd_nfiles;
 1426         if (onfiles >= nnfiles) {
 1427                 /* we lost the race, but that's OK */
 1428                 free(ntable, M_FILEDESC);
 1429                 if (nmap != NULL)
 1430                         free(nmap, M_FILEDESC);
 1431                 return;
 1432         }
 1433         bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
 1434         bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
 1435         otable = fdp->fd_ofiles;
 1436         fdp->fd_ofileflags = nfileflags;
 1437         fdp->fd_ofiles = ntable;
 1438         /*
 1439          * We must preserve ofiles until the process exits because we can't
 1440          * be certain that no threads have references to the old table via
 1441          * _fget().
 1442          */
 1443         if (onfiles > NDFILE) {
 1444                 fo = (struct freetable *)&otable[onfiles];
 1445                 fdp0 = (struct filedesc0 *)fdp;
 1446                 fo->ft_table = otable;
 1447                 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
 1448         }
 1449         if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
 1450                 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
 1451                 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
 1452                         free(fdp->fd_map, M_FILEDESC);
 1453                 fdp->fd_map = nmap;
 1454         }
 1455         fdp->fd_nfiles = nnfiles;
 1456 }
 1457 
 1458 /*
 1459  * Allocate a file descriptor for the process.
 1460  */
 1461 int
 1462 fdalloc(struct thread *td, int minfd, int *result)
 1463 {
 1464         struct proc *p = td->td_proc;
 1465         struct filedesc *fdp = p->p_fd;
 1466         int fd = -1, maxfd;
 1467 
 1468         FILEDESC_XLOCK_ASSERT(fdp);
 1469 
 1470         if (fdp->fd_freefile > minfd)
 1471                 minfd = fdp->fd_freefile;          
 1472 
 1473         PROC_LOCK(p);
 1474         maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
 1475         PROC_UNLOCK(p);
 1476 
 1477         /*
 1478          * Search the bitmap for a free descriptor.  If none is found, try
 1479          * to grow the file table.  Keep at it until we either get a file
 1480          * descriptor or run into process or system limits; fdgrowtable()
 1481          * may drop the filedesc lock, so we're in a race.
 1482          */
 1483         for (;;) {
 1484                 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
 1485                 if (fd >= maxfd)
 1486                         return (EMFILE);
 1487                 if (fd < fdp->fd_nfiles)
 1488                         break;
 1489                 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
 1490         }
 1491 
 1492         /*
 1493          * Perform some sanity checks, then mark the file descriptor as
 1494          * used and return it to the caller.
 1495          */
 1496         KASSERT(!fdisused(fdp, fd),
 1497             ("fd_first_free() returned non-free descriptor"));
 1498         KASSERT(fdp->fd_ofiles[fd] == NULL,
 1499             ("free descriptor isn't"));
 1500         fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
 1501         fdused(fdp, fd);
 1502         *result = fd;
 1503         return (0);
 1504 }
 1505 
 1506 /*
 1507  * Check to see whether n user file descriptors are available to the process
 1508  * p.
 1509  */
 1510 int
 1511 fdavail(struct thread *td, int n)
 1512 {
 1513         struct proc *p = td->td_proc;
 1514         struct filedesc *fdp = td->td_proc->p_fd;
 1515         struct file **fpp;
 1516         int i, lim, last;
 1517 
 1518         FILEDESC_LOCK_ASSERT(fdp);
 1519 
 1520         PROC_LOCK(p);
 1521         lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
 1522         PROC_UNLOCK(p);
 1523         if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
 1524                 return (1);
 1525         last = min(fdp->fd_nfiles, lim);
 1526         fpp = &fdp->fd_ofiles[fdp->fd_freefile];
 1527         for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
 1528                 if (*fpp == NULL && --n <= 0)
 1529                         return (1);
 1530         }
 1531         return (0);
 1532 }
 1533 
 1534 /*
 1535  * Create a new open file structure and allocate a file decriptor for the
 1536  * process that refers to it.  We add one reference to the file for the
 1537  * descriptor table and one reference for resultfp. This is to prevent us
 1538  * being preempted and the entry in the descriptor table closed after we
 1539  * release the FILEDESC lock.
 1540  */
 1541 int
 1542 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
 1543 {
 1544         struct proc *p = td->td_proc;
 1545         struct file *fp;
 1546         int error, i;
 1547         int maxuserfiles = maxfiles - (maxfiles / 20);
 1548         static struct timeval lastfail;
 1549         static int curfail;
 1550 
 1551         fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
 1552         if ((openfiles >= maxuserfiles &&
 1553             priv_check(td, PRIV_MAXFILES) != 0) ||
 1554             openfiles >= maxfiles) {
 1555                 if (ppsratecheck(&lastfail, &curfail, 1)) {
 1556                         printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
 1557                                 td->td_ucred->cr_ruid);
 1558                 }
 1559                 uma_zfree(file_zone, fp);
 1560                 return (ENFILE);
 1561         }
 1562         atomic_add_int(&openfiles, 1);
 1563 
 1564         /*
 1565          * If the process has file descriptor zero open, add the new file
 1566          * descriptor to the list of open files at that point, otherwise
 1567          * put it at the front of the list of open files.
 1568          */
 1569         refcount_init(&fp->f_count, 1);
 1570         if (resultfp)
 1571                 fhold(fp);
 1572         fp->f_cred = crhold(td->td_ucred);
 1573         fp->f_ops = &badfileops;
 1574         fp->f_data = NULL;
 1575         fp->f_vnode = NULL;
 1576         FILEDESC_XLOCK(p->p_fd);
 1577         if ((error = fdalloc(td, 0, &i))) {
 1578                 FILEDESC_XUNLOCK(p->p_fd);
 1579                 fdrop(fp, td);
 1580                 if (resultfp)
 1581                         fdrop(fp, td);
 1582                 return (error);
 1583         }
 1584         p->p_fd->fd_ofiles[i] = fp;
 1585         if ((flags & O_CLOEXEC) != 0)
 1586                 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
 1587         FILEDESC_XUNLOCK(p->p_fd);
 1588         if (resultfp)
 1589                 *resultfp = fp;
 1590         if (resultfd)
 1591                 *resultfd = i;
 1592         return (0);
 1593 }
 1594 
 1595 int
 1596 falloc(struct thread *td, struct file **resultfp, int *resultfd)
 1597 {
 1598 
 1599         return (fallocf(td, resultfp, resultfd, 0));
 1600 }
 1601 
 1602 /*
 1603  * Build a new filedesc structure from another.
 1604  * Copy the current, root, and jail root vnode references.
 1605  */
 1606 struct filedesc *
 1607 fdinit(struct filedesc *fdp)
 1608 {
 1609         struct filedesc0 *newfdp;
 1610 
 1611         newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
 1612         FILEDESC_LOCK_INIT(&newfdp->fd_fd);
 1613         if (fdp != NULL) {
 1614                 FILEDESC_XLOCK(fdp);
 1615                 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
 1616                 if (newfdp->fd_fd.fd_cdir)
 1617                         VREF(newfdp->fd_fd.fd_cdir);
 1618                 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
 1619                 if (newfdp->fd_fd.fd_rdir)
 1620                         VREF(newfdp->fd_fd.fd_rdir);
 1621                 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
 1622                 if (newfdp->fd_fd.fd_jdir)
 1623                         VREF(newfdp->fd_fd.fd_jdir);
 1624                 FILEDESC_XUNLOCK(fdp);
 1625         }
 1626 
 1627         /* Create the file descriptor table. */
 1628         newfdp->fd_fd.fd_refcnt = 1;
 1629         newfdp->fd_fd.fd_holdcnt = 1;
 1630         newfdp->fd_fd.fd_cmask = CMASK;
 1631         newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
 1632         newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
 1633         newfdp->fd_fd.fd_nfiles = NDFILE;
 1634         newfdp->fd_fd.fd_map = newfdp->fd_dmap;
 1635         newfdp->fd_fd.fd_lastfile = -1;
 1636         return (&newfdp->fd_fd);
 1637 }
 1638 
 1639 static struct filedesc *
 1640 fdhold(struct proc *p)
 1641 {
 1642         struct filedesc *fdp;
 1643 
 1644         mtx_lock(&fdesc_mtx);
 1645         fdp = p->p_fd;
 1646         if (fdp != NULL)
 1647                 fdp->fd_holdcnt++;
 1648         mtx_unlock(&fdesc_mtx);
 1649         return (fdp);
 1650 }
 1651 
 1652 static void
 1653 fddrop(struct filedesc *fdp)
 1654 {
 1655         struct filedesc0 *fdp0;
 1656         struct freetable *ft;
 1657         int i;
 1658 
 1659         mtx_lock(&fdesc_mtx);
 1660         i = --fdp->fd_holdcnt;
 1661         mtx_unlock(&fdesc_mtx);
 1662         if (i > 0)
 1663                 return;
 1664 
 1665         FILEDESC_LOCK_DESTROY(fdp);
 1666         fdp0 = (struct filedesc0 *)fdp;
 1667         while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
 1668                 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
 1669                 free(ft->ft_table, M_FILEDESC);
 1670         }
 1671         free(fdp, M_FILEDESC);
 1672 }
 1673 
 1674 /*
 1675  * Share a filedesc structure.
 1676  */
 1677 struct filedesc *
 1678 fdshare(struct filedesc *fdp)
 1679 {
 1680 
 1681         FILEDESC_XLOCK(fdp);
 1682         fdp->fd_refcnt++;
 1683         FILEDESC_XUNLOCK(fdp);
 1684         return (fdp);
 1685 }
 1686 
 1687 /*
 1688  * Unshare a filedesc structure, if necessary by making a copy
 1689  */
 1690 void
 1691 fdunshare(struct proc *p, struct thread *td)
 1692 {
 1693 
 1694         FILEDESC_XLOCK(p->p_fd);
 1695         if (p->p_fd->fd_refcnt > 1) {
 1696                 struct filedesc *tmp;
 1697 
 1698                 FILEDESC_XUNLOCK(p->p_fd);
 1699                 tmp = fdcopy(p->p_fd);
 1700                 fdfree(td);
 1701                 p->p_fd = tmp;
 1702         } else
 1703                 FILEDESC_XUNLOCK(p->p_fd);
 1704 }
 1705 
 1706 /*
 1707  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
 1708  * this is to ease callers, not catch errors.
 1709  */
 1710 struct filedesc *
 1711 fdcopy(struct filedesc *fdp)
 1712 {
 1713         struct filedesc *newfdp;
 1714         int i;
 1715 
 1716         /* Certain daemons might not have file descriptors. */
 1717         if (fdp == NULL)
 1718                 return (NULL);
 1719 
 1720         newfdp = fdinit(fdp);
 1721         FILEDESC_SLOCK(fdp);
 1722         while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
 1723                 FILEDESC_SUNLOCK(fdp);
 1724                 FILEDESC_XLOCK(newfdp);
 1725                 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
 1726                 FILEDESC_XUNLOCK(newfdp);
 1727                 FILEDESC_SLOCK(fdp);
 1728         }
 1729         /* copy everything except kqueue descriptors */
 1730         newfdp->fd_freefile = -1;
 1731         for (i = 0; i <= fdp->fd_lastfile; ++i) {
 1732                 if (fdisused(fdp, i) &&
 1733                     fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
 1734                     fdp->fd_ofiles[i]->f_ops != &badfileops) {
 1735                         newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
 1736                         newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
 1737                         fhold(newfdp->fd_ofiles[i]);
 1738                         newfdp->fd_lastfile = i;
 1739                 } else {
 1740                         if (newfdp->fd_freefile == -1)
 1741                                 newfdp->fd_freefile = i;
 1742                 }
 1743         }
 1744         newfdp->fd_cmask = fdp->fd_cmask;
 1745         FILEDESC_SUNLOCK(fdp);
 1746         FILEDESC_XLOCK(newfdp);
 1747         for (i = 0; i <= newfdp->fd_lastfile; ++i)
 1748                 if (newfdp->fd_ofiles[i] != NULL)
 1749                         fdused(newfdp, i);
 1750         if (newfdp->fd_freefile == -1)
 1751                 newfdp->fd_freefile = i;
 1752         FILEDESC_XUNLOCK(newfdp);
 1753         return (newfdp);
 1754 }
 1755 
 1756 /*
 1757  * Release a filedesc structure.
 1758  */
 1759 void
 1760 fdfree(struct thread *td)
 1761 {
 1762         struct filedesc *fdp;
 1763         struct file **fpp;
 1764         int i, locked;
 1765         struct filedesc_to_leader *fdtol;
 1766         struct file *fp;
 1767         struct vnode *cdir, *jdir, *rdir, *vp;
 1768         struct flock lf;
 1769 
 1770         /* Certain daemons might not have file descriptors. */
 1771         fdp = td->td_proc->p_fd;
 1772         if (fdp == NULL)
 1773                 return;
 1774 
 1775         /* Check for special need to clear POSIX style locks */
 1776         fdtol = td->td_proc->p_fdtol;
 1777         if (fdtol != NULL) {
 1778                 FILEDESC_XLOCK(fdp);
 1779                 KASSERT(fdtol->fdl_refcount > 0,
 1780                         ("filedesc_to_refcount botch: fdl_refcount=%d",
 1781                          fdtol->fdl_refcount));
 1782                 if (fdtol->fdl_refcount == 1 &&
 1783                     (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1784                         for (i = 0, fpp = fdp->fd_ofiles;
 1785                              i <= fdp->fd_lastfile;
 1786                              i++, fpp++) {
 1787                                 if (*fpp == NULL ||
 1788                                     (*fpp)->f_type != DTYPE_VNODE)
 1789                                         continue;
 1790                                 fp = *fpp;
 1791                                 fhold(fp);
 1792                                 FILEDESC_XUNLOCK(fdp);
 1793                                 lf.l_whence = SEEK_SET;
 1794                                 lf.l_start = 0;
 1795                                 lf.l_len = 0;
 1796                                 lf.l_type = F_UNLCK;
 1797                                 vp = fp->f_vnode;
 1798                                 locked = VFS_LOCK_GIANT(vp->v_mount);
 1799                                 (void) VOP_ADVLOCK(vp,
 1800                                                    (caddr_t)td->td_proc->
 1801                                                    p_leader,
 1802                                                    F_UNLCK,
 1803                                                    &lf,
 1804                                                    F_POSIX);
 1805                                 VFS_UNLOCK_GIANT(locked);
 1806                                 FILEDESC_XLOCK(fdp);
 1807                                 fdrop(fp, td);
 1808                                 fpp = fdp->fd_ofiles + i;
 1809                         }
 1810                 }
 1811         retry:
 1812                 if (fdtol->fdl_refcount == 1) {
 1813                         if (fdp->fd_holdleaderscount > 0 &&
 1814                             (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1815                                 /*
 1816                                  * close() or do_dup() has cleared a reference
 1817                                  * in a shared file descriptor table.
 1818                                  */
 1819                                 fdp->fd_holdleaderswakeup = 1;
 1820                                 sx_sleep(&fdp->fd_holdleaderscount,
 1821                                     FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
 1822                                 goto retry;
 1823                         }
 1824                         if (fdtol->fdl_holdcount > 0) {
 1825                                 /*
 1826                                  * Ensure that fdtol->fdl_leader remains
 1827                                  * valid in closef().
 1828                                  */
 1829                                 fdtol->fdl_wakeup = 1;
 1830                                 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
 1831                                     "fdlhold", 0);
 1832                                 goto retry;
 1833                         }
 1834                 }
 1835                 fdtol->fdl_refcount--;
 1836                 if (fdtol->fdl_refcount == 0 &&
 1837                     fdtol->fdl_holdcount == 0) {
 1838                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
 1839                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
 1840                 } else
 1841                         fdtol = NULL;
 1842                 td->td_proc->p_fdtol = NULL;
 1843                 FILEDESC_XUNLOCK(fdp);
 1844                 if (fdtol != NULL)
 1845                         free(fdtol, M_FILEDESC_TO_LEADER);
 1846         }
 1847         FILEDESC_XLOCK(fdp);
 1848         i = --fdp->fd_refcnt;
 1849         FILEDESC_XUNLOCK(fdp);
 1850         if (i > 0)
 1851                 return;
 1852 
 1853         fpp = fdp->fd_ofiles;
 1854         for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
 1855                 if (*fpp) {
 1856                         FILEDESC_XLOCK(fdp);
 1857                         fp = *fpp;
 1858                         *fpp = NULL;
 1859                         FILEDESC_XUNLOCK(fdp);
 1860                         (void) closef(fp, td);
 1861                 }
 1862         }
 1863         FILEDESC_XLOCK(fdp);
 1864 
 1865         /* XXX This should happen earlier. */
 1866         mtx_lock(&fdesc_mtx);
 1867         td->td_proc->p_fd = NULL;
 1868         mtx_unlock(&fdesc_mtx);
 1869 
 1870         if (fdp->fd_nfiles > NDFILE)
 1871                 free(fdp->fd_ofiles, M_FILEDESC);
 1872         if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
 1873                 free(fdp->fd_map, M_FILEDESC);
 1874 
 1875         fdp->fd_nfiles = 0;
 1876 
 1877         cdir = fdp->fd_cdir;
 1878         fdp->fd_cdir = NULL;
 1879         rdir = fdp->fd_rdir;
 1880         fdp->fd_rdir = NULL;
 1881         jdir = fdp->fd_jdir;
 1882         fdp->fd_jdir = NULL;
 1883         FILEDESC_XUNLOCK(fdp);
 1884 
 1885         if (cdir) {
 1886                 locked = VFS_LOCK_GIANT(cdir->v_mount);
 1887                 vrele(cdir);
 1888                 VFS_UNLOCK_GIANT(locked);
 1889         }
 1890         if (rdir) {
 1891                 locked = VFS_LOCK_GIANT(rdir->v_mount);
 1892                 vrele(rdir);
 1893                 VFS_UNLOCK_GIANT(locked);
 1894         }
 1895         if (jdir) {
 1896                 locked = VFS_LOCK_GIANT(jdir->v_mount);
 1897                 vrele(jdir);
 1898                 VFS_UNLOCK_GIANT(locked);
 1899         }
 1900 
 1901         fddrop(fdp);
 1902 }
 1903 
 1904 /*
 1905  * For setugid programs, we don't want to people to use that setugidness
 1906  * to generate error messages which write to a file which otherwise would
 1907  * otherwise be off-limits to the process.  We check for filesystems where
 1908  * the vnode can change out from under us after execve (like [lin]procfs).
 1909  *
 1910  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
 1911  * sufficient.  We also don't check for setugidness since we know we are.
 1912  */
 1913 static int
 1914 is_unsafe(struct file *fp)
 1915 {
 1916         if (fp->f_type == DTYPE_VNODE) {
 1917                 struct vnode *vp = fp->f_vnode;
 1918 
 1919                 if ((vp->v_vflag & VV_PROCDEP) != 0)
 1920                         return (1);
 1921         }
 1922         return (0);
 1923 }
 1924 
 1925 /*
 1926  * Make this setguid thing safe, if at all possible.
 1927  */
 1928 void
 1929 setugidsafety(struct thread *td)
 1930 {
 1931         struct filedesc *fdp;
 1932         int i;
 1933 
 1934         /* Certain daemons might not have file descriptors. */
 1935         fdp = td->td_proc->p_fd;
 1936         if (fdp == NULL)
 1937                 return;
 1938 
 1939         /*
 1940          * Note: fdp->fd_ofiles may be reallocated out from under us while
 1941          * we are blocked in a close.  Be careful!
 1942          */
 1943         FILEDESC_XLOCK(fdp);
 1944         for (i = 0; i <= fdp->fd_lastfile; i++) {
 1945                 if (i > 2)
 1946                         break;
 1947                 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
 1948                         struct file *fp;
 1949 
 1950                         knote_fdclose(td, i);
 1951                         /*
 1952                          * NULL-out descriptor prior to close to avoid
 1953                          * a race while close blocks.
 1954                          */
 1955                         fp = fdp->fd_ofiles[i];
 1956                         fdp->fd_ofiles[i] = NULL;
 1957                         fdp->fd_ofileflags[i] = 0;
 1958                         fdunused(fdp, i);
 1959                         FILEDESC_XUNLOCK(fdp);
 1960                         (void) closef(fp, td);
 1961                         FILEDESC_XLOCK(fdp);
 1962                 }
 1963         }
 1964         FILEDESC_XUNLOCK(fdp);
 1965 }
 1966 
 1967 /*
 1968  * If a specific file object occupies a specific file descriptor, close the
 1969  * file descriptor entry and drop a reference on the file object.  This is a
 1970  * convenience function to handle a subsequent error in a function that calls
 1971  * falloc() that handles the race that another thread might have closed the
 1972  * file descriptor out from under the thread creating the file object.
 1973  */
 1974 void
 1975 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
 1976 {
 1977 
 1978         FILEDESC_XLOCK(fdp);
 1979         if (fdp->fd_ofiles[idx] == fp) {
 1980                 fdp->fd_ofiles[idx] = NULL;
 1981                 fdunused(fdp, idx);
 1982                 FILEDESC_XUNLOCK(fdp);
 1983                 fdrop(fp, td);
 1984         } else
 1985                 FILEDESC_XUNLOCK(fdp);
 1986 }
 1987 
 1988 /*
 1989  * Close any files on exec?
 1990  */
 1991 void
 1992 fdcloseexec(struct thread *td)
 1993 {
 1994         struct filedesc *fdp;
 1995         int i;
 1996 
 1997         /* Certain daemons might not have file descriptors. */
 1998         fdp = td->td_proc->p_fd;
 1999         if (fdp == NULL)
 2000                 return;
 2001 
 2002         FILEDESC_XLOCK(fdp);
 2003 
 2004         /*
 2005          * We cannot cache fd_ofiles or fd_ofileflags since operations
 2006          * may block and rip them out from under us.
 2007          */
 2008         for (i = 0; i <= fdp->fd_lastfile; i++) {
 2009                 if (fdp->fd_ofiles[i] != NULL &&
 2010                     (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
 2011                     (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
 2012                         struct file *fp;
 2013 
 2014                         knote_fdclose(td, i);
 2015                         /*
 2016                          * NULL-out descriptor prior to close to avoid
 2017                          * a race while close blocks.
 2018                          */
 2019                         fp = fdp->fd_ofiles[i];
 2020                         fdp->fd_ofiles[i] = NULL;
 2021                         fdp->fd_ofileflags[i] = 0;
 2022                         fdunused(fdp, i);
 2023                         if (fp->f_type == DTYPE_MQUEUE)
 2024                                 mq_fdclose(td, i, fp);
 2025                         FILEDESC_XUNLOCK(fdp);
 2026                         (void) closef(fp, td);
 2027                         FILEDESC_XLOCK(fdp);
 2028                 }
 2029         }
 2030         FILEDESC_XUNLOCK(fdp);
 2031 }
 2032 
 2033 /*
 2034  * It is unsafe for set[ug]id processes to be started with file
 2035  * descriptors 0..2 closed, as these descriptors are given implicit
 2036  * significance in the Standard C library.  fdcheckstd() will create a
 2037  * descriptor referencing /dev/null for each of stdin, stdout, and
 2038  * stderr that is not already open.
 2039  */
 2040 int
 2041 fdcheckstd(struct thread *td)
 2042 {
 2043         struct filedesc *fdp;
 2044         register_t retval, save;
 2045         int i, error, devnull;
 2046 
 2047         fdp = td->td_proc->p_fd;
 2048         if (fdp == NULL)
 2049                 return (0);
 2050         KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
 2051         devnull = -1;
 2052         error = 0;
 2053         for (i = 0; i < 3; i++) {
 2054                 if (fdp->fd_ofiles[i] != NULL)
 2055                         continue;
 2056                 if (devnull < 0) {
 2057                         save = td->td_retval[0];
 2058                         error = kern_open(td, "/dev/null", UIO_SYSSPACE,
 2059                             O_RDWR, 0);
 2060                         devnull = td->td_retval[0];
 2061                         td->td_retval[0] = save;
 2062                         if (error)
 2063                                 break;
 2064                         KASSERT(devnull == i, ("oof, we didn't get our fd"));
 2065                 } else {
 2066                         error = do_dup(td, DUP_FIXED, devnull, i, &retval);
 2067                         if (error != 0)
 2068                                 break;
 2069                 }
 2070         }
 2071         return (error);
 2072 }
 2073 
 2074 /*
 2075  * Internal form of close.  Decrement reference count on file structure.
 2076  * Note: td may be NULL when closing a file that was being passed in a
 2077  * message.
 2078  *
 2079  * XXXRW: Giant is not required for the caller, but often will be held; this
 2080  * makes it moderately likely the Giant will be recursed in the VFS case.
 2081  */
 2082 int
 2083 closef(struct file *fp, struct thread *td)
 2084 {
 2085         struct vnode *vp;
 2086         struct flock lf;
 2087         struct filedesc_to_leader *fdtol;
 2088         struct filedesc *fdp;
 2089 
 2090         /*
 2091          * POSIX record locking dictates that any close releases ALL
 2092          * locks owned by this process.  This is handled by setting
 2093          * a flag in the unlock to free ONLY locks obeying POSIX
 2094          * semantics, and not to free BSD-style file locks.
 2095          * If the descriptor was in a message, POSIX-style locks
 2096          * aren't passed with the descriptor, and the thread pointer
 2097          * will be NULL.  Callers should be careful only to pass a
 2098          * NULL thread pointer when there really is no owning
 2099          * context that might have locks, or the locks will be
 2100          * leaked.
 2101          */
 2102         if (fp->f_type == DTYPE_VNODE && td != NULL) {
 2103                 int vfslocked;
 2104 
 2105                 vp = fp->f_vnode;
 2106                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2107                 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 2108                         lf.l_whence = SEEK_SET;
 2109                         lf.l_start = 0;
 2110                         lf.l_len = 0;
 2111                         lf.l_type = F_UNLCK;
 2112                         (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
 2113                                            F_UNLCK, &lf, F_POSIX);
 2114                 }
 2115                 fdtol = td->td_proc->p_fdtol;
 2116                 if (fdtol != NULL) {
 2117                         /*
 2118                          * Handle special case where file descriptor table is
 2119                          * shared between multiple process leaders.
 2120                          */
 2121                         fdp = td->td_proc->p_fd;
 2122                         FILEDESC_XLOCK(fdp);
 2123                         for (fdtol = fdtol->fdl_next;
 2124                              fdtol != td->td_proc->p_fdtol;
 2125                              fdtol = fdtol->fdl_next) {
 2126                                 if ((fdtol->fdl_leader->p_flag &
 2127                                      P_ADVLOCK) == 0)
 2128                                         continue;
 2129                                 fdtol->fdl_holdcount++;
 2130                                 FILEDESC_XUNLOCK(fdp);
 2131                                 lf.l_whence = SEEK_SET;
 2132                                 lf.l_start = 0;
 2133                                 lf.l_len = 0;
 2134                                 lf.l_type = F_UNLCK;
 2135                                 vp = fp->f_vnode;
 2136                                 (void) VOP_ADVLOCK(vp,
 2137                                                    (caddr_t)fdtol->fdl_leader,
 2138                                                    F_UNLCK, &lf, F_POSIX);
 2139                                 FILEDESC_XLOCK(fdp);
 2140                                 fdtol->fdl_holdcount--;
 2141                                 if (fdtol->fdl_holdcount == 0 &&
 2142                                     fdtol->fdl_wakeup != 0) {
 2143                                         fdtol->fdl_wakeup = 0;
 2144                                         wakeup(fdtol);
 2145                                 }
 2146                         }
 2147                         FILEDESC_XUNLOCK(fdp);
 2148                 }
 2149                 VFS_UNLOCK_GIANT(vfslocked);
 2150         }
 2151         return (fdrop(fp, td));
 2152 }
 2153 
 2154 /*
 2155  * Initialize the file pointer with the specified properties.
 2156  * 
 2157  * The ops are set with release semantics to be certain that the flags, type,
 2158  * and data are visible when ops is.  This is to prevent ops methods from being
 2159  * called with bad data.
 2160  */
 2161 void
 2162 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
 2163 {
 2164         fp->f_data = data;
 2165         fp->f_flag = flag;
 2166         fp->f_type = type;
 2167         atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
 2168 }
 2169 
 2170 struct file *
 2171 fget_unlocked(struct filedesc *fdp, int fd)
 2172 {
 2173         struct file *fp;
 2174         u_int count;
 2175 
 2176         if (fd < 0 || fd >= fdp->fd_nfiles)
 2177                 return (NULL);
 2178         /*
 2179          * Fetch the descriptor locklessly.  We avoid fdrop() races by
 2180          * never raising a refcount above 0.  To accomplish this we have
 2181          * to use a cmpset loop rather than an atomic_add.  The descriptor
 2182          * must be re-verified once we acquire a reference to be certain
 2183          * that the identity is still correct and we did not lose a race
 2184          * due to preemption.
 2185          */
 2186         for (;;) {
 2187                 fp = fdp->fd_ofiles[fd];
 2188                 if (fp == NULL)
 2189                         break;
 2190                 count = fp->f_count;
 2191                 if (count == 0)
 2192                         continue;
 2193                 /*
 2194                  * Use an acquire barrier to prevent caching of fd_ofiles
 2195                  * so it is refreshed for verification.
 2196                  */
 2197                 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
 2198                         continue;
 2199                 if (fp == fdp->fd_ofiles[fd])
 2200                         break;
 2201                 fdrop(fp, curthread);
 2202         }
 2203 
 2204         return (fp);
 2205 }
 2206 
 2207 /*
 2208  * Extract the file pointer associated with the specified descriptor for the
 2209  * current user process.
 2210  *
 2211  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
 2212  * returned.
 2213  *
 2214  * If an error occured the non-zero error is returned and *fpp is set to
 2215  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
 2216  * responsible for fdrop().
 2217  */
 2218 static __inline int
 2219 _fget(struct thread *td, int fd, struct file **fpp, int flags)
 2220 {
 2221         struct filedesc *fdp;
 2222         struct file *fp;
 2223 
 2224         *fpp = NULL;
 2225         if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
 2226                 return (EBADF);
 2227         if ((fp = fget_unlocked(fdp, fd)) == NULL)
 2228                 return (EBADF);
 2229         if (fp->f_ops == &badfileops) {
 2230                 fdrop(fp, td);
 2231                 return (EBADF);
 2232         }
 2233         /*
 2234          * FREAD and FWRITE failure return EBADF as per POSIX.
 2235          *
 2236          * Only one flag, or 0, may be specified.
 2237          */
 2238         if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
 2239             (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
 2240                 fdrop(fp, td);
 2241                 return (EBADF);
 2242         }
 2243         *fpp = fp;
 2244         return (0);
 2245 }
 2246 
 2247 int
 2248 fget(struct thread *td, int fd, struct file **fpp)
 2249 {
 2250 
 2251         return(_fget(td, fd, fpp, 0));
 2252 }
 2253 
 2254 int
 2255 fget_read(struct thread *td, int fd, struct file **fpp)
 2256 {
 2257 
 2258         return(_fget(td, fd, fpp, FREAD));
 2259 }
 2260 
 2261 int
 2262 fget_write(struct thread *td, int fd, struct file **fpp)
 2263 {
 2264 
 2265         return(_fget(td, fd, fpp, FWRITE));
 2266 }
 2267 
 2268 /*
 2269  * Like fget() but loads the underlying vnode, or returns an error if the
 2270  * descriptor does not represent a vnode.  Note that pipes use vnodes but
 2271  * never have VM objects.  The returned vnode will be vref()'d.
 2272  *
 2273  * XXX: what about the unused flags ?
 2274  */
 2275 static __inline int
 2276 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
 2277 {
 2278         struct file *fp;
 2279         int error;
 2280 
 2281         *vpp = NULL;
 2282         if ((error = _fget(td, fd, &fp, flags)) != 0)
 2283                 return (error);
 2284         if (fp->f_vnode == NULL) {
 2285                 error = EINVAL;
 2286         } else {
 2287                 *vpp = fp->f_vnode;
 2288                 vref(*vpp);
 2289         }
 2290         fdrop(fp, td);
 2291 
 2292         return (error);
 2293 }
 2294 
 2295 int
 2296 fgetvp(struct thread *td, int fd, struct vnode **vpp)
 2297 {
 2298 
 2299         return (_fgetvp(td, fd, vpp, 0));
 2300 }
 2301 
 2302 int
 2303 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
 2304 {
 2305 
 2306         return (_fgetvp(td, fd, vpp, FREAD));
 2307 }
 2308 
 2309 #ifdef notyet
 2310 int
 2311 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
 2312 {
 2313 
 2314         return (_fgetvp(td, fd, vpp, FWRITE));
 2315 }
 2316 #endif
 2317 
 2318 /*
 2319  * Like fget() but loads the underlying socket, or returns an error if the
 2320  * descriptor does not represent a socket.
 2321  *
 2322  * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
 2323  * in the future.
 2324  *
 2325  * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
 2326  * on their file descriptor reference to prevent the socket from being free'd
 2327  * during use.
 2328  */
 2329 int
 2330 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
 2331 {
 2332         struct file *fp;
 2333         int error;
 2334 
 2335         *spp = NULL;
 2336         if (fflagp != NULL)
 2337                 *fflagp = 0;
 2338         if ((error = _fget(td, fd, &fp, 0)) != 0)
 2339                 return (error);
 2340         if (fp->f_type != DTYPE_SOCKET) {
 2341                 error = ENOTSOCK;
 2342         } else {
 2343                 *spp = fp->f_data;
 2344                 if (fflagp)
 2345                         *fflagp = fp->f_flag;
 2346                 SOCK_LOCK(*spp);
 2347                 soref(*spp);
 2348                 SOCK_UNLOCK(*spp);
 2349         }
 2350         fdrop(fp, td);
 2351 
 2352         return (error);
 2353 }
 2354 
 2355 /*
 2356  * Drop the reference count on the socket and XXX release the SX lock in the
 2357  * future.  The last reference closes the socket.
 2358  *
 2359  * Note: fputsock() is deprecated, see comment for fgetsock().
 2360  */
 2361 void
 2362 fputsock(struct socket *so)
 2363 {
 2364 
 2365         ACCEPT_LOCK();
 2366         SOCK_LOCK(so);
 2367         CURVNET_SET(so->so_vnet);
 2368         sorele(so);
 2369         CURVNET_RESTORE();
 2370 }
 2371 
 2372 /*
 2373  * Handle the last reference to a file being closed.
 2374  */
 2375 int
 2376 _fdrop(struct file *fp, struct thread *td)
 2377 {
 2378         int error;
 2379 
 2380         error = 0;
 2381         if (fp->f_count != 0)
 2382                 panic("fdrop: count %d", fp->f_count);
 2383         if (fp->f_ops != &badfileops)
 2384                 error = fo_close(fp, td);
 2385         atomic_subtract_int(&openfiles, 1);
 2386         crfree(fp->f_cred);
 2387         free(fp->f_advice, M_FADVISE);
 2388         uma_zfree(file_zone, fp);
 2389 
 2390         return (error);
 2391 }
 2392 
 2393 /*
 2394  * Apply an advisory lock on a file descriptor.
 2395  *
 2396  * Just attempt to get a record lock of the requested type on the entire file
 2397  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
 2398  */
 2399 #ifndef _SYS_SYSPROTO_H_
 2400 struct flock_args {
 2401         int     fd;
 2402         int     how;
 2403 };
 2404 #endif
 2405 /* ARGSUSED */
 2406 int
 2407 flock(struct thread *td, struct flock_args *uap)
 2408 {
 2409         struct file *fp;
 2410         struct vnode *vp;
 2411         struct flock lf;
 2412         int vfslocked;
 2413         int error;
 2414 
 2415         if ((error = fget(td, uap->fd, &fp)) != 0)
 2416                 return (error);
 2417         if (fp->f_type != DTYPE_VNODE) {
 2418                 fdrop(fp, td);
 2419                 return (EOPNOTSUPP);
 2420         }
 2421 
 2422         vp = fp->f_vnode;
 2423         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2424         lf.l_whence = SEEK_SET;
 2425         lf.l_start = 0;
 2426         lf.l_len = 0;
 2427         if (uap->how & LOCK_UN) {
 2428                 lf.l_type = F_UNLCK;
 2429                 atomic_clear_int(&fp->f_flag, FHASLOCK);
 2430                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
 2431                 goto done2;
 2432         }
 2433         if (uap->how & LOCK_EX)
 2434                 lf.l_type = F_WRLCK;
 2435         else if (uap->how & LOCK_SH)
 2436                 lf.l_type = F_RDLCK;
 2437         else {
 2438                 error = EBADF;
 2439                 goto done2;
 2440         }
 2441         atomic_set_int(&fp->f_flag, FHASLOCK);
 2442         error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
 2443             (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
 2444 done2:
 2445         fdrop(fp, td);
 2446         VFS_UNLOCK_GIANT(vfslocked);
 2447         return (error);
 2448 }
 2449 /*
 2450  * Duplicate the specified descriptor to a free descriptor.
 2451  */
 2452 int
 2453 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
 2454 {
 2455         struct file *wfp;
 2456         struct file *fp;
 2457 
 2458         /*
 2459          * If the to-be-dup'd fd number is greater than the allowed number
 2460          * of file descriptors, or the fd to be dup'd has already been
 2461          * closed, then reject.
 2462          */
 2463         FILEDESC_XLOCK(fdp);
 2464         if (dfd < 0 || dfd >= fdp->fd_nfiles ||
 2465             (wfp = fdp->fd_ofiles[dfd]) == NULL) {
 2466                 FILEDESC_XUNLOCK(fdp);
 2467                 return (EBADF);
 2468         }
 2469 
 2470         /*
 2471          * There are two cases of interest here.
 2472          *
 2473          * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
 2474          *
 2475          * For ENXIO steal away the file structure from (dfd) and store it in
 2476          * (indx).  (dfd) is effectively closed by this operation.
 2477          *
 2478          * Any other error code is just returned.
 2479          */
 2480         switch (error) {
 2481         case ENODEV:
 2482                 /*
 2483                  * Check that the mode the file is being opened for is a
 2484                  * subset of the mode of the existing descriptor.
 2485                  */
 2486                 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
 2487                         FILEDESC_XUNLOCK(fdp);
 2488                         return (EACCES);
 2489                 }
 2490                 fp = fdp->fd_ofiles[indx];
 2491                 fdp->fd_ofiles[indx] = wfp;
 2492                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
 2493                 if (fp == NULL)
 2494                         fdused(fdp, indx);
 2495                 fhold(wfp);
 2496                 FILEDESC_XUNLOCK(fdp);
 2497                 if (fp != NULL)
 2498                         /*
 2499                          * We now own the reference to fp that the ofiles[]
 2500                          * array used to own.  Release it.
 2501                          */
 2502                         fdrop(fp, td);
 2503                 return (0);
 2504 
 2505         case ENXIO:
 2506                 /*
 2507                  * Steal away the file pointer from dfd and stuff it into indx.
 2508                  */
 2509                 fp = fdp->fd_ofiles[indx];
 2510                 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
 2511                 fdp->fd_ofiles[dfd] = NULL;
 2512                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
 2513                 fdp->fd_ofileflags[dfd] = 0;
 2514                 fdunused(fdp, dfd);
 2515                 if (fp == NULL)
 2516                         fdused(fdp, indx);
 2517                 FILEDESC_XUNLOCK(fdp);
 2518 
 2519                 /*
 2520                  * We now own the reference to fp that the ofiles[] array
 2521                  * used to own.  Release it.
 2522                  */
 2523                 if (fp != NULL)
 2524                         fdrop(fp, td);
 2525                 return (0);
 2526 
 2527         default:
 2528                 FILEDESC_XUNLOCK(fdp);
 2529                 return (error);
 2530         }
 2531         /* NOTREACHED */
 2532 }
 2533 
 2534 /*
 2535  * Scan all active processes and prisons to see if any of them have a current
 2536  * or root directory of `olddp'. If so, replace them with the new mount point.
 2537  */
 2538 void
 2539 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
 2540 {
 2541         struct filedesc *fdp;
 2542         struct prison *pr;
 2543         struct proc *p;
 2544         int nrele;
 2545 
 2546         if (vrefcnt(olddp) == 1)
 2547                 return;
 2548         nrele = 0;
 2549         sx_slock(&allproc_lock);
 2550         FOREACH_PROC_IN_SYSTEM(p) {
 2551                 fdp = fdhold(p);
 2552                 if (fdp == NULL)
 2553                         continue;
 2554                 FILEDESC_XLOCK(fdp);
 2555                 if (fdp->fd_cdir == olddp) {
 2556                         vref(newdp);
 2557                         fdp->fd_cdir = newdp;
 2558                         nrele++;
 2559                 }
 2560                 if (fdp->fd_rdir == olddp) {
 2561                         vref(newdp);
 2562                         fdp->fd_rdir = newdp;
 2563                         nrele++;
 2564                 }
 2565                 if (fdp->fd_jdir == olddp) {
 2566                         vref(newdp);
 2567                         fdp->fd_jdir = newdp;
 2568                         nrele++;
 2569                 }
 2570                 FILEDESC_XUNLOCK(fdp);
 2571                 fddrop(fdp);
 2572         }
 2573         sx_sunlock(&allproc_lock);
 2574         if (rootvnode == olddp) {
 2575                 vref(newdp);
 2576                 rootvnode = newdp;
 2577                 nrele++;
 2578         }
 2579         mtx_lock(&prison0.pr_mtx);
 2580         if (prison0.pr_root == olddp) {
 2581                 vref(newdp);
 2582                 prison0.pr_root = newdp;
 2583                 nrele++;
 2584         }
 2585         mtx_unlock(&prison0.pr_mtx);
 2586         sx_slock(&allprison_lock);
 2587         TAILQ_FOREACH(pr, &allprison, pr_list) {
 2588                 mtx_lock(&pr->pr_mtx);
 2589                 if (pr->pr_root == olddp) {
 2590                         vref(newdp);
 2591                         pr->pr_root = newdp;
 2592                         nrele++;
 2593                 }
 2594                 mtx_unlock(&pr->pr_mtx);
 2595         }
 2596         sx_sunlock(&allprison_lock);
 2597         while (nrele--)
 2598                 vrele(olddp);
 2599 }
 2600 
 2601 struct filedesc_to_leader *
 2602 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
 2603 {
 2604         struct filedesc_to_leader *fdtol;
 2605 
 2606         fdtol = malloc(sizeof(struct filedesc_to_leader),
 2607                M_FILEDESC_TO_LEADER,
 2608                M_WAITOK);
 2609         fdtol->fdl_refcount = 1;
 2610         fdtol->fdl_holdcount = 0;
 2611         fdtol->fdl_wakeup = 0;
 2612         fdtol->fdl_leader = leader;
 2613         if (old != NULL) {
 2614                 FILEDESC_XLOCK(fdp);
 2615                 fdtol->fdl_next = old->fdl_next;
 2616                 fdtol->fdl_prev = old;
 2617                 old->fdl_next = fdtol;
 2618                 fdtol->fdl_next->fdl_prev = fdtol;
 2619                 FILEDESC_XUNLOCK(fdp);
 2620         } else {
 2621                 fdtol->fdl_next = fdtol;
 2622                 fdtol->fdl_prev = fdtol;
 2623         }
 2624         return (fdtol);
 2625 }
 2626 
 2627 /*
 2628  * Get file structures globally.
 2629  */
 2630 static int
 2631 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
 2632 {
 2633         struct xfile xf;
 2634         struct filedesc *fdp;
 2635         struct file *fp;
 2636         struct proc *p;
 2637         int error, n;
 2638 
 2639         error = sysctl_wire_old_buffer(req, 0);
 2640         if (error != 0)
 2641                 return (error);
 2642         if (req->oldptr == NULL) {
 2643                 n = 0;
 2644                 sx_slock(&allproc_lock);
 2645                 FOREACH_PROC_IN_SYSTEM(p) {
 2646                         if (p->p_state == PRS_NEW)
 2647                                 continue;
 2648                         fdp = fdhold(p);
 2649                         if (fdp == NULL)
 2650                                 continue;
 2651                         /* overestimates sparse tables. */
 2652                         if (fdp->fd_lastfile > 0)
 2653                                 n += fdp->fd_lastfile;
 2654                         fddrop(fdp);
 2655                 }
 2656                 sx_sunlock(&allproc_lock);
 2657                 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
 2658         }
 2659         error = 0;
 2660         bzero(&xf, sizeof(xf));
 2661         xf.xf_size = sizeof(xf);
 2662         sx_slock(&allproc_lock);
 2663         FOREACH_PROC_IN_SYSTEM(p) {
 2664                 PROC_LOCK(p);
 2665                 if (p->p_state == PRS_NEW) {
 2666                         PROC_UNLOCK(p);
 2667                         continue;
 2668                 }
 2669                 if (p_cansee(req->td, p) != 0) {
 2670                         PROC_UNLOCK(p);
 2671                         continue;
 2672                 }
 2673                 xf.xf_pid = p->p_pid;
 2674                 xf.xf_uid = p->p_ucred->cr_uid;
 2675                 PROC_UNLOCK(p);
 2676                 fdp = fdhold(p);
 2677                 if (fdp == NULL)
 2678                         continue;
 2679                 FILEDESC_SLOCK(fdp);
 2680                 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
 2681                         if ((fp = fdp->fd_ofiles[n]) == NULL)
 2682                                 continue;
 2683                         xf.xf_fd = n;
 2684                         xf.xf_file = fp;
 2685                         xf.xf_data = fp->f_data;
 2686                         xf.xf_vnode = fp->f_vnode;
 2687                         xf.xf_type = fp->f_type;
 2688                         xf.xf_count = fp->f_count;
 2689                         xf.xf_msgcount = 0;
 2690                         xf.xf_offset = fp->f_offset;
 2691                         xf.xf_flag = fp->f_flag;
 2692                         error = SYSCTL_OUT(req, &xf, sizeof(xf));
 2693                         if (error)
 2694                                 break;
 2695                 }
 2696                 FILEDESC_SUNLOCK(fdp);
 2697                 fddrop(fdp);
 2698                 if (error)
 2699                         break;
 2700         }
 2701         sx_sunlock(&allproc_lock);
 2702         return (error);
 2703 }
 2704 
 2705 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
 2706     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
 2707 
 2708 #ifdef KINFO_OFILE_SIZE
 2709 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
 2710 #endif
 2711 
 2712 #ifdef COMPAT_FREEBSD7
 2713 static int
 2714 export_vnode_for_osysctl(struct vnode *vp, int type,
 2715     struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
 2716 {
 2717         int error;
 2718         char *fullpath, *freepath;
 2719         int vfslocked;
 2720 
 2721         bzero(kif, sizeof(*kif));
 2722         kif->kf_structsize = sizeof(*kif);
 2723 
 2724         vref(vp);
 2725         kif->kf_fd = type;
 2726         kif->kf_type = KF_TYPE_VNODE;
 2727         /* This function only handles directories. */
 2728         if (vp->v_type != VDIR) {
 2729                 vrele(vp);
 2730                 return (ENOTDIR);
 2731         }
 2732         kif->kf_vnode_type = KF_VTYPE_VDIR;
 2733 
 2734         /*
 2735          * This is not a true file descriptor, so we set a bogus refcount
 2736          * and offset to indicate these fields should be ignored.
 2737          */
 2738         kif->kf_ref_count = -1;
 2739         kif->kf_offset = -1;
 2740 
 2741         freepath = NULL;
 2742         fullpath = "-";
 2743         FILEDESC_SUNLOCK(fdp);
 2744         vn_fullpath(curthread, vp, &fullpath, &freepath);
 2745         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2746         vrele(vp);
 2747         VFS_UNLOCK_GIANT(vfslocked);
 2748         strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
 2749         if (freepath != NULL)
 2750                 free(freepath, M_TEMP);
 2751         error = SYSCTL_OUT(req, kif, sizeof(*kif));
 2752         FILEDESC_SLOCK(fdp);
 2753         return (error);
 2754 }
 2755 
 2756 /*
 2757  * Get per-process file descriptors for use by procstat(1), et al.
 2758  */
 2759 static int
 2760 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
 2761 {
 2762         char *fullpath, *freepath;
 2763         struct kinfo_ofile *kif;
 2764         struct filedesc *fdp;
 2765         int error, i, *name;
 2766         struct shmfd *shmfd;
 2767         struct socket *so;
 2768         struct vnode *vp;
 2769         struct ksem *ks;
 2770         struct file *fp;
 2771         struct proc *p;
 2772         struct tty *tp;
 2773         int vfslocked;
 2774 
 2775         name = (int *)arg1;
 2776         if ((p = pfind((pid_t)name[0])) == NULL)
 2777                 return (ESRCH);
 2778         if ((error = p_candebug(curthread, p))) {
 2779                 PROC_UNLOCK(p);
 2780                 return (error);
 2781         }
 2782         fdp = fdhold(p);
 2783         PROC_UNLOCK(p);
 2784         if (fdp == NULL)
 2785                 return (ENOENT);
 2786         kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
 2787         FILEDESC_SLOCK(fdp);
 2788         if (fdp->fd_cdir != NULL)
 2789                 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
 2790                                 fdp, req);
 2791         if (fdp->fd_rdir != NULL)
 2792                 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
 2793                                 fdp, req);
 2794         if (fdp->fd_jdir != NULL)
 2795                 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
 2796                                 fdp, req);
 2797         for (i = 0; i < fdp->fd_nfiles; i++) {
 2798                 if ((fp = fdp->fd_ofiles[i]) == NULL)
 2799                         continue;
 2800                 bzero(kif, sizeof(*kif));
 2801                 kif->kf_structsize = sizeof(*kif);
 2802                 ks = NULL;
 2803                 vp = NULL;
 2804                 so = NULL;
 2805                 tp = NULL;
 2806                 shmfd = NULL;
 2807                 kif->kf_fd = i;
 2808                 switch (fp->f_type) {
 2809                 case DTYPE_VNODE:
 2810                         kif->kf_type = KF_TYPE_VNODE;
 2811                         vp = fp->f_vnode;
 2812                         break;
 2813 
 2814                 case DTYPE_SOCKET:
 2815                         kif->kf_type = KF_TYPE_SOCKET;
 2816                         so = fp->f_data;
 2817                         break;
 2818 
 2819                 case DTYPE_PIPE:
 2820                         kif->kf_type = KF_TYPE_PIPE;
 2821                         break;
 2822 
 2823                 case DTYPE_FIFO:
 2824                         kif->kf_type = KF_TYPE_FIFO;
 2825                         vp = fp->f_vnode;
 2826                         break;
 2827 
 2828                 case DTYPE_KQUEUE:
 2829                         kif->kf_type = KF_TYPE_KQUEUE;
 2830                         break;
 2831 
 2832                 case DTYPE_CRYPTO:
 2833                         kif->kf_type = KF_TYPE_CRYPTO;
 2834                         break;
 2835 
 2836                 case DTYPE_MQUEUE:
 2837                         kif->kf_type = KF_TYPE_MQUEUE;
 2838                         break;
 2839 
 2840                 case DTYPE_SHM:
 2841                         kif->kf_type = KF_TYPE_SHM;
 2842                         shmfd = fp->f_data;
 2843                         break;
 2844 
 2845                 case DTYPE_SEM:
 2846                         kif->kf_type = KF_TYPE_SEM;
 2847                         ks = fp->f_data;
 2848                         break;
 2849 
 2850                 case DTYPE_PTS:
 2851                         kif->kf_type = KF_TYPE_PTS;
 2852                         tp = fp->f_data;
 2853                         break;
 2854 
 2855                 default:
 2856                         kif->kf_type = KF_TYPE_UNKNOWN;
 2857                         break;
 2858                 }
 2859                 kif->kf_ref_count = fp->f_count;
 2860                 if (fp->f_flag & FREAD)
 2861                         kif->kf_flags |= KF_FLAG_READ;
 2862                 if (fp->f_flag & FWRITE)
 2863                         kif->kf_flags |= KF_FLAG_WRITE;
 2864                 if (fp->f_flag & FAPPEND)
 2865                         kif->kf_flags |= KF_FLAG_APPEND;
 2866                 if (fp->f_flag & FASYNC)
 2867                         kif->kf_flags |= KF_FLAG_ASYNC;
 2868                 if (fp->f_flag & FFSYNC)
 2869                         kif->kf_flags |= KF_FLAG_FSYNC;
 2870                 if (fp->f_flag & FNONBLOCK)
 2871                         kif->kf_flags |= KF_FLAG_NONBLOCK;
 2872                 if (fp->f_flag & O_DIRECT)
 2873                         kif->kf_flags |= KF_FLAG_DIRECT;
 2874                 if (fp->f_flag & FHASLOCK)
 2875                         kif->kf_flags |= KF_FLAG_HASLOCK;
 2876                 kif->kf_offset = fp->f_offset;
 2877                 if (vp != NULL) {
 2878                         vref(vp);
 2879                         switch (vp->v_type) {
 2880                         case VNON:
 2881                                 kif->kf_vnode_type = KF_VTYPE_VNON;
 2882                                 break;
 2883                         case VREG:
 2884                                 kif->kf_vnode_type = KF_VTYPE_VREG;
 2885                                 break;
 2886                         case VDIR:
 2887                                 kif->kf_vnode_type = KF_VTYPE_VDIR;
 2888                                 break;
 2889                         case VBLK:
 2890                                 kif->kf_vnode_type = KF_VTYPE_VBLK;
 2891                                 break;
 2892                         case VCHR:
 2893                                 kif->kf_vnode_type = KF_VTYPE_VCHR;
 2894                                 break;
 2895                         case VLNK:
 2896                                 kif->kf_vnode_type = KF_VTYPE_VLNK;
 2897                                 break;
 2898                         case VSOCK:
 2899                                 kif->kf_vnode_type = KF_VTYPE_VSOCK;
 2900                                 break;
 2901                         case VFIFO:
 2902                                 kif->kf_vnode_type = KF_VTYPE_VFIFO;
 2903                                 break;
 2904                         case VBAD:
 2905                                 kif->kf_vnode_type = KF_VTYPE_VBAD;
 2906                                 break;
 2907                         default:
 2908                                 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
 2909                                 break;
 2910                         }
 2911                         /*
 2912                          * It is OK to drop the filedesc lock here as we will
 2913                          * re-validate and re-evaluate its properties when
 2914                          * the loop continues.
 2915                          */
 2916                         freepath = NULL;
 2917                         fullpath = "-";
 2918                         FILEDESC_SUNLOCK(fdp);
 2919                         vn_fullpath(curthread, vp, &fullpath, &freepath);
 2920                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2921                         vrele(vp);
 2922                         VFS_UNLOCK_GIANT(vfslocked);
 2923                         strlcpy(kif->kf_path, fullpath,
 2924                             sizeof(kif->kf_path));
 2925                         if (freepath != NULL)
 2926                                 free(freepath, M_TEMP);
 2927                         FILEDESC_SLOCK(fdp);
 2928                 }
 2929                 if (so != NULL) {
 2930                         struct sockaddr *sa;
 2931 
 2932                         if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
 2933                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
 2934                                 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
 2935                                 free(sa, M_SONAME);
 2936                         }
 2937                         if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
 2938                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
 2939                                 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
 2940                                 free(sa, M_SONAME);
 2941                         }
 2942                         kif->kf_sock_domain =
 2943                             so->so_proto->pr_domain->dom_family;
 2944                         kif->kf_sock_type = so->so_type;
 2945                         kif->kf_sock_protocol = so->so_proto->pr_protocol;
 2946                 }
 2947                 if (tp != NULL) {
 2948                         strlcpy(kif->kf_path, tty_devname(tp),
 2949                             sizeof(kif->kf_path));
 2950                 }
 2951                 if (shmfd != NULL)
 2952                         shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
 2953                 if (ks != NULL && ksem_info != NULL)
 2954                         ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
 2955                 error = SYSCTL_OUT(req, kif, sizeof(*kif));
 2956                 if (error)
 2957                         break;
 2958         }
 2959         FILEDESC_SUNLOCK(fdp);
 2960         fddrop(fdp);
 2961         free(kif, M_TEMP);
 2962         return (0);
 2963 }
 2964 
 2965 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
 2966     sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
 2967 #endif  /* COMPAT_FREEBSD7 */
 2968 
 2969 #ifdef KINFO_FILE_SIZE
 2970 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
 2971 #endif
 2972 
 2973 static int
 2974 export_vnode_for_sysctl(struct vnode *vp, int type,
 2975     struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
 2976 {
 2977         int error;
 2978         char *fullpath, *freepath;
 2979         int vfslocked;
 2980 
 2981         bzero(kif, sizeof(*kif));
 2982 
 2983         vref(vp);
 2984         kif->kf_fd = type;
 2985         kif->kf_type = KF_TYPE_VNODE;
 2986         /* This function only handles directories. */
 2987         if (vp->v_type != VDIR) {
 2988                 vrele(vp);
 2989                 return (ENOTDIR);
 2990         }
 2991         kif->kf_vnode_type = KF_VTYPE_VDIR;
 2992 
 2993         /*
 2994          * This is not a true file descriptor, so we set a bogus refcount
 2995          * and offset to indicate these fields should be ignored.
 2996          */
 2997         kif->kf_ref_count = -1;
 2998         kif->kf_offset = -1;
 2999 
 3000         freepath = NULL;
 3001         fullpath = "-";
 3002         FILEDESC_SUNLOCK(fdp);
 3003         vn_fullpath(curthread, vp, &fullpath, &freepath);
 3004         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 3005         vrele(vp);
 3006         VFS_UNLOCK_GIANT(vfslocked);
 3007         strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
 3008         if (freepath != NULL)
 3009                 free(freepath, M_TEMP);
 3010         /* Pack record size down */
 3011         kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
 3012             strlen(kif->kf_path) + 1;
 3013         kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
 3014         error = SYSCTL_OUT(req, kif, kif->kf_structsize);
 3015         FILEDESC_SLOCK(fdp);
 3016         return (error);
 3017 }
 3018 
 3019 /*
 3020  * Get per-process file descriptors for use by procstat(1), et al.
 3021  */
 3022 static int
 3023 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
 3024 {
 3025         char *fullpath, *freepath;
 3026         struct kinfo_file *kif;
 3027         struct filedesc *fdp;
 3028         int error, i, *name;
 3029         struct shmfd *shmfd;
 3030         struct socket *so;
 3031         struct vnode *vp;
 3032         struct ksem *ks;
 3033         struct file *fp;
 3034         struct proc *p;
 3035         struct tty *tp;
 3036         int vfslocked;
 3037         size_t oldidx;
 3038 
 3039         name = (int *)arg1;
 3040         if ((p = pfind((pid_t)name[0])) == NULL)
 3041                 return (ESRCH);
 3042         if ((error = p_candebug(curthread, p))) {
 3043                 PROC_UNLOCK(p);
 3044                 return (error);
 3045         }
 3046         fdp = fdhold(p);
 3047         PROC_UNLOCK(p);
 3048         if (fdp == NULL)
 3049                 return (ENOENT);
 3050         kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
 3051         FILEDESC_SLOCK(fdp);
 3052         if (fdp->fd_cdir != NULL)
 3053                 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
 3054                                 fdp, req);
 3055         if (fdp->fd_rdir != NULL)
 3056                 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
 3057                                 fdp, req);
 3058         if (fdp->fd_jdir != NULL)
 3059                 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
 3060                                 fdp, req);
 3061         for (i = 0; i < fdp->fd_nfiles; i++) {
 3062                 if ((fp = fdp->fd_ofiles[i]) == NULL)
 3063                         continue;
 3064                 bzero(kif, sizeof(*kif));
 3065                 ks = NULL;
 3066                 vp = NULL;
 3067                 so = NULL;
 3068                 tp = NULL;
 3069                 shmfd = NULL;
 3070                 kif->kf_fd = i;
 3071                 switch (fp->f_type) {
 3072                 case DTYPE_VNODE:
 3073                         kif->kf_type = KF_TYPE_VNODE;
 3074                         vp = fp->f_vnode;
 3075                         break;
 3076 
 3077                 case DTYPE_SOCKET:
 3078                         kif->kf_type = KF_TYPE_SOCKET;
 3079                         so = fp->f_data;
 3080                         break;
 3081 
 3082                 case DTYPE_PIPE:
 3083                         kif->kf_type = KF_TYPE_PIPE;
 3084                         break;
 3085 
 3086                 case DTYPE_FIFO:
 3087                         kif->kf_type = KF_TYPE_FIFO;
 3088                         vp = fp->f_vnode;
 3089                         break;
 3090 
 3091                 case DTYPE_KQUEUE:
 3092                         kif->kf_type = KF_TYPE_KQUEUE;
 3093                         break;
 3094 
 3095                 case DTYPE_CRYPTO:
 3096                         kif->kf_type = KF_TYPE_CRYPTO;
 3097                         break;
 3098 
 3099                 case DTYPE_MQUEUE:
 3100                         kif->kf_type = KF_TYPE_MQUEUE;
 3101                         break;
 3102 
 3103                 case DTYPE_SHM:
 3104                         kif->kf_type = KF_TYPE_SHM;
 3105                         shmfd = fp->f_data;
 3106                         break;
 3107 
 3108                 case DTYPE_SEM:
 3109                         kif->kf_type = KF_TYPE_SEM;
 3110                         ks = fp->f_data;
 3111                         break;
 3112 
 3113                 case DTYPE_PTS:
 3114                         kif->kf_type = KF_TYPE_PTS;
 3115                         tp = fp->f_data;
 3116                         break;
 3117 
 3118                 default:
 3119                         kif->kf_type = KF_TYPE_UNKNOWN;
 3120                         break;
 3121                 }
 3122                 kif->kf_ref_count = fp->f_count;
 3123                 if (fp->f_flag & FREAD)
 3124                         kif->kf_flags |= KF_FLAG_READ;
 3125                 if (fp->f_flag & FWRITE)
 3126                         kif->kf_flags |= KF_FLAG_WRITE;
 3127                 if (fp->f_flag & FAPPEND)
 3128                         kif->kf_flags |= KF_FLAG_APPEND;
 3129                 if (fp->f_flag & FASYNC)
 3130                         kif->kf_flags |= KF_FLAG_ASYNC;
 3131                 if (fp->f_flag & FFSYNC)
 3132                         kif->kf_flags |= KF_FLAG_FSYNC;
 3133                 if (fp->f_flag & FNONBLOCK)
 3134                         kif->kf_flags |= KF_FLAG_NONBLOCK;
 3135                 if (fp->f_flag & O_DIRECT)
 3136                         kif->kf_flags |= KF_FLAG_DIRECT;
 3137                 if (fp->f_flag & FHASLOCK)
 3138                         kif->kf_flags |= KF_FLAG_HASLOCK;
 3139                 kif->kf_offset = fp->f_offset;
 3140                 if (vp != NULL) {
 3141                         vref(vp);
 3142                         switch (vp->v_type) {
 3143                         case VNON:
 3144                                 kif->kf_vnode_type = KF_VTYPE_VNON;
 3145                                 break;
 3146                         case VREG:
 3147                                 kif->kf_vnode_type = KF_VTYPE_VREG;
 3148                                 break;
 3149                         case VDIR:
 3150                                 kif->kf_vnode_type = KF_VTYPE_VDIR;
 3151                                 break;
 3152                         case VBLK:
 3153                                 kif->kf_vnode_type = KF_VTYPE_VBLK;
 3154                                 break;
 3155                         case VCHR:
 3156                                 kif->kf_vnode_type = KF_VTYPE_VCHR;
 3157                                 break;
 3158                         case VLNK:
 3159                                 kif->kf_vnode_type = KF_VTYPE_VLNK;
 3160                                 break;
 3161                         case VSOCK:
 3162                                 kif->kf_vnode_type = KF_VTYPE_VSOCK;
 3163                                 break;
 3164                         case VFIFO:
 3165                                 kif->kf_vnode_type = KF_VTYPE_VFIFO;
 3166                                 break;
 3167                         case VBAD:
 3168                                 kif->kf_vnode_type = KF_VTYPE_VBAD;
 3169                                 break;
 3170                         default:
 3171                                 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
 3172                                 break;
 3173                         }
 3174                         /*
 3175                          * It is OK to drop the filedesc lock here as we will
 3176                          * re-validate and re-evaluate its properties when
 3177                          * the loop continues.
 3178                          */
 3179                         freepath = NULL;
 3180                         fullpath = "-";
 3181                         FILEDESC_SUNLOCK(fdp);
 3182                         vn_fullpath(curthread, vp, &fullpath, &freepath);
 3183                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 3184                         vrele(vp);
 3185                         VFS_UNLOCK_GIANT(vfslocked);
 3186                         strlcpy(kif->kf_path, fullpath,
 3187                             sizeof(kif->kf_path));
 3188                         if (freepath != NULL)
 3189                                 free(freepath, M_TEMP);
 3190                         FILEDESC_SLOCK(fdp);
 3191                 }
 3192                 if (so != NULL) {
 3193                         struct sockaddr *sa;
 3194 
 3195                         if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
 3196                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
 3197                                 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
 3198                                 free(sa, M_SONAME);
 3199                         }
 3200                         if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
 3201                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
 3202                                 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
 3203                                 free(sa, M_SONAME);
 3204                         }
 3205                         kif->kf_sock_domain =
 3206                             so->so_proto->pr_domain->dom_family;
 3207                         kif->kf_sock_type = so->so_type;
 3208                         kif->kf_sock_protocol = so->so_proto->pr_protocol;
 3209                 }
 3210                 if (tp != NULL) {
 3211                         strlcpy(kif->kf_path, tty_devname(tp),
 3212                             sizeof(kif->kf_path));
 3213                 }
 3214                 if (shmfd != NULL)
 3215                         shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
 3216                 if (ks != NULL && ksem_info != NULL)
 3217                         ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
 3218                 /* Pack record size down */
 3219                 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
 3220                     strlen(kif->kf_path) + 1;
 3221                 kif->kf_structsize = roundup(kif->kf_structsize,
 3222                     sizeof(uint64_t));
 3223                 oldidx = req->oldidx;
 3224                 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
 3225                 if (error) {
 3226                         if (error == ENOMEM) {
 3227                                 /*
 3228                                  * The hack to keep the ABI of sysctl
 3229                                  * kern.proc.filedesc intact, but not
 3230                                  * to account a partially copied
 3231                                  * kinfo_file into the oldidx.
 3232                                  */
 3233                                 req->oldidx = oldidx;
 3234                                 error = 0;
 3235                         }
 3236                         break;
 3237                 }
 3238         }
 3239         FILEDESC_SUNLOCK(fdp);
 3240         fddrop(fdp);
 3241         free(kif, M_TEMP);
 3242         return (error);
 3243 }
 3244 
 3245 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
 3246     sysctl_kern_proc_filedesc, "Process filedesc entries");
 3247 
 3248 #ifdef DDB
 3249 /*
 3250  * For the purposes of debugging, generate a human-readable string for the
 3251  * file type.
 3252  */
 3253 static const char *
 3254 file_type_to_name(short type)
 3255 {
 3256 
 3257         switch (type) {
 3258         case 0:
 3259                 return ("zero");
 3260         case DTYPE_VNODE:
 3261                 return ("vnod");
 3262         case DTYPE_SOCKET:
 3263                 return ("sock");
 3264         case DTYPE_PIPE:
 3265                 return ("pipe");
 3266         case DTYPE_FIFO:
 3267                 return ("fifo");
 3268         case DTYPE_KQUEUE:
 3269                 return ("kque");
 3270         case DTYPE_CRYPTO:
 3271                 return ("crpt");
 3272         case DTYPE_MQUEUE:
 3273                 return ("mque");
 3274         case DTYPE_SHM:
 3275                 return ("shm");
 3276         case DTYPE_SEM:
 3277                 return ("ksem");
 3278         default:
 3279                 return ("unkn");
 3280         }
 3281 }
 3282 
 3283 /*
 3284  * For the purposes of debugging, identify a process (if any, perhaps one of
 3285  * many) that references the passed file in its file descriptor array. Return
 3286  * NULL if none.
 3287  */
 3288 static struct proc *
 3289 file_to_first_proc(struct file *fp)
 3290 {
 3291         struct filedesc *fdp;
 3292         struct proc *p;
 3293         int n;
 3294 
 3295         FOREACH_PROC_IN_SYSTEM(p) {
 3296                 if (p->p_state == PRS_NEW)
 3297                         continue;
 3298                 fdp = p->p_fd;
 3299                 if (fdp == NULL)
 3300                         continue;
 3301                 for (n = 0; n < fdp->fd_nfiles; n++) {
 3302                         if (fp == fdp->fd_ofiles[n])
 3303                                 return (p);
 3304                 }
 3305         }
 3306         return (NULL);
 3307 }
 3308 
 3309 static void
 3310 db_print_file(struct file *fp, int header)
 3311 {
 3312         struct proc *p;
 3313 
 3314         if (header)
 3315                 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
 3316                     "File", "Type", "Data", "Flag", "GCFl", "Count",
 3317                     "MCount", "Vnode", "FPID", "FCmd");
 3318         p = file_to_first_proc(fp);
 3319         db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
 3320             file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
 3321             0, fp->f_count, 0, fp->f_vnode,
 3322             p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
 3323 }
 3324 
 3325 DB_SHOW_COMMAND(file, db_show_file)
 3326 {
 3327         struct file *fp;
 3328 
 3329         if (!have_addr) {
 3330                 db_printf("usage: show file <addr>\n");
 3331                 return;
 3332         }
 3333         fp = (struct file *)addr;
 3334         db_print_file(fp, 1);
 3335 }
 3336 
 3337 DB_SHOW_COMMAND(files, db_show_files)
 3338 {
 3339         struct filedesc *fdp;
 3340         struct file *fp;
 3341         struct proc *p;
 3342         int header;
 3343         int n;
 3344 
 3345         header = 1;
 3346         FOREACH_PROC_IN_SYSTEM(p) {
 3347                 if (p->p_state == PRS_NEW)
 3348                         continue;
 3349                 if ((fdp = p->p_fd) == NULL)
 3350                         continue;
 3351                 for (n = 0; n < fdp->fd_nfiles; ++n) {
 3352                         if ((fp = fdp->fd_ofiles[n]) == NULL)
 3353                                 continue;
 3354                         db_print_file(fp, header);
 3355                         header = 0;
 3356                 }
 3357         }
 3358 }
 3359 #endif
 3360 
 3361 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
 3362     &maxfilesperproc, 0, "Maximum files allowed open per process");
 3363 
 3364 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
 3365     &maxfiles, 0, "Maximum number of files");
 3366 
 3367 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
 3368     __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
 3369 
 3370 /* ARGSUSED*/
 3371 static void
 3372 filelistinit(void *dummy)
 3373 {
 3374 
 3375         file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
 3376             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
 3377         mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
 3378         mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
 3379 }
 3380 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
 3381 
 3382 /*-------------------------------------------------------------------*/
 3383 
 3384 static int
 3385 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
 3386 {
 3387 
 3388         return (EBADF);
 3389 }
 3390 
 3391 static int
 3392 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
 3393 {
 3394 
 3395         return (EINVAL);
 3396 }
 3397 
 3398 static int
 3399 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
 3400 {
 3401 
 3402         return (EBADF);
 3403 }
 3404 
 3405 static int
 3406 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
 3407 {
 3408 
 3409         return (0);
 3410 }
 3411 
 3412 static int
 3413 badfo_kqfilter(struct file *fp, struct knote *kn)
 3414 {
 3415 
 3416         return (EBADF);
 3417 }
 3418 
 3419 static int
 3420 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
 3421 {
 3422 
 3423         return (EBADF);
 3424 }
 3425 
 3426 static int
 3427 badfo_close(struct file *fp, struct thread *td)
 3428 {
 3429 
 3430         return (EBADF);
 3431 }
 3432 
 3433 struct fileops badfileops = {
 3434         .fo_read = badfo_readwrite,
 3435         .fo_write = badfo_readwrite,
 3436         .fo_truncate = badfo_truncate,
 3437         .fo_ioctl = badfo_ioctl,
 3438         .fo_poll = badfo_poll,
 3439         .fo_kqfilter = badfo_kqfilter,
 3440         .fo_stat = badfo_stat,
 3441         .fo_close = badfo_close,
 3442 };
 3443 
 3444 
 3445 /*-------------------------------------------------------------------*/
 3446 
 3447 /*
 3448  * File Descriptor pseudo-device driver (/dev/fd/).
 3449  *
 3450  * Opening minor device N dup()s the file (if any) connected to file
 3451  * descriptor N belonging to the calling process.  Note that this driver
 3452  * consists of only the ``open()'' routine, because all subsequent
 3453  * references to this file will be direct to the other driver.
 3454  *
 3455  * XXX: we could give this one a cloning event handler if necessary.
 3456  */
 3457 
 3458 /* ARGSUSED */
 3459 static int
 3460 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
 3461 {
 3462 
 3463         /*
 3464          * XXX Kludge: set curthread->td_dupfd to contain the value of the
 3465          * the file descriptor being sought for duplication. The error
 3466          * return ensures that the vnode for this device will be released
 3467          * by vn_open. Open will detect this special error and take the
 3468          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
 3469          * will simply report the error.
 3470          */
 3471         td->td_dupfd = dev2unit(dev);
 3472         return (ENODEV);
 3473 }
 3474 
 3475 static struct cdevsw fildesc_cdevsw = {
 3476         .d_version =    D_VERSION,
 3477         .d_open =       fdopen,
 3478         .d_name =       "FD",
 3479 };
 3480 
 3481 static void
 3482 fildesc_drvinit(void *unused)
 3483 {
 3484         struct cdev *dev;
 3485 
 3486         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
 3487             UID_ROOT, GID_WHEEL, 0666, "fd/0");
 3488         make_dev_alias(dev, "stdin");
 3489         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
 3490             UID_ROOT, GID_WHEEL, 0666, "fd/1");
 3491         make_dev_alias(dev, "stdout");
 3492         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
 3493             UID_ROOT, GID_WHEEL, 0666, "fd/2");
 3494         make_dev_alias(dev, "stderr");
 3495 }
 3496 
 3497 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);

Cache object: a33267eee27bac97117005cc0bc680a3


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