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