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