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