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