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