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