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