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