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