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

Cache object: 8936caeb1a90c2e5cd32587caba29f60


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