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