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