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