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_bio.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) 2004 Poul-Henning Kamp
    3  * Copyright (c) 1994,1997 John S. Dyson
    4  * All rights reserved.
    5  *
    6  * Redistribution and use in source and binary forms, with or without
    7  * modification, are permitted provided that the following conditions
    8  * are met:
    9  * 1. Redistributions of source code must retain the above copyright
   10  *    notice, this list of conditions and the following disclaimer.
   11  * 2. Redistributions in binary form must reproduce the above copyright
   12  *    notice, this list of conditions and the following disclaimer in the
   13  *    documentation and/or other materials provided with the distribution.
   14  *
   15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   25  * SUCH DAMAGE.
   26  */
   27 
   28 /*
   29  * this file contains a new buffer I/O scheme implementing a coherent
   30  * VM object and buffer cache scheme.  Pains have been taken to make
   31  * sure that the performance degradation associated with schemes such
   32  * as this is not realized.
   33  *
   34  * Author:  John S. Dyson
   35  * Significant help during the development and debugging phases
   36  * had been provided by David Greenman, also of the FreeBSD core team.
   37  *
   38  * see man buf(9) for more info.
   39  */
   40 
   41 #include <sys/cdefs.h>
   42 __FBSDID("$FreeBSD: releng/8.3/sys/kern/vfs_bio.c 225663 2011-09-19 11:08:31Z attilio $");
   43 
   44 #include <sys/param.h>
   45 #include <sys/systm.h>
   46 #include <sys/bio.h>
   47 #include <sys/conf.h>
   48 #include <sys/buf.h>
   49 #include <sys/devicestat.h>
   50 #include <sys/eventhandler.h>
   51 #include <sys/fail.h>
   52 #include <sys/limits.h>
   53 #include <sys/lock.h>
   54 #include <sys/malloc.h>
   55 #include <sys/mount.h>
   56 #include <sys/mutex.h>
   57 #include <sys/kernel.h>
   58 #include <sys/kthread.h>
   59 #include <sys/proc.h>
   60 #include <sys/resourcevar.h>
   61 #include <sys/sysctl.h>
   62 #include <sys/vmmeter.h>
   63 #include <sys/vnode.h>
   64 #include <geom/geom.h>
   65 #include <vm/vm.h>
   66 #include <vm/vm_param.h>
   67 #include <vm/vm_kern.h>
   68 #include <vm/vm_pageout.h>
   69 #include <vm/vm_page.h>
   70 #include <vm/vm_object.h>
   71 #include <vm/vm_extern.h>
   72 #include <vm/vm_map.h>
   73 #include "opt_compat.h"
   74 #include "opt_directio.h"
   75 #include "opt_swap.h"
   76 
   77 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
   78 
   79 struct  bio_ops bioops;         /* I/O operation notification */
   80 
   81 struct  buf_ops buf_ops_bio = {
   82         .bop_name       =       "buf_ops_bio",
   83         .bop_write      =       bufwrite,
   84         .bop_strategy   =       bufstrategy,
   85         .bop_sync       =       bufsync,
   86         .bop_bdflush    =       bufbdflush,
   87 };
   88 
   89 /*
   90  * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
   91  * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
   92  */
   93 struct buf *buf;                /* buffer header pool */
   94 
   95 static struct proc *bufdaemonproc;
   96 
   97 static int inmem(struct vnode *vp, daddr_t blkno);
   98 static void vm_hold_free_pages(struct buf *bp, int newbsize);
   99 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
  100                 vm_offset_t to);
  101 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
  102 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
  103                 vm_page_t m);
  104 static void vfs_drain_busy_pages(struct buf *bp);
  105 static void vfs_clean_pages_dirty_buf(struct buf *bp);
  106 static void vfs_setdirty_locked_object(struct buf *bp);
  107 static void vfs_vmio_release(struct buf *bp);
  108 static int vfs_bio_clcheck(struct vnode *vp, int size,
  109                 daddr_t lblkno, daddr_t blkno);
  110 static int buf_do_flush(struct vnode *vp);
  111 static int flushbufqueues(struct vnode *, int, int);
  112 static void buf_daemon(void);
  113 static void bremfreel(struct buf *bp);
  114 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
  115     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
  116 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
  117 #endif
  118 
  119 int vmiodirenable = TRUE;
  120 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
  121     "Use the VM system for directory writes");
  122 long runningbufspace;
  123 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
  124     "Amount of presently outstanding async buffer io");
  125 static long bufspace;
  126 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
  127     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
  128 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
  129     &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
  130 #else
  131 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
  132     "Virtual memory used for buffers");
  133 #endif
  134 static long maxbufspace;
  135 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
  136     "Maximum allowed value of bufspace (including buf_daemon)");
  137 static long bufmallocspace;
  138 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
  139     "Amount of malloced memory for buffers");
  140 static long maxbufmallocspace;
  141 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
  142     "Maximum amount of malloced memory for buffers");
  143 static long lobufspace;
  144 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
  145     "Minimum amount of buffers we want to have");
  146 long hibufspace;
  147 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
  148     "Maximum allowed value of bufspace (excluding buf_daemon)");
  149 static int bufreusecnt;
  150 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
  151     "Number of times we have reused a buffer");
  152 static int buffreekvacnt;
  153 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
  154     "Number of times we have freed the KVA space from some buffer");
  155 static int bufdefragcnt;
  156 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
  157     "Number of times we have had to repeat buffer allocation to defragment");
  158 static long lorunningspace;
  159 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
  160     "Minimum preferred space used for in-progress I/O");
  161 static long hirunningspace;
  162 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
  163     "Maximum amount of space to use for in-progress I/O");
  164 int dirtybufferflushes;
  165 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
  166     0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
  167 int bdwriteskip;
  168 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
  169     0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
  170 int altbufferflushes;
  171 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
  172     0, "Number of fsync flushes to limit dirty buffers");
  173 static int recursiveflushes;
  174 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
  175     0, "Number of flushes skipped due to being recursive");
  176 static int numdirtybuffers;
  177 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
  178     "Number of buffers that are dirty (has unwritten changes) at the moment");
  179 static int lodirtybuffers;
  180 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
  181     "How many buffers we want to have free before bufdaemon can sleep");
  182 static int hidirtybuffers;
  183 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
  184     "When the number of dirty buffers is considered severe");
  185 int dirtybufthresh;
  186 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
  187     0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
  188 static int numfreebuffers;
  189 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
  190     "Number of free buffers");
  191 static int lofreebuffers;
  192 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
  193    "XXX Unused");
  194 static int hifreebuffers;
  195 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
  196    "XXX Complicatedly unused");
  197 static int getnewbufcalls;
  198 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
  199    "Number of calls to getnewbuf");
  200 static int getnewbufrestarts;
  201 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
  202     "Number of times getnewbuf has had to restart a buffer aquisition");
  203 static int flushbufqtarget = 100;
  204 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
  205     "Amount of work to do in flushbufqueues when helping bufdaemon");
  206 static long notbufdflashes;
  207 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, &notbufdflashes, 0,
  208     "Number of dirty buffer flushes done by the bufdaemon helpers");
  209 
  210 /*
  211  * Wakeup point for bufdaemon, as well as indicator of whether it is already
  212  * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
  213  * is idling.
  214  */
  215 static int bd_request;
  216 
  217 /*
  218  * This lock synchronizes access to bd_request.
  219  */
  220 static struct mtx bdlock;
  221 
  222 /*
  223  * bogus page -- for I/O to/from partially complete buffers
  224  * this is a temporary solution to the problem, but it is not
  225  * really that bad.  it would be better to split the buffer
  226  * for input in the case of buffers partially already in memory,
  227  * but the code is intricate enough already.
  228  */
  229 vm_page_t bogus_page;
  230 
  231 /*
  232  * Synchronization (sleep/wakeup) variable for active buffer space requests.
  233  * Set when wait starts, cleared prior to wakeup().
  234  * Used in runningbufwakeup() and waitrunningbufspace().
  235  */
  236 static int runningbufreq;
  237 
  238 /*
  239  * This lock protects the runningbufreq and synchronizes runningbufwakeup and
  240  * waitrunningbufspace().
  241  */
  242 static struct mtx rbreqlock;
  243 
  244 /* 
  245  * Synchronization (sleep/wakeup) variable for buffer requests.
  246  * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
  247  * by and/or.
  248  * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
  249  * getnewbuf(), and getblk().
  250  */
  251 static int needsbuffer;
  252 
  253 /*
  254  * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
  255  */
  256 static struct mtx nblock;
  257 
  258 /*
  259  * Definitions for the buffer free lists.
  260  */
  261 #define BUFFER_QUEUES   6       /* number of free buffer queues */
  262 
  263 #define QUEUE_NONE      0       /* on no queue */
  264 #define QUEUE_CLEAN     1       /* non-B_DELWRI buffers */
  265 #define QUEUE_DIRTY     2       /* B_DELWRI buffers */
  266 #define QUEUE_DIRTY_GIANT 3     /* B_DELWRI buffers that need giant */
  267 #define QUEUE_EMPTYKVA  4       /* empty buffer headers w/KVA assignment */
  268 #define QUEUE_EMPTY     5       /* empty buffer headers */
  269 #define QUEUE_SENTINEL  1024    /* not an queue index, but mark for sentinel */
  270 
  271 /* Queues for free buffers with various properties */
  272 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
  273 
  274 /* Lock for the bufqueues */
  275 static struct mtx bqlock;
  276 
  277 /*
  278  * Single global constant for BUF_WMESG, to avoid getting multiple references.
  279  * buf_wmesg is referred from macros.
  280  */
  281 const char *buf_wmesg = BUF_WMESG;
  282 
  283 #define VFS_BIO_NEED_ANY        0x01    /* any freeable buffer */
  284 #define VFS_BIO_NEED_DIRTYFLUSH 0x02    /* waiting for dirty buffer flush */
  285 #define VFS_BIO_NEED_FREE       0x04    /* wait for free bufs, hi hysteresis */
  286 #define VFS_BIO_NEED_BUFSPACE   0x08    /* wait for buf space, lo hysteresis */
  287 
  288 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
  289     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
  290 static int
  291 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
  292 {
  293         long lvalue;
  294         int ivalue;
  295 
  296         if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
  297                 return (sysctl_handle_long(oidp, arg1, arg2, req));
  298         lvalue = *(long *)arg1;
  299         if (lvalue > INT_MAX)
  300                 /* On overflow, still write out a long to trigger ENOMEM. */
  301                 return (sysctl_handle_long(oidp, &lvalue, 0, req));
  302         ivalue = lvalue;
  303         return (sysctl_handle_int(oidp, &ivalue, 0, req));
  304 }
  305 #endif
  306 
  307 #ifdef DIRECTIO
  308 extern void ffs_rawread_setup(void);
  309 #endif /* DIRECTIO */
  310 /*
  311  *      numdirtywakeup:
  312  *
  313  *      If someone is blocked due to there being too many dirty buffers,
  314  *      and numdirtybuffers is now reasonable, wake them up.
  315  */
  316 
  317 static __inline void
  318 numdirtywakeup(int level)
  319 {
  320 
  321         if (numdirtybuffers <= level) {
  322                 mtx_lock(&nblock);
  323                 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
  324                         needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
  325                         wakeup(&needsbuffer);
  326                 }
  327                 mtx_unlock(&nblock);
  328         }
  329 }
  330 
  331 /*
  332  *      bufspacewakeup:
  333  *
  334  *      Called when buffer space is potentially available for recovery.
  335  *      getnewbuf() will block on this flag when it is unable to free 
  336  *      sufficient buffer space.  Buffer space becomes recoverable when 
  337  *      bp's get placed back in the queues.
  338  */
  339 
  340 static __inline void
  341 bufspacewakeup(void)
  342 {
  343 
  344         /*
  345          * If someone is waiting for BUF space, wake them up.  Even
  346          * though we haven't freed the kva space yet, the waiting
  347          * process will be able to now.
  348          */
  349         mtx_lock(&nblock);
  350         if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
  351                 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
  352                 wakeup(&needsbuffer);
  353         }
  354         mtx_unlock(&nblock);
  355 }
  356 
  357 /*
  358  * runningbufwakeup() - in-progress I/O accounting.
  359  *
  360  */
  361 void
  362 runningbufwakeup(struct buf *bp)
  363 {
  364 
  365         if (bp->b_runningbufspace) {
  366                 atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
  367                 bp->b_runningbufspace = 0;
  368                 mtx_lock(&rbreqlock);
  369                 if (runningbufreq && runningbufspace <= lorunningspace) {
  370                         runningbufreq = 0;
  371                         wakeup(&runningbufreq);
  372                 }
  373                 mtx_unlock(&rbreqlock);
  374         }
  375 }
  376 
  377 /*
  378  *      bufcountwakeup:
  379  *
  380  *      Called when a buffer has been added to one of the free queues to
  381  *      account for the buffer and to wakeup anyone waiting for free buffers.
  382  *      This typically occurs when large amounts of metadata are being handled
  383  *      by the buffer cache ( else buffer space runs out first, usually ).
  384  */
  385 
  386 static __inline void
  387 bufcountwakeup(struct buf *bp) 
  388 {
  389         int old;
  390 
  391         KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
  392             ("buf %p already counted as free", bp));
  393         if (bp->b_bufobj != NULL)
  394                 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
  395         bp->b_vflags |= BV_INFREECNT;
  396         old = atomic_fetchadd_int(&numfreebuffers, 1);
  397         KASSERT(old >= 0 && old < nbuf,
  398             ("numfreebuffers climbed to %d", old + 1));
  399         mtx_lock(&nblock);
  400         if (needsbuffer) {
  401                 needsbuffer &= ~VFS_BIO_NEED_ANY;
  402                 if (numfreebuffers >= hifreebuffers)
  403                         needsbuffer &= ~VFS_BIO_NEED_FREE;
  404                 wakeup(&needsbuffer);
  405         }
  406         mtx_unlock(&nblock);
  407 }
  408 
  409 /*
  410  *      waitrunningbufspace()
  411  *
  412  *      runningbufspace is a measure of the amount of I/O currently
  413  *      running.  This routine is used in async-write situations to
  414  *      prevent creating huge backups of pending writes to a device.
  415  *      Only asynchronous writes are governed by this function.
  416  *
  417  *      Reads will adjust runningbufspace, but will not block based on it.
  418  *      The read load has a side effect of reducing the allowed write load.
  419  *
  420  *      This does NOT turn an async write into a sync write.  It waits  
  421  *      for earlier writes to complete and generally returns before the
  422  *      caller's write has reached the device.
  423  */
  424 void
  425 waitrunningbufspace(void)
  426 {
  427 
  428         mtx_lock(&rbreqlock);
  429         while (runningbufspace > hirunningspace) {
  430                 ++runningbufreq;
  431                 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
  432         }
  433         mtx_unlock(&rbreqlock);
  434 }
  435 
  436 
  437 /*
  438  *      vfs_buf_test_cache:
  439  *
  440  *      Called when a buffer is extended.  This function clears the B_CACHE
  441  *      bit if the newly extended portion of the buffer does not contain
  442  *      valid data.
  443  */
  444 static __inline
  445 void
  446 vfs_buf_test_cache(struct buf *bp,
  447                   vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
  448                   vm_page_t m)
  449 {
  450 
  451         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
  452         if (bp->b_flags & B_CACHE) {
  453                 int base = (foff + off) & PAGE_MASK;
  454                 if (vm_page_is_valid(m, base, size) == 0)
  455                         bp->b_flags &= ~B_CACHE;
  456         }
  457 }
  458 
  459 /* Wake up the buffer daemon if necessary */
  460 static __inline
  461 void
  462 bd_wakeup(int dirtybuflevel)
  463 {
  464 
  465         mtx_lock(&bdlock);
  466         if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
  467                 bd_request = 1;
  468                 wakeup(&bd_request);
  469         }
  470         mtx_unlock(&bdlock);
  471 }
  472 
  473 /*
  474  * bd_speedup - speedup the buffer cache flushing code
  475  */
  476 
  477 static __inline
  478 void
  479 bd_speedup(void)
  480 {
  481 
  482         bd_wakeup(1);
  483 }
  484 
  485 /*
  486  * Calculating buffer cache scaling values and reserve space for buffer
  487  * headers.  This is called during low level kernel initialization and
  488  * may be called more then once.  We CANNOT write to the memory area
  489  * being reserved at this time.
  490  */
  491 caddr_t
  492 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
  493 {
  494         int tuned_nbuf;
  495         long maxbuf;
  496 
  497         /*
  498          * physmem_est is in pages.  Convert it to kilobytes (assumes
  499          * PAGE_SIZE is >= 1K)
  500          */
  501         physmem_est = physmem_est * (PAGE_SIZE / 1024);
  502 
  503         /*
  504          * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
  505          * For the first 64MB of ram nominally allocate sufficient buffers to
  506          * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
  507          * buffers to cover 1/10 of our ram over 64MB.  When auto-sizing
  508          * the buffer cache we limit the eventual kva reservation to
  509          * maxbcache bytes.
  510          *
  511          * factor represents the 1/4 x ram conversion.
  512          */
  513         if (nbuf == 0) {
  514                 int factor = 4 * BKVASIZE / 1024;
  515 
  516                 nbuf = 50;
  517                 if (physmem_est > 4096)
  518                         nbuf += min((physmem_est - 4096) / factor,
  519                             65536 / factor);
  520                 if (physmem_est > 65536)
  521                         nbuf += (physmem_est - 65536) * 2 / (factor * 5);
  522 
  523                 if (maxbcache && nbuf > maxbcache / BKVASIZE)
  524                         nbuf = maxbcache / BKVASIZE;
  525                 tuned_nbuf = 1;
  526         } else
  527                 tuned_nbuf = 0;
  528 
  529         /* XXX Avoid unsigned long overflows later on with maxbufspace. */
  530         maxbuf = (LONG_MAX / 3) / BKVASIZE;
  531         if (nbuf > maxbuf) {
  532                 if (!tuned_nbuf)
  533                         printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
  534                             maxbuf);
  535                 nbuf = maxbuf;
  536         }
  537 
  538         /*
  539          * swbufs are used as temporary holders for I/O, such as paging I/O.
  540          * We have no less then 16 and no more then 256.
  541          */
  542         nswbuf = max(min(nbuf/4, 256), 16);
  543 #ifdef NSWBUF_MIN
  544         if (nswbuf < NSWBUF_MIN)
  545                 nswbuf = NSWBUF_MIN;
  546 #endif
  547 #ifdef DIRECTIO
  548         ffs_rawread_setup();
  549 #endif
  550 
  551         /*
  552          * Reserve space for the buffer cache buffers
  553          */
  554         swbuf = (void *)v;
  555         v = (caddr_t)(swbuf + nswbuf);
  556         buf = (void *)v;
  557         v = (caddr_t)(buf + nbuf);
  558 
  559         return(v);
  560 }
  561 
  562 /* Initialize the buffer subsystem.  Called before use of any buffers. */
  563 void
  564 bufinit(void)
  565 {
  566         struct buf *bp;
  567         int i;
  568 
  569         mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
  570         mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
  571         mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
  572         mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
  573 
  574         /* next, make a null set of free lists */
  575         for (i = 0; i < BUFFER_QUEUES; i++)
  576                 TAILQ_INIT(&bufqueues[i]);
  577 
  578         /* finally, initialize each buffer header and stick on empty q */
  579         for (i = 0; i < nbuf; i++) {
  580                 bp = &buf[i];
  581                 bzero(bp, sizeof *bp);
  582                 bp->b_flags = B_INVAL;  /* we're just an empty header */
  583                 bp->b_rcred = NOCRED;
  584                 bp->b_wcred = NOCRED;
  585                 bp->b_qindex = QUEUE_EMPTY;
  586                 bp->b_vflags = BV_INFREECNT;    /* buf is counted as free */
  587                 bp->b_xflags = 0;
  588                 LIST_INIT(&bp->b_dep);
  589                 BUF_LOCKINIT(bp);
  590                 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
  591         }
  592 
  593         /*
  594          * maxbufspace is the absolute maximum amount of buffer space we are 
  595          * allowed to reserve in KVM and in real terms.  The absolute maximum
  596          * is nominally used by buf_daemon.  hibufspace is the nominal maximum
  597          * used by most other processes.  The differential is required to 
  598          * ensure that buf_daemon is able to run when other processes might 
  599          * be blocked waiting for buffer space.
  600          *
  601          * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
  602          * this may result in KVM fragmentation which is not handled optimally
  603          * by the system.
  604          */
  605         maxbufspace = (long)nbuf * BKVASIZE;
  606         hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
  607         lobufspace = hibufspace - MAXBSIZE;
  608 
  609         lorunningspace = 512 * 1024;
  610         hirunningspace = 1024 * 1024;
  611 
  612 /*
  613  * Limit the amount of malloc memory since it is wired permanently into
  614  * the kernel space.  Even though this is accounted for in the buffer
  615  * allocation, we don't want the malloced region to grow uncontrolled.
  616  * The malloc scheme improves memory utilization significantly on average
  617  * (small) directories.
  618  */
  619         maxbufmallocspace = hibufspace / 20;
  620 
  621 /*
  622  * Reduce the chance of a deadlock occuring by limiting the number
  623  * of delayed-write dirty buffers we allow to stack up.
  624  */
  625         hidirtybuffers = nbuf / 4 + 20;
  626         dirtybufthresh = hidirtybuffers * 9 / 10;
  627         numdirtybuffers = 0;
  628 /*
  629  * To support extreme low-memory systems, make sure hidirtybuffers cannot
  630  * eat up all available buffer space.  This occurs when our minimum cannot
  631  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
  632  * BKVASIZE'd (8K) buffers.
  633  */
  634         while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
  635                 hidirtybuffers >>= 1;
  636         }
  637         lodirtybuffers = hidirtybuffers / 2;
  638 
  639 /*
  640  * Try to keep the number of free buffers in the specified range,
  641  * and give special processes (e.g. like buf_daemon) access to an 
  642  * emergency reserve.
  643  */
  644         lofreebuffers = nbuf / 18 + 5;
  645         hifreebuffers = 2 * lofreebuffers;
  646         numfreebuffers = nbuf;
  647 
  648         bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
  649             VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
  650 }
  651 
  652 /*
  653  * bfreekva() - free the kva allocation for a buffer.
  654  *
  655  *      Since this call frees up buffer space, we call bufspacewakeup().
  656  */
  657 static void
  658 bfreekva(struct buf *bp)
  659 {
  660 
  661         if (bp->b_kvasize) {
  662                 atomic_add_int(&buffreekvacnt, 1);
  663                 atomic_subtract_long(&bufspace, bp->b_kvasize);
  664                 vm_map_remove(buffer_map, (vm_offset_t) bp->b_kvabase,
  665                     (vm_offset_t) bp->b_kvabase + bp->b_kvasize);
  666                 bp->b_kvasize = 0;
  667                 bufspacewakeup();
  668         }
  669 }
  670 
  671 /*
  672  *      bremfree:
  673  *
  674  *      Mark the buffer for removal from the appropriate free list in brelse.
  675  *      
  676  */
  677 void
  678 bremfree(struct buf *bp)
  679 {
  680         int old;
  681 
  682         CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
  683         KASSERT((bp->b_flags & B_REMFREE) == 0,
  684             ("bremfree: buffer %p already marked for delayed removal.", bp));
  685         KASSERT(bp->b_qindex != QUEUE_NONE,
  686             ("bremfree: buffer %p not on a queue.", bp));
  687         BUF_ASSERT_HELD(bp);
  688 
  689         bp->b_flags |= B_REMFREE;
  690         /* Fixup numfreebuffers count.  */
  691         if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
  692                 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
  693                     ("buf %p not counted in numfreebuffers", bp));
  694                 if (bp->b_bufobj != NULL)
  695                         mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
  696                 bp->b_vflags &= ~BV_INFREECNT;
  697                 old = atomic_fetchadd_int(&numfreebuffers, -1);
  698                 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
  699         }
  700 }
  701 
  702 /*
  703  *      bremfreef:
  704  *
  705  *      Force an immediate removal from a free list.  Used only in nfs when
  706  *      it abuses the b_freelist pointer.
  707  */
  708 void
  709 bremfreef(struct buf *bp)
  710 {
  711         mtx_lock(&bqlock);
  712         bremfreel(bp);
  713         mtx_unlock(&bqlock);
  714 }
  715 
  716 /*
  717  *      bremfreel:
  718  *
  719  *      Removes a buffer from the free list, must be called with the
  720  *      bqlock held.
  721  */
  722 static void
  723 bremfreel(struct buf *bp)
  724 {
  725         int old;
  726 
  727         CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
  728             bp, bp->b_vp, bp->b_flags);
  729         KASSERT(bp->b_qindex != QUEUE_NONE,
  730             ("bremfreel: buffer %p not on a queue.", bp));
  731         BUF_ASSERT_HELD(bp);
  732         mtx_assert(&bqlock, MA_OWNED);
  733 
  734         TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
  735         bp->b_qindex = QUEUE_NONE;
  736         /*
  737          * If this was a delayed bremfree() we only need to remove the buffer
  738          * from the queue and return the stats are already done.
  739          */
  740         if (bp->b_flags & B_REMFREE) {
  741                 bp->b_flags &= ~B_REMFREE;
  742                 return;
  743         }
  744         /*
  745          * Fixup numfreebuffers count.  If the buffer is invalid or not
  746          * delayed-write, the buffer was free and we must decrement
  747          * numfreebuffers.
  748          */
  749         if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
  750                 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
  751                     ("buf %p not counted in numfreebuffers", bp));
  752                 if (bp->b_bufobj != NULL)
  753                         mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
  754                 bp->b_vflags &= ~BV_INFREECNT;
  755                 old = atomic_fetchadd_int(&numfreebuffers, -1);
  756                 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
  757         }
  758 }
  759 
  760 
  761 /*
  762  * Get a buffer with the specified data.  Look in the cache first.  We
  763  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
  764  * is set, the buffer is valid and we do not have to do anything ( see
  765  * getblk() ).  This is really just a special case of breadn().
  766  */
  767 int
  768 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
  769     struct buf **bpp)
  770 {
  771 
  772         return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
  773 }
  774 
  775 /*
  776  * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
  777  * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
  778  * the buffer is valid and we do not have to do anything.
  779  */
  780 void
  781 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
  782     int cnt, struct ucred * cred)
  783 {
  784         struct buf *rabp;
  785         int i;
  786 
  787         for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
  788                 if (inmem(vp, *rablkno))
  789                         continue;
  790                 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
  791 
  792                 if ((rabp->b_flags & B_CACHE) == 0) {
  793                         if (!TD_IS_IDLETHREAD(curthread))
  794                                 curthread->td_ru.ru_inblock++;
  795                         rabp->b_flags |= B_ASYNC;
  796                         rabp->b_flags &= ~B_INVAL;
  797                         rabp->b_ioflags &= ~BIO_ERROR;
  798                         rabp->b_iocmd = BIO_READ;
  799                         if (rabp->b_rcred == NOCRED && cred != NOCRED)
  800                                 rabp->b_rcred = crhold(cred);
  801                         vfs_busy_pages(rabp, 0);
  802                         BUF_KERNPROC(rabp);
  803                         rabp->b_iooffset = dbtob(rabp->b_blkno);
  804                         bstrategy(rabp);
  805                 } else {
  806                         brelse(rabp);
  807                 }
  808         }
  809 }
  810 
  811 /*
  812  * Operates like bread, but also starts asynchronous I/O on
  813  * read-ahead blocks.
  814  */
  815 int
  816 breadn(struct vnode * vp, daddr_t blkno, int size,
  817     daddr_t * rablkno, int *rabsize,
  818     int cnt, struct ucred * cred, struct buf **bpp)
  819 {
  820         struct buf *bp;
  821         int rv = 0, readwait = 0;
  822 
  823         CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
  824         *bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
  825 
  826         /* if not found in cache, do some I/O */
  827         if ((bp->b_flags & B_CACHE) == 0) {
  828                 if (!TD_IS_IDLETHREAD(curthread))
  829                         curthread->td_ru.ru_inblock++;
  830                 bp->b_iocmd = BIO_READ;
  831                 bp->b_flags &= ~B_INVAL;
  832                 bp->b_ioflags &= ~BIO_ERROR;
  833                 if (bp->b_rcred == NOCRED && cred != NOCRED)
  834                         bp->b_rcred = crhold(cred);
  835                 vfs_busy_pages(bp, 0);
  836                 bp->b_iooffset = dbtob(bp->b_blkno);
  837                 bstrategy(bp);
  838                 ++readwait;
  839         }
  840 
  841         breada(vp, rablkno, rabsize, cnt, cred);
  842 
  843         if (readwait) {
  844                 rv = bufwait(bp);
  845         }
  846         return (rv);
  847 }
  848 
  849 /*
  850  * Write, release buffer on completion.  (Done by iodone
  851  * if async).  Do not bother writing anything if the buffer
  852  * is invalid.
  853  *
  854  * Note that we set B_CACHE here, indicating that buffer is
  855  * fully valid and thus cacheable.  This is true even of NFS
  856  * now so we set it generally.  This could be set either here 
  857  * or in biodone() since the I/O is synchronous.  We put it
  858  * here.
  859  */
  860 int
  861 bufwrite(struct buf *bp)
  862 {
  863         int oldflags;
  864         struct vnode *vp;
  865         int vp_md;
  866 
  867         CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
  868         if (bp->b_flags & B_INVAL) {
  869                 brelse(bp);
  870                 return (0);
  871         }
  872 
  873         oldflags = bp->b_flags;
  874 
  875         BUF_ASSERT_HELD(bp);
  876 
  877         if (bp->b_pin_count > 0)
  878                 bunpin_wait(bp);
  879 
  880         KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
  881             ("FFS background buffer should not get here %p", bp));
  882 
  883         vp = bp->b_vp;
  884         if (vp)
  885                 vp_md = vp->v_vflag & VV_MD;
  886         else
  887                 vp_md = 0;
  888 
  889         /* Mark the buffer clean */
  890         bundirty(bp);
  891 
  892         bp->b_flags &= ~B_DONE;
  893         bp->b_ioflags &= ~BIO_ERROR;
  894         bp->b_flags |= B_CACHE;
  895         bp->b_iocmd = BIO_WRITE;
  896 
  897         bufobj_wref(bp->b_bufobj);
  898         vfs_busy_pages(bp, 1);
  899 
  900         /*
  901          * Normal bwrites pipeline writes
  902          */
  903         bp->b_runningbufspace = bp->b_bufsize;
  904         atomic_add_long(&runningbufspace, bp->b_runningbufspace);
  905 
  906         if (!TD_IS_IDLETHREAD(curthread))
  907                 curthread->td_ru.ru_oublock++;
  908         if (oldflags & B_ASYNC)
  909                 BUF_KERNPROC(bp);
  910         bp->b_iooffset = dbtob(bp->b_blkno);
  911         bstrategy(bp);
  912 
  913         if ((oldflags & B_ASYNC) == 0) {
  914                 int rtval = bufwait(bp);
  915                 brelse(bp);
  916                 return (rtval);
  917         } else {
  918                 /*
  919                  * don't allow the async write to saturate the I/O
  920                  * system.  We will not deadlock here because
  921                  * we are blocking waiting for I/O that is already in-progress
  922                  * to complete. We do not block here if it is the update
  923                  * or syncer daemon trying to clean up as that can lead
  924                  * to deadlock.
  925                  */
  926                 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
  927                         waitrunningbufspace();
  928         }
  929 
  930         return (0);
  931 }
  932 
  933 void
  934 bufbdflush(struct bufobj *bo, struct buf *bp)
  935 {
  936         struct buf *nbp;
  937 
  938         if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
  939                 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
  940                 altbufferflushes++;
  941         } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
  942                 BO_LOCK(bo);
  943                 /*
  944                  * Try to find a buffer to flush.
  945                  */
  946                 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
  947                         if ((nbp->b_vflags & BV_BKGRDINPROG) ||
  948                             BUF_LOCK(nbp,
  949                                      LK_EXCLUSIVE | LK_NOWAIT, NULL))
  950                                 continue;
  951                         if (bp == nbp)
  952                                 panic("bdwrite: found ourselves");
  953                         BO_UNLOCK(bo);
  954                         /* Don't countdeps with the bo lock held. */
  955                         if (buf_countdeps(nbp, 0)) {
  956                                 BO_LOCK(bo);
  957                                 BUF_UNLOCK(nbp);
  958                                 continue;
  959                         }
  960                         if (nbp->b_flags & B_CLUSTEROK) {
  961                                 vfs_bio_awrite(nbp);
  962                         } else {
  963                                 bremfree(nbp);
  964                                 bawrite(nbp);
  965                         }
  966                         dirtybufferflushes++;
  967                         break;
  968                 }
  969                 if (nbp == NULL)
  970                         BO_UNLOCK(bo);
  971         }
  972 }
  973 
  974 /*
  975  * Delayed write. (Buffer is marked dirty).  Do not bother writing
  976  * anything if the buffer is marked invalid.
  977  *
  978  * Note that since the buffer must be completely valid, we can safely
  979  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
  980  * biodone() in order to prevent getblk from writing the buffer
  981  * out synchronously.
  982  */
  983 void
  984 bdwrite(struct buf *bp)
  985 {
  986         struct thread *td = curthread;
  987         struct vnode *vp;
  988         struct bufobj *bo;
  989 
  990         CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
  991         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
  992         BUF_ASSERT_HELD(bp);
  993 
  994         if (bp->b_flags & B_INVAL) {
  995                 brelse(bp);
  996                 return;
  997         }
  998 
  999         /*
 1000          * If we have too many dirty buffers, don't create any more.
 1001          * If we are wildly over our limit, then force a complete
 1002          * cleanup. Otherwise, just keep the situation from getting
 1003          * out of control. Note that we have to avoid a recursive
 1004          * disaster and not try to clean up after our own cleanup!
 1005          */
 1006         vp = bp->b_vp;
 1007         bo = bp->b_bufobj;
 1008         if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
 1009                 td->td_pflags |= TDP_INBDFLUSH;
 1010                 BO_BDFLUSH(bo, bp);
 1011                 td->td_pflags &= ~TDP_INBDFLUSH;
 1012         } else
 1013                 recursiveflushes++;
 1014 
 1015         bdirty(bp);
 1016         /*
 1017          * Set B_CACHE, indicating that the buffer is fully valid.  This is
 1018          * true even of NFS now.
 1019          */
 1020         bp->b_flags |= B_CACHE;
 1021 
 1022         /*
 1023          * This bmap keeps the system from needing to do the bmap later,
 1024          * perhaps when the system is attempting to do a sync.  Since it
 1025          * is likely that the indirect block -- or whatever other datastructure
 1026          * that the filesystem needs is still in memory now, it is a good
 1027          * thing to do this.  Note also, that if the pageout daemon is
 1028          * requesting a sync -- there might not be enough memory to do
 1029          * the bmap then...  So, this is important to do.
 1030          */
 1031         if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
 1032                 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
 1033         }
 1034 
 1035         /*
 1036          * Set the *dirty* buffer range based upon the VM system dirty
 1037          * pages.
 1038          *
 1039          * Mark the buffer pages as clean.  We need to do this here to
 1040          * satisfy the vnode_pager and the pageout daemon, so that it
 1041          * thinks that the pages have been "cleaned".  Note that since
 1042          * the pages are in a delayed write buffer -- the VFS layer
 1043          * "will" see that the pages get written out on the next sync,
 1044          * or perhaps the cluster will be completed.
 1045          */
 1046         vfs_clean_pages_dirty_buf(bp);
 1047         bqrelse(bp);
 1048 
 1049         /*
 1050          * Wakeup the buffer flushing daemon if we have a lot of dirty
 1051          * buffers (midpoint between our recovery point and our stall
 1052          * point).
 1053          */
 1054         bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
 1055 
 1056         /*
 1057          * note: we cannot initiate I/O from a bdwrite even if we wanted to,
 1058          * due to the softdep code.
 1059          */
 1060 }
 1061 
 1062 /*
 1063  *      bdirty:
 1064  *
 1065  *      Turn buffer into delayed write request.  We must clear BIO_READ and
 1066  *      B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to 
 1067  *      itself to properly update it in the dirty/clean lists.  We mark it
 1068  *      B_DONE to ensure that any asynchronization of the buffer properly
 1069  *      clears B_DONE ( else a panic will occur later ).  
 1070  *
 1071  *      bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
 1072  *      might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
 1073  *      should only be called if the buffer is known-good.
 1074  *
 1075  *      Since the buffer is not on a queue, we do not update the numfreebuffers
 1076  *      count.
 1077  *
 1078  *      The buffer must be on QUEUE_NONE.
 1079  */
 1080 void
 1081 bdirty(struct buf *bp)
 1082 {
 1083 
 1084         CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
 1085             bp, bp->b_vp, bp->b_flags);
 1086         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
 1087         KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
 1088             ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
 1089         BUF_ASSERT_HELD(bp);
 1090         bp->b_flags &= ~(B_RELBUF);
 1091         bp->b_iocmd = BIO_WRITE;
 1092 
 1093         if ((bp->b_flags & B_DELWRI) == 0) {
 1094                 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
 1095                 reassignbuf(bp);
 1096                 atomic_add_int(&numdirtybuffers, 1);
 1097                 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
 1098         }
 1099 }
 1100 
 1101 /*
 1102  *      bundirty:
 1103  *
 1104  *      Clear B_DELWRI for buffer.
 1105  *
 1106  *      Since the buffer is not on a queue, we do not update the numfreebuffers
 1107  *      count.
 1108  *      
 1109  *      The buffer must be on QUEUE_NONE.
 1110  */
 1111 
 1112 void
 1113 bundirty(struct buf *bp)
 1114 {
 1115 
 1116         CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
 1117         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
 1118         KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
 1119             ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
 1120         BUF_ASSERT_HELD(bp);
 1121 
 1122         if (bp->b_flags & B_DELWRI) {
 1123                 bp->b_flags &= ~B_DELWRI;
 1124                 reassignbuf(bp);
 1125                 atomic_subtract_int(&numdirtybuffers, 1);
 1126                 numdirtywakeup(lodirtybuffers);
 1127         }
 1128         /*
 1129          * Since it is now being written, we can clear its deferred write flag.
 1130          */
 1131         bp->b_flags &= ~B_DEFERRED;
 1132 }
 1133 
 1134 /*
 1135  *      bawrite:
 1136  *
 1137  *      Asynchronous write.  Start output on a buffer, but do not wait for
 1138  *      it to complete.  The buffer is released when the output completes.
 1139  *
 1140  *      bwrite() ( or the VOP routine anyway ) is responsible for handling 
 1141  *      B_INVAL buffers.  Not us.
 1142  */
 1143 void
 1144 bawrite(struct buf *bp)
 1145 {
 1146 
 1147         bp->b_flags |= B_ASYNC;
 1148         (void) bwrite(bp);
 1149 }
 1150 
 1151 /*
 1152  *      bwillwrite:
 1153  *
 1154  *      Called prior to the locking of any vnodes when we are expecting to
 1155  *      write.  We do not want to starve the buffer cache with too many
 1156  *      dirty buffers so we block here.  By blocking prior to the locking
 1157  *      of any vnodes we attempt to avoid the situation where a locked vnode
 1158  *      prevents the various system daemons from flushing related buffers.
 1159  */
 1160 
 1161 void
 1162 bwillwrite(void)
 1163 {
 1164 
 1165         if (numdirtybuffers >= hidirtybuffers) {
 1166                 mtx_lock(&nblock);
 1167                 while (numdirtybuffers >= hidirtybuffers) {
 1168                         bd_wakeup(1);
 1169                         needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
 1170                         msleep(&needsbuffer, &nblock,
 1171                             (PRIBIO + 4), "flswai", 0);
 1172                 }
 1173                 mtx_unlock(&nblock);
 1174         }
 1175 }
 1176 
 1177 /*
 1178  * Return true if we have too many dirty buffers.
 1179  */
 1180 int
 1181 buf_dirty_count_severe(void)
 1182 {
 1183 
 1184         return(numdirtybuffers >= hidirtybuffers);
 1185 }
 1186 
 1187 static __noinline int
 1188 buf_vm_page_count_severe(void)
 1189 {
 1190 
 1191         KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
 1192 
 1193         return vm_page_count_severe();
 1194 }
 1195 
 1196 /*
 1197  *      brelse:
 1198  *
 1199  *      Release a busy buffer and, if requested, free its resources.  The
 1200  *      buffer will be stashed in the appropriate bufqueue[] allowing it
 1201  *      to be accessed later as a cache entity or reused for other purposes.
 1202  */
 1203 void
 1204 brelse(struct buf *bp)
 1205 {
 1206         CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
 1207             bp, bp->b_vp, bp->b_flags);
 1208         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
 1209             ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
 1210 
 1211         if (bp->b_flags & B_MANAGED) {
 1212                 bqrelse(bp);
 1213                 return;
 1214         }
 1215 
 1216         if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
 1217             bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
 1218                 /*
 1219                  * Failed write, redirty.  Must clear BIO_ERROR to prevent
 1220                  * pages from being scrapped.  If the error is anything
 1221                  * other than an I/O error (EIO), assume that retrying
 1222                  * is futile.
 1223                  */
 1224                 bp->b_ioflags &= ~BIO_ERROR;
 1225                 bdirty(bp);
 1226         } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
 1227             (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
 1228                 /*
 1229                  * Either a failed I/O or we were asked to free or not
 1230                  * cache the buffer.
 1231                  */
 1232                 bp->b_flags |= B_INVAL;
 1233                 if (!LIST_EMPTY(&bp->b_dep))
 1234                         buf_deallocate(bp);
 1235                 if (bp->b_flags & B_DELWRI) {
 1236                         atomic_subtract_int(&numdirtybuffers, 1);
 1237                         numdirtywakeup(lodirtybuffers);
 1238                 }
 1239                 bp->b_flags &= ~(B_DELWRI | B_CACHE);
 1240                 if ((bp->b_flags & B_VMIO) == 0) {
 1241                         if (bp->b_bufsize)
 1242                                 allocbuf(bp, 0);
 1243                         if (bp->b_vp)
 1244                                 brelvp(bp);
 1245                 }
 1246         }
 1247 
 1248         /*
 1249          * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release() 
 1250          * is called with B_DELWRI set, the underlying pages may wind up
 1251          * getting freed causing a previous write (bdwrite()) to get 'lost'
 1252          * because pages associated with a B_DELWRI bp are marked clean.
 1253          * 
 1254          * We still allow the B_INVAL case to call vfs_vmio_release(), even
 1255          * if B_DELWRI is set.
 1256          *
 1257          * If B_DELWRI is not set we may have to set B_RELBUF if we are low
 1258          * on pages to return pages to the VM page queues.
 1259          */
 1260         if (bp->b_flags & B_DELWRI)
 1261                 bp->b_flags &= ~B_RELBUF;
 1262         else if (buf_vm_page_count_severe()) {
 1263                 /*
 1264                  * The locking of the BO_LOCK is not necessary since
 1265                  * BKGRDINPROG cannot be set while we hold the buf
 1266                  * lock, it can only be cleared if it is already
 1267                  * pending.
 1268                  */
 1269                 if (bp->b_vp) {
 1270                         if (!(bp->b_vflags & BV_BKGRDINPROG))
 1271                                 bp->b_flags |= B_RELBUF;
 1272                 } else
 1273                         bp->b_flags |= B_RELBUF;
 1274         }
 1275 
 1276         /*
 1277          * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
 1278          * constituted, not even NFS buffers now.  Two flags effect this.  If
 1279          * B_INVAL, the struct buf is invalidated but the VM object is kept
 1280          * around ( i.e. so it is trivial to reconstitute the buffer later ).
 1281          *
 1282          * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
 1283          * invalidated.  BIO_ERROR cannot be set for a failed write unless the
 1284          * buffer is also B_INVAL because it hits the re-dirtying code above.
 1285          *
 1286          * Normally we can do this whether a buffer is B_DELWRI or not.  If
 1287          * the buffer is an NFS buffer, it is tracking piecemeal writes or
 1288          * the commit state and we cannot afford to lose the buffer. If the
 1289          * buffer has a background write in progress, we need to keep it
 1290          * around to prevent it from being reconstituted and starting a second
 1291          * background write.
 1292          */
 1293         if ((bp->b_flags & B_VMIO)
 1294             && !(bp->b_vp->v_mount != NULL &&
 1295                  (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
 1296                  !vn_isdisk(bp->b_vp, NULL) &&
 1297                  (bp->b_flags & B_DELWRI))
 1298             ) {
 1299 
 1300                 int i, j, resid;
 1301                 vm_page_t m;
 1302                 off_t foff;
 1303                 vm_pindex_t poff;
 1304                 vm_object_t obj;
 1305 
 1306                 obj = bp->b_bufobj->bo_object;
 1307 
 1308                 /*
 1309                  * Get the base offset and length of the buffer.  Note that 
 1310                  * in the VMIO case if the buffer block size is not
 1311                  * page-aligned then b_data pointer may not be page-aligned.
 1312                  * But our b_pages[] array *IS* page aligned.
 1313                  *
 1314                  * block sizes less then DEV_BSIZE (usually 512) are not 
 1315                  * supported due to the page granularity bits (m->valid,
 1316                  * m->dirty, etc...). 
 1317                  *
 1318                  * See man buf(9) for more information
 1319                  */
 1320                 resid = bp->b_bufsize;
 1321                 foff = bp->b_offset;
 1322                 VM_OBJECT_LOCK(obj);
 1323                 for (i = 0; i < bp->b_npages; i++) {
 1324                         int had_bogus = 0;
 1325 
 1326                         m = bp->b_pages[i];
 1327 
 1328                         /*
 1329                          * If we hit a bogus page, fixup *all* the bogus pages
 1330                          * now.
 1331                          */
 1332                         if (m == bogus_page) {
 1333                                 poff = OFF_TO_IDX(bp->b_offset);
 1334                                 had_bogus = 1;
 1335 
 1336                                 for (j = i; j < bp->b_npages; j++) {
 1337                                         vm_page_t mtmp;
 1338                                         mtmp = bp->b_pages[j];
 1339                                         if (mtmp == bogus_page) {
 1340                                                 mtmp = vm_page_lookup(obj, poff + j);
 1341                                                 if (!mtmp) {
 1342                                                         panic("brelse: page missing\n");
 1343                                                 }
 1344                                                 bp->b_pages[j] = mtmp;
 1345                                         }
 1346                                 }
 1347 
 1348                                 if ((bp->b_flags & B_INVAL) == 0) {
 1349                                         pmap_qenter(
 1350                                             trunc_page((vm_offset_t)bp->b_data),
 1351                                             bp->b_pages, bp->b_npages);
 1352                                 }
 1353                                 m = bp->b_pages[i];
 1354                         }
 1355                         if ((bp->b_flags & B_NOCACHE) ||
 1356                             (bp->b_ioflags & BIO_ERROR &&
 1357                              bp->b_iocmd == BIO_READ)) {
 1358                                 int poffset = foff & PAGE_MASK;
 1359                                 int presid = resid > (PAGE_SIZE - poffset) ?
 1360                                         (PAGE_SIZE - poffset) : resid;
 1361 
 1362                                 KASSERT(presid >= 0, ("brelse: extra page"));
 1363                                 vm_page_lock_queues();
 1364                                 vm_page_set_invalid(m, poffset, presid);
 1365                                 vm_page_unlock_queues();
 1366                                 if (had_bogus)
 1367                                         printf("avoided corruption bug in bogus_page/brelse code\n");
 1368                         }
 1369                         resid -= PAGE_SIZE - (foff & PAGE_MASK);
 1370                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
 1371                 }
 1372                 VM_OBJECT_UNLOCK(obj);
 1373                 if (bp->b_flags & (B_INVAL | B_RELBUF))
 1374                         vfs_vmio_release(bp);
 1375 
 1376         } else if (bp->b_flags & B_VMIO) {
 1377 
 1378                 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
 1379                         vfs_vmio_release(bp);
 1380                 }
 1381 
 1382         } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
 1383                 if (bp->b_bufsize != 0)
 1384                         allocbuf(bp, 0);
 1385                 if (bp->b_vp != NULL)
 1386                         brelvp(bp);
 1387         }
 1388                         
 1389         if (BUF_LOCKRECURSED(bp)) {
 1390                 /* do not release to free list */
 1391                 BUF_UNLOCK(bp);
 1392                 return;
 1393         }
 1394 
 1395         /* enqueue */
 1396         mtx_lock(&bqlock);
 1397         /* Handle delayed bremfree() processing. */
 1398         if (bp->b_flags & B_REMFREE) {
 1399                 struct bufobj *bo;
 1400 
 1401                 bo = bp->b_bufobj;
 1402                 if (bo != NULL)
 1403                         BO_LOCK(bo);
 1404                 bremfreel(bp);
 1405                 if (bo != NULL)
 1406                         BO_UNLOCK(bo);
 1407         }
 1408         if (bp->b_qindex != QUEUE_NONE)
 1409                 panic("brelse: free buffer onto another queue???");
 1410 
 1411         /*
 1412          * If the buffer has junk contents signal it and eventually
 1413          * clean up B_DELWRI and diassociate the vnode so that gbincore()
 1414          * doesn't find it.
 1415          */
 1416         if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
 1417             (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
 1418                 bp->b_flags |= B_INVAL;
 1419         if (bp->b_flags & B_INVAL) {
 1420                 if (bp->b_flags & B_DELWRI)
 1421                         bundirty(bp);
 1422                 if (bp->b_vp)
 1423                         brelvp(bp);
 1424         }
 1425 
 1426         /* buffers with no memory */
 1427         if (bp->b_bufsize == 0) {
 1428                 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
 1429                 if (bp->b_vflags & BV_BKGRDINPROG)
 1430                         panic("losing buffer 1");
 1431                 if (bp->b_kvasize) {
 1432                         bp->b_qindex = QUEUE_EMPTYKVA;
 1433                 } else {
 1434                         bp->b_qindex = QUEUE_EMPTY;
 1435                 }
 1436                 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
 1437         /* buffers with junk contents */
 1438         } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
 1439             (bp->b_ioflags & BIO_ERROR)) {
 1440                 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
 1441                 if (bp->b_vflags & BV_BKGRDINPROG)
 1442                         panic("losing buffer 2");
 1443                 bp->b_qindex = QUEUE_CLEAN;
 1444                 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
 1445         /* remaining buffers */
 1446         } else {
 1447                 if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
 1448                     (B_DELWRI|B_NEEDSGIANT))
 1449                         bp->b_qindex = QUEUE_DIRTY_GIANT;
 1450                 else if (bp->b_flags & B_DELWRI)
 1451                         bp->b_qindex = QUEUE_DIRTY;
 1452                 else
 1453                         bp->b_qindex = QUEUE_CLEAN;
 1454                 if (bp->b_flags & B_AGE)
 1455                         TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
 1456                 else
 1457                         TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
 1458         }
 1459         mtx_unlock(&bqlock);
 1460 
 1461         /*
 1462          * Fixup numfreebuffers count.  The bp is on an appropriate queue
 1463          * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
 1464          * We've already handled the B_INVAL case ( B_DELWRI will be clear
 1465          * if B_INVAL is set ).
 1466          */
 1467 
 1468         if (!(bp->b_flags & B_DELWRI)) {
 1469                 struct bufobj *bo;
 1470 
 1471                 bo = bp->b_bufobj;
 1472                 if (bo != NULL)
 1473                         BO_LOCK(bo);
 1474                 bufcountwakeup(bp);
 1475                 if (bo != NULL)
 1476                         BO_UNLOCK(bo);
 1477         }
 1478 
 1479         /*
 1480          * Something we can maybe free or reuse
 1481          */
 1482         if (bp->b_bufsize || bp->b_kvasize)
 1483                 bufspacewakeup();
 1484 
 1485         bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
 1486         if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
 1487                 panic("brelse: not dirty");
 1488         /* unlock */
 1489         BUF_UNLOCK(bp);
 1490 }
 1491 
 1492 /*
 1493  * Release a buffer back to the appropriate queue but do not try to free
 1494  * it.  The buffer is expected to be used again soon.
 1495  *
 1496  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
 1497  * biodone() to requeue an async I/O on completion.  It is also used when
 1498  * known good buffers need to be requeued but we think we may need the data
 1499  * again soon.
 1500  *
 1501  * XXX we should be able to leave the B_RELBUF hint set on completion.
 1502  */
 1503 void
 1504 bqrelse(struct buf *bp)
 1505 {
 1506         struct bufobj *bo;
 1507 
 1508         CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
 1509         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
 1510             ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
 1511 
 1512         if (BUF_LOCKRECURSED(bp)) {
 1513                 /* do not release to free list */
 1514                 BUF_UNLOCK(bp);
 1515                 return;
 1516         }
 1517 
 1518         bo = bp->b_bufobj;
 1519         if (bp->b_flags & B_MANAGED) {
 1520                 if (bp->b_flags & B_REMFREE) {
 1521                         mtx_lock(&bqlock);
 1522                         if (bo != NULL)
 1523                                 BO_LOCK(bo);
 1524                         bremfreel(bp);
 1525                         if (bo != NULL)
 1526                                 BO_UNLOCK(bo);
 1527                         mtx_unlock(&bqlock);
 1528                 }
 1529                 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
 1530                 BUF_UNLOCK(bp);
 1531                 return;
 1532         }
 1533 
 1534         mtx_lock(&bqlock);
 1535         /* Handle delayed bremfree() processing. */
 1536         if (bp->b_flags & B_REMFREE) {
 1537                 if (bo != NULL)
 1538                         BO_LOCK(bo);
 1539                 bremfreel(bp);
 1540                 if (bo != NULL)
 1541                         BO_UNLOCK(bo);
 1542         }
 1543         if (bp->b_qindex != QUEUE_NONE)
 1544                 panic("bqrelse: free buffer onto another queue???");
 1545         /* buffers with stale but valid contents */
 1546         if (bp->b_flags & B_DELWRI) {
 1547                 if (bp->b_flags & B_NEEDSGIANT)
 1548                         bp->b_qindex = QUEUE_DIRTY_GIANT;
 1549                 else
 1550                         bp->b_qindex = QUEUE_DIRTY;
 1551                 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
 1552         } else {
 1553                 /*
 1554                  * The locking of the BO_LOCK for checking of the
 1555                  * BV_BKGRDINPROG is not necessary since the
 1556                  * BV_BKGRDINPROG cannot be set while we hold the buf
 1557                  * lock, it can only be cleared if it is already
 1558                  * pending.
 1559                  */
 1560                 if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
 1561                         bp->b_qindex = QUEUE_CLEAN;
 1562                         TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
 1563                             b_freelist);
 1564                 } else {
 1565                         /*
 1566                          * We are too low on memory, we have to try to free
 1567                          * the buffer (most importantly: the wired pages
 1568                          * making up its backing store) *now*.
 1569                          */
 1570                         mtx_unlock(&bqlock);
 1571                         brelse(bp);
 1572                         return;
 1573                 }
 1574         }
 1575         mtx_unlock(&bqlock);
 1576 
 1577         if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) {
 1578                 if (bo != NULL)
 1579                         BO_LOCK(bo);
 1580                 bufcountwakeup(bp);
 1581                 if (bo != NULL)
 1582                         BO_UNLOCK(bo);
 1583         }
 1584 
 1585         /*
 1586          * Something we can maybe free or reuse.
 1587          */
 1588         if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
 1589                 bufspacewakeup();
 1590 
 1591         bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
 1592         if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
 1593                 panic("bqrelse: not dirty");
 1594         /* unlock */
 1595         BUF_UNLOCK(bp);
 1596 }
 1597 
 1598 /* Give pages used by the bp back to the VM system (where possible) */
 1599 static void
 1600 vfs_vmio_release(struct buf *bp)
 1601 {
 1602         int i;
 1603         vm_page_t m;
 1604 
 1605         pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
 1606         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
 1607         vm_page_lock_queues();
 1608         for (i = 0; i < bp->b_npages; i++) {
 1609                 m = bp->b_pages[i];
 1610                 bp->b_pages[i] = NULL;
 1611                 /*
 1612                  * In order to keep page LRU ordering consistent, put
 1613                  * everything on the inactive queue.
 1614                  */
 1615                 vm_page_unwire(m, 0);
 1616                 /*
 1617                  * We don't mess with busy pages, it is
 1618                  * the responsibility of the process that
 1619                  * busied the pages to deal with them.
 1620                  */
 1621                 if ((m->oflags & VPO_BUSY) || (m->busy != 0))
 1622                         continue;
 1623                         
 1624                 if (m->wire_count == 0) {
 1625                         /*
 1626                          * Might as well free the page if we can and it has
 1627                          * no valid data.  We also free the page if the
 1628                          * buffer was used for direct I/O
 1629                          */
 1630                         if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
 1631                             m->hold_count == 0) {
 1632                                 vm_page_free(m);
 1633                         } else if (bp->b_flags & B_DIRECT) {
 1634                                 vm_page_try_to_free(m);
 1635                         } else if (buf_vm_page_count_severe()) {
 1636                                 vm_page_try_to_cache(m);
 1637                         }
 1638                 }
 1639         }
 1640         vm_page_unlock_queues();
 1641         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
 1642         
 1643         if (bp->b_bufsize) {
 1644                 bufspacewakeup();
 1645                 bp->b_bufsize = 0;
 1646         }
 1647         bp->b_npages = 0;
 1648         bp->b_flags &= ~B_VMIO;
 1649         if (bp->b_vp)
 1650                 brelvp(bp);
 1651 }
 1652 
 1653 /*
 1654  * Check to see if a block at a particular lbn is available for a clustered
 1655  * write.
 1656  */
 1657 static int
 1658 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
 1659 {
 1660         struct buf *bpa;
 1661         int match;
 1662 
 1663         match = 0;
 1664 
 1665         /* If the buf isn't in core skip it */
 1666         if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
 1667                 return (0);
 1668 
 1669         /* If the buf is busy we don't want to wait for it */
 1670         if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
 1671                 return (0);
 1672 
 1673         /* Only cluster with valid clusterable delayed write buffers */
 1674         if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
 1675             (B_DELWRI | B_CLUSTEROK))
 1676                 goto done;
 1677 
 1678         if (bpa->b_bufsize != size)
 1679                 goto done;
 1680 
 1681         /*
 1682          * Check to see if it is in the expected place on disk and that the
 1683          * block has been mapped.
 1684          */
 1685         if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
 1686                 match = 1;
 1687 done:
 1688         BUF_UNLOCK(bpa);
 1689         return (match);
 1690 }
 1691 
 1692 /*
 1693  *      vfs_bio_awrite:
 1694  *
 1695  *      Implement clustered async writes for clearing out B_DELWRI buffers.
 1696  *      This is much better then the old way of writing only one buffer at
 1697  *      a time.  Note that we may not be presented with the buffers in the 
 1698  *      correct order, so we search for the cluster in both directions.
 1699  */
 1700 int
 1701 vfs_bio_awrite(struct buf *bp)
 1702 {
 1703         struct bufobj *bo;
 1704         int i;
 1705         int j;
 1706         daddr_t lblkno = bp->b_lblkno;
 1707         struct vnode *vp = bp->b_vp;
 1708         int ncl;
 1709         int nwritten;
 1710         int size;
 1711         int maxcl;
 1712 
 1713         bo = &vp->v_bufobj;
 1714         /*
 1715          * right now we support clustered writing only to regular files.  If
 1716          * we find a clusterable block we could be in the middle of a cluster
 1717          * rather then at the beginning.
 1718          */
 1719         if ((vp->v_type == VREG) && 
 1720             (vp->v_mount != 0) && /* Only on nodes that have the size info */
 1721             (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
 1722 
 1723                 size = vp->v_mount->mnt_stat.f_iosize;
 1724                 maxcl = MAXPHYS / size;
 1725 
 1726                 BO_LOCK(bo);
 1727                 for (i = 1; i < maxcl; i++)
 1728                         if (vfs_bio_clcheck(vp, size, lblkno + i,
 1729                             bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
 1730                                 break;
 1731 
 1732                 for (j = 1; i + j <= maxcl && j <= lblkno; j++) 
 1733                         if (vfs_bio_clcheck(vp, size, lblkno - j,
 1734                             bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
 1735                                 break;
 1736                 BO_UNLOCK(bo);
 1737                 --j;
 1738                 ncl = i + j;
 1739                 /*
 1740                  * this is a possible cluster write
 1741                  */
 1742                 if (ncl != 1) {
 1743                         BUF_UNLOCK(bp);
 1744                         nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
 1745                         return nwritten;
 1746                 }
 1747         }
 1748         bremfree(bp);
 1749         bp->b_flags |= B_ASYNC;
 1750         /*
 1751          * default (old) behavior, writing out only one block
 1752          *
 1753          * XXX returns b_bufsize instead of b_bcount for nwritten?
 1754          */
 1755         nwritten = bp->b_bufsize;
 1756         (void) bwrite(bp);
 1757 
 1758         return nwritten;
 1759 }
 1760 
 1761 /*
 1762  *      getnewbuf:
 1763  *
 1764  *      Find and initialize a new buffer header, freeing up existing buffers 
 1765  *      in the bufqueues as necessary.  The new buffer is returned locked.
 1766  *
 1767  *      Important:  B_INVAL is not set.  If the caller wishes to throw the
 1768  *      buffer away, the caller must set B_INVAL prior to calling brelse().
 1769  *
 1770  *      We block if:
 1771  *              We have insufficient buffer headers
 1772  *              We have insufficient buffer space
 1773  *              buffer_map is too fragmented ( space reservation fails )
 1774  *              If we have to flush dirty buffers ( but we try to avoid this )
 1775  *
 1776  *      To avoid VFS layer recursion we do not flush dirty buffers ourselves.
 1777  *      Instead we ask the buf daemon to do it for us.  We attempt to
 1778  *      avoid piecemeal wakeups of the pageout daemon.
 1779  */
 1780 
 1781 static struct buf *
 1782 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
 1783     int gbflags)
 1784 {
 1785         struct thread *td;
 1786         struct buf *bp;
 1787         struct buf *nbp;
 1788         int defrag = 0;
 1789         int nqindex;
 1790         static int flushingbufs;
 1791 
 1792         td = curthread;
 1793         /*
 1794          * We can't afford to block since we might be holding a vnode lock,
 1795          * which may prevent system daemons from running.  We deal with
 1796          * low-memory situations by proactively returning memory and running
 1797          * async I/O rather then sync I/O.
 1798          */
 1799         atomic_add_int(&getnewbufcalls, 1);
 1800         atomic_subtract_int(&getnewbufrestarts, 1);
 1801 restart:
 1802         atomic_add_int(&getnewbufrestarts, 1);
 1803 
 1804         /*
 1805          * Setup for scan.  If we do not have enough free buffers,
 1806          * we setup a degenerate case that immediately fails.  Note
 1807          * that if we are specially marked process, we are allowed to
 1808          * dip into our reserves.
 1809          *
 1810          * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
 1811          *
 1812          * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
 1813          * However, there are a number of cases (defragging, reusing, ...)
 1814          * where we cannot backup.
 1815          */
 1816         mtx_lock(&bqlock);
 1817         nqindex = QUEUE_EMPTYKVA;
 1818         nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
 1819 
 1820         if (nbp == NULL) {
 1821                 /*
 1822                  * If no EMPTYKVA buffers and we are either
 1823                  * defragging or reusing, locate a CLEAN buffer
 1824                  * to free or reuse.  If bufspace useage is low
 1825                  * skip this step so we can allocate a new buffer.
 1826                  */
 1827                 if (defrag || bufspace >= lobufspace) {
 1828                         nqindex = QUEUE_CLEAN;
 1829                         nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
 1830                 }
 1831 
 1832                 /*
 1833                  * If we could not find or were not allowed to reuse a
 1834                  * CLEAN buffer, check to see if it is ok to use an EMPTY
 1835                  * buffer.  We can only use an EMPTY buffer if allocating
 1836                  * its KVA would not otherwise run us out of buffer space.
 1837                  */
 1838                 if (nbp == NULL && defrag == 0 &&
 1839                     bufspace + maxsize < hibufspace) {
 1840                         nqindex = QUEUE_EMPTY;
 1841                         nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
 1842                 }
 1843         }
 1844 
 1845         /*
 1846          * Run scan, possibly freeing data and/or kva mappings on the fly
 1847          * depending.
 1848          */
 1849 
 1850         while ((bp = nbp) != NULL) {
 1851                 int qindex = nqindex;
 1852 
 1853                 /*
 1854                  * Calculate next bp ( we can only use it if we do not block
 1855                  * or do other fancy things ).
 1856                  */
 1857                 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
 1858                         switch(qindex) {
 1859                         case QUEUE_EMPTY:
 1860                                 nqindex = QUEUE_EMPTYKVA;
 1861                                 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
 1862                                         break;
 1863                                 /* FALLTHROUGH */
 1864                         case QUEUE_EMPTYKVA:
 1865                                 nqindex = QUEUE_CLEAN;
 1866                                 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
 1867                                         break;
 1868                                 /* FALLTHROUGH */
 1869                         case QUEUE_CLEAN:
 1870                                 /*
 1871                                  * nbp is NULL. 
 1872                                  */
 1873                                 break;
 1874                         }
 1875                 }
 1876                 /*
 1877                  * If we are defragging then we need a buffer with 
 1878                  * b_kvasize != 0.  XXX this situation should no longer
 1879                  * occur, if defrag is non-zero the buffer's b_kvasize
 1880                  * should also be non-zero at this point.  XXX
 1881                  */
 1882                 if (defrag && bp->b_kvasize == 0) {
 1883                         printf("Warning: defrag empty buffer %p\n", bp);
 1884                         continue;
 1885                 }
 1886 
 1887                 /*
 1888                  * Start freeing the bp.  This is somewhat involved.  nbp
 1889                  * remains valid only for QUEUE_EMPTY[KVA] bp's.
 1890                  */
 1891                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
 1892                         continue;
 1893                 if (bp->b_vp) {
 1894                         BO_LOCK(bp->b_bufobj);
 1895                         if (bp->b_vflags & BV_BKGRDINPROG) {
 1896                                 BO_UNLOCK(bp->b_bufobj);
 1897                                 BUF_UNLOCK(bp);
 1898                                 continue;
 1899                         }
 1900                         BO_UNLOCK(bp->b_bufobj);
 1901                 }
 1902                 CTR6(KTR_BUF,
 1903                     "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
 1904                     "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
 1905                     bp->b_kvasize, bp->b_bufsize, qindex);
 1906 
 1907                 /*
 1908                  * Sanity Checks
 1909                  */
 1910                 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
 1911 
 1912                 /*
 1913                  * Note: we no longer distinguish between VMIO and non-VMIO
 1914                  * buffers.
 1915                  */
 1916 
 1917                 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
 1918 
 1919                 if (bp->b_bufobj != NULL)
 1920                         BO_LOCK(bp->b_bufobj);
 1921                 bremfreel(bp);
 1922                 if (bp->b_bufobj != NULL)
 1923                         BO_UNLOCK(bp->b_bufobj);
 1924                 mtx_unlock(&bqlock);
 1925 
 1926                 if (qindex == QUEUE_CLEAN) {
 1927                         if (bp->b_flags & B_VMIO) {
 1928                                 bp->b_flags &= ~B_ASYNC;
 1929                                 vfs_vmio_release(bp);
 1930                         }
 1931                         if (bp->b_vp)
 1932                                 brelvp(bp);
 1933                 }
 1934 
 1935                 /*
 1936                  * NOTE:  nbp is now entirely invalid.  We can only restart
 1937                  * the scan from this point on.
 1938                  *
 1939                  * Get the rest of the buffer freed up.  b_kva* is still
 1940                  * valid after this operation.
 1941                  */
 1942 
 1943                 if (bp->b_rcred != NOCRED) {
 1944                         crfree(bp->b_rcred);
 1945                         bp->b_rcred = NOCRED;
 1946                 }
 1947                 if (bp->b_wcred != NOCRED) {
 1948                         crfree(bp->b_wcred);
 1949                         bp->b_wcred = NOCRED;
 1950                 }
 1951                 if (!LIST_EMPTY(&bp->b_dep))
 1952                         buf_deallocate(bp);
 1953                 if (bp->b_vflags & BV_BKGRDINPROG)
 1954                         panic("losing buffer 3");
 1955                 KASSERT(bp->b_vp == NULL,
 1956                     ("bp: %p still has vnode %p.  qindex: %d",
 1957                     bp, bp->b_vp, qindex));
 1958                 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
 1959                    ("bp: %p still on a buffer list. xflags %X",
 1960                     bp, bp->b_xflags));
 1961 
 1962                 if (bp->b_bufsize)
 1963                         allocbuf(bp, 0);
 1964 
 1965                 bp->b_flags = 0;
 1966                 bp->b_ioflags = 0;
 1967                 bp->b_xflags = 0;
 1968                 KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
 1969                     ("buf %p still counted as free?", bp));
 1970                 bp->b_vflags = 0;
 1971                 bp->b_vp = NULL;
 1972                 bp->b_blkno = bp->b_lblkno = 0;
 1973                 bp->b_offset = NOOFFSET;
 1974                 bp->b_iodone = 0;
 1975                 bp->b_error = 0;
 1976                 bp->b_resid = 0;
 1977                 bp->b_bcount = 0;
 1978                 bp->b_npages = 0;
 1979                 bp->b_dirtyoff = bp->b_dirtyend = 0;
 1980                 bp->b_bufobj = NULL;
 1981                 bp->b_pin_count = 0;
 1982                 bp->b_fsprivate1 = NULL;
 1983                 bp->b_fsprivate2 = NULL;
 1984                 bp->b_fsprivate3 = NULL;
 1985 
 1986                 LIST_INIT(&bp->b_dep);
 1987 
 1988                 /*
 1989                  * If we are defragging then free the buffer.
 1990                  */
 1991                 if (defrag) {
 1992                         bp->b_flags |= B_INVAL;
 1993                         bfreekva(bp);
 1994                         brelse(bp);
 1995                         defrag = 0;
 1996                         goto restart;
 1997                 }
 1998 
 1999                 /*
 2000                  * Notify any waiters for the buffer lock about
 2001                  * identity change by freeing the buffer.
 2002                  */
 2003                 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
 2004                         bp->b_flags |= B_INVAL;
 2005                         bfreekva(bp);
 2006                         brelse(bp);
 2007                         goto restart;
 2008                 }
 2009 
 2010                 /*
 2011                  * If we are overcomitted then recover the buffer and its
 2012                  * KVM space.  This occurs in rare situations when multiple
 2013                  * processes are blocked in getnewbuf() or allocbuf().
 2014                  */
 2015                 if (bufspace >= hibufspace)
 2016                         flushingbufs = 1;
 2017                 if (flushingbufs && bp->b_kvasize != 0) {
 2018                         bp->b_flags |= B_INVAL;
 2019                         bfreekva(bp);
 2020                         brelse(bp);
 2021                         goto restart;
 2022                 }
 2023                 if (bufspace < lobufspace)
 2024                         flushingbufs = 0;
 2025                 break;
 2026         }
 2027 
 2028         /*
 2029          * If we exhausted our list, sleep as appropriate.  We may have to
 2030          * wakeup various daemons and write out some dirty buffers.
 2031          *
 2032          * Generally we are sleeping due to insufficient buffer space.
 2033          */
 2034 
 2035         if (bp == NULL) {
 2036                 int flags, norunbuf;
 2037                 char *waitmsg;
 2038                 int fl;
 2039 
 2040                 if (defrag) {
 2041                         flags = VFS_BIO_NEED_BUFSPACE;
 2042                         waitmsg = "nbufkv";
 2043                 } else if (bufspace >= hibufspace) {
 2044                         waitmsg = "nbufbs";
 2045                         flags = VFS_BIO_NEED_BUFSPACE;
 2046                 } else {
 2047                         waitmsg = "newbuf";
 2048                         flags = VFS_BIO_NEED_ANY;
 2049                 }
 2050                 mtx_lock(&nblock);
 2051                 needsbuffer |= flags;
 2052                 mtx_unlock(&nblock);
 2053                 mtx_unlock(&bqlock);
 2054 
 2055                 bd_speedup();   /* heeeelp */
 2056                 if (gbflags & GB_NOWAIT_BD)
 2057                         return (NULL);
 2058 
 2059                 mtx_lock(&nblock);
 2060                 while (needsbuffer & flags) {
 2061                         if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
 2062                                 mtx_unlock(&nblock);
 2063                                 /*
 2064                                  * getblk() is called with a vnode
 2065                                  * locked, and some majority of the
 2066                                  * dirty buffers may as well belong to
 2067                                  * the vnode. Flushing the buffers
 2068                                  * there would make a progress that
 2069                                  * cannot be achieved by the
 2070                                  * buf_daemon, that cannot lock the
 2071                                  * vnode.
 2072                                  */
 2073                                 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
 2074                                     (td->td_pflags & TDP_NORUNNINGBUF);
 2075                                 /* play bufdaemon */
 2076                                 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
 2077                                 fl = buf_do_flush(vp);
 2078                                 td->td_pflags &= norunbuf;
 2079                                 mtx_lock(&nblock);
 2080                                 if (fl != 0)
 2081                                         continue;
 2082                                 if ((needsbuffer & flags) == 0)
 2083                                         break;
 2084                         }
 2085                         if (msleep(&needsbuffer, &nblock,
 2086                             (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
 2087                                 mtx_unlock(&nblock);
 2088                                 return (NULL);
 2089                         }
 2090                 }
 2091                 mtx_unlock(&nblock);
 2092         } else {
 2093                 /*
 2094                  * We finally have a valid bp.  We aren't quite out of the
 2095                  * woods, we still have to reserve kva space.  In order
 2096                  * to keep fragmentation sane we only allocate kva in
 2097                  * BKVASIZE chunks.
 2098                  */
 2099                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
 2100 
 2101                 if (maxsize != bp->b_kvasize) {
 2102                         vm_offset_t addr = 0;
 2103 
 2104                         bfreekva(bp);
 2105 
 2106                         vm_map_lock(buffer_map);
 2107                         if (vm_map_findspace(buffer_map,
 2108                                 vm_map_min(buffer_map), maxsize, &addr)) {
 2109                                 /*
 2110                                  * Uh oh.  Buffer map is to fragmented.  We
 2111                                  * must defragment the map.
 2112                                  */
 2113                                 atomic_add_int(&bufdefragcnt, 1);
 2114                                 vm_map_unlock(buffer_map);
 2115                                 defrag = 1;
 2116                                 bp->b_flags |= B_INVAL;
 2117                                 brelse(bp);
 2118                                 goto restart;
 2119                         }
 2120                         if (addr) {
 2121                                 vm_map_insert(buffer_map, NULL, 0,
 2122                                         addr, addr + maxsize,
 2123                                         VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
 2124 
 2125                                 bp->b_kvabase = (caddr_t) addr;
 2126                                 bp->b_kvasize = maxsize;
 2127                                 atomic_add_long(&bufspace, bp->b_kvasize);
 2128                                 atomic_add_int(&bufreusecnt, 1);
 2129                         }
 2130                         vm_map_unlock(buffer_map);
 2131                 }
 2132                 bp->b_saveaddr = bp->b_kvabase;
 2133                 bp->b_data = bp->b_saveaddr;
 2134         }
 2135         return(bp);
 2136 }
 2137 
 2138 /*
 2139  *      buf_daemon:
 2140  *
 2141  *      buffer flushing daemon.  Buffers are normally flushed by the
 2142  *      update daemon but if it cannot keep up this process starts to
 2143  *      take the load in an attempt to prevent getnewbuf() from blocking.
 2144  */
 2145 
 2146 static struct kproc_desc buf_kp = {
 2147         "bufdaemon",
 2148         buf_daemon,
 2149         &bufdaemonproc
 2150 };
 2151 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
 2152 
 2153 static int
 2154 buf_do_flush(struct vnode *vp)
 2155 {
 2156         int flushed;
 2157 
 2158         flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
 2159         /* The list empty check here is slightly racy */
 2160         if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
 2161                 mtx_lock(&Giant);
 2162                 flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
 2163                 mtx_unlock(&Giant);
 2164         }
 2165         if (flushed == 0) {
 2166                 /*
 2167                  * Could not find any buffers without rollback
 2168                  * dependencies, so just write the first one
 2169                  * in the hopes of eventually making progress.
 2170                  */
 2171                 flushbufqueues(vp, QUEUE_DIRTY, 1);
 2172                 if (!TAILQ_EMPTY(
 2173                             &bufqueues[QUEUE_DIRTY_GIANT])) {
 2174                         mtx_lock(&Giant);
 2175                         flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
 2176                         mtx_unlock(&Giant);
 2177                 }
 2178         }
 2179         return (flushed);
 2180 }
 2181 
 2182 static void
 2183 buf_daemon()
 2184 {
 2185 
 2186         /*
 2187          * This process needs to be suspended prior to shutdown sync.
 2188          */
 2189         EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
 2190             SHUTDOWN_PRI_LAST);
 2191 
 2192         /*
 2193          * This process is allowed to take the buffer cache to the limit
 2194          */
 2195         curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
 2196         mtx_lock(&bdlock);
 2197         for (;;) {
 2198                 bd_request = 0;
 2199                 mtx_unlock(&bdlock);
 2200 
 2201                 kproc_suspend_check(bufdaemonproc);
 2202 
 2203                 /*
 2204                  * Do the flush.  Limit the amount of in-transit I/O we
 2205                  * allow to build up, otherwise we would completely saturate
 2206                  * the I/O system.  Wakeup any waiting processes before we
 2207                  * normally would so they can run in parallel with our drain.
 2208                  */
 2209                 while (numdirtybuffers > lodirtybuffers) {
 2210                         if (buf_do_flush(NULL) == 0)
 2211                                 break;
 2212                         uio_yield();
 2213                 }
 2214 
 2215                 /*
 2216                  * Only clear bd_request if we have reached our low water
 2217                  * mark.  The buf_daemon normally waits 1 second and
 2218                  * then incrementally flushes any dirty buffers that have
 2219                  * built up, within reason.
 2220                  *
 2221                  * If we were unable to hit our low water mark and couldn't
 2222                  * find any flushable buffers, we sleep half a second.
 2223                  * Otherwise we loop immediately.
 2224                  */
 2225                 mtx_lock(&bdlock);
 2226                 if (numdirtybuffers <= lodirtybuffers) {
 2227                         /*
 2228                          * We reached our low water mark, reset the
 2229                          * request and sleep until we are needed again.
 2230                          * The sleep is just so the suspend code works.
 2231                          */
 2232                         bd_request = 0;
 2233                         msleep(&bd_request, &bdlock, PVM, "psleep", hz);
 2234                 } else {
 2235                         /*
 2236                          * We couldn't find any flushable dirty buffers but
 2237                          * still have too many dirty buffers, we
 2238                          * have to sleep and try again.  (rare)
 2239                          */
 2240                         msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
 2241                 }
 2242         }
 2243 }
 2244 
 2245 /*
 2246  *      flushbufqueues:
 2247  *
 2248  *      Try to flush a buffer in the dirty queue.  We must be careful to
 2249  *      free up B_INVAL buffers instead of write them, which NFS is 
 2250  *      particularly sensitive to.
 2251  */
 2252 static int flushwithdeps = 0;
 2253 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
 2254     0, "Number of buffers flushed with dependecies that require rollbacks");
 2255 
 2256 static int
 2257 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
 2258 {
 2259         struct buf *sentinel;
 2260         struct vnode *vp;
 2261         struct mount *mp;
 2262         struct buf *bp;
 2263         int hasdeps;
 2264         int flushed;
 2265         int target;
 2266 
 2267         if (lvp == NULL) {
 2268                 target = numdirtybuffers - lodirtybuffers;
 2269                 if (flushdeps && target > 2)
 2270                         target /= 2;
 2271         } else
 2272                 target = flushbufqtarget;
 2273         flushed = 0;
 2274         bp = NULL;
 2275         sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
 2276         sentinel->b_qindex = QUEUE_SENTINEL;
 2277         mtx_lock(&bqlock);
 2278         TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
 2279         while (flushed != target) {
 2280                 bp = TAILQ_NEXT(sentinel, b_freelist);
 2281                 if (bp != NULL) {
 2282                         TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
 2283                         TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
 2284                             b_freelist);
 2285                 } else
 2286                         break;
 2287                 /*
 2288                  * Skip sentinels inserted by other invocations of the
 2289                  * flushbufqueues(), taking care to not reorder them.
 2290                  */
 2291                 if (bp->b_qindex == QUEUE_SENTINEL)
 2292                         continue;
 2293                 /*
 2294                  * Only flush the buffers that belong to the
 2295                  * vnode locked by the curthread.
 2296                  */
 2297                 if (lvp != NULL && bp->b_vp != lvp)
 2298                         continue;
 2299                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
 2300                         continue;
 2301                 if (bp->b_pin_count > 0) {
 2302                         BUF_UNLOCK(bp);
 2303                         continue;
 2304                 }
 2305                 BO_LOCK(bp->b_bufobj);
 2306                 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
 2307                     (bp->b_flags & B_DELWRI) == 0) {
 2308                         BO_UNLOCK(bp->b_bufobj);
 2309                         BUF_UNLOCK(bp);
 2310                         continue;
 2311                 }
 2312                 BO_UNLOCK(bp->b_bufobj);
 2313                 if (bp->b_flags & B_INVAL) {
 2314                         bremfreel(bp);
 2315                         mtx_unlock(&bqlock);
 2316                         brelse(bp);
 2317                         flushed++;
 2318                         numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
 2319                         mtx_lock(&bqlock);
 2320                         continue;
 2321                 }
 2322 
 2323                 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
 2324                         if (flushdeps == 0) {
 2325                                 BUF_UNLOCK(bp);
 2326                                 continue;
 2327                         }
 2328                         hasdeps = 1;
 2329                 } else
 2330                         hasdeps = 0;
 2331                 /*
 2332                  * We must hold the lock on a vnode before writing
 2333                  * one of its buffers. Otherwise we may confuse, or
 2334                  * in the case of a snapshot vnode, deadlock the
 2335                  * system.
 2336                  *
 2337                  * The lock order here is the reverse of the normal
 2338                  * of vnode followed by buf lock.  This is ok because
 2339                  * the NOWAIT will prevent deadlock.
 2340                  */
 2341                 vp = bp->b_vp;
 2342                 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
 2343                         BUF_UNLOCK(bp);
 2344                         continue;
 2345                 }
 2346                 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
 2347                         mtx_unlock(&bqlock);
 2348                         CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
 2349                             bp, bp->b_vp, bp->b_flags);
 2350                         if (curproc == bufdaemonproc)
 2351                                 vfs_bio_awrite(bp);
 2352                         else {
 2353                                 bremfree(bp);
 2354                                 bwrite(bp);
 2355                                 notbufdflashes++;
 2356                         }
 2357                         vn_finished_write(mp);
 2358                         VOP_UNLOCK(vp, 0);
 2359                         flushwithdeps += hasdeps;
 2360                         flushed++;
 2361 
 2362                         /*
 2363                          * Sleeping on runningbufspace while holding
 2364                          * vnode lock leads to deadlock.
 2365                          */
 2366                         if (curproc == bufdaemonproc)
 2367                                 waitrunningbufspace();
 2368                         numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
 2369                         mtx_lock(&bqlock);
 2370                         continue;
 2371                 }
 2372                 vn_finished_write(mp);
 2373                 BUF_UNLOCK(bp);
 2374         }
 2375         TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
 2376         mtx_unlock(&bqlock);
 2377         free(sentinel, M_TEMP);
 2378         return (flushed);
 2379 }
 2380 
 2381 /*
 2382  * Check to see if a block is currently memory resident.
 2383  */
 2384 struct buf *
 2385 incore(struct bufobj *bo, daddr_t blkno)
 2386 {
 2387         struct buf *bp;
 2388 
 2389         BO_LOCK(bo);
 2390         bp = gbincore(bo, blkno);
 2391         BO_UNLOCK(bo);
 2392         return (bp);
 2393 }
 2394 
 2395 /*
 2396  * Returns true if no I/O is needed to access the
 2397  * associated VM object.  This is like incore except
 2398  * it also hunts around in the VM system for the data.
 2399  */
 2400 
 2401 static int
 2402 inmem(struct vnode * vp, daddr_t blkno)
 2403 {
 2404         vm_object_t obj;
 2405         vm_offset_t toff, tinc, size;
 2406         vm_page_t m;
 2407         vm_ooffset_t off;
 2408 
 2409         ASSERT_VOP_LOCKED(vp, "inmem");
 2410 
 2411         if (incore(&vp->v_bufobj, blkno))
 2412                 return 1;
 2413         if (vp->v_mount == NULL)
 2414                 return 0;
 2415         obj = vp->v_object;
 2416         if (obj == NULL)
 2417                 return (0);
 2418 
 2419         size = PAGE_SIZE;
 2420         if (size > vp->v_mount->mnt_stat.f_iosize)
 2421                 size = vp->v_mount->mnt_stat.f_iosize;
 2422         off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
 2423 
 2424         VM_OBJECT_LOCK(obj);
 2425         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
 2426                 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
 2427                 if (!m)
 2428                         goto notinmem;
 2429                 tinc = size;
 2430                 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
 2431                         tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
 2432                 if (vm_page_is_valid(m,
 2433                     (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
 2434                         goto notinmem;
 2435         }
 2436         VM_OBJECT_UNLOCK(obj);
 2437         return 1;
 2438 
 2439 notinmem:
 2440         VM_OBJECT_UNLOCK(obj);
 2441         return (0);
 2442 }
 2443 
 2444 /*
 2445  * Set the dirty range for a buffer based on the status of the dirty
 2446  * bits in the pages comprising the buffer.  The range is limited
 2447  * to the size of the buffer.
 2448  *
 2449  * Tell the VM system that the pages associated with this buffer
 2450  * are clean.  This is used for delayed writes where the data is
 2451  * going to go to disk eventually without additional VM intevention.
 2452  *
 2453  * Note that while we only really need to clean through to b_bcount, we
 2454  * just go ahead and clean through to b_bufsize.
 2455  */
 2456 static void
 2457 vfs_clean_pages_dirty_buf(struct buf *bp)
 2458 {
 2459         vm_ooffset_t foff, noff, eoff;
 2460         vm_page_t m;
 2461         int i;
 2462 
 2463         if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
 2464                 return;
 2465 
 2466         foff = bp->b_offset;
 2467         KASSERT(bp->b_offset != NOOFFSET,
 2468             ("vfs_clean_pages_dirty_buf: no buffer offset"));
 2469 
 2470         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
 2471         vfs_drain_busy_pages(bp);
 2472         vfs_setdirty_locked_object(bp);
 2473         vm_page_lock_queues();
 2474         for (i = 0; i < bp->b_npages; i++) {
 2475                 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
 2476                 eoff = noff;
 2477                 if (eoff > bp->b_offset + bp->b_bufsize)
 2478                         eoff = bp->b_offset + bp->b_bufsize;
 2479                 m = bp->b_pages[i];
 2480                 vfs_page_set_validclean(bp, foff, m);
 2481                 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
 2482                 foff = noff;
 2483         }
 2484         vm_page_unlock_queues();
 2485         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
 2486 }
 2487 
 2488 static void
 2489 vfs_setdirty_locked_object(struct buf *bp)
 2490 {
 2491         vm_object_t object;
 2492         int i;
 2493 
 2494         object = bp->b_bufobj->bo_object;
 2495         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 2496 
 2497         /*
 2498          * We qualify the scan for modified pages on whether the
 2499          * object has been flushed yet.
 2500          */
 2501         if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
 2502                 vm_offset_t boffset;
 2503                 vm_offset_t eoffset;
 2504 
 2505                 vm_page_lock_queues();
 2506                 /*
 2507                  * test the pages to see if they have been modified directly
 2508                  * by users through the VM system.
 2509                  */
 2510                 for (i = 0; i < bp->b_npages; i++)
 2511                         vm_page_test_dirty(bp->b_pages[i]);
 2512 
 2513                 /*
 2514                  * Calculate the encompassing dirty range, boffset and eoffset,
 2515                  * (eoffset - boffset) bytes.
 2516                  */
 2517 
 2518                 for (i = 0; i < bp->b_npages; i++) {
 2519                         if (bp->b_pages[i]->dirty)
 2520                                 break;
 2521                 }
 2522                 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
 2523 
 2524                 for (i = bp->b_npages - 1; i >= 0; --i) {
 2525                         if (bp->b_pages[i]->dirty) {
 2526                                 break;
 2527                         }
 2528                 }
 2529                 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
 2530 
 2531                 vm_page_unlock_queues();
 2532                 /*
 2533                  * Fit it to the buffer.
 2534                  */
 2535 
 2536                 if (eoffset > bp->b_bcount)
 2537                         eoffset = bp->b_bcount;
 2538 
 2539                 /*
 2540                  * If we have a good dirty range, merge with the existing
 2541                  * dirty range.
 2542                  */
 2543 
 2544                 if (boffset < eoffset) {
 2545                         if (bp->b_dirtyoff > boffset)
 2546                                 bp->b_dirtyoff = boffset;
 2547                         if (bp->b_dirtyend < eoffset)
 2548                                 bp->b_dirtyend = eoffset;
 2549                 }
 2550         }
 2551 }
 2552 
 2553 /*
 2554  *      getblk:
 2555  *
 2556  *      Get a block given a specified block and offset into a file/device.
 2557  *      The buffers B_DONE bit will be cleared on return, making it almost
 2558  *      ready for an I/O initiation.  B_INVAL may or may not be set on 
 2559  *      return.  The caller should clear B_INVAL prior to initiating a
 2560  *      READ.
 2561  *
 2562  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
 2563  *      an existing buffer.
 2564  *
 2565  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
 2566  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
 2567  *      and then cleared based on the backing VM.  If the previous buffer is
 2568  *      non-0-sized but invalid, B_CACHE will be cleared.
 2569  *
 2570  *      If getblk() must create a new buffer, the new buffer is returned with
 2571  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
 2572  *      case it is returned with B_INVAL clear and B_CACHE set based on the
 2573  *      backing VM.
 2574  *
 2575  *      getblk() also forces a bwrite() for any B_DELWRI buffer whos
 2576  *      B_CACHE bit is clear.
 2577  *      
 2578  *      What this means, basically, is that the caller should use B_CACHE to
 2579  *      determine whether the buffer is fully valid or not and should clear
 2580  *      B_INVAL prior to issuing a read.  If the caller intends to validate
 2581  *      the buffer by loading its data area with something, the caller needs
 2582  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
 2583  *      the caller should set B_CACHE ( as an optimization ), else the caller
 2584  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
 2585  *      a write attempt or if it was a successfull read.  If the caller 
 2586  *      intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
 2587  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
 2588  */
 2589 struct buf *
 2590 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
 2591     int flags)
 2592 {
 2593         struct buf *bp;
 2594         struct bufobj *bo;
 2595         int error;
 2596 
 2597         CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
 2598         ASSERT_VOP_LOCKED(vp, "getblk");
 2599         if (size > MAXBSIZE)
 2600                 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
 2601 
 2602         bo = &vp->v_bufobj;
 2603 loop:
 2604         /*
 2605          * Block if we are low on buffers.   Certain processes are allowed
 2606          * to completely exhaust the buffer cache.
 2607          *
 2608          * If this check ever becomes a bottleneck it may be better to
 2609          * move it into the else, when gbincore() fails.  At the moment
 2610          * it isn't a problem.
 2611          *
 2612          * XXX remove if 0 sections (clean this up after its proven)
 2613          */
 2614         if (numfreebuffers == 0) {
 2615                 if (TD_IS_IDLETHREAD(curthread))
 2616                         return NULL;
 2617                 mtx_lock(&nblock);
 2618                 needsbuffer |= VFS_BIO_NEED_ANY;
 2619                 mtx_unlock(&nblock);
 2620         }
 2621 
 2622         BO_LOCK(bo);
 2623         bp = gbincore(bo, blkno);
 2624         if (bp != NULL) {
 2625                 int lockflags;
 2626                 /*
 2627                  * Buffer is in-core.  If the buffer is not busy, it must
 2628                  * be on a queue.
 2629                  */
 2630                 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
 2631 
 2632                 if (flags & GB_LOCK_NOWAIT)
 2633                         lockflags |= LK_NOWAIT;
 2634 
 2635                 error = BUF_TIMELOCK(bp, lockflags,
 2636                     BO_MTX(bo), "getblk", slpflag, slptimeo);
 2637 
 2638                 /*
 2639                  * If we slept and got the lock we have to restart in case
 2640                  * the buffer changed identities.
 2641                  */
 2642                 if (error == ENOLCK)
 2643                         goto loop;
 2644                 /* We timed out or were interrupted. */
 2645                 else if (error)
 2646                         return (NULL);
 2647 
 2648                 /*
 2649                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
 2650                  * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
 2651                  * and for a VMIO buffer B_CACHE is adjusted according to the
 2652                  * backing VM cache.
 2653                  */
 2654                 if (bp->b_flags & B_INVAL)
 2655                         bp->b_flags &= ~B_CACHE;
 2656                 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
 2657                         bp->b_flags |= B_CACHE;
 2658                 BO_LOCK(bo);
 2659                 bremfree(bp);
 2660                 BO_UNLOCK(bo);
 2661 
 2662                 /*
 2663                  * check for size inconsistancies for non-VMIO case.
 2664                  */
 2665 
 2666                 if (bp->b_bcount != size) {
 2667                         if ((bp->b_flags & B_VMIO) == 0 ||
 2668                             (size > bp->b_kvasize)) {
 2669                                 if (bp->b_flags & B_DELWRI) {
 2670                                         /*
 2671                                          * If buffer is pinned and caller does
 2672                                          * not want sleep  waiting for it to be
 2673                                          * unpinned, bail out
 2674                                          * */
 2675                                         if (bp->b_pin_count > 0) {
 2676                                                 if (flags & GB_LOCK_NOWAIT) {
 2677                                                         bqrelse(bp);
 2678                                                         return (NULL);
 2679                                                 } else {
 2680                                                         bunpin_wait(bp);
 2681                                                 }
 2682                                         }
 2683                                         bp->b_flags |= B_NOCACHE;
 2684                                         bwrite(bp);
 2685                                 } else {
 2686                                         if (LIST_EMPTY(&bp->b_dep)) {
 2687                                                 bp->b_flags |= B_RELBUF;
 2688                                                 brelse(bp);
 2689                                         } else {
 2690                                                 bp->b_flags |= B_NOCACHE;
 2691                                                 bwrite(bp);
 2692                                         }
 2693                                 }
 2694                                 goto loop;
 2695                         }
 2696                 }
 2697 
 2698                 /*
 2699                  * If the size is inconsistant in the VMIO case, we can resize
 2700                  * the buffer.  This might lead to B_CACHE getting set or
 2701                  * cleared.  If the size has not changed, B_CACHE remains
 2702                  * unchanged from its previous state.
 2703                  */
 2704 
 2705                 if (bp->b_bcount != size)
 2706                         allocbuf(bp, size);
 2707 
 2708                 KASSERT(bp->b_offset != NOOFFSET, 
 2709                     ("getblk: no buffer offset"));
 2710 
 2711                 /*
 2712                  * A buffer with B_DELWRI set and B_CACHE clear must
 2713                  * be committed before we can return the buffer in
 2714                  * order to prevent the caller from issuing a read
 2715                  * ( due to B_CACHE not being set ) and overwriting
 2716                  * it.
 2717                  *
 2718                  * Most callers, including NFS and FFS, need this to
 2719                  * operate properly either because they assume they
 2720                  * can issue a read if B_CACHE is not set, or because
 2721                  * ( for example ) an uncached B_DELWRI might loop due 
 2722                  * to softupdates re-dirtying the buffer.  In the latter
 2723                  * case, B_CACHE is set after the first write completes,
 2724                  * preventing further loops.
 2725                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
 2726                  * above while extending the buffer, we cannot allow the
 2727                  * buffer to remain with B_CACHE set after the write
 2728                  * completes or it will represent a corrupt state.  To
 2729                  * deal with this we set B_NOCACHE to scrap the buffer
 2730                  * after the write.
 2731                  *
 2732                  * We might be able to do something fancy, like setting
 2733                  * B_CACHE in bwrite() except if B_DELWRI is already set,
 2734                  * so the below call doesn't set B_CACHE, but that gets real
 2735                  * confusing.  This is much easier.
 2736                  */
 2737 
 2738                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
 2739                         bp->b_flags |= B_NOCACHE;
 2740                         bwrite(bp);
 2741                         goto loop;
 2742                 }
 2743                 bp->b_flags &= ~B_DONE;
 2744         } else {
 2745                 int bsize, maxsize, vmio;
 2746                 off_t offset;
 2747 
 2748                 /*
 2749                  * Buffer is not in-core, create new buffer.  The buffer
 2750                  * returned by getnewbuf() is locked.  Note that the returned
 2751                  * buffer is also considered valid (not marked B_INVAL).
 2752                  */
 2753                 BO_UNLOCK(bo);
 2754                 /*
 2755                  * If the user does not want us to create the buffer, bail out
 2756                  * here.
 2757                  */
 2758                 if (flags & GB_NOCREAT)
 2759                         return NULL;
 2760                 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
 2761                 offset = blkno * bsize;
 2762                 vmio = vp->v_object != NULL;
 2763                 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
 2764                 maxsize = imax(maxsize, bsize);
 2765 
 2766                 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
 2767                 if (bp == NULL) {
 2768                         if (slpflag || slptimeo)
 2769                                 return NULL;
 2770                         goto loop;
 2771                 }
 2772 
 2773                 /*
 2774                  * This code is used to make sure that a buffer is not
 2775                  * created while the getnewbuf routine is blocked.
 2776                  * This can be a problem whether the vnode is locked or not.
 2777                  * If the buffer is created out from under us, we have to
 2778                  * throw away the one we just created.
 2779                  *
 2780                  * Note: this must occur before we associate the buffer
 2781                  * with the vp especially considering limitations in
 2782                  * the splay tree implementation when dealing with duplicate
 2783                  * lblkno's.
 2784                  */
 2785                 BO_LOCK(bo);
 2786                 if (gbincore(bo, blkno)) {
 2787                         BO_UNLOCK(bo);
 2788                         bp->b_flags |= B_INVAL;
 2789                         brelse(bp);
 2790                         goto loop;
 2791                 }
 2792 
 2793                 /*
 2794                  * Insert the buffer into the hash, so that it can
 2795                  * be found by incore.
 2796                  */
 2797                 bp->b_blkno = bp->b_lblkno = blkno;
 2798                 bp->b_offset = offset;
 2799                 bgetvp(vp, bp);
 2800                 BO_UNLOCK(bo);
 2801 
 2802                 /*
 2803                  * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
 2804                  * buffer size starts out as 0, B_CACHE will be set by
 2805                  * allocbuf() for the VMIO case prior to it testing the
 2806                  * backing store for validity.
 2807                  */
 2808 
 2809                 if (vmio) {
 2810                         bp->b_flags |= B_VMIO;
 2811 #if defined(VFS_BIO_DEBUG)
 2812                         if (vn_canvmio(vp) != TRUE)
 2813                                 printf("getblk: VMIO on vnode type %d\n",
 2814                                         vp->v_type);
 2815 #endif
 2816                         KASSERT(vp->v_object == bp->b_bufobj->bo_object,
 2817                             ("ARGH! different b_bufobj->bo_object %p %p %p\n",
 2818                             bp, vp->v_object, bp->b_bufobj->bo_object));
 2819                 } else {
 2820                         bp->b_flags &= ~B_VMIO;
 2821                         KASSERT(bp->b_bufobj->bo_object == NULL,
 2822                             ("ARGH! has b_bufobj->bo_object %p %p\n",
 2823                             bp, bp->b_bufobj->bo_object));
 2824                 }
 2825 
 2826                 allocbuf(bp, size);
 2827                 bp->b_flags &= ~B_DONE;
 2828         }
 2829         CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
 2830         BUF_ASSERT_HELD(bp);
 2831         KASSERT(bp->b_bufobj == bo,
 2832             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
 2833         return (bp);
 2834 }
 2835 
 2836 /*
 2837  * Get an empty, disassociated buffer of given size.  The buffer is initially
 2838  * set to B_INVAL.
 2839  */
 2840 struct buf *
 2841 geteblk(int size, int flags)
 2842 {
 2843         struct buf *bp;
 2844         int maxsize;
 2845 
 2846         maxsize = (size + BKVAMASK) & ~BKVAMASK;
 2847         while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
 2848                 if ((flags & GB_NOWAIT_BD) &&
 2849                     (curthread->td_pflags & TDP_BUFNEED) != 0)
 2850                         return (NULL);
 2851         }
 2852         allocbuf(bp, size);
 2853         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
 2854         BUF_ASSERT_HELD(bp);
 2855         return (bp);
 2856 }
 2857 
 2858 
 2859 /*
 2860  * This code constitutes the buffer memory from either anonymous system
 2861  * memory (in the case of non-VMIO operations) or from an associated
 2862  * VM object (in the case of VMIO operations).  This code is able to
 2863  * resize a buffer up or down.
 2864  *
 2865  * Note that this code is tricky, and has many complications to resolve
 2866  * deadlock or inconsistant data situations.  Tread lightly!!! 
 2867  * There are B_CACHE and B_DELWRI interactions that must be dealt with by 
 2868  * the caller.  Calling this code willy nilly can result in the loss of data.
 2869  *
 2870  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
 2871  * B_CACHE for the non-VMIO case.
 2872  */
 2873 
 2874 int
 2875 allocbuf(struct buf *bp, int size)
 2876 {
 2877         int newbsize, mbsize;
 2878         int i;
 2879 
 2880         BUF_ASSERT_HELD(bp);
 2881 
 2882         if (bp->b_kvasize < size)
 2883                 panic("allocbuf: buffer too small");
 2884 
 2885         if ((bp->b_flags & B_VMIO) == 0) {
 2886                 caddr_t origbuf;
 2887                 int origbufsize;
 2888                 /*
 2889                  * Just get anonymous memory from the kernel.  Don't
 2890                  * mess with B_CACHE.
 2891                  */
 2892                 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
 2893                 if (bp->b_flags & B_MALLOC)
 2894                         newbsize = mbsize;
 2895                 else
 2896                         newbsize = round_page(size);
 2897 
 2898                 if (newbsize < bp->b_bufsize) {
 2899                         /*
 2900                          * malloced buffers are not shrunk
 2901                          */
 2902                         if (bp->b_flags & B_MALLOC) {
 2903                                 if (newbsize) {
 2904                                         bp->b_bcount = size;
 2905                                 } else {
 2906                                         free(bp->b_data, M_BIOBUF);
 2907                                         if (bp->b_bufsize) {
 2908                                                 atomic_subtract_long(
 2909                                                     &bufmallocspace,
 2910                                                     bp->b_bufsize);
 2911                                                 bufspacewakeup();
 2912                                                 bp->b_bufsize = 0;
 2913                                         }
 2914                                         bp->b_saveaddr = bp->b_kvabase;
 2915                                         bp->b_data = bp->b_saveaddr;
 2916                                         bp->b_bcount = 0;
 2917                                         bp->b_flags &= ~B_MALLOC;
 2918                                 }
 2919                                 return 1;
 2920                         }               
 2921                         vm_hold_free_pages(bp, newbsize);
 2922                 } else if (newbsize > bp->b_bufsize) {
 2923                         /*
 2924                          * We only use malloced memory on the first allocation.
 2925                          * and revert to page-allocated memory when the buffer
 2926                          * grows.
 2927                          */
 2928                         /*
 2929                          * There is a potential smp race here that could lead
 2930                          * to bufmallocspace slightly passing the max.  It
 2931                          * is probably extremely rare and not worth worrying
 2932                          * over.
 2933                          */
 2934                         if ( (bufmallocspace < maxbufmallocspace) &&
 2935                                 (bp->b_bufsize == 0) &&
 2936                                 (mbsize <= PAGE_SIZE/2)) {
 2937 
 2938                                 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
 2939                                 bp->b_bufsize = mbsize;
 2940                                 bp->b_bcount = size;
 2941                                 bp->b_flags |= B_MALLOC;
 2942                                 atomic_add_long(&bufmallocspace, mbsize);
 2943                                 return 1;
 2944                         }
 2945                         origbuf = NULL;
 2946                         origbufsize = 0;
 2947                         /*
 2948                          * If the buffer is growing on its other-than-first allocation,
 2949                          * then we revert to the page-allocation scheme.
 2950                          */
 2951                         if (bp->b_flags & B_MALLOC) {
 2952                                 origbuf = bp->b_data;
 2953                                 origbufsize = bp->b_bufsize;
 2954                                 bp->b_data = bp->b_kvabase;
 2955                                 if (bp->b_bufsize) {
 2956                                         atomic_subtract_long(&bufmallocspace,
 2957                                             bp->b_bufsize);
 2958                                         bufspacewakeup();
 2959                                         bp->b_bufsize = 0;
 2960                                 }
 2961                                 bp->b_flags &= ~B_MALLOC;
 2962                                 newbsize = round_page(newbsize);
 2963                         }
 2964                         vm_hold_load_pages(
 2965                             bp,
 2966                             (vm_offset_t) bp->b_data + bp->b_bufsize,
 2967                             (vm_offset_t) bp->b_data + newbsize);
 2968                         if (origbuf) {
 2969                                 bcopy(origbuf, bp->b_data, origbufsize);
 2970                                 free(origbuf, M_BIOBUF);
 2971                         }
 2972                 }
 2973         } else {
 2974                 int desiredpages;
 2975 
 2976                 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
 2977                 desiredpages = (size == 0) ? 0 :
 2978                         num_pages((bp->b_offset & PAGE_MASK) + newbsize);
 2979 
 2980                 if (bp->b_flags & B_MALLOC)
 2981                         panic("allocbuf: VMIO buffer can't be malloced");
 2982                 /*
 2983                  * Set B_CACHE initially if buffer is 0 length or will become
 2984                  * 0-length.
 2985                  */
 2986                 if (size == 0 || bp->b_bufsize == 0)
 2987                         bp->b_flags |= B_CACHE;
 2988 
 2989                 if (newbsize < bp->b_bufsize) {
 2990                         /*
 2991                          * DEV_BSIZE aligned new buffer size is less then the
 2992                          * DEV_BSIZE aligned existing buffer size.  Figure out
 2993                          * if we have to remove any pages.
 2994                          */
 2995                         if (desiredpages < bp->b_npages) {
 2996                                 vm_page_t m;
 2997 
 2998                                 pmap_qremove((vm_offset_t)trunc_page(
 2999                                     (vm_offset_t)bp->b_data) +
 3000                                     (desiredpages << PAGE_SHIFT),
 3001                                     (bp->b_npages - desiredpages));
 3002                                 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
 3003                                 vm_page_lock_queues();
 3004                                 for (i = desiredpages; i < bp->b_npages; i++) {
 3005                                         /*
 3006                                          * the page is not freed here -- it
 3007                                          * is the responsibility of 
 3008                                          * vnode_pager_setsize
 3009                                          */
 3010                                         m = bp->b_pages[i];
 3011                                         KASSERT(m != bogus_page,
 3012                                             ("allocbuf: bogus page found"));
 3013                                         while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
 3014                                                 vm_page_lock_queues();
 3015 
 3016                                         bp->b_pages[i] = NULL;
 3017                                         vm_page_unwire(m, 0);
 3018                                 }
 3019                                 vm_page_unlock_queues();
 3020                                 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
 3021                                 bp->b_npages = desiredpages;
 3022                         }
 3023                 } else if (size > bp->b_bcount) {
 3024                         /*
 3025                          * We are growing the buffer, possibly in a 
 3026                          * byte-granular fashion.
 3027                          */
 3028                         vm_object_t obj;
 3029                         vm_offset_t toff;
 3030                         vm_offset_t tinc;
 3031 
 3032                         /*
 3033                          * Step 1, bring in the VM pages from the object, 
 3034                          * allocating them if necessary.  We must clear
 3035                          * B_CACHE if these pages are not valid for the 
 3036                          * range covered by the buffer.
 3037                          */
 3038 
 3039                         obj = bp->b_bufobj->bo_object;
 3040 
 3041                         VM_OBJECT_LOCK(obj);
 3042                         while (bp->b_npages < desiredpages) {
 3043                                 vm_page_t m;
 3044                                 vm_pindex_t pi;
 3045 
 3046                                 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
 3047                                 if ((m = vm_page_lookup(obj, pi)) == NULL) {
 3048                                         /*
 3049                                          * note: must allocate system pages
 3050                                          * since blocking here could intefere
 3051                                          * with paging I/O, no matter which
 3052                                          * process we are.
 3053                                          */
 3054                                         m = vm_page_alloc(obj, pi,
 3055                                             VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
 3056                                             VM_ALLOC_WIRED);
 3057                                         if (m == NULL) {
 3058                                                 atomic_add_int(&vm_pageout_deficit,
 3059                                                     desiredpages - bp->b_npages);
 3060                                                 VM_OBJECT_UNLOCK(obj);
 3061                                                 VM_WAIT;
 3062                                                 VM_OBJECT_LOCK(obj);
 3063                                         } else {
 3064                                                 if (m->valid == 0)
 3065                                                         bp->b_flags &= ~B_CACHE;
 3066                                                 bp->b_pages[bp->b_npages] = m;
 3067                                                 ++bp->b_npages;
 3068                                         }
 3069                                         continue;
 3070                                 }
 3071 
 3072                                 /*
 3073                                  * We found a page.  If we have to sleep on it,
 3074                                  * retry because it might have gotten freed out
 3075                                  * from under us.
 3076                                  *
 3077                                  * We can only test VPO_BUSY here.  Blocking on
 3078                                  * m->busy might lead to a deadlock:
 3079                                  *
 3080                                  *  vm_fault->getpages->cluster_read->allocbuf
 3081                                  *
 3082                                  */
 3083                                 if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
 3084                                         continue;
 3085 
 3086                                 /*
 3087                                  * We have a good page.
 3088                                  */
 3089                                 vm_page_lock_queues();
 3090                                 vm_page_wire(m);
 3091                                 vm_page_unlock_queues();
 3092                                 bp->b_pages[bp->b_npages] = m;
 3093                                 ++bp->b_npages;
 3094                         }
 3095 
 3096                         /*
 3097                          * Step 2.  We've loaded the pages into the buffer,
 3098                          * we have to figure out if we can still have B_CACHE
 3099                          * set.  Note that B_CACHE is set according to the
 3100                          * byte-granular range ( bcount and size ), new the
 3101                          * aligned range ( newbsize ).
 3102                          *
 3103                          * The VM test is against m->valid, which is DEV_BSIZE
 3104                          * aligned.  Needless to say, the validity of the data
 3105                          * needs to also be DEV_BSIZE aligned.  Note that this
 3106                          * fails with NFS if the server or some other client
 3107                          * extends the file's EOF.  If our buffer is resized, 
 3108                          * B_CACHE may remain set! XXX
 3109                          */
 3110 
 3111                         toff = bp->b_bcount;
 3112                         tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
 3113 
 3114                         while ((bp->b_flags & B_CACHE) && toff < size) {
 3115                                 vm_pindex_t pi;
 3116 
 3117                                 if (tinc > (size - toff))
 3118                                         tinc = size - toff;
 3119 
 3120                                 pi = ((bp->b_offset & PAGE_MASK) + toff) >> 
 3121                                     PAGE_SHIFT;
 3122 
 3123                                 vfs_buf_test_cache(
 3124                                     bp, 
 3125                                     bp->b_offset,
 3126                                     toff, 
 3127                                     tinc, 
 3128                                     bp->b_pages[pi]
 3129                                 );
 3130                                 toff += tinc;
 3131                                 tinc = PAGE_SIZE;
 3132                         }
 3133                         VM_OBJECT_UNLOCK(obj);
 3134 
 3135                         /*
 3136                          * Step 3, fixup the KVM pmap.  Remember that
 3137                          * bp->b_data is relative to bp->b_offset, but 
 3138                          * bp->b_offset may be offset into the first page.
 3139                          */
 3140 
 3141                         bp->b_data = (caddr_t)
 3142                             trunc_page((vm_offset_t)bp->b_data);
 3143                         pmap_qenter(
 3144                             (vm_offset_t)bp->b_data,
 3145                             bp->b_pages, 
 3146                             bp->b_npages
 3147                         );
 3148                         
 3149                         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 
 3150                             (vm_offset_t)(bp->b_offset & PAGE_MASK));
 3151                 }
 3152         }
 3153         if (newbsize < bp->b_bufsize)
 3154                 bufspacewakeup();
 3155         bp->b_bufsize = newbsize;       /* actual buffer allocation     */
 3156         bp->b_bcount = size;            /* requested buffer size        */
 3157         return 1;
 3158 }
 3159 
 3160 void
 3161 biodone(struct bio *bp)
 3162 {
 3163         struct mtx *mtxp;
 3164         void (*done)(struct bio *);
 3165 
 3166         mtxp = mtx_pool_find(mtxpool_sleep, bp);
 3167         mtx_lock(mtxp);
 3168         bp->bio_flags |= BIO_DONE;
 3169         done = bp->bio_done;
 3170         if (done == NULL)
 3171                 wakeup(bp);
 3172         mtx_unlock(mtxp);
 3173         if (done != NULL)
 3174                 done(bp);
 3175 }
 3176 
 3177 /*
 3178  * Wait for a BIO to finish.
 3179  *
 3180  * XXX: resort to a timeout for now.  The optimal locking (if any) for this
 3181  * case is not yet clear.
 3182  */
 3183 int
 3184 biowait(struct bio *bp, const char *wchan)
 3185 {
 3186         struct mtx *mtxp;
 3187 
 3188         mtxp = mtx_pool_find(mtxpool_sleep, bp);
 3189         mtx_lock(mtxp);
 3190         while ((bp->bio_flags & BIO_DONE) == 0)
 3191                 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
 3192         mtx_unlock(mtxp);
 3193         if (bp->bio_error != 0)
 3194                 return (bp->bio_error);
 3195         if (!(bp->bio_flags & BIO_ERROR))
 3196                 return (0);
 3197         return (EIO);
 3198 }
 3199 
 3200 void
 3201 biofinish(struct bio *bp, struct devstat *stat, int error)
 3202 {
 3203         
 3204         if (error) {
 3205                 bp->bio_error = error;
 3206                 bp->bio_flags |= BIO_ERROR;
 3207         }
 3208         if (stat != NULL)
 3209                 devstat_end_transaction_bio(stat, bp);
 3210         biodone(bp);
 3211 }
 3212 
 3213 /*
 3214  *      bufwait:
 3215  *
 3216  *      Wait for buffer I/O completion, returning error status.  The buffer
 3217  *      is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
 3218  *      error and cleared.
 3219  */
 3220 int
 3221 bufwait(struct buf *bp)
 3222 {
 3223         if (bp->b_iocmd == BIO_READ)
 3224                 bwait(bp, PRIBIO, "biord");
 3225         else
 3226                 bwait(bp, PRIBIO, "biowr");
 3227         if (bp->b_flags & B_EINTR) {
 3228                 bp->b_flags &= ~B_EINTR;
 3229                 return (EINTR);
 3230         }
 3231         if (bp->b_ioflags & BIO_ERROR) {
 3232                 return (bp->b_error ? bp->b_error : EIO);
 3233         } else {
 3234                 return (0);
 3235         }
 3236 }
 3237 
 3238  /*
 3239   * Call back function from struct bio back up to struct buf.
 3240   */
 3241 static void
 3242 bufdonebio(struct bio *bip)
 3243 {
 3244         struct buf *bp;
 3245 
 3246         bp = bip->bio_caller2;
 3247         bp->b_resid = bp->b_bcount - bip->bio_completed;
 3248         bp->b_resid = bip->bio_resid;   /* XXX: remove */
 3249         bp->b_ioflags = bip->bio_flags;
 3250         bp->b_error = bip->bio_error;
 3251         if (bp->b_error)
 3252                 bp->b_ioflags |= BIO_ERROR;
 3253         bufdone(bp);
 3254         g_destroy_bio(bip);
 3255 }
 3256 
 3257 void
 3258 dev_strategy(struct cdev *dev, struct buf *bp)
 3259 {
 3260         struct cdevsw *csw;
 3261         struct bio *bip;
 3262         int ref;
 3263 
 3264         if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
 3265                 panic("b_iocmd botch");
 3266         for (;;) {
 3267                 bip = g_new_bio();
 3268                 if (bip != NULL)
 3269                         break;
 3270                 /* Try again later */
 3271                 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
 3272         }
 3273         bip->bio_cmd = bp->b_iocmd;
 3274         bip->bio_offset = bp->b_iooffset;
 3275         bip->bio_length = bp->b_bcount;
 3276         bip->bio_bcount = bp->b_bcount; /* XXX: remove */
 3277         bip->bio_data = bp->b_data;
 3278         bip->bio_done = bufdonebio;
 3279         bip->bio_caller2 = bp;
 3280         bip->bio_dev = dev;
 3281         KASSERT(dev->si_refcount > 0,
 3282             ("dev_strategy on un-referenced struct cdev *(%s)",
 3283             devtoname(dev)));
 3284         csw = dev_refthread(dev, &ref);
 3285         if (csw == NULL) {
 3286                 g_destroy_bio(bip);
 3287                 bp->b_error = ENXIO;
 3288                 bp->b_ioflags = BIO_ERROR;
 3289                 bufdone(bp);
 3290                 return;
 3291         }
 3292         (*csw->d_strategy)(bip);
 3293         dev_relthread(dev, ref);
 3294 }
 3295 
 3296 /*
 3297  *      bufdone:
 3298  *
 3299  *      Finish I/O on a buffer, optionally calling a completion function.
 3300  *      This is usually called from an interrupt so process blocking is
 3301  *      not allowed.
 3302  *
 3303  *      biodone is also responsible for setting B_CACHE in a B_VMIO bp.
 3304  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
 3305  *      assuming B_INVAL is clear.
 3306  *
 3307  *      For the VMIO case, we set B_CACHE if the op was a read and no
 3308  *      read error occured, or if the op was a write.  B_CACHE is never
 3309  *      set if the buffer is invalid or otherwise uncacheable.
 3310  *
 3311  *      biodone does not mess with B_INVAL, allowing the I/O routine or the
 3312  *      initiator to leave B_INVAL set to brelse the buffer out of existance
 3313  *      in the biodone routine.
 3314  */
 3315 void
 3316 bufdone(struct buf *bp)
 3317 {
 3318         struct bufobj *dropobj;
 3319         void    (*biodone)(struct buf *);
 3320 
 3321         CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
 3322         dropobj = NULL;
 3323 
 3324         KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
 3325         BUF_ASSERT_HELD(bp);
 3326 
 3327         runningbufwakeup(bp);
 3328         if (bp->b_iocmd == BIO_WRITE)
 3329                 dropobj = bp->b_bufobj;
 3330         /* call optional completion function if requested */
 3331         if (bp->b_iodone != NULL) {
 3332                 biodone = bp->b_iodone;
 3333                 bp->b_iodone = NULL;
 3334                 (*biodone) (bp);
 3335                 if (dropobj)
 3336                         bufobj_wdrop(dropobj);
 3337                 return;
 3338         }
 3339 
 3340         bufdone_finish(bp);
 3341 
 3342         if (dropobj)
 3343                 bufobj_wdrop(dropobj);
 3344 }
 3345 
 3346 void
 3347 bufdone_finish(struct buf *bp)
 3348 {
 3349         BUF_ASSERT_HELD(bp);
 3350 
 3351         if (!LIST_EMPTY(&bp->b_dep))
 3352                 buf_complete(bp);
 3353 
 3354         if (bp->b_flags & B_VMIO) {
 3355                 int i;
 3356                 vm_ooffset_t foff;
 3357                 vm_page_t m;
 3358                 vm_object_t obj;
 3359                 int bogus, iosize;
 3360                 struct vnode *vp = bp->b_vp;
 3361 
 3362                 obj = bp->b_bufobj->bo_object;
 3363 
 3364 #if defined(VFS_BIO_DEBUG)
 3365                 mp_fixme("usecount and vflag accessed without locks.");
 3366                 if (vp->v_usecount == 0) {
 3367                         panic("biodone: zero vnode ref count");
 3368                 }
 3369 
 3370                 KASSERT(vp->v_object != NULL,
 3371                         ("biodone: vnode %p has no vm_object", vp));
 3372 #endif
 3373 
 3374                 foff = bp->b_offset;
 3375                 KASSERT(bp->b_offset != NOOFFSET,
 3376                     ("biodone: no buffer offset"));
 3377 
 3378                 VM_OBJECT_LOCK(obj);
 3379 #if defined(VFS_BIO_DEBUG)
 3380                 if (obj->paging_in_progress < bp->b_npages) {
 3381                         printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
 3382                             obj->paging_in_progress, bp->b_npages);
 3383                 }
 3384 #endif
 3385 
 3386                 /*
 3387                  * Set B_CACHE if the op was a normal read and no error
 3388                  * occured.  B_CACHE is set for writes in the b*write()
 3389                  * routines.
 3390                  */
 3391                 iosize = bp->b_bcount - bp->b_resid;
 3392                 if (bp->b_iocmd == BIO_READ &&
 3393                     !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
 3394                     !(bp->b_ioflags & BIO_ERROR)) {
 3395                         bp->b_flags |= B_CACHE;
 3396                 }
 3397                 bogus = 0;
 3398                 for (i = 0; i < bp->b_npages; i++) {
 3399                         int bogusflag = 0;
 3400                         int resid;
 3401 
 3402                         resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
 3403                         if (resid > iosize)
 3404                                 resid = iosize;
 3405 
 3406                         /*
 3407                          * cleanup bogus pages, restoring the originals
 3408                          */
 3409                         m = bp->b_pages[i];
 3410                         if (m == bogus_page) {
 3411                                 bogus = bogusflag = 1;
 3412                                 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
 3413                                 if (m == NULL)
 3414                                         panic("biodone: page disappeared!");
 3415                                 bp->b_pages[i] = m;
 3416                         }
 3417 #if defined(VFS_BIO_DEBUG)
 3418                         if (OFF_TO_IDX(foff) != m->pindex) {
 3419                                 printf(
 3420 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
 3421                                     (intmax_t)foff, (uintmax_t)m->pindex);
 3422                         }
 3423 #endif
 3424 
 3425                         /*
 3426                          * In the write case, the valid and clean bits are
 3427                          * already changed correctly ( see bdwrite() ), so we 
 3428                          * only need to do this here in the read case.
 3429                          */
 3430                         if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
 3431                                 KASSERT((m->dirty & vm_page_bits(foff &
 3432                                     PAGE_MASK, resid)) == 0, ("bufdone_finish:"
 3433                                     " page %p has unexpected dirty bits", m));
 3434                                 vfs_page_set_valid(bp, foff, m);
 3435                         }
 3436 
 3437                         /*
 3438                          * when debugging new filesystems or buffer I/O methods, this
 3439                          * is the most common error that pops up.  if you see this, you
 3440                          * have not set the page busy flag correctly!!!
 3441                          */
 3442                         if (m->busy == 0) {
 3443                                 printf("biodone: page busy < 0, "
 3444                                     "pindex: %d, foff: 0x(%x,%x), "
 3445                                     "resid: %d, index: %d\n",
 3446                                     (int) m->pindex, (int)(foff >> 32),
 3447                                                 (int) foff & 0xffffffff, resid, i);
 3448                                 if (!vn_isdisk(vp, NULL))
 3449                                         printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
 3450                                             (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
 3451                                             (intmax_t) bp->b_lblkno,
 3452                                             bp->b_flags, bp->b_npages);
 3453                                 else
 3454                                         printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
 3455                                             (intmax_t) bp->b_lblkno,
 3456                                             bp->b_flags, bp->b_npages);
 3457                                 printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
 3458                                     (u_long)m->valid, (u_long)m->dirty,
 3459                                     m->wire_count);
 3460                                 panic("biodone: page busy < 0\n");
 3461                         }
 3462                         vm_page_io_finish(m);
 3463                         vm_object_pip_subtract(obj, 1);
 3464                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
 3465                         iosize -= resid;
 3466                 }
 3467                 vm_object_pip_wakeupn(obj, 0);
 3468                 VM_OBJECT_UNLOCK(obj);
 3469                 if (bogus)
 3470                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
 3471                             bp->b_pages, bp->b_npages);
 3472         }
 3473 
 3474         /*
 3475          * For asynchronous completions, release the buffer now. The brelse
 3476          * will do a wakeup there if necessary - so no need to do a wakeup
 3477          * here in the async case. The sync case always needs to do a wakeup.
 3478          */
 3479 
 3480         if (bp->b_flags & B_ASYNC) {
 3481                 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
 3482                         brelse(bp);
 3483                 else
 3484                         bqrelse(bp);
 3485         } else
 3486                 bdone(bp);
 3487 }
 3488 
 3489 /*
 3490  * This routine is called in lieu of iodone in the case of
 3491  * incomplete I/O.  This keeps the busy status for pages
 3492  * consistant.
 3493  */
 3494 void
 3495 vfs_unbusy_pages(struct buf *bp)
 3496 {
 3497         int i;
 3498         vm_object_t obj;
 3499         vm_page_t m;
 3500 
 3501         runningbufwakeup(bp);
 3502         if (!(bp->b_flags & B_VMIO))
 3503                 return;
 3504 
 3505         obj = bp->b_bufobj->bo_object;
 3506         VM_OBJECT_LOCK(obj);
 3507         for (i = 0; i < bp->b_npages; i++) {
 3508                 m = bp->b_pages[i];
 3509                 if (m == bogus_page) {
 3510                         m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
 3511                         if (!m)
 3512                                 panic("vfs_unbusy_pages: page missing\n");
 3513                         bp->b_pages[i] = m;
 3514                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
 3515                             bp->b_pages, bp->b_npages);
 3516                 }
 3517                 vm_object_pip_subtract(obj, 1);
 3518                 vm_page_io_finish(m);
 3519         }
 3520         vm_object_pip_wakeupn(obj, 0);
 3521         VM_OBJECT_UNLOCK(obj);
 3522 }
 3523 
 3524 /*
 3525  * vfs_page_set_valid:
 3526  *
 3527  *      Set the valid bits in a page based on the supplied offset.   The
 3528  *      range is restricted to the buffer's size.
 3529  *
 3530  *      This routine is typically called after a read completes.
 3531  */
 3532 static void
 3533 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
 3534 {
 3535         vm_ooffset_t eoff;
 3536 
 3537         /*
 3538          * Compute the end offset, eoff, such that [off, eoff) does not span a
 3539          * page boundary and eoff is not greater than the end of the buffer.
 3540          * The end of the buffer, in this case, is our file EOF, not the
 3541          * allocation size of the buffer.
 3542          */
 3543         eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
 3544         if (eoff > bp->b_offset + bp->b_bcount)
 3545                 eoff = bp->b_offset + bp->b_bcount;
 3546 
 3547         /*
 3548          * Set valid range.  This is typically the entire buffer and thus the
 3549          * entire page.
 3550          */
 3551         if (eoff > off)
 3552                 vm_page_set_valid(m, off & PAGE_MASK, eoff - off);
 3553 }
 3554 
 3555 /*
 3556  * vfs_page_set_validclean:
 3557  *
 3558  *      Set the valid bits and clear the dirty bits in a page based on the
 3559  *      supplied offset.   The range is restricted to the buffer's size.
 3560  */
 3561 static void
 3562 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
 3563 {
 3564         vm_ooffset_t soff, eoff;
 3565 
 3566         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3567         /*
 3568          * Start and end offsets in buffer.  eoff - soff may not cross a
 3569          * page boundry or cross the end of the buffer.  The end of the
 3570          * buffer, in this case, is our file EOF, not the allocation size
 3571          * of the buffer.
 3572          */
 3573         soff = off;
 3574         eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
 3575         if (eoff > bp->b_offset + bp->b_bcount)
 3576                 eoff = bp->b_offset + bp->b_bcount;
 3577 
 3578         /*
 3579          * Set valid range.  This is typically the entire buffer and thus the
 3580          * entire page.
 3581          */
 3582         if (eoff > soff) {
 3583                 vm_page_set_validclean(
 3584                     m,
 3585                    (vm_offset_t) (soff & PAGE_MASK),
 3586                    (vm_offset_t) (eoff - soff)
 3587                 );
 3588         }
 3589 }
 3590 
 3591 /*
 3592  * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
 3593  * any page is busy, drain the flag.
 3594  */
 3595 static void
 3596 vfs_drain_busy_pages(struct buf *bp)
 3597 {
 3598         vm_page_t m;
 3599         int i, last_busied;
 3600 
 3601         VM_OBJECT_LOCK_ASSERT(bp->b_bufobj->bo_object, MA_OWNED);
 3602         last_busied = 0;
 3603         for (i = 0; i < bp->b_npages; i++) {
 3604                 m = bp->b_pages[i];
 3605                 if ((m->oflags & VPO_BUSY) != 0) {
 3606                         for (; last_busied < i; last_busied++)
 3607                                 vm_page_busy(bp->b_pages[last_busied]);
 3608                         while ((m->oflags & VPO_BUSY) != 0)
 3609                                 vm_page_sleep(m, "vbpage");
 3610                 }
 3611         }
 3612         for (i = 0; i < last_busied; i++)
 3613                 vm_page_wakeup(bp->b_pages[i]);
 3614 }
 3615 
 3616 /*
 3617  * This routine is called before a device strategy routine.
 3618  * It is used to tell the VM system that paging I/O is in
 3619  * progress, and treat the pages associated with the buffer
 3620  * almost as being VPO_BUSY.  Also the object paging_in_progress
 3621  * flag is handled to make sure that the object doesn't become
 3622  * inconsistant.
 3623  *
 3624  * Since I/O has not been initiated yet, certain buffer flags
 3625  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
 3626  * and should be ignored.
 3627  */
 3628 void
 3629 vfs_busy_pages(struct buf *bp, int clear_modify)
 3630 {
 3631         int i, bogus;
 3632         vm_object_t obj;
 3633         vm_ooffset_t foff;
 3634         vm_page_t m;
 3635 
 3636         if (!(bp->b_flags & B_VMIO))
 3637                 return;
 3638 
 3639         obj = bp->b_bufobj->bo_object;
 3640         foff = bp->b_offset;
 3641         KASSERT(bp->b_offset != NOOFFSET,
 3642             ("vfs_busy_pages: no buffer offset"));
 3643         VM_OBJECT_LOCK(obj);
 3644         vfs_drain_busy_pages(bp);
 3645         if (bp->b_bufsize != 0)
 3646                 vfs_setdirty_locked_object(bp);
 3647         bogus = 0;
 3648         if (clear_modify)
 3649                 vm_page_lock_queues();
 3650         for (i = 0; i < bp->b_npages; i++) {
 3651                 m = bp->b_pages[i];
 3652 
 3653                 if ((bp->b_flags & B_CLUSTER) == 0) {
 3654                         vm_object_pip_add(obj, 1);
 3655                         vm_page_io_start(m);
 3656                 }
 3657                 /*
 3658                  * When readying a buffer for a read ( i.e
 3659                  * clear_modify == 0 ), it is important to do
 3660                  * bogus_page replacement for valid pages in 
 3661                  * partially instantiated buffers.  Partially 
 3662                  * instantiated buffers can, in turn, occur when
 3663                  * reconstituting a buffer from its VM backing store
 3664                  * base.  We only have to do this if B_CACHE is
 3665                  * clear ( which causes the I/O to occur in the
 3666                  * first place ).  The replacement prevents the read
 3667                  * I/O from overwriting potentially dirty VM-backed
 3668                  * pages.  XXX bogus page replacement is, uh, bogus.
 3669                  * It may not work properly with small-block devices.
 3670                  * We need to find a better way.
 3671                  */
 3672                 if (clear_modify) {
 3673                         pmap_remove_write(m);
 3674                         vfs_page_set_validclean(bp, foff, m);
 3675                 } else if (m->valid == VM_PAGE_BITS_ALL &&
 3676                     (bp->b_flags & B_CACHE) == 0) {
 3677                         bp->b_pages[i] = bogus_page;
 3678                         bogus++;
 3679                 }
 3680                 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
 3681         }
 3682         if (clear_modify)
 3683                 vm_page_unlock_queues();
 3684         VM_OBJECT_UNLOCK(obj);
 3685         if (bogus)
 3686                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
 3687                     bp->b_pages, bp->b_npages);
 3688 }
 3689 
 3690 /*
 3691  *      vfs_bio_set_valid:
 3692  *
 3693  *      Set the range within the buffer to valid.  The range is
 3694  *      relative to the beginning of the buffer, b_offset.  Note that
 3695  *      b_offset itself may be offset from the beginning of the first
 3696  *      page.
 3697  */
 3698 void   
 3699 vfs_bio_set_valid(struct buf *bp, int base, int size)
 3700 {
 3701         int i, n;
 3702         vm_page_t m;
 3703 
 3704         if (!(bp->b_flags & B_VMIO))
 3705                 return;
 3706 
 3707         /*
 3708          * Fixup base to be relative to beginning of first page.
 3709          * Set initial n to be the maximum number of bytes in the
 3710          * first page that can be validated.
 3711          */
 3712         base += (bp->b_offset & PAGE_MASK);
 3713         n = PAGE_SIZE - (base & PAGE_MASK);
 3714 
 3715         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
 3716         for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
 3717                 m = bp->b_pages[i];
 3718                 if (n > size)
 3719                         n = size;
 3720                 vm_page_set_valid(m, base & PAGE_MASK, n);
 3721                 base += n;
 3722                 size -= n;
 3723                 n = PAGE_SIZE;
 3724         }
 3725         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
 3726 }
 3727 
 3728 /*
 3729  *      vfs_bio_clrbuf:
 3730  *
 3731  *      If the specified buffer is a non-VMIO buffer, clear the entire
 3732  *      buffer.  If the specified buffer is a VMIO buffer, clear and
 3733  *      validate only the previously invalid portions of the buffer.
 3734  *      This routine essentially fakes an I/O, so we need to clear
 3735  *      BIO_ERROR and B_INVAL.
 3736  *
 3737  *      Note that while we only theoretically need to clear through b_bcount,
 3738  *      we go ahead and clear through b_bufsize.
 3739  */
 3740 void
 3741 vfs_bio_clrbuf(struct buf *bp) 
 3742 {
 3743         int i, j, mask;
 3744         caddr_t sa, ea;
 3745 
 3746         if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
 3747                 clrbuf(bp);
 3748                 return;
 3749         }
 3750         bp->b_flags &= ~B_INVAL;
 3751         bp->b_ioflags &= ~BIO_ERROR;
 3752         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
 3753         if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
 3754             (bp->b_offset & PAGE_MASK) == 0) {
 3755                 if (bp->b_pages[0] == bogus_page)
 3756                         goto unlock;
 3757                 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
 3758                 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
 3759                 if ((bp->b_pages[0]->valid & mask) == mask)
 3760                         goto unlock;
 3761                 if ((bp->b_pages[0]->valid & mask) == 0) {
 3762                         bzero(bp->b_data, bp->b_bufsize);
 3763                         bp->b_pages[0]->valid |= mask;
 3764                         goto unlock;
 3765                 }
 3766         }
 3767         ea = sa = bp->b_data;
 3768         for(i = 0; i < bp->b_npages; i++, sa = ea) {
 3769                 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
 3770                 ea = (caddr_t)(vm_offset_t)ulmin(
 3771                     (u_long)(vm_offset_t)ea,
 3772                     (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
 3773                 if (bp->b_pages[i] == bogus_page)
 3774                         continue;
 3775                 j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
 3776                 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
 3777                 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
 3778                 if ((bp->b_pages[i]->valid & mask) == mask)
 3779                         continue;
 3780                 if ((bp->b_pages[i]->valid & mask) == 0)
 3781                         bzero(sa, ea - sa);
 3782                 else {
 3783                         for (; sa < ea; sa += DEV_BSIZE, j++) {
 3784                                 if ((bp->b_pages[i]->valid & (1 << j)) == 0)
 3785                                         bzero(sa, DEV_BSIZE);
 3786                         }
 3787                 }
 3788                 bp->b_pages[i]->valid |= mask;
 3789         }
 3790 unlock:
 3791         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
 3792         bp->b_resid = 0;
 3793 }
 3794 
 3795 /*
 3796  * vm_hold_load_pages and vm_hold_free_pages get pages into
 3797  * a buffers address space.  The pages are anonymous and are
 3798  * not associated with a file object.
 3799  */
 3800 static void
 3801 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
 3802 {
 3803         vm_offset_t pg;
 3804         vm_page_t p;
 3805         int index;
 3806 
 3807         to = round_page(to);
 3808         from = round_page(from);
 3809         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
 3810 
 3811         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
 3812 tryagain:
 3813                 /*
 3814                  * note: must allocate system pages since blocking here
 3815                  * could interfere with paging I/O, no matter which
 3816                  * process we are.
 3817                  */
 3818                 p = vm_page_alloc(NULL, pg >> PAGE_SHIFT, VM_ALLOC_NOOBJ |
 3819                     VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
 3820                 if (!p) {
 3821                         atomic_add_int(&vm_pageout_deficit,
 3822                             (to - pg) >> PAGE_SHIFT);
 3823                         VM_WAIT;
 3824                         goto tryagain;
 3825                 }
 3826                 pmap_qenter(pg, &p, 1);
 3827                 bp->b_pages[index] = p;
 3828         }
 3829         bp->b_npages = index;
 3830 }
 3831 
 3832 /* Return pages associated with this buf to the vm system */
 3833 static void
 3834 vm_hold_free_pages(struct buf *bp, int newbsize)
 3835 {
 3836         vm_offset_t from;
 3837         vm_page_t p;
 3838         int index, newnpages;
 3839 
 3840         from = round_page((vm_offset_t)bp->b_data + newbsize);
 3841         newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
 3842         if (bp->b_npages > newnpages)
 3843                 pmap_qremove(from, bp->b_npages - newnpages);
 3844         for (index = newnpages; index < bp->b_npages; index++) {
 3845                 p = bp->b_pages[index];
 3846                 bp->b_pages[index] = NULL;
 3847                 if (p->busy != 0)
 3848                         printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
 3849                             (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
 3850                 p->wire_count--;
 3851                 vm_page_free(p);
 3852                 atomic_subtract_int(&cnt.v_wire_count, 1);
 3853         }
 3854         bp->b_npages = newnpages;
 3855 }
 3856 
 3857 /*
 3858  * Map an IO request into kernel virtual address space.
 3859  *
 3860  * All requests are (re)mapped into kernel VA space.
 3861  * Notice that we use b_bufsize for the size of the buffer
 3862  * to be mapped.  b_bcount might be modified by the driver.
 3863  *
 3864  * Note that even if the caller determines that the address space should
 3865  * be valid, a race or a smaller-file mapped into a larger space may
 3866  * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
 3867  * check the return value.
 3868  */
 3869 int
 3870 vmapbuf(struct buf *bp)
 3871 {
 3872         caddr_t addr, kva;
 3873         vm_prot_t prot;
 3874         int pidx, i;
 3875         struct vm_page *m;
 3876         struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
 3877 
 3878         if (bp->b_bufsize < 0)
 3879                 return (-1);
 3880         prot = VM_PROT_READ;
 3881         if (bp->b_iocmd == BIO_READ)
 3882                 prot |= VM_PROT_WRITE;  /* Less backwards than it looks */
 3883         for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
 3884              addr < bp->b_data + bp->b_bufsize;
 3885              addr += PAGE_SIZE, pidx++) {
 3886                 /*
 3887                  * Do the vm_fault if needed; do the copy-on-write thing
 3888                  * when reading stuff off device into memory.
 3889                  *
 3890                  * NOTE! Must use pmap_extract() because addr may be in
 3891                  * the userland address space, and kextract is only guarenteed
 3892                  * to work for the kernland address space (see: sparc64 port).
 3893                  */
 3894 retry:
 3895                 if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
 3896                     prot) < 0) {
 3897                         vm_page_lock_queues();
 3898                         for (i = 0; i < pidx; ++i) {
 3899                                 vm_page_unhold(bp->b_pages[i]);
 3900                                 bp->b_pages[i] = NULL;
 3901                         }
 3902                         vm_page_unlock_queues();
 3903                         return(-1);
 3904                 }
 3905                 m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
 3906                 if (m == NULL)
 3907                         goto retry;
 3908                 bp->b_pages[pidx] = m;
 3909         }
 3910         if (pidx > btoc(MAXPHYS))
 3911                 panic("vmapbuf: mapped more than MAXPHYS");
 3912         pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
 3913         
 3914         kva = bp->b_saveaddr;
 3915         bp->b_npages = pidx;
 3916         bp->b_saveaddr = bp->b_data;
 3917         bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
 3918         return(0);
 3919 }
 3920 
 3921 /*
 3922  * Free the io map PTEs associated with this IO operation.
 3923  * We also invalidate the TLB entries and restore the original b_addr.
 3924  */
 3925 void
 3926 vunmapbuf(struct buf *bp)
 3927 {
 3928         int pidx;
 3929         int npages;
 3930 
 3931         npages = bp->b_npages;
 3932         pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
 3933         vm_page_lock_queues();
 3934         for (pidx = 0; pidx < npages; pidx++)
 3935                 vm_page_unhold(bp->b_pages[pidx]);
 3936         vm_page_unlock_queues();
 3937 
 3938         bp->b_data = bp->b_saveaddr;
 3939 }
 3940 
 3941 void
 3942 bdone(struct buf *bp)
 3943 {
 3944         struct mtx *mtxp;
 3945 
 3946         mtxp = mtx_pool_find(mtxpool_sleep, bp);
 3947         mtx_lock(mtxp);
 3948         bp->b_flags |= B_DONE;
 3949         wakeup(bp);
 3950         mtx_unlock(mtxp);
 3951 }
 3952 
 3953 void
 3954 bwait(struct buf *bp, u_char pri, const char *wchan)
 3955 {
 3956         struct mtx *mtxp;
 3957 
 3958         mtxp = mtx_pool_find(mtxpool_sleep, bp);
 3959         mtx_lock(mtxp);
 3960         while ((bp->b_flags & B_DONE) == 0)
 3961                 msleep(bp, mtxp, pri, wchan, 0);
 3962         mtx_unlock(mtxp);
 3963 }
 3964 
 3965 int
 3966 bufsync(struct bufobj *bo, int waitfor)
 3967 {
 3968 
 3969         return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
 3970 }
 3971 
 3972 void
 3973 bufstrategy(struct bufobj *bo, struct buf *bp)
 3974 {
 3975         int i = 0;
 3976         struct vnode *vp;
 3977 
 3978         vp = bp->b_vp;
 3979         KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
 3980         KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
 3981             ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
 3982         i = VOP_STRATEGY(vp, bp);
 3983         KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
 3984 }
 3985 
 3986 void
 3987 bufobj_wrefl(struct bufobj *bo)
 3988 {
 3989 
 3990         KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
 3991         ASSERT_BO_LOCKED(bo);
 3992         bo->bo_numoutput++;
 3993 }
 3994 
 3995 void
 3996 bufobj_wref(struct bufobj *bo)
 3997 {
 3998 
 3999         KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
 4000         BO_LOCK(bo);
 4001         bo->bo_numoutput++;
 4002         BO_UNLOCK(bo);
 4003 }
 4004 
 4005 void
 4006 bufobj_wdrop(struct bufobj *bo)
 4007 {
 4008 
 4009         KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
 4010         BO_LOCK(bo);
 4011         KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
 4012         if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
 4013                 bo->bo_flag &= ~BO_WWAIT;
 4014                 wakeup(&bo->bo_numoutput);
 4015         }
 4016         BO_UNLOCK(bo);
 4017 }
 4018 
 4019 int
 4020 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
 4021 {
 4022         int error;
 4023 
 4024         KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
 4025         ASSERT_BO_LOCKED(bo);
 4026         error = 0;
 4027         while (bo->bo_numoutput) {
 4028                 bo->bo_flag |= BO_WWAIT;
 4029                 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
 4030                     slpflag | (PRIBIO + 1), "bo_wwait", timeo);
 4031                 if (error)
 4032                         break;
 4033         }
 4034         return (error);
 4035 }
 4036 
 4037 void
 4038 bpin(struct buf *bp)
 4039 {
 4040         struct mtx *mtxp;
 4041 
 4042         mtxp = mtx_pool_find(mtxpool_sleep, bp);
 4043         mtx_lock(mtxp);
 4044         bp->b_pin_count++;
 4045         mtx_unlock(mtxp);
 4046 }
 4047 
 4048 void
 4049 bunpin(struct buf *bp)
 4050 {
 4051         struct mtx *mtxp;
 4052 
 4053         mtxp = mtx_pool_find(mtxpool_sleep, bp);
 4054         mtx_lock(mtxp);
 4055         if (--bp->b_pin_count == 0)
 4056                 wakeup(bp);
 4057         mtx_unlock(mtxp);
 4058 }
 4059 
 4060 void
 4061 bunpin_wait(struct buf *bp)
 4062 {
 4063         struct mtx *mtxp;
 4064 
 4065         mtxp = mtx_pool_find(mtxpool_sleep, bp);
 4066         mtx_lock(mtxp);
 4067         while (bp->b_pin_count > 0)
 4068                 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
 4069         mtx_unlock(mtxp);
 4070 }
 4071 
 4072 #include "opt_ddb.h"
 4073 #ifdef DDB
 4074 #include <ddb/ddb.h>
 4075 
 4076 /* DDB command to show buffer data */
 4077 DB_SHOW_COMMAND(buffer, db_show_buffer)
 4078 {
 4079         /* get args */
 4080         struct buf *bp = (struct buf *)addr;
 4081 
 4082         if (!have_addr) {
 4083                 db_printf("usage: show buffer <addr>\n");
 4084                 return;
 4085         }
 4086 
 4087         db_printf("buf at %p\n", bp);
 4088         db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
 4089         db_printf(
 4090             "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
 4091             "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_dep = %p\n",
 4092             bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
 4093             bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
 4094             bp->b_dep.lh_first);
 4095         if (bp->b_npages) {
 4096                 int i;
 4097                 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
 4098                 for (i = 0; i < bp->b_npages; i++) {
 4099                         vm_page_t m;
 4100                         m = bp->b_pages[i];
 4101                         db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
 4102                             (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
 4103                         if ((i + 1) < bp->b_npages)
 4104                                 db_printf(",");
 4105                 }
 4106                 db_printf("\n");
 4107         }
 4108         db_printf(" ");
 4109         BUF_LOCKPRINTINFO(bp);
 4110 }
 4111 
 4112 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
 4113 {
 4114         struct buf *bp;
 4115         int i;
 4116 
 4117         for (i = 0; i < nbuf; i++) {
 4118                 bp = &buf[i];
 4119                 if (BUF_ISLOCKED(bp)) {
 4120                         db_show_buffer((uintptr_t)bp, 1, 0, NULL);
 4121                         db_printf("\n");
 4122                 }
 4123         }
 4124 }
 4125 
 4126 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
 4127 {
 4128         struct vnode *vp;
 4129         struct buf *bp;
 4130 
 4131         if (!have_addr) {
 4132                 db_printf("usage: show vnodebufs <addr>\n");
 4133                 return;
 4134         }
 4135         vp = (struct vnode *)addr;
 4136         db_printf("Clean buffers:\n");
 4137         TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
 4138                 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
 4139                 db_printf("\n");
 4140         }
 4141         db_printf("Dirty buffers:\n");
 4142         TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
 4143                 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
 4144                 db_printf("\n");
 4145         }
 4146 }
 4147 
 4148 DB_COMMAND(countfreebufs, db_coundfreebufs)
 4149 {
 4150         struct buf *bp;
 4151         int i, used = 0, nfree = 0;
 4152 
 4153         if (have_addr) {
 4154                 db_printf("usage: countfreebufs\n");
 4155                 return;
 4156         }
 4157 
 4158         for (i = 0; i < nbuf; i++) {
 4159                 bp = &buf[i];
 4160                 if ((bp->b_vflags & BV_INFREECNT) != 0)
 4161                         nfree++;
 4162                 else
 4163                         used++;
 4164         }
 4165 
 4166         db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
 4167             nfree + used);
 4168         db_printf("numfreebuffers is %d\n", numfreebuffers);
 4169 }
 4170 #endif /* DDB */

Cache object: cd67bcd9eda06ba935a10af5b586f72a


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