vfs_bio.c revision 166193
1219820Sjeff/*-
2219820Sjeff * Copyright (c) 2004 Poul-Henning Kamp
3219820Sjeff * Copyright (c) 1994,1997 John S. Dyson
4219820Sjeff * All rights reserved.
5219820Sjeff *
6219820Sjeff * Redistribution and use in source and binary forms, with or without
7219820Sjeff * modification, are permitted provided that the following conditions
8219820Sjeff * are met:
9219820Sjeff * 1. Redistributions of source code must retain the above copyright
10219820Sjeff *    notice, this list of conditions and the following disclaimer.
11219820Sjeff * 2. Redistributions in binary form must reproduce the above copyright
12219820Sjeff *    notice, this list of conditions and the following disclaimer in the
13219820Sjeff *    documentation and/or other materials provided with the distribution.
14219820Sjeff *
15219820Sjeff * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16219820Sjeff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17219820Sjeff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18219820Sjeff * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19219820Sjeff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20219820Sjeff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21219820Sjeff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22219820Sjeff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23219820Sjeff * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24219820Sjeff * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25219820Sjeff * SUCH DAMAGE.
26219820Sjeff */
27219820Sjeff
28219820Sjeff/*
29219820Sjeff * this file contains a new buffer I/O scheme implementing a coherent
30219820Sjeff * VM object and buffer cache scheme.  Pains have been taken to make
31219820Sjeff * sure that the performance degradation associated with schemes such
32219820Sjeff * as this is not realized.
33219820Sjeff *
34219820Sjeff * Author:  John S. Dyson
35219820Sjeff * Significant help during the development and debugging phases
36219820Sjeff * had been provided by David Greenman, also of the FreeBSD core team.
37219820Sjeff *
38219820Sjeff * see man buf(9) for more info.
39219820Sjeff */
40219820Sjeff
41219820Sjeff#include <sys/cdefs.h>
42219820Sjeff__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 166193 2007-01-23 10:01:19Z kib $");
43219820Sjeff
44219820Sjeff#include <sys/param.h>
45219820Sjeff#include <sys/systm.h>
46219820Sjeff#include <sys/bio.h>
47219820Sjeff#include <sys/conf.h>
48219820Sjeff#include <sys/buf.h>
49219820Sjeff#include <sys/devicestat.h>
50219820Sjeff#include <sys/eventhandler.h>
51219820Sjeff#include <sys/lock.h>
52219820Sjeff#include <sys/malloc.h>
53219820Sjeff#include <sys/mount.h>
54219820Sjeff#include <sys/mutex.h>
55219820Sjeff#include <sys/kernel.h>
56219820Sjeff#include <sys/kthread.h>
57219820Sjeff#include <sys/proc.h>
58219820Sjeff#include <sys/resourcevar.h>
59219820Sjeff#include <sys/sysctl.h>
60219820Sjeff#include <sys/vmmeter.h>
61219820Sjeff#include <sys/vnode.h>
62219820Sjeff#include <geom/geom.h>
63219820Sjeff#include <vm/vm.h>
64219820Sjeff#include <vm/vm_param.h>
65219820Sjeff#include <vm/vm_kern.h>
66219820Sjeff#include <vm/vm_pageout.h>
67219820Sjeff#include <vm/vm_page.h>
68219820Sjeff#include <vm/vm_object.h>
69219820Sjeff#include <vm/vm_extern.h>
70219820Sjeff#include <vm/vm_map.h>
71219820Sjeff#include "opt_directio.h"
72219820Sjeff#include "opt_swap.h"
73219820Sjeff
74219820Sjeffstatic MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
75219820Sjeff
76219820Sjeffstruct	bio_ops bioops;		/* I/O operation notification */
77219820Sjeff
78219820Sjeffstruct	buf_ops buf_ops_bio = {
79219820Sjeff	.bop_name	=	"buf_ops_bio",
80219820Sjeff	.bop_write	=	bufwrite,
81219820Sjeff	.bop_strategy	=	bufstrategy,
82219820Sjeff	.bop_sync	=	bufsync,
83219820Sjeff	.bop_bdflush	=	bufbdflush,
84219820Sjeff};
85219820Sjeff
86219820Sjeff/*
87219820Sjeff * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
88219820Sjeff * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
89219820Sjeff */
90219820Sjeffstruct buf *buf;		/* buffer header pool */
91219820Sjeff
92219820Sjeffstatic struct proc *bufdaemonproc;
93219820Sjeff
94219820Sjeffstatic int inmem(struct vnode *vp, daddr_t blkno);
95219820Sjeffstatic void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
96219820Sjeff		vm_offset_t to);
97219820Sjeffstatic void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
98219820Sjeff		vm_offset_t to);
99219820Sjeffstatic void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
100219820Sjeff			       int pageno, vm_page_t m);
101219820Sjeffstatic void vfs_clean_pages(struct buf *bp);
102219820Sjeffstatic void vfs_setdirty(struct buf *bp);
103219820Sjeffstatic void vfs_setdirty_locked_object(struct buf *bp);
104219820Sjeffstatic void vfs_vmio_release(struct buf *bp);
105219820Sjeffstatic int vfs_bio_clcheck(struct vnode *vp, int size,
106219820Sjeff		daddr_t lblkno, daddr_t blkno);
107219820Sjeffstatic int flushbufqueues(int, int);
108219820Sjeffstatic void buf_daemon(void);
109219820Sjeffstatic void bremfreel(struct buf *bp);
110219820Sjeff
111219820Sjeffint vmiodirenable = TRUE;
112219820SjeffSYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
113219820Sjeff    "Use the VM system for directory writes");
114219820Sjeffint runningbufspace;
115219820SjeffSYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
116219820Sjeff    "Amount of presently outstanding async buffer io");
117219820Sjeffstatic int bufspace;
118219820SjeffSYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
119219820Sjeff    "KVA memory used for bufs");
120219820Sjeffstatic int maxbufspace;
121219820SjeffSYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
122219820Sjeff    "Maximum allowed value of bufspace (including buf_daemon)");
123219820Sjeffstatic int bufmallocspace;
124219820SjeffSYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
125219820Sjeff    "Amount of malloced memory for buffers");
126219820Sjeffstatic int maxbufmallocspace;
127219820SjeffSYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
128219820Sjeff    "Maximum amount of malloced memory for buffers");
129219820Sjeffstatic int lobufspace;
130219820SjeffSYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
131219820Sjeff    "Minimum amount of buffers we want to have");
132219820Sjeffint hibufspace;
133219820SjeffSYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
134219820Sjeff    "Maximum allowed value of bufspace (excluding buf_daemon)");
135219820Sjeffstatic int bufreusecnt;
136219820SjeffSYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
137219820Sjeff    "Number of times we have reused a buffer");
138219820Sjeffstatic int buffreekvacnt;
139219820SjeffSYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
140219820Sjeff    "Number of times we have freed the KVA space from some buffer");
141219820Sjeffstatic int bufdefragcnt;
142219820SjeffSYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
143219820Sjeff    "Number of times we have had to repeat buffer allocation to defragment");
144219820Sjeffstatic int lorunningspace;
145219820SjeffSYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
146219820Sjeff    "Minimum preferred space used for in-progress I/O");
147219820Sjeffstatic int hirunningspace;
148219820SjeffSYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
149219820Sjeff    "Maximum amount of space to use for in-progress I/O");
150219820Sjeffint dirtybufferflushes;
151219820SjeffSYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
152219820Sjeff    0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
153219820Sjeffint bdwriteskip;
154219820SjeffSYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
155219820Sjeff    0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
156219820Sjeffint altbufferflushes;
157219820SjeffSYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
158219820Sjeff    0, "Number of fsync flushes to limit dirty buffers");
159219820Sjeffstatic int recursiveflushes;
160219820SjeffSYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
161219820Sjeff    0, "Number of flushes skipped due to being recursive");
162219820Sjeffstatic int numdirtybuffers;
163219820SjeffSYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
164219820Sjeff    "Number of buffers that are dirty (has unwritten changes) at the moment");
165219820Sjeffstatic int lodirtybuffers;
166219820SjeffSYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
167219820Sjeff    "How many buffers we want to have free before bufdaemon can sleep");
168219820Sjeffstatic int hidirtybuffers;
169219820SjeffSYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
170219820Sjeff    "When the number of dirty buffers is considered severe");
171219820Sjeffint dirtybufthresh;
172219820SjeffSYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
173219820Sjeff    0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
174219820Sjeffstatic int numfreebuffers;
175219820SjeffSYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
176219820Sjeff    "Number of free buffers");
177219820Sjeffstatic int lofreebuffers;
178219820SjeffSYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
179219820Sjeff   "XXX Unused");
180219820Sjeffstatic int hifreebuffers;
181219820SjeffSYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
182219820Sjeff   "XXX Complicatedly unused");
183219820Sjeffstatic int getnewbufcalls;
184219820SjeffSYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
185219820Sjeff   "Number of calls to getnewbuf");
186219820Sjeffstatic int getnewbufrestarts;
187219820SjeffSYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
188219820Sjeff    "Number of times getnewbuf has had to restart a buffer aquisition");
189219820Sjeff
190219820Sjeff/*
191219820Sjeff * Wakeup point for bufdaemon, as well as indicator of whether it is already
192219820Sjeff * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
193219820Sjeff * is idling.
194219820Sjeff */
195219820Sjeffstatic int bd_request;
196219820Sjeff
197219820Sjeff/*
198219820Sjeff * This lock synchronizes access to bd_request.
199219820Sjeff */
200219820Sjeffstatic struct mtx bdlock;
201219820Sjeff
202219820Sjeff/*
203219820Sjeff * bogus page -- for I/O to/from partially complete buffers
204219820Sjeff * this is a temporary solution to the problem, but it is not
205219820Sjeff * really that bad.  it would be better to split the buffer
206219820Sjeff * for input in the case of buffers partially already in memory,
207219820Sjeff * but the code is intricate enough already.
208219820Sjeff */
209219820Sjeffvm_page_t bogus_page;
210219820Sjeff
211219820Sjeff/*
212219820Sjeff * Synchronization (sleep/wakeup) variable for active buffer space requests.
213219820Sjeff * Set when wait starts, cleared prior to wakeup().
214219820Sjeff * Used in runningbufwakeup() and waitrunningbufspace().
215219820Sjeff */
216219820Sjeffstatic int runningbufreq;
217219820Sjeff
218219820Sjeff/*
219219820Sjeff * This lock protects the runningbufreq and synchronizes runningbufwakeup and
220219820Sjeff * waitrunningbufspace().
221219820Sjeff */
222219820Sjeffstatic struct mtx rbreqlock;
223219820Sjeff
224219820Sjeff/*
225219820Sjeff * Synchronization (sleep/wakeup) variable for buffer requests.
226219820Sjeff * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
227219820Sjeff * by and/or.
228219820Sjeff * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
229219820Sjeff * getnewbuf(), and getblk().
230219820Sjeff */
231219820Sjeffstatic int needsbuffer;
232219820Sjeff
233219820Sjeff/*
234219820Sjeff * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
235219820Sjeff */
236219820Sjeffstatic struct mtx nblock;
237219820Sjeff
238219820Sjeff/*
239219820Sjeff * Lock that protects against bwait()/bdone()/B_DONE races.
240219820Sjeff */
241219820Sjeff
242219820Sjeffstatic struct mtx bdonelock;
243219820Sjeff
244219820Sjeff/*
245219820Sjeff * Lock that protects against bwait()/bdone()/B_DONE races.
246219820Sjeff */
247219820Sjeffstatic struct mtx bpinlock;
248219820Sjeff
249219820Sjeff/*
250219820Sjeff * Definitions for the buffer free lists.
251219820Sjeff */
252219820Sjeff#define BUFFER_QUEUES	6	/* number of free buffer queues */
253219820Sjeff
254219820Sjeff#define QUEUE_NONE	0	/* on no queue */
255219820Sjeff#define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
256219820Sjeff#define QUEUE_DIRTY	2	/* B_DELWRI buffers */
257219820Sjeff#define QUEUE_DIRTY_GIANT 3	/* B_DELWRI buffers that need giant */
258219820Sjeff#define QUEUE_EMPTYKVA	4	/* empty buffer headers w/KVA assignment */
259219820Sjeff#define QUEUE_EMPTY	5	/* empty buffer headers */
260219820Sjeff
261219820Sjeff/* Queues for free buffers with various properties */
262219820Sjeffstatic TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
263219820Sjeff
264219820Sjeff/* Lock for the bufqueues */
265219820Sjeffstatic struct mtx bqlock;
266219820Sjeff
267219820Sjeff/*
268219820Sjeff * Single global constant for BUF_WMESG, to avoid getting multiple references.
269219820Sjeff * buf_wmesg is referred from macros.
270219820Sjeff */
271219820Sjeffconst char *buf_wmesg = BUF_WMESG;
272219820Sjeff
273219820Sjeff#define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
274219820Sjeff#define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
275219820Sjeff#define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
276219820Sjeff#define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
277219820Sjeff
278219820Sjeff#ifdef DIRECTIO
279219820Sjeffextern void ffs_rawread_setup(void);
280219820Sjeff#endif /* DIRECTIO */
281219820Sjeff/*
282219820Sjeff *	numdirtywakeup:
283219820Sjeff *
284219820Sjeff *	If someone is blocked due to there being too many dirty buffers,
285219820Sjeff *	and numdirtybuffers is now reasonable, wake them up.
286219820Sjeff */
287219820Sjeff
288219820Sjeffstatic __inline void
289219820Sjeffnumdirtywakeup(int level)
290219820Sjeff{
291219820Sjeff
292219820Sjeff	if (numdirtybuffers <= level) {
293219820Sjeff		mtx_lock(&nblock);
294219820Sjeff		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
295219820Sjeff			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
296219820Sjeff			wakeup(&needsbuffer);
297219820Sjeff		}
298219820Sjeff		mtx_unlock(&nblock);
299219820Sjeff	}
300219820Sjeff}
301219820Sjeff
302219820Sjeff/*
303219820Sjeff *	bufspacewakeup:
304219820Sjeff *
305219820Sjeff *	Called when buffer space is potentially available for recovery.
306219820Sjeff *	getnewbuf() will block on this flag when it is unable to free
307219820Sjeff *	sufficient buffer space.  Buffer space becomes recoverable when
308219820Sjeff *	bp's get placed back in the queues.
309219820Sjeff */
310219820Sjeff
311219820Sjeffstatic __inline void
312219820Sjeffbufspacewakeup(void)
313219820Sjeff{
314219820Sjeff
315219820Sjeff	/*
316219820Sjeff	 * If someone is waiting for BUF space, wake them up.  Even
317219820Sjeff	 * though we haven't freed the kva space yet, the waiting
318219820Sjeff	 * process will be able to now.
319219820Sjeff	 */
320219820Sjeff	mtx_lock(&nblock);
321219820Sjeff	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
322219820Sjeff		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
323219820Sjeff		wakeup(&needsbuffer);
324219820Sjeff	}
325219820Sjeff	mtx_unlock(&nblock);
326219820Sjeff}
327219820Sjeff
328219820Sjeff/*
329219820Sjeff * runningbufwakeup() - in-progress I/O accounting.
330219820Sjeff *
331219820Sjeff */
332219820Sjeffvoid
333219820Sjeffrunningbufwakeup(struct buf *bp)
334219820Sjeff{
335219820Sjeff
336219820Sjeff	if (bp->b_runningbufspace) {
337219820Sjeff		atomic_subtract_int(&runningbufspace, bp->b_runningbufspace);
338219820Sjeff		bp->b_runningbufspace = 0;
339219820Sjeff		mtx_lock(&rbreqlock);
340219820Sjeff		if (runningbufreq && runningbufspace <= lorunningspace) {
341219820Sjeff			runningbufreq = 0;
342219820Sjeff			wakeup(&runningbufreq);
343219820Sjeff		}
344219820Sjeff		mtx_unlock(&rbreqlock);
345219820Sjeff	}
346219820Sjeff}
347219820Sjeff
348219820Sjeff/*
349219820Sjeff *	bufcountwakeup:
350219820Sjeff *
351219820Sjeff *	Called when a buffer has been added to one of the free queues to
352219820Sjeff *	account for the buffer and to wakeup anyone waiting for free buffers.
353219820Sjeff *	This typically occurs when large amounts of metadata are being handled
354219820Sjeff *	by the buffer cache ( else buffer space runs out first, usually ).
355219820Sjeff */
356219820Sjeff
357219820Sjeffstatic __inline void
358219820Sjeffbufcountwakeup(void)
359219820Sjeff{
360219820Sjeff
361219820Sjeff	atomic_add_int(&numfreebuffers, 1);
362219820Sjeff	mtx_lock(&nblock);
363219820Sjeff	if (needsbuffer) {
364219820Sjeff		needsbuffer &= ~VFS_BIO_NEED_ANY;
365219820Sjeff		if (numfreebuffers >= hifreebuffers)
366219820Sjeff			needsbuffer &= ~VFS_BIO_NEED_FREE;
367219820Sjeff		wakeup(&needsbuffer);
368219820Sjeff	}
369219820Sjeff	mtx_unlock(&nblock);
370219820Sjeff}
371219820Sjeff
372219820Sjeff/*
373219820Sjeff *	waitrunningbufspace()
374219820Sjeff *
375219820Sjeff *	runningbufspace is a measure of the amount of I/O currently
376219820Sjeff *	running.  This routine is used in async-write situations to
377219820Sjeff *	prevent creating huge backups of pending writes to a device.
378219820Sjeff *	Only asynchronous writes are governed by this function.
379219820Sjeff *
380219820Sjeff *	Reads will adjust runningbufspace, but will not block based on it.
381219820Sjeff *	The read load has a side effect of reducing the allowed write load.
382219820Sjeff *
383219820Sjeff *	This does NOT turn an async write into a sync write.  It waits
384219820Sjeff *	for earlier writes to complete and generally returns before the
385219820Sjeff *	caller's write has reached the device.
386219820Sjeff */
387219820Sjeffvoid
388219820Sjeffwaitrunningbufspace(void)
389219820Sjeff{
390219820Sjeff
391219820Sjeff	mtx_lock(&rbreqlock);
392219820Sjeff	while (runningbufspace > hirunningspace) {
393219820Sjeff		++runningbufreq;
394219820Sjeff		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
395219820Sjeff	}
396219820Sjeff	mtx_unlock(&rbreqlock);
397219820Sjeff}
398219820Sjeff
399219820Sjeff
400219820Sjeff/*
401219820Sjeff *	vfs_buf_test_cache:
402219820Sjeff *
403219820Sjeff *	Called when a buffer is extended.  This function clears the B_CACHE
404219820Sjeff *	bit if the newly extended portion of the buffer does not contain
405219820Sjeff *	valid data.
406219820Sjeff */
407219820Sjeffstatic __inline
408219820Sjeffvoid
409219820Sjeffvfs_buf_test_cache(struct buf *bp,
410219820Sjeff		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
411219820Sjeff		  vm_page_t m)
412219820Sjeff{
413219820Sjeff
414219820Sjeff	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
415219820Sjeff	if (bp->b_flags & B_CACHE) {
416219820Sjeff		int base = (foff + off) & PAGE_MASK;
417219820Sjeff		if (vm_page_is_valid(m, base, size) == 0)
418219820Sjeff			bp->b_flags &= ~B_CACHE;
419219820Sjeff	}
420219820Sjeff}
421219820Sjeff
422219820Sjeff/* Wake up the buffer deamon if necessary */
423219820Sjeffstatic __inline
424219820Sjeffvoid
425219820Sjeffbd_wakeup(int dirtybuflevel)
426219820Sjeff{
427219820Sjeff
428219820Sjeff	mtx_lock(&bdlock);
429219820Sjeff	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
430219820Sjeff		bd_request = 1;
431219820Sjeff		wakeup(&bd_request);
432219820Sjeff	}
433219820Sjeff	mtx_unlock(&bdlock);
434219820Sjeff}
435219820Sjeff
436219820Sjeff/*
437219820Sjeff * bd_speedup - speedup the buffer cache flushing code
438219820Sjeff */
439219820Sjeff
440219820Sjeffstatic __inline
441219820Sjeffvoid
442219820Sjeffbd_speedup(void)
443219820Sjeff{
444219820Sjeff
445219820Sjeff	bd_wakeup(1);
446219820Sjeff}
447219820Sjeff
448219820Sjeff/*
449219820Sjeff * Calculating buffer cache scaling values and reserve space for buffer
450219820Sjeff * headers.  This is called during low level kernel initialization and
451219820Sjeff * may be called more then once.  We CANNOT write to the memory area
452219820Sjeff * being reserved at this time.
453219820Sjeff */
454219820Sjeffcaddr_t
455219820Sjeffkern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
456219820Sjeff{
457219820Sjeff
458219820Sjeff	/*
459219820Sjeff	 * physmem_est is in pages.  Convert it to kilobytes (assumes
460219820Sjeff	 * PAGE_SIZE is >= 1K)
461219820Sjeff	 */
462219820Sjeff	physmem_est = physmem_est * (PAGE_SIZE / 1024);
463219820Sjeff
464219820Sjeff	/*
465219820Sjeff	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
466219820Sjeff	 * For the first 64MB of ram nominally allocate sufficient buffers to
467219820Sjeff	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
468219820Sjeff	 * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
469219820Sjeff	 * the buffer cache we limit the eventual kva reservation to
470219820Sjeff	 * maxbcache bytes.
471219820Sjeff	 *
472219820Sjeff	 * factor represents the 1/4 x ram conversion.
473219820Sjeff	 */
474219820Sjeff	if (nbuf == 0) {
475219820Sjeff		int factor = 4 * BKVASIZE / 1024;
476219820Sjeff
477219820Sjeff		nbuf = 50;
478219820Sjeff		if (physmem_est > 4096)
479219820Sjeff			nbuf += min((physmem_est - 4096) / factor,
480219820Sjeff			    65536 / factor);
481219820Sjeff		if (physmem_est > 65536)
482219820Sjeff			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
483219820Sjeff
484219820Sjeff		if (maxbcache && nbuf > maxbcache / BKVASIZE)
485219820Sjeff			nbuf = maxbcache / BKVASIZE;
486219820Sjeff	}
487219820Sjeff
488219820Sjeff#if 0
489219820Sjeff	/*
490219820Sjeff	 * Do not allow the buffer_map to be more then 1/2 the size of the
491219820Sjeff	 * kernel_map.
492219820Sjeff	 */
493219820Sjeff	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
494219820Sjeff	    (BKVASIZE * 2)) {
495219820Sjeff		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
496219820Sjeff		    (BKVASIZE * 2);
497219820Sjeff		printf("Warning: nbufs capped at %d\n", nbuf);
498219820Sjeff	}
499219820Sjeff#endif
500219820Sjeff
501219820Sjeff	/*
502219820Sjeff	 * swbufs are used as temporary holders for I/O, such as paging I/O.
503219820Sjeff	 * We have no less then 16 and no more then 256.
504219820Sjeff	 */
505219820Sjeff	nswbuf = max(min(nbuf/4, 256), 16);
506219820Sjeff#ifdef NSWBUF_MIN
507219820Sjeff	if (nswbuf < NSWBUF_MIN)
508219820Sjeff		nswbuf = NSWBUF_MIN;
509219820Sjeff#endif
510219820Sjeff#ifdef DIRECTIO
511219820Sjeff	ffs_rawread_setup();
512219820Sjeff#endif
513219820Sjeff
514219820Sjeff	/*
515219820Sjeff	 * Reserve space for the buffer cache buffers
516219820Sjeff	 */
517219820Sjeff	swbuf = (void *)v;
518219820Sjeff	v = (caddr_t)(swbuf + nswbuf);
519219820Sjeff	buf = (void *)v;
520219820Sjeff	v = (caddr_t)(buf + nbuf);
521219820Sjeff
522219820Sjeff	return(v);
523219820Sjeff}
524219820Sjeff
525219820Sjeff/* Initialize the buffer subsystem.  Called before use of any buffers. */
526219820Sjeffvoid
527219820Sjeffbufinit(void)
528219820Sjeff{
529219820Sjeff	struct buf *bp;
530219820Sjeff	int i;
531219820Sjeff
532219820Sjeff	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
533219820Sjeff	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
534219820Sjeff	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
535219820Sjeff	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
536219820Sjeff	mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
537219820Sjeff	mtx_init(&bpinlock, "bpin lock", NULL, MTX_DEF);
538219820Sjeff
539219820Sjeff	/* next, make a null set of free lists */
540219820Sjeff	for (i = 0; i < BUFFER_QUEUES; i++)
541219820Sjeff		TAILQ_INIT(&bufqueues[i]);
542219820Sjeff
543219820Sjeff	/* finally, initialize each buffer header and stick on empty q */
544219820Sjeff	for (i = 0; i < nbuf; i++) {
545219820Sjeff		bp = &buf[i];
546219820Sjeff		bzero(bp, sizeof *bp);
547219820Sjeff		bp->b_flags = B_INVAL;	/* we're just an empty header */
548219820Sjeff		bp->b_rcred = NOCRED;
549219820Sjeff		bp->b_wcred = NOCRED;
550219820Sjeff		bp->b_qindex = QUEUE_EMPTY;
551219820Sjeff		bp->b_vflags = 0;
552219820Sjeff		bp->b_xflags = 0;
553219820Sjeff		LIST_INIT(&bp->b_dep);
554219820Sjeff		BUF_LOCKINIT(bp);
555219820Sjeff		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
556219820Sjeff	}
557219820Sjeff
558219820Sjeff	/*
559219820Sjeff	 * maxbufspace is the absolute maximum amount of buffer space we are
560219820Sjeff	 * allowed to reserve in KVM and in real terms.  The absolute maximum
561219820Sjeff	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
562219820Sjeff	 * used by most other processes.  The differential is required to
563219820Sjeff	 * ensure that buf_daemon is able to run when other processes might
564219820Sjeff	 * be blocked waiting for buffer space.
565219820Sjeff	 *
566219820Sjeff	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
567219820Sjeff	 * this may result in KVM fragmentation which is not handled optimally
568219820Sjeff	 * by the system.
569219820Sjeff	 */
570219820Sjeff	maxbufspace = nbuf * BKVASIZE;
571219820Sjeff	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
572219820Sjeff	lobufspace = hibufspace - MAXBSIZE;
573219820Sjeff
574219820Sjeff	lorunningspace = 512 * 1024;
575219820Sjeff	hirunningspace = 1024 * 1024;
576219820Sjeff
577219820Sjeff/*
578219820Sjeff * Limit the amount of malloc memory since it is wired permanently into
579219820Sjeff * the kernel space.  Even though this is accounted for in the buffer
580219820Sjeff * allocation, we don't want the malloced region to grow uncontrolled.
581219820Sjeff * The malloc scheme improves memory utilization significantly on average
582219820Sjeff * (small) directories.
583219820Sjeff */
584219820Sjeff	maxbufmallocspace = hibufspace / 20;
585219820Sjeff
586219820Sjeff/*
587219820Sjeff * Reduce the chance of a deadlock occuring by limiting the number
588219820Sjeff * of delayed-write dirty buffers we allow to stack up.
589219820Sjeff */
590219820Sjeff	hidirtybuffers = nbuf / 4 + 20;
591219820Sjeff	dirtybufthresh = hidirtybuffers * 9 / 10;
592219820Sjeff	numdirtybuffers = 0;
593219820Sjeff/*
594219820Sjeff * To support extreme low-memory systems, make sure hidirtybuffers cannot
595219820Sjeff * eat up all available buffer space.  This occurs when our minimum cannot
596219820Sjeff * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
597219820Sjeff * BKVASIZE'd (8K) buffers.
598219820Sjeff */
599219820Sjeff	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
600219820Sjeff		hidirtybuffers >>= 1;
601219820Sjeff	}
602219820Sjeff	lodirtybuffers = hidirtybuffers / 2;
603219820Sjeff
604219820Sjeff/*
605219820Sjeff * Try to keep the number of free buffers in the specified range,
606219820Sjeff * and give special processes (e.g. like buf_daemon) access to an
607219820Sjeff * emergency reserve.
608219820Sjeff */
609219820Sjeff	lofreebuffers = nbuf / 18 + 5;
610219820Sjeff	hifreebuffers = 2 * lofreebuffers;
611219820Sjeff	numfreebuffers = nbuf;
612219820Sjeff
613219820Sjeff/*
614219820Sjeff * Maximum number of async ops initiated per buf_daemon loop.  This is
615219820Sjeff * somewhat of a hack at the moment, we really need to limit ourselves
616219820Sjeff * based on the number of bytes of I/O in-transit that were initiated
617219820Sjeff * from buf_daemon.
618219820Sjeff */
619219820Sjeff
620219820Sjeff	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
621219820Sjeff	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
622219820Sjeff}
623219820Sjeff
624219820Sjeff/*
625219820Sjeff * bfreekva() - free the kva allocation for a buffer.
626219820Sjeff *
627219820Sjeff *	Since this call frees up buffer space, we call bufspacewakeup().
628219820Sjeff */
629219820Sjeffstatic void
630219820Sjeffbfreekva(struct buf *bp)
631219820Sjeff{
632219820Sjeff
633219820Sjeff	if (bp->b_kvasize) {
634219820Sjeff		atomic_add_int(&buffreekvacnt, 1);
635219820Sjeff		atomic_subtract_int(&bufspace, bp->b_kvasize);
636219820Sjeff		vm_map_lock(buffer_map);
637219820Sjeff		vm_map_delete(buffer_map,
638219820Sjeff		    (vm_offset_t) bp->b_kvabase,
639219820Sjeff		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
640219820Sjeff		);
641219820Sjeff		vm_map_unlock(buffer_map);
642219820Sjeff		bp->b_kvasize = 0;
643219820Sjeff		bufspacewakeup();
644219820Sjeff	}
645219820Sjeff}
646219820Sjeff
647219820Sjeff/*
648219820Sjeff *	bremfree:
649219820Sjeff *
650219820Sjeff *	Mark the buffer for removal from the appropriate free list in brelse.
651219820Sjeff *
652219820Sjeff */
653219820Sjeffvoid
654219820Sjeffbremfree(struct buf *bp)
655219820Sjeff{
656219820Sjeff
657219820Sjeff	CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
658219820Sjeff	KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked."));
659219820Sjeff	KASSERT((bp->b_flags & B_REMFREE) == 0,
660219820Sjeff	    ("bremfree: buffer %p already marked for delayed removal.", bp));
661219820Sjeff	KASSERT(bp->b_qindex != QUEUE_NONE,
662219820Sjeff	    ("bremfree: buffer %p not on a queue.", bp));
663219820Sjeff
664219820Sjeff	bp->b_flags |= B_REMFREE;
665219820Sjeff	/* Fixup numfreebuffers count.  */
666219820Sjeff	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
667219820Sjeff		atomic_subtract_int(&numfreebuffers, 1);
668219820Sjeff}
669219820Sjeff
670219820Sjeff/*
671219820Sjeff *	bremfreef:
672219820Sjeff *
673219820Sjeff *	Force an immediate removal from a free list.  Used only in nfs when
674219820Sjeff *	it abuses the b_freelist pointer.
675219820Sjeff */
676219820Sjeffvoid
677219820Sjeffbremfreef(struct buf *bp)
678219820Sjeff{
679219820Sjeff	mtx_lock(&bqlock);
680219820Sjeff	bremfreel(bp);
681219820Sjeff	mtx_unlock(&bqlock);
682219820Sjeff}
683219820Sjeff
684219820Sjeff/*
685219820Sjeff *	bremfreel:
686219820Sjeff *
687219820Sjeff *	Removes a buffer from the free list, must be called with the
688219820Sjeff *	bqlock held.
689219820Sjeff */
690219820Sjeffstatic void
691219820Sjeffbremfreel(struct buf *bp)
692219820Sjeff{
693219820Sjeff	CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
694219820Sjeff	    bp, bp->b_vp, bp->b_flags);
695219820Sjeff	KASSERT(BUF_REFCNT(bp), ("bremfreel: buffer %p not locked.", bp));
696219820Sjeff	KASSERT(bp->b_qindex != QUEUE_NONE,
697219820Sjeff	    ("bremfreel: buffer %p not on a queue.", bp));
698219820Sjeff	mtx_assert(&bqlock, MA_OWNED);
699219820Sjeff
700219820Sjeff	TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
701219820Sjeff	bp->b_qindex = QUEUE_NONE;
702219820Sjeff	/*
703219820Sjeff	 * If this was a delayed bremfree() we only need to remove the buffer
704219820Sjeff	 * from the queue and return the stats are already done.
705219820Sjeff	 */
706219820Sjeff	if (bp->b_flags & B_REMFREE) {
707219820Sjeff		bp->b_flags &= ~B_REMFREE;
708219820Sjeff		return;
709219820Sjeff	}
710219820Sjeff	/*
711219820Sjeff	 * Fixup numfreebuffers count.  If the buffer is invalid or not
712219820Sjeff	 * delayed-write, the buffer was free and we must decrement
713219820Sjeff	 * numfreebuffers.
714219820Sjeff	 */
715219820Sjeff	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
716219820Sjeff		atomic_subtract_int(&numfreebuffers, 1);
717219820Sjeff}
718219820Sjeff
719219820Sjeff
720219820Sjeff/*
721219820Sjeff * Get a buffer with the specified data.  Look in the cache first.  We
722219820Sjeff * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
723219820Sjeff * is set, the buffer is valid and we do not have to do anything ( see
724219820Sjeff * getblk() ).  This is really just a special case of breadn().
725219820Sjeff */
726219820Sjeffint
727219820Sjeffbread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
728219820Sjeff    struct buf **bpp)
729219820Sjeff{
730219820Sjeff
731219820Sjeff	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
732219820Sjeff}
733219820Sjeff
734219820Sjeff/*
735219820Sjeff * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
736219820Sjeff * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
737219820Sjeff * the buffer is valid and we do not have to do anything.
738219820Sjeff */
739219820Sjeffvoid
740219820Sjeffbreada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
741219820Sjeff    int cnt, struct ucred * cred)
742219820Sjeff{
743219820Sjeff	struct buf *rabp;
744219820Sjeff	int i;
745219820Sjeff
746219820Sjeff	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
747219820Sjeff		if (inmem(vp, *rablkno))
748219820Sjeff			continue;
749219820Sjeff		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
750219820Sjeff
751219820Sjeff		if ((rabp->b_flags & B_CACHE) == 0) {
752219820Sjeff			if (curthread != PCPU_GET(idlethread))
753219820Sjeff				curthread->td_proc->p_stats->p_ru.ru_inblock++;
754219820Sjeff			rabp->b_flags |= B_ASYNC;
755219820Sjeff			rabp->b_flags &= ~B_INVAL;
756219820Sjeff			rabp->b_ioflags &= ~BIO_ERROR;
757219820Sjeff			rabp->b_iocmd = BIO_READ;
758219820Sjeff			if (rabp->b_rcred == NOCRED && cred != NOCRED)
759219820Sjeff				rabp->b_rcred = crhold(cred);
760219820Sjeff			vfs_busy_pages(rabp, 0);
761219820Sjeff			BUF_KERNPROC(rabp);
762219820Sjeff			rabp->b_iooffset = dbtob(rabp->b_blkno);
763219820Sjeff			bstrategy(rabp);
764219820Sjeff		} else {
765219820Sjeff			brelse(rabp);
766219820Sjeff		}
767219820Sjeff	}
768219820Sjeff}
769219820Sjeff
770219820Sjeff/*
771219820Sjeff * Operates like bread, but also starts asynchronous I/O on
772219820Sjeff * read-ahead blocks.
773219820Sjeff */
774219820Sjeffint
775219820Sjeffbreadn(struct vnode * vp, daddr_t blkno, int size,
776219820Sjeff    daddr_t * rablkno, int *rabsize,
777219820Sjeff    int cnt, struct ucred * cred, struct buf **bpp)
778219820Sjeff{
779219820Sjeff	struct buf *bp;
780219820Sjeff	int rv = 0, readwait = 0;
781219820Sjeff
782219820Sjeff	CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
783219820Sjeff	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
784219820Sjeff
785219820Sjeff	/* if not found in cache, do some I/O */
786219820Sjeff	if ((bp->b_flags & B_CACHE) == 0) {
787219820Sjeff		if (curthread != PCPU_GET(idlethread))
788219820Sjeff			curthread->td_proc->p_stats->p_ru.ru_inblock++;
789219820Sjeff		bp->b_iocmd = BIO_READ;
790219820Sjeff		bp->b_flags &= ~B_INVAL;
791219820Sjeff		bp->b_ioflags &= ~BIO_ERROR;
792219820Sjeff		if (bp->b_rcred == NOCRED && cred != NOCRED)
793219820Sjeff			bp->b_rcred = crhold(cred);
794219820Sjeff		vfs_busy_pages(bp, 0);
795219820Sjeff		bp->b_iooffset = dbtob(bp->b_blkno);
796219820Sjeff		bstrategy(bp);
797219820Sjeff		++readwait;
798219820Sjeff	}
799219820Sjeff
800219820Sjeff	breada(vp, rablkno, rabsize, cnt, cred);
801219820Sjeff
802219820Sjeff	if (readwait) {
803219820Sjeff		rv = bufwait(bp);
804219820Sjeff	}
805219820Sjeff	return (rv);
806219820Sjeff}
807219820Sjeff
808219820Sjeff/*
809219820Sjeff * Write, release buffer on completion.  (Done by iodone
810219820Sjeff * if async).  Do not bother writing anything if the buffer
811219820Sjeff * is invalid.
812219820Sjeff *
813219820Sjeff * Note that we set B_CACHE here, indicating that buffer is
814219820Sjeff * fully valid and thus cacheable.  This is true even of NFS
815219820Sjeff * now so we set it generally.  This could be set either here
816219820Sjeff * or in biodone() since the I/O is synchronous.  We put it
817219820Sjeff * here.
818219820Sjeff */
819219820Sjeffint
820219820Sjeffbufwrite(struct buf *bp)
821219820Sjeff{
822219820Sjeff	int oldflags;
823219820Sjeff	struct vnode *vp;
824219820Sjeff	int vp_md;
825219820Sjeff
826219820Sjeff	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
827219820Sjeff	if (bp->b_flags & B_INVAL) {
828219820Sjeff		brelse(bp);
829219820Sjeff		return (0);
830219820Sjeff	}
831219820Sjeff
832219820Sjeff	oldflags = bp->b_flags;
833219820Sjeff
834219820Sjeff	if (BUF_REFCNT(bp) == 0)
835219820Sjeff		panic("bufwrite: buffer is not busy???");
836219820Sjeff
837219820Sjeff	if (bp->b_pin_count > 0)
838219820Sjeff		bunpin_wait(bp);
839219820Sjeff
840219820Sjeff	KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
841219820Sjeff	    ("FFS background buffer should not get here %p", bp));
842219820Sjeff
843219820Sjeff	vp = bp->b_vp;
844219820Sjeff	if (vp)
845219820Sjeff		vp_md = vp->v_vflag & VV_MD;
846219820Sjeff	else
847219820Sjeff		vp_md = 0;
848219820Sjeff
849219820Sjeff	/* Mark the buffer clean */
850219820Sjeff	bundirty(bp);
851219820Sjeff
852219820Sjeff	bp->b_flags &= ~B_DONE;
853219820Sjeff	bp->b_ioflags &= ~BIO_ERROR;
854219820Sjeff	bp->b_flags |= B_CACHE;
855219820Sjeff	bp->b_iocmd = BIO_WRITE;
856219820Sjeff
857219820Sjeff	bufobj_wref(bp->b_bufobj);
858219820Sjeff	vfs_busy_pages(bp, 1);
859219820Sjeff
860219820Sjeff	/*
861219820Sjeff	 * Normal bwrites pipeline writes
862219820Sjeff	 */
863219820Sjeff	bp->b_runningbufspace = bp->b_bufsize;
864219820Sjeff	atomic_add_int(&runningbufspace, bp->b_runningbufspace);
865
866	if (curthread != PCPU_GET(idlethread))
867		curthread->td_proc->p_stats->p_ru.ru_oublock++;
868	if (oldflags & B_ASYNC)
869		BUF_KERNPROC(bp);
870	bp->b_iooffset = dbtob(bp->b_blkno);
871	bstrategy(bp);
872
873	if ((oldflags & B_ASYNC) == 0) {
874		int rtval = bufwait(bp);
875		brelse(bp);
876		return (rtval);
877	} else {
878		/*
879		 * don't allow the async write to saturate the I/O
880		 * system.  We will not deadlock here because
881		 * we are blocking waiting for I/O that is already in-progress
882		 * to complete. We do not block here if it is the update
883		 * or syncer daemon trying to clean up as that can lead
884		 * to deadlock.
885		 */
886		if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
887			waitrunningbufspace();
888	}
889
890	return (0);
891}
892
893void
894bufbdflush(struct bufobj *bo, struct buf *bp)
895{
896	struct buf *nbp;
897
898	if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
899		(void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
900		altbufferflushes++;
901	} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
902		BO_LOCK(bo);
903		/*
904		 * Try to find a buffer to flush.
905		 */
906		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
907			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
908			    BUF_LOCK(nbp,
909				     LK_EXCLUSIVE | LK_NOWAIT, NULL))
910				continue;
911			if (bp == nbp)
912				panic("bdwrite: found ourselves");
913			BO_UNLOCK(bo);
914			/* Don't countdeps with the bo lock held. */
915			if (buf_countdeps(nbp, 0)) {
916				BO_LOCK(bo);
917				BUF_UNLOCK(nbp);
918				continue;
919			}
920			if (nbp->b_flags & B_CLUSTEROK) {
921				vfs_bio_awrite(nbp);
922			} else {
923				bremfree(nbp);
924				bawrite(nbp);
925			}
926			dirtybufferflushes++;
927			break;
928		}
929		if (nbp == NULL)
930			BO_UNLOCK(bo);
931	}
932}
933
934/*
935 * Delayed write. (Buffer is marked dirty).  Do not bother writing
936 * anything if the buffer is marked invalid.
937 *
938 * Note that since the buffer must be completely valid, we can safely
939 * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
940 * biodone() in order to prevent getblk from writing the buffer
941 * out synchronously.
942 */
943void
944bdwrite(struct buf *bp)
945{
946	struct thread *td = curthread;
947	struct vnode *vp;
948	struct bufobj *bo;
949
950	CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
951	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
952	KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy"));
953
954	if (bp->b_flags & B_INVAL) {
955		brelse(bp);
956		return;
957	}
958
959	/*
960	 * If we have too many dirty buffers, don't create any more.
961	 * If we are wildly over our limit, then force a complete
962	 * cleanup. Otherwise, just keep the situation from getting
963	 * out of control. Note that we have to avoid a recursive
964	 * disaster and not try to clean up after our own cleanup!
965	 */
966	vp = bp->b_vp;
967	bo = bp->b_bufobj;
968	if ((td->td_pflags & TDP_COWINPROGRESS) == 0)
969		BO_BDFLUSH(bo, bp);
970	else
971		recursiveflushes++;
972
973	bdirty(bp);
974	/*
975	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
976	 * true even of NFS now.
977	 */
978	bp->b_flags |= B_CACHE;
979
980	/*
981	 * This bmap keeps the system from needing to do the bmap later,
982	 * perhaps when the system is attempting to do a sync.  Since it
983	 * is likely that the indirect block -- or whatever other datastructure
984	 * that the filesystem needs is still in memory now, it is a good
985	 * thing to do this.  Note also, that if the pageout daemon is
986	 * requesting a sync -- there might not be enough memory to do
987	 * the bmap then...  So, this is important to do.
988	 */
989	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
990		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
991	}
992
993	/*
994	 * Set the *dirty* buffer range based upon the VM system dirty pages.
995	 */
996	vfs_setdirty(bp);
997
998	/*
999	 * We need to do this here to satisfy the vnode_pager and the
1000	 * pageout daemon, so that it thinks that the pages have been
1001	 * "cleaned".  Note that since the pages are in a delayed write
1002	 * buffer -- the VFS layer "will" see that the pages get written
1003	 * out on the next sync, or perhaps the cluster will be completed.
1004	 */
1005	vfs_clean_pages(bp);
1006	bqrelse(bp);
1007
1008	/*
1009	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1010	 * buffers (midpoint between our recovery point and our stall
1011	 * point).
1012	 */
1013	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1014
1015	/*
1016	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1017	 * due to the softdep code.
1018	 */
1019}
1020
1021/*
1022 *	bdirty:
1023 *
1024 *	Turn buffer into delayed write request.  We must clear BIO_READ and
1025 *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1026 *	itself to properly update it in the dirty/clean lists.  We mark it
1027 *	B_DONE to ensure that any asynchronization of the buffer properly
1028 *	clears B_DONE ( else a panic will occur later ).
1029 *
1030 *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1031 *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1032 *	should only be called if the buffer is known-good.
1033 *
1034 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1035 *	count.
1036 *
1037 *	The buffer must be on QUEUE_NONE.
1038 */
1039void
1040bdirty(struct buf *bp)
1041{
1042
1043	CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1044	    bp, bp->b_vp, bp->b_flags);
1045	KASSERT(BUF_REFCNT(bp) == 1, ("bdirty: bp %p not locked",bp));
1046	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1047	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1048	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1049	bp->b_flags &= ~(B_RELBUF);
1050	bp->b_iocmd = BIO_WRITE;
1051
1052	if ((bp->b_flags & B_DELWRI) == 0) {
1053		bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1054		reassignbuf(bp);
1055		atomic_add_int(&numdirtybuffers, 1);
1056		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1057	}
1058}
1059
1060/*
1061 *	bundirty:
1062 *
1063 *	Clear B_DELWRI for buffer.
1064 *
1065 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1066 *	count.
1067 *
1068 *	The buffer must be on QUEUE_NONE.
1069 */
1070
1071void
1072bundirty(struct buf *bp)
1073{
1074
1075	CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1076	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1077	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1078	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1079	KASSERT(BUF_REFCNT(bp) == 1, ("bundirty: bp %p not locked",bp));
1080
1081	if (bp->b_flags & B_DELWRI) {
1082		bp->b_flags &= ~B_DELWRI;
1083		reassignbuf(bp);
1084		atomic_subtract_int(&numdirtybuffers, 1);
1085		numdirtywakeup(lodirtybuffers);
1086	}
1087	/*
1088	 * Since it is now being written, we can clear its deferred write flag.
1089	 */
1090	bp->b_flags &= ~B_DEFERRED;
1091}
1092
1093/*
1094 *	bawrite:
1095 *
1096 *	Asynchronous write.  Start output on a buffer, but do not wait for
1097 *	it to complete.  The buffer is released when the output completes.
1098 *
1099 *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1100 *	B_INVAL buffers.  Not us.
1101 */
1102void
1103bawrite(struct buf *bp)
1104{
1105
1106	bp->b_flags |= B_ASYNC;
1107	(void) bwrite(bp);
1108}
1109
1110/*
1111 *	bwillwrite:
1112 *
1113 *	Called prior to the locking of any vnodes when we are expecting to
1114 *	write.  We do not want to starve the buffer cache with too many
1115 *	dirty buffers so we block here.  By blocking prior to the locking
1116 *	of any vnodes we attempt to avoid the situation where a locked vnode
1117 *	prevents the various system daemons from flushing related buffers.
1118 */
1119
1120void
1121bwillwrite(void)
1122{
1123
1124	if (numdirtybuffers >= hidirtybuffers) {
1125		mtx_lock(&nblock);
1126		while (numdirtybuffers >= hidirtybuffers) {
1127			bd_wakeup(1);
1128			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1129			msleep(&needsbuffer, &nblock,
1130			    (PRIBIO + 4), "flswai", 0);
1131		}
1132		mtx_unlock(&nblock);
1133	}
1134}
1135
1136/*
1137 * Return true if we have too many dirty buffers.
1138 */
1139int
1140buf_dirty_count_severe(void)
1141{
1142
1143	return(numdirtybuffers >= hidirtybuffers);
1144}
1145
1146/*
1147 *	brelse:
1148 *
1149 *	Release a busy buffer and, if requested, free its resources.  The
1150 *	buffer will be stashed in the appropriate bufqueue[] allowing it
1151 *	to be accessed later as a cache entity or reused for other purposes.
1152 */
1153void
1154brelse(struct buf *bp)
1155{
1156	CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1157	    bp, bp->b_vp, bp->b_flags);
1158	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1159	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1160
1161	if (bp->b_flags & B_MANAGED) {
1162		bqrelse(bp);
1163		return;
1164	}
1165
1166	if (bp->b_iocmd == BIO_WRITE &&
1167	    (bp->b_ioflags & BIO_ERROR) &&
1168	    !(bp->b_flags & B_INVAL)) {
1169		/*
1170		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1171		 * pages from being scrapped.  If B_INVAL is set then
1172		 * this case is not run and the next case is run to
1173		 * destroy the buffer.  B_INVAL can occur if the buffer
1174		 * is outside the range supported by the underlying device.
1175		 */
1176		bp->b_ioflags &= ~BIO_ERROR;
1177		bdirty(bp);
1178	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1179	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1180		/*
1181		 * Either a failed I/O or we were asked to free or not
1182		 * cache the buffer.
1183		 */
1184		bp->b_flags |= B_INVAL;
1185		if (LIST_FIRST(&bp->b_dep) != NULL)
1186			buf_deallocate(bp);
1187		if (bp->b_flags & B_DELWRI) {
1188			atomic_subtract_int(&numdirtybuffers, 1);
1189			numdirtywakeup(lodirtybuffers);
1190		}
1191		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1192		if ((bp->b_flags & B_VMIO) == 0) {
1193			if (bp->b_bufsize)
1194				allocbuf(bp, 0);
1195			if (bp->b_vp)
1196				brelvp(bp);
1197		}
1198	}
1199
1200	/*
1201	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1202	 * is called with B_DELWRI set, the underlying pages may wind up
1203	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1204	 * because pages associated with a B_DELWRI bp are marked clean.
1205	 *
1206	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1207	 * if B_DELWRI is set.
1208	 *
1209	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1210	 * on pages to return pages to the VM page queues.
1211	 */
1212	if (bp->b_flags & B_DELWRI)
1213		bp->b_flags &= ~B_RELBUF;
1214	else if (vm_page_count_severe()) {
1215		/*
1216		 * XXX This lock may not be necessary since BKGRDINPROG
1217		 * cannot be set while we hold the buf lock, it can only be
1218		 * cleared if it is already pending.
1219		 */
1220		if (bp->b_vp) {
1221			BO_LOCK(bp->b_bufobj);
1222			if (!(bp->b_vflags & BV_BKGRDINPROG))
1223				bp->b_flags |= B_RELBUF;
1224			BO_UNLOCK(bp->b_bufobj);
1225		} else
1226			bp->b_flags |= B_RELBUF;
1227	}
1228
1229	/*
1230	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1231	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1232	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1233	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1234	 *
1235	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1236	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1237	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1238	 *
1239	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1240	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1241	 * the commit state and we cannot afford to lose the buffer. If the
1242	 * buffer has a background write in progress, we need to keep it
1243	 * around to prevent it from being reconstituted and starting a second
1244	 * background write.
1245	 */
1246	if ((bp->b_flags & B_VMIO)
1247	    && !(bp->b_vp->v_mount != NULL &&
1248		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1249		 !vn_isdisk(bp->b_vp, NULL) &&
1250		 (bp->b_flags & B_DELWRI))
1251	    ) {
1252
1253		int i, j, resid;
1254		vm_page_t m;
1255		off_t foff;
1256		vm_pindex_t poff;
1257		vm_object_t obj;
1258
1259		obj = bp->b_bufobj->bo_object;
1260
1261		/*
1262		 * Get the base offset and length of the buffer.  Note that
1263		 * in the VMIO case if the buffer block size is not
1264		 * page-aligned then b_data pointer may not be page-aligned.
1265		 * But our b_pages[] array *IS* page aligned.
1266		 *
1267		 * block sizes less then DEV_BSIZE (usually 512) are not
1268		 * supported due to the page granularity bits (m->valid,
1269		 * m->dirty, etc...).
1270		 *
1271		 * See man buf(9) for more information
1272		 */
1273		resid = bp->b_bufsize;
1274		foff = bp->b_offset;
1275		VM_OBJECT_LOCK(obj);
1276		for (i = 0; i < bp->b_npages; i++) {
1277			int had_bogus = 0;
1278
1279			m = bp->b_pages[i];
1280
1281			/*
1282			 * If we hit a bogus page, fixup *all* the bogus pages
1283			 * now.
1284			 */
1285			if (m == bogus_page) {
1286				poff = OFF_TO_IDX(bp->b_offset);
1287				had_bogus = 1;
1288
1289				for (j = i; j < bp->b_npages; j++) {
1290					vm_page_t mtmp;
1291					mtmp = bp->b_pages[j];
1292					if (mtmp == bogus_page) {
1293						mtmp = vm_page_lookup(obj, poff + j);
1294						if (!mtmp) {
1295							panic("brelse: page missing\n");
1296						}
1297						bp->b_pages[j] = mtmp;
1298					}
1299				}
1300
1301				if ((bp->b_flags & B_INVAL) == 0) {
1302					pmap_qenter(
1303					    trunc_page((vm_offset_t)bp->b_data),
1304					    bp->b_pages, bp->b_npages);
1305				}
1306				m = bp->b_pages[i];
1307			}
1308			if ((bp->b_flags & B_NOCACHE) ||
1309			    (bp->b_ioflags & BIO_ERROR)) {
1310				int poffset = foff & PAGE_MASK;
1311				int presid = resid > (PAGE_SIZE - poffset) ?
1312					(PAGE_SIZE - poffset) : resid;
1313
1314				KASSERT(presid >= 0, ("brelse: extra page"));
1315				vm_page_lock_queues();
1316				vm_page_set_invalid(m, poffset, presid);
1317				vm_page_unlock_queues();
1318				if (had_bogus)
1319					printf("avoided corruption bug in bogus_page/brelse code\n");
1320			}
1321			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1322			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1323		}
1324		VM_OBJECT_UNLOCK(obj);
1325		if (bp->b_flags & (B_INVAL | B_RELBUF))
1326			vfs_vmio_release(bp);
1327
1328	} else if (bp->b_flags & B_VMIO) {
1329
1330		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1331			vfs_vmio_release(bp);
1332		}
1333
1334	} else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1335		if (bp->b_bufsize != 0)
1336			allocbuf(bp, 0);
1337		if (bp->b_vp != NULL)
1338			brelvp(bp);
1339	}
1340
1341	if (BUF_REFCNT(bp) > 1) {
1342		/* do not release to free list */
1343		BUF_UNLOCK(bp);
1344		return;
1345	}
1346
1347	/* enqueue */
1348	mtx_lock(&bqlock);
1349	/* Handle delayed bremfree() processing. */
1350	if (bp->b_flags & B_REMFREE)
1351		bremfreel(bp);
1352	if (bp->b_qindex != QUEUE_NONE)
1353		panic("brelse: free buffer onto another queue???");
1354
1355	/* buffers with no memory */
1356	if (bp->b_bufsize == 0) {
1357		bp->b_flags |= B_INVAL;
1358		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1359		if (bp->b_vflags & BV_BKGRDINPROG)
1360			panic("losing buffer 1");
1361		if (bp->b_kvasize) {
1362			bp->b_qindex = QUEUE_EMPTYKVA;
1363		} else {
1364			bp->b_qindex = QUEUE_EMPTY;
1365		}
1366		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1367	/* buffers with junk contents */
1368	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1369	    (bp->b_ioflags & BIO_ERROR)) {
1370		bp->b_flags |= B_INVAL;
1371		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1372		if (bp->b_vflags & BV_BKGRDINPROG)
1373			panic("losing buffer 2");
1374		bp->b_qindex = QUEUE_CLEAN;
1375		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1376	/* remaining buffers */
1377	} else {
1378		if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1379		    (B_DELWRI|B_NEEDSGIANT))
1380			bp->b_qindex = QUEUE_DIRTY_GIANT;
1381		if (bp->b_flags & B_DELWRI)
1382			bp->b_qindex = QUEUE_DIRTY;
1383		else
1384			bp->b_qindex = QUEUE_CLEAN;
1385		if (bp->b_flags & B_AGE)
1386			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1387		else
1388			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1389	}
1390	mtx_unlock(&bqlock);
1391
1392	/*
1393	 * If B_INVAL and B_DELWRI is set, clear B_DELWRI.  We have already
1394	 * placed the buffer on the correct queue.  We must also disassociate
1395	 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1396	 * find it.
1397	 */
1398	if (bp->b_flags & B_INVAL) {
1399		if (bp->b_flags & B_DELWRI)
1400			bundirty(bp);
1401		if (bp->b_vp)
1402			brelvp(bp);
1403	}
1404
1405	/*
1406	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1407	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1408	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1409	 * if B_INVAL is set ).
1410	 */
1411
1412	if (!(bp->b_flags & B_DELWRI))
1413		bufcountwakeup();
1414
1415	/*
1416	 * Something we can maybe free or reuse
1417	 */
1418	if (bp->b_bufsize || bp->b_kvasize)
1419		bufspacewakeup();
1420
1421	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1422	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1423		panic("brelse: not dirty");
1424	/* unlock */
1425	BUF_UNLOCK(bp);
1426}
1427
1428/*
1429 * Release a buffer back to the appropriate queue but do not try to free
1430 * it.  The buffer is expected to be used again soon.
1431 *
1432 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1433 * biodone() to requeue an async I/O on completion.  It is also used when
1434 * known good buffers need to be requeued but we think we may need the data
1435 * again soon.
1436 *
1437 * XXX we should be able to leave the B_RELBUF hint set on completion.
1438 */
1439void
1440bqrelse(struct buf *bp)
1441{
1442	CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1443	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1444	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1445
1446	if (BUF_REFCNT(bp) > 1) {
1447		/* do not release to free list */
1448		BUF_UNLOCK(bp);
1449		return;
1450	}
1451
1452	if (bp->b_flags & B_MANAGED) {
1453		if (bp->b_flags & B_REMFREE) {
1454			mtx_lock(&bqlock);
1455			bremfreel(bp);
1456			mtx_unlock(&bqlock);
1457		}
1458		bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1459		BUF_UNLOCK(bp);
1460		return;
1461	}
1462
1463	mtx_lock(&bqlock);
1464	/* Handle delayed bremfree() processing. */
1465	if (bp->b_flags & B_REMFREE)
1466		bremfreel(bp);
1467	if (bp->b_qindex != QUEUE_NONE)
1468		panic("bqrelse: free buffer onto another queue???");
1469	/* buffers with stale but valid contents */
1470	if (bp->b_flags & B_DELWRI) {
1471		if (bp->b_flags & B_NEEDSGIANT)
1472			bp->b_qindex = QUEUE_DIRTY_GIANT;
1473		else
1474			bp->b_qindex = QUEUE_DIRTY;
1475		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1476	} else {
1477		/*
1478		 * XXX This lock may not be necessary since BKGRDINPROG
1479		 * cannot be set while we hold the buf lock, it can only be
1480		 * cleared if it is already pending.
1481		 */
1482		BO_LOCK(bp->b_bufobj);
1483		if (!vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) {
1484			BO_UNLOCK(bp->b_bufobj);
1485			bp->b_qindex = QUEUE_CLEAN;
1486			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1487			    b_freelist);
1488		} else {
1489			/*
1490			 * We are too low on memory, we have to try to free
1491			 * the buffer (most importantly: the wired pages
1492			 * making up its backing store) *now*.
1493			 */
1494			BO_UNLOCK(bp->b_bufobj);
1495			mtx_unlock(&bqlock);
1496			brelse(bp);
1497			return;
1498		}
1499	}
1500	mtx_unlock(&bqlock);
1501
1502	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1503		bufcountwakeup();
1504
1505	/*
1506	 * Something we can maybe free or reuse.
1507	 */
1508	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1509		bufspacewakeup();
1510
1511	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1512	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1513		panic("bqrelse: not dirty");
1514	/* unlock */
1515	BUF_UNLOCK(bp);
1516}
1517
1518/* Give pages used by the bp back to the VM system (where possible) */
1519static void
1520vfs_vmio_release(struct buf *bp)
1521{
1522	int i;
1523	vm_page_t m;
1524
1525	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1526	vm_page_lock_queues();
1527	for (i = 0; i < bp->b_npages; i++) {
1528		m = bp->b_pages[i];
1529		bp->b_pages[i] = NULL;
1530		/*
1531		 * In order to keep page LRU ordering consistent, put
1532		 * everything on the inactive queue.
1533		 */
1534		vm_page_unwire(m, 0);
1535		/*
1536		 * We don't mess with busy pages, it is
1537		 * the responsibility of the process that
1538		 * busied the pages to deal with them.
1539		 */
1540		if ((m->oflags & VPO_BUSY) || (m->busy != 0))
1541			continue;
1542
1543		if (m->wire_count == 0) {
1544			/*
1545			 * Might as well free the page if we can and it has
1546			 * no valid data.  We also free the page if the
1547			 * buffer was used for direct I/O
1548			 */
1549			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1550			    m->hold_count == 0) {
1551				vm_page_free(m);
1552			} else if (bp->b_flags & B_DIRECT) {
1553				vm_page_try_to_free(m);
1554			} else if (vm_page_count_severe()) {
1555				vm_page_try_to_cache(m);
1556			}
1557		}
1558	}
1559	vm_page_unlock_queues();
1560	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1561	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1562
1563	if (bp->b_bufsize) {
1564		bufspacewakeup();
1565		bp->b_bufsize = 0;
1566	}
1567	bp->b_npages = 0;
1568	bp->b_flags &= ~B_VMIO;
1569	if (bp->b_vp)
1570		brelvp(bp);
1571}
1572
1573/*
1574 * Check to see if a block at a particular lbn is available for a clustered
1575 * write.
1576 */
1577static int
1578vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1579{
1580	struct buf *bpa;
1581	int match;
1582
1583	match = 0;
1584
1585	/* If the buf isn't in core skip it */
1586	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1587		return (0);
1588
1589	/* If the buf is busy we don't want to wait for it */
1590	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1591		return (0);
1592
1593	/* Only cluster with valid clusterable delayed write buffers */
1594	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1595	    (B_DELWRI | B_CLUSTEROK))
1596		goto done;
1597
1598	if (bpa->b_bufsize != size)
1599		goto done;
1600
1601	/*
1602	 * Check to see if it is in the expected place on disk and that the
1603	 * block has been mapped.
1604	 */
1605	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1606		match = 1;
1607done:
1608	BUF_UNLOCK(bpa);
1609	return (match);
1610}
1611
1612/*
1613 *	vfs_bio_awrite:
1614 *
1615 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1616 *	This is much better then the old way of writing only one buffer at
1617 *	a time.  Note that we may not be presented with the buffers in the
1618 *	correct order, so we search for the cluster in both directions.
1619 */
1620int
1621vfs_bio_awrite(struct buf *bp)
1622{
1623	int i;
1624	int j;
1625	daddr_t lblkno = bp->b_lblkno;
1626	struct vnode *vp = bp->b_vp;
1627	int ncl;
1628	int nwritten;
1629	int size;
1630	int maxcl;
1631
1632	/*
1633	 * right now we support clustered writing only to regular files.  If
1634	 * we find a clusterable block we could be in the middle of a cluster
1635	 * rather then at the beginning.
1636	 */
1637	if ((vp->v_type == VREG) &&
1638	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1639	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1640
1641		size = vp->v_mount->mnt_stat.f_iosize;
1642		maxcl = MAXPHYS / size;
1643
1644		VI_LOCK(vp);
1645		for (i = 1; i < maxcl; i++)
1646			if (vfs_bio_clcheck(vp, size, lblkno + i,
1647			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1648				break;
1649
1650		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1651			if (vfs_bio_clcheck(vp, size, lblkno - j,
1652			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1653				break;
1654
1655		VI_UNLOCK(vp);
1656		--j;
1657		ncl = i + j;
1658		/*
1659		 * this is a possible cluster write
1660		 */
1661		if (ncl != 1) {
1662			BUF_UNLOCK(bp);
1663			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1664			return nwritten;
1665		}
1666	}
1667	bremfree(bp);
1668	bp->b_flags |= B_ASYNC;
1669	/*
1670	 * default (old) behavior, writing out only one block
1671	 *
1672	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1673	 */
1674	nwritten = bp->b_bufsize;
1675	(void) bwrite(bp);
1676
1677	return nwritten;
1678}
1679
1680/*
1681 *	getnewbuf:
1682 *
1683 *	Find and initialize a new buffer header, freeing up existing buffers
1684 *	in the bufqueues as necessary.  The new buffer is returned locked.
1685 *
1686 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1687 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1688 *
1689 *	We block if:
1690 *		We have insufficient buffer headers
1691 *		We have insufficient buffer space
1692 *		buffer_map is too fragmented ( space reservation fails )
1693 *		If we have to flush dirty buffers ( but we try to avoid this )
1694 *
1695 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1696 *	Instead we ask the buf daemon to do it for us.  We attempt to
1697 *	avoid piecemeal wakeups of the pageout daemon.
1698 */
1699
1700static struct buf *
1701getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1702{
1703	struct buf *bp;
1704	struct buf *nbp;
1705	int defrag = 0;
1706	int nqindex;
1707	static int flushingbufs;
1708
1709	/*
1710	 * We can't afford to block since we might be holding a vnode lock,
1711	 * which may prevent system daemons from running.  We deal with
1712	 * low-memory situations by proactively returning memory and running
1713	 * async I/O rather then sync I/O.
1714	 */
1715
1716	atomic_add_int(&getnewbufcalls, 1);
1717	atomic_subtract_int(&getnewbufrestarts, 1);
1718restart:
1719	atomic_add_int(&getnewbufrestarts, 1);
1720
1721	/*
1722	 * Setup for scan.  If we do not have enough free buffers,
1723	 * we setup a degenerate case that immediately fails.  Note
1724	 * that if we are specially marked process, we are allowed to
1725	 * dip into our reserves.
1726	 *
1727	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1728	 *
1729	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1730	 * However, there are a number of cases (defragging, reusing, ...)
1731	 * where we cannot backup.
1732	 */
1733	mtx_lock(&bqlock);
1734	nqindex = QUEUE_EMPTYKVA;
1735	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1736
1737	if (nbp == NULL) {
1738		/*
1739		 * If no EMPTYKVA buffers and we are either
1740		 * defragging or reusing, locate a CLEAN buffer
1741		 * to free or reuse.  If bufspace useage is low
1742		 * skip this step so we can allocate a new buffer.
1743		 */
1744		if (defrag || bufspace >= lobufspace) {
1745			nqindex = QUEUE_CLEAN;
1746			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1747		}
1748
1749		/*
1750		 * If we could not find or were not allowed to reuse a
1751		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1752		 * buffer.  We can only use an EMPTY buffer if allocating
1753		 * its KVA would not otherwise run us out of buffer space.
1754		 */
1755		if (nbp == NULL && defrag == 0 &&
1756		    bufspace + maxsize < hibufspace) {
1757			nqindex = QUEUE_EMPTY;
1758			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1759		}
1760	}
1761
1762	/*
1763	 * Run scan, possibly freeing data and/or kva mappings on the fly
1764	 * depending.
1765	 */
1766
1767	while ((bp = nbp) != NULL) {
1768		int qindex = nqindex;
1769
1770		/*
1771		 * Calculate next bp ( we can only use it if we do not block
1772		 * or do other fancy things ).
1773		 */
1774		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1775			switch(qindex) {
1776			case QUEUE_EMPTY:
1777				nqindex = QUEUE_EMPTYKVA;
1778				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1779					break;
1780				/* FALLTHROUGH */
1781			case QUEUE_EMPTYKVA:
1782				nqindex = QUEUE_CLEAN;
1783				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1784					break;
1785				/* FALLTHROUGH */
1786			case QUEUE_CLEAN:
1787				/*
1788				 * nbp is NULL.
1789				 */
1790				break;
1791			}
1792		}
1793		/*
1794		 * If we are defragging then we need a buffer with
1795		 * b_kvasize != 0.  XXX this situation should no longer
1796		 * occur, if defrag is non-zero the buffer's b_kvasize
1797		 * should also be non-zero at this point.  XXX
1798		 */
1799		if (defrag && bp->b_kvasize == 0) {
1800			printf("Warning: defrag empty buffer %p\n", bp);
1801			continue;
1802		}
1803
1804		/*
1805		 * Start freeing the bp.  This is somewhat involved.  nbp
1806		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1807		 */
1808		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1809			continue;
1810		if (bp->b_vp) {
1811			BO_LOCK(bp->b_bufobj);
1812			if (bp->b_vflags & BV_BKGRDINPROG) {
1813				BO_UNLOCK(bp->b_bufobj);
1814				BUF_UNLOCK(bp);
1815				continue;
1816			}
1817			BO_UNLOCK(bp->b_bufobj);
1818		}
1819		CTR6(KTR_BUF,
1820		    "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1821		    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1822		    bp->b_kvasize, bp->b_bufsize, qindex);
1823
1824		/*
1825		 * Sanity Checks
1826		 */
1827		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1828
1829		/*
1830		 * Note: we no longer distinguish between VMIO and non-VMIO
1831		 * buffers.
1832		 */
1833
1834		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1835
1836		bremfreel(bp);
1837		mtx_unlock(&bqlock);
1838
1839		if (qindex == QUEUE_CLEAN) {
1840			if (bp->b_flags & B_VMIO) {
1841				bp->b_flags &= ~B_ASYNC;
1842				vfs_vmio_release(bp);
1843			}
1844			if (bp->b_vp)
1845				brelvp(bp);
1846		}
1847
1848		/*
1849		 * NOTE:  nbp is now entirely invalid.  We can only restart
1850		 * the scan from this point on.
1851		 *
1852		 * Get the rest of the buffer freed up.  b_kva* is still
1853		 * valid after this operation.
1854		 */
1855
1856		if (bp->b_rcred != NOCRED) {
1857			crfree(bp->b_rcred);
1858			bp->b_rcred = NOCRED;
1859		}
1860		if (bp->b_wcred != NOCRED) {
1861			crfree(bp->b_wcred);
1862			bp->b_wcred = NOCRED;
1863		}
1864		if (LIST_FIRST(&bp->b_dep) != NULL)
1865			buf_deallocate(bp);
1866		if (bp->b_vflags & BV_BKGRDINPROG)
1867			panic("losing buffer 3");
1868		KASSERT(bp->b_vp == NULL,
1869		    ("bp: %p still has vnode %p.  qindex: %d",
1870		    bp, bp->b_vp, qindex));
1871		KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1872		   ("bp: %p still on a buffer list. xflags %X",
1873		    bp, bp->b_xflags));
1874
1875		if (bp->b_bufsize)
1876			allocbuf(bp, 0);
1877
1878		bp->b_flags = 0;
1879		bp->b_ioflags = 0;
1880		bp->b_xflags = 0;
1881		bp->b_vflags = 0;
1882		bp->b_vp = NULL;
1883		bp->b_blkno = bp->b_lblkno = 0;
1884		bp->b_offset = NOOFFSET;
1885		bp->b_iodone = 0;
1886		bp->b_error = 0;
1887		bp->b_resid = 0;
1888		bp->b_bcount = 0;
1889		bp->b_npages = 0;
1890		bp->b_dirtyoff = bp->b_dirtyend = 0;
1891		bp->b_bufobj = NULL;
1892		bp->b_pin_count = 0;
1893		bp->b_fsprivate1 = NULL;
1894		bp->b_fsprivate2 = NULL;
1895		bp->b_fsprivate3 = NULL;
1896
1897		LIST_INIT(&bp->b_dep);
1898
1899		/*
1900		 * If we are defragging then free the buffer.
1901		 */
1902		if (defrag) {
1903			bp->b_flags |= B_INVAL;
1904			bfreekva(bp);
1905			brelse(bp);
1906			defrag = 0;
1907			goto restart;
1908		}
1909
1910		/*
1911		 * Notify any waiters for the buffer lock about
1912		 * identity change by freeing the buffer.
1913		 */
1914		if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp) > 0) {
1915			bp->b_flags |= B_INVAL;
1916			bfreekva(bp);
1917			brelse(bp);
1918			goto restart;
1919		}
1920
1921		/*
1922		 * If we are overcomitted then recover the buffer and its
1923		 * KVM space.  This occurs in rare situations when multiple
1924		 * processes are blocked in getnewbuf() or allocbuf().
1925		 */
1926		if (bufspace >= hibufspace)
1927			flushingbufs = 1;
1928		if (flushingbufs && bp->b_kvasize != 0) {
1929			bp->b_flags |= B_INVAL;
1930			bfreekva(bp);
1931			brelse(bp);
1932			goto restart;
1933		}
1934		if (bufspace < lobufspace)
1935			flushingbufs = 0;
1936		break;
1937	}
1938
1939	/*
1940	 * If we exhausted our list, sleep as appropriate.  We may have to
1941	 * wakeup various daemons and write out some dirty buffers.
1942	 *
1943	 * Generally we are sleeping due to insufficient buffer space.
1944	 */
1945
1946	if (bp == NULL) {
1947		int flags;
1948		char *waitmsg;
1949
1950		if (defrag) {
1951			flags = VFS_BIO_NEED_BUFSPACE;
1952			waitmsg = "nbufkv";
1953		} else if (bufspace >= hibufspace) {
1954			waitmsg = "nbufbs";
1955			flags = VFS_BIO_NEED_BUFSPACE;
1956		} else {
1957			waitmsg = "newbuf";
1958			flags = VFS_BIO_NEED_ANY;
1959		}
1960		mtx_lock(&nblock);
1961		needsbuffer |= flags;
1962		mtx_unlock(&nblock);
1963		mtx_unlock(&bqlock);
1964
1965		bd_speedup();	/* heeeelp */
1966
1967		mtx_lock(&nblock);
1968		while (needsbuffer & flags) {
1969			if (msleep(&needsbuffer, &nblock,
1970			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
1971				mtx_unlock(&nblock);
1972				return (NULL);
1973			}
1974		}
1975		mtx_unlock(&nblock);
1976	} else {
1977		/*
1978		 * We finally have a valid bp.  We aren't quite out of the
1979		 * woods, we still have to reserve kva space.  In order
1980		 * to keep fragmentation sane we only allocate kva in
1981		 * BKVASIZE chunks.
1982		 */
1983		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1984
1985		if (maxsize != bp->b_kvasize) {
1986			vm_offset_t addr = 0;
1987
1988			bfreekva(bp);
1989
1990			vm_map_lock(buffer_map);
1991			if (vm_map_findspace(buffer_map,
1992				vm_map_min(buffer_map), maxsize, &addr)) {
1993				/*
1994				 * Uh oh.  Buffer map is to fragmented.  We
1995				 * must defragment the map.
1996				 */
1997				atomic_add_int(&bufdefragcnt, 1);
1998				vm_map_unlock(buffer_map);
1999				defrag = 1;
2000				bp->b_flags |= B_INVAL;
2001				brelse(bp);
2002				goto restart;
2003			}
2004			if (addr) {
2005				vm_map_insert(buffer_map, NULL, 0,
2006					addr, addr + maxsize,
2007					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2008
2009				bp->b_kvabase = (caddr_t) addr;
2010				bp->b_kvasize = maxsize;
2011				atomic_add_int(&bufspace, bp->b_kvasize);
2012				atomic_add_int(&bufreusecnt, 1);
2013			}
2014			vm_map_unlock(buffer_map);
2015		}
2016		bp->b_saveaddr = bp->b_kvabase;
2017		bp->b_data = bp->b_saveaddr;
2018	}
2019	return(bp);
2020}
2021
2022/*
2023 *	buf_daemon:
2024 *
2025 *	buffer flushing daemon.  Buffers are normally flushed by the
2026 *	update daemon but if it cannot keep up this process starts to
2027 *	take the load in an attempt to prevent getnewbuf() from blocking.
2028 */
2029
2030static struct kproc_desc buf_kp = {
2031	"bufdaemon",
2032	buf_daemon,
2033	&bufdaemonproc
2034};
2035SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2036
2037static void
2038buf_daemon()
2039{
2040
2041	/*
2042	 * This process needs to be suspended prior to shutdown sync.
2043	 */
2044	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2045	    SHUTDOWN_PRI_LAST);
2046
2047	/*
2048	 * This process is allowed to take the buffer cache to the limit
2049	 */
2050	curthread->td_pflags |= TDP_NORUNNINGBUF;
2051	mtx_lock(&bdlock);
2052	for (;;) {
2053		bd_request = 0;
2054		mtx_unlock(&bdlock);
2055
2056		kthread_suspend_check(bufdaemonproc);
2057
2058		/*
2059		 * Do the flush.  Limit the amount of in-transit I/O we
2060		 * allow to build up, otherwise we would completely saturate
2061		 * the I/O system.  Wakeup any waiting processes before we
2062		 * normally would so they can run in parallel with our drain.
2063		 */
2064		while (numdirtybuffers > lodirtybuffers) {
2065			int flushed;
2066
2067			flushed = flushbufqueues(QUEUE_DIRTY, 0);
2068			/* The list empty check here is slightly racy */
2069			if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2070				mtx_lock(&Giant);
2071				flushed += flushbufqueues(QUEUE_DIRTY_GIANT, 0);
2072				mtx_unlock(&Giant);
2073			}
2074			if (flushed == 0) {
2075				/*
2076				 * Could not find any buffers without rollback
2077				 * dependencies, so just write the first one
2078				 * in the hopes of eventually making progress.
2079				 */
2080				flushbufqueues(QUEUE_DIRTY, 1);
2081				if (!TAILQ_EMPTY(
2082				    &bufqueues[QUEUE_DIRTY_GIANT])) {
2083					mtx_lock(&Giant);
2084					flushbufqueues(QUEUE_DIRTY_GIANT, 1);
2085					mtx_unlock(&Giant);
2086				}
2087				break;
2088			}
2089			uio_yield();
2090		}
2091
2092		/*
2093		 * Only clear bd_request if we have reached our low water
2094		 * mark.  The buf_daemon normally waits 1 second and
2095		 * then incrementally flushes any dirty buffers that have
2096		 * built up, within reason.
2097		 *
2098		 * If we were unable to hit our low water mark and couldn't
2099		 * find any flushable buffers, we sleep half a second.
2100		 * Otherwise we loop immediately.
2101		 */
2102		mtx_lock(&bdlock);
2103		if (numdirtybuffers <= lodirtybuffers) {
2104			/*
2105			 * We reached our low water mark, reset the
2106			 * request and sleep until we are needed again.
2107			 * The sleep is just so the suspend code works.
2108			 */
2109			bd_request = 0;
2110			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2111		} else {
2112			/*
2113			 * We couldn't find any flushable dirty buffers but
2114			 * still have too many dirty buffers, we
2115			 * have to sleep and try again.  (rare)
2116			 */
2117			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2118		}
2119	}
2120}
2121
2122/*
2123 *	flushbufqueues:
2124 *
2125 *	Try to flush a buffer in the dirty queue.  We must be careful to
2126 *	free up B_INVAL buffers instead of write them, which NFS is
2127 *	particularly sensitive to.
2128 */
2129static int flushwithdeps = 0;
2130SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2131    0, "Number of buffers flushed with dependecies that require rollbacks");
2132
2133static int
2134flushbufqueues(int queue, int flushdeps)
2135{
2136	struct thread *td = curthread;
2137	struct buf sentinel;
2138	struct vnode *vp;
2139	struct mount *mp;
2140	struct buf *bp;
2141	int hasdeps;
2142	int flushed;
2143	int target;
2144
2145	target = numdirtybuffers - lodirtybuffers;
2146	if (flushdeps && target > 2)
2147		target /= 2;
2148	flushed = 0;
2149	bp = NULL;
2150	mtx_lock(&bqlock);
2151	TAILQ_INSERT_TAIL(&bufqueues[queue], &sentinel, b_freelist);
2152	while (flushed != target) {
2153		bp = TAILQ_FIRST(&bufqueues[queue]);
2154		if (bp == &sentinel)
2155			break;
2156		TAILQ_REMOVE(&bufqueues[queue], bp, b_freelist);
2157		TAILQ_INSERT_TAIL(&bufqueues[queue], bp, b_freelist);
2158
2159		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2160			continue;
2161		if (bp->b_pin_count > 0) {
2162			BUF_UNLOCK(bp);
2163			continue;
2164		}
2165		BO_LOCK(bp->b_bufobj);
2166		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2167		    (bp->b_flags & B_DELWRI) == 0) {
2168			BO_UNLOCK(bp->b_bufobj);
2169			BUF_UNLOCK(bp);
2170			continue;
2171		}
2172		BO_UNLOCK(bp->b_bufobj);
2173		if (bp->b_flags & B_INVAL) {
2174			bremfreel(bp);
2175			mtx_unlock(&bqlock);
2176			brelse(bp);
2177			flushed++;
2178			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2179			mtx_lock(&bqlock);
2180			continue;
2181		}
2182
2183		if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2184			if (flushdeps == 0) {
2185				BUF_UNLOCK(bp);
2186				continue;
2187			}
2188			hasdeps = 1;
2189		} else
2190			hasdeps = 0;
2191		/*
2192		 * We must hold the lock on a vnode before writing
2193		 * one of its buffers. Otherwise we may confuse, or
2194		 * in the case of a snapshot vnode, deadlock the
2195		 * system.
2196		 *
2197		 * The lock order here is the reverse of the normal
2198		 * of vnode followed by buf lock.  This is ok because
2199		 * the NOWAIT will prevent deadlock.
2200		 */
2201		vp = bp->b_vp;
2202		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2203			BUF_UNLOCK(bp);
2204			continue;
2205		}
2206		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2207			mtx_unlock(&bqlock);
2208			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2209			    bp, bp->b_vp, bp->b_flags);
2210			vfs_bio_awrite(bp);
2211			vn_finished_write(mp);
2212			VOP_UNLOCK(vp, 0, td);
2213			flushwithdeps += hasdeps;
2214			flushed++;
2215			waitrunningbufspace();
2216			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2217			mtx_lock(&bqlock);
2218			continue;
2219		}
2220		vn_finished_write(mp);
2221		BUF_UNLOCK(bp);
2222	}
2223	TAILQ_REMOVE(&bufqueues[queue], &sentinel, b_freelist);
2224	mtx_unlock(&bqlock);
2225	return (flushed);
2226}
2227
2228/*
2229 * Check to see if a block is currently memory resident.
2230 */
2231struct buf *
2232incore(struct bufobj *bo, daddr_t blkno)
2233{
2234	struct buf *bp;
2235
2236	BO_LOCK(bo);
2237	bp = gbincore(bo, blkno);
2238	BO_UNLOCK(bo);
2239	return (bp);
2240}
2241
2242/*
2243 * Returns true if no I/O is needed to access the
2244 * associated VM object.  This is like incore except
2245 * it also hunts around in the VM system for the data.
2246 */
2247
2248static int
2249inmem(struct vnode * vp, daddr_t blkno)
2250{
2251	vm_object_t obj;
2252	vm_offset_t toff, tinc, size;
2253	vm_page_t m;
2254	vm_ooffset_t off;
2255
2256	ASSERT_VOP_LOCKED(vp, "inmem");
2257
2258	if (incore(&vp->v_bufobj, blkno))
2259		return 1;
2260	if (vp->v_mount == NULL)
2261		return 0;
2262	obj = vp->v_object;
2263	if (obj == NULL)
2264		return (0);
2265
2266	size = PAGE_SIZE;
2267	if (size > vp->v_mount->mnt_stat.f_iosize)
2268		size = vp->v_mount->mnt_stat.f_iosize;
2269	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2270
2271	VM_OBJECT_LOCK(obj);
2272	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2273		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2274		if (!m)
2275			goto notinmem;
2276		tinc = size;
2277		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2278			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2279		if (vm_page_is_valid(m,
2280		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2281			goto notinmem;
2282	}
2283	VM_OBJECT_UNLOCK(obj);
2284	return 1;
2285
2286notinmem:
2287	VM_OBJECT_UNLOCK(obj);
2288	return (0);
2289}
2290
2291/*
2292 *	vfs_setdirty:
2293 *
2294 *	Sets the dirty range for a buffer based on the status of the dirty
2295 *	bits in the pages comprising the buffer.
2296 *
2297 *	The range is limited to the size of the buffer.
2298 *
2299 *	This routine is primarily used by NFS, but is generalized for the
2300 *	B_VMIO case.
2301 */
2302static void
2303vfs_setdirty(struct buf *bp)
2304{
2305
2306	/*
2307	 * Degenerate case - empty buffer
2308	 */
2309
2310	if (bp->b_bufsize == 0)
2311		return;
2312
2313	/*
2314	 * We qualify the scan for modified pages on whether the
2315	 * object has been flushed yet.
2316	 */
2317
2318	if ((bp->b_flags & B_VMIO) == 0)
2319		return;
2320
2321	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2322	vfs_setdirty_locked_object(bp);
2323	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2324}
2325
2326static void
2327vfs_setdirty_locked_object(struct buf *bp)
2328{
2329	vm_object_t object;
2330	int i;
2331
2332	object = bp->b_bufobj->bo_object;
2333	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2334	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2335		vm_offset_t boffset;
2336		vm_offset_t eoffset;
2337
2338		vm_page_lock_queues();
2339		/*
2340		 * test the pages to see if they have been modified directly
2341		 * by users through the VM system.
2342		 */
2343		for (i = 0; i < bp->b_npages; i++)
2344			vm_page_test_dirty(bp->b_pages[i]);
2345
2346		/*
2347		 * Calculate the encompassing dirty range, boffset and eoffset,
2348		 * (eoffset - boffset) bytes.
2349		 */
2350
2351		for (i = 0; i < bp->b_npages; i++) {
2352			if (bp->b_pages[i]->dirty)
2353				break;
2354		}
2355		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2356
2357		for (i = bp->b_npages - 1; i >= 0; --i) {
2358			if (bp->b_pages[i]->dirty) {
2359				break;
2360			}
2361		}
2362		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2363
2364		vm_page_unlock_queues();
2365		/*
2366		 * Fit it to the buffer.
2367		 */
2368
2369		if (eoffset > bp->b_bcount)
2370			eoffset = bp->b_bcount;
2371
2372		/*
2373		 * If we have a good dirty range, merge with the existing
2374		 * dirty range.
2375		 */
2376
2377		if (boffset < eoffset) {
2378			if (bp->b_dirtyoff > boffset)
2379				bp->b_dirtyoff = boffset;
2380			if (bp->b_dirtyend < eoffset)
2381				bp->b_dirtyend = eoffset;
2382		}
2383	}
2384}
2385
2386/*
2387 *	getblk:
2388 *
2389 *	Get a block given a specified block and offset into a file/device.
2390 *	The buffers B_DONE bit will be cleared on return, making it almost
2391 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2392 *	return.  The caller should clear B_INVAL prior to initiating a
2393 *	READ.
2394 *
2395 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2396 *	an existing buffer.
2397 *
2398 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2399 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2400 *	and then cleared based on the backing VM.  If the previous buffer is
2401 *	non-0-sized but invalid, B_CACHE will be cleared.
2402 *
2403 *	If getblk() must create a new buffer, the new buffer is returned with
2404 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2405 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2406 *	backing VM.
2407 *
2408 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2409 *	B_CACHE bit is clear.
2410 *
2411 *	What this means, basically, is that the caller should use B_CACHE to
2412 *	determine whether the buffer is fully valid or not and should clear
2413 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2414 *	the buffer by loading its data area with something, the caller needs
2415 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2416 *	the caller should set B_CACHE ( as an optimization ), else the caller
2417 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2418 *	a write attempt or if it was a successfull read.  If the caller
2419 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2420 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2421 */
2422struct buf *
2423getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2424    int flags)
2425{
2426	struct buf *bp;
2427	struct bufobj *bo;
2428	int error;
2429
2430	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2431	ASSERT_VOP_LOCKED(vp, "getblk");
2432	if (size > MAXBSIZE)
2433		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2434
2435	bo = &vp->v_bufobj;
2436loop:
2437	/*
2438	 * Block if we are low on buffers.   Certain processes are allowed
2439	 * to completely exhaust the buffer cache.
2440         *
2441         * If this check ever becomes a bottleneck it may be better to
2442         * move it into the else, when gbincore() fails.  At the moment
2443         * it isn't a problem.
2444	 *
2445	 * XXX remove if 0 sections (clean this up after its proven)
2446         */
2447	if (numfreebuffers == 0) {
2448		if (curthread == PCPU_GET(idlethread))
2449			return NULL;
2450		mtx_lock(&nblock);
2451		needsbuffer |= VFS_BIO_NEED_ANY;
2452		mtx_unlock(&nblock);
2453	}
2454
2455	VI_LOCK(vp);
2456	bp = gbincore(bo, blkno);
2457	if (bp != NULL) {
2458		int lockflags;
2459		/*
2460		 * Buffer is in-core.  If the buffer is not busy, it must
2461		 * be on a queue.
2462		 */
2463		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2464
2465		if (flags & GB_LOCK_NOWAIT)
2466			lockflags |= LK_NOWAIT;
2467
2468		error = BUF_TIMELOCK(bp, lockflags,
2469		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2470
2471		/*
2472		 * If we slept and got the lock we have to restart in case
2473		 * the buffer changed identities.
2474		 */
2475		if (error == ENOLCK)
2476			goto loop;
2477		/* We timed out or were interrupted. */
2478		else if (error)
2479			return (NULL);
2480
2481		/*
2482		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2483		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2484		 * and for a VMIO buffer B_CACHE is adjusted according to the
2485		 * backing VM cache.
2486		 */
2487		if (bp->b_flags & B_INVAL)
2488			bp->b_flags &= ~B_CACHE;
2489		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2490			bp->b_flags |= B_CACHE;
2491		bremfree(bp);
2492
2493		/*
2494		 * check for size inconsistancies for non-VMIO case.
2495		 */
2496
2497		if (bp->b_bcount != size) {
2498			if ((bp->b_flags & B_VMIO) == 0 ||
2499			    (size > bp->b_kvasize)) {
2500				if (bp->b_flags & B_DELWRI) {
2501					/*
2502					 * If buffer is pinned and caller does
2503					 * not want sleep  waiting for it to be
2504					 * unpinned, bail out
2505					 * */
2506					if (bp->b_pin_count > 0) {
2507						if (flags & GB_LOCK_NOWAIT) {
2508							bqrelse(bp);
2509							return (NULL);
2510						} else {
2511							bunpin_wait(bp);
2512						}
2513					}
2514					bp->b_flags |= B_NOCACHE;
2515					bwrite(bp);
2516				} else {
2517					if (LIST_FIRST(&bp->b_dep) == NULL) {
2518						bp->b_flags |= B_RELBUF;
2519						brelse(bp);
2520					} else {
2521						bp->b_flags |= B_NOCACHE;
2522						bwrite(bp);
2523					}
2524				}
2525				goto loop;
2526			}
2527		}
2528
2529		/*
2530		 * If the size is inconsistant in the VMIO case, we can resize
2531		 * the buffer.  This might lead to B_CACHE getting set or
2532		 * cleared.  If the size has not changed, B_CACHE remains
2533		 * unchanged from its previous state.
2534		 */
2535
2536		if (bp->b_bcount != size)
2537			allocbuf(bp, size);
2538
2539		KASSERT(bp->b_offset != NOOFFSET,
2540		    ("getblk: no buffer offset"));
2541
2542		/*
2543		 * A buffer with B_DELWRI set and B_CACHE clear must
2544		 * be committed before we can return the buffer in
2545		 * order to prevent the caller from issuing a read
2546		 * ( due to B_CACHE not being set ) and overwriting
2547		 * it.
2548		 *
2549		 * Most callers, including NFS and FFS, need this to
2550		 * operate properly either because they assume they
2551		 * can issue a read if B_CACHE is not set, or because
2552		 * ( for example ) an uncached B_DELWRI might loop due
2553		 * to softupdates re-dirtying the buffer.  In the latter
2554		 * case, B_CACHE is set after the first write completes,
2555		 * preventing further loops.
2556		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2557		 * above while extending the buffer, we cannot allow the
2558		 * buffer to remain with B_CACHE set after the write
2559		 * completes or it will represent a corrupt state.  To
2560		 * deal with this we set B_NOCACHE to scrap the buffer
2561		 * after the write.
2562		 *
2563		 * We might be able to do something fancy, like setting
2564		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2565		 * so the below call doesn't set B_CACHE, but that gets real
2566		 * confusing.  This is much easier.
2567		 */
2568
2569		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2570			bp->b_flags |= B_NOCACHE;
2571			bwrite(bp);
2572			goto loop;
2573		}
2574		bp->b_flags &= ~B_DONE;
2575	} else {
2576		int bsize, maxsize, vmio;
2577		off_t offset;
2578
2579		/*
2580		 * Buffer is not in-core, create new buffer.  The buffer
2581		 * returned by getnewbuf() is locked.  Note that the returned
2582		 * buffer is also considered valid (not marked B_INVAL).
2583		 */
2584		VI_UNLOCK(vp);
2585		/*
2586		 * If the user does not want us to create the buffer, bail out
2587		 * here.
2588		 */
2589		if (flags & GB_NOCREAT)
2590			return NULL;
2591		bsize = bo->bo_bsize;
2592		offset = blkno * bsize;
2593		vmio = vp->v_object != NULL;
2594		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2595		maxsize = imax(maxsize, bsize);
2596
2597		bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2598		if (bp == NULL) {
2599			if (slpflag || slptimeo)
2600				return NULL;
2601			goto loop;
2602		}
2603
2604		/*
2605		 * This code is used to make sure that a buffer is not
2606		 * created while the getnewbuf routine is blocked.
2607		 * This can be a problem whether the vnode is locked or not.
2608		 * If the buffer is created out from under us, we have to
2609		 * throw away the one we just created.
2610		 *
2611		 * Note: this must occur before we associate the buffer
2612		 * with the vp especially considering limitations in
2613		 * the splay tree implementation when dealing with duplicate
2614		 * lblkno's.
2615		 */
2616		BO_LOCK(bo);
2617		if (gbincore(bo, blkno)) {
2618			BO_UNLOCK(bo);
2619			bp->b_flags |= B_INVAL;
2620			brelse(bp);
2621			goto loop;
2622		}
2623
2624		/*
2625		 * Insert the buffer into the hash, so that it can
2626		 * be found by incore.
2627		 */
2628		bp->b_blkno = bp->b_lblkno = blkno;
2629		bp->b_offset = offset;
2630		bgetvp(vp, bp);
2631		BO_UNLOCK(bo);
2632
2633		/*
2634		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2635		 * buffer size starts out as 0, B_CACHE will be set by
2636		 * allocbuf() for the VMIO case prior to it testing the
2637		 * backing store for validity.
2638		 */
2639
2640		if (vmio) {
2641			bp->b_flags |= B_VMIO;
2642#if defined(VFS_BIO_DEBUG)
2643			if (vn_canvmio(vp) != TRUE)
2644				printf("getblk: VMIO on vnode type %d\n",
2645					vp->v_type);
2646#endif
2647			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2648			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2649			    bp, vp->v_object, bp->b_bufobj->bo_object));
2650		} else {
2651			bp->b_flags &= ~B_VMIO;
2652			KASSERT(bp->b_bufobj->bo_object == NULL,
2653			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2654			    bp, bp->b_bufobj->bo_object));
2655		}
2656
2657		allocbuf(bp, size);
2658		bp->b_flags &= ~B_DONE;
2659	}
2660	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2661	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2662	KASSERT(bp->b_bufobj == bo,
2663	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2664	return (bp);
2665}
2666
2667/*
2668 * Get an empty, disassociated buffer of given size.  The buffer is initially
2669 * set to B_INVAL.
2670 */
2671struct buf *
2672geteblk(int size)
2673{
2674	struct buf *bp;
2675	int maxsize;
2676
2677	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2678	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2679		continue;
2680	allocbuf(bp, size);
2681	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2682	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2683	return (bp);
2684}
2685
2686
2687/*
2688 * This code constitutes the buffer memory from either anonymous system
2689 * memory (in the case of non-VMIO operations) or from an associated
2690 * VM object (in the case of VMIO operations).  This code is able to
2691 * resize a buffer up or down.
2692 *
2693 * Note that this code is tricky, and has many complications to resolve
2694 * deadlock or inconsistant data situations.  Tread lightly!!!
2695 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2696 * the caller.  Calling this code willy nilly can result in the loss of data.
2697 *
2698 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2699 * B_CACHE for the non-VMIO case.
2700 */
2701
2702int
2703allocbuf(struct buf *bp, int size)
2704{
2705	int newbsize, mbsize;
2706	int i;
2707
2708	if (BUF_REFCNT(bp) == 0)
2709		panic("allocbuf: buffer not busy");
2710
2711	if (bp->b_kvasize < size)
2712		panic("allocbuf: buffer too small");
2713
2714	if ((bp->b_flags & B_VMIO) == 0) {
2715		caddr_t origbuf;
2716		int origbufsize;
2717		/*
2718		 * Just get anonymous memory from the kernel.  Don't
2719		 * mess with B_CACHE.
2720		 */
2721		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2722		if (bp->b_flags & B_MALLOC)
2723			newbsize = mbsize;
2724		else
2725			newbsize = round_page(size);
2726
2727		if (newbsize < bp->b_bufsize) {
2728			/*
2729			 * malloced buffers are not shrunk
2730			 */
2731			if (bp->b_flags & B_MALLOC) {
2732				if (newbsize) {
2733					bp->b_bcount = size;
2734				} else {
2735					free(bp->b_data, M_BIOBUF);
2736					if (bp->b_bufsize) {
2737						atomic_subtract_int(
2738						    &bufmallocspace,
2739						    bp->b_bufsize);
2740						bufspacewakeup();
2741						bp->b_bufsize = 0;
2742					}
2743					bp->b_saveaddr = bp->b_kvabase;
2744					bp->b_data = bp->b_saveaddr;
2745					bp->b_bcount = 0;
2746					bp->b_flags &= ~B_MALLOC;
2747				}
2748				return 1;
2749			}
2750			vm_hold_free_pages(
2751			    bp,
2752			    (vm_offset_t) bp->b_data + newbsize,
2753			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2754		} else if (newbsize > bp->b_bufsize) {
2755			/*
2756			 * We only use malloced memory on the first allocation.
2757			 * and revert to page-allocated memory when the buffer
2758			 * grows.
2759			 */
2760			/*
2761			 * There is a potential smp race here that could lead
2762			 * to bufmallocspace slightly passing the max.  It
2763			 * is probably extremely rare and not worth worrying
2764			 * over.
2765			 */
2766			if ( (bufmallocspace < maxbufmallocspace) &&
2767				(bp->b_bufsize == 0) &&
2768				(mbsize <= PAGE_SIZE/2)) {
2769
2770				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2771				bp->b_bufsize = mbsize;
2772				bp->b_bcount = size;
2773				bp->b_flags |= B_MALLOC;
2774				atomic_add_int(&bufmallocspace, mbsize);
2775				return 1;
2776			}
2777			origbuf = NULL;
2778			origbufsize = 0;
2779			/*
2780			 * If the buffer is growing on its other-than-first allocation,
2781			 * then we revert to the page-allocation scheme.
2782			 */
2783			if (bp->b_flags & B_MALLOC) {
2784				origbuf = bp->b_data;
2785				origbufsize = bp->b_bufsize;
2786				bp->b_data = bp->b_kvabase;
2787				if (bp->b_bufsize) {
2788					atomic_subtract_int(&bufmallocspace,
2789					    bp->b_bufsize);
2790					bufspacewakeup();
2791					bp->b_bufsize = 0;
2792				}
2793				bp->b_flags &= ~B_MALLOC;
2794				newbsize = round_page(newbsize);
2795			}
2796			vm_hold_load_pages(
2797			    bp,
2798			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2799			    (vm_offset_t) bp->b_data + newbsize);
2800			if (origbuf) {
2801				bcopy(origbuf, bp->b_data, origbufsize);
2802				free(origbuf, M_BIOBUF);
2803			}
2804		}
2805	} else {
2806		int desiredpages;
2807
2808		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2809		desiredpages = (size == 0) ? 0 :
2810			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2811
2812		if (bp->b_flags & B_MALLOC)
2813			panic("allocbuf: VMIO buffer can't be malloced");
2814		/*
2815		 * Set B_CACHE initially if buffer is 0 length or will become
2816		 * 0-length.
2817		 */
2818		if (size == 0 || bp->b_bufsize == 0)
2819			bp->b_flags |= B_CACHE;
2820
2821		if (newbsize < bp->b_bufsize) {
2822			/*
2823			 * DEV_BSIZE aligned new buffer size is less then the
2824			 * DEV_BSIZE aligned existing buffer size.  Figure out
2825			 * if we have to remove any pages.
2826			 */
2827			if (desiredpages < bp->b_npages) {
2828				vm_page_t m;
2829
2830				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2831				vm_page_lock_queues();
2832				for (i = desiredpages; i < bp->b_npages; i++) {
2833					/*
2834					 * the page is not freed here -- it
2835					 * is the responsibility of
2836					 * vnode_pager_setsize
2837					 */
2838					m = bp->b_pages[i];
2839					KASSERT(m != bogus_page,
2840					    ("allocbuf: bogus page found"));
2841					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2842						vm_page_lock_queues();
2843
2844					bp->b_pages[i] = NULL;
2845					vm_page_unwire(m, 0);
2846				}
2847				vm_page_unlock_queues();
2848				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2849				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2850				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2851				bp->b_npages = desiredpages;
2852			}
2853		} else if (size > bp->b_bcount) {
2854			/*
2855			 * We are growing the buffer, possibly in a
2856			 * byte-granular fashion.
2857			 */
2858			struct vnode *vp;
2859			vm_object_t obj;
2860			vm_offset_t toff;
2861			vm_offset_t tinc;
2862
2863			/*
2864			 * Step 1, bring in the VM pages from the object,
2865			 * allocating them if necessary.  We must clear
2866			 * B_CACHE if these pages are not valid for the
2867			 * range covered by the buffer.
2868			 */
2869
2870			vp = bp->b_vp;
2871			obj = bp->b_bufobj->bo_object;
2872
2873			VM_OBJECT_LOCK(obj);
2874			while (bp->b_npages < desiredpages) {
2875				vm_page_t m;
2876				vm_pindex_t pi;
2877
2878				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2879				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2880					/*
2881					 * note: must allocate system pages
2882					 * since blocking here could intefere
2883					 * with paging I/O, no matter which
2884					 * process we are.
2885					 */
2886					m = vm_page_alloc(obj, pi,
2887					    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2888					    VM_ALLOC_WIRED);
2889					if (m == NULL) {
2890						atomic_add_int(&vm_pageout_deficit,
2891						    desiredpages - bp->b_npages);
2892						VM_OBJECT_UNLOCK(obj);
2893						VM_WAIT;
2894						VM_OBJECT_LOCK(obj);
2895					} else {
2896						bp->b_flags &= ~B_CACHE;
2897						bp->b_pages[bp->b_npages] = m;
2898						++bp->b_npages;
2899					}
2900					continue;
2901				}
2902
2903				/*
2904				 * We found a page.  If we have to sleep on it,
2905				 * retry because it might have gotten freed out
2906				 * from under us.
2907				 *
2908				 * We can only test VPO_BUSY here.  Blocking on
2909				 * m->busy might lead to a deadlock:
2910				 *
2911				 *  vm_fault->getpages->cluster_read->allocbuf
2912				 *
2913				 */
2914				vm_page_lock_queues();
2915				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2916					continue;
2917
2918				/*
2919				 * We have a good page.  Should we wakeup the
2920				 * page daemon?
2921				 */
2922				if ((curproc != pageproc) &&
2923				    (VM_PAGE_INQUEUE1(m, PQ_CACHE)) &&
2924				    ((cnt.v_free_count + cnt.v_cache_count) <
2925			 		(cnt.v_free_min + cnt.v_cache_min))) {
2926					pagedaemon_wakeup();
2927				}
2928				vm_page_wire(m);
2929				vm_page_unlock_queues();
2930				bp->b_pages[bp->b_npages] = m;
2931				++bp->b_npages;
2932			}
2933
2934			/*
2935			 * Step 2.  We've loaded the pages into the buffer,
2936			 * we have to figure out if we can still have B_CACHE
2937			 * set.  Note that B_CACHE is set according to the
2938			 * byte-granular range ( bcount and size ), new the
2939			 * aligned range ( newbsize ).
2940			 *
2941			 * The VM test is against m->valid, which is DEV_BSIZE
2942			 * aligned.  Needless to say, the validity of the data
2943			 * needs to also be DEV_BSIZE aligned.  Note that this
2944			 * fails with NFS if the server or some other client
2945			 * extends the file's EOF.  If our buffer is resized,
2946			 * B_CACHE may remain set! XXX
2947			 */
2948
2949			toff = bp->b_bcount;
2950			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2951
2952			while ((bp->b_flags & B_CACHE) && toff < size) {
2953				vm_pindex_t pi;
2954
2955				if (tinc > (size - toff))
2956					tinc = size - toff;
2957
2958				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2959				    PAGE_SHIFT;
2960
2961				vfs_buf_test_cache(
2962				    bp,
2963				    bp->b_offset,
2964				    toff,
2965				    tinc,
2966				    bp->b_pages[pi]
2967				);
2968				toff += tinc;
2969				tinc = PAGE_SIZE;
2970			}
2971			VM_OBJECT_UNLOCK(obj);
2972
2973			/*
2974			 * Step 3, fixup the KVM pmap.  Remember that
2975			 * bp->b_data is relative to bp->b_offset, but
2976			 * bp->b_offset may be offset into the first page.
2977			 */
2978
2979			bp->b_data = (caddr_t)
2980			    trunc_page((vm_offset_t)bp->b_data);
2981			pmap_qenter(
2982			    (vm_offset_t)bp->b_data,
2983			    bp->b_pages,
2984			    bp->b_npages
2985			);
2986
2987			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2988			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2989		}
2990	}
2991	if (newbsize < bp->b_bufsize)
2992		bufspacewakeup();
2993	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2994	bp->b_bcount = size;		/* requested buffer size	*/
2995	return 1;
2996}
2997
2998void
2999biodone(struct bio *bp)
3000{
3001	void (*done)(struct bio *);
3002
3003	mtx_lock(&bdonelock);
3004	bp->bio_flags |= BIO_DONE;
3005	done = bp->bio_done;
3006	if (done == NULL)
3007		wakeup(bp);
3008	mtx_unlock(&bdonelock);
3009	if (done != NULL)
3010		done(bp);
3011}
3012
3013/*
3014 * Wait for a BIO to finish.
3015 *
3016 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3017 * case is not yet clear.
3018 */
3019int
3020biowait(struct bio *bp, const char *wchan)
3021{
3022
3023	mtx_lock(&bdonelock);
3024	while ((bp->bio_flags & BIO_DONE) == 0)
3025		msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
3026	mtx_unlock(&bdonelock);
3027	if (bp->bio_error != 0)
3028		return (bp->bio_error);
3029	if (!(bp->bio_flags & BIO_ERROR))
3030		return (0);
3031	return (EIO);
3032}
3033
3034void
3035biofinish(struct bio *bp, struct devstat *stat, int error)
3036{
3037
3038	if (error) {
3039		bp->bio_error = error;
3040		bp->bio_flags |= BIO_ERROR;
3041	}
3042	if (stat != NULL)
3043		devstat_end_transaction_bio(stat, bp);
3044	biodone(bp);
3045}
3046
3047/*
3048 *	bufwait:
3049 *
3050 *	Wait for buffer I/O completion, returning error status.  The buffer
3051 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3052 *	error and cleared.
3053 */
3054int
3055bufwait(struct buf *bp)
3056{
3057	if (bp->b_iocmd == BIO_READ)
3058		bwait(bp, PRIBIO, "biord");
3059	else
3060		bwait(bp, PRIBIO, "biowr");
3061	if (bp->b_flags & B_EINTR) {
3062		bp->b_flags &= ~B_EINTR;
3063		return (EINTR);
3064	}
3065	if (bp->b_ioflags & BIO_ERROR) {
3066		return (bp->b_error ? bp->b_error : EIO);
3067	} else {
3068		return (0);
3069	}
3070}
3071
3072 /*
3073  * Call back function from struct bio back up to struct buf.
3074  */
3075static void
3076bufdonebio(struct bio *bip)
3077{
3078	struct buf *bp;
3079
3080	bp = bip->bio_caller2;
3081	bp->b_resid = bp->b_bcount - bip->bio_completed;
3082	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3083	bp->b_ioflags = bip->bio_flags;
3084	bp->b_error = bip->bio_error;
3085	if (bp->b_error)
3086		bp->b_ioflags |= BIO_ERROR;
3087	bufdone(bp);
3088	g_destroy_bio(bip);
3089}
3090
3091void
3092dev_strategy(struct cdev *dev, struct buf *bp)
3093{
3094	struct cdevsw *csw;
3095	struct bio *bip;
3096
3097	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3098		panic("b_iocmd botch");
3099	for (;;) {
3100		bip = g_new_bio();
3101		if (bip != NULL)
3102			break;
3103		/* Try again later */
3104		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3105	}
3106	bip->bio_cmd = bp->b_iocmd;
3107	bip->bio_offset = bp->b_iooffset;
3108	bip->bio_length = bp->b_bcount;
3109	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3110	bip->bio_data = bp->b_data;
3111	bip->bio_done = bufdonebio;
3112	bip->bio_caller2 = bp;
3113	bip->bio_dev = dev;
3114	KASSERT(dev->si_refcount > 0,
3115	    ("dev_strategy on un-referenced struct cdev *(%s)",
3116	    devtoname(dev)));
3117	csw = dev_refthread(dev);
3118	if (csw == NULL) {
3119		g_destroy_bio(bip);
3120		bp->b_error = ENXIO;
3121		bp->b_ioflags = BIO_ERROR;
3122		bufdone(bp);
3123		return;
3124	}
3125	(*csw->d_strategy)(bip);
3126	dev_relthread(dev);
3127}
3128
3129/*
3130 *	bufdone:
3131 *
3132 *	Finish I/O on a buffer, optionally calling a completion function.
3133 *	This is usually called from an interrupt so process blocking is
3134 *	not allowed.
3135 *
3136 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3137 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3138 *	assuming B_INVAL is clear.
3139 *
3140 *	For the VMIO case, we set B_CACHE if the op was a read and no
3141 *	read error occured, or if the op was a write.  B_CACHE is never
3142 *	set if the buffer is invalid or otherwise uncacheable.
3143 *
3144 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3145 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3146 *	in the biodone routine.
3147 */
3148void
3149bufdone(struct buf *bp)
3150{
3151	struct bufobj *dropobj;
3152	void    (*biodone)(struct buf *);
3153
3154	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3155	dropobj = NULL;
3156
3157	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3158	    BUF_REFCNT(bp)));
3159	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3160
3161	runningbufwakeup(bp);
3162	if (bp->b_iocmd == BIO_WRITE)
3163		dropobj = bp->b_bufobj;
3164	/* call optional completion function if requested */
3165	if (bp->b_iodone != NULL) {
3166		biodone = bp->b_iodone;
3167		bp->b_iodone = NULL;
3168		(*biodone) (bp);
3169		if (dropobj)
3170			bufobj_wdrop(dropobj);
3171		return;
3172	}
3173
3174	bufdone_finish(bp);
3175
3176	if (dropobj)
3177		bufobj_wdrop(dropobj);
3178}
3179
3180void
3181bufdone_finish(struct buf *bp)
3182{
3183	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3184	    BUF_REFCNT(bp)));
3185
3186	if (LIST_FIRST(&bp->b_dep) != NULL)
3187		buf_complete(bp);
3188
3189	if (bp->b_flags & B_VMIO) {
3190		int i;
3191		vm_ooffset_t foff;
3192		vm_page_t m;
3193		vm_object_t obj;
3194		int iosize;
3195		struct vnode *vp = bp->b_vp;
3196		boolean_t are_queues_locked;
3197
3198		obj = bp->b_bufobj->bo_object;
3199
3200#if defined(VFS_BIO_DEBUG)
3201		mp_fixme("usecount and vflag accessed without locks.");
3202		if (vp->v_usecount == 0) {
3203			panic("biodone: zero vnode ref count");
3204		}
3205
3206		KASSERT(vp->v_object != NULL,
3207			("biodone: vnode %p has no vm_object", vp));
3208#endif
3209
3210		foff = bp->b_offset;
3211		KASSERT(bp->b_offset != NOOFFSET,
3212		    ("biodone: no buffer offset"));
3213
3214		VM_OBJECT_LOCK(obj);
3215#if defined(VFS_BIO_DEBUG)
3216		if (obj->paging_in_progress < bp->b_npages) {
3217			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3218			    obj->paging_in_progress, bp->b_npages);
3219		}
3220#endif
3221
3222		/*
3223		 * Set B_CACHE if the op was a normal read and no error
3224		 * occured.  B_CACHE is set for writes in the b*write()
3225		 * routines.
3226		 */
3227		iosize = bp->b_bcount - bp->b_resid;
3228		if (bp->b_iocmd == BIO_READ &&
3229		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3230		    !(bp->b_ioflags & BIO_ERROR)) {
3231			bp->b_flags |= B_CACHE;
3232		}
3233		if (bp->b_iocmd == BIO_READ) {
3234			vm_page_lock_queues();
3235			are_queues_locked = TRUE;
3236		} else
3237			are_queues_locked = FALSE;
3238		for (i = 0; i < bp->b_npages; i++) {
3239			int bogusflag = 0;
3240			int resid;
3241
3242			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3243			if (resid > iosize)
3244				resid = iosize;
3245
3246			/*
3247			 * cleanup bogus pages, restoring the originals
3248			 */
3249			m = bp->b_pages[i];
3250			if (m == bogus_page) {
3251				bogusflag = 1;
3252				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3253				if (m == NULL)
3254					panic("biodone: page disappeared!");
3255				bp->b_pages[i] = m;
3256				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3257				    bp->b_pages, bp->b_npages);
3258			}
3259#if defined(VFS_BIO_DEBUG)
3260			if (OFF_TO_IDX(foff) != m->pindex) {
3261				printf(
3262"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3263				    (intmax_t)foff, (uintmax_t)m->pindex);
3264			}
3265#endif
3266
3267			/*
3268			 * In the write case, the valid and clean bits are
3269			 * already changed correctly ( see bdwrite() ), so we
3270			 * only need to do this here in the read case.
3271			 */
3272			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3273				vfs_page_set_valid(bp, foff, i, m);
3274			}
3275
3276			/*
3277			 * when debugging new filesystems or buffer I/O methods, this
3278			 * is the most common error that pops up.  if you see this, you
3279			 * have not set the page busy flag correctly!!!
3280			 */
3281			if (m->busy == 0) {
3282				printf("biodone: page busy < 0, "
3283				    "pindex: %d, foff: 0x(%x,%x), "
3284				    "resid: %d, index: %d\n",
3285				    (int) m->pindex, (int)(foff >> 32),
3286						(int) foff & 0xffffffff, resid, i);
3287				if (!vn_isdisk(vp, NULL))
3288					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3289					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3290					    (intmax_t) bp->b_lblkno,
3291					    bp->b_flags, bp->b_npages);
3292				else
3293					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3294					    (intmax_t) bp->b_lblkno,
3295					    bp->b_flags, bp->b_npages);
3296				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3297				    (u_long)m->valid, (u_long)m->dirty,
3298				    m->wire_count);
3299				panic("biodone: page busy < 0\n");
3300			}
3301			vm_page_io_finish(m);
3302			vm_object_pip_subtract(obj, 1);
3303			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3304			iosize -= resid;
3305		}
3306		if (are_queues_locked)
3307			vm_page_unlock_queues();
3308		vm_object_pip_wakeupn(obj, 0);
3309		VM_OBJECT_UNLOCK(obj);
3310	}
3311
3312	/*
3313	 * For asynchronous completions, release the buffer now. The brelse
3314	 * will do a wakeup there if necessary - so no need to do a wakeup
3315	 * here in the async case. The sync case always needs to do a wakeup.
3316	 */
3317
3318	if (bp->b_flags & B_ASYNC) {
3319		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3320			brelse(bp);
3321		else
3322			bqrelse(bp);
3323	} else
3324		bdone(bp);
3325}
3326
3327/*
3328 * This routine is called in lieu of iodone in the case of
3329 * incomplete I/O.  This keeps the busy status for pages
3330 * consistant.
3331 */
3332void
3333vfs_unbusy_pages(struct buf *bp)
3334{
3335	int i;
3336	vm_object_t obj;
3337	vm_page_t m;
3338
3339	runningbufwakeup(bp);
3340	if (!(bp->b_flags & B_VMIO))
3341		return;
3342
3343	obj = bp->b_bufobj->bo_object;
3344	VM_OBJECT_LOCK(obj);
3345	for (i = 0; i < bp->b_npages; i++) {
3346		m = bp->b_pages[i];
3347		if (m == bogus_page) {
3348			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3349			if (!m)
3350				panic("vfs_unbusy_pages: page missing\n");
3351			bp->b_pages[i] = m;
3352			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3353			    bp->b_pages, bp->b_npages);
3354		}
3355		vm_object_pip_subtract(obj, 1);
3356		vm_page_io_finish(m);
3357	}
3358	vm_object_pip_wakeupn(obj, 0);
3359	VM_OBJECT_UNLOCK(obj);
3360}
3361
3362/*
3363 * vfs_page_set_valid:
3364 *
3365 *	Set the valid bits in a page based on the supplied offset.   The
3366 *	range is restricted to the buffer's size.
3367 *
3368 *	This routine is typically called after a read completes.
3369 */
3370static void
3371vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3372{
3373	vm_ooffset_t soff, eoff;
3374
3375	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3376	/*
3377	 * Start and end offsets in buffer.  eoff - soff may not cross a
3378	 * page boundry or cross the end of the buffer.  The end of the
3379	 * buffer, in this case, is our file EOF, not the allocation size
3380	 * of the buffer.
3381	 */
3382	soff = off;
3383	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3384	if (eoff > bp->b_offset + bp->b_bcount)
3385		eoff = bp->b_offset + bp->b_bcount;
3386
3387	/*
3388	 * Set valid range.  This is typically the entire buffer and thus the
3389	 * entire page.
3390	 */
3391	if (eoff > soff) {
3392		vm_page_set_validclean(
3393		    m,
3394		   (vm_offset_t) (soff & PAGE_MASK),
3395		   (vm_offset_t) (eoff - soff)
3396		);
3397	}
3398}
3399
3400/*
3401 * This routine is called before a device strategy routine.
3402 * It is used to tell the VM system that paging I/O is in
3403 * progress, and treat the pages associated with the buffer
3404 * almost as being VPO_BUSY.  Also the object paging_in_progress
3405 * flag is handled to make sure that the object doesn't become
3406 * inconsistant.
3407 *
3408 * Since I/O has not been initiated yet, certain buffer flags
3409 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3410 * and should be ignored.
3411 */
3412void
3413vfs_busy_pages(struct buf *bp, int clear_modify)
3414{
3415	int i, bogus;
3416	vm_object_t obj;
3417	vm_ooffset_t foff;
3418	vm_page_t m;
3419
3420	if (!(bp->b_flags & B_VMIO))
3421		return;
3422
3423	obj = bp->b_bufobj->bo_object;
3424	foff = bp->b_offset;
3425	KASSERT(bp->b_offset != NOOFFSET,
3426	    ("vfs_busy_pages: no buffer offset"));
3427	VM_OBJECT_LOCK(obj);
3428	if (bp->b_bufsize != 0)
3429		vfs_setdirty_locked_object(bp);
3430retry:
3431	for (i = 0; i < bp->b_npages; i++) {
3432		m = bp->b_pages[i];
3433
3434		if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3435			goto retry;
3436	}
3437	bogus = 0;
3438	vm_page_lock_queues();
3439	for (i = 0; i < bp->b_npages; i++) {
3440		m = bp->b_pages[i];
3441
3442		if ((bp->b_flags & B_CLUSTER) == 0) {
3443			vm_object_pip_add(obj, 1);
3444			vm_page_io_start(m);
3445		}
3446		/*
3447		 * When readying a buffer for a read ( i.e
3448		 * clear_modify == 0 ), it is important to do
3449		 * bogus_page replacement for valid pages in
3450		 * partially instantiated buffers.  Partially
3451		 * instantiated buffers can, in turn, occur when
3452		 * reconstituting a buffer from its VM backing store
3453		 * base.  We only have to do this if B_CACHE is
3454		 * clear ( which causes the I/O to occur in the
3455		 * first place ).  The replacement prevents the read
3456		 * I/O from overwriting potentially dirty VM-backed
3457		 * pages.  XXX bogus page replacement is, uh, bogus.
3458		 * It may not work properly with small-block devices.
3459		 * We need to find a better way.
3460		 */
3461		pmap_remove_all(m);
3462		if (clear_modify)
3463			vfs_page_set_valid(bp, foff, i, m);
3464		else if (m->valid == VM_PAGE_BITS_ALL &&
3465		    (bp->b_flags & B_CACHE) == 0) {
3466			bp->b_pages[i] = bogus_page;
3467			bogus++;
3468		}
3469		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3470	}
3471	vm_page_unlock_queues();
3472	VM_OBJECT_UNLOCK(obj);
3473	if (bogus)
3474		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3475		    bp->b_pages, bp->b_npages);
3476}
3477
3478/*
3479 * Tell the VM system that the pages associated with this buffer
3480 * are clean.  This is used for delayed writes where the data is
3481 * going to go to disk eventually without additional VM intevention.
3482 *
3483 * Note that while we only really need to clean through to b_bcount, we
3484 * just go ahead and clean through to b_bufsize.
3485 */
3486static void
3487vfs_clean_pages(struct buf *bp)
3488{
3489	int i;
3490	vm_ooffset_t foff, noff, eoff;
3491	vm_page_t m;
3492
3493	if (!(bp->b_flags & B_VMIO))
3494		return;
3495
3496	foff = bp->b_offset;
3497	KASSERT(bp->b_offset != NOOFFSET,
3498	    ("vfs_clean_pages: no buffer offset"));
3499	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3500	vm_page_lock_queues();
3501	for (i = 0; i < bp->b_npages; i++) {
3502		m = bp->b_pages[i];
3503		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3504		eoff = noff;
3505
3506		if (eoff > bp->b_offset + bp->b_bufsize)
3507			eoff = bp->b_offset + bp->b_bufsize;
3508		vfs_page_set_valid(bp, foff, i, m);
3509		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3510		foff = noff;
3511	}
3512	vm_page_unlock_queues();
3513	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3514}
3515
3516/*
3517 *	vfs_bio_set_validclean:
3518 *
3519 *	Set the range within the buffer to valid and clean.  The range is
3520 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3521 *	itself may be offset from the beginning of the first page.
3522 *
3523 */
3524
3525void
3526vfs_bio_set_validclean(struct buf *bp, int base, int size)
3527{
3528	int i, n;
3529	vm_page_t m;
3530
3531	if (!(bp->b_flags & B_VMIO))
3532		return;
3533	/*
3534	 * Fixup base to be relative to beginning of first page.
3535	 * Set initial n to be the maximum number of bytes in the
3536	 * first page that can be validated.
3537	 */
3538
3539	base += (bp->b_offset & PAGE_MASK);
3540	n = PAGE_SIZE - (base & PAGE_MASK);
3541
3542	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3543	vm_page_lock_queues();
3544	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3545		m = bp->b_pages[i];
3546		if (n > size)
3547			n = size;
3548		vm_page_set_validclean(m, base & PAGE_MASK, n);
3549		base += n;
3550		size -= n;
3551		n = PAGE_SIZE;
3552	}
3553	vm_page_unlock_queues();
3554	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3555}
3556
3557/*
3558 *	vfs_bio_clrbuf:
3559 *
3560 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3561 *	to clear BIO_ERROR and B_INVAL.
3562 *
3563 *	Note that while we only theoretically need to clear through b_bcount,
3564 *	we go ahead and clear through b_bufsize.
3565 */
3566
3567void
3568vfs_bio_clrbuf(struct buf *bp)
3569{
3570	int i, j, mask = 0;
3571	caddr_t sa, ea;
3572
3573	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3574		clrbuf(bp);
3575		return;
3576	}
3577
3578	bp->b_flags &= ~B_INVAL;
3579	bp->b_ioflags &= ~BIO_ERROR;
3580	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3581	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3582	    (bp->b_offset & PAGE_MASK) == 0) {
3583		if (bp->b_pages[0] == bogus_page)
3584			goto unlock;
3585		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3586		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3587		if ((bp->b_pages[0]->valid & mask) == mask)
3588			goto unlock;
3589		if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3590		    ((bp->b_pages[0]->valid & mask) == 0)) {
3591			bzero(bp->b_data, bp->b_bufsize);
3592			bp->b_pages[0]->valid |= mask;
3593			goto unlock;
3594		}
3595	}
3596	ea = sa = bp->b_data;
3597	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3598		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3599		ea = (caddr_t)(vm_offset_t)ulmin(
3600		    (u_long)(vm_offset_t)ea,
3601		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3602		if (bp->b_pages[i] == bogus_page)
3603			continue;
3604		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3605		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3606		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3607		if ((bp->b_pages[i]->valid & mask) == mask)
3608			continue;
3609		if ((bp->b_pages[i]->valid & mask) == 0) {
3610			if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3611				bzero(sa, ea - sa);
3612		} else {
3613			for (; sa < ea; sa += DEV_BSIZE, j++) {
3614				if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3615				    (bp->b_pages[i]->valid & (1 << j)) == 0)
3616					bzero(sa, DEV_BSIZE);
3617			}
3618		}
3619		bp->b_pages[i]->valid |= mask;
3620	}
3621unlock:
3622	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3623	bp->b_resid = 0;
3624}
3625
3626/*
3627 * vm_hold_load_pages and vm_hold_free_pages get pages into
3628 * a buffers address space.  The pages are anonymous and are
3629 * not associated with a file object.
3630 */
3631static void
3632vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3633{
3634	vm_offset_t pg;
3635	vm_page_t p;
3636	int index;
3637
3638	to = round_page(to);
3639	from = round_page(from);
3640	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3641
3642	VM_OBJECT_LOCK(kernel_object);
3643	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3644tryagain:
3645		/*
3646		 * note: must allocate system pages since blocking here
3647		 * could intefere with paging I/O, no matter which
3648		 * process we are.
3649		 */
3650		p = vm_page_alloc(kernel_object,
3651			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3652		    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3653		if (!p) {
3654			atomic_add_int(&vm_pageout_deficit,
3655			    (to - pg) >> PAGE_SHIFT);
3656			VM_OBJECT_UNLOCK(kernel_object);
3657			VM_WAIT;
3658			VM_OBJECT_LOCK(kernel_object);
3659			goto tryagain;
3660		}
3661		p->valid = VM_PAGE_BITS_ALL;
3662		pmap_qenter(pg, &p, 1);
3663		bp->b_pages[index] = p;
3664	}
3665	VM_OBJECT_UNLOCK(kernel_object);
3666	bp->b_npages = index;
3667}
3668
3669/* Return pages associated with this buf to the vm system */
3670static void
3671vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3672{
3673	vm_offset_t pg;
3674	vm_page_t p;
3675	int index, newnpages;
3676
3677	from = round_page(from);
3678	to = round_page(to);
3679	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3680
3681	VM_OBJECT_LOCK(kernel_object);
3682	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3683		p = bp->b_pages[index];
3684		if (p && (index < bp->b_npages)) {
3685			if (p->busy) {
3686				printf(
3687			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3688				    (intmax_t)bp->b_blkno,
3689				    (intmax_t)bp->b_lblkno);
3690			}
3691			bp->b_pages[index] = NULL;
3692			pmap_qremove(pg, 1);
3693			vm_page_lock_queues();
3694			vm_page_unwire(p, 0);
3695			vm_page_free(p);
3696			vm_page_unlock_queues();
3697		}
3698	}
3699	VM_OBJECT_UNLOCK(kernel_object);
3700	bp->b_npages = newnpages;
3701}
3702
3703/*
3704 * Map an IO request into kernel virtual address space.
3705 *
3706 * All requests are (re)mapped into kernel VA space.
3707 * Notice that we use b_bufsize for the size of the buffer
3708 * to be mapped.  b_bcount might be modified by the driver.
3709 *
3710 * Note that even if the caller determines that the address space should
3711 * be valid, a race or a smaller-file mapped into a larger space may
3712 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3713 * check the return value.
3714 */
3715int
3716vmapbuf(struct buf *bp)
3717{
3718	caddr_t addr, kva;
3719	vm_prot_t prot;
3720	int pidx, i;
3721	struct vm_page *m;
3722	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3723
3724	if (bp->b_bufsize < 0)
3725		return (-1);
3726	prot = VM_PROT_READ;
3727	if (bp->b_iocmd == BIO_READ)
3728		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3729	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3730	     addr < bp->b_data + bp->b_bufsize;
3731	     addr += PAGE_SIZE, pidx++) {
3732		/*
3733		 * Do the vm_fault if needed; do the copy-on-write thing
3734		 * when reading stuff off device into memory.
3735		 *
3736		 * NOTE! Must use pmap_extract() because addr may be in
3737		 * the userland address space, and kextract is only guarenteed
3738		 * to work for the kernland address space (see: sparc64 port).
3739		 */
3740retry:
3741		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3742		    prot) < 0) {
3743			vm_page_lock_queues();
3744			for (i = 0; i < pidx; ++i) {
3745				vm_page_unhold(bp->b_pages[i]);
3746				bp->b_pages[i] = NULL;
3747			}
3748			vm_page_unlock_queues();
3749			return(-1);
3750		}
3751		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3752		if (m == NULL)
3753			goto retry;
3754		bp->b_pages[pidx] = m;
3755	}
3756	if (pidx > btoc(MAXPHYS))
3757		panic("vmapbuf: mapped more than MAXPHYS");
3758	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3759
3760	kva = bp->b_saveaddr;
3761	bp->b_npages = pidx;
3762	bp->b_saveaddr = bp->b_data;
3763	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3764	return(0);
3765}
3766
3767/*
3768 * Free the io map PTEs associated with this IO operation.
3769 * We also invalidate the TLB entries and restore the original b_addr.
3770 */
3771void
3772vunmapbuf(struct buf *bp)
3773{
3774	int pidx;
3775	int npages;
3776
3777	npages = bp->b_npages;
3778	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3779	vm_page_lock_queues();
3780	for (pidx = 0; pidx < npages; pidx++)
3781		vm_page_unhold(bp->b_pages[pidx]);
3782	vm_page_unlock_queues();
3783
3784	bp->b_data = bp->b_saveaddr;
3785}
3786
3787void
3788bdone(struct buf *bp)
3789{
3790
3791	mtx_lock(&bdonelock);
3792	bp->b_flags |= B_DONE;
3793	wakeup(bp);
3794	mtx_unlock(&bdonelock);
3795}
3796
3797void
3798bwait(struct buf *bp, u_char pri, const char *wchan)
3799{
3800
3801	mtx_lock(&bdonelock);
3802	while ((bp->b_flags & B_DONE) == 0)
3803		msleep(bp, &bdonelock, pri, wchan, 0);
3804	mtx_unlock(&bdonelock);
3805}
3806
3807int
3808bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3809{
3810
3811	return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3812}
3813
3814void
3815bufstrategy(struct bufobj *bo, struct buf *bp)
3816{
3817	int i = 0;
3818	struct vnode *vp;
3819
3820	vp = bp->b_vp;
3821	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3822	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3823	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3824	i = VOP_STRATEGY(vp, bp);
3825	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3826}
3827
3828void
3829bufobj_wrefl(struct bufobj *bo)
3830{
3831
3832	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3833	ASSERT_BO_LOCKED(bo);
3834	bo->bo_numoutput++;
3835}
3836
3837void
3838bufobj_wref(struct bufobj *bo)
3839{
3840
3841	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3842	BO_LOCK(bo);
3843	bo->bo_numoutput++;
3844	BO_UNLOCK(bo);
3845}
3846
3847void
3848bufobj_wdrop(struct bufobj *bo)
3849{
3850
3851	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3852	BO_LOCK(bo);
3853	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3854	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3855		bo->bo_flag &= ~BO_WWAIT;
3856		wakeup(&bo->bo_numoutput);
3857	}
3858	BO_UNLOCK(bo);
3859}
3860
3861int
3862bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3863{
3864	int error;
3865
3866	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3867	ASSERT_BO_LOCKED(bo);
3868	error = 0;
3869	while (bo->bo_numoutput) {
3870		bo->bo_flag |= BO_WWAIT;
3871		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3872		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3873		if (error)
3874			break;
3875	}
3876	return (error);
3877}
3878
3879void
3880bpin(struct buf *bp)
3881{
3882	mtx_lock(&bpinlock);
3883	bp->b_pin_count++;
3884	mtx_unlock(&bpinlock);
3885}
3886
3887void
3888bunpin(struct buf *bp)
3889{
3890	mtx_lock(&bpinlock);
3891	if (--bp->b_pin_count == 0)
3892		wakeup(bp);
3893	mtx_unlock(&bpinlock);
3894}
3895
3896void
3897bunpin_wait(struct buf *bp)
3898{
3899	mtx_lock(&bpinlock);
3900	while (bp->b_pin_count > 0)
3901		msleep(bp, &bpinlock, PRIBIO, "bwunpin", 0);
3902	mtx_unlock(&bpinlock);
3903}
3904
3905#include "opt_ddb.h"
3906#ifdef DDB
3907#include <ddb/ddb.h>
3908
3909/* DDB command to show buffer data */
3910DB_SHOW_COMMAND(buffer, db_show_buffer)
3911{
3912	/* get args */
3913	struct buf *bp = (struct buf *)addr;
3914
3915	if (!have_addr) {
3916		db_printf("usage: show buffer <addr>\n");
3917		return;
3918	}
3919
3920	db_printf("buf at %p\n", bp);
3921	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3922	db_printf(
3923	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3924	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n",
3925	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3926	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno);
3927	if (bp->b_npages) {
3928		int i;
3929		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3930		for (i = 0; i < bp->b_npages; i++) {
3931			vm_page_t m;
3932			m = bp->b_pages[i];
3933			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3934			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3935			if ((i + 1) < bp->b_npages)
3936				db_printf(",");
3937		}
3938		db_printf("\n");
3939	}
3940	lockmgr_printinfo(&bp->b_lock);
3941}
3942
3943DB_SHOW_COMMAND(lockedbufs, lockedbufs)
3944{
3945	struct buf *bp;
3946	int i;
3947
3948	for (i = 0; i < nbuf; i++) {
3949		bp = &buf[i];
3950		if (lockcount(&bp->b_lock)) {
3951			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
3952			db_printf("\n");
3953		}
3954	}
3955}
3956#endif /* DDB */
3957