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