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

Cache object: 21532201899acd79b861d2601856b095


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