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