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