Merge from vendor branch GDB:
[dragonfly.git] / sys / kern / vfs_bio.c
1 /*
2  * Copyright (c) 1994,1997 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Absolutely no warranty of function or purpose is made by the author
12  *              John S. Dyson.
13  *
14  * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15  * $DragonFly: src/sys/kern/vfs_bio.c,v 1.97 2008/01/28 07:19:06 nth Exp $
16  */
17
18 /*
19  * this file contains a new buffer I/O scheme implementing a coherent
20  * VM object and buffer cache scheme.  Pains have been taken to make
21  * sure that the performance degradation associated with schemes such
22  * as this is not realized.
23  *
24  * Author:  John S. Dyson
25  * Significant help during the development and debugging phases
26  * had been provided by David Greenman, also of the FreeBSD core team.
27  *
28  * see man buf(9) for more info.
29  */
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
47 #include <sys/proc.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
56
57 #include <sys/buf2.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <vm/vm_page2.h>
61
62 #include "opt_ddb.h"
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
66
67 /*
68  * Buffer queues.
69  */
70 enum bufq_type {
71         BQUEUE_NONE,            /* not on any queue */
72         BQUEUE_LOCKED,          /* locked buffers */
73         BQUEUE_CLEAN,           /* non-B_DELWRI buffers */
74         BQUEUE_DIRTY,           /* B_DELWRI buffers */
75         BQUEUE_DIRTY_HW,        /* B_DELWRI buffers - heavy weight */
76         BQUEUE_EMPTYKVA,        /* empty buffer headers with KVA assignment */
77         BQUEUE_EMPTY,           /* empty buffer headers */
78
79         BUFFER_QUEUES           /* number of buffer queues */
80 };
81
82 typedef enum bufq_type bufq_type_t;
83
84 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
85
86 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
87
88 struct buf *buf;                /* buffer header pool */
89
90 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
91                 vm_offset_t to);
92 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
93                 vm_offset_t to);
94 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
95                                int pageno, vm_page_t m);
96 static void vfs_clean_pages(struct buf *bp);
97 static void vfs_setdirty(struct buf *bp);
98 static void vfs_vmio_release(struct buf *bp);
99 static int flushbufqueues(bufq_type_t q);
100
101 static void buf_daemon(void);
102 static void buf_daemon_hw(void);
103 /*
104  * bogus page -- for I/O to/from partially complete buffers
105  * this is a temporary solution to the problem, but it is not
106  * really that bad.  it would be better to split the buffer
107  * for input in the case of buffers partially already in memory,
108  * but the code is intricate enough already.
109  */
110 vm_page_t bogus_page;
111 int runningbufspace;
112
113 /*
114  * These are all static, but make the ones we export globals so we do
115  * not need to use compiler magic.
116  */
117 int bufspace, maxbufspace,
118         bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
119 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
120 static int lorunningspace, hirunningspace, runningbufreq;
121 int numdirtybuffers, numdirtybuffershw, lodirtybuffers, hidirtybuffers;
122 static int numfreebuffers, lofreebuffers, hifreebuffers;
123 static int getnewbufcalls;
124 static int getnewbufrestarts;
125
126 static int needsbuffer;         /* locked by needsbuffer_spin */
127 static int bd_request;          /* locked by needsbuffer_spin */
128 static int bd_request_hw;       /* locked by needsbuffer_spin */
129 static struct spinlock needsbuffer_spin;
130
131 /*
132  * Sysctls for operational control of the buffer cache.
133  */
134 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
135         "Number of dirty buffers to flush before bufdaemon becomes inactive");
136 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
137         "High watermark used to trigger explicit flushing of dirty buffers");
138 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
139         "Low watermark for special reserve in low-memory situations");
140 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
141         "High watermark for special reserve in low-memory situations");
142 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
143         "Minimum amount of buffer space required for active I/O");
144 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
145         "Maximum amount of buffer space to usable for active I/O");
146 /*
147  * Sysctls determining current state of the buffer cache.
148  */
149 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
150         "Pending number of dirty buffers (all)");
151 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffershw, CTLFLAG_RD, &numdirtybuffershw, 0,
152         "Pending number of dirty buffers (heavy weight)");
153 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
154         "Number of free buffers on the buffer cache free list");
155 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
156         "I/O bytes currently in progress due to asynchronous writes");
157 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
158         "Hard limit on maximum amount of memory usable for buffer space");
159 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
160         "Soft limit on maximum amount of memory usable for buffer space");
161 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
162         "Minimum amount of memory to reserve for system buffer space");
163 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
164         "Amount of memory available for buffers");
165 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
166         0, "Maximum amount of memory reserved for buffers using malloc");
167 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
168         "Amount of memory left for buffers using malloc-scheme");
169 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
170         "New buffer header acquisition requests");
171 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
172         0, "New buffer header acquisition restarts");
173 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
174         "Buffer acquisition restarts due to fragmented buffer map");
175 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
176         "Amount of time KVA space was deallocated in an arbitrary buffer");
177 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
178         "Amount of time buffer re-use operations were successful");
179 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
180         "sizeof(struct buf)");
181
182 char *buf_wmesg = BUF_WMESG;
183
184 extern int vm_swap_size;
185
186 #define VFS_BIO_NEED_ANY        0x01    /* any freeable buffer */
187 #define VFS_BIO_NEED_DIRTYFLUSH 0x02    /* waiting for dirty buffer flush */
188 #define VFS_BIO_NEED_FREE       0x04    /* wait for free bufs, hi hysteresis */
189 #define VFS_BIO_NEED_BUFSPACE   0x08    /* wait for buf space, lo hysteresis */
190
191 /*
192  * numdirtywakeup:
193  *
194  *      If someone is blocked due to there being too many dirty buffers,
195  *      and numdirtybuffers is now reasonable, wake them up.
196  */
197 static __inline void
198 numdirtywakeup(void)
199 {
200         if (numdirtybuffers <= (lodirtybuffers + hidirtybuffers) / 2) {
201                 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
202                         spin_lock_wr(&needsbuffer_spin);
203                         needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
204                         spin_unlock_wr(&needsbuffer_spin);
205                         wakeup(&needsbuffer);
206                 }
207         }
208 }
209
210 /*
211  * bufspacewakeup:
212  *
213  *      Called when buffer space is potentially available for recovery.
214  *      getnewbuf() will block on this flag when it is unable to free 
215  *      sufficient buffer space.  Buffer space becomes recoverable when 
216  *      bp's get placed back in the queues.
217  */
218
219 static __inline void
220 bufspacewakeup(void)
221 {
222         /*
223          * If someone is waiting for BUF space, wake them up.  Even
224          * though we haven't freed the kva space yet, the waiting
225          * process will be able to now.
226          */
227         if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
228                 spin_lock_wr(&needsbuffer_spin);
229                 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
230                 spin_unlock_wr(&needsbuffer_spin);
231                 wakeup(&needsbuffer);
232         }
233 }
234
235 /*
236  * runningbufwakeup:
237  *
238  *      Accounting for I/O in progress.
239  *
240  */
241 static __inline void
242 runningbufwakeup(struct buf *bp)
243 {
244         if (bp->b_runningbufspace) {
245                 runningbufspace -= bp->b_runningbufspace;
246                 bp->b_runningbufspace = 0;
247                 if (runningbufreq && runningbufspace <= lorunningspace) {
248                         runningbufreq = 0;
249                         wakeup(&runningbufreq);
250                 }
251         }
252 }
253
254 /*
255  * bufcountwakeup:
256  *
257  *      Called when a buffer has been added to one of the free queues to
258  *      account for the buffer and to wakeup anyone waiting for free buffers.
259  *      This typically occurs when large amounts of metadata are being handled
260  *      by the buffer cache ( else buffer space runs out first, usually ).
261  */
262
263 static __inline void
264 bufcountwakeup(void) 
265 {
266         ++numfreebuffers;
267         if (needsbuffer) {
268                 spin_lock_wr(&needsbuffer_spin);
269                 needsbuffer &= ~VFS_BIO_NEED_ANY;
270                 if (numfreebuffers >= hifreebuffers)
271                         needsbuffer &= ~VFS_BIO_NEED_FREE;
272                 spin_unlock_wr(&needsbuffer_spin);
273                 wakeup(&needsbuffer);
274         }
275 }
276
277 /*
278  * waitrunningbufspace()
279  *
280  *      runningbufspace is a measure of the amount of I/O currently
281  *      running.  This routine is used in async-write situations to
282  *      prevent creating huge backups of pending writes to a device.
283  *      Only asynchronous writes are governed by this function.  
284  *
285  *      Reads will adjust runningbufspace, but will not block based on it.
286  *      The read load has a side effect of reducing the allowed write load.
287  *
288  *      This does NOT turn an async write into a sync write.  It waits
289  *      for earlier writes to complete and generally returns before the
290  *      caller's write has reached the device.
291  */
292 static __inline void
293 waitrunningbufspace(void)
294 {
295         if (runningbufspace > hirunningspace) {
296                 crit_enter();
297                 while (runningbufspace > hirunningspace) {
298                         ++runningbufreq;
299                         tsleep(&runningbufreq, 0, "wdrain", 0);
300                 }
301                 crit_exit();
302         }
303 }
304
305 /*
306  * vfs_buf_test_cache:
307  *
308  *      Called when a buffer is extended.  This function clears the B_CACHE
309  *      bit if the newly extended portion of the buffer does not contain
310  *      valid data.
311  */
312 static __inline__
313 void
314 vfs_buf_test_cache(struct buf *bp,
315                   vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
316                   vm_page_t m)
317 {
318         if (bp->b_flags & B_CACHE) {
319                 int base = (foff + off) & PAGE_MASK;
320                 if (vm_page_is_valid(m, base, size) == 0)
321                         bp->b_flags &= ~B_CACHE;
322         }
323 }
324
325 /*
326  * bd_wakeup:
327  *
328  *      Wake up the buffer daemon if the number of outstanding dirty buffers
329  *      is above specified threshold 'dirtybuflevel'.
330  *
331  *      The buffer daemons are explicitly woken up when (a) the pending number
332  *      of dirty buffers exceeds the recovery and stall mid-point value,
333  *      (b) during bwillwrite() or (c) buf freelist was exhausted.
334  *
335  *      The buffer daemons will generally not stop flushing until the dirty
336  *      buffer count goes below lodirtybuffers.
337  */
338 static __inline__
339 void
340 bd_wakeup(int dirtybuflevel)
341 {
342         if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
343                 spin_lock_wr(&needsbuffer_spin);
344                 bd_request = 1;
345                 spin_unlock_wr(&needsbuffer_spin);
346                 wakeup(&bd_request);
347         }
348         if (bd_request_hw == 0 && numdirtybuffershw >= dirtybuflevel) {
349                 spin_lock_wr(&needsbuffer_spin);
350                 bd_request_hw = 1;
351                 spin_unlock_wr(&needsbuffer_spin);
352                 wakeup(&bd_request_hw);
353         }
354 }
355
356 /*
357  * bd_speedup:
358  *
359  *      Speed up the buffer cache flushing process.
360  */
361
362 static __inline__
363 void
364 bd_speedup(void)
365 {
366         bd_wakeup(1);
367 }
368
369 /*
370  * bufinit:
371  *
372  *      Load time initialisation of the buffer cache, called from machine
373  *      dependant initialization code. 
374  */
375 void
376 bufinit(void)
377 {
378         struct buf *bp;
379         vm_offset_t bogus_offset;
380         int i;
381
382         spin_init(&needsbuffer_spin);
383
384         /* next, make a null set of free lists */
385         for (i = 0; i < BUFFER_QUEUES; i++)
386                 TAILQ_INIT(&bufqueues[i]);
387
388         /* finally, initialize each buffer header and stick on empty q */
389         for (i = 0; i < nbuf; i++) {
390                 bp = &buf[i];
391                 bzero(bp, sizeof *bp);
392                 bp->b_flags = B_INVAL;  /* we're just an empty header */
393                 bp->b_cmd = BUF_CMD_DONE;
394                 bp->b_qindex = BQUEUE_EMPTY;
395                 initbufbio(bp);
396                 xio_init(&bp->b_xio);
397                 buf_dep_init(bp);
398                 BUF_LOCKINIT(bp);
399                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
400         }
401
402         /*
403          * maxbufspace is the absolute maximum amount of buffer space we are 
404          * allowed to reserve in KVM and in real terms.  The absolute maximum
405          * is nominally used by buf_daemon.  hibufspace is the nominal maximum
406          * used by most other processes.  The differential is required to 
407          * ensure that buf_daemon is able to run when other processes might 
408          * be blocked waiting for buffer space.
409          *
410          * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
411          * this may result in KVM fragmentation which is not handled optimally
412          * by the system.
413          */
414         maxbufspace = nbuf * BKVASIZE;
415         hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
416         lobufspace = hibufspace - MAXBSIZE;
417
418         lorunningspace = 512 * 1024;
419         hirunningspace = 1024 * 1024;
420
421 /*
422  * Limit the amount of malloc memory since it is wired permanently into
423  * the kernel space.  Even though this is accounted for in the buffer
424  * allocation, we don't want the malloced region to grow uncontrolled.
425  * The malloc scheme improves memory utilization significantly on average
426  * (small) directories.
427  */
428         maxbufmallocspace = hibufspace / 20;
429
430 /*
431  * Reduce the chance of a deadlock occuring by limiting the number
432  * of delayed-write dirty buffers we allow to stack up.
433  */
434         hidirtybuffers = nbuf / 4 + 20;
435         numdirtybuffers = 0;
436         numdirtybuffershw = 0;
437 /*
438  * To support extreme low-memory systems, make sure hidirtybuffers cannot
439  * eat up all available buffer space.  This occurs when our minimum cannot
440  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
441  * BKVASIZE'd (8K) buffers.
442  */
443         while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
444                 hidirtybuffers >>= 1;
445         }
446         lodirtybuffers = hidirtybuffers / 2;
447
448 /*
449  * Try to keep the number of free buffers in the specified range,
450  * and give special processes (e.g. like buf_daemon) access to an 
451  * emergency reserve.
452  */
453         lofreebuffers = nbuf / 18 + 5;
454         hifreebuffers = 2 * lofreebuffers;
455         numfreebuffers = nbuf;
456
457 /*
458  * Maximum number of async ops initiated per buf_daemon loop.  This is
459  * somewhat of a hack at the moment, we really need to limit ourselves
460  * based on the number of bytes of I/O in-transit that were initiated
461  * from buf_daemon.
462  */
463
464         bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
465         bogus_page = vm_page_alloc(&kernel_object,
466                                    (bogus_offset >> PAGE_SHIFT),
467                                    VM_ALLOC_NORMAL);
468         vmstats.v_wire_count++;
469
470 }
471
472 /*
473  * Initialize the embedded bio structures
474  */
475 void
476 initbufbio(struct buf *bp)
477 {
478         bp->b_bio1.bio_buf = bp;
479         bp->b_bio1.bio_prev = NULL;
480         bp->b_bio1.bio_offset = NOOFFSET;
481         bp->b_bio1.bio_next = &bp->b_bio2;
482         bp->b_bio1.bio_done = NULL;
483
484         bp->b_bio2.bio_buf = bp;
485         bp->b_bio2.bio_prev = &bp->b_bio1;
486         bp->b_bio2.bio_offset = NOOFFSET;
487         bp->b_bio2.bio_next = NULL;
488         bp->b_bio2.bio_done = NULL;
489 }
490
491 /*
492  * Reinitialize the embedded bio structures as well as any additional
493  * translation cache layers.
494  */
495 void
496 reinitbufbio(struct buf *bp)
497 {
498         struct bio *bio;
499
500         for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
501                 bio->bio_done = NULL;
502                 bio->bio_offset = NOOFFSET;
503         }
504 }
505
506 /*
507  * Push another BIO layer onto an existing BIO and return it.  The new
508  * BIO layer may already exist, holding cached translation data.
509  */
510 struct bio *
511 push_bio(struct bio *bio)
512 {
513         struct bio *nbio;
514
515         if ((nbio = bio->bio_next) == NULL) {
516                 int index = bio - &bio->bio_buf->b_bio_array[0];
517                 if (index >= NBUF_BIO - 1) {
518                         panic("push_bio: too many layers bp %p\n",
519                                 bio->bio_buf);
520                 }
521                 nbio = &bio->bio_buf->b_bio_array[index + 1];
522                 bio->bio_next = nbio;
523                 nbio->bio_prev = bio;
524                 nbio->bio_buf = bio->bio_buf;
525                 nbio->bio_offset = NOOFFSET;
526                 nbio->bio_done = NULL;
527                 nbio->bio_next = NULL;
528         }
529         KKASSERT(nbio->bio_done == NULL);
530         return(nbio);
531 }
532
533 void
534 pop_bio(struct bio *bio)
535 {
536         /* NOP */
537 }
538
539 void
540 clearbiocache(struct bio *bio)
541 {
542         while (bio) {
543                 bio->bio_offset = NOOFFSET;
544                 bio = bio->bio_next;
545         }
546 }
547
548 /*
549  * bfreekva:
550  *
551  *      Free the KVA allocation for buffer 'bp'.
552  *
553  *      Must be called from a critical section as this is the only locking for
554  *      buffer_map.
555  *
556  *      Since this call frees up buffer space, we call bufspacewakeup().
557  */
558 static void
559 bfreekva(struct buf *bp)
560 {
561         int count;
562
563         if (bp->b_kvasize) {
564                 ++buffreekvacnt;
565                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
566                 vm_map_lock(&buffer_map);
567                 bufspace -= bp->b_kvasize;
568                 vm_map_delete(&buffer_map,
569                     (vm_offset_t) bp->b_kvabase,
570                     (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
571                     &count
572                 );
573                 vm_map_unlock(&buffer_map);
574                 vm_map_entry_release(count);
575                 bp->b_kvasize = 0;
576                 bufspacewakeup();
577         }
578 }
579
580 /*
581  * bremfree:
582  *
583  *      Remove the buffer from the appropriate free list.
584  */
585 void
586 bremfree(struct buf *bp)
587 {
588         int old_qindex;
589
590         crit_enter();
591         old_qindex = bp->b_qindex;
592
593         if (bp->b_qindex != BQUEUE_NONE) {
594                 KASSERT(BUF_REFCNTNB(bp) == 1, 
595                                 ("bremfree: bp %p not locked",bp));
596                 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
597                 bp->b_qindex = BQUEUE_NONE;
598         } else {
599                 if (BUF_REFCNTNB(bp) <= 1)
600                         panic("bremfree: removing a buffer not on a queue");
601         }
602
603         /*
604          * Fixup numfreebuffers count.  If the buffer is invalid or not
605          * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
606          * the buffer was free and we must decrement numfreebuffers.
607          */
608         if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
609                 switch(old_qindex) {
610                 case BQUEUE_DIRTY:
611                 case BQUEUE_DIRTY_HW:
612                 case BQUEUE_CLEAN:
613                 case BQUEUE_EMPTY:
614                 case BQUEUE_EMPTYKVA:
615                         --numfreebuffers;
616                         break;
617                 default:
618                         break;
619                 }
620         }
621         crit_exit();
622 }
623
624
625 /*
626  * bread:
627  *
628  *      Get a buffer with the specified data.  Look in the cache first.  We
629  *      must clear B_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
630  *      is set, the buffer is valid and we do not have to do anything ( see
631  *      getblk() ).
632  */
633 int
634 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
635 {
636         struct buf *bp;
637
638         bp = getblk(vp, loffset, size, 0, 0);
639         *bpp = bp;
640
641         /* if not found in cache, do some I/O */
642         if ((bp->b_flags & B_CACHE) == 0) {
643                 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
644                 bp->b_flags &= ~(B_ERROR | B_INVAL);
645                 bp->b_cmd = BUF_CMD_READ;
646                 vfs_busy_pages(vp, bp);
647                 vn_strategy(vp, &bp->b_bio1);
648                 return (biowait(bp));
649         }
650         return (0);
651 }
652
653 /*
654  * breadn:
655  *
656  *      Operates like bread, but also starts asynchronous I/O on
657  *      read-ahead blocks.  We must clear B_ERROR and B_INVAL prior
658  *      to initiating I/O . If B_CACHE is set, the buffer is valid 
659  *      and we do not have to do anything.
660  */
661 int
662 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
663         int *rabsize, int cnt, struct buf **bpp)
664 {
665         struct buf *bp, *rabp;
666         int i;
667         int rv = 0, readwait = 0;
668
669         *bpp = bp = getblk(vp, loffset, size, 0, 0);
670
671         /* if not found in cache, do some I/O */
672         if ((bp->b_flags & B_CACHE) == 0) {
673                 bp->b_flags &= ~(B_ERROR | B_INVAL);
674                 bp->b_cmd = BUF_CMD_READ;
675                 vfs_busy_pages(vp, bp);
676                 vn_strategy(vp, &bp->b_bio1);
677                 ++readwait;
678         }
679
680         for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
681                 if (inmem(vp, *raoffset))
682                         continue;
683                 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
684
685                 if ((rabp->b_flags & B_CACHE) == 0) {
686                         rabp->b_flags |= B_ASYNC;
687                         rabp->b_flags &= ~(B_ERROR | B_INVAL);
688                         rabp->b_cmd = BUF_CMD_READ;
689                         vfs_busy_pages(vp, rabp);
690                         BUF_KERNPROC(rabp);
691                         vn_strategy(vp, &rabp->b_bio1);
692                 } else {
693                         brelse(rabp);
694                 }
695         }
696
697         if (readwait) {
698                 rv = biowait(bp);
699         }
700         return (rv);
701 }
702
703 /*
704  * bwrite:
705  *
706  *      Write, release buffer on completion.  (Done by iodone
707  *      if async).  Do not bother writing anything if the buffer
708  *      is invalid.
709  *
710  *      Note that we set B_CACHE here, indicating that buffer is
711  *      fully valid and thus cacheable.  This is true even of NFS
712  *      now so we set it generally.  This could be set either here 
713  *      or in biodone() since the I/O is synchronous.  We put it
714  *      here.
715  */
716 int
717 bwrite(struct buf *bp)
718 {
719         int oldflags;
720
721         if (bp->b_flags & B_INVAL) {
722                 brelse(bp);
723                 return (0);
724         }
725
726         oldflags = bp->b_flags;
727
728         if (BUF_REFCNTNB(bp) == 0)
729                 panic("bwrite: buffer is not busy???");
730         crit_enter();
731
732         /* Mark the buffer clean */
733         bundirty(bp);
734
735         bp->b_flags &= ~B_ERROR;
736         bp->b_flags |= B_CACHE;
737         bp->b_cmd = BUF_CMD_WRITE;
738         vfs_busy_pages(bp->b_vp, bp);
739
740         /*
741          * Normal bwrites pipeline writes.  NOTE: b_bufsize is only
742          * valid for vnode-backed buffers.
743          */
744         bp->b_runningbufspace = bp->b_bufsize;
745         runningbufspace += bp->b_runningbufspace;
746
747         crit_exit();
748         if (oldflags & B_ASYNC)
749                 BUF_KERNPROC(bp);
750         vn_strategy(bp->b_vp, &bp->b_bio1);
751
752         if ((oldflags & B_ASYNC) == 0) {
753                 int rtval = biowait(bp);
754                 brelse(bp);
755                 return (rtval);
756         } else if ((oldflags & B_NOWDRAIN) == 0) {
757                 /*
758                  * don't allow the async write to saturate the I/O
759                  * system.  Deadlocks can occur only if a device strategy
760                  * routine (like in VN) turns around and issues another
761                  * high-level write, in which case B_NOWDRAIN is expected
762                  * to be set.   Otherwise we will not deadlock here because
763                  * we are blocking waiting for I/O that is already in-progress
764                  * to complete.
765                  */
766                 waitrunningbufspace();
767         }
768
769         return (0);
770 }
771
772 /*
773  * bdwrite:
774  *
775  *      Delayed write. (Buffer is marked dirty).  Do not bother writing
776  *      anything if the buffer is marked invalid.
777  *
778  *      Note that since the buffer must be completely valid, we can safely
779  *      set B_CACHE.  In fact, we have to set B_CACHE here rather then in
780  *      biodone() in order to prevent getblk from writing the buffer
781  *      out synchronously.
782  */
783 void
784 bdwrite(struct buf *bp)
785 {
786         if (BUF_REFCNTNB(bp) == 0)
787                 panic("bdwrite: buffer is not busy");
788
789         if (bp->b_flags & B_INVAL) {
790                 brelse(bp);
791                 return;
792         }
793         bdirty(bp);
794
795         /*
796          * Set B_CACHE, indicating that the buffer is fully valid.  This is
797          * true even of NFS now.
798          */
799         bp->b_flags |= B_CACHE;
800
801         /*
802          * This bmap keeps the system from needing to do the bmap later,
803          * perhaps when the system is attempting to do a sync.  Since it
804          * is likely that the indirect block -- or whatever other datastructure
805          * that the filesystem needs is still in memory now, it is a good
806          * thing to do this.  Note also, that if the pageout daemon is
807          * requesting a sync -- there might not be enough memory to do
808          * the bmap then...  So, this is important to do.
809          */
810         if (bp->b_bio2.bio_offset == NOOFFSET) {
811                 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
812                          NULL, NULL);
813         }
814
815         /*
816          * Set the *dirty* buffer range based upon the VM system dirty pages.
817          */
818         vfs_setdirty(bp);
819
820         /*
821          * We need to do this here to satisfy the vnode_pager and the
822          * pageout daemon, so that it thinks that the pages have been
823          * "cleaned".  Note that since the pages are in a delayed write
824          * buffer -- the VFS layer "will" see that the pages get written
825          * out on the next sync, or perhaps the cluster will be completed.
826          */
827         vfs_clean_pages(bp);
828         bqrelse(bp);
829
830         /*
831          * Wakeup the buffer flushing daemon if we have a lot of dirty
832          * buffers (midpoint between our recovery point and our stall
833          * point).
834          */
835         bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
836
837         /*
838          * note: we cannot initiate I/O from a bdwrite even if we wanted to,
839          * due to the softdep code.
840          */
841 }
842
843 /*
844  * bdirty:
845  *
846  *      Turn buffer into delayed write request by marking it B_DELWRI.
847  *      B_RELBUF and B_NOCACHE must be cleared.
848  *
849  *      We reassign the buffer to itself to properly update it in the
850  *      dirty/clean lists. 
851  *
852  *      Since the buffer is not on a queue, we do not update the 
853  *      numfreebuffers count.
854  *
855  *      Must be called from a critical section.
856  *      The buffer must be on BQUEUE_NONE.
857  */
858 void
859 bdirty(struct buf *bp)
860 {
861         KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
862         if (bp->b_flags & B_NOCACHE) {
863                 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
864                 bp->b_flags &= ~B_NOCACHE;
865         }
866         if (bp->b_flags & B_INVAL) {
867                 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
868         }
869         bp->b_flags &= ~B_RELBUF;
870
871         if ((bp->b_flags & B_DELWRI) == 0) {
872                 bp->b_flags |= B_DELWRI;
873                 reassignbuf(bp);
874                 ++numdirtybuffers;
875                 if (bp->b_flags & B_HEAVY)
876                         ++numdirtybuffershw;
877                 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
878         }
879 }
880
881 /*
882  * Set B_HEAVY, indicating that this is a heavy-weight buffer that
883  * needs to be flushed with a different buf_daemon thread to avoid
884  * deadlocks.  B_HEAVY also imposes restrictions in getnewbuf().
885  */
886 void
887 bheavy(struct buf *bp)
888 {
889         if ((bp->b_flags & B_HEAVY) == 0) {
890                 bp->b_flags |= B_HEAVY;
891                 if (bp->b_flags & B_DELWRI)
892                         ++numdirtybuffershw;
893         }
894 }
895
896 /*
897  * bundirty:
898  *
899  *      Clear B_DELWRI for buffer.
900  *
901  *      Since the buffer is not on a queue, we do not update the numfreebuffers
902  *      count.
903  *      
904  *      Must be called from a critical section.
905  *
906  *      The buffer is typically on BQUEUE_NONE but there is one case in 
907  *      brelse() that calls this function after placing the buffer on
908  *      a different queue.
909  */
910
911 void
912 bundirty(struct buf *bp)
913 {
914         if (bp->b_flags & B_DELWRI) {
915                 bp->b_flags &= ~B_DELWRI;
916                 reassignbuf(bp);
917                 --numdirtybuffers;
918                 if (bp->b_flags & B_HEAVY)
919                         --numdirtybuffershw;
920                 numdirtywakeup();
921         }
922         /*
923          * Since it is now being written, we can clear its deferred write flag.
924          */
925         bp->b_flags &= ~B_DEFERRED;
926 }
927
928 /*
929  * bawrite:
930  *
931  *      Asynchronous write.  Start output on a buffer, but do not wait for
932  *      it to complete.  The buffer is released when the output completes.
933  *
934  *      bwrite() ( or the VOP routine anyway ) is responsible for handling 
935  *      B_INVAL buffers.  Not us.
936  */
937 void
938 bawrite(struct buf *bp)
939 {
940         bp->b_flags |= B_ASYNC;
941         bwrite(bp);
942 }
943
944 /*
945  * bowrite:
946  *
947  *      Ordered write.  Start output on a buffer, and flag it so that the 
948  *      device will write it in the order it was queued.  The buffer is 
949  *      released when the output completes.  bwrite() ( or the VOP routine
950  *      anyway ) is responsible for handling B_INVAL buffers.
951  */
952 int
953 bowrite(struct buf *bp)
954 {
955         bp->b_flags |= B_ORDERED | B_ASYNC;
956         return (bwrite(bp));
957 }
958
959 /*
960  * bwillwrite:
961  *
962  *      Called prior to the locking of any vnodes when we are expecting to
963  *      write.  We do not want to starve the buffer cache with too many
964  *      dirty buffers so we block here.  By blocking prior to the locking
965  *      of any vnodes we attempt to avoid the situation where a locked vnode
966  *      prevents the various system daemons from flushing related buffers.
967  */
968 void
969 bwillwrite(void)
970 {
971         if (numdirtybuffers >= hidirtybuffers) {
972                 while (numdirtybuffers >= hidirtybuffers) {
973                         bd_wakeup(1);
974                         spin_lock_wr(&needsbuffer_spin);
975                         if (numdirtybuffers >= hidirtybuffers) {
976                                 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
977                                 msleep(&needsbuffer, &needsbuffer_spin, 0,
978                                        "flswai", 0);
979                         }
980                         spin_unlock_wr(&needsbuffer_spin);
981                 }
982         }
983 }
984
985 /*
986  * buf_dirty_count_severe:
987  *
988  *      Return true if we have too many dirty buffers.
989  */
990 int
991 buf_dirty_count_severe(void)
992 {
993         return(numdirtybuffers >= hidirtybuffers);
994 }
995
996 /*
997  * brelse:
998  *
999  *      Release a busy buffer and, if requested, free its resources.  The
1000  *      buffer will be stashed in the appropriate bufqueue[] allowing it
1001  *      to be accessed later as a cache entity or reused for other purposes.
1002  */
1003 void
1004 brelse(struct buf *bp)
1005 {
1006 #ifdef INVARIANTS
1007         int saved_flags = bp->b_flags;
1008 #endif
1009
1010         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1011
1012         crit_enter();
1013
1014         /*
1015          * If B_NOCACHE is set we are being asked to destroy the buffer and
1016          * its backing store.  Clear B_DELWRI.
1017          *
1018          * B_NOCACHE is set in two cases: (1) when the caller really wants
1019          * to destroy the buffer and backing store and (2) when the caller
1020          * wants to destroy the buffer and backing store after a write 
1021          * completes.
1022          */
1023         if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1024                 bundirty(bp);
1025         }
1026
1027         if (bp->b_flags & B_LOCKED)
1028                 bp->b_flags &= ~B_ERROR;
1029
1030         /*
1031          * If a write error occurs and the caller does not want to throw
1032          * away the buffer, redirty the buffer.  This will also clear
1033          * B_NOCACHE.
1034          */
1035         if (bp->b_cmd == BUF_CMD_WRITE &&
1036             (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
1037                 /*
1038                  * Failed write, redirty.  Must clear B_ERROR to prevent
1039                  * pages from being scrapped.  If B_INVAL is set then
1040                  * this case is not run and the next case is run to 
1041                  * destroy the buffer.  B_INVAL can occur if the buffer
1042                  * is outside the range supported by the underlying device.
1043                  */
1044                 bp->b_flags &= ~B_ERROR;
1045                 bdirty(bp);
1046         } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1047                    (bp->b_bufsize <= 0) || bp->b_cmd == BUF_CMD_FREEBLKS) {
1048                 /*
1049                  * Either a failed I/O or we were asked to free or not
1050                  * cache the buffer.
1051                  *
1052                  * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1053                  * buffer cannot be immediately freed.
1054                  */
1055                 bp->b_flags |= B_INVAL;
1056                 if (LIST_FIRST(&bp->b_dep) != NULL)
1057                         buf_deallocate(bp);
1058                 if (bp->b_flags & B_DELWRI) {
1059                         --numdirtybuffers;
1060                         if (bp->b_flags & B_HEAVY)
1061                                 --numdirtybuffershw;
1062                         numdirtywakeup();
1063                 }
1064                 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1065         }
1066
1067         /*
1068          * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1069          * If vfs_vmio_release() is called with either bit set, the
1070          * underlying pages may wind up getting freed causing a previous
1071          * write (bdwrite()) to get 'lost' because pages associated with
1072          * a B_DELWRI bp are marked clean.  Pages associated with a
1073          * B_LOCKED buffer may be mapped by the filesystem.
1074          *
1075          * If we want to release the buffer ourselves (rather then the
1076          * originator asking us to release it), give the originator a
1077          * chance to countermand the release by setting B_LOCKED.
1078          * 
1079          * We still allow the B_INVAL case to call vfs_vmio_release(), even
1080          * if B_DELWRI is set.
1081          *
1082          * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1083          * on pages to return pages to the VM page queues.
1084          */
1085         if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1086                 bp->b_flags &= ~B_RELBUF;
1087         } else if (vm_page_count_severe()) {
1088                 if (LIST_FIRST(&bp->b_dep) != NULL)
1089                         buf_deallocate(bp);
1090                 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1091                         bp->b_flags &= ~B_RELBUF;
1092                 else
1093                         bp->b_flags |= B_RELBUF;
1094         }
1095
1096         /*
1097          * At this point destroying the buffer is governed by the B_INVAL 
1098          * or B_RELBUF flags.
1099          */
1100         bp->b_cmd = BUF_CMD_DONE;
1101
1102         /*
1103          * VMIO buffer rundown.  Make sure the VM page array is restored
1104          * after an I/O may have replaces some of the pages with bogus pages
1105          * in order to not destroy dirty pages in a fill-in read.
1106          *
1107          * Note that due to the code above, if a buffer is marked B_DELWRI
1108          * then the B_RELBUF and B_NOCACHE bits will always be clear.
1109          * B_INVAL may still be set, however.
1110          *
1111          * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1112          * but not the backing store.   B_NOCACHE will destroy the backing
1113          * store.
1114          *
1115          * Note that dirty NFS buffers contain byte-granular write ranges
1116          * and should not be destroyed w/ B_INVAL even if the backing store
1117          * is left intact.
1118          */
1119         if (bp->b_flags & B_VMIO) {
1120                 /*
1121                  * Rundown for VMIO buffers which are not dirty NFS buffers.
1122                  */
1123                 int i, j, resid;
1124                 vm_page_t m;
1125                 off_t foff;
1126                 vm_pindex_t poff;
1127                 vm_object_t obj;
1128                 struct vnode *vp;
1129
1130                 vp = bp->b_vp;
1131
1132                 /*
1133                  * Get the base offset and length of the buffer.  Note that 
1134                  * in the VMIO case if the buffer block size is not
1135                  * page-aligned then b_data pointer may not be page-aligned.
1136                  * But our b_xio.xio_pages array *IS* page aligned.
1137                  *
1138                  * block sizes less then DEV_BSIZE (usually 512) are not 
1139                  * supported due to the page granularity bits (m->valid,
1140                  * m->dirty, etc...). 
1141                  *
1142                  * See man buf(9) for more information
1143                  */
1144
1145                 resid = bp->b_bufsize;
1146                 foff = bp->b_loffset;
1147
1148                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1149                         m = bp->b_xio.xio_pages[i];
1150                         vm_page_flag_clear(m, PG_ZERO);
1151                         /*
1152                          * If we hit a bogus page, fixup *all* of them
1153                          * now.  Note that we left these pages wired
1154                          * when we removed them so they had better exist,
1155                          * and they cannot be ripped out from under us so
1156                          * no critical section protection is necessary.
1157                          */
1158                         if (m == bogus_page) {
1159                                 obj = vp->v_object;
1160                                 poff = OFF_TO_IDX(bp->b_loffset);
1161
1162                                 for (j = i; j < bp->b_xio.xio_npages; j++) {
1163                                         vm_page_t mtmp;
1164
1165                                         mtmp = bp->b_xio.xio_pages[j];
1166                                         if (mtmp == bogus_page) {
1167                                                 mtmp = vm_page_lookup(obj, poff + j);
1168                                                 if (!mtmp) {
1169                                                         panic("brelse: page missing");
1170                                                 }
1171                                                 bp->b_xio.xio_pages[j] = mtmp;
1172                                         }
1173                                 }
1174
1175                                 if ((bp->b_flags & B_INVAL) == 0) {
1176                                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1177                                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1178                                 }
1179                                 m = bp->b_xio.xio_pages[i];
1180                         }
1181
1182                         /*
1183                          * Invalidate the backing store if B_NOCACHE is set
1184                          * (e.g. used with vinvalbuf()).  If this is NFS
1185                          * we impose a requirement that the block size be
1186                          * a multiple of PAGE_SIZE and create a temporary
1187                          * hack to basically invalidate the whole page.  The
1188                          * problem is that NFS uses really odd buffer sizes
1189                          * especially when tracking piecemeal writes and
1190                          * it also vinvalbuf()'s a lot, which would result
1191                          * in only partial page validation and invalidation
1192                          * here.  If the file page is mmap()'d, however,
1193                          * all the valid bits get set so after we invalidate
1194                          * here we would end up with weird m->valid values
1195                          * like 0xfc.  nfs_getpages() can't handle this so
1196                          * we clear all the valid bits for the NFS case
1197                          * instead of just some of them.
1198                          *
1199                          * The real bug is the VM system having to set m->valid
1200                          * to VM_PAGE_BITS_ALL for faulted-in pages, which
1201                          * itself is an artifact of the whole 512-byte
1202                          * granular mess that exists to support odd block 
1203                          * sizes and UFS meta-data block sizes (e.g. 6144).
1204                          * A complete rewrite is required.
1205                          */
1206                         if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1207                                 int poffset = foff & PAGE_MASK;
1208                                 int presid;
1209
1210                                 presid = PAGE_SIZE - poffset;
1211                                 if (bp->b_vp->v_tag == VT_NFS &&
1212                                     bp->b_vp->v_type == VREG) {
1213                                         ; /* entire page */
1214                                 } else if (presid > resid) {
1215                                         presid = resid;
1216                                 }
1217                                 KASSERT(presid >= 0, ("brelse: extra page"));
1218                                 vm_page_set_invalid(m, poffset, presid);
1219                         }
1220                         resid -= PAGE_SIZE - (foff & PAGE_MASK);
1221                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1222                 }
1223                 if (bp->b_flags & (B_INVAL | B_RELBUF))
1224                         vfs_vmio_release(bp);
1225         } else {
1226                 /*
1227                  * Rundown for non-VMIO buffers.
1228                  */
1229                 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1230 #if 0
1231                         if (bp->b_vp)
1232                                 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1233 #endif
1234                         if (bp->b_bufsize)
1235                                 allocbuf(bp, 0);
1236                         if (bp->b_vp)
1237                                 brelvp(bp);
1238                 }
1239         }
1240                         
1241         if (bp->b_qindex != BQUEUE_NONE)
1242                 panic("brelse: free buffer onto another queue???");
1243         if (BUF_REFCNTNB(bp) > 1) {
1244                 /* Temporary panic to verify exclusive locking */
1245                 /* This panic goes away when we allow shared refs */
1246                 panic("brelse: multiple refs");
1247                 /* do not release to free list */
1248                 BUF_UNLOCK(bp);
1249                 crit_exit();
1250                 return;
1251         }
1252
1253         /*
1254          * Figure out the correct queue to place the cleaned up buffer on.
1255          * Buffers placed in the EMPTY or EMPTYKVA had better already be
1256          * disassociated from their vnode.
1257          */
1258         if (bp->b_flags & B_LOCKED) {
1259                 /*
1260                  * Buffers that are locked are placed in the locked queue
1261                  * immediately, regardless of their state.
1262                  */
1263                 bp->b_qindex = BQUEUE_LOCKED;
1264                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1265         } else if (bp->b_bufsize == 0) {
1266                 /*
1267                  * Buffers with no memory.  Due to conditionals near the top
1268                  * of brelse() such buffers should probably already be
1269                  * marked B_INVAL and disassociated from their vnode.
1270                  */
1271                 bp->b_flags |= B_INVAL;
1272                 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1273                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1274                 if (bp->b_kvasize) {
1275                         bp->b_qindex = BQUEUE_EMPTYKVA;
1276                 } else {
1277                         bp->b_qindex = BQUEUE_EMPTY;
1278                 }
1279                 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1280         } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1281                 /*
1282                  * Buffers with junk contents.   Again these buffers had better
1283                  * already be disassociated from their vnode.
1284                  */
1285                 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1286                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1287                 bp->b_flags |= B_INVAL;
1288                 bp->b_qindex = BQUEUE_CLEAN;
1289                 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1290         } else {
1291                 /*
1292                  * Remaining buffers.  These buffers are still associated with
1293                  * their vnode.
1294                  */
1295                 switch(bp->b_flags & (B_DELWRI|B_HEAVY|B_AGE)) {
1296                 case B_DELWRI | B_AGE:
1297                     bp->b_qindex = BQUEUE_DIRTY;
1298                     TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1299                     break;
1300                 case B_DELWRI:
1301                     bp->b_qindex = BQUEUE_DIRTY;
1302                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1303                     break;
1304                 case B_DELWRI | B_HEAVY | B_AGE:
1305                     bp->b_qindex = BQUEUE_DIRTY_HW;
1306                     TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY_HW], bp,
1307                                       b_freelist);
1308                     break;
1309                 case B_DELWRI | B_HEAVY:
1310                     bp->b_qindex = BQUEUE_DIRTY_HW;
1311                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1312                                       b_freelist);
1313                     break;
1314                 case B_HEAVY | B_AGE:
1315                 case B_AGE:
1316                     bp->b_qindex = BQUEUE_CLEAN;
1317                     TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1318                     break;
1319                 default:
1320                     bp->b_qindex = BQUEUE_CLEAN;
1321                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1322                     break;
1323                 }
1324         }
1325
1326         /*
1327          * If B_INVAL, clear B_DELWRI.  We've already placed the buffer
1328          * on the correct queue.
1329          */
1330         if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1331                 bundirty(bp);
1332
1333         /*
1334          * Fixup numfreebuffers count.  The bp is on an appropriate queue
1335          * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1336          * We've already handled the B_INVAL case ( B_DELWRI will be clear
1337          * if B_INVAL is set ).
1338          */
1339         if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1340                 bufcountwakeup();
1341
1342         /*
1343          * Something we can maybe free or reuse
1344          */
1345         if (bp->b_bufsize || bp->b_kvasize)
1346                 bufspacewakeup();
1347
1348         /*
1349          * Clean up temporary flags and unlock the buffer.
1350          */
1351         bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1352                         B_DIRECT | B_NOWDRAIN);
1353         BUF_UNLOCK(bp);
1354         crit_exit();
1355 }
1356
1357 /*
1358  * bqrelse:
1359  *
1360  *      Release a buffer back to the appropriate queue but do not try to free
1361  *      it.  The buffer is expected to be used again soon.
1362  *
1363  *      bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1364  *      biodone() to requeue an async I/O on completion.  It is also used when
1365  *      known good buffers need to be requeued but we think we may need the data
1366  *      again soon.
1367  *
1368  *      XXX we should be able to leave the B_RELBUF hint set on completion.
1369  */
1370 void
1371 bqrelse(struct buf *bp)
1372 {
1373         crit_enter();
1374
1375         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1376
1377         if (bp->b_qindex != BQUEUE_NONE)
1378                 panic("bqrelse: free buffer onto another queue???");
1379         if (BUF_REFCNTNB(bp) > 1) {
1380                 /* do not release to free list */
1381                 panic("bqrelse: multiple refs");
1382                 BUF_UNLOCK(bp);
1383                 crit_exit();
1384                 return;
1385         }
1386         if (bp->b_flags & B_LOCKED) {
1387                 /*
1388                  * Locked buffers are released to the locked queue.  However,
1389                  * if the buffer is dirty it will first go into the dirty
1390                  * queue and later on after the I/O completes successfully it
1391                  * will be released to the locked queue.
1392                  */
1393                 bp->b_flags &= ~B_ERROR;
1394                 bp->b_qindex = BQUEUE_LOCKED;
1395                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1396         } else if (bp->b_flags & B_DELWRI) {
1397                 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1398                                BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1399                 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1400         } else if (vm_page_count_severe()) {
1401                 /*
1402                  * We are too low on memory, we have to try to free the
1403                  * buffer (most importantly: the wired pages making up its
1404                  * backing store) *now*.
1405                  */
1406                 crit_exit();
1407                 brelse(bp);
1408                 return;
1409         } else {
1410                 bp->b_qindex = BQUEUE_CLEAN;
1411                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1412         }
1413
1414         if ((bp->b_flags & B_LOCKED) == 0 &&
1415             ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1416                 bufcountwakeup();
1417         }
1418
1419         /*
1420          * Something we can maybe free or reuse.
1421          */
1422         if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1423                 bufspacewakeup();
1424
1425         /*
1426          * Final cleanup and unlock.  Clear bits that are only used while a
1427          * buffer is actively locked.
1428          */
1429         bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1430         BUF_UNLOCK(bp);
1431         crit_exit();
1432 }
1433
1434 /*
1435  * vfs_vmio_release:
1436  *
1437  *      Return backing pages held by the buffer 'bp' back to the VM system
1438  *      if possible.  The pages are freed if they are no longer valid or
1439  *      attempt to free if it was used for direct I/O otherwise they are
1440  *      sent to the page cache.
1441  *
1442  *      Pages that were marked busy are left alone and skipped.
1443  *
1444  *      The KVA mapping (b_data) for the underlying pages is removed by
1445  *      this function.
1446  */
1447 static void
1448 vfs_vmio_release(struct buf *bp)
1449 {
1450         int i;
1451         vm_page_t m;
1452
1453         crit_enter();
1454         for (i = 0; i < bp->b_xio.xio_npages; i++) {
1455                 m = bp->b_xio.xio_pages[i];
1456                 bp->b_xio.xio_pages[i] = NULL;
1457                 /*
1458                  * In order to keep page LRU ordering consistent, put
1459                  * everything on the inactive queue.
1460                  */
1461                 vm_page_unwire(m, 0);
1462                 /*
1463                  * We don't mess with busy pages, it is
1464                  * the responsibility of the process that
1465                  * busied the pages to deal with them.
1466                  */
1467                 if ((m->flags & PG_BUSY) || (m->busy != 0))
1468                         continue;
1469                         
1470                 if (m->wire_count == 0) {
1471                         vm_page_flag_clear(m, PG_ZERO);
1472                         /*
1473                          * Might as well free the page if we can and it has
1474                          * no valid data.  We also free the page if the
1475                          * buffer was used for direct I/O.
1476                          */
1477                         if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1478                                         m->hold_count == 0) {
1479                                 vm_page_busy(m);
1480                                 vm_page_protect(m, VM_PROT_NONE);
1481                                 vm_page_free(m);
1482                         } else if (bp->b_flags & B_DIRECT) {
1483                                 vm_page_try_to_free(m);
1484                         } else if (vm_page_count_severe()) {
1485                                 vm_page_try_to_cache(m);
1486                         }
1487                 }
1488         }
1489         crit_exit();
1490         pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1491         if (bp->b_bufsize) {
1492                 bufspacewakeup();
1493                 bp->b_bufsize = 0;
1494         }
1495         bp->b_xio.xio_npages = 0;
1496         bp->b_flags &= ~B_VMIO;
1497         if (bp->b_vp)
1498                 brelvp(bp);
1499 }
1500
1501 /*
1502  * vfs_bio_awrite:
1503  *
1504  *      Implement clustered async writes for clearing out B_DELWRI buffers.
1505  *      This is much better then the old way of writing only one buffer at
1506  *      a time.  Note that we may not be presented with the buffers in the 
1507  *      correct order, so we search for the cluster in both directions.
1508  *
1509  *      The buffer is locked on call.
1510  */
1511 int
1512 vfs_bio_awrite(struct buf *bp)
1513 {
1514         int i;
1515         int j;
1516         off_t loffset = bp->b_loffset;
1517         struct vnode *vp = bp->b_vp;
1518         int nbytes;
1519         struct buf *bpa;
1520         int nwritten;
1521         int size;
1522
1523         crit_enter();
1524         /*
1525          * right now we support clustered writing only to regular files.  If
1526          * we find a clusterable block we could be in the middle of a cluster
1527          * rather then at the beginning.
1528          *
1529          * NOTE: b_bio1 contains the logical loffset and is aliased
1530          * to b_loffset.  b_bio2 contains the translated block number.
1531          */
1532         if ((vp->v_type == VREG) && 
1533             (vp->v_mount != 0) && /* Only on nodes that have the size info */
1534             (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1535
1536                 size = vp->v_mount->mnt_stat.f_iosize;
1537
1538                 for (i = size; i < MAXPHYS; i += size) {
1539                         if ((bpa = findblk(vp, loffset + i)) &&
1540                             BUF_REFCNT(bpa) == 0 &&
1541                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1542                             (B_DELWRI | B_CLUSTEROK)) &&
1543                             (bpa->b_bufsize == size)) {
1544                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1545                                     (bpa->b_bio2.bio_offset !=
1546                                      bp->b_bio2.bio_offset + i))
1547                                         break;
1548                         } else {
1549                                 break;
1550                         }
1551                 }
1552                 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1553                         if ((bpa = findblk(vp, loffset - j)) &&
1554                             BUF_REFCNT(bpa) == 0 &&
1555                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1556                             (B_DELWRI | B_CLUSTEROK)) &&
1557                             (bpa->b_bufsize == size)) {
1558                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1559                                     (bpa->b_bio2.bio_offset !=
1560                                      bp->b_bio2.bio_offset - j))
1561                                         break;
1562                         } else {
1563                                 break;
1564                         }
1565                 }
1566                 j -= size;
1567                 nbytes = (i + j);
1568                 /*
1569                  * this is a possible cluster write
1570                  */
1571                 if (nbytes != size) {
1572                         BUF_UNLOCK(bp);
1573                         nwritten = cluster_wbuild(vp, size,
1574                                                   loffset - j, nbytes);
1575                         crit_exit();
1576                         return nwritten;
1577                 }
1578         }
1579
1580         bremfree(bp);
1581         bp->b_flags |= B_ASYNC;
1582
1583         crit_exit();
1584         /*
1585          * default (old) behavior, writing out only one block
1586          *
1587          * XXX returns b_bufsize instead of b_bcount for nwritten?
1588          */
1589         nwritten = bp->b_bufsize;
1590         bwrite(bp);
1591
1592         return nwritten;
1593 }
1594
1595 /*
1596  * getnewbuf:
1597  *
1598  *      Find and initialize a new buffer header, freeing up existing buffers 
1599  *      in the bufqueues as necessary.  The new buffer is returned locked.
1600  *
1601  *      Important:  B_INVAL is not set.  If the caller wishes to throw the
1602  *      buffer away, the caller must set B_INVAL prior to calling brelse().
1603  *
1604  *      We block if:
1605  *              We have insufficient buffer headers
1606  *              We have insufficient buffer space
1607  *              buffer_map is too fragmented ( space reservation fails )
1608  *              If we have to flush dirty buffers ( but we try to avoid this )
1609  *
1610  *      To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1611  *      Instead we ask the buf daemon to do it for us.  We attempt to
1612  *      avoid piecemeal wakeups of the pageout daemon.
1613  */
1614
1615 static struct buf *
1616 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1617 {
1618         struct buf *bp;
1619         struct buf *nbp;
1620         int defrag = 0;
1621         int nqindex;
1622         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1623         static int flushingbufs;
1624
1625         /*
1626          * We can't afford to block since we might be holding a vnode lock,
1627          * which may prevent system daemons from running.  We deal with
1628          * low-memory situations by proactively returning memory and running
1629          * async I/O rather then sync I/O.
1630          */
1631         
1632         ++getnewbufcalls;
1633         --getnewbufrestarts;
1634 restart:
1635         ++getnewbufrestarts;
1636
1637         /*
1638          * Setup for scan.  If we do not have enough free buffers,
1639          * we setup a degenerate case that immediately fails.  Note
1640          * that if we are specially marked process, we are allowed to
1641          * dip into our reserves.
1642          *
1643          * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1644          *
1645          * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1646          * However, there are a number of cases (defragging, reusing, ...)
1647          * where we cannot backup.
1648          */
1649         nqindex = BQUEUE_EMPTYKVA;
1650         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1651
1652         if (nbp == NULL) {
1653                 /*
1654                  * If no EMPTYKVA buffers and we are either
1655                  * defragging or reusing, locate a CLEAN buffer
1656                  * to free or reuse.  If bufspace useage is low
1657                  * skip this step so we can allocate a new buffer.
1658                  */
1659                 if (defrag || bufspace >= lobufspace) {
1660                         nqindex = BQUEUE_CLEAN;
1661                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1662                 }
1663
1664                 /*
1665                  * If we could not find or were not allowed to reuse a
1666                  * CLEAN buffer, check to see if it is ok to use an EMPTY
1667                  * buffer.  We can only use an EMPTY buffer if allocating
1668                  * its KVA would not otherwise run us out of buffer space.
1669                  */
1670                 if (nbp == NULL && defrag == 0 &&
1671                     bufspace + maxsize < hibufspace) {
1672                         nqindex = BQUEUE_EMPTY;
1673                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1674                 }
1675         }
1676
1677         /*
1678          * Run scan, possibly freeing data and/or kva mappings on the fly
1679          * depending.
1680          */
1681
1682         while ((bp = nbp) != NULL) {
1683                 int qindex = nqindex;
1684
1685                 /*
1686                  * Calculate next bp ( we can only use it if we do not block
1687                  * or do other fancy things ).
1688                  */
1689                 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1690                         switch(qindex) {
1691                         case BQUEUE_EMPTY:
1692                                 nqindex = BQUEUE_EMPTYKVA;
1693                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1694                                         break;
1695                                 /* fall through */
1696                         case BQUEUE_EMPTYKVA:
1697                                 nqindex = BQUEUE_CLEAN;
1698                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1699                                         break;
1700                                 /* fall through */
1701                         case BQUEUE_CLEAN:
1702                                 /*
1703                                  * nbp is NULL. 
1704                                  */
1705                                 break;
1706                         }
1707                 }
1708
1709                 /*
1710                  * Sanity Checks
1711                  */
1712                 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1713
1714                 /*
1715                  * Note: we no longer distinguish between VMIO and non-VMIO
1716                  * buffers.
1717                  */
1718
1719                 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1720
1721                 /*
1722                  * If we are defragging then we need a buffer with 
1723                  * b_kvasize != 0.  XXX this situation should no longer
1724                  * occur, if defrag is non-zero the buffer's b_kvasize
1725                  * should also be non-zero at this point.  XXX
1726                  */
1727                 if (defrag && bp->b_kvasize == 0) {
1728                         kprintf("Warning: defrag empty buffer %p\n", bp);
1729                         continue;
1730                 }
1731
1732                 /*
1733                  * Start freeing the bp.  This is somewhat involved.  nbp
1734                  * remains valid only for BQUEUE_EMPTY[KVA] bp's.  Buffers
1735                  * on the clean list must be disassociated from their 
1736                  * current vnode.  Buffers on the empty[kva] lists have
1737                  * already been disassociated.
1738                  */
1739
1740                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1741                         kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1742                         tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1743                         goto restart;
1744                 }
1745                 if (bp->b_qindex != qindex) {
1746                         kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1747                         BUF_UNLOCK(bp);
1748                         goto restart;
1749                 }
1750                 bremfree(bp);
1751
1752                 /*
1753                  * Dependancies must be handled before we disassociate the
1754                  * vnode.
1755                  *
1756                  * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1757                  * be immediately disassociated.  HAMMER then becomes
1758                  * responsible for releasing the buffer.
1759                  */
1760                 if (LIST_FIRST(&bp->b_dep) != NULL) {
1761                         buf_deallocate(bp);
1762                         if (bp->b_flags & B_LOCKED) {
1763                                 bqrelse(bp);
1764                                 goto restart;
1765                         }
1766                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1767                 }
1768
1769                 if (qindex == BQUEUE_CLEAN) {
1770                         if (bp->b_flags & B_VMIO) {
1771                                 bp->b_flags &= ~B_ASYNC;
1772                                 vfs_vmio_release(bp);
1773                         }
1774                         if (bp->b_vp)
1775                                 brelvp(bp);
1776                 }
1777
1778                 /*
1779                  * NOTE:  nbp is now entirely invalid.  We can only restart
1780                  * the scan from this point on.
1781                  *
1782                  * Get the rest of the buffer freed up.  b_kva* is still
1783                  * valid after this operation.
1784                  */
1785
1786                 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1787                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1788
1789                 /*
1790                  * critical section protection is not required when
1791                  * scrapping a buffer's contents because it is already 
1792                  * wired.
1793                  */
1794                 if (bp->b_bufsize)
1795                         allocbuf(bp, 0);
1796
1797                 bp->b_flags = B_BNOCLIP;
1798                 bp->b_cmd = BUF_CMD_DONE;
1799                 bp->b_vp = NULL;
1800                 bp->b_error = 0;
1801                 bp->b_resid = 0;
1802                 bp->b_bcount = 0;
1803                 bp->b_xio.xio_npages = 0;
1804                 bp->b_dirtyoff = bp->b_dirtyend = 0;
1805                 reinitbufbio(bp);
1806                 buf_dep_init(bp);
1807                 if (blkflags & GETBLK_BHEAVY)
1808                         bp->b_flags |= B_HEAVY;
1809
1810                 /*
1811                  * If we are defragging then free the buffer.
1812                  */
1813                 if (defrag) {
1814                         bp->b_flags |= B_INVAL;
1815                         bfreekva(bp);
1816                         brelse(bp);
1817                         defrag = 0;
1818                         goto restart;
1819                 }
1820
1821                 /*
1822                  * If we are overcomitted then recover the buffer and its
1823                  * KVM space.  This occurs in rare situations when multiple
1824                  * processes are blocked in getnewbuf() or allocbuf().
1825                  */
1826                 if (bufspace >= hibufspace)
1827                         flushingbufs = 1;
1828                 if (flushingbufs && bp->b_kvasize != 0) {
1829                         bp->b_flags |= B_INVAL;
1830                         bfreekva(bp);
1831                         brelse(bp);
1832                         goto restart;
1833                 }
1834                 if (bufspace < lobufspace)
1835                         flushingbufs = 0;
1836                 break;
1837         }
1838
1839         /*
1840          * If we exhausted our list, sleep as appropriate.  We may have to
1841          * wakeup various daemons and write out some dirty buffers.
1842          *
1843          * Generally we are sleeping due to insufficient buffer space.
1844          */
1845
1846         if (bp == NULL) {
1847                 int flags;
1848                 char *waitmsg;
1849
1850                 if (defrag) {
1851                         flags = VFS_BIO_NEED_BUFSPACE;
1852                         waitmsg = "nbufkv";
1853                 } else if (bufspace >= hibufspace) {
1854                         waitmsg = "nbufbs";
1855                         flags = VFS_BIO_NEED_BUFSPACE;
1856                 } else {
1857                         waitmsg = "newbuf";
1858                         flags = VFS_BIO_NEED_ANY;
1859                 }
1860
1861                 needsbuffer |= flags;
1862                 bd_speedup();   /* heeeelp */
1863                 while (needsbuffer & flags) {
1864                         if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1865                                 return (NULL);
1866                 }
1867         } else {
1868                 /*
1869                  * We finally have a valid bp.  We aren't quite out of the
1870                  * woods, we still have to reserve kva space.  In order
1871                  * to keep fragmentation sane we only allocate kva in
1872                  * BKVASIZE chunks.
1873                  */
1874                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1875
1876                 if (maxsize != bp->b_kvasize) {
1877                         vm_offset_t addr = 0;
1878                         int count;
1879
1880                         bfreekva(bp);
1881
1882                         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1883                         vm_map_lock(&buffer_map);
1884
1885                         if (vm_map_findspace(&buffer_map,
1886                                     vm_map_min(&buffer_map), maxsize,
1887                                     maxsize, &addr)) {
1888                                 /*
1889                                  * Uh oh.  Buffer map is too fragmented.  We
1890                                  * must defragment the map.
1891                                  */
1892                                 vm_map_unlock(&buffer_map);
1893                                 vm_map_entry_release(count);
1894                                 ++bufdefragcnt;
1895                                 defrag = 1;
1896                                 bp->b_flags |= B_INVAL;
1897                                 brelse(bp);
1898                                 goto restart;
1899                         }
1900                         if (addr) {
1901                                 vm_map_insert(&buffer_map, &count,
1902                                         NULL, 0,
1903                                         addr, addr + maxsize,
1904                                         VM_MAPTYPE_NORMAL,
1905                                         VM_PROT_ALL, VM_PROT_ALL,
1906                                         MAP_NOFAULT);
1907
1908                                 bp->b_kvabase = (caddr_t) addr;
1909                                 bp->b_kvasize = maxsize;
1910                                 bufspace += bp->b_kvasize;
1911                                 ++bufreusecnt;
1912                         }
1913                         vm_map_unlock(&buffer_map);
1914                         vm_map_entry_release(count);
1915                 }
1916                 bp->b_data = bp->b_kvabase;
1917         }
1918         return(bp);
1919 }
1920
1921 /*
1922  * buf_daemon:
1923  *
1924  *      Buffer flushing daemon.  Buffers are normally flushed by the
1925  *      update daemon but if it cannot keep up this process starts to
1926  *      take the load in an attempt to prevent getnewbuf() from blocking.
1927  *
1928  *      Once a flush is initiated it does not stop until the number
1929  *      of buffers falls below lodirtybuffers, but we will wake up anyone
1930  *      waiting at the mid-point.
1931  */
1932
1933 static struct thread *bufdaemon_td;
1934 static struct thread *bufdaemonhw_td;
1935
1936 static struct kproc_desc buf_kp = {
1937         "bufdaemon",
1938         buf_daemon,
1939         &bufdaemon_td
1940 };
1941 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1942         kproc_start, &buf_kp)
1943
1944 static struct kproc_desc bufhw_kp = {
1945         "bufdaemon_hw",
1946         buf_daemon_hw,
1947         &bufdaemonhw_td
1948 };
1949 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1950         kproc_start, &bufhw_kp)
1951
1952 static void
1953 buf_daemon(void)
1954 {
1955         /*
1956          * This process needs to be suspended prior to shutdown sync.
1957          */
1958         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1959                               bufdaemon_td, SHUTDOWN_PRI_LAST);
1960
1961         /*
1962          * This process is allowed to take the buffer cache to the limit
1963          */
1964         crit_enter();
1965
1966         for (;;) {
1967                 kproc_suspend_loop();
1968
1969                 /*
1970                  * Do the flush.  Limit the amount of in-transit I/O we
1971                  * allow to build up, otherwise we would completely saturate
1972                  * the I/O system.  Wakeup any waiting processes before we
1973                  * normally would so they can run in parallel with our drain.
1974                  */
1975                 while (numdirtybuffers > lodirtybuffers) {
1976                         if (flushbufqueues(BQUEUE_DIRTY) == 0)
1977                                 break;
1978                         waitrunningbufspace();
1979                         numdirtywakeup();
1980                 }
1981                 numdirtywakeup();
1982
1983                 /*
1984                  * Only clear bd_request if we have reached our low water
1985                  * mark.  The buf_daemon normally waits 5 seconds and
1986                  * then incrementally flushes any dirty buffers that have
1987                  * built up, within reason.
1988                  *
1989                  * If we were unable to hit our low water mark and couldn't
1990                  * find any flushable buffers, we sleep half a second. 
1991                  * Otherwise we loop immediately.
1992                  */
1993                 if (numdirtybuffers <= lodirtybuffers) {
1994                         /*
1995                          * We reached our low water mark, reset the
1996                          * request and sleep until we are needed again.
1997                          * The sleep is just so the suspend code works.
1998                          */
1999                         spin_lock_wr(&needsbuffer_spin);
2000                         bd_request = 0;
2001                         msleep(&bd_request, &needsbuffer_spin, 0,
2002                                "psleep", hz);
2003                         spin_unlock_wr(&needsbuffer_spin);
2004                 } else {
2005                         /*
2006                          * We couldn't find any flushable dirty buffers but
2007                          * still have too many dirty buffers, we
2008                          * have to sleep and try again.  (rare)
2009                          */
2010                         tsleep(&bd_request, 0, "qsleep", hz / 2);
2011                 }
2012         }
2013 }
2014
2015 static void
2016 buf_daemon_hw(void)
2017 {
2018         /*
2019          * This process needs to be suspended prior to shutdown sync.
2020          */
2021         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2022                               bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2023
2024         /*
2025          * This process is allowed to take the buffer cache to the limit
2026          */
2027         crit_enter();
2028
2029         for (;;) {
2030                 kproc_suspend_loop();
2031
2032                 /*
2033                  * Do the flush.  Limit the amount of in-transit I/O we
2034                  * allow to build up, otherwise we would completely saturate
2035                  * the I/O system.  Wakeup any waiting processes before we
2036                  * normally would so they can run in parallel with our drain.
2037                  */
2038                 while (numdirtybuffershw > lodirtybuffers) {
2039                         if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2040                                 break;
2041                         waitrunningbufspace();
2042                         numdirtywakeup();
2043                 }
2044
2045                 /*
2046                  * Only clear bd_request if we have reached our low water
2047                  * mark.  The buf_daemon normally waits 5 seconds and
2048                  * then incrementally flushes any dirty buffers that have
2049                  * built up, within reason.
2050                  *
2051                  * If we were unable to hit our low water mark and couldn't
2052                  * find any flushable buffers, we sleep half a second. 
2053                  * Otherwise we loop immediately.
2054                  */
2055                 if (numdirtybuffershw <= lodirtybuffers) {
2056                         /*
2057                          * We reached our low water mark, reset the
2058                          * request and sleep until we are needed again.
2059                          * The sleep is just so the suspend code works.
2060                          */
2061                         spin_lock_wr(&needsbuffer_spin);
2062                         bd_request_hw = 0;
2063                         msleep(&bd_request_hw, &needsbuffer_spin, 0,
2064                                "psleep", hz);
2065                         spin_unlock_wr(&needsbuffer_spin);
2066                 } else {
2067                         /*
2068                          * We couldn't find any flushable dirty buffers but
2069                          * still have too many dirty buffers, we
2070                          * have to sleep and try again.  (rare)
2071                          */
2072                         tsleep(&bd_request_hw, 0, "qsleep", hz / 2);
2073                 }
2074         }
2075 }
2076
2077 /*
2078  * flushbufqueues:
2079  *
2080  *      Try to flush a buffer in the dirty queue.  We must be careful to
2081  *      free up B_INVAL buffers instead of write them, which NFS is 
2082  *      particularly sensitive to.
2083  */
2084
2085 static int
2086 flushbufqueues(bufq_type_t q)
2087 {
2088         struct buf *bp;
2089         int r = 0;
2090
2091         bp = TAILQ_FIRST(&bufqueues[q]);
2092
2093         while (bp) {
2094                 KASSERT((bp->b_flags & B_DELWRI),
2095                         ("unexpected clean buffer %p", bp));
2096                 if (bp->b_flags & B_DELWRI) {
2097                         if (bp->b_flags & B_INVAL) {
2098                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2099                                         panic("flushbufqueues: locked buf");
2100                                 bremfree(bp);
2101                                 brelse(bp);
2102                                 ++r;
2103                                 break;
2104                         }
2105                         if (LIST_FIRST(&bp->b_dep) != NULL &&
2106                             (bp->b_flags & B_DEFERRED) == 0 &&
2107                             buf_countdeps(bp, 0)) {
2108                                 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2109                                 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2110                                                   b_freelist);
2111                                 bp->b_flags |= B_DEFERRED;
2112                                 bp = TAILQ_FIRST(&bufqueues[q]);
2113                                 continue;
2114                         }
2115
2116                         /*
2117                          * Only write it out if we can successfully lock
2118                          * it.  If the buffer has a dependancy,
2119                          * buf_checkwrite must also return 0.
2120                          */
2121                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2122                                 if (LIST_FIRST(&bp->b_dep) != NULL &&
2123                                     buf_checkwrite(bp)) {
2124                                         bremfree(bp);
2125                                         brelse(bp);
2126                                 } else {
2127                                         vfs_bio_awrite(bp);
2128                                 }
2129                                 ++r;
2130                                 break;
2131                         }
2132                 }
2133                 bp = TAILQ_NEXT(bp, b_freelist);
2134         }
2135         return (r);
2136 }
2137
2138 /*
2139  * inmem:
2140  *
2141  *      Returns true if no I/O is needed to access the associated VM object.
2142  *      This is like findblk except it also hunts around in the VM system for
2143  *      the data.
2144  *
2145  *      Note that we ignore vm_page_free() races from interrupts against our
2146  *      lookup, since if the caller is not protected our return value will not
2147  *      be any more valid then otherwise once we exit the critical section.
2148  */
2149 int
2150 inmem(struct vnode *vp, off_t loffset)
2151 {
2152         vm_object_t obj;
2153         vm_offset_t toff, tinc, size;
2154         vm_page_t m;
2155
2156         if (findblk(vp, loffset))
2157                 return 1;
2158         if (vp->v_mount == NULL)
2159                 return 0;
2160         if ((obj = vp->v_object) == NULL)
2161                 return 0;
2162
2163         size = PAGE_SIZE;
2164         if (size > vp->v_mount->mnt_stat.f_iosize)
2165                 size = vp->v_mount->mnt_stat.f_iosize;
2166
2167         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2168                 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2169                 if (m == NULL)
2170                         return 0;
2171                 tinc = size;
2172                 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2173                         tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2174                 if (vm_page_is_valid(m,
2175                     (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2176                         return 0;
2177         }
2178         return 1;
2179 }
2180
2181 /*
2182  * vfs_setdirty:
2183  *
2184  *      Sets the dirty range for a buffer based on the status of the dirty
2185  *      bits in the pages comprising the buffer.
2186  *
2187  *      The range is limited to the size of the buffer.
2188  *
2189  *      This routine is primarily used by NFS, but is generalized for the
2190  *      B_VMIO case.
2191  */
2192 static void
2193 vfs_setdirty(struct buf *bp) 
2194 {
2195         int i;
2196         vm_object_t object;
2197
2198         /*
2199          * Degenerate case - empty buffer
2200          */
2201
2202         if (bp->b_bufsize == 0)
2203                 return;
2204
2205         /*
2206          * We qualify the scan for modified pages on whether the
2207          * object has been flushed yet.  The OBJ_WRITEABLE flag
2208          * is not cleared simply by protecting pages off.
2209          */
2210
2211         if ((bp->b_flags & B_VMIO) == 0)
2212                 return;
2213
2214         object = bp->b_xio.xio_pages[0]->object;
2215
2216         if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2217                 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2218         if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2219                 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2220
2221         if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2222                 vm_offset_t boffset;
2223                 vm_offset_t eoffset;
2224
2225                 /*
2226                  * test the pages to see if they have been modified directly
2227                  * by users through the VM system.
2228                  */
2229                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2230                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2231                         vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2232                 }
2233
2234                 /*
2235                  * Calculate the encompassing dirty range, boffset and eoffset,
2236                  * (eoffset - boffset) bytes.
2237                  */
2238
2239                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2240                         if (bp->b_xio.xio_pages[i]->dirty)
2241                                 break;
2242                 }
2243                 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2244
2245                 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2246                         if (bp->b_xio.xio_pages[i]->dirty) {
2247                                 break;
2248                         }
2249                 }
2250                 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2251
2252                 /*
2253                  * Fit it to the buffer.
2254                  */
2255
2256                 if (eoffset > bp->b_bcount)
2257                         eoffset = bp->b_bcount;
2258
2259                 /*
2260                  * If we have a good dirty range, merge with the existing
2261                  * dirty range.
2262                  */
2263
2264                 if (boffset < eoffset) {
2265                         if (bp->b_dirtyoff > boffset)
2266                                 bp->b_dirtyoff = boffset;
2267                         if (bp->b_dirtyend < eoffset)
2268                                 bp->b_dirtyend = eoffset;
2269                 }
2270         }
2271 }
2272
2273 /*
2274  * findblk:
2275  *
2276  *      Locate and return the specified buffer, or NULL if the buffer does
2277  *      not exist.  Do not attempt to lock the buffer or manipulate it in
2278  *      any way.  The caller must validate that the correct buffer has been
2279  *      obtain after locking it.
2280  */
2281 struct buf *
2282 findblk(struct vnode *vp, off_t loffset)
2283 {
2284         struct buf *bp;
2285
2286         crit_enter();
2287         bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2288         crit_exit();
2289         return(bp);
2290 }
2291
2292 /*
2293  * getblk:
2294  *
2295  *      Get a block given a specified block and offset into a file/device.
2296  *      B_INVAL may or may not be set on return.  The caller should clear
2297  *      B_INVAL prior to initiating a READ.
2298  *
2299  *      IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2300  *      IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2301  *      OR SET B_INVAL BEFORE RETIRING IT.  If you retire a getblk'd buffer
2302  *      without doing any of those things the system will likely believe
2303  *      the buffer to be valid (especially if it is not B_VMIO), and the
2304  *      next getblk() will return the buffer with B_CACHE set.
2305  *
2306  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2307  *      an existing buffer.
2308  *
2309  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
2310  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2311  *      and then cleared based on the backing VM.  If the previous buffer is
2312  *      non-0-sized but invalid, B_CACHE will be cleared.
2313  *
2314  *      If getblk() must create a new buffer, the new buffer is returned with
2315  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2316  *      case it is returned with B_INVAL clear and B_CACHE set based on the
2317  *      backing VM.
2318  *
2319  *      getblk() also forces a bwrite() for any B_DELWRI buffer whos
2320  *      B_CACHE bit is clear.
2321  *      
2322  *      What this means, basically, is that the caller should use B_CACHE to
2323  *      determine whether the buffer is fully valid or not and should clear
2324  *      B_INVAL prior to issuing a read.  If the caller intends to validate
2325  *      the buffer by loading its data area with something, the caller needs
2326  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
2327  *      the caller should set B_CACHE ( as an optimization ), else the caller
2328  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
2329  *      a write attempt or if it was a successfull read.  If the caller 
2330  *      intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2331  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2332  *
2333  *      getblk flags:
2334  *
2335  *      GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2336  *      GETBLK_BHEAVY - heavy-weight buffer cache buffer
2337  */
2338 struct buf *
2339 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2340 {
2341         struct buf *bp;
2342         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2343
2344         if (size > MAXBSIZE)
2345                 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2346         if (vp->v_object == NULL)
2347                 panic("getblk: vnode %p has no object!", vp);
2348
2349         crit_enter();
2350 loop:
2351         if ((bp = findblk(vp, loffset))) {
2352                 /*
2353                  * The buffer was found in the cache, but we need to lock it.
2354                  * Even with LK_NOWAIT the lockmgr may break our critical
2355                  * section, so double-check the validity of the buffer
2356                  * once the lock has been obtained.
2357                  */
2358                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2359                         int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2360                         if (blkflags & GETBLK_PCATCH)
2361                                 lkflags |= LK_PCATCH;
2362                         if (BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo) ==
2363                             ENOLCK) {
2364                                 goto loop;
2365                         }
2366                         crit_exit();
2367                         return (NULL);
2368                 }
2369
2370                 /*
2371                  * Once the buffer has been locked, make sure we didn't race
2372                  * a buffer recyclement.  Buffers that are no longer hashed
2373                  * will have b_vp == NULL, so this takes care of that check
2374                  * as well.
2375                  */
2376                 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2377                         kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2378                         BUF_UNLOCK(bp);
2379                         goto loop;
2380                 }
2381
2382                 /*
2383                  * All vnode-based buffers must be backed by a VM object.
2384                  */
2385                 KKASSERT(bp->b_flags & B_VMIO);
2386                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2387
2388                 /*
2389                  * Make sure that B_INVAL buffers do not have a cached
2390                  * block number translation.
2391                  */
2392                 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2393                         kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2394                         clearbiocache(&bp->b_bio2);
2395                 }
2396
2397                 /*
2398                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
2399                  * invalid.
2400                  */
2401                 if (bp->b_flags & B_INVAL)
2402                         bp->b_flags &= ~B_CACHE;
2403                 bremfree(bp);
2404
2405                 /*
2406                  * Any size inconsistancy with a dirty buffer or a buffer
2407                  * with a softupdates dependancy must be resolved.  Resizing
2408                  * the buffer in such circumstances can lead to problems.
2409                  */
2410                 if (size != bp->b_bcount) {
2411                         if (bp->b_flags & B_DELWRI) {
2412                                 bp->b_flags |= B_NOCACHE;
2413                                 bwrite(bp);
2414                         } else if (LIST_FIRST(&bp->b_dep)) {
2415                                 bp->b_flags |= B_NOCACHE;
2416                                 bwrite(bp);
2417                         } else {
2418                                 bp->b_flags |= B_RELBUF;
2419                                 brelse(bp);
2420                         }
2421                         goto loop;
2422                 }
2423                 KKASSERT(size <= bp->b_kvasize);
2424                 KASSERT(bp->b_loffset != NOOFFSET, 
2425                         ("getblk: no buffer offset"));
2426
2427                 /*
2428                  * A buffer with B_DELWRI set and B_CACHE clear must
2429                  * be committed before we can return the buffer in
2430                  * order to prevent the caller from issuing a read
2431                  * ( due to B_CACHE not being set ) and overwriting
2432                  * it.
2433                  *
2434                  * Most callers, including NFS and FFS, need this to
2435                  * operate properly either because they assume they
2436                  * can issue a read if B_CACHE is not set, or because
2437                  * ( for example ) an uncached B_DELWRI might loop due 
2438                  * to softupdates re-dirtying the buffer.  In the latter
2439                  * case, B_CACHE is set after the first write completes,
2440                  * preventing further loops.
2441                  *
2442                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2443                  * above while extending the buffer, we cannot allow the
2444                  * buffer to remain with B_CACHE set after the write
2445                  * completes or it will represent a corrupt state.  To
2446                  * deal with this we set B_NOCACHE to scrap the buffer
2447                  * after the write.
2448                  *
2449                  * We might be able to do something fancy, like setting
2450                  * B_CACHE in bwrite() except if B_DELWRI is already set,
2451                  * so the below call doesn't set B_CACHE, but that gets real
2452                  * confusing.  This is much easier.
2453                  */
2454
2455                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2456                         bp->b_flags |= B_NOCACHE;
2457                         bwrite(bp);
2458                         goto loop;
2459                 }
2460                 crit_exit();
2461         } else {
2462                 /*
2463                  * Buffer is not in-core, create new buffer.  The buffer
2464                  * returned by getnewbuf() is locked.  Note that the returned
2465                  * buffer is also considered valid (not marked B_INVAL).
2466                  *
2467                  * Calculating the offset for the I/O requires figuring out
2468                  * the block size.  We use DEV_BSIZE for VBLK or VCHR and
2469                  * the mount's f_iosize otherwise.  If the vnode does not
2470                  * have an associated mount we assume that the passed size is 
2471                  * the block size.  
2472                  *
2473                  * Note that vn_isdisk() cannot be used here since it may
2474                  * return a failure for numerous reasons.   Note that the
2475                  * buffer size may be larger then the block size (the caller
2476                  * will use block numbers with the proper multiple).  Beware
2477                  * of using any v_* fields which are part of unions.  In
2478                  * particular, in DragonFly the mount point overloading 
2479                  * mechanism uses the namecache only and the underlying
2480                  * directory vnode is not a special case.
2481                  */
2482                 int bsize, maxsize;
2483
2484                 /*
2485                  * Don't let heavy weight buffers deadlock us.
2486                  */
2487                 if ((blkflags & GETBLK_BHEAVY) &&
2488                     numdirtybuffershw > hidirtybuffers) {
2489                         while (numdirtybuffershw > hidirtybuffers) {
2490                                 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
2491                                 tsleep(&needsbuffer, slpflags, "newbuf",
2492                                        slptimeo);
2493                         }
2494                         goto loop;
2495                 }
2496
2497                 if (vp->v_type == VBLK || vp->v_type == VCHR)
2498                         bsize = DEV_BSIZE;
2499                 else if (vp->v_mount)
2500                         bsize = vp->v_mount->mnt_stat.f_iosize;
2501                 else
2502                         bsize = size;
2503
2504                 maxsize = size + (loffset & PAGE_MASK);
2505                 maxsize = imax(maxsize, bsize);
2506
2507                 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2508                         if (slpflags || slptimeo) {
2509                                 crit_exit();
2510                                 return NULL;
2511                         }
2512                         goto loop;
2513                 }
2514
2515                 /*
2516                  * This code is used to make sure that a buffer is not
2517                  * created while the getnewbuf routine is blocked.
2518                  * This can be a problem whether the vnode is locked or not.
2519                  * If the buffer is created out from under us, we have to
2520                  * throw away the one we just created.  There is no window
2521                  * race because we are safely running in a critical section
2522                  * from the point of the duplicate buffer creation through
2523                  * to here, and we've locked the buffer.
2524                  */
2525                 if (findblk(vp, loffset)) {
2526                         bp->b_flags |= B_INVAL;
2527                         brelse(bp);
2528                         goto loop;
2529                 }
2530
2531                 /*
2532                  * Insert the buffer into the hash, so that it can
2533                  * be found by findblk(). 
2534                  *
2535                  * Make sure the translation layer has been cleared.
2536                  */
2537                 bp->b_loffset = loffset;
2538                 bp->b_bio2.bio_offset = NOOFFSET;
2539                 /* bp->b_bio2.bio_next = NULL; */
2540
2541                 bgetvp(vp, bp);
2542
2543                 /*
2544                  * All vnode-based buffers must be backed by a VM object.
2545                  */
2546                 KKASSERT(vp->v_object != NULL);
2547                 bp->b_flags |= B_VMIO;
2548                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2549
2550                 allocbuf(bp, size);
2551
2552                 crit_exit();
2553         }
2554         return (bp);
2555 }
2556
2557 /*
2558  * regetblk(bp)
2559  *
2560  * Reacquire a buffer that was previously released to the locked queue,
2561  * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2562  * set B_LOCKED (which handles the acquisition race).
2563  *
2564  * To this end, either B_LOCKED must be set or the dependancy list must be
2565  * non-empty.
2566  */
2567 void
2568 regetblk(struct buf *bp)
2569 {
2570         KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2571         BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2572         crit_enter();
2573         bremfree(bp);
2574         crit_exit();
2575 }
2576
2577 /*
2578  * geteblk:
2579  *
2580  *      Get an empty, disassociated buffer of given size.  The buffer is
2581  *      initially set to B_INVAL.
2582  *
2583  *      critical section protection is not required for the allocbuf()
2584  *      call because races are impossible here.
2585  */
2586 struct buf *
2587 geteblk(int size)
2588 {
2589         struct buf *bp;
2590         int maxsize;
2591
2592         maxsize = (size + BKVAMASK) & ~BKVAMASK;
2593
2594         crit_enter();
2595         while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2596                 ;
2597         crit_exit();
2598         allocbuf(bp, size);
2599         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2600         return (bp);
2601 }
2602
2603
2604 /*
2605  * allocbuf:
2606  *
2607  *      This code constitutes the buffer memory from either anonymous system
2608  *      memory (in the case of non-VMIO operations) or from an associated
2609  *      VM object (in the case of VMIO operations).  This code is able to
2610  *      resize a buffer up or down.
2611  *
2612  *      Note that this code is tricky, and has many complications to resolve
2613  *      deadlock or inconsistant data situations.  Tread lightly!!! 
2614  *      There are B_CACHE and B_DELWRI interactions that must be dealt with by 
2615  *      the caller.  Calling this code willy nilly can result in the loss of data.
2616  *
2617  *      allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2618  *      B_CACHE for the non-VMIO case.
2619  *
2620  *      This routine does not need to be called from a critical section but you
2621  *      must own the buffer.
2622  */
2623 int
2624 allocbuf(struct buf *bp, int size)
2625 {
2626         int newbsize, mbsize;
2627         int i;
2628
2629         if (BUF_REFCNT(bp) == 0)
2630                 panic("allocbuf: buffer not busy");
2631
2632         if (bp->b_kvasize < size)
2633                 panic("allocbuf: buffer too small");
2634
2635         if ((bp->b_flags & B_VMIO) == 0) {
2636                 caddr_t origbuf;
2637                 int origbufsize;
2638                 /*
2639                  * Just get anonymous memory from the kernel.  Don't
2640                  * mess with B_CACHE.
2641                  */
2642                 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2643                 if (bp->b_flags & B_MALLOC)
2644                         newbsize = mbsize;
2645                 else
2646                         newbsize = round_page(size);
2647
2648                 if (newbsize < bp->b_bufsize) {
2649                         /*
2650                          * Malloced buffers are not shrunk
2651                          */
2652                         if (bp->b_flags & B_MALLOC) {
2653                                 if (newbsize) {
2654                                         bp->b_bcount = size;
2655                                 } else {
2656                                         kfree(bp->b_data, M_BIOBUF);
2657                                         if (bp->b_bufsize) {
2658                                                 bufmallocspace -= bp->b_bufsize;
2659                                                 bufspacewakeup();
2660                                                 bp->b_bufsize = 0;
2661                                         }
2662                                         bp->b_data = bp->b_kvabase;
2663                                         bp->b_bcount = 0;
2664                                         bp->b_flags &= ~B_MALLOC;
2665                                 }
2666                                 return 1;
2667                         }               
2668                         vm_hold_free_pages(
2669                             bp,
2670                             (vm_offset_t) bp->b_data + newbsize,
2671                             (vm_offset_t) bp->b_data + bp->b_bufsize);
2672                 } else if (newbsize > bp->b_bufsize) {
2673                         /*
2674                          * We only use malloced memory on the first allocation.
2675                          * and revert to page-allocated memory when the buffer
2676                          * grows.
2677                          */
2678                         if ((bufmallocspace < maxbufmallocspace) &&
2679                                 (bp->b_bufsize == 0) &&
2680                                 (mbsize <= PAGE_SIZE/2)) {
2681
2682                                 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2683                                 bp->b_bufsize = mbsize;
2684                                 bp->b_bcount = size;
2685                                 bp->b_flags |= B_MALLOC;
2686                                 bufmallocspace += mbsize;
2687                                 return 1;
2688                         }
2689                         origbuf = NULL;
2690                         origbufsize = 0;
2691                         /*
2692                          * If the buffer is growing on its other-than-first
2693                          * allocation, then we revert to the page-allocation
2694                          * scheme.
2695                          */
2696                         if (bp->b_flags & B_MALLOC) {
2697                                 origbuf = bp->b_data;
2698                                 origbufsize = bp->b_bufsize;
2699                                 bp->b_data = bp->b_kvabase;
2700                                 if (bp->b_bufsize) {
2701                                         bufmallocspace -= bp->b_bufsize;
2702                                         bufspacewakeup();
2703                                         bp->b_bufsize = 0;
2704                                 }
2705                                 bp->b_flags &= ~B_MALLOC;
2706                                 newbsize = round_page(newbsize);
2707                         }
2708                         vm_hold_load_pages(
2709                             bp,
2710                             (vm_offset_t) bp->b_data + bp->b_bufsize,
2711                             (vm_offset_t) bp->b_data + newbsize);
2712                         if (origbuf) {
2713                                 bcopy(origbuf, bp->b_data, origbufsize);
2714                                 kfree(origbuf, M_BIOBUF);
2715                         }
2716                 }
2717         } else {
2718                 vm_page_t m;
2719                 int desiredpages;
2720
2721                 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2722                 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2723                                 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2724                 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2725
2726                 if (bp->b_flags & B_MALLOC)
2727                         panic("allocbuf: VMIO buffer can't be malloced");
2728                 /*
2729                  * Set B_CACHE initially if buffer is 0 length or will become
2730                  * 0-length.
2731                  */
2732                 if (size == 0 || bp->b_bufsize == 0)
2733                         bp->b_flags |= B_CACHE;
2734
2735                 if (newbsize < bp->b_bufsize) {
2736                         /*
2737                          * DEV_BSIZE aligned new buffer size is less then the
2738                          * DEV_BSIZE aligned existing buffer size.  Figure out
2739                          * if we have to remove any pages.
2740                          */
2741                         if (desiredpages < bp->b_xio.xio_npages) {
2742                                 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2743                                         /*
2744                                          * the page is not freed here -- it
2745                                          * is the responsibility of 
2746                                          * vnode_pager_setsize
2747                                          */
2748                                         m = bp->b_xio.xio_pages[i];
2749                                         KASSERT(m != bogus_page,
2750                                             ("allocbuf: bogus page found"));
2751                                         while (vm_page_sleep_busy(m, TRUE, "biodep"))
2752                                                 ;
2753
2754                                         bp->b_xio.xio_pages[i] = NULL;
2755                                         vm_page_unwire(m, 0);
2756                                 }
2757                                 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2758                                     (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2759                                 bp->b_xio.xio_npages = desiredpages;
2760                         }
2761                 } else if (size > bp->b_bcount) {
2762                         /*
2763                          * We are growing the buffer, possibly in a 
2764                          * byte-granular fashion.
2765                          */
2766                         struct vnode *vp;
2767                         vm_object_t obj;
2768                         vm_offset_t toff;
2769                         vm_offset_t tinc;
2770
2771                         /*
2772                          * Step 1, bring in the VM pages from the object, 
2773                          * allocating them if necessary.  We must clear
2774                          * B_CACHE if these pages are not valid for the 
2775                          * range covered by the buffer.
2776                          *
2777                          * critical section protection is required to protect
2778                          * against interrupts unbusying and freeing pages
2779                          * between our vm_page_lookup() and our
2780                          * busycheck/wiring call.
2781                          */
2782                         vp = bp->b_vp;
2783                         obj = vp->v_object;
2784
2785                         crit_enter();
2786                         while (bp->b_xio.xio_npages < desiredpages) {
2787                                 vm_page_t m;
2788                                 vm_pindex_t pi;
2789
2790                                 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2791                                 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2792                                         /*
2793                                          * note: must allocate system pages
2794                                          * since blocking here could intefere
2795                                          * with paging I/O, no matter which
2796                                          * process we are.
2797                                          */
2798                                         m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2799                                         if (m == NULL) {
2800                                                 vm_wait();
2801                                                 vm_pageout_deficit += desiredpages -
2802                                                         bp->b_xio.xio_npages;
2803                                         } else {
2804                                                 vm_page_wire(m);
2805                                                 vm_page_wakeup(m);
2806                                                 bp->b_flags &= ~B_CACHE;
2807                                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2808                                                 ++bp->b_xio.xio_npages;
2809                                         }
2810                                         continue;
2811                                 }
2812
2813                                 /*
2814                                  * We found a page.  If we have to sleep on it,
2815                                  * retry because it might have gotten freed out
2816                                  * from under us.
2817                                  *
2818                                  * We can only test PG_BUSY here.  Blocking on
2819                                  * m->busy might lead to a deadlock:
2820                                  *
2821                                  *  vm_fault->getpages->cluster_read->allocbuf
2822                                  *
2823                                  */
2824
2825                                 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2826                                         continue;
2827
2828                                 /*
2829                                  * We have a good page.  Should we wakeup the
2830                                  * page daemon?
2831                                  */
2832                                 if ((curthread != pagethread) &&
2833                                     ((m->queue - m->pc) == PQ_CACHE) &&
2834                                     ((vmstats.v_free_count + vmstats.v_cache_count) <
2835                                         (vmstats.v_free_min + vmstats.v_cache_min))) {
2836                                         pagedaemon_wakeup();
2837                                 }
2838                                 vm_page_flag_clear(m, PG_ZERO);
2839                                 vm_page_wire(m);
2840                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2841                                 ++bp->b_xio.xio_npages;
2842                         }
2843                         crit_exit();
2844
2845                         /*
2846                          * Step 2.  We've loaded the pages into the buffer,
2847                          * we have to figure out if we can still have B_CACHE
2848                          * set.  Note that B_CACHE is set according to the
2849                          * byte-granular range ( bcount and size ), not the
2850                          * aligned range ( newbsize ).
2851                          *
2852                          * The VM test is against m->valid, which is DEV_BSIZE
2853                          * aligned.  Needless to say, the validity of the data
2854                          * needs to also be DEV_BSIZE aligned.  Note that this
2855                          * fails with NFS if the server or some other client
2856                          * extends the file's EOF.  If our buffer is resized, 
2857                          * B_CACHE may remain set! XXX
2858                          */
2859
2860                         toff = bp->b_bcount;
2861                         tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2862
2863                         while ((bp->b_flags & B_CACHE) && toff < size) {
2864                                 vm_pindex_t pi;
2865
2866                                 if (tinc > (size - toff))
2867                                         tinc = size - toff;
2868
2869                                 pi = ((bp->b_loffset & PAGE_MASK) + toff) >> 
2870                                     PAGE_SHIFT;
2871
2872                                 vfs_buf_test_cache(
2873                                     bp, 
2874                                     bp->b_loffset,
2875                                     toff, 
2876                                     tinc, 
2877                                     bp->b_xio.xio_pages[pi]
2878                                 );
2879                                 toff += tinc;
2880                                 tinc = PAGE_SIZE;
2881                         }
2882
2883                         /*
2884                          * Step 3, fixup the KVM pmap.  Remember that
2885                          * bp->b_data is relative to bp->b_loffset, but 
2886                          * bp->b_loffset may be offset into the first page.
2887                          */
2888
2889                         bp->b_data = (caddr_t)
2890                             trunc_page((vm_offset_t)bp->b_data);
2891                         pmap_qenter(
2892                             (vm_offset_t)bp->b_data,
2893                             bp->b_xio.xio_pages, 
2894                             bp->b_xio.xio_npages
2895                         );
2896                         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 
2897                             (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2898                 }
2899         }
2900         if (newbsize < bp->b_bufsize)
2901                 bufspacewakeup();
2902         bp->b_bufsize = newbsize;       /* actual buffer allocation     */
2903         bp->b_bcount = size;            /* requested buffer size        */
2904         return 1;
2905 }
2906
2907 /*
2908  * biowait:
2909  *
2910  *      Wait for buffer I/O completion, returning error status.  The buffer
2911  *      is left locked on return.  B_EINTR is converted into an EINTR error
2912  *      and cleared.
2913  *
2914  *      NOTE!  The original b_cmd is lost on return, since b_cmd will be
2915  *      set to BUF_CMD_DONE.
2916  */
2917 int
2918 biowait(struct buf *bp)
2919 {
2920         crit_enter();
2921         while (bp->b_cmd != BUF_CMD_DONE) {
2922                 if (bp->b_cmd == BUF_CMD_READ)
2923                         tsleep(bp, 0, "biord", 0);
2924                 else
2925                         tsleep(bp, 0, "biowr", 0);
2926         }
2927         crit_exit();
2928         if (bp->b_flags & B_EINTR) {
2929                 bp->b_flags &= ~B_EINTR;
2930                 return (EINTR);
2931         }
2932         if (bp->b_flags & B_ERROR) {
2933                 return (bp->b_error ? bp->b_error : EIO);
2934         } else {
2935                 return (0);
2936         }
2937 }
2938
2939 /*
2940  * This associates a tracking count with an I/O.  vn_strategy() and
2941  * dev_dstrategy() do this automatically but there are a few cases
2942  * where a vnode or device layer is bypassed when a block translation
2943  * is cached.  In such cases bio_start_transaction() may be called on
2944  * the bypassed layers so the system gets an I/O in progress indication 
2945  * for those higher layers.
2946  */
2947 void
2948 bio_start_transaction(struct bio *bio, struct bio_track *track)
2949 {
2950         bio->bio_track = track;
2951         atomic_add_int(&track->bk_active, 1);
2952 }
2953
2954 /*
2955  * Initiate I/O on a vnode.
2956  */
2957 void
2958 vn_strategy(struct vnode *vp, struct bio *bio)
2959 {
2960         struct bio_track *track;
2961
2962         KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
2963         if (bio->bio_buf->b_cmd == BUF_CMD_READ)
2964                 track = &vp->v_track_read;
2965         else
2966                 track = &vp->v_track_write;
2967         bio->bio_track = track;
2968         atomic_add_int(&track->bk_active, 1);
2969         vop_strategy(*vp->v_ops, vp, bio);
2970 }
2971
2972
2973 /*
2974  * biodone:
2975  *
2976  *      Finish I/O on a buffer, optionally calling a completion function.
2977  *      This is usually called from an interrupt so process blocking is
2978  *      not allowed.
2979  *
2980  *      biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2981  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
2982  *      assuming B_INVAL is clear.
2983  *
2984  *      For the VMIO case, we set B_CACHE if the op was a read and no
2985  *      read error occured, or if the op was a write.  B_CACHE is never
2986  *      set if the buffer is invalid or otherwise uncacheable.
2987  *
2988  *      biodone does not mess with B_INVAL, allowing the I/O routine or the
2989  *      initiator to leave B_INVAL set to brelse the buffer out of existance
2990  *      in the biodone routine.
2991  */
2992 void
2993 biodone(struct bio *bio)
2994 {
2995         struct buf *bp = bio->bio_buf;
2996         buf_cmd_t cmd;
2997
2998         crit_enter();
2999
3000         KASSERT(BUF_REFCNTNB(bp) > 0, 
3001                 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3002         KASSERT(bp->b_cmd != BUF_CMD_DONE, 
3003                 ("biodone: bp %p already done!", bp));
3004
3005         runningbufwakeup(bp);
3006
3007         /*
3008          * Run up the chain of BIO's.   Leave b_cmd intact for the duration.
3009          */
3010         while (bio) {
3011                 biodone_t *done_func; 
3012                 struct bio_track *track;
3013
3014                 /*
3015                  * BIO tracking.  Most but not all BIOs are tracked.
3016                  */
3017                 if ((track = bio->bio_track) != NULL) {
3018                         atomic_subtract_int(&track->bk_active, 1);
3019                         if (track->bk_active < 0) {
3020                                 panic("biodone: bad active count bio %p\n",
3021                                       bio);
3022                         }
3023                         if (track->bk_waitflag) {
3024                                 track->bk_waitflag = 0;
3025                                 wakeup(track);
3026                         }
3027                         bio->bio_track = NULL;
3028                 }
3029
3030                 /*
3031                  * A bio_done function terminates the loop.  The function
3032                  * will be responsible for any further chaining and/or 
3033                  * buffer management.
3034                  *
3035                  * WARNING!  The done function can deallocate the buffer!
3036                  */
3037                 if ((done_func = bio->bio_done) != NULL) {
3038                         bio->bio_done = NULL;
3039                         done_func(bio);
3040                         crit_exit();
3041                         return;
3042                 }
3043                 bio = bio->bio_prev;
3044         }
3045
3046         cmd = bp->b_cmd;
3047         bp->b_cmd = BUF_CMD_DONE;
3048
3049         /*
3050          * Only reads and writes are processed past this point.
3051          */
3052         if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3053                 brelse(bp);
3054                 crit_exit();
3055                 return;
3056         }
3057
3058         /*
3059          * Warning: softupdates may re-dirty the buffer.
3060          */
3061         if (LIST_FIRST(&bp->b_dep) != NULL)
3062                 buf_complete(bp);
3063
3064         if (bp->b_flags & B_VMIO) {
3065                 int i;
3066                 vm_ooffset_t foff;
3067                 vm_page_t m;
3068                 vm_object_t obj;
3069                 int iosize;
3070                 struct vnode *vp = bp->b_vp;
3071
3072                 obj = vp->v_object;
3073
3074 #if defined(VFS_BIO_DEBUG)
3075                 if (vp->v_auxrefs == 0)
3076                         panic("biodone: zero vnode hold count");
3077                 if ((vp->v_flag & VOBJBUF) == 0)
3078                         panic("biodone: vnode is not setup for merged cache");
3079 #endif
3080
3081                 foff = bp->b_loffset;
3082                 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3083                 KASSERT(obj != NULL, ("biodone: missing VM object"));
3084
3085 #if defined(VFS_BIO_DEBUG)
3086                 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3087                         kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3088                             obj->paging_in_progress, bp->b_xio.xio_npages);
3089                 }
3090 #endif
3091
3092                 /*
3093                  * Set B_CACHE if the op was a normal read and no error
3094                  * occured.  B_CACHE is set for writes in the b*write()
3095                  * routines.
3096                  */
3097                 iosize = bp->b_bcount - bp->b_resid;
3098                 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3099                         bp->b_flags |= B_CACHE;
3100                 }
3101
3102                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3103                         int bogusflag = 0;
3104                         int resid;
3105
3106                         resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3107                         if (resid > iosize)
3108                                 resid = iosize;
3109
3110                         /*
3111                          * cleanup bogus pages, restoring the originals.  Since
3112                          * the originals should still be wired, we don't have
3113                          * to worry about interrupt/freeing races destroying
3114                          * the VM object association.
3115                          */
3116                         m = bp->b_xio.xio_pages[i];
3117                         if (m == bogus_page) {
3118                                 bogusflag = 1;
3119                                 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3120                                 if (m == NULL)
3121                                         panic("biodone: page disappeared");
3122                                 bp->b_xio.xio_pages[i] = m;
3123                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3124                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3125                         }
3126 #if defined(VFS_BIO_DEBUG)
3127                         if (OFF_TO_IDX(foff) != m->pindex) {
3128                                 kprintf(
3129 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3130                                     (unsigned long)foff, m->pindex);
3131                         }
3132 #endif
3133
3134                         /*
3135                          * In the write case, the valid and clean bits are
3136                          * already changed correctly ( see bdwrite() ), so we 
3137                          * only need to do this here in the read case.
3138                          */
3139                         if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3140                                 vfs_page_set_valid(bp, foff, i, m);
3141                         }
3142                         vm_page_flag_clear(m, PG_ZERO);
3143
3144                         /*
3145                          * when debugging new filesystems or buffer I/O methods, this
3146                          * is the most common error that pops up.  if you see this, you
3147                          * have not set the page busy flag correctly!!!
3148                          */
3149                         if (m->busy == 0) {
3150                                 kprintf("biodone: page busy < 0, "
3151                                     "pindex: %d, foff: 0x(%x,%x), "
3152                                     "resid: %d, index: %d\n",
3153                                     (int) m->pindex, (int)(foff >> 32),
3154                                                 (int) foff & 0xffffffff, resid, i);
3155                                 if (!vn_isdisk(vp, NULL))
3156                                         kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3157                                             bp->b_vp->v_mount->mnt_stat.f_iosize,
3158                                             bp->b_loffset,
3159                                             bp->b_flags, bp->b_xio.xio_npages);
3160                                 else
3161                                         kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3162                                             bp->b_loffset,
3163                                             bp->b_flags, bp->b_xio.xio_npages);
3164                                 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3165                                     m->valid, m->dirty, m->wire_count);
3166                                 panic("biodone: page busy < 0");
3167                         }
3168                         vm_page_io_finish(m);
3169                         vm_object_pip_subtract(obj, 1);
3170                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3171                         iosize -= resid;
3172                 }
3173                 if (obj)
3174                         vm_object_pip_wakeupn(obj, 0);
3175         }
3176
3177         /*
3178          * For asynchronous completions, release the buffer now. The brelse
3179          * will do a wakeup there if necessary - so no need to do a wakeup
3180          * here in the async case. The sync case always needs to do a wakeup.
3181          */
3182
3183         if (bp->b_flags & B_ASYNC) {
3184                 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3185                         brelse(bp);
3186                 else
3187                         bqrelse(bp);
3188         } else {
3189                 wakeup(bp);
3190         }
3191         crit_exit();
3192 }
3193
3194 /*
3195  * vfs_unbusy_pages:
3196  *
3197  *      This routine is called in lieu of iodone in the case of
3198  *      incomplete I/O.  This keeps the busy status for pages
3199  *      consistant.
3200  */
3201 void
3202 vfs_unbusy_pages(struct buf *bp)
3203 {
3204         int i;
3205
3206         runningbufwakeup(bp);
3207         if (bp->b_flags & B_VMIO) {
3208                 struct vnode *vp = bp->b_vp;
3209                 vm_object_t obj;
3210
3211                 obj = vp->v_object;
3212
3213                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3214                         vm_page_t m = bp->b_xio.xio_pages[i];
3215
3216                         /*
3217                          * When restoring bogus changes the original pages
3218                          * should still be wired, so we are in no danger of
3219                          * losing the object association and do not need
3220                          * critical section protection particularly.
3221                          */
3222                         if (m == bogus_page) {
3223                                 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3224                                 if (!m) {
3225                                         panic("vfs_unbusy_pages: page missing");
3226                                 }
3227                                 bp->b_xio.xio_pages[i] = m;
3228                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3229                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3230                         }
3231                         vm_object_pip_subtract(obj, 1);
3232                         vm_page_flag_clear(m, PG_ZERO);
3233                         vm_page_io_finish(m);
3234                 }
3235                 vm_object_pip_wakeupn(obj, 0);
3236         }
3237 }
3238
3239 /*
3240  * vfs_page_set_valid:
3241  *
3242  *      Set the valid bits in a page based on the supplied offset.   The
3243  *      range is restricted to the buffer's size.
3244  *
3245  *      This routine is typically called after a read completes.
3246  */
3247 static void
3248 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3249 {
3250         vm_ooffset_t soff, eoff;
3251
3252         /*
3253          * Start and end offsets in buffer.  eoff - soff may not cross a
3254          * page boundry or cross the end of the buffer.  The end of the
3255          * buffer, in this case, is our file EOF, not the allocation size
3256          * of the buffer.
3257          */
3258         soff = off;
3259         eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3260         if (eoff > bp->b_loffset + bp->b_bcount)
3261                 eoff = bp->b_loffset + bp->b_bcount;
3262
3263         /*
3264          * Set valid range.  This is typically the entire buffer and thus the
3265          * entire page.
3266          */
3267         if (eoff > soff) {
3268                 vm_page_set_validclean(
3269                     m,
3270                    (vm_offset_t) (soff & PAGE_MASK),
3271                    (vm_offset_t) (eoff - soff)
3272                 );
3273         }
3274 }
3275
3276 /*
3277  * vfs_busy_pages:
3278  *
3279  *      This routine is called before a device strategy routine.
3280  *      It is used to tell the VM system that paging I/O is in
3281  *      progress, and treat the pages associated with the buffer
3282  *      almost as being PG_BUSY.  Also the object 'paging_in_progress'
3283  *      flag is handled to make sure that the object doesn't become
3284  *      inconsistant.
3285  *
3286  *      Since I/O has not been initiated yet, certain buffer flags
3287  *      such as B_ERROR or B_INVAL may be in an inconsistant state
3288  *      and should be ignored.
3289  */
3290 void
3291 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3292 {
3293         int i, bogus;
3294         struct lwp *lp = curthread->td_lwp;
3295
3296         /*
3297          * The buffer's I/O command must already be set.  If reading,
3298          * B_CACHE must be 0 (double check against callers only doing
3299          * I/O when B_CACHE is 0).
3300          */
3301         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3302         KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3303
3304         if (bp->b_flags & B_VMIO) {
3305                 vm_object_t obj;
3306                 vm_ooffset_t foff;
3307
3308                 obj = vp->v_object;
3309                 foff = bp->b_loffset;
3310                 KASSERT(bp->b_loffset != NOOFFSET,
3311                         ("vfs_busy_pages: no buffer offset"));
3312                 vfs_setdirty(bp);
3313
3314 retry:
3315                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3316                         vm_page_t m = bp->b_xio.xio_pages[i];
3317                         if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3318                                 goto retry;
3319                 }
3320
3321                 bogus = 0;
3322                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3323                         vm_page_t m = bp->b_xio.xio_pages[i];
3324
3325                         vm_page_flag_clear(m, PG_ZERO);
3326                         if ((bp->b_flags & B_CLUSTER) == 0) {
3327                                 vm_object_pip_add(obj, 1);
3328                                 vm_page_io_start(m);
3329                         }
3330
3331                         /*
3332                          * When readying a vnode-backed buffer for a write
3333                          * we must zero-fill any invalid portions of the
3334                          * backing VM pages.
3335                          *
3336                          * When readying a vnode-backed buffer for a read
3337                          * we must replace any dirty pages with a bogus
3338                          * page so we do not destroy dirty data when
3339                          * filling in gaps.  Dirty pages might not
3340                          * necessarily be marked dirty yet, so use m->valid
3341                          * as a reasonable test.
3342                          *
3343                          * Bogus page replacement is, uh, bogus.  We need
3344                          * to find a better way.
3345                          */
3346                         vm_page_protect(m, VM_PROT_NONE);
3347                         if (bp->b_cmd == BUF_CMD_WRITE) {
3348                                 vfs_page_set_valid(bp, foff, i, m);
3349                         } else if (m->valid == VM_PAGE_BITS_ALL) {
3350                                 bp->b_xio.xio_pages[i] = bogus_page;
3351                                 bogus++;
3352                         }
3353                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3354                 }
3355                 if (bogus)
3356                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3357                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3358         }
3359
3360         /*
3361          * This is the easiest place to put the process accounting for the I/O
3362          * for now.
3363          */
3364         if (lp != NULL) {
3365                 if (bp->b_cmd == BUF_CMD_READ)
3366                         lp->lwp_ru.ru_inblock++;
3367                 else
3368                         lp->lwp_ru.ru_oublock++;
3369         }
3370 }
3371
3372 /*
3373  * vfs_clean_pages:
3374  *      
3375  *      Tell the VM system that the pages associated with this buffer
3376  *      are clean.  This is used for delayed writes where the data is
3377  *      going to go to disk eventually without additional VM intevention.
3378  *
3379  *      Note that while we only really need to clean through to b_bcount, we
3380  *      just go ahead and clean through to b_bufsize.
3381  */
3382 static void
3383 vfs_clean_pages(struct buf *bp)
3384 {
3385         int i;
3386
3387         if (bp->b_flags & B_VMIO) {
3388                 vm_ooffset_t foff;
3389
3390                 foff = bp->b_loffset;
3391                 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3392                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3393                         vm_page_t m = bp->b_xio.xio_pages[i];
3394                         vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3395                         vm_ooffset_t eoff = noff;
3396
3397                         if (eoff > bp->b_loffset + bp->b_bufsize)
3398                                 eoff = bp->b_loffset + bp->b_bufsize;
3399                         vfs_page_set_valid(bp, foff, i, m);
3400                         /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3401                         foff = noff;
3402                 }
3403         }
3404 }
3405
3406 /*
3407  * vfs_bio_set_validclean:
3408  *
3409  *      Set the range within the buffer to valid and clean.  The range is 
3410  *      relative to the beginning of the buffer, b_loffset.  Note that
3411  *      b_loffset itself may be offset from the beginning of the first page.
3412  */
3413
3414 void   
3415 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3416 {
3417         if (bp->b_flags & B_VMIO) {
3418                 int i;
3419                 int n;
3420
3421                 /*
3422                  * Fixup base to be relative to beginning of first page.
3423                  * Set initial n to be the maximum number of bytes in the
3424                  * first page that can be validated.
3425                  */
3426
3427                 base += (bp->b_loffset & PAGE_MASK);
3428                 n = PAGE_SIZE - (base & PAGE_MASK);
3429
3430                 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3431                         vm_page_t m = bp->b_xio.xio_pages[i];
3432
3433                         if (n > size)
3434                                 n = size;
3435
3436                         vm_page_set_validclean(m, base & PAGE_MASK, n);
3437                         base += n;
3438                         size -= n;
3439                         n = PAGE_SIZE;
3440                 }
3441         }
3442 }
3443
3444 /*
3445  * vfs_bio_clrbuf:
3446  *
3447  *      Clear a buffer.  This routine essentially fakes an I/O, so we need
3448  *      to clear B_ERROR and B_INVAL.
3449  *
3450  *      Note that while we only theoretically need to clear through b_bcount,
3451  *      we go ahead and clear through b_bufsize.
3452  */
3453
3454 void
3455 vfs_bio_clrbuf(struct buf *bp)
3456 {
3457         int i, mask = 0;
3458         caddr_t sa, ea;
3459         if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3460                 bp->b_flags &= ~(B_INVAL|B_ERROR);
3461                 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3462                     (bp->b_loffset & PAGE_MASK) == 0) {
3463                         mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3464                         if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3465                                 bp->b_resid = 0;
3466                                 return;
3467                         }
3468                         if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3469                             ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3470                                 bzero(bp->b_data, bp->b_bufsize);
3471                                 bp->b_xio.xio_pages[0]->valid |= mask;
3472                                 bp->b_resid = 0;
3473                                 return;
3474                         }
3475                 }
3476                 ea = sa = bp->b_data;
3477                 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3478                         int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3479                         ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3480                         ea = (caddr_t)(vm_offset_t)ulmin(
3481                             (u_long)(vm_offset_t)ea,
3482                             (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3483                         mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3484                         if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3485                                 continue;
3486                         if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3487                                 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3488                                         bzero(sa, ea - sa);
3489                                 }
3490                         } else {
3491                                 for (; sa < ea; sa += DEV_BSIZE, j++) {
3492                                         if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3493                                                 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3494                                                 bzero(sa, DEV_BSIZE);
3495                                 }
3496                         }
3497                         bp->b_xio.xio_pages[i]->valid |= mask;
3498                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3499                 }
3500                 bp->b_resid = 0;
3501         } else {
3502                 clrbuf(bp);
3503         }
3504 }
3505
3506 /*
3507  * vm_hold_load_pages:
3508  *
3509  *      Load pages into the buffer's address space.  The pages are
3510  *      allocated from the kernel object in order to reduce interference
3511  *      with the any VM paging I/O activity.  The range of loaded
3512  *      pages will be wired.
3513  *
3514  *      If a page cannot be allocated, the 'pagedaemon' is woken up to
3515  *      retrieve the full range (to - from) of pages.
3516  *
3517  */
3518 void
3519 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3520 {
3521         vm_offset_t pg;
3522         vm_page_t p;
3523         int index;
3524
3525         to = round_page(to);
3526         from = round_page(from);
3527         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3528
3529         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3530
3531 tryagain:
3532
3533                 /*
3534                  * Note: must allocate system pages since blocking here
3535                  * could intefere with paging I/O, no matter which
3536                  * process we are.
3537                  */
3538                 p = vm_page_alloc(&kernel_object,
3539                                   (pg >> PAGE_SHIFT),
3540                                   VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3541                 if (!p) {
3542                         vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3543                         vm_wait();
3544                         goto tryagain;
3545                 }
3546                 vm_page_wire(p);
3547                 p->valid = VM_PAGE_BITS_ALL;
3548                 vm_page_flag_clear(p, PG_ZERO);
3549                 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3550                 bp->b_xio.xio_pages[index] = p;
3551                 vm_page_wakeup(p);
3552         }
3553         bp->b_xio.xio_npages = index;
3554 }
3555
3556 /*
3557  * vm_hold_free_pages:
3558  *
3559  *      Return pages associated with the buffer back to the VM system.
3560  *
3561  *      The range of pages underlying the buffer's address space will
3562  *      be unmapped and un-wired.
3563  */
3564 void
3565 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3566 {
3567         vm_offset_t pg;
3568         vm_page_t p;
3569         int index, newnpages;
3570
3571         from = round_page(from);
3572         to = round_page(to);
3573         newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3574
3575         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3576                 p = bp->b_xio.xio_pages[index];
3577                 if (p && (index < bp->b_xio.xio_npages)) {
3578                         if (p->busy) {
3579                                 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3580                                         bp->b_bio2.bio_offset, bp->b_loffset);
3581                         }
3582                         bp->b_xio.xio_pages[index] = NULL;
3583                         pmap_kremove(pg);
3584                         vm_page_busy(p);
3585                         vm_page_unwire(p, 0);
3586                         vm_page_free(p);
3587                 }
3588         }
3589         bp->b_xio.xio_npages = newnpages;
3590 }
3591
3592 /*
3593  * vmapbuf:
3594  *
3595  *      Map a user buffer into KVM via a pbuf.  On return the buffer's
3596  *      b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3597  *      initialized.
3598  */
3599 int
3600 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3601 {
3602         caddr_t addr;
3603         vm_offset_t va;
3604         vm_page_t m;
3605         int vmprot;
3606         int error;
3607         int pidx;
3608         int i;
3609
3610         /* 
3611          * bp had better have a command and it better be a pbuf.
3612          */
3613         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3614         KKASSERT(bp->b_flags & B_PAGING);
3615
3616         if (bytes < 0)
3617                 return (-1);
3618
3619         /*
3620          * Map the user data into KVM.  Mappings have to be page-aligned.
3621          */
3622         addr = (caddr_t)trunc_page((vm_offset_t)udata);
3623         pidx = 0;
3624
3625         vmprot = VM_PROT_READ;
3626         if (bp->b_cmd == BUF_CMD_READ)
3627                 vmprot |= VM_PROT_WRITE;
3628
3629         while (addr < udata + bytes) {
3630                 /*
3631                  * Do the vm_fault if needed; do the copy-on-write thing
3632                  * when reading stuff off device into memory.
3633                  *
3634                  * vm_fault_page*() returns a held VM page.
3635                  */
3636                 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3637                 va = trunc_page(va);
3638
3639                 m = vm_fault_page_quick(va, vmprot, &error);
3640                 if (m == NULL) {
3641                         for (i = 0; i < pidx; ++i) {
3642                             vm_page_unhold(bp->b_xio.xio_pages[i]);
3643                             bp->b_xio.xio_pages[i] = NULL;
3644                         }
3645                         return(-1);
3646                 }
3647                 bp->b_xio.xio_pages[pidx] = m;
3648                 addr += PAGE_SIZE;
3649                 ++pidx;
3650         }
3651
3652         /*
3653          * Map the page array and set the buffer fields to point to
3654          * the mapped data buffer.
3655          */
3656         if (pidx > btoc(MAXPHYS))
3657                 panic("vmapbuf: mapped more than MAXPHYS");
3658         pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3659
3660         bp->b_xio.xio_npages = pidx;
3661         bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3662         bp->b_bcount = bytes;
3663         bp->b_bufsize = bytes;
3664         return(0);
3665 }
3666
3667 /*
3668  * vunmapbuf:
3669  *
3670  *      Free the io map PTEs associated with this IO operation.
3671  *      We also invalidate the TLB entries and restore the original b_addr.
3672  */
3673 void
3674 vunmapbuf(struct buf *bp)
3675 {
3676         int pidx;
3677         int npages;
3678
3679         KKASSERT(bp->b_flags & B_PAGING);
3680
3681         npages = bp->b_xio.xio_npages;
3682         pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3683         for (pidx = 0; pidx < npages; ++pidx) {
3684                 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3685                 bp->b_xio.xio_pages[pidx] = NULL;
3686         }
3687         bp->b_xio.xio_npages = 0;
3688         bp->b_data = bp->b_kvabase;
3689 }
3690
3691 /*
3692  * Scan all buffers in the system and issue the callback.
3693  */
3694 int
3695 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3696 {
3697         int count = 0;
3698         int error;
3699         int n;
3700
3701         for (n = 0; n < nbuf; ++n) {
3702                 if ((error = callback(&buf[n], info)) < 0) {
3703                         count = error;
3704                         break;
3705                 }
3706                 count += error;
3707         }
3708         return (count);
3709 }
3710
3711 /*
3712  * print out statistics from the current status of the buffer pool
3713  * this can be toggeled by the system control option debug.syncprt
3714  */
3715 #ifdef DEBUG
3716 void
3717 vfs_bufstats(void)
3718 {
3719         int i, j, count;
3720         struct buf *bp;
3721         struct bqueues *dp;
3722         int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3723         static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3724
3725         for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3726                 count = 0;
3727                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3728                         counts[j] = 0;
3729                 crit_enter();
3730                 TAILQ_FOREACH(bp, dp, b_freelist) {
3731                         counts[bp->b_bufsize/PAGE_SIZE]++;
3732                         count++;
3733                 }
3734                 crit_exit();
3735                 kprintf("%s: total-%d", bname[i], count);
3736                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3737                         if (counts[j] != 0)
3738                                 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3739                 kprintf("\n");
3740         }
3741 }
3742 #endif
3743
3744 #ifdef DDB
3745
3746 DB_SHOW_COMMAND(buffer, db_show_buffer)
3747 {
3748         /* get args */
3749         struct buf *bp = (struct buf *)addr;
3750
3751         if (!have_addr) {
3752                 db_printf("usage: show buffer <addr>\n");
3753                 return;
3754         }
3755
3756         db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3757         db_printf("b_cmd = %d\n", bp->b_cmd);
3758         db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3759                   "b_resid = %d\n, b_data = %p, "
3760                   "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3761                   bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3762                   bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3763         if (bp->b_xio.xio_npages) {
3764                 int i;
3765                 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3766                         bp->b_xio.xio_npages);
3767                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3768                         vm_page_t m;
3769                         m = bp->b_xio.xio_pages[i];
3770                         db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3771                             (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3772                         if ((i + 1) < bp->b_xio.xio_npages)
3773                                 db_printf(",");
3774                 }
3775                 db_printf("\n");
3776         }
3777 }
3778 #endif /* DDB */