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