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