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


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

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

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

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

Cache object: 8cea87a698d7bac64bd3a863e20dc227


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