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