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