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