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/vfs_subr.c

Version: -  FREEBSD  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1989, 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  *      @(#)vfs_subr.c  8.31 (Berkeley) 5/26/95
   35  */
   36 
   37 /*
   38  * External virtual filesystem routines
   39  */
   40 
   41 #include <sys/cdefs.h>
   42 __FBSDID("$FreeBSD: stable/11/sys/kern/vfs_subr.c 354169 2019-10-30 08:06:22Z kib $");
   43 
   44 #include "opt_compat.h"
   45 #include "opt_ddb.h"
   46 #include "opt_watchdog.h"
   47 
   48 #include <sys/param.h>
   49 #include <sys/systm.h>
   50 #include <sys/bio.h>
   51 #include <sys/buf.h>
   52 #include <sys/capsicum.h>
   53 #include <sys/condvar.h>
   54 #include <sys/conf.h>
   55 #include <sys/counter.h>
   56 #include <sys/dirent.h>
   57 #include <sys/event.h>
   58 #include <sys/eventhandler.h>
   59 #include <sys/extattr.h>
   60 #include <sys/file.h>
   61 #include <sys/fcntl.h>
   62 #include <sys/jail.h>
   63 #include <sys/kdb.h>
   64 #include <sys/kernel.h>
   65 #include <sys/kthread.h>
   66 #include <sys/lockf.h>
   67 #include <sys/malloc.h>
   68 #include <sys/mount.h>
   69 #include <sys/namei.h>
   70 #include <sys/pctrie.h>
   71 #include <sys/priv.h>
   72 #include <sys/reboot.h>
   73 #include <sys/refcount.h>
   74 #include <sys/rwlock.h>
   75 #include <sys/sched.h>
   76 #include <sys/sleepqueue.h>
   77 #include <sys/smp.h>
   78 #include <sys/stat.h>
   79 #include <sys/sysctl.h>
   80 #include <sys/syslog.h>
   81 #include <sys/vmmeter.h>
   82 #include <sys/vnode.h>
   83 #include <sys/watchdog.h>
   84 
   85 #include <machine/stdarg.h>
   86 
   87 #include <security/mac/mac_framework.h>
   88 
   89 #include <vm/vm.h>
   90 #include <vm/vm_object.h>
   91 #include <vm/vm_extern.h>
   92 #include <vm/pmap.h>
   93 #include <vm/vm_map.h>
   94 #include <vm/vm_page.h>
   95 #include <vm/vm_kern.h>
   96 #include <vm/uma.h>
   97 
   98 #ifdef DDB
   99 #include <ddb/ddb.h>
  100 #endif
  101 
  102 static void     delmntque(struct vnode *vp);
  103 static int      flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
  104                     int slpflag, int slptimeo);
  105 static void     syncer_shutdown(void *arg, int howto);
  106 static int      vtryrecycle(struct vnode *vp);
  107 static void     v_init_counters(struct vnode *);
  108 static void     v_incr_usecount(struct vnode *);
  109 static void     v_incr_usecount_locked(struct vnode *);
  110 static void     v_incr_devcount(struct vnode *);
  111 static void     v_decr_devcount(struct vnode *);
  112 static void     vgonel(struct vnode *);
  113 static void     vfs_knllock(void *arg);
  114 static void     vfs_knlunlock(void *arg);
  115 static void     vfs_knl_assert_locked(void *arg);
  116 static void     vfs_knl_assert_unlocked(void *arg);
  117 static void     destroy_vpollinfo(struct vpollinfo *vi);
  118 
  119 /*
  120  * These fences are intended for cases where some synchronization is
  121  * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
  122  * and v_usecount) updates.  Access to v_iflags is generally synchronized
  123  * by the interlock, but we have some internal assertions that check vnode
  124  * flags * without acquiring the lock.  Thus, these fences are INVARIANTS-only
  125  * for now.
  126  */
  127 #ifdef INVARIANTS
  128 #define VNODE_REFCOUNT_FENCE_ACQ()      atomic_thread_fence_acq()
  129 #define VNODE_REFCOUNT_FENCE_REL()      atomic_thread_fence_rel()
  130 #else
  131 #define VNODE_REFCOUNT_FENCE_ACQ()
  132 #define VNODE_REFCOUNT_FENCE_REL()
  133 #endif
  134 
  135 /*
  136  * Number of vnodes in existence.  Increased whenever getnewvnode()
  137  * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
  138  */
  139 static unsigned long    numvnodes;
  140 
  141 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
  142     "Number of vnodes in existence");
  143 
  144 static counter_u64_t vnodes_created;
  145 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
  146     "Number of vnodes created by getnewvnode");
  147 
  148 /*
  149  * Conversion tables for conversion from vnode types to inode formats
  150  * and back.
  151  */
  152 enum vtype iftovt_tab[16] = {
  153         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
  154         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
  155 };
  156 int vttoif_tab[10] = {
  157         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
  158         S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
  159 };
  160 
  161 /*
  162  * List of vnodes that are ready for recycling.
  163  */
  164 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
  165 
  166 /*
  167  * "Free" vnode target.  Free vnodes are rarely completely free, but are
  168  * just ones that are cheap to recycle.  Usually they are for files which
  169  * have been stat'd but not read; these usually have inode and namecache
  170  * data attached to them.  This target is the preferred minimum size of a
  171  * sub-cache consisting mostly of such files. The system balances the size
  172  * of this sub-cache with its complement to try to prevent either from
  173  * thrashing while the other is relatively inactive.  The targets express
  174  * a preference for the best balance.
  175  *
  176  * "Above" this target there are 2 further targets (watermarks) related
  177  * to recyling of free vnodes.  In the best-operating case, the cache is
  178  * exactly full, the free list has size between vlowat and vhiwat above the
  179  * free target, and recycling from it and normal use maintains this state.
  180  * Sometimes the free list is below vlowat or even empty, but this state
  181  * is even better for immediate use provided the cache is not full.
  182  * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
  183  * ones) to reach one of these states.  The watermarks are currently hard-
  184  * coded as 4% and 9% of the available space higher.  These and the default
  185  * of 25% for wantfreevnodes are too large if the memory size is large.
  186  * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
  187  * whenever vnlru_proc() becomes active.
  188  */
  189 static u_long wantfreevnodes;
  190 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
  191     &wantfreevnodes, 0, "Target for minimum number of \"free\" vnodes");
  192 static u_long freevnodes;
  193 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
  194     &freevnodes, 0, "Number of \"free\" vnodes");
  195 
  196 static counter_u64_t recycles_count;
  197 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
  198     "Number of vnodes recycled to meet vnode cache targets");
  199 
  200 /*
  201  * Various variables used for debugging the new implementation of
  202  * reassignbuf().
  203  * XXX these are probably of (very) limited utility now.
  204  */
  205 static int reassignbufcalls;
  206 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
  207     "Number of calls to reassignbuf");
  208 
  209 static counter_u64_t free_owe_inact;
  210 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, free_owe_inact, CTLFLAG_RD, &free_owe_inact,
  211     "Number of times free vnodes kept on active list due to VFS "
  212     "owing inactivation");
  213 
  214 /* To keep more than one thread at a time from running vfs_getnewfsid */
  215 static struct mtx mntid_mtx;
  216 
  217 /*
  218  * Lock for any access to the following:
  219  *      vnode_free_list
  220  *      numvnodes
  221  *      freevnodes
  222  */
  223 static struct mtx vnode_free_list_mtx;
  224 
  225 /* Publicly exported FS */
  226 struct nfs_public nfs_pub;
  227 
  228 static uma_zone_t buf_trie_zone;
  229 
  230 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
  231 static uma_zone_t vnode_zone;
  232 static uma_zone_t vnodepoll_zone;
  233 
  234 /*
  235  * The workitem queue.
  236  *
  237  * It is useful to delay writes of file data and filesystem metadata
  238  * for tens of seconds so that quickly created and deleted files need
  239  * not waste disk bandwidth being created and removed. To realize this,
  240  * we append vnodes to a "workitem" queue. When running with a soft
  241  * updates implementation, most pending metadata dependencies should
  242  * not wait for more than a few seconds. Thus, mounted on block devices
  243  * are delayed only about a half the time that file data is delayed.
  244  * Similarly, directory updates are more critical, so are only delayed
  245  * about a third the time that file data is delayed. Thus, there are
  246  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
  247  * one each second (driven off the filesystem syncer process). The
  248  * syncer_delayno variable indicates the next queue that is to be processed.
  249  * Items that need to be processed soon are placed in this queue:
  250  *
  251  *      syncer_workitem_pending[syncer_delayno]
  252  *
  253  * A delay of fifteen seconds is done by placing the request fifteen
  254  * entries later in the queue:
  255  *
  256  *      syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
  257  *
  258  */
  259 static int syncer_delayno;
  260 static long syncer_mask;
  261 LIST_HEAD(synclist, bufobj);
  262 static struct synclist *syncer_workitem_pending;
  263 /*
  264  * The sync_mtx protects:
  265  *      bo->bo_synclist
  266  *      sync_vnode_count
  267  *      syncer_delayno
  268  *      syncer_state
  269  *      syncer_workitem_pending
  270  *      syncer_worklist_len
  271  *      rushjob
  272  */
  273 static struct mtx sync_mtx;
  274 static struct cv sync_wakeup;
  275 
  276 #define SYNCER_MAXDELAY         32
  277 static int syncer_maxdelay = SYNCER_MAXDELAY;   /* maximum delay time */
  278 static int syncdelay = 30;              /* max time to delay syncing data */
  279 static int filedelay = 30;              /* time to delay syncing files */
  280 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
  281     "Time to delay syncing files (in seconds)");
  282 static int dirdelay = 29;               /* time to delay syncing directories */
  283 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
  284     "Time to delay syncing directories (in seconds)");
  285 static int metadelay = 28;              /* time to delay syncing metadata */
  286 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
  287     "Time to delay syncing metadata (in seconds)");
  288 static int rushjob;             /* number of slots to run ASAP */
  289 static int stat_rush_requests;  /* number of times I/O speeded up */
  290 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
  291     "Number of times I/O speeded up (rush requests)");
  292 
  293 /*
  294  * When shutting down the syncer, run it at four times normal speed.
  295  */
  296 #define SYNCER_SHUTDOWN_SPEEDUP         4
  297 static int sync_vnode_count;
  298 static int syncer_worklist_len;
  299 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
  300     syncer_state;
  301 
  302 /* Target for maximum number of vnodes. */
  303 int desiredvnodes;
  304 static int gapvnodes;           /* gap between wanted and desired */
  305 static int vhiwat;              /* enough extras after expansion */
  306 static int vlowat;              /* minimal extras before expansion */
  307 static int vstir;               /* nonzero to stir non-free vnodes */
  308 static volatile int vsmalltrigger = 8;  /* pref to keep if > this many pages */
  309 
  310 static int
  311 sysctl_update_desiredvnodes(SYSCTL_HANDLER_ARGS)
  312 {
  313         int error, old_desiredvnodes;
  314 
  315         old_desiredvnodes = desiredvnodes;
  316         if ((error = sysctl_handle_int(oidp, arg1, arg2, req)) != 0)
  317                 return (error);
  318         if (old_desiredvnodes != desiredvnodes) {
  319                 wantfreevnodes = desiredvnodes / 4;
  320                 /* XXX locking seems to be incomplete. */
  321                 vfs_hash_changesize(desiredvnodes);
  322                 cache_changesize(desiredvnodes);
  323         }
  324         return (0);
  325 }
  326 
  327 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
  328     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, &desiredvnodes, 0,
  329     sysctl_update_desiredvnodes, "I", "Target for maximum number of vnodes");
  330 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
  331     &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
  332 static int vnlru_nowhere;
  333 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
  334     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
  335 
  336 static int
  337 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
  338 {
  339         struct vnode *vp;
  340         struct nameidata nd;
  341         char *buf;
  342         unsigned long ndflags;
  343         int error;
  344 
  345         if (req->newptr == NULL)
  346                 return (EINVAL);
  347         if (req->newlen > PATH_MAX)
  348                 return (E2BIG);
  349 
  350         buf = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
  351         error = SYSCTL_IN(req, buf, req->newlen);
  352         if (error != 0)
  353                 goto out;
  354 
  355         buf[req->newlen] = '\0';
  356 
  357         ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
  358         NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
  359         if ((error = namei(&nd)) != 0)
  360                 goto out;
  361         vp = nd.ni_vp;
  362 
  363         if ((vp->v_iflag & VI_DOOMED) != 0) {
  364                 /*
  365                  * This vnode is being recycled.  Return != 0 to let the caller
  366                  * know that the sysctl had no effect.  Return EAGAIN because a
  367                  * subsequent call will likely succeed (since namei will create
  368                  * a new vnode if necessary)
  369                  */
  370                 error = EAGAIN;
  371                 goto putvnode;
  372         }
  373 
  374         counter_u64_add(recycles_count, 1);
  375         vgone(vp);
  376 putvnode:
  377         NDFREE(&nd, 0);
  378 out:
  379         free(buf, M_TEMP);
  380         return (error);
  381 }
  382 
  383 static int
  384 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
  385 {
  386         struct thread *td = curthread;
  387         struct vnode *vp;
  388         struct file *fp;
  389         cap_rights_t rights;
  390         int error;
  391         int fd;
  392 
  393         if (req->newptr == NULL)
  394                 return (EBADF);
  395 
  396         error = sysctl_handle_int(oidp, &fd, 0, req);
  397         if (error != 0)
  398                 return (error);
  399         cap_rights_init(&rights, CAP_FCNTL);
  400         error = getvnode(curthread, fd, &rights, &fp);
  401         if (error != 0)
  402                 return (error);
  403         vp = fp->f_vnode;
  404 
  405         error = vn_lock(vp, LK_EXCLUSIVE);
  406         if (error != 0)
  407                 goto drop;
  408 
  409         counter_u64_add(recycles_count, 1);
  410         vgone(vp);
  411         VOP_UNLOCK(vp, 0);
  412 drop:
  413         fdrop(fp, td);
  414         return (error);
  415 }
  416 
  417 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
  418     CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
  419     sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
  420 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
  421     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
  422     sysctl_ftry_reclaim_vnode, "I",
  423     "Try to reclaim a vnode by its file descriptor");
  424 
  425 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
  426 static int vnsz2log;
  427 
  428 /*
  429  * Support for the bufobj clean & dirty pctrie.
  430  */
  431 static void *
  432 buf_trie_alloc(struct pctrie *ptree)
  433 {
  434 
  435         return uma_zalloc(buf_trie_zone, M_NOWAIT);
  436 }
  437 
  438 static void
  439 buf_trie_free(struct pctrie *ptree, void *node)
  440 {
  441 
  442         uma_zfree(buf_trie_zone, node);
  443 }
  444 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
  445 
  446 /*
  447  * Initialize the vnode management data structures.
  448  *
  449  * Reevaluate the following cap on the number of vnodes after the physical
  450  * memory size exceeds 512GB.  In the limit, as the physical memory size
  451  * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
  452  */
  453 #ifndef MAXVNODES_MAX
  454 #define MAXVNODES_MAX   (512 * 1024 * 1024 / 64)        /* 8M */
  455 #endif
  456 
  457 /*
  458  * Initialize a vnode as it first enters the zone.
  459  */
  460 static int
  461 vnode_init(void *mem, int size, int flags)
  462 {
  463         struct vnode *vp;
  464         struct bufobj *bo;
  465 
  466         vp = mem;
  467         bzero(vp, size);
  468         /*
  469          * Setup locks.
  470          */
  471         vp->v_vnlock = &vp->v_lock;
  472         mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
  473         /*
  474          * By default, don't allow shared locks unless filesystems opt-in.
  475          */
  476         lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
  477             LK_NOSHARE | LK_IS_VNODE);
  478         /*
  479          * Initialize bufobj.
  480          */
  481         bo = &vp->v_bufobj;
  482         bo->__bo_vnode = vp;
  483         rw_init(BO_LOCKPTR(bo), "bufobj interlock");
  484         bo->bo_private = vp;
  485         TAILQ_INIT(&bo->bo_clean.bv_hd);
  486         TAILQ_INIT(&bo->bo_dirty.bv_hd);
  487         /*
  488          * Initialize namecache.
  489          */
  490         LIST_INIT(&vp->v_cache_src);
  491         TAILQ_INIT(&vp->v_cache_dst);
  492         /*
  493          * Initialize rangelocks.
  494          */
  495         rangelock_init(&vp->v_rl);
  496         return (0);
  497 }
  498 
  499 /*
  500  * Free a vnode when it is cleared from the zone.
  501  */
  502 static void
  503 vnode_fini(void *mem, int size)
  504 {
  505         struct vnode *vp;
  506         struct bufobj *bo;
  507 
  508         vp = mem;
  509         rangelock_destroy(&vp->v_rl);
  510         lockdestroy(vp->v_vnlock);
  511         mtx_destroy(&vp->v_interlock);
  512         bo = &vp->v_bufobj;
  513         rw_destroy(BO_LOCKPTR(bo));
  514 }
  515 
  516 /*
  517  * Provide the size of NFS nclnode and NFS fh for calculation of the
  518  * vnode memory consumption.  The size is specified directly to
  519  * eliminate dependency on NFS-private header.
  520  *
  521  * Other filesystems may use bigger or smaller (like UFS and ZFS)
  522  * private inode data, but the NFS-based estimation is ample enough.
  523  * Still, we care about differences in the size between 64- and 32-bit
  524  * platforms.
  525  *
  526  * Namecache structure size is heuristically
  527  * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
  528  */
  529 #ifdef _LP64
  530 #define NFS_NCLNODE_SZ  (528 + 64)
  531 #define NC_SZ           148
  532 #else
  533 #define NFS_NCLNODE_SZ  (360 + 32)
  534 #define NC_SZ           92
  535 #endif
  536 
  537 static void
  538 vntblinit(void *dummy __unused)
  539 {
  540         u_int i;
  541         int physvnodes, virtvnodes;
  542 
  543         /*
  544          * Desiredvnodes is a function of the physical memory size and the
  545          * kernel's heap size.  Generally speaking, it scales with the
  546          * physical memory size.  The ratio of desiredvnodes to the physical
  547          * memory size is 1:16 until desiredvnodes exceeds 98,304.
  548          * Thereafter, the
  549          * marginal ratio of desiredvnodes to the physical memory size is
  550          * 1:64.  However, desiredvnodes is limited by the kernel's heap
  551          * size.  The memory required by desiredvnodes vnodes and vm objects
  552          * must not exceed 1/10th of the kernel's heap size.
  553          */
  554         physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
  555             3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
  556         virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
  557             sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
  558         desiredvnodes = min(physvnodes, virtvnodes);
  559         if (desiredvnodes > MAXVNODES_MAX) {
  560                 if (bootverbose)
  561                         printf("Reducing kern.maxvnodes %d -> %d\n",
  562                             desiredvnodes, MAXVNODES_MAX);
  563                 desiredvnodes = MAXVNODES_MAX;
  564         }
  565         wantfreevnodes = desiredvnodes / 4;
  566         mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
  567         TAILQ_INIT(&vnode_free_list);
  568         mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
  569         vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
  570             vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
  571         vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
  572             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
  573         /*
  574          * Preallocate enough nodes to support one-per buf so that
  575          * we can not fail an insert.  reassignbuf() callers can not
  576          * tolerate the insertion failure.
  577          */
  578         buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
  579             NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR, 
  580             UMA_ZONE_NOFREE | UMA_ZONE_VM);
  581         uma_prealloc(buf_trie_zone, nbuf);
  582 
  583         vnodes_created = counter_u64_alloc(M_WAITOK);
  584         recycles_count = counter_u64_alloc(M_WAITOK);
  585         free_owe_inact = counter_u64_alloc(M_WAITOK);
  586 
  587         /*
  588          * Initialize the filesystem syncer.
  589          */
  590         syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
  591             &syncer_mask);
  592         syncer_maxdelay = syncer_mask + 1;
  593         mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
  594         cv_init(&sync_wakeup, "syncer");
  595         for (i = 1; i <= sizeof(struct vnode); i <<= 1)
  596                 vnsz2log++;
  597         vnsz2log--;
  598 }
  599 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
  600 
  601 
  602 /*
  603  * Mark a mount point as busy. Used to synchronize access and to delay
  604  * unmounting. Eventually, mountlist_mtx is not released on failure.
  605  *
  606  * vfs_busy() is a custom lock, it can block the caller.
  607  * vfs_busy() only sleeps if the unmount is active on the mount point.
  608  * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
  609  * vnode belonging to mp.
  610  *
  611  * Lookup uses vfs_busy() to traverse mount points.
  612  * root fs                      var fs
  613  * / vnode lock         A       / vnode lock (/var)             D
  614  * /var vnode lock      B       /log vnode lock(/var/log)       E
  615  * vfs_busy lock        C       vfs_busy lock                   F
  616  *
  617  * Within each file system, the lock order is C->A->B and F->D->E.
  618  *
  619  * When traversing across mounts, the system follows that lock order:
  620  *
  621  *        C->A->B
  622  *              |
  623  *              +->F->D->E
  624  *
  625  * The lookup() process for namei("/var") illustrates the process:
  626  *  VOP_LOOKUP() obtains B while A is held
  627  *  vfs_busy() obtains a shared lock on F while A and B are held
  628  *  vput() releases lock on B
  629  *  vput() releases lock on A
  630  *  VFS_ROOT() obtains lock on D while shared lock on F is held
  631  *  vfs_unbusy() releases shared lock on F
  632  *  vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
  633  *    Attempt to lock A (instead of vp_crossmp) while D is held would
  634  *    violate the global order, causing deadlocks.
  635  *
  636  * dounmount() locks B while F is drained.
  637  */
  638 int
  639 vfs_busy(struct mount *mp, int flags)
  640 {
  641 
  642         MPASS((flags & ~MBF_MASK) == 0);
  643         CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
  644 
  645         MNT_ILOCK(mp);
  646         MNT_REF(mp);
  647         /*
  648          * If mount point is currently being unmounted, sleep until the
  649          * mount point fate is decided.  If thread doing the unmounting fails,
  650          * it will clear MNTK_UNMOUNT flag before waking us up, indicating
  651          * that this mount point has survived the unmount attempt and vfs_busy
  652          * should retry.  Otherwise the unmounter thread will set MNTK_REFEXPIRE
  653          * flag in addition to MNTK_UNMOUNT, indicating that mount point is
  654          * about to be really destroyed.  vfs_busy needs to release its
  655          * reference on the mount point in this case and return with ENOENT,
  656          * telling the caller that mount mount it tried to busy is no longer
  657          * valid.
  658          */
  659         while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
  660                 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
  661                         MNT_REL(mp);
  662                         MNT_IUNLOCK(mp);
  663                         CTR1(KTR_VFS, "%s: failed busying before sleeping",
  664                             __func__);
  665                         return (ENOENT);
  666                 }
  667                 if (flags & MBF_MNTLSTLOCK)
  668                         mtx_unlock(&mountlist_mtx);
  669                 mp->mnt_kern_flag |= MNTK_MWAIT;
  670                 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
  671                 if (flags & MBF_MNTLSTLOCK)
  672                         mtx_lock(&mountlist_mtx);
  673                 MNT_ILOCK(mp);
  674         }
  675         if (flags & MBF_MNTLSTLOCK)
  676                 mtx_unlock(&mountlist_mtx);
  677         mp->mnt_lockref++;
  678         MNT_IUNLOCK(mp);
  679         return (0);
  680 }
  681 
  682 /*
  683  * Free a busy filesystem.
  684  */
  685 void
  686 vfs_unbusy(struct mount *mp)
  687 {
  688 
  689         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
  690         MNT_ILOCK(mp);
  691         MNT_REL(mp);
  692         KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
  693         mp->mnt_lockref--;
  694         if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
  695                 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
  696                 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
  697                 mp->mnt_kern_flag &= ~MNTK_DRAINING;
  698                 wakeup(&mp->mnt_lockref);
  699         }
  700         MNT_IUNLOCK(mp);
  701 }
  702 
  703 /*
  704  * Lookup a mount point by filesystem identifier.
  705  */
  706 struct mount *
  707 vfs_getvfs(fsid_t *fsid)
  708 {
  709         struct mount *mp;
  710 
  711         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
  712         mtx_lock(&mountlist_mtx);
  713         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
  714                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
  715                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
  716                         vfs_ref(mp);
  717                         mtx_unlock(&mountlist_mtx);
  718                         return (mp);
  719                 }
  720         }
  721         mtx_unlock(&mountlist_mtx);
  722         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
  723         return ((struct mount *) 0);
  724 }
  725 
  726 /*
  727  * Lookup a mount point by filesystem identifier, busying it before
  728  * returning.
  729  *
  730  * To avoid congestion on mountlist_mtx, implement simple direct-mapped
  731  * cache for popular filesystem identifiers.  The cache is lockess, using
  732  * the fact that struct mount's are never freed.  In worst case we may
  733  * get pointer to unmounted or even different filesystem, so we have to
  734  * check what we got, and go slow way if so.
  735  */
  736 struct mount *
  737 vfs_busyfs(fsid_t *fsid)
  738 {
  739 #define FSID_CACHE_SIZE 256
  740         typedef struct mount * volatile vmp_t;
  741         static vmp_t cache[FSID_CACHE_SIZE];
  742         struct mount *mp;
  743         int error;
  744         uint32_t hash;
  745 
  746         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
  747         hash = fsid->val[0] ^ fsid->val[1];
  748         hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
  749         mp = cache[hash];
  750         if (mp == NULL ||
  751             mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
  752             mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
  753                 goto slow;
  754         if (vfs_busy(mp, 0) != 0) {
  755                 cache[hash] = NULL;
  756                 goto slow;
  757         }
  758         if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
  759             mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
  760                 return (mp);
  761         else
  762             vfs_unbusy(mp);
  763 
  764 slow:
  765         mtx_lock(&mountlist_mtx);
  766         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
  767                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
  768                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
  769                         error = vfs_busy(mp, MBF_MNTLSTLOCK);
  770                         if (error) {
  771                                 cache[hash] = NULL;
  772                                 mtx_unlock(&mountlist_mtx);
  773                                 return (NULL);
  774                         }
  775                         cache[hash] = mp;
  776                         return (mp);
  777                 }
  778         }
  779         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
  780         mtx_unlock(&mountlist_mtx);
  781         return ((struct mount *) 0);
  782 }
  783 
  784 /*
  785  * Check if a user can access privileged mount options.
  786  */
  787 int
  788 vfs_suser(struct mount *mp, struct thread *td)
  789 {
  790         int error;
  791 
  792         /*
  793          * If the thread is jailed, but this is not a jail-friendly file
  794          * system, deny immediately.
  795          */
  796         if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
  797                 return (EPERM);
  798 
  799         /*
  800          * If the file system was mounted outside the jail of the calling
  801          * thread, deny immediately.
  802          */
  803         if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
  804                 return (EPERM);
  805 
  806         /*
  807          * If file system supports delegated administration, we don't check
  808          * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
  809          * by the file system itself.
  810          * If this is not the user that did original mount, we check for
  811          * the PRIV_VFS_MOUNT_OWNER privilege.
  812          */
  813         if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
  814             mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
  815                 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
  816                         return (error);
  817         }
  818         return (0);
  819 }
  820 
  821 /*
  822  * Get a new unique fsid.  Try to make its val[0] unique, since this value
  823  * will be used to create fake device numbers for stat().  Also try (but
  824  * not so hard) make its val[0] unique mod 2^16, since some emulators only
  825  * support 16-bit device numbers.  We end up with unique val[0]'s for the
  826  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
  827  *
  828  * Keep in mind that several mounts may be running in parallel.  Starting
  829  * the search one past where the previous search terminated is both a
  830  * micro-optimization and a defense against returning the same fsid to
  831  * different mounts.
  832  */
  833 void
  834 vfs_getnewfsid(struct mount *mp)
  835 {
  836         static uint16_t mntid_base;
  837         struct mount *nmp;
  838         fsid_t tfsid;
  839         int mtype;
  840 
  841         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
  842         mtx_lock(&mntid_mtx);
  843         mtype = mp->mnt_vfc->vfc_typenum;
  844         tfsid.val[1] = mtype;
  845         mtype = (mtype & 0xFF) << 24;
  846         for (;;) {
  847                 tfsid.val[0] = makedev(255,
  848                     mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
  849                 mntid_base++;
  850                 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
  851                         break;
  852                 vfs_rel(nmp);
  853         }
  854         mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
  855         mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
  856         mtx_unlock(&mntid_mtx);
  857 }
  858 
  859 /*
  860  * Knob to control the precision of file timestamps:
  861  *
  862  *   0 = seconds only; nanoseconds zeroed.
  863  *   1 = seconds and nanoseconds, accurate within 1/HZ.
  864  *   2 = seconds and nanoseconds, truncated to microseconds.
  865  * >=3 = seconds and nanoseconds, maximum precision.
  866  */
  867 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
  868 
  869 static int timestamp_precision = TSP_USEC;
  870 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
  871     &timestamp_precision, 0, "File timestamp precision (0: seconds, "
  872     "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
  873     "3+: sec + ns (max. precision))");
  874 
  875 /*
  876  * Get a current timestamp.
  877  */
  878 void
  879 vfs_timestamp(struct timespec *tsp)
  880 {
  881         struct timeval tv;
  882 
  883         switch (timestamp_precision) {
  884         case TSP_SEC:
  885                 tsp->tv_sec = time_second;
  886                 tsp->tv_nsec = 0;
  887                 break;
  888         case TSP_HZ:
  889                 getnanotime(tsp);
  890                 break;
  891         case TSP_USEC:
  892                 microtime(&tv);
  893                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
  894                 break;
  895         case TSP_NSEC:
  896         default:
  897                 nanotime(tsp);
  898                 break;
  899         }
  900 }
  901 
  902 /*
  903  * Set vnode attributes to VNOVAL
  904  */
  905 void
  906 vattr_null(struct vattr *vap)
  907 {
  908 
  909         vap->va_type = VNON;
  910         vap->va_size = VNOVAL;
  911         vap->va_bytes = VNOVAL;
  912         vap->va_mode = VNOVAL;
  913         vap->va_nlink = VNOVAL;
  914         vap->va_uid = VNOVAL;
  915         vap->va_gid = VNOVAL;
  916         vap->va_fsid = VNOVAL;
  917         vap->va_fileid = VNOVAL;
  918         vap->va_blocksize = VNOVAL;
  919         vap->va_rdev = VNOVAL;
  920         vap->va_atime.tv_sec = VNOVAL;
  921         vap->va_atime.tv_nsec = VNOVAL;
  922         vap->va_mtime.tv_sec = VNOVAL;
  923         vap->va_mtime.tv_nsec = VNOVAL;
  924         vap->va_ctime.tv_sec = VNOVAL;
  925         vap->va_ctime.tv_nsec = VNOVAL;
  926         vap->va_birthtime.tv_sec = VNOVAL;
  927         vap->va_birthtime.tv_nsec = VNOVAL;
  928         vap->va_flags = VNOVAL;
  929         vap->va_gen = VNOVAL;
  930         vap->va_vaflags = 0;
  931 }
  932 
  933 /*
  934  * This routine is called when we have too many vnodes.  It attempts
  935  * to free <count> vnodes and will potentially free vnodes that still
  936  * have VM backing store (VM backing store is typically the cause
  937  * of a vnode blowout so we want to do this).  Therefore, this operation
  938  * is not considered cheap.
  939  *
  940  * A number of conditions may prevent a vnode from being reclaimed.
  941  * the buffer cache may have references on the vnode, a directory
  942  * vnode may still have references due to the namei cache representing
  943  * underlying files, or the vnode may be in active use.   It is not
  944  * desirable to reuse such vnodes.  These conditions may cause the
  945  * number of vnodes to reach some minimum value regardless of what
  946  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
  947  */
  948 static int
  949 vlrureclaim(struct mount *mp, int reclaim_nc_src, int trigger)
  950 {
  951         struct vnode *vp;
  952         int count, done, target;
  953 
  954         done = 0;
  955         vn_start_write(NULL, &mp, V_WAIT);
  956         MNT_ILOCK(mp);
  957         count = mp->mnt_nvnodelistsize;
  958         target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
  959         target = target / 10 + 1;
  960         while (count != 0 && done < target) {
  961                 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
  962                 while (vp != NULL && vp->v_type == VMARKER)
  963                         vp = TAILQ_NEXT(vp, v_nmntvnodes);
  964                 if (vp == NULL)
  965                         break;
  966                 /*
  967                  * XXX LRU is completely broken for non-free vnodes.  First
  968                  * by calling here in mountpoint order, then by moving
  969                  * unselected vnodes to the end here, and most grossly by
  970                  * removing the vlruvp() function that was supposed to
  971                  * maintain the order.  (This function was born broken
  972                  * since syncer problems prevented it doing anything.)  The
  973                  * order is closer to LRC (C = Created).
  974                  *
  975                  * LRU reclaiming of vnodes seems to have last worked in
  976                  * FreeBSD-3 where LRU wasn't mentioned under any spelling.
  977                  * Then there was no hold count, and inactive vnodes were
  978                  * simply put on the free list in LRU order.  The separate
  979                  * lists also break LRU.  We prefer to reclaim from the
  980                  * free list for technical reasons.  This tends to thrash
  981                  * the free list to keep very unrecently used held vnodes.
  982                  * The problem is mitigated by keeping the free list large.
  983                  */
  984                 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
  985                 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
  986                 --count;
  987                 if (!VI_TRYLOCK(vp))
  988                         goto next_iter;
  989                 /*
  990                  * If it's been deconstructed already, it's still
  991                  * referenced, or it exceeds the trigger, skip it.
  992                  * Also skip free vnodes.  We are trying to make space
  993                  * to expand the free list, not reduce it.
  994                  */
  995                 if (vp->v_usecount ||
  996                     (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
  997                     ((vp->v_iflag & VI_FREE) != 0) ||
  998                     (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
  999                     vp->v_object->resident_page_count > trigger)) {
 1000                         VI_UNLOCK(vp);
 1001                         goto next_iter;
 1002                 }
 1003                 MNT_IUNLOCK(mp);
 1004                 vholdl(vp);
 1005                 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
 1006                         vdrop(vp);
 1007                         goto next_iter_mntunlocked;
 1008                 }
 1009                 VI_LOCK(vp);
 1010                 /*
 1011                  * v_usecount may have been bumped after VOP_LOCK() dropped
 1012                  * the vnode interlock and before it was locked again.
 1013                  *
 1014                  * It is not necessary to recheck VI_DOOMED because it can
 1015                  * only be set by another thread that holds both the vnode
 1016                  * lock and vnode interlock.  If another thread has the
 1017                  * vnode lock before we get to VOP_LOCK() and obtains the
 1018                  * vnode interlock after VOP_LOCK() drops the vnode
 1019                  * interlock, the other thread will be unable to drop the
 1020                  * vnode lock before our VOP_LOCK() call fails.
 1021                  */
 1022                 if (vp->v_usecount ||
 1023                     (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
 1024                     (vp->v_iflag & VI_FREE) != 0 ||
 1025                     (vp->v_object != NULL &&
 1026                     vp->v_object->resident_page_count > trigger)) {
 1027                         VOP_UNLOCK(vp, LK_INTERLOCK);
 1028                         vdrop(vp);
 1029                         goto next_iter_mntunlocked;
 1030                 }
 1031                 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
 1032                     ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
 1033                 counter_u64_add(recycles_count, 1);
 1034                 vgonel(vp);
 1035                 VOP_UNLOCK(vp, 0);
 1036                 vdropl(vp);
 1037                 done++;
 1038 next_iter_mntunlocked:
 1039                 if (!should_yield())
 1040                         goto relock_mnt;
 1041                 goto yield;
 1042 next_iter:
 1043                 if (!should_yield())
 1044                         continue;
 1045                 MNT_IUNLOCK(mp);
 1046 yield:
 1047                 kern_yield(PRI_USER);
 1048 relock_mnt:
 1049                 MNT_ILOCK(mp);
 1050         }
 1051         MNT_IUNLOCK(mp);
 1052         vn_finished_write(mp);
 1053         return done;
 1054 }
 1055 
 1056 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
 1057 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
 1058     0,
 1059     "limit on vnode free requests per call to the vnlru_free routine");
 1060 
 1061 /*
 1062  * Attempt to reduce the free list by the requested amount.
 1063  */
 1064 static void
 1065 vnlru_free_locked(int count, struct vfsops *mnt_op)
 1066 {
 1067         struct vnode *vp;
 1068         struct mount *mp;
 1069 
 1070         mtx_assert(&vnode_free_list_mtx, MA_OWNED);
 1071         if (count > max_vnlru_free)
 1072                 count = max_vnlru_free;
 1073         for (; count > 0; count--) {
 1074                 vp = TAILQ_FIRST(&vnode_free_list);
 1075                 /*
 1076                  * The list can be modified while the free_list_mtx
 1077                  * has been dropped and vp could be NULL here.
 1078                  */
 1079                 if (!vp)
 1080                         break;
 1081                 VNASSERT(vp->v_op != NULL, vp,
 1082                     ("vnlru_free: vnode already reclaimed."));
 1083                 KASSERT((vp->v_iflag & VI_FREE) != 0,
 1084                     ("Removing vnode not on freelist"));
 1085                 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
 1086                     ("Mangling active vnode"));
 1087                 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
 1088 
 1089                 /*
 1090                  * Don't recycle if our vnode is from different type
 1091                  * of mount point.  Note that mp is type-safe, the
 1092                  * check does not reach unmapped address even if
 1093                  * vnode is reclaimed.
 1094                  * Don't recycle if we can't get the interlock without
 1095                  * blocking.
 1096                  */
 1097                 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
 1098                     mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
 1099                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
 1100                         continue;
 1101                 }
 1102                 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
 1103                     vp, ("vp inconsistent on freelist"));
 1104 
 1105                 /*
 1106                  * The clear of VI_FREE prevents activation of the
 1107                  * vnode.  There is no sense in putting the vnode on
 1108                  * the mount point active list, only to remove it
 1109                  * later during recycling.  Inline the relevant part
 1110                  * of vholdl(), to avoid triggering assertions or
 1111                  * activating.
 1112                  */
 1113                 freevnodes--;
 1114                 vp->v_iflag &= ~VI_FREE;
 1115                 VNODE_REFCOUNT_FENCE_REL();
 1116                 refcount_acquire(&vp->v_holdcnt);
 1117 
 1118                 mtx_unlock(&vnode_free_list_mtx);
 1119                 VI_UNLOCK(vp);
 1120                 vtryrecycle(vp);
 1121                 /*
 1122                  * If the recycled succeeded this vdrop will actually free
 1123                  * the vnode.  If not it will simply place it back on
 1124                  * the free list.
 1125                  */
 1126                 vdrop(vp);
 1127                 mtx_lock(&vnode_free_list_mtx);
 1128         }
 1129 }
 1130 
 1131 void
 1132 vnlru_free(int count, struct vfsops *mnt_op)
 1133 {
 1134 
 1135         mtx_lock(&vnode_free_list_mtx);
 1136         vnlru_free_locked(count, mnt_op);
 1137         mtx_unlock(&vnode_free_list_mtx);
 1138 }
 1139 
 1140 
 1141 /* XXX some names and initialization are bad for limits and watermarks. */
 1142 static int
 1143 vspace(void)
 1144 {
 1145         int space;
 1146 
 1147         gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
 1148         vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
 1149         vlowat = vhiwat / 2;
 1150         if (numvnodes > desiredvnodes)
 1151                 return (0);
 1152         space = desiredvnodes - numvnodes;
 1153         if (freevnodes > wantfreevnodes)
 1154                 space += freevnodes - wantfreevnodes;
 1155         return (space);
 1156 }
 1157 
 1158 /*
 1159  * Attempt to recycle vnodes in a context that is always safe to block.
 1160  * Calling vlrurecycle() from the bowels of filesystem code has some
 1161  * interesting deadlock problems.
 1162  */
 1163 static struct proc *vnlruproc;
 1164 static int vnlruproc_sig;
 1165 
 1166 static void
 1167 vnlru_proc(void)
 1168 {
 1169         struct mount *mp, *nmp;
 1170         unsigned long ofreevnodes, onumvnodes;
 1171         int done, force, reclaim_nc_src, trigger, usevnodes, vsp;
 1172 
 1173         EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
 1174             SHUTDOWN_PRI_FIRST);
 1175 
 1176         force = 0;
 1177         for (;;) {
 1178                 kproc_suspend_check(vnlruproc);
 1179                 mtx_lock(&vnode_free_list_mtx);
 1180                 /*
 1181                  * If numvnodes is too large (due to desiredvnodes being
 1182                  * adjusted using its sysctl, or emergency growth), first
 1183                  * try to reduce it by discarding from the free list.
 1184                  */
 1185                 if (numvnodes > desiredvnodes && freevnodes > 0)
 1186                         vnlru_free_locked(ulmin(numvnodes - desiredvnodes,
 1187                             freevnodes), NULL);
 1188                 /*
 1189                  * Sleep if the vnode cache is in a good state.  This is
 1190                  * when it is not over-full and has space for about a 4%
 1191                  * or 9% expansion (by growing its size or inexcessively
 1192                  * reducing its free list).  Otherwise, try to reclaim
 1193                  * space for a 10% expansion.
 1194                  */
 1195                 if (vstir && force == 0) {
 1196                         force = 1;
 1197                         vstir = 0;
 1198                 }
 1199                 vsp = vspace();
 1200                 if (vsp >= vlowat && force == 0) {
 1201                         vnlruproc_sig = 0;
 1202                         wakeup(&vnlruproc_sig);
 1203                         msleep(vnlruproc, &vnode_free_list_mtx,
 1204                             PVFS|PDROP, "vlruwt", hz);
 1205                         continue;
 1206                 }
 1207                 mtx_unlock(&vnode_free_list_mtx);
 1208                 done = 0;
 1209                 ofreevnodes = freevnodes;
 1210                 onumvnodes = numvnodes;
 1211                 /*
 1212                  * Calculate parameters for recycling.  These are the same
 1213                  * throughout the loop to give some semblance of fairness.
 1214                  * The trigger point is to avoid recycling vnodes with lots
 1215                  * of resident pages.  We aren't trying to free memory; we
 1216                  * are trying to recycle or at least free vnodes.
 1217                  */
 1218                 if (numvnodes <= desiredvnodes)
 1219                         usevnodes = numvnodes - freevnodes;
 1220                 else
 1221                         usevnodes = numvnodes;
 1222                 if (usevnodes <= 0)
 1223                         usevnodes = 1;
 1224                 /*
 1225                  * The trigger value is is chosen to give a conservatively
 1226                  * large value to ensure that it alone doesn't prevent
 1227                  * making progress.  The value can easily be so large that
 1228                  * it is effectively infinite in some congested and
 1229                  * misconfigured cases, and this is necessary.  Normally
 1230                  * it is about 8 to 100 (pages), which is quite large.
 1231                  */
 1232                 trigger = vm_cnt.v_page_count * 2 / usevnodes;
 1233                 if (force < 2)
 1234                         trigger = vsmalltrigger;
 1235                 reclaim_nc_src = force >= 3;
 1236                 mtx_lock(&mountlist_mtx);
 1237                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
 1238                         if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
 1239                                 nmp = TAILQ_NEXT(mp, mnt_list);
 1240                                 continue;
 1241                         }
 1242                         done += vlrureclaim(mp, reclaim_nc_src, trigger);
 1243                         mtx_lock(&mountlist_mtx);
 1244                         nmp = TAILQ_NEXT(mp, mnt_list);
 1245                         vfs_unbusy(mp);
 1246                 }
 1247                 mtx_unlock(&mountlist_mtx);
 1248                 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
 1249                         uma_reclaim();
 1250                 if (done == 0) {
 1251                         if (force == 0 || force == 1) {
 1252                                 force = 2;
 1253                                 continue;
 1254                         }
 1255                         if (force == 2) {
 1256                                 force = 3;
 1257                                 continue;
 1258                         }
 1259                         force = 0;
 1260                         vnlru_nowhere++;
 1261                         tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
 1262                 } else
 1263                         kern_yield(PRI_USER);
 1264                 /*
 1265                  * After becoming active to expand above low water, keep
 1266                  * active until above high water.
 1267                  */
 1268                 vsp = vspace();
 1269                 force = vsp < vhiwat;
 1270         }
 1271 }
 1272 
 1273 static struct kproc_desc vnlru_kp = {
 1274         "vnlru",
 1275         vnlru_proc,
 1276         &vnlruproc
 1277 };
 1278 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
 1279     &vnlru_kp);
 1280  
 1281 /*
 1282  * Routines having to do with the management of the vnode table.
 1283  */
 1284 
 1285 /*
 1286  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
 1287  * before we actually vgone().  This function must be called with the vnode
 1288  * held to prevent the vnode from being returned to the free list midway
 1289  * through vgone().
 1290  */
 1291 static int
 1292 vtryrecycle(struct vnode *vp)
 1293 {
 1294         struct mount *vnmp;
 1295 
 1296         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 1297         VNASSERT(vp->v_holdcnt, vp,
 1298             ("vtryrecycle: Recycling vp %p without a reference.", vp));
 1299         /*
 1300          * This vnode may found and locked via some other list, if so we
 1301          * can't recycle it yet.
 1302          */
 1303         if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
 1304                 CTR2(KTR_VFS,
 1305                     "%s: impossible to recycle, vp %p lock is already held",
 1306                     __func__, vp);
 1307                 return (EWOULDBLOCK);
 1308         }
 1309         /*
 1310          * Don't recycle if its filesystem is being suspended.
 1311          */
 1312         if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
 1313                 VOP_UNLOCK(vp, 0);
 1314                 CTR2(KTR_VFS,
 1315                     "%s: impossible to recycle, cannot start the write for %p",
 1316                     __func__, vp);
 1317                 return (EBUSY);
 1318         }
 1319         /*
 1320          * If we got this far, we need to acquire the interlock and see if
 1321          * anyone picked up this vnode from another list.  If not, we will
 1322          * mark it with DOOMED via vgonel() so that anyone who does find it
 1323          * will skip over it.
 1324          */
 1325         VI_LOCK(vp);
 1326         if (vp->v_usecount) {
 1327                 VOP_UNLOCK(vp, LK_INTERLOCK);
 1328                 vn_finished_write(vnmp);
 1329                 CTR2(KTR_VFS,
 1330                     "%s: impossible to recycle, %p is already referenced",
 1331                     __func__, vp);
 1332                 return (EBUSY);
 1333         }
 1334         if ((vp->v_iflag & VI_DOOMED) == 0) {
 1335                 counter_u64_add(recycles_count, 1);
 1336                 vgonel(vp);
 1337         }
 1338         VOP_UNLOCK(vp, LK_INTERLOCK);
 1339         vn_finished_write(vnmp);
 1340         return (0);
 1341 }
 1342 
 1343 static void
 1344 vcheckspace(void)
 1345 {
 1346         int vsp;
 1347 
 1348         vsp = vspace();
 1349         if (vsp < vlowat && vnlruproc_sig == 0) {
 1350                 vnlruproc_sig = 1;
 1351                 wakeup(vnlruproc);
 1352         }
 1353 }
 1354 
 1355 /*
 1356  * Wait if necessary for space for a new vnode.
 1357  */
 1358 static int
 1359 getnewvnode_wait(int suspended)
 1360 {
 1361 
 1362         mtx_assert(&vnode_free_list_mtx, MA_OWNED);
 1363         if (numvnodes >= desiredvnodes) {
 1364                 if (suspended) {
 1365                         /*
 1366                          * The file system is being suspended.  We cannot
 1367                          * risk a deadlock here, so allow allocation of
 1368                          * another vnode even if this would give too many.
 1369                          */
 1370                         return (0);
 1371                 }
 1372                 if (vnlruproc_sig == 0) {
 1373                         vnlruproc_sig = 1;      /* avoid unnecessary wakeups */
 1374                         wakeup(vnlruproc);
 1375                 }
 1376                 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
 1377                     "vlruwk", hz);
 1378         }
 1379         /* Post-adjust like the pre-adjust in getnewvnode(). */
 1380         if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
 1381                 vnlru_free_locked(1, NULL);
 1382         return (numvnodes >= desiredvnodes ? ENFILE : 0);
 1383 }
 1384 
 1385 /*
 1386  * This hack is fragile, and probably not needed any more now that the
 1387  * watermark handling works.
 1388  */
 1389 void
 1390 getnewvnode_reserve(u_int count)
 1391 {
 1392         struct thread *td;
 1393 
 1394         /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
 1395         /* XXX no longer so quick, but this part is not racy. */
 1396         mtx_lock(&vnode_free_list_mtx);
 1397         if (numvnodes + count > desiredvnodes && freevnodes > wantfreevnodes)
 1398                 vnlru_free_locked(ulmin(numvnodes + count - desiredvnodes,
 1399                     freevnodes - wantfreevnodes), NULL);
 1400         mtx_unlock(&vnode_free_list_mtx);
 1401 
 1402         td = curthread;
 1403         /* First try to be quick and racy. */
 1404         if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
 1405                 td->td_vp_reserv += count;
 1406                 vcheckspace();  /* XXX no longer so quick, but more racy */
 1407                 return;
 1408         } else
 1409                 atomic_subtract_long(&numvnodes, count);
 1410 
 1411         mtx_lock(&vnode_free_list_mtx);
 1412         while (count > 0) {
 1413                 if (getnewvnode_wait(0) == 0) {
 1414                         count--;
 1415                         td->td_vp_reserv++;
 1416                         atomic_add_long(&numvnodes, 1);
 1417                 }
 1418         }
 1419         vcheckspace();
 1420         mtx_unlock(&vnode_free_list_mtx);
 1421 }
 1422 
 1423 /*
 1424  * This hack is fragile, especially if desiredvnodes or wantvnodes are
 1425  * misconfgured or changed significantly.  Reducing desiredvnodes below
 1426  * the reserved amount should cause bizarre behaviour like reducing it
 1427  * below the number of active vnodes -- the system will try to reduce
 1428  * numvnodes to match, but should fail, so the subtraction below should
 1429  * not overflow.
 1430  */
 1431 void
 1432 getnewvnode_drop_reserve(void)
 1433 {
 1434         struct thread *td;
 1435 
 1436         td = curthread;
 1437         atomic_subtract_long(&numvnodes, td->td_vp_reserv);
 1438         td->td_vp_reserv = 0;
 1439 }
 1440 
 1441 /*
 1442  * Return the next vnode from the free list.
 1443  */
 1444 int
 1445 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
 1446     struct vnode **vpp)
 1447 {
 1448         struct vnode *vp;
 1449         struct thread *td;
 1450         struct lock_object *lo;
 1451         static int cyclecount;
 1452         int error;
 1453 
 1454         CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
 1455         vp = NULL;
 1456         td = curthread;
 1457         if (td->td_vp_reserv > 0) {
 1458                 td->td_vp_reserv -= 1;
 1459                 goto alloc;
 1460         }
 1461         mtx_lock(&vnode_free_list_mtx);
 1462         if (numvnodes < desiredvnodes)
 1463                 cyclecount = 0;
 1464         else if (cyclecount++ >= freevnodes) {
 1465                 cyclecount = 0;
 1466                 vstir = 1;
 1467         }
 1468         /*
 1469          * Grow the vnode cache if it will not be above its target max
 1470          * after growing.  Otherwise, if the free list is nonempty, try
 1471          * to reclaim 1 item from it before growing the cache (possibly
 1472          * above its target max if the reclamation failed or is delayed).
 1473          * Otherwise, wait for some space.  In all cases, schedule
 1474          * vnlru_proc() if we are getting short of space.  The watermarks
 1475          * should be chosen so that we never wait or even reclaim from
 1476          * the free list to below its target minimum.
 1477          */
 1478         if (numvnodes + 1 <= desiredvnodes)
 1479                 ;
 1480         else if (freevnodes > 0)
 1481                 vnlru_free_locked(1, NULL);
 1482         else {
 1483                 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
 1484                     MNTK_SUSPEND));
 1485 #if 0   /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
 1486                 if (error != 0) {
 1487                         mtx_unlock(&vnode_free_list_mtx);
 1488                         return (error);
 1489                 }
 1490 #endif
 1491         }
 1492         vcheckspace();
 1493         atomic_add_long(&numvnodes, 1);
 1494         mtx_unlock(&vnode_free_list_mtx);
 1495 alloc:
 1496         counter_u64_add(vnodes_created, 1);
 1497         vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
 1498         /*
 1499          * Locks are given the generic name "vnode" when created.
 1500          * Follow the historic practice of using the filesystem
 1501          * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
 1502          *
 1503          * Locks live in a witness group keyed on their name. Thus,
 1504          * when a lock is renamed, it must also move from the witness
 1505          * group of its old name to the witness group of its new name.
 1506          *
 1507          * The change only needs to be made when the vnode moves
 1508          * from one filesystem type to another. We ensure that each
 1509          * filesystem use a single static name pointer for its tag so
 1510          * that we can compare pointers rather than doing a strcmp().
 1511          */
 1512         lo = &vp->v_vnlock->lock_object;
 1513         if (lo->lo_name != tag) {
 1514                 lo->lo_name = tag;
 1515                 WITNESS_DESTROY(lo);
 1516                 WITNESS_INIT(lo, tag);
 1517         }
 1518         /*
 1519          * By default, don't allow shared locks unless filesystems opt-in.
 1520          */
 1521         vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
 1522         /*
 1523          * Finalize various vnode identity bits.
 1524          */
 1525         KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
 1526         KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
 1527         KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
 1528         vp->v_type = VNON;
 1529         vp->v_tag = tag;
 1530         vp->v_op = vops;
 1531         v_init_counters(vp);
 1532         vp->v_bufobj.bo_ops = &buf_ops_bio;
 1533 #ifdef DIAGNOSTIC
 1534         if (mp == NULL && vops != &dead_vnodeops)
 1535                 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
 1536 #endif
 1537 #ifdef MAC
 1538         mac_vnode_init(vp);
 1539         if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
 1540                 mac_vnode_associate_singlelabel(mp, vp);
 1541 #endif
 1542         if (mp != NULL) {
 1543                 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
 1544                 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
 1545                         vp->v_vflag |= VV_NOKNOTE;
 1546         }
 1547 
 1548         /*
 1549          * For the filesystems which do not use vfs_hash_insert(),
 1550          * still initialize v_hash to have vfs_hash_index() useful.
 1551          * E.g., nullfs uses vfs_hash_index() on the lower vnode for
 1552          * its own hashing.
 1553          */
 1554         vp->v_hash = (uintptr_t)vp >> vnsz2log;
 1555 
 1556         *vpp = vp;
 1557         return (0);
 1558 }
 1559 
 1560 /*
 1561  * Delete from old mount point vnode list, if on one.
 1562  */
 1563 static void
 1564 delmntque(struct vnode *vp)
 1565 {
 1566         struct mount *mp;
 1567         int active;
 1568 
 1569         mp = vp->v_mount;
 1570         if (mp == NULL)
 1571                 return;
 1572         MNT_ILOCK(mp);
 1573         VI_LOCK(vp);
 1574         KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
 1575             ("Active vnode list size %d > Vnode list size %d",
 1576              mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
 1577         active = vp->v_iflag & VI_ACTIVE;
 1578         vp->v_iflag &= ~VI_ACTIVE;
 1579         if (active) {
 1580                 mtx_lock(&vnode_free_list_mtx);
 1581                 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
 1582                 mp->mnt_activevnodelistsize--;
 1583                 mtx_unlock(&vnode_free_list_mtx);
 1584         }
 1585         vp->v_mount = NULL;
 1586         VI_UNLOCK(vp);
 1587         VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
 1588                 ("bad mount point vnode list size"));
 1589         TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
 1590         mp->mnt_nvnodelistsize--;
 1591         MNT_REL(mp);
 1592         MNT_IUNLOCK(mp);
 1593 }
 1594 
 1595 static void
 1596 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
 1597 {
 1598 
 1599         vp->v_data = NULL;
 1600         vp->v_op = &dead_vnodeops;
 1601         vgone(vp);
 1602         vput(vp);
 1603 }
 1604 
 1605 /*
 1606  * Insert into list of vnodes for the new mount point, if available.
 1607  */
 1608 int
 1609 insmntque1(struct vnode *vp, struct mount *mp,
 1610         void (*dtr)(struct vnode *, void *), void *dtr_arg)
 1611 {
 1612 
 1613         KASSERT(vp->v_mount == NULL,
 1614                 ("insmntque: vnode already on per mount vnode list"));
 1615         VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
 1616         ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
 1617 
 1618         /*
 1619          * We acquire the vnode interlock early to ensure that the
 1620          * vnode cannot be recycled by another process releasing a
 1621          * holdcnt on it before we get it on both the vnode list
 1622          * and the active vnode list. The mount mutex protects only
 1623          * manipulation of the vnode list and the vnode freelist
 1624          * mutex protects only manipulation of the active vnode list.
 1625          * Hence the need to hold the vnode interlock throughout.
 1626          */
 1627         MNT_ILOCK(mp);
 1628         VI_LOCK(vp);
 1629         if (((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
 1630             ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
 1631             mp->mnt_nvnodelistsize == 0)) &&
 1632             (vp->v_vflag & VV_FORCEINSMQ) == 0) {
 1633                 VI_UNLOCK(vp);
 1634                 MNT_IUNLOCK(mp);
 1635                 if (dtr != NULL)
 1636                         dtr(vp, dtr_arg);
 1637                 return (EBUSY);
 1638         }
 1639         vp->v_mount = mp;
 1640         MNT_REF(mp);
 1641         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
 1642         VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
 1643                 ("neg mount point vnode list size"));
 1644         mp->mnt_nvnodelistsize++;
 1645         KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
 1646             ("Activating already active vnode"));
 1647         vp->v_iflag |= VI_ACTIVE;
 1648         mtx_lock(&vnode_free_list_mtx);
 1649         TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
 1650         mp->mnt_activevnodelistsize++;
 1651         mtx_unlock(&vnode_free_list_mtx);
 1652         VI_UNLOCK(vp);
 1653         MNT_IUNLOCK(mp);
 1654         return (0);
 1655 }
 1656 
 1657 int
 1658 insmntque(struct vnode *vp, struct mount *mp)
 1659 {
 1660 
 1661         return (insmntque1(vp, mp, insmntque_stddtr, NULL));
 1662 }
 1663 
 1664 /*
 1665  * Flush out and invalidate all buffers associated with a bufobj
 1666  * Called with the underlying object locked.
 1667  */
 1668 int
 1669 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
 1670 {
 1671         int error;
 1672 
 1673         BO_LOCK(bo);
 1674         if (flags & V_SAVE) {
 1675                 error = bufobj_wwait(bo, slpflag, slptimeo);
 1676                 if (error) {
 1677                         BO_UNLOCK(bo);
 1678                         return (error);
 1679                 }
 1680                 if (bo->bo_dirty.bv_cnt > 0) {
 1681                         BO_UNLOCK(bo);
 1682                         if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
 1683                                 return (error);
 1684                         /*
 1685                          * XXX We could save a lock/unlock if this was only
 1686                          * enabled under INVARIANTS
 1687                          */
 1688                         BO_LOCK(bo);
 1689                         if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
 1690                                 panic("vinvalbuf: dirty bufs");
 1691                 }
 1692         }
 1693         /*
 1694          * If you alter this loop please notice that interlock is dropped and
 1695          * reacquired in flushbuflist.  Special care is needed to ensure that
 1696          * no race conditions occur from this.
 1697          */
 1698         do {
 1699                 error = flushbuflist(&bo->bo_clean,
 1700                     flags, bo, slpflag, slptimeo);
 1701                 if (error == 0 && !(flags & V_CLEANONLY))
 1702                         error = flushbuflist(&bo->bo_dirty,
 1703                             flags, bo, slpflag, slptimeo);
 1704                 if (error != 0 && error != EAGAIN) {
 1705                         BO_UNLOCK(bo);
 1706                         return (error);
 1707                 }
 1708         } while (error != 0);
 1709 
 1710         /*
 1711          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
 1712          * have write I/O in-progress but if there is a VM object then the
 1713          * VM object can also have read-I/O in-progress.
 1714          */
 1715         do {
 1716                 bufobj_wwait(bo, 0, 0);
 1717                 if ((flags & V_VMIO) == 0) {
 1718                         BO_UNLOCK(bo);
 1719                         if (bo->bo_object != NULL) {
 1720                                 VM_OBJECT_WLOCK(bo->bo_object);
 1721                                 vm_object_pip_wait(bo->bo_object, "bovlbx");
 1722                                 VM_OBJECT_WUNLOCK(bo->bo_object);
 1723                         }
 1724                         BO_LOCK(bo);
 1725                 }
 1726         } while (bo->bo_numoutput > 0);
 1727         BO_UNLOCK(bo);
 1728 
 1729         /*
 1730          * Destroy the copy in the VM cache, too.
 1731          */
 1732         if (bo->bo_object != NULL &&
 1733             (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
 1734                 VM_OBJECT_WLOCK(bo->bo_object);
 1735                 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
 1736                     OBJPR_CLEANONLY : 0);
 1737                 VM_OBJECT_WUNLOCK(bo->bo_object);
 1738         }
 1739 
 1740 #ifdef INVARIANTS
 1741         BO_LOCK(bo);
 1742         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
 1743             V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
 1744             bo->bo_clean.bv_cnt > 0))
 1745                 panic("vinvalbuf: flush failed");
 1746         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
 1747             bo->bo_dirty.bv_cnt > 0)
 1748                 panic("vinvalbuf: flush dirty failed");
 1749         BO_UNLOCK(bo);
 1750 #endif
 1751         return (0);
 1752 }
 1753 
 1754 /*
 1755  * Flush out and invalidate all buffers associated with a vnode.
 1756  * Called with the underlying object locked.
 1757  */
 1758 int
 1759 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
 1760 {
 1761 
 1762         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
 1763         ASSERT_VOP_LOCKED(vp, "vinvalbuf");
 1764         if (vp->v_object != NULL && vp->v_object->handle != vp)
 1765                 return (0);
 1766         return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
 1767 }
 1768 
 1769 /*
 1770  * Flush out buffers on the specified list.
 1771  *
 1772  */
 1773 static int
 1774 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
 1775     int slptimeo)
 1776 {
 1777         struct buf *bp, *nbp;
 1778         int retval, error;
 1779         daddr_t lblkno;
 1780         b_xflags_t xflags;
 1781 
 1782         ASSERT_BO_WLOCKED(bo);
 1783 
 1784         retval = 0;
 1785         TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
 1786                 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
 1787                     ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
 1788                         continue;
 1789                 }
 1790                 if (nbp != NULL) {
 1791                         lblkno = nbp->b_lblkno;
 1792                         xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
 1793                 }
 1794                 retval = EAGAIN;
 1795                 error = BUF_TIMELOCK(bp,
 1796                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
 1797                     "flushbuf", slpflag, slptimeo);
 1798                 if (error) {
 1799                         BO_LOCK(bo);
 1800                         return (error != ENOLCK ? error : EAGAIN);
 1801                 }
 1802                 KASSERT(bp->b_bufobj == bo,
 1803                     ("bp %p wrong b_bufobj %p should be %p",
 1804                     bp, bp->b_bufobj, bo));
 1805                 /*
 1806                  * XXX Since there are no node locks for NFS, I
 1807                  * believe there is a slight chance that a delayed
 1808                  * write will occur while sleeping just above, so
 1809                  * check for it.
 1810                  */
 1811                 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
 1812                     (flags & V_SAVE)) {
 1813                         bremfree(bp);
 1814                         bp->b_flags |= B_ASYNC;
 1815                         bwrite(bp);
 1816                         BO_LOCK(bo);
 1817                         return (EAGAIN);        /* XXX: why not loop ? */
 1818                 }
 1819                 bremfree(bp);
 1820                 bp->b_flags |= (B_INVAL | B_RELBUF);
 1821                 bp->b_flags &= ~B_ASYNC;
 1822                 brelse(bp);
 1823                 BO_LOCK(bo);
 1824                 if (nbp == NULL)
 1825                         break;
 1826                 nbp = gbincore(bo, lblkno);
 1827                 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
 1828                     != xflags)
 1829                         break;                  /* nbp invalid */
 1830         }
 1831         return (retval);
 1832 }
 1833 
 1834 int
 1835 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
 1836 {
 1837         struct buf *bp;
 1838         int error;
 1839         daddr_t lblkno;
 1840 
 1841         ASSERT_BO_LOCKED(bo);
 1842 
 1843         for (lblkno = startn;;) {
 1844 again:
 1845                 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
 1846                 if (bp == NULL || bp->b_lblkno >= endn ||
 1847                     bp->b_lblkno < startn)
 1848                         break;
 1849                 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
 1850                     LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
 1851                 if (error != 0) {
 1852                         BO_RLOCK(bo);
 1853                         if (error == ENOLCK)
 1854                                 goto again;
 1855                         return (error);
 1856                 }
 1857                 KASSERT(bp->b_bufobj == bo,
 1858                     ("bp %p wrong b_bufobj %p should be %p",
 1859                     bp, bp->b_bufobj, bo));
 1860                 lblkno = bp->b_lblkno + 1;
 1861                 if ((bp->b_flags & B_MANAGED) == 0)
 1862                         bremfree(bp);
 1863                 bp->b_flags |= B_RELBUF;
 1864                 /*
 1865                  * In the VMIO case, use the B_NOREUSE flag to hint that the
 1866                  * pages backing each buffer in the range are unlikely to be
 1867                  * reused.  Dirty buffers will have the hint applied once
 1868                  * they've been written.
 1869                  */
 1870                 if ((bp->b_flags & B_VMIO) != 0)
 1871                         bp->b_flags |= B_NOREUSE;
 1872                 brelse(bp);
 1873                 BO_RLOCK(bo);
 1874         }
 1875         return (0);
 1876 }
 1877 
 1878 /*
 1879  * Truncate a file's buffer and pages to a specified length.  This
 1880  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
 1881  * sync activity.
 1882  */
 1883 int
 1884 vtruncbuf(struct vnode *vp, off_t length, int blksize)
 1885 {
 1886         struct buf *bp, *nbp;
 1887         int anyfreed;
 1888         daddr_t trunclbn;
 1889         struct bufobj *bo;
 1890 
 1891         CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
 1892             vp, blksize, (uintmax_t)length);
 1893 
 1894         /*
 1895          * Round up to the *next* lbn.
 1896          */
 1897         trunclbn = howmany(length, blksize);
 1898 
 1899         ASSERT_VOP_LOCKED(vp, "vtruncbuf");
 1900 restart:
 1901         bo = &vp->v_bufobj;
 1902         BO_LOCK(bo);
 1903         anyfreed = 1;
 1904         for (;anyfreed;) {
 1905                 anyfreed = 0;
 1906                 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
 1907                         if (bp->b_lblkno < trunclbn)
 1908                                 continue;
 1909                         if (BUF_LOCK(bp,
 1910                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
 1911                             BO_LOCKPTR(bo)) == ENOLCK)
 1912                                 goto restart;
 1913 
 1914                         bremfree(bp);
 1915                         bp->b_flags |= (B_INVAL | B_RELBUF);
 1916                         bp->b_flags &= ~B_ASYNC;
 1917                         brelse(bp);
 1918                         anyfreed = 1;
 1919 
 1920                         BO_LOCK(bo);
 1921                         if (nbp != NULL &&
 1922                             (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
 1923                             (nbp->b_vp != vp) ||
 1924                             (nbp->b_flags & B_DELWRI))) {
 1925                                 BO_UNLOCK(bo);
 1926                                 goto restart;
 1927                         }
 1928                 }
 1929 
 1930                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
 1931                         if (bp->b_lblkno < trunclbn)
 1932                                 continue;
 1933                         if (BUF_LOCK(bp,
 1934                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
 1935                             BO_LOCKPTR(bo)) == ENOLCK)
 1936                                 goto restart;
 1937                         bremfree(bp);
 1938                         bp->b_flags |= (B_INVAL | B_RELBUF);
 1939                         bp->b_flags &= ~B_ASYNC;
 1940                         brelse(bp);
 1941                         anyfreed = 1;
 1942 
 1943                         BO_LOCK(bo);
 1944                         if (nbp != NULL &&
 1945                             (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
 1946                             (nbp->b_vp != vp) ||
 1947                             (nbp->b_flags & B_DELWRI) == 0)) {
 1948                                 BO_UNLOCK(bo);
 1949                                 goto restart;
 1950                         }
 1951                 }
 1952         }
 1953 
 1954         if (length > 0) {
 1955 restartsync:
 1956                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
 1957                         if (bp->b_lblkno > 0)
 1958                                 continue;
 1959                         /*
 1960                          * Since we hold the vnode lock this should only
 1961                          * fail if we're racing with the buf daemon.
 1962                          */
 1963                         if (BUF_LOCK(bp,
 1964                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
 1965                             BO_LOCKPTR(bo)) == ENOLCK) {
 1966                                 goto restart;
 1967                         }
 1968                         VNASSERT((bp->b_flags & B_DELWRI), vp,
 1969                             ("buf(%p) on dirty queue without DELWRI", bp));
 1970 
 1971                         bremfree(bp);
 1972                         bawrite(bp);
 1973                         BO_LOCK(bo);
 1974                         goto restartsync;
 1975                 }
 1976         }
 1977 
 1978         bufobj_wwait(bo, 0, 0);
 1979         BO_UNLOCK(bo);
 1980         vnode_pager_setsize(vp, length);
 1981 
 1982         return (0);
 1983 }
 1984 
 1985 static void
 1986 buf_vlist_remove(struct buf *bp)
 1987 {
 1988         struct bufv *bv;
 1989 
 1990         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
 1991         ASSERT_BO_WLOCKED(bp->b_bufobj);
 1992         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
 1993             (BX_VNDIRTY|BX_VNCLEAN),
 1994             ("buf_vlist_remove: Buf %p is on two lists", bp));
 1995         if (bp->b_xflags & BX_VNDIRTY)
 1996                 bv = &bp->b_bufobj->bo_dirty;
 1997         else
 1998                 bv = &bp->b_bufobj->bo_clean;
 1999         BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
 2000         TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
 2001         bv->bv_cnt--;
 2002         bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
 2003 }
 2004 
 2005 /*
 2006  * Add the buffer to the sorted clean or dirty block list.
 2007  *
 2008  * NOTE: xflags is passed as a constant, optimizing this inline function!
 2009  */
 2010 static void
 2011 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
 2012 {
 2013         struct bufv *bv;
 2014         struct buf *n;
 2015         int error;
 2016 
 2017         ASSERT_BO_WLOCKED(bo);
 2018         KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
 2019             ("dead bo %p", bo));
 2020         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
 2021             ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
 2022         bp->b_xflags |= xflags;
 2023         if (xflags & BX_VNDIRTY)
 2024                 bv = &bo->bo_dirty;
 2025         else
 2026                 bv = &bo->bo_clean;
 2027 
 2028         /*
 2029          * Keep the list ordered.  Optimize empty list insertion.  Assume
 2030          * we tend to grow at the tail so lookup_le should usually be cheaper
 2031          * than _ge. 
 2032          */
 2033         if (bv->bv_cnt == 0 ||
 2034             bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
 2035                 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
 2036         else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
 2037                 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
 2038         else
 2039                 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
 2040         error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
 2041         if (error)
 2042                 panic("buf_vlist_add:  Preallocated nodes insufficient.");
 2043         bv->bv_cnt++;
 2044 }
 2045 
 2046 /*
 2047  * Look up a buffer using the buffer tries.
 2048  */
 2049 struct buf *
 2050 gbincore(struct bufobj *bo, daddr_t lblkno)
 2051 {
 2052         struct buf *bp;
 2053 
 2054         ASSERT_BO_LOCKED(bo);
 2055         bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
 2056         if (bp != NULL)
 2057                 return (bp);
 2058         return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
 2059 }
 2060 
 2061 /*
 2062  * Associate a buffer with a vnode.
 2063  */
 2064 void
 2065 bgetvp(struct vnode *vp, struct buf *bp)
 2066 {
 2067         struct bufobj *bo;
 2068 
 2069         bo = &vp->v_bufobj;
 2070         ASSERT_BO_WLOCKED(bo);
 2071         VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
 2072 
 2073         CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
 2074         VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
 2075             ("bgetvp: bp already attached! %p", bp));
 2076 
 2077         vhold(vp);
 2078         bp->b_vp = vp;
 2079         bp->b_bufobj = bo;
 2080         /*
 2081          * Insert onto list for new vnode.
 2082          */
 2083         buf_vlist_add(bp, bo, BX_VNCLEAN);
 2084 }
 2085 
 2086 /*
 2087  * Disassociate a buffer from a vnode.
 2088  */
 2089 void
 2090 brelvp(struct buf *bp)
 2091 {
 2092         struct bufobj *bo;
 2093         struct vnode *vp;
 2094 
 2095         CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
 2096         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
 2097 
 2098         /*
 2099          * Delete from old vnode list, if on one.
 2100          */
 2101         vp = bp->b_vp;          /* XXX */
 2102         bo = bp->b_bufobj;
 2103         BO_LOCK(bo);
 2104         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
 2105                 buf_vlist_remove(bp);
 2106         else
 2107                 panic("brelvp: Buffer %p not on queue.", bp);
 2108         if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
 2109                 bo->bo_flag &= ~BO_ONWORKLST;
 2110                 mtx_lock(&sync_mtx);
 2111                 LIST_REMOVE(bo, bo_synclist);
 2112                 syncer_worklist_len--;
 2113                 mtx_unlock(&sync_mtx);
 2114         }
 2115         bp->b_vp = NULL;
 2116         bp->b_bufobj = NULL;
 2117         BO_UNLOCK(bo);
 2118         vdrop(vp);
 2119 }
 2120 
 2121 /*
 2122  * Add an item to the syncer work queue.
 2123  */
 2124 static void
 2125 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
 2126 {
 2127         int slot;
 2128 
 2129         ASSERT_BO_WLOCKED(bo);
 2130 
 2131         mtx_lock(&sync_mtx);
 2132         if (bo->bo_flag & BO_ONWORKLST)
 2133                 LIST_REMOVE(bo, bo_synclist);
 2134         else {
 2135                 bo->bo_flag |= BO_ONWORKLST;
 2136                 syncer_worklist_len++;
 2137         }
 2138 
 2139         if (delay > syncer_maxdelay - 2)
 2140                 delay = syncer_maxdelay - 2;
 2141         slot = (syncer_delayno + delay) & syncer_mask;
 2142 
 2143         LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
 2144         mtx_unlock(&sync_mtx);
 2145 }
 2146 
 2147 static int
 2148 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
 2149 {
 2150         int error, len;
 2151 
 2152         mtx_lock(&sync_mtx);
 2153         len = syncer_worklist_len - sync_vnode_count;
 2154         mtx_unlock(&sync_mtx);
 2155         error = SYSCTL_OUT(req, &len, sizeof(len));
 2156         return (error);
 2157 }
 2158 
 2159 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
 2160     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
 2161 
 2162 static struct proc *updateproc;
 2163 static void sched_sync(void);
 2164 static struct kproc_desc up_kp = {
 2165         "syncer",
 2166         sched_sync,
 2167         &updateproc
 2168 };
 2169 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
 2170 
 2171 static int
 2172 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
 2173 {
 2174         struct vnode *vp;
 2175         struct mount *mp;
 2176 
 2177         *bo = LIST_FIRST(slp);
 2178         if (*bo == NULL)
 2179                 return (0);
 2180         vp = (*bo)->__bo_vnode; /* XXX */
 2181         if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
 2182                 return (1);
 2183         /*
 2184          * We use vhold in case the vnode does not
 2185          * successfully sync.  vhold prevents the vnode from
 2186          * going away when we unlock the sync_mtx so that
 2187          * we can acquire the vnode interlock.
 2188          */
 2189         vholdl(vp);
 2190         mtx_unlock(&sync_mtx);
 2191         VI_UNLOCK(vp);
 2192         if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
 2193                 vdrop(vp);
 2194                 mtx_lock(&sync_mtx);
 2195                 return (*bo == LIST_FIRST(slp));
 2196         }
 2197         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
 2198         (void) VOP_FSYNC(vp, MNT_LAZY, td);
 2199         VOP_UNLOCK(vp, 0);
 2200         vn_finished_write(mp);
 2201         BO_LOCK(*bo);
 2202         if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
 2203                 /*
 2204                  * Put us back on the worklist.  The worklist
 2205                  * routine will remove us from our current
 2206                  * position and then add us back in at a later
 2207                  * position.
 2208                  */
 2209                 vn_syncer_add_to_worklist(*bo, syncdelay);
 2210         }
 2211         BO_UNLOCK(*bo);
 2212         vdrop(vp);
 2213         mtx_lock(&sync_mtx);
 2214         return (0);
 2215 }
 2216 
 2217 static int first_printf = 1;
 2218 
 2219 /*
 2220  * System filesystem synchronizer daemon.
 2221  */
 2222 static void
 2223 sched_sync(void)
 2224 {
 2225         struct synclist *next, *slp;
 2226         struct bufobj *bo;
 2227         long starttime;
 2228         struct thread *td = curthread;
 2229         int last_work_seen;
 2230         int net_worklist_len;
 2231         int syncer_final_iter;
 2232         int error;
 2233 
 2234         last_work_seen = 0;
 2235         syncer_final_iter = 0;
 2236         syncer_state = SYNCER_RUNNING;
 2237         starttime = time_uptime;
 2238         td->td_pflags |= TDP_NORUNNINGBUF;
 2239 
 2240         EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
 2241             SHUTDOWN_PRI_LAST);
 2242 
 2243         mtx_lock(&sync_mtx);
 2244         for (;;) {
 2245                 if (syncer_state == SYNCER_FINAL_DELAY &&
 2246                     syncer_final_iter == 0) {
 2247                         mtx_unlock(&sync_mtx);
 2248                         kproc_suspend_check(td->td_proc);
 2249                         mtx_lock(&sync_mtx);
 2250                 }
 2251                 net_worklist_len = syncer_worklist_len - sync_vnode_count;
 2252                 if (syncer_state != SYNCER_RUNNING &&
 2253                     starttime != time_uptime) {
 2254                         if (first_printf) {
 2255                                 printf("\nSyncing disks, vnodes remaining... ");
 2256                                 first_printf = 0;
 2257                         }
 2258                         printf("%d ", net_worklist_len);
 2259                 }
 2260                 starttime = time_uptime;
 2261 
 2262                 /*
 2263                  * Push files whose dirty time has expired.  Be careful
 2264                  * of interrupt race on slp queue.
 2265                  *
 2266                  * Skip over empty worklist slots when shutting down.
 2267                  */
 2268                 do {
 2269                         slp = &syncer_workitem_pending[syncer_delayno];
 2270                         syncer_delayno += 1;
 2271                         if (syncer_delayno == syncer_maxdelay)
 2272                                 syncer_delayno = 0;
 2273                         next = &syncer_workitem_pending[syncer_delayno];
 2274                         /*
 2275                          * If the worklist has wrapped since the
 2276                          * it was emptied of all but syncer vnodes,
 2277                          * switch to the FINAL_DELAY state and run
 2278                          * for one more second.
 2279                          */
 2280                         if (syncer_state == SYNCER_SHUTTING_DOWN &&
 2281                             net_worklist_len == 0 &&
 2282                             last_work_seen == syncer_delayno) {
 2283                                 syncer_state = SYNCER_FINAL_DELAY;
 2284                                 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
 2285                         }
 2286                 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
 2287                     syncer_worklist_len > 0);
 2288 
 2289                 /*
 2290                  * Keep track of the last time there was anything
 2291                  * on the worklist other than syncer vnodes.
 2292                  * Return to the SHUTTING_DOWN state if any
 2293                  * new work appears.
 2294                  */
 2295                 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
 2296                         last_work_seen = syncer_delayno;
 2297                 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
 2298                         syncer_state = SYNCER_SHUTTING_DOWN;
 2299                 while (!LIST_EMPTY(slp)) {
 2300                         error = sync_vnode(slp, &bo, td);
 2301                         if (error == 1) {
 2302                                 LIST_REMOVE(bo, bo_synclist);
 2303                                 LIST_INSERT_HEAD(next, bo, bo_synclist);
 2304                                 continue;
 2305                         }
 2306 
 2307                         if (first_printf == 0) {
 2308                                 /*
 2309                                  * Drop the sync mutex, because some watchdog
 2310                                  * drivers need to sleep while patting
 2311                                  */
 2312                                 mtx_unlock(&sync_mtx);
 2313                                 wdog_kern_pat(WD_LASTVAL);
 2314                                 mtx_lock(&sync_mtx);
 2315                         }
 2316 
 2317                 }
 2318                 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
 2319                         syncer_final_iter--;
 2320                 /*
 2321                  * The variable rushjob allows the kernel to speed up the
 2322                  * processing of the filesystem syncer process. A rushjob
 2323                  * value of N tells the filesystem syncer to process the next
 2324                  * N seconds worth of work on its queue ASAP. Currently rushjob
 2325                  * is used by the soft update code to speed up the filesystem
 2326                  * syncer process when the incore state is getting so far
 2327                  * ahead of the disk that the kernel memory pool is being
 2328                  * threatened with exhaustion.
 2329                  */
 2330                 if (rushjob > 0) {
 2331                         rushjob -= 1;
 2332                         continue;
 2333                 }
 2334                 /*
 2335                  * Just sleep for a short period of time between
 2336                  * iterations when shutting down to allow some I/O
 2337                  * to happen.
 2338                  *
 2339                  * If it has taken us less than a second to process the
 2340                  * current work, then wait. Otherwise start right over
 2341                  * again. We can still lose time if any single round
 2342                  * takes more than two seconds, but it does not really
 2343                  * matter as we are just trying to generally pace the
 2344                  * filesystem activity.
 2345                  */
 2346                 if (syncer_state != SYNCER_RUNNING ||
 2347                     time_uptime == starttime) {
 2348                         thread_lock(td);
 2349                         sched_prio(td, PPAUSE);
 2350                         thread_unlock(td);
 2351                 }
 2352                 if (syncer_state != SYNCER_RUNNING)
 2353                         cv_timedwait(&sync_wakeup, &sync_mtx,
 2354                             hz / SYNCER_SHUTDOWN_SPEEDUP);
 2355                 else if (time_uptime == starttime)
 2356                         cv_timedwait(&sync_wakeup, &sync_mtx, hz);
 2357         }
 2358 }
 2359 
 2360 /*
 2361  * Request the syncer daemon to speed up its work.
 2362  * We never push it to speed up more than half of its
 2363  * normal turn time, otherwise it could take over the cpu.
 2364  */
 2365 int
 2366 speedup_syncer(void)
 2367 {
 2368         int ret = 0;
 2369 
 2370         mtx_lock(&sync_mtx);
 2371         if (rushjob < syncdelay / 2) {
 2372                 rushjob += 1;
 2373                 stat_rush_requests += 1;
 2374                 ret = 1;
 2375         }
 2376         mtx_unlock(&sync_mtx);
 2377         cv_broadcast(&sync_wakeup);
 2378         return (ret);
 2379 }
 2380 
 2381 /*
 2382  * Tell the syncer to speed up its work and run though its work
 2383  * list several times, then tell it to shut down.
 2384  */
 2385 static void
 2386 syncer_shutdown(void *arg, int howto)
 2387 {
 2388 
 2389         if (howto & RB_NOSYNC)
 2390                 return;
 2391         mtx_lock(&sync_mtx);
 2392         syncer_state = SYNCER_SHUTTING_DOWN;
 2393         rushjob = 0;
 2394         mtx_unlock(&sync_mtx);
 2395         cv_broadcast(&sync_wakeup);
 2396         kproc_shutdown(arg, howto);
 2397 }
 2398 
 2399 void
 2400 syncer_suspend(void)
 2401 {
 2402 
 2403         syncer_shutdown(updateproc, 0);
 2404 }
 2405 
 2406 void
 2407 syncer_resume(void)
 2408 {
 2409 
 2410         mtx_lock(&sync_mtx);
 2411         first_printf = 1;
 2412         syncer_state = SYNCER_RUNNING;
 2413         mtx_unlock(&sync_mtx);
 2414         cv_broadcast(&sync_wakeup);
 2415         kproc_resume(updateproc);
 2416 }
 2417 
 2418 /*
 2419  * Reassign a buffer from one vnode to another.
 2420  * Used to assign file specific control information
 2421  * (indirect blocks) to the vnode to which they belong.
 2422  */
 2423 void
 2424 reassignbuf(struct buf *bp)
 2425 {
 2426         struct vnode *vp;
 2427         struct bufobj *bo;
 2428         int delay;
 2429 #ifdef INVARIANTS
 2430         struct bufv *bv;
 2431 #endif
 2432 
 2433         vp = bp->b_vp;
 2434         bo = bp->b_bufobj;
 2435         ++reassignbufcalls;
 2436 
 2437         CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
 2438             bp, bp->b_vp, bp->b_flags);
 2439         /*
 2440          * B_PAGING flagged buffers cannot be reassigned because their vp
 2441          * is not fully linked in.
 2442          */
 2443         if (bp->b_flags & B_PAGING)
 2444                 panic("cannot reassign paging buffer");
 2445 
 2446         /*
 2447          * Delete from old vnode list, if on one.
 2448          */
 2449         BO_LOCK(bo);
 2450         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
 2451                 buf_vlist_remove(bp);
 2452         else
 2453                 panic("reassignbuf: Buffer %p not on queue.", bp);
 2454         /*
 2455          * If dirty, put on list of dirty buffers; otherwise insert onto list
 2456          * of clean buffers.
 2457          */
 2458         if (bp->b_flags & B_DELWRI) {
 2459                 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
 2460                         switch (vp->v_type) {
 2461                         case VDIR:
 2462                                 delay = dirdelay;
 2463                                 break;
 2464                         case VCHR:
 2465                                 delay = metadelay;
 2466                                 break;
 2467                         default:
 2468                                 delay = filedelay;
 2469                         }
 2470                         vn_syncer_add_to_worklist(bo, delay);
 2471                 }
 2472                 buf_vlist_add(bp, bo, BX_VNDIRTY);
 2473         } else {
 2474                 buf_vlist_add(bp, bo, BX_VNCLEAN);
 2475 
 2476                 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
 2477                         mtx_lock(&sync_mtx);
 2478                         LIST_REMOVE(bo, bo_synclist);
 2479                         syncer_worklist_len--;
 2480                         mtx_unlock(&sync_mtx);
 2481                         bo->bo_flag &= ~BO_ONWORKLST;
 2482                 }
 2483         }
 2484 #ifdef INVARIANTS
 2485         bv = &bo->bo_clean;
 2486         bp = TAILQ_FIRST(&bv->bv_hd);
 2487         KASSERT(bp == NULL || bp->b_bufobj == bo,
 2488             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 2489         bp = TAILQ_LAST(&bv->bv_hd, buflists);
 2490         KASSERT(bp == NULL || bp->b_bufobj == bo,
 2491             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 2492         bv = &bo->bo_dirty;
 2493         bp = TAILQ_FIRST(&bv->bv_hd);
 2494         KASSERT(bp == NULL || bp->b_bufobj == bo,
 2495             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 2496         bp = TAILQ_LAST(&bv->bv_hd, buflists);
 2497         KASSERT(bp == NULL || bp->b_bufobj == bo,
 2498             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 2499 #endif
 2500         BO_UNLOCK(bo);
 2501 }
 2502 
 2503 static void
 2504 v_init_counters(struct vnode *vp)
 2505 {
 2506 
 2507         VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
 2508             vp, ("%s called for an initialized vnode", __FUNCTION__));
 2509         ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
 2510 
 2511         refcount_init(&vp->v_holdcnt, 1);
 2512         refcount_init(&vp->v_usecount, 1);
 2513 }
 2514 
 2515 static void
 2516 v_incr_usecount_locked(struct vnode *vp)
 2517 {
 2518 
 2519         ASSERT_VI_LOCKED(vp, __func__);
 2520         if ((vp->v_iflag & VI_OWEINACT) != 0) {
 2521                 VNASSERT(vp->v_usecount == 0, vp,
 2522                     ("vnode with usecount and VI_OWEINACT set"));
 2523                 vp->v_iflag &= ~VI_OWEINACT;
 2524         }
 2525         refcount_acquire(&vp->v_usecount);
 2526         v_incr_devcount(vp);
 2527 }
 2528 
 2529 /*
 2530  * Increment the use and hold counts on the vnode, taking care to reference
 2531  * the driver's usecount if this is a chardev.  The _vhold() will remove
 2532  * the vnode from the free list if it is presently free.
 2533  */
 2534 static void
 2535 v_incr_usecount(struct vnode *vp)
 2536 {
 2537 
 2538         ASSERT_VI_UNLOCKED(vp, __func__);
 2539         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 2540 
 2541         if (vp->v_type != VCHR &&
 2542             refcount_acquire_if_not_zero(&vp->v_usecount)) {
 2543                 VNODE_REFCOUNT_FENCE_ACQ();
 2544                 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
 2545                     ("vnode with usecount and VI_OWEINACT set"));
 2546         } else {
 2547                 VI_LOCK(vp);
 2548                 v_incr_usecount_locked(vp);
 2549                 VI_UNLOCK(vp);
 2550         }
 2551 }
 2552 
 2553 /*
 2554  * Increment si_usecount of the associated device, if any.
 2555  */
 2556 static void
 2557 v_incr_devcount(struct vnode *vp)
 2558 {
 2559 
 2560         ASSERT_VI_LOCKED(vp, __FUNCTION__);
 2561         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
 2562                 dev_lock();
 2563                 vp->v_rdev->si_usecount++;
 2564                 dev_unlock();
 2565         }
 2566 }
 2567 
 2568 /*
 2569  * Decrement si_usecount of the associated device, if any.
 2570  */
 2571 static void
 2572 v_decr_devcount(struct vnode *vp)
 2573 {
 2574 
 2575         ASSERT_VI_LOCKED(vp, __FUNCTION__);
 2576         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
 2577                 dev_lock();
 2578                 vp->v_rdev->si_usecount--;
 2579                 dev_unlock();
 2580         }
 2581 }
 2582 
 2583 /*
 2584  * Grab a particular vnode from the free list, increment its
 2585  * reference count and lock it.  VI_DOOMED is set if the vnode
 2586  * is being destroyed.  Only callers who specify LK_RETRY will
 2587  * see doomed vnodes.  If inactive processing was delayed in
 2588  * vput try to do it here.
 2589  *
 2590  * Notes on lockless counter manipulation:
 2591  * _vhold, vputx and other routines make various decisions based
 2592  * on either holdcnt or usecount being 0. As long as either counter
 2593  * is not transitioning 0->1 nor 1->0, the manipulation can be done
 2594  * with atomic operations. Otherwise the interlock is taken covering
 2595  * both the atomic and additional actions.
 2596  */
 2597 int
 2598 vget(struct vnode *vp, int flags, struct thread *td)
 2599 {
 2600         int error, oweinact;
 2601 
 2602         VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
 2603             ("vget: invalid lock operation"));
 2604 
 2605         if ((flags & LK_INTERLOCK) != 0)
 2606                 ASSERT_VI_LOCKED(vp, __func__);
 2607         else
 2608                 ASSERT_VI_UNLOCKED(vp, __func__);
 2609         if ((flags & LK_VNHELD) != 0)
 2610                 VNASSERT((vp->v_holdcnt > 0), vp,
 2611                     ("vget: LK_VNHELD passed but vnode not held"));
 2612 
 2613         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
 2614 
 2615         if ((flags & LK_VNHELD) == 0)
 2616                 _vhold(vp, (flags & LK_INTERLOCK) != 0);
 2617 
 2618         if ((error = vn_lock(vp, flags)) != 0) {
 2619                 vdrop(vp);
 2620                 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
 2621                     vp);
 2622                 return (error);
 2623         }
 2624         if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
 2625                 panic("vget: vn_lock failed to return ENOENT\n");
 2626         /*
 2627          * We don't guarantee that any particular close will
 2628          * trigger inactive processing so just make a best effort
 2629          * here at preventing a reference to a removed file.  If
 2630          * we don't succeed no harm is done.
 2631          *
 2632          * Upgrade our holdcnt to a usecount.
 2633          */
 2634         if (vp->v_type == VCHR ||
 2635             !refcount_acquire_if_not_zero(&vp->v_usecount)) {
 2636                 VI_LOCK(vp);
 2637                 if ((vp->v_iflag & VI_OWEINACT) == 0) {
 2638                         oweinact = 0;
 2639                 } else {
 2640                         oweinact = 1;
 2641                         vp->v_iflag &= ~VI_OWEINACT;
 2642                         VNODE_REFCOUNT_FENCE_REL();
 2643                 }
 2644                 refcount_acquire(&vp->v_usecount);
 2645                 v_incr_devcount(vp);
 2646                 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
 2647                     (flags & LK_NOWAIT) == 0)
 2648                         vinactive(vp, td);
 2649                 VI_UNLOCK(vp);
 2650         }
 2651         return (0);
 2652 }
 2653 
 2654 /*
 2655  * Increase the reference count of a vnode.
 2656  */
 2657 void
 2658 vref(struct vnode *vp)
 2659 {
 2660 
 2661         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 2662         _vhold(vp, false);
 2663         v_incr_usecount(vp);
 2664 }
 2665 
 2666 void
 2667 vrefl(struct vnode *vp)
 2668 {
 2669 
 2670         ASSERT_VI_LOCKED(vp, __func__);
 2671         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 2672         _vhold(vp, true);
 2673         v_incr_usecount_locked(vp);
 2674 }
 2675 
 2676 void
 2677 vrefact(struct vnode *vp)
 2678 {
 2679 
 2680         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 2681         if (__predict_false(vp->v_type == VCHR)) {
 2682                 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
 2683                     ("%s: wrong ref counts", __func__));
 2684                 vref(vp);
 2685                 return;
 2686         }
 2687 #ifdef INVARIANTS
 2688         int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
 2689         VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
 2690         old = atomic_fetchadd_int(&vp->v_usecount, 1);
 2691         VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
 2692 #else
 2693         refcount_acquire(&vp->v_holdcnt);
 2694         refcount_acquire(&vp->v_usecount);
 2695 #endif
 2696 }
 2697 
 2698 /*
 2699  * Return reference count of a vnode.
 2700  *
 2701  * The results of this call are only guaranteed when some mechanism is used to
 2702  * stop other processes from gaining references to the vnode.  This may be the
 2703  * case if the caller holds the only reference.  This is also useful when stale
 2704  * data is acceptable as race conditions may be accounted for by some other
 2705  * means.
 2706  */
 2707 int
 2708 vrefcnt(struct vnode *vp)
 2709 {
 2710 
 2711         return (vp->v_usecount);
 2712 }
 2713 
 2714 #define VPUTX_VRELE     1
 2715 #define VPUTX_VPUT      2
 2716 #define VPUTX_VUNREF    3
 2717 
 2718 /*
 2719  * Decrement the use and hold counts for a vnode.
 2720  *
 2721  * See an explanation near vget() as to why atomic operation is safe.
 2722  */
 2723 static void
 2724 vputx(struct vnode *vp, int func)
 2725 {
 2726         int error;
 2727 
 2728         KASSERT(vp != NULL, ("vputx: null vp"));
 2729         if (func == VPUTX_VUNREF)
 2730                 ASSERT_VOP_LOCKED(vp, "vunref");
 2731         else if (func == VPUTX_VPUT)
 2732                 ASSERT_VOP_LOCKED(vp, "vput");
 2733         else
 2734                 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
 2735         ASSERT_VI_UNLOCKED(vp, __func__);
 2736         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 2737 
 2738         if (vp->v_type != VCHR &&
 2739             refcount_release_if_not_last(&vp->v_usecount)) {
 2740                 if (func == VPUTX_VPUT)
 2741                         VOP_UNLOCK(vp, 0);
 2742                 vdrop(vp);
 2743                 return;
 2744         }
 2745 
 2746         VI_LOCK(vp);
 2747 
 2748         /*
 2749          * We want to hold the vnode until the inactive finishes to
 2750          * prevent vgone() races.  We drop the use count here and the
 2751          * hold count below when we're done.
 2752          */
 2753         if (!refcount_release(&vp->v_usecount) ||
 2754             (vp->v_iflag & VI_DOINGINACT)) {
 2755                 if (func == VPUTX_VPUT)
 2756                         VOP_UNLOCK(vp, 0);
 2757                 v_decr_devcount(vp);
 2758                 vdropl(vp);
 2759                 return;
 2760         }
 2761 
 2762         v_decr_devcount(vp);
 2763 
 2764         error = 0;
 2765 
 2766         if (vp->v_usecount != 0) {
 2767                 vn_printf(vp, "vputx: usecount not zero for vnode ");
 2768                 panic("vputx: usecount not zero");
 2769         }
 2770 
 2771         CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
 2772 
 2773         /*
 2774          * We must call VOP_INACTIVE with the node locked. Mark
 2775          * as VI_DOINGINACT to avoid recursion.
 2776          */
 2777         vp->v_iflag |= VI_OWEINACT;
 2778         switch (func) {
 2779         case VPUTX_VRELE:
 2780                 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
 2781                 VI_LOCK(vp);
 2782                 break;
 2783         case VPUTX_VPUT:
 2784                 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
 2785                         error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
 2786                             LK_NOWAIT);
 2787                         VI_LOCK(vp);
 2788                 }
 2789                 break;
 2790         case VPUTX_VUNREF:
 2791                 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
 2792                         error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
 2793                         VI_LOCK(vp);
 2794                 }
 2795                 break;
 2796         }
 2797         VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
 2798             ("vnode with usecount and VI_OWEINACT set"));
 2799         if (error == 0) {
 2800                 if (vp->v_iflag & VI_OWEINACT)
 2801                         vinactive(vp, curthread);
 2802                 if (func != VPUTX_VUNREF)
 2803                         VOP_UNLOCK(vp, 0);
 2804         }
 2805         vdropl(vp);
 2806 }
 2807 
 2808 /*
 2809  * Vnode put/release.
 2810  * If count drops to zero, call inactive routine and return to freelist.
 2811  */
 2812 void
 2813 vrele(struct vnode *vp)
 2814 {
 2815 
 2816         vputx(vp, VPUTX_VRELE);
 2817 }
 2818 
 2819 /*
 2820  * Release an already locked vnode.  This give the same effects as
 2821  * unlock+vrele(), but takes less time and avoids releasing and
 2822  * re-aquiring the lock (as vrele() acquires the lock internally.)
 2823  */
 2824 void
 2825 vput(struct vnode *vp)
 2826 {
 2827 
 2828         vputx(vp, VPUTX_VPUT);
 2829 }
 2830 
 2831 /*
 2832  * Release an exclusively locked vnode. Do not unlock the vnode lock.
 2833  */
 2834 void
 2835 vunref(struct vnode *vp)
 2836 {
 2837 
 2838         vputx(vp, VPUTX_VUNREF);
 2839 }
 2840 
 2841 /*
 2842  * Increase the hold count and activate if this is the first reference.
 2843  */
 2844 void
 2845 _vhold(struct vnode *vp, bool locked)
 2846 {
 2847         struct mount *mp;
 2848 
 2849         if (locked)
 2850                 ASSERT_VI_LOCKED(vp, __func__);
 2851         else
 2852                 ASSERT_VI_UNLOCKED(vp, __func__);
 2853         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 2854         if (!locked) {
 2855                 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
 2856                         VNODE_REFCOUNT_FENCE_ACQ();
 2857                         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
 2858                             ("_vhold: vnode with holdcnt is free"));
 2859                         return;
 2860                 }
 2861                 VI_LOCK(vp);
 2862         }
 2863         if ((vp->v_iflag & VI_FREE) == 0) {
 2864                 refcount_acquire(&vp->v_holdcnt);
 2865                 if (!locked)
 2866                         VI_UNLOCK(vp);
 2867                 return;
 2868         }
 2869         VNASSERT(vp->v_holdcnt == 0, vp,
 2870             ("%s: wrong hold count", __func__));
 2871         VNASSERT(vp->v_op != NULL, vp,
 2872             ("%s: vnode already reclaimed.", __func__));
 2873         /*
 2874          * Remove a vnode from the free list, mark it as in use,
 2875          * and put it on the active list.
 2876          */
 2877         mtx_lock(&vnode_free_list_mtx);
 2878         TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
 2879         freevnodes--;
 2880         vp->v_iflag &= ~VI_FREE;
 2881         KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
 2882             ("Activating already active vnode"));
 2883         vp->v_iflag |= VI_ACTIVE;
 2884         mp = vp->v_mount;
 2885         TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
 2886         mp->mnt_activevnodelistsize++;
 2887         mtx_unlock(&vnode_free_list_mtx);
 2888         refcount_acquire(&vp->v_holdcnt);
 2889         if (!locked)
 2890                 VI_UNLOCK(vp);
 2891 }
 2892 
 2893 /*
 2894  * Drop the hold count of the vnode.  If this is the last reference to
 2895  * the vnode we place it on the free list unless it has been vgone'd
 2896  * (marked VI_DOOMED) in which case we will free it.
 2897  *
 2898  * Because the vnode vm object keeps a hold reference on the vnode if
 2899  * there is at least one resident non-cached page, the vnode cannot
 2900  * leave the active list without the page cleanup done.
 2901  */
 2902 void
 2903 _vdrop(struct vnode *vp, bool locked)
 2904 {
 2905         struct bufobj *bo;
 2906         struct mount *mp;
 2907         int active;
 2908 
 2909         if (locked)
 2910                 ASSERT_VI_LOCKED(vp, __func__);
 2911         else
 2912                 ASSERT_VI_UNLOCKED(vp, __func__);
 2913         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 2914         if ((int)vp->v_holdcnt <= 0)
 2915                 panic("vdrop: holdcnt %d", vp->v_holdcnt);
 2916         if (!locked) {
 2917                 if (refcount_release_if_not_last(&vp->v_holdcnt))
 2918                         return;
 2919                 VI_LOCK(vp);
 2920         }
 2921         if (refcount_release(&vp->v_holdcnt) == 0) {
 2922                 VI_UNLOCK(vp);
 2923                 return;
 2924         }
 2925         if ((vp->v_iflag & VI_DOOMED) == 0) {
 2926                 /*
 2927                  * Mark a vnode as free: remove it from its active list
 2928                  * and put it up for recycling on the freelist.
 2929                  */
 2930                 VNASSERT(vp->v_op != NULL, vp,
 2931                     ("vdropl: vnode already reclaimed."));
 2932                 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
 2933                     ("vnode already free"));
 2934                 VNASSERT(vp->v_holdcnt == 0, vp,
 2935                     ("vdropl: freeing when we shouldn't"));
 2936                 active = vp->v_iflag & VI_ACTIVE;
 2937                 if ((vp->v_iflag & VI_OWEINACT) == 0) {
 2938                         vp->v_iflag &= ~VI_ACTIVE;
 2939                         mp = vp->v_mount;
 2940                         mtx_lock(&vnode_free_list_mtx);
 2941                         if (active) {
 2942                                 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp,
 2943                                     v_actfreelist);
 2944                                 mp->mnt_activevnodelistsize--;
 2945                         }
 2946                         TAILQ_INSERT_TAIL(&vnode_free_list, vp,
 2947                             v_actfreelist);
 2948                         freevnodes++;
 2949                         vp->v_iflag |= VI_FREE;
 2950                         mtx_unlock(&vnode_free_list_mtx);
 2951                 } else {
 2952                         counter_u64_add(free_owe_inact, 1);
 2953                 }
 2954                 VI_UNLOCK(vp);
 2955                 return;
 2956         }
 2957         /*
 2958          * The vnode has been marked for destruction, so free it.
 2959          *
 2960          * The vnode will be returned to the zone where it will
 2961          * normally remain until it is needed for another vnode. We
 2962          * need to cleanup (or verify that the cleanup has already
 2963          * been done) any residual data left from its current use
 2964          * so as not to contaminate the freshly allocated vnode.
 2965          */
 2966         CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
 2967         atomic_subtract_long(&numvnodes, 1);
 2968         bo = &vp->v_bufobj;
 2969         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
 2970             ("cleaned vnode still on the free list."));
 2971         VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
 2972         VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
 2973         VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
 2974         VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
 2975         VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
 2976         VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
 2977         VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
 2978             ("clean blk trie not empty"));
 2979         VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
 2980         VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
 2981             ("dirty blk trie not empty"));
 2982         VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
 2983         VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
 2984         VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
 2985         VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
 2986             ("Dangling rangelock waiters"));
 2987         VI_UNLOCK(vp);
 2988 #ifdef MAC
 2989         mac_vnode_destroy(vp);
 2990 #endif
 2991         if (vp->v_pollinfo != NULL) {
 2992                 destroy_vpollinfo(vp->v_pollinfo);
 2993                 vp->v_pollinfo = NULL;
 2994         }
 2995 #ifdef INVARIANTS
 2996         /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
 2997         vp->v_op = NULL;
 2998 #endif
 2999         bzero(&vp->v_un, sizeof(vp->v_un));
 3000         vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
 3001         vp->v_iflag = 0;
 3002         vp->v_vflag = 0;
 3003         bo->bo_flag = 0;
 3004         uma_zfree(vnode_zone, vp);
 3005 }
 3006 
 3007 /*
 3008  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
 3009  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
 3010  * OWEINACT tracks whether a vnode missed a call to inactive due to a
 3011  * failed lock upgrade.
 3012  */
 3013 void
 3014 vinactive(struct vnode *vp, struct thread *td)
 3015 {
 3016         struct vm_object *obj;
 3017 
 3018         ASSERT_VOP_ELOCKED(vp, "vinactive");
 3019         ASSERT_VI_LOCKED(vp, "vinactive");
 3020         VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
 3021             ("vinactive: recursed on VI_DOINGINACT"));
 3022         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 3023         vp->v_iflag |= VI_DOINGINACT;
 3024         vp->v_iflag &= ~VI_OWEINACT;
 3025         VI_UNLOCK(vp);
 3026         /*
 3027          * Before moving off the active list, we must be sure that any
 3028          * modified pages are converted into the vnode's dirty
 3029          * buffers, since these will no longer be checked once the
 3030          * vnode is on the inactive list.
 3031          *
 3032          * The write-out of the dirty pages is asynchronous.  At the
 3033          * point that VOP_INACTIVE() is called, there could still be
 3034          * pending I/O and dirty pages in the object.
 3035          */
 3036         if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
 3037             (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
 3038                 VM_OBJECT_WLOCK(obj);
 3039                 vm_object_page_clean(obj, 0, 0, 0);
 3040                 VM_OBJECT_WUNLOCK(obj);
 3041         }
 3042         VOP_INACTIVE(vp, td);
 3043         VI_LOCK(vp);
 3044         VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
 3045             ("vinactive: lost VI_DOINGINACT"));
 3046         vp->v_iflag &= ~VI_DOINGINACT;
 3047 }
 3048 
 3049 /*
 3050  * Remove any vnodes in the vnode table belonging to mount point mp.
 3051  *
 3052  * If FORCECLOSE is not specified, there should not be any active ones,
 3053  * return error if any are found (nb: this is a user error, not a
 3054  * system error). If FORCECLOSE is specified, detach any active vnodes
 3055  * that are found.
 3056  *
 3057  * If WRITECLOSE is set, only flush out regular file vnodes open for
 3058  * writing.
 3059  *
 3060  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
 3061  *
 3062  * `rootrefs' specifies the base reference count for the root vnode
 3063  * of this filesystem. The root vnode is considered busy if its
 3064  * v_usecount exceeds this value. On a successful return, vflush(, td)
 3065  * will call vrele() on the root vnode exactly rootrefs times.
 3066  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
 3067  * be zero.
 3068  */
 3069 #ifdef DIAGNOSTIC
 3070 static int busyprt = 0;         /* print out busy vnodes */
 3071 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
 3072 #endif
 3073 
 3074 int
 3075 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
 3076 {
 3077         struct vnode *vp, *mvp, *rootvp = NULL;
 3078         struct vattr vattr;
 3079         int busy = 0, error;
 3080 
 3081         CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
 3082             rootrefs, flags);
 3083         if (rootrefs > 0) {
 3084                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
 3085                     ("vflush: bad args"));
 3086                 /*
 3087                  * Get the filesystem root vnode. We can vput() it
 3088                  * immediately, since with rootrefs > 0, it won't go away.
 3089                  */
 3090                 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
 3091                         CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
 3092                             __func__, error);
 3093                         return (error);
 3094                 }
 3095                 vput(rootvp);
 3096         }
 3097 loop:
 3098         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
 3099                 vholdl(vp);
 3100                 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
 3101                 if (error) {
 3102                         vdrop(vp);
 3103                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
 3104                         goto loop;
 3105                 }
 3106                 /*
 3107                  * Skip over a vnodes marked VV_SYSTEM.
 3108                  */
 3109                 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
 3110                         VOP_UNLOCK(vp, 0);
 3111                         vdrop(vp);
 3112                         continue;
 3113                 }
 3114                 /*
 3115                  * If WRITECLOSE is set, flush out unlinked but still open
 3116                  * files (even if open only for reading) and regular file
 3117                  * vnodes open for writing.
 3118                  */
 3119                 if (flags & WRITECLOSE) {
 3120                         if (vp->v_object != NULL) {
 3121                                 VM_OBJECT_WLOCK(vp->v_object);
 3122                                 vm_object_page_clean(vp->v_object, 0, 0, 0);
 3123                                 VM_OBJECT_WUNLOCK(vp->v_object);
 3124                         }
 3125                         error = VOP_FSYNC(vp, MNT_WAIT, td);
 3126                         if (error != 0) {
 3127                                 VOP_UNLOCK(vp, 0);
 3128                                 vdrop(vp);
 3129                                 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
 3130                                 return (error);
 3131                         }
 3132                         error = VOP_GETATTR(vp, &vattr, td->td_ucred);
 3133                         VI_LOCK(vp);
 3134 
 3135                         if ((vp->v_type == VNON ||
 3136                             (error == 0 && vattr.va_nlink > 0)) &&
 3137                             (vp->v_writecount == 0 || vp->v_type != VREG)) {
 3138                                 VOP_UNLOCK(vp, 0);
 3139                                 vdropl(vp);
 3140                                 continue;
 3141                         }
 3142                 } else
 3143                         VI_LOCK(vp);
 3144                 /*
 3145                  * With v_usecount == 0, all we need to do is clear out the
 3146                  * vnode data structures and we are done.
 3147                  *
 3148                  * If FORCECLOSE is set, forcibly close the vnode.
 3149                  */
 3150                 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
 3151                         vgonel(vp);
 3152                 } else {
 3153                         busy++;
 3154 #ifdef DIAGNOSTIC
 3155                         if (busyprt)
 3156                                 vn_printf(vp, "vflush: busy vnode ");
 3157 #endif
 3158                 }
 3159                 VOP_UNLOCK(vp, 0);
 3160                 vdropl(vp);
 3161         }
 3162         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
 3163                 /*
 3164                  * If just the root vnode is busy, and if its refcount
 3165                  * is equal to `rootrefs', then go ahead and kill it.
 3166                  */
 3167                 VI_LOCK(rootvp);
 3168                 KASSERT(busy > 0, ("vflush: not busy"));
 3169                 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
 3170                     ("vflush: usecount %d < rootrefs %d",
 3171                      rootvp->v_usecount, rootrefs));
 3172                 if (busy == 1 && rootvp->v_usecount == rootrefs) {
 3173                         VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
 3174                         vgone(rootvp);
 3175                         VOP_UNLOCK(rootvp, 0);
 3176                         busy = 0;
 3177                 } else
 3178                         VI_UNLOCK(rootvp);
 3179         }
 3180         if (busy) {
 3181                 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
 3182                     busy);
 3183                 return (EBUSY);
 3184         }
 3185         for (; rootrefs > 0; rootrefs--)
 3186                 vrele(rootvp);
 3187         return (0);
 3188 }
 3189 
 3190 /*
 3191  * Recycle an unused vnode to the front of the free list.
 3192  */
 3193 int
 3194 vrecycle(struct vnode *vp)
 3195 {
 3196         int recycled;
 3197 
 3198         ASSERT_VOP_ELOCKED(vp, "vrecycle");
 3199         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 3200         recycled = 0;
 3201         VI_LOCK(vp);
 3202         if (vp->v_usecount == 0) {
 3203                 recycled = 1;
 3204                 vgonel(vp);
 3205         }
 3206         VI_UNLOCK(vp);
 3207         return (recycled);
 3208 }
 3209 
 3210 /*
 3211  * Eliminate all activity associated with a vnode
 3212  * in preparation for reuse.
 3213  */
 3214 void
 3215 vgone(struct vnode *vp)
 3216 {
 3217         VI_LOCK(vp);
 3218         vgonel(vp);
 3219         VI_UNLOCK(vp);
 3220 }
 3221 
 3222 static void
 3223 notify_lowervp_vfs_dummy(struct mount *mp __unused,
 3224     struct vnode *lowervp __unused)
 3225 {
 3226 }
 3227 
 3228 /*
 3229  * Notify upper mounts about reclaimed or unlinked vnode.
 3230  */
 3231 void
 3232 vfs_notify_upper(struct vnode *vp, int event)
 3233 {
 3234         static struct vfsops vgonel_vfsops = {
 3235                 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
 3236                 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
 3237         };
 3238         struct mount *mp, *ump, *mmp;
 3239 
 3240         mp = vp->v_mount;
 3241         if (mp == NULL)
 3242                 return;
 3243 
 3244         MNT_ILOCK(mp);
 3245         if (TAILQ_EMPTY(&mp->mnt_uppers))
 3246                 goto unlock;
 3247         MNT_IUNLOCK(mp);
 3248         mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
 3249         mmp->mnt_op = &vgonel_vfsops;
 3250         mmp->mnt_kern_flag |= MNTK_MARKER;
 3251         MNT_ILOCK(mp);
 3252         mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
 3253         for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
 3254                 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
 3255                         ump = TAILQ_NEXT(ump, mnt_upper_link);
 3256                         continue;
 3257                 }
 3258                 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
 3259                 MNT_IUNLOCK(mp);
 3260                 switch (event) {
 3261                 case VFS_NOTIFY_UPPER_RECLAIM:
 3262                         VFS_RECLAIM_LOWERVP(ump, vp);
 3263                         break;
 3264                 case VFS_NOTIFY_UPPER_UNLINK:
 3265                         VFS_UNLINK_LOWERVP(ump, vp);
 3266                         break;
 3267                 default:
 3268                         KASSERT(0, ("invalid event %d", event));
 3269                         break;
 3270                 }
 3271                 MNT_ILOCK(mp);
 3272                 ump = TAILQ_NEXT(mmp, mnt_upper_link);
 3273                 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
 3274         }
 3275         free(mmp, M_TEMP);
 3276         mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
 3277         if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
 3278                 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
 3279                 wakeup(&mp->mnt_uppers);
 3280         }
 3281 unlock:
 3282         MNT_IUNLOCK(mp);
 3283 }
 3284 
 3285 /*
 3286  * vgone, with the vp interlock held.
 3287  */
 3288 static void
 3289 vgonel(struct vnode *vp)
 3290 {
 3291         struct thread *td;
 3292         int oweinact;
 3293         int active;
 3294         struct mount *mp;
 3295 
 3296         ASSERT_VOP_ELOCKED(vp, "vgonel");
 3297         ASSERT_VI_LOCKED(vp, "vgonel");
 3298         VNASSERT(vp->v_holdcnt, vp,
 3299             ("vgonel: vp %p has no reference.", vp));
 3300         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
 3301         td = curthread;
 3302 
 3303         /*
 3304          * Don't vgonel if we're already doomed.
 3305          */
 3306         if (vp->v_iflag & VI_DOOMED)
 3307                 return;
 3308         vp->v_iflag |= VI_DOOMED;
 3309 
 3310         /*
 3311          * Check to see if the vnode is in use.  If so, we have to call
 3312          * VOP_CLOSE() and VOP_INACTIVE().
 3313          */
 3314         active = vp->v_usecount;
 3315         oweinact = (vp->v_iflag & VI_OWEINACT);
 3316         VI_UNLOCK(vp);
 3317         vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
 3318 
 3319         /*
 3320          * If purging an active vnode, it must be closed and
 3321          * deactivated before being reclaimed.
 3322          */
 3323         if (active)
 3324                 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
 3325         if (oweinact || active) {
 3326                 VI_LOCK(vp);
 3327                 if ((vp->v_iflag & VI_DOINGINACT) == 0)
 3328                         vinactive(vp, td);
 3329                 VI_UNLOCK(vp);
 3330         }
 3331         if (vp->v_type == VSOCK)
 3332                 vfs_unp_reclaim(vp);
 3333 
 3334         /*
 3335          * Clean out any buffers associated with the vnode.
 3336          * If the flush fails, just toss the buffers.
 3337          */
 3338         mp = NULL;
 3339         if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
 3340                 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
 3341         if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
 3342                 while (vinvalbuf(vp, 0, 0, 0) != 0)
 3343                         ;
 3344         }
 3345 
 3346         BO_LOCK(&vp->v_bufobj);
 3347         KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
 3348             vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
 3349             TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
 3350             vp->v_bufobj.bo_clean.bv_cnt == 0,
 3351             ("vp %p bufobj not invalidated", vp));
 3352 
 3353         /*
 3354          * For VMIO bufobj, BO_DEAD is set in vm_object_terminate()
 3355          * after the object's page queue is flushed.
 3356          */
 3357         if (vp->v_bufobj.bo_object == NULL)
 3358                 vp->v_bufobj.bo_flag |= BO_DEAD;
 3359         BO_UNLOCK(&vp->v_bufobj);
 3360 
 3361         /*
 3362          * Reclaim the vnode.
 3363          */
 3364         if (VOP_RECLAIM(vp, td))
 3365                 panic("vgone: cannot reclaim");
 3366         if (mp != NULL)
 3367                 vn_finished_secondary_write(mp);
 3368         VNASSERT(vp->v_object == NULL, vp,
 3369             ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
 3370         /*
 3371          * Clear the advisory locks and wake up waiting threads.
 3372          */
 3373         (void)VOP_ADVLOCKPURGE(vp);
 3374         vp->v_lockf = NULL;
 3375         /*
 3376          * Delete from old mount point vnode list.
 3377          */
 3378         delmntque(vp);
 3379         cache_purge(vp);
 3380         /*
 3381          * Done with purge, reset to the standard lock and invalidate
 3382          * the vnode.
 3383          */
 3384         VI_LOCK(vp);
 3385         vp->v_vnlock = &vp->v_lock;
 3386         vp->v_op = &dead_vnodeops;
 3387         vp->v_tag = "none";
 3388         vp->v_type = VBAD;
 3389 }
 3390 
 3391 /*
 3392  * Calculate the total number of references to a special device.
 3393  */
 3394 int
 3395 vcount(struct vnode *vp)
 3396 {
 3397         int count;
 3398 
 3399         dev_lock();
 3400         count = vp->v_rdev->si_usecount;
 3401         dev_unlock();
 3402         return (count);
 3403 }
 3404 
 3405 /*
 3406  * Same as above, but using the struct cdev *as argument
 3407  */
 3408 int
 3409 count_dev(struct cdev *dev)
 3410 {
 3411         int count;
 3412 
 3413         dev_lock();
 3414         count = dev->si_usecount;
 3415         dev_unlock();
 3416         return(count);
 3417 }
 3418 
 3419 /*
 3420  * Print out a description of a vnode.
 3421  */
 3422 static char *typename[] =
 3423 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
 3424  "VMARKER"};
 3425 
 3426 void
 3427 vn_printf(struct vnode *vp, const char *fmt, ...)
 3428 {
 3429         va_list ap;
 3430         char buf[256], buf2[16];
 3431         u_long flags;
 3432 
 3433         va_start(ap, fmt);
 3434         vprintf(fmt, ap);
 3435         va_end(ap);
 3436         printf("%p: ", (void *)vp);
 3437         printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
 3438         printf("    usecount %d, writecount %d, refcount %d",
 3439             vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
 3440         switch (vp->v_type) {
 3441         case VDIR:
 3442                 printf(" mountedhere %p\n", vp->v_mountedhere);
 3443                 break;
 3444         case VCHR:
 3445                 printf(" rdev %p\n", vp->v_rdev);
 3446                 break;
 3447         case VSOCK:
 3448                 printf(" socket %p\n", vp->v_socket);
 3449                 break;
 3450         case VFIFO:
 3451                 printf(" fifoinfo %p\n", vp->v_fifoinfo);
 3452                 break;
 3453         default:
 3454                 printf("\n");
 3455                 break;
 3456         }
 3457         buf[0] = '\0';
 3458         buf[1] = '\0';
 3459         if (vp->v_vflag & VV_ROOT)
 3460                 strlcat(buf, "|VV_ROOT", sizeof(buf));
 3461         if (vp->v_vflag & VV_ISTTY)
 3462                 strlcat(buf, "|VV_ISTTY", sizeof(buf));
 3463         if (vp->v_vflag & VV_NOSYNC)
 3464                 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
 3465         if (vp->v_vflag & VV_ETERNALDEV)
 3466                 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
 3467         if (vp->v_vflag & VV_CACHEDLABEL)
 3468                 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
 3469         if (vp->v_vflag & VV_TEXT)
 3470                 strlcat(buf, "|VV_TEXT", sizeof(buf));
 3471         if (vp->v_vflag & VV_COPYONWRITE)
 3472                 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
 3473         if (vp->v_vflag & VV_SYSTEM)
 3474                 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
 3475         if (vp->v_vflag & VV_PROCDEP)
 3476                 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
 3477         if (vp->v_vflag & VV_NOKNOTE)
 3478                 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
 3479         if (vp->v_vflag & VV_DELETED)
 3480                 strlcat(buf, "|VV_DELETED", sizeof(buf));
 3481         if (vp->v_vflag & VV_MD)
 3482                 strlcat(buf, "|VV_MD", sizeof(buf));
 3483         if (vp->v_vflag & VV_FORCEINSMQ)
 3484                 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
 3485         flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
 3486             VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
 3487             VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
 3488         if (flags != 0) {
 3489                 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
 3490                 strlcat(buf, buf2, sizeof(buf));
 3491         }
 3492         if (vp->v_iflag & VI_MOUNT)
 3493                 strlcat(buf, "|VI_MOUNT", sizeof(buf));
 3494         if (vp->v_iflag & VI_DOOMED)
 3495                 strlcat(buf, "|VI_DOOMED", sizeof(buf));
 3496         if (vp->v_iflag & VI_FREE)
 3497                 strlcat(buf, "|VI_FREE", sizeof(buf));
 3498         if (vp->v_iflag & VI_ACTIVE)
 3499                 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
 3500         if (vp->v_iflag & VI_DOINGINACT)
 3501                 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
 3502         if (vp->v_iflag & VI_OWEINACT)
 3503                 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
 3504         flags = vp->v_iflag & ~(VI_MOUNT | VI_DOOMED | VI_FREE |
 3505             VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
 3506         if (flags != 0) {
 3507                 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
 3508                 strlcat(buf, buf2, sizeof(buf));
 3509         }
 3510         printf("    flags (%s)\n", buf + 1);
 3511         if (mtx_owned(VI_MTX(vp)))
 3512                 printf(" VI_LOCKed");
 3513         if (vp->v_object != NULL)
 3514                 printf("    v_object %p ref %d pages %d "
 3515                     "cleanbuf %d dirtybuf %d\n",
 3516                     vp->v_object, vp->v_object->ref_count,
 3517                     vp->v_object->resident_page_count,
 3518                     vp->v_bufobj.bo_clean.bv_cnt,
 3519                     vp->v_bufobj.bo_dirty.bv_cnt);
 3520         printf("    ");
 3521         lockmgr_printinfo(vp->v_vnlock);
 3522         if (vp->v_data != NULL)
 3523                 VOP_PRINT(vp);
 3524 }
 3525 
 3526 #ifdef DDB
 3527 /*
 3528  * List all of the locked vnodes in the system.
 3529  * Called when debugging the kernel.
 3530  */
 3531 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
 3532 {
 3533         struct mount *mp;
 3534         struct vnode *vp;
 3535 
 3536         /*
 3537          * Note: because this is DDB, we can't obey the locking semantics
 3538          * for these structures, which means we could catch an inconsistent
 3539          * state and dereference a nasty pointer.  Not much to be done
 3540          * about that.
 3541          */
 3542         db_printf("Locked vnodes\n");
 3543         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
 3544                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
 3545                         if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
 3546                                 vn_printf(vp, "vnode ");
 3547                 }
 3548         }
 3549 }
 3550 
 3551 /*
 3552  * Show details about the given vnode.
 3553  */
 3554 DB_SHOW_COMMAND(vnode, db_show_vnode)
 3555 {
 3556         struct vnode *vp;
 3557 
 3558         if (!have_addr)
 3559                 return;
 3560         vp = (struct vnode *)addr;
 3561         vn_printf(vp, "vnode ");
 3562 }
 3563 
 3564 /*
 3565  * Show details about the given mount point.
 3566  */
 3567 DB_SHOW_COMMAND(mount, db_show_mount)
 3568 {
 3569         struct mount *mp;
 3570         struct vfsopt *opt;
 3571         struct statfs *sp;
 3572         struct vnode *vp;
 3573         char buf[512];
 3574         uint64_t mflags;
 3575         u_int flags;
 3576 
 3577         if (!have_addr) {
 3578                 /* No address given, print short info about all mount points. */
 3579                 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
 3580                         db_printf("%p %s on %s (%s)\n", mp,
 3581                             mp->mnt_stat.f_mntfromname,
 3582                             mp->mnt_stat.f_mntonname,
 3583                             mp->mnt_stat.f_fstypename);
 3584                         if (db_pager_quit)
 3585                                 break;
 3586                 }
 3587                 db_printf("\nMore info: show mount <addr>\n");
 3588                 return;
 3589         }
 3590 
 3591         mp = (struct mount *)addr;
 3592         db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
 3593             mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
 3594 
 3595         buf[0] = '\0';
 3596         mflags = mp->mnt_flag;
 3597 #define MNT_FLAG(flag)  do {                                            \
 3598         if (mflags & (flag)) {                                          \
 3599                 if (buf[0] != '\0')                                     \
 3600                         strlcat(buf, ", ", sizeof(buf));                \
 3601                 strlcat(buf, (#flag) + 4, sizeof(buf));                 \
 3602                 mflags &= ~(flag);                                      \
 3603         }                                                               \
 3604 } while (0)
 3605         MNT_FLAG(MNT_RDONLY);
 3606         MNT_FLAG(MNT_SYNCHRONOUS);
 3607         MNT_FLAG(MNT_NOEXEC);
 3608         MNT_FLAG(MNT_NOSUID);
 3609         MNT_FLAG(MNT_NFS4ACLS);
 3610         MNT_FLAG(MNT_UNION);
 3611         MNT_FLAG(MNT_ASYNC);
 3612         MNT_FLAG(MNT_SUIDDIR);
 3613         MNT_FLAG(MNT_SOFTDEP);
 3614         MNT_FLAG(MNT_NOSYMFOLLOW);
 3615         MNT_FLAG(MNT_GJOURNAL);
 3616         MNT_FLAG(MNT_MULTILABEL);
 3617         MNT_FLAG(MNT_ACLS);
 3618         MNT_FLAG(MNT_NOATIME);
 3619         MNT_FLAG(MNT_NOCLUSTERR);
 3620         MNT_FLAG(MNT_NOCLUSTERW);
 3621         MNT_FLAG(MNT_SUJ);
 3622         MNT_FLAG(MNT_EXRDONLY);
 3623         MNT_FLAG(MNT_EXPORTED);
 3624         MNT_FLAG(MNT_DEFEXPORTED);
 3625         MNT_FLAG(MNT_EXPORTANON);
 3626         MNT_FLAG(MNT_EXKERB);
 3627         MNT_FLAG(MNT_EXPUBLIC);
 3628         MNT_FLAG(MNT_LOCAL);
 3629         MNT_FLAG(MNT_QUOTA);
 3630         MNT_FLAG(MNT_ROOTFS);
 3631         MNT_FLAG(MNT_USER);
 3632         MNT_FLAG(MNT_IGNORE);
 3633         MNT_FLAG(MNT_UPDATE);
 3634         MNT_FLAG(MNT_DELEXPORT);
 3635         MNT_FLAG(MNT_RELOAD);
 3636         MNT_FLAG(MNT_FORCE);
 3637         MNT_FLAG(MNT_SNAPSHOT);
 3638         MNT_FLAG(MNT_BYFSID);
 3639 #undef MNT_FLAG
 3640         if (mflags != 0) {
 3641                 if (buf[0] != '\0')
 3642                         strlcat(buf, ", ", sizeof(buf));
 3643                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
 3644                     "0x%016jx", mflags);
 3645         }
 3646         db_printf("    mnt_flag = %s\n", buf);
 3647 
 3648         buf[0] = '\0';
 3649         flags = mp->mnt_kern_flag;
 3650 #define MNT_KERN_FLAG(flag)     do {                                    \
 3651         if (flags & (flag)) {                                           \
 3652                 if (buf[0] != '\0')                                     \
 3653                         strlcat(buf, ", ", sizeof(buf));                \
 3654                 strlcat(buf, (#flag) + 5, sizeof(buf));                 \
 3655                 flags &= ~(flag);                                       \
 3656         }                                                               \
 3657 } while (0)
 3658         MNT_KERN_FLAG(MNTK_UNMOUNTF);
 3659         MNT_KERN_FLAG(MNTK_ASYNC);
 3660         MNT_KERN_FLAG(MNTK_SOFTDEP);
 3661         MNT_KERN_FLAG(MNTK_NOINSMNTQ);
 3662         MNT_KERN_FLAG(MNTK_DRAINING);
 3663         MNT_KERN_FLAG(MNTK_REFEXPIRE);
 3664         MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
 3665         MNT_KERN_FLAG(MNTK_SHARED_WRITES);
 3666         MNT_KERN_FLAG(MNTK_NO_IOPF);
 3667         MNT_KERN_FLAG(MNTK_VGONE_UPPER);
 3668         MNT_KERN_FLAG(MNTK_VGONE_WAITER);
 3669         MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
 3670         MNT_KERN_FLAG(MNTK_MARKER);
 3671         MNT_KERN_FLAG(MNTK_USES_BCACHE);
 3672         MNT_KERN_FLAG(MNTK_NOASYNC);
 3673         MNT_KERN_FLAG(MNTK_UNMOUNT);
 3674         MNT_KERN_FLAG(MNTK_MWAIT);
 3675         MNT_KERN_FLAG(MNTK_SUSPEND);
 3676         MNT_KERN_FLAG(MNTK_SUSPEND2);
 3677         MNT_KERN_FLAG(MNTK_SUSPENDED);
 3678         MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
 3679         MNT_KERN_FLAG(MNTK_NOKNOTE);
 3680 #undef MNT_KERN_FLAG
 3681         if (flags != 0) {
 3682                 if (buf[0] != '\0')
 3683                         strlcat(buf, ", ", sizeof(buf));
 3684                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
 3685                     "0x%08x", flags);
 3686         }
 3687         db_printf("    mnt_kern_flag = %s\n", buf);
 3688 
 3689         db_printf("    mnt_opt = ");
 3690         opt = TAILQ_FIRST(mp->mnt_opt);
 3691         if (opt != NULL) {
 3692                 db_printf("%s", opt->name);
 3693                 opt = TAILQ_NEXT(opt, link);
 3694                 while (opt != NULL) {
 3695                         db_printf(", %s", opt->name);
 3696                         opt = TAILQ_NEXT(opt, link);
 3697                 }
 3698         }
 3699         db_printf("\n");
 3700 
 3701         sp = &mp->mnt_stat;
 3702         db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
 3703             "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
 3704             "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
 3705             "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
 3706             (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
 3707             (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
 3708             (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
 3709             (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
 3710             (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
 3711             (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
 3712             (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
 3713             (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
 3714 
 3715         db_printf("    mnt_cred = { uid=%u ruid=%u",
 3716             (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
 3717         if (jailed(mp->mnt_cred))
 3718                 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
 3719         db_printf(" }\n");
 3720         db_printf("    mnt_ref = %d\n", mp->mnt_ref);
 3721         db_printf("    mnt_gen = %d\n", mp->mnt_gen);
 3722         db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
 3723         db_printf("    mnt_activevnodelistsize = %d\n",
 3724             mp->mnt_activevnodelistsize);
 3725         db_printf("    mnt_writeopcount = %d\n", mp->mnt_writeopcount);
 3726         db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
 3727         db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
 3728         db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
 3729         db_printf("    mnt_lockref = %d\n", mp->mnt_lockref);
 3730         db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
 3731         db_printf("    mnt_secondary_accwrites = %d\n",
 3732             mp->mnt_secondary_accwrites);
 3733         db_printf("    mnt_gjprovider = %s\n",
 3734             mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
 3735 
 3736         db_printf("\n\nList of active vnodes\n");
 3737         TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
 3738                 if (vp->v_type != VMARKER) {
 3739                         vn_printf(vp, "vnode ");
 3740                         if (db_pager_quit)
 3741                                 break;
 3742                 }
 3743         }
 3744         db_printf("\n\nList of inactive vnodes\n");
 3745         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
 3746                 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
 3747                         vn_printf(vp, "vnode ");
 3748                         if (db_pager_quit)
 3749                                 break;
 3750                 }
 3751         }
 3752 }
 3753 #endif  /* DDB */
 3754 
 3755 /*
 3756  * Fill in a struct xvfsconf based on a struct vfsconf.
 3757  */
 3758 static int
 3759 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
 3760 {
 3761         struct xvfsconf xvfsp;
 3762 
 3763         bzero(&xvfsp, sizeof(xvfsp));
 3764         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
 3765         xvfsp.vfc_typenum = vfsp->vfc_typenum;
 3766         xvfsp.vfc_refcount = vfsp->vfc_refcount;
 3767         xvfsp.vfc_flags = vfsp->vfc_flags;
 3768         /*
 3769          * These are unused in userland, we keep them
 3770          * to not break binary compatibility.
 3771          */
 3772         xvfsp.vfc_vfsops = NULL;
 3773         xvfsp.vfc_next = NULL;
 3774         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
 3775 }
 3776 
 3777 #ifdef COMPAT_FREEBSD32
 3778 struct xvfsconf32 {
 3779         uint32_t        vfc_vfsops;
 3780         char            vfc_name[MFSNAMELEN];
 3781         int32_t         vfc_typenum;
 3782         int32_t         vfc_refcount;
 3783         int32_t         vfc_flags;
 3784         uint32_t        vfc_next;
 3785 };
 3786 
 3787 static int
 3788 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
 3789 {
 3790         struct xvfsconf32 xvfsp;
 3791 
 3792         bzero(&xvfsp, sizeof(xvfsp));
 3793         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
 3794         xvfsp.vfc_typenum = vfsp->vfc_typenum;
 3795         xvfsp.vfc_refcount = vfsp->vfc_refcount;
 3796         xvfsp.vfc_flags = vfsp->vfc_flags;
 3797         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
 3798 }
 3799 #endif
 3800 
 3801 /*
 3802  * Top level filesystem related information gathering.
 3803  */
 3804 static int
 3805 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
 3806 {
 3807         struct vfsconf *vfsp;
 3808         int error;
 3809 
 3810         error = 0;
 3811         vfsconf_slock();
 3812         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
 3813 #ifdef COMPAT_FREEBSD32
 3814                 if (req->flags & SCTL_MASK32)
 3815                         error = vfsconf2x32(req, vfsp);
 3816                 else
 3817 #endif
 3818                         error = vfsconf2x(req, vfsp);
 3819                 if (error)
 3820                         break;
 3821         }
 3822         vfsconf_sunlock();
 3823         return (error);
 3824 }
 3825 
 3826 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
 3827     CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
 3828     "S,xvfsconf", "List of all configured filesystems");
 3829 
 3830 #ifndef BURN_BRIDGES
 3831 static int      sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
 3832 
 3833 static int
 3834 vfs_sysctl(SYSCTL_HANDLER_ARGS)
 3835 {
 3836         int *name = (int *)arg1 - 1;    /* XXX */
 3837         u_int namelen = arg2 + 1;       /* XXX */
 3838         struct vfsconf *vfsp;
 3839 
 3840         log(LOG_WARNING, "userland calling deprecated sysctl, "
 3841             "please rebuild world\n");
 3842 
 3843 #if 1 || defined(COMPAT_PRELITE2)
 3844         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
 3845         if (namelen == 1)
 3846                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
 3847 #endif
 3848 
 3849         switch (name[1]) {
 3850         case VFS_MAXTYPENUM:
 3851                 if (namelen != 2)
 3852                         return (ENOTDIR);
 3853                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
 3854         case VFS_CONF:
 3855                 if (namelen != 3)
 3856                         return (ENOTDIR);       /* overloaded */
 3857                 vfsconf_slock();
 3858                 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
 3859                         if (vfsp->vfc_typenum == name[2])
 3860                                 break;
 3861                 }
 3862                 vfsconf_sunlock();
 3863                 if (vfsp == NULL)
 3864                         return (EOPNOTSUPP);
 3865 #ifdef COMPAT_FREEBSD32
 3866                 if (req->flags & SCTL_MASK32)
 3867                         return (vfsconf2x32(req, vfsp));
 3868                 else
 3869 #endif
 3870                         return (vfsconf2x(req, vfsp));
 3871         }
 3872         return (EOPNOTSUPP);
 3873 }
 3874 
 3875 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
 3876     CTLFLAG_MPSAFE, vfs_sysctl,
 3877     "Generic filesystem");
 3878 
 3879 #if 1 || defined(COMPAT_PRELITE2)
 3880 
 3881 static int
 3882 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
 3883 {
 3884         int error;
 3885         struct vfsconf *vfsp;
 3886         struct ovfsconf ovfs;
 3887 
 3888         vfsconf_slock();
 3889         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
 3890                 bzero(&ovfs, sizeof(ovfs));
 3891                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
 3892                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
 3893                 ovfs.vfc_index = vfsp->vfc_typenum;
 3894                 ovfs.vfc_refcount = vfsp->vfc_refcount;
 3895                 ovfs.vfc_flags = vfsp->vfc_flags;
 3896                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
 3897                 if (error != 0) {
 3898                         vfsconf_sunlock();
 3899                         return (error);
 3900                 }
 3901         }
 3902         vfsconf_sunlock();
 3903         return (0);
 3904 }
 3905 
 3906 #endif /* 1 || COMPAT_PRELITE2 */
 3907 #endif /* !BURN_BRIDGES */
 3908 
 3909 #define KINFO_VNODESLOP         10
 3910 #ifdef notyet
 3911 /*
 3912  * Dump vnode list (via sysctl).
 3913  */
 3914 /* ARGSUSED */
 3915 static int
 3916 sysctl_vnode(SYSCTL_HANDLER_ARGS)
 3917 {
 3918         struct xvnode *xvn;
 3919         struct mount *mp;
 3920         struct vnode *vp;
 3921         int error, len, n;
 3922 
 3923         /*
 3924          * Stale numvnodes access is not fatal here.
 3925          */
 3926         req->lock = 0;
 3927         len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
 3928         if (!req->oldptr)
 3929                 /* Make an estimate */
 3930                 return (SYSCTL_OUT(req, 0, len));
 3931 
 3932         error = sysctl_wire_old_buffer(req, 0);
 3933         if (error != 0)
 3934                 return (error);
 3935         xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
 3936         n = 0;
 3937         mtx_lock(&mountlist_mtx);
 3938         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
 3939                 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
 3940                         continue;
 3941                 MNT_ILOCK(mp);
 3942                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
 3943                         if (n == len)
 3944                                 break;
 3945                         vref(vp);
 3946                         xvn[n].xv_size = sizeof *xvn;
 3947                         xvn[n].xv_vnode = vp;
 3948                         xvn[n].xv_id = 0;       /* XXX compat */
 3949 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
 3950                         XV_COPY(usecount);
 3951                         XV_COPY(writecount);
 3952                         XV_COPY(holdcnt);
 3953                         XV_COPY(mount);
 3954                         XV_COPY(numoutput);
 3955                         XV_COPY(type);
 3956 #undef XV_COPY
 3957                         xvn[n].xv_flag = vp->v_vflag;
 3958 
 3959                         switch (vp->v_type) {
 3960                         case VREG:
 3961                         case VDIR:
 3962                         case VLNK:
 3963                                 break;
 3964                         case VBLK:
 3965                         case VCHR:
 3966                                 if (vp->v_rdev == NULL) {
 3967                                         vrele(vp);
 3968                                         continue;
 3969                                 }
 3970                                 xvn[n].xv_dev = dev2udev(vp->v_rdev);
 3971                                 break;
 3972                         case VSOCK:
 3973                                 xvn[n].xv_socket = vp->v_socket;
 3974                                 break;
 3975                         case VFIFO:
 3976                                 xvn[n].xv_fifo = vp->v_fifoinfo;
 3977                                 break;
 3978                         case VNON:
 3979                         case VBAD:
 3980                         default:
 3981                                 /* shouldn't happen? */
 3982                                 vrele(vp);
 3983                                 continue;
 3984                         }
 3985                         vrele(vp);
 3986                         ++n;
 3987                 }
 3988                 MNT_IUNLOCK(mp);
 3989                 mtx_lock(&mountlist_mtx);
 3990                 vfs_unbusy(mp);
 3991                 if (n == len)
 3992                         break;
 3993         }
 3994         mtx_unlock(&mountlist_mtx);
 3995 
 3996         error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
 3997         free(xvn, M_TEMP);
 3998         return (error);
 3999 }
 4000 
 4001 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
 4002     CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
 4003     "");
 4004 #endif
 4005 
 4006 static void
 4007 unmount_or_warn(struct mount *mp)
 4008 {
 4009         int error;
 4010 
 4011         error = dounmount(mp, MNT_FORCE, curthread);
 4012         if (error != 0) {
 4013                 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
 4014                 if (error == EBUSY)
 4015                         printf("BUSY)\n");
 4016                 else
 4017                         printf("%d)\n", error);
 4018         }
 4019 }
 4020 
 4021 /*
 4022  * Unmount all filesystems. The list is traversed in reverse order
 4023  * of mounting to avoid dependencies.
 4024  */
 4025 void
 4026 vfs_unmountall(void)
 4027 {
 4028         struct mount *mp, *tmp;
 4029 
 4030         CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
 4031 
 4032         /*
 4033          * Since this only runs when rebooting, it is not interlocked.
 4034          */
 4035         TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
 4036                 vfs_ref(mp);
 4037 
 4038                 /*
 4039                  * Forcibly unmounting "/dev" before "/" would prevent clean
 4040                  * unmount of the latter.
 4041                  */
 4042                 if (mp == rootdevmp)
 4043                         continue;
 4044 
 4045                 unmount_or_warn(mp);
 4046         }
 4047 
 4048         if (rootdevmp != NULL)
 4049                 unmount_or_warn(rootdevmp);
 4050 }
 4051 
 4052 /*
 4053  * perform msync on all vnodes under a mount point
 4054  * the mount point must be locked.
 4055  */
 4056 void
 4057 vfs_msync(struct mount *mp, int flags)
 4058 {
 4059         struct vnode *vp, *mvp;
 4060         struct vm_object *obj;
 4061 
 4062         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
 4063         MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
 4064                 obj = vp->v_object;
 4065                 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
 4066                     (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
 4067                         if (!vget(vp,
 4068                             LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
 4069                             curthread)) {
 4070                                 if (vp->v_vflag & VV_NOSYNC) {  /* unlinked */
 4071                                         vput(vp);
 4072                                         continue;
 4073                                 }
 4074 
 4075                                 obj = vp->v_object;
 4076                                 if (obj != NULL) {
 4077                                         VM_OBJECT_WLOCK(obj);
 4078                                         vm_object_page_clean(obj, 0, 0,
 4079                                             flags == MNT_WAIT ?
 4080                                             OBJPC_SYNC : OBJPC_NOSYNC);
 4081                                         VM_OBJECT_WUNLOCK(obj);
 4082                                 }
 4083                                 vput(vp);
 4084                         }
 4085                 } else
 4086                         VI_UNLOCK(vp);
 4087         }
 4088 }
 4089 
 4090 static void
 4091 destroy_vpollinfo_free(struct vpollinfo *vi)
 4092 {
 4093 
 4094         knlist_destroy(&vi->vpi_selinfo.si_note);
 4095         mtx_destroy(&vi->vpi_lock);
 4096         uma_zfree(vnodepoll_zone, vi);
 4097 }
 4098 
 4099 static void
 4100 destroy_vpollinfo(struct vpollinfo *vi)
 4101 {
 4102 
 4103         knlist_clear(&vi->vpi_selinfo.si_note, 1);
 4104         seldrain(&vi->vpi_selinfo);
 4105         destroy_vpollinfo_free(vi);
 4106 }
 4107 
 4108 /*
 4109  * Initialize per-vnode helper structure to hold poll-related state.
 4110  */
 4111 void
 4112 v_addpollinfo(struct vnode *vp)
 4113 {
 4114         struct vpollinfo *vi;
 4115 
 4116         if (vp->v_pollinfo != NULL)
 4117                 return;
 4118         vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
 4119         mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
 4120         knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
 4121             vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
 4122         VI_LOCK(vp);
 4123         if (vp->v_pollinfo != NULL) {
 4124                 VI_UNLOCK(vp);
 4125                 destroy_vpollinfo_free(vi);
 4126                 return;
 4127         }
 4128         vp->v_pollinfo = vi;
 4129         VI_UNLOCK(vp);
 4130 }
 4131 
 4132 /*
 4133  * Record a process's interest in events which might happen to
 4134  * a vnode.  Because poll uses the historic select-style interface
 4135  * internally, this routine serves as both the ``check for any
 4136  * pending events'' and the ``record my interest in future events''
 4137  * functions.  (These are done together, while the lock is held,
 4138  * to avoid race conditions.)
 4139  */
 4140 int
 4141 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
 4142 {
 4143 
 4144         v_addpollinfo(vp);
 4145         mtx_lock(&vp->v_pollinfo->vpi_lock);
 4146         if (vp->v_pollinfo->vpi_revents & events) {
 4147                 /*
 4148                  * This leaves events we are not interested
 4149                  * in available for the other process which
 4150                  * which presumably had requested them
 4151                  * (otherwise they would never have been
 4152                  * recorded).
 4153                  */
 4154                 events &= vp->v_pollinfo->vpi_revents;
 4155                 vp->v_pollinfo->vpi_revents &= ~events;
 4156 
 4157                 mtx_unlock(&vp->v_pollinfo->vpi_lock);
 4158                 return (events);
 4159         }
 4160         vp->v_pollinfo->vpi_events |= events;
 4161         selrecord(td, &vp->v_pollinfo->vpi_selinfo);
 4162         mtx_unlock(&vp->v_pollinfo->vpi_lock);
 4163         return (0);
 4164 }
 4165 
 4166 /*
 4167  * Routine to create and manage a filesystem syncer vnode.
 4168  */
 4169 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
 4170 static int      sync_fsync(struct  vop_fsync_args *);
 4171 static int      sync_inactive(struct  vop_inactive_args *);
 4172 static int      sync_reclaim(struct  vop_reclaim_args *);
 4173 
 4174 static struct vop_vector sync_vnodeops = {
 4175         .vop_bypass =   VOP_EOPNOTSUPP,
 4176         .vop_close =    sync_close,             /* close */
 4177         .vop_fsync =    sync_fsync,             /* fsync */
 4178         .vop_inactive = sync_inactive,  /* inactive */
 4179         .vop_reclaim =  sync_reclaim,   /* reclaim */
 4180         .vop_lock1 =    vop_stdlock,    /* lock */
 4181         .vop_unlock =   vop_stdunlock,  /* unlock */
 4182         .vop_islocked = vop_stdislocked,        /* islocked */
 4183 };
 4184 
 4185 /*
 4186  * Create a new filesystem syncer vnode for the specified mount point.
 4187  */
 4188 void
 4189 vfs_allocate_syncvnode(struct mount *mp)
 4190 {
 4191         struct vnode *vp;
 4192         struct bufobj *bo;
 4193         static long start, incr, next;
 4194         int error;
 4195 
 4196         /* Allocate a new vnode */
 4197         error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
 4198         if (error != 0)
 4199                 panic("vfs_allocate_syncvnode: getnewvnode() failed");
 4200         vp->v_type = VNON;
 4201         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
 4202         vp->v_vflag |= VV_FORCEINSMQ;
 4203         error = insmntque(vp, mp);
 4204         if (error != 0)
 4205                 panic("vfs_allocate_syncvnode: insmntque() failed");
 4206         vp->v_vflag &= ~VV_FORCEINSMQ;
 4207         VOP_UNLOCK(vp, 0);
 4208         /*
 4209          * Place the vnode onto the syncer worklist. We attempt to
 4210          * scatter them about on the list so that they will go off
 4211          * at evenly distributed times even if all the filesystems
 4212          * are mounted at once.
 4213          */
 4214         next += incr;
 4215         if (next == 0 || next > syncer_maxdelay) {
 4216                 start /= 2;
 4217                 incr /= 2;
 4218                 if (start == 0) {
 4219                         start = syncer_maxdelay / 2;
 4220                         incr = syncer_maxdelay;
 4221                 }
 4222                 next = start;
 4223         }
 4224         bo = &vp->v_bufobj;
 4225         BO_LOCK(bo);
 4226         vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
 4227         /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
 4228         mtx_lock(&sync_mtx);
 4229         sync_vnode_count++;
 4230         if (mp->mnt_syncer == NULL) {
 4231                 mp->mnt_syncer = vp;
 4232                 vp = NULL;
 4233         }
 4234         mtx_unlock(&sync_mtx);
 4235         BO_UNLOCK(bo);
 4236         if (vp != NULL) {
 4237                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
 4238                 vgone(vp);
 4239                 vput(vp);
 4240         }
 4241 }
 4242 
 4243 void
 4244 vfs_deallocate_syncvnode(struct mount *mp)
 4245 {
 4246         struct vnode *vp;
 4247 
 4248         mtx_lock(&sync_mtx);
 4249         vp = mp->mnt_syncer;
 4250         if (vp != NULL)
 4251                 mp->mnt_syncer = NULL;
 4252         mtx_unlock(&sync_mtx);
 4253         if (vp != NULL)
 4254                 vrele(vp);
 4255 }
 4256 
 4257 /*
 4258  * Do a lazy sync of the filesystem.
 4259  */
 4260 static int
 4261 sync_fsync(struct vop_fsync_args *ap)
 4262 {
 4263         struct vnode *syncvp = ap->a_vp;
 4264         struct mount *mp = syncvp->v_mount;
 4265         int error, save;
 4266         struct bufobj *bo;
 4267 
 4268         /*
 4269          * We only need to do something if this is a lazy evaluation.
 4270          */
 4271         if (ap->a_waitfor != MNT_LAZY)
 4272                 return (0);
 4273 
 4274         /*
 4275          * Move ourselves to the back of the sync list.
 4276          */
 4277         bo = &syncvp->v_bufobj;
 4278         BO_LOCK(bo);
 4279         vn_syncer_add_to_worklist(bo, syncdelay);
 4280         BO_UNLOCK(bo);
 4281 
 4282         /*
 4283          * Walk the list of vnodes pushing all that are dirty and
 4284          * not already on the sync list.
 4285          */
 4286         if (vfs_busy(mp, MBF_NOWAIT) != 0)
 4287                 return (0);
 4288         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
 4289                 vfs_unbusy(mp);
 4290                 return (0);
 4291         }
 4292         save = curthread_pflags_set(TDP_SYNCIO);
 4293         vfs_msync(mp, MNT_NOWAIT);
 4294         error = VFS_SYNC(mp, MNT_LAZY);
 4295         curthread_pflags_restore(save);
 4296         vn_finished_write(mp);
 4297         vfs_unbusy(mp);
 4298         return (error);
 4299 }
 4300 
 4301 /*
 4302  * The syncer vnode is no referenced.
 4303  */
 4304 static int
 4305 sync_inactive(struct vop_inactive_args *ap)
 4306 {
 4307 
 4308         vgone(ap->a_vp);
 4309         return (0);
 4310 }
 4311 
 4312 /*
 4313  * The syncer vnode is no longer needed and is being decommissioned.
 4314  *
 4315  * Modifications to the worklist must be protected by sync_mtx.
 4316  */
 4317 static int
 4318 sync_reclaim(struct vop_reclaim_args *ap)
 4319 {
 4320         struct vnode *vp = ap->a_vp;
 4321         struct bufobj *bo;
 4322 
 4323         bo = &vp->v_bufobj;
 4324         BO_LOCK(bo);
 4325         mtx_lock(&sync_mtx);
 4326         if (vp->v_mount->mnt_syncer == vp)
 4327                 vp->v_mount->mnt_syncer = NULL;
 4328         if (bo->bo_flag & BO_ONWORKLST) {
 4329                 LIST_REMOVE(bo, bo_synclist);
 4330                 syncer_worklist_len--;
 4331                 sync_vnode_count--;
 4332                 bo->bo_flag &= ~BO_ONWORKLST;
 4333         }
 4334         mtx_unlock(&sync_mtx);
 4335         BO_UNLOCK(bo);
 4336 
 4337         return (0);
 4338 }
 4339 
 4340 /*
 4341  * Check if vnode represents a disk device
 4342  */
 4343 int
 4344 vn_isdisk(struct vnode *vp, int *errp)
 4345 {
 4346         int error;
 4347 
 4348         if (vp->v_type != VCHR) {
 4349                 error = ENOTBLK;
 4350                 goto out;
 4351         }
 4352         error = 0;
 4353         dev_lock();
 4354         if (vp->v_rdev == NULL)
 4355                 error = ENXIO;
 4356         else if (vp->v_rdev->si_devsw == NULL)
 4357                 error = ENXIO;
 4358         else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
 4359                 error = ENOTBLK;
 4360         dev_unlock();
 4361 out:
 4362         if (errp != NULL)
 4363                 *errp = error;
 4364         return (error == 0);
 4365 }
 4366 
 4367 /*
 4368  * Common filesystem object access control check routine.  Accepts a
 4369  * vnode's type, "mode", uid and gid, requested access mode, credentials,
 4370  * and optional call-by-reference privused argument allowing vaccess()
 4371  * to indicate to the caller whether privilege was used to satisfy the
 4372  * request (obsoleted).  Returns 0 on success, or an errno on failure.
 4373  */
 4374 int
 4375 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
 4376     accmode_t accmode, struct ucred *cred, int *privused)
 4377 {
 4378         accmode_t dac_granted;
 4379         accmode_t priv_granted;
 4380 
 4381         KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
 4382             ("invalid bit in accmode"));
 4383         KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
 4384             ("VAPPEND without VWRITE"));
 4385 
 4386         /*
 4387          * Look for a normal, non-privileged way to access the file/directory
 4388          * as requested.  If it exists, go with that.
 4389          */
 4390 
 4391         if (privused != NULL)
 4392                 *privused = 0;
 4393 
 4394         dac_granted = 0;
 4395 
 4396         /* Check the owner. */
 4397         if (cred->cr_uid == file_uid) {
 4398                 dac_granted |= VADMIN;
 4399                 if (file_mode & S_IXUSR)
 4400                         dac_granted |= VEXEC;
 4401                 if (file_mode & S_IRUSR)
 4402                         dac_granted |= VREAD;
 4403                 if (file_mode & S_IWUSR)
 4404                         dac_granted |= (VWRITE | VAPPEND);
 4405 
 4406                 if ((accmode & dac_granted) == accmode)
 4407                         return (0);
 4408 
 4409                 goto privcheck;
 4410         }
 4411 
 4412         /* Otherwise, check the groups (first match) */
 4413         if (groupmember(file_gid, cred)) {
 4414                 if (file_mode & S_IXGRP)
 4415                         dac_granted |= VEXEC;
 4416                 if (file_mode & S_IRGRP)
 4417                         dac_granted |= VREAD;
 4418                 if (file_mode & S_IWGRP)
 4419                         dac_granted |= (VWRITE | VAPPEND);
 4420 
 4421                 if ((accmode & dac_granted) == accmode)
 4422                         return (0);
 4423 
 4424                 goto privcheck;
 4425         }
 4426 
 4427         /* Otherwise, check everyone else. */
 4428         if (file_mode & S_IXOTH)
 4429                 dac_granted |= VEXEC;
 4430         if (file_mode & S_IROTH)
 4431                 dac_granted |= VREAD;
 4432         if (file_mode & S_IWOTH)
 4433                 dac_granted |= (VWRITE | VAPPEND);
 4434         if ((accmode & dac_granted) == accmode)
 4435                 return (0);
 4436 
 4437 privcheck:
 4438         /*
 4439          * Build a privilege mask to determine if the set of privileges
 4440          * satisfies the requirements when combined with the granted mask
 4441          * from above.  For each privilege, if the privilege is required,
 4442          * bitwise or the request type onto the priv_granted mask.
 4443          */
 4444         priv_granted = 0;
 4445 
 4446         if (type == VDIR) {
 4447                 /*
 4448                  * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
 4449                  * requests, instead of PRIV_VFS_EXEC.
 4450                  */
 4451                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
 4452                     !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
 4453                         priv_granted |= VEXEC;
 4454         } else {
 4455                 /*
 4456                  * Ensure that at least one execute bit is on. Otherwise,
 4457                  * a privileged user will always succeed, and we don't want
 4458                  * this to happen unless the file really is executable.
 4459                  */
 4460                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
 4461                     (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
 4462                     !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
 4463                         priv_granted |= VEXEC;
 4464         }
 4465 
 4466         if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
 4467             !priv_check_cred(cred, PRIV_VFS_READ, 0))
 4468                 priv_granted |= VREAD;
 4469 
 4470         if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
 4471             !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
 4472                 priv_granted |= (VWRITE | VAPPEND);
 4473 
 4474         if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
 4475             !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
 4476                 priv_granted |= VADMIN;
 4477 
 4478         if ((accmode & (priv_granted | dac_granted)) == accmode) {
 4479                 /* XXX audit: privilege used */
 4480                 if (privused != NULL)
 4481                         *privused = 1;
 4482                 return (0);
 4483         }
 4484 
 4485         return ((accmode & VADMIN) ? EPERM : EACCES);
 4486 }
 4487 
 4488 /*
 4489  * Credential check based on process requesting service, and per-attribute
 4490  * permissions.
 4491  */
 4492 int
 4493 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
 4494     struct thread *td, accmode_t accmode)
 4495 {
 4496 
 4497         /*
 4498          * Kernel-invoked always succeeds.
 4499          */
 4500         if (cred == NOCRED)
 4501                 return (0);
 4502 
 4503         /*
 4504          * Do not allow privileged processes in jail to directly manipulate
 4505          * system attributes.
 4506          */
 4507         switch (attrnamespace) {
 4508         case EXTATTR_NAMESPACE_SYSTEM:
 4509                 /* Potentially should be: return (EPERM); */
 4510                 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
 4511         case EXTATTR_NAMESPACE_USER:
 4512                 return (VOP_ACCESS(vp, accmode, cred, td));
 4513         default:
 4514                 return (EPERM);
 4515         }
 4516 }
 4517 
 4518 #ifdef DEBUG_VFS_LOCKS
 4519 /*
 4520  * This only exists to suppress warnings from unlocked specfs accesses.  It is
 4521  * no longer ok to have an unlocked VFS.
 4522  */
 4523 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL ||            \
 4524         (vp)->v_type == VCHR || (vp)->v_type == VBAD)
 4525 
 4526 int vfs_badlock_ddb = 1;        /* Drop into debugger on violation. */
 4527 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
 4528     "Drop into debugger on lock violation");
 4529 
 4530 int vfs_badlock_mutex = 1;      /* Check for interlock across VOPs. */
 4531 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
 4532     0, "Check for interlock across VOPs");
 4533 
 4534 int vfs_badlock_print = 1;      /* Print lock violations. */
 4535 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
 4536     0, "Print lock violations");
 4537 
 4538 int vfs_badlock_vnode = 1;      /* Print vnode details on lock violations. */
 4539 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
 4540     0, "Print vnode details on lock violations");
 4541 
 4542 #ifdef KDB
 4543 int vfs_badlock_backtrace = 1;  /* Print backtrace at lock violations. */
 4544 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
 4545     &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
 4546 #endif
 4547 
 4548 static void
 4549 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
 4550 {
 4551 
 4552 #ifdef KDB
 4553         if (vfs_badlock_backtrace)
 4554                 kdb_backtrace();
 4555 #endif
 4556         if (vfs_badlock_vnode)
 4557                 vn_printf(vp, "vnode ");
 4558         if (vfs_badlock_print)
 4559                 printf("%s: %p %s\n", str, (void *)vp, msg);
 4560         if (vfs_badlock_ddb)
 4561                 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
 4562 }
 4563 
 4564 void
 4565 assert_vi_locked(struct vnode *vp, const char *str)
 4566 {
 4567 
 4568         if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
 4569                 vfs_badlock("interlock is not locked but should be", str, vp);
 4570 }
 4571 
 4572 void
 4573 assert_vi_unlocked(struct vnode *vp, const char *str)
 4574 {
 4575 
 4576         if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
 4577                 vfs_badlock("interlock is locked but should not be", str, vp);
 4578 }
 4579 
 4580 void
 4581 assert_vop_locked(struct vnode *vp, const char *str)
 4582 {
 4583         int locked;
 4584 
 4585         if (!IGNORE_LOCK(vp)) {
 4586                 locked = VOP_ISLOCKED(vp);
 4587                 if (locked == 0 || locked == LK_EXCLOTHER)
 4588                         vfs_badlock("is not locked but should be", str, vp);
 4589         }
 4590 }
 4591 
 4592 void
 4593 assert_vop_unlocked(struct vnode *vp, const char *str)
 4594 {
 4595 
 4596         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
 4597                 vfs_badlock("is locked but should not be", str, vp);
 4598 }
 4599 
 4600 void
 4601 assert_vop_elocked(struct vnode *vp, const char *str)
 4602 {
 4603 
 4604         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
 4605                 vfs_badlock("is not exclusive locked but should be", str, vp);
 4606 }
 4607 
 4608 #if 0
 4609 void
 4610 assert_vop_elocked_other(struct vnode *vp, const char *str)
 4611 {
 4612 
 4613         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
 4614                 vfs_badlock("is not exclusive locked by another thread",
 4615                     str, vp);
 4616 }
 4617 
 4618 void
 4619 assert_vop_slocked(struct vnode *vp, const char *str)
 4620 {
 4621 
 4622         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
 4623                 vfs_badlock("is not locked shared but should be", str, vp);
 4624 }
 4625 #endif /* 0 */
 4626 #endif /* DEBUG_VFS_LOCKS */
 4627 
 4628 void
 4629 vop_rename_fail(struct vop_rename_args *ap)
 4630 {
 4631 
 4632         if (ap->a_tvp != NULL)
 4633                 vput(ap->a_tvp);
 4634         if (ap->a_tdvp == ap->a_tvp)
 4635                 vrele(ap->a_tdvp);
 4636         else
 4637                 vput(ap->a_tdvp);
 4638         vrele(ap->a_fdvp);
 4639         vrele(ap->a_fvp);
 4640 }
 4641 
 4642 void
 4643 vop_rename_pre(void *ap)
 4644 {
 4645         struct vop_rename_args *a = ap;
 4646 
 4647 #ifdef DEBUG_VFS_LOCKS
 4648         if (a->a_tvp)
 4649                 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
 4650         ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
 4651         ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
 4652         ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
 4653 
 4654         /* Check the source (from). */
 4655         if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
 4656             (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
 4657                 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
 4658         if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
 4659                 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
 4660 
 4661         /* Check the target. */
 4662         if (a->a_tvp)
 4663                 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
 4664         ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
 4665 #endif
 4666         if (a->a_tdvp != a->a_fdvp)
 4667                 vhold(a->a_fdvp);
 4668         if (a->a_tvp != a->a_fvp)
 4669                 vhold(a->a_fvp);
 4670         vhold(a->a_tdvp);
 4671         if (a->a_tvp)
 4672                 vhold(a->a_tvp);
 4673 }
 4674 
 4675 #ifdef DEBUG_VFS_LOCKS
 4676 void
 4677 vop_strategy_pre(void *ap)
 4678 {
 4679         struct vop_strategy_args *a;
 4680         struct buf *bp;
 4681 
 4682         a = ap;
 4683         bp = a->a_bp;
 4684 
 4685         /*
 4686          * Cluster ops lock their component buffers but not the IO container.
 4687          */
 4688         if ((bp->b_flags & B_CLUSTER) != 0)
 4689                 return;
 4690 
 4691         if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
 4692                 if (vfs_badlock_print)
 4693                         printf(
 4694                             "VOP_STRATEGY: bp is not locked but should be\n");
 4695                 if (vfs_badlock_ddb)
 4696                         kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
 4697         }
 4698 }
 4699 
 4700 void
 4701 vop_lock_pre(void *ap)
 4702 {
 4703         struct vop_lock1_args *a = ap;
 4704 
 4705         if ((a->a_flags & LK_INTERLOCK) == 0)
 4706                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
 4707         else
 4708                 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
 4709 }
 4710 
 4711 void
 4712 vop_lock_post(void *ap, int rc)
 4713 {
 4714         struct vop_lock1_args *a = ap;
 4715 
 4716         ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
 4717         if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
 4718                 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
 4719 }
 4720 
 4721 void
 4722 vop_unlock_pre(void *ap)
 4723 {
 4724         struct vop_unlock_args *a = ap;
 4725 
 4726         if (a->a_flags & LK_INTERLOCK)
 4727                 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
 4728         ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
 4729 }
 4730 
 4731 void
 4732 vop_unlock_post(void *ap, int rc)
 4733 {
 4734         struct vop_unlock_args *a = ap;
 4735 
 4736         if (a->a_flags & LK_INTERLOCK)
 4737                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
 4738 }
 4739 #endif
 4740 
 4741 void
 4742 vop_create_post(void *ap, int rc)
 4743 {
 4744         struct vop_create_args *a = ap;
 4745 
 4746         if (!rc)
 4747                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 4748 }
 4749 
 4750 void
 4751 vop_deleteextattr_post(void *ap, int rc)
 4752 {
 4753         struct vop_deleteextattr_args *a = ap;
 4754 
 4755         if (!rc)
 4756                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
 4757 }
 4758 
 4759 void
 4760 vop_link_post(void *ap, int rc)
 4761 {
 4762         struct vop_link_args *a = ap;
 4763 
 4764         if (!rc) {
 4765                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
 4766                 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
 4767         }
 4768 }
 4769 
 4770 void
 4771 vop_mkdir_post(void *ap, int rc)
 4772 {
 4773         struct vop_mkdir_args *a = ap;
 4774 
 4775         if (!rc)
 4776                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
 4777 }
 4778 
 4779 void
 4780 vop_mknod_post(void *ap, int rc)
 4781 {
 4782         struct vop_mknod_args *a = ap;
 4783 
 4784         if (!rc)
 4785                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 4786 }
 4787 
 4788 void
 4789 vop_reclaim_post(void *ap, int rc)
 4790 {
 4791         struct vop_reclaim_args *a = ap;
 4792 
 4793         if (!rc)
 4794                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
 4795 }
 4796 
 4797 void
 4798 vop_remove_post(void *ap, int rc)
 4799 {
 4800         struct vop_remove_args *a = ap;
 4801 
 4802         if (!rc) {
 4803                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 4804                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
 4805         }
 4806 }
 4807 
 4808 void
 4809 vop_rename_post(void *ap, int rc)
 4810 {
 4811         struct vop_rename_args *a = ap;
 4812         long hint;
 4813 
 4814         if (!rc) {
 4815                 hint = NOTE_WRITE;
 4816                 if (a->a_fdvp == a->a_tdvp) {
 4817                         if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
 4818                                 hint |= NOTE_LINK;
 4819                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
 4820                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
 4821                 } else {
 4822                         hint |= NOTE_EXTEND;
 4823                         if (a->a_fvp->v_type == VDIR)
 4824                                 hint |= NOTE_LINK;
 4825                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
 4826 
 4827                         if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
 4828                             a->a_tvp->v_type == VDIR)
 4829                                 hint &= ~NOTE_LINK;
 4830                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
 4831                 }
 4832 
 4833                 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
 4834                 if (a->a_tvp)
 4835                         VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
 4836         }
 4837         if (a->a_tdvp != a->a_fdvp)
 4838                 vdrop(a->a_fdvp);
 4839         if (a->a_tvp != a->a_fvp)
 4840                 vdrop(a->a_fvp);
 4841         vdrop(a->a_tdvp);
 4842         if (a->a_tvp)
 4843                 vdrop(a->a_tvp);
 4844 }
 4845 
 4846 void
 4847 vop_rmdir_post(void *ap, int rc)
 4848 {
 4849         struct vop_rmdir_args *a = ap;
 4850 
 4851         if (!rc) {
 4852                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
 4853                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
 4854         }
 4855 }
 4856 
 4857 void
 4858 vop_setattr_post(void *ap, int rc)
 4859 {
 4860         struct vop_setattr_args *a = ap;
 4861 
 4862         if (!rc)
 4863                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
 4864 }
 4865 
 4866 void
 4867 vop_setextattr_post(void *ap, int rc)
 4868 {
 4869         struct vop_setextattr_args *a = ap;
 4870 
 4871         if (!rc)
 4872                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
 4873 }
 4874 
 4875 void
 4876 vop_symlink_post(void *ap, int rc)
 4877 {
 4878         struct vop_symlink_args *a = ap;
 4879 
 4880         if (!rc)
 4881                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 4882 }
 4883 
 4884 void
 4885 vop_open_post(void *ap, int rc)
 4886 {
 4887         struct vop_open_args *a = ap;
 4888 
 4889         if (!rc)
 4890                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
 4891 }
 4892 
 4893 void
 4894 vop_close_post(void *ap, int rc)
 4895 {
 4896         struct vop_close_args *a = ap;
 4897 
 4898         if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
 4899             (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
 4900                 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
 4901                     NOTE_CLOSE_WRITE : NOTE_CLOSE);
 4902         }
 4903 }
 4904 
 4905 void
 4906 vop_read_post(void *ap, int rc)
 4907 {
 4908         struct vop_read_args *a = ap;
 4909 
 4910         if (!rc)
 4911                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
 4912 }
 4913 
 4914 void
 4915 vop_readdir_post(void *ap, int rc)
 4916 {
 4917         struct vop_readdir_args *a = ap;
 4918 
 4919         if (!rc)
 4920                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
 4921 }
 4922 
 4923 static struct knlist fs_knlist;
 4924 
 4925 static void
 4926 vfs_event_init(void *arg)
 4927 {
 4928         knlist_init_mtx(&fs_knlist, NULL);
 4929 }
 4930 /* XXX - correct order? */
 4931 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
 4932 
 4933 void
 4934 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
 4935 {
 4936 
 4937         KNOTE_UNLOCKED(&fs_knlist, event);
 4938 }
 4939 
 4940 static int      filt_fsattach(struct knote *kn);
 4941 static void     filt_fsdetach(struct knote *kn);
 4942 static int      filt_fsevent(struct knote *kn, long hint);
 4943 
 4944 struct filterops fs_filtops = {
 4945         .f_isfd = 0,
 4946         .f_attach = filt_fsattach,
 4947         .f_detach = filt_fsdetach,
 4948         .f_event = filt_fsevent
 4949 };
 4950 
 4951 static int
 4952 filt_fsattach(struct knote *kn)
 4953 {
 4954 
 4955         kn->kn_flags |= EV_CLEAR;
 4956         knlist_add(&fs_knlist, kn, 0);
 4957         return (0);
 4958 }
 4959 
 4960 static void
 4961 filt_fsdetach(struct knote *kn)
 4962 {
 4963 
 4964         knlist_remove(&fs_knlist, kn, 0);
 4965 }
 4966 
 4967 static int
 4968 filt_fsevent(struct knote *kn, long hint)
 4969 {
 4970 
 4971         kn->kn_fflags |= hint;
 4972         return (kn->kn_fflags != 0);
 4973 }
 4974 
 4975 static int
 4976 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
 4977 {
 4978         struct vfsidctl vc;
 4979         int error;
 4980         struct mount *mp;
 4981 
 4982         error = SYSCTL_IN(req, &vc, sizeof(vc));
 4983         if (error)
 4984                 return (error);
 4985         if (vc.vc_vers != VFS_CTL_VERS1)
 4986                 return (EINVAL);
 4987         mp = vfs_getvfs(&vc.vc_fsid);
 4988         if (mp == NULL)
 4989                 return (ENOENT);
 4990         /* ensure that a specific sysctl goes to the right filesystem. */
 4991         if (strcmp(vc.vc_fstypename, "*") != 0 &&
 4992             strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
 4993                 vfs_rel(mp);
 4994                 return (EINVAL);
 4995         }
 4996         VCTLTOREQ(&vc, req);
 4997         error = VFS_SYSCTL(mp, vc.vc_op, req);
 4998         vfs_rel(mp);
 4999         return (error);
 5000 }
 5001 
 5002 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
 5003     NULL, 0, sysctl_vfs_ctl, "",
 5004     "Sysctl by fsid");
 5005 
 5006 /*
 5007  * Function to initialize a va_filerev field sensibly.
 5008  * XXX: Wouldn't a random number make a lot more sense ??
 5009  */
 5010 u_quad_t
 5011 init_va_filerev(void)
 5012 {
 5013         struct bintime bt;
 5014 
 5015         getbinuptime(&bt);
 5016         return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
 5017 }
 5018 
 5019 static int      filt_vfsread(struct knote *kn, long hint);
 5020 static int      filt_vfswrite(struct knote *kn, long hint);
 5021 static int      filt_vfsvnode(struct knote *kn, long hint);
 5022 static void     filt_vfsdetach(struct knote *kn);
 5023 static struct filterops vfsread_filtops = {
 5024         .f_isfd = 1,
 5025         .f_detach = filt_vfsdetach,
 5026         .f_event = filt_vfsread
 5027 };
 5028 static struct filterops vfswrite_filtops = {
 5029         .f_isfd = 1,
 5030         .f_detach = filt_vfsdetach,
 5031         .f_event = filt_vfswrite
 5032 };
 5033 static struct filterops vfsvnode_filtops = {
 5034         .f_isfd = 1,
 5035         .f_detach = filt_vfsdetach,
 5036         .f_event = filt_vfsvnode
 5037 };
 5038 
 5039 static void
 5040 vfs_knllock(void *arg)
 5041 {
 5042         struct vnode *vp = arg;
 5043 
 5044         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
 5045 }
 5046 
 5047 static void
 5048 vfs_knlunlock(void *arg)
 5049 {
 5050         struct vnode *vp = arg;
 5051 
 5052         VOP_UNLOCK(vp, 0);
 5053 }
 5054 
 5055 static void
 5056 vfs_knl_assert_locked(void *arg)
 5057 {
 5058 #ifdef DEBUG_VFS_LOCKS
 5059         struct vnode *vp = arg;
 5060 
 5061         ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
 5062 #endif
 5063 }
 5064 
 5065 static void
 5066 vfs_knl_assert_unlocked(void *arg)
 5067 {
 5068 #ifdef DEBUG_VFS_LOCKS
 5069         struct vnode *vp = arg;
 5070 
 5071         ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
 5072 #endif
 5073 }
 5074 
 5075 int
 5076 vfs_kqfilter(struct vop_kqfilter_args *ap)
 5077 {
 5078         struct vnode *vp = ap->a_vp;
 5079         struct knote *kn = ap->a_kn;
 5080         struct knlist *knl;
 5081 
 5082         switch (kn->kn_filter) {
 5083         case EVFILT_READ:
 5084                 kn->kn_fop = &vfsread_filtops;
 5085                 break;
 5086         case EVFILT_WRITE:
 5087                 kn->kn_fop = &vfswrite_filtops;
 5088                 break;
 5089         case EVFILT_VNODE:
 5090                 kn->kn_fop = &vfsvnode_filtops;
 5091                 break;
 5092         default:
 5093                 return (EINVAL);
 5094         }
 5095 
 5096         kn->kn_hook = (caddr_t)vp;
 5097 
 5098         v_addpollinfo(vp);
 5099         if (vp->v_pollinfo == NULL)
 5100                 return (ENOMEM);
 5101         knl = &vp->v_pollinfo->vpi_selinfo.si_note;
 5102         vhold(vp);
 5103         knlist_add(knl, kn, 0);
 5104 
 5105         return (0);
 5106 }
 5107 
 5108 /*
 5109  * Detach knote from vnode
 5110  */
 5111 static void
 5112 filt_vfsdetach(struct knote *kn)
 5113 {
 5114         struct vnode *vp = (struct vnode *)kn->kn_hook;
 5115 
 5116         KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
 5117         knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
 5118         vdrop(vp);
 5119 }
 5120 
 5121 /*ARGSUSED*/
 5122 static int
 5123 filt_vfsread(struct knote *kn, long hint)
 5124 {
 5125         struct vnode *vp = (struct vnode *)kn->kn_hook;
 5126         struct vattr va;
 5127         int res;
 5128 
 5129         /*
 5130          * filesystem is gone, so set the EOF flag and schedule
 5131          * the knote for deletion.
 5132          */
 5133         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
 5134                 VI_LOCK(vp);
 5135                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
 5136                 VI_UNLOCK(vp);
 5137                 return (1);
 5138         }
 5139 
 5140         if (VOP_GETATTR(vp, &va, curthread->td_ucred))
 5141                 return (0);
 5142 
 5143         VI_LOCK(vp);
 5144         kn->kn_data = va.va_size - kn->kn_fp->f_offset;
 5145         res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
 5146         VI_UNLOCK(vp);
 5147         return (res);
 5148 }
 5149 
 5150 /*ARGSUSED*/
 5151 static int
 5152 filt_vfswrite(struct knote *kn, long hint)
 5153 {
 5154         struct vnode *vp = (struct vnode *)kn->kn_hook;
 5155 
 5156         VI_LOCK(vp);
 5157 
 5158         /*
 5159          * filesystem is gone, so set the EOF flag and schedule
 5160          * the knote for deletion.
 5161          */
 5162         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
 5163                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
 5164 
 5165         kn->kn_data = 0;
 5166         VI_UNLOCK(vp);
 5167         return (1);
 5168 }
 5169 
 5170 static int
 5171 filt_vfsvnode(struct knote *kn, long hint)
 5172 {
 5173         struct vnode *vp = (struct vnode *)kn->kn_hook;
 5174         int res;
 5175 
 5176         VI_LOCK(vp);
 5177         if (kn->kn_sfflags & hint)
 5178                 kn->kn_fflags |= hint;
 5179         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
 5180                 kn->kn_flags |= EV_EOF;
 5181                 VI_UNLOCK(vp);
 5182                 return (1);
 5183         }
 5184         res = (kn->kn_fflags != 0);
 5185         VI_UNLOCK(vp);
 5186         return (res);
 5187 }
 5188 
 5189 int
 5190 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
 5191 {
 5192         int error;
 5193 
 5194         if (dp->d_reclen > ap->a_uio->uio_resid)
 5195                 return (ENAMETOOLONG);
 5196         error = uiomove(dp, dp->d_reclen, ap->a_uio);
 5197         if (error) {
 5198                 if (ap->a_ncookies != NULL) {
 5199                         if (ap->a_cookies != NULL)
 5200                                 free(ap->a_cookies, M_TEMP);
 5201                         ap->a_cookies = NULL;
 5202                         *ap->a_ncookies = 0;
 5203                 }
 5204                 return (error);
 5205         }
 5206         if (ap->a_ncookies == NULL)
 5207                 return (0);
 5208 
 5209         KASSERT(ap->a_cookies,
 5210             ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
 5211 
 5212         *ap->a_cookies = realloc(*ap->a_cookies,
 5213             (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
 5214         (*ap->a_cookies)[*ap->a_ncookies] = off;
 5215         *ap->a_ncookies += 1;
 5216         return (0);
 5217 }
 5218 
 5219 /*
 5220  * Mark for update the access time of the file if the filesystem
 5221  * supports VOP_MARKATIME.  This functionality is used by execve and
 5222  * mmap, so we want to avoid the I/O implied by directly setting
 5223  * va_atime for the sake of efficiency.
 5224  */
 5225 void
 5226 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
 5227 {
 5228         struct mount *mp;
 5229 
 5230         mp = vp->v_mount;
 5231         ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
 5232         if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
 5233                 (void)VOP_MARKATIME(vp);
 5234 }
 5235 
 5236 /*
 5237  * The purpose of this routine is to remove granularity from accmode_t,
 5238  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
 5239  * VADMIN and VAPPEND.
 5240  *
 5241  * If it returns 0, the caller is supposed to continue with the usual
 5242  * access checks using 'accmode' as modified by this routine.  If it
 5243  * returns nonzero value, the caller is supposed to return that value
 5244  * as errno.
 5245  *
 5246  * Note that after this routine runs, accmode may be zero.
 5247  */
 5248 int
 5249 vfs_unixify_accmode(accmode_t *accmode)
 5250 {
 5251         /*
 5252          * There is no way to specify explicit "deny" rule using
 5253          * file mode or POSIX.1e ACLs.
 5254          */
 5255         if (*accmode & VEXPLICIT_DENY) {
 5256                 *accmode = 0;
 5257                 return (0);
 5258         }
 5259 
 5260         /*
 5261          * None of these can be translated into usual access bits.
 5262          * Also, the common case for NFSv4 ACLs is to not contain
 5263          * either of these bits. Caller should check for VWRITE
 5264          * on the containing directory instead.
 5265          */
 5266         if (*accmode & (VDELETE_CHILD | VDELETE))
 5267                 return (EPERM);
 5268 
 5269         if (*accmode & VADMIN_PERMS) {
 5270                 *accmode &= ~VADMIN_PERMS;
 5271                 *accmode |= VADMIN;
 5272         }
 5273 
 5274         /*
 5275          * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
 5276          * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
 5277          */
 5278         *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
 5279 
 5280         return (0);
 5281 }
 5282 
 5283 /*
 5284  * These are helper functions for filesystems to traverse all
 5285  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
 5286  *
 5287  * This interface replaces MNT_VNODE_FOREACH.
 5288  */
 5289 
 5290 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
 5291 
 5292 struct vnode *
 5293 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
 5294 {
 5295         struct vnode *vp;
 5296 
 5297         if (should_yield())
 5298                 kern_yield(PRI_USER);
 5299         MNT_ILOCK(mp);
 5300         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
 5301         for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
 5302             vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
 5303                 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
 5304                 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
 5305                         continue;
 5306                 VI_LOCK(vp);
 5307                 if ((vp->v_iflag & VI_DOOMED) != 0) {
 5308                         VI_UNLOCK(vp);
 5309                         continue;
 5310                 }
 5311                 break;
 5312         }
 5313         if (vp == NULL) {
 5314                 __mnt_vnode_markerfree_all(mvp, mp);
 5315                 /* MNT_IUNLOCK(mp); -- done in above function */
 5316                 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
 5317                 return (NULL);
 5318         }
 5319         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
 5320         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
 5321         MNT_IUNLOCK(mp);
 5322         return (vp);
 5323 }
 5324 
 5325 struct vnode *
 5326 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
 5327 {
 5328         struct vnode *vp;
 5329 
 5330         *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
 5331         MNT_ILOCK(mp);
 5332         MNT_REF(mp);
 5333         (*mvp)->v_mount = mp;
 5334         (*mvp)->v_type = VMARKER;
 5335 
 5336         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
 5337                 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
 5338                 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
 5339                         continue;
 5340                 VI_LOCK(vp);
 5341                 if ((vp->v_iflag & VI_DOOMED) != 0) {
 5342                         VI_UNLOCK(vp);
 5343                         continue;
 5344                 }
 5345                 break;
 5346         }
 5347         if (vp == NULL) {
 5348                 MNT_REL(mp);
 5349                 MNT_IUNLOCK(mp);
 5350                 free(*mvp, M_VNODE_MARKER);
 5351                 *mvp = NULL;
 5352                 return (NULL);
 5353         }
 5354         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
 5355         MNT_IUNLOCK(mp);
 5356         return (vp);
 5357 }
 5358 
 5359 void
 5360 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
 5361 {
 5362 
 5363         if (*mvp == NULL) {
 5364                 MNT_IUNLOCK(mp);
 5365                 return;
 5366         }
 5367 
 5368         mtx_assert(MNT_MTX(mp), MA_OWNED);
 5369 
 5370         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
 5371         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
 5372         MNT_REL(mp);
 5373         MNT_IUNLOCK(mp);
 5374         free(*mvp, M_VNODE_MARKER);
 5375         *mvp = NULL;
 5376 }
 5377 
 5378 /*
 5379  * These are helper functions for filesystems to traverse their
 5380  * active vnodes.  See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
 5381  */
 5382 static void
 5383 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
 5384 {
 5385 
 5386         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
 5387 
 5388         MNT_ILOCK(mp);
 5389         MNT_REL(mp);
 5390         MNT_IUNLOCK(mp);
 5391         free(*mvp, M_VNODE_MARKER);
 5392         *mvp = NULL;
 5393 }
 5394 
 5395 static struct vnode *
 5396 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
 5397 {
 5398         struct vnode *vp, *nvp;
 5399 
 5400         mtx_assert(&vnode_free_list_mtx, MA_OWNED);
 5401         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
 5402 restart:
 5403         vp = TAILQ_NEXT(*mvp, v_actfreelist);
 5404         TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
 5405         while (vp != NULL) {
 5406                 if (vp->v_type == VMARKER) {
 5407                         vp = TAILQ_NEXT(vp, v_actfreelist);
 5408                         continue;
 5409                 }
 5410                 if (!VI_TRYLOCK(vp)) {
 5411                         if (mp_ncpus == 1 || should_yield()) {
 5412                                 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
 5413                                 mtx_unlock(&vnode_free_list_mtx);
 5414                                 pause("vnacti", 1);
 5415                                 mtx_lock(&vnode_free_list_mtx);
 5416                                 goto restart;
 5417                         }
 5418                         continue;
 5419                 }
 5420                 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
 5421                 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
 5422                     ("alien vnode on the active list %p %p", vp, mp));
 5423                 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
 5424                         break;
 5425                 nvp = TAILQ_NEXT(vp, v_actfreelist);
 5426                 VI_UNLOCK(vp);
 5427                 vp = nvp;
 5428         }
 5429 
 5430         /* Check if we are done */
 5431         if (vp == NULL) {
 5432                 mtx_unlock(&vnode_free_list_mtx);
 5433                 mnt_vnode_markerfree_active(mvp, mp);
 5434                 return (NULL);
 5435         }
 5436         TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
 5437         mtx_unlock(&vnode_free_list_mtx);
 5438         ASSERT_VI_LOCKED(vp, "active iter");
 5439         KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
 5440         return (vp);
 5441 }
 5442 
 5443 struct vnode *
 5444 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
 5445 {
 5446 
 5447         if (should_yield())
 5448                 kern_yield(PRI_USER);
 5449         mtx_lock(&vnode_free_list_mtx);
 5450         return (mnt_vnode_next_active(mvp, mp));
 5451 }
 5452 
 5453 struct vnode *
 5454 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
 5455 {
 5456         struct vnode *vp;
 5457 
 5458         *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
 5459         MNT_ILOCK(mp);
 5460         MNT_REF(mp);
 5461         MNT_IUNLOCK(mp);
 5462         (*mvp)->v_type = VMARKER;
 5463         (*mvp)->v_mount = mp;
 5464 
 5465         mtx_lock(&vnode_free_list_mtx);
 5466         vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
 5467         if (vp == NULL) {
 5468                 mtx_unlock(&vnode_free_list_mtx);
 5469                 mnt_vnode_markerfree_active(mvp, mp);
 5470                 return (NULL);
 5471         }
 5472         TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
 5473         return (mnt_vnode_next_active(mvp, mp));
 5474 }
 5475 
 5476 void
 5477 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
 5478 {
 5479 
 5480         if (*mvp == NULL)
 5481                 return;
 5482 
 5483         mtx_lock(&vnode_free_list_mtx);
 5484         TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
 5485         mtx_unlock(&vnode_free_list_mtx);
 5486         mnt_vnode_markerfree_active(mvp, mp);
 5487 }

Cache object: 20ea2658bf45a8ca481a8718eda5147e


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