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