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

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

Cache object: 8a3269f2c53e1a9d9c5e84aa49a31074


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