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


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

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

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

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

Cache object: ddbfaaa42f4a8f6baa889849bf4ba9da


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