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