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