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