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