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