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