]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_bio.c
nvi: import version 2.2.1
[FreeBSD/FreeBSD.git] / sys / kern / vfs_bio.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2004 Poul-Henning Kamp
5  * Copyright (c) 1994,1997 John S. Dyson
6  * Copyright (c) 2013 The FreeBSD Foundation
7  * All rights reserved.
8  *
9  * Portions of this software were developed by Konstantin Belousov
10  * under sponsorship from the FreeBSD Foundation.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * this file contains a new buffer I/O scheme implementing a coherent
36  * VM object and buffer cache scheme.  Pains have been taken to make
37  * sure that the performance degradation associated with schemes such
38  * as this is not realized.
39  *
40  * Author:  John S. Dyson
41  * Significant help during the development and debugging phases
42  * had been provided by David Greenman, also of the FreeBSD core team.
43  *
44  * see man buf(9) for more info.
45  */
46
47 #include <sys/cdefs.h>
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/asan.h>
51 #include <sys/bio.h>
52 #include <sys/bitset.h>
53 #include <sys/boottrace.h>
54 #include <sys/buf.h>
55 #include <sys/conf.h>
56 #include <sys/counter.h>
57 #include <sys/devicestat.h>
58 #include <sys/eventhandler.h>
59 #include <sys/fail.h>
60 #include <sys/ktr.h>
61 #include <sys/limits.h>
62 #include <sys/lock.h>
63 #include <sys/malloc.h>
64 #include <sys/memdesc.h>
65 #include <sys/mount.h>
66 #include <sys/mutex.h>
67 #include <sys/kernel.h>
68 #include <sys/kthread.h>
69 #include <sys/pctrie.h>
70 #include <sys/proc.h>
71 #include <sys/racct.h>
72 #include <sys/refcount.h>
73 #include <sys/resourcevar.h>
74 #include <sys/rwlock.h>
75 #include <sys/sched.h>
76 #include <sys/smp.h>
77 #include <sys/sysctl.h>
78 #include <sys/syscallsubr.h>
79 #include <sys/vmem.h>
80 #include <sys/vmmeter.h>
81 #include <sys/vnode.h>
82 #include <sys/watchdog.h>
83 #include <geom/geom.h>
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_pager.h>
91 #include <vm/vm_extern.h>
92 #include <vm/vm_map.h>
93 #include <vm/swap_pager.h>
94
95 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
96
97 struct  bio_ops bioops;         /* I/O operation notification */
98
99 struct  buf_ops buf_ops_bio = {
100         .bop_name       =       "buf_ops_bio",
101         .bop_write      =       bufwrite,
102         .bop_strategy   =       bufstrategy,
103         .bop_sync       =       bufsync,
104         .bop_bdflush    =       bufbdflush,
105 };
106
107 struct bufqueue {
108         struct mtx_padalign     bq_lock;
109         TAILQ_HEAD(, buf)       bq_queue;
110         uint8_t                 bq_index;
111         uint16_t                bq_subqueue;
112         int                     bq_len;
113 } __aligned(CACHE_LINE_SIZE);
114
115 #define BQ_LOCKPTR(bq)          (&(bq)->bq_lock)
116 #define BQ_LOCK(bq)             mtx_lock(BQ_LOCKPTR((bq)))
117 #define BQ_UNLOCK(bq)           mtx_unlock(BQ_LOCKPTR((bq)))
118 #define BQ_ASSERT_LOCKED(bq)    mtx_assert(BQ_LOCKPTR((bq)), MA_OWNED)
119
120 struct bufdomain {
121         struct bufqueue *bd_subq;
122         struct bufqueue bd_dirtyq;
123         struct bufqueue *bd_cleanq;
124         struct mtx_padalign bd_run_lock;
125         /* Constants */
126         long            bd_maxbufspace;
127         long            bd_hibufspace;
128         long            bd_lobufspace;
129         long            bd_bufspacethresh;
130         int             bd_hifreebuffers;
131         int             bd_lofreebuffers;
132         int             bd_hidirtybuffers;
133         int             bd_lodirtybuffers;
134         int             bd_dirtybufthresh;
135         int             bd_lim;
136         /* atomics */
137         int             bd_wanted;
138         bool            bd_shutdown;
139         int __aligned(CACHE_LINE_SIZE)  bd_numdirtybuffers;
140         int __aligned(CACHE_LINE_SIZE)  bd_running;
141         long __aligned(CACHE_LINE_SIZE) bd_bufspace;
142         int __aligned(CACHE_LINE_SIZE)  bd_freebuffers;
143 } __aligned(CACHE_LINE_SIZE);
144
145 #define BD_LOCKPTR(bd)          (&(bd)->bd_cleanq->bq_lock)
146 #define BD_LOCK(bd)             mtx_lock(BD_LOCKPTR((bd)))
147 #define BD_UNLOCK(bd)           mtx_unlock(BD_LOCKPTR((bd)))
148 #define BD_ASSERT_LOCKED(bd)    mtx_assert(BD_LOCKPTR((bd)), MA_OWNED)
149 #define BD_RUN_LOCKPTR(bd)      (&(bd)->bd_run_lock)
150 #define BD_RUN_LOCK(bd)         mtx_lock(BD_RUN_LOCKPTR((bd)))
151 #define BD_RUN_UNLOCK(bd)       mtx_unlock(BD_RUN_LOCKPTR((bd)))
152 #define BD_DOMAIN(bd)           (bd - bdomain)
153
154 static char *buf;               /* buffer header pool */
155 static struct buf *
156 nbufp(unsigned i)
157 {
158         return ((struct buf *)(buf + (sizeof(struct buf) +
159             sizeof(vm_page_t) * atop(maxbcachebuf)) * i));
160 }
161
162 caddr_t __read_mostly unmapped_buf;
163
164 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
165 struct proc *bufdaemonproc;
166
167 static void vm_hold_free_pages(struct buf *bp, int newbsize);
168 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
169                 vm_offset_t to);
170 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
171 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
172                 vm_page_t m);
173 static void vfs_clean_pages_dirty_buf(struct buf *bp);
174 static void vfs_setdirty_range(struct buf *bp);
175 static void vfs_vmio_invalidate(struct buf *bp);
176 static void vfs_vmio_truncate(struct buf *bp, int npages);
177 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
178 static int vfs_bio_clcheck(struct vnode *vp, int size,
179                 daddr_t lblkno, daddr_t blkno);
180 static void breada(struct vnode *, daddr_t *, int *, int, struct ucred *, int,
181                 void (*)(struct buf *));
182 static int buf_flush(struct vnode *vp, struct bufdomain *, int);
183 static int flushbufqueues(struct vnode *, struct bufdomain *, int, int);
184 static void buf_daemon(void);
185 static __inline void bd_wakeup(void);
186 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
187 static void bufkva_reclaim(vmem_t *, int);
188 static void bufkva_free(struct buf *);
189 static int buf_import(void *, void **, int, int, int);
190 static void buf_release(void *, void **, int);
191 static void maxbcachebuf_adjust(void);
192 static inline struct bufdomain *bufdomain(struct buf *);
193 static void bq_remove(struct bufqueue *bq, struct buf *bp);
194 static void bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock);
195 static int buf_recycle(struct bufdomain *, bool kva);
196 static void bq_init(struct bufqueue *bq, int qindex, int cpu,
197             const char *lockname);
198 static void bd_init(struct bufdomain *bd);
199 static int bd_flushall(struct bufdomain *bd);
200 static int sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS);
201 static int sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS);
202
203 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
204 int vmiodirenable = TRUE;
205 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
206     "Use the VM system for directory writes");
207 long runningbufspace;
208 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
209     "Amount of presently outstanding async buffer io");
210 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
211     NULL, 0, sysctl_bufspace, "L", "Physical memory used for buffers");
212 static counter_u64_t bufkvaspace;
213 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace,
214     "Kernel virtual memory used for buffers");
215 static long maxbufspace;
216 SYSCTL_PROC(_vfs, OID_AUTO, maxbufspace,
217     CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &maxbufspace,
218     __offsetof(struct bufdomain, bd_maxbufspace), sysctl_bufdomain_long, "L",
219     "Maximum allowed value of bufspace (including metadata)");
220 static long bufmallocspace;
221 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
222     "Amount of malloced memory for buffers");
223 static long maxbufmallocspace;
224 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
225     0, "Maximum amount of malloced memory for buffers");
226 static long lobufspace;
227 SYSCTL_PROC(_vfs, OID_AUTO, lobufspace,
228     CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &lobufspace,
229     __offsetof(struct bufdomain, bd_lobufspace), sysctl_bufdomain_long, "L",
230     "Minimum amount of buffers we want to have");
231 long hibufspace;
232 SYSCTL_PROC(_vfs, OID_AUTO, hibufspace,
233     CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &hibufspace,
234     __offsetof(struct bufdomain, bd_hibufspace), sysctl_bufdomain_long, "L",
235     "Maximum allowed value of bufspace (excluding metadata)");
236 long bufspacethresh;
237 SYSCTL_PROC(_vfs, OID_AUTO, bufspacethresh,
238     CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &bufspacethresh,
239     __offsetof(struct bufdomain, bd_bufspacethresh), sysctl_bufdomain_long, "L",
240     "Bufspace consumed before waking the daemon to free some");
241 static counter_u64_t buffreekvacnt;
242 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt,
243     "Number of times we have freed the KVA space from some buffer");
244 static counter_u64_t bufdefragcnt;
245 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt,
246     "Number of times we have had to repeat buffer allocation to defragment");
247 static long lorunningspace;
248 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
249     CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
250     "Minimum preferred space used for in-progress I/O");
251 static long hirunningspace;
252 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
253     CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
254     "Maximum amount of space to use for in-progress I/O");
255 int dirtybufferflushes;
256 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
257     0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
258 int bdwriteskip;
259 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
260     0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
261 int altbufferflushes;
262 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW | CTLFLAG_STATS,
263     &altbufferflushes, 0, "Number of fsync flushes to limit dirty buffers");
264 static int recursiveflushes;
265 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW | CTLFLAG_STATS,
266     &recursiveflushes, 0, "Number of flushes skipped due to being recursive");
267 static int sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS);
268 SYSCTL_PROC(_vfs, OID_AUTO, numdirtybuffers,
269     CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RD, NULL, 0, sysctl_numdirtybuffers, "I",
270     "Number of buffers that are dirty (has unwritten changes) at the moment");
271 static int lodirtybuffers;
272 SYSCTL_PROC(_vfs, OID_AUTO, lodirtybuffers,
273     CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lodirtybuffers,
274     __offsetof(struct bufdomain, bd_lodirtybuffers), sysctl_bufdomain_int, "I",
275     "How many buffers we want to have free before bufdaemon can sleep");
276 static int hidirtybuffers;
277 SYSCTL_PROC(_vfs, OID_AUTO, hidirtybuffers,
278     CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hidirtybuffers,
279     __offsetof(struct bufdomain, bd_hidirtybuffers), sysctl_bufdomain_int, "I",
280     "When the number of dirty buffers is considered severe");
281 int dirtybufthresh;
282 SYSCTL_PROC(_vfs, OID_AUTO, dirtybufthresh,
283     CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &dirtybufthresh,
284     __offsetof(struct bufdomain, bd_dirtybufthresh), sysctl_bufdomain_int, "I",
285     "Number of bdwrite to bawrite conversions to clear dirty buffers");
286 static int numfreebuffers;
287 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
288     "Number of free buffers");
289 static int lofreebuffers;
290 SYSCTL_PROC(_vfs, OID_AUTO, lofreebuffers,
291     CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lofreebuffers,
292     __offsetof(struct bufdomain, bd_lofreebuffers), sysctl_bufdomain_int, "I",
293    "Target number of free buffers");
294 static int hifreebuffers;
295 SYSCTL_PROC(_vfs, OID_AUTO, hifreebuffers,
296     CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hifreebuffers,
297     __offsetof(struct bufdomain, bd_hifreebuffers), sysctl_bufdomain_int, "I",
298    "Threshold for clean buffer recycling");
299 static counter_u64_t getnewbufcalls;
300 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD,
301    &getnewbufcalls, "Number of calls to getnewbuf");
302 static counter_u64_t getnewbufrestarts;
303 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD,
304     &getnewbufrestarts,
305     "Number of times getnewbuf has had to restart a buffer acquisition");
306 static counter_u64_t mappingrestarts;
307 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RD,
308     &mappingrestarts,
309     "Number of times getblk has had to restart a buffer mapping for "
310     "unmapped buffer");
311 static counter_u64_t numbufallocfails;
312 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW,
313     &numbufallocfails, "Number of times buffer allocations failed");
314 static int flushbufqtarget = 100;
315 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
316     "Amount of work to do in flushbufqueues when helping bufdaemon");
317 static counter_u64_t notbufdflushes;
318 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, &notbufdflushes,
319     "Number of dirty buffer flushes done by the bufdaemon helpers");
320 static long barrierwrites;
321 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW | CTLFLAG_STATS,
322     &barrierwrites, 0, "Number of barrier writes");
323 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
324     &unmapped_buf_allowed, 0,
325     "Permit the use of the unmapped i/o");
326 int maxbcachebuf = MAXBCACHEBUF;
327 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
328     "Maximum size of a buffer cache block");
329
330 /*
331  * This lock synchronizes access to bd_request.
332  */
333 static struct mtx_padalign __exclusive_cache_line bdlock;
334
335 /*
336  * This lock protects the runningbufreq and synchronizes runningbufwakeup and
337  * waitrunningbufspace().
338  */
339 static struct mtx_padalign __exclusive_cache_line rbreqlock;
340
341 /*
342  * Lock that protects bdirtywait.
343  */
344 static struct mtx_padalign __exclusive_cache_line bdirtylock;
345
346 /*
347  * bufdaemon shutdown request and sleep channel.
348  */
349 static bool bd_shutdown;
350
351 /*
352  * Wakeup point for bufdaemon, as well as indicator of whether it is already
353  * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
354  * is idling.
355  */
356 static int bd_request;
357
358 /*
359  * Request for the buf daemon to write more buffers than is indicated by
360  * lodirtybuf.  This may be necessary to push out excess dependencies or
361  * defragment the address space where a simple count of the number of dirty
362  * buffers is insufficient to characterize the demand for flushing them.
363  */
364 static int bd_speedupreq;
365
366 /*
367  * Synchronization (sleep/wakeup) variable for active buffer space requests.
368  * Set when wait starts, cleared prior to wakeup().
369  * Used in runningbufwakeup() and waitrunningbufspace().
370  */
371 static int runningbufreq;
372
373 /*
374  * Synchronization for bwillwrite() waiters.
375  */
376 static int bdirtywait;
377
378 /*
379  * Definitions for the buffer free lists.
380  */
381 #define QUEUE_NONE      0       /* on no queue */
382 #define QUEUE_EMPTY     1       /* empty buffer headers */
383 #define QUEUE_DIRTY     2       /* B_DELWRI buffers */
384 #define QUEUE_CLEAN     3       /* non-B_DELWRI buffers */
385 #define QUEUE_SENTINEL  4       /* not an queue index, but mark for sentinel */
386
387 /* Maximum number of buffer domains. */
388 #define BUF_DOMAINS     8
389
390 struct bufdomainset bdlodirty;          /* Domains > lodirty */
391 struct bufdomainset bdhidirty;          /* Domains > hidirty */
392
393 /* Configured number of clean queues. */
394 static int __read_mostly buf_domains;
395
396 BITSET_DEFINE(bufdomainset, BUF_DOMAINS);
397 struct bufdomain __exclusive_cache_line bdomain[BUF_DOMAINS];
398 struct bufqueue __exclusive_cache_line bqempty;
399
400 /*
401  * per-cpu empty buffer cache.
402  */
403 uma_zone_t buf_zone;
404
405 static int
406 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
407 {
408         long value;
409         int error;
410
411         value = *(long *)arg1;
412         error = sysctl_handle_long(oidp, &value, 0, req);
413         if (error != 0 || req->newptr == NULL)
414                 return (error);
415         mtx_lock(&rbreqlock);
416         if (arg1 == &hirunningspace) {
417                 if (value < lorunningspace)
418                         error = EINVAL;
419                 else
420                         hirunningspace = value;
421         } else {
422                 KASSERT(arg1 == &lorunningspace,
423                     ("%s: unknown arg1", __func__));
424                 if (value > hirunningspace)
425                         error = EINVAL;
426                 else
427                         lorunningspace = value;
428         }
429         mtx_unlock(&rbreqlock);
430         return (error);
431 }
432
433 static int
434 sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS)
435 {
436         int error;
437         int value;
438         int i;
439
440         value = *(int *)arg1;
441         error = sysctl_handle_int(oidp, &value, 0, req);
442         if (error != 0 || req->newptr == NULL)
443                 return (error);
444         *(int *)arg1 = value;
445         for (i = 0; i < buf_domains; i++)
446                 *(int *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
447                     value / buf_domains;
448
449         return (error);
450 }
451
452 static int
453 sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS)
454 {
455         long value;
456         int error;
457         int i;
458
459         value = *(long *)arg1;
460         error = sysctl_handle_long(oidp, &value, 0, req);
461         if (error != 0 || req->newptr == NULL)
462                 return (error);
463         *(long *)arg1 = value;
464         for (i = 0; i < buf_domains; i++)
465                 *(long *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
466                     value / buf_domains;
467
468         return (error);
469 }
470
471 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
472     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
473 static int
474 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
475 {
476         long lvalue;
477         int ivalue;
478         int i;
479
480         lvalue = 0;
481         for (i = 0; i < buf_domains; i++)
482                 lvalue += bdomain[i].bd_bufspace;
483         if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
484                 return (sysctl_handle_long(oidp, &lvalue, 0, req));
485         if (lvalue > INT_MAX)
486                 /* On overflow, still write out a long to trigger ENOMEM. */
487                 return (sysctl_handle_long(oidp, &lvalue, 0, req));
488         ivalue = lvalue;
489         return (sysctl_handle_int(oidp, &ivalue, 0, req));
490 }
491 #else
492 static int
493 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
494 {
495         long lvalue;
496         int i;
497
498         lvalue = 0;
499         for (i = 0; i < buf_domains; i++)
500                 lvalue += bdomain[i].bd_bufspace;
501         return (sysctl_handle_long(oidp, &lvalue, 0, req));
502 }
503 #endif
504
505 static int
506 sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS)
507 {
508         int value;
509         int i;
510
511         value = 0;
512         for (i = 0; i < buf_domains; i++)
513                 value += bdomain[i].bd_numdirtybuffers;
514         return (sysctl_handle_int(oidp, &value, 0, req));
515 }
516
517 /*
518  *      bdirtywakeup:
519  *
520  *      Wakeup any bwillwrite() waiters.
521  */
522 static void
523 bdirtywakeup(void)
524 {
525         mtx_lock(&bdirtylock);
526         if (bdirtywait) {
527                 bdirtywait = 0;
528                 wakeup(&bdirtywait);
529         }
530         mtx_unlock(&bdirtylock);
531 }
532
533 /*
534  *      bd_clear:
535  *
536  *      Clear a domain from the appropriate bitsets when dirtybuffers
537  *      is decremented.
538  */
539 static void
540 bd_clear(struct bufdomain *bd)
541 {
542
543         mtx_lock(&bdirtylock);
544         if (bd->bd_numdirtybuffers <= bd->bd_lodirtybuffers)
545                 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
546         if (bd->bd_numdirtybuffers <= bd->bd_hidirtybuffers)
547                 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
548         mtx_unlock(&bdirtylock);
549 }
550
551 /*
552  *      bd_set:
553  *
554  *      Set a domain in the appropriate bitsets when dirtybuffers
555  *      is incremented.
556  */
557 static void
558 bd_set(struct bufdomain *bd)
559 {
560
561         mtx_lock(&bdirtylock);
562         if (bd->bd_numdirtybuffers > bd->bd_lodirtybuffers)
563                 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
564         if (bd->bd_numdirtybuffers > bd->bd_hidirtybuffers)
565                 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
566         mtx_unlock(&bdirtylock);
567 }
568
569 /*
570  *      bdirtysub:
571  *
572  *      Decrement the numdirtybuffers count by one and wakeup any
573  *      threads blocked in bwillwrite().
574  */
575 static void
576 bdirtysub(struct buf *bp)
577 {
578         struct bufdomain *bd;
579         int num;
580
581         bd = bufdomain(bp);
582         num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, -1);
583         if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
584                 bdirtywakeup();
585         if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
586                 bd_clear(bd);
587 }
588
589 /*
590  *      bdirtyadd:
591  *
592  *      Increment the numdirtybuffers count by one and wakeup the buf 
593  *      daemon if needed.
594  */
595 static void
596 bdirtyadd(struct buf *bp)
597 {
598         struct bufdomain *bd;
599         int num;
600
601         /*
602          * Only do the wakeup once as we cross the boundary.  The
603          * buf daemon will keep running until the condition clears.
604          */
605         bd = bufdomain(bp);
606         num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, 1);
607         if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
608                 bd_wakeup();
609         if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
610                 bd_set(bd);
611 }
612
613 /*
614  *      bufspace_daemon_wakeup:
615  *
616  *      Wakeup the daemons responsible for freeing clean bufs.
617  */
618 static void
619 bufspace_daemon_wakeup(struct bufdomain *bd)
620 {
621
622         /*
623          * avoid the lock if the daemon is running.
624          */
625         if (atomic_fetchadd_int(&bd->bd_running, 1) == 0) {
626                 BD_RUN_LOCK(bd);
627                 atomic_store_int(&bd->bd_running, 1);
628                 wakeup(&bd->bd_running);
629                 BD_RUN_UNLOCK(bd);
630         }
631 }
632
633 /*
634  *      bufspace_adjust:
635  *
636  *      Adjust the reported bufspace for a KVA managed buffer, possibly
637  *      waking any waiters.
638  */
639 static void
640 bufspace_adjust(struct buf *bp, int bufsize)
641 {
642         struct bufdomain *bd;
643         long space;
644         int diff;
645
646         KASSERT((bp->b_flags & B_MALLOC) == 0,
647             ("bufspace_adjust: malloc buf %p", bp));
648         bd = bufdomain(bp);
649         diff = bufsize - bp->b_bufsize;
650         if (diff < 0) {
651                 atomic_subtract_long(&bd->bd_bufspace, -diff);
652         } else if (diff > 0) {
653                 space = atomic_fetchadd_long(&bd->bd_bufspace, diff);
654                 /* Wake up the daemon on the transition. */
655                 if (space < bd->bd_bufspacethresh &&
656                     space + diff >= bd->bd_bufspacethresh)
657                         bufspace_daemon_wakeup(bd);
658         }
659         bp->b_bufsize = bufsize;
660 }
661
662 /*
663  *      bufspace_reserve:
664  *
665  *      Reserve bufspace before calling allocbuf().  metadata has a
666  *      different space limit than data.
667  */
668 static int
669 bufspace_reserve(struct bufdomain *bd, int size, bool metadata)
670 {
671         long limit, new;
672         long space;
673
674         if (metadata)
675                 limit = bd->bd_maxbufspace;
676         else
677                 limit = bd->bd_hibufspace;
678         space = atomic_fetchadd_long(&bd->bd_bufspace, size);
679         new = space + size;
680         if (new > limit) {
681                 atomic_subtract_long(&bd->bd_bufspace, size);
682                 return (ENOSPC);
683         }
684
685         /* Wake up the daemon on the transition. */
686         if (space < bd->bd_bufspacethresh && new >= bd->bd_bufspacethresh)
687                 bufspace_daemon_wakeup(bd);
688
689         return (0);
690 }
691
692 /*
693  *      bufspace_release:
694  *
695  *      Release reserved bufspace after bufspace_adjust() has consumed it.
696  */
697 static void
698 bufspace_release(struct bufdomain *bd, int size)
699 {
700
701         atomic_subtract_long(&bd->bd_bufspace, size);
702 }
703
704 /*
705  *      bufspace_wait:
706  *
707  *      Wait for bufspace, acting as the buf daemon if a locked vnode is
708  *      supplied.  bd_wanted must be set prior to polling for space.  The
709  *      operation must be re-tried on return.
710  */
711 static void
712 bufspace_wait(struct bufdomain *bd, struct vnode *vp, int gbflags,
713     int slpflag, int slptimeo)
714 {
715         struct thread *td;
716         int error, fl, norunbuf;
717
718         if ((gbflags & GB_NOWAIT_BD) != 0)
719                 return;
720
721         td = curthread;
722         BD_LOCK(bd);
723         while (bd->bd_wanted) {
724                 if (vp != NULL && vp->v_type != VCHR &&
725                     (td->td_pflags & TDP_BUFNEED) == 0) {
726                         BD_UNLOCK(bd);
727                         /*
728                          * getblk() is called with a vnode locked, and
729                          * some majority of the dirty buffers may as
730                          * well belong to the vnode.  Flushing the
731                          * buffers there would make a progress that
732                          * cannot be achieved by the buf_daemon, that
733                          * cannot lock the vnode.
734                          */
735                         norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
736                             (td->td_pflags & TDP_NORUNNINGBUF);
737
738                         /*
739                          * Play bufdaemon.  The getnewbuf() function
740                          * may be called while the thread owns lock
741                          * for another dirty buffer for the same
742                          * vnode, which makes it impossible to use
743                          * VOP_FSYNC() there, due to the buffer lock
744                          * recursion.
745                          */
746                         td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
747                         fl = buf_flush(vp, bd, flushbufqtarget);
748                         td->td_pflags &= norunbuf;
749                         BD_LOCK(bd);
750                         if (fl != 0)
751                                 continue;
752                         if (bd->bd_wanted == 0)
753                                 break;
754                 }
755                 error = msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
756                     (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
757                 if (error != 0)
758                         break;
759         }
760         BD_UNLOCK(bd);
761 }
762
763 static void
764 bufspace_daemon_shutdown(void *arg, int howto __unused)
765 {
766         struct bufdomain *bd = arg;
767         int error;
768
769         if (KERNEL_PANICKED())
770                 return;
771
772         BD_RUN_LOCK(bd);
773         bd->bd_shutdown = true;
774         wakeup(&bd->bd_running);
775         error = msleep(&bd->bd_shutdown, BD_RUN_LOCKPTR(bd), 0,
776             "bufspace_shutdown", 60 * hz);
777         BD_RUN_UNLOCK(bd);
778         if (error != 0)
779                 printf("bufspacedaemon wait error: %d\n", error);
780 }
781
782 /*
783  *      bufspace_daemon:
784  *
785  *      buffer space management daemon.  Tries to maintain some marginal
786  *      amount of free buffer space so that requesting processes neither
787  *      block nor work to reclaim buffers.
788  */
789 static void
790 bufspace_daemon(void *arg)
791 {
792         struct bufdomain *bd = arg;
793
794         EVENTHANDLER_REGISTER(shutdown_pre_sync, bufspace_daemon_shutdown, bd,
795             SHUTDOWN_PRI_LAST + 100);
796
797         BD_RUN_LOCK(bd);
798         while (!bd->bd_shutdown) {
799                 BD_RUN_UNLOCK(bd);
800
801                 /*
802                  * Free buffers from the clean queue until we meet our
803                  * targets.
804                  *
805                  * Theory of operation:  The buffer cache is most efficient
806                  * when some free buffer headers and space are always
807                  * available to getnewbuf().  This daemon attempts to prevent
808                  * the excessive blocking and synchronization associated
809                  * with shortfall.  It goes through three phases according
810                  * demand:
811                  *
812                  * 1)   The daemon wakes up voluntarily once per-second
813                  *      during idle periods when the counters are below
814                  *      the wakeup thresholds (bufspacethresh, lofreebuffers).
815                  *
816                  * 2)   The daemon wakes up as we cross the thresholds
817                  *      ahead of any potential blocking.  This may bounce
818                  *      slightly according to the rate of consumption and
819                  *      release.
820                  *
821                  * 3)   The daemon and consumers are starved for working
822                  *      clean buffers.  This is the 'bufspace' sleep below
823                  *      which will inefficiently trade bufs with bqrelse
824                  *      until we return to condition 2.
825                  */
826                 while (bd->bd_bufspace > bd->bd_lobufspace ||
827                     bd->bd_freebuffers < bd->bd_hifreebuffers) {
828                         if (buf_recycle(bd, false) != 0) {
829                                 if (bd_flushall(bd))
830                                         continue;
831                                 /*
832                                  * Speedup dirty if we've run out of clean
833                                  * buffers.  This is possible in particular
834                                  * because softdep may held many bufs locked
835                                  * pending writes to other bufs which are
836                                  * marked for delayed write, exhausting
837                                  * clean space until they are written.
838                                  */
839                                 bd_speedup();
840                                 BD_LOCK(bd);
841                                 if (bd->bd_wanted) {
842                                         msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
843                                             PRIBIO|PDROP, "bufspace", hz/10);
844                                 } else
845                                         BD_UNLOCK(bd);
846                         }
847                         maybe_yield();
848                 }
849
850                 /*
851                  * Re-check our limits and sleep.  bd_running must be
852                  * cleared prior to checking the limits to avoid missed
853                  * wakeups.  The waker will adjust one of bufspace or
854                  * freebuffers prior to checking bd_running.
855                  */
856                 BD_RUN_LOCK(bd);
857                 if (bd->bd_shutdown)
858                         break;
859                 atomic_store_int(&bd->bd_running, 0);
860                 if (bd->bd_bufspace < bd->bd_bufspacethresh &&
861                     bd->bd_freebuffers > bd->bd_lofreebuffers) {
862                         msleep(&bd->bd_running, BD_RUN_LOCKPTR(bd),
863                             PRIBIO, "-", hz);
864                 } else {
865                         /* Avoid spurious wakeups while running. */
866                         atomic_store_int(&bd->bd_running, 1);
867                 }
868         }
869         wakeup(&bd->bd_shutdown);
870         BD_RUN_UNLOCK(bd);
871         kthread_exit();
872 }
873
874 /*
875  *      bufmallocadjust:
876  *
877  *      Adjust the reported bufspace for a malloc managed buffer, possibly
878  *      waking any waiters.
879  */
880 static void
881 bufmallocadjust(struct buf *bp, int bufsize)
882 {
883         int diff;
884
885         KASSERT((bp->b_flags & B_MALLOC) != 0,
886             ("bufmallocadjust: non-malloc buf %p", bp));
887         diff = bufsize - bp->b_bufsize;
888         if (diff < 0)
889                 atomic_subtract_long(&bufmallocspace, -diff);
890         else
891                 atomic_add_long(&bufmallocspace, diff);
892         bp->b_bufsize = bufsize;
893 }
894
895 /*
896  *      runningwakeup:
897  *
898  *      Wake up processes that are waiting on asynchronous writes to fall
899  *      below lorunningspace.
900  */
901 static void
902 runningwakeup(void)
903 {
904
905         mtx_lock(&rbreqlock);
906         if (runningbufreq) {
907                 runningbufreq = 0;
908                 wakeup(&runningbufreq);
909         }
910         mtx_unlock(&rbreqlock);
911 }
912
913 /*
914  *      runningbufwakeup:
915  *
916  *      Decrement the outstanding write count according.
917  */
918 void
919 runningbufwakeup(struct buf *bp)
920 {
921         long space, bspace;
922
923         bspace = bp->b_runningbufspace;
924         if (bspace == 0)
925                 return;
926         space = atomic_fetchadd_long(&runningbufspace, -bspace);
927         KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
928             space, bspace));
929         bp->b_runningbufspace = 0;
930         /*
931          * Only acquire the lock and wakeup on the transition from exceeding
932          * the threshold to falling below it.
933          */
934         if (space < lorunningspace)
935                 return;
936         if (space - bspace > lorunningspace)
937                 return;
938         runningwakeup();
939 }
940
941 /*
942  *      waitrunningbufspace()
943  *
944  *      runningbufspace is a measure of the amount of I/O currently
945  *      running.  This routine is used in async-write situations to
946  *      prevent creating huge backups of pending writes to a device.
947  *      Only asynchronous writes are governed by this function.
948  *
949  *      This does NOT turn an async write into a sync write.  It waits  
950  *      for earlier writes to complete and generally returns before the
951  *      caller's write has reached the device.
952  */
953 void
954 waitrunningbufspace(void)
955 {
956
957         mtx_lock(&rbreqlock);
958         while (runningbufspace > hirunningspace) {
959                 runningbufreq = 1;
960                 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
961         }
962         mtx_unlock(&rbreqlock);
963 }
964
965 /*
966  *      vfs_buf_test_cache:
967  *
968  *      Called when a buffer is extended.  This function clears the B_CACHE
969  *      bit if the newly extended portion of the buffer does not contain
970  *      valid data.
971  */
972 static __inline void
973 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
974     vm_offset_t size, vm_page_t m)
975 {
976
977         /*
978          * This function and its results are protected by higher level
979          * synchronization requiring vnode and buf locks to page in and
980          * validate pages.
981          */
982         if (bp->b_flags & B_CACHE) {
983                 int base = (foff + off) & PAGE_MASK;
984                 if (vm_page_is_valid(m, base, size) == 0)
985                         bp->b_flags &= ~B_CACHE;
986         }
987 }
988
989 /* Wake up the buffer daemon if necessary */
990 static void
991 bd_wakeup(void)
992 {
993
994         mtx_lock(&bdlock);
995         if (bd_request == 0) {
996                 bd_request = 1;
997                 wakeup(&bd_request);
998         }
999         mtx_unlock(&bdlock);
1000 }
1001
1002 /*
1003  * Adjust the maxbcachbuf tunable.
1004  */
1005 static void
1006 maxbcachebuf_adjust(void)
1007 {
1008         int i;
1009
1010         /*
1011          * maxbcachebuf must be a power of 2 >= MAXBSIZE.
1012          */
1013         i = 2;
1014         while (i * 2 <= maxbcachebuf)
1015                 i *= 2;
1016         maxbcachebuf = i;
1017         if (maxbcachebuf < MAXBSIZE)
1018                 maxbcachebuf = MAXBSIZE;
1019         if (maxbcachebuf > maxphys)
1020                 maxbcachebuf = maxphys;
1021         if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
1022                 printf("maxbcachebuf=%d\n", maxbcachebuf);
1023 }
1024
1025 /*
1026  * bd_speedup - speedup the buffer cache flushing code
1027  */
1028 void
1029 bd_speedup(void)
1030 {
1031         int needwake;
1032
1033         mtx_lock(&bdlock);
1034         needwake = 0;
1035         if (bd_speedupreq == 0 || bd_request == 0)
1036                 needwake = 1;
1037         bd_speedupreq = 1;
1038         bd_request = 1;
1039         if (needwake)
1040                 wakeup(&bd_request);
1041         mtx_unlock(&bdlock);
1042 }
1043
1044 #ifdef __i386__
1045 #define TRANSIENT_DENOM 5
1046 #else
1047 #define TRANSIENT_DENOM 10
1048 #endif
1049
1050 /*
1051  * Calculating buffer cache scaling values and reserve space for buffer
1052  * headers.  This is called during low level kernel initialization and
1053  * may be called more then once.  We CANNOT write to the memory area
1054  * being reserved at this time.
1055  */
1056 caddr_t
1057 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
1058 {
1059         int tuned_nbuf;
1060         long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
1061
1062         /*
1063          * With KASAN or KMSAN enabled, the kernel map is shadowed.  Account for
1064          * this when sizing maps based on the amount of physical memory
1065          * available.
1066          */
1067 #if defined(KASAN)
1068         physmem_est = (physmem_est * KASAN_SHADOW_SCALE) /
1069             (KASAN_SHADOW_SCALE + 1);
1070 #elif defined(KMSAN)
1071         physmem_est /= 3;
1072
1073         /*
1074          * KMSAN cannot reliably determine whether buffer data is initialized
1075          * unless it is updated through a KVA mapping.
1076          */
1077         unmapped_buf_allowed = 0;
1078 #endif
1079
1080         /*
1081          * physmem_est is in pages.  Convert it to kilobytes (assumes
1082          * PAGE_SIZE is >= 1K)
1083          */
1084         physmem_est = physmem_est * (PAGE_SIZE / 1024);
1085
1086         maxbcachebuf_adjust();
1087         /*
1088          * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
1089          * For the first 64MB of ram nominally allocate sufficient buffers to
1090          * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
1091          * buffers to cover 1/10 of our ram over 64MB.  When auto-sizing
1092          * the buffer cache we limit the eventual kva reservation to
1093          * maxbcache bytes.
1094          *
1095          * factor represents the 1/4 x ram conversion.
1096          */
1097         if (nbuf == 0) {
1098                 int factor = 4 * BKVASIZE / 1024;
1099
1100                 nbuf = 50;
1101                 if (physmem_est > 4096)
1102                         nbuf += min((physmem_est - 4096) / factor,
1103                             65536 / factor);
1104                 if (physmem_est > 65536)
1105                         nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
1106                             32 * 1024 * 1024 / (factor * 5));
1107
1108                 if (maxbcache && nbuf > maxbcache / BKVASIZE)
1109                         nbuf = maxbcache / BKVASIZE;
1110                 tuned_nbuf = 1;
1111         } else
1112                 tuned_nbuf = 0;
1113
1114         /* XXX Avoid unsigned long overflows later on with maxbufspace. */
1115         maxbuf = (LONG_MAX / 3) / BKVASIZE;
1116         if (nbuf > maxbuf) {
1117                 if (!tuned_nbuf)
1118                         printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
1119                             maxbuf);
1120                 nbuf = maxbuf;
1121         }
1122
1123         /*
1124          * Ideal allocation size for the transient bio submap is 10%
1125          * of the maximal space buffer map.  This roughly corresponds
1126          * to the amount of the buffer mapped for typical UFS load.
1127          *
1128          * Clip the buffer map to reserve space for the transient
1129          * BIOs, if its extent is bigger than 90% (80% on i386) of the
1130          * maximum buffer map extent on the platform.
1131          *
1132          * The fall-back to the maxbuf in case of maxbcache unset,
1133          * allows to not trim the buffer KVA for the architectures
1134          * with ample KVA space.
1135          */
1136         if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
1137                 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
1138                 buf_sz = (long)nbuf * BKVASIZE;
1139                 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
1140                     (TRANSIENT_DENOM - 1)) {
1141                         /*
1142                          * There is more KVA than memory.  Do not
1143                          * adjust buffer map size, and assign the rest
1144                          * of maxbuf to transient map.
1145                          */
1146                         biotmap_sz = maxbuf_sz - buf_sz;
1147                 } else {
1148                         /*
1149                          * Buffer map spans all KVA we could afford on
1150                          * this platform.  Give 10% (20% on i386) of
1151                          * the buffer map to the transient bio map.
1152                          */
1153                         biotmap_sz = buf_sz / TRANSIENT_DENOM;
1154                         buf_sz -= biotmap_sz;
1155                 }
1156                 if (biotmap_sz / INT_MAX > maxphys)
1157                         bio_transient_maxcnt = INT_MAX;
1158                 else
1159                         bio_transient_maxcnt = biotmap_sz / maxphys;
1160                 /*
1161                  * Artificially limit to 1024 simultaneous in-flight I/Os
1162                  * using the transient mapping.
1163                  */
1164                 if (bio_transient_maxcnt > 1024)
1165                         bio_transient_maxcnt = 1024;
1166                 if (tuned_nbuf)
1167                         nbuf = buf_sz / BKVASIZE;
1168         }
1169
1170         if (nswbuf == 0) {
1171                 /*
1172                  * Pager buffers are allocated for short periods, so scale the
1173                  * number of reserved buffers based on the number of CPUs rather
1174                  * than amount of memory.
1175                  */
1176                 nswbuf = min(nbuf / 4, 32 * mp_ncpus);
1177                 if (nswbuf < NSWBUF_MIN)
1178                         nswbuf = NSWBUF_MIN;
1179         }
1180
1181         /*
1182          * Reserve space for the buffer cache buffers
1183          */
1184         buf = (char *)v;
1185         v = (caddr_t)buf + (sizeof(struct buf) + sizeof(vm_page_t) *
1186             atop(maxbcachebuf)) * nbuf;
1187
1188         return (v);
1189 }
1190
1191 /*
1192  * Single global constant for BUF_WMESG, to avoid getting multiple
1193  * references.
1194  */
1195 static const char buf_wmesg[] = "bufwait";
1196
1197 /* Initialize the buffer subsystem.  Called before use of any buffers. */
1198 void
1199 bufinit(void)
1200 {
1201         struct buf *bp;
1202         int i;
1203
1204         TSENTER();
1205         KASSERT(maxbcachebuf >= MAXBSIZE,
1206             ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1207             MAXBSIZE));
1208         bq_init(&bqempty, QUEUE_EMPTY, -1, "bufq empty lock");
1209         mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1210         mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1211         mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1212
1213         unmapped_buf = (caddr_t)kva_alloc(maxphys);
1214
1215         /* finally, initialize each buffer header and stick on empty q */
1216         for (i = 0; i < nbuf; i++) {
1217                 bp = nbufp(i);
1218                 bzero(bp, sizeof(*bp) + sizeof(vm_page_t) * atop(maxbcachebuf));
1219                 bp->b_flags = B_INVAL;
1220                 bp->b_rcred = NOCRED;
1221                 bp->b_wcred = NOCRED;
1222                 bp->b_qindex = QUEUE_NONE;
1223                 bp->b_domain = -1;
1224                 bp->b_subqueue = mp_maxid + 1;
1225                 bp->b_xflags = 0;
1226                 bp->b_data = bp->b_kvabase = unmapped_buf;
1227                 LIST_INIT(&bp->b_dep);
1228                 BUF_LOCKINIT(bp, buf_wmesg);
1229                 bq_insert(&bqempty, bp, false);
1230         }
1231
1232         /*
1233          * maxbufspace is the absolute maximum amount of buffer space we are 
1234          * allowed to reserve in KVM and in real terms.  The absolute maximum
1235          * is nominally used by metadata.  hibufspace is the nominal maximum
1236          * used by most other requests.  The differential is required to 
1237          * ensure that metadata deadlocks don't occur.
1238          *
1239          * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
1240          * this may result in KVM fragmentation which is not handled optimally
1241          * by the system. XXX This is less true with vmem.  We could use
1242          * PAGE_SIZE.
1243          */
1244         maxbufspace = (long)nbuf * BKVASIZE;
1245         hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1246         lobufspace = (hibufspace / 20) * 19; /* 95% */
1247         bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1248
1249         /*
1250          * Note: The 16 MiB upper limit for hirunningspace was chosen
1251          * arbitrarily and may need further tuning. It corresponds to
1252          * 128 outstanding write IO requests (if IO size is 128 KiB),
1253          * which fits with many RAID controllers' tagged queuing limits.
1254          * The lower 1 MiB limit is the historical upper limit for
1255          * hirunningspace.
1256          */
1257         hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1258             16 * 1024 * 1024), 1024 * 1024);
1259         lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1260
1261         /*
1262          * Limit the amount of malloc memory since it is wired permanently into
1263          * the kernel space.  Even though this is accounted for in the buffer
1264          * allocation, we don't want the malloced region to grow uncontrolled.
1265          * The malloc scheme improves memory utilization significantly on
1266          * average (small) directories.
1267          */
1268         maxbufmallocspace = hibufspace / 20;
1269
1270         /*
1271          * Reduce the chance of a deadlock occurring by limiting the number
1272          * of delayed-write dirty buffers we allow to stack up.
1273          */
1274         hidirtybuffers = nbuf / 4 + 20;
1275         dirtybufthresh = hidirtybuffers * 9 / 10;
1276         /*
1277          * To support extreme low-memory systems, make sure hidirtybuffers
1278          * cannot eat up all available buffer space.  This occurs when our
1279          * minimum cannot be met.  We try to size hidirtybuffers to 3/4 our
1280          * buffer space assuming BKVASIZE'd buffers.
1281          */
1282         while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1283                 hidirtybuffers >>= 1;
1284         }
1285         lodirtybuffers = hidirtybuffers / 2;
1286
1287         /*
1288          * lofreebuffers should be sufficient to avoid stalling waiting on
1289          * buf headers under heavy utilization.  The bufs in per-cpu caches
1290          * are counted as free but will be unavailable to threads executing
1291          * on other cpus.
1292          *
1293          * hifreebuffers is the free target for the bufspace daemon.  This
1294          * should be set appropriately to limit work per-iteration.
1295          */
1296         lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1297         hifreebuffers = (3 * lofreebuffers) / 2;
1298         numfreebuffers = nbuf;
1299
1300         /* Setup the kva and free list allocators. */
1301         vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1302         buf_zone = uma_zcache_create("buf free cache",
1303             sizeof(struct buf) + sizeof(vm_page_t) * atop(maxbcachebuf),
1304             NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1305
1306         /*
1307          * Size the clean queue according to the amount of buffer space.
1308          * One queue per-256mb up to the max.  More queues gives better
1309          * concurrency but less accurate LRU.
1310          */
1311         buf_domains = MIN(howmany(maxbufspace, 256*1024*1024), BUF_DOMAINS);
1312         for (i = 0 ; i < buf_domains; i++) {
1313                 struct bufdomain *bd;
1314
1315                 bd = &bdomain[i];
1316                 bd_init(bd);
1317                 bd->bd_freebuffers = nbuf / buf_domains;
1318                 bd->bd_hifreebuffers = hifreebuffers / buf_domains;
1319                 bd->bd_lofreebuffers = lofreebuffers / buf_domains;
1320                 bd->bd_bufspace = 0;
1321                 bd->bd_maxbufspace = maxbufspace / buf_domains;
1322                 bd->bd_hibufspace = hibufspace / buf_domains;
1323                 bd->bd_lobufspace = lobufspace / buf_domains;
1324                 bd->bd_bufspacethresh = bufspacethresh / buf_domains;
1325                 bd->bd_numdirtybuffers = 0;
1326                 bd->bd_hidirtybuffers = hidirtybuffers / buf_domains;
1327                 bd->bd_lodirtybuffers = lodirtybuffers / buf_domains;
1328                 bd->bd_dirtybufthresh = dirtybufthresh / buf_domains;
1329                 /* Don't allow more than 2% of bufs in the per-cpu caches. */
1330                 bd->bd_lim = nbuf / buf_domains / 50 / mp_ncpus;
1331         }
1332         getnewbufcalls = counter_u64_alloc(M_WAITOK);
1333         getnewbufrestarts = counter_u64_alloc(M_WAITOK);
1334         mappingrestarts = counter_u64_alloc(M_WAITOK);
1335         numbufallocfails = counter_u64_alloc(M_WAITOK);
1336         notbufdflushes = counter_u64_alloc(M_WAITOK);
1337         buffreekvacnt = counter_u64_alloc(M_WAITOK);
1338         bufdefragcnt = counter_u64_alloc(M_WAITOK);
1339         bufkvaspace = counter_u64_alloc(M_WAITOK);
1340         TSEXIT();
1341 }
1342
1343 #ifdef INVARIANTS
1344 static inline void
1345 vfs_buf_check_mapped(struct buf *bp)
1346 {
1347
1348         KASSERT(bp->b_kvabase != unmapped_buf,
1349             ("mapped buf: b_kvabase was not updated %p", bp));
1350         KASSERT(bp->b_data != unmapped_buf,
1351             ("mapped buf: b_data was not updated %p", bp));
1352         KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1353             maxphys, ("b_data + b_offset unmapped %p", bp));
1354 }
1355
1356 static inline void
1357 vfs_buf_check_unmapped(struct buf *bp)
1358 {
1359
1360         KASSERT(bp->b_data == unmapped_buf,
1361             ("unmapped buf: corrupted b_data %p", bp));
1362 }
1363
1364 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1365 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1366 #else
1367 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1368 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1369 #endif
1370
1371 static int
1372 isbufbusy(struct buf *bp)
1373 {
1374         if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1375             ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1376                 return (1);
1377         return (0);
1378 }
1379
1380 /*
1381  * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1382  */
1383 void
1384 bufshutdown(int show_busybufs)
1385 {
1386         static int first_buf_printf = 1;
1387         struct buf *bp;
1388         int i, iter, nbusy, pbusy;
1389 #ifndef PREEMPTION
1390         int subiter;
1391 #endif
1392
1393         /*
1394          * Sync filesystems for shutdown
1395          */
1396         wdog_kern_pat(WD_LASTVAL);
1397         kern_sync(curthread);
1398
1399         /*
1400          * With soft updates, some buffers that are
1401          * written will be remarked as dirty until other
1402          * buffers are written.
1403          */
1404         for (iter = pbusy = 0; iter < 20; iter++) {
1405                 nbusy = 0;
1406                 for (i = nbuf - 1; i >= 0; i--) {
1407                         bp = nbufp(i);
1408                         if (isbufbusy(bp))
1409                                 nbusy++;
1410                 }
1411                 if (nbusy == 0) {
1412                         if (first_buf_printf)
1413                                 printf("All buffers synced.");
1414                         break;
1415                 }
1416                 if (first_buf_printf) {
1417                         printf("Syncing disks, buffers remaining... ");
1418                         first_buf_printf = 0;
1419                 }
1420                 printf("%d ", nbusy);
1421                 if (nbusy < pbusy)
1422                         iter = 0;
1423                 pbusy = nbusy;
1424
1425                 wdog_kern_pat(WD_LASTVAL);
1426                 kern_sync(curthread);
1427
1428 #ifdef PREEMPTION
1429                 /*
1430                  * Spin for a while to allow interrupt threads to run.
1431                  */
1432                 DELAY(50000 * iter);
1433 #else
1434                 /*
1435                  * Context switch several times to allow interrupt
1436                  * threads to run.
1437                  */
1438                 for (subiter = 0; subiter < 50 * iter; subiter++) {
1439                         sched_relinquish(curthread);
1440                         DELAY(1000);
1441                 }
1442 #endif
1443         }
1444         printf("\n");
1445         /*
1446          * Count only busy local buffers to prevent forcing 
1447          * a fsck if we're just a client of a wedged NFS server
1448          */
1449         nbusy = 0;
1450         for (i = nbuf - 1; i >= 0; i--) {
1451                 bp = nbufp(i);
1452                 if (isbufbusy(bp)) {
1453 #if 0
1454 /* XXX: This is bogus.  We should probably have a BO_REMOTE flag instead */
1455                         if (bp->b_dev == NULL) {
1456                                 TAILQ_REMOVE(&mountlist,
1457                                     bp->b_vp->v_mount, mnt_list);
1458                                 continue;
1459                         }
1460 #endif
1461                         nbusy++;
1462                         if (show_busybufs > 0) {
1463                                 printf(
1464             "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1465                                     nbusy, bp, bp->b_vp, bp->b_flags,
1466                                     (intmax_t)bp->b_blkno,
1467                                     (intmax_t)bp->b_lblkno);
1468                                 BUF_LOCKPRINTINFO(bp);
1469                                 if (show_busybufs > 1)
1470                                         vn_printf(bp->b_vp,
1471                                             "vnode content: ");
1472                         }
1473                 }
1474         }
1475         if (nbusy) {
1476                 /*
1477                  * Failed to sync all blocks. Indicate this and don't
1478                  * unmount filesystems (thus forcing an fsck on reboot).
1479                  */
1480                 BOOTTRACE("shutdown failed to sync buffers");
1481                 printf("Giving up on %d buffers\n", nbusy);
1482                 DELAY(5000000); /* 5 seconds */
1483                 swapoff_all();
1484         } else {
1485                 BOOTTRACE("shutdown sync complete");
1486                 if (!first_buf_printf)
1487                         printf("Final sync complete\n");
1488
1489                 /*
1490                  * Unmount filesystems and perform swapoff, to quiesce
1491                  * the system as much as possible.  In particular, no
1492                  * I/O should be initiated from top levels since it
1493                  * might be abruptly terminated by reset, or otherwise
1494                  * erronously handled because other parts of the
1495                  * system are disabled.
1496                  *
1497                  * Swapoff before unmount, because file-backed swap is
1498                  * non-operational after unmount of the underlying
1499                  * filesystem.
1500                  */
1501                 if (!KERNEL_PANICKED()) {
1502                         swapoff_all();
1503                         vfs_unmountall();
1504                 }
1505                 BOOTTRACE("shutdown unmounted all filesystems");
1506         }
1507         DELAY(100000);          /* wait for console output to finish */
1508 }
1509
1510 static void
1511 bpmap_qenter(struct buf *bp)
1512 {
1513
1514         BUF_CHECK_MAPPED(bp);
1515
1516         /*
1517          * bp->b_data is relative to bp->b_offset, but
1518          * bp->b_offset may be offset into the first page.
1519          */
1520         bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1521         pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1522         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1523             (vm_offset_t)(bp->b_offset & PAGE_MASK));
1524 }
1525
1526 static inline struct bufdomain *
1527 bufdomain(struct buf *bp)
1528 {
1529
1530         return (&bdomain[bp->b_domain]);
1531 }
1532
1533 static struct bufqueue *
1534 bufqueue(struct buf *bp)
1535 {
1536
1537         switch (bp->b_qindex) {
1538         case QUEUE_NONE:
1539                 /* FALLTHROUGH */
1540         case QUEUE_SENTINEL:
1541                 return (NULL);
1542         case QUEUE_EMPTY:
1543                 return (&bqempty);
1544         case QUEUE_DIRTY:
1545                 return (&bufdomain(bp)->bd_dirtyq);
1546         case QUEUE_CLEAN:
1547                 return (&bufdomain(bp)->bd_subq[bp->b_subqueue]);
1548         default:
1549                 break;
1550         }
1551         panic("bufqueue(%p): Unhandled type %d\n", bp, bp->b_qindex);
1552 }
1553
1554 /*
1555  * Return the locked bufqueue that bp is a member of.
1556  */
1557 static struct bufqueue *
1558 bufqueue_acquire(struct buf *bp)
1559 {
1560         struct bufqueue *bq, *nbq;
1561
1562         /*
1563          * bp can be pushed from a per-cpu queue to the
1564          * cleanq while we're waiting on the lock.  Retry
1565          * if the queues don't match.
1566          */
1567         bq = bufqueue(bp);
1568         BQ_LOCK(bq);
1569         for (;;) {
1570                 nbq = bufqueue(bp);
1571                 if (bq == nbq)
1572                         break;
1573                 BQ_UNLOCK(bq);
1574                 BQ_LOCK(nbq);
1575                 bq = nbq;
1576         }
1577         return (bq);
1578 }
1579
1580 /*
1581  *      binsfree:
1582  *
1583  *      Insert the buffer into the appropriate free list.  Requires a
1584  *      locked buffer on entry and buffer is unlocked before return.
1585  */
1586 static void
1587 binsfree(struct buf *bp, int qindex)
1588 {
1589         struct bufdomain *bd;
1590         struct bufqueue *bq;
1591
1592         KASSERT(qindex == QUEUE_CLEAN || qindex == QUEUE_DIRTY,
1593             ("binsfree: Invalid qindex %d", qindex));
1594         BUF_ASSERT_XLOCKED(bp);
1595
1596         /*
1597          * Handle delayed bremfree() processing.
1598          */
1599         if (bp->b_flags & B_REMFREE) {
1600                 if (bp->b_qindex == qindex) {
1601                         bp->b_flags |= B_REUSE;
1602                         bp->b_flags &= ~B_REMFREE;
1603                         BUF_UNLOCK(bp);
1604                         return;
1605                 }
1606                 bq = bufqueue_acquire(bp);
1607                 bq_remove(bq, bp);
1608                 BQ_UNLOCK(bq);
1609         }
1610         bd = bufdomain(bp);
1611         if (qindex == QUEUE_CLEAN) {
1612                 if (bd->bd_lim != 0)
1613                         bq = &bd->bd_subq[PCPU_GET(cpuid)];
1614                 else
1615                         bq = bd->bd_cleanq;
1616         } else
1617                 bq = &bd->bd_dirtyq;
1618         bq_insert(bq, bp, true);
1619 }
1620
1621 /*
1622  * buf_free:
1623  *
1624  *      Free a buffer to the buf zone once it no longer has valid contents.
1625  */
1626 static void
1627 buf_free(struct buf *bp)
1628 {
1629
1630         if (bp->b_flags & B_REMFREE)
1631                 bremfreef(bp);
1632         if (bp->b_vflags & BV_BKGRDINPROG)
1633                 panic("losing buffer 1");
1634         if (bp->b_rcred != NOCRED) {
1635                 crfree(bp->b_rcred);
1636                 bp->b_rcred = NOCRED;
1637         }
1638         if (bp->b_wcred != NOCRED) {
1639                 crfree(bp->b_wcred);
1640                 bp->b_wcred = NOCRED;
1641         }
1642         if (!LIST_EMPTY(&bp->b_dep))
1643                 buf_deallocate(bp);
1644         bufkva_free(bp);
1645         atomic_add_int(&bufdomain(bp)->bd_freebuffers, 1);
1646         MPASS((bp->b_flags & B_MAXPHYS) == 0);
1647         BUF_UNLOCK(bp);
1648         uma_zfree(buf_zone, bp);
1649 }
1650
1651 /*
1652  * buf_import:
1653  *
1654  *      Import bufs into the uma cache from the buf list.  The system still
1655  *      expects a static array of bufs and much of the synchronization
1656  *      around bufs assumes type stable storage.  As a result, UMA is used
1657  *      only as a per-cpu cache of bufs still maintained on a global list.
1658  */
1659 static int
1660 buf_import(void *arg, void **store, int cnt, int domain, int flags)
1661 {
1662         struct buf *bp;
1663         int i;
1664
1665         BQ_LOCK(&bqempty);
1666         for (i = 0; i < cnt; i++) {
1667                 bp = TAILQ_FIRST(&bqempty.bq_queue);
1668                 if (bp == NULL)
1669                         break;
1670                 bq_remove(&bqempty, bp);
1671                 store[i] = bp;
1672         }
1673         BQ_UNLOCK(&bqempty);
1674
1675         return (i);
1676 }
1677
1678 /*
1679  * buf_release:
1680  *
1681  *      Release bufs from the uma cache back to the buffer queues.
1682  */
1683 static void
1684 buf_release(void *arg, void **store, int cnt)
1685 {
1686         struct bufqueue *bq;
1687         struct buf *bp;
1688         int i;
1689
1690         bq = &bqempty;
1691         BQ_LOCK(bq);
1692         for (i = 0; i < cnt; i++) {
1693                 bp = store[i];
1694                 /* Inline bq_insert() to batch locking. */
1695                 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1696                 bp->b_flags &= ~(B_AGE | B_REUSE);
1697                 bq->bq_len++;
1698                 bp->b_qindex = bq->bq_index;
1699         }
1700         BQ_UNLOCK(bq);
1701 }
1702
1703 /*
1704  * buf_alloc:
1705  *
1706  *      Allocate an empty buffer header.
1707  */
1708 static struct buf *
1709 buf_alloc(struct bufdomain *bd)
1710 {
1711         struct buf *bp;
1712         int freebufs, error;
1713
1714         /*
1715          * We can only run out of bufs in the buf zone if the average buf
1716          * is less than BKVASIZE.  In this case the actual wait/block will
1717          * come from buf_reycle() failing to flush one of these small bufs.
1718          */
1719         bp = NULL;
1720         freebufs = atomic_fetchadd_int(&bd->bd_freebuffers, -1);
1721         if (freebufs > 0)
1722                 bp = uma_zalloc(buf_zone, M_NOWAIT);
1723         if (bp == NULL) {
1724                 atomic_add_int(&bd->bd_freebuffers, 1);
1725                 bufspace_daemon_wakeup(bd);
1726                 counter_u64_add(numbufallocfails, 1);
1727                 return (NULL);
1728         }
1729         /*
1730          * Wake-up the bufspace daemon on transition below threshold.
1731          */
1732         if (freebufs == bd->bd_lofreebuffers)
1733                 bufspace_daemon_wakeup(bd);
1734
1735         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
1736         KASSERT(error == 0, ("%s: BUF_LOCK on free buf %p: %d.", __func__, bp,
1737             error));
1738         (void)error;
1739
1740         KASSERT(bp->b_vp == NULL,
1741             ("bp: %p still has vnode %p.", bp, bp->b_vp));
1742         KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1743             ("invalid buffer %p flags %#x", bp, bp->b_flags));
1744         KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1745             ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1746         KASSERT(bp->b_npages == 0,
1747             ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1748         KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1749         KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1750         MPASS((bp->b_flags & B_MAXPHYS) == 0);
1751
1752         bp->b_domain = BD_DOMAIN(bd);
1753         bp->b_flags = 0;
1754         bp->b_ioflags = 0;
1755         bp->b_xflags = 0;
1756         bp->b_vflags = 0;
1757         bp->b_vp = NULL;
1758         bp->b_blkno = bp->b_lblkno = 0;
1759         bp->b_offset = NOOFFSET;
1760         bp->b_iodone = 0;
1761         bp->b_error = 0;
1762         bp->b_resid = 0;
1763         bp->b_bcount = 0;
1764         bp->b_npages = 0;
1765         bp->b_dirtyoff = bp->b_dirtyend = 0;
1766         bp->b_bufobj = NULL;
1767         bp->b_data = bp->b_kvabase = unmapped_buf;
1768         bp->b_fsprivate1 = NULL;
1769         bp->b_fsprivate2 = NULL;
1770         bp->b_fsprivate3 = NULL;
1771         LIST_INIT(&bp->b_dep);
1772
1773         return (bp);
1774 }
1775
1776 /*
1777  *      buf_recycle:
1778  *
1779  *      Free a buffer from the given bufqueue.  kva controls whether the
1780  *      freed buf must own some kva resources.  This is used for
1781  *      defragmenting.
1782  */
1783 static int
1784 buf_recycle(struct bufdomain *bd, bool kva)
1785 {
1786         struct bufqueue *bq;
1787         struct buf *bp, *nbp;
1788
1789         if (kva)
1790                 counter_u64_add(bufdefragcnt, 1);
1791         nbp = NULL;
1792         bq = bd->bd_cleanq;
1793         BQ_LOCK(bq);
1794         KASSERT(BQ_LOCKPTR(bq) == BD_LOCKPTR(bd),
1795             ("buf_recycle: Locks don't match"));
1796         nbp = TAILQ_FIRST(&bq->bq_queue);
1797
1798         /*
1799          * Run scan, possibly freeing data and/or kva mappings on the fly
1800          * depending.
1801          */
1802         while ((bp = nbp) != NULL) {
1803                 /*
1804                  * Calculate next bp (we can only use it if we do not
1805                  * release the bqlock).
1806                  */
1807                 nbp = TAILQ_NEXT(bp, b_freelist);
1808
1809                 /*
1810                  * If we are defragging then we need a buffer with 
1811                  * some kva to reclaim.
1812                  */
1813                 if (kva && bp->b_kvasize == 0)
1814                         continue;
1815
1816                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1817                         continue;
1818
1819                 /*
1820                  * Implement a second chance algorithm for frequently
1821                  * accessed buffers.
1822                  */
1823                 if ((bp->b_flags & B_REUSE) != 0) {
1824                         TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1825                         TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1826                         bp->b_flags &= ~B_REUSE;
1827                         BUF_UNLOCK(bp);
1828                         continue;
1829                 }
1830
1831                 /*
1832                  * Skip buffers with background writes in progress.
1833                  */
1834                 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1835                         BUF_UNLOCK(bp);
1836                         continue;
1837                 }
1838
1839                 KASSERT(bp->b_qindex == QUEUE_CLEAN,
1840                     ("buf_recycle: inconsistent queue %d bp %p",
1841                     bp->b_qindex, bp));
1842                 KASSERT(bp->b_domain == BD_DOMAIN(bd),
1843                     ("getnewbuf: queue domain %d doesn't match request %d",
1844                     bp->b_domain, (int)BD_DOMAIN(bd)));
1845                 /*
1846                  * NOTE:  nbp is now entirely invalid.  We can only restart
1847                  * the scan from this point on.
1848                  */
1849                 bq_remove(bq, bp);
1850                 BQ_UNLOCK(bq);
1851
1852                 /*
1853                  * Requeue the background write buffer with error and
1854                  * restart the scan.
1855                  */
1856                 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1857                         bqrelse(bp);
1858                         BQ_LOCK(bq);
1859                         nbp = TAILQ_FIRST(&bq->bq_queue);
1860                         continue;
1861                 }
1862                 bp->b_flags |= B_INVAL;
1863                 brelse(bp);
1864                 return (0);
1865         }
1866         bd->bd_wanted = 1;
1867         BQ_UNLOCK(bq);
1868
1869         return (ENOBUFS);
1870 }
1871
1872 /*
1873  *      bremfree:
1874  *
1875  *      Mark the buffer for removal from the appropriate free list.
1876  *
1877  */
1878 void
1879 bremfree(struct buf *bp)
1880 {
1881
1882         CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1883         KASSERT((bp->b_flags & B_REMFREE) == 0,
1884             ("bremfree: buffer %p already marked for delayed removal.", bp));
1885         KASSERT(bp->b_qindex != QUEUE_NONE,
1886             ("bremfree: buffer %p not on a queue.", bp));
1887         BUF_ASSERT_XLOCKED(bp);
1888
1889         bp->b_flags |= B_REMFREE;
1890 }
1891
1892 /*
1893  *      bremfreef:
1894  *
1895  *      Force an immediate removal from a free list.  Used only in nfs when
1896  *      it abuses the b_freelist pointer.
1897  */
1898 void
1899 bremfreef(struct buf *bp)
1900 {
1901         struct bufqueue *bq;
1902
1903         bq = bufqueue_acquire(bp);
1904         bq_remove(bq, bp);
1905         BQ_UNLOCK(bq);
1906 }
1907
1908 static void
1909 bq_init(struct bufqueue *bq, int qindex, int subqueue, const char *lockname)
1910 {
1911
1912         mtx_init(&bq->bq_lock, lockname, NULL, MTX_DEF);
1913         TAILQ_INIT(&bq->bq_queue);
1914         bq->bq_len = 0;
1915         bq->bq_index = qindex;
1916         bq->bq_subqueue = subqueue;
1917 }
1918
1919 static void
1920 bd_init(struct bufdomain *bd)
1921 {
1922         int i;
1923
1924         /* Per-CPU clean buf queues, plus one global queue. */
1925         bd->bd_subq = mallocarray(mp_maxid + 2, sizeof(struct bufqueue),
1926             M_BIOBUF, M_WAITOK | M_ZERO);
1927         bd->bd_cleanq = &bd->bd_subq[mp_maxid + 1];
1928         bq_init(bd->bd_cleanq, QUEUE_CLEAN, mp_maxid + 1, "bufq clean lock");
1929         bq_init(&bd->bd_dirtyq, QUEUE_DIRTY, -1, "bufq dirty lock");
1930         for (i = 0; i <= mp_maxid; i++)
1931                 bq_init(&bd->bd_subq[i], QUEUE_CLEAN, i,
1932                     "bufq clean subqueue lock");
1933         mtx_init(&bd->bd_run_lock, "bufspace daemon run lock", NULL, MTX_DEF);
1934 }
1935
1936 /*
1937  *      bq_remove:
1938  *
1939  *      Removes a buffer from the free list, must be called with the
1940  *      correct qlock held.
1941  */
1942 static void
1943 bq_remove(struct bufqueue *bq, struct buf *bp)
1944 {
1945
1946         CTR3(KTR_BUF, "bq_remove(%p) vp %p flags %X",
1947             bp, bp->b_vp, bp->b_flags);
1948         KASSERT(bp->b_qindex != QUEUE_NONE,
1949             ("bq_remove: buffer %p not on a queue.", bp));
1950         KASSERT(bufqueue(bp) == bq,
1951             ("bq_remove: Remove buffer %p from wrong queue.", bp));
1952
1953         BQ_ASSERT_LOCKED(bq);
1954         if (bp->b_qindex != QUEUE_EMPTY) {
1955                 BUF_ASSERT_XLOCKED(bp);
1956         }
1957         KASSERT(bq->bq_len >= 1,
1958             ("queue %d underflow", bp->b_qindex));
1959         TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1960         bq->bq_len--;
1961         bp->b_qindex = QUEUE_NONE;
1962         bp->b_flags &= ~(B_REMFREE | B_REUSE);
1963 }
1964
1965 static void
1966 bd_flush(struct bufdomain *bd, struct bufqueue *bq)
1967 {
1968         struct buf *bp;
1969
1970         BQ_ASSERT_LOCKED(bq);
1971         if (bq != bd->bd_cleanq) {
1972                 BD_LOCK(bd);
1973                 while ((bp = TAILQ_FIRST(&bq->bq_queue)) != NULL) {
1974                         TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1975                         TAILQ_INSERT_TAIL(&bd->bd_cleanq->bq_queue, bp,
1976                             b_freelist);
1977                         bp->b_subqueue = bd->bd_cleanq->bq_subqueue;
1978                 }
1979                 bd->bd_cleanq->bq_len += bq->bq_len;
1980                 bq->bq_len = 0;
1981         }
1982         if (bd->bd_wanted) {
1983                 bd->bd_wanted = 0;
1984                 wakeup(&bd->bd_wanted);
1985         }
1986         if (bq != bd->bd_cleanq)
1987                 BD_UNLOCK(bd);
1988 }
1989
1990 static int
1991 bd_flushall(struct bufdomain *bd)
1992 {
1993         struct bufqueue *bq;
1994         int flushed;
1995         int i;
1996
1997         if (bd->bd_lim == 0)
1998                 return (0);
1999         flushed = 0;
2000         for (i = 0; i <= mp_maxid; i++) {
2001                 bq = &bd->bd_subq[i];
2002                 if (bq->bq_len == 0)
2003                         continue;
2004                 BQ_LOCK(bq);
2005                 bd_flush(bd, bq);
2006                 BQ_UNLOCK(bq);
2007                 flushed++;
2008         }
2009
2010         return (flushed);
2011 }
2012
2013 static void
2014 bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock)
2015 {
2016         struct bufdomain *bd;
2017
2018         if (bp->b_qindex != QUEUE_NONE)
2019                 panic("bq_insert: free buffer %p onto another queue?", bp);
2020
2021         bd = bufdomain(bp);
2022         if (bp->b_flags & B_AGE) {
2023                 /* Place this buf directly on the real queue. */
2024                 if (bq->bq_index == QUEUE_CLEAN)
2025                         bq = bd->bd_cleanq;
2026                 BQ_LOCK(bq);
2027                 TAILQ_INSERT_HEAD(&bq->bq_queue, bp, b_freelist);
2028         } else {
2029                 BQ_LOCK(bq);
2030                 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
2031         }
2032         bp->b_flags &= ~(B_AGE | B_REUSE);
2033         bq->bq_len++;
2034         bp->b_qindex = bq->bq_index;
2035         bp->b_subqueue = bq->bq_subqueue;
2036
2037         /*
2038          * Unlock before we notify so that we don't wakeup a waiter that
2039          * fails a trylock on the buf and sleeps again.
2040          */
2041         if (unlock)
2042                 BUF_UNLOCK(bp);
2043
2044         if (bp->b_qindex == QUEUE_CLEAN) {
2045                 /*
2046                  * Flush the per-cpu queue and notify any waiters.
2047                  */
2048                 if (bd->bd_wanted || (bq != bd->bd_cleanq &&
2049                     bq->bq_len >= bd->bd_lim))
2050                         bd_flush(bd, bq);
2051         }
2052         BQ_UNLOCK(bq);
2053 }
2054
2055 /*
2056  *      bufkva_free:
2057  *
2058  *      Free the kva allocation for a buffer.
2059  *
2060  */
2061 static void
2062 bufkva_free(struct buf *bp)
2063 {
2064
2065 #ifdef INVARIANTS
2066         if (bp->b_kvasize == 0) {
2067                 KASSERT(bp->b_kvabase == unmapped_buf &&
2068                     bp->b_data == unmapped_buf,
2069                     ("Leaked KVA space on %p", bp));
2070         } else if (buf_mapped(bp))
2071                 BUF_CHECK_MAPPED(bp);
2072         else
2073                 BUF_CHECK_UNMAPPED(bp);
2074 #endif
2075         if (bp->b_kvasize == 0)
2076                 return;
2077
2078         vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
2079         counter_u64_add(bufkvaspace, -bp->b_kvasize);
2080         counter_u64_add(buffreekvacnt, 1);
2081         bp->b_data = bp->b_kvabase = unmapped_buf;
2082         bp->b_kvasize = 0;
2083 }
2084
2085 /*
2086  *      bufkva_alloc:
2087  *
2088  *      Allocate the buffer KVA and set b_kvasize and b_kvabase.
2089  */
2090 static int
2091 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
2092 {
2093         vm_offset_t addr;
2094         int error;
2095
2096         KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
2097             ("Invalid gbflags 0x%x in %s", gbflags, __func__));
2098         MPASS((bp->b_flags & B_MAXPHYS) == 0);
2099         KASSERT(maxsize <= maxbcachebuf,
2100             ("bufkva_alloc kva too large %d %u", maxsize, maxbcachebuf));
2101
2102         bufkva_free(bp);
2103
2104         addr = 0;
2105         error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
2106         if (error != 0) {
2107                 /*
2108                  * Buffer map is too fragmented.  Request the caller
2109                  * to defragment the map.
2110                  */
2111                 return (error);
2112         }
2113         bp->b_kvabase = (caddr_t)addr;
2114         bp->b_kvasize = maxsize;
2115         counter_u64_add(bufkvaspace, bp->b_kvasize);
2116         if ((gbflags & GB_UNMAPPED) != 0) {
2117                 bp->b_data = unmapped_buf;
2118                 BUF_CHECK_UNMAPPED(bp);
2119         } else {
2120                 bp->b_data = bp->b_kvabase;
2121                 BUF_CHECK_MAPPED(bp);
2122         }
2123         return (0);
2124 }
2125
2126 /*
2127  *      bufkva_reclaim:
2128  *
2129  *      Reclaim buffer kva by freeing buffers holding kva.  This is a vmem
2130  *      callback that fires to avoid returning failure.
2131  */
2132 static void
2133 bufkva_reclaim(vmem_t *vmem, int flags)
2134 {
2135         bool done;
2136         int q;
2137         int i;
2138
2139         done = false;
2140         for (i = 0; i < 5; i++) {
2141                 for (q = 0; q < buf_domains; q++)
2142                         if (buf_recycle(&bdomain[q], true) != 0)
2143                                 done = true;
2144                 if (done)
2145                         break;
2146         }
2147         return;
2148 }
2149
2150 /*
2151  * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
2152  * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
2153  * the buffer is valid and we do not have to do anything.
2154  */
2155 static void
2156 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize, int cnt,
2157     struct ucred * cred, int flags, void (*ckhashfunc)(struct buf *))
2158 {
2159         struct buf *rabp;
2160         struct thread *td;
2161         int i;
2162
2163         td = curthread;
2164
2165         for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
2166                 if (inmem(vp, *rablkno))
2167                         continue;
2168                 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
2169                 if ((rabp->b_flags & B_CACHE) != 0) {
2170                         brelse(rabp);
2171                         continue;
2172                 }
2173 #ifdef RACCT
2174                 if (racct_enable) {
2175                         PROC_LOCK(curproc);
2176                         racct_add_buf(curproc, rabp, 0);
2177                         PROC_UNLOCK(curproc);
2178                 }
2179 #endif /* RACCT */
2180                 td->td_ru.ru_inblock++;
2181                 rabp->b_flags |= B_ASYNC;
2182                 rabp->b_flags &= ~B_INVAL;
2183                 if ((flags & GB_CKHASH) != 0) {
2184                         rabp->b_flags |= B_CKHASH;
2185                         rabp->b_ckhashcalc = ckhashfunc;
2186                 }
2187                 rabp->b_ioflags &= ~BIO_ERROR;
2188                 rabp->b_iocmd = BIO_READ;
2189                 if (rabp->b_rcred == NOCRED && cred != NOCRED)
2190                         rabp->b_rcred = crhold(cred);
2191                 vfs_busy_pages(rabp, 0);
2192                 BUF_KERNPROC(rabp);
2193                 rabp->b_iooffset = dbtob(rabp->b_blkno);
2194                 bstrategy(rabp);
2195         }
2196 }
2197
2198 /*
2199  * Entry point for bread() and breadn() via #defines in sys/buf.h.
2200  *
2201  * Get a buffer with the specified data.  Look in the cache first.  We
2202  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
2203  * is set, the buffer is valid and we do not have to do anything, see
2204  * getblk(). Also starts asynchronous I/O on read-ahead blocks.
2205  *
2206  * Always return a NULL buffer pointer (in bpp) when returning an error.
2207  *
2208  * The blkno parameter is the logical block being requested. Normally
2209  * the mapping of logical block number to disk block address is done
2210  * by calling VOP_BMAP(). However, if the mapping is already known, the
2211  * disk block address can be passed using the dblkno parameter. If the
2212  * disk block address is not known, then the same value should be passed
2213  * for blkno and dblkno.
2214  */
2215 int
2216 breadn_flags(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size,
2217     daddr_t *rablkno, int *rabsize, int cnt, struct ucred *cred, int flags,
2218     void (*ckhashfunc)(struct buf *), struct buf **bpp)
2219 {
2220         struct buf *bp;
2221         struct thread *td;
2222         int error, readwait, rv;
2223
2224         CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
2225         td = curthread;
2226         /*
2227          * Can only return NULL if GB_LOCK_NOWAIT or GB_SPARSE flags
2228          * are specified.
2229          */
2230         error = getblkx(vp, blkno, dblkno, size, 0, 0, flags, &bp);
2231         if (error != 0) {
2232                 *bpp = NULL;
2233                 return (error);
2234         }
2235         KASSERT(blkno == bp->b_lblkno,
2236             ("getblkx returned buffer for blkno %jd instead of blkno %jd",
2237             (intmax_t)bp->b_lblkno, (intmax_t)blkno));
2238         flags &= ~GB_NOSPARSE;
2239         *bpp = bp;
2240
2241         /*
2242          * If not found in cache, do some I/O
2243          */
2244         readwait = 0;
2245         if ((bp->b_flags & B_CACHE) == 0) {
2246 #ifdef RACCT
2247                 if (racct_enable) {
2248                         PROC_LOCK(td->td_proc);
2249                         racct_add_buf(td->td_proc, bp, 0);
2250                         PROC_UNLOCK(td->td_proc);
2251                 }
2252 #endif /* RACCT */
2253                 td->td_ru.ru_inblock++;
2254                 bp->b_iocmd = BIO_READ;
2255                 bp->b_flags &= ~B_INVAL;
2256                 if ((flags & GB_CKHASH) != 0) {
2257                         bp->b_flags |= B_CKHASH;
2258                         bp->b_ckhashcalc = ckhashfunc;
2259                 }
2260                 if ((flags & GB_CVTENXIO) != 0)
2261                         bp->b_xflags |= BX_CVTENXIO;
2262                 bp->b_ioflags &= ~BIO_ERROR;
2263                 if (bp->b_rcred == NOCRED && cred != NOCRED)
2264                         bp->b_rcred = crhold(cred);
2265                 vfs_busy_pages(bp, 0);
2266                 bp->b_iooffset = dbtob(bp->b_blkno);
2267                 bstrategy(bp);
2268                 ++readwait;
2269         }
2270
2271         /*
2272          * Attempt to initiate asynchronous I/O on read-ahead blocks.
2273          */
2274         breada(vp, rablkno, rabsize, cnt, cred, flags, ckhashfunc);
2275
2276         rv = 0;
2277         if (readwait) {
2278                 rv = bufwait(bp);
2279                 if (rv != 0) {
2280                         brelse(bp);
2281                         *bpp = NULL;
2282                 }
2283         }
2284         return (rv);
2285 }
2286
2287 /*
2288  * Write, release buffer on completion.  (Done by iodone
2289  * if async).  Do not bother writing anything if the buffer
2290  * is invalid.
2291  *
2292  * Note that we set B_CACHE here, indicating that buffer is
2293  * fully valid and thus cacheable.  This is true even of NFS
2294  * now so we set it generally.  This could be set either here 
2295  * or in biodone() since the I/O is synchronous.  We put it
2296  * here.
2297  */
2298 int
2299 bufwrite(struct buf *bp)
2300 {
2301         int oldflags;
2302         struct vnode *vp;
2303         long space;
2304         int vp_md;
2305
2306         CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2307         if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
2308                 bp->b_flags |= B_INVAL | B_RELBUF;
2309                 bp->b_flags &= ~B_CACHE;
2310                 brelse(bp);
2311                 return (ENXIO);
2312         }
2313         if (bp->b_flags & B_INVAL) {
2314                 brelse(bp);
2315                 return (0);
2316         }
2317
2318         if (bp->b_flags & B_BARRIER)
2319                 atomic_add_long(&barrierwrites, 1);
2320
2321         oldflags = bp->b_flags;
2322
2323         KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
2324             ("FFS background buffer should not get here %p", bp));
2325
2326         vp = bp->b_vp;
2327         if (vp)
2328                 vp_md = vp->v_vflag & VV_MD;
2329         else
2330                 vp_md = 0;
2331
2332         /*
2333          * Mark the buffer clean.  Increment the bufobj write count
2334          * before bundirty() call, to prevent other thread from seeing
2335          * empty dirty list and zero counter for writes in progress,
2336          * falsely indicating that the bufobj is clean.
2337          */
2338         bufobj_wref(bp->b_bufobj);
2339         bundirty(bp);
2340
2341         bp->b_flags &= ~B_DONE;
2342         bp->b_ioflags &= ~BIO_ERROR;
2343         bp->b_flags |= B_CACHE;
2344         bp->b_iocmd = BIO_WRITE;
2345
2346         vfs_busy_pages(bp, 1);
2347
2348         /*
2349          * Normal bwrites pipeline writes
2350          */
2351         bp->b_runningbufspace = bp->b_bufsize;
2352         space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
2353
2354 #ifdef RACCT
2355         if (racct_enable) {
2356                 PROC_LOCK(curproc);
2357                 racct_add_buf(curproc, bp, 1);
2358                 PROC_UNLOCK(curproc);
2359         }
2360 #endif /* RACCT */
2361         curthread->td_ru.ru_oublock++;
2362         if (oldflags & B_ASYNC)
2363                 BUF_KERNPROC(bp);
2364         bp->b_iooffset = dbtob(bp->b_blkno);
2365         buf_track(bp, __func__);
2366         bstrategy(bp);
2367
2368         if ((oldflags & B_ASYNC) == 0) {
2369                 int rtval = bufwait(bp);
2370                 brelse(bp);
2371                 return (rtval);
2372         } else if (space > hirunningspace) {
2373                 /*
2374                  * don't allow the async write to saturate the I/O
2375                  * system.  We will not deadlock here because
2376                  * we are blocking waiting for I/O that is already in-progress
2377                  * to complete. We do not block here if it is the update
2378                  * or syncer daemon trying to clean up as that can lead
2379                  * to deadlock.
2380                  */
2381                 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
2382                         waitrunningbufspace();
2383         }
2384
2385         return (0);
2386 }
2387
2388 void
2389 bufbdflush(struct bufobj *bo, struct buf *bp)
2390 {
2391         struct buf *nbp;
2392         struct bufdomain *bd;
2393
2394         bd = &bdomain[bo->bo_domain];
2395         if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh + 10) {
2396                 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2397                 altbufferflushes++;
2398         } else if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh) {
2399                 BO_LOCK(bo);
2400                 /*
2401                  * Try to find a buffer to flush.
2402                  */
2403                 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2404                         if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2405                             BUF_LOCK(nbp,
2406                                      LK_EXCLUSIVE | LK_NOWAIT, NULL))
2407                                 continue;
2408                         if (bp == nbp)
2409                                 panic("bdwrite: found ourselves");
2410                         BO_UNLOCK(bo);
2411                         /* Don't countdeps with the bo lock held. */
2412                         if (buf_countdeps(nbp, 0)) {
2413                                 BO_LOCK(bo);
2414                                 BUF_UNLOCK(nbp);
2415                                 continue;
2416                         }
2417                         if (nbp->b_flags & B_CLUSTEROK) {
2418                                 vfs_bio_awrite(nbp);
2419                         } else {
2420                                 bremfree(nbp);
2421                                 bawrite(nbp);
2422                         }
2423                         dirtybufferflushes++;
2424                         break;
2425                 }
2426                 if (nbp == NULL)
2427                         BO_UNLOCK(bo);
2428         }
2429 }
2430
2431 /*
2432  * Delayed write. (Buffer is marked dirty).  Do not bother writing
2433  * anything if the buffer is marked invalid.
2434  *
2435  * Note that since the buffer must be completely valid, we can safely
2436  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
2437  * biodone() in order to prevent getblk from writing the buffer
2438  * out synchronously.
2439  */
2440 void
2441 bdwrite(struct buf *bp)
2442 {
2443         struct thread *td = curthread;
2444         struct vnode *vp;
2445         struct bufobj *bo;
2446
2447         CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2448         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2449         KASSERT((bp->b_flags & B_BARRIER) == 0,
2450             ("Barrier request in delayed write %p", bp));
2451
2452         if (bp->b_flags & B_INVAL) {
2453                 brelse(bp);
2454                 return;
2455         }
2456
2457         /*
2458          * If we have too many dirty buffers, don't create any more.
2459          * If we are wildly over our limit, then force a complete
2460          * cleanup. Otherwise, just keep the situation from getting
2461          * out of control. Note that we have to avoid a recursive
2462          * disaster and not try to clean up after our own cleanup!
2463          */
2464         vp = bp->b_vp;
2465         bo = bp->b_bufobj;
2466         if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2467                 td->td_pflags |= TDP_INBDFLUSH;
2468                 BO_BDFLUSH(bo, bp);
2469                 td->td_pflags &= ~TDP_INBDFLUSH;
2470         } else
2471                 recursiveflushes++;
2472
2473         bdirty(bp);
2474         /*
2475          * Set B_CACHE, indicating that the buffer is fully valid.  This is
2476          * true even of NFS now.
2477          */
2478         bp->b_flags |= B_CACHE;
2479
2480         /*
2481          * This bmap keeps the system from needing to do the bmap later,
2482          * perhaps when the system is attempting to do a sync.  Since it
2483          * is likely that the indirect block -- or whatever other datastructure
2484          * that the filesystem needs is still in memory now, it is a good
2485          * thing to do this.  Note also, that if the pageout daemon is
2486          * requesting a sync -- there might not be enough memory to do
2487          * the bmap then...  So, this is important to do.
2488          */
2489         if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2490                 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2491         }
2492
2493         buf_track(bp, __func__);
2494
2495         /*
2496          * Set the *dirty* buffer range based upon the VM system dirty
2497          * pages.
2498          *
2499          * Mark the buffer pages as clean.  We need to do this here to
2500          * satisfy the vnode_pager and the pageout daemon, so that it
2501          * thinks that the pages have been "cleaned".  Note that since
2502          * the pages are in a delayed write buffer -- the VFS layer
2503          * "will" see that the pages get written out on the next sync,
2504          * or perhaps the cluster will be completed.
2505          */
2506         vfs_clean_pages_dirty_buf(bp);
2507         bqrelse(bp);
2508
2509         /*
2510          * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2511          * due to the softdep code.
2512          */
2513 }
2514
2515 /*
2516  *      bdirty:
2517  *
2518  *      Turn buffer into delayed write request.  We must clear BIO_READ and
2519  *      B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to 
2520  *      itself to properly update it in the dirty/clean lists.  We mark it
2521  *      B_DONE to ensure that any asynchronization of the buffer properly
2522  *      clears B_DONE ( else a panic will occur later ).  
2523  *
2524  *      bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2525  *      might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
2526  *      should only be called if the buffer is known-good.
2527  *
2528  *      Since the buffer is not on a queue, we do not update the numfreebuffers
2529  *      count.
2530  *
2531  *      The buffer must be on QUEUE_NONE.
2532  */
2533 void
2534 bdirty(struct buf *bp)
2535 {
2536
2537         CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2538             bp, bp->b_vp, bp->b_flags);
2539         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2540         KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2541             ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2542         bp->b_flags &= ~(B_RELBUF);
2543         bp->b_iocmd = BIO_WRITE;
2544
2545         if ((bp->b_flags & B_DELWRI) == 0) {
2546                 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2547                 reassignbuf(bp);
2548                 bdirtyadd(bp);
2549         }
2550 }
2551
2552 /*
2553  *      bundirty:
2554  *
2555  *      Clear B_DELWRI for buffer.
2556  *
2557  *      Since the buffer is not on a queue, we do not update the numfreebuffers
2558  *      count.
2559  *
2560  *      The buffer must be on QUEUE_NONE.
2561  */
2562
2563 void
2564 bundirty(struct buf *bp)
2565 {
2566
2567         CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2568         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2569         KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2570             ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2571
2572         if (bp->b_flags & B_DELWRI) {
2573                 bp->b_flags &= ~B_DELWRI;
2574                 reassignbuf(bp);
2575                 bdirtysub(bp);
2576         }
2577         /*
2578          * Since it is now being written, we can clear its deferred write flag.
2579          */
2580         bp->b_flags &= ~B_DEFERRED;
2581 }
2582
2583 /*
2584  *      bawrite:
2585  *
2586  *      Asynchronous write.  Start output on a buffer, but do not wait for
2587  *      it to complete.  The buffer is released when the output completes.
2588  *
2589  *      bwrite() ( or the VOP routine anyway ) is responsible for handling 
2590  *      B_INVAL buffers.  Not us.
2591  */
2592 void
2593 bawrite(struct buf *bp)
2594 {
2595
2596         bp->b_flags |= B_ASYNC;
2597         (void) bwrite(bp);
2598 }
2599
2600 /*
2601  *      babarrierwrite:
2602  *
2603  *      Asynchronous barrier write.  Start output on a buffer, but do not
2604  *      wait for it to complete.  Place a write barrier after this write so
2605  *      that this buffer and all buffers written before it are committed to
2606  *      the disk before any buffers written after this write are committed
2607  *      to the disk.  The buffer is released when the output completes.
2608  */
2609 void
2610 babarrierwrite(struct buf *bp)
2611 {
2612
2613         bp->b_flags |= B_ASYNC | B_BARRIER;
2614         (void) bwrite(bp);
2615 }
2616
2617 /*
2618  *      bbarrierwrite:
2619  *
2620  *      Synchronous barrier write.  Start output on a buffer and wait for
2621  *      it to complete.  Place a write barrier after this write so that
2622  *      this buffer and all buffers written before it are committed to 
2623  *      the disk before any buffers written after this write are committed
2624  *      to the disk.  The buffer is released when the output completes.
2625  */
2626 int
2627 bbarrierwrite(struct buf *bp)
2628 {
2629
2630         bp->b_flags |= B_BARRIER;
2631         return (bwrite(bp));
2632 }
2633
2634 /*
2635  *      bwillwrite:
2636  *
2637  *      Called prior to the locking of any vnodes when we are expecting to
2638  *      write.  We do not want to starve the buffer cache with too many
2639  *      dirty buffers so we block here.  By blocking prior to the locking
2640  *      of any vnodes we attempt to avoid the situation where a locked vnode
2641  *      prevents the various system daemons from flushing related buffers.
2642  */
2643 void
2644 bwillwrite(void)
2645 {
2646
2647         if (buf_dirty_count_severe()) {
2648                 mtx_lock(&bdirtylock);
2649                 while (buf_dirty_count_severe()) {
2650                         bdirtywait = 1;
2651                         msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2652                             "flswai", 0);
2653                 }
2654                 mtx_unlock(&bdirtylock);
2655         }
2656 }
2657
2658 /*
2659  * Return true if we have too many dirty buffers.
2660  */
2661 int
2662 buf_dirty_count_severe(void)
2663 {
2664
2665         return (!BIT_EMPTY(BUF_DOMAINS, &bdhidirty));
2666 }
2667
2668 /*
2669  *      brelse:
2670  *
2671  *      Release a busy buffer and, if requested, free its resources.  The
2672  *      buffer will be stashed in the appropriate bufqueue[] allowing it
2673  *      to be accessed later as a cache entity or reused for other purposes.
2674  */
2675 void
2676 brelse(struct buf *bp)
2677 {
2678         struct mount *v_mnt;
2679         int qindex;
2680
2681         /*
2682          * Many functions erroneously call brelse with a NULL bp under rare
2683          * error conditions. Simply return when called with a NULL bp.
2684          */
2685         if (bp == NULL)
2686                 return;
2687         CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2688             bp, bp->b_vp, bp->b_flags);
2689         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2690             ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2691         KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2692             ("brelse: non-VMIO buffer marked NOREUSE"));
2693
2694         if (BUF_LOCKRECURSED(bp)) {
2695                 /*
2696                  * Do not process, in particular, do not handle the
2697                  * B_INVAL/B_RELBUF and do not release to free list.
2698                  */
2699                 BUF_UNLOCK(bp);
2700                 return;
2701         }
2702
2703         if (bp->b_flags & B_MANAGED) {
2704                 bqrelse(bp);
2705                 return;
2706         }
2707
2708         if (LIST_EMPTY(&bp->b_dep)) {
2709                 bp->b_flags &= ~B_IOSTARTED;
2710         } else {
2711                 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2712                     ("brelse: SU io not finished bp %p", bp));
2713         }
2714
2715         if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2716                 BO_LOCK(bp->b_bufobj);
2717                 bp->b_vflags &= ~BV_BKGRDERR;
2718                 BO_UNLOCK(bp->b_bufobj);
2719                 bdirty(bp);
2720         }
2721
2722         if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2723             (bp->b_flags & B_INVALONERR)) {
2724                 /*
2725                  * Forced invalidation of dirty buffer contents, to be used
2726                  * after a failed write in the rare case that the loss of the
2727                  * contents is acceptable.  The buffer is invalidated and
2728                  * freed.
2729                  */
2730                 bp->b_flags |= B_INVAL | B_RELBUF | B_NOCACHE;
2731                 bp->b_flags &= ~(B_ASYNC | B_CACHE);
2732         }
2733
2734         if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2735             (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2736             !(bp->b_flags & B_INVAL)) {
2737                 /*
2738                  * Failed write, redirty.  All errors except ENXIO (which
2739                  * means the device is gone) are treated as being
2740                  * transient.
2741                  *
2742                  * XXX Treating EIO as transient is not correct; the
2743                  * contract with the local storage device drivers is that
2744                  * they will only return EIO once the I/O is no longer
2745                  * retriable.  Network I/O also respects this through the
2746                  * guarantees of TCP and/or the internal retries of NFS.
2747                  * ENOMEM might be transient, but we also have no way of
2748                  * knowing when its ok to retry/reschedule.  In general,
2749                  * this entire case should be made obsolete through better
2750                  * error handling/recovery and resource scheduling.
2751                  *
2752                  * Do this also for buffers that failed with ENXIO, but have
2753                  * non-empty dependencies - the soft updates code might need
2754                  * to access the buffer to untangle them.
2755                  *
2756                  * Must clear BIO_ERROR to prevent pages from being scrapped.
2757                  */
2758                 bp->b_ioflags &= ~BIO_ERROR;
2759                 bdirty(bp);
2760         } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2761             (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2762                 /*
2763                  * Either a failed read I/O, or we were asked to free or not
2764                  * cache the buffer, or we failed to write to a device that's
2765                  * no longer present.
2766                  */
2767                 bp->b_flags |= B_INVAL;
2768                 if (!LIST_EMPTY(&bp->b_dep))
2769                         buf_deallocate(bp);
2770                 if (bp->b_flags & B_DELWRI)
2771                         bdirtysub(bp);
2772                 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2773                 if ((bp->b_flags & B_VMIO) == 0) {
2774                         allocbuf(bp, 0);
2775                         if (bp->b_vp)
2776                                 brelvp(bp);
2777                 }
2778         }
2779
2780         /*
2781          * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_truncate() 
2782          * is called with B_DELWRI set, the underlying pages may wind up
2783          * getting freed causing a previous write (bdwrite()) to get 'lost'
2784          * because pages associated with a B_DELWRI bp are marked clean.
2785          * 
2786          * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2787          * if B_DELWRI is set.
2788          */
2789         if (bp->b_flags & B_DELWRI)
2790                 bp->b_flags &= ~B_RELBUF;
2791
2792         /*
2793          * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
2794          * constituted, not even NFS buffers now.  Two flags effect this.  If
2795          * B_INVAL, the struct buf is invalidated but the VM object is kept
2796          * around ( i.e. so it is trivial to reconstitute the buffer later ).
2797          *
2798          * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2799          * invalidated.  BIO_ERROR cannot be set for a failed write unless the
2800          * buffer is also B_INVAL because it hits the re-dirtying code above.
2801          *
2802          * Normally we can do this whether a buffer is B_DELWRI or not.  If
2803          * the buffer is an NFS buffer, it is tracking piecemeal writes or
2804          * the commit state and we cannot afford to lose the buffer. If the
2805          * buffer has a background write in progress, we need to keep it
2806          * around to prevent it from being reconstituted and starting a second
2807          * background write.
2808          */
2809
2810         v_mnt = bp->b_vp != NULL ? bp->b_vp->v_mount : NULL;
2811
2812         if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2813             (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2814             (v_mnt == NULL || (v_mnt->mnt_vfc->vfc_flags & VFCF_NETWORK) == 0 ||
2815             vn_isdisk(bp->b_vp) || (bp->b_flags & B_DELWRI) == 0)) {
2816                 vfs_vmio_invalidate(bp);
2817                 allocbuf(bp, 0);
2818         }
2819
2820         if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2821             (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2822                 allocbuf(bp, 0);
2823                 bp->b_flags &= ~B_NOREUSE;
2824                 if (bp->b_vp != NULL)
2825                         brelvp(bp);
2826         }
2827
2828         /*
2829          * If the buffer has junk contents signal it and eventually
2830          * clean up B_DELWRI and diassociate the vnode so that gbincore()
2831          * doesn't find it.
2832          */
2833         if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2834             (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2835                 bp->b_flags |= B_INVAL;
2836         if (bp->b_flags & B_INVAL) {
2837                 if (bp->b_flags & B_DELWRI)
2838                         bundirty(bp);
2839                 if (bp->b_vp)
2840                         brelvp(bp);
2841         }
2842
2843         buf_track(bp, __func__);
2844
2845         /* buffers with no memory */
2846         if (bp->b_bufsize == 0) {
2847                 buf_free(bp);
2848                 return;
2849         }
2850         /* buffers with junk contents */
2851         if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2852             (bp->b_ioflags & BIO_ERROR)) {
2853                 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2854                 if (bp->b_vflags & BV_BKGRDINPROG)
2855                         panic("losing buffer 2");
2856                 qindex = QUEUE_CLEAN;
2857                 bp->b_flags |= B_AGE;
2858         /* remaining buffers */
2859         } else if (bp->b_flags & B_DELWRI)
2860                 qindex = QUEUE_DIRTY;
2861         else
2862                 qindex = QUEUE_CLEAN;
2863
2864         if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2865                 panic("brelse: not dirty");
2866
2867         bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
2868         bp->b_xflags &= ~(BX_CVTENXIO);
2869         /* binsfree unlocks bp. */
2870         binsfree(bp, qindex);
2871 }
2872
2873 /*
2874  * Release a buffer back to the appropriate queue but do not try to free
2875  * it.  The buffer is expected to be used again soon.
2876  *
2877  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2878  * biodone() to requeue an async I/O on completion.  It is also used when
2879  * known good buffers need to be requeued but we think we may need the data
2880  * again soon.
2881  *
2882  * XXX we should be able to leave the B_RELBUF hint set on completion.
2883  */
2884 void
2885 bqrelse(struct buf *bp)
2886 {
2887         int qindex;
2888
2889         CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2890         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2891             ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2892
2893         qindex = QUEUE_NONE;
2894         if (BUF_LOCKRECURSED(bp)) {
2895                 /* do not release to free list */
2896                 BUF_UNLOCK(bp);
2897                 return;
2898         }
2899         bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2900         bp->b_xflags &= ~(BX_CVTENXIO);
2901
2902         if (LIST_EMPTY(&bp->b_dep)) {
2903                 bp->b_flags &= ~B_IOSTARTED;
2904         } else {
2905                 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2906                     ("bqrelse: SU io not finished bp %p", bp));
2907         }
2908
2909         if (bp->b_flags & B_MANAGED) {
2910                 if (bp->b_flags & B_REMFREE)
2911                         bremfreef(bp);
2912                 goto out;
2913         }
2914
2915         /* buffers with stale but valid contents */
2916         if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2917             BV_BKGRDERR)) == BV_BKGRDERR) {
2918                 BO_LOCK(bp->b_bufobj);
2919                 bp->b_vflags &= ~BV_BKGRDERR;
2920                 BO_UNLOCK(bp->b_bufobj);
2921                 qindex = QUEUE_DIRTY;
2922         } else {
2923                 if ((bp->b_flags & B_DELWRI) == 0 &&
2924                     (bp->b_xflags & BX_VNDIRTY))
2925                         panic("bqrelse: not dirty");
2926                 if ((bp->b_flags & B_NOREUSE) != 0) {
2927                         brelse(bp);
2928                         return;
2929                 }
2930                 qindex = QUEUE_CLEAN;
2931         }
2932         buf_track(bp, __func__);
2933         /* binsfree unlocks bp. */
2934         binsfree(bp, qindex);
2935         return;
2936
2937 out:
2938         buf_track(bp, __func__);
2939         /* unlock */
2940         BUF_UNLOCK(bp);
2941 }
2942
2943 /*
2944  * Complete I/O to a VMIO backed page.  Validate the pages as appropriate,
2945  * restore bogus pages.
2946  */
2947 static void
2948 vfs_vmio_iodone(struct buf *bp)
2949 {
2950         vm_ooffset_t foff;
2951         vm_page_t m;
2952         vm_object_t obj;
2953         struct vnode *vp __unused;
2954         int i, iosize, resid;
2955         bool bogus;
2956
2957         obj = bp->b_bufobj->bo_object;
2958         KASSERT(blockcount_read(&obj->paging_in_progress) >= bp->b_npages,
2959             ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2960             blockcount_read(&obj->paging_in_progress), bp->b_npages));
2961
2962         vp = bp->b_vp;
2963         VNPASS(vp->v_holdcnt > 0, vp);
2964         VNPASS(vp->v_object != NULL, vp);
2965
2966         foff = bp->b_offset;
2967         KASSERT(bp->b_offset != NOOFFSET,
2968             ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2969
2970         bogus = false;
2971         iosize = bp->b_bcount - bp->b_resid;
2972         for (i = 0; i < bp->b_npages; i++) {
2973                 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2974                 if (resid > iosize)
2975                         resid = iosize;
2976
2977                 /*
2978                  * cleanup bogus pages, restoring the originals
2979                  */
2980                 m = bp->b_pages[i];
2981                 if (m == bogus_page) {
2982                         bogus = true;
2983                         m = vm_page_relookup(obj, OFF_TO_IDX(foff));
2984                         if (m == NULL)
2985                                 panic("biodone: page disappeared!");
2986                         bp->b_pages[i] = m;
2987                 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2988                         /*
2989                          * In the write case, the valid and clean bits are
2990                          * already changed correctly ( see bdwrite() ), so we 
2991                          * only need to do this here in the read case.
2992                          */
2993                         KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2994                             resid)) == 0, ("vfs_vmio_iodone: page %p "
2995                             "has unexpected dirty bits", m));
2996                         vfs_page_set_valid(bp, foff, m);
2997                 }
2998                 KASSERT(OFF_TO_IDX(foff) == m->pindex,
2999                     ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
3000                     (intmax_t)foff, (uintmax_t)m->pindex));
3001
3002                 vm_page_sunbusy(m);
3003                 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3004                 iosize -= resid;
3005         }
3006         vm_object_pip_wakeupn(obj, bp->b_npages);
3007         if (bogus && buf_mapped(bp)) {
3008                 BUF_CHECK_MAPPED(bp);
3009                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3010                     bp->b_pages, bp->b_npages);
3011         }
3012 }
3013
3014 /*
3015  * Perform page invalidation when a buffer is released.  The fully invalid
3016  * pages will be reclaimed later in vfs_vmio_truncate().
3017  */
3018 static void
3019 vfs_vmio_invalidate(struct buf *bp)
3020 {
3021         vm_object_t obj;
3022         vm_page_t m;
3023         int flags, i, resid, poffset, presid;
3024
3025         if (buf_mapped(bp)) {
3026                 BUF_CHECK_MAPPED(bp);
3027                 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
3028         } else
3029                 BUF_CHECK_UNMAPPED(bp);
3030         /*
3031          * Get the base offset and length of the buffer.  Note that 
3032          * in the VMIO case if the buffer block size is not
3033          * page-aligned then b_data pointer may not be page-aligned.
3034          * But our b_pages[] array *IS* page aligned.
3035          *
3036          * block sizes less then DEV_BSIZE (usually 512) are not 
3037          * supported due to the page granularity bits (m->valid,
3038          * m->dirty, etc...). 
3039          *
3040          * See man buf(9) for more information
3041          */
3042         flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3043         obj = bp->b_bufobj->bo_object;
3044         resid = bp->b_bufsize;
3045         poffset = bp->b_offset & PAGE_MASK;
3046         VM_OBJECT_WLOCK(obj);
3047         for (i = 0; i < bp->b_npages; i++) {
3048                 m = bp->b_pages[i];
3049                 if (m == bogus_page)
3050                         panic("vfs_vmio_invalidate: Unexpected bogus page.");
3051                 bp->b_pages[i] = NULL;
3052
3053                 presid = resid > (PAGE_SIZE - poffset) ?
3054                     (PAGE_SIZE - poffset) : resid;
3055                 KASSERT(presid >= 0, ("brelse: extra page"));
3056                 vm_page_busy_acquire(m, VM_ALLOC_SBUSY);
3057                 if (pmap_page_wired_mappings(m) == 0)
3058                         vm_page_set_invalid(m, poffset, presid);
3059                 vm_page_sunbusy(m);
3060                 vm_page_release_locked(m, flags);
3061                 resid -= presid;
3062                 poffset = 0;
3063         }
3064         VM_OBJECT_WUNLOCK(obj);
3065         bp->b_npages = 0;
3066 }
3067
3068 /*
3069  * Page-granular truncation of an existing VMIO buffer.
3070  */
3071 static void
3072 vfs_vmio_truncate(struct buf *bp, int desiredpages)
3073 {
3074         vm_object_t obj;
3075         vm_page_t m;
3076         int flags, i;
3077
3078         if (bp->b_npages == desiredpages)
3079                 return;
3080
3081         if (buf_mapped(bp)) {
3082                 BUF_CHECK_MAPPED(bp);
3083                 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
3084                     (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
3085         } else
3086                 BUF_CHECK_UNMAPPED(bp);
3087
3088         /*
3089          * The object lock is needed only if we will attempt to free pages.
3090          */
3091         flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3092         if ((bp->b_flags & B_DIRECT) != 0) {
3093                 flags |= VPR_TRYFREE;
3094                 obj = bp->b_bufobj->bo_object;
3095                 VM_OBJECT_WLOCK(obj);
3096         } else {
3097                 obj = NULL;
3098         }
3099         for (i = desiredpages; i < bp->b_npages; i++) {
3100                 m = bp->b_pages[i];
3101                 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
3102                 bp->b_pages[i] = NULL;
3103                 if (obj != NULL)
3104                         vm_page_release_locked(m, flags);
3105                 else
3106                         vm_page_release(m, flags);
3107         }
3108         if (obj != NULL)
3109                 VM_OBJECT_WUNLOCK(obj);
3110         bp->b_npages = desiredpages;
3111 }
3112
3113 /*
3114  * Byte granular extension of VMIO buffers.
3115  */
3116 static void
3117 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
3118 {
3119         /*
3120          * We are growing the buffer, possibly in a 
3121          * byte-granular fashion.
3122          */
3123         vm_object_t obj;
3124         vm_offset_t toff;
3125         vm_offset_t tinc;
3126         vm_page_t m;
3127
3128         /*
3129          * Step 1, bring in the VM pages from the object, allocating
3130          * them if necessary.  We must clear B_CACHE if these pages
3131          * are not valid for the range covered by the buffer.
3132          */
3133         obj = bp->b_bufobj->bo_object;
3134         if (bp->b_npages < desiredpages) {
3135                 KASSERT(desiredpages <= atop(maxbcachebuf),
3136                     ("vfs_vmio_extend past maxbcachebuf %p %d %u",
3137                     bp, desiredpages, maxbcachebuf));
3138
3139                 /*
3140                  * We must allocate system pages since blocking
3141                  * here could interfere with paging I/O, no
3142                  * matter which process we are.
3143                  *
3144                  * Only exclusive busy can be tested here.
3145                  * Blocking on shared busy might lead to
3146                  * deadlocks once allocbuf() is called after
3147                  * pages are vfs_busy_pages().
3148                  */
3149                 (void)vm_page_grab_pages_unlocked(obj,
3150                     OFF_TO_IDX(bp->b_offset) + bp->b_npages,
3151                     VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
3152                     VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
3153                     &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
3154                 bp->b_npages = desiredpages;
3155         }
3156
3157         /*
3158          * Step 2.  We've loaded the pages into the buffer,
3159          * we have to figure out if we can still have B_CACHE
3160          * set.  Note that B_CACHE is set according to the
3161          * byte-granular range ( bcount and size ), not the
3162          * aligned range ( newbsize ).
3163          *
3164          * The VM test is against m->valid, which is DEV_BSIZE
3165          * aligned.  Needless to say, the validity of the data
3166          * needs to also be DEV_BSIZE aligned.  Note that this
3167          * fails with NFS if the server or some other client
3168          * extends the file's EOF.  If our buffer is resized, 
3169          * B_CACHE may remain set! XXX
3170          */
3171         toff = bp->b_bcount;
3172         tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3173         while ((bp->b_flags & B_CACHE) && toff < size) {
3174                 vm_pindex_t pi;
3175
3176                 if (tinc > (size - toff))
3177                         tinc = size - toff;
3178                 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
3179                 m = bp->b_pages[pi];
3180                 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
3181                 toff += tinc;
3182                 tinc = PAGE_SIZE;
3183         }
3184
3185         /*
3186          * Step 3, fixup the KVA pmap.
3187          */
3188         if (buf_mapped(bp))
3189                 bpmap_qenter(bp);
3190         else
3191                 BUF_CHECK_UNMAPPED(bp);
3192 }
3193
3194 /*
3195  * Check to see if a block at a particular lbn is available for a clustered
3196  * write.
3197  */
3198 static int
3199 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
3200 {
3201         struct buf *bpa;
3202         int match;
3203
3204         match = 0;
3205
3206         /* If the buf isn't in core skip it */
3207         if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
3208                 return (0);
3209
3210         /* If the buf is busy we don't want to wait for it */
3211         if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
3212                 return (0);
3213
3214         /* Only cluster with valid clusterable delayed write buffers */
3215         if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
3216             (B_DELWRI | B_CLUSTEROK))
3217                 goto done;
3218
3219         if (bpa->b_bufsize != size)
3220                 goto done;
3221
3222         /*
3223          * Check to see if it is in the expected place on disk and that the
3224          * block has been mapped.
3225          */
3226         if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
3227                 match = 1;
3228 done:
3229         BUF_UNLOCK(bpa);
3230         return (match);
3231 }
3232
3233 /*
3234  *      vfs_bio_awrite:
3235  *
3236  *      Implement clustered async writes for clearing out B_DELWRI buffers.
3237  *      This is much better then the old way of writing only one buffer at
3238  *      a time.  Note that we may not be presented with the buffers in the 
3239  *      correct order, so we search for the cluster in both directions.
3240  */
3241 int
3242 vfs_bio_awrite(struct buf *bp)
3243 {
3244         struct bufobj *bo;
3245         int i;
3246         int j;
3247         daddr_t lblkno = bp->b_lblkno;
3248         struct vnode *vp = bp->b_vp;
3249         int ncl;
3250         int nwritten;
3251         int size;
3252         int maxcl;
3253         int gbflags;
3254
3255         bo = &vp->v_bufobj;
3256         gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
3257         /*
3258          * right now we support clustered writing only to regular files.  If
3259          * we find a clusterable block we could be in the middle of a cluster
3260          * rather then at the beginning.
3261          */
3262         if ((vp->v_type == VREG) && 
3263             (vp->v_mount != 0) && /* Only on nodes that have the size info */
3264             (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
3265                 size = vp->v_mount->mnt_stat.f_iosize;
3266                 maxcl = maxphys / size;
3267
3268                 BO_RLOCK(bo);
3269                 for (i = 1; i < maxcl; i++)
3270                         if (vfs_bio_clcheck(vp, size, lblkno + i,
3271                             bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
3272                                 break;
3273
3274                 for (j = 1; i + j <= maxcl && j <= lblkno; j++) 
3275                         if (vfs_bio_clcheck(vp, size, lblkno - j,
3276                             bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
3277                                 break;
3278                 BO_RUNLOCK(bo);
3279                 --j;
3280                 ncl = i + j;
3281                 /*
3282                  * this is a possible cluster write
3283                  */
3284                 if (ncl != 1) {
3285                         BUF_UNLOCK(bp);
3286                         nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
3287                             gbflags);
3288                         return (nwritten);
3289                 }
3290         }
3291         bremfree(bp);
3292         bp->b_flags |= B_ASYNC;
3293         /*
3294          * default (old) behavior, writing out only one block
3295          *
3296          * XXX returns b_bufsize instead of b_bcount for nwritten?
3297          */
3298         nwritten = bp->b_bufsize;
3299         (void) bwrite(bp);
3300
3301         return (nwritten);
3302 }
3303
3304 /*
3305  *      getnewbuf_kva:
3306  *
3307  *      Allocate KVA for an empty buf header according to gbflags.
3308  */
3309 static int
3310 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
3311 {
3312
3313         if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
3314                 /*
3315                  * In order to keep fragmentation sane we only allocate kva
3316                  * in BKVASIZE chunks.  XXX with vmem we can do page size.
3317                  */
3318                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
3319
3320                 if (maxsize != bp->b_kvasize &&
3321                     bufkva_alloc(bp, maxsize, gbflags))
3322                         return (ENOSPC);
3323         }
3324         return (0);
3325 }
3326
3327 /*
3328  *      getnewbuf:
3329  *
3330  *      Find and initialize a new buffer header, freeing up existing buffers
3331  *      in the bufqueues as necessary.  The new buffer is returned locked.
3332  *
3333  *      We block if:
3334  *              We have insufficient buffer headers
3335  *              We have insufficient buffer space
3336  *              buffer_arena is too fragmented ( space reservation fails )
3337  *              If we have to flush dirty buffers ( but we try to avoid this )
3338  *
3339  *      The caller is responsible for releasing the reserved bufspace after
3340  *      allocbuf() is called.
3341  */
3342 static struct buf *
3343 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
3344 {
3345         struct bufdomain *bd;
3346         struct buf *bp;
3347         bool metadata, reserved;
3348
3349         bp = NULL;
3350         KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3351             ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3352         if (!unmapped_buf_allowed)
3353                 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3354
3355         if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
3356             vp->v_type == VCHR)
3357                 metadata = true;
3358         else
3359                 metadata = false;
3360         if (vp == NULL)
3361                 bd = &bdomain[0];
3362         else
3363                 bd = &bdomain[vp->v_bufobj.bo_domain];
3364
3365         counter_u64_add(getnewbufcalls, 1);
3366         reserved = false;
3367         do {
3368                 if (reserved == false &&
3369                     bufspace_reserve(bd, maxsize, metadata) != 0) {
3370                         counter_u64_add(getnewbufrestarts, 1);
3371                         continue;
3372                 }
3373                 reserved = true;
3374                 if ((bp = buf_alloc(bd)) == NULL) {
3375                         counter_u64_add(getnewbufrestarts, 1);
3376                         continue;
3377                 }
3378                 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
3379                         return (bp);
3380                 break;
3381         } while (buf_recycle(bd, false) == 0);
3382
3383         if (reserved)
3384                 bufspace_release(bd, maxsize);
3385         if (bp != NULL) {
3386                 bp->b_flags |= B_INVAL;
3387                 brelse(bp);
3388         }
3389         bufspace_wait(bd, vp, gbflags, slpflag, slptimeo);
3390
3391         return (NULL);
3392 }
3393
3394 /*
3395  *      buf_daemon:
3396  *
3397  *      buffer flushing daemon.  Buffers are normally flushed by the
3398  *      update daemon but if it cannot keep up this process starts to
3399  *      take the load in an attempt to prevent getnewbuf() from blocking.
3400  */
3401 static struct kproc_desc buf_kp = {
3402         "bufdaemon",
3403         buf_daemon,
3404         &bufdaemonproc
3405 };
3406 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3407
3408 static int
3409 buf_flush(struct vnode *vp, struct bufdomain *bd, int target)
3410 {
3411         int flushed;
3412
3413         flushed = flushbufqueues(vp, bd, target, 0);
3414         if (flushed == 0) {
3415                 /*
3416                  * Could not find any buffers without rollback
3417                  * dependencies, so just write the first one
3418                  * in the hopes of eventually making progress.
3419                  */
3420                 if (vp != NULL && target > 2)
3421                         target /= 2;
3422                 flushbufqueues(vp, bd, target, 1);
3423         }
3424         return (flushed);
3425 }
3426
3427 static void
3428 buf_daemon_shutdown(void *arg __unused, int howto __unused)
3429 {
3430         int error;
3431
3432         if (KERNEL_PANICKED())
3433                 return;
3434
3435         mtx_lock(&bdlock);
3436         bd_shutdown = true;
3437         wakeup(&bd_request);
3438         error = msleep(&bd_shutdown, &bdlock, 0, "buf_daemon_shutdown",
3439             60 * hz);
3440         mtx_unlock(&bdlock);
3441         if (error != 0)
3442                 printf("bufdaemon wait error: %d\n", error);
3443 }
3444
3445 static void
3446 buf_daemon(void)
3447 {
3448         struct bufdomain *bd;
3449         int speedupreq;
3450         int lodirty;
3451         int i;
3452
3453         /*
3454          * This process needs to be suspended prior to shutdown sync.
3455          */
3456         EVENTHANDLER_REGISTER(shutdown_pre_sync, buf_daemon_shutdown, NULL,
3457             SHUTDOWN_PRI_LAST + 100);
3458
3459         /*
3460          * Start the buf clean daemons as children threads.
3461          */
3462         for (i = 0 ; i < buf_domains; i++) {
3463                 int error;
3464
3465                 error = kthread_add((void (*)(void *))bufspace_daemon,
3466                     &bdomain[i], curproc, NULL, 0, 0, "bufspacedaemon-%d", i);
3467                 if (error)
3468                         panic("error %d spawning bufspace daemon", error);
3469         }
3470
3471         /*
3472          * This process is allowed to take the buffer cache to the limit
3473          */
3474         curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3475         mtx_lock(&bdlock);
3476         while (!bd_shutdown) {
3477                 bd_request = 0;
3478                 mtx_unlock(&bdlock);
3479
3480                 /*
3481                  * Save speedupreq for this pass and reset to capture new
3482                  * requests.
3483                  */
3484                 speedupreq = bd_speedupreq;
3485                 bd_speedupreq = 0;
3486
3487                 /*
3488                  * Flush each domain sequentially according to its level and
3489                  * the speedup request.
3490                  */
3491                 for (i = 0; i < buf_domains; i++) {
3492                         bd = &bdomain[i];
3493                         if (speedupreq)
3494                                 lodirty = bd->bd_numdirtybuffers / 2;
3495                         else
3496                                 lodirty = bd->bd_lodirtybuffers;
3497                         while (bd->bd_numdirtybuffers > lodirty) {
3498                                 if (buf_flush(NULL, bd,
3499                                     bd->bd_numdirtybuffers - lodirty) == 0)
3500                                         break;
3501                                 kern_yield(PRI_USER);
3502                         }
3503                 }
3504
3505                 /*
3506                  * Only clear bd_request if we have reached our low water
3507                  * mark.  The buf_daemon normally waits 1 second and
3508                  * then incrementally flushes any dirty buffers that have
3509                  * built up, within reason.
3510                  *
3511                  * If we were unable to hit our low water mark and couldn't
3512                  * find any flushable buffers, we sleep for a short period
3513                  * to avoid endless loops on unlockable buffers.
3514                  */
3515                 mtx_lock(&bdlock);
3516                 if (bd_shutdown)
3517                         break;
3518                 if (BIT_EMPTY(BUF_DOMAINS, &bdlodirty)) {
3519                         /*
3520                          * We reached our low water mark, reset the
3521                          * request and sleep until we are needed again.
3522                          * The sleep is just so the suspend code works.
3523                          */
3524                         bd_request = 0;
3525                         /*
3526                          * Do an extra wakeup in case dirty threshold
3527                          * changed via sysctl and the explicit transition
3528                          * out of shortfall was missed.
3529                          */
3530                         bdirtywakeup();
3531                         if (runningbufspace <= lorunningspace)
3532                                 runningwakeup();
3533                         msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3534                 } else {
3535                         /*
3536                          * We couldn't find any flushable dirty buffers but
3537                          * still have too many dirty buffers, we
3538                          * have to sleep and try again.  (rare)
3539                          */
3540                         msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3541                 }
3542         }
3543         wakeup(&bd_shutdown);
3544         mtx_unlock(&bdlock);
3545         kthread_exit();
3546 }
3547
3548 /*
3549  *      flushbufqueues:
3550  *
3551  *      Try to flush a buffer in the dirty queue.  We must be careful to
3552  *      free up B_INVAL buffers instead of write them, which NFS is 
3553  *      particularly sensitive to.
3554  */
3555 static int flushwithdeps = 0;
3556 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW | CTLFLAG_STATS,
3557     &flushwithdeps, 0,
3558     "Number of buffers flushed with dependencies that require rollbacks");
3559
3560 static int
3561 flushbufqueues(struct vnode *lvp, struct bufdomain *bd, int target,
3562     int flushdeps)
3563 {
3564         struct bufqueue *bq;
3565         struct buf *sentinel;
3566         struct vnode *vp;
3567         struct mount *mp;
3568         struct buf *bp;
3569         int hasdeps;
3570         int flushed;
3571         int error;
3572         bool unlock;
3573
3574         flushed = 0;
3575         bq = &bd->bd_dirtyq;
3576         bp = NULL;
3577         sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3578         sentinel->b_qindex = QUEUE_SENTINEL;
3579         BQ_LOCK(bq);
3580         TAILQ_INSERT_HEAD(&bq->bq_queue, sentinel, b_freelist);
3581         BQ_UNLOCK(bq);
3582         while (flushed != target) {
3583                 maybe_yield();
3584                 BQ_LOCK(bq);
3585                 bp = TAILQ_NEXT(sentinel, b_freelist);
3586                 if (bp != NULL) {
3587                         TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3588                         TAILQ_INSERT_AFTER(&bq->bq_queue, bp, sentinel,
3589                             b_freelist);
3590                 } else {
3591                         BQ_UNLOCK(bq);
3592                         break;
3593                 }
3594                 /*
3595                  * Skip sentinels inserted by other invocations of the
3596                  * flushbufqueues(), taking care to not reorder them.
3597                  *
3598                  * Only flush the buffers that belong to the
3599                  * vnode locked by the curthread.
3600                  */
3601                 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3602                     bp->b_vp != lvp)) {
3603                         BQ_UNLOCK(bq);
3604                         continue;
3605                 }
3606                 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3607                 BQ_UNLOCK(bq);
3608                 if (error != 0)
3609                         continue;
3610
3611                 /*
3612                  * BKGRDINPROG can only be set with the buf and bufobj
3613                  * locks both held.  We tolerate a race to clear it here.
3614                  */
3615                 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3616                     (bp->b_flags & B_DELWRI) == 0) {
3617                         BUF_UNLOCK(bp);
3618                         continue;
3619                 }
3620                 if (bp->b_flags & B_INVAL) {
3621                         bremfreef(bp);
3622                         brelse(bp);
3623                         flushed++;
3624                         continue;
3625                 }
3626
3627                 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3628                         if (flushdeps == 0) {
3629                                 BUF_UNLOCK(bp);
3630                                 continue;
3631                         }
3632                         hasdeps = 1;
3633                 } else
3634                         hasdeps = 0;
3635                 /*
3636                  * We must hold the lock on a vnode before writing
3637                  * one of its buffers. Otherwise we may confuse, or
3638                  * in the case of a snapshot vnode, deadlock the
3639                  * system.
3640                  *
3641                  * The lock order here is the reverse of the normal
3642                  * of vnode followed by buf lock.  This is ok because
3643                  * the NOWAIT will prevent deadlock.
3644                  */
3645                 vp = bp->b_vp;
3646                 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3647                         BUF_UNLOCK(bp);
3648                         continue;
3649                 }
3650                 if (lvp == NULL) {
3651                         unlock = true;
3652                         error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3653                 } else {
3654                         ASSERT_VOP_LOCKED(vp, "getbuf");
3655                         unlock = false;
3656                         error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3657                             vn_lock(vp, LK_TRYUPGRADE);
3658                 }
3659                 if (error == 0) {
3660                         CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3661                             bp, bp->b_vp, bp->b_flags);
3662                         if (curproc == bufdaemonproc) {
3663                                 vfs_bio_awrite(bp);
3664                         } else {
3665                                 bremfree(bp);
3666                                 bwrite(bp);
3667                                 counter_u64_add(notbufdflushes, 1);
3668                         }
3669                         vn_finished_write(mp);
3670                         if (unlock)
3671                                 VOP_UNLOCK(vp);
3672                         flushwithdeps += hasdeps;
3673                         flushed++;
3674
3675                         /*
3676                          * Sleeping on runningbufspace while holding
3677                          * vnode lock leads to deadlock.
3678                          */
3679                         if (curproc == bufdaemonproc &&
3680                             runningbufspace > hirunningspace)
3681                                 waitrunningbufspace();
3682                         continue;
3683                 }
3684                 vn_finished_write(mp);
3685                 BUF_UNLOCK(bp);
3686         }
3687         BQ_LOCK(bq);
3688         TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3689         BQ_UNLOCK(bq);
3690         free(sentinel, M_TEMP);
3691         return (flushed);
3692 }
3693
3694 /*
3695  * Check to see if a block is currently memory resident.
3696  */
3697 struct buf *
3698 incore(struct bufobj *bo, daddr_t blkno)
3699 {
3700         return (gbincore_unlocked(bo, blkno));
3701 }
3702
3703 /*
3704  * Returns true if no I/O is needed to access the
3705  * associated VM object.  This is like incore except
3706  * it also hunts around in the VM system for the data.
3707  */
3708 bool
3709 inmem(struct vnode * vp, daddr_t blkno)
3710 {
3711         vm_object_t obj;
3712         vm_offset_t toff, tinc, size;
3713         vm_page_t m, n;
3714         vm_ooffset_t off;
3715         int valid;
3716
3717         ASSERT_VOP_LOCKED(vp, "inmem");
3718
3719         if (incore(&vp->v_bufobj, blkno))
3720                 return (true);
3721         if (vp->v_mount == NULL)
3722                 return (false);
3723         obj = vp->v_object;
3724         if (obj == NULL)
3725                 return (false);
3726
3727         size = PAGE_SIZE;
3728         if (size > vp->v_mount->mnt_stat.f_iosize)
3729                 size = vp->v_mount->mnt_stat.f_iosize;
3730         off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3731
3732         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3733                 m = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3734 recheck:
3735                 if (m == NULL)
3736                         return (false);
3737
3738                 tinc = size;
3739                 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3740                         tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3741                 /*
3742                  * Consider page validity only if page mapping didn't change
3743                  * during the check.
3744                  */
3745                 valid = vm_page_is_valid(m,
3746                     (vm_offset_t)((toff + off) & PAGE_MASK), tinc);
3747                 n = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3748                 if (m != n) {
3749                         m = n;
3750                         goto recheck;
3751                 }
3752                 if (!valid)
3753                         return (false);
3754         }
3755         return (true);
3756 }
3757
3758 /*
3759  * Set the dirty range for a buffer based on the status of the dirty
3760  * bits in the pages comprising the buffer.  The range is limited
3761  * to the size of the buffer.
3762  *
3763  * Tell the VM system that the pages associated with this buffer
3764  * are clean.  This is used for delayed writes where the data is
3765  * going to go to disk eventually without additional VM intevention.
3766  *
3767  * Note that while we only really need to clean through to b_bcount, we
3768  * just go ahead and clean through to b_bufsize.
3769  */
3770 static void
3771 vfs_clean_pages_dirty_buf(struct buf *bp)
3772 {
3773         vm_ooffset_t foff, noff, eoff;
3774         vm_page_t m;
3775         int i;
3776
3777         if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3778                 return;
3779
3780         foff = bp->b_offset;
3781         KASSERT(bp->b_offset != NOOFFSET,
3782             ("vfs_clean_pages_dirty_buf: no buffer offset"));
3783
3784         vfs_busy_pages_acquire(bp);
3785         vfs_setdirty_range(bp);
3786         for (i = 0; i < bp->b_npages; i++) {
3787                 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3788                 eoff = noff;
3789                 if (eoff > bp->b_offset + bp->b_bufsize)
3790                         eoff = bp->b_offset + bp->b_bufsize;
3791                 m = bp->b_pages[i];
3792                 vfs_page_set_validclean(bp, foff, m);
3793                 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3794                 foff = noff;
3795         }
3796         vfs_busy_pages_release(bp);
3797 }
3798
3799 static void
3800 vfs_setdirty_range(struct buf *bp)
3801 {
3802         vm_offset_t boffset;
3803         vm_offset_t eoffset;
3804         int i;
3805
3806         /*
3807          * test the pages to see if they have been modified directly
3808          * by users through the VM system.
3809          */
3810         for (i = 0; i < bp->b_npages; i++)
3811                 vm_page_test_dirty(bp->b_pages[i]);
3812
3813         /*
3814          * Calculate the encompassing dirty range, boffset and eoffset,
3815          * (eoffset - boffset) bytes.
3816          */
3817
3818         for (i = 0; i < bp->b_npages; i++) {
3819                 if (bp->b_pages[i]->dirty)
3820                         break;
3821         }
3822         boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3823
3824         for (i = bp->b_npages - 1; i >= 0; --i) {
3825                 if (bp->b_pages[i]->dirty) {
3826                         break;
3827                 }
3828         }
3829         eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3830
3831         /*
3832          * Fit it to the buffer.
3833          */
3834
3835         if (eoffset > bp->b_bcount)
3836                 eoffset = bp->b_bcount;
3837
3838         /*
3839          * If we have a good dirty range, merge with the existing
3840          * dirty range.
3841          */
3842
3843         if (boffset < eoffset) {
3844                 if (bp->b_dirtyoff > boffset)
3845                         bp->b_dirtyoff = boffset;
3846                 if (bp->b_dirtyend < eoffset)
3847                         bp->b_dirtyend = eoffset;
3848         }
3849 }
3850
3851 /*
3852  * Allocate the KVA mapping for an existing buffer.
3853  * If an unmapped buffer is provided but a mapped buffer is requested, take
3854  * also care to properly setup mappings between pages and KVA.
3855  */
3856 static void
3857 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3858 {
3859         int bsize, maxsize, need_mapping, need_kva;
3860         off_t offset;
3861
3862         need_mapping = bp->b_data == unmapped_buf &&
3863             (gbflags & GB_UNMAPPED) == 0;
3864         need_kva = bp->b_kvabase == unmapped_buf &&
3865             bp->b_data == unmapped_buf &&
3866             (gbflags & GB_KVAALLOC) != 0;
3867         if (!need_mapping && !need_kva)
3868                 return;
3869
3870         BUF_CHECK_UNMAPPED(bp);
3871
3872         if (need_mapping && bp->b_kvabase != unmapped_buf) {
3873                 /*
3874                  * Buffer is not mapped, but the KVA was already
3875                  * reserved at the time of the instantiation.  Use the
3876                  * allocated space.
3877                  */
3878                 goto has_addr;
3879         }
3880
3881         /*
3882          * Calculate the amount of the address space we would reserve
3883          * if the buffer was mapped.
3884          */
3885         bsize = vn_isdisk(bp->b_vp) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3886         KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3887         offset = blkno * bsize;
3888         maxsize = size + (offset & PAGE_MASK);
3889         maxsize = imax(maxsize, bsize);
3890
3891         while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3892                 if ((gbflags & GB_NOWAIT_BD) != 0) {
3893                         /*
3894                          * XXXKIB: defragmentation cannot
3895                          * succeed, not sure what else to do.
3896                          */
3897                         panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3898                 }
3899                 counter_u64_add(mappingrestarts, 1);
3900                 bufspace_wait(bufdomain(bp), bp->b_vp, gbflags, 0, 0);
3901         }
3902 has_addr:
3903         if (need_mapping) {
3904                 /* b_offset is handled by bpmap_qenter. */
3905                 bp->b_data = bp->b_kvabase;
3906                 BUF_CHECK_MAPPED(bp);
3907                 bpmap_qenter(bp);
3908         }
3909 }
3910
3911 struct buf *
3912 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3913     int flags)
3914 {
3915         struct buf *bp;
3916         int error;
3917
3918         error = getblkx(vp, blkno, blkno, size, slpflag, slptimeo, flags, &bp);
3919         if (error != 0)
3920                 return (NULL);
3921         return (bp);
3922 }
3923
3924 /*
3925  *      getblkx:
3926  *
3927  *      Get a block given a specified block and offset into a file/device.
3928  *      The buffers B_DONE bit will be cleared on return, making it almost
3929  *      ready for an I/O initiation.  B_INVAL may or may not be set on 
3930  *      return.  The caller should clear B_INVAL prior to initiating a
3931  *      READ.
3932  *
3933  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3934  *      an existing buffer.
3935  *
3936  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
3937  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3938  *      and then cleared based on the backing VM.  If the previous buffer is
3939  *      non-0-sized but invalid, B_CACHE will be cleared.
3940  *
3941  *      If getblk() must create a new buffer, the new buffer is returned with
3942  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3943  *      case it is returned with B_INVAL clear and B_CACHE set based on the
3944  *      backing VM.
3945  *
3946  *      getblk() also forces a bwrite() for any B_DELWRI buffer whose
3947  *      B_CACHE bit is clear.
3948  *
3949  *      What this means, basically, is that the caller should use B_CACHE to
3950  *      determine whether the buffer is fully valid or not and should clear
3951  *      B_INVAL prior to issuing a read.  If the caller intends to validate
3952  *      the buffer by loading its data area with something, the caller needs
3953  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
3954  *      the caller should set B_CACHE ( as an optimization ), else the caller
3955  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
3956  *      a write attempt or if it was a successful read.  If the caller 
3957  *      intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3958  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
3959  *
3960  *      The blkno parameter is the logical block being requested. Normally
3961  *      the mapping of logical block number to disk block address is done
3962  *      by calling VOP_BMAP(). However, if the mapping is already known, the
3963  *      disk block address can be passed using the dblkno parameter. If the
3964  *      disk block address is not known, then the same value should be passed
3965  *      for blkno and dblkno.
3966  */
3967 int
3968 getblkx(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size, int slpflag,
3969     int slptimeo, int flags, struct buf **bpp)
3970 {
3971         struct buf *bp;
3972         struct bufobj *bo;
3973         daddr_t d_blkno;
3974         int bsize, error, maxsize, vmio;
3975         off_t offset;
3976
3977         CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3978         KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3979             ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3980         if (vp->v_type != VCHR)
3981                 ASSERT_VOP_LOCKED(vp, "getblk");
3982         if (size > maxbcachebuf)
3983                 panic("getblk: size(%d) > maxbcachebuf(%d)\n", size,
3984                     maxbcachebuf);
3985         if (!unmapped_buf_allowed)
3986                 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3987
3988         bo = &vp->v_bufobj;
3989         d_blkno = dblkno;
3990
3991         /* Attempt lockless lookup first. */
3992         bp = gbincore_unlocked(bo, blkno);
3993         if (bp == NULL) {
3994                 /*
3995                  * With GB_NOCREAT we must be sure about not finding the buffer
3996                  * as it may have been reassigned during unlocked lookup.
3997                  */
3998                 if ((flags & GB_NOCREAT) != 0)
3999                         goto loop;
4000                 goto newbuf_unlocked;
4001         }
4002
4003         error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL, "getblku", 0,
4004             0);
4005         if (error != 0)
4006                 goto loop;
4007
4008         /* Verify buf identify has not changed since lookup. */
4009         if (bp->b_bufobj == bo && bp->b_lblkno == blkno)
4010                 goto foundbuf_fastpath;
4011
4012         /* It changed, fallback to locked lookup. */
4013         BUF_UNLOCK_RAW(bp);
4014
4015 loop:
4016         BO_RLOCK(bo);
4017         bp = gbincore(bo, blkno);
4018         if (bp != NULL) {
4019                 int lockflags;
4020
4021                 /*
4022                  * Buffer is in-core.  If the buffer is not busy nor managed,
4023                  * it must be on a queue.
4024                  */
4025                 lockflags = LK_EXCLUSIVE | LK_INTERLOCK |
4026                     ((flags & GB_LOCK_NOWAIT) != 0 ? LK_NOWAIT : LK_SLEEPFAIL);
4027 #ifdef WITNESS
4028                 lockflags |= (flags & GB_NOWITNESS) != 0 ? LK_NOWITNESS : 0;
4029 #endif
4030
4031                 error = BUF_TIMELOCK(bp, lockflags,
4032                     BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
4033
4034                 /*
4035                  * If we slept and got the lock we have to restart in case
4036                  * the buffer changed identities.
4037                  */
4038                 if (error == ENOLCK)
4039                         goto loop;
4040                 /* We timed out or were interrupted. */
4041                 else if (error != 0)
4042                         return (error);
4043
4044 foundbuf_fastpath:
4045                 /* If recursed, assume caller knows the rules. */
4046                 if (BUF_LOCKRECURSED(bp))
4047                         goto end;
4048
4049                 /*
4050                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
4051                  * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
4052                  * and for a VMIO buffer B_CACHE is adjusted according to the
4053                  * backing VM cache.
4054                  */
4055                 if (bp->b_flags & B_INVAL)
4056                         bp->b_flags &= ~B_CACHE;
4057                 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
4058                         bp->b_flags |= B_CACHE;
4059                 if (bp->b_flags & B_MANAGED)
4060                         MPASS(bp->b_qindex == QUEUE_NONE);
4061                 else
4062                         bremfree(bp);
4063
4064                 /*
4065                  * check for size inconsistencies for non-VMIO case.
4066                  */
4067                 if (bp->b_bcount != size) {
4068                         if ((bp->b_flags & B_VMIO) == 0 ||
4069                             (size > bp->b_kvasize)) {
4070                                 if (bp->b_flags & B_DELWRI) {
4071                                         bp->b_flags |= B_NOCACHE;
4072                                         bwrite(bp);
4073                                 } else {
4074                                         if (LIST_EMPTY(&bp->b_dep)) {
4075                                                 bp->b_flags |= B_RELBUF;
4076                                                 brelse(bp);
4077                                         } else {
4078                                                 bp->b_flags |= B_NOCACHE;
4079                                                 bwrite(bp);
4080                                         }
4081                                 }
4082                                 goto loop;
4083                         }
4084                 }
4085
4086                 /*
4087                  * Handle the case of unmapped buffer which should
4088                  * become mapped, or the buffer for which KVA
4089                  * reservation is requested.
4090                  */
4091                 bp_unmapped_get_kva(bp, blkno, size, flags);
4092
4093                 /*
4094                  * If the size is inconsistent in the VMIO case, we can resize
4095                  * the buffer.  This might lead to B_CACHE getting set or
4096                  * cleared.  If the size has not changed, B_CACHE remains
4097                  * unchanged from its previous state.
4098                  */
4099                 allocbuf(bp, size);
4100
4101                 KASSERT(bp->b_offset != NOOFFSET, 
4102                     ("getblk: no buffer offset"));
4103
4104                 /*
4105                  * A buffer with B_DELWRI set and B_CACHE clear must
4106                  * be committed before we can return the buffer in
4107                  * order to prevent the caller from issuing a read
4108                  * ( due to B_CACHE not being set ) and overwriting
4109                  * it.
4110                  *
4111                  * Most callers, including NFS and FFS, need this to
4112                  * operate properly either because they assume they
4113                  * can issue a read if B_CACHE is not set, or because
4114                  * ( for example ) an uncached B_DELWRI might loop due 
4115                  * to softupdates re-dirtying the buffer.  In the latter
4116                  * case, B_CACHE is set after the first write completes,
4117                  * preventing further loops.
4118                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
4119                  * above while extending the buffer, we cannot allow the
4120                  * buffer to remain with B_CACHE set after the write
4121                  * completes or it will represent a corrupt state.  To
4122                  * deal with this we set B_NOCACHE to scrap the buffer
4123                  * after the write.
4124                  *
4125                  * We might be able to do something fancy, like setting
4126                  * B_CACHE in bwrite() except if B_DELWRI is already set,
4127                  * so the below call doesn't set B_CACHE, but that gets real
4128                  * confusing.  This is much easier.
4129                  */
4130
4131                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
4132                         bp->b_flags |= B_NOCACHE;
4133                         bwrite(bp);
4134                         goto loop;
4135                 }
4136                 bp->b_flags &= ~B_DONE;
4137         } else {
4138                 /*
4139                  * Buffer is not in-core, create new buffer.  The buffer
4140                  * returned by getnewbuf() is locked.  Note that the returned
4141                  * buffer is also considered valid (not marked B_INVAL).
4142                  */
4143                 BO_RUNLOCK(bo);
4144 newbuf_unlocked:
4145                 /*
4146                  * If the user does not want us to create the buffer, bail out
4147                  * here.
4148                  */
4149                 if (flags & GB_NOCREAT)
4150                         return (EEXIST);
4151
4152                 bsize = vn_isdisk(vp) ? DEV_BSIZE : bo->bo_bsize;
4153                 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
4154                 offset = blkno * bsize;
4155                 vmio = vp->v_object != NULL;
4156                 if (vmio) {
4157                         maxsize = size + (offset & PAGE_MASK);
4158                 } else {
4159                         maxsize = size;
4160                         /* Do not allow non-VMIO notmapped buffers. */
4161                         flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
4162                 }
4163                 maxsize = imax(maxsize, bsize);
4164                 if ((flags & GB_NOSPARSE) != 0 && vmio &&
4165                     !vn_isdisk(vp)) {
4166                         error = VOP_BMAP(vp, blkno, NULL, &d_blkno, 0, 0);
4167                         KASSERT(error != EOPNOTSUPP,
4168                             ("GB_NOSPARSE from fs not supporting bmap, vp %p",
4169                             vp));
4170                         if (error != 0)
4171                                 return (error);
4172                         if (d_blkno == -1)
4173                                 return (EJUSTRETURN);
4174                 }
4175
4176                 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
4177                 if (bp == NULL) {
4178                         if (slpflag || slptimeo)
4179                                 return (ETIMEDOUT);
4180                         /*
4181                          * XXX This is here until the sleep path is diagnosed
4182                          * enough to work under very low memory conditions.
4183                          *
4184                          * There's an issue on low memory, 4BSD+non-preempt
4185                          * systems (eg MIPS routers with 32MB RAM) where buffer
4186                          * exhaustion occurs without sleeping for buffer
4187                          * reclaimation.  This just sticks in a loop and
4188                          * constantly attempts to allocate a buffer, which
4189                          * hits exhaustion and tries to wakeup bufdaemon.
4190                          * This never happens because we never yield.
4191                          *
4192                          * The real solution is to identify and fix these cases
4193                          * so we aren't effectively busy-waiting in a loop
4194                          * until the reclaimation path has cycles to run.
4195                          */
4196                         kern_yield(PRI_USER);
4197                         goto loop;
4198                 }
4199
4200                 /*
4201                  * This code is used to make sure that a buffer is not
4202                  * created while the getnewbuf routine is blocked.
4203                  * This can be a problem whether the vnode is locked or not.
4204                  * If the buffer is created out from under us, we have to
4205                  * throw away the one we just created.
4206                  *
4207                  * Note: this must occur before we associate the buffer
4208                  * with the vp especially considering limitations in
4209                  * the splay tree implementation when dealing with duplicate
4210                  * lblkno's.
4211                  */
4212                 BO_LOCK(bo);
4213                 if (gbincore(bo, blkno)) {
4214                         BO_UNLOCK(bo);
4215                         bp->b_flags |= B_INVAL;
4216                         bufspace_release(bufdomain(bp), maxsize);
4217                         brelse(bp);
4218                         goto loop;
4219                 }
4220
4221                 /*
4222                  * Insert the buffer into the hash, so that it can
4223                  * be found by incore.
4224                  */
4225                 bp->b_lblkno = blkno;
4226                 bp->b_blkno = d_blkno;
4227                 bp->b_offset = offset;
4228                 bgetvp(vp, bp);
4229                 BO_UNLOCK(bo);
4230
4231                 /*
4232                  * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
4233                  * buffer size starts out as 0, B_CACHE will be set by
4234                  * allocbuf() for the VMIO case prior to it testing the
4235                  * backing store for validity.
4236                  */
4237
4238                 if (vmio) {
4239                         bp->b_flags |= B_VMIO;
4240                         KASSERT(vp->v_object == bp->b_bufobj->bo_object,
4241                             ("ARGH! different b_bufobj->bo_object %p %p %p\n",
4242                             bp, vp->v_object, bp->b_bufobj->bo_object));
4243                 } else {
4244                         bp->b_flags &= ~B_VMIO;
4245                         KASSERT(bp->b_bufobj->bo_object == NULL,
4246                             ("ARGH! has b_bufobj->bo_object %p %p\n",
4247                             bp, bp->b_bufobj->bo_object));
4248                         BUF_CHECK_MAPPED(bp);
4249                 }
4250
4251                 allocbuf(bp, size);
4252                 bufspace_release(bufdomain(bp), maxsize);
4253                 bp->b_flags &= ~B_DONE;
4254         }
4255         CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
4256 end:
4257         buf_track(bp, __func__);
4258         KASSERT(bp->b_bufobj == bo,
4259             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
4260         *bpp = bp;
4261         return (0);
4262 }
4263
4264 /*
4265  * Get an empty, disassociated buffer of given size.  The buffer is initially
4266  * set to B_INVAL.
4267  */
4268 struct buf *
4269 geteblk(int size, int flags)
4270 {
4271         struct buf *bp;
4272         int maxsize;
4273
4274         maxsize = (size + BKVAMASK) & ~BKVAMASK;
4275         while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
4276                 if ((flags & GB_NOWAIT_BD) &&
4277                     (curthread->td_pflags & TDP_BUFNEED) != 0)
4278                         return (NULL);
4279         }
4280         allocbuf(bp, size);
4281         bufspace_release(bufdomain(bp), maxsize);
4282         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
4283         return (bp);
4284 }
4285
4286 /*
4287  * Truncate the backing store for a non-vmio buffer.
4288  */
4289 static void
4290 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
4291 {
4292
4293         if (bp->b_flags & B_MALLOC) {
4294                 /*
4295                  * malloced buffers are not shrunk
4296                  */
4297                 if (newbsize == 0) {
4298                         bufmallocadjust(bp, 0);
4299                         free(bp->b_data, M_BIOBUF);
4300                         bp->b_data = bp->b_kvabase;
4301                         bp->b_flags &= ~B_MALLOC;
4302                 }
4303                 return;
4304         }
4305         vm_hold_free_pages(bp, newbsize);
4306         bufspace_adjust(bp, newbsize);
4307 }
4308
4309 /*
4310  * Extend the backing for a non-VMIO buffer.
4311  */
4312 static void
4313 vfs_nonvmio_extend(struct buf *bp, int newbsize)
4314 {
4315         caddr_t origbuf;
4316         int origbufsize;
4317
4318         /*
4319          * We only use malloced memory on the first allocation.
4320          * and revert to page-allocated memory when the buffer
4321          * grows.
4322          *
4323          * There is a potential smp race here that could lead
4324          * to bufmallocspace slightly passing the max.  It
4325          * is probably extremely rare and not worth worrying
4326          * over.
4327          */
4328         if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
4329             bufmallocspace < maxbufmallocspace) {
4330                 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
4331                 bp->b_flags |= B_MALLOC;
4332                 bufmallocadjust(bp, newbsize);
4333                 return;
4334         }
4335
4336         /*
4337          * If the buffer is growing on its other-than-first
4338          * allocation then we revert to the page-allocation
4339          * scheme.
4340          */
4341         origbuf = NULL;
4342         origbufsize = 0;
4343         if (bp->b_flags & B_MALLOC) {
4344                 origbuf = bp->b_data;
4345                 origbufsize = bp->b_bufsize;
4346                 bp->b_data = bp->b_kvabase;
4347                 bufmallocadjust(bp, 0);
4348                 bp->b_flags &= ~B_MALLOC;
4349                 newbsize = round_page(newbsize);
4350         }
4351         vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
4352             (vm_offset_t) bp->b_data + newbsize);
4353         if (origbuf != NULL) {
4354                 bcopy(origbuf, bp->b_data, origbufsize);
4355                 free(origbuf, M_BIOBUF);
4356         }
4357         bufspace_adjust(bp, newbsize);
4358 }
4359
4360 /*
4361  * This code constitutes the buffer memory from either anonymous system
4362  * memory (in the case of non-VMIO operations) or from an associated
4363  * VM object (in the case of VMIO operations).  This code is able to
4364  * resize a buffer up or down.
4365  *
4366  * Note that this code is tricky, and has many complications to resolve
4367  * deadlock or inconsistent data situations.  Tread lightly!!! 
4368  * There are B_CACHE and B_DELWRI interactions that must be dealt with by 
4369  * the caller.  Calling this code willy nilly can result in the loss of data.
4370  *
4371  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
4372  * B_CACHE for the non-VMIO case.
4373  */
4374 int
4375 allocbuf(struct buf *bp, int size)
4376 {
4377         int newbsize;
4378
4379         if (bp->b_bcount == size)
4380                 return (1);
4381
4382         KASSERT(bp->b_kvasize == 0 || bp->b_kvasize >= size,
4383             ("allocbuf: buffer too small %p %#x %#x",
4384             bp, bp->b_kvasize, size));
4385
4386         newbsize = roundup2(size, DEV_BSIZE);
4387         if ((bp->b_flags & B_VMIO) == 0) {
4388                 if ((bp->b_flags & B_MALLOC) == 0)
4389                         newbsize = round_page(newbsize);
4390                 /*
4391                  * Just get anonymous memory from the kernel.  Don't
4392                  * mess with B_CACHE.
4393                  */
4394                 if (newbsize < bp->b_bufsize)
4395                         vfs_nonvmio_truncate(bp, newbsize);
4396                 else if (newbsize > bp->b_bufsize)
4397                         vfs_nonvmio_extend(bp, newbsize);
4398         } else {
4399                 int desiredpages;
4400
4401                 desiredpages = size == 0 ? 0 :
4402                     num_pages((bp->b_offset & PAGE_MASK) + newbsize);
4403
4404                 KASSERT((bp->b_flags & B_MALLOC) == 0,
4405                     ("allocbuf: VMIO buffer can't be malloced %p", bp));
4406
4407                 /*
4408                  * Set B_CACHE initially if buffer is 0 length or will become
4409                  * 0-length.
4410                  */
4411                 if (size == 0 || bp->b_bufsize == 0)
4412                         bp->b_flags |= B_CACHE;
4413
4414                 if (newbsize < bp->b_bufsize)
4415                         vfs_vmio_truncate(bp, desiredpages);
4416                 /* XXX This looks as if it should be newbsize > b_bufsize */
4417                 else if (size > bp->b_bcount)
4418                         vfs_vmio_extend(bp, desiredpages, size);
4419                 bufspace_adjust(bp, newbsize);
4420         }
4421         bp->b_bcount = size;            /* requested buffer size. */
4422         return (1);
4423 }
4424
4425 extern int inflight_transient_maps;
4426
4427 static struct bio_queue nondump_bios;
4428
4429 void
4430 biodone(struct bio *bp)
4431 {
4432         struct mtx *mtxp;
4433         void (*done)(struct bio *);
4434         vm_offset_t start, end;
4435
4436         biotrack(bp, __func__);
4437
4438         /*
4439          * Avoid completing I/O when dumping after a panic since that may
4440          * result in a deadlock in the filesystem or pager code.  Note that
4441          * this doesn't affect dumps that were started manually since we aim
4442          * to keep the system usable after it has been resumed.
4443          */
4444         if (__predict_false(dumping && SCHEDULER_STOPPED())) {
4445                 TAILQ_INSERT_HEAD(&nondump_bios, bp, bio_queue);
4446                 return;
4447         }
4448         if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
4449                 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
4450                 bp->bio_flags |= BIO_UNMAPPED;
4451                 start = trunc_page((vm_offset_t)bp->bio_data);
4452                 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
4453                 bp->bio_data = unmapped_buf;
4454                 pmap_qremove(start, atop(end - start));
4455                 vmem_free(transient_arena, start, end - start);
4456                 atomic_add_int(&inflight_transient_maps, -1);
4457         }
4458         done = bp->bio_done;
4459         /*
4460          * The check for done == biodone is to allow biodone to be
4461          * used as a bio_done routine.
4462          */
4463         if (done == NULL || done == biodone) {
4464                 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4465                 mtx_lock(mtxp);
4466                 bp->bio_flags |= BIO_DONE;
4467                 wakeup(bp);
4468                 mtx_unlock(mtxp);
4469         } else
4470                 done(bp);
4471 }
4472
4473 /*
4474  * Wait for a BIO to finish.
4475  */
4476 int
4477 biowait(struct bio *bp, const char *wmesg)
4478 {
4479         struct mtx *mtxp;
4480
4481         mtxp = mtx_pool_find(mtxpool_sleep, bp);
4482         mtx_lock(mtxp);
4483         while ((bp->bio_flags & BIO_DONE) == 0)
4484                 msleep(bp, mtxp, PRIBIO, wmesg, 0);
4485         mtx_unlock(mtxp);
4486         if (bp->bio_error != 0)
4487                 return (bp->bio_error);
4488         if (!(bp->bio_flags & BIO_ERROR))
4489                 return (0);
4490         return (EIO);
4491 }
4492
4493 void
4494 biofinish(struct bio *bp, struct devstat *stat, int error)
4495 {
4496
4497         if (error) {
4498                 bp->bio_error = error;
4499                 bp->bio_flags |= BIO_ERROR;
4500         }
4501         if (stat != NULL)
4502                 devstat_end_transaction_bio(stat, bp);
4503         biodone(bp);
4504 }
4505
4506 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4507 void
4508 biotrack_buf(struct bio *bp, const char *location)
4509 {
4510
4511         buf_track(bp->bio_track_bp, location);
4512 }
4513 #endif
4514
4515 /*
4516  *      bufwait:
4517  *
4518  *      Wait for buffer I/O completion, returning error status.  The buffer
4519  *      is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
4520  *      error and cleared.
4521  */
4522 int
4523 bufwait(struct buf *bp)
4524 {
4525         if (bp->b_iocmd == BIO_READ)
4526                 bwait(bp, PRIBIO, "biord");
4527         else
4528                 bwait(bp, PRIBIO, "biowr");
4529         if (bp->b_flags & B_EINTR) {
4530                 bp->b_flags &= ~B_EINTR;
4531                 return (EINTR);
4532         }
4533         if (bp->b_ioflags & BIO_ERROR) {
4534                 return (bp->b_error ? bp->b_error : EIO);
4535         } else {
4536                 return (0);
4537         }
4538 }
4539
4540 /*
4541  *      bufdone:
4542  *
4543  *      Finish I/O on a buffer, optionally calling a completion function.
4544  *      This is usually called from an interrupt so process blocking is
4545  *      not allowed.
4546  *
4547  *      biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4548  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
4549  *      assuming B_INVAL is clear.
4550  *
4551  *      For the VMIO case, we set B_CACHE if the op was a read and no
4552  *      read error occurred, or if the op was a write.  B_CACHE is never
4553  *      set if the buffer is invalid or otherwise uncacheable.
4554  *
4555  *      bufdone does not mess with B_INVAL, allowing the I/O routine or the
4556  *      initiator to leave B_INVAL set to brelse the buffer out of existence
4557  *      in the biodone routine.
4558  */
4559 void
4560 bufdone(struct buf *bp)
4561 {
4562         struct bufobj *dropobj;
4563         void    (*biodone)(struct buf *);
4564
4565         buf_track(bp, __func__);
4566         CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4567         dropobj = NULL;
4568
4569         KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4570
4571         runningbufwakeup(bp);
4572         if (bp->b_iocmd == BIO_WRITE)
4573                 dropobj = bp->b_bufobj;
4574         /* call optional completion function if requested */
4575         if (bp->b_iodone != NULL) {
4576                 biodone = bp->b_iodone;
4577                 bp->b_iodone = NULL;
4578                 (*biodone) (bp);
4579                 if (dropobj)
4580                         bufobj_wdrop(dropobj);
4581                 return;
4582         }
4583         if (bp->b_flags & B_VMIO) {
4584                 /*
4585                  * Set B_CACHE if the op was a normal read and no error
4586                  * occurred.  B_CACHE is set for writes in the b*write()
4587                  * routines.
4588                  */
4589                 if (bp->b_iocmd == BIO_READ &&
4590                     !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4591                     !(bp->b_ioflags & BIO_ERROR))
4592                         bp->b_flags |= B_CACHE;
4593                 vfs_vmio_iodone(bp);
4594         }
4595         if (!LIST_EMPTY(&bp->b_dep))
4596                 buf_complete(bp);
4597         if ((bp->b_flags & B_CKHASH) != 0) {
4598                 KASSERT(bp->b_iocmd == BIO_READ,
4599                     ("bufdone: b_iocmd %d not BIO_READ", bp->b_iocmd));
4600                 KASSERT(buf_mapped(bp), ("bufdone: bp %p not mapped", bp));
4601                 (*bp->b_ckhashcalc)(bp);
4602         }
4603         /*
4604          * For asynchronous completions, release the buffer now. The brelse
4605          * will do a wakeup there if necessary - so no need to do a wakeup
4606          * here in the async case. The sync case always needs to do a wakeup.
4607          */
4608         if (bp->b_flags & B_ASYNC) {
4609                 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4610                     (bp->b_ioflags & BIO_ERROR))
4611                         brelse(bp);
4612                 else
4613                         bqrelse(bp);
4614         } else
4615                 bdone(bp);
4616         if (dropobj)
4617                 bufobj_wdrop(dropobj);
4618 }
4619
4620 /*
4621  * This routine is called in lieu of iodone in the case of
4622  * incomplete I/O.  This keeps the busy status for pages
4623  * consistent.
4624  */
4625 void
4626 vfs_unbusy_pages(struct buf *bp)
4627 {
4628         int i;
4629         vm_object_t obj;
4630         vm_page_t m;
4631
4632         runningbufwakeup(bp);
4633         if (!(bp->b_flags & B_VMIO))
4634                 return;
4635
4636         obj = bp->b_bufobj->bo_object;
4637         for (i = 0; i < bp->b_npages; i++) {
4638                 m = bp->b_pages[i];
4639                 if (m == bogus_page) {
4640                         m = vm_page_relookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4641                         if (!m)
4642                                 panic("vfs_unbusy_pages: page missing\n");
4643                         bp->b_pages[i] = m;
4644                         if (buf_mapped(bp)) {
4645                                 BUF_CHECK_MAPPED(bp);
4646                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4647                                     bp->b_pages, bp->b_npages);
4648                         } else
4649                                 BUF_CHECK_UNMAPPED(bp);
4650                 }
4651                 vm_page_sunbusy(m);
4652         }
4653         vm_object_pip_wakeupn(obj, bp->b_npages);
4654 }
4655
4656 /*
4657  * vfs_page_set_valid:
4658  *
4659  *      Set the valid bits in a page based on the supplied offset.   The
4660  *      range is restricted to the buffer's size.
4661  *
4662  *      This routine is typically called after a read completes.
4663  */
4664 static void
4665 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4666 {
4667         vm_ooffset_t eoff;
4668
4669         /*
4670          * Compute the end offset, eoff, such that [off, eoff) does not span a
4671          * page boundary and eoff is not greater than the end of the buffer.
4672          * The end of the buffer, in this case, is our file EOF, not the
4673          * allocation size of the buffer.
4674          */
4675         eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4676         if (eoff > bp->b_offset + bp->b_bcount)
4677                 eoff = bp->b_offset + bp->b_bcount;
4678
4679         /*
4680          * Set valid range.  This is typically the entire buffer and thus the
4681          * entire page.
4682          */
4683         if (eoff > off)
4684                 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4685 }
4686
4687 /*
4688  * vfs_page_set_validclean:
4689  *
4690  *      Set the valid bits and clear the dirty bits in a page based on the
4691  *      supplied offset.   The range is restricted to the buffer's size.
4692  */
4693 static void
4694 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4695 {
4696         vm_ooffset_t soff, eoff;
4697
4698         /*
4699          * Start and end offsets in buffer.  eoff - soff may not cross a
4700          * page boundary or cross the end of the buffer.  The end of the
4701          * buffer, in this case, is our file EOF, not the allocation size
4702          * of the buffer.
4703          */
4704         soff = off;
4705         eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4706         if (eoff > bp->b_offset + bp->b_bcount)
4707                 eoff = bp->b_offset + bp->b_bcount;
4708
4709         /*
4710          * Set valid range.  This is typically the entire buffer and thus the
4711          * entire page.
4712          */
4713         if (eoff > soff) {
4714                 vm_page_set_validclean(
4715                     m,
4716                    (vm_offset_t) (soff & PAGE_MASK),
4717                    (vm_offset_t) (eoff - soff)
4718                 );
4719         }
4720 }
4721
4722 /*
4723  * Acquire a shared busy on all pages in the buf.
4724  */
4725 void
4726 vfs_busy_pages_acquire(struct buf *bp)
4727 {
4728         int i;
4729
4730         for (i = 0; i < bp->b_npages; i++)
4731                 vm_page_busy_acquire(bp->b_pages[i], VM_ALLOC_SBUSY);
4732 }
4733
4734 void
4735 vfs_busy_pages_release(struct buf *bp)
4736 {
4737         int i;
4738
4739         for (i = 0; i < bp->b_npages; i++)
4740                 vm_page_sunbusy(bp->b_pages[i]);
4741 }
4742
4743 /*
4744  * This routine is called before a device strategy routine.
4745  * It is used to tell the VM system that paging I/O is in
4746  * progress, and treat the pages associated with the buffer
4747  * almost as being exclusive busy.  Also the object paging_in_progress
4748  * flag is handled to make sure that the object doesn't become
4749  * inconsistent.
4750  *
4751  * Since I/O has not been initiated yet, certain buffer flags
4752  * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4753  * and should be ignored.
4754  */
4755 void
4756 vfs_busy_pages(struct buf *bp, int clear_modify)
4757 {
4758         vm_object_t obj;
4759         vm_ooffset_t foff;
4760         vm_page_t m;
4761         int i;
4762         bool bogus;
4763
4764         if (!(bp->b_flags & B_VMIO))
4765                 return;
4766
4767         obj = bp->b_bufobj->bo_object;
4768         foff = bp->b_offset;
4769         KASSERT(bp->b_offset != NOOFFSET,
4770             ("vfs_busy_pages: no buffer offset"));
4771         if ((bp->b_flags & B_CLUSTER) == 0) {
4772                 vm_object_pip_add(obj, bp->b_npages);
4773                 vfs_busy_pages_acquire(bp);
4774         }
4775         if (bp->b_bufsize != 0)
4776                 vfs_setdirty_range(bp);
4777         bogus = false;
4778         for (i = 0; i < bp->b_npages; i++) {
4779                 m = bp->b_pages[i];
4780                 vm_page_assert_sbusied(m);
4781
4782                 /*
4783                  * When readying a buffer for a read ( i.e
4784                  * clear_modify == 0 ), it is important to do
4785                  * bogus_page replacement for valid pages in 
4786                  * partially instantiated buffers.  Partially 
4787                  * instantiated buffers can, in turn, occur when
4788                  * reconstituting a buffer from its VM backing store
4789                  * base.  We only have to do this if B_CACHE is
4790                  * clear ( which causes the I/O to occur in the
4791                  * first place ).  The replacement prevents the read
4792                  * I/O from overwriting potentially dirty VM-backed
4793                  * pages.  XXX bogus page replacement is, uh, bogus.
4794                  * It may not work properly with small-block devices.
4795                  * We need to find a better way.
4796                  */
4797                 if (clear_modify) {
4798                         pmap_remove_write(m);
4799                         vfs_page_set_validclean(bp, foff, m);
4800                 } else if (vm_page_all_valid(m) &&
4801                     (bp->b_flags & B_CACHE) == 0) {
4802                         bp->b_pages[i] = bogus_page;
4803                         bogus = true;
4804                 }
4805                 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4806         }
4807         if (bogus && buf_mapped(bp)) {
4808                 BUF_CHECK_MAPPED(bp);
4809                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4810                     bp->b_pages, bp->b_npages);
4811         }
4812 }
4813
4814 /*
4815  *      vfs_bio_set_valid:
4816  *
4817  *      Set the range within the buffer to valid.  The range is
4818  *      relative to the beginning of the buffer, b_offset.  Note that
4819  *      b_offset itself may be offset from the beginning of the first
4820  *      page.
4821  */
4822 void
4823 vfs_bio_set_valid(struct buf *bp, int base, int size)
4824 {
4825         int i, n;
4826         vm_page_t m;
4827
4828         if (!(bp->b_flags & B_VMIO))
4829                 return;
4830
4831         /*
4832          * Fixup base to be relative to beginning of first page.
4833          * Set initial n to be the maximum number of bytes in the
4834          * first page that can be validated.
4835          */
4836         base += (bp->b_offset & PAGE_MASK);
4837         n = PAGE_SIZE - (base & PAGE_MASK);
4838
4839         /*
4840          * Busy may not be strictly necessary here because the pages are
4841          * unlikely to be fully valid and the vnode lock will synchronize
4842          * their access via getpages.  It is grabbed for consistency with
4843          * other page validation.
4844          */
4845         vfs_busy_pages_acquire(bp);
4846         for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4847                 m = bp->b_pages[i];
4848                 if (n > size)
4849                         n = size;
4850                 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4851                 base += n;
4852                 size -= n;
4853                 n = PAGE_SIZE;
4854         }
4855         vfs_busy_pages_release(bp);
4856 }
4857
4858 /*
4859  *      vfs_bio_clrbuf:
4860  *
4861  *      If the specified buffer is a non-VMIO buffer, clear the entire
4862  *      buffer.  If the specified buffer is a VMIO buffer, clear and
4863  *      validate only the previously invalid portions of the buffer.
4864  *      This routine essentially fakes an I/O, so we need to clear
4865  *      BIO_ERROR and B_INVAL.
4866  *
4867  *      Note that while we only theoretically need to clear through b_bcount,
4868  *      we go ahead and clear through b_bufsize.
4869  */
4870 void
4871 vfs_bio_clrbuf(struct buf *bp) 
4872 {
4873         int i, j, sa, ea, slide, zbits;
4874         vm_page_bits_t mask;
4875
4876         if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4877                 clrbuf(bp);
4878                 return;
4879         }
4880         bp->b_flags &= ~B_INVAL;
4881         bp->b_ioflags &= ~BIO_ERROR;
4882         vfs_busy_pages_acquire(bp);
4883         sa = bp->b_offset & PAGE_MASK;
4884         slide = 0;
4885         for (i = 0; i < bp->b_npages; i++, sa = 0) {
4886                 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4887                 ea = slide & PAGE_MASK;
4888                 if (ea == 0)
4889                         ea = PAGE_SIZE;
4890                 if (bp->b_pages[i] == bogus_page)
4891                         continue;
4892                 j = sa / DEV_BSIZE;
4893                 zbits = (sizeof(vm_page_bits_t) * NBBY) -
4894                     (ea - sa) / DEV_BSIZE;
4895                 mask = (VM_PAGE_BITS_ALL >> zbits) << j;
4896                 if ((bp->b_pages[i]->valid & mask) == mask)
4897                         continue;
4898                 if ((bp->b_pages[i]->valid & mask) == 0)
4899                         pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4900                 else {
4901                         for (; sa < ea; sa += DEV_BSIZE, j++) {
4902                                 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4903                                         pmap_zero_page_area(bp->b_pages[i],
4904                                             sa, DEV_BSIZE);
4905                                 }
4906                         }
4907                 }
4908                 vm_page_set_valid_range(bp->b_pages[i], j * DEV_BSIZE,
4909                     roundup2(ea - sa, DEV_BSIZE));
4910         }
4911         vfs_busy_pages_release(bp);
4912         bp->b_resid = 0;
4913 }
4914
4915 void
4916 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4917 {
4918         vm_page_t m;
4919         int i, n;
4920
4921         if (buf_mapped(bp)) {
4922                 BUF_CHECK_MAPPED(bp);
4923                 bzero(bp->b_data + base, size);
4924         } else {
4925                 BUF_CHECK_UNMAPPED(bp);
4926                 n = PAGE_SIZE - (base & PAGE_MASK);
4927                 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4928                         m = bp->b_pages[i];
4929                         if (n > size)
4930                                 n = size;
4931                         pmap_zero_page_area(m, base & PAGE_MASK, n);
4932                         base += n;
4933                         size -= n;
4934                         n = PAGE_SIZE;
4935                 }
4936         }
4937 }
4938
4939 /*
4940  * Update buffer flags based on I/O request parameters, optionally releasing the
4941  * buffer.  If it's VMIO or direct I/O, the buffer pages are released to the VM,
4942  * where they may be placed on a page queue (VMIO) or freed immediately (direct
4943  * I/O).  Otherwise the buffer is released to the cache.
4944  */
4945 static void
4946 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4947 {
4948
4949         KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4950             ("buf %p non-VMIO noreuse", bp));
4951
4952         if ((ioflag & IO_DIRECT) != 0)
4953                 bp->b_flags |= B_DIRECT;
4954         if ((ioflag & IO_EXT) != 0)
4955                 bp->b_xflags |= BX_ALTDATA;
4956         if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4957                 bp->b_flags |= B_RELBUF;
4958                 if ((ioflag & IO_NOREUSE) != 0)
4959                         bp->b_flags |= B_NOREUSE;
4960                 if (release)
4961                         brelse(bp);
4962         } else if (release)
4963                 bqrelse(bp);
4964 }
4965
4966 void
4967 vfs_bio_brelse(struct buf *bp, int ioflag)
4968 {
4969
4970         b_io_dismiss(bp, ioflag, true);
4971 }
4972
4973 void
4974 vfs_bio_set_flags(struct buf *bp, int ioflag)
4975 {
4976
4977         b_io_dismiss(bp, ioflag, false);
4978 }
4979
4980 /*
4981  * vm_hold_load_pages and vm_hold_free_pages get pages into
4982  * a buffers address space.  The pages are anonymous and are
4983  * not associated with a file object.
4984  */
4985 static void
4986 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4987 {
4988         vm_offset_t pg;
4989         vm_page_t p;
4990         int index;
4991
4992         BUF_CHECK_MAPPED(bp);
4993
4994         to = round_page(to);
4995         from = round_page(from);
4996         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4997         MPASS((bp->b_flags & B_MAXPHYS) == 0);
4998         KASSERT(to - from <= maxbcachebuf,
4999             ("vm_hold_load_pages too large %p %#jx %#jx %u",
5000             bp, (uintmax_t)from, (uintmax_t)to, maxbcachebuf));
5001
5002         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
5003                 /*
5004                  * note: must allocate system pages since blocking here
5005                  * could interfere with paging I/O, no matter which
5006                  * process we are.
5007                  */
5008                 p = vm_page_alloc_noobj(VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
5009                     VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) | VM_ALLOC_WAITOK);
5010                 pmap_qenter(pg, &p, 1);
5011                 bp->b_pages[index] = p;
5012         }
5013         bp->b_npages = index;
5014 }
5015
5016 /* Return pages associated with this buf to the vm system */
5017 static void
5018 vm_hold_free_pages(struct buf *bp, int newbsize)
5019 {
5020         vm_offset_t from;
5021         vm_page_t p;
5022         int index, newnpages;
5023
5024         BUF_CHECK_MAPPED(bp);
5025
5026         from = round_page((vm_offset_t)bp->b_data + newbsize);
5027         newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
5028         if (bp->b_npages > newnpages)
5029                 pmap_qremove(from, bp->b_npages - newnpages);
5030         for (index = newnpages; index < bp->b_npages; index++) {
5031                 p = bp->b_pages[index];
5032                 bp->b_pages[index] = NULL;
5033                 vm_page_unwire_noq(p);
5034                 vm_page_free(p);
5035         }
5036         bp->b_npages = newnpages;
5037 }
5038
5039 /*
5040  * Map an IO request into kernel virtual address space.
5041  *
5042  * All requests are (re)mapped into kernel VA space.
5043  * Notice that we use b_bufsize for the size of the buffer
5044  * to be mapped.  b_bcount might be modified by the driver.
5045  *
5046  * Note that even if the caller determines that the address space should
5047  * be valid, a race or a smaller-file mapped into a larger space may
5048  * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
5049  * check the return value.
5050  *
5051  * This function only works with pager buffers.
5052  */
5053 int
5054 vmapbuf(struct buf *bp, void *uaddr, size_t len, int mapbuf)
5055 {
5056         vm_prot_t prot;
5057         int pidx;
5058
5059         MPASS((bp->b_flags & B_MAXPHYS) != 0);
5060         prot = VM_PROT_READ;
5061         if (bp->b_iocmd == BIO_READ)
5062                 prot |= VM_PROT_WRITE;  /* Less backwards than it looks */
5063         pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
5064             (vm_offset_t)uaddr, len, prot, bp->b_pages, PBUF_PAGES);
5065         if (pidx < 0)
5066                 return (-1);
5067         bp->b_bufsize = len;
5068         bp->b_npages = pidx;
5069         bp->b_offset = ((vm_offset_t)uaddr) & PAGE_MASK;
5070         if (mapbuf || !unmapped_buf_allowed) {
5071                 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
5072                 bp->b_data = bp->b_kvabase + bp->b_offset;
5073         } else
5074                 bp->b_data = unmapped_buf;
5075         return (0);
5076 }
5077
5078 /*
5079  * Free the io map PTEs associated with this IO operation.
5080  * We also invalidate the TLB entries and restore the original b_addr.
5081  *
5082  * This function only works with pager buffers.
5083  */
5084 void
5085 vunmapbuf(struct buf *bp)
5086 {
5087         int npages;
5088
5089         npages = bp->b_npages;
5090         if (buf_mapped(bp))
5091                 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
5092         vm_page_unhold_pages(bp->b_pages, npages);
5093
5094         bp->b_data = unmapped_buf;
5095 }
5096
5097 void
5098 bdone(struct buf *bp)
5099 {
5100         struct mtx *mtxp;
5101
5102         mtxp = mtx_pool_find(mtxpool_sleep, bp);
5103         mtx_lock(mtxp);
5104         bp->b_flags |= B_DONE;
5105         wakeup(bp);
5106         mtx_unlock(mtxp);
5107 }
5108
5109 void
5110 bwait(struct buf *bp, u_char pri, const char *wchan)
5111 {
5112         struct mtx *mtxp;
5113
5114         mtxp = mtx_pool_find(mtxpool_sleep, bp);
5115         mtx_lock(mtxp);
5116         while ((bp->b_flags & B_DONE) == 0)
5117                 msleep(bp, mtxp, pri, wchan, 0);
5118         mtx_unlock(mtxp);
5119 }
5120
5121 int
5122 bufsync(struct bufobj *bo, int waitfor)
5123 {
5124
5125         return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
5126 }
5127
5128 void
5129 bufstrategy(struct bufobj *bo, struct buf *bp)
5130 {
5131         int i __unused;
5132         struct vnode *vp;
5133
5134         vp = bp->b_vp;
5135         KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
5136         KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
5137             ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
5138         i = VOP_STRATEGY(vp, bp);
5139         KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
5140 }
5141
5142 /*
5143  * Initialize a struct bufobj before use.  Memory is assumed zero filled.
5144  */
5145 void
5146 bufobj_init(struct bufobj *bo, void *private)
5147 {
5148         static volatile int bufobj_cleanq;
5149
5150         bo->bo_domain =
5151             atomic_fetchadd_int(&bufobj_cleanq, 1) % buf_domains;
5152         rw_init(BO_LOCKPTR(bo), "bufobj interlock");
5153         bo->bo_private = private;
5154         TAILQ_INIT(&bo->bo_clean.bv_hd);
5155         pctrie_init(&bo->bo_clean.bv_root);
5156         TAILQ_INIT(&bo->bo_dirty.bv_hd);
5157         pctrie_init(&bo->bo_dirty.bv_root);
5158 }
5159
5160 void
5161 bufobj_wrefl(struct bufobj *bo)
5162 {
5163
5164         KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5165         ASSERT_BO_WLOCKED(bo);
5166         bo->bo_numoutput++;
5167 }
5168
5169 void
5170 bufobj_wref(struct bufobj *bo)
5171 {
5172
5173         KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5174         BO_LOCK(bo);
5175         bo->bo_numoutput++;
5176         BO_UNLOCK(bo);
5177 }
5178
5179 void
5180 bufobj_wdrop(struct bufobj *bo)
5181 {
5182
5183         KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
5184         BO_LOCK(bo);
5185         KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
5186         if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
5187                 bo->bo_flag &= ~BO_WWAIT;
5188                 wakeup(&bo->bo_numoutput);
5189         }
5190         BO_UNLOCK(bo);
5191 }
5192
5193 int
5194 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
5195 {
5196         int error;
5197
5198         KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
5199         ASSERT_BO_WLOCKED(bo);
5200         error = 0;
5201         while (bo->bo_numoutput) {
5202                 bo->bo_flag |= BO_WWAIT;
5203                 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
5204                     slpflag | (PRIBIO + 1), "bo_wwait", timeo);
5205                 if (error)
5206                         break;
5207         }
5208         return (error);
5209 }
5210
5211 /*
5212  * Set bio_data or bio_ma for struct bio from the struct buf.
5213  */
5214 void
5215 bdata2bio(struct buf *bp, struct bio *bip)
5216 {
5217
5218         if (!buf_mapped(bp)) {
5219                 KASSERT(unmapped_buf_allowed, ("unmapped"));
5220                 bip->bio_ma = bp->b_pages;
5221                 bip->bio_ma_n = bp->b_npages;
5222                 bip->bio_data = unmapped_buf;
5223                 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
5224                 bip->bio_flags |= BIO_UNMAPPED;
5225                 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
5226                     PAGE_SIZE == bp->b_npages,
5227                     ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
5228                     (long long)bip->bio_length, bip->bio_ma_n));
5229         } else {
5230                 bip->bio_data = bp->b_data;
5231                 bip->bio_ma = NULL;
5232         }
5233 }
5234
5235 struct memdesc
5236 memdesc_bio(struct bio *bio)
5237 {
5238         if ((bio->bio_flags & BIO_VLIST) != 0)
5239                 return (memdesc_vlist((struct bus_dma_segment *)bio->bio_data,
5240                     bio->bio_ma_n));
5241
5242         if ((bio->bio_flags & BIO_UNMAPPED) != 0)
5243                 return (memdesc_vmpages(bio->bio_ma, bio->bio_bcount,
5244                     bio->bio_ma_offset));
5245
5246         return (memdesc_vaddr(bio->bio_data, bio->bio_bcount));
5247 }
5248
5249 static int buf_pager_relbuf;
5250 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
5251     &buf_pager_relbuf, 0,
5252     "Make buffer pager release buffers after reading");
5253
5254 /*
5255  * The buffer pager.  It uses buffer reads to validate pages.
5256  *
5257  * In contrast to the generic local pager from vm/vnode_pager.c, this
5258  * pager correctly and easily handles volumes where the underlying
5259  * device block size is greater than the machine page size.  The
5260  * buffer cache transparently extends the requested page run to be
5261  * aligned at the block boundary, and does the necessary bogus page
5262  * replacements in the addends to avoid obliterating already valid
5263  * pages.
5264  *
5265  * The only non-trivial issue is that the exclusive busy state for
5266  * pages, which is assumed by the vm_pager_getpages() interface, is
5267  * incompatible with the VMIO buffer cache's desire to share-busy the
5268  * pages.  This function performs a trivial downgrade of the pages'
5269  * state before reading buffers, and a less trivial upgrade from the
5270  * shared-busy to excl-busy state after the read.
5271  */
5272 int
5273 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
5274     int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
5275     vbg_get_blksize_t get_blksize)
5276 {
5277         vm_page_t m;
5278         vm_object_t object;
5279         struct buf *bp;
5280         struct mount *mp;
5281         daddr_t lbn, lbnp;
5282         vm_ooffset_t la, lb, poff, poffe;
5283         long bo_bs, bsize;
5284         int br_flags, error, i, pgsin, pgsin_a, pgsin_b;
5285         bool redo, lpart;
5286
5287         object = vp->v_object;
5288         mp = vp->v_mount;
5289         error = 0;
5290         la = IDX_TO_OFF(ma[count - 1]->pindex);
5291         if (la >= object->un_pager.vnp.vnp_size)
5292                 return (VM_PAGER_BAD);
5293
5294         /*
5295          * Change the meaning of la from where the last requested page starts
5296          * to where it ends, because that's the end of the requested region
5297          * and the start of the potential read-ahead region.
5298          */
5299         la += PAGE_SIZE;
5300         lpart = la > object->un_pager.vnp.vnp_size;
5301         error = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)),
5302             &bo_bs);
5303         if (error != 0)
5304                 return (VM_PAGER_ERROR);
5305
5306         /*
5307          * Calculate read-ahead, behind and total pages.
5308          */
5309         pgsin = count;
5310         lb = IDX_TO_OFF(ma[0]->pindex);
5311         pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
5312         pgsin += pgsin_b;
5313         if (rbehind != NULL)
5314                 *rbehind = pgsin_b;
5315         pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
5316         if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
5317                 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
5318                     PAGE_SIZE) - la);
5319         pgsin += pgsin_a;
5320         if (rahead != NULL)
5321                 *rahead = pgsin_a;
5322         VM_CNT_INC(v_vnodein);
5323         VM_CNT_ADD(v_vnodepgsin, pgsin);
5324
5325         br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
5326             != 0) ? GB_UNMAPPED : 0;
5327 again:
5328         for (i = 0; i < count; i++) {
5329                 if (ma[i] != bogus_page)
5330                         vm_page_busy_downgrade(ma[i]);
5331         }
5332
5333         lbnp = -1;
5334         for (i = 0; i < count; i++) {
5335                 m = ma[i];
5336                 if (m == bogus_page)
5337                         continue;
5338
5339                 /*
5340                  * Pages are shared busy and the object lock is not
5341                  * owned, which together allow for the pages'
5342                  * invalidation.  The racy test for validity avoids
5343                  * useless creation of the buffer for the most typical
5344                  * case when invalidation is not used in redo or for
5345                  * parallel read.  The shared->excl upgrade loop at
5346                  * the end of the function catches the race in a
5347                  * reliable way (protected by the object lock).
5348                  */
5349                 if (vm_page_all_valid(m))
5350                         continue;
5351
5352                 poff = IDX_TO_OFF(m->pindex);
5353                 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
5354                 for (; poff < poffe; poff += bsize) {
5355                         lbn = get_lblkno(vp, poff);
5356                         if (lbn == lbnp)
5357                                 goto next_page;
5358                         lbnp = lbn;
5359
5360                         error = get_blksize(vp, lbn, &bsize);
5361                         if (error == 0)
5362                                 error = bread_gb(vp, lbn, bsize,
5363                                     curthread->td_ucred, br_flags, &bp);
5364                         if (error != 0)
5365                                 goto end_pages;
5366                         if (bp->b_rcred == curthread->td_ucred) {
5367                                 crfree(bp->b_rcred);
5368                                 bp->b_rcred = NOCRED;
5369                         }
5370                         if (LIST_EMPTY(&bp->b_dep)) {
5371                                 /*
5372                                  * Invalidation clears m->valid, but
5373                                  * may leave B_CACHE flag if the
5374                                  * buffer existed at the invalidation
5375                                  * time.  In this case, recycle the
5376                                  * buffer to do real read on next
5377                                  * bread() after redo.
5378                                  *
5379                                  * Otherwise B_RELBUF is not strictly
5380                                  * necessary, enable to reduce buf
5381                                  * cache pressure.
5382                                  */
5383                                 if (buf_pager_relbuf ||
5384                                     !vm_page_all_valid(m))
5385                                         bp->b_flags |= B_RELBUF;
5386
5387                                 bp->b_flags &= ~B_NOCACHE;
5388                                 brelse(bp);
5389                         } else {
5390                                 bqrelse(bp);
5391                         }
5392                 }
5393                 KASSERT(1 /* racy, enable for debugging */ ||
5394                     vm_page_all_valid(m) || i == count - 1,
5395                     ("buf %d %p invalid", i, m));
5396                 if (i == count - 1 && lpart) {
5397                         if (!vm_page_none_valid(m) &&
5398                             !vm_page_all_valid(m))
5399                                 vm_page_zero_invalid(m, TRUE);
5400                 }
5401 next_page:;
5402         }
5403 end_pages:
5404
5405         redo = false;
5406         for (i = 0; i < count; i++) {
5407                 if (ma[i] == bogus_page)
5408                         continue;
5409                 if (vm_page_busy_tryupgrade(ma[i]) == 0) {
5410                         vm_page_sunbusy(ma[i]);
5411                         ma[i] = vm_page_grab_unlocked(object, ma[i]->pindex,
5412                             VM_ALLOC_NORMAL);
5413                 }
5414
5415                 /*
5416                  * Since the pages were only sbusy while neither the
5417                  * buffer nor the object lock was held by us, or
5418                  * reallocated while vm_page_grab() slept for busy
5419                  * relinguish, they could have been invalidated.
5420                  * Recheck the valid bits and re-read as needed.
5421                  *
5422                  * Note that the last page is made fully valid in the
5423                  * read loop, and partial validity for the page at
5424                  * index count - 1 could mean that the page was
5425                  * invalidated or removed, so we must restart for
5426                  * safety as well.
5427                  */
5428                 if (!vm_page_all_valid(ma[i]))
5429                         redo = true;
5430         }
5431         if (redo && error == 0)
5432                 goto again;
5433         return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
5434 }
5435
5436 #include "opt_ddb.h"
5437 #ifdef DDB
5438 #include <ddb/ddb.h>
5439
5440 /* DDB command to show buffer data */
5441 DB_SHOW_COMMAND(buffer, db_show_buffer)
5442 {
5443         /* get args */
5444         struct buf *bp = (struct buf *)addr;
5445 #ifdef FULL_BUF_TRACKING
5446         uint32_t i, j;
5447 #endif
5448
5449         if (!have_addr) {
5450                 db_printf("usage: show buffer <addr>\n");
5451                 return;
5452         }
5453
5454         db_printf("buf at %p\n", bp);
5455         db_printf("b_flags = 0x%b, b_xflags=0x%b\n",
5456             (u_int)bp->b_flags, PRINT_BUF_FLAGS,
5457             (u_int)bp->b_xflags, PRINT_BUF_XFLAGS);
5458         db_printf("b_vflags=0x%b b_ioflags0x%b\n",
5459             (u_int)bp->b_vflags, PRINT_BUF_VFLAGS,
5460             (u_int)bp->b_ioflags, PRINT_BIO_FLAGS);
5461         db_printf(
5462             "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
5463             "b_bufobj = (%p), b_data = %p\n, b_blkno = %jd, b_lblkno = %jd, "
5464             "b_vp = %p, b_dep = %p\n",
5465             bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
5466             bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
5467             (intmax_t)bp->b_lblkno, bp->b_vp, bp->b_dep.lh_first);
5468         db_printf("b_kvabase = %p, b_kvasize = %d\n",
5469             bp->b_kvabase, bp->b_kvasize);
5470         if (bp->b_npages) {
5471                 int i;
5472                 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
5473                 for (i = 0; i < bp->b_npages; i++) {
5474                         vm_page_t m;
5475                         m = bp->b_pages[i];
5476                         if (m != NULL)
5477                                 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
5478                                     (u_long)m->pindex,
5479                                     (u_long)VM_PAGE_TO_PHYS(m));
5480                         else
5481                                 db_printf("( ??? )");
5482                         if ((i + 1) < bp->b_npages)
5483                                 db_printf(",");
5484                 }
5485                 db_printf("\n");
5486         }
5487         BUF_LOCKPRINTINFO(bp);
5488 #if defined(FULL_BUF_TRACKING)
5489         db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
5490
5491         i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
5492         for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
5493                 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
5494                         continue;
5495                 db_printf(" %2u: %s\n", j,
5496                     bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
5497         }
5498 #elif defined(BUF_TRACKING)
5499         db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
5500 #endif
5501         db_printf(" ");
5502 }
5503
5504 DB_SHOW_COMMAND_FLAGS(bufqueues, bufqueues, DB_CMD_MEMSAFE)
5505 {
5506         struct bufdomain *bd;
5507         struct buf *bp;
5508         long total;
5509         int i, j, cnt;
5510
5511         db_printf("bqempty: %d\n", bqempty.bq_len);
5512
5513         for (i = 0; i < buf_domains; i++) {
5514                 bd = &bdomain[i];
5515                 db_printf("Buf domain %d\n", i);
5516                 db_printf("\tfreebufs\t%d\n", bd->bd_freebuffers);
5517                 db_printf("\tlofreebufs\t%d\n", bd->bd_lofreebuffers);
5518                 db_printf("\thifreebufs\t%d\n", bd->bd_hifreebuffers);
5519                 db_printf("\n");
5520                 db_printf("\tbufspace\t%ld\n", bd->bd_bufspace);
5521                 db_printf("\tmaxbufspace\t%ld\n", bd->bd_maxbufspace);
5522                 db_printf("\thibufspace\t%ld\n", bd->bd_hibufspace);
5523                 db_printf("\tlobufspace\t%ld\n", bd->bd_lobufspace);
5524                 db_printf("\tbufspacethresh\t%ld\n", bd->bd_bufspacethresh);
5525                 db_printf("\n");
5526                 db_printf("\tnumdirtybuffers\t%d\n", bd->bd_numdirtybuffers);
5527                 db_printf("\tlodirtybuffers\t%d\n", bd->bd_lodirtybuffers);
5528                 db_printf("\thidirtybuffers\t%d\n", bd->bd_hidirtybuffers);
5529                 db_printf("\tdirtybufthresh\t%d\n", bd->bd_dirtybufthresh);
5530                 db_printf("\n");
5531                 total = 0;
5532                 TAILQ_FOREACH(bp, &bd->bd_cleanq->bq_queue, b_freelist)
5533                         total += bp->b_bufsize;
5534                 db_printf("\tcleanq count\t%d (%ld)\n",
5535                     bd->bd_cleanq->bq_len, total);
5536                 total = 0;
5537                 TAILQ_FOREACH(bp, &bd->bd_dirtyq.bq_queue, b_freelist)
5538                         total += bp->b_bufsize;
5539                 db_printf("\tdirtyq count\t%d (%ld)\n",
5540                     bd->bd_dirtyq.bq_len, total);
5541                 db_printf("\twakeup\t\t%d\n", bd->bd_wanted);
5542                 db_printf("\tlim\t\t%d\n", bd->bd_lim);
5543                 db_printf("\tCPU ");
5544                 for (j = 0; j <= mp_maxid; j++)
5545                         db_printf("%d, ", bd->bd_subq[j].bq_len);
5546                 db_printf("\n");
5547                 cnt = 0;
5548                 total = 0;
5549                 for (j = 0; j < nbuf; j++) {
5550                         bp = nbufp(j);
5551                         if (bp->b_domain == i && BUF_ISLOCKED(bp)) {
5552                                 cnt++;
5553                                 total += bp->b_bufsize;
5554                         }
5555                 }
5556                 db_printf("\tLocked buffers: %d space %ld\n", cnt, total);
5557                 cnt = 0;
5558                 total = 0;
5559                 for (j = 0; j < nbuf; j++) {
5560                         bp = nbufp(j);
5561                         if (bp->b_domain == i) {
5562                                 cnt++;
5563                                 total += bp->b_bufsize;
5564                         }
5565                 }
5566                 db_printf("\tTotal buffers: %d space %ld\n", cnt, total);
5567         }
5568 }
5569
5570 DB_SHOW_COMMAND_FLAGS(lockedbufs, lockedbufs, DB_CMD_MEMSAFE)
5571 {
5572         struct buf *bp;
5573         int i;
5574
5575         for (i = 0; i < nbuf; i++) {
5576                 bp = nbufp(i);
5577                 if (BUF_ISLOCKED(bp)) {
5578                         db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5579                         db_printf("\n");
5580                         if (db_pager_quit)
5581                                 break;
5582                 }
5583         }
5584 }
5585
5586 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5587 {
5588         struct vnode *vp;
5589         struct buf *bp;
5590
5591         if (!have_addr) {
5592                 db_printf("usage: show vnodebufs <addr>\n");
5593                 return;
5594         }
5595         vp = (struct vnode *)addr;
5596         db_printf("Clean buffers:\n");
5597         TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5598                 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5599                 db_printf("\n");
5600         }
5601         db_printf("Dirty buffers:\n");
5602         TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5603                 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5604                 db_printf("\n");
5605         }
5606 }
5607
5608 DB_COMMAND_FLAGS(countfreebufs, db_coundfreebufs, DB_CMD_MEMSAFE)
5609 {
5610         struct buf *bp;
5611         int i, used = 0, nfree = 0;
5612
5613         if (have_addr) {
5614                 db_printf("usage: countfreebufs\n");
5615                 return;
5616         }
5617
5618         for (i = 0; i < nbuf; i++) {
5619                 bp = nbufp(i);
5620                 if (bp->b_qindex == QUEUE_EMPTY)
5621                         nfree++;
5622                 else
5623                         used++;
5624         }
5625
5626         db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5627             nfree + used);
5628         db_printf("numfreebuffers is %d\n", numfreebuffers);
5629 }
5630 #endif /* DDB */