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