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-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 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/7.4/sys/kern/vfs_subr.c 213652 2010-10-09 09:24:16Z avg $");
   43 
   44 #include "opt_ddb.h"
   45 #include "opt_mac.h"
   46 
   47 #include <sys/param.h>
   48 #include <sys/systm.h>
   49 #include <sys/bio.h>
   50 #include <sys/buf.h>
   51 #include <sys/conf.h>
   52 #include <sys/dirent.h>
   53 #include <sys/event.h>
   54 #include <sys/eventhandler.h>
   55 #include <sys/extattr.h>
   56 #include <sys/file.h>
   57 #include <sys/fcntl.h>
   58 #include <sys/jail.h>
   59 #include <sys/kdb.h>
   60 #include <sys/kernel.h>
   61 #include <sys/kthread.h>
   62 #include <sys/lockf.h>
   63 #include <sys/malloc.h>
   64 #include <sys/mount.h>
   65 #include <sys/namei.h>
   66 #include <sys/priv.h>
   67 #include <sys/reboot.h>
   68 #include <sys/sleepqueue.h>
   69 #include <sys/stat.h>
   70 #include <sys/sysctl.h>
   71 #include <sys/syslog.h>
   72 #include <sys/vmmeter.h>
   73 #include <sys/vnode.h>
   74 
   75 #include <machine/stdarg.h>
   76 
   77 #include <security/mac/mac_framework.h>
   78 
   79 #include <vm/vm.h>
   80 #include <vm/vm_object.h>
   81 #include <vm/vm_extern.h>
   82 #include <vm/pmap.h>
   83 #include <vm/vm_map.h>
   84 #include <vm/vm_page.h>
   85 #include <vm/vm_kern.h>
   86 #include <vm/uma.h>
   87 
   88 #ifdef DDB
   89 #include <ddb/ddb.h>
   90 #endif
   91 
   92 static MALLOC_DEFINE(M_NETADDR, "subr_export_host", "Export host address structure");
   93 
   94 static void     delmntque(struct vnode *vp);
   95 static int      flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
   96                     int slpflag, int slptimeo);
   97 static void     syncer_shutdown(void *arg, int howto);
   98 static int      vtryrecycle(struct vnode *vp);
   99 static void     vbusy(struct vnode *vp);
  100 static void     vinactive(struct vnode *, struct thread *);
  101 static void     v_incr_usecount(struct vnode *);
  102 static void     v_decr_usecount(struct vnode *);
  103 static void     v_decr_useonly(struct vnode *);
  104 static void     v_upgrade_usecount(struct vnode *);
  105 static void     vfree(struct vnode *);
  106 static void     vnlru_free(int);
  107 static void     vgonel(struct vnode *);
  108 static void     vfs_knllock(void *arg);
  109 static void     vfs_knlunlock(void *arg);
  110 static void     destroy_vpollinfo(struct vpollinfo *vi);
  111 
  112 /*
  113  * Enable Giant pushdown based on whether or not the vm is mpsafe in this
  114  * build.  Without mpsafevm the buffer cache can not run Giant free.
  115  */
  116 int mpsafe_vfs = 1;
  117 TUNABLE_INT("debug.mpsafevfs", &mpsafe_vfs);
  118 SYSCTL_INT(_debug, OID_AUTO, mpsafevfs, CTLFLAG_RD, &mpsafe_vfs, 0,
  119     "MPSAFE VFS");
  120 
  121 /*
  122  * Number of vnodes in existence.  Increased whenever getnewvnode()
  123  * allocates a new vnode, decreased on vdestroy() called on VI_DOOMed
  124  * vnode.
  125  */
  126 static unsigned long    numvnodes;
  127 
  128 SYSCTL_LONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
  129 
  130 /*
  131  * Conversion tables for conversion from vnode types to inode formats
  132  * and back.
  133  */
  134 enum vtype iftovt_tab[16] = {
  135         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
  136         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
  137 };
  138 int vttoif_tab[10] = {
  139         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
  140         S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
  141 };
  142 
  143 /*
  144  * List of vnodes that are ready for recycling.
  145  */
  146 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
  147 
  148 /*
  149  * Free vnode target.  Free vnodes may simply be files which have been stat'd
  150  * but not read.  This is somewhat common, and a small cache of such files
  151  * should be kept to avoid recreation costs.
  152  */
  153 static u_long wantfreevnodes;
  154 SYSCTL_LONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
  155 /* Number of vnodes in the free list. */
  156 static u_long freevnodes;
  157 SYSCTL_LONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
  158 
  159 /*
  160  * Various variables used for debugging the new implementation of
  161  * reassignbuf().
  162  * XXX these are probably of (very) limited utility now.
  163  */
  164 static int reassignbufcalls;
  165 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
  166 
  167 /*
  168  * Cache for the mount type id assigned to NFS.  This is used for
  169  * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
  170  */
  171 int     nfs_mount_type = -1;
  172 
  173 /* To keep more than one thread at a time from running vfs_getnewfsid */
  174 static struct mtx mntid_mtx;
  175 
  176 /*
  177  * Lock for any access to the following:
  178  *      vnode_free_list
  179  *      numvnodes
  180  *      freevnodes
  181  */
  182 static struct mtx vnode_free_list_mtx;
  183 
  184 /* Publicly exported FS */
  185 struct nfs_public nfs_pub;
  186 
  187 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
  188 static uma_zone_t vnode_zone;
  189 static uma_zone_t vnodepoll_zone;
  190 
  191 /* Set to 1 to print out reclaim of active vnodes */
  192 int     prtactive;
  193 
  194 /*
  195  * The workitem queue.
  196  *
  197  * It is useful to delay writes of file data and filesystem metadata
  198  * for tens of seconds so that quickly created and deleted files need
  199  * not waste disk bandwidth being created and removed. To realize this,
  200  * we append vnodes to a "workitem" queue. When running with a soft
  201  * updates implementation, most pending metadata dependencies should
  202  * not wait for more than a few seconds. Thus, mounted on block devices
  203  * are delayed only about a half the time that file data is delayed.
  204  * Similarly, directory updates are more critical, so are only delayed
  205  * about a third the time that file data is delayed. Thus, there are
  206  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
  207  * one each second (driven off the filesystem syncer process). The
  208  * syncer_delayno variable indicates the next queue that is to be processed.
  209  * Items that need to be processed soon are placed in this queue:
  210  *
  211  *      syncer_workitem_pending[syncer_delayno]
  212  *
  213  * A delay of fifteen seconds is done by placing the request fifteen
  214  * entries later in the queue:
  215  *
  216  *      syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
  217  *
  218  */
  219 static int syncer_delayno;
  220 static long syncer_mask;
  221 LIST_HEAD(synclist, bufobj);
  222 static struct synclist *syncer_workitem_pending;
  223 /*
  224  * The sync_mtx protects:
  225  *      bo->bo_synclist
  226  *      sync_vnode_count
  227  *      syncer_delayno
  228  *      syncer_state
  229  *      syncer_workitem_pending
  230  *      syncer_worklist_len
  231  *      rushjob
  232  */
  233 static struct mtx sync_mtx;
  234 
  235 #define SYNCER_MAXDELAY         32
  236 static int syncer_maxdelay = SYNCER_MAXDELAY;   /* maximum delay time */
  237 static int syncdelay = 30;              /* max time to delay syncing data */
  238 static int filedelay = 30;              /* time to delay syncing files */
  239 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
  240 static int dirdelay = 29;               /* time to delay syncing directories */
  241 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
  242 static int metadelay = 28;              /* time to delay syncing metadata */
  243 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
  244 static int rushjob;             /* number of slots to run ASAP */
  245 static int stat_rush_requests;  /* number of times I/O speeded up */
  246 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
  247 
  248 /*
  249  * When shutting down the syncer, run it at four times normal speed.
  250  */
  251 #define SYNCER_SHUTDOWN_SPEEDUP         4
  252 static int sync_vnode_count;
  253 static int syncer_worklist_len;
  254 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
  255     syncer_state;
  256 
  257 /*
  258  * Number of vnodes we want to exist at any one time.  This is mostly used
  259  * to size hash tables in vnode-related code.  It is normally not used in
  260  * getnewvnode(), as wantfreevnodes is normally nonzero.)
  261  *
  262  * XXX desiredvnodes is historical cruft and should not exist.
  263  */
  264 int desiredvnodes;
  265 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
  266     &desiredvnodes, 0, "Maximum number of vnodes");
  267 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
  268     &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
  269 static int vnlru_nowhere;
  270 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
  271     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
  272 
  273 /*
  274  * Macros to control when a vnode is freed and recycled.  All require
  275  * the vnode interlock.
  276  */
  277 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
  278 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
  279 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
  280 
  281 
  282 /*
  283  * Initialize the vnode management data structures.
  284  *
  285  * Reevaluate the following cap on the number of vnodes after the physical
  286  * memory size exceeds 512GB.  In the limit, as the physical memory size
  287  * grows, the ratio of physical pages to vnodes approaches sixteen to one.
  288  */
  289 #ifndef MAXVNODES_MAX
  290 #define MAXVNODES_MAX   (512 * (1024 * 1024 * 1024 / (int)PAGE_SIZE / 16))
  291 #endif
  292 static void
  293 vntblinit(void *dummy __unused)
  294 {
  295         int physvnodes, virtvnodes;
  296 
  297         /*
  298          * Desiredvnodes is a function of the physical memory size and the
  299          * kernel's heap size.  Generally speaking, it scales with the
  300          * physical memory size.  The ratio of desiredvnodes to physical pages
  301          * is one to four until desiredvnodes exceeds 98,304.  Thereafter, the
  302          * marginal ratio of desiredvnodes to physical pages is one to
  303          * sixteen.  However, desiredvnodes is limited by the kernel's heap
  304          * size.  The memory required by desiredvnodes vnodes and vm objects
  305          * may not exceed one seventh of the kernel's heap size.
  306          */
  307         physvnodes = maxproc + cnt.v_page_count / 16 + 3 * min(98304 * 4,
  308             cnt.v_page_count) / 16;
  309         virtvnodes = vm_kmem_size / (7 * (sizeof(struct vm_object) +
  310             sizeof(struct vnode)));
  311         desiredvnodes = min(physvnodes, virtvnodes);
  312         if (desiredvnodes > MAXVNODES_MAX) {
  313                 if (bootverbose)
  314                         printf("Reducing kern.maxvnodes %d -> %d\n",
  315                             desiredvnodes, MAXVNODES_MAX);
  316                 desiredvnodes = MAXVNODES_MAX;
  317         }
  318         wantfreevnodes = desiredvnodes / 4;
  319         mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
  320         TAILQ_INIT(&vnode_free_list);
  321         mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
  322         vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
  323             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  324         vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
  325             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  326         /*
  327          * Initialize the filesystem syncer.
  328          */
  329         syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
  330                 &syncer_mask);
  331         syncer_maxdelay = syncer_mask + 1;
  332         mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
  333 }
  334 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
  335 
  336 
  337 /*
  338  * Mark a mount point as busy. Used to synchronize access and to delay
  339  * unmounting. Interlock is not released on failure.
  340  */
  341 int
  342 vfs_busy(struct mount *mp, int flags, struct mtx *interlkp,
  343     struct thread *td)
  344 {
  345         int lkflags;
  346 
  347         MNT_ILOCK(mp);
  348         MNT_REF(mp);
  349         while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
  350                 if (flags & LK_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
  351                         MNT_REL(mp);
  352                         MNT_IUNLOCK(mp);
  353                         return (ENOENT);
  354                 }
  355                 if (interlkp)
  356                         mtx_unlock(interlkp);
  357                 mp->mnt_kern_flag |= MNTK_MWAIT;
  358                 /*
  359                  * Since all busy locks are shared except the exclusive
  360                  * lock granted when unmounting, the only place that a
  361                  * wakeup needs to be done is at the release of the
  362                  * exclusive lock at the end of dounmount.
  363                  */
  364                 msleep(mp, MNT_MTX(mp), PVFS, "vfs_busy", 0);
  365                 if (interlkp)
  366                         mtx_lock(interlkp);
  367         }
  368         if (interlkp)
  369                 mtx_unlock(interlkp);
  370         lkflags = LK_SHARED | LK_INTERLOCK | LK_NOWAIT;
  371         if (lockmgr(&mp->mnt_lock, lkflags, MNT_MTX(mp), td))
  372                 panic("vfs_busy: unexpected lock failure");
  373         return (0);
  374 }
  375 
  376 /*
  377  * Free a busy filesystem.
  378  */
  379 void
  380 vfs_unbusy(struct mount *mp, struct thread *td)
  381 {
  382 
  383         lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, td);
  384         vfs_rel(mp);
  385 }
  386 
  387 /*
  388  * Lookup a mount point by filesystem identifier.
  389  */
  390 struct mount *
  391 vfs_getvfs(fsid_t *fsid)
  392 {
  393         struct mount *mp;
  394 
  395         mtx_lock(&mountlist_mtx);
  396         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
  397                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
  398                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
  399                         vfs_ref(mp);
  400                         mtx_unlock(&mountlist_mtx);
  401                         return (mp);
  402                 }
  403         }
  404         mtx_unlock(&mountlist_mtx);
  405         return ((struct mount *) 0);
  406 }
  407 
  408 /*
  409  * Check if a user can access privileged mount options.
  410  */
  411 int
  412 vfs_suser(struct mount *mp, struct thread *td)
  413 {
  414         int error;
  415 
  416         /*
  417          * If the thread is jailed, but this is not a jail-friendly file
  418          * system, deny immediately.
  419          */
  420         if (jailed(td->td_ucred) && !(mp->mnt_vfc->vfc_flags & VFCF_JAIL))
  421                 return (EPERM);
  422 
  423         /*
  424          * If the file system was mounted outside a jail and a jailed thread
  425          * tries to access it, deny immediately.
  426          */
  427         if (!jailed(mp->mnt_cred) && jailed(td->td_ucred))
  428                 return (EPERM);
  429 
  430         /*
  431          * If the file system was mounted inside different jail that the jail of
  432          * the calling thread, deny immediately.
  433          */
  434         if (jailed(mp->mnt_cred) && jailed(td->td_ucred) &&
  435             mp->mnt_cred->cr_prison != td->td_ucred->cr_prison) {
  436                 return (EPERM);
  437         }
  438 
  439         if ((mp->mnt_flag & MNT_USER) == 0 ||
  440             mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
  441                 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
  442                         return (error);
  443         }
  444         return (0);
  445 }
  446 
  447 /*
  448  * Get a new unique fsid.  Try to make its val[0] unique, since this value
  449  * will be used to create fake device numbers for stat().  Also try (but
  450  * not so hard) make its val[0] unique mod 2^16, since some emulators only
  451  * support 16-bit device numbers.  We end up with unique val[0]'s for the
  452  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
  453  *
  454  * Keep in mind that several mounts may be running in parallel.  Starting
  455  * the search one past where the previous search terminated is both a
  456  * micro-optimization and a defense against returning the same fsid to
  457  * different mounts.
  458  */
  459 void
  460 vfs_getnewfsid(struct mount *mp)
  461 {
  462         static u_int16_t mntid_base;
  463         struct mount *nmp;
  464         fsid_t tfsid;
  465         int mtype;
  466 
  467         mtx_lock(&mntid_mtx);
  468         mtype = mp->mnt_vfc->vfc_typenum;
  469         tfsid.val[1] = mtype;
  470         mtype = (mtype & 0xFF) << 24;
  471         for (;;) {
  472                 tfsid.val[0] = makedev(255,
  473                     mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
  474                 mntid_base++;
  475                 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
  476                         break;
  477                 vfs_rel(nmp);
  478         }
  479         mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
  480         mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
  481         mtx_unlock(&mntid_mtx);
  482 }
  483 
  484 /*
  485  * Knob to control the precision of file timestamps:
  486  *
  487  *   0 = seconds only; nanoseconds zeroed.
  488  *   1 = seconds and nanoseconds, accurate within 1/HZ.
  489  *   2 = seconds and nanoseconds, truncated to microseconds.
  490  * >=3 = seconds and nanoseconds, maximum precision.
  491  */
  492 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
  493 
  494 static int timestamp_precision = TSP_SEC;
  495 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
  496     &timestamp_precision, 0, "");
  497 
  498 /*
  499  * Get a current timestamp.
  500  */
  501 void
  502 vfs_timestamp(struct timespec *tsp)
  503 {
  504         struct timeval tv;
  505 
  506         switch (timestamp_precision) {
  507         case TSP_SEC:
  508                 tsp->tv_sec = time_second;
  509                 tsp->tv_nsec = 0;
  510                 break;
  511         case TSP_HZ:
  512                 getnanotime(tsp);
  513                 break;
  514         case TSP_USEC:
  515                 microtime(&tv);
  516                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
  517                 break;
  518         case TSP_NSEC:
  519         default:
  520                 nanotime(tsp);
  521                 break;
  522         }
  523 }
  524 
  525 /*
  526  * Set vnode attributes to VNOVAL
  527  */
  528 void
  529 vattr_null(struct vattr *vap)
  530 {
  531 
  532         vap->va_type = VNON;
  533         vap->va_size = VNOVAL;
  534         vap->va_bytes = VNOVAL;
  535         vap->va_mode = VNOVAL;
  536         vap->va_nlink = VNOVAL;
  537         vap->va_uid = VNOVAL;
  538         vap->va_gid = VNOVAL;
  539         vap->va_fsid = VNOVAL;
  540         vap->va_fileid = VNOVAL;
  541         vap->va_blocksize = VNOVAL;
  542         vap->va_rdev = VNOVAL;
  543         vap->va_atime.tv_sec = VNOVAL;
  544         vap->va_atime.tv_nsec = VNOVAL;
  545         vap->va_mtime.tv_sec = VNOVAL;
  546         vap->va_mtime.tv_nsec = VNOVAL;
  547         vap->va_ctime.tv_sec = VNOVAL;
  548         vap->va_ctime.tv_nsec = VNOVAL;
  549         vap->va_birthtime.tv_sec = VNOVAL;
  550         vap->va_birthtime.tv_nsec = VNOVAL;
  551         vap->va_flags = VNOVAL;
  552         vap->va_gen = VNOVAL;
  553         vap->va_vaflags = 0;
  554 }
  555 
  556 /*
  557  * This routine is called when we have too many vnodes.  It attempts
  558  * to free <count> vnodes and will potentially free vnodes that still
  559  * have VM backing store (VM backing store is typically the cause
  560  * of a vnode blowout so we want to do this).  Therefore, this operation
  561  * is not considered cheap.
  562  *
  563  * A number of conditions may prevent a vnode from being reclaimed.
  564  * the buffer cache may have references on the vnode, a directory
  565  * vnode may still have references due to the namei cache representing
  566  * underlying files, or the vnode may be in active use.   It is not
  567  * desireable to reuse such vnodes.  These conditions may cause the
  568  * number of vnodes to reach some minimum value regardless of what
  569  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
  570  */
  571 static int
  572 vlrureclaim(struct mount *mp)
  573 {
  574         struct thread *td;
  575         struct vnode *vp;
  576         int done;
  577         int trigger;
  578         int usevnodes;
  579         int count;
  580 
  581         /*
  582          * Calculate the trigger point, don't allow user
  583          * screwups to blow us up.   This prevents us from
  584          * recycling vnodes with lots of resident pages.  We
  585          * aren't trying to free memory, we are trying to
  586          * free vnodes.
  587          */
  588         usevnodes = desiredvnodes;
  589         if (usevnodes <= 0)
  590                 usevnodes = 1;
  591         trigger = cnt.v_page_count * 2 / usevnodes;
  592         done = 0;
  593         td = curthread;
  594         vn_start_write(NULL, &mp, V_WAIT);
  595         MNT_ILOCK(mp);
  596         count = mp->mnt_nvnodelistsize / 10 + 1;
  597         while (count != 0) {
  598                 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
  599                 while (vp != NULL && vp->v_type == VMARKER)
  600                         vp = TAILQ_NEXT(vp, v_nmntvnodes);
  601                 if (vp == NULL)
  602                         break;
  603                 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
  604                 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
  605                 --count;
  606                 if (!VI_TRYLOCK(vp))
  607                         goto next_iter;
  608                 /*
  609                  * If it's been deconstructed already, it's still
  610                  * referenced, or it exceeds the trigger, skip it.
  611                  */
  612                 if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
  613                     (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
  614                     vp->v_object->resident_page_count > trigger)) {
  615                         VI_UNLOCK(vp);
  616                         goto next_iter;
  617                 }
  618                 MNT_IUNLOCK(mp);
  619                 vholdl(vp);
  620                 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT, td)) {
  621                         vdrop(vp);
  622                         goto next_iter_mntunlocked;
  623                 }
  624                 VI_LOCK(vp);
  625                 /*
  626                  * v_usecount may have been bumped after VOP_LOCK() dropped
  627                  * the vnode interlock and before it was locked again.
  628                  *
  629                  * It is not necessary to recheck VI_DOOMED because it can
  630                  * only be set by another thread that holds both the vnode
  631                  * lock and vnode interlock.  If another thread has the
  632                  * vnode lock before we get to VOP_LOCK() and obtains the
  633                  * vnode interlock after VOP_LOCK() drops the vnode
  634                  * interlock, the other thread will be unable to drop the
  635                  * vnode lock before our VOP_LOCK() call fails.
  636                  */
  637                 if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
  638                     (vp->v_object != NULL &&
  639                     vp->v_object->resident_page_count > trigger)) {
  640                         VOP_UNLOCK(vp, LK_INTERLOCK, td);
  641                         goto next_iter_mntunlocked;
  642                 }
  643                 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
  644                     ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
  645                 vgonel(vp);
  646                 VOP_UNLOCK(vp, 0, td);
  647                 vdropl(vp);
  648                 done++;
  649 next_iter_mntunlocked:
  650                 if ((count % 256) != 0)
  651                         goto relock_mnt;
  652                 goto yield;
  653 next_iter:
  654                 if ((count % 256) != 0)
  655                         continue;
  656                 MNT_IUNLOCK(mp);
  657 yield:
  658                 uio_yield();
  659 relock_mnt:
  660                 MNT_ILOCK(mp);
  661         }
  662         MNT_IUNLOCK(mp);
  663         vn_finished_write(mp);
  664         return done;
  665 }
  666 
  667 /*
  668  * Attempt to keep the free list at wantfreevnodes length.
  669  */
  670 static void
  671 vnlru_free(int count)
  672 {
  673         struct vnode *vp;
  674         int vfslocked;
  675 
  676         mtx_assert(&vnode_free_list_mtx, MA_OWNED);
  677         for (; count > 0; count--) {
  678                 vp = TAILQ_FIRST(&vnode_free_list);
  679                 /*
  680                  * The list can be modified while the free_list_mtx
  681                  * has been dropped and vp could be NULL here.
  682                  */
  683                 if (!vp)
  684                         break;
  685                 VNASSERT(vp->v_op != NULL, vp,
  686                     ("vnlru_free: vnode already reclaimed."));
  687                 TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
  688                 /*
  689                  * Don't recycle if we can't get the interlock.
  690                  */
  691                 if (!VI_TRYLOCK(vp)) {
  692                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
  693                         continue;
  694                 }
  695                 VNASSERT(VCANRECYCLE(vp), vp,
  696                     ("vp inconsistent on freelist"));
  697                 freevnodes--;
  698                 vp->v_iflag &= ~VI_FREE;
  699                 vholdl(vp);
  700                 mtx_unlock(&vnode_free_list_mtx);
  701                 VI_UNLOCK(vp);
  702                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
  703                 vtryrecycle(vp);
  704                 VFS_UNLOCK_GIANT(vfslocked);
  705                 /*
  706                  * If the recycled succeeded this vdrop will actually free
  707                  * the vnode.  If not it will simply place it back on
  708                  * the free list.
  709                  */
  710                 vdrop(vp);
  711                 mtx_lock(&vnode_free_list_mtx);
  712         }
  713 }
  714 /*
  715  * Attempt to recycle vnodes in a context that is always safe to block.
  716  * Calling vlrurecycle() from the bowels of filesystem code has some
  717  * interesting deadlock problems.
  718  */
  719 static struct proc *vnlruproc;
  720 static int vnlruproc_sig;
  721 
  722 static void
  723 vnlru_proc(void)
  724 {
  725         struct mount *mp, *nmp;
  726         int done, vfslocked;
  727         struct proc *p = vnlruproc;
  728         struct thread *td = curthread;
  729 
  730         EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
  731             SHUTDOWN_PRI_FIRST);
  732 
  733         for (;;) {
  734                 kthread_suspend_check(p);
  735                 mtx_lock(&vnode_free_list_mtx);
  736                 if (freevnodes > wantfreevnodes)
  737                         vnlru_free(freevnodes - wantfreevnodes);
  738                 if (numvnodes <= desiredvnodes * 9 / 10) {
  739                         vnlruproc_sig = 0;
  740                         wakeup(&vnlruproc_sig);
  741                         msleep(vnlruproc, &vnode_free_list_mtx,
  742                             PVFS|PDROP, "vlruwt", hz);
  743                         continue;
  744                 }
  745                 mtx_unlock(&vnode_free_list_mtx);
  746                 done = 0;
  747                 mtx_lock(&mountlist_mtx);
  748                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
  749                         if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td)) {
  750                                 nmp = TAILQ_NEXT(mp, mnt_list);
  751                                 continue;
  752                         }
  753                         vfslocked = VFS_LOCK_GIANT(mp);
  754                         done += vlrureclaim(mp);
  755                         VFS_UNLOCK_GIANT(vfslocked);
  756                         mtx_lock(&mountlist_mtx);
  757                         nmp = TAILQ_NEXT(mp, mnt_list);
  758                         vfs_unbusy(mp, td);
  759                 }
  760                 mtx_unlock(&mountlist_mtx);
  761                 if (done == 0) {
  762                         EVENTHANDLER_INVOKE(vfs_lowvnodes, desiredvnodes / 10);
  763 #if 0
  764                         /* These messages are temporary debugging aids */
  765                         if (vnlru_nowhere < 5)
  766                                 printf("vnlru process getting nowhere..\n");
  767                         else if (vnlru_nowhere == 5)
  768                                 printf("vnlru process messages stopped.\n");
  769 #endif
  770                         vnlru_nowhere++;
  771                         tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
  772                 } else
  773                         uio_yield();
  774         }
  775 }
  776 
  777 static struct kproc_desc vnlru_kp = {
  778         "vnlru",
  779         vnlru_proc,
  780         &vnlruproc
  781 };
  782 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
  783     &vnlru_kp);
  784 
  785 /*
  786  * Routines having to do with the management of the vnode table.
  787  */
  788 
  789 void
  790 vdestroy(struct vnode *vp)
  791 {
  792         struct bufobj *bo;
  793 
  794         CTR1(KTR_VFS, "vdestroy vp %p", vp);
  795         mtx_lock(&vnode_free_list_mtx);
  796         numvnodes--;
  797         mtx_unlock(&vnode_free_list_mtx);
  798         bo = &vp->v_bufobj;
  799         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
  800             ("cleaned vnode still on the free list."));
  801         VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
  802         VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
  803         VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
  804         VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
  805         VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
  806         VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
  807         VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
  808         VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
  809         VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
  810         VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
  811         VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
  812         VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
  813         VI_UNLOCK(vp);
  814 #ifdef MAC
  815         mac_destroy_vnode(vp);
  816 #endif
  817         if (vp->v_pollinfo != NULL)
  818                 destroy_vpollinfo(vp->v_pollinfo);
  819 #ifdef INVARIANTS
  820         /* XXX Elsewhere we can detect an already freed vnode via NULL v_op. */
  821         vp->v_op = NULL;
  822 #endif
  823         lockdestroy(vp->v_vnlock);
  824         mtx_destroy(&vp->v_interlock);
  825         uma_zfree(vnode_zone, vp);
  826 }
  827 
  828 /*
  829  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
  830  * before we actually vgone().  This function must be called with the vnode
  831  * held to prevent the vnode from being returned to the free list midway
  832  * through vgone().
  833  */
  834 static int
  835 vtryrecycle(struct vnode *vp)
  836 {
  837         struct thread *td = curthread;
  838         struct mount *vnmp;
  839 
  840         CTR1(KTR_VFS, "vtryrecycle: trying vp %p", vp);
  841         VNASSERT(vp->v_holdcnt, vp,
  842             ("vtryrecycle: Recycling vp %p without a reference.", vp));
  843         /*
  844          * This vnode may found and locked via some other list, if so we
  845          * can't recycle it yet.
  846          */
  847         if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT, td) != 0)
  848                 return (EWOULDBLOCK);
  849         /*
  850          * Don't recycle if its filesystem is being suspended.
  851          */
  852         if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
  853                 VOP_UNLOCK(vp, 0, td);
  854                 return (EBUSY);
  855         }
  856         /*
  857          * If we got this far, we need to acquire the interlock and see if
  858          * anyone picked up this vnode from another list.  If not, we will
  859          * mark it with DOOMED via vgonel() so that anyone who does find it
  860          * will skip over it.
  861          */
  862         VI_LOCK(vp);
  863         if (vp->v_usecount) {
  864                 VOP_UNLOCK(vp, LK_INTERLOCK, td);
  865                 vn_finished_write(vnmp);
  866                 return (EBUSY);
  867         }
  868         if ((vp->v_iflag & VI_DOOMED) == 0)
  869                 vgonel(vp);
  870         VOP_UNLOCK(vp, LK_INTERLOCK, td);
  871         vn_finished_write(vnmp);
  872         CTR1(KTR_VFS, "vtryrecycle: recycled vp %p", vp);
  873         return (0);
  874 }
  875 
  876 /*
  877  * Return the next vnode from the free list.
  878  */
  879 int
  880 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
  881     struct vnode **vpp)
  882 {
  883         struct vnode *vp = NULL;
  884         struct bufobj *bo;
  885 
  886         mtx_lock(&vnode_free_list_mtx);
  887         /*
  888          * Lend our context to reclaim vnodes if they've exceeded the max.
  889          */
  890         if (freevnodes > wantfreevnodes)
  891                 vnlru_free(1);
  892         /*
  893          * Wait for available vnodes.
  894          */
  895         if (numvnodes > desiredvnodes) {
  896                 if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
  897                         /*
  898                          * File system is beeing suspended, we cannot risk a
  899                          * deadlock here, so allocate new vnode anyway.
  900                          */
  901                         if (freevnodes > wantfreevnodes)
  902                                 vnlru_free(freevnodes - wantfreevnodes);
  903                         goto alloc;
  904                 }
  905                 if (vnlruproc_sig == 0) {
  906                         vnlruproc_sig = 1;      /* avoid unnecessary wakeups */
  907                         wakeup(vnlruproc);
  908                 }
  909                 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
  910                     "vlruwk", hz);
  911 #if 0   /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
  912                 if (numvnodes > desiredvnodes) {
  913                         mtx_unlock(&vnode_free_list_mtx);
  914                         return (ENFILE);
  915                 }
  916 #endif
  917         }
  918 alloc:
  919         numvnodes++;
  920         mtx_unlock(&vnode_free_list_mtx);
  921         vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
  922         /*
  923          * Setup locks.
  924          */
  925         vp->v_vnlock = &vp->v_lock;
  926         mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
  927         /*
  928          * By default, don't allow shared locks unless filesystems
  929          * opt-in.
  930          */
  931         lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
  932         /*
  933          * Initialize bufobj.
  934          */
  935         bo = &vp->v_bufobj;
  936         bo->__bo_vnode = vp;
  937         bo->bo_mtx = &vp->v_interlock;
  938         bo->bo_ops = &buf_ops_bio;
  939         bo->bo_private = vp;
  940         TAILQ_INIT(&bo->bo_clean.bv_hd);
  941         TAILQ_INIT(&bo->bo_dirty.bv_hd);
  942         /*
  943          * Initialize namecache.
  944          */
  945         LIST_INIT(&vp->v_cache_src);
  946         TAILQ_INIT(&vp->v_cache_dst);
  947         /*
  948          * Finalize various vnode identity bits.
  949          */
  950         vp->v_type = VNON;
  951         vp->v_tag = tag;
  952         vp->v_op = vops;
  953         v_incr_usecount(vp);
  954         vp->v_data = 0;
  955 #ifdef MAC
  956         mac_init_vnode(vp);
  957         if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
  958                 mac_associate_vnode_singlelabel(mp, vp);
  959         else if (mp == NULL && vops != &dead_vnodeops)
  960                 printf("NULL mp in getnewvnode()\n");
  961 #endif
  962         if (mp != NULL) {
  963                 bo->bo_bsize = mp->mnt_stat.f_iosize;
  964                 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
  965                         vp->v_vflag |= VV_NOKNOTE;
  966         }
  967 
  968         CTR2(KTR_VFS, "getnewvnode: mp %p vp %p", mp, vp);
  969         *vpp = vp;
  970         return (0);
  971 }
  972 
  973 /*
  974  * Delete from old mount point vnode list, if on one.
  975  */
  976 static void
  977 delmntque(struct vnode *vp)
  978 {
  979         struct mount *mp;
  980 
  981         mp = vp->v_mount;
  982         if (mp == NULL)
  983                 return;
  984         MNT_ILOCK(mp);
  985         vp->v_mount = NULL;
  986         VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
  987                 ("bad mount point vnode list size"));
  988         TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
  989         mp->mnt_nvnodelistsize--;
  990         MNT_REL(mp);
  991         MNT_IUNLOCK(mp);
  992 }
  993 
  994 static void
  995 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
  996 {
  997         struct thread *td;
  998 
  999         td = curthread; /* XXX ? */
 1000         vp->v_data = NULL;
 1001         vp->v_op = &dead_vnodeops;
 1002         /* XXX non mp-safe fs may still call insmntque with vnode
 1003            unlocked */
 1004         if (!VOP_ISLOCKED(vp, td))
 1005                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
 1006         vgone(vp);
 1007         vput(vp);
 1008 }
 1009 
 1010 /*
 1011  * Insert into list of vnodes for the new mount point, if available.
 1012  */
 1013 int
 1014 insmntque1(struct vnode *vp, struct mount *mp,
 1015         void (*dtr)(struct vnode *, void *), void *dtr_arg)
 1016 {
 1017         int locked;
 1018 
 1019         KASSERT(vp->v_mount == NULL,
 1020                 ("insmntque: vnode already on per mount vnode list"));
 1021         VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
 1022 #if 0
 1023 #ifdef DEBUG_VFS_LOCKS
 1024         if (!VFS_NEEDSGIANT(mp))
 1025                 ASSERT_VOP_ELOCKED(vp,
 1026                     "insmntque: mp-safe fs and non-locked vp");
 1027 #endif
 1028 #endif
 1029         MNT_ILOCK(mp);
 1030         if ((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
 1031             ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
 1032              mp->mnt_nvnodelistsize == 0)) {
 1033                 locked = VOP_ISLOCKED(vp, curthread);
 1034                 if (!locked || (locked == LK_EXCLUSIVE &&
 1035                      (vp->v_vflag & VV_FORCEINSMQ) == 0)) {
 1036                         MNT_IUNLOCK(mp);
 1037                         if (dtr != NULL)
 1038                                 dtr(vp, dtr_arg);
 1039                         return (EBUSY);
 1040                 }
 1041         }
 1042         vp->v_mount = mp;
 1043         MNT_REF(mp);
 1044         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
 1045         VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
 1046                 ("neg mount point vnode list size"));
 1047         mp->mnt_nvnodelistsize++;
 1048         MNT_IUNLOCK(mp);
 1049         return (0);
 1050 }
 1051 
 1052 int
 1053 insmntque(struct vnode *vp, struct mount *mp)
 1054 {
 1055 
 1056         return (insmntque1(vp, mp, insmntque_stddtr, NULL));
 1057 }
 1058 
 1059 /*
 1060  * Flush out and invalidate all buffers associated with a bufobj
 1061  * Called with the underlying object locked.
 1062  */
 1063 int
 1064 bufobj_invalbuf(struct bufobj *bo, int flags, struct thread *td, int slpflag,
 1065     int slptimeo)
 1066 {
 1067         int error;
 1068 
 1069         BO_LOCK(bo);
 1070         if (flags & V_SAVE) {
 1071                 error = bufobj_wwait(bo, slpflag, slptimeo);
 1072                 if (error) {
 1073                         BO_UNLOCK(bo);
 1074                         return (error);
 1075                 }
 1076                 if (bo->bo_dirty.bv_cnt > 0) {
 1077                         BO_UNLOCK(bo);
 1078                         if ((error = BO_SYNC(bo, MNT_WAIT, td)) != 0)
 1079                                 return (error);
 1080                         /*
 1081                          * XXX We could save a lock/unlock if this was only
 1082                          * enabled under INVARIANTS
 1083                          */
 1084                         BO_LOCK(bo);
 1085                         if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
 1086                                 panic("vinvalbuf: dirty bufs");
 1087                 }
 1088         }
 1089         /*
 1090          * If you alter this loop please notice that interlock is dropped and
 1091          * reacquired in flushbuflist.  Special care is needed to ensure that
 1092          * no race conditions occur from this.
 1093          */
 1094         do {
 1095                 error = flushbuflist(&bo->bo_clean,
 1096                     flags, bo, slpflag, slptimeo);
 1097                 if (error == 0)
 1098                         error = flushbuflist(&bo->bo_dirty,
 1099                             flags, bo, slpflag, slptimeo);
 1100                 if (error != 0 && error != EAGAIN) {
 1101                         BO_UNLOCK(bo);
 1102                         return (error);
 1103                 }
 1104         } while (error != 0);
 1105 
 1106         /*
 1107          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
 1108          * have write I/O in-progress but if there is a VM object then the
 1109          * VM object can also have read-I/O in-progress.
 1110          */
 1111         do {
 1112                 bufobj_wwait(bo, 0, 0);
 1113                 BO_UNLOCK(bo);
 1114                 if (bo->bo_object != NULL) {
 1115                         VM_OBJECT_LOCK(bo->bo_object);
 1116                         vm_object_pip_wait(bo->bo_object, "bovlbx");
 1117                         VM_OBJECT_UNLOCK(bo->bo_object);
 1118                 }
 1119                 BO_LOCK(bo);
 1120         } while (bo->bo_numoutput > 0);
 1121         BO_UNLOCK(bo);
 1122 
 1123         /*
 1124          * Destroy the copy in the VM cache, too.
 1125          */
 1126         if (bo->bo_object != NULL && (flags & (V_ALT | V_NORMAL)) == 0) {
 1127                 VM_OBJECT_LOCK(bo->bo_object);
 1128                 vm_object_page_remove(bo->bo_object, 0, 0,
 1129                         (flags & V_SAVE) ? TRUE : FALSE);
 1130                 VM_OBJECT_UNLOCK(bo->bo_object);
 1131         }
 1132 
 1133 #ifdef INVARIANTS
 1134         BO_LOCK(bo);
 1135         if ((flags & (V_ALT | V_NORMAL)) == 0 &&
 1136             (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
 1137                 panic("vinvalbuf: flush failed");
 1138         BO_UNLOCK(bo);
 1139 #endif
 1140         return (0);
 1141 }
 1142 
 1143 /*
 1144  * Flush out and invalidate all buffers associated with a vnode.
 1145  * Called with the underlying object locked.
 1146  */
 1147 int
 1148 vinvalbuf(struct vnode *vp, int flags, struct thread *td, int slpflag,
 1149     int slptimeo)
 1150 {
 1151 
 1152         CTR2(KTR_VFS, "vinvalbuf vp %p flags %d", vp, flags);
 1153         ASSERT_VOP_LOCKED(vp, "vinvalbuf");
 1154         return (bufobj_invalbuf(&vp->v_bufobj, flags, td, slpflag, slptimeo));
 1155 }
 1156 
 1157 /*
 1158  * Flush out buffers on the specified list.
 1159  *
 1160  */
 1161 static int
 1162 flushbuflist( struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
 1163     int slptimeo)
 1164 {
 1165         struct buf *bp, *nbp;
 1166         int retval, error;
 1167         daddr_t lblkno;
 1168         b_xflags_t xflags;
 1169 
 1170         ASSERT_BO_LOCKED(bo);
 1171 
 1172         retval = 0;
 1173         TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
 1174                 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
 1175                     ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
 1176                         continue;
 1177                 }
 1178                 lblkno = 0;
 1179                 xflags = 0;
 1180                 if (nbp != NULL) {
 1181                         lblkno = nbp->b_lblkno;
 1182                         xflags = nbp->b_xflags &
 1183                                 (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
 1184                 }
 1185                 retval = EAGAIN;
 1186                 error = BUF_TIMELOCK(bp,
 1187                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
 1188                     "flushbuf", slpflag, slptimeo);
 1189                 if (error) {
 1190                         BO_LOCK(bo);
 1191                         return (error != ENOLCK ? error : EAGAIN);
 1192                 }
 1193                 KASSERT(bp->b_bufobj == bo,
 1194                     ("bp %p wrong b_bufobj %p should be %p",
 1195                     bp, bp->b_bufobj, bo));
 1196                 if (bp->b_bufobj != bo) {       /* XXX: necessary ? */
 1197                         BUF_UNLOCK(bp);
 1198                         BO_LOCK(bo);
 1199                         return (EAGAIN);
 1200                 }
 1201                 /*
 1202                  * XXX Since there are no node locks for NFS, I
 1203                  * believe there is a slight chance that a delayed
 1204                  * write will occur while sleeping just above, so
 1205                  * check for it.
 1206                  */
 1207                 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
 1208                     (flags & V_SAVE)) {
 1209                         bremfree(bp);
 1210                         bp->b_flags |= B_ASYNC;
 1211                         bwrite(bp);
 1212                         BO_LOCK(bo);
 1213                         return (EAGAIN);        /* XXX: why not loop ? */
 1214                 }
 1215                 bremfree(bp);
 1216                 bp->b_flags |= (B_INVAL | B_RELBUF);
 1217                 bp->b_flags &= ~B_ASYNC;
 1218                 brelse(bp);
 1219                 BO_LOCK(bo);
 1220                 if (nbp != NULL &&
 1221                     (nbp->b_bufobj != bo ||
 1222                      nbp->b_lblkno != lblkno ||
 1223                      (nbp->b_xflags &
 1224                       (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
 1225                         break;                  /* nbp invalid */
 1226         }
 1227         return (retval);
 1228 }
 1229 
 1230 /*
 1231  * Truncate a file's buffer and pages to a specified length.  This
 1232  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
 1233  * sync activity.
 1234  */
 1235 int
 1236 vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
 1237     off_t length, int blksize)
 1238 {
 1239         struct buf *bp, *nbp;
 1240         int anyfreed;
 1241         int trunclbn;
 1242         struct bufobj *bo;
 1243 
 1244         CTR2(KTR_VFS, "vtruncbuf vp %p length %jd", vp, length);
 1245         /*
 1246          * Round up to the *next* lbn.
 1247          */
 1248         trunclbn = (length + blksize - 1) / blksize;
 1249 
 1250         ASSERT_VOP_LOCKED(vp, "vtruncbuf");
 1251 restart:
 1252         VI_LOCK(vp);
 1253         bo = &vp->v_bufobj;
 1254         anyfreed = 1;
 1255         for (;anyfreed;) {
 1256                 anyfreed = 0;
 1257                 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
 1258                         if (bp->b_lblkno < trunclbn)
 1259                                 continue;
 1260                         if (BUF_LOCK(bp,
 1261                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
 1262                             VI_MTX(vp)) == ENOLCK)
 1263                                 goto restart;
 1264 
 1265                         bremfree(bp);
 1266                         bp->b_flags |= (B_INVAL | B_RELBUF);
 1267                         bp->b_flags &= ~B_ASYNC;
 1268                         brelse(bp);
 1269                         anyfreed = 1;
 1270 
 1271                         if (nbp != NULL &&
 1272                             (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
 1273                             (nbp->b_vp != vp) ||
 1274                             (nbp->b_flags & B_DELWRI))) {
 1275                                 goto restart;
 1276                         }
 1277                         VI_LOCK(vp);
 1278                 }
 1279 
 1280                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
 1281                         if (bp->b_lblkno < trunclbn)
 1282                                 continue;
 1283                         if (BUF_LOCK(bp,
 1284                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
 1285                             VI_MTX(vp)) == ENOLCK)
 1286                                 goto restart;
 1287                         bremfree(bp);
 1288                         bp->b_flags |= (B_INVAL | B_RELBUF);
 1289                         bp->b_flags &= ~B_ASYNC;
 1290                         brelse(bp);
 1291                         anyfreed = 1;
 1292                         if (nbp != NULL &&
 1293                             (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
 1294                             (nbp->b_vp != vp) ||
 1295                             (nbp->b_flags & B_DELWRI) == 0)) {
 1296                                 goto restart;
 1297                         }
 1298                         VI_LOCK(vp);
 1299                 }
 1300         }
 1301 
 1302         if (length > 0) {
 1303 restartsync:
 1304                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
 1305                         if (bp->b_lblkno > 0)
 1306                                 continue;
 1307                         /*
 1308                          * Since we hold the vnode lock this should only
 1309                          * fail if we're racing with the buf daemon.
 1310                          */
 1311                         if (BUF_LOCK(bp,
 1312                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
 1313                             VI_MTX(vp)) == ENOLCK) {
 1314                                 goto restart;
 1315                         }
 1316                         VNASSERT((bp->b_flags & B_DELWRI), vp,
 1317                             ("buf(%p) on dirty queue without DELWRI", bp));
 1318 
 1319                         bremfree(bp);
 1320                         bawrite(bp);
 1321                         VI_LOCK(vp);
 1322                         goto restartsync;
 1323                 }
 1324         }
 1325 
 1326         bufobj_wwait(bo, 0, 0);
 1327         VI_UNLOCK(vp);
 1328         vnode_pager_setsize(vp, length);
 1329 
 1330         return (0);
 1331 }
 1332 
 1333 /*
 1334  * buf_splay() - splay tree core for the clean/dirty list of buffers in
 1335  *               a vnode.
 1336  *
 1337  *      NOTE: We have to deal with the special case of a background bitmap
 1338  *      buffer, a situation where two buffers will have the same logical
 1339  *      block offset.  We want (1) only the foreground buffer to be accessed
 1340  *      in a lookup and (2) must differentiate between the foreground and
 1341  *      background buffer in the splay tree algorithm because the splay
 1342  *      tree cannot normally handle multiple entities with the same 'index'.
 1343  *      We accomplish this by adding differentiating flags to the splay tree's
 1344  *      numerical domain.
 1345  */
 1346 static
 1347 struct buf *
 1348 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
 1349 {
 1350         struct buf dummy;
 1351         struct buf *lefttreemax, *righttreemin, *y;
 1352 
 1353         if (root == NULL)
 1354                 return (NULL);
 1355         lefttreemax = righttreemin = &dummy;
 1356         for (;;) {
 1357                 if (lblkno < root->b_lblkno ||
 1358                     (lblkno == root->b_lblkno &&
 1359                     (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
 1360                         if ((y = root->b_left) == NULL)
 1361                                 break;
 1362                         if (lblkno < y->b_lblkno) {
 1363                                 /* Rotate right. */
 1364                                 root->b_left = y->b_right;
 1365                                 y->b_right = root;
 1366                                 root = y;
 1367                                 if ((y = root->b_left) == NULL)
 1368                                         break;
 1369                         }
 1370                         /* Link into the new root's right tree. */
 1371                         righttreemin->b_left = root;
 1372                         righttreemin = root;
 1373                 } else if (lblkno > root->b_lblkno ||
 1374                     (lblkno == root->b_lblkno &&
 1375                     (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
 1376                         if ((y = root->b_right) == NULL)
 1377                                 break;
 1378                         if (lblkno > y->b_lblkno) {
 1379                                 /* Rotate left. */
 1380                                 root->b_right = y->b_left;
 1381                                 y->b_left = root;
 1382                                 root = y;
 1383                                 if ((y = root->b_right) == NULL)
 1384                                         break;
 1385                         }
 1386                         /* Link into the new root's left tree. */
 1387                         lefttreemax->b_right = root;
 1388                         lefttreemax = root;
 1389                 } else {
 1390                         break;
 1391                 }
 1392                 root = y;
 1393         }
 1394         /* Assemble the new root. */
 1395         lefttreemax->b_right = root->b_left;
 1396         righttreemin->b_left = root->b_right;
 1397         root->b_left = dummy.b_right;
 1398         root->b_right = dummy.b_left;
 1399         return (root);
 1400 }
 1401 
 1402 static void
 1403 buf_vlist_remove(struct buf *bp)
 1404 {
 1405         struct buf *root;
 1406         struct bufv *bv;
 1407 
 1408         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
 1409         ASSERT_BO_LOCKED(bp->b_bufobj);
 1410         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
 1411             (BX_VNDIRTY|BX_VNCLEAN),
 1412             ("buf_vlist_remove: Buf %p is on two lists", bp));
 1413         if (bp->b_xflags & BX_VNDIRTY)
 1414                 bv = &bp->b_bufobj->bo_dirty;
 1415         else
 1416                 bv = &bp->b_bufobj->bo_clean;
 1417         if (bp != bv->bv_root) {
 1418                 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
 1419                 KASSERT(root == bp, ("splay lookup failed in remove"));
 1420         }
 1421         if (bp->b_left == NULL) {
 1422                 root = bp->b_right;
 1423         } else {
 1424                 root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
 1425                 root->b_right = bp->b_right;
 1426         }
 1427         bv->bv_root = root;
 1428         TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
 1429         bv->bv_cnt--;
 1430         bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
 1431 }
 1432 
 1433 /*
 1434  * Add the buffer to the sorted clean or dirty block list using a
 1435  * splay tree algorithm.
 1436  *
 1437  * NOTE: xflags is passed as a constant, optimizing this inline function!
 1438  */
 1439 static void
 1440 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
 1441 {
 1442         struct buf *root;
 1443         struct bufv *bv;
 1444 
 1445         ASSERT_BO_LOCKED(bo);
 1446         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
 1447             ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
 1448         bp->b_xflags |= xflags;
 1449         if (xflags & BX_VNDIRTY)
 1450                 bv = &bo->bo_dirty;
 1451         else
 1452                 bv = &bo->bo_clean;
 1453 
 1454         root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
 1455         if (root == NULL) {
 1456                 bp->b_left = NULL;
 1457                 bp->b_right = NULL;
 1458                 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
 1459         } else if (bp->b_lblkno < root->b_lblkno ||
 1460             (bp->b_lblkno == root->b_lblkno &&
 1461             (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
 1462                 bp->b_left = root->b_left;
 1463                 bp->b_right = root;
 1464                 root->b_left = NULL;
 1465                 TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
 1466         } else {
 1467                 bp->b_right = root->b_right;
 1468                 bp->b_left = root;
 1469                 root->b_right = NULL;
 1470                 TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
 1471         }
 1472         bv->bv_cnt++;
 1473         bv->bv_root = bp;
 1474 }
 1475 
 1476 /*
 1477  * Lookup a buffer using the splay tree.  Note that we specifically avoid
 1478  * shadow buffers used in background bitmap writes.
 1479  *
 1480  * This code isn't quite efficient as it could be because we are maintaining
 1481  * two sorted lists and do not know which list the block resides in.
 1482  *
 1483  * During a "make buildworld" the desired buffer is found at one of
 1484  * the roots more than 60% of the time.  Thus, checking both roots
 1485  * before performing either splay eliminates unnecessary splays on the
 1486  * first tree splayed.
 1487  */
 1488 struct buf *
 1489 gbincore(struct bufobj *bo, daddr_t lblkno)
 1490 {
 1491         struct buf *bp;
 1492 
 1493         ASSERT_BO_LOCKED(bo);
 1494         if ((bp = bo->bo_clean.bv_root) != NULL &&
 1495             bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
 1496                 return (bp);
 1497         if ((bp = bo->bo_dirty.bv_root) != NULL &&
 1498             bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
 1499                 return (bp);
 1500         if ((bp = bo->bo_clean.bv_root) != NULL) {
 1501                 bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
 1502                 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
 1503                         return (bp);
 1504         }
 1505         if ((bp = bo->bo_dirty.bv_root) != NULL) {
 1506                 bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
 1507                 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
 1508                         return (bp);
 1509         }
 1510         return (NULL);
 1511 }
 1512 
 1513 /*
 1514  * Associate a buffer with a vnode.
 1515  */
 1516 void
 1517 bgetvp(struct vnode *vp, struct buf *bp)
 1518 {
 1519 
 1520         VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
 1521 
 1522         CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
 1523         VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
 1524             ("bgetvp: bp already attached! %p", bp));
 1525 
 1526         ASSERT_VI_LOCKED(vp, "bgetvp");
 1527         vholdl(vp);
 1528         if (VFS_NEEDSGIANT(vp->v_mount) ||
 1529             vp->v_bufobj.bo_flag & BO_NEEDSGIANT)
 1530                 bp->b_flags |= B_NEEDSGIANT;
 1531         bp->b_vp = vp;
 1532         bp->b_bufobj = &vp->v_bufobj;
 1533         /*
 1534          * Insert onto list for new vnode.
 1535          */
 1536         buf_vlist_add(bp, &vp->v_bufobj, BX_VNCLEAN);
 1537 }
 1538 
 1539 /*
 1540  * Disassociate a buffer from a vnode.
 1541  */
 1542 void
 1543 brelvp(struct buf *bp)
 1544 {
 1545         struct bufobj *bo;
 1546         struct vnode *vp;
 1547 
 1548         CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
 1549         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
 1550 
 1551         /*
 1552          * Delete from old vnode list, if on one.
 1553          */
 1554         vp = bp->b_vp;          /* XXX */
 1555         bo = bp->b_bufobj;
 1556         BO_LOCK(bo);
 1557         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
 1558                 buf_vlist_remove(bp);
 1559         else
 1560                 panic("brelvp: Buffer %p not on queue.", bp);
 1561         if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
 1562                 bo->bo_flag &= ~BO_ONWORKLST;
 1563                 mtx_lock(&sync_mtx);
 1564                 LIST_REMOVE(bo, bo_synclist);
 1565                 syncer_worklist_len--;
 1566                 mtx_unlock(&sync_mtx);
 1567         }
 1568         bp->b_flags &= ~B_NEEDSGIANT;
 1569         bp->b_vp = NULL;
 1570         bp->b_bufobj = NULL;
 1571         vdropl(vp);
 1572 }
 1573 
 1574 /*
 1575  * Add an item to the syncer work queue.
 1576  */
 1577 static void
 1578 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
 1579 {
 1580         int slot;
 1581 
 1582         ASSERT_BO_LOCKED(bo);
 1583 
 1584         mtx_lock(&sync_mtx);
 1585         if (bo->bo_flag & BO_ONWORKLST)
 1586                 LIST_REMOVE(bo, bo_synclist);
 1587         else {
 1588                 bo->bo_flag |= BO_ONWORKLST;
 1589                 syncer_worklist_len++;
 1590         }
 1591 
 1592         if (delay > syncer_maxdelay - 2)
 1593                 delay = syncer_maxdelay - 2;
 1594         slot = (syncer_delayno + delay) & syncer_mask;
 1595 
 1596         LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
 1597         mtx_unlock(&sync_mtx);
 1598 }
 1599 
 1600 static int
 1601 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
 1602 {
 1603         int error, len;
 1604 
 1605         mtx_lock(&sync_mtx);
 1606         len = syncer_worklist_len - sync_vnode_count;
 1607         mtx_unlock(&sync_mtx);
 1608         error = SYSCTL_OUT(req, &len, sizeof(len));
 1609         return (error);
 1610 }
 1611 
 1612 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
 1613     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
 1614 
 1615 static struct proc *updateproc;
 1616 static void sched_sync(void);
 1617 static struct kproc_desc up_kp = {
 1618         "syncer",
 1619         sched_sync,
 1620         &updateproc
 1621 };
 1622 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
 1623 
 1624 static int
 1625 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
 1626 {
 1627         struct vnode *vp;
 1628         struct mount *mp;
 1629         int vfslocked;
 1630 
 1631         vfslocked = 0;
 1632 restart:
 1633         *bo = LIST_FIRST(slp);
 1634         if (*bo == NULL) {
 1635                 VFS_UNLOCK_GIANT(vfslocked);
 1636                 return (0);
 1637         }
 1638         vp = (*bo)->__bo_vnode; /* XXX */
 1639         if (VFS_NEEDSGIANT(vp->v_mount)) {
 1640                 if (!vfslocked) {
 1641                         vfslocked = 1;
 1642                         if (mtx_trylock(&Giant) == 0) {
 1643                                 mtx_unlock(&sync_mtx);
 1644                                 mtx_lock(&Giant);
 1645                                 mtx_lock(&sync_mtx);
 1646                                 goto restart;
 1647                         }
 1648                 }
 1649         } else {
 1650                 VFS_UNLOCK_GIANT(vfslocked);
 1651                 vfslocked = 0;
 1652         }
 1653         if (VOP_ISLOCKED(vp, NULL) != 0) {
 1654                 VFS_UNLOCK_GIANT(vfslocked);
 1655                 return (1);
 1656         }
 1657         if (VI_TRYLOCK(vp) == 0) {
 1658                 VFS_UNLOCK_GIANT(vfslocked);
 1659                 return (1);
 1660         }
 1661         /*
 1662          * We use vhold in case the vnode does not
 1663          * successfully sync.  vhold prevents the vnode from
 1664          * going away when we unlock the sync_mtx so that
 1665          * we can acquire the vnode interlock.
 1666          */
 1667         vholdl(vp);
 1668         mtx_unlock(&sync_mtx);
 1669         VI_UNLOCK(vp);
 1670         if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
 1671                 vdrop(vp);
 1672                 VFS_UNLOCK_GIANT(vfslocked);
 1673                 mtx_lock(&sync_mtx);
 1674                 return (*bo == LIST_FIRST(slp));
 1675         }
 1676         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
 1677         (void) VOP_FSYNC(vp, MNT_LAZY, td);
 1678         VOP_UNLOCK(vp, 0, td);
 1679         vn_finished_write(mp);
 1680         VI_LOCK(vp);
 1681         if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
 1682                 /*
 1683                  * Put us back on the worklist.  The worklist
 1684                  * routine will remove us from our current
 1685                  * position and then add us back in at a later
 1686                  * position.
 1687                  */
 1688                 vn_syncer_add_to_worklist(*bo, syncdelay);
 1689         }
 1690         vdropl(vp);
 1691         VFS_UNLOCK_GIANT(vfslocked);
 1692         mtx_lock(&sync_mtx);
 1693         return (0);
 1694 }
 1695 
 1696 /*
 1697  * System filesystem synchronizer daemon.
 1698  */
 1699 static void
 1700 sched_sync(void)
 1701 {
 1702         struct synclist *next;
 1703         struct synclist *slp;
 1704         struct bufobj *bo;
 1705         long starttime;
 1706         struct thread *td = curthread;
 1707         static int dummychan;
 1708         int last_work_seen;
 1709         int net_worklist_len;
 1710         int syncer_final_iter;
 1711         int first_printf;
 1712         int error;
 1713 
 1714         last_work_seen = 0;
 1715         syncer_final_iter = 0;
 1716         first_printf = 1;
 1717         syncer_state = SYNCER_RUNNING;
 1718         starttime = time_uptime;
 1719         td->td_pflags |= TDP_NORUNNINGBUF;
 1720 
 1721         EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
 1722             SHUTDOWN_PRI_LAST);
 1723 
 1724         mtx_lock(&sync_mtx);
 1725         for (;;) {
 1726                 if (syncer_state == SYNCER_FINAL_DELAY &&
 1727                     syncer_final_iter == 0) {
 1728                         mtx_unlock(&sync_mtx);
 1729                         kthread_suspend_check(td->td_proc);
 1730                         mtx_lock(&sync_mtx);
 1731                 }
 1732                 net_worklist_len = syncer_worklist_len - sync_vnode_count;
 1733                 if (syncer_state != SYNCER_RUNNING &&
 1734                     starttime != time_uptime) {
 1735                         if (first_printf) {
 1736                                 printf("\nSyncing disks, vnodes remaining...");
 1737                                 first_printf = 0;
 1738                         }
 1739                         printf("%d ", net_worklist_len);
 1740                 }
 1741                 starttime = time_uptime;
 1742 
 1743                 /*
 1744                  * Push files whose dirty time has expired.  Be careful
 1745                  * of interrupt race on slp queue.
 1746                  *
 1747                  * Skip over empty worklist slots when shutting down.
 1748                  */
 1749                 do {
 1750                         slp = &syncer_workitem_pending[syncer_delayno];
 1751                         syncer_delayno += 1;
 1752                         if (syncer_delayno == syncer_maxdelay)
 1753                                 syncer_delayno = 0;
 1754                         next = &syncer_workitem_pending[syncer_delayno];
 1755                         /*
 1756                          * If the worklist has wrapped since the
 1757                          * it was emptied of all but syncer vnodes,
 1758                          * switch to the FINAL_DELAY state and run
 1759                          * for one more second.
 1760                          */
 1761                         if (syncer_state == SYNCER_SHUTTING_DOWN &&
 1762                             net_worklist_len == 0 &&
 1763                             last_work_seen == syncer_delayno) {
 1764                                 syncer_state = SYNCER_FINAL_DELAY;
 1765                                 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
 1766                         }
 1767                 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
 1768                     syncer_worklist_len > 0);
 1769 
 1770                 /*
 1771                  * Keep track of the last time there was anything
 1772                  * on the worklist other than syncer vnodes.
 1773                  * Return to the SHUTTING_DOWN state if any
 1774                  * new work appears.
 1775                  */
 1776                 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
 1777                         last_work_seen = syncer_delayno;
 1778                 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
 1779                         syncer_state = SYNCER_SHUTTING_DOWN;
 1780                 while (!LIST_EMPTY(slp)) {
 1781                         error = sync_vnode(slp, &bo, td);
 1782                         if (error == 1) {
 1783                                 LIST_REMOVE(bo, bo_synclist);
 1784                                 LIST_INSERT_HEAD(next, bo, bo_synclist);
 1785                                 continue;
 1786                         }
 1787                 }
 1788                 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
 1789                         syncer_final_iter--;
 1790                 /*
 1791                  * The variable rushjob allows the kernel to speed up the
 1792                  * processing of the filesystem syncer process. A rushjob
 1793                  * value of N tells the filesystem syncer to process the next
 1794                  * N seconds worth of work on its queue ASAP. Currently rushjob
 1795                  * is used by the soft update code to speed up the filesystem
 1796                  * syncer process when the incore state is getting so far
 1797                  * ahead of the disk that the kernel memory pool is being
 1798                  * threatened with exhaustion.
 1799                  */
 1800                 if (rushjob > 0) {
 1801                         rushjob -= 1;
 1802                         continue;
 1803                 }
 1804                 /*
 1805                  * Just sleep for a short period of time between
 1806                  * iterations when shutting down to allow some I/O
 1807                  * to happen.
 1808                  *
 1809                  * If it has taken us less than a second to process the
 1810                  * current work, then wait. Otherwise start right over
 1811                  * again. We can still lose time if any single round
 1812                  * takes more than two seconds, but it does not really
 1813                  * matter as we are just trying to generally pace the
 1814                  * filesystem activity.
 1815                  */
 1816                 if (syncer_state != SYNCER_RUNNING)
 1817                         msleep(&dummychan, &sync_mtx, PPAUSE, "syncfnl",
 1818                             hz / SYNCER_SHUTDOWN_SPEEDUP);
 1819                 else if (time_uptime == starttime)
 1820                         msleep(&lbolt, &sync_mtx, PPAUSE, "syncer", 0);
 1821         }
 1822 }
 1823 
 1824 /*
 1825  * Request the syncer daemon to speed up its work.
 1826  * We never push it to speed up more than half of its
 1827  * normal turn time, otherwise it could take over the cpu.
 1828  */
 1829 int
 1830 speedup_syncer(void)
 1831 {
 1832         struct thread *td;
 1833         int ret = 0;
 1834 
 1835         td = FIRST_THREAD_IN_PROC(updateproc);
 1836         mtx_lock(&sync_mtx);
 1837         if (rushjob < syncdelay / 2) {
 1838                 rushjob += 1;
 1839                 stat_rush_requests += 1;
 1840                 ret = 1;
 1841         }
 1842         mtx_unlock(&sync_mtx);
 1843         sleepq_remove(td, &lbolt);
 1844         return (ret);
 1845 }
 1846 
 1847 /*
 1848  * Tell the syncer to speed up its work and run though its work
 1849  * list several times, then tell it to shut down.
 1850  */
 1851 static void
 1852 syncer_shutdown(void *arg, int howto)
 1853 {
 1854         struct thread *td;
 1855 
 1856         if (howto & RB_NOSYNC)
 1857                 return;
 1858         td = FIRST_THREAD_IN_PROC(updateproc);
 1859         mtx_lock(&sync_mtx);
 1860         syncer_state = SYNCER_SHUTTING_DOWN;
 1861         rushjob = 0;
 1862         mtx_unlock(&sync_mtx);
 1863         sleepq_remove(td, &lbolt);
 1864         kproc_shutdown(arg, howto);
 1865 }
 1866 
 1867 /*
 1868  * Reassign a buffer from one vnode to another.
 1869  * Used to assign file specific control information
 1870  * (indirect blocks) to the vnode to which they belong.
 1871  */
 1872 void
 1873 reassignbuf(struct buf *bp)
 1874 {
 1875         struct vnode *vp;
 1876         struct bufobj *bo;
 1877         int delay;
 1878 #ifdef INVARIANTS
 1879         struct bufv *bv;
 1880 #endif
 1881 
 1882         vp = bp->b_vp;
 1883         bo = bp->b_bufobj;
 1884         ++reassignbufcalls;
 1885 
 1886         CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
 1887             bp, bp->b_vp, bp->b_flags);
 1888         /*
 1889          * B_PAGING flagged buffers cannot be reassigned because their vp
 1890          * is not fully linked in.
 1891          */
 1892         if (bp->b_flags & B_PAGING)
 1893                 panic("cannot reassign paging buffer");
 1894 
 1895         /*
 1896          * Delete from old vnode list, if on one.
 1897          */
 1898         VI_LOCK(vp);
 1899         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
 1900                 buf_vlist_remove(bp);
 1901         else
 1902                 panic("reassignbuf: Buffer %p not on queue.", bp);
 1903         /*
 1904          * If dirty, put on list of dirty buffers; otherwise insert onto list
 1905          * of clean buffers.
 1906          */
 1907         if (bp->b_flags & B_DELWRI) {
 1908                 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
 1909                         switch (vp->v_type) {
 1910                         case VDIR:
 1911                                 delay = dirdelay;
 1912                                 break;
 1913                         case VCHR:
 1914                                 delay = metadelay;
 1915                                 break;
 1916                         default:
 1917                                 delay = filedelay;
 1918                         }
 1919                         vn_syncer_add_to_worklist(bo, delay);
 1920                 }
 1921                 buf_vlist_add(bp, bo, BX_VNDIRTY);
 1922         } else {
 1923                 buf_vlist_add(bp, bo, BX_VNCLEAN);
 1924 
 1925                 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
 1926                         mtx_lock(&sync_mtx);
 1927                         LIST_REMOVE(bo, bo_synclist);
 1928                         syncer_worklist_len--;
 1929                         mtx_unlock(&sync_mtx);
 1930                         bo->bo_flag &= ~BO_ONWORKLST;
 1931                 }
 1932         }
 1933 #ifdef INVARIANTS
 1934         bv = &bo->bo_clean;
 1935         bp = TAILQ_FIRST(&bv->bv_hd);
 1936         KASSERT(bp == NULL || bp->b_bufobj == bo,
 1937             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 1938         bp = TAILQ_LAST(&bv->bv_hd, buflists);
 1939         KASSERT(bp == NULL || bp->b_bufobj == bo,
 1940             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 1941         bv = &bo->bo_dirty;
 1942         bp = TAILQ_FIRST(&bv->bv_hd);
 1943         KASSERT(bp == NULL || bp->b_bufobj == bo,
 1944             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 1945         bp = TAILQ_LAST(&bv->bv_hd, buflists);
 1946         KASSERT(bp == NULL || bp->b_bufobj == bo,
 1947             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 1948 #endif
 1949         VI_UNLOCK(vp);
 1950 }
 1951 
 1952 /*
 1953  * Increment the use and hold counts on the vnode, taking care to reference
 1954  * the driver's usecount if this is a chardev.  The vholdl() will remove
 1955  * the vnode from the free list if it is presently free.  Requires the
 1956  * vnode interlock and returns with it held.
 1957  */
 1958 static void
 1959 v_incr_usecount(struct vnode *vp)
 1960 {
 1961 
 1962         CTR3(KTR_VFS, "v_incr_usecount: vp %p holdcnt %d usecount %d\n",
 1963             vp, vp->v_holdcnt, vp->v_usecount);
 1964         vp->v_usecount++;
 1965         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
 1966                 dev_lock();
 1967                 vp->v_rdev->si_usecount++;
 1968                 dev_unlock();
 1969         }
 1970         vholdl(vp);
 1971 }
 1972 
 1973 /*
 1974  * Turn a holdcnt into a use+holdcnt such that only one call to
 1975  * v_decr_usecount is needed.
 1976  */
 1977 static void
 1978 v_upgrade_usecount(struct vnode *vp)
 1979 {
 1980 
 1981         CTR3(KTR_VFS, "v_upgrade_usecount: vp %p holdcnt %d usecount %d\n",
 1982             vp, vp->v_holdcnt, vp->v_usecount);
 1983         vp->v_usecount++;
 1984         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
 1985                 dev_lock();
 1986                 vp->v_rdev->si_usecount++;
 1987                 dev_unlock();
 1988         }
 1989 }
 1990 
 1991 /*
 1992  * Decrement the vnode use and hold count along with the driver's usecount
 1993  * if this is a chardev.  The vdropl() below releases the vnode interlock
 1994  * as it may free the vnode.
 1995  */
 1996 static void
 1997 v_decr_usecount(struct vnode *vp)
 1998 {
 1999 
 2000         CTR3(KTR_VFS, "v_decr_usecount: vp %p holdcnt %d usecount %d\n",
 2001             vp, vp->v_holdcnt, vp->v_usecount);
 2002         ASSERT_VI_LOCKED(vp, __FUNCTION__);
 2003         VNASSERT(vp->v_usecount > 0, vp,
 2004             ("v_decr_usecount: negative usecount"));
 2005         vp->v_usecount--;
 2006         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
 2007                 dev_lock();
 2008                 vp->v_rdev->si_usecount--;
 2009                 dev_unlock();
 2010         }
 2011         vdropl(vp);
 2012 }
 2013 
 2014 /*
 2015  * Decrement only the use count and driver use count.  This is intended to
 2016  * be paired with a follow on vdropl() to release the remaining hold count.
 2017  * In this way we may vgone() a vnode with a 0 usecount without risk of
 2018  * having it end up on a free list because the hold count is kept above 0.
 2019  */
 2020 static void
 2021 v_decr_useonly(struct vnode *vp)
 2022 {
 2023 
 2024         CTR3(KTR_VFS, "v_decr_useonly: vp %p holdcnt %d usecount %d\n",
 2025             vp, vp->v_holdcnt, vp->v_usecount);
 2026         ASSERT_VI_LOCKED(vp, __FUNCTION__);
 2027         VNASSERT(vp->v_usecount > 0, vp,
 2028             ("v_decr_useonly: negative usecount"));
 2029         vp->v_usecount--;
 2030         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
 2031                 dev_lock();
 2032                 vp->v_rdev->si_usecount--;
 2033                 dev_unlock();
 2034         }
 2035 }
 2036 
 2037 /*
 2038  * Grab a particular vnode from the free list, increment its
 2039  * reference count and lock it. The vnode lock bit is set if the
 2040  * vnode is being eliminated in vgone. The process is awakened
 2041  * when the transition is completed, and an error returned to
 2042  * indicate that the vnode is no longer usable (possibly having
 2043  * been changed to a new filesystem type).
 2044  */
 2045 int
 2046 vget(struct vnode *vp, int flags, struct thread *td)
 2047 {
 2048         int oweinact;
 2049         int oldflags;
 2050         int error;
 2051 
 2052         error = 0;
 2053         oldflags = flags;
 2054         oweinact = 0;
 2055         VFS_ASSERT_GIANT(vp->v_mount);
 2056         if ((flags & LK_INTERLOCK) == 0)
 2057                 VI_LOCK(vp);
 2058         /*
 2059          * If the inactive call was deferred because vput() was called
 2060          * with a shared lock, we have to do it here before another thread
 2061          * gets a reference to data that should be dead.
 2062          */
 2063         if (vp->v_iflag & VI_OWEINACT) {
 2064                 if (flags & LK_NOWAIT) {
 2065                         VI_UNLOCK(vp);
 2066                         return (EBUSY);
 2067                 }
 2068                 flags &= ~LK_TYPE_MASK;
 2069                 flags |= LK_EXCLUSIVE;
 2070                 oweinact = 1;
 2071         }
 2072         vholdl(vp);
 2073         if ((error = vn_lock(vp, flags | LK_INTERLOCK, td)) != 0) {
 2074                 vdrop(vp);
 2075                 return (error);
 2076         }
 2077         VI_LOCK(vp);
 2078         /*
 2079          * Deal with a timing window when the interlock is not held
 2080          * and VI_DOOMED can be set, since we only have a holdcnt,
 2081          * not a usecount.
 2082          */
 2083         if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0) {
 2084                KASSERT((flags & LK_TYPE_MASK) == 0, ("Unexpected flags %x", flags));
 2085                vdropl(vp);
 2086                return (ENOENT);
 2087         }
 2088         /* Upgrade our holdcnt to a usecount. */
 2089         v_upgrade_usecount(vp);
 2090         if (oweinact) {
 2091                 if (vp->v_iflag & VI_OWEINACT)
 2092                         vinactive(vp, td);
 2093                 VI_UNLOCK(vp);
 2094                 if ((oldflags & LK_TYPE_MASK) == 0)
 2095                         VOP_UNLOCK(vp, 0, td);
 2096         } else
 2097                 VI_UNLOCK(vp);
 2098         return (0);
 2099 }
 2100 
 2101 /*
 2102  * Increase the reference count of a vnode.
 2103  */
 2104 void
 2105 vref(struct vnode *vp)
 2106 {
 2107 
 2108         VI_LOCK(vp);
 2109         v_incr_usecount(vp);
 2110         VI_UNLOCK(vp);
 2111 }
 2112 
 2113 /*
 2114  * Return reference count of a vnode.
 2115  *
 2116  * The results of this call are only guaranteed when some mechanism other
 2117  * than the VI lock is used to stop other processes from gaining references
 2118  * to the vnode.  This may be the case if the caller holds the only reference.
 2119  * This is also useful when stale data is acceptable as race conditions may
 2120  * be accounted for by some other means.
 2121  */
 2122 int
 2123 vrefcnt(struct vnode *vp)
 2124 {
 2125         int usecnt;
 2126 
 2127         VI_LOCK(vp);
 2128         usecnt = vp->v_usecount;
 2129         VI_UNLOCK(vp);
 2130 
 2131         return (usecnt);
 2132 }
 2133 
 2134 
 2135 /*
 2136  * Vnode put/release.
 2137  * If count drops to zero, call inactive routine and return to freelist.
 2138  */
 2139 void
 2140 vrele(struct vnode *vp)
 2141 {
 2142         struct thread *td = curthread;  /* XXX */
 2143 
 2144         KASSERT(vp != NULL, ("vrele: null vp"));
 2145         VFS_ASSERT_GIANT(vp->v_mount);
 2146 
 2147         VI_LOCK(vp);
 2148 
 2149         /* Skip this v_writecount check if we're going to panic below. */
 2150         VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
 2151             ("vrele: missed vn_close"));
 2152 
 2153         if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
 2154             vp->v_usecount == 1)) {
 2155                 v_decr_usecount(vp);
 2156                 return;
 2157         }
 2158         if (vp->v_usecount != 1) {
 2159 #ifdef DIAGNOSTIC
 2160                 vprint("vrele: negative ref count", vp);
 2161 #endif
 2162                 VI_UNLOCK(vp);
 2163                 panic("vrele: negative ref cnt");
 2164         }
 2165         /*
 2166          * We want to hold the vnode until the inactive finishes to
 2167          * prevent vgone() races.  We drop the use count here and the
 2168          * hold count below when we're done.
 2169          */
 2170         v_decr_useonly(vp);
 2171         /*
 2172          * We must call VOP_INACTIVE with the node locked. Mark
 2173          * as VI_DOINGINACT to avoid recursion.
 2174          */
 2175         vp->v_iflag |= VI_OWEINACT;
 2176         if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, td) == 0) {
 2177                 VI_LOCK(vp);
 2178                 if (vp->v_usecount > 0)
 2179                         vp->v_iflag &= ~VI_OWEINACT;
 2180                 if (vp->v_iflag & VI_OWEINACT)
 2181                         vinactive(vp, td);
 2182                 VOP_UNLOCK(vp, 0, td);
 2183         } else {
 2184                 VI_LOCK(vp);
 2185                 if (vp->v_usecount > 0)
 2186                         vp->v_iflag &= ~VI_OWEINACT;
 2187         }
 2188         vdropl(vp);
 2189 }
 2190 
 2191 /*
 2192  * Release an already locked vnode.  This give the same effects as
 2193  * unlock+vrele(), but takes less time and avoids releasing and
 2194  * re-aquiring the lock (as vrele() acquires the lock internally.)
 2195  */
 2196 void
 2197 vput(struct vnode *vp)
 2198 {
 2199         struct thread *td = curthread;  /* XXX */
 2200         int error;
 2201 
 2202         KASSERT(vp != NULL, ("vput: null vp"));
 2203         ASSERT_VOP_LOCKED(vp, "vput");
 2204         VFS_ASSERT_GIANT(vp->v_mount);
 2205         VI_LOCK(vp);
 2206         /* Skip this v_writecount check if we're going to panic below. */
 2207         VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
 2208             ("vput: missed vn_close"));
 2209         error = 0;
 2210 
 2211         if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
 2212             vp->v_usecount == 1)) {
 2213                 VOP_UNLOCK(vp, 0, td);
 2214                 v_decr_usecount(vp);
 2215                 return;
 2216         }
 2217 
 2218         if (vp->v_usecount != 1) {
 2219 #ifdef DIAGNOSTIC
 2220                 vprint("vput: negative ref count", vp);
 2221 #endif
 2222                 panic("vput: negative ref cnt");
 2223         }
 2224         /*
 2225          * We want to hold the vnode until the inactive finishes to
 2226          * prevent vgone() races.  We drop the use count here and the
 2227          * hold count below when we're done.
 2228          */
 2229         v_decr_useonly(vp);
 2230         vp->v_iflag |= VI_OWEINACT;
 2231         if (VOP_ISLOCKED(vp, NULL) != LK_EXCLUSIVE) {
 2232                 error = VOP_LOCK(vp, LK_UPGRADE|LK_INTERLOCK|LK_NOWAIT, td);
 2233                 VI_LOCK(vp);
 2234                 if (error) {
 2235                         if (vp->v_usecount > 0)
 2236                                 vp->v_iflag &= ~VI_OWEINACT;
 2237                         goto done;
 2238                 }
 2239         }
 2240         if (vp->v_usecount > 0)
 2241                 vp->v_iflag &= ~VI_OWEINACT;
 2242         if (vp->v_iflag & VI_OWEINACT)
 2243                 vinactive(vp, td);
 2244         VOP_UNLOCK(vp, 0, td);
 2245 done:
 2246         vdropl(vp);
 2247 }
 2248 
 2249 /*
 2250  * Somebody doesn't want the vnode recycled.
 2251  */
 2252 void
 2253 vhold(struct vnode *vp)
 2254 {
 2255 
 2256         VI_LOCK(vp);
 2257         vholdl(vp);
 2258         VI_UNLOCK(vp);
 2259 }
 2260 
 2261 void
 2262 vholdl(struct vnode *vp)
 2263 {
 2264 
 2265         vp->v_holdcnt++;
 2266         if (VSHOULDBUSY(vp))
 2267                 vbusy(vp);
 2268 }
 2269 
 2270 /*
 2271  * Note that there is one less who cares about this vnode.  vdrop() is the
 2272  * opposite of vhold().
 2273  */
 2274 void
 2275 vdrop(struct vnode *vp)
 2276 {
 2277 
 2278         VI_LOCK(vp);
 2279         vdropl(vp);
 2280 }
 2281 
 2282 /*
 2283  * Drop the hold count of the vnode.  If this is the last reference to
 2284  * the vnode we will free it if it has been vgone'd otherwise it is
 2285  * placed on the free list.
 2286  */
 2287 void
 2288 vdropl(struct vnode *vp)
 2289 {
 2290 
 2291         ASSERT_VI_LOCKED(vp, "vdropl");
 2292         if (vp->v_holdcnt <= 0)
 2293                 panic("vdrop: holdcnt %d", vp->v_holdcnt);
 2294         vp->v_holdcnt--;
 2295         if (vp->v_holdcnt == 0) {
 2296                 if (vp->v_iflag & VI_DOOMED) {
 2297                         vdestroy(vp);
 2298                         return;
 2299                 } else
 2300                         vfree(vp);
 2301         }
 2302         VI_UNLOCK(vp);
 2303 }
 2304 
 2305 /*
 2306  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
 2307  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
 2308  * OWEINACT tracks whether a vnode missed a call to inactive due to a
 2309  * failed lock upgrade.
 2310  */
 2311 static void
 2312 vinactive(struct vnode *vp, struct thread *td)
 2313 {
 2314 
 2315         ASSERT_VOP_LOCKED(vp, "vinactive");
 2316         ASSERT_VI_LOCKED(vp, "vinactive");
 2317         VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
 2318             ("vinactive: recursed on VI_DOINGINACT"));
 2319         vp->v_iflag |= VI_DOINGINACT;
 2320         vp->v_iflag &= ~VI_OWEINACT;
 2321         VI_UNLOCK(vp);
 2322         VOP_INACTIVE(vp, td);
 2323         VI_LOCK(vp);
 2324         VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
 2325             ("vinactive: lost VI_DOINGINACT"));
 2326         vp->v_iflag &= ~VI_DOINGINACT;
 2327 }
 2328 
 2329 /*
 2330  * Remove any vnodes in the vnode table belonging to mount point mp.
 2331  *
 2332  * If FORCECLOSE is not specified, there should not be any active ones,
 2333  * return error if any are found (nb: this is a user error, not a
 2334  * system error). If FORCECLOSE is specified, detach any active vnodes
 2335  * that are found.
 2336  *
 2337  * If WRITECLOSE is set, only flush out regular file vnodes open for
 2338  * writing.
 2339  *
 2340  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
 2341  *
 2342  * `rootrefs' specifies the base reference count for the root vnode
 2343  * of this filesystem. The root vnode is considered busy if its
 2344  * v_usecount exceeds this value. On a successful return, vflush(, td)
 2345  * will call vrele() on the root vnode exactly rootrefs times.
 2346  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
 2347  * be zero.
 2348  */
 2349 #ifdef DIAGNOSTIC
 2350 static int busyprt = 0;         /* print out busy vnodes */
 2351 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
 2352 #endif
 2353 
 2354 int
 2355 vflush( struct mount *mp, int rootrefs, int flags, struct thread *td)
 2356 {
 2357         struct vnode *vp, *mvp, *rootvp = NULL;
 2358         struct vattr vattr;
 2359         int busy = 0, error;
 2360 
 2361         CTR1(KTR_VFS, "vflush: mp %p", mp);
 2362         if (rootrefs > 0) {
 2363                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
 2364                     ("vflush: bad args"));
 2365                 /*
 2366                  * Get the filesystem root vnode. We can vput() it
 2367                  * immediately, since with rootrefs > 0, it won't go away.
 2368                  */
 2369                 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp, td)) != 0)
 2370                         return (error);
 2371                 vput(rootvp);
 2372 
 2373         }
 2374         MNT_ILOCK(mp);
 2375 loop:
 2376         MNT_VNODE_FOREACH(vp, mp, mvp) {
 2377 
 2378                 VI_LOCK(vp);
 2379                 vholdl(vp);
 2380                 MNT_IUNLOCK(mp);
 2381                 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE, td);
 2382                 if (error) {
 2383                         vdrop(vp);
 2384                         MNT_ILOCK(mp);
 2385                         MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);
 2386                         goto loop;
 2387                 }
 2388                 /*
 2389                  * Skip over a vnodes marked VV_SYSTEM.
 2390                  */
 2391                 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
 2392                         VOP_UNLOCK(vp, 0, td);
 2393                         vdrop(vp);
 2394                         MNT_ILOCK(mp);
 2395                         continue;
 2396                 }
 2397                 /*
 2398                  * If WRITECLOSE is set, flush out unlinked but still open
 2399                  * files (even if open only for reading) and regular file
 2400                  * vnodes open for writing.
 2401                  */
 2402                 if (flags & WRITECLOSE) {
 2403                         error = VOP_GETATTR(vp, &vattr, td->td_ucred, td);
 2404                         VI_LOCK(vp);
 2405 
 2406                         if ((vp->v_type == VNON ||
 2407                             (error == 0 && vattr.va_nlink > 0)) &&
 2408                             (vp->v_writecount == 0 || vp->v_type != VREG)) {
 2409                                 VOP_UNLOCK(vp, 0, td);
 2410                                 vdropl(vp);
 2411                                 MNT_ILOCK(mp);
 2412                                 continue;
 2413                         }
 2414                 } else
 2415                         VI_LOCK(vp);
 2416                 /*
 2417                  * With v_usecount == 0, all we need to do is clear out the
 2418                  * vnode data structures and we are done.
 2419                  *
 2420                  * If FORCECLOSE is set, forcibly close the vnode.
 2421                  */
 2422                 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
 2423                         VNASSERT(vp->v_usecount == 0 ||
 2424                             (vp->v_type != VCHR && vp->v_type != VBLK), vp,
 2425                             ("device VNODE %p is FORCECLOSED", vp));
 2426                         vgonel(vp);
 2427                 } else {
 2428                         busy++;
 2429 #ifdef DIAGNOSTIC
 2430                         if (busyprt)
 2431                                 vprint("vflush: busy vnode", vp);
 2432 #endif
 2433                 }
 2434                 VOP_UNLOCK(vp, 0, td);
 2435                 vdropl(vp);
 2436                 MNT_ILOCK(mp);
 2437         }
 2438         MNT_IUNLOCK(mp);
 2439         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
 2440                 /*
 2441                  * If just the root vnode is busy, and if its refcount
 2442                  * is equal to `rootrefs', then go ahead and kill it.
 2443                  */
 2444                 VI_LOCK(rootvp);
 2445                 KASSERT(busy > 0, ("vflush: not busy"));
 2446                 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
 2447                     ("vflush: usecount %d < rootrefs %d",
 2448                      rootvp->v_usecount, rootrefs));
 2449                 if (busy == 1 && rootvp->v_usecount == rootrefs) {
 2450                         VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK, td);
 2451                         vgone(rootvp);
 2452                         VOP_UNLOCK(rootvp, 0, td);
 2453                         busy = 0;
 2454                 } else
 2455                         VI_UNLOCK(rootvp);
 2456         }
 2457         if (busy)
 2458                 return (EBUSY);
 2459         for (; rootrefs > 0; rootrefs--)
 2460                 vrele(rootvp);
 2461         return (0);
 2462 }
 2463 
 2464 /*
 2465  * Recycle an unused vnode to the front of the free list.
 2466  */
 2467 int
 2468 vrecycle(struct vnode *vp, struct thread *td)
 2469 {
 2470         int recycled;
 2471 
 2472         ASSERT_VOP_LOCKED(vp, "vrecycle");
 2473         recycled = 0;
 2474         VI_LOCK(vp);
 2475         if (vp->v_usecount == 0) {
 2476                 recycled = 1;
 2477                 vgonel(vp);
 2478         }
 2479         VI_UNLOCK(vp);
 2480         return (recycled);
 2481 }
 2482 
 2483 /*
 2484  * Eliminate all activity associated with a vnode
 2485  * in preparation for reuse.
 2486  */
 2487 void
 2488 vgone(struct vnode *vp)
 2489 {
 2490         VI_LOCK(vp);
 2491         vgonel(vp);
 2492         VI_UNLOCK(vp);
 2493 }
 2494 
 2495 /*
 2496  * vgone, with the vp interlock held.
 2497  */
 2498 void
 2499 vgonel(struct vnode *vp)
 2500 {
 2501         struct thread *td;
 2502         int oweinact;
 2503         int active;
 2504         struct mount *mp;
 2505 
 2506         CTR1(KTR_VFS, "vgonel: vp %p", vp);
 2507         ASSERT_VOP_LOCKED(vp, "vgonel");
 2508         ASSERT_VI_LOCKED(vp, "vgonel");
 2509         VNASSERT(vp->v_holdcnt, vp,
 2510             ("vgonel: vp %p has no reference.", vp));
 2511         td = curthread;
 2512 
 2513         /*
 2514          * Don't vgonel if we're already doomed.
 2515          */
 2516         if (vp->v_iflag & VI_DOOMED)
 2517                 return;
 2518         vp->v_iflag |= VI_DOOMED;
 2519         /*
 2520          * Check to see if the vnode is in use.  If so, we have to call
 2521          * VOP_CLOSE() and VOP_INACTIVE().
 2522          */
 2523         active = vp->v_usecount;
 2524         oweinact = (vp->v_iflag & VI_OWEINACT);
 2525         VI_UNLOCK(vp);
 2526         /*
 2527          * Clean out any buffers associated with the vnode.
 2528          * If the flush fails, just toss the buffers.
 2529          */
 2530         mp = NULL;
 2531         if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
 2532                 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
 2533         if (vinvalbuf(vp, V_SAVE, td, 0, 0) != 0)
 2534                 vinvalbuf(vp, 0, td, 0, 0);
 2535 
 2536         /*
 2537          * If purging an active vnode, it must be closed and
 2538          * deactivated before being reclaimed.
 2539          */
 2540         if (active)
 2541                 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
 2542         if (oweinact || active) {
 2543                 VI_LOCK(vp);
 2544                 if ((vp->v_iflag & VI_DOINGINACT) == 0)
 2545                         vinactive(vp, td);
 2546                 VI_UNLOCK(vp);
 2547         }
 2548         /*
 2549          * Reclaim the vnode.
 2550          */
 2551         if (VOP_RECLAIM(vp, td))
 2552                 panic("vgone: cannot reclaim");
 2553         if (mp != NULL)
 2554                 vn_finished_secondary_write(mp);
 2555         VNASSERT(vp->v_object == NULL, vp,
 2556             ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
 2557         /*
 2558          * Clear the advisory locks and wake up waiting threads.
 2559          */
 2560         lf_purgelocks(vp, &(vp->v_lockf));
 2561         /*
 2562          * Delete from old mount point vnode list.
 2563          */
 2564         delmntque(vp);
 2565         cache_purge(vp);
 2566         /*
 2567          * Done with purge, reset to the standard lock and invalidate
 2568          * the vnode.
 2569          */
 2570         VI_LOCK(vp);
 2571         vp->v_vnlock = &vp->v_lock;
 2572         vp->v_op = &dead_vnodeops;
 2573         vp->v_tag = "none";
 2574         vp->v_type = VBAD;
 2575 }
 2576 
 2577 /*
 2578  * Calculate the total number of references to a special device.
 2579  */
 2580 int
 2581 vcount(struct vnode *vp)
 2582 {
 2583         int count;
 2584 
 2585         dev_lock();
 2586         count = vp->v_rdev->si_usecount;
 2587         dev_unlock();
 2588         return (count);
 2589 }
 2590 
 2591 /*
 2592  * Same as above, but using the struct cdev *as argument
 2593  */
 2594 int
 2595 count_dev(struct cdev *dev)
 2596 {
 2597         int count;
 2598 
 2599         dev_lock();
 2600         count = dev->si_usecount;
 2601         dev_unlock();
 2602         return(count);
 2603 }
 2604 
 2605 /*
 2606  * Print out a description of a vnode.
 2607  */
 2608 static char *typename[] =
 2609 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
 2610  "VMARKER"};
 2611 
 2612 void
 2613 vn_printf(struct vnode *vp, const char *fmt, ...)
 2614 {
 2615         va_list ap;
 2616         char buf[256], buf2[16];
 2617         u_long flags;
 2618 
 2619         va_start(ap, fmt);
 2620         vprintf(fmt, ap);
 2621         va_end(ap);
 2622         printf("%p: ", (void *)vp);
 2623         printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
 2624         printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
 2625             vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
 2626         buf[0] = '\0';
 2627         buf[1] = '\0';
 2628         if (vp->v_vflag & VV_ROOT)
 2629                 strlcat(buf, "|VV_ROOT", sizeof(buf));
 2630         if (vp->v_vflag & VV_ISTTY)
 2631                 strlcat(buf, "|VV_ISTTY", sizeof(buf));
 2632         if (vp->v_vflag & VV_NOSYNC)
 2633                 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
 2634         if (vp->v_vflag & VV_CACHEDLABEL)
 2635                 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
 2636         if (vp->v_vflag & VV_TEXT)
 2637                 strlcat(buf, "|VV_TEXT", sizeof(buf));
 2638         if (vp->v_vflag & VV_COPYONWRITE)
 2639                 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
 2640         if (vp->v_vflag & VV_SYSTEM)
 2641                 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
 2642         if (vp->v_vflag & VV_PROCDEP)
 2643                 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
 2644         if (vp->v_vflag & VV_NOKNOTE)
 2645                 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
 2646         if (vp->v_vflag & VV_DELETED)
 2647                 strlcat(buf, "|VV_DELETED", sizeof(buf));
 2648         if (vp->v_vflag & VV_MD)
 2649                 strlcat(buf, "|VV_MD", sizeof(buf));
 2650         flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC |
 2651             VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
 2652             VV_NOKNOTE | VV_DELETED | VV_MD);
 2653         if (flags != 0) {
 2654                 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
 2655                 strlcat(buf, buf2, sizeof(buf));
 2656         }
 2657         if (vp->v_iflag & VI_MOUNT)
 2658                 strlcat(buf, "|VI_MOUNT", sizeof(buf));
 2659         if (vp->v_iflag & VI_AGE)
 2660                 strlcat(buf, "|VI_AGE", sizeof(buf));
 2661         if (vp->v_iflag & VI_DOOMED)
 2662                 strlcat(buf, "|VI_DOOMED", sizeof(buf));
 2663         if (vp->v_iflag & VI_FREE)
 2664                 strlcat(buf, "|VI_FREE", sizeof(buf));
 2665         if (vp->v_iflag & VI_OBJDIRTY)
 2666                 strlcat(buf, "|VI_OBJDIRTY", sizeof(buf));
 2667         if (vp->v_iflag & VI_DOINGINACT)
 2668                 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
 2669         if (vp->v_iflag & VI_OWEINACT)
 2670                 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
 2671         flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
 2672             VI_OBJDIRTY | VI_DOINGINACT | VI_OWEINACT);
 2673         if (flags != 0) {
 2674                 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
 2675                 strlcat(buf, buf2, sizeof(buf));
 2676         }
 2677         printf("    flags (%s)\n", buf + 1);
 2678         if (mtx_owned(VI_MTX(vp)))
 2679                 printf(" VI_LOCKed");
 2680         if (vp->v_object != NULL)
 2681                 printf("    v_object %p ref %d pages %d\n",
 2682                     vp->v_object, vp->v_object->ref_count,
 2683                     vp->v_object->resident_page_count);
 2684         printf("    ");
 2685         lockmgr_printinfo(vp->v_vnlock);
 2686         printf("\n");
 2687         if (vp->v_data != NULL)
 2688                 VOP_PRINT(vp);
 2689 }
 2690 
 2691 #ifdef DDB
 2692 /*
 2693  * List all of the locked vnodes in the system.
 2694  * Called when debugging the kernel.
 2695  */
 2696 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
 2697 {
 2698         struct mount *mp, *nmp;
 2699         struct vnode *vp;
 2700 
 2701         /*
 2702          * Note: because this is DDB, we can't obey the locking semantics
 2703          * for these structures, which means we could catch an inconsistent
 2704          * state and dereference a nasty pointer.  Not much to be done
 2705          * about that.
 2706          */
 2707         db_printf("Locked vnodes\n");
 2708         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
 2709                 nmp = TAILQ_NEXT(mp, mnt_list);
 2710                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
 2711                         if (vp->v_type != VMARKER && VOP_ISLOCKED(vp, NULL))
 2712                                 vprint("", vp);
 2713                 }
 2714                 nmp = TAILQ_NEXT(mp, mnt_list);
 2715         }
 2716 }
 2717 
 2718 /*
 2719  * Show details about the given vnode.
 2720  */
 2721 DB_SHOW_COMMAND(vnode, db_show_vnode)
 2722 {
 2723         struct vnode *vp;
 2724 
 2725         if (!have_addr)
 2726                 return;
 2727         vp = (struct vnode *)addr;
 2728         vn_printf(vp, "vnode ");
 2729 }
 2730 
 2731 /*
 2732  * Show details about the given mount point.
 2733  */
 2734 DB_SHOW_COMMAND(mount, db_show_mount)
 2735 {
 2736         struct mount *mp;
 2737         struct statfs *sp;
 2738         struct vnode *vp;
 2739         char buf[512];
 2740         u_int flags;
 2741 
 2742         if (!have_addr) {
 2743                 /* No address given, print short info about all mount points. */
 2744                 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
 2745                         db_printf("%p %s on %s (%s)\n", mp,
 2746                             mp->mnt_stat.f_mntfromname,
 2747                             mp->mnt_stat.f_mntonname,
 2748                             mp->mnt_stat.f_fstypename);
 2749                         if (db_pager_quit)
 2750                                 break;
 2751                 }
 2752                 db_printf("\nMore info: show mount <addr>\n");
 2753                 return;
 2754         }
 2755 
 2756         mp = (struct mount *)addr;
 2757         db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
 2758             mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
 2759 
 2760         buf[0] = '\0';
 2761         flags = mp->mnt_flag;
 2762 #define MNT_FLAG(flag)  do {                                            \
 2763         if (flags & (flag)) {                                           \
 2764                 if (buf[0] != '\0')                                     \
 2765                         strlcat(buf, ", ", sizeof(buf));                \
 2766                 strlcat(buf, (#flag) + 4, sizeof(buf));                 \
 2767                 flags &= ~(flag);                                       \
 2768         }                                                               \
 2769 } while (0)
 2770         MNT_FLAG(MNT_RDONLY);
 2771         MNT_FLAG(MNT_SYNCHRONOUS);
 2772         MNT_FLAG(MNT_NOEXEC);
 2773         MNT_FLAG(MNT_NOSUID);
 2774         MNT_FLAG(MNT_UNION);
 2775         MNT_FLAG(MNT_ASYNC);
 2776         MNT_FLAG(MNT_SUIDDIR);
 2777         MNT_FLAG(MNT_SOFTDEP);
 2778         MNT_FLAG(MNT_NOSYMFOLLOW);
 2779         MNT_FLAG(MNT_GJOURNAL);
 2780         MNT_FLAG(MNT_MULTILABEL);
 2781         MNT_FLAG(MNT_ACLS);
 2782         MNT_FLAG(MNT_NOATIME);
 2783         MNT_FLAG(MNT_NOCLUSTERR);
 2784         MNT_FLAG(MNT_NOCLUSTERW);
 2785         MNT_FLAG(MNT_EXRDONLY);
 2786         MNT_FLAG(MNT_EXPORTED);
 2787         MNT_FLAG(MNT_DEFEXPORTED);
 2788         MNT_FLAG(MNT_EXPORTANON);
 2789         MNT_FLAG(MNT_EXKERB);
 2790         MNT_FLAG(MNT_EXPUBLIC);
 2791         MNT_FLAG(MNT_LOCAL);
 2792         MNT_FLAG(MNT_QUOTA);
 2793         MNT_FLAG(MNT_ROOTFS);
 2794         MNT_FLAG(MNT_USER);
 2795         MNT_FLAG(MNT_IGNORE);
 2796         MNT_FLAG(MNT_UPDATE);
 2797         MNT_FLAG(MNT_DELEXPORT);
 2798         MNT_FLAG(MNT_RELOAD);
 2799         MNT_FLAG(MNT_FORCE);
 2800         MNT_FLAG(MNT_SNAPSHOT);
 2801         MNT_FLAG(MNT_BYFSID);
 2802 #undef MNT_FLAG
 2803         if (flags != 0) {
 2804                 if (buf[0] != '\0')
 2805                         strlcat(buf, ", ", sizeof(buf));
 2806                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
 2807                     "0x%08x", flags);
 2808         }
 2809         db_printf("    mnt_flag = %s\n", buf);
 2810 
 2811         buf[0] = '\0';
 2812         flags = mp->mnt_kern_flag;
 2813 #define MNT_KERN_FLAG(flag)     do {                                    \
 2814         if (flags & (flag)) {                                           \
 2815                 if (buf[0] != '\0')                                     \
 2816                         strlcat(buf, ", ", sizeof(buf));                \
 2817                 strlcat(buf, (#flag) + 5, sizeof(buf));                 \
 2818                 flags &= ~(flag);                                       \
 2819         }                                                               \
 2820 } while (0)
 2821         MNT_KERN_FLAG(MNTK_UNMOUNTF);
 2822         MNT_KERN_FLAG(MNTK_ASYNC);
 2823         MNT_KERN_FLAG(MNTK_SOFTDEP);
 2824         MNT_KERN_FLAG(MNTK_NOINSMNTQ);
 2825         MNT_KERN_FLAG(MNTK_UNMOUNT);
 2826         MNT_KERN_FLAG(MNTK_MWAIT);
 2827         MNT_KERN_FLAG(MNTK_SUSPEND);
 2828         MNT_KERN_FLAG(MNTK_SUSPEND2);
 2829         MNT_KERN_FLAG(MNTK_SUSPENDED);
 2830         MNT_KERN_FLAG(MNTK_MPSAFE);
 2831         MNT_KERN_FLAG(MNTK_NOKNOTE);
 2832         MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
 2833 #undef MNT_KERN_FLAG
 2834         if (flags != 0) {
 2835                 if (buf[0] != '\0')
 2836                         strlcat(buf, ", ", sizeof(buf));
 2837                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
 2838                     "0x%08x", flags);
 2839         }
 2840         db_printf("    mnt_kern_flag = %s\n", buf);
 2841 
 2842         sp = &mp->mnt_stat;
 2843         db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
 2844             "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
 2845             "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
 2846             "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
 2847             (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
 2848             (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
 2849             (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
 2850             (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
 2851             (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
 2852             (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
 2853             (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
 2854             (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
 2855 
 2856         db_printf("    mnt_cred = { uid=%u ruid=%u",
 2857             (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
 2858         if (mp->mnt_cred->cr_prison != NULL)
 2859                 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
 2860         db_printf(" }\n");
 2861         db_printf("    mnt_ref = %d\n", mp->mnt_ref);
 2862         db_printf("    mnt_gen = %d\n", mp->mnt_gen);
 2863         db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
 2864         db_printf("    mnt_writeopcount = %d\n", mp->mnt_writeopcount);
 2865         db_printf("    mnt_noasync = %u\n", mp->mnt_noasync);
 2866         db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
 2867         db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
 2868         db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
 2869         db_printf("    mnt_markercnt = %d\n", mp->mnt_markercnt);
 2870         db_printf("    mnt_holdcnt = %d\n", mp->mnt_holdcnt);
 2871         db_printf("    mnt_holdcntwaiters = %d\n", mp->mnt_holdcntwaiters);
 2872         db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
 2873         db_printf("    mnt_secondary_accwrites = %d\n",
 2874             mp->mnt_secondary_accwrites);
 2875         db_printf("    mnt_gjprovider = %s\n",
 2876             mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
 2877         db_printf("\n");
 2878 
 2879         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
 2880                 if (vp->v_type != VMARKER) {
 2881                         vn_printf(vp, "vnode ");
 2882                         if (db_pager_quit)
 2883                                 break;
 2884                 }
 2885         }
 2886 }
 2887 #endif  /* DDB */
 2888 
 2889 /*
 2890  * Fill in a struct xvfsconf based on a struct vfsconf.
 2891  */
 2892 static void
 2893 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
 2894 {
 2895 
 2896         strcpy(xvfsp->vfc_name, vfsp->vfc_name);
 2897         xvfsp->vfc_typenum = vfsp->vfc_typenum;
 2898         xvfsp->vfc_refcount = vfsp->vfc_refcount;
 2899         xvfsp->vfc_flags = vfsp->vfc_flags;
 2900         /*
 2901          * These are unused in userland, we keep them
 2902          * to not break binary compatibility.
 2903          */
 2904         xvfsp->vfc_vfsops = NULL;
 2905         xvfsp->vfc_next = NULL;
 2906 }
 2907 
 2908 /*
 2909  * Top level filesystem related information gathering.
 2910  */
 2911 static int
 2912 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
 2913 {
 2914         struct vfsconf *vfsp;
 2915         struct xvfsconf xvfsp;
 2916         int error;
 2917 
 2918         error = 0;
 2919         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
 2920                 bzero(&xvfsp, sizeof(xvfsp));
 2921                 vfsconf2x(vfsp, &xvfsp);
 2922                 error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
 2923                 if (error)
 2924                         break;
 2925         }
 2926         return (error);
 2927 }
 2928 
 2929 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLFLAG_RD, NULL, 0, sysctl_vfs_conflist,
 2930     "S,xvfsconf", "List of all configured filesystems");
 2931 
 2932 #ifndef BURN_BRIDGES
 2933 static int      sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
 2934 
 2935 static int
 2936 vfs_sysctl(SYSCTL_HANDLER_ARGS)
 2937 {
 2938         int *name = (int *)arg1 - 1;    /* XXX */
 2939         u_int namelen = arg2 + 1;       /* XXX */
 2940         struct vfsconf *vfsp;
 2941         struct xvfsconf xvfsp;
 2942 
 2943         printf("WARNING: userland calling deprecated sysctl, "
 2944             "please rebuild world\n");
 2945 
 2946 #if 1 || defined(COMPAT_PRELITE2)
 2947         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
 2948         if (namelen == 1)
 2949                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
 2950 #endif
 2951 
 2952         switch (name[1]) {
 2953         case VFS_MAXTYPENUM:
 2954                 if (namelen != 2)
 2955                         return (ENOTDIR);
 2956                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
 2957         case VFS_CONF:
 2958                 if (namelen != 3)
 2959                         return (ENOTDIR);       /* overloaded */
 2960                 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
 2961                         if (vfsp->vfc_typenum == name[2])
 2962                                 break;
 2963                 if (vfsp == NULL)
 2964                         return (EOPNOTSUPP);
 2965                 bzero(&xvfsp, sizeof(xvfsp));
 2966                 vfsconf2x(vfsp, &xvfsp);
 2967                 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
 2968         }
 2969         return (EOPNOTSUPP);
 2970 }
 2971 
 2972 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
 2973         vfs_sysctl, "Generic filesystem");
 2974 
 2975 #if 1 || defined(COMPAT_PRELITE2)
 2976 
 2977 static int
 2978 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
 2979 {
 2980         int error;
 2981         struct vfsconf *vfsp;
 2982         struct ovfsconf ovfs;
 2983 
 2984         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
 2985                 bzero(&ovfs, sizeof(ovfs));
 2986                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
 2987                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
 2988                 ovfs.vfc_index = vfsp->vfc_typenum;
 2989                 ovfs.vfc_refcount = vfsp->vfc_refcount;
 2990                 ovfs.vfc_flags = vfsp->vfc_flags;
 2991                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
 2992                 if (error)
 2993                         return error;
 2994         }
 2995         return 0;
 2996 }
 2997 
 2998 #endif /* 1 || COMPAT_PRELITE2 */
 2999 #endif /* !BURN_BRIDGES */
 3000 
 3001 #define KINFO_VNODESLOP         10
 3002 #ifdef notyet
 3003 /*
 3004  * Dump vnode list (via sysctl).
 3005  */
 3006 /* ARGSUSED */
 3007 static int
 3008 sysctl_vnode(SYSCTL_HANDLER_ARGS)
 3009 {
 3010         struct xvnode *xvn;
 3011         struct thread *td = req->td;
 3012         struct mount *mp;
 3013         struct vnode *vp;
 3014         int error, len, n;
 3015 
 3016         /*
 3017          * Stale numvnodes access is not fatal here.
 3018          */
 3019         req->lock = 0;
 3020         len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
 3021         if (!req->oldptr)
 3022                 /* Make an estimate */
 3023                 return (SYSCTL_OUT(req, 0, len));
 3024 
 3025         error = sysctl_wire_old_buffer(req, 0);
 3026         if (error != 0)
 3027                 return (error);
 3028         xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
 3029         n = 0;
 3030         mtx_lock(&mountlist_mtx);
 3031         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
 3032                 if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td))
 3033                         continue;
 3034                 MNT_ILOCK(mp);
 3035                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
 3036                         if (n == len)
 3037                                 break;
 3038                         vref(vp);
 3039                         xvn[n].xv_size = sizeof *xvn;
 3040                         xvn[n].xv_vnode = vp;
 3041                         xvn[n].xv_id = 0;       /* XXX compat */
 3042 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
 3043                         XV_COPY(usecount);
 3044                         XV_COPY(writecount);
 3045                         XV_COPY(holdcnt);
 3046                         XV_COPY(mount);
 3047                         XV_COPY(numoutput);
 3048                         XV_COPY(type);
 3049 #undef XV_COPY
 3050                         xvn[n].xv_flag = vp->v_vflag;
 3051 
 3052                         switch (vp->v_type) {
 3053                         case VREG:
 3054                         case VDIR:
 3055                         case VLNK:
 3056                                 break;
 3057                         case VBLK:
 3058                         case VCHR:
 3059                                 if (vp->v_rdev == NULL) {
 3060                                         vrele(vp);
 3061                                         continue;
 3062                                 }
 3063                                 xvn[n].xv_dev = dev2udev(vp->v_rdev);
 3064                                 break;
 3065                         case VSOCK:
 3066                                 xvn[n].xv_socket = vp->v_socket;
 3067                                 break;
 3068                         case VFIFO:
 3069                                 xvn[n].xv_fifo = vp->v_fifoinfo;
 3070                                 break;
 3071                         case VNON:
 3072                         case VBAD:
 3073                         default:
 3074                                 /* shouldn't happen? */
 3075                                 vrele(vp);
 3076                                 continue;
 3077                         }
 3078                         vrele(vp);
 3079                         ++n;
 3080                 }
 3081                 MNT_IUNLOCK(mp);
 3082                 mtx_lock(&mountlist_mtx);
 3083                 vfs_unbusy(mp, td);
 3084                 if (n == len)
 3085                         break;
 3086         }
 3087         mtx_unlock(&mountlist_mtx);
 3088 
 3089         error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
 3090         free(xvn, M_TEMP);
 3091         return (error);
 3092 }
 3093 
 3094 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
 3095         0, 0, sysctl_vnode, "S,xvnode", "");
 3096 #endif
 3097 
 3098 /*
 3099  * Unmount all filesystems. The list is traversed in reverse order
 3100  * of mounting to avoid dependencies.
 3101  */
 3102 void
 3103 vfs_unmountall(void)
 3104 {
 3105         struct mount *mp;
 3106         struct thread *td;
 3107         int error;
 3108 
 3109         KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
 3110         td = curthread;
 3111         /*
 3112          * Since this only runs when rebooting, it is not interlocked.
 3113          */
 3114         while(!TAILQ_EMPTY(&mountlist)) {
 3115                 mp = TAILQ_LAST(&mountlist, mntlist);
 3116                 error = dounmount(mp, MNT_FORCE, td);
 3117                 if (error) {
 3118                         TAILQ_REMOVE(&mountlist, mp, mnt_list);
 3119                         /*
 3120                          * XXX: Due to the way in which we mount the root
 3121                          * file system off of devfs, devfs will generate a
 3122                          * "busy" warning when we try to unmount it before
 3123                          * the root.  Don't print a warning as a result in
 3124                          * order to avoid false positive errors that may
 3125                          * cause needless upset.
 3126                          */
 3127                         if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
 3128                                 printf("unmount of %s failed (",
 3129                                     mp->mnt_stat.f_mntonname);
 3130                                 if (error == EBUSY)
 3131                                         printf("BUSY)\n");
 3132                                 else
 3133                                         printf("%d)\n", error);
 3134                         }
 3135                 } else {
 3136                         /* The unmount has removed mp from the mountlist */
 3137                 }
 3138         }
 3139 }
 3140 
 3141 /*
 3142  * perform msync on all vnodes under a mount point
 3143  * the mount point must be locked.
 3144  */
 3145 void
 3146 vfs_msync(struct mount *mp, int flags)
 3147 {
 3148         struct vnode *vp, *mvp;
 3149         struct vm_object *obj;
 3150 
 3151         MNT_ILOCK(mp);
 3152         MNT_VNODE_FOREACH(vp, mp, mvp) {
 3153                 VI_LOCK(vp);
 3154                 if ((vp->v_iflag & VI_OBJDIRTY) &&
 3155                     (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
 3156                         MNT_IUNLOCK(mp);
 3157                         if (!vget(vp,
 3158                             LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
 3159                             curthread)) {
 3160                                 if (vp->v_vflag & VV_NOSYNC) {  /* unlinked */
 3161                                         vput(vp);
 3162                                         MNT_ILOCK(mp);
 3163                                         continue;
 3164                                 }
 3165 
 3166                                 obj = vp->v_object;
 3167                                 if (obj != NULL) {
 3168                                         VM_OBJECT_LOCK(obj);
 3169                                         vm_object_page_clean(obj, 0, 0,
 3170                                             flags == MNT_WAIT ?
 3171                                             OBJPC_SYNC : OBJPC_NOSYNC);
 3172                                         VM_OBJECT_UNLOCK(obj);
 3173                                 }
 3174                                 vput(vp);
 3175                         }
 3176                         MNT_ILOCK(mp);
 3177                 } else
 3178                         VI_UNLOCK(vp);
 3179         }
 3180         MNT_IUNLOCK(mp);
 3181 }
 3182 
 3183 /*
 3184  * Mark a vnode as free, putting it up for recycling.
 3185  */
 3186 static void
 3187 vfree(struct vnode *vp)
 3188 {
 3189 
 3190         CTR1(KTR_VFS, "vfree vp %p", vp);
 3191         ASSERT_VI_LOCKED(vp, "vfree");
 3192         mtx_lock(&vnode_free_list_mtx);
 3193         VNASSERT(vp->v_op != NULL, vp, ("vfree: vnode already reclaimed."));
 3194         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp, ("vnode already free"));
 3195         VNASSERT(VSHOULDFREE(vp), vp, ("vfree: freeing when we shouldn't"));
 3196         VNASSERT((vp->v_iflag & VI_DOOMED) == 0, vp,
 3197             ("vfree: Freeing doomed vnode"));
 3198         if (vp->v_iflag & VI_AGE) {
 3199                 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
 3200         } else {
 3201                 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
 3202         }
 3203         freevnodes++;
 3204         vp->v_iflag &= ~VI_AGE;
 3205         vp->v_iflag |= VI_FREE;
 3206         mtx_unlock(&vnode_free_list_mtx);
 3207 }
 3208 
 3209 /*
 3210  * Opposite of vfree() - mark a vnode as in use.
 3211  */
 3212 static void
 3213 vbusy(struct vnode *vp)
 3214 {
 3215         CTR1(KTR_VFS, "vbusy vp %p", vp);
 3216         ASSERT_VI_LOCKED(vp, "vbusy");
 3217         VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
 3218         VNASSERT(vp->v_op != NULL, vp, ("vbusy: vnode already reclaimed."));
 3219 
 3220         mtx_lock(&vnode_free_list_mtx);
 3221         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
 3222         freevnodes--;
 3223         vp->v_iflag &= ~(VI_FREE|VI_AGE);
 3224         mtx_unlock(&vnode_free_list_mtx);
 3225 }
 3226 
 3227 static void
 3228 destroy_vpollinfo(struct vpollinfo *vi)
 3229 {
 3230         knlist_destroy(&vi->vpi_selinfo.si_note);
 3231         mtx_destroy(&vi->vpi_lock);
 3232         uma_zfree(vnodepoll_zone, vi);
 3233 }
 3234 
 3235 /*
 3236  * Initalize per-vnode helper structure to hold poll-related state.
 3237  */
 3238 void
 3239 v_addpollinfo(struct vnode *vp)
 3240 {
 3241         struct vpollinfo *vi;
 3242 
 3243         if (vp->v_pollinfo != NULL)
 3244                 return;
 3245         vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
 3246         mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
 3247         knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
 3248             vfs_knlunlock, NULL);
 3249         VI_LOCK(vp);
 3250         if (vp->v_pollinfo != NULL) {
 3251                 VI_UNLOCK(vp);
 3252                 destroy_vpollinfo(vi);
 3253                 return;
 3254         }
 3255         vp->v_pollinfo = vi;
 3256         VI_UNLOCK(vp);
 3257 }
 3258 
 3259 /*
 3260  * Record a process's interest in events which might happen to
 3261  * a vnode.  Because poll uses the historic select-style interface
 3262  * internally, this routine serves as both the ``check for any
 3263  * pending events'' and the ``record my interest in future events''
 3264  * functions.  (These are done together, while the lock is held,
 3265  * to avoid race conditions.)
 3266  */
 3267 int
 3268 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
 3269 {
 3270 
 3271         v_addpollinfo(vp);
 3272         mtx_lock(&vp->v_pollinfo->vpi_lock);
 3273         if (vp->v_pollinfo->vpi_revents & events) {
 3274                 /*
 3275                  * This leaves events we are not interested
 3276                  * in available for the other process which
 3277                  * which presumably had requested them
 3278                  * (otherwise they would never have been
 3279                  * recorded).
 3280                  */
 3281                 events &= vp->v_pollinfo->vpi_revents;
 3282                 vp->v_pollinfo->vpi_revents &= ~events;
 3283 
 3284                 mtx_unlock(&vp->v_pollinfo->vpi_lock);
 3285                 return events;
 3286         }
 3287         vp->v_pollinfo->vpi_events |= events;
 3288         selrecord(td, &vp->v_pollinfo->vpi_selinfo);
 3289         mtx_unlock(&vp->v_pollinfo->vpi_lock);
 3290         return 0;
 3291 }
 3292 
 3293 /*
 3294  * Routine to create and manage a filesystem syncer vnode.
 3295  */
 3296 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
 3297 static int      sync_fsync(struct  vop_fsync_args *);
 3298 static int      sync_inactive(struct  vop_inactive_args *);
 3299 static int      sync_reclaim(struct  vop_reclaim_args *);
 3300 
 3301 static struct vop_vector sync_vnodeops = {
 3302         .vop_bypass =   VOP_EOPNOTSUPP,
 3303         .vop_close =    sync_close,             /* close */
 3304         .vop_fsync =    sync_fsync,             /* fsync */
 3305         .vop_inactive = sync_inactive,  /* inactive */
 3306         .vop_reclaim =  sync_reclaim,   /* reclaim */
 3307         .vop_lock1 =    vop_stdlock,    /* lock */
 3308         .vop_unlock =   vop_stdunlock,  /* unlock */
 3309         .vop_islocked = vop_stdislocked,        /* islocked */
 3310 };
 3311 
 3312 /*
 3313  * Create a new filesystem syncer vnode for the specified mount point.
 3314  */
 3315 int
 3316 vfs_allocate_syncvnode(struct mount *mp)
 3317 {
 3318         struct vnode *vp;
 3319         static long start, incr, next;
 3320         int error;
 3321 
 3322         /* Allocate a new vnode */
 3323         if ((error = getnewvnode("syncer", mp, &sync_vnodeops, &vp)) != 0) {
 3324                 mp->mnt_syncer = NULL;
 3325                 return (error);
 3326         }
 3327         vp->v_type = VNON;
 3328         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
 3329         vp->v_vflag |= VV_FORCEINSMQ;
 3330         error = insmntque(vp, mp);
 3331         if (error != 0)
 3332                 panic("vfs_allocate_syncvnode: insmntque failed");
 3333         vp->v_vflag &= ~VV_FORCEINSMQ;
 3334         VOP_UNLOCK(vp, 0, curthread);
 3335         /*
 3336          * Place the vnode onto the syncer worklist. We attempt to
 3337          * scatter them about on the list so that they will go off
 3338          * at evenly distributed times even if all the filesystems
 3339          * are mounted at once.
 3340          */
 3341         next += incr;
 3342         if (next == 0 || next > syncer_maxdelay) {
 3343                 start /= 2;
 3344                 incr /= 2;
 3345                 if (start == 0) {
 3346                         start = syncer_maxdelay / 2;
 3347                         incr = syncer_maxdelay;
 3348                 }
 3349                 next = start;
 3350         }
 3351         VI_LOCK(vp);
 3352         vn_syncer_add_to_worklist(&vp->v_bufobj,
 3353             syncdelay > 0 ? next % syncdelay : 0);
 3354         /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
 3355         mtx_lock(&sync_mtx);
 3356         sync_vnode_count++;
 3357         mtx_unlock(&sync_mtx);
 3358         VI_UNLOCK(vp);
 3359         mp->mnt_syncer = vp;
 3360         return (0);
 3361 }
 3362 
 3363 /*
 3364  * Do a lazy sync of the filesystem.
 3365  */
 3366 static int
 3367 sync_fsync(struct vop_fsync_args *ap)
 3368 {
 3369         struct vnode *syncvp = ap->a_vp;
 3370         struct mount *mp = syncvp->v_mount;
 3371         struct thread *td = ap->a_td;
 3372         int error;
 3373         struct bufobj *bo;
 3374 
 3375         /*
 3376          * We only need to do something if this is a lazy evaluation.
 3377          */
 3378         if (ap->a_waitfor != MNT_LAZY)
 3379                 return (0);
 3380 
 3381         /*
 3382          * Move ourselves to the back of the sync list.
 3383          */
 3384         bo = &syncvp->v_bufobj;
 3385         BO_LOCK(bo);
 3386         vn_syncer_add_to_worklist(bo, syncdelay);
 3387         BO_UNLOCK(bo);
 3388 
 3389         /*
 3390          * Walk the list of vnodes pushing all that are dirty and
 3391          * not already on the sync list.
 3392          */
 3393         mtx_lock(&mountlist_mtx);
 3394         if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_mtx, td) != 0) {
 3395                 mtx_unlock(&mountlist_mtx);
 3396                 return (0);
 3397         }
 3398         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
 3399                 vfs_unbusy(mp, td);
 3400                 return (0);
 3401         }
 3402         MNT_ILOCK(mp);
 3403         mp->mnt_noasync++;
 3404         mp->mnt_kern_flag &= ~MNTK_ASYNC;
 3405         MNT_IUNLOCK(mp);
 3406         vfs_msync(mp, MNT_NOWAIT);
 3407         error = VFS_SYNC(mp, MNT_LAZY, td);
 3408         MNT_ILOCK(mp);
 3409         mp->mnt_noasync--;
 3410         if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
 3411                 mp->mnt_kern_flag |= MNTK_ASYNC;
 3412         MNT_IUNLOCK(mp);
 3413         vn_finished_write(mp);
 3414         vfs_unbusy(mp, td);
 3415         return (error);
 3416 }
 3417 
 3418 /*
 3419  * The syncer vnode is no referenced.
 3420  */
 3421 static int
 3422 sync_inactive(struct vop_inactive_args *ap)
 3423 {
 3424 
 3425         vgone(ap->a_vp);
 3426         return (0);
 3427 }
 3428 
 3429 /*
 3430  * The syncer vnode is no longer needed and is being decommissioned.
 3431  *
 3432  * Modifications to the worklist must be protected by sync_mtx.
 3433  */
 3434 static int
 3435 sync_reclaim(struct vop_reclaim_args *ap)
 3436 {
 3437         struct vnode *vp = ap->a_vp;
 3438         struct bufobj *bo;
 3439 
 3440         VI_LOCK(vp);
 3441         bo = &vp->v_bufobj;
 3442         vp->v_mount->mnt_syncer = NULL;
 3443         if (bo->bo_flag & BO_ONWORKLST) {
 3444                 mtx_lock(&sync_mtx);
 3445                 LIST_REMOVE(bo, bo_synclist);
 3446                 syncer_worklist_len--;
 3447                 sync_vnode_count--;
 3448                 mtx_unlock(&sync_mtx);
 3449                 bo->bo_flag &= ~BO_ONWORKLST;
 3450         }
 3451         VI_UNLOCK(vp);
 3452 
 3453         return (0);
 3454 }
 3455 
 3456 /*
 3457  * Check if vnode represents a disk device
 3458  */
 3459 int
 3460 vn_isdisk(struct vnode *vp, int *errp)
 3461 {
 3462         int error;
 3463 
 3464         error = 0;
 3465         dev_lock();
 3466         if (vp->v_type != VCHR)
 3467                 error = ENOTBLK;
 3468         else if (vp->v_rdev == NULL)
 3469                 error = ENXIO;
 3470         else if (vp->v_rdev->si_devsw == NULL)
 3471                 error = ENXIO;
 3472         else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
 3473                 error = ENOTBLK;
 3474         dev_unlock();
 3475         if (errp != NULL)
 3476                 *errp = error;
 3477         return (error == 0);
 3478 }
 3479 
 3480 /*
 3481  * Common filesystem object access control check routine.  Accepts a
 3482  * vnode's type, "mode", uid and gid, requested access mode, credentials,
 3483  * and optional call-by-reference privused argument allowing vaccess()
 3484  * to indicate to the caller whether privilege was used to satisfy the
 3485  * request (obsoleted).  Returns 0 on success, or an errno on failure.
 3486  *
 3487  * The ifdef'd CAPABILITIES version is here for reference, but is not
 3488  * actually used.
 3489  */
 3490 int
 3491 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
 3492     mode_t acc_mode, struct ucred *cred, int *privused)
 3493 {
 3494         mode_t dac_granted;
 3495         mode_t priv_granted;
 3496 
 3497         /*
 3498          * Look for a normal, non-privileged way to access the file/directory
 3499          * as requested.  If it exists, go with that.
 3500          */
 3501 
 3502         if (privused != NULL)
 3503                 *privused = 0;
 3504 
 3505         dac_granted = 0;
 3506 
 3507         /* Check the owner. */
 3508         if (cred->cr_uid == file_uid) {
 3509                 dac_granted |= VADMIN;
 3510                 if (file_mode & S_IXUSR)
 3511                         dac_granted |= VEXEC;
 3512                 if (file_mode & S_IRUSR)
 3513                         dac_granted |= VREAD;
 3514                 if (file_mode & S_IWUSR)
 3515                         dac_granted |= (VWRITE | VAPPEND);
 3516 
 3517                 if ((acc_mode & dac_granted) == acc_mode)
 3518                         return (0);
 3519 
 3520                 goto privcheck;
 3521         }
 3522 
 3523         /* Otherwise, check the groups (first match) */
 3524         if (groupmember(file_gid, cred)) {
 3525                 if (file_mode & S_IXGRP)
 3526                         dac_granted |= VEXEC;
 3527                 if (file_mode & S_IRGRP)
 3528                         dac_granted |= VREAD;
 3529                 if (file_mode & S_IWGRP)
 3530                         dac_granted |= (VWRITE | VAPPEND);
 3531 
 3532                 if ((acc_mode & dac_granted) == acc_mode)
 3533                         return (0);
 3534 
 3535                 goto privcheck;
 3536         }
 3537 
 3538         /* Otherwise, check everyone else. */
 3539         if (file_mode & S_IXOTH)
 3540                 dac_granted |= VEXEC;
 3541         if (file_mode & S_IROTH)
 3542                 dac_granted |= VREAD;
 3543         if (file_mode & S_IWOTH)
 3544                 dac_granted |= (VWRITE | VAPPEND);
 3545         if ((acc_mode & dac_granted) == acc_mode)
 3546                 return (0);
 3547 
 3548 privcheck:
 3549         /*
 3550          * Build a privilege mask to determine if the set of privileges
 3551          * satisfies the requirements when combined with the granted mask
 3552          * from above.  For each privilege, if the privilege is required,
 3553          * bitwise or the request type onto the priv_granted mask.
 3554          */
 3555         priv_granted = 0;
 3556 
 3557         if (type == VDIR) {
 3558                 /*
 3559                  * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
 3560                  * requests, instead of PRIV_VFS_EXEC.
 3561                  */
 3562                 if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
 3563                     !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
 3564                         priv_granted |= VEXEC;
 3565         } else {
 3566                 if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
 3567                     !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
 3568                         priv_granted |= VEXEC;
 3569         }
 3570 
 3571         if ((acc_mode & VREAD) && ((dac_granted & VREAD) == 0) &&
 3572             !priv_check_cred(cred, PRIV_VFS_READ, 0))
 3573                 priv_granted |= VREAD;
 3574 
 3575         if ((acc_mode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
 3576             !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
 3577                 priv_granted |= (VWRITE | VAPPEND);
 3578 
 3579         if ((acc_mode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
 3580             !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
 3581                 priv_granted |= VADMIN;
 3582 
 3583         if ((acc_mode & (priv_granted | dac_granted)) == acc_mode) {
 3584                 /* XXX audit: privilege used */
 3585                 if (privused != NULL)
 3586                         *privused = 1;
 3587                 return (0);
 3588         }
 3589 
 3590         return ((acc_mode & VADMIN) ? EPERM : EACCES);
 3591 }
 3592 
 3593 /*
 3594  * Credential check based on process requesting service, and per-attribute
 3595  * permissions.
 3596  */
 3597 int
 3598 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
 3599     struct thread *td, int access)
 3600 {
 3601 
 3602         /*
 3603          * Kernel-invoked always succeeds.
 3604          */
 3605         if (cred == NOCRED)
 3606                 return (0);
 3607 
 3608         /*
 3609          * Do not allow privileged processes in jail to directly manipulate
 3610          * system attributes.
 3611          */
 3612         switch (attrnamespace) {
 3613         case EXTATTR_NAMESPACE_SYSTEM:
 3614                 /* Potentially should be: return (EPERM); */
 3615                 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
 3616         case EXTATTR_NAMESPACE_USER:
 3617                 return (VOP_ACCESS(vp, access, cred, td));
 3618         default:
 3619                 return (EPERM);
 3620         }
 3621 }
 3622 
 3623 #ifdef DEBUG_VFS_LOCKS
 3624 /*
 3625  * This only exists to supress warnings from unlocked specfs accesses.  It is
 3626  * no longer ok to have an unlocked VFS.
 3627  */
 3628 #define IGNORE_LOCK(vp) ((vp)->v_type == VCHR || (vp)->v_type == VBAD)
 3629 
 3630 int vfs_badlock_ddb = 1;        /* Drop into debugger on violation. */
 3631 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0, "");
 3632 
 3633 int vfs_badlock_mutex = 1;      /* Check for interlock across VOPs. */
 3634 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex, 0, "");
 3635 
 3636 int vfs_badlock_print = 1;      /* Print lock violations. */
 3637 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print, 0, "");
 3638 
 3639 #ifdef KDB
 3640 int vfs_badlock_backtrace = 1;  /* Print backtrace at lock violations. */
 3641 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW, &vfs_badlock_backtrace, 0, "");
 3642 #endif
 3643 
 3644 static void
 3645 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
 3646 {
 3647 
 3648 #ifdef KDB
 3649         if (vfs_badlock_backtrace)
 3650                 kdb_backtrace();
 3651 #endif
 3652         if (vfs_badlock_print)
 3653                 printf("%s: %p %s\n", str, (void *)vp, msg);
 3654         if (vfs_badlock_ddb)
 3655                 kdb_enter_why(KDB_WHY_VFSLOCK, "lock violation");
 3656 }
 3657 
 3658 void
 3659 assert_vi_locked(struct vnode *vp, const char *str)
 3660 {
 3661 
 3662         if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
 3663                 vfs_badlock("interlock is not locked but should be", str, vp);
 3664 }
 3665 
 3666 void
 3667 assert_vi_unlocked(struct vnode *vp, const char *str)
 3668 {
 3669 
 3670         if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
 3671                 vfs_badlock("interlock is locked but should not be", str, vp);
 3672 }
 3673 
 3674 void
 3675 assert_vop_locked(struct vnode *vp, const char *str)
 3676 {
 3677 
 3678         if (vp && !IGNORE_LOCK(vp) && VOP_ISLOCKED(vp, NULL) == 0)
 3679                 vfs_badlock("is not locked but should be", str, vp);
 3680 }
 3681 
 3682 void
 3683 assert_vop_unlocked(struct vnode *vp, const char *str)
 3684 {
 3685 
 3686         if (vp && !IGNORE_LOCK(vp) &&
 3687             VOP_ISLOCKED(vp, curthread) == LK_EXCLUSIVE)
 3688                 vfs_badlock("is locked but should not be", str, vp);
 3689 }
 3690 
 3691 void
 3692 assert_vop_elocked(struct vnode *vp, const char *str)
 3693 {
 3694 
 3695         if (vp && !IGNORE_LOCK(vp) &&
 3696             VOP_ISLOCKED(vp, curthread) != LK_EXCLUSIVE)
 3697                 vfs_badlock("is not exclusive locked but should be", str, vp);
 3698 }
 3699 
 3700 #if 0
 3701 void
 3702 assert_vop_elocked_other(struct vnode *vp, const char *str)
 3703 {
 3704 
 3705         if (vp && !IGNORE_LOCK(vp) &&
 3706             VOP_ISLOCKED(vp, curthread) != LK_EXCLOTHER)
 3707                 vfs_badlock("is not exclusive locked by another thread",
 3708                     str, vp);
 3709 }
 3710 
 3711 void
 3712 assert_vop_slocked(struct vnode *vp, const char *str)
 3713 {
 3714 
 3715         if (vp && !IGNORE_LOCK(vp) &&
 3716             VOP_ISLOCKED(vp, curthread) != LK_SHARED)
 3717                 vfs_badlock("is not locked shared but should be", str, vp);
 3718 }
 3719 #endif /* 0 */
 3720 #endif /* DEBUG_VFS_LOCKS */
 3721 
 3722 void
 3723 vop_rename_pre(void *ap)
 3724 {
 3725         struct vop_rename_args *a = ap;
 3726 
 3727 #ifdef DEBUG_VFS_LOCKS
 3728         if (a->a_tvp)
 3729                 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
 3730         ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
 3731         ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
 3732         ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
 3733 
 3734         /* Check the source (from). */
 3735         if (a->a_tdvp != a->a_fdvp && a->a_tvp != a->a_fdvp)
 3736                 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
 3737         if (a->a_tvp != a->a_fvp)
 3738                 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
 3739 
 3740         /* Check the target. */
 3741         if (a->a_tvp)
 3742                 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
 3743         ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
 3744 #endif
 3745         if (a->a_tdvp != a->a_fdvp)
 3746                 vhold(a->a_fdvp);
 3747         if (a->a_tvp != a->a_fvp)
 3748                 vhold(a->a_fvp);
 3749         vhold(a->a_tdvp);
 3750         if (a->a_tvp)
 3751                 vhold(a->a_tvp);
 3752 }
 3753 
 3754 void
 3755 vop_strategy_pre(void *ap)
 3756 {
 3757 #ifdef DEBUG_VFS_LOCKS
 3758         struct vop_strategy_args *a;
 3759         struct buf *bp;
 3760 
 3761         a = ap;
 3762         bp = a->a_bp;
 3763 
 3764         /*
 3765          * Cluster ops lock their component buffers but not the IO container.
 3766          */
 3767         if ((bp->b_flags & B_CLUSTER) != 0)
 3768                 return;
 3769 
 3770         if (BUF_REFCNT(bp) < 1) {
 3771                 if (vfs_badlock_print)
 3772                         printf(
 3773                             "VOP_STRATEGY: bp is not locked but should be\n");
 3774                 if (vfs_badlock_ddb)
 3775                         kdb_enter_why(KDB_WHY_VFSLOCK, "lock violation");
 3776         }
 3777 #endif
 3778 }
 3779 
 3780 void
 3781 vop_lookup_pre(void *ap)
 3782 {
 3783 #ifdef DEBUG_VFS_LOCKS
 3784         struct vop_lookup_args *a;
 3785         struct vnode *dvp;
 3786 
 3787         a = ap;
 3788         dvp = a->a_dvp;
 3789         ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
 3790         ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
 3791 #endif
 3792 }
 3793 
 3794 void
 3795 vop_lookup_post(void *ap, int rc)
 3796 {
 3797 #ifdef DEBUG_VFS_LOCKS
 3798         struct vop_lookup_args *a;
 3799         struct vnode *dvp;
 3800         struct vnode *vp;
 3801 
 3802         a = ap;
 3803         dvp = a->a_dvp;
 3804         vp = *(a->a_vpp);
 3805 
 3806         ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
 3807         ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
 3808 
 3809         if (!rc)
 3810                 ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
 3811 #endif
 3812 }
 3813 
 3814 void
 3815 vop_lock_pre(void *ap)
 3816 {
 3817 #ifdef DEBUG_VFS_LOCKS
 3818         struct vop_lock1_args *a = ap;
 3819 
 3820         if ((a->a_flags & LK_INTERLOCK) == 0)
 3821                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
 3822         else
 3823                 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
 3824 #endif
 3825 }
 3826 
 3827 void
 3828 vop_lock_post(void *ap, int rc)
 3829 {
 3830 #ifdef DEBUG_VFS_LOCKS
 3831         struct vop_lock1_args *a = ap;
 3832 
 3833         ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
 3834         if (rc == 0)
 3835                 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
 3836 #endif
 3837 }
 3838 
 3839 void
 3840 vop_unlock_pre(void *ap)
 3841 {
 3842 #ifdef DEBUG_VFS_LOCKS
 3843         struct vop_unlock_args *a = ap;
 3844 
 3845         if (a->a_flags & LK_INTERLOCK)
 3846                 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
 3847         ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
 3848 #endif
 3849 }
 3850 
 3851 void
 3852 vop_unlock_post(void *ap, int rc)
 3853 {
 3854 #ifdef DEBUG_VFS_LOCKS
 3855         struct vop_unlock_args *a = ap;
 3856 
 3857         if (a->a_flags & LK_INTERLOCK)
 3858                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
 3859 #endif
 3860 }
 3861 
 3862 void
 3863 vop_create_post(void *ap, int rc)
 3864 {
 3865         struct vop_create_args *a = ap;
 3866 
 3867         if (!rc)
 3868                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 3869 }
 3870 
 3871 void
 3872 vop_link_post(void *ap, int rc)
 3873 {
 3874         struct vop_link_args *a = ap;
 3875 
 3876         if (!rc) {
 3877                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
 3878                 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
 3879         }
 3880 }
 3881 
 3882 void
 3883 vop_mkdir_post(void *ap, int rc)
 3884 {
 3885         struct vop_mkdir_args *a = ap;
 3886 
 3887         if (!rc)
 3888                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
 3889 }
 3890 
 3891 void
 3892 vop_mknod_post(void *ap, int rc)
 3893 {
 3894         struct vop_mknod_args *a = ap;
 3895 
 3896         if (!rc)
 3897                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 3898 }
 3899 
 3900 void
 3901 vop_remove_post(void *ap, int rc)
 3902 {
 3903         struct vop_remove_args *a = ap;
 3904 
 3905         if (!rc) {
 3906                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 3907                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
 3908         }
 3909 }
 3910 
 3911 void
 3912 vop_rename_post(void *ap, int rc)
 3913 {
 3914         struct vop_rename_args *a = ap;
 3915 
 3916         if (!rc) {
 3917                 VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
 3918                 VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
 3919                 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
 3920                 if (a->a_tvp)
 3921                         VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
 3922         }
 3923         if (a->a_tdvp != a->a_fdvp)
 3924                 vdrop(a->a_fdvp);
 3925         if (a->a_tvp != a->a_fvp)
 3926                 vdrop(a->a_fvp);
 3927         vdrop(a->a_tdvp);
 3928         if (a->a_tvp)
 3929                 vdrop(a->a_tvp);
 3930 }
 3931 
 3932 void
 3933 vop_rmdir_post(void *ap, int rc)
 3934 {
 3935         struct vop_rmdir_args *a = ap;
 3936 
 3937         if (!rc) {
 3938                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
 3939                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
 3940         }
 3941 }
 3942 
 3943 void
 3944 vop_setattr_post(void *ap, int rc)
 3945 {
 3946         struct vop_setattr_args *a = ap;
 3947 
 3948         if (!rc)
 3949                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
 3950 }
 3951 
 3952 void
 3953 vop_symlink_post(void *ap, int rc)
 3954 {
 3955         struct vop_symlink_args *a = ap;
 3956 
 3957         if (!rc)
 3958                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
 3959 }
 3960 
 3961 static struct knlist fs_knlist;
 3962 
 3963 static void
 3964 vfs_event_init(void *arg)
 3965 {
 3966         knlist_init_mtx(&fs_knlist, NULL);
 3967 }
 3968 /* XXX - correct order? */
 3969 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
 3970 
 3971 void
 3972 vfs_event_signal(fsid_t *fsid, u_int32_t event, intptr_t data __unused)
 3973 {
 3974 
 3975         KNOTE_UNLOCKED(&fs_knlist, event);
 3976 }
 3977 
 3978 static int      filt_fsattach(struct knote *kn);
 3979 static void     filt_fsdetach(struct knote *kn);
 3980 static int      filt_fsevent(struct knote *kn, long hint);
 3981 
 3982 struct filterops fs_filtops =
 3983         { 0, filt_fsattach, filt_fsdetach, filt_fsevent };
 3984 
 3985 static int
 3986 filt_fsattach(struct knote *kn)
 3987 {
 3988 
 3989         kn->kn_flags |= EV_CLEAR;
 3990         knlist_add(&fs_knlist, kn, 0);
 3991         return (0);
 3992 }
 3993 
 3994 static void
 3995 filt_fsdetach(struct knote *kn)
 3996 {
 3997 
 3998         knlist_remove(&fs_knlist, kn, 0);
 3999 }
 4000 
 4001 static int
 4002 filt_fsevent(struct knote *kn, long hint)
 4003 {
 4004 
 4005         kn->kn_fflags |= hint;
 4006         return (kn->kn_fflags != 0);
 4007 }
 4008 
 4009 static int
 4010 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
 4011 {
 4012         struct vfsidctl vc;
 4013         int error;
 4014         struct mount *mp;
 4015 
 4016         error = SYSCTL_IN(req, &vc, sizeof(vc));
 4017         if (error)
 4018                 return (error);
 4019         if (vc.vc_vers != VFS_CTL_VERS1)
 4020                 return (EINVAL);
 4021         mp = vfs_getvfs(&vc.vc_fsid);
 4022         if (mp == NULL)
 4023                 return (ENOENT);
 4024         /* ensure that a specific sysctl goes to the right filesystem. */
 4025         if (strcmp(vc.vc_fstypename, "*") != 0 &&
 4026             strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
 4027                 vfs_rel(mp);
 4028                 return (EINVAL);
 4029         }
 4030         VCTLTOREQ(&vc, req);
 4031         error = VFS_SYSCTL(mp, vc.vc_op, req);
 4032         vfs_rel(mp);
 4033         return (error);
 4034 }
 4035 
 4036 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLFLAG_WR, NULL, 0, sysctl_vfs_ctl, "",
 4037     "Sysctl by fsid");
 4038 
 4039 /*
 4040  * Function to initialize a va_filerev field sensibly.
 4041  * XXX: Wouldn't a random number make a lot more sense ??
 4042  */
 4043 u_quad_t
 4044 init_va_filerev(void)
 4045 {
 4046         struct bintime bt;
 4047 
 4048         getbinuptime(&bt);
 4049         return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
 4050 }
 4051 
 4052 static int      filt_vfsread(struct knote *kn, long hint);
 4053 static int      filt_vfswrite(struct knote *kn, long hint);
 4054 static int      filt_vfsvnode(struct knote *kn, long hint);
 4055 static void     filt_vfsdetach(struct knote *kn);
 4056 static struct filterops vfsread_filtops =
 4057         { 1, NULL, filt_vfsdetach, filt_vfsread };
 4058 static struct filterops vfswrite_filtops =
 4059         { 1, NULL, filt_vfsdetach, filt_vfswrite };
 4060 static struct filterops vfsvnode_filtops =
 4061         { 1, NULL, filt_vfsdetach, filt_vfsvnode };
 4062 
 4063 static void
 4064 vfs_knllock(void *arg)
 4065 {
 4066         struct vnode *vp = arg;
 4067 
 4068         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
 4069 }
 4070 
 4071 static void
 4072 vfs_knlunlock(void *arg)
 4073 {
 4074         struct vnode *vp = arg;
 4075 
 4076         VOP_UNLOCK(vp, 0, curthread);
 4077 }
 4078 
 4079 int
 4080 vfs_kqfilter(struct vop_kqfilter_args *ap)
 4081 {
 4082         struct vnode *vp = ap->a_vp;
 4083         struct knote *kn = ap->a_kn;
 4084         struct knlist *knl;
 4085 
 4086         switch (kn->kn_filter) {
 4087         case EVFILT_READ:
 4088                 kn->kn_fop = &vfsread_filtops;
 4089                 break;
 4090         case EVFILT_WRITE:
 4091                 kn->kn_fop = &vfswrite_filtops;
 4092                 break;
 4093         case EVFILT_VNODE:
 4094                 kn->kn_fop = &vfsvnode_filtops;
 4095                 break;
 4096         default:
 4097                 return (EINVAL);
 4098         }
 4099 
 4100         kn->kn_hook = (caddr_t)vp;
 4101 
 4102         v_addpollinfo(vp);
 4103         if (vp->v_pollinfo == NULL)
 4104                 return (ENOMEM);
 4105         knl = &vp->v_pollinfo->vpi_selinfo.si_note;
 4106         knlist_add(knl, kn, 0);
 4107 
 4108         return (0);
 4109 }
 4110 
 4111 /*
 4112  * Detach knote from vnode
 4113  */
 4114 static void
 4115 filt_vfsdetach(struct knote *kn)
 4116 {
 4117         struct vnode *vp = (struct vnode *)kn->kn_hook;
 4118 
 4119         KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
 4120         knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
 4121 }
 4122 
 4123 /*ARGSUSED*/
 4124 static int
 4125 filt_vfsread(struct knote *kn, long hint)
 4126 {
 4127         struct vnode *vp = (struct vnode *)kn->kn_hook;
 4128         struct vattr va;
 4129         int res;
 4130 
 4131         /*
 4132          * filesystem is gone, so set the EOF flag and schedule
 4133          * the knote for deletion.
 4134          */
 4135         if (hint == NOTE_REVOKE) {
 4136                 VI_LOCK(vp);
 4137                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
 4138                 VI_UNLOCK(vp);
 4139                 return (1);
 4140         }
 4141 
 4142         if (VOP_GETATTR(vp, &va, curthread->td_ucred, curthread))
 4143                 return (0);
 4144 
 4145         VI_LOCK(vp);
 4146         kn->kn_data = va.va_size - kn->kn_fp->f_offset;
 4147         res = (kn->kn_data != 0);
 4148         VI_UNLOCK(vp);
 4149         return (res);
 4150 }
 4151 
 4152 /*ARGSUSED*/
 4153 static int
 4154 filt_vfswrite(struct knote *kn, long hint)
 4155 {
 4156         struct vnode *vp = (struct vnode *)kn->kn_hook;
 4157 
 4158         VI_LOCK(vp);
 4159 
 4160         /*
 4161          * filesystem is gone, so set the EOF flag and schedule
 4162          * the knote for deletion.
 4163          */
 4164         if (hint == NOTE_REVOKE)
 4165                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
 4166 
 4167         kn->kn_data = 0;
 4168         VI_UNLOCK(vp);
 4169         return (1);
 4170 }
 4171 
 4172 static int
 4173 filt_vfsvnode(struct knote *kn, long hint)
 4174 {
 4175         struct vnode *vp = (struct vnode *)kn->kn_hook;
 4176         int res;
 4177 
 4178         VI_LOCK(vp);
 4179         if (kn->kn_sfflags & hint)
 4180                 kn->kn_fflags |= hint;
 4181         if (hint == NOTE_REVOKE) {
 4182                 kn->kn_flags |= EV_EOF;
 4183                 VI_UNLOCK(vp);
 4184                 return (1);
 4185         }
 4186         res = (kn->kn_fflags != 0);
 4187         VI_UNLOCK(vp);
 4188         return (res);
 4189 }
 4190 
 4191 int
 4192 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
 4193 {
 4194         int error;
 4195 
 4196         if (dp->d_reclen > ap->a_uio->uio_resid)
 4197                 return (ENAMETOOLONG);
 4198         error = uiomove(dp, dp->d_reclen, ap->a_uio);
 4199         if (error) {
 4200                 if (ap->a_ncookies != NULL) {
 4201                         if (ap->a_cookies != NULL)
 4202                                 free(ap->a_cookies, M_TEMP);
 4203                         ap->a_cookies = NULL;
 4204                         *ap->a_ncookies = 0;
 4205                 }
 4206                 return (error);
 4207         }
 4208         if (ap->a_ncookies == NULL)
 4209                 return (0);
 4210 
 4211         KASSERT(ap->a_cookies,
 4212             ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
 4213 
 4214         *ap->a_cookies = realloc(*ap->a_cookies,
 4215             (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
 4216         (*ap->a_cookies)[*ap->a_ncookies] = off;
 4217         return (0);
 4218 }
 4219 
 4220 /*
 4221  * Mark for update the access time of the file if the filesystem
 4222  * supports VA_MARK_ATIME.  This functionality is used by execve
 4223  * and mmap, so we want to avoid the synchronous I/O implied by
 4224  * directly setting va_atime for the sake of efficiency.
 4225  */
 4226 void
 4227 vfs_mark_atime(struct vnode *vp, struct thread *td)
 4228 {
 4229         struct vattr atimeattr;
 4230 
 4231         if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
 4232                 VATTR_NULL(&atimeattr);
 4233                 atimeattr.va_vaflags |= VA_MARK_ATIME;
 4234                 (void)VOP_SETATTR(vp, &atimeattr, td->td_ucred, td);
 4235         }
 4236 }

Cache object: 6076cc9edb2ad9b27d0a46db4bd53059


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