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

Cache object: 429736c34f29364ff264dfffc3d64765


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