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