vfs_bio.c revision 177475
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 177475 2008-03-21 12:38:44Z kib $");
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	int i;
1612	int j;
1613	daddr_t lblkno = bp->b_lblkno;
1614	struct vnode *vp = bp->b_vp;
1615	int ncl;
1616	int nwritten;
1617	int size;
1618	int maxcl;
1619
1620	/*
1621	 * right now we support clustered writing only to regular files.  If
1622	 * we find a clusterable block we could be in the middle of a cluster
1623	 * rather then at the beginning.
1624	 */
1625	if ((vp->v_type == VREG) &&
1626	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1627	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1628
1629		size = vp->v_mount->mnt_stat.f_iosize;
1630		maxcl = MAXPHYS / size;
1631
1632		VI_LOCK(vp);
1633		for (i = 1; i < maxcl; i++)
1634			if (vfs_bio_clcheck(vp, size, lblkno + i,
1635			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1636				break;
1637
1638		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1639			if (vfs_bio_clcheck(vp, size, lblkno - j,
1640			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1641				break;
1642
1643		VI_UNLOCK(vp);
1644		--j;
1645		ncl = i + j;
1646		/*
1647		 * this is a possible cluster write
1648		 */
1649		if (ncl != 1) {
1650			BUF_UNLOCK(bp);
1651			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1652			return nwritten;
1653		}
1654	}
1655	bremfree(bp);
1656	bp->b_flags |= B_ASYNC;
1657	/*
1658	 * default (old) behavior, writing out only one block
1659	 *
1660	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1661	 */
1662	nwritten = bp->b_bufsize;
1663	(void) bwrite(bp);
1664
1665	return nwritten;
1666}
1667
1668/*
1669 *	getnewbuf:
1670 *
1671 *	Find and initialize a new buffer header, freeing up existing buffers
1672 *	in the bufqueues as necessary.  The new buffer is returned locked.
1673 *
1674 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1675 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1676 *
1677 *	We block if:
1678 *		We have insufficient buffer headers
1679 *		We have insufficient buffer space
1680 *		buffer_map is too fragmented ( space reservation fails )
1681 *		If we have to flush dirty buffers ( but we try to avoid this )
1682 *
1683 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1684 *	Instead we ask the buf daemon to do it for us.  We attempt to
1685 *	avoid piecemeal wakeups of the pageout daemon.
1686 */
1687
1688static struct buf *
1689getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1690{
1691	struct buf *bp;
1692	struct buf *nbp;
1693	int defrag = 0;
1694	int nqindex;
1695	int waiters = 0;
1696	static int flushingbufs;
1697
1698	/*
1699	 * We can't afford to block since we might be holding a vnode lock,
1700	 * which may prevent system daemons from running.  We deal with
1701	 * low-memory situations by proactively returning memory and running
1702	 * async I/O rather then sync I/O.
1703	 */
1704
1705	atomic_add_int(&getnewbufcalls, 1);
1706	atomic_subtract_int(&getnewbufrestarts, 1);
1707restart:
1708	atomic_add_int(&getnewbufrestarts, 1);
1709
1710	/*
1711	 * Setup for scan.  If we do not have enough free buffers,
1712	 * we setup a degenerate case that immediately fails.  Note
1713	 * that if we are specially marked process, we are allowed to
1714	 * dip into our reserves.
1715	 *
1716	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1717	 *
1718	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1719	 * However, there are a number of cases (defragging, reusing, ...)
1720	 * where we cannot backup.
1721	 */
1722	mtx_lock(&bqlock);
1723	nqindex = QUEUE_EMPTYKVA;
1724	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1725
1726	if (nbp == NULL) {
1727		/*
1728		 * If no EMPTYKVA buffers and we are either
1729		 * defragging or reusing, locate a CLEAN buffer
1730		 * to free or reuse.  If bufspace useage is low
1731		 * skip this step so we can allocate a new buffer.
1732		 */
1733		if (defrag || bufspace >= lobufspace) {
1734			nqindex = QUEUE_CLEAN;
1735			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1736		}
1737
1738		/*
1739		 * If we could not find or were not allowed to reuse a
1740		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1741		 * buffer.  We can only use an EMPTY buffer if allocating
1742		 * its KVA would not otherwise run us out of buffer space.
1743		 */
1744		if (nbp == NULL && defrag == 0 &&
1745		    bufspace + maxsize < hibufspace) {
1746			nqindex = QUEUE_EMPTY;
1747			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1748		}
1749	}
1750
1751	/*
1752	 * Run scan, possibly freeing data and/or kva mappings on the fly
1753	 * depending.
1754	 */
1755
1756	while ((bp = nbp) != NULL) {
1757		int qindex = nqindex;
1758
1759		/*
1760		 * Calculate next bp ( we can only use it if we do not block
1761		 * or do other fancy things ).
1762		 */
1763		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1764			switch(qindex) {
1765			case QUEUE_EMPTY:
1766				nqindex = QUEUE_EMPTYKVA;
1767				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1768					break;
1769				/* FALLTHROUGH */
1770			case QUEUE_EMPTYKVA:
1771				nqindex = QUEUE_CLEAN;
1772				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1773					break;
1774				/* FALLTHROUGH */
1775			case QUEUE_CLEAN:
1776				/*
1777				 * nbp is NULL.
1778				 */
1779				break;
1780			}
1781		}
1782		/*
1783		 * If we are defragging then we need a buffer with
1784		 * b_kvasize != 0.  XXX this situation should no longer
1785		 * occur, if defrag is non-zero the buffer's b_kvasize
1786		 * should also be non-zero at this point.  XXX
1787		 */
1788		if (defrag && bp->b_kvasize == 0) {
1789			printf("Warning: defrag empty buffer %p\n", bp);
1790			continue;
1791		}
1792
1793		/*
1794		 * Start freeing the bp.  This is somewhat involved.  nbp
1795		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1796		 */
1797		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1798			continue;
1799		if (bp->b_vp) {
1800			BO_LOCK(bp->b_bufobj);
1801			if (bp->b_vflags & BV_BKGRDINPROG) {
1802				BO_UNLOCK(bp->b_bufobj);
1803				BUF_UNLOCK(bp);
1804				continue;
1805			}
1806			BO_UNLOCK(bp->b_bufobj);
1807		}
1808		CTR6(KTR_BUF,
1809		    "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1810		    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1811		    bp->b_kvasize, bp->b_bufsize, qindex);
1812
1813		/*
1814		 * Sanity Checks
1815		 */
1816		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1817
1818		/*
1819		 * Note: we no longer distinguish between VMIO and non-VMIO
1820		 * buffers.
1821		 */
1822
1823		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1824
1825		bremfreel(bp);
1826		mtx_unlock(&bqlock);
1827
1828		if (qindex == QUEUE_CLEAN) {
1829			if (bp->b_flags & B_VMIO) {
1830				bp->b_flags &= ~B_ASYNC;
1831				vfs_vmio_release(bp);
1832			}
1833			if (bp->b_vp)
1834				waiters = brelvp(bp);
1835		}
1836
1837		/*
1838		 * NOTE:  nbp is now entirely invalid.  We can only restart
1839		 * the scan from this point on.
1840		 *
1841		 * Get the rest of the buffer freed up.  b_kva* is still
1842		 * valid after this operation.
1843		 */
1844
1845		if (bp->b_rcred != NOCRED) {
1846			crfree(bp->b_rcred);
1847			bp->b_rcred = NOCRED;
1848		}
1849		if (bp->b_wcred != NOCRED) {
1850			crfree(bp->b_wcred);
1851			bp->b_wcred = NOCRED;
1852		}
1853		if (!LIST_EMPTY(&bp->b_dep))
1854			buf_deallocate(bp);
1855		if (bp->b_vflags & BV_BKGRDINPROG)
1856			panic("losing buffer 3");
1857		KASSERT(bp->b_vp == NULL,
1858		    ("bp: %p still has vnode %p.  qindex: %d",
1859		    bp, bp->b_vp, qindex));
1860		KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1861		   ("bp: %p still on a buffer list. xflags %X",
1862		    bp, bp->b_xflags));
1863
1864		if (bp->b_bufsize)
1865			allocbuf(bp, 0);
1866
1867		bp->b_flags = 0;
1868		bp->b_ioflags = 0;
1869		bp->b_xflags = 0;
1870		bp->b_vflags = 0;
1871		bp->b_vp = NULL;
1872		bp->b_blkno = bp->b_lblkno = 0;
1873		bp->b_offset = NOOFFSET;
1874		bp->b_iodone = 0;
1875		bp->b_error = 0;
1876		bp->b_resid = 0;
1877		bp->b_bcount = 0;
1878		bp->b_npages = 0;
1879		bp->b_dirtyoff = bp->b_dirtyend = 0;
1880		bp->b_bufobj = NULL;
1881		bp->b_pin_count = 0;
1882		bp->b_fsprivate1 = NULL;
1883		bp->b_fsprivate2 = NULL;
1884		bp->b_fsprivate3 = NULL;
1885
1886		LIST_INIT(&bp->b_dep);
1887
1888		/*
1889		 * If we are defragging then free the buffer.
1890		 */
1891		if (defrag) {
1892			bp->b_flags |= B_INVAL;
1893			bfreekva(bp);
1894			brelse(bp);
1895			defrag = 0;
1896			goto restart;
1897		}
1898
1899		/*
1900		 * Notify any waiters for the buffer lock about
1901		 * identity change by freeing the buffer.
1902		 */
1903		if (qindex == QUEUE_CLEAN && waiters > 0) {
1904			bp->b_flags |= B_INVAL;
1905			bfreekva(bp);
1906			brelse(bp);
1907			goto restart;
1908		}
1909
1910		/*
1911		 * If we are overcomitted then recover the buffer and its
1912		 * KVM space.  This occurs in rare situations when multiple
1913		 * processes are blocked in getnewbuf() or allocbuf().
1914		 */
1915		if (bufspace >= hibufspace)
1916			flushingbufs = 1;
1917		if (flushingbufs && bp->b_kvasize != 0) {
1918			bp->b_flags |= B_INVAL;
1919			bfreekva(bp);
1920			brelse(bp);
1921			goto restart;
1922		}
1923		if (bufspace < lobufspace)
1924			flushingbufs = 0;
1925		break;
1926	}
1927
1928	/*
1929	 * If we exhausted our list, sleep as appropriate.  We may have to
1930	 * wakeup various daemons and write out some dirty buffers.
1931	 *
1932	 * Generally we are sleeping due to insufficient buffer space.
1933	 */
1934
1935	if (bp == NULL) {
1936		int flags;
1937		char *waitmsg;
1938
1939		if (defrag) {
1940			flags = VFS_BIO_NEED_BUFSPACE;
1941			waitmsg = "nbufkv";
1942		} else if (bufspace >= hibufspace) {
1943			waitmsg = "nbufbs";
1944			flags = VFS_BIO_NEED_BUFSPACE;
1945		} else {
1946			waitmsg = "newbuf";
1947			flags = VFS_BIO_NEED_ANY;
1948		}
1949		mtx_lock(&nblock);
1950		needsbuffer |= flags;
1951		mtx_unlock(&nblock);
1952		mtx_unlock(&bqlock);
1953
1954		bd_speedup();	/* heeeelp */
1955
1956		mtx_lock(&nblock);
1957		while (needsbuffer & flags) {
1958			if (msleep(&needsbuffer, &nblock,
1959			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
1960				mtx_unlock(&nblock);
1961				return (NULL);
1962			}
1963		}
1964		mtx_unlock(&nblock);
1965	} else {
1966		/*
1967		 * We finally have a valid bp.  We aren't quite out of the
1968		 * woods, we still have to reserve kva space.  In order
1969		 * to keep fragmentation sane we only allocate kva in
1970		 * BKVASIZE chunks.
1971		 */
1972		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1973
1974		if (maxsize != bp->b_kvasize) {
1975			vm_offset_t addr = 0;
1976
1977			bfreekva(bp);
1978
1979			vm_map_lock(buffer_map);
1980			if (vm_map_findspace(buffer_map,
1981				vm_map_min(buffer_map), maxsize, &addr)) {
1982				/*
1983				 * Uh oh.  Buffer map is to fragmented.  We
1984				 * must defragment the map.
1985				 */
1986				atomic_add_int(&bufdefragcnt, 1);
1987				vm_map_unlock(buffer_map);
1988				defrag = 1;
1989				bp->b_flags |= B_INVAL;
1990				brelse(bp);
1991				goto restart;
1992			}
1993			if (addr) {
1994				vm_map_insert(buffer_map, NULL, 0,
1995					addr, addr + maxsize,
1996					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1997
1998				bp->b_kvabase = (caddr_t) addr;
1999				bp->b_kvasize = maxsize;
2000				atomic_add_int(&bufspace, bp->b_kvasize);
2001				atomic_add_int(&bufreusecnt, 1);
2002			}
2003			vm_map_unlock(buffer_map);
2004		}
2005		bp->b_saveaddr = bp->b_kvabase;
2006		bp->b_data = bp->b_saveaddr;
2007	}
2008	return(bp);
2009}
2010
2011/*
2012 *	buf_daemon:
2013 *
2014 *	buffer flushing daemon.  Buffers are normally flushed by the
2015 *	update daemon but if it cannot keep up this process starts to
2016 *	take the load in an attempt to prevent getnewbuf() from blocking.
2017 */
2018
2019static struct kproc_desc buf_kp = {
2020	"bufdaemon",
2021	buf_daemon,
2022	&bufdaemonproc
2023};
2024SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2025
2026static void
2027buf_daemon()
2028{
2029
2030	/*
2031	 * This process needs to be suspended prior to shutdown sync.
2032	 */
2033	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2034	    SHUTDOWN_PRI_LAST);
2035
2036	/*
2037	 * This process is allowed to take the buffer cache to the limit
2038	 */
2039	curthread->td_pflags |= TDP_NORUNNINGBUF;
2040	mtx_lock(&bdlock);
2041	for (;;) {
2042		bd_request = 0;
2043		mtx_unlock(&bdlock);
2044
2045		kproc_suspend_check(bufdaemonproc);
2046
2047		/*
2048		 * Do the flush.  Limit the amount of in-transit I/O we
2049		 * allow to build up, otherwise we would completely saturate
2050		 * the I/O system.  Wakeup any waiting processes before we
2051		 * normally would so they can run in parallel with our drain.
2052		 */
2053		while (numdirtybuffers > lodirtybuffers) {
2054			int flushed;
2055
2056			flushed = flushbufqueues(QUEUE_DIRTY, 0);
2057			/* The list empty check here is slightly racy */
2058			if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2059				mtx_lock(&Giant);
2060				flushed += flushbufqueues(QUEUE_DIRTY_GIANT, 0);
2061				mtx_unlock(&Giant);
2062			}
2063			if (flushed == 0) {
2064				/*
2065				 * Could not find any buffers without rollback
2066				 * dependencies, so just write the first one
2067				 * in the hopes of eventually making progress.
2068				 */
2069				flushbufqueues(QUEUE_DIRTY, 1);
2070				if (!TAILQ_EMPTY(
2071				    &bufqueues[QUEUE_DIRTY_GIANT])) {
2072					mtx_lock(&Giant);
2073					flushbufqueues(QUEUE_DIRTY_GIANT, 1);
2074					mtx_unlock(&Giant);
2075				}
2076				break;
2077			}
2078			uio_yield();
2079		}
2080
2081		/*
2082		 * Only clear bd_request if we have reached our low water
2083		 * mark.  The buf_daemon normally waits 1 second and
2084		 * then incrementally flushes any dirty buffers that have
2085		 * built up, within reason.
2086		 *
2087		 * If we were unable to hit our low water mark and couldn't
2088		 * find any flushable buffers, we sleep half a second.
2089		 * Otherwise we loop immediately.
2090		 */
2091		mtx_lock(&bdlock);
2092		if (numdirtybuffers <= lodirtybuffers) {
2093			/*
2094			 * We reached our low water mark, reset the
2095			 * request and sleep until we are needed again.
2096			 * The sleep is just so the suspend code works.
2097			 */
2098			bd_request = 0;
2099			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2100		} else {
2101			/*
2102			 * We couldn't find any flushable dirty buffers but
2103			 * still have too many dirty buffers, we
2104			 * have to sleep and try again.  (rare)
2105			 */
2106			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2107		}
2108	}
2109}
2110
2111/*
2112 *	flushbufqueues:
2113 *
2114 *	Try to flush a buffer in the dirty queue.  We must be careful to
2115 *	free up B_INVAL buffers instead of write them, which NFS is
2116 *	particularly sensitive to.
2117 */
2118static int flushwithdeps = 0;
2119SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2120    0, "Number of buffers flushed with dependecies that require rollbacks");
2121
2122static int
2123flushbufqueues(int queue, int flushdeps)
2124{
2125	struct buf sentinel;
2126	struct vnode *vp;
2127	struct mount *mp;
2128	struct buf *bp;
2129	int hasdeps;
2130	int flushed;
2131	int target;
2132
2133	target = numdirtybuffers - lodirtybuffers;
2134	if (flushdeps && target > 2)
2135		target /= 2;
2136	flushed = 0;
2137	bp = NULL;
2138	mtx_lock(&bqlock);
2139	TAILQ_INSERT_TAIL(&bufqueues[queue], &sentinel, b_freelist);
2140	while (flushed != target) {
2141		bp = TAILQ_FIRST(&bufqueues[queue]);
2142		if (bp == &sentinel)
2143			break;
2144		TAILQ_REMOVE(&bufqueues[queue], bp, b_freelist);
2145		TAILQ_INSERT_TAIL(&bufqueues[queue], bp, b_freelist);
2146
2147		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2148			continue;
2149		if (bp->b_pin_count > 0) {
2150			BUF_UNLOCK(bp);
2151			continue;
2152		}
2153		BO_LOCK(bp->b_bufobj);
2154		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2155		    (bp->b_flags & B_DELWRI) == 0) {
2156			BO_UNLOCK(bp->b_bufobj);
2157			BUF_UNLOCK(bp);
2158			continue;
2159		}
2160		BO_UNLOCK(bp->b_bufobj);
2161		if (bp->b_flags & B_INVAL) {
2162			bremfreel(bp);
2163			mtx_unlock(&bqlock);
2164			brelse(bp);
2165			flushed++;
2166			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2167			mtx_lock(&bqlock);
2168			continue;
2169		}
2170
2171		if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2172			if (flushdeps == 0) {
2173				BUF_UNLOCK(bp);
2174				continue;
2175			}
2176			hasdeps = 1;
2177		} else
2178			hasdeps = 0;
2179		/*
2180		 * We must hold the lock on a vnode before writing
2181		 * one of its buffers. Otherwise we may confuse, or
2182		 * in the case of a snapshot vnode, deadlock the
2183		 * system.
2184		 *
2185		 * The lock order here is the reverse of the normal
2186		 * of vnode followed by buf lock.  This is ok because
2187		 * the NOWAIT will prevent deadlock.
2188		 */
2189		vp = bp->b_vp;
2190		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2191			BUF_UNLOCK(bp);
2192			continue;
2193		}
2194		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2195			mtx_unlock(&bqlock);
2196			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2197			    bp, bp->b_vp, bp->b_flags);
2198			vfs_bio_awrite(bp);
2199			vn_finished_write(mp);
2200			VOP_UNLOCK(vp, 0);
2201			flushwithdeps += hasdeps;
2202			flushed++;
2203			waitrunningbufspace();
2204			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2205			mtx_lock(&bqlock);
2206			continue;
2207		}
2208		vn_finished_write(mp);
2209		BUF_UNLOCK(bp);
2210	}
2211	TAILQ_REMOVE(&bufqueues[queue], &sentinel, b_freelist);
2212	mtx_unlock(&bqlock);
2213	return (flushed);
2214}
2215
2216/*
2217 * Check to see if a block is currently memory resident.
2218 */
2219struct buf *
2220incore(struct bufobj *bo, daddr_t blkno)
2221{
2222	struct buf *bp;
2223
2224	BO_LOCK(bo);
2225	bp = gbincore(bo, blkno);
2226	BO_UNLOCK(bo);
2227	return (bp);
2228}
2229
2230/*
2231 * Returns true if no I/O is needed to access the
2232 * associated VM object.  This is like incore except
2233 * it also hunts around in the VM system for the data.
2234 */
2235
2236static int
2237inmem(struct vnode * vp, daddr_t blkno)
2238{
2239	vm_object_t obj;
2240	vm_offset_t toff, tinc, size;
2241	vm_page_t m;
2242	vm_ooffset_t off;
2243
2244	ASSERT_VOP_LOCKED(vp, "inmem");
2245
2246	if (incore(&vp->v_bufobj, blkno))
2247		return 1;
2248	if (vp->v_mount == NULL)
2249		return 0;
2250	obj = vp->v_object;
2251	if (obj == NULL)
2252		return (0);
2253
2254	size = PAGE_SIZE;
2255	if (size > vp->v_mount->mnt_stat.f_iosize)
2256		size = vp->v_mount->mnt_stat.f_iosize;
2257	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2258
2259	VM_OBJECT_LOCK(obj);
2260	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2261		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2262		if (!m)
2263			goto notinmem;
2264		tinc = size;
2265		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2266			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2267		if (vm_page_is_valid(m,
2268		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2269			goto notinmem;
2270	}
2271	VM_OBJECT_UNLOCK(obj);
2272	return 1;
2273
2274notinmem:
2275	VM_OBJECT_UNLOCK(obj);
2276	return (0);
2277}
2278
2279/*
2280 *	vfs_setdirty:
2281 *
2282 *	Sets the dirty range for a buffer based on the status of the dirty
2283 *	bits in the pages comprising the buffer.
2284 *
2285 *	The range is limited to the size of the buffer.
2286 *
2287 *	This routine is primarily used by NFS, but is generalized for the
2288 *	B_VMIO case.
2289 */
2290static void
2291vfs_setdirty(struct buf *bp)
2292{
2293
2294	/*
2295	 * Degenerate case - empty buffer
2296	 */
2297
2298	if (bp->b_bufsize == 0)
2299		return;
2300
2301	/*
2302	 * We qualify the scan for modified pages on whether the
2303	 * object has been flushed yet.
2304	 */
2305
2306	if ((bp->b_flags & B_VMIO) == 0)
2307		return;
2308
2309	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2310	vfs_setdirty_locked_object(bp);
2311	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2312}
2313
2314static void
2315vfs_setdirty_locked_object(struct buf *bp)
2316{
2317	vm_object_t object;
2318	int i;
2319
2320	object = bp->b_bufobj->bo_object;
2321	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2322	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2323		vm_offset_t boffset;
2324		vm_offset_t eoffset;
2325
2326		vm_page_lock_queues();
2327		/*
2328		 * test the pages to see if they have been modified directly
2329		 * by users through the VM system.
2330		 */
2331		for (i = 0; i < bp->b_npages; i++)
2332			vm_page_test_dirty(bp->b_pages[i]);
2333
2334		/*
2335		 * Calculate the encompassing dirty range, boffset and eoffset,
2336		 * (eoffset - boffset) bytes.
2337		 */
2338
2339		for (i = 0; i < bp->b_npages; i++) {
2340			if (bp->b_pages[i]->dirty)
2341				break;
2342		}
2343		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2344
2345		for (i = bp->b_npages - 1; i >= 0; --i) {
2346			if (bp->b_pages[i]->dirty) {
2347				break;
2348			}
2349		}
2350		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2351
2352		vm_page_unlock_queues();
2353		/*
2354		 * Fit it to the buffer.
2355		 */
2356
2357		if (eoffset > bp->b_bcount)
2358			eoffset = bp->b_bcount;
2359
2360		/*
2361		 * If we have a good dirty range, merge with the existing
2362		 * dirty range.
2363		 */
2364
2365		if (boffset < eoffset) {
2366			if (bp->b_dirtyoff > boffset)
2367				bp->b_dirtyoff = boffset;
2368			if (bp->b_dirtyend < eoffset)
2369				bp->b_dirtyend = eoffset;
2370		}
2371	}
2372}
2373
2374/*
2375 *	getblk:
2376 *
2377 *	Get a block given a specified block and offset into a file/device.
2378 *	The buffers B_DONE bit will be cleared on return, making it almost
2379 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2380 *	return.  The caller should clear B_INVAL prior to initiating a
2381 *	READ.
2382 *
2383 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2384 *	an existing buffer.
2385 *
2386 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2387 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2388 *	and then cleared based on the backing VM.  If the previous buffer is
2389 *	non-0-sized but invalid, B_CACHE will be cleared.
2390 *
2391 *	If getblk() must create a new buffer, the new buffer is returned with
2392 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2393 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2394 *	backing VM.
2395 *
2396 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2397 *	B_CACHE bit is clear.
2398 *
2399 *	What this means, basically, is that the caller should use B_CACHE to
2400 *	determine whether the buffer is fully valid or not and should clear
2401 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2402 *	the buffer by loading its data area with something, the caller needs
2403 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2404 *	the caller should set B_CACHE ( as an optimization ), else the caller
2405 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2406 *	a write attempt or if it was a successfull read.  If the caller
2407 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2408 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2409 */
2410struct buf *
2411getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2412    int flags)
2413{
2414	struct buf *bp;
2415	struct bufobj *bo;
2416	int error;
2417
2418	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2419	ASSERT_VOP_LOCKED(vp, "getblk");
2420	if (size > MAXBSIZE)
2421		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2422
2423	bo = &vp->v_bufobj;
2424loop:
2425	/*
2426	 * Block if we are low on buffers.   Certain processes are allowed
2427	 * to completely exhaust the buffer cache.
2428         *
2429         * If this check ever becomes a bottleneck it may be better to
2430         * move it into the else, when gbincore() fails.  At the moment
2431         * it isn't a problem.
2432	 *
2433	 * XXX remove if 0 sections (clean this up after its proven)
2434         */
2435	if (numfreebuffers == 0) {
2436		if (TD_IS_IDLETHREAD(curthread))
2437			return NULL;
2438		mtx_lock(&nblock);
2439		needsbuffer |= VFS_BIO_NEED_ANY;
2440		mtx_unlock(&nblock);
2441	}
2442
2443	BO_LOCK(bo);
2444	bp = gbincore(bo, blkno);
2445	if (bp != NULL) {
2446		int lockflags;
2447		/*
2448		 * Buffer is in-core.  If the buffer is not busy, it must
2449		 * be on a queue.
2450		 */
2451		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2452
2453		if (flags & GB_LOCK_NOWAIT)
2454			lockflags |= LK_NOWAIT;
2455
2456		error = BUF_TIMELOCK(bp, lockflags,
2457		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2458
2459		/*
2460		 * If we slept and got the lock we have to restart in case
2461		 * the buffer changed identities.
2462		 */
2463		if (error == ENOLCK)
2464			goto loop;
2465		/* We timed out or were interrupted. */
2466		else if (error)
2467			return (NULL);
2468
2469		/*
2470		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2471		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2472		 * and for a VMIO buffer B_CACHE is adjusted according to the
2473		 * backing VM cache.
2474		 */
2475		if (bp->b_flags & B_INVAL)
2476			bp->b_flags &= ~B_CACHE;
2477		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2478			bp->b_flags |= B_CACHE;
2479		bremfree(bp);
2480
2481		/*
2482		 * check for size inconsistancies for non-VMIO case.
2483		 */
2484
2485		if (bp->b_bcount != size) {
2486			if ((bp->b_flags & B_VMIO) == 0 ||
2487			    (size > bp->b_kvasize)) {
2488				if (bp->b_flags & B_DELWRI) {
2489					/*
2490					 * If buffer is pinned and caller does
2491					 * not want sleep  waiting for it to be
2492					 * unpinned, bail out
2493					 * */
2494					if (bp->b_pin_count > 0) {
2495						if (flags & GB_LOCK_NOWAIT) {
2496							bqrelse(bp);
2497							return (NULL);
2498						} else {
2499							bunpin_wait(bp);
2500						}
2501					}
2502					bp->b_flags |= B_NOCACHE;
2503					bwrite(bp);
2504				} else {
2505					if (LIST_EMPTY(&bp->b_dep)) {
2506						bp->b_flags |= B_RELBUF;
2507						brelse(bp);
2508					} else {
2509						bp->b_flags |= B_NOCACHE;
2510						bwrite(bp);
2511					}
2512				}
2513				goto loop;
2514			}
2515		}
2516
2517		/*
2518		 * If the size is inconsistant in the VMIO case, we can resize
2519		 * the buffer.  This might lead to B_CACHE getting set or
2520		 * cleared.  If the size has not changed, B_CACHE remains
2521		 * unchanged from its previous state.
2522		 */
2523
2524		if (bp->b_bcount != size)
2525			allocbuf(bp, size);
2526
2527		KASSERT(bp->b_offset != NOOFFSET,
2528		    ("getblk: no buffer offset"));
2529
2530		/*
2531		 * A buffer with B_DELWRI set and B_CACHE clear must
2532		 * be committed before we can return the buffer in
2533		 * order to prevent the caller from issuing a read
2534		 * ( due to B_CACHE not being set ) and overwriting
2535		 * it.
2536		 *
2537		 * Most callers, including NFS and FFS, need this to
2538		 * operate properly either because they assume they
2539		 * can issue a read if B_CACHE is not set, or because
2540		 * ( for example ) an uncached B_DELWRI might loop due
2541		 * to softupdates re-dirtying the buffer.  In the latter
2542		 * case, B_CACHE is set after the first write completes,
2543		 * preventing further loops.
2544		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2545		 * above while extending the buffer, we cannot allow the
2546		 * buffer to remain with B_CACHE set after the write
2547		 * completes or it will represent a corrupt state.  To
2548		 * deal with this we set B_NOCACHE to scrap the buffer
2549		 * after the write.
2550		 *
2551		 * We might be able to do something fancy, like setting
2552		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2553		 * so the below call doesn't set B_CACHE, but that gets real
2554		 * confusing.  This is much easier.
2555		 */
2556
2557		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2558			bp->b_flags |= B_NOCACHE;
2559			bwrite(bp);
2560			goto loop;
2561		}
2562		bp->b_flags &= ~B_DONE;
2563	} else {
2564		int bsize, maxsize, vmio;
2565		off_t offset;
2566
2567		/*
2568		 * Buffer is not in-core, create new buffer.  The buffer
2569		 * returned by getnewbuf() is locked.  Note that the returned
2570		 * buffer is also considered valid (not marked B_INVAL).
2571		 */
2572		BO_UNLOCK(bo);
2573		/*
2574		 * If the user does not want us to create the buffer, bail out
2575		 * here.
2576		 */
2577		if (flags & GB_NOCREAT)
2578			return NULL;
2579		bsize = bo->bo_bsize;
2580		offset = blkno * bsize;
2581		vmio = vp->v_object != NULL;
2582		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2583		maxsize = imax(maxsize, bsize);
2584
2585		bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2586		if (bp == NULL) {
2587			if (slpflag || slptimeo)
2588				return NULL;
2589			goto loop;
2590		}
2591
2592		/*
2593		 * This code is used to make sure that a buffer is not
2594		 * created while the getnewbuf routine is blocked.
2595		 * This can be a problem whether the vnode is locked or not.
2596		 * If the buffer is created out from under us, we have to
2597		 * throw away the one we just created.
2598		 *
2599		 * Note: this must occur before we associate the buffer
2600		 * with the vp especially considering limitations in
2601		 * the splay tree implementation when dealing with duplicate
2602		 * lblkno's.
2603		 */
2604		BO_LOCK(bo);
2605		if (gbincore(bo, blkno)) {
2606			BO_UNLOCK(bo);
2607			bp->b_flags |= B_INVAL;
2608			brelse(bp);
2609			goto loop;
2610		}
2611
2612		/*
2613		 * Insert the buffer into the hash, so that it can
2614		 * be found by incore.
2615		 */
2616		bp->b_blkno = bp->b_lblkno = blkno;
2617		bp->b_offset = offset;
2618		bgetvp(vp, bp);
2619		BO_UNLOCK(bo);
2620
2621		/*
2622		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2623		 * buffer size starts out as 0, B_CACHE will be set by
2624		 * allocbuf() for the VMIO case prior to it testing the
2625		 * backing store for validity.
2626		 */
2627
2628		if (vmio) {
2629			bp->b_flags |= B_VMIO;
2630#if defined(VFS_BIO_DEBUG)
2631			if (vn_canvmio(vp) != TRUE)
2632				printf("getblk: VMIO on vnode type %d\n",
2633					vp->v_type);
2634#endif
2635			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2636			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2637			    bp, vp->v_object, bp->b_bufobj->bo_object));
2638		} else {
2639			bp->b_flags &= ~B_VMIO;
2640			KASSERT(bp->b_bufobj->bo_object == NULL,
2641			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2642			    bp, bp->b_bufobj->bo_object));
2643		}
2644
2645		allocbuf(bp, size);
2646		bp->b_flags &= ~B_DONE;
2647	}
2648	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2649	BUF_ASSERT_HELD(bp);
2650	KASSERT(bp->b_bufobj == bo,
2651	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2652	return (bp);
2653}
2654
2655/*
2656 * Get an empty, disassociated buffer of given size.  The buffer is initially
2657 * set to B_INVAL.
2658 */
2659struct buf *
2660geteblk(int size)
2661{
2662	struct buf *bp;
2663	int maxsize;
2664
2665	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2666	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2667		continue;
2668	allocbuf(bp, size);
2669	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2670	BUF_ASSERT_HELD(bp);
2671	return (bp);
2672}
2673
2674
2675/*
2676 * This code constitutes the buffer memory from either anonymous system
2677 * memory (in the case of non-VMIO operations) or from an associated
2678 * VM object (in the case of VMIO operations).  This code is able to
2679 * resize a buffer up or down.
2680 *
2681 * Note that this code is tricky, and has many complications to resolve
2682 * deadlock or inconsistant data situations.  Tread lightly!!!
2683 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2684 * the caller.  Calling this code willy nilly can result in the loss of data.
2685 *
2686 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2687 * B_CACHE for the non-VMIO case.
2688 */
2689
2690int
2691allocbuf(struct buf *bp, int size)
2692{
2693	int newbsize, mbsize;
2694	int i;
2695
2696	BUF_ASSERT_HELD(bp);
2697
2698	if (bp->b_kvasize < size)
2699		panic("allocbuf: buffer too small");
2700
2701	if ((bp->b_flags & B_VMIO) == 0) {
2702		caddr_t origbuf;
2703		int origbufsize;
2704		/*
2705		 * Just get anonymous memory from the kernel.  Don't
2706		 * mess with B_CACHE.
2707		 */
2708		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2709		if (bp->b_flags & B_MALLOC)
2710			newbsize = mbsize;
2711		else
2712			newbsize = round_page(size);
2713
2714		if (newbsize < bp->b_bufsize) {
2715			/*
2716			 * malloced buffers are not shrunk
2717			 */
2718			if (bp->b_flags & B_MALLOC) {
2719				if (newbsize) {
2720					bp->b_bcount = size;
2721				} else {
2722					free(bp->b_data, M_BIOBUF);
2723					if (bp->b_bufsize) {
2724						atomic_subtract_int(
2725						    &bufmallocspace,
2726						    bp->b_bufsize);
2727						bufspacewakeup();
2728						bp->b_bufsize = 0;
2729					}
2730					bp->b_saveaddr = bp->b_kvabase;
2731					bp->b_data = bp->b_saveaddr;
2732					bp->b_bcount = 0;
2733					bp->b_flags &= ~B_MALLOC;
2734				}
2735				return 1;
2736			}
2737			vm_hold_free_pages(
2738			    bp,
2739			    (vm_offset_t) bp->b_data + newbsize,
2740			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2741		} else if (newbsize > bp->b_bufsize) {
2742			/*
2743			 * We only use malloced memory on the first allocation.
2744			 * and revert to page-allocated memory when the buffer
2745			 * grows.
2746			 */
2747			/*
2748			 * There is a potential smp race here that could lead
2749			 * to bufmallocspace slightly passing the max.  It
2750			 * is probably extremely rare and not worth worrying
2751			 * over.
2752			 */
2753			if ( (bufmallocspace < maxbufmallocspace) &&
2754				(bp->b_bufsize == 0) &&
2755				(mbsize <= PAGE_SIZE/2)) {
2756
2757				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2758				bp->b_bufsize = mbsize;
2759				bp->b_bcount = size;
2760				bp->b_flags |= B_MALLOC;
2761				atomic_add_int(&bufmallocspace, mbsize);
2762				return 1;
2763			}
2764			origbuf = NULL;
2765			origbufsize = 0;
2766			/*
2767			 * If the buffer is growing on its other-than-first allocation,
2768			 * then we revert to the page-allocation scheme.
2769			 */
2770			if (bp->b_flags & B_MALLOC) {
2771				origbuf = bp->b_data;
2772				origbufsize = bp->b_bufsize;
2773				bp->b_data = bp->b_kvabase;
2774				if (bp->b_bufsize) {
2775					atomic_subtract_int(&bufmallocspace,
2776					    bp->b_bufsize);
2777					bufspacewakeup();
2778					bp->b_bufsize = 0;
2779				}
2780				bp->b_flags &= ~B_MALLOC;
2781				newbsize = round_page(newbsize);
2782			}
2783			vm_hold_load_pages(
2784			    bp,
2785			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2786			    (vm_offset_t) bp->b_data + newbsize);
2787			if (origbuf) {
2788				bcopy(origbuf, bp->b_data, origbufsize);
2789				free(origbuf, M_BIOBUF);
2790			}
2791		}
2792	} else {
2793		int desiredpages;
2794
2795		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2796		desiredpages = (size == 0) ? 0 :
2797			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2798
2799		if (bp->b_flags & B_MALLOC)
2800			panic("allocbuf: VMIO buffer can't be malloced");
2801		/*
2802		 * Set B_CACHE initially if buffer is 0 length or will become
2803		 * 0-length.
2804		 */
2805		if (size == 0 || bp->b_bufsize == 0)
2806			bp->b_flags |= B_CACHE;
2807
2808		if (newbsize < bp->b_bufsize) {
2809			/*
2810			 * DEV_BSIZE aligned new buffer size is less then the
2811			 * DEV_BSIZE aligned existing buffer size.  Figure out
2812			 * if we have to remove any pages.
2813			 */
2814			if (desiredpages < bp->b_npages) {
2815				vm_page_t m;
2816
2817				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2818				vm_page_lock_queues();
2819				for (i = desiredpages; i < bp->b_npages; i++) {
2820					/*
2821					 * the page is not freed here -- it
2822					 * is the responsibility of
2823					 * vnode_pager_setsize
2824					 */
2825					m = bp->b_pages[i];
2826					KASSERT(m != bogus_page,
2827					    ("allocbuf: bogus page found"));
2828					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2829						vm_page_lock_queues();
2830
2831					bp->b_pages[i] = NULL;
2832					vm_page_unwire(m, 0);
2833				}
2834				vm_page_unlock_queues();
2835				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2836				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2837				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2838				bp->b_npages = desiredpages;
2839			}
2840		} else if (size > bp->b_bcount) {
2841			/*
2842			 * We are growing the buffer, possibly in a
2843			 * byte-granular fashion.
2844			 */
2845			struct vnode *vp;
2846			vm_object_t obj;
2847			vm_offset_t toff;
2848			vm_offset_t tinc;
2849
2850			/*
2851			 * Step 1, bring in the VM pages from the object,
2852			 * allocating them if necessary.  We must clear
2853			 * B_CACHE if these pages are not valid for the
2854			 * range covered by the buffer.
2855			 */
2856
2857			vp = bp->b_vp;
2858			obj = bp->b_bufobj->bo_object;
2859
2860			VM_OBJECT_LOCK(obj);
2861			while (bp->b_npages < desiredpages) {
2862				vm_page_t m;
2863				vm_pindex_t pi;
2864
2865				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2866				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2867					/*
2868					 * note: must allocate system pages
2869					 * since blocking here could intefere
2870					 * with paging I/O, no matter which
2871					 * process we are.
2872					 */
2873					m = vm_page_alloc(obj, pi,
2874					    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2875					    VM_ALLOC_WIRED);
2876					if (m == NULL) {
2877						atomic_add_int(&vm_pageout_deficit,
2878						    desiredpages - bp->b_npages);
2879						VM_OBJECT_UNLOCK(obj);
2880						VM_WAIT;
2881						VM_OBJECT_LOCK(obj);
2882					} else {
2883						if (m->valid == 0)
2884							bp->b_flags &= ~B_CACHE;
2885						bp->b_pages[bp->b_npages] = m;
2886						++bp->b_npages;
2887					}
2888					continue;
2889				}
2890
2891				/*
2892				 * We found a page.  If we have to sleep on it,
2893				 * retry because it might have gotten freed out
2894				 * from under us.
2895				 *
2896				 * We can only test VPO_BUSY here.  Blocking on
2897				 * m->busy might lead to a deadlock:
2898				 *
2899				 *  vm_fault->getpages->cluster_read->allocbuf
2900				 *
2901				 */
2902				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2903					continue;
2904
2905				/*
2906				 * We have a good page.
2907				 */
2908				vm_page_lock_queues();
2909				vm_page_wire(m);
2910				vm_page_unlock_queues();
2911				bp->b_pages[bp->b_npages] = m;
2912				++bp->b_npages;
2913			}
2914
2915			/*
2916			 * Step 2.  We've loaded the pages into the buffer,
2917			 * we have to figure out if we can still have B_CACHE
2918			 * set.  Note that B_CACHE is set according to the
2919			 * byte-granular range ( bcount and size ), new the
2920			 * aligned range ( newbsize ).
2921			 *
2922			 * The VM test is against m->valid, which is DEV_BSIZE
2923			 * aligned.  Needless to say, the validity of the data
2924			 * needs to also be DEV_BSIZE aligned.  Note that this
2925			 * fails with NFS if the server or some other client
2926			 * extends the file's EOF.  If our buffer is resized,
2927			 * B_CACHE may remain set! XXX
2928			 */
2929
2930			toff = bp->b_bcount;
2931			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2932
2933			while ((bp->b_flags & B_CACHE) && toff < size) {
2934				vm_pindex_t pi;
2935
2936				if (tinc > (size - toff))
2937					tinc = size - toff;
2938
2939				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2940				    PAGE_SHIFT;
2941
2942				vfs_buf_test_cache(
2943				    bp,
2944				    bp->b_offset,
2945				    toff,
2946				    tinc,
2947				    bp->b_pages[pi]
2948				);
2949				toff += tinc;
2950				tinc = PAGE_SIZE;
2951			}
2952			VM_OBJECT_UNLOCK(obj);
2953
2954			/*
2955			 * Step 3, fixup the KVM pmap.  Remember that
2956			 * bp->b_data is relative to bp->b_offset, but
2957			 * bp->b_offset may be offset into the first page.
2958			 */
2959
2960			bp->b_data = (caddr_t)
2961			    trunc_page((vm_offset_t)bp->b_data);
2962			pmap_qenter(
2963			    (vm_offset_t)bp->b_data,
2964			    bp->b_pages,
2965			    bp->b_npages
2966			);
2967
2968			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2969			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2970		}
2971	}
2972	if (newbsize < bp->b_bufsize)
2973		bufspacewakeup();
2974	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2975	bp->b_bcount = size;		/* requested buffer size	*/
2976	return 1;
2977}
2978
2979void
2980biodone(struct bio *bp)
2981{
2982	struct mtx *mtxp;
2983	void (*done)(struct bio *);
2984
2985	mtxp = mtx_pool_find(mtxpool_sleep, bp);
2986	mtx_lock(mtxp);
2987	bp->bio_flags |= BIO_DONE;
2988	done = bp->bio_done;
2989	if (done == NULL)
2990		wakeup(bp);
2991	mtx_unlock(mtxp);
2992	if (done != NULL)
2993		done(bp);
2994}
2995
2996/*
2997 * Wait for a BIO to finish.
2998 *
2999 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3000 * case is not yet clear.
3001 */
3002int
3003biowait(struct bio *bp, const char *wchan)
3004{
3005	struct mtx *mtxp;
3006
3007	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3008	mtx_lock(mtxp);
3009	while ((bp->bio_flags & BIO_DONE) == 0)
3010		msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3011	mtx_unlock(mtxp);
3012	if (bp->bio_error != 0)
3013		return (bp->bio_error);
3014	if (!(bp->bio_flags & BIO_ERROR))
3015		return (0);
3016	return (EIO);
3017}
3018
3019void
3020biofinish(struct bio *bp, struct devstat *stat, int error)
3021{
3022
3023	if (error) {
3024		bp->bio_error = error;
3025		bp->bio_flags |= BIO_ERROR;
3026	}
3027	if (stat != NULL)
3028		devstat_end_transaction_bio(stat, bp);
3029	biodone(bp);
3030}
3031
3032/*
3033 *	bufwait:
3034 *
3035 *	Wait for buffer I/O completion, returning error status.  The buffer
3036 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3037 *	error and cleared.
3038 */
3039int
3040bufwait(struct buf *bp)
3041{
3042	if (bp->b_iocmd == BIO_READ)
3043		bwait(bp, PRIBIO, "biord");
3044	else
3045		bwait(bp, PRIBIO, "biowr");
3046	if (bp->b_flags & B_EINTR) {
3047		bp->b_flags &= ~B_EINTR;
3048		return (EINTR);
3049	}
3050	if (bp->b_ioflags & BIO_ERROR) {
3051		return (bp->b_error ? bp->b_error : EIO);
3052	} else {
3053		return (0);
3054	}
3055}
3056
3057 /*
3058  * Call back function from struct bio back up to struct buf.
3059  */
3060static void
3061bufdonebio(struct bio *bip)
3062{
3063	struct buf *bp;
3064
3065	bp = bip->bio_caller2;
3066	bp->b_resid = bp->b_bcount - bip->bio_completed;
3067	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3068	bp->b_ioflags = bip->bio_flags;
3069	bp->b_error = bip->bio_error;
3070	if (bp->b_error)
3071		bp->b_ioflags |= BIO_ERROR;
3072	bufdone(bp);
3073	g_destroy_bio(bip);
3074}
3075
3076void
3077dev_strategy(struct cdev *dev, struct buf *bp)
3078{
3079	struct cdevsw *csw;
3080	struct bio *bip;
3081
3082	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3083		panic("b_iocmd botch");
3084	for (;;) {
3085		bip = g_new_bio();
3086		if (bip != NULL)
3087			break;
3088		/* Try again later */
3089		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3090	}
3091	bip->bio_cmd = bp->b_iocmd;
3092	bip->bio_offset = bp->b_iooffset;
3093	bip->bio_length = bp->b_bcount;
3094	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3095	bip->bio_data = bp->b_data;
3096	bip->bio_done = bufdonebio;
3097	bip->bio_caller2 = bp;
3098	bip->bio_dev = dev;
3099	KASSERT(dev->si_refcount > 0,
3100	    ("dev_strategy on un-referenced struct cdev *(%s)",
3101	    devtoname(dev)));
3102	csw = dev_refthread(dev);
3103	if (csw == NULL) {
3104		g_destroy_bio(bip);
3105		bp->b_error = ENXIO;
3106		bp->b_ioflags = BIO_ERROR;
3107		bufdone(bp);
3108		return;
3109	}
3110	(*csw->d_strategy)(bip);
3111	dev_relthread(dev);
3112}
3113
3114/*
3115 *	bufdone:
3116 *
3117 *	Finish I/O on a buffer, optionally calling a completion function.
3118 *	This is usually called from an interrupt so process blocking is
3119 *	not allowed.
3120 *
3121 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3122 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3123 *	assuming B_INVAL is clear.
3124 *
3125 *	For the VMIO case, we set B_CACHE if the op was a read and no
3126 *	read error occured, or if the op was a write.  B_CACHE is never
3127 *	set if the buffer is invalid or otherwise uncacheable.
3128 *
3129 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3130 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3131 *	in the biodone routine.
3132 */
3133void
3134bufdone(struct buf *bp)
3135{
3136	struct bufobj *dropobj;
3137	void    (*biodone)(struct buf *);
3138
3139	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3140	dropobj = NULL;
3141
3142	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3143	BUF_ASSERT_HELD(bp);
3144
3145	runningbufwakeup(bp);
3146	if (bp->b_iocmd == BIO_WRITE)
3147		dropobj = bp->b_bufobj;
3148	/* call optional completion function if requested */
3149	if (bp->b_iodone != NULL) {
3150		biodone = bp->b_iodone;
3151		bp->b_iodone = NULL;
3152		(*biodone) (bp);
3153		if (dropobj)
3154			bufobj_wdrop(dropobj);
3155		return;
3156	}
3157
3158	bufdone_finish(bp);
3159
3160	if (dropobj)
3161		bufobj_wdrop(dropobj);
3162}
3163
3164void
3165bufdone_finish(struct buf *bp)
3166{
3167	BUF_ASSERT_HELD(bp);
3168
3169	if (!LIST_EMPTY(&bp->b_dep))
3170		buf_complete(bp);
3171
3172	if (bp->b_flags & B_VMIO) {
3173		int i;
3174		vm_ooffset_t foff;
3175		vm_page_t m;
3176		vm_object_t obj;
3177		int iosize;
3178		struct vnode *vp = bp->b_vp;
3179		boolean_t are_queues_locked;
3180
3181		obj = bp->b_bufobj->bo_object;
3182
3183#if defined(VFS_BIO_DEBUG)
3184		mp_fixme("usecount and vflag accessed without locks.");
3185		if (vp->v_usecount == 0) {
3186			panic("biodone: zero vnode ref count");
3187		}
3188
3189		KASSERT(vp->v_object != NULL,
3190			("biodone: vnode %p has no vm_object", vp));
3191#endif
3192
3193		foff = bp->b_offset;
3194		KASSERT(bp->b_offset != NOOFFSET,
3195		    ("biodone: no buffer offset"));
3196
3197		VM_OBJECT_LOCK(obj);
3198#if defined(VFS_BIO_DEBUG)
3199		if (obj->paging_in_progress < bp->b_npages) {
3200			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3201			    obj->paging_in_progress, bp->b_npages);
3202		}
3203#endif
3204
3205		/*
3206		 * Set B_CACHE if the op was a normal read and no error
3207		 * occured.  B_CACHE is set for writes in the b*write()
3208		 * routines.
3209		 */
3210		iosize = bp->b_bcount - bp->b_resid;
3211		if (bp->b_iocmd == BIO_READ &&
3212		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3213		    !(bp->b_ioflags & BIO_ERROR)) {
3214			bp->b_flags |= B_CACHE;
3215		}
3216		if (bp->b_iocmd == BIO_READ) {
3217			vm_page_lock_queues();
3218			are_queues_locked = TRUE;
3219		} else
3220			are_queues_locked = FALSE;
3221		for (i = 0; i < bp->b_npages; i++) {
3222			int bogusflag = 0;
3223			int resid;
3224
3225			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3226			if (resid > iosize)
3227				resid = iosize;
3228
3229			/*
3230			 * cleanup bogus pages, restoring the originals
3231			 */
3232			m = bp->b_pages[i];
3233			if (m == bogus_page) {
3234				bogusflag = 1;
3235				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3236				if (m == NULL)
3237					panic("biodone: page disappeared!");
3238				bp->b_pages[i] = m;
3239				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3240				    bp->b_pages, bp->b_npages);
3241			}
3242#if defined(VFS_BIO_DEBUG)
3243			if (OFF_TO_IDX(foff) != m->pindex) {
3244				printf(
3245"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3246				    (intmax_t)foff, (uintmax_t)m->pindex);
3247			}
3248#endif
3249
3250			/*
3251			 * In the write case, the valid and clean bits are
3252			 * already changed correctly ( see bdwrite() ), so we
3253			 * only need to do this here in the read case.
3254			 */
3255			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3256				vfs_page_set_valid(bp, foff, m);
3257			}
3258
3259			/*
3260			 * when debugging new filesystems or buffer I/O methods, this
3261			 * is the most common error that pops up.  if you see this, you
3262			 * have not set the page busy flag correctly!!!
3263			 */
3264			if (m->busy == 0) {
3265				printf("biodone: page busy < 0, "
3266				    "pindex: %d, foff: 0x(%x,%x), "
3267				    "resid: %d, index: %d\n",
3268				    (int) m->pindex, (int)(foff >> 32),
3269						(int) foff & 0xffffffff, resid, i);
3270				if (!vn_isdisk(vp, NULL))
3271					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3272					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3273					    (intmax_t) bp->b_lblkno,
3274					    bp->b_flags, bp->b_npages);
3275				else
3276					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3277					    (intmax_t) bp->b_lblkno,
3278					    bp->b_flags, bp->b_npages);
3279				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3280				    (u_long)m->valid, (u_long)m->dirty,
3281				    m->wire_count);
3282				panic("biodone: page busy < 0\n");
3283			}
3284			vm_page_io_finish(m);
3285			vm_object_pip_subtract(obj, 1);
3286			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3287			iosize -= resid;
3288		}
3289		if (are_queues_locked)
3290			vm_page_unlock_queues();
3291		vm_object_pip_wakeupn(obj, 0);
3292		VM_OBJECT_UNLOCK(obj);
3293	}
3294
3295	/*
3296	 * For asynchronous completions, release the buffer now. The brelse
3297	 * will do a wakeup there if necessary - so no need to do a wakeup
3298	 * here in the async case. The sync case always needs to do a wakeup.
3299	 */
3300
3301	if (bp->b_flags & B_ASYNC) {
3302		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3303			brelse(bp);
3304		else
3305			bqrelse(bp);
3306	} else
3307		bdone(bp);
3308}
3309
3310/*
3311 * This routine is called in lieu of iodone in the case of
3312 * incomplete I/O.  This keeps the busy status for pages
3313 * consistant.
3314 */
3315void
3316vfs_unbusy_pages(struct buf *bp)
3317{
3318	int i;
3319	vm_object_t obj;
3320	vm_page_t m;
3321
3322	runningbufwakeup(bp);
3323	if (!(bp->b_flags & B_VMIO))
3324		return;
3325
3326	obj = bp->b_bufobj->bo_object;
3327	VM_OBJECT_LOCK(obj);
3328	for (i = 0; i < bp->b_npages; i++) {
3329		m = bp->b_pages[i];
3330		if (m == bogus_page) {
3331			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3332			if (!m)
3333				panic("vfs_unbusy_pages: page missing\n");
3334			bp->b_pages[i] = m;
3335			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3336			    bp->b_pages, bp->b_npages);
3337		}
3338		vm_object_pip_subtract(obj, 1);
3339		vm_page_io_finish(m);
3340	}
3341	vm_object_pip_wakeupn(obj, 0);
3342	VM_OBJECT_UNLOCK(obj);
3343}
3344
3345/*
3346 * vfs_page_set_valid:
3347 *
3348 *	Set the valid bits in a page based on the supplied offset.   The
3349 *	range is restricted to the buffer's size.
3350 *
3351 *	This routine is typically called after a read completes.
3352 */
3353static void
3354vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3355{
3356	vm_ooffset_t soff, eoff;
3357
3358	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3359	/*
3360	 * Start and end offsets in buffer.  eoff - soff may not cross a
3361	 * page boundry or cross the end of the buffer.  The end of the
3362	 * buffer, in this case, is our file EOF, not the allocation size
3363	 * of the buffer.
3364	 */
3365	soff = off;
3366	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3367	if (eoff > bp->b_offset + bp->b_bcount)
3368		eoff = bp->b_offset + bp->b_bcount;
3369
3370	/*
3371	 * Set valid range.  This is typically the entire buffer and thus the
3372	 * entire page.
3373	 */
3374	if (eoff > soff) {
3375		vm_page_set_validclean(
3376		    m,
3377		   (vm_offset_t) (soff & PAGE_MASK),
3378		   (vm_offset_t) (eoff - soff)
3379		);
3380	}
3381}
3382
3383/*
3384 * This routine is called before a device strategy routine.
3385 * It is used to tell the VM system that paging I/O is in
3386 * progress, and treat the pages associated with the buffer
3387 * almost as being VPO_BUSY.  Also the object paging_in_progress
3388 * flag is handled to make sure that the object doesn't become
3389 * inconsistant.
3390 *
3391 * Since I/O has not been initiated yet, certain buffer flags
3392 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3393 * and should be ignored.
3394 */
3395void
3396vfs_busy_pages(struct buf *bp, int clear_modify)
3397{
3398	int i, bogus;
3399	vm_object_t obj;
3400	vm_ooffset_t foff;
3401	vm_page_t m;
3402
3403	if (!(bp->b_flags & B_VMIO))
3404		return;
3405
3406	obj = bp->b_bufobj->bo_object;
3407	foff = bp->b_offset;
3408	KASSERT(bp->b_offset != NOOFFSET,
3409	    ("vfs_busy_pages: no buffer offset"));
3410	VM_OBJECT_LOCK(obj);
3411	if (bp->b_bufsize != 0)
3412		vfs_setdirty_locked_object(bp);
3413retry:
3414	for (i = 0; i < bp->b_npages; i++) {
3415		m = bp->b_pages[i];
3416
3417		if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3418			goto retry;
3419	}
3420	bogus = 0;
3421	vm_page_lock_queues();
3422	for (i = 0; i < bp->b_npages; i++) {
3423		m = bp->b_pages[i];
3424
3425		if ((bp->b_flags & B_CLUSTER) == 0) {
3426			vm_object_pip_add(obj, 1);
3427			vm_page_io_start(m);
3428		}
3429		/*
3430		 * When readying a buffer for a read ( i.e
3431		 * clear_modify == 0 ), it is important to do
3432		 * bogus_page replacement for valid pages in
3433		 * partially instantiated buffers.  Partially
3434		 * instantiated buffers can, in turn, occur when
3435		 * reconstituting a buffer from its VM backing store
3436		 * base.  We only have to do this if B_CACHE is
3437		 * clear ( which causes the I/O to occur in the
3438		 * first place ).  The replacement prevents the read
3439		 * I/O from overwriting potentially dirty VM-backed
3440		 * pages.  XXX bogus page replacement is, uh, bogus.
3441		 * It may not work properly with small-block devices.
3442		 * We need to find a better way.
3443		 */
3444		pmap_remove_all(m);
3445		if (clear_modify)
3446			vfs_page_set_valid(bp, foff, m);
3447		else if (m->valid == VM_PAGE_BITS_ALL &&
3448		    (bp->b_flags & B_CACHE) == 0) {
3449			bp->b_pages[i] = bogus_page;
3450			bogus++;
3451		}
3452		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3453	}
3454	vm_page_unlock_queues();
3455	VM_OBJECT_UNLOCK(obj);
3456	if (bogus)
3457		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3458		    bp->b_pages, bp->b_npages);
3459}
3460
3461/*
3462 * Tell the VM system that the pages associated with this buffer
3463 * are clean.  This is used for delayed writes where the data is
3464 * going to go to disk eventually without additional VM intevention.
3465 *
3466 * Note that while we only really need to clean through to b_bcount, we
3467 * just go ahead and clean through to b_bufsize.
3468 */
3469static void
3470vfs_clean_pages(struct buf *bp)
3471{
3472	int i;
3473	vm_ooffset_t foff, noff, eoff;
3474	vm_page_t m;
3475
3476	if (!(bp->b_flags & B_VMIO))
3477		return;
3478
3479	foff = bp->b_offset;
3480	KASSERT(bp->b_offset != NOOFFSET,
3481	    ("vfs_clean_pages: no buffer offset"));
3482	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3483	vm_page_lock_queues();
3484	for (i = 0; i < bp->b_npages; i++) {
3485		m = bp->b_pages[i];
3486		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3487		eoff = noff;
3488
3489		if (eoff > bp->b_offset + bp->b_bufsize)
3490			eoff = bp->b_offset + bp->b_bufsize;
3491		vfs_page_set_valid(bp, foff, m);
3492		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3493		foff = noff;
3494	}
3495	vm_page_unlock_queues();
3496	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3497}
3498
3499/*
3500 *	vfs_bio_set_validclean:
3501 *
3502 *	Set the range within the buffer to valid and clean.  The range is
3503 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3504 *	itself may be offset from the beginning of the first page.
3505 *
3506 */
3507
3508void
3509vfs_bio_set_validclean(struct buf *bp, int base, int size)
3510{
3511	int i, n;
3512	vm_page_t m;
3513
3514	if (!(bp->b_flags & B_VMIO))
3515		return;
3516	/*
3517	 * Fixup base to be relative to beginning of first page.
3518	 * Set initial n to be the maximum number of bytes in the
3519	 * first page that can be validated.
3520	 */
3521
3522	base += (bp->b_offset & PAGE_MASK);
3523	n = PAGE_SIZE - (base & PAGE_MASK);
3524
3525	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3526	vm_page_lock_queues();
3527	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3528		m = bp->b_pages[i];
3529		if (n > size)
3530			n = size;
3531		vm_page_set_validclean(m, base & PAGE_MASK, n);
3532		base += n;
3533		size -= n;
3534		n = PAGE_SIZE;
3535	}
3536	vm_page_unlock_queues();
3537	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3538}
3539
3540/*
3541 *	vfs_bio_clrbuf:
3542 *
3543 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3544 *	to clear BIO_ERROR and B_INVAL.
3545 *
3546 *	Note that while we only theoretically need to clear through b_bcount,
3547 *	we go ahead and clear through b_bufsize.
3548 */
3549
3550void
3551vfs_bio_clrbuf(struct buf *bp)
3552{
3553	int i, j, mask = 0;
3554	caddr_t sa, ea;
3555
3556	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3557		clrbuf(bp);
3558		return;
3559	}
3560
3561	bp->b_flags &= ~B_INVAL;
3562	bp->b_ioflags &= ~BIO_ERROR;
3563	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3564	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3565	    (bp->b_offset & PAGE_MASK) == 0) {
3566		if (bp->b_pages[0] == bogus_page)
3567			goto unlock;
3568		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3569		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3570		if ((bp->b_pages[0]->valid & mask) == mask)
3571			goto unlock;
3572		if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3573		    ((bp->b_pages[0]->valid & mask) == 0)) {
3574			bzero(bp->b_data, bp->b_bufsize);
3575			bp->b_pages[0]->valid |= mask;
3576			goto unlock;
3577		}
3578	}
3579	ea = sa = bp->b_data;
3580	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3581		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3582		ea = (caddr_t)(vm_offset_t)ulmin(
3583		    (u_long)(vm_offset_t)ea,
3584		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3585		if (bp->b_pages[i] == bogus_page)
3586			continue;
3587		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3588		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3589		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3590		if ((bp->b_pages[i]->valid & mask) == mask)
3591			continue;
3592		if ((bp->b_pages[i]->valid & mask) == 0) {
3593			if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3594				bzero(sa, ea - sa);
3595		} else {
3596			for (; sa < ea; sa += DEV_BSIZE, j++) {
3597				if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3598				    (bp->b_pages[i]->valid & (1 << j)) == 0)
3599					bzero(sa, DEV_BSIZE);
3600			}
3601		}
3602		bp->b_pages[i]->valid |= mask;
3603	}
3604unlock:
3605	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3606	bp->b_resid = 0;
3607}
3608
3609/*
3610 * vm_hold_load_pages and vm_hold_free_pages get pages into
3611 * a buffers address space.  The pages are anonymous and are
3612 * not associated with a file object.
3613 */
3614static void
3615vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3616{
3617	vm_offset_t pg;
3618	vm_page_t p;
3619	int index;
3620
3621	to = round_page(to);
3622	from = round_page(from);
3623	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3624
3625	VM_OBJECT_LOCK(kernel_object);
3626	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3627tryagain:
3628		/*
3629		 * note: must allocate system pages since blocking here
3630		 * could intefere with paging I/O, no matter which
3631		 * process we are.
3632		 */
3633		p = vm_page_alloc(kernel_object,
3634			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3635		    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3636		if (!p) {
3637			atomic_add_int(&vm_pageout_deficit,
3638			    (to - pg) >> PAGE_SHIFT);
3639			VM_OBJECT_UNLOCK(kernel_object);
3640			VM_WAIT;
3641			VM_OBJECT_LOCK(kernel_object);
3642			goto tryagain;
3643		}
3644		p->valid = VM_PAGE_BITS_ALL;
3645		pmap_qenter(pg, &p, 1);
3646		bp->b_pages[index] = p;
3647	}
3648	VM_OBJECT_UNLOCK(kernel_object);
3649	bp->b_npages = index;
3650}
3651
3652/* Return pages associated with this buf to the vm system */
3653static void
3654vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3655{
3656	vm_offset_t pg;
3657	vm_page_t p;
3658	int index, newnpages;
3659
3660	from = round_page(from);
3661	to = round_page(to);
3662	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3663
3664	VM_OBJECT_LOCK(kernel_object);
3665	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3666		p = bp->b_pages[index];
3667		if (p && (index < bp->b_npages)) {
3668			if (p->busy) {
3669				printf(
3670			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3671				    (intmax_t)bp->b_blkno,
3672				    (intmax_t)bp->b_lblkno);
3673			}
3674			bp->b_pages[index] = NULL;
3675			pmap_qremove(pg, 1);
3676			vm_page_lock_queues();
3677			vm_page_unwire(p, 0);
3678			vm_page_free(p);
3679			vm_page_unlock_queues();
3680		}
3681	}
3682	VM_OBJECT_UNLOCK(kernel_object);
3683	bp->b_npages = newnpages;
3684}
3685
3686/*
3687 * Map an IO request into kernel virtual address space.
3688 *
3689 * All requests are (re)mapped into kernel VA space.
3690 * Notice that we use b_bufsize for the size of the buffer
3691 * to be mapped.  b_bcount might be modified by the driver.
3692 *
3693 * Note that even if the caller determines that the address space should
3694 * be valid, a race or a smaller-file mapped into a larger space may
3695 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3696 * check the return value.
3697 */
3698int
3699vmapbuf(struct buf *bp)
3700{
3701	caddr_t addr, kva;
3702	vm_prot_t prot;
3703	int pidx, i;
3704	struct vm_page *m;
3705	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3706
3707	if (bp->b_bufsize < 0)
3708		return (-1);
3709	prot = VM_PROT_READ;
3710	if (bp->b_iocmd == BIO_READ)
3711		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3712	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3713	     addr < bp->b_data + bp->b_bufsize;
3714	     addr += PAGE_SIZE, pidx++) {
3715		/*
3716		 * Do the vm_fault if needed; do the copy-on-write thing
3717		 * when reading stuff off device into memory.
3718		 *
3719		 * NOTE! Must use pmap_extract() because addr may be in
3720		 * the userland address space, and kextract is only guarenteed
3721		 * to work for the kernland address space (see: sparc64 port).
3722		 */
3723retry:
3724		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3725		    prot) < 0) {
3726			vm_page_lock_queues();
3727			for (i = 0; i < pidx; ++i) {
3728				vm_page_unhold(bp->b_pages[i]);
3729				bp->b_pages[i] = NULL;
3730			}
3731			vm_page_unlock_queues();
3732			return(-1);
3733		}
3734		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3735		if (m == NULL)
3736			goto retry;
3737		bp->b_pages[pidx] = m;
3738	}
3739	if (pidx > btoc(MAXPHYS))
3740		panic("vmapbuf: mapped more than MAXPHYS");
3741	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3742
3743	kva = bp->b_saveaddr;
3744	bp->b_npages = pidx;
3745	bp->b_saveaddr = bp->b_data;
3746	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3747	return(0);
3748}
3749
3750/*
3751 * Free the io map PTEs associated with this IO operation.
3752 * We also invalidate the TLB entries and restore the original b_addr.
3753 */
3754void
3755vunmapbuf(struct buf *bp)
3756{
3757	int pidx;
3758	int npages;
3759
3760	npages = bp->b_npages;
3761	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3762	vm_page_lock_queues();
3763	for (pidx = 0; pidx < npages; pidx++)
3764		vm_page_unhold(bp->b_pages[pidx]);
3765	vm_page_unlock_queues();
3766
3767	bp->b_data = bp->b_saveaddr;
3768}
3769
3770void
3771bdone(struct buf *bp)
3772{
3773	struct mtx *mtxp;
3774
3775	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3776	mtx_lock(mtxp);
3777	bp->b_flags |= B_DONE;
3778	wakeup(bp);
3779	mtx_unlock(mtxp);
3780}
3781
3782void
3783bwait(struct buf *bp, u_char pri, const char *wchan)
3784{
3785	struct mtx *mtxp;
3786
3787	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3788	mtx_lock(mtxp);
3789	while ((bp->b_flags & B_DONE) == 0)
3790		msleep(bp, mtxp, pri, wchan, 0);
3791	mtx_unlock(mtxp);
3792}
3793
3794int
3795bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3796{
3797
3798	return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3799}
3800
3801void
3802bufstrategy(struct bufobj *bo, struct buf *bp)
3803{
3804	int i = 0;
3805	struct vnode *vp;
3806
3807	vp = bp->b_vp;
3808	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3809	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3810	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3811	i = VOP_STRATEGY(vp, bp);
3812	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3813}
3814
3815void
3816bufobj_wrefl(struct bufobj *bo)
3817{
3818
3819	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3820	ASSERT_BO_LOCKED(bo);
3821	bo->bo_numoutput++;
3822}
3823
3824void
3825bufobj_wref(struct bufobj *bo)
3826{
3827
3828	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3829	BO_LOCK(bo);
3830	bo->bo_numoutput++;
3831	BO_UNLOCK(bo);
3832}
3833
3834void
3835bufobj_wdrop(struct bufobj *bo)
3836{
3837
3838	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3839	BO_LOCK(bo);
3840	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3841	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3842		bo->bo_flag &= ~BO_WWAIT;
3843		wakeup(&bo->bo_numoutput);
3844	}
3845	BO_UNLOCK(bo);
3846}
3847
3848int
3849bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3850{
3851	int error;
3852
3853	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3854	ASSERT_BO_LOCKED(bo);
3855	error = 0;
3856	while (bo->bo_numoutput) {
3857		bo->bo_flag |= BO_WWAIT;
3858		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3859		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3860		if (error)
3861			break;
3862	}
3863	return (error);
3864}
3865
3866void
3867bpin(struct buf *bp)
3868{
3869	struct mtx *mtxp;
3870
3871	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3872	mtx_lock(mtxp);
3873	bp->b_pin_count++;
3874	mtx_unlock(mtxp);
3875}
3876
3877void
3878bunpin(struct buf *bp)
3879{
3880	struct mtx *mtxp;
3881
3882	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3883	mtx_lock(mtxp);
3884	if (--bp->b_pin_count == 0)
3885		wakeup(bp);
3886	mtx_unlock(mtxp);
3887}
3888
3889void
3890bunpin_wait(struct buf *bp)
3891{
3892	struct mtx *mtxp;
3893
3894	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3895	mtx_lock(mtxp);
3896	while (bp->b_pin_count > 0)
3897		msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
3898	mtx_unlock(mtxp);
3899}
3900
3901#include "opt_ddb.h"
3902#ifdef DDB
3903#include <ddb/ddb.h>
3904
3905/* DDB command to show buffer data */
3906DB_SHOW_COMMAND(buffer, db_show_buffer)
3907{
3908	/* get args */
3909	struct buf *bp = (struct buf *)addr;
3910
3911	if (!have_addr) {
3912		db_printf("usage: show buffer <addr>\n");
3913		return;
3914	}
3915
3916	db_printf("buf at %p\n", bp);
3917	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3918	db_printf(
3919	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3920	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n",
3921	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3922	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno);
3923	if (bp->b_npages) {
3924		int i;
3925		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3926		for (i = 0; i < bp->b_npages; i++) {
3927			vm_page_t m;
3928			m = bp->b_pages[i];
3929			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3930			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3931			if ((i + 1) < bp->b_npages)
3932				db_printf(",");
3933		}
3934		db_printf("\n");
3935	}
3936	lockmgr_printinfo(&bp->b_lock);
3937}
3938
3939DB_SHOW_COMMAND(lockedbufs, lockedbufs)
3940{
3941	struct buf *bp;
3942	int i;
3943
3944	for (i = 0; i < nbuf; i++) {
3945		bp = &buf[i];
3946		if (BUF_ISLOCKED(bp)) {
3947			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
3948			db_printf("\n");
3949		}
3950	}
3951}
3952#endif /* DDB */
3953