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