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