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