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