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-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
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_SHARED | 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                     fdp->fd_ofiles[i]->f_ops != &badfileops) {
 1618                         newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
 1619                         newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
 1620                         fhold(newfdp->fd_ofiles[i]);
 1621                         newfdp->fd_lastfile = i;
 1622                 } else {
 1623                         if (newfdp->fd_freefile == -1)
 1624                                 newfdp->fd_freefile = i;
 1625                 }
 1626         }
 1627         FILEDESC_SUNLOCK(fdp);
 1628         FILEDESC_XLOCK(newfdp);
 1629         for (i = 0; i <= newfdp->fd_lastfile; ++i)
 1630                 if (newfdp->fd_ofiles[i] != NULL)
 1631                         fdused(newfdp, i);
 1632         FILEDESC_XUNLOCK(newfdp);
 1633         FILEDESC_SLOCK(fdp);
 1634         if (newfdp->fd_freefile == -1)
 1635                 newfdp->fd_freefile = i;
 1636         newfdp->fd_cmask = fdp->fd_cmask;
 1637         FILEDESC_SUNLOCK(fdp);
 1638         return (newfdp);
 1639 }
 1640 
 1641 /*
 1642  * Release a filedesc structure.
 1643  */
 1644 void
 1645 fdfree(struct thread *td)
 1646 {
 1647         struct filedesc *fdp;
 1648         struct file **fpp;
 1649         int i, locked;
 1650         struct filedesc_to_leader *fdtol;
 1651         struct file *fp;
 1652         struct vnode *cdir, *jdir, *rdir, *vp;
 1653         struct flock lf;
 1654 
 1655         /* Certain daemons might not have file descriptors. */
 1656         fdp = td->td_proc->p_fd;
 1657         if (fdp == NULL)
 1658                 return;
 1659 
 1660         /* Check for special need to clear POSIX style locks */
 1661         fdtol = td->td_proc->p_fdtol;
 1662         if (fdtol != NULL) {
 1663                 FILEDESC_XLOCK(fdp);
 1664                 KASSERT(fdtol->fdl_refcount > 0,
 1665                         ("filedesc_to_refcount botch: fdl_refcount=%d",
 1666                          fdtol->fdl_refcount));
 1667                 if (fdtol->fdl_refcount == 1 &&
 1668                     (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1669                         for (i = 0, fpp = fdp->fd_ofiles;
 1670                              i <= fdp->fd_lastfile;
 1671                              i++, fpp++) {
 1672                                 if (*fpp == NULL ||
 1673                                     (*fpp)->f_type != DTYPE_VNODE)
 1674                                         continue;
 1675                                 fp = *fpp;
 1676                                 fhold(fp);
 1677                                 FILEDESC_XUNLOCK(fdp);
 1678                                 lf.l_whence = SEEK_SET;
 1679                                 lf.l_start = 0;
 1680                                 lf.l_len = 0;
 1681                                 lf.l_type = F_UNLCK;
 1682                                 vp = fp->f_vnode;
 1683                                 locked = VFS_LOCK_GIANT(vp->v_mount);
 1684                                 (void) VOP_ADVLOCK(vp,
 1685                                                    (caddr_t)td->td_proc->
 1686                                                    p_leader,
 1687                                                    F_UNLCK,
 1688                                                    &lf,
 1689                                                    F_POSIX);
 1690                                 VFS_UNLOCK_GIANT(locked);
 1691                                 FILEDESC_XLOCK(fdp);
 1692                                 fdrop(fp, td);
 1693                                 fpp = fdp->fd_ofiles + i;
 1694                         }
 1695                 }
 1696         retry:
 1697                 if (fdtol->fdl_refcount == 1) {
 1698                         if (fdp->fd_holdleaderscount > 0 &&
 1699                             (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1700                                 /*
 1701                                  * close() or do_dup() has cleared a reference
 1702                                  * in a shared file descriptor table.
 1703                                  */
 1704                                 fdp->fd_holdleaderswakeup = 1;
 1705                                 sx_sleep(&fdp->fd_holdleaderscount,
 1706                                     FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
 1707                                 goto retry;
 1708                         }
 1709                         if (fdtol->fdl_holdcount > 0) {
 1710                                 /*
 1711                                  * Ensure that fdtol->fdl_leader remains
 1712                                  * valid in closef().
 1713                                  */
 1714                                 fdtol->fdl_wakeup = 1;
 1715                                 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
 1716                                     "fdlhold", 0);
 1717                                 goto retry;
 1718                         }
 1719                 }
 1720                 fdtol->fdl_refcount--;
 1721                 if (fdtol->fdl_refcount == 0 &&
 1722                     fdtol->fdl_holdcount == 0) {
 1723                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
 1724                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
 1725                 } else
 1726                         fdtol = NULL;
 1727                 td->td_proc->p_fdtol = NULL;
 1728                 FILEDESC_XUNLOCK(fdp);
 1729                 if (fdtol != NULL)
 1730                         FREE(fdtol, M_FILEDESC_TO_LEADER);
 1731         }
 1732         FILEDESC_XLOCK(fdp);
 1733         i = --fdp->fd_refcnt;
 1734         FILEDESC_XUNLOCK(fdp);
 1735         if (i > 0)
 1736                 return;
 1737 
 1738         fpp = fdp->fd_ofiles;
 1739         for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
 1740                 if (*fpp) {
 1741                         FILEDESC_XLOCK(fdp);
 1742                         fp = *fpp;
 1743                         *fpp = NULL;
 1744                         FILEDESC_XUNLOCK(fdp);
 1745                         (void) closef(fp, td);
 1746                 }
 1747         }
 1748         FILEDESC_XLOCK(fdp);
 1749 
 1750         /* XXX This should happen earlier. */
 1751         mtx_lock(&fdesc_mtx);
 1752         td->td_proc->p_fd = NULL;
 1753         mtx_unlock(&fdesc_mtx);
 1754 
 1755         if (fdp->fd_nfiles > NDFILE)
 1756                 FREE(fdp->fd_ofiles, M_FILEDESC);
 1757         if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
 1758                 FREE(fdp->fd_map, M_FILEDESC);
 1759 
 1760         fdp->fd_nfiles = 0;
 1761 
 1762         cdir = fdp->fd_cdir;
 1763         fdp->fd_cdir = NULL;
 1764         rdir = fdp->fd_rdir;
 1765         fdp->fd_rdir = NULL;
 1766         jdir = fdp->fd_jdir;
 1767         fdp->fd_jdir = NULL;
 1768         FILEDESC_XUNLOCK(fdp);
 1769 
 1770         if (cdir) {
 1771                 locked = VFS_LOCK_GIANT(cdir->v_mount);
 1772                 vrele(cdir);
 1773                 VFS_UNLOCK_GIANT(locked);
 1774         }
 1775         if (rdir) {
 1776                 locked = VFS_LOCK_GIANT(rdir->v_mount);
 1777                 vrele(rdir);
 1778                 VFS_UNLOCK_GIANT(locked);
 1779         }
 1780         if (jdir) {
 1781                 locked = VFS_LOCK_GIANT(jdir->v_mount);
 1782                 vrele(jdir);
 1783                 VFS_UNLOCK_GIANT(locked);
 1784         }
 1785 
 1786         fddrop(fdp);
 1787 }
 1788 
 1789 /*
 1790  * For setugid programs, we don't want to people to use that setugidness
 1791  * to generate error messages which write to a file which otherwise would
 1792  * otherwise be off-limits to the process.  We check for filesystems where
 1793  * the vnode can change out from under us after execve (like [lin]procfs).
 1794  *
 1795  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
 1796  * sufficient.  We also don't check for setugidness since we know we are.
 1797  */
 1798 static int
 1799 is_unsafe(struct file *fp)
 1800 {
 1801         if (fp->f_type == DTYPE_VNODE) {
 1802                 struct vnode *vp = fp->f_vnode;
 1803 
 1804                 if ((vp->v_vflag & VV_PROCDEP) != 0)
 1805                         return (1);
 1806         }
 1807         return (0);
 1808 }
 1809 
 1810 /*
 1811  * Make this setguid thing safe, if at all possible.
 1812  */
 1813 void
 1814 setugidsafety(struct thread *td)
 1815 {
 1816         struct filedesc *fdp;
 1817         int i;
 1818 
 1819         /* Certain daemons might not have file descriptors. */
 1820         fdp = td->td_proc->p_fd;
 1821         if (fdp == NULL)
 1822                 return;
 1823 
 1824         /*
 1825          * Note: fdp->fd_ofiles may be reallocated out from under us while
 1826          * we are blocked in a close.  Be careful!
 1827          */
 1828         FILEDESC_XLOCK(fdp);
 1829         for (i = 0; i <= fdp->fd_lastfile; i++) {
 1830                 if (i > 2)
 1831                         break;
 1832                 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
 1833                         struct file *fp;
 1834 
 1835                         knote_fdclose(td, i);
 1836                         /*
 1837                          * NULL-out descriptor prior to close to avoid
 1838                          * a race while close blocks.
 1839                          */
 1840                         fp = fdp->fd_ofiles[i];
 1841                         fdp->fd_ofiles[i] = NULL;
 1842                         fdp->fd_ofileflags[i] = 0;
 1843                         fdunused(fdp, i);
 1844                         FILEDESC_XUNLOCK(fdp);
 1845                         (void) closef(fp, td);
 1846                         FILEDESC_XLOCK(fdp);
 1847                 }
 1848         }
 1849         FILEDESC_XUNLOCK(fdp);
 1850 }
 1851 
 1852 /*
 1853  * If a specific file object occupies a specific file descriptor, close the
 1854  * file descriptor entry and drop a reference on the file object.  This is a
 1855  * convenience function to handle a subsequent error in a function that calls
 1856  * falloc() that handles the race that another thread might have closed the
 1857  * file descriptor out from under the thread creating the file object.
 1858  */
 1859 void
 1860 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
 1861 {
 1862 
 1863         FILEDESC_XLOCK(fdp);
 1864         if (fdp->fd_ofiles[idx] == fp) {
 1865                 fdp->fd_ofiles[idx] = NULL;
 1866                 fdunused(fdp, idx);
 1867                 FILEDESC_XUNLOCK(fdp);
 1868                 fdrop(fp, td);
 1869         } else
 1870                 FILEDESC_XUNLOCK(fdp);
 1871 }
 1872 
 1873 /*
 1874  * Close any files on exec?
 1875  */
 1876 void
 1877 fdcloseexec(struct thread *td)
 1878 {
 1879         struct filedesc *fdp;
 1880         int i;
 1881 
 1882         /* Certain daemons might not have file descriptors. */
 1883         fdp = td->td_proc->p_fd;
 1884         if (fdp == NULL)
 1885                 return;
 1886 
 1887         FILEDESC_XLOCK(fdp);
 1888 
 1889         /*
 1890          * We cannot cache fd_ofiles or fd_ofileflags since operations
 1891          * may block and rip them out from under us.
 1892          */
 1893         for (i = 0; i <= fdp->fd_lastfile; i++) {
 1894                 if (fdp->fd_ofiles[i] != NULL &&
 1895                     (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
 1896                     (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
 1897                         struct file *fp;
 1898 
 1899                         knote_fdclose(td, i);
 1900                         /*
 1901                          * NULL-out descriptor prior to close to avoid
 1902                          * a race while close blocks.
 1903                          */
 1904                         fp = fdp->fd_ofiles[i];
 1905                         fdp->fd_ofiles[i] = NULL;
 1906                         fdp->fd_ofileflags[i] = 0;
 1907                         fdunused(fdp, i);
 1908                         if (fp->f_type == DTYPE_MQUEUE)
 1909                                 mq_fdclose(td, i, fp);
 1910                         FILEDESC_XUNLOCK(fdp);
 1911                         (void) closef(fp, td);
 1912                         FILEDESC_XLOCK(fdp);
 1913                 }
 1914         }
 1915         FILEDESC_XUNLOCK(fdp);
 1916 }
 1917 
 1918 /*
 1919  * It is unsafe for set[ug]id processes to be started with file
 1920  * descriptors 0..2 closed, as these descriptors are given implicit
 1921  * significance in the Standard C library.  fdcheckstd() will create a
 1922  * descriptor referencing /dev/null for each of stdin, stdout, and
 1923  * stderr that is not already open.
 1924  */
 1925 int
 1926 fdcheckstd(struct thread *td)
 1927 {
 1928         struct filedesc *fdp;
 1929         register_t retval, save;
 1930         int i, error, devnull;
 1931 
 1932         fdp = td->td_proc->p_fd;
 1933         if (fdp == NULL)
 1934                 return (0);
 1935         KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
 1936         devnull = -1;
 1937         error = 0;
 1938         for (i = 0; i < 3; i++) {
 1939                 if (fdp->fd_ofiles[i] != NULL)
 1940                         continue;
 1941                 if (devnull < 0) {
 1942                         save = td->td_retval[0];
 1943                         error = kern_open(td, "/dev/null", UIO_SYSSPACE,
 1944                             O_RDWR, 0);
 1945                         devnull = td->td_retval[0];
 1946                         KASSERT(devnull == i, ("oof, we didn't get our fd"));
 1947                         td->td_retval[0] = save;
 1948                         if (error)
 1949                                 break;
 1950                 } else {
 1951                         error = do_dup(td, DUP_FIXED, devnull, i, &retval);
 1952                         if (error != 0)
 1953                                 break;
 1954                 }
 1955         }
 1956         return (error);
 1957 }
 1958 
 1959 /*
 1960  * Internal form of close.  Decrement reference count on file structure.
 1961  * Note: td may be NULL when closing a file that was being passed in a
 1962  * message.
 1963  *
 1964  * XXXRW: Giant is not required for the caller, but often will be held; this
 1965  * makes it moderately likely the Giant will be recursed in the VFS case.
 1966  */
 1967 int
 1968 closef(struct file *fp, struct thread *td)
 1969 {
 1970         struct vnode *vp;
 1971         struct flock lf;
 1972         struct filedesc_to_leader *fdtol;
 1973         struct filedesc *fdp;
 1974 
 1975         /*
 1976          * POSIX record locking dictates that any close releases ALL
 1977          * locks owned by this process.  This is handled by setting
 1978          * a flag in the unlock to free ONLY locks obeying POSIX
 1979          * semantics, and not to free BSD-style file locks.
 1980          * If the descriptor was in a message, POSIX-style locks
 1981          * aren't passed with the descriptor, and the thread pointer
 1982          * will be NULL.  Callers should be careful only to pass a
 1983          * NULL thread pointer when there really is no owning
 1984          * context that might have locks, or the locks will be
 1985          * leaked.
 1986          */
 1987         if (fp->f_type == DTYPE_VNODE && td != NULL) {
 1988                 int vfslocked;
 1989 
 1990                 vp = fp->f_vnode;
 1991                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 1992                 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
 1993                         lf.l_whence = SEEK_SET;
 1994                         lf.l_start = 0;
 1995                         lf.l_len = 0;
 1996                         lf.l_type = F_UNLCK;
 1997                         (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
 1998                                            F_UNLCK, &lf, F_POSIX);
 1999                 }
 2000                 fdtol = td->td_proc->p_fdtol;
 2001                 if (fdtol != NULL) {
 2002                         /*
 2003                          * Handle special case where file descriptor table is
 2004                          * shared between multiple process leaders.
 2005                          */
 2006                         fdp = td->td_proc->p_fd;
 2007                         FILEDESC_XLOCK(fdp);
 2008                         for (fdtol = fdtol->fdl_next;
 2009                              fdtol != td->td_proc->p_fdtol;
 2010                              fdtol = fdtol->fdl_next) {
 2011                                 if ((fdtol->fdl_leader->p_flag &
 2012                                      P_ADVLOCK) == 0)
 2013                                         continue;
 2014                                 fdtol->fdl_holdcount++;
 2015                                 FILEDESC_XUNLOCK(fdp);
 2016                                 lf.l_whence = SEEK_SET;
 2017                                 lf.l_start = 0;
 2018                                 lf.l_len = 0;
 2019                                 lf.l_type = F_UNLCK;
 2020                                 vp = fp->f_vnode;
 2021                                 (void) VOP_ADVLOCK(vp,
 2022                                                    (caddr_t)fdtol->fdl_leader,
 2023                                                    F_UNLCK, &lf, F_POSIX);
 2024                                 FILEDESC_XLOCK(fdp);
 2025                                 fdtol->fdl_holdcount--;
 2026                                 if (fdtol->fdl_holdcount == 0 &&
 2027                                     fdtol->fdl_wakeup != 0) {
 2028                                         fdtol->fdl_wakeup = 0;
 2029                                         wakeup(fdtol);
 2030                                 }
 2031                         }
 2032                         FILEDESC_XUNLOCK(fdp);
 2033                 }
 2034                 VFS_UNLOCK_GIANT(vfslocked);
 2035         }
 2036         return (fdrop(fp, td));
 2037 }
 2038 
 2039 /*
 2040  * Extract the file pointer associated with the specified descriptor for the
 2041  * current user process.
 2042  *
 2043  * If the descriptor doesn't exist, EBADF is returned.
 2044  *
 2045  * If the descriptor exists but doesn't match 'flags' then return EBADF for
 2046  * read attempts and EINVAL for write attempts.
 2047  *
 2048  * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
 2049  * It should be dropped with fdrop().  If it is not set, then the refcount
 2050  * will not be bumped however the thread's filedesc struct will be returned
 2051  * locked (for fgetsock).
 2052  *
 2053  * If an error occured the non-zero error is returned and *fpp is set to
 2054  * NULL.  Otherwise *fpp is set and zero is returned.
 2055  */
 2056 static __inline int
 2057 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
 2058 {
 2059         struct filedesc *fdp;
 2060         struct file *fp;
 2061 
 2062         *fpp = NULL;
 2063         if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
 2064                 return (EBADF);
 2065         FILEDESC_SLOCK(fdp);
 2066         if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
 2067                 FILEDESC_SUNLOCK(fdp);
 2068                 return (EBADF);
 2069         }
 2070 
 2071         /*
 2072          * FREAD and FWRITE failure return EBADF as per POSIX.
 2073          *
 2074          * Only one flag, or 0, may be specified.
 2075          */
 2076         if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
 2077                 FILEDESC_SUNLOCK(fdp);
 2078                 return (EBADF);
 2079         }
 2080         if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
 2081                 FILEDESC_SUNLOCK(fdp);
 2082                 return (EBADF);
 2083         }
 2084         if (hold) {
 2085                 fhold(fp);
 2086                 FILEDESC_SUNLOCK(fdp);
 2087         }
 2088         *fpp = fp;
 2089         return (0);
 2090 }
 2091 
 2092 int
 2093 fget(struct thread *td, int fd, struct file **fpp)
 2094 {
 2095 
 2096         return(_fget(td, fd, fpp, 0, 1));
 2097 }
 2098 
 2099 int
 2100 fget_read(struct thread *td, int fd, struct file **fpp)
 2101 {
 2102 
 2103         return(_fget(td, fd, fpp, FREAD, 1));
 2104 }
 2105 
 2106 int
 2107 fget_write(struct thread *td, int fd, struct file **fpp)
 2108 {
 2109 
 2110         return(_fget(td, fd, fpp, FWRITE, 1));
 2111 }
 2112 
 2113 /*
 2114  * Like fget() but loads the underlying vnode, or returns an error if the
 2115  * descriptor does not represent a vnode.  Note that pipes use vnodes but
 2116  * never have VM objects.  The returned vnode will be vref()'d.
 2117  *
 2118  * XXX: what about the unused flags ?
 2119  */
 2120 static __inline int
 2121 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
 2122 {
 2123         struct file *fp;
 2124         int error;
 2125 
 2126         *vpp = NULL;
 2127         if ((error = _fget(td, fd, &fp, flags, 0)) != 0)
 2128                 return (error);
 2129         if (fp->f_vnode == NULL) {
 2130                 error = EINVAL;
 2131         } else {
 2132                 *vpp = fp->f_vnode;
 2133                 vref(*vpp);
 2134         }
 2135         FILEDESC_SUNLOCK(td->td_proc->p_fd);
 2136         return (error);
 2137 }
 2138 
 2139 int
 2140 fgetvp(struct thread *td, int fd, struct vnode **vpp)
 2141 {
 2142 
 2143         return (_fgetvp(td, fd, vpp, 0));
 2144 }
 2145 
 2146 int
 2147 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
 2148 {
 2149 
 2150         return (_fgetvp(td, fd, vpp, FREAD));
 2151 }
 2152 
 2153 #ifdef notyet
 2154 int
 2155 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
 2156 {
 2157 
 2158         return (_fgetvp(td, fd, vpp, FWRITE));
 2159 }
 2160 #endif
 2161 
 2162 /*
 2163  * Like fget() but loads the underlying socket, or returns an error if the
 2164  * descriptor does not represent a socket.
 2165  *
 2166  * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
 2167  * in the future.
 2168  *
 2169  * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
 2170  * on their file descriptor reference to prevent the socket from being free'd
 2171  * during use.
 2172  */
 2173 int
 2174 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
 2175 {
 2176         struct file *fp;
 2177         int error;
 2178 
 2179         *spp = NULL;
 2180         if (fflagp != NULL)
 2181                 *fflagp = 0;
 2182         if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
 2183                 return (error);
 2184         if (fp->f_type != DTYPE_SOCKET) {
 2185                 error = ENOTSOCK;
 2186         } else {
 2187                 *spp = fp->f_data;
 2188                 if (fflagp)
 2189                         *fflagp = fp->f_flag;
 2190                 SOCK_LOCK(*spp);
 2191                 soref(*spp);
 2192                 SOCK_UNLOCK(*spp);
 2193         }
 2194         FILEDESC_SUNLOCK(td->td_proc->p_fd);
 2195         return (error);
 2196 }
 2197 
 2198 /*
 2199  * Drop the reference count on the socket and XXX release the SX lock in the
 2200  * future.  The last reference closes the socket.
 2201  *
 2202  * Note: fputsock() is deprecated, see comment for fgetsock().
 2203  */
 2204 void
 2205 fputsock(struct socket *so)
 2206 {
 2207 
 2208         ACCEPT_LOCK();
 2209         SOCK_LOCK(so);
 2210         sorele(so);
 2211 }
 2212 
 2213 int
 2214 fdrop(struct file *fp, struct thread *td)
 2215 {
 2216 
 2217         FILE_LOCK(fp);
 2218         return (fdrop_locked(fp, td));
 2219 }
 2220 
 2221 /*
 2222  * Drop reference on struct file passed in, may call closef if the
 2223  * reference hits zero.
 2224  * Expects struct file locked, and will unlock it.
 2225  */
 2226 static int
 2227 fdrop_locked(struct file *fp, struct thread *td)
 2228 {
 2229         int error;
 2230 
 2231         FILE_LOCK_ASSERT(fp, MA_OWNED);
 2232 
 2233         if (--fp->f_count > 0) {
 2234                 FILE_UNLOCK(fp);
 2235                 return (0);
 2236         }
 2237 
 2238         /*
 2239          * We might have just dropped the last reference to a file
 2240          * object that is for a UNIX domain socket whose message
 2241          * buffers are being examined in unp_gc().  If that is the
 2242          * case, FWAIT will be set in f_gcflag and we need to wait for
 2243          * unp_gc() to finish its scan.
 2244          */
 2245         while (fp->f_gcflag & FWAIT)
 2246                 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
 2247 
 2248         /* We have the last ref so we can proceed without the file lock. */
 2249         FILE_UNLOCK(fp);
 2250         if (fp->f_count < 0)
 2251                 panic("fdrop: count < 0");
 2252         if (fp->f_ops != &badfileops)
 2253                 error = fo_close(fp, td);
 2254         else
 2255                 error = 0;
 2256 
 2257         sx_xlock(&filelist_lock);
 2258         LIST_REMOVE(fp, f_list);
 2259         openfiles--;
 2260         sx_xunlock(&filelist_lock);
 2261 
 2262         /*
 2263          * The f_cdevpriv cannot be assigned non-NULL value while we
 2264          * are destroying the file.
 2265          */
 2266         if (fp->f_cdevpriv != NULL)
 2267                 devfs_fpdrop(fp);
 2268         crfree(fp->f_cred);
 2269         uma_zfree(file_zone, fp);
 2270 
 2271         return (error);
 2272 }
 2273 
 2274 /*
 2275  * Apply an advisory lock on a file descriptor.
 2276  *
 2277  * Just attempt to get a record lock of the requested type on the entire file
 2278  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
 2279  */
 2280 #ifndef _SYS_SYSPROTO_H_
 2281 struct flock_args {
 2282         int     fd;
 2283         int     how;
 2284 };
 2285 #endif
 2286 /* ARGSUSED */
 2287 int
 2288 flock(struct thread *td, struct flock_args *uap)
 2289 {
 2290         struct file *fp;
 2291         struct vnode *vp;
 2292         struct flock lf;
 2293         int vfslocked;
 2294         int error;
 2295 
 2296         if ((error = fget(td, uap->fd, &fp)) != 0)
 2297                 return (error);
 2298         if (fp->f_type != DTYPE_VNODE) {
 2299                 fdrop(fp, td);
 2300                 return (EOPNOTSUPP);
 2301         }
 2302 
 2303         vp = fp->f_vnode;
 2304         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2305         lf.l_whence = SEEK_SET;
 2306         lf.l_start = 0;
 2307         lf.l_len = 0;
 2308         if (uap->how & LOCK_UN) {
 2309                 lf.l_type = F_UNLCK;
 2310                 FILE_LOCK(fp);
 2311                 fp->f_flag &= ~FHASLOCK;
 2312                 FILE_UNLOCK(fp);
 2313                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
 2314                 goto done2;
 2315         }
 2316         if (uap->how & LOCK_EX)
 2317                 lf.l_type = F_WRLCK;
 2318         else if (uap->how & LOCK_SH)
 2319                 lf.l_type = F_RDLCK;
 2320         else {
 2321                 error = EBADF;
 2322                 goto done2;
 2323         }
 2324         FILE_LOCK(fp);
 2325         fp->f_flag |= FHASLOCK;
 2326         FILE_UNLOCK(fp);
 2327         error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
 2328             (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
 2329 done2:
 2330         fdrop(fp, td);
 2331         VFS_UNLOCK_GIANT(vfslocked);
 2332         return (error);
 2333 }
 2334 /*
 2335  * Duplicate the specified descriptor to a free descriptor.
 2336  */
 2337 int
 2338 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
 2339 {
 2340         struct file *wfp;
 2341         struct file *fp;
 2342 
 2343         /*
 2344          * If the to-be-dup'd fd number is greater than the allowed number
 2345          * of file descriptors, or the fd to be dup'd has already been
 2346          * closed, then reject.
 2347          */
 2348         FILEDESC_XLOCK(fdp);
 2349         if (dfd < 0 || dfd >= fdp->fd_nfiles ||
 2350             (wfp = fdp->fd_ofiles[dfd]) == NULL) {
 2351                 FILEDESC_XUNLOCK(fdp);
 2352                 return (EBADF);
 2353         }
 2354 
 2355         /*
 2356          * There are two cases of interest here.
 2357          *
 2358          * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
 2359          *
 2360          * For ENXIO steal away the file structure from (dfd) and store it in
 2361          * (indx).  (dfd) is effectively closed by this operation.
 2362          *
 2363          * Any other error code is just returned.
 2364          */
 2365         switch (error) {
 2366         case ENODEV:
 2367                 /*
 2368                  * Check that the mode the file is being opened for is a
 2369                  * subset of the mode of the existing descriptor.
 2370                  */
 2371                 FILE_LOCK(wfp);
 2372                 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
 2373                         FILE_UNLOCK(wfp);
 2374                         FILEDESC_XUNLOCK(fdp);
 2375                         return (EACCES);
 2376                 }
 2377                 fp = fdp->fd_ofiles[indx];
 2378                 fdp->fd_ofiles[indx] = wfp;
 2379                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
 2380                 if (fp == NULL)
 2381                         fdused(fdp, indx);
 2382                 fhold_locked(wfp);
 2383                 FILE_UNLOCK(wfp);
 2384                 FILEDESC_XUNLOCK(fdp);
 2385                 if (fp != NULL)
 2386                         /*
 2387                          * We now own the reference to fp that the ofiles[]
 2388                          * array used to own.  Release it.
 2389                          */
 2390                         fdrop(fp, td);
 2391                 return (0);
 2392 
 2393         case ENXIO:
 2394                 /*
 2395                  * Steal away the file pointer from dfd and stuff it into indx.
 2396                  */
 2397                 fp = fdp->fd_ofiles[indx];
 2398                 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
 2399                 fdp->fd_ofiles[dfd] = NULL;
 2400                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
 2401                 fdp->fd_ofileflags[dfd] = 0;
 2402                 fdunused(fdp, dfd);
 2403                 if (fp == NULL)
 2404                         fdused(fdp, indx);
 2405                 FILEDESC_XUNLOCK(fdp);
 2406 
 2407                 /*
 2408                  * We now own the reference to fp that the ofiles[] array
 2409                  * used to own.  Release it.
 2410                  */
 2411                 if (fp != NULL)
 2412                         fdrop(fp, td);
 2413                 return (0);
 2414 
 2415         default:
 2416                 FILEDESC_XUNLOCK(fdp);
 2417                 return (error);
 2418         }
 2419         /* NOTREACHED */
 2420 }
 2421 
 2422 /*
 2423  * Scan all active processes to see if any of them have a current or root
 2424  * directory of `olddp'. If so, replace them with the new mount point.
 2425  */
 2426 void
 2427 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
 2428 {
 2429         struct filedesc *fdp;
 2430         struct proc *p;
 2431         int nrele;
 2432 
 2433         if (vrefcnt(olddp) == 1)
 2434                 return;
 2435         sx_slock(&allproc_lock);
 2436         FOREACH_PROC_IN_SYSTEM(p) {
 2437                 fdp = fdhold(p);
 2438                 if (fdp == NULL)
 2439                         continue;
 2440                 nrele = 0;
 2441                 FILEDESC_XLOCK(fdp);
 2442                 if (fdp->fd_cdir == olddp) {
 2443                         vref(newdp);
 2444                         fdp->fd_cdir = newdp;
 2445                         nrele++;
 2446                 }
 2447                 if (fdp->fd_rdir == olddp) {
 2448                         vref(newdp);
 2449                         fdp->fd_rdir = newdp;
 2450                         nrele++;
 2451                 }
 2452                 FILEDESC_XUNLOCK(fdp);
 2453                 fddrop(fdp);
 2454                 while (nrele--)
 2455                         vrele(olddp);
 2456         }
 2457         sx_sunlock(&allproc_lock);
 2458         if (rootvnode == olddp) {
 2459                 vrele(rootvnode);
 2460                 vref(newdp);
 2461                 rootvnode = newdp;
 2462         }
 2463 }
 2464 
 2465 struct filedesc_to_leader *
 2466 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
 2467 {
 2468         struct filedesc_to_leader *fdtol;
 2469 
 2470         MALLOC(fdtol, struct filedesc_to_leader *,
 2471                sizeof(struct filedesc_to_leader),
 2472                M_FILEDESC_TO_LEADER,
 2473                M_WAITOK);
 2474         fdtol->fdl_refcount = 1;
 2475         fdtol->fdl_holdcount = 0;
 2476         fdtol->fdl_wakeup = 0;
 2477         fdtol->fdl_leader = leader;
 2478         if (old != NULL) {
 2479                 FILEDESC_XLOCK(fdp);
 2480                 fdtol->fdl_next = old->fdl_next;
 2481                 fdtol->fdl_prev = old;
 2482                 old->fdl_next = fdtol;
 2483                 fdtol->fdl_next->fdl_prev = fdtol;
 2484                 FILEDESC_XUNLOCK(fdp);
 2485         } else {
 2486                 fdtol->fdl_next = fdtol;
 2487                 fdtol->fdl_prev = fdtol;
 2488         }
 2489         return (fdtol);
 2490 }
 2491 
 2492 /*
 2493  * Get file structures globally.
 2494  */
 2495 static int
 2496 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
 2497 {
 2498         struct xfile xf;
 2499         struct filedesc *fdp;
 2500         struct file *fp;
 2501         struct proc *p;
 2502         int error, n;
 2503 
 2504         /*
 2505          * Note: because the number of file descriptors is calculated
 2506          * in different ways for sizing vs returning the data,
 2507          * there is information leakage from the first loop.  However,
 2508          * it is of a similar order of magnitude to the leakage from
 2509          * global system statistics such as kern.openfiles.
 2510          */
 2511         error = sysctl_wire_old_buffer(req, 0);
 2512         if (error != 0)
 2513                 return (error);
 2514         if (req->oldptr == NULL) {
 2515                 n = 16;         /* A slight overestimate. */
 2516                 sx_slock(&filelist_lock);
 2517                 LIST_FOREACH(fp, &filehead, f_list) {
 2518                         /*
 2519                          * We should grab the lock, but this is an
 2520                          * estimate, so does it really matter?
 2521                          */
 2522                         /* mtx_lock(fp->f_mtxp); */
 2523                         n += fp->f_count;
 2524                         /* mtx_unlock(f->f_mtxp); */
 2525                 }
 2526                 sx_sunlock(&filelist_lock);
 2527                 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
 2528         }
 2529         error = 0;
 2530         bzero(&xf, sizeof(xf));
 2531         xf.xf_size = sizeof(xf);
 2532         sx_slock(&allproc_lock);
 2533         FOREACH_PROC_IN_SYSTEM(p) {
 2534                 if (p->p_state == PRS_NEW)
 2535                         continue;
 2536                 PROC_LOCK(p);
 2537                 if (p_cansee(req->td, p) != 0) {
 2538                         PROC_UNLOCK(p);
 2539                         continue;
 2540                 }
 2541                 xf.xf_pid = p->p_pid;
 2542                 xf.xf_uid = p->p_ucred->cr_uid;
 2543                 PROC_UNLOCK(p);
 2544                 fdp = fdhold(p);
 2545                 if (fdp == NULL)
 2546                         continue;
 2547                 FILEDESC_SLOCK(fdp);
 2548                 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
 2549                         if ((fp = fdp->fd_ofiles[n]) == NULL)
 2550                                 continue;
 2551                         xf.xf_fd = n;
 2552                         xf.xf_file = fp;
 2553                         xf.xf_data = fp->f_data;
 2554                         xf.xf_vnode = fp->f_vnode;
 2555                         xf.xf_type = fp->f_type;
 2556                         xf.xf_count = fp->f_count;
 2557                         xf.xf_msgcount = fp->f_msgcount;
 2558                         xf.xf_offset = fp->f_offset;
 2559                         xf.xf_flag = fp->f_flag;
 2560                         error = SYSCTL_OUT(req, &xf, sizeof(xf));
 2561                         if (error)
 2562                                 break;
 2563                 }
 2564                 FILEDESC_SUNLOCK(fdp);
 2565                 fddrop(fdp);
 2566                 if (error)
 2567                         break;
 2568         }
 2569         sx_sunlock(&allproc_lock);
 2570         return (error);
 2571 }
 2572 
 2573 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
 2574     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
 2575 
 2576 #ifdef KINFO_OFILE_SIZE
 2577 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
 2578 #endif
 2579 
 2580 /* Compatability with early 7-stable */
 2581 static int
 2582 export_vnode_for_osysctl(struct vnode *vp, int type,
 2583     struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
 2584 {
 2585         int error;
 2586         char *fullpath, *freepath;
 2587         int vfslocked;
 2588 
 2589         bzero(kif, sizeof(*kif));
 2590         kif->kf_structsize = sizeof(*kif);
 2591 
 2592         vref(vp);
 2593         kif->kf_fd = type;
 2594         kif->kf_type = KF_TYPE_VNODE;
 2595         /* This function only handles directories. */
 2596         KASSERT(vp->v_type == VDIR, ("export_vnode_for_osysctl: vnode not directory"));
 2597         kif->kf_vnode_type = KF_VTYPE_VDIR;
 2598 
 2599         /*
 2600          * This is not a true file descriptor, so we set a bogus refcount
 2601          * and offset to indicate these fields should be ignored.
 2602          */
 2603         kif->kf_ref_count = -1;
 2604         kif->kf_offset = -1;
 2605 
 2606         freepath = NULL;
 2607         fullpath = "-";
 2608         FILEDESC_SUNLOCK(fdp);
 2609         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2610         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
 2611         vn_fullpath(curthread, vp, &fullpath, &freepath);
 2612         vput(vp);
 2613         VFS_UNLOCK_GIANT(vfslocked);
 2614         strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
 2615         if (freepath != NULL)
 2616                 free(freepath, M_TEMP);
 2617         error = SYSCTL_OUT(req, kif, sizeof(*kif));
 2618         FILEDESC_SLOCK(fdp);
 2619         return (error);
 2620 }
 2621 
 2622 /*
 2623  * Get per-process file descriptors for use by procstat(1), et al.
 2624  */
 2625 static int
 2626 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
 2627 {
 2628         char *fullpath, *freepath;
 2629         struct kinfo_ofile *kif;
 2630         struct filedesc *fdp;
 2631         int error, i, *name;
 2632         struct socket *so;
 2633         struct vnode *vp;
 2634         struct file *fp;
 2635         struct proc *p;
 2636         int vfslocked;
 2637 
 2638         name = (int *)arg1;
 2639         if ((p = pfind((pid_t)name[0])) == NULL)
 2640                 return (ESRCH);
 2641         if ((error = p_candebug(curthread, p))) {
 2642                 PROC_UNLOCK(p);
 2643                 return (error);
 2644         }
 2645         fdp = fdhold(p);
 2646         PROC_UNLOCK(p);
 2647         if (fdp == NULL)
 2648                 return (ENOENT);
 2649         kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
 2650         FILEDESC_SLOCK(fdp);
 2651         if (fdp->fd_cdir != NULL)
 2652                 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
 2653                                 fdp, req);
 2654         if (fdp->fd_rdir != NULL)
 2655                 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
 2656                                 fdp, req);
 2657         if (fdp->fd_jdir != NULL)
 2658                 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
 2659                                 fdp, req);
 2660         for (i = 0; i < fdp->fd_nfiles; i++) {
 2661                 if ((fp = fdp->fd_ofiles[i]) == NULL)
 2662                         continue;
 2663                 bzero(kif, sizeof(*kif));
 2664                 kif->kf_structsize = sizeof(*kif);
 2665                 FILE_LOCK(fp);
 2666                 vp = NULL;
 2667                 so = NULL;
 2668                 kif->kf_fd = i;
 2669                 switch (fp->f_type) {
 2670                 case DTYPE_VNODE:
 2671                         kif->kf_type = KF_TYPE_VNODE;
 2672                         vp = fp->f_vnode;
 2673                         vref(vp);
 2674                         break;
 2675 
 2676                 case DTYPE_SOCKET:
 2677                         kif->kf_type = KF_TYPE_SOCKET;
 2678                         so = fp->f_data;
 2679                         break;
 2680 
 2681                 case DTYPE_PIPE:
 2682                         kif->kf_type = KF_TYPE_PIPE;
 2683                         break;
 2684 
 2685                 case DTYPE_FIFO:
 2686                         kif->kf_type = KF_TYPE_FIFO;
 2687                         vp = fp->f_vnode;
 2688                         vref(vp);
 2689                         break;
 2690 
 2691                 case DTYPE_KQUEUE:
 2692                         kif->kf_type = KF_TYPE_KQUEUE;
 2693                         break;
 2694 
 2695                 case DTYPE_CRYPTO:
 2696                         kif->kf_type = KF_TYPE_CRYPTO;
 2697                         break;
 2698 
 2699                 case DTYPE_MQUEUE:
 2700                         kif->kf_type = KF_TYPE_MQUEUE;
 2701                         break;
 2702 
 2703                 default:
 2704                         kif->kf_type = KF_TYPE_UNKNOWN;
 2705                         break;
 2706                 }
 2707                 kif->kf_ref_count = fp->f_count;
 2708                 if (fp->f_flag & FREAD)
 2709                         kif->kf_flags |= KF_FLAG_READ;
 2710                 if (fp->f_flag & FWRITE)
 2711                         kif->kf_flags |= KF_FLAG_WRITE;
 2712                 if (fp->f_flag & FAPPEND)
 2713                         kif->kf_flags |= KF_FLAG_APPEND;
 2714                 if (fp->f_flag & FASYNC)
 2715                         kif->kf_flags |= KF_FLAG_ASYNC;
 2716                 if (fp->f_flag & FFSYNC)
 2717                         kif->kf_flags |= KF_FLAG_FSYNC;
 2718                 if (fp->f_flag & FNONBLOCK)
 2719                         kif->kf_flags |= KF_FLAG_NONBLOCK;
 2720                 if (fp->f_flag & O_DIRECT)
 2721                         kif->kf_flags |= KF_FLAG_DIRECT;
 2722                 if (fp->f_flag & FHASLOCK)
 2723                         kif->kf_flags |= KF_FLAG_HASLOCK;
 2724                 kif->kf_offset = fp->f_offset;
 2725                 FILE_UNLOCK(fp);
 2726                 if (vp != NULL) {
 2727                         switch (vp->v_type) {
 2728                         case VNON:
 2729                                 kif->kf_vnode_type = KF_VTYPE_VNON;
 2730                                 break;
 2731                         case VREG:
 2732                                 kif->kf_vnode_type = KF_VTYPE_VREG;
 2733                                 break;
 2734                         case VDIR:
 2735                                 kif->kf_vnode_type = KF_VTYPE_VDIR;
 2736                                 break;
 2737                         case VBLK:
 2738                                 kif->kf_vnode_type = KF_VTYPE_VBLK;
 2739                                 break;
 2740                         case VCHR:
 2741                                 kif->kf_vnode_type = KF_VTYPE_VCHR;
 2742                                 break;
 2743                         case VLNK:
 2744                                 kif->kf_vnode_type = KF_VTYPE_VLNK;
 2745                                 break;
 2746                         case VSOCK:
 2747                                 kif->kf_vnode_type = KF_VTYPE_VSOCK;
 2748                                 break;
 2749                         case VFIFO:
 2750                                 kif->kf_vnode_type = KF_VTYPE_VFIFO;
 2751                                 break;
 2752                         case VBAD:
 2753                                 kif->kf_vnode_type = KF_VTYPE_VBAD;
 2754                                 break;
 2755                         default:
 2756                                 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
 2757                                 break;
 2758                         }
 2759                         /*
 2760                          * It is OK to drop the filedesc lock here as we will
 2761                          * re-validate and re-evaluate its properties when
 2762                          * the loop continues.
 2763                          */
 2764                         freepath = NULL;
 2765                         fullpath = "-";
 2766                         FILEDESC_SUNLOCK(fdp);
 2767                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2768                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
 2769                         vn_fullpath(curthread, vp, &fullpath, &freepath);
 2770                         vput(vp);
 2771                         VFS_UNLOCK_GIANT(vfslocked);
 2772                         strlcpy(kif->kf_path, fullpath,
 2773                             sizeof(kif->kf_path));
 2774                         if (freepath != NULL)
 2775                                 free(freepath, M_TEMP);
 2776                         FILEDESC_SLOCK(fdp);
 2777                 }
 2778                 if (so != NULL) {
 2779                         struct sockaddr *sa;
 2780 
 2781                         if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
 2782                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
 2783                                 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
 2784                                 free(sa, M_SONAME);
 2785                         }
 2786                         if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
 2787                             == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
 2788                                 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
 2789                                 free(sa, M_SONAME);
 2790                         }
 2791                         kif->kf_sock_domain =
 2792                             so->so_proto->pr_domain->dom_family;
 2793                         kif->kf_sock_type = so->so_type;
 2794                         kif->kf_sock_protocol = so->so_proto->pr_protocol;
 2795                 }
 2796                 error = SYSCTL_OUT(req, kif, sizeof(*kif));
 2797                 if (error)
 2798                         break;
 2799         }
 2800         FILEDESC_SUNLOCK(fdp);
 2801         fddrop(fdp);
 2802         free(kif, M_TEMP);
 2803         return (0);
 2804 }
 2805 
 2806 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
 2807     sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
 2808 
 2809 #ifdef KINFO_FILE_SIZE
 2810 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
 2811 #endif
 2812 
 2813 static int
 2814 export_vnode_for_sysctl(struct vnode *vp, int type,
 2815     struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
 2816 {
 2817         int error;
 2818         char *fullpath, *freepath;
 2819         int vfslocked;
 2820 
 2821         bzero(kif, sizeof(*kif));
 2822 
 2823         vref(vp);
 2824         kif->kf_fd = type;
 2825         kif->kf_type = KF_TYPE_VNODE;
 2826         /* This function only handles directories. */
 2827         KASSERT(vp->v_type == VDIR, ("export_vnode_for_sysctl: vnode not directory"));
 2828         kif->kf_vnode_type = KF_VTYPE_VDIR;
 2829 
 2830         /*
 2831          * This is not a true file descriptor, so we set a bogus refcount
 2832          * and offset to indicate these fields should be ignored.
 2833          */
 2834         kif->kf_ref_count = -1;
 2835         kif->kf_offset = -1;
 2836 
 2837         freepath = NULL;
 2838         fullpath = "-";
 2839         FILEDESC_SUNLOCK(fdp);
 2840         vn_fullpath(curthread, vp, &fullpath, &freepath);
 2841         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 2842         vrele(vp);
 2843         VFS_UNLOCK_GIANT(vfslocked);
 2844         strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
 2845         if (freepath != NULL)
 2846                 free(freepath, M_TEMP);
 2847         /* Pack record size down */
 2848         kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
 2849             strlen(kif->kf_path) + 1;
 2850         kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
 2851         error = SYSCTL_OUT(req, kif, kif->kf_structsize);
 2852         FILEDESC_SLOCK(fdp);
 2853         return (error);
 2854 }
 2855 
 2856 /*
 2857  * Get per-process file descriptors for use by procstat(1), et al.
 2858  */
 2859 static int
 2860 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
 2861 {
 2862         char *fullpath, *freepath;
 2863         struct kinfo_file *kif;
 2864         struct filedesc *fdp;
 2865         int error, i, *name;
 2866         struct socket *so;
 2867         struct vnode *vp;
 2868         struct file *fp;
 2869         struct proc *p;
 2870         int vfslocked;
 2871 
 2872         name = (int *)arg1;
 2873         if ((p = pfind((pid_t)name[0])) == NULL)
 2874                 return (ESRCH);
 2875         if ((error = p_candebug(curthread, p))) {
 2876                 PROC_UNLOCK(p);
 2877                 return (error);
 2878         }
 2879         fdp = fdhold(p);
 2880         PROC_UNLOCK(p);
 2881         if (fdp == NULL)
 2882                 return (ENOENT);
 2883         kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
 2884         FILEDESC_SLOCK(fdp);
 2885         if (fdp->fd_cdir != NULL)
 2886                 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
 2887                                 fdp, req);
 2888         if (fdp->fd_rdir != NULL)
 2889                 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
 2890                                 fdp, req);
 2891         if (fdp->fd_jdir != NULL)
 2892                 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
 2893                                 fdp, req);
 2894         for (i = 0; i < fdp->fd_nfiles; i++) {
 2895                 if ((fp = fdp->fd_ofiles[i]) == NULL)
 2896                         continue;
 2897                 bzero(kif, sizeof(*kif));
 2898                 FILE_LOCK(fp);
 2899                 vp = NULL;
 2900                 so = NULL;
 2901                 kif->kf_fd = i;
 2902                 switch (fp->f_type) {
 2903                 case DTYPE_VNODE:
 2904                         kif->kf_type = KF_TYPE_VNODE;
 2905                         vp = fp->f_vnode;
 2906                         vref(vp);
 2907                         break;
 2908 
 2909                 case DTYPE_SOCKET:
 2910                         kif->kf_type = KF_TYPE_SOCKET;
 2911                         so = fp->f_data;
 2912                         break;
 2913 
 2914                 case DTYPE_PIPE:
 2915                         kif->kf_type = KF_TYPE_PIPE;
 2916                         break;
 2917 
 2918                 case DTYPE_FIFO:
 2919                         kif->kf_type = KF_TYPE_FIFO;
 2920                         vp = fp->f_vnode;
 2921                         vref(vp);
 2922                         break;
 2923 
 2924                 case DTYPE_KQUEUE:
 2925                         kif->kf_type = KF_TYPE_KQUEUE;
 2926                         break;
 2927 
 2928                 case DTYPE_CRYPTO:
 2929                         kif->kf_type = KF_TYPE_CRYPTO;
 2930                         break;
 2931 
 2932                 case DTYPE_MQUEUE:
 2933                         kif->kf_type = KF_TYPE_MQUEUE;
 2934                         break;
 2935 
 2936                 case DTYPE_SEM:
 2937                         kif->kf_type = KF_TYPE_SEM;
 2938                         break;
 2939 
 2940                 default:
 2941                         kif->kf_type = KF_TYPE_UNKNOWN;
 2942                         break;
 2943                 }
 2944                 kif->kf_ref_count = fp->f_count;
 2945                 if (fp->f_flag & FREAD)
 2946                         kif->kf_flags |= KF_FLAG_READ;
 2947                 if (fp->f_flag & FWRITE)
 2948                         kif->kf_flags |= KF_FLAG_WRITE;
 2949                 if (fp->f_flag & FAPPEND)
 2950                         kif->kf_flags |= KF_FLAG_APPEND;
 2951                 if (fp->f_flag & FASYNC)
 2952                         kif->kf_flags |= KF_FLAG_ASYNC;
 2953                 if (fp->f_flag & FFSYNC)
 2954                         kif->kf_flags |= KF_FLAG_FSYNC;
 2955                 if (fp->f_flag & FNONBLOCK)
 2956                         kif->kf_flags |= KF_FLAG_NONBLOCK;
 2957                 if (fp->f_flag & O_DIRECT)
 2958                         kif->kf_flags |= KF_FLAG_DIRECT;
 2959                 if (fp->f_flag & FHASLOCK)
 2960                         kif->kf_flags |= KF_FLAG_HASLOCK;
 2961                 kif->kf_offset = fp->f_offset;
 2962                 FILE_UNLOCK(fp);
 2963                 if (vp != NULL) {
 2964                         switch (vp->v_type) {
 2965                         case VNON:
 2966                                 kif->kf_vnode_type = KF_VTYPE_VNON;
 2967                                 break;
 2968                         case VREG:
 2969                                 kif->kf_vnode_type = KF_VTYPE_VREG;
 2970                                 break;
 2971                         case VDIR:
 2972                                 kif->kf_vnode_type = KF_VTYPE_VDIR;
 2973                                 break;
 2974                         case VBLK:
 2975                                 kif->kf_vnode_type = KF_VTYPE_VBLK;
 2976                                 break;
 2977                         case VCHR:
 2978                                 kif->kf_vnode_type = KF_VTYPE_VCHR;
 2979                                 break;
 2980                         case VLNK:
 2981                                 kif->kf_vnode_type = KF_VTYPE_VLNK;
 2982                                 break;
 2983                         case VSOCK:
 2984                                 kif->kf_vnode_type = KF_VTYPE_VSOCK;
 2985                                 break;
 2986                         case VFIFO:
 2987                                 kif->kf_vnode_type = KF_VTYPE_VFIFO;
 2988                                 break;
 2989                         case VBAD:
 2990                                 kif->kf_vnode_type = KF_VTYPE_VBAD;
 2991                                 break;
 2992                         default:
 2993                                 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
 2994                                 break;
 2995                         }
 2996                         /*
 2997                          * It is OK to drop the filedesc lock here as we will
 2998                          * re-validate and re-evaluate its properties when
 2999                          * the loop continues.
 3000                          */
 3001                         freepath = NULL;
 3002                         fullpath = "-";
 3003                         FILEDESC_SUNLOCK(fdp);
 3004                         vn_fullpath(curthread, vp, &fullpath, &freepath);
 3005                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
 3006                         vrele(vp);
 3007                         VFS_UNLOCK_GIANT(vfslocked);
 3008                         strlcpy(kif->kf_path, fullpath,
 3009                             sizeof(kif->kf_path));
 3010                         if (freepath != NULL)
 3011                                 free(freepath, M_TEMP);
 3012                         FILEDESC_SLOCK(fdp);
 3013                 }
 3014                 if (so != NULL) {
 3015                         struct sockaddr *sa;
 3016 
 3017                         if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
 3018                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
 3019                                 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
 3020                                 free(sa, M_SONAME);
 3021                         }
 3022                         if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
 3023                             == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
 3024                                 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
 3025                                 free(sa, M_SONAME);
 3026                         }
 3027                         kif->kf_sock_domain =
 3028                             so->so_proto->pr_domain->dom_family;
 3029                         kif->kf_sock_type = so->so_type;
 3030                         kif->kf_sock_protocol = so->so_proto->pr_protocol;
 3031                 }
 3032                 /* Pack record size down */
 3033                 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
 3034                     strlen(kif->kf_path) + 1;
 3035                 kif->kf_structsize = roundup(kif->kf_structsize,
 3036                     sizeof(uint64_t));
 3037                 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
 3038                 if (error)
 3039                         break;
 3040         }
 3041         FILEDESC_SUNLOCK(fdp);
 3042         fddrop(fdp);
 3043         free(kif, M_TEMP);
 3044         return (0);
 3045 }
 3046 
 3047 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
 3048     sysctl_kern_proc_filedesc, "Process filedesc entries");
 3049 
 3050 #ifdef DDB
 3051 /*
 3052  * For the purposes of debugging, generate a human-readable string for the
 3053  * file type.
 3054  */
 3055 static const char *
 3056 file_type_to_name(short type)
 3057 {
 3058 
 3059         switch (type) {
 3060         case 0:
 3061                 return ("zero");
 3062         case DTYPE_VNODE:
 3063                 return ("vnod");
 3064         case DTYPE_SOCKET:
 3065                 return ("sock");
 3066         case DTYPE_PIPE:
 3067                 return ("pipe");
 3068         case DTYPE_FIFO:
 3069                 return ("fifo");
 3070         case DTYPE_KQUEUE:
 3071                 return ("kque");
 3072         case DTYPE_CRYPTO:
 3073                 return ("crpt");
 3074         case DTYPE_MQUEUE:
 3075                 return ("mque");
 3076         case DTYPE_SEM:
 3077                 return ("ksem");
 3078         default:
 3079                 return ("unkn");
 3080         }
 3081 }
 3082 
 3083 /*
 3084  * For the purposes of debugging, identify a process (if any, perhaps one of
 3085  * many) that references the passed file in its file descriptor array. Return
 3086  * NULL if none.
 3087  */
 3088 static struct proc *
 3089 file_to_first_proc(struct file *fp)
 3090 {
 3091         struct filedesc *fdp;
 3092         struct proc *p;
 3093         int n;
 3094 
 3095         FOREACH_PROC_IN_SYSTEM(p) {
 3096                 if (p->p_state == PRS_NEW)
 3097                         continue;
 3098                 fdp = p->p_fd;
 3099                 if (fdp == NULL)
 3100                         continue;
 3101                 for (n = 0; n < fdp->fd_nfiles; n++) {
 3102                         if (fp == fdp->fd_ofiles[n])
 3103                                 return (p);
 3104                 }
 3105         }
 3106         return (NULL);
 3107 }
 3108 
 3109 static void
 3110 db_print_file(struct file *fp, int header)
 3111 {
 3112         struct proc *p;
 3113 
 3114         if (header)
 3115                 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
 3116                     "File", "Type", "Data", "Flag", "GCFl", "Count",
 3117                     "MCount", "Vnode", "FPID", "FCmd");
 3118         p = file_to_first_proc(fp);
 3119         db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
 3120             file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
 3121             fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
 3122             p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
 3123 }
 3124 
 3125 DB_SHOW_COMMAND(file, db_show_file)
 3126 {
 3127         struct file *fp;
 3128 
 3129         if (!have_addr) {
 3130                 db_printf("usage: show file <addr>\n");
 3131                 return;
 3132         }
 3133         fp = (struct file *)addr;
 3134         db_print_file(fp, 1);
 3135 }
 3136 
 3137 DB_SHOW_COMMAND(files, db_show_files)
 3138 {
 3139         struct file *fp;
 3140         int header;
 3141 
 3142         header = 1;
 3143         LIST_FOREACH(fp, &filehead, f_list) {
 3144                 db_print_file(fp, header);
 3145                 header = 0;
 3146         }
 3147 }
 3148 #endif
 3149 
 3150 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
 3151     &maxfilesperproc, 0, "Maximum files allowed open per process");
 3152 
 3153 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
 3154     &maxfiles, 0, "Maximum number of files");
 3155 
 3156 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
 3157     &openfiles, 0, "System-wide number of open files");
 3158 
 3159 /* ARGSUSED*/
 3160 static void
 3161 filelistinit(void *dummy)
 3162 {
 3163 
 3164         file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
 3165             NULL, NULL, UMA_ALIGN_PTR, 0);
 3166         sx_init(&filelist_lock, "filelist lock");
 3167         mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
 3168         mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
 3169 }
 3170 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
 3171 
 3172 /*-------------------------------------------------------------------*/
 3173 
 3174 static int
 3175 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
 3176 {
 3177 
 3178         return (EBADF);
 3179 }
 3180 
 3181 static int
 3182 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
 3183 {
 3184 
 3185         return (EBADF);
 3186 }
 3187 
 3188 static int
 3189 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
 3190 {
 3191 
 3192         return (0);
 3193 }
 3194 
 3195 static int
 3196 badfo_kqfilter(struct file *fp, struct knote *kn)
 3197 {
 3198 
 3199         return (EBADF);
 3200 }
 3201 
 3202 static int
 3203 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
 3204 {
 3205 
 3206         return (EBADF);
 3207 }
 3208 
 3209 static int
 3210 badfo_close(struct file *fp, struct thread *td)
 3211 {
 3212 
 3213         return (EBADF);
 3214 }
 3215 
 3216 struct fileops badfileops = {
 3217         .fo_read = badfo_readwrite,
 3218         .fo_write = badfo_readwrite,
 3219         .fo_ioctl = badfo_ioctl,
 3220         .fo_poll = badfo_poll,
 3221         .fo_kqfilter = badfo_kqfilter,
 3222         .fo_stat = badfo_stat,
 3223         .fo_close = badfo_close,
 3224 };
 3225 
 3226 
 3227 /*-------------------------------------------------------------------*/
 3228 
 3229 /*
 3230  * File Descriptor pseudo-device driver (/dev/fd/).
 3231  *
 3232  * Opening minor device N dup()s the file (if any) connected to file
 3233  * descriptor N belonging to the calling process.  Note that this driver
 3234  * consists of only the ``open()'' routine, because all subsequent
 3235  * references to this file will be direct to the other driver.
 3236  *
 3237  * XXX: we could give this one a cloning event handler if necessary.
 3238  */
 3239 
 3240 /* ARGSUSED */
 3241 static int
 3242 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
 3243 {
 3244 
 3245         /*
 3246          * XXX Kludge: set curthread->td_dupfd to contain the value of the
 3247          * the file descriptor being sought for duplication. The error
 3248          * return ensures that the vnode for this device will be released
 3249          * by vn_open. Open will detect this special error and take the
 3250          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
 3251          * will simply report the error.
 3252          */
 3253         td->td_dupfd = dev2unit(dev);
 3254         return (ENODEV);
 3255 }
 3256 
 3257 static struct cdevsw fildesc_cdevsw = {
 3258         .d_version =    D_VERSION,
 3259         .d_flags =      D_NEEDGIANT,
 3260         .d_open =       fdopen,
 3261         .d_name =       "FD",
 3262 };
 3263 
 3264 static void
 3265 fildesc_drvinit(void *unused)
 3266 {
 3267         struct cdev *dev;
 3268 
 3269         dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
 3270         make_dev_alias(dev, "stdin");
 3271         dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
 3272         make_dev_alias(dev, "stdout");
 3273         dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
 3274         make_dev_alias(dev, "stderr");
 3275 }
 3276 
 3277 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);

Cache object: 7d789c36477112c279cd036639840e44


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