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