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


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

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

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

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

Cache object: 10d4578afea74e29b51732b1856c32b2


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