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