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