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