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