vfs_bio.c revision 140056
1118611Snjl/*-
2118611Snjl * Copyright (c) 2004 Poul-Henning Kamp
3118611Snjl * Copyright (c) 1994,1997 John S. Dyson
4151937Sjkim * All rights reserved.
5118611Snjl *
6118611Snjl * Redistribution and use in source and binary forms, with or without
7118611Snjl * modification, are permitted provided that the following conditions
8217365Sjkim * are met:
9217365Sjkim * 1. Redistributions of source code must retain the above copyright
10118611Snjl *    notice, this list of conditions and the following disclaimer.
11118611Snjl * 2. Redistributions in binary form must reproduce the above copyright
12217365Sjkim *    notice, this list of conditions and the following disclaimer in the
13217365Sjkim *    documentation and/or other materials provided with the distribution.
14217365Sjkim *
15217365Sjkim * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16217365Sjkim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17217365Sjkim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18217365Sjkim * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19217365Sjkim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20217365Sjkim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21217365Sjkim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22217365Sjkim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23217365Sjkim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24217365Sjkim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25217365Sjkim * SUCH DAMAGE.
26118611Snjl */
27217365Sjkim
28217365Sjkim/*
29217365Sjkim * this file contains a new buffer I/O scheme implementing a coherent
30118611Snjl * VM object and buffer cache scheme.  Pains have been taken to make
31217365Sjkim * sure that the performance degradation associated with schemes such
32217365Sjkim * as this is not realized.
33217365Sjkim *
34217365Sjkim * Author:  John S. Dyson
35217365Sjkim * Significant help during the development and debugging phases
36217365Sjkim * had been provided by David Greenman, also of the FreeBSD core team.
37217365Sjkim *
38217365Sjkim * see man buf(9) for more info.
39217365Sjkim */
40217365Sjkim
41217365Sjkim#include <sys/cdefs.h>
42217365Sjkim__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 140056 2005-01-11 10:43:08Z phk $");
43217365Sjkim
44118611Snjl#include <sys/param.h>
45118611Snjl#include <sys/systm.h>
46118611Snjl#include <sys/bio.h>
47118611Snjl#include <sys/conf.h>
48118611Snjl#include <sys/buf.h>
49217365Sjkim#include <sys/devicestat.h>
50217365Sjkim#include <sys/eventhandler.h>
51217365Sjkim#include <sys/lock.h>
52217365Sjkim#include <sys/malloc.h>
53118611Snjl#include <sys/mount.h>
54118611Snjl#include <sys/mutex.h>
55118611Snjl#include <sys/kernel.h>
56118611Snjl#include <sys/kthread.h>
57118611Snjl#include <sys/proc.h>
58118611Snjl#include <sys/resourcevar.h>
59118611Snjl#include <sys/sysctl.h>
60118611Snjl#include <sys/vmmeter.h>
61118611Snjl#include <sys/vnode.h>
62118611Snjl#include <geom/geom.h>
63118611Snjl#include <vm/vm.h>
64118611Snjl#include <vm/vm_param.h>
65118611Snjl#include <vm/vm_kern.h>
66118611Snjl#include <vm/vm_pageout.h>
67118611Snjl#include <vm/vm_page.h>
68118611Snjl#include <vm/vm_object.h>
69118611Snjl#include <vm/vm_extern.h>
70118611Snjl#include <vm/vm_map.h>
71118611Snjl#include "opt_directio.h"
72151937Sjkim#include "opt_swap.h"
73118611Snjl
74151937Sjkimstatic MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
75151937Sjkim
76213806Sjkimstruct	bio_ops bioops;		/* I/O operation notification */
77151937Sjkim
78118611Snjlstruct	buf_ops buf_ops_bio = {
79118611Snjl	.bop_name	=	"buf_ops_bio",
80118611Snjl	.bop_write	=	bufwrite,
81118611Snjl	.bop_strategy	=	bufstrategy,
82118611Snjl	.bop_sync	=	bufsync,
83118611Snjl};
84118611Snjl
85118611Snjl/*
86151937Sjkim * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
87151937Sjkim * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
88151937Sjkim */
89118611Snjlstruct buf *buf;		/* buffer header pool */
90118611Snjl
91118611Snjlstatic struct proc *bufdaemonproc;
92118611Snjl
93118611Snjlstatic int inmem(struct vnode *vp, daddr_t blkno);
94118611Snjlstatic void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
95118611Snjl		vm_offset_t to);
96118611Snjlstatic void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
97118611Snjl		vm_offset_t to);
98118611Snjlstatic void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
99118611Snjl			       int pageno, vm_page_t m);
100118611Snjlstatic void vfs_clean_pages(struct buf *bp);
101118611Snjlstatic void vfs_setdirty(struct buf *bp);
102118611Snjlstatic void vfs_vmio_release(struct buf *bp);
103118611Snjlstatic void vfs_backgroundwritedone(struct buf *bp);
104118611Snjlstatic int vfs_bio_clcheck(struct vnode *vp, int size,
105118611Snjl		daddr_t lblkno, daddr_t blkno);
106118611Snjlstatic int flushbufqueues(int flushdeps);
107118611Snjlstatic void buf_daemon(void);
108118611Snjlvoid bremfreel(struct buf *bp);
109118611Snjl
110118611Snjlint vmiodirenable = TRUE;
111118611SnjlSYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
112118611Snjl    "Use the VM system for directory writes");
113118611Snjlint runningbufspace;
114118611SnjlSYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
115118611Snjl    "Amount of presently outstanding async buffer io");
116118611Snjlstatic int bufspace;
117118611SnjlSYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
118193529Sjkim    "KVA memory used for bufs");
119209746Sjkimstatic int maxbufspace;
120193529SjkimSYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
121209746Sjkim    "Maximum allowed value of bufspace (including buf_daemon)");
122209746Sjkimstatic int bufmallocspace;
123209746SjkimSYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
124209746Sjkim    "Amount of malloced memory for buffers");
125210976Sjkimstatic int maxbufmallocspace;
126210976SjkimSYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
127210976Sjkim    "Maximum amount of malloced memory for buffers");
128210976Sjkimstatic int lobufspace;
129193529SjkimSYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
130193529Sjkim    "Minimum amount of buffers we want to have");
131210976Sjkimstatic int hibufspace;
132210976SjkimSYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
133118611Snjl    "Maximum allowed value of bufspace (excluding buf_daemon)");
134193529Sjkimstatic int bufreusecnt;
135193529SjkimSYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
136193529Sjkim    "Number of times we have reused a buffer");
137193529Sjkimstatic int buffreekvacnt;
138151937SjkimSYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
139151937Sjkim    "Number of times we have freed the KVA space from some buffer");
140151937Sjkimstatic int bufdefragcnt;
141118611SnjlSYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
142118611Snjl    "Number of times we have had to repeat buffer allocation to defragment");
143118611Snjlstatic int lorunningspace;
144118611SnjlSYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
145118611Snjl    "Minimum preferred space used for in-progress I/O");
146118611Snjlstatic int hirunningspace;
147118611SnjlSYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
148118611Snjl    "Maximum amount of space to use for in-progress I/O");
149151937Sjkimstatic int dirtybufferflushes;
150151937SjkimSYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
151151937Sjkim    0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
152151937Sjkimstatic int altbufferflushes;
153118611SnjlSYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
154151937Sjkim    0, "Number of fsync flushes to limit dirty buffers");
155151937Sjkimstatic int recursiveflushes;
156118611SnjlSYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
157151937Sjkim    0, "Number of flushes skipped due to being recursive");
158151937Sjkimstatic int numdirtybuffers;
159151937SjkimSYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
160118611Snjl    "Number of buffers that are dirty (has unwritten changes) at the moment");
161209746Sjkimstatic int lodirtybuffers;
162209746SjkimSYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
163209746Sjkim    "How many buffers we want to have free before bufdaemon can sleep");
164118611Snjlstatic int hidirtybuffers;
165209746SjkimSYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
166151937Sjkim    "When the number of dirty buffers is considered severe");
167218590Sjkimstatic int dirtybufthresh;
168151937SjkimSYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
169151937Sjkim    0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
170151937Sjkimstatic int numfreebuffers;
171151937SjkimSYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
172151937Sjkim    "Number of free buffers");
173151937Sjkimstatic int lofreebuffers;
174118611SnjlSYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
175151937Sjkim   "XXX Unused");
176151937Sjkimstatic int hifreebuffers;
177151937SjkimSYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
178151937Sjkim   "XXX Complicatedly unused");
179151937Sjkimstatic int getnewbufcalls;
180118611SnjlSYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
181151937Sjkim   "Number of calls to getnewbuf");
182151937Sjkimstatic int getnewbufrestarts;
183151937SjkimSYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
184151937Sjkim    "Number of times getnewbuf has had to restart a buffer aquisition");
185151937Sjkimstatic int dobkgrdwrite = 1;
186118611SnjlSYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
187151937Sjkim    "Do background writes (honoring the BV_BKGRDWRITE flag)?");
188151937Sjkim
189151937Sjkim/*
190151937Sjkim * Wakeup point for bufdaemon, as well as indicator of whether it is already
191151937Sjkim * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
192118611Snjl * is idling.
193151937Sjkim */
194151937Sjkimstatic int bd_request;
195151937Sjkim
196151937Sjkim/*
197151937Sjkim * This lock synchronizes access to bd_request.
198118611Snjl */
199151937Sjkimstatic struct mtx bdlock;
200218590Sjkim
201151937Sjkim/*
202151937Sjkim * bogus page -- for I/O to/from partially complete buffers
203151937Sjkim * this is a temporary solution to the problem, but it is not
204118611Snjl * really that bad.  it would be better to split the buffer
205218590Sjkim * for input in the case of buffers partially already in memory,
206218590Sjkim * but the code is intricate enough already.
207218590Sjkim */
208218590Sjkimvm_page_t bogus_page;
209218590Sjkim
210218590Sjkim/*
211218590Sjkim * Synchronization (sleep/wakeup) variable for active buffer space requests.
212218590Sjkim * Set when wait starts, cleared prior to wakeup().
213218590Sjkim * Used in runningbufwakeup() and waitrunningbufspace().
214218590Sjkim */
215218590Sjkimstatic int runningbufreq;
216218590Sjkim
217218590Sjkim/*
218218590Sjkim * This lock protects the runningbufreq and synchronizes runningbufwakeup and
219218590Sjkim * waitrunningbufspace().
220218590Sjkim */
221218590Sjkimstatic struct mtx rbreqlock;
222218590Sjkim
223218590Sjkim/*
224218590Sjkim * Synchronization (sleep/wakeup) variable for buffer requests.
225218590Sjkim * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
226218590Sjkim * by and/or.
227218590Sjkim * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
228218590Sjkim * getnewbuf(), and getblk().
229218590Sjkim */
230218590Sjkimstatic int needsbuffer;
231218590Sjkim
232151937Sjkim/*
233218590Sjkim * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
234118611Snjl */
235218590Sjkimstatic struct mtx nblock;
236151937Sjkim
237218590Sjkim/*
238218590Sjkim * Lock that protects against bwait()/bdone()/B_DONE races.
239218590Sjkim */
240218590Sjkim
241218590Sjkimstatic struct mtx bdonelock;
242218590Sjkim
243218590Sjkim/*
244218590Sjkim * Definitions for the buffer free lists.
245218590Sjkim */
246218590Sjkim#define BUFFER_QUEUES	5	/* number of free buffer queues */
247218590Sjkim
248218590Sjkim#define QUEUE_NONE	0	/* on no queue */
249218590Sjkim#define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
250218590Sjkim#define QUEUE_DIRTY	2	/* B_DELWRI buffers */
251218590Sjkim#define QUEUE_EMPTYKVA	3	/* empty buffer headers w/KVA assignment */
252218590Sjkim#define QUEUE_EMPTY	4	/* empty buffer headers */
253218590Sjkim
254218590Sjkim/* Queues for free buffers with various properties */
255218590Sjkimstatic TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
256218590Sjkim
257218590Sjkim/* Lock for the bufqueues */
258218590Sjkimstatic struct mtx bqlock;
259218590Sjkim
260218590Sjkim/*
261218590Sjkim * Single global constant for BUF_WMESG, to avoid getting multiple references.
262218590Sjkim * buf_wmesg is referred from macros.
263218590Sjkim */
264218590Sjkimconst char *buf_wmesg = BUF_WMESG;
265218590Sjkim
266218590Sjkim#define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
267218590Sjkim#define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
268218590Sjkim#define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
269151937Sjkim#define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
270151937Sjkim
271151937Sjkim#ifdef DIRECTIO
272118611Snjlextern void ffs_rawread_setup(void);
273118611Snjl#endif /* DIRECTIO */
274118611Snjl/*
275118611Snjl *	numdirtywakeup:
276118611Snjl *
277118611Snjl *	If someone is blocked due to there being too many dirty buffers,
278118611Snjl *	and numdirtybuffers is now reasonable, wake them up.
279118611Snjl */
280118611Snjl
281118611Snjlstatic __inline void
282118611Snjlnumdirtywakeup(int level)
283118611Snjl{
284118611Snjl
285118611Snjl	if (numdirtybuffers <= level) {
286151937Sjkim		mtx_lock(&nblock);
287151937Sjkim		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
288151937Sjkim			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
289151937Sjkim			wakeup(&needsbuffer);
290118611Snjl		}
291118611Snjl		mtx_unlock(&nblock);
292118611Snjl	}
293118611Snjl}
294118611Snjl
295118611Snjl/*
296118611Snjl *	bufspacewakeup:
297118611Snjl *
298118611Snjl *	Called when buffer space is potentially available for recovery.
299118611Snjl *	getnewbuf() will block on this flag when it is unable to free
300118611Snjl *	sufficient buffer space.  Buffer space becomes recoverable when
301118611Snjl *	bp's get placed back in the queues.
302118611Snjl */
303118611Snjl
304118611Snjlstatic __inline void
305118611Snjlbufspacewakeup(void)
306118611Snjl{
307118611Snjl
308118611Snjl	/*
309118611Snjl	 * If someone is waiting for BUF space, wake them up.  Even
310118611Snjl	 * though we haven't freed the kva space yet, the waiting
311193529Sjkim	 * process will be able to now.
312193529Sjkim	 */
313193529Sjkim	mtx_lock(&nblock);
314193529Sjkim	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
315167802Sjkim		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
316118611Snjl		wakeup(&needsbuffer);
317167802Sjkim	}
318118611Snjl	mtx_unlock(&nblock);
319118611Snjl}
320151937Sjkim
321151937Sjkim/*
322151937Sjkim * runningbufwakeup() - in-progress I/O accounting.
323118611Snjl *
324151937Sjkim */
325151937Sjkimstatic __inline void
326118611Snjlrunningbufwakeup(struct buf *bp)
327118611Snjl{
328118611Snjl
329118611Snjl	if (bp->b_runningbufspace) {
330118611Snjl		atomic_subtract_int(&runningbufspace, bp->b_runningbufspace);
331118611Snjl		bp->b_runningbufspace = 0;
332118611Snjl		mtx_lock(&rbreqlock);
333118611Snjl		if (runningbufreq && runningbufspace <= lorunningspace) {
334118611Snjl			runningbufreq = 0;
335118611Snjl			wakeup(&runningbufreq);
336118611Snjl		}
337118611Snjl		mtx_unlock(&rbreqlock);
338118611Snjl	}
339118611Snjl}
340167802Sjkim
341167802Sjkim/*
342167802Sjkim *	bufcountwakeup:
343118611Snjl *
344151937Sjkim *	Called when a buffer has been added to one of the free queues to
345151937Sjkim *	account for the buffer and to wakeup anyone waiting for free buffers.
346151937Sjkim *	This typically occurs when large amounts of metadata are being handled
347151937Sjkim *	by the buffer cache ( else buffer space runs out first, usually ).
348151937Sjkim */
349151937Sjkim
350151937Sjkimstatic __inline void
351151937Sjkimbufcountwakeup(void)
352118611Snjl{
353118611Snjl
354118611Snjl	atomic_add_int(&numfreebuffers, 1);
355118611Snjl	mtx_lock(&nblock);
356118611Snjl	if (needsbuffer) {
357118611Snjl		needsbuffer &= ~VFS_BIO_NEED_ANY;
358118611Snjl		if (numfreebuffers >= hifreebuffers)
359118611Snjl			needsbuffer &= ~VFS_BIO_NEED_FREE;
360118611Snjl		wakeup(&needsbuffer);
361118611Snjl	}
362118611Snjl	mtx_unlock(&nblock);
363118611Snjl}
364151937Sjkim
365118611Snjl/*
366118611Snjl *	waitrunningbufspace()
367118611Snjl *
368118611Snjl *	runningbufspace is a measure of the amount of I/O currently
369118611Snjl *	running.  This routine is used in async-write situations to
370118611Snjl *	prevent creating huge backups of pending writes to a device.
371118611Snjl *	Only asynchronous writes are governed by this function.
372118611Snjl *
373118611Snjl *	Reads will adjust runningbufspace, but will not block based on it.
374118611Snjl *	The read load has a side effect of reducing the allowed write load.
375118611Snjl *
376118611Snjl *	This does NOT turn an async write into a sync write.  It waits
377118611Snjl *	for earlier writes to complete and generally returns before the
378118611Snjl *	caller's write has reached the device.
379118611Snjl */
380118611Snjlstatic __inline void
381151937Sjkimwaitrunningbufspace(void)
382118611Snjl{
383118611Snjl
384118611Snjl	mtx_lock(&rbreqlock);
385151937Sjkim	while (runningbufspace > hirunningspace) {
386151937Sjkim		++runningbufreq;
387151937Sjkim		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
388151937Sjkim	}
389118611Snjl	mtx_unlock(&rbreqlock);
390118611Snjl}
391118611Snjl
392118611Snjl
393118611Snjl/*
394118611Snjl *	vfs_buf_test_cache:
395118611Snjl *
396118611Snjl *	Called when a buffer is extended.  This function clears the B_CACHE
397118611Snjl *	bit if the newly extended portion of the buffer does not contain
398118611Snjl *	valid data.
399118611Snjl */
400118611Snjlstatic __inline
401118611Snjlvoid
402118611Snjlvfs_buf_test_cache(struct buf *bp,
403118611Snjl		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
404118611Snjl		  vm_page_t m)
405118611Snjl{
406118611Snjl
407118611Snjl	GIANT_REQUIRED;
408118611Snjl
409118611Snjl	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
410118611Snjl	if (bp->b_flags & B_CACHE) {
411118611Snjl		int base = (foff + off) & PAGE_MASK;
412151937Sjkim		if (vm_page_is_valid(m, base, size) == 0)
413118611Snjl			bp->b_flags &= ~B_CACHE;
414118611Snjl	}
415151937Sjkim}
416151937Sjkim
417118611Snjl/* Wake up the buffer deamon if necessary */
418118611Snjlstatic __inline
419151937Sjkimvoid
420209746Sjkimbd_wakeup(int dirtybuflevel)
421209746Sjkim{
422209746Sjkim
423209746Sjkim	mtx_lock(&bdlock);
424209746Sjkim	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
425209746Sjkim		bd_request = 1;
426209746Sjkim		wakeup(&bd_request);
427209746Sjkim	}
428209746Sjkim	mtx_unlock(&bdlock);
429209746Sjkim}
430151937Sjkim
431151937Sjkim/*
432118611Snjl * bd_speedup - speedup the buffer cache flushing code
433118611Snjl */
434118611Snjl
435118611Snjlstatic __inline
436118611Snjlvoid
437118611Snjlbd_speedup(void)
438118611Snjl{
439118611Snjl
440118611Snjl	bd_wakeup(1);
441118611Snjl}
442118611Snjl
443118611Snjl/*
444118611Snjl * Calculating buffer cache scaling values and reserve space for buffer
445151937Sjkim * headers.  This is called during low level kernel initialization and
446151937Sjkim * may be called more then once.  We CANNOT write to the memory area
447118611Snjl * being reserved at this time.
448118611Snjl */
449118611Snjlcaddr_t
450151937Sjkimkern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
451118611Snjl{
452118611Snjl
453118611Snjl	/*
454118611Snjl	 * physmem_est is in pages.  Convert it to kilobytes (assumes
455118611Snjl	 * PAGE_SIZE is >= 1K)
456204773Sjkim	 */
457204773Sjkim	physmem_est = physmem_est * (PAGE_SIZE / 1024);
458204773Sjkim
459204773Sjkim	/*
460151937Sjkim	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
461204773Sjkim	 * For the first 64MB of ram nominally allocate sufficient buffers to
462204773Sjkim	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
463204773Sjkim	 * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
464204773Sjkim	 * the buffer cache we limit the eventual kva reservation to
465206117Sjkim	 * maxbcache bytes.
466206117Sjkim	 *
467206117Sjkim	 * factor represents the 1/4 x ram conversion.
468206117Sjkim	 */
469206117Sjkim	if (nbuf == 0) {
470204773Sjkim		int factor = 4 * BKVASIZE / 1024;
471204773Sjkim
472204773Sjkim		nbuf = 50;
473204773Sjkim		if (physmem_est > 4096)
474204773Sjkim			nbuf += min((physmem_est - 4096) / factor,
475204773Sjkim			    65536 / factor);
476204773Sjkim		if (physmem_est > 65536)
477204773Sjkim			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
478204773Sjkim
479204773Sjkim		if (maxbcache && nbuf > maxbcache / BKVASIZE)
480204773Sjkim			nbuf = maxbcache / BKVASIZE;
481204773Sjkim	}
482151937Sjkim
483151937Sjkim#if 0
484151937Sjkim	/*
485118611Snjl	 * Do not allow the buffer_map to be more then 1/2 the size of the
486118611Snjl	 * kernel_map.
487118611Snjl	 */
488118611Snjl	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
489118611Snjl	    (BKVASIZE * 2)) {
490118611Snjl		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
491118611Snjl		    (BKVASIZE * 2);
492118611Snjl		printf("Warning: nbufs capped at %d\n", nbuf);
493118611Snjl	}
494118611Snjl#endif
495118611Snjl
496118611Snjl	/*
497118611Snjl	 * swbufs are used as temporary holders for I/O, such as paging I/O.
498118611Snjl	 * We have no less then 16 and no more then 256.
499118611Snjl	 */
500118611Snjl	nswbuf = max(min(nbuf/4, 256), 16);
501118611Snjl#ifdef NSWBUF_MIN
502118611Snjl	if (nswbuf < NSWBUF_MIN)
503118611Snjl		nswbuf = NSWBUF_MIN;
504118611Snjl#endif
505118611Snjl#ifdef DIRECTIO
506118611Snjl	ffs_rawread_setup();
507118611Snjl#endif
508118611Snjl
509118611Snjl	/*
510118611Snjl	 * Reserve space for the buffer cache buffers
511118611Snjl	 */
512118611Snjl	swbuf = (void *)v;
513151937Sjkim	v = (caddr_t)(swbuf + nswbuf);
514151937Sjkim	buf = (void *)v;
515151937Sjkim	v = (caddr_t)(buf + nbuf);
516118611Snjl
517151937Sjkim	return(v);
518151937Sjkim}
519151937Sjkim
520151937Sjkim/* Initialize the buffer subsystem.  Called before use of any buffers. */
521118611Snjlvoid
522118611Snjlbufinit(void)
523118611Snjl{
524118611Snjl	struct buf *bp;
525118611Snjl	int i;
526118611Snjl
527118611Snjl	GIANT_REQUIRED;
528118611Snjl
529118611Snjl	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
530118611Snjl	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
531118611Snjl	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
532118611Snjl	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
533118611Snjl	mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
534118611Snjl
535118611Snjl	/* next, make a null set of free lists */
536118611Snjl	for (i = 0; i < BUFFER_QUEUES; i++)
537118611Snjl		TAILQ_INIT(&bufqueues[i]);
538118611Snjl
539202771Sjkim	/* finally, initialize each buffer header and stick on empty q */
540118611Snjl	for (i = 0; i < nbuf; i++) {
541118611Snjl		bp = &buf[i];
542218590Sjkim		bzero(bp, sizeof *bp);
543218590Sjkim		bp->b_flags = B_INVAL;	/* we're just an empty header */
544218590Sjkim		bp->b_rcred = NOCRED;
545218590Sjkim		bp->b_wcred = NOCRED;
546118611Snjl		bp->b_qindex = QUEUE_EMPTY;
547118611Snjl		bp->b_vflags = 0;
548118611Snjl		bp->b_xflags = 0;
549118611Snjl		LIST_INIT(&bp->b_dep);
550118611Snjl		BUF_LOCKINIT(bp);
551118611Snjl		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
552118611Snjl	}
553118611Snjl
554118611Snjl	/*
555118611Snjl	 * maxbufspace is the absolute maximum amount of buffer space we are
556151937Sjkim	 * allowed to reserve in KVM and in real terms.  The absolute maximum
557151937Sjkim	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
558118611Snjl	 * used by most other processes.  The differential is required to
559118611Snjl	 * ensure that buf_daemon is able to run when other processes might
560118611Snjl	 * be blocked waiting for buffer space.
561118611Snjl	 *
562118611Snjl	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
563118611Snjl	 * this may result in KVM fragmentation which is not handled optimally
564118611Snjl	 * by the system.
565118611Snjl	 */
566118611Snjl	maxbufspace = nbuf * BKVASIZE;
567118611Snjl	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
568118611Snjl	lobufspace = hibufspace - MAXBSIZE;
569118611Snjl
570118611Snjl	lorunningspace = 512 * 1024;
571118611Snjl	hirunningspace = 1024 * 1024;
572118611Snjl
573118611Snjl/*
574118611Snjl * Limit the amount of malloc memory since it is wired permanently into
575118611Snjl * the kernel space.  Even though this is accounted for in the buffer
576118611Snjl * allocation, we don't want the malloced region to grow uncontrolled.
577118611Snjl * The malloc scheme improves memory utilization significantly on average
578118611Snjl * (small) directories.
579118611Snjl */
580118611Snjl	maxbufmallocspace = hibufspace / 20;
581118611Snjl
582118611Snjl/*
583118611Snjl * Reduce the chance of a deadlock occuring by limiting the number
584151937Sjkim * of delayed-write dirty buffers we allow to stack up.
585151937Sjkim */
586118611Snjl	hidirtybuffers = nbuf / 4 + 20;
587118611Snjl	dirtybufthresh = hidirtybuffers * 9 / 10;
588197104Sjkim	numdirtybuffers = 0;
589197104Sjkim/*
590197104Sjkim * To support extreme low-memory systems, make sure hidirtybuffers cannot
591197104Sjkim * eat up all available buffer space.  This occurs when our minimum cannot
592118611Snjl * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
593118611Snjl * BKVASIZE'd (8K) buffers.
594118611Snjl */
595118611Snjl	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
596118611Snjl		hidirtybuffers >>= 1;
597118611Snjl	}
598118611Snjl	lodirtybuffers = hidirtybuffers / 2;
599118611Snjl
600207344Sjkim/*
601207344Sjkim * Try to keep the number of free buffers in the specified range,
602207344Sjkim * and give special processes (e.g. like buf_daemon) access to an
603207344Sjkim * emergency reserve.
604118611Snjl */
605118611Snjl	lofreebuffers = nbuf / 18 + 5;
606118611Snjl	hifreebuffers = 2 * lofreebuffers;
607118611Snjl	numfreebuffers = nbuf;
608118611Snjl
609118611Snjl/*
610118611Snjl * Maximum number of async ops initiated per buf_daemon loop.  This is
611118611Snjl * somewhat of a hack at the moment, we really need to limit ourselves
612118611Snjl * based on the number of bytes of I/O in-transit that were initiated
613118611Snjl * from buf_daemon.
614118611Snjl */
615118611Snjl
616118611Snjl	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
617118611Snjl	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
618118611Snjl}
619118611Snjl
620118611Snjl/*
621118611Snjl * bfreekva() - free the kva allocation for a buffer.
622118611Snjl *
623118611Snjl *	Must be called at splbio() or higher as this is the only locking for
624118611Snjl *	buffer_map.
625118611Snjl *
626118611Snjl *	Since this call frees up buffer space, we call bufspacewakeup().
627118611Snjl */
628118611Snjlstatic void
629118611Snjlbfreekva(struct buf *bp)
630118611Snjl{
631118611Snjl
632118611Snjl	GIANT_REQUIRED;
633118611Snjl
634118611Snjl	if (bp->b_kvasize) {
635118611Snjl		atomic_add_int(&buffreekvacnt, 1);
636118611Snjl		atomic_subtract_int(&bufspace, bp->b_kvasize);
637118611Snjl		vm_map_delete(buffer_map,
638118611Snjl		    (vm_offset_t) bp->b_kvabase,
639118611Snjl		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
640118611Snjl		);
641118611Snjl		bp->b_kvasize = 0;
642118611Snjl		bufspacewakeup();
643118611Snjl	}
644118611Snjl}
645118611Snjl
646118611Snjl/*
647118611Snjl *	bremfree:
648151937Sjkim *
649151937Sjkim *	Mark the buffer for removal from the appropriate free list in brelse.
650151937Sjkim *
651118611Snjl */
652118611Snjlvoid
653118611Snjlbremfree(struct buf *bp)
654118611Snjl{
655118611Snjl
656151937Sjkim	KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked."));
657151937Sjkim	KASSERT((bp->b_flags & B_REMFREE) == 0 && bp->b_qindex != QUEUE_NONE,
658151937Sjkim	    ("bremfree: buffer not on a queue."));
659118611Snjl
660151937Sjkim	bp->b_flags |= B_REMFREE;
661151937Sjkim	/* Fixup numfreebuffers count.  */
662118611Snjl	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
663167802Sjkim		atomic_subtract_int(&numfreebuffers, 1);
664167802Sjkim}
665167802Sjkim
666167802Sjkim/*
667118611Snjl *	bremfreef:
668118611Snjl *
669118611Snjl *	Force an immediate removal from a free list.  Used only in nfs when
670118611Snjl *	it abuses the b_freelist pointer.
671212761Sjkim */
672212761Sjkimvoid
673212761Sjkimbremfreef(struct buf *bp)
674118611Snjl{
675212761Sjkim	mtx_lock(&bqlock);
676151937Sjkim	bremfreel(bp);
677151937Sjkim	mtx_unlock(&bqlock);
678151937Sjkim}
679151937Sjkim
680151937Sjkim/*
681151937Sjkim *	bremfreel:
682151937Sjkim *
683151937Sjkim *	Removes a buffer from the free list, must be called with the
684118611Snjl *	bqlock held.
685151937Sjkim */
686118611Snjlvoid
687151937Sjkimbremfreel(struct buf *bp)
688151937Sjkim{
689151937Sjkim	int s = splbio();
690151937Sjkim
691118611Snjl	mtx_assert(&bqlock, MA_OWNED);
692209746Sjkim
693209746Sjkim	if (bp->b_qindex != QUEUE_NONE) {
694209746Sjkim		KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
695209746Sjkim		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
696118611Snjl		bp->b_qindex = QUEUE_NONE;
697118611Snjl	} else {
698118611Snjl		if (BUF_REFCNT(bp) <= 1)
699151937Sjkim			panic("bremfree: removing a buffer not on a queue");
700118611Snjl	}
701118611Snjl	/*
702118611Snjl	 * If this was a delayed bremfree() we only need to remove the buffer
703118611Snjl	 * from the queue and return the stats are already done.
704118611Snjl	 */
705151937Sjkim	if (bp->b_flags & B_REMFREE) {
706118611Snjl		bp->b_flags &= ~B_REMFREE;
707118611Snjl		splx(s);
708118611Snjl		return;
709118611Snjl	}
710118611Snjl	/*
711118611Snjl	 * Fixup numfreebuffers count.  If the buffer is invalid or not
712118611Snjl	 * delayed-write, the buffer was free and we must decrement
713118611Snjl	 * numfreebuffers.
714118611Snjl	 */
715118611Snjl	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
716118611Snjl		atomic_subtract_int(&numfreebuffers, 1);
717118611Snjl	splx(s);
718118611Snjl}
719118611Snjl
720118611Snjl
721118611Snjl/*
722151937Sjkim * Get a buffer with the specified data.  Look in the cache first.  We
723118611Snjl * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
724118611Snjl * is set, the buffer is valid and we do not have to do anything ( see
725118611Snjl * getblk() ).  This is really just a special case of breadn().
726118611Snjl */
727118611Snjlint
728118611Snjlbread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
729118611Snjl    struct buf **bpp)
730118611Snjl{
731118611Snjl
732118611Snjl	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
733118611Snjl}
734118611Snjl
735118611Snjl/*
736118611Snjl * Operates like bread, but also starts asynchronous I/O on
737118611Snjl * read-ahead blocks.  We must clear BIO_ERROR and B_INVAL prior
738118611Snjl * to initiating I/O . If B_CACHE is set, the buffer is valid
739118611Snjl * and we do not have to do anything.
740118611Snjl */
741118611Snjlint
742118611Snjlbreadn(struct vnode * vp, daddr_t blkno, int size,
743118611Snjl    daddr_t * rablkno, int *rabsize,
744118611Snjl    int cnt, struct ucred * cred, struct buf **bpp)
745118611Snjl{
746118611Snjl	struct buf *bp, *rabp;
747118611Snjl	int i;
748118611Snjl	int rv = 0, readwait = 0;
749118611Snjl
750118611Snjl	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
751118611Snjl
752118611Snjl	/* if not found in cache, do some I/O */
753118611Snjl	if ((bp->b_flags & B_CACHE) == 0) {
754118611Snjl		if (curthread != PCPU_GET(idlethread))
755118611Snjl			curthread->td_proc->p_stats->p_ru.ru_inblock++;
756118611Snjl		bp->b_iocmd = BIO_READ;
757118611Snjl		bp->b_flags &= ~B_INVAL;
758118611Snjl		bp->b_ioflags &= ~BIO_ERROR;
759118611Snjl		if (bp->b_rcred == NOCRED && cred != NOCRED)
760118611Snjl			bp->b_rcred = crhold(cred);
761118611Snjl		vfs_busy_pages(bp, 0);
762202771Sjkim		bp->b_iooffset = dbtob(bp->b_blkno);
763118611Snjl		bstrategy(bp);
764118611Snjl		++readwait;
765118611Snjl	}
766217365Sjkim
767217365Sjkim	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
768217365Sjkim		if (inmem(vp, *rablkno))
769217365Sjkim			continue;
770217365Sjkim		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
771217365Sjkim
772118611Snjl		if ((rabp->b_flags & B_CACHE) == 0) {
773217365Sjkim			if (curthread != PCPU_GET(idlethread))
774217365Sjkim				curthread->td_proc->p_stats->p_ru.ru_inblock++;
775217365Sjkim			rabp->b_flags |= B_ASYNC;
776217365Sjkim			rabp->b_flags &= ~B_INVAL;
777217365Sjkim			rabp->b_ioflags &= ~BIO_ERROR;
778217365Sjkim			rabp->b_iocmd = BIO_READ;
779217365Sjkim			if (rabp->b_rcred == NOCRED && cred != NOCRED)
780217365Sjkim				rabp->b_rcred = crhold(cred);
781217365Sjkim			vfs_busy_pages(rabp, 0);
782217365Sjkim			BUF_KERNPROC(rabp);
783118611Snjl			rabp->b_iooffset = dbtob(rabp->b_blkno);
784151937Sjkim			bstrategy(rabp);
785118611Snjl		} else {
786207344Sjkim			brelse(rabp);
787207344Sjkim		}
788207344Sjkim	}
789207344Sjkim
790207344Sjkim	if (readwait) {
791207344Sjkim		rv = bufwait(bp);
792207344Sjkim	}
793207344Sjkim	return (rv);
794207344Sjkim}
795207344Sjkim
796213806Sjkim/*
797213806Sjkim * Write, release buffer on completion.  (Done by iodone
798207344Sjkim * if async).  Do not bother writing anything if the buffer
799207344Sjkim * is invalid.
800207344Sjkim *
801207344Sjkim * Note that we set B_CACHE here, indicating that buffer is
802207344Sjkim * fully valid and thus cacheable.  This is true even of NFS
803207344Sjkim * now so we set it generally.  This could be set either here
804207344Sjkim * or in biodone() since the I/O is synchronous.  We put it
805207344Sjkim * here.
806207344Sjkim */
807207344Sjkimint
808207344Sjkimbufwrite(struct buf *bp)
809213806Sjkim{
810213806Sjkim	int oldflags, s;
811207344Sjkim	struct buf *newbp;
812207344Sjkim
813207344Sjkim	if (bp->b_flags & B_INVAL) {
814207344Sjkim		brelse(bp);
815207344Sjkim		return (0);
816118611Snjl	}
817118611Snjl
818118611Snjl	oldflags = bp->b_flags;
819118611Snjl
820151937Sjkim	if (BUF_REFCNT(bp) == 0)
821118611Snjl		panic("bufwrite: buffer is not busy???");
822118611Snjl	s = splbio();
823118611Snjl	/*
824118611Snjl	 * If a background write is already in progress, delay
825118611Snjl	 * writing this block if it is asynchronous. Otherwise
826118611Snjl	 * wait for the background write to complete.
827118611Snjl	 */
828118611Snjl	BO_LOCK(bp->b_bufobj);
829118611Snjl	if (bp->b_vflags & BV_BKGRDINPROG) {
830118611Snjl		if (bp->b_flags & B_ASYNC) {
831118611Snjl			BO_UNLOCK(bp->b_bufobj);
832118611Snjl			splx(s);
833118611Snjl			bdwrite(bp);
834118611Snjl			return (0);
835118611Snjl		}
836118611Snjl		bp->b_vflags |= BV_BKGRDWAIT;
837118611Snjl		msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj), PRIBIO, "bwrbg", 0);
838118611Snjl		if (bp->b_vflags & BV_BKGRDINPROG)
839118611Snjl			panic("bufwrite: still writing");
840118611Snjl	}
841118611Snjl	BO_UNLOCK(bp->b_bufobj);
842118611Snjl
843118611Snjl	/* Mark the buffer clean */
844151937Sjkim	bundirty(bp);
845151937Sjkim
846151937Sjkim	/*
847151937Sjkim	 * If this buffer is marked for background writing and we
848118611Snjl	 * do not have to wait for it, make a copy and write the
849118611Snjl	 * copy so as to leave this buffer ready for further use.
850118611Snjl	 *
851118611Snjl	 * This optimization eats a lot of memory.  If we have a page
852118611Snjl	 * or buffer shortfall we can't do it.
853118611Snjl	 */
854151937Sjkim	if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) &&
855151937Sjkim	    (bp->b_flags & B_ASYNC) &&
856118611Snjl	    !vm_page_count_severe() &&
857118611Snjl	    !buf_dirty_count_severe()) {
858118611Snjl		KASSERT(bp->b_iodone == NULL,
859118611Snjl		    ("bufwrite: needs chained iodone (%p)", bp->b_iodone));
860118611Snjl
861118611Snjl		/* get a new block */
862118611Snjl		newbp = geteblk(bp->b_bufsize);
863118611Snjl
864118611Snjl		/*
865151937Sjkim		 * set it to be identical to the old block.  We have to
866151937Sjkim		 * set b_lblkno and BKGRDMARKER before calling bgetvp()
867151937Sjkim		 * to avoid confusing the splay tree and gbincore().
868118611Snjl		 */
869151937Sjkim		memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
870118611Snjl		newbp->b_lblkno = bp->b_lblkno;
871207344Sjkim		newbp->b_xflags |= BX_BKGRDMARKER;
872118611Snjl		BO_LOCK(bp->b_bufobj);
873118611Snjl		bp->b_vflags |= BV_BKGRDINPROG;
874167802Sjkim		bgetvp(bp->b_vp, newbp);
875167802Sjkim		BO_UNLOCK(bp->b_bufobj);
876167802Sjkim		newbp->b_bufobj = &bp->b_vp->v_bufobj;
877167802Sjkim		newbp->b_blkno = bp->b_blkno;
878167802Sjkim		newbp->b_offset = bp->b_offset;
879207344Sjkim		newbp->b_iodone = vfs_backgroundwritedone;
880118611Snjl		newbp->b_flags |= B_ASYNC;
881118611Snjl		newbp->b_flags &= ~B_INVAL;
882118611Snjl
883118611Snjl		/* move over the dependencies */
884207344Sjkim		if (LIST_FIRST(&bp->b_dep) != NULL)
885118611Snjl			buf_movedeps(bp, newbp);
886118611Snjl
887118611Snjl		/*
888118611Snjl		 * Initiate write on the copy, release the original to
889207344Sjkim		 * the B_LOCKED queue so that it cannot go away until
890118611Snjl		 * the background write completes. If not locked it could go
891118611Snjl		 * away and then be reconstituted while it was being written.
892118611Snjl		 * If the reconstituted buffer were written, we could end up
893118611Snjl		 * with two background copies being written at the same time.
894207344Sjkim		 */
895118611Snjl		bqrelse(bp);
896118611Snjl		bp = newbp;
897118611Snjl	}
898118611Snjl
899207344Sjkim	bp->b_flags &= ~B_DONE;
900118611Snjl	bp->b_ioflags &= ~BIO_ERROR;
901118611Snjl	bp->b_flags |= B_CACHE;
902118611Snjl	bp->b_iocmd = BIO_WRITE;
903118611Snjl
904207344Sjkim	bufobj_wref(bp->b_bufobj);
905118611Snjl	vfs_busy_pages(bp, 1);
906118611Snjl
907118611Snjl	/*
908118611Snjl	 * Normal bwrites pipeline writes
909207344Sjkim	 */
910118611Snjl	bp->b_runningbufspace = bp->b_bufsize;
911118611Snjl	atomic_add_int(&runningbufspace, bp->b_runningbufspace);
912118611Snjl
913207344Sjkim	if (curthread != PCPU_GET(idlethread))
914207344Sjkim		curthread->td_proc->p_stats->p_ru.ru_oublock++;
915207344Sjkim	splx(s);
916207344Sjkim	if (oldflags & B_ASYNC)
917118611Snjl		BUF_KERNPROC(bp);
918207344Sjkim	bp->b_iooffset = dbtob(bp->b_blkno);
919118611Snjl	bstrategy(bp);
920118611Snjl
921118611Snjl	if ((oldflags & B_ASYNC) == 0) {
922118611Snjl		int rtval = bufwait(bp);
923207344Sjkim		brelse(bp);
924118611Snjl		return (rtval);
925118611Snjl	} else {
926118611Snjl		/*
927118611Snjl		 * don't allow the async write to saturate the I/O
928207344Sjkim		 * system.  We will not deadlock here because
929118611Snjl		 * we are blocking waiting for I/O that is already in-progress
930118611Snjl		 * to complete. We do not block here if it is the update
931118611Snjl		 * or syncer daemon trying to clean up as that can lead
932118611Snjl		 * to deadlock.
933207344Sjkim		 */
934118611Snjl		if (curthread->td_proc != bufdaemonproc &&
935118611Snjl		    curthread->td_proc != updateproc)
936118611Snjl			waitrunningbufspace();
937118611Snjl	}
938207344Sjkim
939118611Snjl	return (0);
940118611Snjl}
941118611Snjl
942118611Snjl/*
943118611Snjl * Complete a background write started from bwrite.
944207344Sjkim */
945118611Snjlstatic void
946151937Sjkimvfs_backgroundwritedone(struct buf *bp)
947151937Sjkim{
948151937Sjkim	struct buf *origbp;
949151937Sjkim
950118611Snjl	/*
951118611Snjl	 * Find the original buffer that we are writing.
952207344Sjkim	 */
953207344Sjkim	BO_LOCK(bp->b_bufobj);
954207344Sjkim	if ((origbp = gbincore(bp->b_bufobj, bp->b_lblkno)) == NULL)
955207344Sjkim		panic("backgroundwritedone: lost buffer");
956207344Sjkim
957207344Sjkim	/*
958207344Sjkim	 * Clear the BV_BKGRDINPROG flag in the original buffer
959207344Sjkim	 * and awaken it if it is waiting for the write to complete.
960207344Sjkim	 * If BV_BKGRDINPROG is not set in the original buffer it must
961207344Sjkim	 * have been released and re-instantiated - which is not legal.
962207344Sjkim	 */
963207344Sjkim	KASSERT((origbp->b_vflags & BV_BKGRDINPROG),
964207344Sjkim	    ("backgroundwritedone: lost buffer2"));
965207344Sjkim	origbp->b_vflags &= ~BV_BKGRDINPROG;
966118611Snjl	if (origbp->b_vflags & BV_BKGRDWAIT) {
967118611Snjl		origbp->b_vflags &= ~BV_BKGRDWAIT;
968118611Snjl		wakeup(&origbp->b_xflags);
969118611Snjl	}
970118611Snjl	BO_UNLOCK(bp->b_bufobj);
971118611Snjl	/*
972118611Snjl	 * Process dependencies then return any unfinished ones.
973118611Snjl	 */
974118611Snjl	if (LIST_FIRST(&bp->b_dep) != NULL)
975118611Snjl		buf_complete(bp);
976151937Sjkim	if (LIST_FIRST(&bp->b_dep) != NULL)
977151937Sjkim		buf_movedeps(bp, origbp);
978151937Sjkim
979151937Sjkim	/*
980207344Sjkim	 * This buffer is marked B_NOCACHE, so when it is released
981207344Sjkim	 * by biodone, it will be tossed. We mark it with BIO_READ
982207344Sjkim	 * to avoid biodone doing a second bufobj_wdrop.
983207344Sjkim	 */
984151937Sjkim	bp->b_flags |= B_NOCACHE;
985151937Sjkim	bp->b_iocmd = BIO_READ;
986151937Sjkim	bp->b_flags &= ~(B_CACHE | B_DONE);
987151937Sjkim	bp->b_iodone = 0;
988151937Sjkim	bufdone(bp);
989151937Sjkim}
990151937Sjkim
991151937Sjkim/*
992151937Sjkim * Delayed write. (Buffer is marked dirty).  Do not bother writing
993151937Sjkim * anything if the buffer is marked invalid.
994151937Sjkim *
995151937Sjkim * Note that since the buffer must be completely valid, we can safely
996151937Sjkim * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
997151937Sjkim * biodone() in order to prevent getblk from writing the buffer
998151937Sjkim * out synchronously.
999207344Sjkim */
1000207344Sjkimvoid
1001207344Sjkimbdwrite(struct buf *bp)
1002207344Sjkim{
1003151937Sjkim	struct thread *td = curthread;
1004118611Snjl	struct vnode *vp;
1005118611Snjl	struct buf *nbp;
1006118611Snjl	struct bufobj *bo;
1007118611Snjl
1008118611Snjl	GIANT_REQUIRED;
1009118611Snjl
1010118611Snjl	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1011118611Snjl	KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy"));
1012118611Snjl
1013118611Snjl	if (bp->b_flags & B_INVAL) {
1014151937Sjkim		brelse(bp);
1015151937Sjkim		return;
1016151937Sjkim	}
1017151937Sjkim
1018207344Sjkim	/*
1019207344Sjkim	 * If we have too many dirty buffers, don't create any more.
1020207344Sjkim	 * If we are wildly over our limit, then force a complete
1021207344Sjkim	 * cleanup. Otherwise, just keep the situation from getting
1022151937Sjkim	 * out of control. Note that we have to avoid a recursive
1023118611Snjl	 * disaster and not try to clean up after our own cleanup!
1024118611Snjl	 */
1025118611Snjl	vp = bp->b_vp;
1026118611Snjl	bo = bp->b_bufobj;
1027118611Snjl	BO_LOCK(bo);
1028151937Sjkim	if (td->td_pflags & TDP_COWINPROGRESS) {
1029151937Sjkim		recursiveflushes++;
1030151937Sjkim	} else if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1031151937Sjkim		BO_UNLOCK(bo);
1032151937Sjkim		(void) VOP_FSYNC(vp, MNT_NOWAIT, td);
1033118611Snjl		BO_LOCK(bo);
1034118611Snjl		altbufferflushes++;
1035118611Snjl	} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1036118611Snjl		/*
1037209746Sjkim		 * Try to find a buffer to flush.
1038209746Sjkim		 */
1039209746Sjkim		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1040209746Sjkim			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1041209746Sjkim			    buf_countdeps(nbp, 0) ||
1042209746Sjkim			    BUF_LOCK(nbp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
1043209746Sjkim				continue;
1044209746Sjkim			if (bp == nbp)
1045209746Sjkim				panic("bdwrite: found ourselves");
1046209746Sjkim			BO_UNLOCK(bo);
1047209746Sjkim			if (nbp->b_flags & B_CLUSTEROK) {
1048118611Snjl				vfs_bio_awrite(nbp);
1049118611Snjl			} else {
1050				bremfree(nbp);
1051				bawrite(nbp);
1052			}
1053			BO_LOCK(bo);
1054			dirtybufferflushes++;
1055			break;
1056		}
1057	}
1058	BO_UNLOCK(bo);
1059
1060	bdirty(bp);
1061	/*
1062	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1063	 * true even of NFS now.
1064	 */
1065	bp->b_flags |= B_CACHE;
1066
1067	/*
1068	 * This bmap keeps the system from needing to do the bmap later,
1069	 * perhaps when the system is attempting to do a sync.  Since it
1070	 * is likely that the indirect block -- or whatever other datastructure
1071	 * that the filesystem needs is still in memory now, it is a good
1072	 * thing to do this.  Note also, that if the pageout daemon is
1073	 * requesting a sync -- there might not be enough memory to do
1074	 * the bmap then...  So, this is important to do.
1075	 */
1076	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1077		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1078	}
1079
1080	/*
1081	 * Set the *dirty* buffer range based upon the VM system dirty pages.
1082	 */
1083	vfs_setdirty(bp);
1084
1085	/*
1086	 * We need to do this here to satisfy the vnode_pager and the
1087	 * pageout daemon, so that it thinks that the pages have been
1088	 * "cleaned".  Note that since the pages are in a delayed write
1089	 * buffer -- the VFS layer "will" see that the pages get written
1090	 * out on the next sync, or perhaps the cluster will be completed.
1091	 */
1092	vfs_clean_pages(bp);
1093	bqrelse(bp);
1094
1095	/*
1096	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1097	 * buffers (midpoint between our recovery point and our stall
1098	 * point).
1099	 */
1100	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1101
1102	/*
1103	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1104	 * due to the softdep code.
1105	 */
1106}
1107
1108/*
1109 *	bdirty:
1110 *
1111 *	Turn buffer into delayed write request.  We must clear BIO_READ and
1112 *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1113 *	itself to properly update it in the dirty/clean lists.  We mark it
1114 *	B_DONE to ensure that any asynchronization of the buffer properly
1115 *	clears B_DONE ( else a panic will occur later ).
1116 *
1117 *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1118 *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1119 *	should only be called if the buffer is known-good.
1120 *
1121 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1122 *	count.
1123 *
1124 *	Must be called at splbio().
1125 *	The buffer must be on QUEUE_NONE.
1126 */
1127void
1128bdirty(struct buf *bp)
1129{
1130
1131	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1132	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1133	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1134	bp->b_flags &= ~(B_RELBUF);
1135	bp->b_iocmd = BIO_WRITE;
1136
1137	if ((bp->b_flags & B_DELWRI) == 0) {
1138		bp->b_flags |= B_DONE | B_DELWRI;
1139		reassignbuf(bp);
1140		atomic_add_int(&numdirtybuffers, 1);
1141		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1142	}
1143}
1144
1145/*
1146 *	bundirty:
1147 *
1148 *	Clear B_DELWRI for buffer.
1149 *
1150 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1151 *	count.
1152 *
1153 *	Must be called at splbio().
1154 *	The buffer must be on QUEUE_NONE.
1155 */
1156
1157void
1158bundirty(struct buf *bp)
1159{
1160
1161	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1162	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1163	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1164
1165	if (bp->b_flags & B_DELWRI) {
1166		bp->b_flags &= ~B_DELWRI;
1167		reassignbuf(bp);
1168		atomic_subtract_int(&numdirtybuffers, 1);
1169		numdirtywakeup(lodirtybuffers);
1170	}
1171	/*
1172	 * Since it is now being written, we can clear its deferred write flag.
1173	 */
1174	bp->b_flags &= ~B_DEFERRED;
1175}
1176
1177/*
1178 *	bawrite:
1179 *
1180 *	Asynchronous write.  Start output on a buffer, but do not wait for
1181 *	it to complete.  The buffer is released when the output completes.
1182 *
1183 *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1184 *	B_INVAL buffers.  Not us.
1185 */
1186void
1187bawrite(struct buf *bp)
1188{
1189
1190	bp->b_flags |= B_ASYNC;
1191	(void) bwrite(bp);
1192}
1193
1194/*
1195 *	bwillwrite:
1196 *
1197 *	Called prior to the locking of any vnodes when we are expecting to
1198 *	write.  We do not want to starve the buffer cache with too many
1199 *	dirty buffers so we block here.  By blocking prior to the locking
1200 *	of any vnodes we attempt to avoid the situation where a locked vnode
1201 *	prevents the various system daemons from flushing related buffers.
1202 */
1203
1204void
1205bwillwrite(void)
1206{
1207
1208	if (numdirtybuffers >= hidirtybuffers) {
1209		int s;
1210
1211		mtx_lock(&Giant);
1212		s = splbio();
1213		mtx_lock(&nblock);
1214		while (numdirtybuffers >= hidirtybuffers) {
1215			bd_wakeup(1);
1216			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1217			msleep(&needsbuffer, &nblock,
1218			    (PRIBIO + 4), "flswai", 0);
1219		}
1220		splx(s);
1221		mtx_unlock(&nblock);
1222		mtx_unlock(&Giant);
1223	}
1224}
1225
1226/*
1227 * Return true if we have too many dirty buffers.
1228 */
1229int
1230buf_dirty_count_severe(void)
1231{
1232
1233	return(numdirtybuffers >= hidirtybuffers);
1234}
1235
1236/*
1237 *	brelse:
1238 *
1239 *	Release a busy buffer and, if requested, free its resources.  The
1240 *	buffer will be stashed in the appropriate bufqueue[] allowing it
1241 *	to be accessed later as a cache entity or reused for other purposes.
1242 */
1243void
1244brelse(struct buf *bp)
1245{
1246	int s;
1247
1248	GIANT_REQUIRED;
1249
1250	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1251	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1252
1253	s = splbio();
1254
1255	if (bp->b_iocmd == BIO_WRITE &&
1256	    (bp->b_ioflags & BIO_ERROR) &&
1257	    !(bp->b_flags & B_INVAL)) {
1258		/*
1259		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1260		 * pages from being scrapped.  If B_INVAL is set then
1261		 * this case is not run and the next case is run to
1262		 * destroy the buffer.  B_INVAL can occur if the buffer
1263		 * is outside the range supported by the underlying device.
1264		 */
1265		bp->b_ioflags &= ~BIO_ERROR;
1266		bdirty(bp);
1267	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1268	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1269		/*
1270		 * Either a failed I/O or we were asked to free or not
1271		 * cache the buffer.
1272		 */
1273		bp->b_flags |= B_INVAL;
1274		if (LIST_FIRST(&bp->b_dep) != NULL)
1275			buf_deallocate(bp);
1276		if (bp->b_flags & B_DELWRI) {
1277			atomic_subtract_int(&numdirtybuffers, 1);
1278			numdirtywakeup(lodirtybuffers);
1279		}
1280		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1281		if ((bp->b_flags & B_VMIO) == 0) {
1282			if (bp->b_bufsize)
1283				allocbuf(bp, 0);
1284			if (bp->b_vp)
1285				brelvp(bp);
1286		}
1287	}
1288
1289	/*
1290	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1291	 * is called with B_DELWRI set, the underlying pages may wind up
1292	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1293	 * because pages associated with a B_DELWRI bp are marked clean.
1294	 *
1295	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1296	 * if B_DELWRI is set.
1297	 *
1298	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1299	 * on pages to return pages to the VM page queues.
1300	 */
1301	if (bp->b_flags & B_DELWRI)
1302		bp->b_flags &= ~B_RELBUF;
1303	else if (vm_page_count_severe()) {
1304		/*
1305		 * XXX This lock may not be necessary since BKGRDINPROG
1306		 * cannot be set while we hold the buf lock, it can only be
1307		 * cleared if it is already pending.
1308		 */
1309		if (bp->b_vp) {
1310			BO_LOCK(bp->b_bufobj);
1311			if (!(bp->b_vflags & BV_BKGRDINPROG))
1312				bp->b_flags |= B_RELBUF;
1313			BO_UNLOCK(bp->b_bufobj);
1314		} else
1315			bp->b_flags |= B_RELBUF;
1316	}
1317
1318	/*
1319	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1320	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1321	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1322	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1323	 *
1324	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1325	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1326	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1327	 *
1328	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1329	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1330	 * the commit state and we cannot afford to lose the buffer. If the
1331	 * buffer has a background write in progress, we need to keep it
1332	 * around to prevent it from being reconstituted and starting a second
1333	 * background write.
1334	 */
1335	if ((bp->b_flags & B_VMIO)
1336	    && !(bp->b_vp->v_mount != NULL &&
1337		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1338		 !vn_isdisk(bp->b_vp, NULL) &&
1339		 (bp->b_flags & B_DELWRI))
1340	    ) {
1341
1342		int i, j, resid;
1343		vm_page_t m;
1344		off_t foff;
1345		vm_pindex_t poff;
1346		vm_object_t obj;
1347
1348		obj = bp->b_bufobj->bo_object;
1349
1350		/*
1351		 * Get the base offset and length of the buffer.  Note that
1352		 * in the VMIO case if the buffer block size is not
1353		 * page-aligned then b_data pointer may not be page-aligned.
1354		 * But our b_pages[] array *IS* page aligned.
1355		 *
1356		 * block sizes less then DEV_BSIZE (usually 512) are not
1357		 * supported due to the page granularity bits (m->valid,
1358		 * m->dirty, etc...).
1359		 *
1360		 * See man buf(9) for more information
1361		 */
1362		resid = bp->b_bufsize;
1363		foff = bp->b_offset;
1364		VM_OBJECT_LOCK(obj);
1365		for (i = 0; i < bp->b_npages; i++) {
1366			int had_bogus = 0;
1367
1368			m = bp->b_pages[i];
1369
1370			/*
1371			 * If we hit a bogus page, fixup *all* the bogus pages
1372			 * now.
1373			 */
1374			if (m == bogus_page) {
1375				poff = OFF_TO_IDX(bp->b_offset);
1376				had_bogus = 1;
1377
1378				for (j = i; j < bp->b_npages; j++) {
1379					vm_page_t mtmp;
1380					mtmp = bp->b_pages[j];
1381					if (mtmp == bogus_page) {
1382						mtmp = vm_page_lookup(obj, poff + j);
1383						if (!mtmp) {
1384							panic("brelse: page missing\n");
1385						}
1386						bp->b_pages[j] = mtmp;
1387					}
1388				}
1389
1390				if ((bp->b_flags & B_INVAL) == 0) {
1391					pmap_qenter(
1392					    trunc_page((vm_offset_t)bp->b_data),
1393					    bp->b_pages, bp->b_npages);
1394				}
1395				m = bp->b_pages[i];
1396			}
1397			if ((bp->b_flags & B_NOCACHE) ||
1398			    (bp->b_ioflags & BIO_ERROR)) {
1399				int poffset = foff & PAGE_MASK;
1400				int presid = resid > (PAGE_SIZE - poffset) ?
1401					(PAGE_SIZE - poffset) : resid;
1402
1403				KASSERT(presid >= 0, ("brelse: extra page"));
1404				vm_page_lock_queues();
1405				vm_page_set_invalid(m, poffset, presid);
1406				vm_page_unlock_queues();
1407				if (had_bogus)
1408					printf("avoided corruption bug in bogus_page/brelse code\n");
1409			}
1410			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1411			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1412		}
1413		VM_OBJECT_UNLOCK(obj);
1414		if (bp->b_flags & (B_INVAL | B_RELBUF))
1415			vfs_vmio_release(bp);
1416
1417	} else if (bp->b_flags & B_VMIO) {
1418
1419		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1420			vfs_vmio_release(bp);
1421		}
1422
1423	}
1424
1425	if (BUF_REFCNT(bp) > 1) {
1426		/* do not release to free list */
1427		BUF_UNLOCK(bp);
1428		splx(s);
1429		return;
1430	}
1431
1432	/* enqueue */
1433	mtx_lock(&bqlock);
1434	/* Handle delayed bremfree() processing. */
1435	if (bp->b_flags & B_REMFREE)
1436		bremfreel(bp);
1437	if (bp->b_qindex != QUEUE_NONE)
1438		panic("brelse: free buffer onto another queue???");
1439
1440	/* buffers with no memory */
1441	if (bp->b_bufsize == 0) {
1442		bp->b_flags |= B_INVAL;
1443		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1444		if (bp->b_vflags & BV_BKGRDINPROG)
1445			panic("losing buffer 1");
1446		if (bp->b_kvasize) {
1447			bp->b_qindex = QUEUE_EMPTYKVA;
1448		} else {
1449			bp->b_qindex = QUEUE_EMPTY;
1450		}
1451		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1452	/* buffers with junk contents */
1453	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1454	    (bp->b_ioflags & BIO_ERROR)) {
1455		bp->b_flags |= B_INVAL;
1456		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1457		if (bp->b_vflags & BV_BKGRDINPROG)
1458			panic("losing buffer 2");
1459		bp->b_qindex = QUEUE_CLEAN;
1460		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1461	/* remaining buffers */
1462	} else {
1463		if (bp->b_flags & B_DELWRI)
1464			bp->b_qindex = QUEUE_DIRTY;
1465		else
1466			bp->b_qindex = QUEUE_CLEAN;
1467		if (bp->b_flags & B_AGE)
1468			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1469		else
1470			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1471	}
1472	mtx_unlock(&bqlock);
1473
1474	/*
1475	 * If B_INVAL and B_DELWRI is set, clear B_DELWRI.  We have already
1476	 * placed the buffer on the correct queue.  We must also disassociate
1477	 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1478	 * find it.
1479	 */
1480	if (bp->b_flags & B_INVAL) {
1481		if (bp->b_flags & B_DELWRI)
1482			bundirty(bp);
1483		if (bp->b_vp)
1484			brelvp(bp);
1485	}
1486
1487	/*
1488	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1489	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1490	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1491	 * if B_INVAL is set ).
1492	 */
1493
1494	if (!(bp->b_flags & B_DELWRI))
1495		bufcountwakeup();
1496
1497	/*
1498	 * Something we can maybe free or reuse
1499	 */
1500	if (bp->b_bufsize || bp->b_kvasize)
1501		bufspacewakeup();
1502
1503	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1504	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1505		panic("brelse: not dirty");
1506	/* unlock */
1507	BUF_UNLOCK(bp);
1508	splx(s);
1509}
1510
1511/*
1512 * Release a buffer back to the appropriate queue but do not try to free
1513 * it.  The buffer is expected to be used again soon.
1514 *
1515 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1516 * biodone() to requeue an async I/O on completion.  It is also used when
1517 * known good buffers need to be requeued but we think we may need the data
1518 * again soon.
1519 *
1520 * XXX we should be able to leave the B_RELBUF hint set on completion.
1521 */
1522void
1523bqrelse(struct buf *bp)
1524{
1525	int s;
1526
1527	s = splbio();
1528
1529	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1530	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1531
1532	if (BUF_REFCNT(bp) > 1) {
1533		/* do not release to free list */
1534		BUF_UNLOCK(bp);
1535		splx(s);
1536		return;
1537	}
1538	mtx_lock(&bqlock);
1539	/* Handle delayed bremfree() processing. */
1540	if (bp->b_flags & B_REMFREE)
1541		bremfreel(bp);
1542	if (bp->b_qindex != QUEUE_NONE)
1543		panic("bqrelse: free buffer onto another queue???");
1544	/* buffers with stale but valid contents */
1545	if (bp->b_flags & B_DELWRI) {
1546		bp->b_qindex = QUEUE_DIRTY;
1547		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1548	} else {
1549		/*
1550		 * XXX This lock may not be necessary since BKGRDINPROG
1551		 * cannot be set while we hold the buf lock, it can only be
1552		 * cleared if it is already pending.
1553		 */
1554		BO_LOCK(bp->b_bufobj);
1555		if (!vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) {
1556			BO_UNLOCK(bp->b_bufobj);
1557			bp->b_qindex = QUEUE_CLEAN;
1558			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1559			    b_freelist);
1560		} else {
1561			/*
1562			 * We are too low on memory, we have to try to free
1563			 * the buffer (most importantly: the wired pages
1564			 * making up its backing store) *now*.
1565			 */
1566			BO_UNLOCK(bp->b_bufobj);
1567			mtx_unlock(&bqlock);
1568			splx(s);
1569			brelse(bp);
1570			return;
1571		}
1572	}
1573	mtx_unlock(&bqlock);
1574
1575	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1576		bufcountwakeup();
1577
1578	/*
1579	 * Something we can maybe free or reuse.
1580	 */
1581	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1582		bufspacewakeup();
1583
1584	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1585	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1586		panic("bqrelse: not dirty");
1587	/* unlock */
1588	BUF_UNLOCK(bp);
1589	splx(s);
1590}
1591
1592/* Give pages used by the bp back to the VM system (where possible) */
1593static void
1594vfs_vmio_release(struct buf *bp)
1595{
1596	int i;
1597	vm_page_t m;
1598
1599	GIANT_REQUIRED;
1600	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1601	vm_page_lock_queues();
1602	for (i = 0; i < bp->b_npages; i++) {
1603		m = bp->b_pages[i];
1604		bp->b_pages[i] = NULL;
1605		/*
1606		 * In order to keep page LRU ordering consistent, put
1607		 * everything on the inactive queue.
1608		 */
1609		vm_page_unwire(m, 0);
1610		/*
1611		 * We don't mess with busy pages, it is
1612		 * the responsibility of the process that
1613		 * busied the pages to deal with them.
1614		 */
1615		if ((m->flags & PG_BUSY) || (m->busy != 0))
1616			continue;
1617
1618		if (m->wire_count == 0) {
1619			/*
1620			 * Might as well free the page if we can and it has
1621			 * no valid data.  We also free the page if the
1622			 * buffer was used for direct I/O
1623			 */
1624			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1625			    m->hold_count == 0) {
1626				pmap_remove_all(m);
1627				vm_page_free(m);
1628			} else if (bp->b_flags & B_DIRECT) {
1629				vm_page_try_to_free(m);
1630			} else if (vm_page_count_severe()) {
1631				vm_page_try_to_cache(m);
1632			}
1633		}
1634	}
1635	vm_page_unlock_queues();
1636	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1637	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1638
1639	if (bp->b_bufsize) {
1640		bufspacewakeup();
1641		bp->b_bufsize = 0;
1642	}
1643	bp->b_npages = 0;
1644	bp->b_flags &= ~B_VMIO;
1645	if (bp->b_vp)
1646		brelvp(bp);
1647}
1648
1649/*
1650 * Check to see if a block at a particular lbn is available for a clustered
1651 * write.
1652 */
1653static int
1654vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1655{
1656	struct buf *bpa;
1657	int match;
1658
1659	match = 0;
1660
1661	/* If the buf isn't in core skip it */
1662	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1663		return (0);
1664
1665	/* If the buf is busy we don't want to wait for it */
1666	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1667		return (0);
1668
1669	/* Only cluster with valid clusterable delayed write buffers */
1670	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1671	    (B_DELWRI | B_CLUSTEROK))
1672		goto done;
1673
1674	if (bpa->b_bufsize != size)
1675		goto done;
1676
1677	/*
1678	 * Check to see if it is in the expected place on disk and that the
1679	 * block has been mapped.
1680	 */
1681	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1682		match = 1;
1683done:
1684	BUF_UNLOCK(bpa);
1685	return (match);
1686}
1687
1688/*
1689 *	vfs_bio_awrite:
1690 *
1691 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1692 *	This is much better then the old way of writing only one buffer at
1693 *	a time.  Note that we may not be presented with the buffers in the
1694 *	correct order, so we search for the cluster in both directions.
1695 */
1696int
1697vfs_bio_awrite(struct buf *bp)
1698{
1699	int i;
1700	int j;
1701	daddr_t lblkno = bp->b_lblkno;
1702	struct vnode *vp = bp->b_vp;
1703	int s;
1704	int ncl;
1705	int nwritten;
1706	int size;
1707	int maxcl;
1708
1709	s = splbio();
1710	/*
1711	 * right now we support clustered writing only to regular files.  If
1712	 * we find a clusterable block we could be in the middle of a cluster
1713	 * rather then at the beginning.
1714	 */
1715	if ((vp->v_type == VREG) &&
1716	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1717	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1718
1719		size = vp->v_mount->mnt_stat.f_iosize;
1720		maxcl = MAXPHYS / size;
1721
1722		VI_LOCK(vp);
1723		for (i = 1; i < maxcl; i++)
1724			if (vfs_bio_clcheck(vp, size, lblkno + i,
1725			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1726				break;
1727
1728		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1729			if (vfs_bio_clcheck(vp, size, lblkno - j,
1730			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1731				break;
1732
1733		VI_UNLOCK(vp);
1734		--j;
1735		ncl = i + j;
1736		/*
1737		 * this is a possible cluster write
1738		 */
1739		if (ncl != 1) {
1740			BUF_UNLOCK(bp);
1741			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1742			splx(s);
1743			return nwritten;
1744		}
1745	}
1746
1747	bremfree(bp);
1748	bp->b_flags |= B_ASYNC;
1749
1750	splx(s);
1751	/*
1752	 * default (old) behavior, writing out only one block
1753	 *
1754	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1755	 */
1756	nwritten = bp->b_bufsize;
1757	(void) bwrite(bp);
1758
1759	return nwritten;
1760}
1761
1762/*
1763 *	getnewbuf:
1764 *
1765 *	Find and initialize a new buffer header, freeing up existing buffers
1766 *	in the bufqueues as necessary.  The new buffer is returned locked.
1767 *
1768 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1769 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1770 *
1771 *	We block if:
1772 *		We have insufficient buffer headers
1773 *		We have insufficient buffer space
1774 *		buffer_map is too fragmented ( space reservation fails )
1775 *		If we have to flush dirty buffers ( but we try to avoid this )
1776 *
1777 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1778 *	Instead we ask the buf daemon to do it for us.  We attempt to
1779 *	avoid piecemeal wakeups of the pageout daemon.
1780 */
1781
1782static struct buf *
1783getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1784{
1785	struct buf *bp;
1786	struct buf *nbp;
1787	int defrag = 0;
1788	int nqindex;
1789	static int flushingbufs;
1790
1791	GIANT_REQUIRED;
1792
1793	/*
1794	 * We can't afford to block since we might be holding a vnode lock,
1795	 * which may prevent system daemons from running.  We deal with
1796	 * low-memory situations by proactively returning memory and running
1797	 * async I/O rather then sync I/O.
1798	 */
1799
1800	atomic_add_int(&getnewbufcalls, 1);
1801	atomic_subtract_int(&getnewbufrestarts, 1);
1802restart:
1803	atomic_add_int(&getnewbufrestarts, 1);
1804
1805	/*
1806	 * Setup for scan.  If we do not have enough free buffers,
1807	 * we setup a degenerate case that immediately fails.  Note
1808	 * that if we are specially marked process, we are allowed to
1809	 * dip into our reserves.
1810	 *
1811	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1812	 *
1813	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1814	 * However, there are a number of cases (defragging, reusing, ...)
1815	 * where we cannot backup.
1816	 */
1817	mtx_lock(&bqlock);
1818	nqindex = QUEUE_EMPTYKVA;
1819	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1820
1821	if (nbp == NULL) {
1822		/*
1823		 * If no EMPTYKVA buffers and we are either
1824		 * defragging or reusing, locate a CLEAN buffer
1825		 * to free or reuse.  If bufspace useage is low
1826		 * skip this step so we can allocate a new buffer.
1827		 */
1828		if (defrag || bufspace >= lobufspace) {
1829			nqindex = QUEUE_CLEAN;
1830			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1831		}
1832
1833		/*
1834		 * If we could not find or were not allowed to reuse a
1835		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1836		 * buffer.  We can only use an EMPTY buffer if allocating
1837		 * its KVA would not otherwise run us out of buffer space.
1838		 */
1839		if (nbp == NULL && defrag == 0 &&
1840		    bufspace + maxsize < hibufspace) {
1841			nqindex = QUEUE_EMPTY;
1842			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1843		}
1844	}
1845
1846	/*
1847	 * Run scan, possibly freeing data and/or kva mappings on the fly
1848	 * depending.
1849	 */
1850
1851	while ((bp = nbp) != NULL) {
1852		int qindex = nqindex;
1853
1854		/*
1855		 * Calculate next bp ( we can only use it if we do not block
1856		 * or do other fancy things ).
1857		 */
1858		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1859			switch(qindex) {
1860			case QUEUE_EMPTY:
1861				nqindex = QUEUE_EMPTYKVA;
1862				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1863					break;
1864				/* FALLTHROUGH */
1865			case QUEUE_EMPTYKVA:
1866				nqindex = QUEUE_CLEAN;
1867				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1868					break;
1869				/* FALLTHROUGH */
1870			case QUEUE_CLEAN:
1871				/*
1872				 * nbp is NULL.
1873				 */
1874				break;
1875			}
1876		}
1877		if (bp->b_vp) {
1878			BO_LOCK(bp->b_bufobj);
1879			if (bp->b_vflags & BV_BKGRDINPROG) {
1880				BO_UNLOCK(bp->b_bufobj);
1881				continue;
1882			}
1883			BO_UNLOCK(bp->b_bufobj);
1884		}
1885
1886		/*
1887		 * If we are defragging then we need a buffer with
1888		 * b_kvasize != 0.  XXX this situation should no longer
1889		 * occur, if defrag is non-zero the buffer's b_kvasize
1890		 * should also be non-zero at this point.  XXX
1891		 */
1892		if (defrag && bp->b_kvasize == 0) {
1893			printf("Warning: defrag empty buffer %p\n", bp);
1894			continue;
1895		}
1896
1897		/*
1898		 * Start freeing the bp.  This is somewhat involved.  nbp
1899		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1900		 */
1901		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1902			continue;
1903		/*
1904		 * Sanity Checks
1905		 */
1906		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1907
1908		/*
1909		 * Note: we no longer distinguish between VMIO and non-VMIO
1910		 * buffers.
1911		 */
1912
1913		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1914
1915		bremfreel(bp);
1916		mtx_unlock(&bqlock);
1917
1918		if (qindex == QUEUE_CLEAN) {
1919			if (bp->b_flags & B_VMIO) {
1920				bp->b_flags &= ~B_ASYNC;
1921				vfs_vmio_release(bp);
1922			}
1923			if (bp->b_vp)
1924				brelvp(bp);
1925		}
1926
1927		/*
1928		 * NOTE:  nbp is now entirely invalid.  We can only restart
1929		 * the scan from this point on.
1930		 *
1931		 * Get the rest of the buffer freed up.  b_kva* is still
1932		 * valid after this operation.
1933		 */
1934
1935		if (bp->b_rcred != NOCRED) {
1936			crfree(bp->b_rcred);
1937			bp->b_rcred = NOCRED;
1938		}
1939		if (bp->b_wcred != NOCRED) {
1940			crfree(bp->b_wcred);
1941			bp->b_wcred = NOCRED;
1942		}
1943		if (LIST_FIRST(&bp->b_dep) != NULL)
1944			buf_deallocate(bp);
1945		if (bp->b_vflags & BV_BKGRDINPROG)
1946			panic("losing buffer 3");
1947
1948		if (bp->b_bufsize)
1949			allocbuf(bp, 0);
1950
1951		bp->b_flags = 0;
1952		bp->b_ioflags = 0;
1953		bp->b_xflags = 0;
1954		bp->b_vflags = 0;
1955		bp->b_vp = NULL;
1956		bp->b_blkno = bp->b_lblkno = 0;
1957		bp->b_offset = NOOFFSET;
1958		bp->b_iodone = 0;
1959		bp->b_error = 0;
1960		bp->b_resid = 0;
1961		bp->b_bcount = 0;
1962		bp->b_npages = 0;
1963		bp->b_dirtyoff = bp->b_dirtyend = 0;
1964		bp->b_bufobj = NULL;
1965
1966		LIST_INIT(&bp->b_dep);
1967
1968		/*
1969		 * If we are defragging then free the buffer.
1970		 */
1971		if (defrag) {
1972			bp->b_flags |= B_INVAL;
1973			bfreekva(bp);
1974			brelse(bp);
1975			defrag = 0;
1976			goto restart;
1977		}
1978
1979		/*
1980		 * If we are overcomitted then recover the buffer and its
1981		 * KVM space.  This occurs in rare situations when multiple
1982		 * processes are blocked in getnewbuf() or allocbuf().
1983		 */
1984		if (bufspace >= hibufspace)
1985			flushingbufs = 1;
1986		if (flushingbufs && bp->b_kvasize != 0) {
1987			bp->b_flags |= B_INVAL;
1988			bfreekva(bp);
1989			brelse(bp);
1990			goto restart;
1991		}
1992		if (bufspace < lobufspace)
1993			flushingbufs = 0;
1994		break;
1995	}
1996
1997	/*
1998	 * If we exhausted our list, sleep as appropriate.  We may have to
1999	 * wakeup various daemons and write out some dirty buffers.
2000	 *
2001	 * Generally we are sleeping due to insufficient buffer space.
2002	 */
2003
2004	if (bp == NULL) {
2005		int flags;
2006		char *waitmsg;
2007
2008		mtx_unlock(&bqlock);
2009		if (defrag) {
2010			flags = VFS_BIO_NEED_BUFSPACE;
2011			waitmsg = "nbufkv";
2012		} else if (bufspace >= hibufspace) {
2013			waitmsg = "nbufbs";
2014			flags = VFS_BIO_NEED_BUFSPACE;
2015		} else {
2016			waitmsg = "newbuf";
2017			flags = VFS_BIO_NEED_ANY;
2018		}
2019
2020		bd_speedup();	/* heeeelp */
2021
2022		mtx_lock(&nblock);
2023		needsbuffer |= flags;
2024		while (needsbuffer & flags) {
2025			if (msleep(&needsbuffer, &nblock,
2026			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2027				mtx_unlock(&nblock);
2028				return (NULL);
2029			}
2030		}
2031		mtx_unlock(&nblock);
2032	} else {
2033		/*
2034		 * We finally have a valid bp.  We aren't quite out of the
2035		 * woods, we still have to reserve kva space.  In order
2036		 * to keep fragmentation sane we only allocate kva in
2037		 * BKVASIZE chunks.
2038		 */
2039		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2040
2041		if (maxsize != bp->b_kvasize) {
2042			vm_offset_t addr = 0;
2043
2044			bfreekva(bp);
2045
2046			if (vm_map_findspace(buffer_map,
2047				vm_map_min(buffer_map), maxsize, &addr)) {
2048				/*
2049				 * Uh oh.  Buffer map is to fragmented.  We
2050				 * must defragment the map.
2051				 */
2052				atomic_add_int(&bufdefragcnt, 1);
2053				defrag = 1;
2054				bp->b_flags |= B_INVAL;
2055				brelse(bp);
2056				goto restart;
2057			}
2058			if (addr) {
2059				vm_map_insert(buffer_map, NULL, 0,
2060					addr, addr + maxsize,
2061					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2062
2063				bp->b_kvabase = (caddr_t) addr;
2064				bp->b_kvasize = maxsize;
2065				atomic_add_int(&bufspace, bp->b_kvasize);
2066				atomic_add_int(&bufreusecnt, 1);
2067			}
2068		}
2069		bp->b_saveaddr = bp->b_kvabase;
2070		bp->b_data = bp->b_saveaddr;
2071	}
2072	return(bp);
2073}
2074
2075/*
2076 *	buf_daemon:
2077 *
2078 *	buffer flushing daemon.  Buffers are normally flushed by the
2079 *	update daemon but if it cannot keep up this process starts to
2080 *	take the load in an attempt to prevent getnewbuf() from blocking.
2081 */
2082
2083static struct kproc_desc buf_kp = {
2084	"bufdaemon",
2085	buf_daemon,
2086	&bufdaemonproc
2087};
2088SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2089
2090static void
2091buf_daemon()
2092{
2093	int s;
2094
2095	mtx_lock(&Giant);
2096
2097	/*
2098	 * This process needs to be suspended prior to shutdown sync.
2099	 */
2100	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2101	    SHUTDOWN_PRI_LAST);
2102
2103	/*
2104	 * This process is allowed to take the buffer cache to the limit
2105	 */
2106	s = splbio();
2107	mtx_lock(&bdlock);
2108
2109	for (;;) {
2110		bd_request = 0;
2111		mtx_unlock(&bdlock);
2112
2113		kthread_suspend_check(bufdaemonproc);
2114
2115		/*
2116		 * Do the flush.  Limit the amount of in-transit I/O we
2117		 * allow to build up, otherwise we would completely saturate
2118		 * the I/O system.  Wakeup any waiting processes before we
2119		 * normally would so they can run in parallel with our drain.
2120		 */
2121		while (numdirtybuffers > lodirtybuffers) {
2122			if (flushbufqueues(0) == 0) {
2123				/*
2124				 * Could not find any buffers without rollback
2125				 * dependencies, so just write the first one
2126				 * in the hopes of eventually making progress.
2127				 */
2128				flushbufqueues(1);
2129				break;
2130			}
2131			waitrunningbufspace();
2132			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2133		}
2134
2135		/*
2136		 * Only clear bd_request if we have reached our low water
2137		 * mark.  The buf_daemon normally waits 1 second and
2138		 * then incrementally flushes any dirty buffers that have
2139		 * built up, within reason.
2140		 *
2141		 * If we were unable to hit our low water mark and couldn't
2142		 * find any flushable buffers, we sleep half a second.
2143		 * Otherwise we loop immediately.
2144		 */
2145		mtx_lock(&bdlock);
2146		if (numdirtybuffers <= lodirtybuffers) {
2147			/*
2148			 * We reached our low water mark, reset the
2149			 * request and sleep until we are needed again.
2150			 * The sleep is just so the suspend code works.
2151			 */
2152			bd_request = 0;
2153			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2154		} else {
2155			/*
2156			 * We couldn't find any flushable dirty buffers but
2157			 * still have too many dirty buffers, we
2158			 * have to sleep and try again.  (rare)
2159			 */
2160			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2161		}
2162	}
2163}
2164
2165/*
2166 *	flushbufqueues:
2167 *
2168 *	Try to flush a buffer in the dirty queue.  We must be careful to
2169 *	free up B_INVAL buffers instead of write them, which NFS is
2170 *	particularly sensitive to.
2171 */
2172int flushwithdeps = 0;
2173SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2174    0, "Number of buffers flushed with dependecies that require rollbacks");
2175
2176static int
2177flushbufqueues(int flushdeps)
2178{
2179	struct thread *td = curthread;
2180	struct vnode *vp;
2181	struct mount *mp;
2182	struct buf *bp;
2183	int hasdeps;
2184
2185	mtx_lock(&bqlock);
2186	TAILQ_FOREACH(bp, &bufqueues[QUEUE_DIRTY], b_freelist) {
2187		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2188			continue;
2189		KASSERT((bp->b_flags & B_DELWRI),
2190		    ("unexpected clean buffer %p", bp));
2191		BO_LOCK(bp->b_bufobj);
2192		if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
2193			BO_UNLOCK(bp->b_bufobj);
2194			BUF_UNLOCK(bp);
2195			continue;
2196		}
2197		BO_UNLOCK(bp->b_bufobj);
2198		if (bp->b_flags & B_INVAL) {
2199			bremfreel(bp);
2200			mtx_unlock(&bqlock);
2201			brelse(bp);
2202			return (1);
2203		}
2204
2205		if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2206			if (flushdeps == 0) {
2207				BUF_UNLOCK(bp);
2208				continue;
2209			}
2210			hasdeps = 1;
2211		} else
2212			hasdeps = 0;
2213		/*
2214		 * We must hold the lock on a vnode before writing
2215		 * one of its buffers. Otherwise we may confuse, or
2216		 * in the case of a snapshot vnode, deadlock the
2217		 * system.
2218		 *
2219		 * The lock order here is the reverse of the normal
2220		 * of vnode followed by buf lock.  This is ok because
2221		 * the NOWAIT will prevent deadlock.
2222		 */
2223		vp = bp->b_vp;
2224		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2225			BUF_UNLOCK(bp);
2226			continue;
2227		}
2228		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2229			mtx_unlock(&bqlock);
2230			vfs_bio_awrite(bp);
2231			vn_finished_write(mp);
2232			VOP_UNLOCK(vp, 0, td);
2233			flushwithdeps += hasdeps;
2234			return (1);
2235		}
2236		vn_finished_write(mp);
2237		BUF_UNLOCK(bp);
2238	}
2239	mtx_unlock(&bqlock);
2240	return (0);
2241}
2242
2243/*
2244 * Check to see if a block is currently memory resident.
2245 */
2246struct buf *
2247incore(struct bufobj *bo, daddr_t blkno)
2248{
2249	struct buf *bp;
2250
2251	int s = splbio();
2252	BO_LOCK(bo);
2253	bp = gbincore(bo, blkno);
2254	BO_UNLOCK(bo);
2255	splx(s);
2256	return (bp);
2257}
2258
2259/*
2260 * Returns true if no I/O is needed to access the
2261 * associated VM object.  This is like incore except
2262 * it also hunts around in the VM system for the data.
2263 */
2264
2265static int
2266inmem(struct vnode * vp, daddr_t blkno)
2267{
2268	vm_object_t obj;
2269	vm_offset_t toff, tinc, size;
2270	vm_page_t m;
2271	vm_ooffset_t off;
2272
2273	GIANT_REQUIRED;
2274	ASSERT_VOP_LOCKED(vp, "inmem");
2275
2276	if (incore(&vp->v_bufobj, blkno))
2277		return 1;
2278	if (vp->v_mount == NULL)
2279		return 0;
2280	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_vflag & VV_OBJBUF) == 0)
2281		return 0;
2282
2283	size = PAGE_SIZE;
2284	if (size > vp->v_mount->mnt_stat.f_iosize)
2285		size = vp->v_mount->mnt_stat.f_iosize;
2286	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2287
2288	VM_OBJECT_LOCK(obj);
2289	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2290		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2291		if (!m)
2292			goto notinmem;
2293		tinc = size;
2294		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2295			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2296		if (vm_page_is_valid(m,
2297		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2298			goto notinmem;
2299	}
2300	VM_OBJECT_UNLOCK(obj);
2301	return 1;
2302
2303notinmem:
2304	VM_OBJECT_UNLOCK(obj);
2305	return (0);
2306}
2307
2308/*
2309 *	vfs_setdirty:
2310 *
2311 *	Sets the dirty range for a buffer based on the status of the dirty
2312 *	bits in the pages comprising the buffer.
2313 *
2314 *	The range is limited to the size of the buffer.
2315 *
2316 *	This routine is primarily used by NFS, but is generalized for the
2317 *	B_VMIO case.
2318 */
2319static void
2320vfs_setdirty(struct buf *bp)
2321{
2322	int i;
2323	vm_object_t object;
2324
2325	GIANT_REQUIRED;
2326	/*
2327	 * Degenerate case - empty buffer
2328	 */
2329
2330	if (bp->b_bufsize == 0)
2331		return;
2332
2333	/*
2334	 * We qualify the scan for modified pages on whether the
2335	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2336	 * is not cleared simply by protecting pages off.
2337	 */
2338
2339	if ((bp->b_flags & B_VMIO) == 0)
2340		return;
2341
2342	object = bp->b_pages[0]->object;
2343	VM_OBJECT_LOCK(object);
2344	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2345		printf("Warning: object %p writeable but not mightbedirty\n", object);
2346	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2347		printf("Warning: object %p mightbedirty but not writeable\n", object);
2348
2349	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2350		vm_offset_t boffset;
2351		vm_offset_t eoffset;
2352
2353		vm_page_lock_queues();
2354		/*
2355		 * test the pages to see if they have been modified directly
2356		 * by users through the VM system.
2357		 */
2358		for (i = 0; i < bp->b_npages; i++)
2359			vm_page_test_dirty(bp->b_pages[i]);
2360
2361		/*
2362		 * Calculate the encompassing dirty range, boffset and eoffset,
2363		 * (eoffset - boffset) bytes.
2364		 */
2365
2366		for (i = 0; i < bp->b_npages; i++) {
2367			if (bp->b_pages[i]->dirty)
2368				break;
2369		}
2370		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2371
2372		for (i = bp->b_npages - 1; i >= 0; --i) {
2373			if (bp->b_pages[i]->dirty) {
2374				break;
2375			}
2376		}
2377		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2378
2379		vm_page_unlock_queues();
2380		/*
2381		 * Fit it to the buffer.
2382		 */
2383
2384		if (eoffset > bp->b_bcount)
2385			eoffset = bp->b_bcount;
2386
2387		/*
2388		 * If we have a good dirty range, merge with the existing
2389		 * dirty range.
2390		 */
2391
2392		if (boffset < eoffset) {
2393			if (bp->b_dirtyoff > boffset)
2394				bp->b_dirtyoff = boffset;
2395			if (bp->b_dirtyend < eoffset)
2396				bp->b_dirtyend = eoffset;
2397		}
2398	}
2399	VM_OBJECT_UNLOCK(object);
2400}
2401
2402/*
2403 *	getblk:
2404 *
2405 *	Get a block given a specified block and offset into a file/device.
2406 *	The buffers B_DONE bit will be cleared on return, making it almost
2407 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2408 *	return.  The caller should clear B_INVAL prior to initiating a
2409 *	READ.
2410 *
2411 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2412 *	an existing buffer.
2413 *
2414 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2415 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2416 *	and then cleared based on the backing VM.  If the previous buffer is
2417 *	non-0-sized but invalid, B_CACHE will be cleared.
2418 *
2419 *	If getblk() must create a new buffer, the new buffer is returned with
2420 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2421 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2422 *	backing VM.
2423 *
2424 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2425 *	B_CACHE bit is clear.
2426 *
2427 *	What this means, basically, is that the caller should use B_CACHE to
2428 *	determine whether the buffer is fully valid or not and should clear
2429 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2430 *	the buffer by loading its data area with something, the caller needs
2431 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2432 *	the caller should set B_CACHE ( as an optimization ), else the caller
2433 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2434 *	a write attempt or if it was a successfull read.  If the caller
2435 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2436 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2437 */
2438struct buf *
2439getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2440    int flags)
2441{
2442	struct buf *bp;
2443	struct bufobj *bo;
2444	int s;
2445	int error;
2446	ASSERT_VOP_LOCKED(vp, "getblk");
2447	struct vm_object *vmo;
2448
2449	if (size > MAXBSIZE)
2450		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2451
2452	bo = &vp->v_bufobj;
2453	s = splbio();
2454loop:
2455	/*
2456	 * Block if we are low on buffers.   Certain processes are allowed
2457	 * to completely exhaust the buffer cache.
2458         *
2459         * If this check ever becomes a bottleneck it may be better to
2460         * move it into the else, when gbincore() fails.  At the moment
2461         * it isn't a problem.
2462	 *
2463	 * XXX remove if 0 sections (clean this up after its proven)
2464         */
2465	if (numfreebuffers == 0) {
2466		if (curthread == PCPU_GET(idlethread))
2467			return NULL;
2468		mtx_lock(&nblock);
2469		needsbuffer |= VFS_BIO_NEED_ANY;
2470		mtx_unlock(&nblock);
2471	}
2472
2473	VI_LOCK(vp);
2474	bp = gbincore(bo, blkno);
2475	if (bp != NULL) {
2476		int lockflags;
2477		/*
2478		 * Buffer is in-core.  If the buffer is not busy, it must
2479		 * be on a queue.
2480		 */
2481		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2482
2483		if (flags & GB_LOCK_NOWAIT)
2484			lockflags |= LK_NOWAIT;
2485
2486		error = BUF_TIMELOCK(bp, lockflags,
2487		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2488
2489		/*
2490		 * If we slept and got the lock we have to restart in case
2491		 * the buffer changed identities.
2492		 */
2493		if (error == ENOLCK)
2494			goto loop;
2495		/* We timed out or were interrupted. */
2496		else if (error)
2497			return (NULL);
2498
2499		/*
2500		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2501		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2502		 * and for a VMIO buffer B_CACHE is adjusted according to the
2503		 * backing VM cache.
2504		 */
2505		if (bp->b_flags & B_INVAL)
2506			bp->b_flags &= ~B_CACHE;
2507		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2508			bp->b_flags |= B_CACHE;
2509		bremfree(bp);
2510
2511		/*
2512		 * check for size inconsistancies for non-VMIO case.
2513		 */
2514
2515		if (bp->b_bcount != size) {
2516			if ((bp->b_flags & B_VMIO) == 0 ||
2517			    (size > bp->b_kvasize)) {
2518				if (bp->b_flags & B_DELWRI) {
2519					bp->b_flags |= B_NOCACHE;
2520					bwrite(bp);
2521				} else {
2522					if ((bp->b_flags & B_VMIO) &&
2523					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2524						bp->b_flags |= B_RELBUF;
2525						brelse(bp);
2526					} else {
2527						bp->b_flags |= B_NOCACHE;
2528						bwrite(bp);
2529					}
2530				}
2531				goto loop;
2532			}
2533		}
2534
2535		/*
2536		 * If the size is inconsistant in the VMIO case, we can resize
2537		 * the buffer.  This might lead to B_CACHE getting set or
2538		 * cleared.  If the size has not changed, B_CACHE remains
2539		 * unchanged from its previous state.
2540		 */
2541
2542		if (bp->b_bcount != size)
2543			allocbuf(bp, size);
2544
2545		KASSERT(bp->b_offset != NOOFFSET,
2546		    ("getblk: no buffer offset"));
2547
2548		/*
2549		 * A buffer with B_DELWRI set and B_CACHE clear must
2550		 * be committed before we can return the buffer in
2551		 * order to prevent the caller from issuing a read
2552		 * ( due to B_CACHE not being set ) and overwriting
2553		 * it.
2554		 *
2555		 * Most callers, including NFS and FFS, need this to
2556		 * operate properly either because they assume they
2557		 * can issue a read if B_CACHE is not set, or because
2558		 * ( for example ) an uncached B_DELWRI might loop due
2559		 * to softupdates re-dirtying the buffer.  In the latter
2560		 * case, B_CACHE is set after the first write completes,
2561		 * preventing further loops.
2562		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2563		 * above while extending the buffer, we cannot allow the
2564		 * buffer to remain with B_CACHE set after the write
2565		 * completes or it will represent a corrupt state.  To
2566		 * deal with this we set B_NOCACHE to scrap the buffer
2567		 * after the write.
2568		 *
2569		 * We might be able to do something fancy, like setting
2570		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2571		 * so the below call doesn't set B_CACHE, but that gets real
2572		 * confusing.  This is much easier.
2573		 */
2574
2575		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2576			bp->b_flags |= B_NOCACHE;
2577			bwrite(bp);
2578			goto loop;
2579		}
2580
2581		splx(s);
2582		bp->b_flags &= ~B_DONE;
2583	} else {
2584		int bsize, maxsize, vmio;
2585		off_t offset;
2586
2587		/*
2588		 * Buffer is not in-core, create new buffer.  The buffer
2589		 * returned by getnewbuf() is locked.  Note that the returned
2590		 * buffer is also considered valid (not marked B_INVAL).
2591		 */
2592		VI_UNLOCK(vp);
2593		/*
2594		 * If the user does not want us to create the buffer, bail out
2595		 * here.
2596		 */
2597		if (flags & GB_NOCREAT) {
2598			splx(s);
2599			return NULL;
2600		}
2601
2602		bsize = bo->bo_bsize;
2603		offset = blkno * bsize;
2604		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) &&
2605		    (vp->v_vflag & VV_OBJBUF);
2606		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2607		maxsize = imax(maxsize, bsize);
2608
2609		bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2610		if (bp == NULL) {
2611			if (slpflag || slptimeo) {
2612				splx(s);
2613				return NULL;
2614			}
2615			goto loop;
2616		}
2617
2618		/*
2619		 * This code is used to make sure that a buffer is not
2620		 * created while the getnewbuf routine is blocked.
2621		 * This can be a problem whether the vnode is locked or not.
2622		 * If the buffer is created out from under us, we have to
2623		 * throw away the one we just created.  There is now window
2624		 * race because we are safely running at splbio() from the
2625		 * point of the duplicate buffer creation through to here,
2626		 * and we've locked the buffer.
2627		 *
2628		 * Note: this must occur before we associate the buffer
2629		 * with the vp especially considering limitations in
2630		 * the splay tree implementation when dealing with duplicate
2631		 * lblkno's.
2632		 */
2633		BO_LOCK(bo);
2634		if (gbincore(bo, blkno)) {
2635			BO_UNLOCK(bo);
2636			bp->b_flags |= B_INVAL;
2637			brelse(bp);
2638			goto loop;
2639		}
2640
2641		/*
2642		 * Insert the buffer into the hash, so that it can
2643		 * be found by incore.
2644		 */
2645		bp->b_blkno = bp->b_lblkno = blkno;
2646		bp->b_offset = offset;
2647
2648		bgetvp(vp, bp);
2649		BO_UNLOCK(bo);
2650
2651		/*
2652		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2653		 * buffer size starts out as 0, B_CACHE will be set by
2654		 * allocbuf() for the VMIO case prior to it testing the
2655		 * backing store for validity.
2656		 */
2657
2658		if (vmio) {
2659			bp->b_flags |= B_VMIO;
2660#if defined(VFS_BIO_DEBUG)
2661			if (vn_canvmio(vp) != TRUE)
2662				printf("getblk: VMIO on vnode type %d\n",
2663					vp->v_type);
2664#endif
2665			VOP_GETVOBJECT(vp, &vmo);
2666			KASSERT(vmo == bp->b_bufobj->bo_object,
2667			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2668			    bp, vmo, bp->b_bufobj->bo_object));
2669		} else {
2670			bp->b_flags &= ~B_VMIO;
2671			KASSERT(bp->b_bufobj->bo_object == NULL,
2672			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2673			    bp, bp->b_bufobj->bo_object));
2674		}
2675
2676		allocbuf(bp, size);
2677
2678		splx(s);
2679		bp->b_flags &= ~B_DONE;
2680	}
2681	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2682	KASSERT(bp->b_bufobj == bo,
2683	    ("wrong b_bufobj %p should be %p", bp->b_bufobj, bo));
2684	return (bp);
2685}
2686
2687/*
2688 * Get an empty, disassociated buffer of given size.  The buffer is initially
2689 * set to B_INVAL.
2690 */
2691struct buf *
2692geteblk(int size)
2693{
2694	struct buf *bp;
2695	int s;
2696	int maxsize;
2697
2698	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2699
2700	s = splbio();
2701	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2702		continue;
2703	splx(s);
2704	allocbuf(bp, size);
2705	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2706	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2707	return (bp);
2708}
2709
2710
2711/*
2712 * This code constitutes the buffer memory from either anonymous system
2713 * memory (in the case of non-VMIO operations) or from an associated
2714 * VM object (in the case of VMIO operations).  This code is able to
2715 * resize a buffer up or down.
2716 *
2717 * Note that this code is tricky, and has many complications to resolve
2718 * deadlock or inconsistant data situations.  Tread lightly!!!
2719 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2720 * the caller.  Calling this code willy nilly can result in the loss of data.
2721 *
2722 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2723 * B_CACHE for the non-VMIO case.
2724 */
2725
2726int
2727allocbuf(struct buf *bp, int size)
2728{
2729	int newbsize, mbsize;
2730	int i;
2731
2732	GIANT_REQUIRED;
2733
2734	if (BUF_REFCNT(bp) == 0)
2735		panic("allocbuf: buffer not busy");
2736
2737	if (bp->b_kvasize < size)
2738		panic("allocbuf: buffer too small");
2739
2740	if ((bp->b_flags & B_VMIO) == 0) {
2741		caddr_t origbuf;
2742		int origbufsize;
2743		/*
2744		 * Just get anonymous memory from the kernel.  Don't
2745		 * mess with B_CACHE.
2746		 */
2747		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2748		if (bp->b_flags & B_MALLOC)
2749			newbsize = mbsize;
2750		else
2751			newbsize = round_page(size);
2752
2753		if (newbsize < bp->b_bufsize) {
2754			/*
2755			 * malloced buffers are not shrunk
2756			 */
2757			if (bp->b_flags & B_MALLOC) {
2758				if (newbsize) {
2759					bp->b_bcount = size;
2760				} else {
2761					free(bp->b_data, M_BIOBUF);
2762					if (bp->b_bufsize) {
2763						atomic_subtract_int(
2764						    &bufmallocspace,
2765						    bp->b_bufsize);
2766						bufspacewakeup();
2767						bp->b_bufsize = 0;
2768					}
2769					bp->b_saveaddr = bp->b_kvabase;
2770					bp->b_data = bp->b_saveaddr;
2771					bp->b_bcount = 0;
2772					bp->b_flags &= ~B_MALLOC;
2773				}
2774				return 1;
2775			}
2776			vm_hold_free_pages(
2777			    bp,
2778			    (vm_offset_t) bp->b_data + newbsize,
2779			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2780		} else if (newbsize > bp->b_bufsize) {
2781			/*
2782			 * We only use malloced memory on the first allocation.
2783			 * and revert to page-allocated memory when the buffer
2784			 * grows.
2785			 */
2786			/*
2787			 * There is a potential smp race here that could lead
2788			 * to bufmallocspace slightly passing the max.  It
2789			 * is probably extremely rare and not worth worrying
2790			 * over.
2791			 */
2792			if ( (bufmallocspace < maxbufmallocspace) &&
2793				(bp->b_bufsize == 0) &&
2794				(mbsize <= PAGE_SIZE/2)) {
2795
2796				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2797				bp->b_bufsize = mbsize;
2798				bp->b_bcount = size;
2799				bp->b_flags |= B_MALLOC;
2800				atomic_add_int(&bufmallocspace, mbsize);
2801				return 1;
2802			}
2803			origbuf = NULL;
2804			origbufsize = 0;
2805			/*
2806			 * If the buffer is growing on its other-than-first allocation,
2807			 * then we revert to the page-allocation scheme.
2808			 */
2809			if (bp->b_flags & B_MALLOC) {
2810				origbuf = bp->b_data;
2811				origbufsize = bp->b_bufsize;
2812				bp->b_data = bp->b_kvabase;
2813				if (bp->b_bufsize) {
2814					atomic_subtract_int(&bufmallocspace,
2815					    bp->b_bufsize);
2816					bufspacewakeup();
2817					bp->b_bufsize = 0;
2818				}
2819				bp->b_flags &= ~B_MALLOC;
2820				newbsize = round_page(newbsize);
2821			}
2822			vm_hold_load_pages(
2823			    bp,
2824			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2825			    (vm_offset_t) bp->b_data + newbsize);
2826			if (origbuf) {
2827				bcopy(origbuf, bp->b_data, origbufsize);
2828				free(origbuf, M_BIOBUF);
2829			}
2830		}
2831	} else {
2832		int desiredpages;
2833
2834		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2835		desiredpages = (size == 0) ? 0 :
2836			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2837
2838		if (bp->b_flags & B_MALLOC)
2839			panic("allocbuf: VMIO buffer can't be malloced");
2840		/*
2841		 * Set B_CACHE initially if buffer is 0 length or will become
2842		 * 0-length.
2843		 */
2844		if (size == 0 || bp->b_bufsize == 0)
2845			bp->b_flags |= B_CACHE;
2846
2847		if (newbsize < bp->b_bufsize) {
2848			/*
2849			 * DEV_BSIZE aligned new buffer size is less then the
2850			 * DEV_BSIZE aligned existing buffer size.  Figure out
2851			 * if we have to remove any pages.
2852			 */
2853			if (desiredpages < bp->b_npages) {
2854				vm_page_t m;
2855
2856				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2857				vm_page_lock_queues();
2858				for (i = desiredpages; i < bp->b_npages; i++) {
2859					/*
2860					 * the page is not freed here -- it
2861					 * is the responsibility of
2862					 * vnode_pager_setsize
2863					 */
2864					m = bp->b_pages[i];
2865					KASSERT(m != bogus_page,
2866					    ("allocbuf: bogus page found"));
2867					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2868						vm_page_lock_queues();
2869
2870					bp->b_pages[i] = NULL;
2871					vm_page_unwire(m, 0);
2872				}
2873				vm_page_unlock_queues();
2874				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2875				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2876				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2877				bp->b_npages = desiredpages;
2878			}
2879		} else if (size > bp->b_bcount) {
2880			/*
2881			 * We are growing the buffer, possibly in a
2882			 * byte-granular fashion.
2883			 */
2884			struct vnode *vp;
2885			vm_object_t obj;
2886			vm_offset_t toff;
2887			vm_offset_t tinc;
2888
2889			/*
2890			 * Step 1, bring in the VM pages from the object,
2891			 * allocating them if necessary.  We must clear
2892			 * B_CACHE if these pages are not valid for the
2893			 * range covered by the buffer.
2894			 */
2895
2896			vp = bp->b_vp;
2897			obj = bp->b_bufobj->bo_object;
2898
2899			VM_OBJECT_LOCK(obj);
2900			while (bp->b_npages < desiredpages) {
2901				vm_page_t m;
2902				vm_pindex_t pi;
2903
2904				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2905				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2906					/*
2907					 * note: must allocate system pages
2908					 * since blocking here could intefere
2909					 * with paging I/O, no matter which
2910					 * process we are.
2911					 */
2912					m = vm_page_alloc(obj, pi,
2913					    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2914					    VM_ALLOC_WIRED);
2915					if (m == NULL) {
2916						atomic_add_int(&vm_pageout_deficit,
2917						    desiredpages - bp->b_npages);
2918						VM_OBJECT_UNLOCK(obj);
2919						VM_WAIT;
2920						VM_OBJECT_LOCK(obj);
2921					} else {
2922						bp->b_flags &= ~B_CACHE;
2923						bp->b_pages[bp->b_npages] = m;
2924						++bp->b_npages;
2925					}
2926					continue;
2927				}
2928
2929				/*
2930				 * We found a page.  If we have to sleep on it,
2931				 * retry because it might have gotten freed out
2932				 * from under us.
2933				 *
2934				 * We can only test PG_BUSY here.  Blocking on
2935				 * m->busy might lead to a deadlock:
2936				 *
2937				 *  vm_fault->getpages->cluster_read->allocbuf
2938				 *
2939				 */
2940				vm_page_lock_queues();
2941				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2942					continue;
2943
2944				/*
2945				 * We have a good page.  Should we wakeup the
2946				 * page daemon?
2947				 */
2948				if ((curproc != pageproc) &&
2949				    ((m->queue - m->pc) == PQ_CACHE) &&
2950				    ((cnt.v_free_count + cnt.v_cache_count) <
2951					(cnt.v_free_min + cnt.v_cache_min))) {
2952					pagedaemon_wakeup();
2953				}
2954				vm_page_wire(m);
2955				vm_page_unlock_queues();
2956				bp->b_pages[bp->b_npages] = m;
2957				++bp->b_npages;
2958			}
2959
2960			/*
2961			 * Step 2.  We've loaded the pages into the buffer,
2962			 * we have to figure out if we can still have B_CACHE
2963			 * set.  Note that B_CACHE is set according to the
2964			 * byte-granular range ( bcount and size ), new the
2965			 * aligned range ( newbsize ).
2966			 *
2967			 * The VM test is against m->valid, which is DEV_BSIZE
2968			 * aligned.  Needless to say, the validity of the data
2969			 * needs to also be DEV_BSIZE aligned.  Note that this
2970			 * fails with NFS if the server or some other client
2971			 * extends the file's EOF.  If our buffer is resized,
2972			 * B_CACHE may remain set! XXX
2973			 */
2974
2975			toff = bp->b_bcount;
2976			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2977
2978			while ((bp->b_flags & B_CACHE) && toff < size) {
2979				vm_pindex_t pi;
2980
2981				if (tinc > (size - toff))
2982					tinc = size - toff;
2983
2984				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2985				    PAGE_SHIFT;
2986
2987				vfs_buf_test_cache(
2988				    bp,
2989				    bp->b_offset,
2990				    toff,
2991				    tinc,
2992				    bp->b_pages[pi]
2993				);
2994				toff += tinc;
2995				tinc = PAGE_SIZE;
2996			}
2997			VM_OBJECT_UNLOCK(obj);
2998
2999			/*
3000			 * Step 3, fixup the KVM pmap.  Remember that
3001			 * bp->b_data is relative to bp->b_offset, but
3002			 * bp->b_offset may be offset into the first page.
3003			 */
3004
3005			bp->b_data = (caddr_t)
3006			    trunc_page((vm_offset_t)bp->b_data);
3007			pmap_qenter(
3008			    (vm_offset_t)bp->b_data,
3009			    bp->b_pages,
3010			    bp->b_npages
3011			);
3012
3013			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3014			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
3015		}
3016	}
3017	if (newbsize < bp->b_bufsize)
3018		bufspacewakeup();
3019	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3020	bp->b_bcount = size;		/* requested buffer size	*/
3021	return 1;
3022}
3023
3024void
3025biodone(struct bio *bp)
3026{
3027
3028	mtx_lock(&bdonelock);
3029	bp->bio_flags |= BIO_DONE;
3030	if (bp->bio_done == NULL)
3031		wakeup(bp);
3032	mtx_unlock(&bdonelock);
3033	if (bp->bio_done != NULL)
3034		bp->bio_done(bp);
3035}
3036
3037/*
3038 * Wait for a BIO to finish.
3039 *
3040 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3041 * case is not yet clear.
3042 */
3043int
3044biowait(struct bio *bp, const char *wchan)
3045{
3046
3047	mtx_lock(&bdonelock);
3048	while ((bp->bio_flags & BIO_DONE) == 0)
3049		msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
3050	mtx_unlock(&bdonelock);
3051	if (bp->bio_error != 0)
3052		return (bp->bio_error);
3053	if (!(bp->bio_flags & BIO_ERROR))
3054		return (0);
3055	return (EIO);
3056}
3057
3058void
3059biofinish(struct bio *bp, struct devstat *stat, int error)
3060{
3061
3062	if (error) {
3063		bp->bio_error = error;
3064		bp->bio_flags |= BIO_ERROR;
3065	}
3066	if (stat != NULL)
3067		devstat_end_transaction_bio(stat, bp);
3068	biodone(bp);
3069}
3070
3071/*
3072 *	bufwait:
3073 *
3074 *	Wait for buffer I/O completion, returning error status.  The buffer
3075 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3076 *	error and cleared.
3077 */
3078int
3079bufwait(struct buf *bp)
3080{
3081	int s;
3082
3083	s = splbio();
3084	if (bp->b_iocmd == BIO_READ)
3085		bwait(bp, PRIBIO, "biord");
3086	else
3087		bwait(bp, PRIBIO, "biowr");
3088	splx(s);
3089	if (bp->b_flags & B_EINTR) {
3090		bp->b_flags &= ~B_EINTR;
3091		return (EINTR);
3092	}
3093	if (bp->b_ioflags & BIO_ERROR) {
3094		return (bp->b_error ? bp->b_error : EIO);
3095	} else {
3096		return (0);
3097	}
3098}
3099
3100 /*
3101  * Call back function from struct bio back up to struct buf.
3102  */
3103static void
3104bufdonebio(struct bio *bip)
3105{
3106	struct buf *bp;
3107
3108	/* Device drivers may or may not hold giant, hold it here. */
3109	mtx_lock(&Giant);
3110	bp = bip->bio_caller2;
3111	bp->b_resid = bp->b_bcount - bip->bio_completed;
3112	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3113	bp->b_ioflags = bip->bio_flags;
3114	bp->b_error = bip->bio_error;
3115	if (bp->b_error)
3116		bp->b_ioflags |= BIO_ERROR;
3117	bufdone(bp);
3118	mtx_unlock(&Giant);
3119	g_destroy_bio(bip);
3120}
3121
3122void
3123dev_strategy(struct cdev *dev, struct buf *bp)
3124{
3125	struct cdevsw *csw;
3126	struct bio *bip;
3127
3128	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3129		panic("b_iocmd botch");
3130	for (;;) {
3131		bip = g_new_bio();
3132		if (bip != NULL)
3133			break;
3134		/* Try again later */
3135		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3136	}
3137	bip->bio_cmd = bp->b_iocmd;
3138	bip->bio_offset = bp->b_iooffset;
3139	bip->bio_length = bp->b_bcount;
3140	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3141	bip->bio_data = bp->b_data;
3142	bip->bio_done = bufdonebio;
3143	bip->bio_caller2 = bp;
3144	bip->bio_dev = dev;
3145	KASSERT(dev->si_refcount > 0,
3146	    ("dev_strategy on un-referenced struct cdev *(%s)",
3147	    devtoname(dev)));
3148	csw = dev_refthread(dev);
3149	if (csw == NULL) {
3150		bp->b_error = ENXIO;
3151		bp->b_ioflags = BIO_ERROR;
3152		mtx_lock(&Giant);	/* XXX: too defensive ? */
3153		bufdone(bp);
3154		mtx_unlock(&Giant);	/* XXX: too defensive ? */
3155		return;
3156	}
3157	(*csw->d_strategy)(bip);
3158	dev_relthread(dev);
3159}
3160
3161/*
3162 *	bufdone:
3163 *
3164 *	Finish I/O on a buffer, optionally calling a completion function.
3165 *	This is usually called from an interrupt so process blocking is
3166 *	not allowed.
3167 *
3168 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3169 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3170 *	assuming B_INVAL is clear.
3171 *
3172 *	For the VMIO case, we set B_CACHE if the op was a read and no
3173 *	read error occured, or if the op was a write.  B_CACHE is never
3174 *	set if the buffer is invalid or otherwise uncacheable.
3175 *
3176 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3177 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3178 *	in the biodone routine.
3179 */
3180void
3181bufdone(struct buf *bp)
3182{
3183	int s;
3184	void    (*biodone)(struct buf *);
3185
3186
3187	s = splbio();
3188
3189	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
3190	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3191
3192	bp->b_flags |= B_DONE;
3193	runningbufwakeup(bp);
3194
3195	if (bp->b_iocmd == BIO_WRITE && bp->b_bufobj != NULL)
3196		bufobj_wdrop(bp->b_bufobj);
3197
3198	/* call optional completion function if requested */
3199	if (bp->b_iodone != NULL) {
3200		biodone = bp->b_iodone;
3201		bp->b_iodone = NULL;
3202		(*biodone) (bp);
3203		splx(s);
3204		return;
3205	}
3206	if (LIST_FIRST(&bp->b_dep) != NULL)
3207		buf_complete(bp);
3208
3209	if (bp->b_flags & B_VMIO) {
3210		int i;
3211		vm_ooffset_t foff;
3212		vm_page_t m;
3213		vm_object_t obj;
3214		int iosize;
3215		struct vnode *vp = bp->b_vp;
3216
3217		obj = bp->b_bufobj->bo_object;
3218
3219#if defined(VFS_BIO_DEBUG)
3220		mp_fixme("usecount and vflag accessed without locks.");
3221		if (vp->v_usecount == 0) {
3222			panic("biodone: zero vnode ref count");
3223		}
3224
3225		if ((vp->v_vflag & VV_OBJBUF) == 0) {
3226			panic("biodone: vnode is not setup for merged cache");
3227		}
3228#endif
3229
3230		foff = bp->b_offset;
3231		KASSERT(bp->b_offset != NOOFFSET,
3232		    ("biodone: no buffer offset"));
3233
3234		VM_OBJECT_LOCK(obj);
3235#if defined(VFS_BIO_DEBUG)
3236		if (obj->paging_in_progress < bp->b_npages) {
3237			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3238			    obj->paging_in_progress, bp->b_npages);
3239		}
3240#endif
3241
3242		/*
3243		 * Set B_CACHE if the op was a normal read and no error
3244		 * occured.  B_CACHE is set for writes in the b*write()
3245		 * routines.
3246		 */
3247		iosize = bp->b_bcount - bp->b_resid;
3248		if (bp->b_iocmd == BIO_READ &&
3249		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3250		    !(bp->b_ioflags & BIO_ERROR)) {
3251			bp->b_flags |= B_CACHE;
3252		}
3253		vm_page_lock_queues();
3254		for (i = 0; i < bp->b_npages; i++) {
3255			int bogusflag = 0;
3256			int resid;
3257
3258			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3259			if (resid > iosize)
3260				resid = iosize;
3261
3262			/*
3263			 * cleanup bogus pages, restoring the originals
3264			 */
3265			m = bp->b_pages[i];
3266			if (m == bogus_page) {
3267				bogusflag = 1;
3268				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3269				if (m == NULL)
3270					panic("biodone: page disappeared!");
3271				bp->b_pages[i] = m;
3272				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3273			}
3274#if defined(VFS_BIO_DEBUG)
3275			if (OFF_TO_IDX(foff) != m->pindex) {
3276				printf(
3277"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3278				    (intmax_t)foff, (uintmax_t)m->pindex);
3279			}
3280#endif
3281
3282			/*
3283			 * In the write case, the valid and clean bits are
3284			 * already changed correctly ( see bdwrite() ), so we
3285			 * only need to do this here in the read case.
3286			 */
3287			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3288				vfs_page_set_valid(bp, foff, i, m);
3289			}
3290
3291			/*
3292			 * when debugging new filesystems or buffer I/O methods, this
3293			 * is the most common error that pops up.  if you see this, you
3294			 * have not set the page busy flag correctly!!!
3295			 */
3296			if (m->busy == 0) {
3297				printf("biodone: page busy < 0, "
3298				    "pindex: %d, foff: 0x(%x,%x), "
3299				    "resid: %d, index: %d\n",
3300				    (int) m->pindex, (int)(foff >> 32),
3301						(int) foff & 0xffffffff, resid, i);
3302				if (!vn_isdisk(vp, NULL))
3303					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3304					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3305					    (intmax_t) bp->b_lblkno,
3306					    bp->b_flags, bp->b_npages);
3307				else
3308					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3309					    (intmax_t) bp->b_lblkno,
3310					    bp->b_flags, bp->b_npages);
3311				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3312				    (u_long)m->valid, (u_long)m->dirty,
3313				    m->wire_count);
3314				panic("biodone: page busy < 0\n");
3315			}
3316			vm_page_io_finish(m);
3317			vm_object_pip_subtract(obj, 1);
3318			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3319			iosize -= resid;
3320		}
3321		vm_page_unlock_queues();
3322		vm_object_pip_wakeupn(obj, 0);
3323		VM_OBJECT_UNLOCK(obj);
3324	}
3325
3326	/*
3327	 * For asynchronous completions, release the buffer now. The brelse
3328	 * will do a wakeup there if necessary - so no need to do a wakeup
3329	 * here in the async case. The sync case always needs to do a wakeup.
3330	 */
3331
3332	if (bp->b_flags & B_ASYNC) {
3333		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3334			brelse(bp);
3335		else
3336			bqrelse(bp);
3337	} else {
3338		bdone(bp);
3339	}
3340	splx(s);
3341}
3342
3343/*
3344 * This routine is called in lieu of iodone in the case of
3345 * incomplete I/O.  This keeps the busy status for pages
3346 * consistant.
3347 */
3348void
3349vfs_unbusy_pages(struct buf *bp)
3350{
3351	int i;
3352	vm_object_t obj;
3353	vm_page_t m;
3354
3355	runningbufwakeup(bp);
3356	if (!(bp->b_flags & B_VMIO))
3357		return;
3358
3359	obj = bp->b_bufobj->bo_object;
3360	VM_OBJECT_LOCK(obj);
3361	vm_page_lock_queues();
3362	for (i = 0; i < bp->b_npages; i++) {
3363		m = bp->b_pages[i];
3364		if (m == bogus_page) {
3365			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3366			if (!m)
3367				panic("vfs_unbusy_pages: page missing\n");
3368			bp->b_pages[i] = m;
3369			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3370			    bp->b_pages, bp->b_npages);
3371		}
3372		vm_object_pip_subtract(obj, 1);
3373		vm_page_io_finish(m);
3374	}
3375	vm_page_unlock_queues();
3376	vm_object_pip_wakeupn(obj, 0);
3377	VM_OBJECT_UNLOCK(obj);
3378}
3379
3380/*
3381 * vfs_page_set_valid:
3382 *
3383 *	Set the valid bits in a page based on the supplied offset.   The
3384 *	range is restricted to the buffer's size.
3385 *
3386 *	This routine is typically called after a read completes.
3387 */
3388static void
3389vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3390{
3391	vm_ooffset_t soff, eoff;
3392
3393	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3394	/*
3395	 * Start and end offsets in buffer.  eoff - soff may not cross a
3396	 * page boundry or cross the end of the buffer.  The end of the
3397	 * buffer, in this case, is our file EOF, not the allocation size
3398	 * of the buffer.
3399	 */
3400	soff = off;
3401	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3402	if (eoff > bp->b_offset + bp->b_bcount)
3403		eoff = bp->b_offset + bp->b_bcount;
3404
3405	/*
3406	 * Set valid range.  This is typically the entire buffer and thus the
3407	 * entire page.
3408	 */
3409	if (eoff > soff) {
3410		vm_page_set_validclean(
3411		    m,
3412		   (vm_offset_t) (soff & PAGE_MASK),
3413		   (vm_offset_t) (eoff - soff)
3414		);
3415	}
3416}
3417
3418/*
3419 * This routine is called before a device strategy routine.
3420 * It is used to tell the VM system that paging I/O is in
3421 * progress, and treat the pages associated with the buffer
3422 * almost as being PG_BUSY.  Also the object paging_in_progress
3423 * flag is handled to make sure that the object doesn't become
3424 * inconsistant.
3425 *
3426 * Since I/O has not been initiated yet, certain buffer flags
3427 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3428 * and should be ignored.
3429 */
3430void
3431vfs_busy_pages(struct buf *bp, int clear_modify)
3432{
3433	int i, bogus;
3434	vm_object_t obj;
3435	vm_ooffset_t foff;
3436	vm_page_t m;
3437
3438	if (!(bp->b_flags & B_VMIO))
3439		return;
3440
3441	obj = bp->b_bufobj->bo_object;
3442	foff = bp->b_offset;
3443	KASSERT(bp->b_offset != NOOFFSET,
3444	    ("vfs_busy_pages: no buffer offset"));
3445	vfs_setdirty(bp);
3446	VM_OBJECT_LOCK(obj);
3447retry:
3448	vm_page_lock_queues();
3449	for (i = 0; i < bp->b_npages; i++) {
3450		m = bp->b_pages[i];
3451
3452		if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3453			goto retry;
3454	}
3455	bogus = 0;
3456	for (i = 0; i < bp->b_npages; i++) {
3457		m = bp->b_pages[i];
3458
3459		if ((bp->b_flags & B_CLUSTER) == 0) {
3460			vm_object_pip_add(obj, 1);
3461			vm_page_io_start(m);
3462		}
3463		/*
3464		 * When readying a buffer for a read ( i.e
3465		 * clear_modify == 0 ), it is important to do
3466		 * bogus_page replacement for valid pages in
3467		 * partially instantiated buffers.  Partially
3468		 * instantiated buffers can, in turn, occur when
3469		 * reconstituting a buffer from its VM backing store
3470		 * base.  We only have to do this if B_CACHE is
3471		 * clear ( which causes the I/O to occur in the
3472		 * first place ).  The replacement prevents the read
3473		 * I/O from overwriting potentially dirty VM-backed
3474		 * pages.  XXX bogus page replacement is, uh, bogus.
3475		 * It may not work properly with small-block devices.
3476		 * We need to find a better way.
3477		 */
3478		pmap_remove_all(m);
3479		if (clear_modify)
3480			vfs_page_set_valid(bp, foff, i, m);
3481		else if (m->valid == VM_PAGE_BITS_ALL &&
3482		    (bp->b_flags & B_CACHE) == 0) {
3483			bp->b_pages[i] = bogus_page;
3484			bogus++;
3485		}
3486		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3487	}
3488	vm_page_unlock_queues();
3489	VM_OBJECT_UNLOCK(obj);
3490	if (bogus)
3491		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3492		    bp->b_pages, bp->b_npages);
3493}
3494
3495/*
3496 * Tell the VM system that the pages associated with this buffer
3497 * are clean.  This is used for delayed writes where the data is
3498 * going to go to disk eventually without additional VM intevention.
3499 *
3500 * Note that while we only really need to clean through to b_bcount, we
3501 * just go ahead and clean through to b_bufsize.
3502 */
3503static void
3504vfs_clean_pages(struct buf *bp)
3505{
3506	int i;
3507	vm_ooffset_t foff, noff, eoff;
3508	vm_page_t m;
3509
3510	if (!(bp->b_flags & B_VMIO))
3511		return;
3512
3513	foff = bp->b_offset;
3514	KASSERT(bp->b_offset != NOOFFSET,
3515	    ("vfs_clean_pages: no buffer offset"));
3516	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3517	vm_page_lock_queues();
3518	for (i = 0; i < bp->b_npages; i++) {
3519		m = bp->b_pages[i];
3520		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3521		eoff = noff;
3522
3523		if (eoff > bp->b_offset + bp->b_bufsize)
3524			eoff = bp->b_offset + bp->b_bufsize;
3525		vfs_page_set_valid(bp, foff, i, m);
3526		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3527		foff = noff;
3528	}
3529	vm_page_unlock_queues();
3530	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3531}
3532
3533/*
3534 *	vfs_bio_set_validclean:
3535 *
3536 *	Set the range within the buffer to valid and clean.  The range is
3537 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3538 *	itself may be offset from the beginning of the first page.
3539 *
3540 */
3541
3542void
3543vfs_bio_set_validclean(struct buf *bp, int base, int size)
3544{
3545	int i, n;
3546	vm_page_t m;
3547
3548	if (!(bp->b_flags & B_VMIO))
3549		return;
3550	/*
3551	 * Fixup base to be relative to beginning of first page.
3552	 * Set initial n to be the maximum number of bytes in the
3553	 * first page that can be validated.
3554	 */
3555
3556	base += (bp->b_offset & PAGE_MASK);
3557	n = PAGE_SIZE - (base & PAGE_MASK);
3558
3559	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3560	vm_page_lock_queues();
3561	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3562		m = bp->b_pages[i];
3563		if (n > size)
3564			n = size;
3565		vm_page_set_validclean(m, base & PAGE_MASK, n);
3566		base += n;
3567		size -= n;
3568		n = PAGE_SIZE;
3569	}
3570	vm_page_unlock_queues();
3571	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3572}
3573
3574/*
3575 *	vfs_bio_clrbuf:
3576 *
3577 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3578 *	to clear BIO_ERROR and B_INVAL.
3579 *
3580 *	Note that while we only theoretically need to clear through b_bcount,
3581 *	we go ahead and clear through b_bufsize.
3582 */
3583
3584void
3585vfs_bio_clrbuf(struct buf *bp)
3586{
3587	int i, j, mask = 0;
3588	caddr_t sa, ea;
3589
3590	GIANT_REQUIRED;
3591
3592	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3593		clrbuf(bp);
3594		return;
3595	}
3596
3597	bp->b_flags &= ~B_INVAL;
3598	bp->b_ioflags &= ~BIO_ERROR;
3599	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3600	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3601	    (bp->b_offset & PAGE_MASK) == 0) {
3602		if (bp->b_pages[0] == bogus_page)
3603			goto unlock;
3604		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3605		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3606		if ((bp->b_pages[0]->valid & mask) == mask)
3607			goto unlock;
3608		if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3609		    ((bp->b_pages[0]->valid & mask) == 0)) {
3610			bzero(bp->b_data, bp->b_bufsize);
3611			bp->b_pages[0]->valid |= mask;
3612			goto unlock;
3613		}
3614	}
3615	ea = sa = bp->b_data;
3616	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3617		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3618		ea = (caddr_t)(vm_offset_t)ulmin(
3619		    (u_long)(vm_offset_t)ea,
3620		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3621		if (bp->b_pages[i] == bogus_page)
3622			continue;
3623		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3624		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3625		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3626		if ((bp->b_pages[i]->valid & mask) == mask)
3627			continue;
3628		if ((bp->b_pages[i]->valid & mask) == 0) {
3629			if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3630				bzero(sa, ea - sa);
3631		} else {
3632			for (; sa < ea; sa += DEV_BSIZE, j++) {
3633				if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3634				    (bp->b_pages[i]->valid & (1 << j)) == 0)
3635					bzero(sa, DEV_BSIZE);
3636			}
3637		}
3638		bp->b_pages[i]->valid |= mask;
3639	}
3640unlock:
3641	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3642	bp->b_resid = 0;
3643}
3644
3645/*
3646 * vm_hold_load_pages and vm_hold_free_pages get pages into
3647 * a buffers address space.  The pages are anonymous and are
3648 * not associated with a file object.
3649 */
3650static void
3651vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3652{
3653	vm_offset_t pg;
3654	vm_page_t p;
3655	int index;
3656
3657	to = round_page(to);
3658	from = round_page(from);
3659	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3660
3661	VM_OBJECT_LOCK(kernel_object);
3662	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3663tryagain:
3664		/*
3665		 * note: must allocate system pages since blocking here
3666		 * could intefere with paging I/O, no matter which
3667		 * process we are.
3668		 */
3669		p = vm_page_alloc(kernel_object,
3670			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3671		    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3672		if (!p) {
3673			atomic_add_int(&vm_pageout_deficit,
3674			    (to - pg) >> PAGE_SHIFT);
3675			VM_OBJECT_UNLOCK(kernel_object);
3676			VM_WAIT;
3677			VM_OBJECT_LOCK(kernel_object);
3678			goto tryagain;
3679		}
3680		p->valid = VM_PAGE_BITS_ALL;
3681		pmap_qenter(pg, &p, 1);
3682		bp->b_pages[index] = p;
3683	}
3684	VM_OBJECT_UNLOCK(kernel_object);
3685	bp->b_npages = index;
3686}
3687
3688/* Return pages associated with this buf to the vm system */
3689static void
3690vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3691{
3692	vm_offset_t pg;
3693	vm_page_t p;
3694	int index, newnpages;
3695
3696	from = round_page(from);
3697	to = round_page(to);
3698	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3699
3700	VM_OBJECT_LOCK(kernel_object);
3701	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3702		p = bp->b_pages[index];
3703		if (p && (index < bp->b_npages)) {
3704			if (p->busy) {
3705				printf(
3706			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3707				    (intmax_t)bp->b_blkno,
3708				    (intmax_t)bp->b_lblkno);
3709			}
3710			bp->b_pages[index] = NULL;
3711			pmap_qremove(pg, 1);
3712			vm_page_lock_queues();
3713			vm_page_unwire(p, 0);
3714			vm_page_free(p);
3715			vm_page_unlock_queues();
3716		}
3717	}
3718	VM_OBJECT_UNLOCK(kernel_object);
3719	bp->b_npages = newnpages;
3720}
3721
3722/*
3723 * Map an IO request into kernel virtual address space.
3724 *
3725 * All requests are (re)mapped into kernel VA space.
3726 * Notice that we use b_bufsize for the size of the buffer
3727 * to be mapped.  b_bcount might be modified by the driver.
3728 *
3729 * Note that even if the caller determines that the address space should
3730 * be valid, a race or a smaller-file mapped into a larger space may
3731 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3732 * check the return value.
3733 */
3734int
3735vmapbuf(struct buf *bp)
3736{
3737	caddr_t addr, kva;
3738	vm_prot_t prot;
3739	int pidx, i;
3740	struct vm_page *m;
3741	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3742
3743	if (bp->b_bufsize < 0)
3744		return (-1);
3745	prot = VM_PROT_READ;
3746	if (bp->b_iocmd == BIO_READ)
3747		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3748	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3749	     addr < bp->b_data + bp->b_bufsize;
3750	     addr += PAGE_SIZE, pidx++) {
3751		/*
3752		 * Do the vm_fault if needed; do the copy-on-write thing
3753		 * when reading stuff off device into memory.
3754		 *
3755		 * NOTE! Must use pmap_extract() because addr may be in
3756		 * the userland address space, and kextract is only guarenteed
3757		 * to work for the kernland address space (see: sparc64 port).
3758		 */
3759retry:
3760		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3761		    prot) < 0) {
3762			vm_page_lock_queues();
3763			for (i = 0; i < pidx; ++i) {
3764				vm_page_unhold(bp->b_pages[i]);
3765				bp->b_pages[i] = NULL;
3766			}
3767			vm_page_unlock_queues();
3768			return(-1);
3769		}
3770		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3771		if (m == NULL)
3772			goto retry;
3773		bp->b_pages[pidx] = m;
3774	}
3775	if (pidx > btoc(MAXPHYS))
3776		panic("vmapbuf: mapped more than MAXPHYS");
3777	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3778
3779	kva = bp->b_saveaddr;
3780	bp->b_npages = pidx;
3781	bp->b_saveaddr = bp->b_data;
3782	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3783	return(0);
3784}
3785
3786/*
3787 * Free the io map PTEs associated with this IO operation.
3788 * We also invalidate the TLB entries and restore the original b_addr.
3789 */
3790void
3791vunmapbuf(struct buf *bp)
3792{
3793	int pidx;
3794	int npages;
3795
3796	npages = bp->b_npages;
3797	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3798	vm_page_lock_queues();
3799	for (pidx = 0; pidx < npages; pidx++)
3800		vm_page_unhold(bp->b_pages[pidx]);
3801	vm_page_unlock_queues();
3802
3803	bp->b_data = bp->b_saveaddr;
3804}
3805
3806void
3807bdone(struct buf *bp)
3808{
3809
3810	mtx_lock(&bdonelock);
3811	bp->b_flags |= B_DONE;
3812	wakeup(bp);
3813	mtx_unlock(&bdonelock);
3814}
3815
3816void
3817bwait(struct buf *bp, u_char pri, const char *wchan)
3818{
3819
3820	mtx_lock(&bdonelock);
3821	while ((bp->b_flags & B_DONE) == 0)
3822		msleep(bp, &bdonelock, pri, wchan, 0);
3823	mtx_unlock(&bdonelock);
3824}
3825
3826int
3827bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3828{
3829
3830	return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3831}
3832
3833void
3834bufstrategy(struct bufobj *bo, struct buf *bp)
3835{
3836	int i = 0;
3837	struct vnode *vp;
3838
3839	vp = bp->b_vp;
3840	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3841	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3842	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3843	i = VOP_STRATEGY(vp, bp);
3844	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3845}
3846
3847void
3848bufobj_wref(struct bufobj *bo)
3849{
3850
3851	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3852	BO_LOCK(bo);
3853	bo->bo_numoutput++;
3854	BO_UNLOCK(bo);
3855}
3856
3857void
3858bufobj_wdrop(struct bufobj *bo)
3859{
3860
3861	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3862	BO_LOCK(bo);
3863	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3864	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3865		bo->bo_flag &= ~BO_WWAIT;
3866		wakeup(&bo->bo_numoutput);
3867	}
3868	BO_UNLOCK(bo);
3869}
3870
3871int
3872bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3873{
3874	int error;
3875
3876	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3877	ASSERT_BO_LOCKED(bo);
3878	error = 0;
3879	while (bo->bo_numoutput) {
3880		bo->bo_flag |= BO_WWAIT;
3881		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3882		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3883		if (error)
3884			break;
3885	}
3886	return (error);
3887}
3888
3889#include "opt_ddb.h"
3890#ifdef DDB
3891#include <ddb/ddb.h>
3892
3893/* DDB command to show buffer data */
3894DB_SHOW_COMMAND(buffer, db_show_buffer)
3895{
3896	/* get args */
3897	struct buf *bp = (struct buf *)addr;
3898
3899	if (!have_addr) {
3900		db_printf("usage: show buffer <addr>\n");
3901		return;
3902	}
3903
3904	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3905	db_printf(
3906	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3907	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n",
3908	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3909	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno);
3910	if (bp->b_npages) {
3911		int i;
3912		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3913		for (i = 0; i < bp->b_npages; i++) {
3914			vm_page_t m;
3915			m = bp->b_pages[i];
3916			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3917			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3918			if ((i + 1) < bp->b_npages)
3919				db_printf(",");
3920		}
3921		db_printf("\n");
3922	}
3923}
3924#endif /* DDB */
3925