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