xref: /freebsd/sys/kern/vfs_bio.c (revision a07d59d1daafdaae0d1b1ad1f977f9eda92dc83b)
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, 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 domain, 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_noq(m)) {
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.
2641 			 */
2642 			if ((bp->b_flags & B_NOREUSE) != 0)
2643 				vm_page_deactivate_noreuse(m);
2644 			else if (m->queue == PQ_ACTIVE)
2645 				vm_page_reference(m);
2646 			else if (m->queue != PQ_INACTIVE)
2647 				vm_page_deactivate(m);
2648 			else
2649 				vm_page_requeue(m);
2650 		}
2651 	}
2652 	vm_page_unlock(m);
2653 }
2654 
2655 /*
2656  * Perform page invalidation when a buffer is released.  The fully invalid
2657  * pages will be reclaimed later in vfs_vmio_truncate().
2658  */
2659 static void
2660 vfs_vmio_invalidate(struct buf *bp)
2661 {
2662 	vm_object_t obj;
2663 	vm_page_t m;
2664 	int i, resid, poffset, presid;
2665 
2666 	if (buf_mapped(bp)) {
2667 		BUF_CHECK_MAPPED(bp);
2668 		pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
2669 	} else
2670 		BUF_CHECK_UNMAPPED(bp);
2671 	/*
2672 	 * Get the base offset and length of the buffer.  Note that
2673 	 * in the VMIO case if the buffer block size is not
2674 	 * page-aligned then b_data pointer may not be page-aligned.
2675 	 * But our b_pages[] array *IS* page aligned.
2676 	 *
2677 	 * block sizes less then DEV_BSIZE (usually 512) are not
2678 	 * supported due to the page granularity bits (m->valid,
2679 	 * m->dirty, etc...).
2680 	 *
2681 	 * See man buf(9) for more information
2682 	 */
2683 	obj = bp->b_bufobj->bo_object;
2684 	resid = bp->b_bufsize;
2685 	poffset = bp->b_offset & PAGE_MASK;
2686 	VM_OBJECT_WLOCK(obj);
2687 	for (i = 0; i < bp->b_npages; i++) {
2688 		m = bp->b_pages[i];
2689 		if (m == bogus_page)
2690 			panic("vfs_vmio_invalidate: Unexpected bogus page.");
2691 		bp->b_pages[i] = NULL;
2692 
2693 		presid = resid > (PAGE_SIZE - poffset) ?
2694 		    (PAGE_SIZE - poffset) : resid;
2695 		KASSERT(presid >= 0, ("brelse: extra page"));
2696 		while (vm_page_xbusied(m)) {
2697 			vm_page_lock(m);
2698 			VM_OBJECT_WUNLOCK(obj);
2699 			vm_page_busy_sleep(m, "mbncsh", true);
2700 			VM_OBJECT_WLOCK(obj);
2701 		}
2702 		if (pmap_page_wired_mappings(m) == 0)
2703 			vm_page_set_invalid(m, poffset, presid);
2704 		vfs_vmio_unwire(bp, m);
2705 		resid -= presid;
2706 		poffset = 0;
2707 	}
2708 	VM_OBJECT_WUNLOCK(obj);
2709 	bp->b_npages = 0;
2710 }
2711 
2712 /*
2713  * Page-granular truncation of an existing VMIO buffer.
2714  */
2715 static void
2716 vfs_vmio_truncate(struct buf *bp, int desiredpages)
2717 {
2718 	vm_object_t obj;
2719 	vm_page_t m;
2720 	int i;
2721 
2722 	if (bp->b_npages == desiredpages)
2723 		return;
2724 
2725 	if (buf_mapped(bp)) {
2726 		BUF_CHECK_MAPPED(bp);
2727 		pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
2728 		    (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
2729 	} else
2730 		BUF_CHECK_UNMAPPED(bp);
2731 	obj = bp->b_bufobj->bo_object;
2732 	if (obj != NULL)
2733 		VM_OBJECT_WLOCK(obj);
2734 	for (i = desiredpages; i < bp->b_npages; i++) {
2735 		m = bp->b_pages[i];
2736 		KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
2737 		bp->b_pages[i] = NULL;
2738 		vfs_vmio_unwire(bp, m);
2739 	}
2740 	if (obj != NULL)
2741 		VM_OBJECT_WUNLOCK(obj);
2742 	bp->b_npages = desiredpages;
2743 }
2744 
2745 /*
2746  * Byte granular extension of VMIO buffers.
2747  */
2748 static void
2749 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
2750 {
2751 	/*
2752 	 * We are growing the buffer, possibly in a
2753 	 * byte-granular fashion.
2754 	 */
2755 	vm_object_t obj;
2756 	vm_offset_t toff;
2757 	vm_offset_t tinc;
2758 	vm_page_t m;
2759 
2760 	/*
2761 	 * Step 1, bring in the VM pages from the object, allocating
2762 	 * them if necessary.  We must clear B_CACHE if these pages
2763 	 * are not valid for the range covered by the buffer.
2764 	 */
2765 	obj = bp->b_bufobj->bo_object;
2766 	VM_OBJECT_WLOCK(obj);
2767 	if (bp->b_npages < desiredpages) {
2768 		/*
2769 		 * We must allocate system pages since blocking
2770 		 * here could interfere with paging I/O, no
2771 		 * matter which process we are.
2772 		 *
2773 		 * Only exclusive busy can be tested here.
2774 		 * Blocking on shared busy might lead to
2775 		 * deadlocks once allocbuf() is called after
2776 		 * pages are vfs_busy_pages().
2777 		 */
2778 		(void)vm_page_grab_pages(obj,
2779 		    OFF_TO_IDX(bp->b_offset) + bp->b_npages,
2780 		    VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
2781 		    VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
2782 		    &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
2783 		bp->b_npages = desiredpages;
2784 	}
2785 
2786 	/*
2787 	 * Step 2.  We've loaded the pages into the buffer,
2788 	 * we have to figure out if we can still have B_CACHE
2789 	 * set.  Note that B_CACHE is set according to the
2790 	 * byte-granular range ( bcount and size ), not the
2791 	 * aligned range ( newbsize ).
2792 	 *
2793 	 * The VM test is against m->valid, which is DEV_BSIZE
2794 	 * aligned.  Needless to say, the validity of the data
2795 	 * needs to also be DEV_BSIZE aligned.  Note that this
2796 	 * fails with NFS if the server or some other client
2797 	 * extends the file's EOF.  If our buffer is resized,
2798 	 * B_CACHE may remain set! XXX
2799 	 */
2800 	toff = bp->b_bcount;
2801 	tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2802 	while ((bp->b_flags & B_CACHE) && toff < size) {
2803 		vm_pindex_t pi;
2804 
2805 		if (tinc > (size - toff))
2806 			tinc = size - toff;
2807 		pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
2808 		m = bp->b_pages[pi];
2809 		vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
2810 		toff += tinc;
2811 		tinc = PAGE_SIZE;
2812 	}
2813 	VM_OBJECT_WUNLOCK(obj);
2814 
2815 	/*
2816 	 * Step 3, fixup the KVA pmap.
2817 	 */
2818 	if (buf_mapped(bp))
2819 		bpmap_qenter(bp);
2820 	else
2821 		BUF_CHECK_UNMAPPED(bp);
2822 }
2823 
2824 /*
2825  * Check to see if a block at a particular lbn is available for a clustered
2826  * write.
2827  */
2828 static int
2829 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
2830 {
2831 	struct buf *bpa;
2832 	int match;
2833 
2834 	match = 0;
2835 
2836 	/* If the buf isn't in core skip it */
2837 	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
2838 		return (0);
2839 
2840 	/* If the buf is busy we don't want to wait for it */
2841 	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2842 		return (0);
2843 
2844 	/* Only cluster with valid clusterable delayed write buffers */
2845 	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
2846 	    (B_DELWRI | B_CLUSTEROK))
2847 		goto done;
2848 
2849 	if (bpa->b_bufsize != size)
2850 		goto done;
2851 
2852 	/*
2853 	 * Check to see if it is in the expected place on disk and that the
2854 	 * block has been mapped.
2855 	 */
2856 	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
2857 		match = 1;
2858 done:
2859 	BUF_UNLOCK(bpa);
2860 	return (match);
2861 }
2862 
2863 /*
2864  *	vfs_bio_awrite:
2865  *
2866  *	Implement clustered async writes for clearing out B_DELWRI buffers.
2867  *	This is much better then the old way of writing only one buffer at
2868  *	a time.  Note that we may not be presented with the buffers in the
2869  *	correct order, so we search for the cluster in both directions.
2870  */
2871 int
2872 vfs_bio_awrite(struct buf *bp)
2873 {
2874 	struct bufobj *bo;
2875 	int i;
2876 	int j;
2877 	daddr_t lblkno = bp->b_lblkno;
2878 	struct vnode *vp = bp->b_vp;
2879 	int ncl;
2880 	int nwritten;
2881 	int size;
2882 	int maxcl;
2883 	int gbflags;
2884 
2885 	bo = &vp->v_bufobj;
2886 	gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
2887 	/*
2888 	 * right now we support clustered writing only to regular files.  If
2889 	 * we find a clusterable block we could be in the middle of a cluster
2890 	 * rather then at the beginning.
2891 	 */
2892 	if ((vp->v_type == VREG) &&
2893 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
2894 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2895 
2896 		size = vp->v_mount->mnt_stat.f_iosize;
2897 		maxcl = MAXPHYS / size;
2898 
2899 		BO_RLOCK(bo);
2900 		for (i = 1; i < maxcl; i++)
2901 			if (vfs_bio_clcheck(vp, size, lblkno + i,
2902 			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2903 				break;
2904 
2905 		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2906 			if (vfs_bio_clcheck(vp, size, lblkno - j,
2907 			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2908 				break;
2909 		BO_RUNLOCK(bo);
2910 		--j;
2911 		ncl = i + j;
2912 		/*
2913 		 * this is a possible cluster write
2914 		 */
2915 		if (ncl != 1) {
2916 			BUF_UNLOCK(bp);
2917 			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2918 			    gbflags);
2919 			return (nwritten);
2920 		}
2921 	}
2922 	bremfree(bp);
2923 	bp->b_flags |= B_ASYNC;
2924 	/*
2925 	 * default (old) behavior, writing out only one block
2926 	 *
2927 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
2928 	 */
2929 	nwritten = bp->b_bufsize;
2930 	(void) bwrite(bp);
2931 
2932 	return (nwritten);
2933 }
2934 
2935 /*
2936  *	getnewbuf_kva:
2937  *
2938  *	Allocate KVA for an empty buf header according to gbflags.
2939  */
2940 static int
2941 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
2942 {
2943 
2944 	if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
2945 		/*
2946 		 * In order to keep fragmentation sane we only allocate kva
2947 		 * in BKVASIZE chunks.  XXX with vmem we can do page size.
2948 		 */
2949 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2950 
2951 		if (maxsize != bp->b_kvasize &&
2952 		    bufkva_alloc(bp, maxsize, gbflags))
2953 			return (ENOSPC);
2954 	}
2955 	return (0);
2956 }
2957 
2958 /*
2959  *	getnewbuf:
2960  *
2961  *	Find and initialize a new buffer header, freeing up existing buffers
2962  *	in the bufqueues as necessary.  The new buffer is returned locked.
2963  *
2964  *	We block if:
2965  *		We have insufficient buffer headers
2966  *		We have insufficient buffer space
2967  *		buffer_arena is too fragmented ( space reservation fails )
2968  *		If we have to flush dirty buffers ( but we try to avoid this )
2969  *
2970  *	The caller is responsible for releasing the reserved bufspace after
2971  *	allocbuf() is called.
2972  */
2973 static struct buf *
2974 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
2975 {
2976 	struct buf *bp;
2977 	bool metadata, reserved;
2978 
2979 	bp = NULL;
2980 	KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2981 	    ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2982 	if (!unmapped_buf_allowed)
2983 		gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2984 
2985 	if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2986 	    vp->v_type == VCHR)
2987 		metadata = true;
2988 	else
2989 		metadata = false;
2990 	atomic_add_int(&getnewbufcalls, 1);
2991 	reserved = false;
2992 	do {
2993 		if (reserved == false &&
2994 		    bufspace_reserve(maxsize, metadata) != 0)
2995 			continue;
2996 		reserved = true;
2997 		if ((bp = buf_alloc()) == NULL)
2998 			continue;
2999 		if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
3000 			return (bp);
3001 		break;
3002 	} while(buf_scan(false) == 0);
3003 
3004 	if (reserved)
3005 		atomic_subtract_long(&bufspace, maxsize);
3006 	if (bp != NULL) {
3007 		bp->b_flags |= B_INVAL;
3008 		brelse(bp);
3009 	}
3010 	bufspace_wait(vp, gbflags, slpflag, slptimeo);
3011 
3012 	return (NULL);
3013 }
3014 
3015 /*
3016  *	buf_daemon:
3017  *
3018  *	buffer flushing daemon.  Buffers are normally flushed by the
3019  *	update daemon but if it cannot keep up this process starts to
3020  *	take the load in an attempt to prevent getnewbuf() from blocking.
3021  */
3022 static struct kproc_desc buf_kp = {
3023 	"bufdaemon",
3024 	buf_daemon,
3025 	&bufdaemonproc
3026 };
3027 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3028 
3029 static int
3030 buf_flush(struct vnode *vp, int target)
3031 {
3032 	int flushed;
3033 
3034 	flushed = flushbufqueues(vp, target, 0);
3035 	if (flushed == 0) {
3036 		/*
3037 		 * Could not find any buffers without rollback
3038 		 * dependencies, so just write the first one
3039 		 * in the hopes of eventually making progress.
3040 		 */
3041 		if (vp != NULL && target > 2)
3042 			target /= 2;
3043 		flushbufqueues(vp, target, 1);
3044 	}
3045 	return (flushed);
3046 }
3047 
3048 static void
3049 buf_daemon()
3050 {
3051 	int lodirty;
3052 
3053 	/*
3054 	 * This process needs to be suspended prior to shutdown sync.
3055 	 */
3056 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
3057 	    SHUTDOWN_PRI_LAST);
3058 
3059 	/*
3060 	 * This process is allowed to take the buffer cache to the limit
3061 	 */
3062 	curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3063 	mtx_lock(&bdlock);
3064 	for (;;) {
3065 		bd_request = 0;
3066 		mtx_unlock(&bdlock);
3067 
3068 		kproc_suspend_check(bufdaemonproc);
3069 		lodirty = lodirtybuffers;
3070 		if (bd_speedupreq) {
3071 			lodirty = numdirtybuffers / 2;
3072 			bd_speedupreq = 0;
3073 		}
3074 		/*
3075 		 * Do the flush.  Limit the amount of in-transit I/O we
3076 		 * allow to build up, otherwise we would completely saturate
3077 		 * the I/O system.
3078 		 */
3079 		while (numdirtybuffers > lodirty) {
3080 			if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
3081 				break;
3082 			kern_yield(PRI_USER);
3083 		}
3084 
3085 		/*
3086 		 * Only clear bd_request if we have reached our low water
3087 		 * mark.  The buf_daemon normally waits 1 second and
3088 		 * then incrementally flushes any dirty buffers that have
3089 		 * built up, within reason.
3090 		 *
3091 		 * If we were unable to hit our low water mark and couldn't
3092 		 * find any flushable buffers, we sleep for a short period
3093 		 * to avoid endless loops on unlockable buffers.
3094 		 */
3095 		mtx_lock(&bdlock);
3096 		if (numdirtybuffers <= lodirtybuffers) {
3097 			/*
3098 			 * We reached our low water mark, reset the
3099 			 * request and sleep until we are needed again.
3100 			 * The sleep is just so the suspend code works.
3101 			 */
3102 			bd_request = 0;
3103 			/*
3104 			 * Do an extra wakeup in case dirty threshold
3105 			 * changed via sysctl and the explicit transition
3106 			 * out of shortfall was missed.
3107 			 */
3108 			bdirtywakeup();
3109 			if (runningbufspace <= lorunningspace)
3110 				runningwakeup();
3111 			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3112 		} else {
3113 			/*
3114 			 * We couldn't find any flushable dirty buffers but
3115 			 * still have too many dirty buffers, we
3116 			 * have to sleep and try again.  (rare)
3117 			 */
3118 			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3119 		}
3120 	}
3121 }
3122 
3123 /*
3124  *	flushbufqueues:
3125  *
3126  *	Try to flush a buffer in the dirty queue.  We must be careful to
3127  *	free up B_INVAL buffers instead of write them, which NFS is
3128  *	particularly sensitive to.
3129  */
3130 static int flushwithdeps = 0;
3131 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
3132     0, "Number of buffers flushed with dependecies that require rollbacks");
3133 
3134 static int
3135 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
3136 {
3137 	struct buf *sentinel;
3138 	struct vnode *vp;
3139 	struct mount *mp;
3140 	struct buf *bp;
3141 	int hasdeps;
3142 	int flushed;
3143 	int queue;
3144 	int error;
3145 	bool unlock;
3146 
3147 	flushed = 0;
3148 	queue = QUEUE_DIRTY;
3149 	bp = NULL;
3150 	sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3151 	sentinel->b_qindex = QUEUE_SENTINEL;
3152 	mtx_lock(&bqlocks[queue]);
3153 	TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
3154 	mtx_unlock(&bqlocks[queue]);
3155 	while (flushed != target) {
3156 		maybe_yield();
3157 		mtx_lock(&bqlocks[queue]);
3158 		bp = TAILQ_NEXT(sentinel, b_freelist);
3159 		if (bp != NULL) {
3160 			TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3161 			TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
3162 			    b_freelist);
3163 		} else {
3164 			mtx_unlock(&bqlocks[queue]);
3165 			break;
3166 		}
3167 		/*
3168 		 * Skip sentinels inserted by other invocations of the
3169 		 * flushbufqueues(), taking care to not reorder them.
3170 		 *
3171 		 * Only flush the buffers that belong to the
3172 		 * vnode locked by the curthread.
3173 		 */
3174 		if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3175 		    bp->b_vp != lvp)) {
3176 			mtx_unlock(&bqlocks[queue]);
3177 			continue;
3178 		}
3179 		error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3180 		mtx_unlock(&bqlocks[queue]);
3181 		if (error != 0)
3182 			continue;
3183 
3184 		/*
3185 		 * BKGRDINPROG can only be set with the buf and bufobj
3186 		 * locks both held.  We tolerate a race to clear it here.
3187 		 */
3188 		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3189 		    (bp->b_flags & B_DELWRI) == 0) {
3190 			BUF_UNLOCK(bp);
3191 			continue;
3192 		}
3193 		if (bp->b_flags & B_INVAL) {
3194 			bremfreef(bp);
3195 			brelse(bp);
3196 			flushed++;
3197 			continue;
3198 		}
3199 
3200 		if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3201 			if (flushdeps == 0) {
3202 				BUF_UNLOCK(bp);
3203 				continue;
3204 			}
3205 			hasdeps = 1;
3206 		} else
3207 			hasdeps = 0;
3208 		/*
3209 		 * We must hold the lock on a vnode before writing
3210 		 * one of its buffers. Otherwise we may confuse, or
3211 		 * in the case of a snapshot vnode, deadlock the
3212 		 * system.
3213 		 *
3214 		 * The lock order here is the reverse of the normal
3215 		 * of vnode followed by buf lock.  This is ok because
3216 		 * the NOWAIT will prevent deadlock.
3217 		 */
3218 		vp = bp->b_vp;
3219 		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3220 			BUF_UNLOCK(bp);
3221 			continue;
3222 		}
3223 		if (lvp == NULL) {
3224 			unlock = true;
3225 			error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3226 		} else {
3227 			ASSERT_VOP_LOCKED(vp, "getbuf");
3228 			unlock = false;
3229 			error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3230 			    vn_lock(vp, LK_TRYUPGRADE);
3231 		}
3232 		if (error == 0) {
3233 			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3234 			    bp, bp->b_vp, bp->b_flags);
3235 			if (curproc == bufdaemonproc) {
3236 				vfs_bio_awrite(bp);
3237 			} else {
3238 				bremfree(bp);
3239 				bwrite(bp);
3240 				notbufdflushes++;
3241 			}
3242 			vn_finished_write(mp);
3243 			if (unlock)
3244 				VOP_UNLOCK(vp, 0);
3245 			flushwithdeps += hasdeps;
3246 			flushed++;
3247 
3248 			/*
3249 			 * Sleeping on runningbufspace while holding
3250 			 * vnode lock leads to deadlock.
3251 			 */
3252 			if (curproc == bufdaemonproc &&
3253 			    runningbufspace > hirunningspace)
3254 				waitrunningbufspace();
3255 			continue;
3256 		}
3257 		vn_finished_write(mp);
3258 		BUF_UNLOCK(bp);
3259 	}
3260 	mtx_lock(&bqlocks[queue]);
3261 	TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3262 	mtx_unlock(&bqlocks[queue]);
3263 	free(sentinel, M_TEMP);
3264 	return (flushed);
3265 }
3266 
3267 /*
3268  * Check to see if a block is currently memory resident.
3269  */
3270 struct buf *
3271 incore(struct bufobj *bo, daddr_t blkno)
3272 {
3273 	struct buf *bp;
3274 
3275 	BO_RLOCK(bo);
3276 	bp = gbincore(bo, blkno);
3277 	BO_RUNLOCK(bo);
3278 	return (bp);
3279 }
3280 
3281 /*
3282  * Returns true if no I/O is needed to access the
3283  * associated VM object.  This is like incore except
3284  * it also hunts around in the VM system for the data.
3285  */
3286 
3287 static int
3288 inmem(struct vnode * vp, daddr_t blkno)
3289 {
3290 	vm_object_t obj;
3291 	vm_offset_t toff, tinc, size;
3292 	vm_page_t m;
3293 	vm_ooffset_t off;
3294 
3295 	ASSERT_VOP_LOCKED(vp, "inmem");
3296 
3297 	if (incore(&vp->v_bufobj, blkno))
3298 		return 1;
3299 	if (vp->v_mount == NULL)
3300 		return 0;
3301 	obj = vp->v_object;
3302 	if (obj == NULL)
3303 		return (0);
3304 
3305 	size = PAGE_SIZE;
3306 	if (size > vp->v_mount->mnt_stat.f_iosize)
3307 		size = vp->v_mount->mnt_stat.f_iosize;
3308 	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3309 
3310 	VM_OBJECT_RLOCK(obj);
3311 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3312 		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
3313 		if (!m)
3314 			goto notinmem;
3315 		tinc = size;
3316 		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3317 			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3318 		if (vm_page_is_valid(m,
3319 		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
3320 			goto notinmem;
3321 	}
3322 	VM_OBJECT_RUNLOCK(obj);
3323 	return 1;
3324 
3325 notinmem:
3326 	VM_OBJECT_RUNLOCK(obj);
3327 	return (0);
3328 }
3329 
3330 /*
3331  * Set the dirty range for a buffer based on the status of the dirty
3332  * bits in the pages comprising the buffer.  The range is limited
3333  * to the size of the buffer.
3334  *
3335  * Tell the VM system that the pages associated with this buffer
3336  * are clean.  This is used for delayed writes where the data is
3337  * going to go to disk eventually without additional VM intevention.
3338  *
3339  * Note that while we only really need to clean through to b_bcount, we
3340  * just go ahead and clean through to b_bufsize.
3341  */
3342 static void
3343 vfs_clean_pages_dirty_buf(struct buf *bp)
3344 {
3345 	vm_ooffset_t foff, noff, eoff;
3346 	vm_page_t m;
3347 	int i;
3348 
3349 	if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3350 		return;
3351 
3352 	foff = bp->b_offset;
3353 	KASSERT(bp->b_offset != NOOFFSET,
3354 	    ("vfs_clean_pages_dirty_buf: no buffer offset"));
3355 
3356 	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3357 	vfs_drain_busy_pages(bp);
3358 	vfs_setdirty_locked_object(bp);
3359 	for (i = 0; i < bp->b_npages; i++) {
3360 		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3361 		eoff = noff;
3362 		if (eoff > bp->b_offset + bp->b_bufsize)
3363 			eoff = bp->b_offset + bp->b_bufsize;
3364 		m = bp->b_pages[i];
3365 		vfs_page_set_validclean(bp, foff, m);
3366 		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3367 		foff = noff;
3368 	}
3369 	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3370 }
3371 
3372 static void
3373 vfs_setdirty_locked_object(struct buf *bp)
3374 {
3375 	vm_object_t object;
3376 	int i;
3377 
3378 	object = bp->b_bufobj->bo_object;
3379 	VM_OBJECT_ASSERT_WLOCKED(object);
3380 
3381 	/*
3382 	 * We qualify the scan for modified pages on whether the
3383 	 * object has been flushed yet.
3384 	 */
3385 	if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
3386 		vm_offset_t boffset;
3387 		vm_offset_t eoffset;
3388 
3389 		/*
3390 		 * test the pages to see if they have been modified directly
3391 		 * by users through the VM system.
3392 		 */
3393 		for (i = 0; i < bp->b_npages; i++)
3394 			vm_page_test_dirty(bp->b_pages[i]);
3395 
3396 		/*
3397 		 * Calculate the encompassing dirty range, boffset and eoffset,
3398 		 * (eoffset - boffset) bytes.
3399 		 */
3400 
3401 		for (i = 0; i < bp->b_npages; i++) {
3402 			if (bp->b_pages[i]->dirty)
3403 				break;
3404 		}
3405 		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3406 
3407 		for (i = bp->b_npages - 1; i >= 0; --i) {
3408 			if (bp->b_pages[i]->dirty) {
3409 				break;
3410 			}
3411 		}
3412 		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3413 
3414 		/*
3415 		 * Fit it to the buffer.
3416 		 */
3417 
3418 		if (eoffset > bp->b_bcount)
3419 			eoffset = bp->b_bcount;
3420 
3421 		/*
3422 		 * If we have a good dirty range, merge with the existing
3423 		 * dirty range.
3424 		 */
3425 
3426 		if (boffset < eoffset) {
3427 			if (bp->b_dirtyoff > boffset)
3428 				bp->b_dirtyoff = boffset;
3429 			if (bp->b_dirtyend < eoffset)
3430 				bp->b_dirtyend = eoffset;
3431 		}
3432 	}
3433 }
3434 
3435 /*
3436  * Allocate the KVA mapping for an existing buffer.
3437  * If an unmapped buffer is provided but a mapped buffer is requested, take
3438  * also care to properly setup mappings between pages and KVA.
3439  */
3440 static void
3441 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3442 {
3443 	int bsize, maxsize, need_mapping, need_kva;
3444 	off_t offset;
3445 
3446 	need_mapping = bp->b_data == unmapped_buf &&
3447 	    (gbflags & GB_UNMAPPED) == 0;
3448 	need_kva = bp->b_kvabase == unmapped_buf &&
3449 	    bp->b_data == unmapped_buf &&
3450 	    (gbflags & GB_KVAALLOC) != 0;
3451 	if (!need_mapping && !need_kva)
3452 		return;
3453 
3454 	BUF_CHECK_UNMAPPED(bp);
3455 
3456 	if (need_mapping && bp->b_kvabase != unmapped_buf) {
3457 		/*
3458 		 * Buffer is not mapped, but the KVA was already
3459 		 * reserved at the time of the instantiation.  Use the
3460 		 * allocated space.
3461 		 */
3462 		goto has_addr;
3463 	}
3464 
3465 	/*
3466 	 * Calculate the amount of the address space we would reserve
3467 	 * if the buffer was mapped.
3468 	 */
3469 	bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3470 	KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3471 	offset = blkno * bsize;
3472 	maxsize = size + (offset & PAGE_MASK);
3473 	maxsize = imax(maxsize, bsize);
3474 
3475 	while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3476 		if ((gbflags & GB_NOWAIT_BD) != 0) {
3477 			/*
3478 			 * XXXKIB: defragmentation cannot
3479 			 * succeed, not sure what else to do.
3480 			 */
3481 			panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3482 		}
3483 		atomic_add_int(&mappingrestarts, 1);
3484 		bufspace_wait(bp->b_vp, gbflags, 0, 0);
3485 	}
3486 has_addr:
3487 	if (need_mapping) {
3488 		/* b_offset is handled by bpmap_qenter. */
3489 		bp->b_data = bp->b_kvabase;
3490 		BUF_CHECK_MAPPED(bp);
3491 		bpmap_qenter(bp);
3492 	}
3493 }
3494 
3495 /*
3496  *	getblk:
3497  *
3498  *	Get a block given a specified block and offset into a file/device.
3499  *	The buffers B_DONE bit will be cleared on return, making it almost
3500  * 	ready for an I/O initiation.  B_INVAL may or may not be set on
3501  *	return.  The caller should clear B_INVAL prior to initiating a
3502  *	READ.
3503  *
3504  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3505  *	an existing buffer.
3506  *
3507  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
3508  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3509  *	and then cleared based on the backing VM.  If the previous buffer is
3510  *	non-0-sized but invalid, B_CACHE will be cleared.
3511  *
3512  *	If getblk() must create a new buffer, the new buffer is returned with
3513  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3514  *	case it is returned with B_INVAL clear and B_CACHE set based on the
3515  *	backing VM.
3516  *
3517  *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
3518  *	B_CACHE bit is clear.
3519  *
3520  *	What this means, basically, is that the caller should use B_CACHE to
3521  *	determine whether the buffer is fully valid or not and should clear
3522  *	B_INVAL prior to issuing a read.  If the caller intends to validate
3523  *	the buffer by loading its data area with something, the caller needs
3524  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
3525  *	the caller should set B_CACHE ( as an optimization ), else the caller
3526  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
3527  *	a write attempt or if it was a successful read.  If the caller
3528  *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3529  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
3530  */
3531 struct buf *
3532 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3533     int flags)
3534 {
3535 	struct buf *bp;
3536 	struct bufobj *bo;
3537 	int bsize, error, maxsize, vmio;
3538 	off_t offset;
3539 
3540 	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3541 	KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3542 	    ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3543 	ASSERT_VOP_LOCKED(vp, "getblk");
3544 	if (size > maxbcachebuf)
3545 		panic("getblk: size(%d) > maxbcachebuf(%d)\n", size,
3546 		    maxbcachebuf);
3547 	if (!unmapped_buf_allowed)
3548 		flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3549 
3550 	bo = &vp->v_bufobj;
3551 loop:
3552 	BO_RLOCK(bo);
3553 	bp = gbincore(bo, blkno);
3554 	if (bp != NULL) {
3555 		int lockflags;
3556 		/*
3557 		 * Buffer is in-core.  If the buffer is not busy nor managed,
3558 		 * it must be on a queue.
3559 		 */
3560 		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3561 
3562 		if (flags & GB_LOCK_NOWAIT)
3563 			lockflags |= LK_NOWAIT;
3564 
3565 		error = BUF_TIMELOCK(bp, lockflags,
3566 		    BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3567 
3568 		/*
3569 		 * If we slept and got the lock we have to restart in case
3570 		 * the buffer changed identities.
3571 		 */
3572 		if (error == ENOLCK)
3573 			goto loop;
3574 		/* We timed out or were interrupted. */
3575 		else if (error)
3576 			return (NULL);
3577 		/* If recursed, assume caller knows the rules. */
3578 		else if (BUF_LOCKRECURSED(bp))
3579 			goto end;
3580 
3581 		/*
3582 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
3583 		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
3584 		 * and for a VMIO buffer B_CACHE is adjusted according to the
3585 		 * backing VM cache.
3586 		 */
3587 		if (bp->b_flags & B_INVAL)
3588 			bp->b_flags &= ~B_CACHE;
3589 		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3590 			bp->b_flags |= B_CACHE;
3591 		if (bp->b_flags & B_MANAGED)
3592 			MPASS(bp->b_qindex == QUEUE_NONE);
3593 		else
3594 			bremfree(bp);
3595 
3596 		/*
3597 		 * check for size inconsistencies for non-VMIO case.
3598 		 */
3599 		if (bp->b_bcount != size) {
3600 			if ((bp->b_flags & B_VMIO) == 0 ||
3601 			    (size > bp->b_kvasize)) {
3602 				if (bp->b_flags & B_DELWRI) {
3603 					bp->b_flags |= B_NOCACHE;
3604 					bwrite(bp);
3605 				} else {
3606 					if (LIST_EMPTY(&bp->b_dep)) {
3607 						bp->b_flags |= B_RELBUF;
3608 						brelse(bp);
3609 					} else {
3610 						bp->b_flags |= B_NOCACHE;
3611 						bwrite(bp);
3612 					}
3613 				}
3614 				goto loop;
3615 			}
3616 		}
3617 
3618 		/*
3619 		 * Handle the case of unmapped buffer which should
3620 		 * become mapped, or the buffer for which KVA
3621 		 * reservation is requested.
3622 		 */
3623 		bp_unmapped_get_kva(bp, blkno, size, flags);
3624 
3625 		/*
3626 		 * If the size is inconsistent in the VMIO case, we can resize
3627 		 * the buffer.  This might lead to B_CACHE getting set or
3628 		 * cleared.  If the size has not changed, B_CACHE remains
3629 		 * unchanged from its previous state.
3630 		 */
3631 		allocbuf(bp, size);
3632 
3633 		KASSERT(bp->b_offset != NOOFFSET,
3634 		    ("getblk: no buffer offset"));
3635 
3636 		/*
3637 		 * A buffer with B_DELWRI set and B_CACHE clear must
3638 		 * be committed before we can return the buffer in
3639 		 * order to prevent the caller from issuing a read
3640 		 * ( due to B_CACHE not being set ) and overwriting
3641 		 * it.
3642 		 *
3643 		 * Most callers, including NFS and FFS, need this to
3644 		 * operate properly either because they assume they
3645 		 * can issue a read if B_CACHE is not set, or because
3646 		 * ( for example ) an uncached B_DELWRI might loop due
3647 		 * to softupdates re-dirtying the buffer.  In the latter
3648 		 * case, B_CACHE is set after the first write completes,
3649 		 * preventing further loops.
3650 		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
3651 		 * above while extending the buffer, we cannot allow the
3652 		 * buffer to remain with B_CACHE set after the write
3653 		 * completes or it will represent a corrupt state.  To
3654 		 * deal with this we set B_NOCACHE to scrap the buffer
3655 		 * after the write.
3656 		 *
3657 		 * We might be able to do something fancy, like setting
3658 		 * B_CACHE in bwrite() except if B_DELWRI is already set,
3659 		 * so the below call doesn't set B_CACHE, but that gets real
3660 		 * confusing.  This is much easier.
3661 		 */
3662 
3663 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3664 			bp->b_flags |= B_NOCACHE;
3665 			bwrite(bp);
3666 			goto loop;
3667 		}
3668 		bp->b_flags &= ~B_DONE;
3669 	} else {
3670 		/*
3671 		 * Buffer is not in-core, create new buffer.  The buffer
3672 		 * returned by getnewbuf() is locked.  Note that the returned
3673 		 * buffer is also considered valid (not marked B_INVAL).
3674 		 */
3675 		BO_RUNLOCK(bo);
3676 		/*
3677 		 * If the user does not want us to create the buffer, bail out
3678 		 * here.
3679 		 */
3680 		if (flags & GB_NOCREAT)
3681 			return NULL;
3682 		if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3683 			return NULL;
3684 
3685 		bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3686 		KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3687 		offset = blkno * bsize;
3688 		vmio = vp->v_object != NULL;
3689 		if (vmio) {
3690 			maxsize = size + (offset & PAGE_MASK);
3691 		} else {
3692 			maxsize = size;
3693 			/* Do not allow non-VMIO notmapped buffers. */
3694 			flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3695 		}
3696 		maxsize = imax(maxsize, bsize);
3697 
3698 		bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
3699 		if (bp == NULL) {
3700 			if (slpflag || slptimeo)
3701 				return NULL;
3702 			/*
3703 			 * XXX This is here until the sleep path is diagnosed
3704 			 * enough to work under very low memory conditions.
3705 			 *
3706 			 * There's an issue on low memory, 4BSD+non-preempt
3707 			 * systems (eg MIPS routers with 32MB RAM) where buffer
3708 			 * exhaustion occurs without sleeping for buffer
3709 			 * reclaimation.  This just sticks in a loop and
3710 			 * constantly attempts to allocate a buffer, which
3711 			 * hits exhaustion and tries to wakeup bufdaemon.
3712 			 * This never happens because we never yield.
3713 			 *
3714 			 * The real solution is to identify and fix these cases
3715 			 * so we aren't effectively busy-waiting in a loop
3716 			 * until the reclaimation path has cycles to run.
3717 			 */
3718 			kern_yield(PRI_USER);
3719 			goto loop;
3720 		}
3721 
3722 		/*
3723 		 * This code is used to make sure that a buffer is not
3724 		 * created while the getnewbuf routine is blocked.
3725 		 * This can be a problem whether the vnode is locked or not.
3726 		 * If the buffer is created out from under us, we have to
3727 		 * throw away the one we just created.
3728 		 *
3729 		 * Note: this must occur before we associate the buffer
3730 		 * with the vp especially considering limitations in
3731 		 * the splay tree implementation when dealing with duplicate
3732 		 * lblkno's.
3733 		 */
3734 		BO_LOCK(bo);
3735 		if (gbincore(bo, blkno)) {
3736 			BO_UNLOCK(bo);
3737 			bp->b_flags |= B_INVAL;
3738 			brelse(bp);
3739 			bufspace_release(maxsize);
3740 			goto loop;
3741 		}
3742 
3743 		/*
3744 		 * Insert the buffer into the hash, so that it can
3745 		 * be found by incore.
3746 		 */
3747 		bp->b_blkno = bp->b_lblkno = blkno;
3748 		bp->b_offset = offset;
3749 		bgetvp(vp, bp);
3750 		BO_UNLOCK(bo);
3751 
3752 		/*
3753 		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
3754 		 * buffer size starts out as 0, B_CACHE will be set by
3755 		 * allocbuf() for the VMIO case prior to it testing the
3756 		 * backing store for validity.
3757 		 */
3758 
3759 		if (vmio) {
3760 			bp->b_flags |= B_VMIO;
3761 			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3762 			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3763 			    bp, vp->v_object, bp->b_bufobj->bo_object));
3764 		} else {
3765 			bp->b_flags &= ~B_VMIO;
3766 			KASSERT(bp->b_bufobj->bo_object == NULL,
3767 			    ("ARGH! has b_bufobj->bo_object %p %p\n",
3768 			    bp, bp->b_bufobj->bo_object));
3769 			BUF_CHECK_MAPPED(bp);
3770 		}
3771 
3772 		allocbuf(bp, size);
3773 		bufspace_release(maxsize);
3774 		bp->b_flags &= ~B_DONE;
3775 	}
3776 	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3777 	BUF_ASSERT_HELD(bp);
3778 end:
3779 	buf_track(bp, __func__);
3780 	KASSERT(bp->b_bufobj == bo,
3781 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3782 	return (bp);
3783 }
3784 
3785 /*
3786  * Get an empty, disassociated buffer of given size.  The buffer is initially
3787  * set to B_INVAL.
3788  */
3789 struct buf *
3790 geteblk(int size, int flags)
3791 {
3792 	struct buf *bp;
3793 	int maxsize;
3794 
3795 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
3796 	while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
3797 		if ((flags & GB_NOWAIT_BD) &&
3798 		    (curthread->td_pflags & TDP_BUFNEED) != 0)
3799 			return (NULL);
3800 	}
3801 	allocbuf(bp, size);
3802 	bufspace_release(maxsize);
3803 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
3804 	BUF_ASSERT_HELD(bp);
3805 	return (bp);
3806 }
3807 
3808 /*
3809  * Truncate the backing store for a non-vmio buffer.
3810  */
3811 static void
3812 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
3813 {
3814 
3815 	if (bp->b_flags & B_MALLOC) {
3816 		/*
3817 		 * malloced buffers are not shrunk
3818 		 */
3819 		if (newbsize == 0) {
3820 			bufmallocadjust(bp, 0);
3821 			free(bp->b_data, M_BIOBUF);
3822 			bp->b_data = bp->b_kvabase;
3823 			bp->b_flags &= ~B_MALLOC;
3824 		}
3825 		return;
3826 	}
3827 	vm_hold_free_pages(bp, newbsize);
3828 	bufspace_adjust(bp, newbsize);
3829 }
3830 
3831 /*
3832  * Extend the backing for a non-VMIO buffer.
3833  */
3834 static void
3835 vfs_nonvmio_extend(struct buf *bp, int newbsize)
3836 {
3837 	caddr_t origbuf;
3838 	int origbufsize;
3839 
3840 	/*
3841 	 * We only use malloced memory on the first allocation.
3842 	 * and revert to page-allocated memory when the buffer
3843 	 * grows.
3844 	 *
3845 	 * There is a potential smp race here that could lead
3846 	 * to bufmallocspace slightly passing the max.  It
3847 	 * is probably extremely rare and not worth worrying
3848 	 * over.
3849 	 */
3850 	if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
3851 	    bufmallocspace < maxbufmallocspace) {
3852 		bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
3853 		bp->b_flags |= B_MALLOC;
3854 		bufmallocadjust(bp, newbsize);
3855 		return;
3856 	}
3857 
3858 	/*
3859 	 * If the buffer is growing on its other-than-first
3860 	 * allocation then we revert to the page-allocation
3861 	 * scheme.
3862 	 */
3863 	origbuf = NULL;
3864 	origbufsize = 0;
3865 	if (bp->b_flags & B_MALLOC) {
3866 		origbuf = bp->b_data;
3867 		origbufsize = bp->b_bufsize;
3868 		bp->b_data = bp->b_kvabase;
3869 		bufmallocadjust(bp, 0);
3870 		bp->b_flags &= ~B_MALLOC;
3871 		newbsize = round_page(newbsize);
3872 	}
3873 	vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
3874 	    (vm_offset_t) bp->b_data + newbsize);
3875 	if (origbuf != NULL) {
3876 		bcopy(origbuf, bp->b_data, origbufsize);
3877 		free(origbuf, M_BIOBUF);
3878 	}
3879 	bufspace_adjust(bp, newbsize);
3880 }
3881 
3882 /*
3883  * This code constitutes the buffer memory from either anonymous system
3884  * memory (in the case of non-VMIO operations) or from an associated
3885  * VM object (in the case of VMIO operations).  This code is able to
3886  * resize a buffer up or down.
3887  *
3888  * Note that this code is tricky, and has many complications to resolve
3889  * deadlock or inconsistent data situations.  Tread lightly!!!
3890  * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3891  * the caller.  Calling this code willy nilly can result in the loss of data.
3892  *
3893  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
3894  * B_CACHE for the non-VMIO case.
3895  */
3896 int
3897 allocbuf(struct buf *bp, int size)
3898 {
3899 	int newbsize;
3900 
3901 	BUF_ASSERT_HELD(bp);
3902 
3903 	if (bp->b_bcount == size)
3904 		return (1);
3905 
3906 	if (bp->b_kvasize != 0 && bp->b_kvasize < size)
3907 		panic("allocbuf: buffer too small");
3908 
3909 	newbsize = roundup2(size, DEV_BSIZE);
3910 	if ((bp->b_flags & B_VMIO) == 0) {
3911 		if ((bp->b_flags & B_MALLOC) == 0)
3912 			newbsize = round_page(newbsize);
3913 		/*
3914 		 * Just get anonymous memory from the kernel.  Don't
3915 		 * mess with B_CACHE.
3916 		 */
3917 		if (newbsize < bp->b_bufsize)
3918 			vfs_nonvmio_truncate(bp, newbsize);
3919 		else if (newbsize > bp->b_bufsize)
3920 			vfs_nonvmio_extend(bp, newbsize);
3921 	} else {
3922 		int desiredpages;
3923 
3924 		desiredpages = (size == 0) ? 0 :
3925 		    num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3926 
3927 		if (bp->b_flags & B_MALLOC)
3928 			panic("allocbuf: VMIO buffer can't be malloced");
3929 		/*
3930 		 * Set B_CACHE initially if buffer is 0 length or will become
3931 		 * 0-length.
3932 		 */
3933 		if (size == 0 || bp->b_bufsize == 0)
3934 			bp->b_flags |= B_CACHE;
3935 
3936 		if (newbsize < bp->b_bufsize)
3937 			vfs_vmio_truncate(bp, desiredpages);
3938 		/* XXX This looks as if it should be newbsize > b_bufsize */
3939 		else if (size > bp->b_bcount)
3940 			vfs_vmio_extend(bp, desiredpages, size);
3941 		bufspace_adjust(bp, newbsize);
3942 	}
3943 	bp->b_bcount = size;		/* requested buffer size. */
3944 	return (1);
3945 }
3946 
3947 extern int inflight_transient_maps;
3948 
3949 void
3950 biodone(struct bio *bp)
3951 {
3952 	struct mtx *mtxp;
3953 	void (*done)(struct bio *);
3954 	vm_offset_t start, end;
3955 
3956 	biotrack(bp, __func__);
3957 	if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3958 		bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3959 		bp->bio_flags |= BIO_UNMAPPED;
3960 		start = trunc_page((vm_offset_t)bp->bio_data);
3961 		end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3962 		bp->bio_data = unmapped_buf;
3963 		pmap_qremove(start, atop(end - start));
3964 		vmem_free(transient_arena, start, end - start);
3965 		atomic_add_int(&inflight_transient_maps, -1);
3966 	}
3967 	done = bp->bio_done;
3968 	if (done == NULL) {
3969 		mtxp = mtx_pool_find(mtxpool_sleep, bp);
3970 		mtx_lock(mtxp);
3971 		bp->bio_flags |= BIO_DONE;
3972 		wakeup(bp);
3973 		mtx_unlock(mtxp);
3974 	} else
3975 		done(bp);
3976 }
3977 
3978 /*
3979  * Wait for a BIO to finish.
3980  */
3981 int
3982 biowait(struct bio *bp, const char *wchan)
3983 {
3984 	struct mtx *mtxp;
3985 
3986 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3987 	mtx_lock(mtxp);
3988 	while ((bp->bio_flags & BIO_DONE) == 0)
3989 		msleep(bp, mtxp, PRIBIO, wchan, 0);
3990 	mtx_unlock(mtxp);
3991 	if (bp->bio_error != 0)
3992 		return (bp->bio_error);
3993 	if (!(bp->bio_flags & BIO_ERROR))
3994 		return (0);
3995 	return (EIO);
3996 }
3997 
3998 void
3999 biofinish(struct bio *bp, struct devstat *stat, int error)
4000 {
4001 
4002 	if (error) {
4003 		bp->bio_error = error;
4004 		bp->bio_flags |= BIO_ERROR;
4005 	}
4006 	if (stat != NULL)
4007 		devstat_end_transaction_bio(stat, bp);
4008 	biodone(bp);
4009 }
4010 
4011 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4012 void
4013 biotrack_buf(struct bio *bp, const char *location)
4014 {
4015 
4016 	buf_track(bp->bio_track_bp, location);
4017 }
4018 #endif
4019 
4020 /*
4021  *	bufwait:
4022  *
4023  *	Wait for buffer I/O completion, returning error status.  The buffer
4024  *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
4025  *	error and cleared.
4026  */
4027 int
4028 bufwait(struct buf *bp)
4029 {
4030 	if (bp->b_iocmd == BIO_READ)
4031 		bwait(bp, PRIBIO, "biord");
4032 	else
4033 		bwait(bp, PRIBIO, "biowr");
4034 	if (bp->b_flags & B_EINTR) {
4035 		bp->b_flags &= ~B_EINTR;
4036 		return (EINTR);
4037 	}
4038 	if (bp->b_ioflags & BIO_ERROR) {
4039 		return (bp->b_error ? bp->b_error : EIO);
4040 	} else {
4041 		return (0);
4042 	}
4043 }
4044 
4045 /*
4046  *	bufdone:
4047  *
4048  *	Finish I/O on a buffer, optionally calling a completion function.
4049  *	This is usually called from an interrupt so process blocking is
4050  *	not allowed.
4051  *
4052  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4053  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
4054  *	assuming B_INVAL is clear.
4055  *
4056  *	For the VMIO case, we set B_CACHE if the op was a read and no
4057  *	read error occurred, or if the op was a write.  B_CACHE is never
4058  *	set if the buffer is invalid or otherwise uncacheable.
4059  *
4060  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
4061  *	initiator to leave B_INVAL set to brelse the buffer out of existence
4062  *	in the biodone routine.
4063  */
4064 void
4065 bufdone(struct buf *bp)
4066 {
4067 	struct bufobj *dropobj;
4068 	void    (*biodone)(struct buf *);
4069 
4070 	buf_track(bp, __func__);
4071 	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4072 	dropobj = NULL;
4073 
4074 	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4075 	BUF_ASSERT_HELD(bp);
4076 
4077 	runningbufwakeup(bp);
4078 	if (bp->b_iocmd == BIO_WRITE)
4079 		dropobj = bp->b_bufobj;
4080 	/* call optional completion function if requested */
4081 	if (bp->b_iodone != NULL) {
4082 		biodone = bp->b_iodone;
4083 		bp->b_iodone = NULL;
4084 		(*biodone) (bp);
4085 		if (dropobj)
4086 			bufobj_wdrop(dropobj);
4087 		return;
4088 	}
4089 	if (bp->b_flags & B_VMIO) {
4090 		/*
4091 		 * Set B_CACHE if the op was a normal read and no error
4092 		 * occurred.  B_CACHE is set for writes in the b*write()
4093 		 * routines.
4094 		 */
4095 		if (bp->b_iocmd == BIO_READ &&
4096 		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4097 		    !(bp->b_ioflags & BIO_ERROR))
4098 			bp->b_flags |= B_CACHE;
4099 		vfs_vmio_iodone(bp);
4100 	}
4101 	if (!LIST_EMPTY(&bp->b_dep))
4102 		buf_complete(bp);
4103 	if ((bp->b_flags & B_CKHASH) != 0) {
4104 		KASSERT(bp->b_iocmd == BIO_READ,
4105 		    ("bufdone: b_iocmd %d not BIO_READ", bp->b_iocmd));
4106 		KASSERT(buf_mapped(bp), ("bufdone: bp %p not mapped", bp));
4107 		(*bp->b_ckhashcalc)(bp);
4108 	}
4109 	/*
4110 	 * For asynchronous completions, release the buffer now. The brelse
4111 	 * will do a wakeup there if necessary - so no need to do a wakeup
4112 	 * here in the async case. The sync case always needs to do a wakeup.
4113 	 */
4114 	if (bp->b_flags & B_ASYNC) {
4115 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4116 		    (bp->b_ioflags & BIO_ERROR))
4117 			brelse(bp);
4118 		else
4119 			bqrelse(bp);
4120 	} else
4121 		bdone(bp);
4122 	if (dropobj)
4123 		bufobj_wdrop(dropobj);
4124 }
4125 
4126 /*
4127  * This routine is called in lieu of iodone in the case of
4128  * incomplete I/O.  This keeps the busy status for pages
4129  * consistent.
4130  */
4131 void
4132 vfs_unbusy_pages(struct buf *bp)
4133 {
4134 	int i;
4135 	vm_object_t obj;
4136 	vm_page_t m;
4137 
4138 	runningbufwakeup(bp);
4139 	if (!(bp->b_flags & B_VMIO))
4140 		return;
4141 
4142 	obj = bp->b_bufobj->bo_object;
4143 	VM_OBJECT_WLOCK(obj);
4144 	for (i = 0; i < bp->b_npages; i++) {
4145 		m = bp->b_pages[i];
4146 		if (m == bogus_page) {
4147 			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4148 			if (!m)
4149 				panic("vfs_unbusy_pages: page missing\n");
4150 			bp->b_pages[i] = m;
4151 			if (buf_mapped(bp)) {
4152 				BUF_CHECK_MAPPED(bp);
4153 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4154 				    bp->b_pages, bp->b_npages);
4155 			} else
4156 				BUF_CHECK_UNMAPPED(bp);
4157 		}
4158 		vm_page_sunbusy(m);
4159 	}
4160 	vm_object_pip_wakeupn(obj, bp->b_npages);
4161 	VM_OBJECT_WUNLOCK(obj);
4162 }
4163 
4164 /*
4165  * vfs_page_set_valid:
4166  *
4167  *	Set the valid bits in a page based on the supplied offset.   The
4168  *	range is restricted to the buffer's size.
4169  *
4170  *	This routine is typically called after a read completes.
4171  */
4172 static void
4173 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4174 {
4175 	vm_ooffset_t eoff;
4176 
4177 	/*
4178 	 * Compute the end offset, eoff, such that [off, eoff) does not span a
4179 	 * page boundary and eoff is not greater than the end of the buffer.
4180 	 * The end of the buffer, in this case, is our file EOF, not the
4181 	 * allocation size of the buffer.
4182 	 */
4183 	eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4184 	if (eoff > bp->b_offset + bp->b_bcount)
4185 		eoff = bp->b_offset + bp->b_bcount;
4186 
4187 	/*
4188 	 * Set valid range.  This is typically the entire buffer and thus the
4189 	 * entire page.
4190 	 */
4191 	if (eoff > off)
4192 		vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4193 }
4194 
4195 /*
4196  * vfs_page_set_validclean:
4197  *
4198  *	Set the valid bits and clear the dirty bits in a page based on the
4199  *	supplied offset.   The range is restricted to the buffer's size.
4200  */
4201 static void
4202 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4203 {
4204 	vm_ooffset_t soff, eoff;
4205 
4206 	/*
4207 	 * Start and end offsets in buffer.  eoff - soff may not cross a
4208 	 * page boundary or cross the end of the buffer.  The end of the
4209 	 * buffer, in this case, is our file EOF, not the allocation size
4210 	 * of the buffer.
4211 	 */
4212 	soff = off;
4213 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4214 	if (eoff > bp->b_offset + bp->b_bcount)
4215 		eoff = bp->b_offset + bp->b_bcount;
4216 
4217 	/*
4218 	 * Set valid range.  This is typically the entire buffer and thus the
4219 	 * entire page.
4220 	 */
4221 	if (eoff > soff) {
4222 		vm_page_set_validclean(
4223 		    m,
4224 		   (vm_offset_t) (soff & PAGE_MASK),
4225 		   (vm_offset_t) (eoff - soff)
4226 		);
4227 	}
4228 }
4229 
4230 /*
4231  * Ensure that all buffer pages are not exclusive busied.  If any page is
4232  * exclusive busy, drain it.
4233  */
4234 void
4235 vfs_drain_busy_pages(struct buf *bp)
4236 {
4237 	vm_page_t m;
4238 	int i, last_busied;
4239 
4240 	VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4241 	last_busied = 0;
4242 	for (i = 0; i < bp->b_npages; i++) {
4243 		m = bp->b_pages[i];
4244 		if (vm_page_xbusied(m)) {
4245 			for (; last_busied < i; last_busied++)
4246 				vm_page_sbusy(bp->b_pages[last_busied]);
4247 			while (vm_page_xbusied(m)) {
4248 				vm_page_lock(m);
4249 				VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4250 				vm_page_busy_sleep(m, "vbpage", true);
4251 				VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4252 			}
4253 		}
4254 	}
4255 	for (i = 0; i < last_busied; i++)
4256 		vm_page_sunbusy(bp->b_pages[i]);
4257 }
4258 
4259 /*
4260  * This routine is called before a device strategy routine.
4261  * It is used to tell the VM system that paging I/O is in
4262  * progress, and treat the pages associated with the buffer
4263  * almost as being exclusive busy.  Also the object paging_in_progress
4264  * flag is handled to make sure that the object doesn't become
4265  * inconsistent.
4266  *
4267  * Since I/O has not been initiated yet, certain buffer flags
4268  * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4269  * and should be ignored.
4270  */
4271 void
4272 vfs_busy_pages(struct buf *bp, int clear_modify)
4273 {
4274 	vm_object_t obj;
4275 	vm_ooffset_t foff;
4276 	vm_page_t m;
4277 	int i;
4278 	bool bogus;
4279 
4280 	if (!(bp->b_flags & B_VMIO))
4281 		return;
4282 
4283 	obj = bp->b_bufobj->bo_object;
4284 	foff = bp->b_offset;
4285 	KASSERT(bp->b_offset != NOOFFSET,
4286 	    ("vfs_busy_pages: no buffer offset"));
4287 	VM_OBJECT_WLOCK(obj);
4288 	vfs_drain_busy_pages(bp);
4289 	if (bp->b_bufsize != 0)
4290 		vfs_setdirty_locked_object(bp);
4291 	bogus = false;
4292 	for (i = 0; i < bp->b_npages; i++) {
4293 		m = bp->b_pages[i];
4294 
4295 		if ((bp->b_flags & B_CLUSTER) == 0) {
4296 			vm_object_pip_add(obj, 1);
4297 			vm_page_sbusy(m);
4298 		}
4299 		/*
4300 		 * When readying a buffer for a read ( i.e
4301 		 * clear_modify == 0 ), it is important to do
4302 		 * bogus_page replacement for valid pages in
4303 		 * partially instantiated buffers.  Partially
4304 		 * instantiated buffers can, in turn, occur when
4305 		 * reconstituting a buffer from its VM backing store
4306 		 * base.  We only have to do this if B_CACHE is
4307 		 * clear ( which causes the I/O to occur in the
4308 		 * first place ).  The replacement prevents the read
4309 		 * I/O from overwriting potentially dirty VM-backed
4310 		 * pages.  XXX bogus page replacement is, uh, bogus.
4311 		 * It may not work properly with small-block devices.
4312 		 * We need to find a better way.
4313 		 */
4314 		if (clear_modify) {
4315 			pmap_remove_write(m);
4316 			vfs_page_set_validclean(bp, foff, m);
4317 		} else if (m->valid == VM_PAGE_BITS_ALL &&
4318 		    (bp->b_flags & B_CACHE) == 0) {
4319 			bp->b_pages[i] = bogus_page;
4320 			bogus = true;
4321 		}
4322 		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4323 	}
4324 	VM_OBJECT_WUNLOCK(obj);
4325 	if (bogus && buf_mapped(bp)) {
4326 		BUF_CHECK_MAPPED(bp);
4327 		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4328 		    bp->b_pages, bp->b_npages);
4329 	}
4330 }
4331 
4332 /*
4333  *	vfs_bio_set_valid:
4334  *
4335  *	Set the range within the buffer to valid.  The range is
4336  *	relative to the beginning of the buffer, b_offset.  Note that
4337  *	b_offset itself may be offset from the beginning of the first
4338  *	page.
4339  */
4340 void
4341 vfs_bio_set_valid(struct buf *bp, int base, int size)
4342 {
4343 	int i, n;
4344 	vm_page_t m;
4345 
4346 	if (!(bp->b_flags & B_VMIO))
4347 		return;
4348 
4349 	/*
4350 	 * Fixup base to be relative to beginning of first page.
4351 	 * Set initial n to be the maximum number of bytes in the
4352 	 * first page that can be validated.
4353 	 */
4354 	base += (bp->b_offset & PAGE_MASK);
4355 	n = PAGE_SIZE - (base & PAGE_MASK);
4356 
4357 	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4358 	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4359 		m = bp->b_pages[i];
4360 		if (n > size)
4361 			n = size;
4362 		vm_page_set_valid_range(m, base & PAGE_MASK, n);
4363 		base += n;
4364 		size -= n;
4365 		n = PAGE_SIZE;
4366 	}
4367 	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4368 }
4369 
4370 /*
4371  *	vfs_bio_clrbuf:
4372  *
4373  *	If the specified buffer is a non-VMIO buffer, clear the entire
4374  *	buffer.  If the specified buffer is a VMIO buffer, clear and
4375  *	validate only the previously invalid portions of the buffer.
4376  *	This routine essentially fakes an I/O, so we need to clear
4377  *	BIO_ERROR and B_INVAL.
4378  *
4379  *	Note that while we only theoretically need to clear through b_bcount,
4380  *	we go ahead and clear through b_bufsize.
4381  */
4382 void
4383 vfs_bio_clrbuf(struct buf *bp)
4384 {
4385 	int i, j, mask, sa, ea, slide;
4386 
4387 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4388 		clrbuf(bp);
4389 		return;
4390 	}
4391 	bp->b_flags &= ~B_INVAL;
4392 	bp->b_ioflags &= ~BIO_ERROR;
4393 	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4394 	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4395 	    (bp->b_offset & PAGE_MASK) == 0) {
4396 		if (bp->b_pages[0] == bogus_page)
4397 			goto unlock;
4398 		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4399 		VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4400 		if ((bp->b_pages[0]->valid & mask) == mask)
4401 			goto unlock;
4402 		if ((bp->b_pages[0]->valid & mask) == 0) {
4403 			pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4404 			bp->b_pages[0]->valid |= mask;
4405 			goto unlock;
4406 		}
4407 	}
4408 	sa = bp->b_offset & PAGE_MASK;
4409 	slide = 0;
4410 	for (i = 0; i < bp->b_npages; i++, sa = 0) {
4411 		slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4412 		ea = slide & PAGE_MASK;
4413 		if (ea == 0)
4414 			ea = PAGE_SIZE;
4415 		if (bp->b_pages[i] == bogus_page)
4416 			continue;
4417 		j = sa / DEV_BSIZE;
4418 		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4419 		VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4420 		if ((bp->b_pages[i]->valid & mask) == mask)
4421 			continue;
4422 		if ((bp->b_pages[i]->valid & mask) == 0)
4423 			pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4424 		else {
4425 			for (; sa < ea; sa += DEV_BSIZE, j++) {
4426 				if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4427 					pmap_zero_page_area(bp->b_pages[i],
4428 					    sa, DEV_BSIZE);
4429 				}
4430 			}
4431 		}
4432 		bp->b_pages[i]->valid |= mask;
4433 	}
4434 unlock:
4435 	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4436 	bp->b_resid = 0;
4437 }
4438 
4439 void
4440 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4441 {
4442 	vm_page_t m;
4443 	int i, n;
4444 
4445 	if (buf_mapped(bp)) {
4446 		BUF_CHECK_MAPPED(bp);
4447 		bzero(bp->b_data + base, size);
4448 	} else {
4449 		BUF_CHECK_UNMAPPED(bp);
4450 		n = PAGE_SIZE - (base & PAGE_MASK);
4451 		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4452 			m = bp->b_pages[i];
4453 			if (n > size)
4454 				n = size;
4455 			pmap_zero_page_area(m, base & PAGE_MASK, n);
4456 			base += n;
4457 			size -= n;
4458 			n = PAGE_SIZE;
4459 		}
4460 	}
4461 }
4462 
4463 /*
4464  * Update buffer flags based on I/O request parameters, optionally releasing the
4465  * buffer.  If it's VMIO or direct I/O, the buffer pages are released to the VM,
4466  * where they may be placed on a page queue (VMIO) or freed immediately (direct
4467  * I/O).  Otherwise the buffer is released to the cache.
4468  */
4469 static void
4470 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4471 {
4472 
4473 	KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4474 	    ("buf %p non-VMIO noreuse", bp));
4475 
4476 	if ((ioflag & IO_DIRECT) != 0)
4477 		bp->b_flags |= B_DIRECT;
4478 	if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4479 		bp->b_flags |= B_RELBUF;
4480 		if ((ioflag & IO_NOREUSE) != 0)
4481 			bp->b_flags |= B_NOREUSE;
4482 		if (release)
4483 			brelse(bp);
4484 	} else if (release)
4485 		bqrelse(bp);
4486 }
4487 
4488 void
4489 vfs_bio_brelse(struct buf *bp, int ioflag)
4490 {
4491 
4492 	b_io_dismiss(bp, ioflag, true);
4493 }
4494 
4495 void
4496 vfs_bio_set_flags(struct buf *bp, int ioflag)
4497 {
4498 
4499 	b_io_dismiss(bp, ioflag, false);
4500 }
4501 
4502 /*
4503  * vm_hold_load_pages and vm_hold_free_pages get pages into
4504  * a buffers address space.  The pages are anonymous and are
4505  * not associated with a file object.
4506  */
4507 static void
4508 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4509 {
4510 	vm_offset_t pg;
4511 	vm_page_t p;
4512 	int index;
4513 
4514 	BUF_CHECK_MAPPED(bp);
4515 
4516 	to = round_page(to);
4517 	from = round_page(from);
4518 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4519 
4520 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4521 		/*
4522 		 * note: must allocate system pages since blocking here
4523 		 * could interfere with paging I/O, no matter which
4524 		 * process we are.
4525 		 */
4526 		p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4527 		    VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) |
4528 		    VM_ALLOC_WAITOK);
4529 		pmap_qenter(pg, &p, 1);
4530 		bp->b_pages[index] = p;
4531 	}
4532 	bp->b_npages = index;
4533 }
4534 
4535 /* Return pages associated with this buf to the vm system */
4536 static void
4537 vm_hold_free_pages(struct buf *bp, int newbsize)
4538 {
4539 	vm_offset_t from;
4540 	vm_page_t p;
4541 	int index, newnpages;
4542 
4543 	BUF_CHECK_MAPPED(bp);
4544 
4545 	from = round_page((vm_offset_t)bp->b_data + newbsize);
4546 	newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4547 	if (bp->b_npages > newnpages)
4548 		pmap_qremove(from, bp->b_npages - newnpages);
4549 	for (index = newnpages; index < bp->b_npages; index++) {
4550 		p = bp->b_pages[index];
4551 		bp->b_pages[index] = NULL;
4552 		p->wire_count--;
4553 		vm_page_free(p);
4554 	}
4555 	vm_wire_sub(bp->b_npages - newnpages);
4556 	bp->b_npages = newnpages;
4557 }
4558 
4559 /*
4560  * Map an IO request into kernel virtual address space.
4561  *
4562  * All requests are (re)mapped into kernel VA space.
4563  * Notice that we use b_bufsize for the size of the buffer
4564  * to be mapped.  b_bcount might be modified by the driver.
4565  *
4566  * Note that even if the caller determines that the address space should
4567  * be valid, a race or a smaller-file mapped into a larger space may
4568  * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4569  * check the return value.
4570  *
4571  * This function only works with pager buffers.
4572  */
4573 int
4574 vmapbuf(struct buf *bp, int mapbuf)
4575 {
4576 	vm_prot_t prot;
4577 	int pidx;
4578 
4579 	if (bp->b_bufsize < 0)
4580 		return (-1);
4581 	prot = VM_PROT_READ;
4582 	if (bp->b_iocmd == BIO_READ)
4583 		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
4584 	if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4585 	    (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4586 	    btoc(MAXPHYS))) < 0)
4587 		return (-1);
4588 	bp->b_npages = pidx;
4589 	bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4590 	if (mapbuf || !unmapped_buf_allowed) {
4591 		pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
4592 		bp->b_data = bp->b_kvabase + bp->b_offset;
4593 	} else
4594 		bp->b_data = unmapped_buf;
4595 	return(0);
4596 }
4597 
4598 /*
4599  * Free the io map PTEs associated with this IO operation.
4600  * We also invalidate the TLB entries and restore the original b_addr.
4601  *
4602  * This function only works with pager buffers.
4603  */
4604 void
4605 vunmapbuf(struct buf *bp)
4606 {
4607 	int npages;
4608 
4609 	npages = bp->b_npages;
4610 	if (buf_mapped(bp))
4611 		pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4612 	vm_page_unhold_pages(bp->b_pages, npages);
4613 
4614 	bp->b_data = unmapped_buf;
4615 }
4616 
4617 void
4618 bdone(struct buf *bp)
4619 {
4620 	struct mtx *mtxp;
4621 
4622 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
4623 	mtx_lock(mtxp);
4624 	bp->b_flags |= B_DONE;
4625 	wakeup(bp);
4626 	mtx_unlock(mtxp);
4627 }
4628 
4629 void
4630 bwait(struct buf *bp, u_char pri, const char *wchan)
4631 {
4632 	struct mtx *mtxp;
4633 
4634 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
4635 	mtx_lock(mtxp);
4636 	while ((bp->b_flags & B_DONE) == 0)
4637 		msleep(bp, mtxp, pri, wchan, 0);
4638 	mtx_unlock(mtxp);
4639 }
4640 
4641 int
4642 bufsync(struct bufobj *bo, int waitfor)
4643 {
4644 
4645 	return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
4646 }
4647 
4648 void
4649 bufstrategy(struct bufobj *bo, struct buf *bp)
4650 {
4651 	int i = 0;
4652 	struct vnode *vp;
4653 
4654 	vp = bp->b_vp;
4655 	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4656 	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4657 	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4658 	i = VOP_STRATEGY(vp, bp);
4659 	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4660 }
4661 
4662 void
4663 bufobj_wrefl(struct bufobj *bo)
4664 {
4665 
4666 	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4667 	ASSERT_BO_WLOCKED(bo);
4668 	bo->bo_numoutput++;
4669 }
4670 
4671 void
4672 bufobj_wref(struct bufobj *bo)
4673 {
4674 
4675 	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4676 	BO_LOCK(bo);
4677 	bo->bo_numoutput++;
4678 	BO_UNLOCK(bo);
4679 }
4680 
4681 void
4682 bufobj_wdrop(struct bufobj *bo)
4683 {
4684 
4685 	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4686 	BO_LOCK(bo);
4687 	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4688 	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4689 		bo->bo_flag &= ~BO_WWAIT;
4690 		wakeup(&bo->bo_numoutput);
4691 	}
4692 	BO_UNLOCK(bo);
4693 }
4694 
4695 int
4696 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4697 {
4698 	int error;
4699 
4700 	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4701 	ASSERT_BO_WLOCKED(bo);
4702 	error = 0;
4703 	while (bo->bo_numoutput) {
4704 		bo->bo_flag |= BO_WWAIT;
4705 		error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4706 		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4707 		if (error)
4708 			break;
4709 	}
4710 	return (error);
4711 }
4712 
4713 /*
4714  * Set bio_data or bio_ma for struct bio from the struct buf.
4715  */
4716 void
4717 bdata2bio(struct buf *bp, struct bio *bip)
4718 {
4719 
4720 	if (!buf_mapped(bp)) {
4721 		KASSERT(unmapped_buf_allowed, ("unmapped"));
4722 		bip->bio_ma = bp->b_pages;
4723 		bip->bio_ma_n = bp->b_npages;
4724 		bip->bio_data = unmapped_buf;
4725 		bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4726 		bip->bio_flags |= BIO_UNMAPPED;
4727 		KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4728 		    PAGE_SIZE == bp->b_npages,
4729 		    ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4730 		    (long long)bip->bio_length, bip->bio_ma_n));
4731 	} else {
4732 		bip->bio_data = bp->b_data;
4733 		bip->bio_ma = NULL;
4734 	}
4735 }
4736 
4737 /*
4738  * The MIPS pmap code currently doesn't handle aliased pages.
4739  * The VIPT caches may not handle page aliasing themselves, leading
4740  * to data corruption.
4741  *
4742  * As such, this code makes a system extremely unhappy if said
4743  * system doesn't support unaliasing the above situation in hardware.
4744  * Some "recent" systems (eg some mips24k/mips74k cores) don't enable
4745  * this feature at build time, so it has to be handled in software.
4746  *
4747  * Once the MIPS pmap/cache code grows to support this function on
4748  * earlier chips, it should be flipped back off.
4749  */
4750 #ifdef	__mips__
4751 static int buf_pager_relbuf = 1;
4752 #else
4753 static int buf_pager_relbuf = 0;
4754 #endif
4755 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
4756     &buf_pager_relbuf, 0,
4757     "Make buffer pager release buffers after reading");
4758 
4759 /*
4760  * The buffer pager.  It uses buffer reads to validate pages.
4761  *
4762  * In contrast to the generic local pager from vm/vnode_pager.c, this
4763  * pager correctly and easily handles volumes where the underlying
4764  * device block size is greater than the machine page size.  The
4765  * buffer cache transparently extends the requested page run to be
4766  * aligned at the block boundary, and does the necessary bogus page
4767  * replacements in the addends to avoid obliterating already valid
4768  * pages.
4769  *
4770  * The only non-trivial issue is that the exclusive busy state for
4771  * pages, which is assumed by the vm_pager_getpages() interface, is
4772  * incompatible with the VMIO buffer cache's desire to share-busy the
4773  * pages.  This function performs a trivial downgrade of the pages'
4774  * state before reading buffers, and a less trivial upgrade from the
4775  * shared-busy to excl-busy state after the read.
4776  */
4777 int
4778 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
4779     int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
4780     vbg_get_blksize_t get_blksize)
4781 {
4782 	vm_page_t m;
4783 	vm_object_t object;
4784 	struct buf *bp;
4785 	struct mount *mp;
4786 	daddr_t lbn, lbnp;
4787 	vm_ooffset_t la, lb, poff, poffe;
4788 	long bsize;
4789 	int bo_bs, br_flags, error, i, pgsin, pgsin_a, pgsin_b;
4790 	bool redo, lpart;
4791 
4792 	object = vp->v_object;
4793 	mp = vp->v_mount;
4794 	la = IDX_TO_OFF(ma[count - 1]->pindex);
4795 	if (la >= object->un_pager.vnp.vnp_size)
4796 		return (VM_PAGER_BAD);
4797 
4798 	/*
4799 	 * Change the meaning of la from where the last requested page starts
4800 	 * to where it ends, because that's the end of the requested region
4801 	 * and the start of the potential read-ahead region.
4802 	 */
4803 	la += PAGE_SIZE;
4804 	lpart = la > object->un_pager.vnp.vnp_size;
4805 	bo_bs = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)));
4806 
4807 	/*
4808 	 * Calculate read-ahead, behind and total pages.
4809 	 */
4810 	pgsin = count;
4811 	lb = IDX_TO_OFF(ma[0]->pindex);
4812 	pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
4813 	pgsin += pgsin_b;
4814 	if (rbehind != NULL)
4815 		*rbehind = pgsin_b;
4816 	pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
4817 	if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
4818 		pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
4819 		    PAGE_SIZE) - la);
4820 	pgsin += pgsin_a;
4821 	if (rahead != NULL)
4822 		*rahead = pgsin_a;
4823 	VM_CNT_INC(v_vnodein);
4824 	VM_CNT_ADD(v_vnodepgsin, pgsin);
4825 
4826 	br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
4827 	    != 0) ? GB_UNMAPPED : 0;
4828 	VM_OBJECT_WLOCK(object);
4829 again:
4830 	for (i = 0; i < count; i++)
4831 		vm_page_busy_downgrade(ma[i]);
4832 	VM_OBJECT_WUNLOCK(object);
4833 
4834 	lbnp = -1;
4835 	for (i = 0; i < count; i++) {
4836 		m = ma[i];
4837 
4838 		/*
4839 		 * Pages are shared busy and the object lock is not
4840 		 * owned, which together allow for the pages'
4841 		 * invalidation.  The racy test for validity avoids
4842 		 * useless creation of the buffer for the most typical
4843 		 * case when invalidation is not used in redo or for
4844 		 * parallel read.  The shared->excl upgrade loop at
4845 		 * the end of the function catches the race in a
4846 		 * reliable way (protected by the object lock).
4847 		 */
4848 		if (m->valid == VM_PAGE_BITS_ALL)
4849 			continue;
4850 
4851 		poff = IDX_TO_OFF(m->pindex);
4852 		poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
4853 		for (; poff < poffe; poff += bsize) {
4854 			lbn = get_lblkno(vp, poff);
4855 			if (lbn == lbnp)
4856 				goto next_page;
4857 			lbnp = lbn;
4858 
4859 			bsize = get_blksize(vp, lbn);
4860 			error = bread_gb(vp, lbn, bsize, curthread->td_ucred,
4861 			    br_flags, &bp);
4862 			if (error != 0)
4863 				goto end_pages;
4864 			if (LIST_EMPTY(&bp->b_dep)) {
4865 				/*
4866 				 * Invalidation clears m->valid, but
4867 				 * may leave B_CACHE flag if the
4868 				 * buffer existed at the invalidation
4869 				 * time.  In this case, recycle the
4870 				 * buffer to do real read on next
4871 				 * bread() after redo.
4872 				 *
4873 				 * Otherwise B_RELBUF is not strictly
4874 				 * necessary, enable to reduce buf
4875 				 * cache pressure.
4876 				 */
4877 				if (buf_pager_relbuf ||
4878 				    m->valid != VM_PAGE_BITS_ALL)
4879 					bp->b_flags |= B_RELBUF;
4880 
4881 				bp->b_flags &= ~B_NOCACHE;
4882 				brelse(bp);
4883 			} else {
4884 				bqrelse(bp);
4885 			}
4886 		}
4887 		KASSERT(1 /* racy, enable for debugging */ ||
4888 		    m->valid == VM_PAGE_BITS_ALL || i == count - 1,
4889 		    ("buf %d %p invalid", i, m));
4890 		if (i == count - 1 && lpart) {
4891 			VM_OBJECT_WLOCK(object);
4892 			if (m->valid != 0 &&
4893 			    m->valid != VM_PAGE_BITS_ALL)
4894 				vm_page_zero_invalid(m, TRUE);
4895 			VM_OBJECT_WUNLOCK(object);
4896 		}
4897 next_page:;
4898 	}
4899 end_pages:
4900 
4901 	VM_OBJECT_WLOCK(object);
4902 	redo = false;
4903 	for (i = 0; i < count; i++) {
4904 		vm_page_sunbusy(ma[i]);
4905 		ma[i] = vm_page_grab(object, ma[i]->pindex, VM_ALLOC_NORMAL);
4906 
4907 		/*
4908 		 * Since the pages were only sbusy while neither the
4909 		 * buffer nor the object lock was held by us, or
4910 		 * reallocated while vm_page_grab() slept for busy
4911 		 * relinguish, they could have been invalidated.
4912 		 * Recheck the valid bits and re-read as needed.
4913 		 *
4914 		 * Note that the last page is made fully valid in the
4915 		 * read loop, and partial validity for the page at
4916 		 * index count - 1 could mean that the page was
4917 		 * invalidated or removed, so we must restart for
4918 		 * safety as well.
4919 		 */
4920 		if (ma[i]->valid != VM_PAGE_BITS_ALL)
4921 			redo = true;
4922 	}
4923 	if (redo && error == 0)
4924 		goto again;
4925 	VM_OBJECT_WUNLOCK(object);
4926 	return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
4927 }
4928 
4929 #include "opt_ddb.h"
4930 #ifdef DDB
4931 #include <ddb/ddb.h>
4932 
4933 /* DDB command to show buffer data */
4934 DB_SHOW_COMMAND(buffer, db_show_buffer)
4935 {
4936 	/* get args */
4937 	struct buf *bp = (struct buf *)addr;
4938 #ifdef FULL_BUF_TRACKING
4939 	uint32_t i, j;
4940 #endif
4941 
4942 	if (!have_addr) {
4943 		db_printf("usage: show buffer <addr>\n");
4944 		return;
4945 	}
4946 
4947 	db_printf("buf at %p\n", bp);
4948 	db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4949 	    (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4950 	    PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4951 	db_printf(
4952 	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4953 	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4954 	    "b_dep = %p\n",
4955 	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4956 	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4957 	    (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4958 	db_printf("b_kvabase = %p, b_kvasize = %d\n",
4959 	    bp->b_kvabase, bp->b_kvasize);
4960 	if (bp->b_npages) {
4961 		int i;
4962 		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4963 		for (i = 0; i < bp->b_npages; i++) {
4964 			vm_page_t m;
4965 			m = bp->b_pages[i];
4966 			if (m != NULL)
4967 				db_printf("(%p, 0x%lx, 0x%lx)", m->object,
4968 				    (u_long)m->pindex,
4969 				    (u_long)VM_PAGE_TO_PHYS(m));
4970 			else
4971 				db_printf("( ??? )");
4972 			if ((i + 1) < bp->b_npages)
4973 				db_printf(",");
4974 		}
4975 		db_printf("\n");
4976 	}
4977 #if defined(FULL_BUF_TRACKING)
4978 	db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
4979 
4980 	i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
4981 	for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
4982 		if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
4983 			continue;
4984 		db_printf(" %2u: %s\n", j,
4985 		    bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
4986 	}
4987 #elif defined(BUF_TRACKING)
4988 	db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
4989 #endif
4990 	db_printf(" ");
4991 	BUF_LOCKPRINTINFO(bp);
4992 }
4993 
4994 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4995 {
4996 	struct buf *bp;
4997 	int i;
4998 
4999 	for (i = 0; i < nbuf; i++) {
5000 		bp = &buf[i];
5001 		if (BUF_ISLOCKED(bp)) {
5002 			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5003 			db_printf("\n");
5004 			if (db_pager_quit)
5005 				break;
5006 		}
5007 	}
5008 }
5009 
5010 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5011 {
5012 	struct vnode *vp;
5013 	struct buf *bp;
5014 
5015 	if (!have_addr) {
5016 		db_printf("usage: show vnodebufs <addr>\n");
5017 		return;
5018 	}
5019 	vp = (struct vnode *)addr;
5020 	db_printf("Clean buffers:\n");
5021 	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5022 		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5023 		db_printf("\n");
5024 	}
5025 	db_printf("Dirty buffers:\n");
5026 	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5027 		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5028 		db_printf("\n");
5029 	}
5030 }
5031 
5032 DB_COMMAND(countfreebufs, db_coundfreebufs)
5033 {
5034 	struct buf *bp;
5035 	int i, used = 0, nfree = 0;
5036 
5037 	if (have_addr) {
5038 		db_printf("usage: countfreebufs\n");
5039 		return;
5040 	}
5041 
5042 	for (i = 0; i < nbuf; i++) {
5043 		bp = &buf[i];
5044 		if (bp->b_qindex == QUEUE_EMPTY)
5045 			nfree++;
5046 		else
5047 			used++;
5048 	}
5049 
5050 	db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5051 	    nfree + used);
5052 	db_printf("numfreebuffers is %d\n", numfreebuffers);
5053 }
5054 #endif /* DDB */
5055