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