Constify second parameter of timeval{add,sub}()
[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.98 2008/02/23 21:55:49 dillon 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                 bp->b_tid = 0;
1806                 reinitbufbio(bp);
1807                 buf_dep_init(bp);
1808                 if (blkflags & GETBLK_BHEAVY)
1809                         bp->b_flags |= B_HEAVY;
1810
1811                 /*
1812                  * If we are defragging then free the buffer.
1813                  */
1814                 if (defrag) {
1815                         bp->b_flags |= B_INVAL;
1816                         bfreekva(bp);
1817                         brelse(bp);
1818                         defrag = 0;
1819                         goto restart;
1820                 }
1821
1822                 /*
1823                  * If we are overcomitted then recover the buffer and its
1824                  * KVM space.  This occurs in rare situations when multiple
1825                  * processes are blocked in getnewbuf() or allocbuf().
1826                  */
1827                 if (bufspace >= hibufspace)
1828                         flushingbufs = 1;
1829                 if (flushingbufs && bp->b_kvasize != 0) {
1830                         bp->b_flags |= B_INVAL;
1831                         bfreekva(bp);
1832                         brelse(bp);
1833                         goto restart;
1834                 }
1835                 if (bufspace < lobufspace)
1836                         flushingbufs = 0;
1837                 break;
1838         }
1839
1840         /*
1841          * If we exhausted our list, sleep as appropriate.  We may have to
1842          * wakeup various daemons and write out some dirty buffers.
1843          *
1844          * Generally we are sleeping due to insufficient buffer space.
1845          */
1846
1847         if (bp == NULL) {
1848                 int flags;
1849                 char *waitmsg;
1850
1851                 if (defrag) {
1852                         flags = VFS_BIO_NEED_BUFSPACE;
1853                         waitmsg = "nbufkv";
1854                 } else if (bufspace >= hibufspace) {
1855                         waitmsg = "nbufbs";
1856                         flags = VFS_BIO_NEED_BUFSPACE;
1857                 } else {
1858                         waitmsg = "newbuf";
1859                         flags = VFS_BIO_NEED_ANY;
1860                 }
1861
1862                 needsbuffer |= flags;
1863                 bd_speedup();   /* heeeelp */
1864                 while (needsbuffer & flags) {
1865                         if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1866                                 return (NULL);
1867                 }
1868         } else {
1869                 /*
1870                  * We finally have a valid bp.  We aren't quite out of the
1871                  * woods, we still have to reserve kva space.  In order
1872                  * to keep fragmentation sane we only allocate kva in
1873                  * BKVASIZE chunks.
1874                  */
1875                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1876
1877                 if (maxsize != bp->b_kvasize) {
1878                         vm_offset_t addr = 0;
1879                         int count;
1880
1881                         bfreekva(bp);
1882
1883                         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1884                         vm_map_lock(&buffer_map);
1885
1886                         if (vm_map_findspace(&buffer_map,
1887                                     vm_map_min(&buffer_map), maxsize,
1888                                     maxsize, &addr)) {
1889                                 /*
1890                                  * Uh oh.  Buffer map is too fragmented.  We
1891                                  * must defragment the map.
1892                                  */
1893                                 vm_map_unlock(&buffer_map);
1894                                 vm_map_entry_release(count);
1895                                 ++bufdefragcnt;
1896                                 defrag = 1;
1897                                 bp->b_flags |= B_INVAL;
1898                                 brelse(bp);
1899                                 goto restart;
1900                         }
1901                         if (addr) {
1902                                 vm_map_insert(&buffer_map, &count,
1903                                         NULL, 0,
1904                                         addr, addr + maxsize,
1905                                         VM_MAPTYPE_NORMAL,
1906                                         VM_PROT_ALL, VM_PROT_ALL,
1907                                         MAP_NOFAULT);
1908
1909                                 bp->b_kvabase = (caddr_t) addr;
1910                                 bp->b_kvasize = maxsize;
1911                                 bufspace += bp->b_kvasize;
1912                                 ++bufreusecnt;
1913                         }
1914                         vm_map_unlock(&buffer_map);
1915                         vm_map_entry_release(count);
1916                 }
1917                 bp->b_data = bp->b_kvabase;
1918         }
1919         return(bp);
1920 }
1921
1922 /*
1923  * buf_daemon:
1924  *
1925  *      Buffer flushing daemon.  Buffers are normally flushed by the
1926  *      update daemon but if it cannot keep up this process starts to
1927  *      take the load in an attempt to prevent getnewbuf() from blocking.
1928  *
1929  *      Once a flush is initiated it does not stop until the number
1930  *      of buffers falls below lodirtybuffers, but we will wake up anyone
1931  *      waiting at the mid-point.
1932  */
1933
1934 static struct thread *bufdaemon_td;
1935 static struct thread *bufdaemonhw_td;
1936
1937 static struct kproc_desc buf_kp = {
1938         "bufdaemon",
1939         buf_daemon,
1940         &bufdaemon_td
1941 };
1942 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1943         kproc_start, &buf_kp)
1944
1945 static struct kproc_desc bufhw_kp = {
1946         "bufdaemon_hw",
1947         buf_daemon_hw,
1948         &bufdaemonhw_td
1949 };
1950 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1951         kproc_start, &bufhw_kp)
1952
1953 static void
1954 buf_daemon(void)
1955 {
1956         /*
1957          * This process needs to be suspended prior to shutdown sync.
1958          */
1959         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1960                               bufdaemon_td, SHUTDOWN_PRI_LAST);
1961
1962         /*
1963          * This process is allowed to take the buffer cache to the limit
1964          */
1965         crit_enter();
1966
1967         for (;;) {
1968                 kproc_suspend_loop();
1969
1970                 /*
1971                  * Do the flush.  Limit the amount of in-transit I/O we
1972                  * allow to build up, otherwise we would completely saturate
1973                  * the I/O system.  Wakeup any waiting processes before we
1974                  * normally would so they can run in parallel with our drain.
1975                  */
1976                 while (numdirtybuffers > lodirtybuffers) {
1977                         if (flushbufqueues(BQUEUE_DIRTY) == 0)
1978                                 break;
1979                         waitrunningbufspace();
1980                         numdirtywakeup();
1981                 }
1982                 numdirtywakeup();
1983
1984                 /*
1985                  * Only clear bd_request if we have reached our low water
1986                  * mark.  The buf_daemon normally waits 5 seconds and
1987                  * then incrementally flushes any dirty buffers that have
1988                  * built up, within reason.
1989                  *
1990                  * If we were unable to hit our low water mark and couldn't
1991                  * find any flushable buffers, we sleep half a second. 
1992                  * Otherwise we loop immediately.
1993                  */
1994                 if (numdirtybuffers <= lodirtybuffers) {
1995                         /*
1996                          * We reached our low water mark, reset the
1997                          * request and sleep until we are needed again.
1998                          * The sleep is just so the suspend code works.
1999                          */
2000                         spin_lock_wr(&needsbuffer_spin);
2001                         bd_request = 0;
2002                         msleep(&bd_request, &needsbuffer_spin, 0,
2003                                "psleep", hz);
2004                         spin_unlock_wr(&needsbuffer_spin);
2005                 } else {
2006                         /*
2007                          * We couldn't find any flushable dirty buffers but
2008                          * still have too many dirty buffers, we
2009                          * have to sleep and try again.  (rare)
2010                          */
2011                         tsleep(&bd_request, 0, "qsleep", hz / 2);
2012                 }
2013         }
2014 }
2015
2016 static void
2017 buf_daemon_hw(void)
2018 {
2019         /*
2020          * This process needs to be suspended prior to shutdown sync.
2021          */
2022         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2023                               bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2024
2025         /*
2026          * This process is allowed to take the buffer cache to the limit
2027          */
2028         crit_enter();
2029
2030         for (;;) {
2031                 kproc_suspend_loop();
2032
2033                 /*
2034                  * Do the flush.  Limit the amount of in-transit I/O we
2035                  * allow to build up, otherwise we would completely saturate
2036                  * the I/O system.  Wakeup any waiting processes before we
2037                  * normally would so they can run in parallel with our drain.
2038                  */
2039                 while (numdirtybuffershw > lodirtybuffers) {
2040                         if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2041                                 break;
2042                         waitrunningbufspace();
2043                         numdirtywakeup();
2044                 }
2045
2046                 /*
2047                  * Only clear bd_request if we have reached our low water
2048                  * mark.  The buf_daemon normally waits 5 seconds and
2049                  * then incrementally flushes any dirty buffers that have
2050                  * built up, within reason.
2051                  *
2052                  * If we were unable to hit our low water mark and couldn't
2053                  * find any flushable buffers, we sleep half a second. 
2054                  * Otherwise we loop immediately.
2055                  */
2056                 if (numdirtybuffershw <= lodirtybuffers) {
2057                         /*
2058                          * We reached our low water mark, reset the
2059                          * request and sleep until we are needed again.
2060                          * The sleep is just so the suspend code works.
2061                          */
2062                         spin_lock_wr(&needsbuffer_spin);
2063                         bd_request_hw = 0;
2064                         msleep(&bd_request_hw, &needsbuffer_spin, 0,
2065                                "psleep", hz);
2066                         spin_unlock_wr(&needsbuffer_spin);
2067                 } else {
2068                         /*
2069                          * We couldn't find any flushable dirty buffers but
2070                          * still have too many dirty buffers, we
2071                          * have to sleep and try again.  (rare)
2072                          */
2073                         tsleep(&bd_request_hw, 0, "qsleep", hz / 2);
2074                 }
2075         }
2076 }
2077
2078 /*
2079  * flushbufqueues:
2080  *
2081  *      Try to flush a buffer in the dirty queue.  We must be careful to
2082  *      free up B_INVAL buffers instead of write them, which NFS is 
2083  *      particularly sensitive to.
2084  */
2085
2086 static int
2087 flushbufqueues(bufq_type_t q)
2088 {
2089         struct buf *bp;
2090         int r = 0;
2091
2092         bp = TAILQ_FIRST(&bufqueues[q]);
2093
2094         while (bp) {
2095                 KASSERT((bp->b_flags & B_DELWRI),
2096                         ("unexpected clean buffer %p", bp));
2097                 if (bp->b_flags & B_DELWRI) {
2098                         if (bp->b_flags & B_INVAL) {
2099                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2100                                         panic("flushbufqueues: locked buf");
2101                                 bremfree(bp);
2102                                 brelse(bp);
2103                                 ++r;
2104                                 break;
2105                         }
2106                         if (LIST_FIRST(&bp->b_dep) != NULL &&
2107                             (bp->b_flags & B_DEFERRED) == 0 &&
2108                             buf_countdeps(bp, 0)) {
2109                                 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2110                                 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2111                                                   b_freelist);
2112                                 bp->b_flags |= B_DEFERRED;
2113                                 bp = TAILQ_FIRST(&bufqueues[q]);
2114                                 continue;
2115                         }
2116
2117                         /*
2118                          * Only write it out if we can successfully lock
2119                          * it.  If the buffer has a dependancy,
2120                          * buf_checkwrite must also return 0.
2121                          */
2122                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2123                                 if (LIST_FIRST(&bp->b_dep) != NULL &&
2124                                     buf_checkwrite(bp)) {
2125                                         bremfree(bp);
2126                                         brelse(bp);
2127                                 } else {
2128                                         vfs_bio_awrite(bp);
2129                                 }
2130                                 ++r;
2131                                 break;
2132                         }
2133                 }
2134                 bp = TAILQ_NEXT(bp, b_freelist);
2135         }
2136         return (r);
2137 }
2138
2139 /*
2140  * inmem:
2141  *
2142  *      Returns true if no I/O is needed to access the associated VM object.
2143  *      This is like findblk except it also hunts around in the VM system for
2144  *      the data.
2145  *
2146  *      Note that we ignore vm_page_free() races from interrupts against our
2147  *      lookup, since if the caller is not protected our return value will not
2148  *      be any more valid then otherwise once we exit the critical section.
2149  */
2150 int
2151 inmem(struct vnode *vp, off_t loffset)
2152 {
2153         vm_object_t obj;
2154         vm_offset_t toff, tinc, size;
2155         vm_page_t m;
2156
2157         if (findblk(vp, loffset))
2158                 return 1;
2159         if (vp->v_mount == NULL)
2160                 return 0;
2161         if ((obj = vp->v_object) == NULL)
2162                 return 0;
2163
2164         size = PAGE_SIZE;
2165         if (size > vp->v_mount->mnt_stat.f_iosize)
2166                 size = vp->v_mount->mnt_stat.f_iosize;
2167
2168         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2169                 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2170                 if (m == NULL)
2171                         return 0;
2172                 tinc = size;
2173                 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2174                         tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2175                 if (vm_page_is_valid(m,
2176                     (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2177                         return 0;
2178         }
2179         return 1;
2180 }
2181
2182 /*
2183  * vfs_setdirty:
2184  *
2185  *      Sets the dirty range for a buffer based on the status of the dirty
2186  *      bits in the pages comprising the buffer.
2187  *
2188  *      The range is limited to the size of the buffer.
2189  *
2190  *      This routine is primarily used by NFS, but is generalized for the
2191  *      B_VMIO case.
2192  */
2193 static void
2194 vfs_setdirty(struct buf *bp) 
2195 {
2196         int i;
2197         vm_object_t object;
2198
2199         /*
2200          * Degenerate case - empty buffer
2201          */
2202
2203         if (bp->b_bufsize == 0)
2204                 return;
2205
2206         /*
2207          * We qualify the scan for modified pages on whether the
2208          * object has been flushed yet.  The OBJ_WRITEABLE flag
2209          * is not cleared simply by protecting pages off.
2210          */
2211
2212         if ((bp->b_flags & B_VMIO) == 0)
2213                 return;
2214
2215         object = bp->b_xio.xio_pages[0]->object;
2216
2217         if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2218                 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2219         if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2220                 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2221
2222         if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2223                 vm_offset_t boffset;
2224                 vm_offset_t eoffset;
2225
2226                 /*
2227                  * test the pages to see if they have been modified directly
2228                  * by users through the VM system.
2229                  */
2230                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2231                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2232                         vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2233                 }
2234
2235                 /*
2236                  * Calculate the encompassing dirty range, boffset and eoffset,
2237                  * (eoffset - boffset) bytes.
2238                  */
2239
2240                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2241                         if (bp->b_xio.xio_pages[i]->dirty)
2242                                 break;
2243                 }
2244                 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2245
2246                 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2247                         if (bp->b_xio.xio_pages[i]->dirty) {
2248                                 break;
2249                         }
2250                 }
2251                 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2252
2253                 /*
2254                  * Fit it to the buffer.
2255                  */
2256
2257                 if (eoffset > bp->b_bcount)
2258                         eoffset = bp->b_bcount;
2259
2260                 /*
2261                  * If we have a good dirty range, merge with the existing
2262                  * dirty range.
2263                  */
2264
2265                 if (boffset < eoffset) {
2266                         if (bp->b_dirtyoff > boffset)
2267                                 bp->b_dirtyoff = boffset;
2268                         if (bp->b_dirtyend < eoffset)
2269                                 bp->b_dirtyend = eoffset;
2270                 }
2271         }
2272 }
2273
2274 /*
2275  * findblk:
2276  *
2277  *      Locate and return the specified buffer, or NULL if the buffer does
2278  *      not exist.  Do not attempt to lock the buffer or manipulate it in
2279  *      any way.  The caller must validate that the correct buffer has been
2280  *      obtain after locking it.
2281  */
2282 struct buf *
2283 findblk(struct vnode *vp, off_t loffset)
2284 {
2285         struct buf *bp;
2286
2287         crit_enter();
2288         bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2289         crit_exit();
2290         return(bp);
2291 }
2292
2293 /*
2294  * getblk:
2295  *
2296  *      Get a block given a specified block and offset into a file/device.
2297  *      B_INVAL may or may not be set on return.  The caller should clear
2298  *      B_INVAL prior to initiating a READ.
2299  *
2300  *      IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2301  *      IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2302  *      OR SET B_INVAL BEFORE RETIRING IT.  If you retire a getblk'd buffer
2303  *      without doing any of those things the system will likely believe
2304  *      the buffer to be valid (especially if it is not B_VMIO), and the
2305  *      next getblk() will return the buffer with B_CACHE set.
2306  *
2307  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2308  *      an existing buffer.
2309  *
2310  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
2311  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2312  *      and then cleared based on the backing VM.  If the previous buffer is
2313  *      non-0-sized but invalid, B_CACHE will be cleared.
2314  *
2315  *      If getblk() must create a new buffer, the new buffer is returned with
2316  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2317  *      case it is returned with B_INVAL clear and B_CACHE set based on the
2318  *      backing VM.
2319  *
2320  *      getblk() also forces a bwrite() for any B_DELWRI buffer whos
2321  *      B_CACHE bit is clear.
2322  *      
2323  *      What this means, basically, is that the caller should use B_CACHE to
2324  *      determine whether the buffer is fully valid or not and should clear
2325  *      B_INVAL prior to issuing a read.  If the caller intends to validate
2326  *      the buffer by loading its data area with something, the caller needs
2327  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
2328  *      the caller should set B_CACHE ( as an optimization ), else the caller
2329  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
2330  *      a write attempt or if it was a successfull read.  If the caller 
2331  *      intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2332  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2333  *
2334  *      getblk flags:
2335  *
2336  *      GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2337  *      GETBLK_BHEAVY - heavy-weight buffer cache buffer
2338  */
2339 struct buf *
2340 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2341 {
2342         struct buf *bp;
2343         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2344
2345         if (size > MAXBSIZE)
2346                 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2347         if (vp->v_object == NULL)
2348                 panic("getblk: vnode %p has no object!", vp);
2349
2350         crit_enter();
2351 loop:
2352         if ((bp = findblk(vp, loffset))) {
2353                 /*
2354                  * The buffer was found in the cache, but we need to lock it.
2355                  * Even with LK_NOWAIT the lockmgr may break our critical
2356                  * section, so double-check the validity of the buffer
2357                  * once the lock has been obtained.
2358                  */
2359                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2360                         int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2361                         if (blkflags & GETBLK_PCATCH)
2362                                 lkflags |= LK_PCATCH;
2363                         if (BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo) ==
2364                             ENOLCK) {
2365                                 goto loop;
2366                         }
2367                         crit_exit();
2368                         return (NULL);
2369                 }
2370
2371                 /*
2372                  * Once the buffer has been locked, make sure we didn't race
2373                  * a buffer recyclement.  Buffers that are no longer hashed
2374                  * will have b_vp == NULL, so this takes care of that check
2375                  * as well.
2376                  */
2377                 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2378                         kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2379                         BUF_UNLOCK(bp);
2380                         goto loop;
2381                 }
2382
2383                 /*
2384                  * All vnode-based buffers must be backed by a VM object.
2385                  */
2386                 KKASSERT(bp->b_flags & B_VMIO);
2387                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2388
2389                 /*
2390                  * Make sure that B_INVAL buffers do not have a cached
2391                  * block number translation.
2392                  */
2393                 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2394                         kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2395                         clearbiocache(&bp->b_bio2);
2396                 }
2397
2398                 /*
2399                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
2400                  * invalid.
2401                  */
2402                 if (bp->b_flags & B_INVAL)
2403                         bp->b_flags &= ~B_CACHE;
2404                 bremfree(bp);
2405
2406                 /*
2407                  * Any size inconsistancy with a dirty buffer or a buffer
2408                  * with a softupdates dependancy must be resolved.  Resizing
2409                  * the buffer in such circumstances can lead to problems.
2410                  */
2411                 if (size != bp->b_bcount) {
2412                         if (bp->b_flags & B_DELWRI) {
2413                                 bp->b_flags |= B_NOCACHE;
2414                                 bwrite(bp);
2415                         } else if (LIST_FIRST(&bp->b_dep)) {
2416                                 bp->b_flags |= B_NOCACHE;
2417                                 bwrite(bp);
2418                         } else {
2419                                 bp->b_flags |= B_RELBUF;
2420                                 brelse(bp);
2421                         }
2422                         goto loop;
2423                 }
2424                 KKASSERT(size <= bp->b_kvasize);
2425                 KASSERT(bp->b_loffset != NOOFFSET, 
2426                         ("getblk: no buffer offset"));
2427
2428                 /*
2429                  * A buffer with B_DELWRI set and B_CACHE clear must
2430                  * be committed before we can return the buffer in
2431                  * order to prevent the caller from issuing a read
2432                  * ( due to B_CACHE not being set ) and overwriting
2433                  * it.
2434                  *
2435                  * Most callers, including NFS and FFS, need this to
2436                  * operate properly either because they assume they
2437                  * can issue a read if B_CACHE is not set, or because
2438                  * ( for example ) an uncached B_DELWRI might loop due 
2439                  * to softupdates re-dirtying the buffer.  In the latter
2440                  * case, B_CACHE is set after the first write completes,
2441                  * preventing further loops.
2442                  *
2443                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2444                  * above while extending the buffer, we cannot allow the
2445                  * buffer to remain with B_CACHE set after the write
2446                  * completes or it will represent a corrupt state.  To
2447                  * deal with this we set B_NOCACHE to scrap the buffer
2448                  * after the write.
2449                  *
2450                  * We might be able to do something fancy, like setting
2451                  * B_CACHE in bwrite() except if B_DELWRI is already set,
2452                  * so the below call doesn't set B_CACHE, but that gets real
2453                  * confusing.  This is much easier.
2454                  */
2455
2456                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2457                         bp->b_flags |= B_NOCACHE;
2458                         bwrite(bp);
2459                         goto loop;
2460                 }
2461                 crit_exit();
2462         } else {
2463                 /*
2464                  * Buffer is not in-core, create new buffer.  The buffer
2465                  * returned by getnewbuf() is locked.  Note that the returned
2466                  * buffer is also considered valid (not marked B_INVAL).
2467                  *
2468                  * Calculating the offset for the I/O requires figuring out
2469                  * the block size.  We use DEV_BSIZE for VBLK or VCHR and
2470                  * the mount's f_iosize otherwise.  If the vnode does not
2471                  * have an associated mount we assume that the passed size is 
2472                  * the block size.  
2473                  *
2474                  * Note that vn_isdisk() cannot be used here since it may
2475                  * return a failure for numerous reasons.   Note that the
2476                  * buffer size may be larger then the block size (the caller
2477                  * will use block numbers with the proper multiple).  Beware
2478                  * of using any v_* fields which are part of unions.  In
2479                  * particular, in DragonFly the mount point overloading 
2480                  * mechanism uses the namecache only and the underlying
2481                  * directory vnode is not a special case.
2482                  */
2483                 int bsize, maxsize;
2484
2485                 /*
2486                  * Don't let heavy weight buffers deadlock us.
2487                  */
2488                 if ((blkflags & GETBLK_BHEAVY) &&
2489                     numdirtybuffershw > hidirtybuffers) {
2490                         while (numdirtybuffershw > hidirtybuffers) {
2491                                 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
2492                                 tsleep(&needsbuffer, slpflags, "newbuf",
2493                                        slptimeo);
2494                         }
2495                         goto loop;
2496                 }
2497
2498                 if (vp->v_type == VBLK || vp->v_type == VCHR)
2499                         bsize = DEV_BSIZE;
2500                 else if (vp->v_mount)
2501                         bsize = vp->v_mount->mnt_stat.f_iosize;
2502                 else
2503                         bsize = size;
2504
2505                 maxsize = size + (loffset & PAGE_MASK);
2506                 maxsize = imax(maxsize, bsize);
2507
2508                 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2509                         if (slpflags || slptimeo) {
2510                                 crit_exit();
2511                                 return NULL;
2512                         }
2513                         goto loop;
2514                 }
2515
2516                 /*
2517                  * This code is used to make sure that a buffer is not
2518                  * created while the getnewbuf routine is blocked.
2519                  * This can be a problem whether the vnode is locked or not.
2520                  * If the buffer is created out from under us, we have to
2521                  * throw away the one we just created.  There is no window
2522                  * race because we are safely running in a critical section
2523                  * from the point of the duplicate buffer creation through
2524                  * to here, and we've locked the buffer.
2525                  */
2526                 if (findblk(vp, loffset)) {
2527                         bp->b_flags |= B_INVAL;
2528                         brelse(bp);
2529                         goto loop;
2530                 }
2531
2532                 /*
2533                  * Insert the buffer into the hash, so that it can
2534                  * be found by findblk(). 
2535                  *
2536                  * Make sure the translation layer has been cleared.
2537                  */
2538                 bp->b_loffset = loffset;
2539                 bp->b_bio2.bio_offset = NOOFFSET;
2540                 /* bp->b_bio2.bio_next = NULL; */
2541
2542                 bgetvp(vp, bp);
2543
2544                 /*
2545                  * All vnode-based buffers must be backed by a VM object.
2546                  */
2547                 KKASSERT(vp->v_object != NULL);
2548                 bp->b_flags |= B_VMIO;
2549                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2550
2551                 allocbuf(bp, size);
2552
2553                 crit_exit();
2554         }
2555         return (bp);
2556 }
2557
2558 /*
2559  * regetblk(bp)
2560  *
2561  * Reacquire a buffer that was previously released to the locked queue,
2562  * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2563  * set B_LOCKED (which handles the acquisition race).
2564  *
2565  * To this end, either B_LOCKED must be set or the dependancy list must be
2566  * non-empty.
2567  */
2568 void
2569 regetblk(struct buf *bp)
2570 {
2571         KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2572         BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2573         crit_enter();
2574         bremfree(bp);
2575         crit_exit();
2576 }
2577
2578 /*
2579  * geteblk:
2580  *
2581  *      Get an empty, disassociated buffer of given size.  The buffer is
2582  *      initially set to B_INVAL.
2583  *
2584  *      critical section protection is not required for the allocbuf()
2585  *      call because races are impossible here.
2586  */
2587 struct buf *
2588 geteblk(int size)
2589 {
2590         struct buf *bp;
2591         int maxsize;
2592
2593         maxsize = (size + BKVAMASK) & ~BKVAMASK;
2594
2595         crit_enter();
2596         while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2597                 ;
2598         crit_exit();
2599         allocbuf(bp, size);
2600         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2601         return (bp);
2602 }
2603
2604
2605 /*
2606  * allocbuf:
2607  *
2608  *      This code constitutes the buffer memory from either anonymous system
2609  *      memory (in the case of non-VMIO operations) or from an associated
2610  *      VM object (in the case of VMIO operations).  This code is able to
2611  *      resize a buffer up or down.
2612  *
2613  *      Note that this code is tricky, and has many complications to resolve
2614  *      deadlock or inconsistant data situations.  Tread lightly!!! 
2615  *      There are B_CACHE and B_DELWRI interactions that must be dealt with by 
2616  *      the caller.  Calling this code willy nilly can result in the loss of data.
2617  *
2618  *      allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2619  *      B_CACHE for the non-VMIO case.
2620  *
2621  *      This routine does not need to be called from a critical section but you
2622  *      must own the buffer.
2623  */
2624 int
2625 allocbuf(struct buf *bp, int size)
2626 {
2627         int newbsize, mbsize;
2628         int i;
2629
2630         if (BUF_REFCNT(bp) == 0)
2631                 panic("allocbuf: buffer not busy");
2632
2633         if (bp->b_kvasize < size)
2634                 panic("allocbuf: buffer too small");
2635
2636         if ((bp->b_flags & B_VMIO) == 0) {
2637                 caddr_t origbuf;
2638                 int origbufsize;
2639                 /*
2640                  * Just get anonymous memory from the kernel.  Don't
2641                  * mess with B_CACHE.
2642                  */
2643                 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2644                 if (bp->b_flags & B_MALLOC)
2645                         newbsize = mbsize;
2646                 else
2647                         newbsize = round_page(size);
2648
2649                 if (newbsize < bp->b_bufsize) {
2650                         /*
2651                          * Malloced buffers are not shrunk
2652                          */
2653                         if (bp->b_flags & B_MALLOC) {
2654                                 if (newbsize) {
2655                                         bp->b_bcount = size;
2656                                 } else {
2657                                         kfree(bp->b_data, M_BIOBUF);
2658                                         if (bp->b_bufsize) {
2659                                                 bufmallocspace -= bp->b_bufsize;
2660                                                 bufspacewakeup();
2661                                                 bp->b_bufsize = 0;
2662                                         }
2663                                         bp->b_data = bp->b_kvabase;
2664                                         bp->b_bcount = 0;
2665                                         bp->b_flags &= ~B_MALLOC;
2666                                 }
2667                                 return 1;
2668                         }               
2669                         vm_hold_free_pages(
2670                             bp,
2671                             (vm_offset_t) bp->b_data + newbsize,
2672                             (vm_offset_t) bp->b_data + bp->b_bufsize);
2673                 } else if (newbsize > bp->b_bufsize) {
2674                         /*
2675                          * We only use malloced memory on the first allocation.
2676                          * and revert to page-allocated memory when the buffer
2677                          * grows.
2678                          */
2679                         if ((bufmallocspace < maxbufmallocspace) &&
2680                                 (bp->b_bufsize == 0) &&
2681                                 (mbsize <= PAGE_SIZE/2)) {
2682
2683                                 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2684                                 bp->b_bufsize = mbsize;
2685                                 bp->b_bcount = size;
2686                                 bp->b_flags |= B_MALLOC;
2687                                 bufmallocspace += mbsize;
2688                                 return 1;
2689                         }
2690                         origbuf = NULL;
2691                         origbufsize = 0;
2692                         /*
2693                          * If the buffer is growing on its other-than-first
2694                          * allocation, then we revert to the page-allocation
2695                          * scheme.
2696                          */
2697                         if (bp->b_flags & B_MALLOC) {
2698                                 origbuf = bp->b_data;
2699                                 origbufsize = bp->b_bufsize;
2700                                 bp->b_data = bp->b_kvabase;
2701                                 if (bp->b_bufsize) {
2702                                         bufmallocspace -= bp->b_bufsize;
2703                                         bufspacewakeup();
2704                                         bp->b_bufsize = 0;
2705                                 }
2706                                 bp->b_flags &= ~B_MALLOC;
2707                                 newbsize = round_page(newbsize);
2708                         }
2709                         vm_hold_load_pages(
2710                             bp,
2711                             (vm_offset_t) bp->b_data + bp->b_bufsize,
2712                             (vm_offset_t) bp->b_data + newbsize);
2713                         if (origbuf) {
2714                                 bcopy(origbuf, bp->b_data, origbufsize);
2715                                 kfree(origbuf, M_BIOBUF);
2716                         }
2717                 }
2718         } else {
2719                 vm_page_t m;
2720                 int desiredpages;
2721
2722                 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2723                 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2724                                 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2725                 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2726
2727                 if (bp->b_flags & B_MALLOC)
2728                         panic("allocbuf: VMIO buffer can't be malloced");
2729                 /*
2730                  * Set B_CACHE initially if buffer is 0 length or will become
2731                  * 0-length.
2732                  */
2733                 if (size == 0 || bp->b_bufsize == 0)
2734                         bp->b_flags |= B_CACHE;
2735
2736                 if (newbsize < bp->b_bufsize) {
2737                         /*
2738                          * DEV_BSIZE aligned new buffer size is less then the
2739                          * DEV_BSIZE aligned existing buffer size.  Figure out
2740                          * if we have to remove any pages.
2741                          */
2742                         if (desiredpages < bp->b_xio.xio_npages) {
2743                                 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2744                                         /*
2745                                          * the page is not freed here -- it
2746                                          * is the responsibility of 
2747                                          * vnode_pager_setsize
2748                                          */
2749                                         m = bp->b_xio.xio_pages[i];
2750                                         KASSERT(m != bogus_page,
2751                                             ("allocbuf: bogus page found"));
2752                                         while (vm_page_sleep_busy(m, TRUE, "biodep"))
2753                                                 ;
2754
2755                                         bp->b_xio.xio_pages[i] = NULL;
2756                                         vm_page_unwire(m, 0);
2757                                 }
2758                                 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2759                                     (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2760                                 bp->b_xio.xio_npages = desiredpages;
2761                         }
2762                 } else if (size > bp->b_bcount) {
2763                         /*
2764                          * We are growing the buffer, possibly in a 
2765                          * byte-granular fashion.
2766                          */
2767                         struct vnode *vp;
2768                         vm_object_t obj;
2769                         vm_offset_t toff;
2770                         vm_offset_t tinc;
2771
2772                         /*
2773                          * Step 1, bring in the VM pages from the object, 
2774                          * allocating them if necessary.  We must clear
2775                          * B_CACHE if these pages are not valid for the 
2776                          * range covered by the buffer.
2777                          *
2778                          * critical section protection is required to protect
2779                          * against interrupts unbusying and freeing pages
2780                          * between our vm_page_lookup() and our
2781                          * busycheck/wiring call.
2782                          */
2783                         vp = bp->b_vp;
2784                         obj = vp->v_object;
2785
2786                         crit_enter();
2787                         while (bp->b_xio.xio_npages < desiredpages) {
2788                                 vm_page_t m;
2789                                 vm_pindex_t pi;
2790
2791                                 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2792                                 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2793                                         /*
2794                                          * note: must allocate system pages
2795                                          * since blocking here could intefere
2796                                          * with paging I/O, no matter which
2797                                          * process we are.
2798                                          */
2799                                         m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2800                                         if (m == NULL) {
2801                                                 vm_wait();
2802                                                 vm_pageout_deficit += desiredpages -
2803                                                         bp->b_xio.xio_npages;
2804                                         } else {
2805                                                 vm_page_wire(m);
2806                                                 vm_page_wakeup(m);
2807                                                 bp->b_flags &= ~B_CACHE;
2808                                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2809                                                 ++bp->b_xio.xio_npages;
2810                                         }
2811                                         continue;
2812                                 }
2813
2814                                 /*
2815                                  * We found a page.  If we have to sleep on it,
2816                                  * retry because it might have gotten freed out
2817                                  * from under us.
2818                                  *
2819                                  * We can only test PG_BUSY here.  Blocking on
2820                                  * m->busy might lead to a deadlock:
2821                                  *
2822                                  *  vm_fault->getpages->cluster_read->allocbuf
2823                                  *
2824                                  */
2825
2826                                 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2827                                         continue;
2828
2829                                 /*
2830                                  * We have a good page.  Should we wakeup the
2831                                  * page daemon?
2832                                  */
2833                                 if ((curthread != pagethread) &&
2834                                     ((m->queue - m->pc) == PQ_CACHE) &&
2835                                     ((vmstats.v_free_count + vmstats.v_cache_count) <
2836                                         (vmstats.v_free_min + vmstats.v_cache_min))) {
2837                                         pagedaemon_wakeup();
2838                                 }
2839                                 vm_page_flag_clear(m, PG_ZERO);
2840                                 vm_page_wire(m);
2841                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2842                                 ++bp->b_xio.xio_npages;
2843                         }
2844                         crit_exit();
2845
2846                         /*
2847                          * Step 2.  We've loaded the pages into the buffer,
2848                          * we have to figure out if we can still have B_CACHE
2849                          * set.  Note that B_CACHE is set according to the
2850                          * byte-granular range ( bcount and size ), not the
2851                          * aligned range ( newbsize ).
2852                          *
2853                          * The VM test is against m->valid, which is DEV_BSIZE
2854                          * aligned.  Needless to say, the validity of the data
2855                          * needs to also be DEV_BSIZE aligned.  Note that this
2856                          * fails with NFS if the server or some other client
2857                          * extends the file's EOF.  If our buffer is resized, 
2858                          * B_CACHE may remain set! XXX
2859                          */
2860
2861                         toff = bp->b_bcount;
2862                         tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2863
2864                         while ((bp->b_flags & B_CACHE) && toff < size) {
2865                                 vm_pindex_t pi;
2866
2867                                 if (tinc > (size - toff))
2868                                         tinc = size - toff;
2869
2870                                 pi = ((bp->b_loffset & PAGE_MASK) + toff) >> 
2871                                     PAGE_SHIFT;
2872
2873                                 vfs_buf_test_cache(
2874                                     bp, 
2875                                     bp->b_loffset,
2876                                     toff, 
2877                                     tinc, 
2878                                     bp->b_xio.xio_pages[pi]
2879                                 );
2880                                 toff += tinc;
2881                                 tinc = PAGE_SIZE;
2882                         }
2883
2884                         /*
2885                          * Step 3, fixup the KVM pmap.  Remember that
2886                          * bp->b_data is relative to bp->b_loffset, but 
2887                          * bp->b_loffset may be offset into the first page.
2888                          */
2889
2890                         bp->b_data = (caddr_t)
2891                             trunc_page((vm_offset_t)bp->b_data);
2892                         pmap_qenter(
2893                             (vm_offset_t)bp->b_data,
2894                             bp->b_xio.xio_pages, 
2895                             bp->b_xio.xio_npages
2896                         );
2897                         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 
2898                             (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2899                 }
2900         }
2901         if (newbsize < bp->b_bufsize)
2902                 bufspacewakeup();
2903         bp->b_bufsize = newbsize;       /* actual buffer allocation     */
2904         bp->b_bcount = size;            /* requested buffer size        */
2905         return 1;
2906 }
2907
2908 /*
2909  * biowait:
2910  *
2911  *      Wait for buffer I/O completion, returning error status.  The buffer
2912  *      is left locked on return.  B_EINTR is converted into an EINTR error
2913  *      and cleared.
2914  *
2915  *      NOTE!  The original b_cmd is lost on return, since b_cmd will be
2916  *      set to BUF_CMD_DONE.
2917  */
2918 int
2919 biowait(struct buf *bp)
2920 {
2921         crit_enter();
2922         while (bp->b_cmd != BUF_CMD_DONE) {
2923                 if (bp->b_cmd == BUF_CMD_READ)
2924                         tsleep(bp, 0, "biord", 0);
2925                 else
2926                         tsleep(bp, 0, "biowr", 0);
2927         }
2928         crit_exit();
2929         if (bp->b_flags & B_EINTR) {
2930                 bp->b_flags &= ~B_EINTR;
2931                 return (EINTR);
2932         }
2933         if (bp->b_flags & B_ERROR) {
2934                 return (bp->b_error ? bp->b_error : EIO);
2935         } else {
2936                 return (0);
2937         }
2938 }
2939
2940 /*
2941  * This associates a tracking count with an I/O.  vn_strategy() and
2942  * dev_dstrategy() do this automatically but there are a few cases
2943  * where a vnode or device layer is bypassed when a block translation
2944  * is cached.  In such cases bio_start_transaction() may be called on
2945  * the bypassed layers so the system gets an I/O in progress indication 
2946  * for those higher layers.
2947  */
2948 void
2949 bio_start_transaction(struct bio *bio, struct bio_track *track)
2950 {
2951         bio->bio_track = track;
2952         atomic_add_int(&track->bk_active, 1);
2953 }
2954
2955 /*
2956  * Initiate I/O on a vnode.
2957  */
2958 void
2959 vn_strategy(struct vnode *vp, struct bio *bio)
2960 {
2961         struct bio_track *track;
2962
2963         KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
2964         if (bio->bio_buf->b_cmd == BUF_CMD_READ)
2965                 track = &vp->v_track_read;
2966         else
2967                 track = &vp->v_track_write;
2968         bio->bio_track = track;
2969         atomic_add_int(&track->bk_active, 1);
2970         vop_strategy(*vp->v_ops, vp, bio);
2971 }
2972
2973
2974 /*
2975  * biodone:
2976  *
2977  *      Finish I/O on a buffer, optionally calling a completion function.
2978  *      This is usually called from an interrupt so process blocking is
2979  *      not allowed.
2980  *
2981  *      biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2982  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
2983  *      assuming B_INVAL is clear.
2984  *
2985  *      For the VMIO case, we set B_CACHE if the op was a read and no
2986  *      read error occured, or if the op was a write.  B_CACHE is never
2987  *      set if the buffer is invalid or otherwise uncacheable.
2988  *
2989  *      biodone does not mess with B_INVAL, allowing the I/O routine or the
2990  *      initiator to leave B_INVAL set to brelse the buffer out of existance
2991  *      in the biodone routine.
2992  */
2993 void
2994 biodone(struct bio *bio)
2995 {
2996         struct buf *bp = bio->bio_buf;
2997         buf_cmd_t cmd;
2998
2999         crit_enter();
3000
3001         KASSERT(BUF_REFCNTNB(bp) > 0, 
3002                 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3003         KASSERT(bp->b_cmd != BUF_CMD_DONE, 
3004                 ("biodone: bp %p already done!", bp));
3005
3006         runningbufwakeup(bp);
3007
3008         /*
3009          * Run up the chain of BIO's.   Leave b_cmd intact for the duration.
3010          */
3011         while (bio) {
3012                 biodone_t *done_func; 
3013                 struct bio_track *track;
3014
3015                 /*
3016                  * BIO tracking.  Most but not all BIOs are tracked.
3017                  */
3018                 if ((track = bio->bio_track) != NULL) {
3019                         atomic_subtract_int(&track->bk_active, 1);
3020                         if (track->bk_active < 0) {
3021                                 panic("biodone: bad active count bio %p\n",
3022                                       bio);
3023                         }
3024                         if (track->bk_waitflag) {
3025                                 track->bk_waitflag = 0;
3026                                 wakeup(track);
3027                         }
3028                         bio->bio_track = NULL;
3029                 }
3030
3031                 /*
3032                  * A bio_done function terminates the loop.  The function
3033                  * will be responsible for any further chaining and/or 
3034                  * buffer management.
3035                  *
3036                  * WARNING!  The done function can deallocate the buffer!
3037                  */
3038                 if ((done_func = bio->bio_done) != NULL) {
3039                         bio->bio_done = NULL;
3040                         done_func(bio);
3041                         crit_exit();
3042                         return;
3043                 }
3044                 bio = bio->bio_prev;
3045         }
3046
3047         cmd = bp->b_cmd;
3048         bp->b_cmd = BUF_CMD_DONE;
3049
3050         /*
3051          * Only reads and writes are processed past this point.
3052          */
3053         if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3054                 brelse(bp);
3055                 crit_exit();
3056                 return;
3057         }
3058
3059         /*
3060          * Warning: softupdates may re-dirty the buffer.
3061          */
3062         if (LIST_FIRST(&bp->b_dep) != NULL)
3063                 buf_complete(bp);
3064
3065         if (bp->b_flags & B_VMIO) {
3066                 int i;
3067                 vm_ooffset_t foff;
3068                 vm_page_t m;
3069                 vm_object_t obj;
3070                 int iosize;
3071                 struct vnode *vp = bp->b_vp;
3072
3073                 obj = vp->v_object;
3074
3075 #if defined(VFS_BIO_DEBUG)
3076                 if (vp->v_auxrefs == 0)
3077                         panic("biodone: zero vnode hold count");
3078                 if ((vp->v_flag & VOBJBUF) == 0)
3079                         panic("biodone: vnode is not setup for merged cache");
3080 #endif
3081
3082                 foff = bp->b_loffset;
3083                 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3084                 KASSERT(obj != NULL, ("biodone: missing VM object"));
3085
3086 #if defined(VFS_BIO_DEBUG)
3087                 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3088                         kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3089                             obj->paging_in_progress, bp->b_xio.xio_npages);
3090                 }
3091 #endif
3092
3093                 /*
3094                  * Set B_CACHE if the op was a normal read and no error
3095                  * occured.  B_CACHE is set for writes in the b*write()
3096                  * routines.
3097                  */
3098                 iosize = bp->b_bcount - bp->b_resid;
3099                 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3100                         bp->b_flags |= B_CACHE;
3101                 }
3102
3103                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3104                         int bogusflag = 0;
3105                         int resid;
3106
3107                         resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3108                         if (resid > iosize)
3109                                 resid = iosize;
3110
3111                         /*
3112                          * cleanup bogus pages, restoring the originals.  Since
3113                          * the originals should still be wired, we don't have
3114                          * to worry about interrupt/freeing races destroying
3115                          * the VM object association.
3116                          */
3117                         m = bp->b_xio.xio_pages[i];
3118                         if (m == bogus_page) {
3119                                 bogusflag = 1;
3120                                 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3121                                 if (m == NULL)
3122                                         panic("biodone: page disappeared");
3123                                 bp->b_xio.xio_pages[i] = m;
3124                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3125                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3126                         }
3127 #if defined(VFS_BIO_DEBUG)
3128                         if (OFF_TO_IDX(foff) != m->pindex) {
3129                                 kprintf(
3130 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3131                                     (unsigned long)foff, m->pindex);
3132                         }
3133 #endif
3134
3135                         /*
3136                          * In the write case, the valid and clean bits are
3137                          * already changed correctly ( see bdwrite() ), so we 
3138                          * only need to do this here in the read case.
3139                          */
3140                         if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3141                                 vfs_page_set_valid(bp, foff, i, m);
3142                         }
3143                         vm_page_flag_clear(m, PG_ZERO);
3144
3145                         /*
3146                          * when debugging new filesystems or buffer I/O methods, this
3147                          * is the most common error that pops up.  if you see this, you
3148                          * have not set the page busy flag correctly!!!
3149                          */
3150                         if (m->busy == 0) {
3151                                 kprintf("biodone: page busy < 0, "
3152                                     "pindex: %d, foff: 0x(%x,%x), "
3153                                     "resid: %d, index: %d\n",
3154                                     (int) m->pindex, (int)(foff >> 32),
3155                                                 (int) foff & 0xffffffff, resid, i);
3156                                 if (!vn_isdisk(vp, NULL))
3157                                         kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3158                                             bp->b_vp->v_mount->mnt_stat.f_iosize,
3159                                             bp->b_loffset,
3160                                             bp->b_flags, bp->b_xio.xio_npages);
3161                                 else
3162                                         kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3163                                             bp->b_loffset,
3164                                             bp->b_flags, bp->b_xio.xio_npages);
3165                                 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3166                                     m->valid, m->dirty, m->wire_count);
3167                                 panic("biodone: page busy < 0");
3168                         }
3169                         vm_page_io_finish(m);
3170                         vm_object_pip_subtract(obj, 1);
3171                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3172                         iosize -= resid;
3173                 }
3174                 if (obj)
3175                         vm_object_pip_wakeupn(obj, 0);
3176         }
3177
3178         /*
3179          * For asynchronous completions, release the buffer now. The brelse
3180          * will do a wakeup there if necessary - so no need to do a wakeup
3181          * here in the async case. The sync case always needs to do a wakeup.
3182          */
3183
3184         if (bp->b_flags & B_ASYNC) {
3185                 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3186                         brelse(bp);
3187                 else
3188                         bqrelse(bp);
3189         } else {
3190                 wakeup(bp);
3191         }
3192         crit_exit();
3193 }
3194
3195 /*
3196  * vfs_unbusy_pages:
3197  *
3198  *      This routine is called in lieu of iodone in the case of
3199  *      incomplete I/O.  This keeps the busy status for pages
3200  *      consistant.
3201  */
3202 void
3203 vfs_unbusy_pages(struct buf *bp)
3204 {
3205         int i;
3206
3207         runningbufwakeup(bp);
3208         if (bp->b_flags & B_VMIO) {
3209                 struct vnode *vp = bp->b_vp;
3210                 vm_object_t obj;
3211
3212                 obj = vp->v_object;
3213
3214                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3215                         vm_page_t m = bp->b_xio.xio_pages[i];
3216
3217                         /*
3218                          * When restoring bogus changes the original pages
3219                          * should still be wired, so we are in no danger of
3220                          * losing the object association and do not need
3221                          * critical section protection particularly.
3222                          */
3223                         if (m == bogus_page) {
3224                                 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3225                                 if (!m) {
3226                                         panic("vfs_unbusy_pages: page missing");
3227                                 }
3228                                 bp->b_xio.xio_pages[i] = m;
3229                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3230                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3231                         }
3232                         vm_object_pip_subtract(obj, 1);
3233                         vm_page_flag_clear(m, PG_ZERO);
3234                         vm_page_io_finish(m);
3235                 }
3236                 vm_object_pip_wakeupn(obj, 0);
3237         }
3238 }
3239
3240 /*
3241  * vfs_page_set_valid:
3242  *
3243  *      Set the valid bits in a page based on the supplied offset.   The
3244  *      range is restricted to the buffer's size.
3245  *
3246  *      This routine is typically called after a read completes.
3247  */
3248 static void
3249 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3250 {
3251         vm_ooffset_t soff, eoff;
3252
3253         /*
3254          * Start and end offsets in buffer.  eoff - soff may not cross a
3255          * page boundry or cross the end of the buffer.  The end of the
3256          * buffer, in this case, is our file EOF, not the allocation size
3257          * of the buffer.
3258          */
3259         soff = off;
3260         eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3261         if (eoff > bp->b_loffset + bp->b_bcount)
3262                 eoff = bp->b_loffset + bp->b_bcount;
3263
3264         /*
3265          * Set valid range.  This is typically the entire buffer and thus the
3266          * entire page.
3267          */
3268         if (eoff > soff) {
3269                 vm_page_set_validclean(
3270                     m,
3271                    (vm_offset_t) (soff & PAGE_MASK),
3272                    (vm_offset_t) (eoff - soff)
3273                 );
3274         }
3275 }
3276
3277 /*
3278  * vfs_busy_pages:
3279  *
3280  *      This routine is called before a device strategy routine.
3281  *      It is used to tell the VM system that paging I/O is in
3282  *      progress, and treat the pages associated with the buffer
3283  *      almost as being PG_BUSY.  Also the object 'paging_in_progress'
3284  *      flag is handled to make sure that the object doesn't become
3285  *      inconsistant.
3286  *
3287  *      Since I/O has not been initiated yet, certain buffer flags
3288  *      such as B_ERROR or B_INVAL may be in an inconsistant state
3289  *      and should be ignored.
3290  */
3291 void
3292 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3293 {
3294         int i, bogus;
3295         struct lwp *lp = curthread->td_lwp;
3296
3297         /*
3298          * The buffer's I/O command must already be set.  If reading,
3299          * B_CACHE must be 0 (double check against callers only doing
3300          * I/O when B_CACHE is 0).
3301          */
3302         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3303         KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3304
3305         if (bp->b_flags & B_VMIO) {
3306                 vm_object_t obj;
3307                 vm_ooffset_t foff;
3308
3309                 obj = vp->v_object;
3310                 foff = bp->b_loffset;
3311                 KASSERT(bp->b_loffset != NOOFFSET,
3312                         ("vfs_busy_pages: no buffer offset"));
3313                 vfs_setdirty(bp);
3314
3315 retry:
3316                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3317                         vm_page_t m = bp->b_xio.xio_pages[i];
3318                         if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3319                                 goto retry;
3320                 }
3321
3322                 bogus = 0;
3323                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3324                         vm_page_t m = bp->b_xio.xio_pages[i];
3325
3326                         vm_page_flag_clear(m, PG_ZERO);
3327                         if ((bp->b_flags & B_CLUSTER) == 0) {
3328                                 vm_object_pip_add(obj, 1);
3329                                 vm_page_io_start(m);
3330                         }
3331
3332                         /*
3333                          * When readying a vnode-backed buffer for a write
3334                          * we must zero-fill any invalid portions of the
3335                          * backing VM pages.
3336                          *
3337                          * When readying a vnode-backed buffer for a read
3338                          * we must replace any dirty pages with a bogus
3339                          * page so we do not destroy dirty data when
3340                          * filling in gaps.  Dirty pages might not
3341                          * necessarily be marked dirty yet, so use m->valid
3342                          * as a reasonable test.
3343                          *
3344                          * Bogus page replacement is, uh, bogus.  We need
3345                          * to find a better way.
3346                          */
3347                         vm_page_protect(m, VM_PROT_NONE);
3348                         if (bp->b_cmd == BUF_CMD_WRITE) {
3349                                 vfs_page_set_valid(bp, foff, i, m);
3350                         } else if (m->valid == VM_PAGE_BITS_ALL) {
3351                                 bp->b_xio.xio_pages[i] = bogus_page;
3352                                 bogus++;
3353                         }
3354                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3355                 }
3356                 if (bogus)
3357                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3358                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3359         }
3360
3361         /*
3362          * This is the easiest place to put the process accounting for the I/O
3363          * for now.
3364          */
3365         if (lp != NULL) {
3366                 if (bp->b_cmd == BUF_CMD_READ)
3367                         lp->lwp_ru.ru_inblock++;
3368                 else
3369                         lp->lwp_ru.ru_oublock++;
3370         }
3371 }
3372
3373 /*
3374  * vfs_clean_pages:
3375  *      
3376  *      Tell the VM system that the pages associated with this buffer
3377  *      are clean.  This is used for delayed writes where the data is
3378  *      going to go to disk eventually without additional VM intevention.
3379  *
3380  *      Note that while we only really need to clean through to b_bcount, we
3381  *      just go ahead and clean through to b_bufsize.
3382  */
3383 static void
3384 vfs_clean_pages(struct buf *bp)
3385 {
3386         int i;
3387
3388         if (bp->b_flags & B_VMIO) {
3389                 vm_ooffset_t foff;
3390
3391                 foff = bp->b_loffset;
3392                 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3393                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3394                         vm_page_t m = bp->b_xio.xio_pages[i];
3395                         vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3396                         vm_ooffset_t eoff = noff;
3397
3398                         if (eoff > bp->b_loffset + bp->b_bufsize)
3399                                 eoff = bp->b_loffset + bp->b_bufsize;
3400                         vfs_page_set_valid(bp, foff, i, m);
3401                         /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3402                         foff = noff;
3403                 }
3404         }
3405 }
3406
3407 /*
3408  * vfs_bio_set_validclean:
3409  *
3410  *      Set the range within the buffer to valid and clean.  The range is 
3411  *      relative to the beginning of the buffer, b_loffset.  Note that
3412  *      b_loffset itself may be offset from the beginning of the first page.
3413  */
3414
3415 void   
3416 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3417 {
3418         if (bp->b_flags & B_VMIO) {
3419                 int i;
3420                 int n;
3421
3422                 /*
3423                  * Fixup base to be relative to beginning of first page.
3424                  * Set initial n to be the maximum number of bytes in the
3425                  * first page that can be validated.
3426                  */
3427
3428                 base += (bp->b_loffset & PAGE_MASK);
3429                 n = PAGE_SIZE - (base & PAGE_MASK);
3430
3431                 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3432                         vm_page_t m = bp->b_xio.xio_pages[i];
3433
3434                         if (n > size)
3435                                 n = size;
3436
3437                         vm_page_set_validclean(m, base & PAGE_MASK, n);
3438                         base += n;
3439                         size -= n;
3440                         n = PAGE_SIZE;
3441                 }
3442         }
3443 }
3444
3445 /*
3446  * vfs_bio_clrbuf:
3447  *
3448  *      Clear a buffer.  This routine essentially fakes an I/O, so we need
3449  *      to clear B_ERROR and B_INVAL.
3450  *
3451  *      Note that while we only theoretically need to clear through b_bcount,
3452  *      we go ahead and clear through b_bufsize.
3453  */
3454
3455 void
3456 vfs_bio_clrbuf(struct buf *bp)
3457 {
3458         int i, mask = 0;
3459         caddr_t sa, ea;
3460         if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3461                 bp->b_flags &= ~(B_INVAL|B_ERROR);
3462                 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3463                     (bp->b_loffset & PAGE_MASK) == 0) {
3464                         mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3465                         if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3466                                 bp->b_resid = 0;
3467                                 return;
3468                         }
3469                         if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3470                             ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3471                                 bzero(bp->b_data, bp->b_bufsize);
3472                                 bp->b_xio.xio_pages[0]->valid |= mask;
3473                                 bp->b_resid = 0;
3474                                 return;
3475                         }
3476                 }
3477                 ea = sa = bp->b_data;
3478                 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3479                         int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3480                         ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3481                         ea = (caddr_t)(vm_offset_t)ulmin(
3482                             (u_long)(vm_offset_t)ea,
3483                             (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3484                         mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3485                         if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3486                                 continue;
3487                         if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3488                                 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3489                                         bzero(sa, ea - sa);
3490                                 }
3491                         } else {
3492                                 for (; sa < ea; sa += DEV_BSIZE, j++) {
3493                                         if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3494                                                 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3495                                                 bzero(sa, DEV_BSIZE);
3496                                 }
3497                         }
3498                         bp->b_xio.xio_pages[i]->valid |= mask;
3499                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3500                 }
3501                 bp->b_resid = 0;
3502         } else {
3503                 clrbuf(bp);
3504         }
3505 }
3506
3507 /*
3508  * vm_hold_load_pages:
3509  *
3510  *      Load pages into the buffer's address space.  The pages are
3511  *      allocated from the kernel object in order to reduce interference
3512  *      with the any VM paging I/O activity.  The range of loaded
3513  *      pages will be wired.
3514  *
3515  *      If a page cannot be allocated, the 'pagedaemon' is woken up to
3516  *      retrieve the full range (to - from) of pages.
3517  *
3518  */
3519 void
3520 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3521 {
3522         vm_offset_t pg;
3523         vm_page_t p;
3524         int index;
3525
3526         to = round_page(to);
3527         from = round_page(from);
3528         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3529
3530         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3531
3532 tryagain:
3533
3534                 /*
3535                  * Note: must allocate system pages since blocking here
3536                  * could intefere with paging I/O, no matter which
3537                  * process we are.
3538                  */
3539                 p = vm_page_alloc(&kernel_object,
3540                                   (pg >> PAGE_SHIFT),
3541                                   VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3542                 if (!p) {
3543                         vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3544                         vm_wait();
3545                         goto tryagain;
3546                 }
3547                 vm_page_wire(p);
3548                 p->valid = VM_PAGE_BITS_ALL;
3549                 vm_page_flag_clear(p, PG_ZERO);
3550                 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3551                 bp->b_xio.xio_pages[index] = p;
3552                 vm_page_wakeup(p);
3553         }
3554         bp->b_xio.xio_npages = index;
3555 }
3556
3557 /*
3558  * vm_hold_free_pages:
3559  *
3560  *      Return pages associated with the buffer back to the VM system.
3561  *
3562  *      The range of pages underlying the buffer's address space will
3563  *      be unmapped and un-wired.
3564  */
3565 void
3566 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3567 {
3568         vm_offset_t pg;
3569         vm_page_t p;
3570         int index, newnpages;
3571
3572         from = round_page(from);
3573         to = round_page(to);
3574         newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3575
3576         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3577                 p = bp->b_xio.xio_pages[index];
3578                 if (p && (index < bp->b_xio.xio_npages)) {
3579                         if (p->busy) {
3580                                 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3581                                         bp->b_bio2.bio_offset, bp->b_loffset);
3582                         }
3583                         bp->b_xio.xio_pages[index] = NULL;
3584                         pmap_kremove(pg);
3585                         vm_page_busy(p);
3586                         vm_page_unwire(p, 0);
3587                         vm_page_free(p);
3588                 }
3589         }
3590         bp->b_xio.xio_npages = newnpages;
3591 }
3592
3593 /*
3594  * vmapbuf:
3595  *
3596  *      Map a user buffer into KVM via a pbuf.  On return the buffer's
3597  *      b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3598  *      initialized.
3599  */
3600 int
3601 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3602 {
3603         caddr_t addr;
3604         vm_offset_t va;
3605         vm_page_t m;
3606         int vmprot;
3607         int error;
3608         int pidx;
3609         int i;
3610
3611         /* 
3612          * bp had better have a command and it better be a pbuf.
3613          */
3614         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3615         KKASSERT(bp->b_flags & B_PAGING);
3616
3617         if (bytes < 0)
3618                 return (-1);
3619
3620         /*
3621          * Map the user data into KVM.  Mappings have to be page-aligned.
3622          */
3623         addr = (caddr_t)trunc_page((vm_offset_t)udata);
3624         pidx = 0;
3625
3626         vmprot = VM_PROT_READ;
3627         if (bp->b_cmd == BUF_CMD_READ)
3628                 vmprot |= VM_PROT_WRITE;
3629
3630         while (addr < udata + bytes) {
3631                 /*
3632                  * Do the vm_fault if needed; do the copy-on-write thing
3633                  * when reading stuff off device into memory.
3634                  *
3635                  * vm_fault_page*() returns a held VM page.
3636                  */
3637                 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3638                 va = trunc_page(va);
3639
3640                 m = vm_fault_page_quick(va, vmprot, &error);
3641                 if (m == NULL) {
3642                         for (i = 0; i < pidx; ++i) {
3643                             vm_page_unhold(bp->b_xio.xio_pages[i]);
3644                             bp->b_xio.xio_pages[i] = NULL;
3645                         }
3646                         return(-1);
3647                 }
3648                 bp->b_xio.xio_pages[pidx] = m;
3649                 addr += PAGE_SIZE;
3650                 ++pidx;
3651         }
3652
3653         /*
3654          * Map the page array and set the buffer fields to point to
3655          * the mapped data buffer.
3656          */
3657         if (pidx > btoc(MAXPHYS))
3658                 panic("vmapbuf: mapped more than MAXPHYS");
3659         pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3660
3661         bp->b_xio.xio_npages = pidx;
3662         bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3663         bp->b_bcount = bytes;
3664         bp->b_bufsize = bytes;
3665         return(0);
3666 }
3667
3668 /*
3669  * vunmapbuf:
3670  *
3671  *      Free the io map PTEs associated with this IO operation.
3672  *      We also invalidate the TLB entries and restore the original b_addr.
3673  */
3674 void
3675 vunmapbuf(struct buf *bp)
3676 {
3677         int pidx;
3678         int npages;
3679
3680         KKASSERT(bp->b_flags & B_PAGING);
3681
3682         npages = bp->b_xio.xio_npages;
3683         pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3684         for (pidx = 0; pidx < npages; ++pidx) {
3685                 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3686                 bp->b_xio.xio_pages[pidx] = NULL;
3687         }
3688         bp->b_xio.xio_npages = 0;
3689         bp->b_data = bp->b_kvabase;
3690 }
3691
3692 /*
3693  * Scan all buffers in the system and issue the callback.
3694  */
3695 int
3696 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3697 {
3698         int count = 0;
3699         int error;
3700         int n;
3701
3702         for (n = 0; n < nbuf; ++n) {
3703                 if ((error = callback(&buf[n], info)) < 0) {
3704                         count = error;
3705                         break;
3706                 }
3707                 count += error;
3708         }
3709         return (count);
3710 }
3711
3712 /*
3713  * print out statistics from the current status of the buffer pool
3714  * this can be toggeled by the system control option debug.syncprt
3715  */
3716 #ifdef DEBUG
3717 void
3718 vfs_bufstats(void)
3719 {
3720         int i, j, count;
3721         struct buf *bp;
3722         struct bqueues *dp;
3723         int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3724         static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3725
3726         for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3727                 count = 0;
3728                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3729                         counts[j] = 0;
3730                 crit_enter();
3731                 TAILQ_FOREACH(bp, dp, b_freelist) {
3732                         counts[bp->b_bufsize/PAGE_SIZE]++;
3733                         count++;
3734                 }
3735                 crit_exit();
3736                 kprintf("%s: total-%d", bname[i], count);
3737                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3738                         if (counts[j] != 0)
3739                                 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3740                 kprintf("\n");
3741         }
3742 }
3743 #endif
3744
3745 #ifdef DDB
3746
3747 DB_SHOW_COMMAND(buffer, db_show_buffer)
3748 {
3749         /* get args */
3750         struct buf *bp = (struct buf *)addr;
3751
3752         if (!have_addr) {
3753                 db_printf("usage: show buffer <addr>\n");
3754                 return;
3755         }
3756
3757         db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3758         db_printf("b_cmd = %d\n", bp->b_cmd);
3759         db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3760                   "b_resid = %d\n, b_data = %p, "
3761                   "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3762                   bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3763                   bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3764         if (bp->b_xio.xio_npages) {
3765                 int i;
3766                 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3767                         bp->b_xio.xio_npages);
3768                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3769                         vm_page_t m;
3770                         m = bp->b_xio.xio_pages[i];
3771                         db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3772                             (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3773                         if ((i + 1) < bp->b_xio.xio_npages)
3774                                 db_printf(",");
3775                 }
3776                 db_printf("\n");
3777         }
3778 }
3779 #endif /* DDB */