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