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

Cache object: 8a26dd90496fe31203c49c4df508506e


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