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