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


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

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

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

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

Cache object: b5364ad1f4b16ad447e809125cd9ff21


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