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