vfs_bio.c revision 222220
1156321Sdamien/*-
2156321Sdamien * Copyright (c) 2004 Poul-Henning Kamp
3156321Sdamien * Copyright (c) 1994,1997 John S. Dyson
4156321Sdamien * All rights reserved.
5156321Sdamien *
6156321Sdamien * Redistribution and use in source and binary forms, with or without
7156321Sdamien * modification, are permitted provided that the following conditions
8156321Sdamien * are met:
9156321Sdamien * 1. Redistributions of source code must retain the above copyright
10156321Sdamien *    notice, this list of conditions and the following disclaimer.
11156321Sdamien * 2. Redistributions in binary form must reproduce the above copyright
12156321Sdamien *    notice, this list of conditions and the following disclaimer in the
13156321Sdamien *    documentation and/or other materials provided with the distribution.
14156321Sdamien *
15156321Sdamien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16156321Sdamien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17156321Sdamien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18156321Sdamien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19156321Sdamien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20156321Sdamien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21156321Sdamien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22156321Sdamien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23156321Sdamien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24156321Sdamien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25156321Sdamien * SUCH DAMAGE.
26156321Sdamien */
27156321Sdamien
28156321Sdamien/*
29156321Sdamien * this file contains a new buffer I/O scheme implementing a coherent
30156321Sdamien * VM object and buffer cache scheme.  Pains have been taken to make
31156321Sdamien * sure that the performance degradation associated with schemes such
32156321Sdamien * as this is not realized.
33156321Sdamien *
34156321Sdamien * Author:  John S. Dyson
35156321Sdamien * Significant help during the development and debugging phases
36164982Skevlo * had been provided by David Greenman, also of the FreeBSD core team.
37164982Skevlo *
38156321Sdamien * see man buf(9) for more info.
39156321Sdamien */
40156321Sdamien
41178354Ssam#include <sys/cdefs.h>
42156321Sdamien__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 222220 2011-05-23 19:59:01Z ru $");
43156321Sdamien
44156321Sdamien#include <sys/param.h>
45156321Sdamien#include <sys/systm.h>
46156321Sdamien#include <sys/bio.h>
47156321Sdamien#include <sys/conf.h>
48156321Sdamien#include <sys/buf.h>
49156321Sdamien#include <sys/devicestat.h>
50156321Sdamien#include <sys/eventhandler.h>
51156321Sdamien#include <sys/fail.h>
52156321Sdamien#include <sys/limits.h>
53156321Sdamien#include <sys/lock.h>
54156321Sdamien#include <sys/malloc.h>
55156321Sdamien#include <sys/mount.h>
56156321Sdamien#include <sys/mutex.h>
57170530Ssam#include <sys/kernel.h>
58206358Srpaulo#include <sys/kthread.h>
59156321Sdamien#include <sys/proc.h>
60156321Sdamien#include <sys/resourcevar.h>
61156321Sdamien#include <sys/sysctl.h>
62156321Sdamien#include <sys/vmmeter.h>
63156321Sdamien#include <sys/vnode.h>
64156321Sdamien#include <geom/geom.h>
65156321Sdamien#include <vm/vm.h>
66156327Ssilby#include <vm/vm_param.h>
67156327Ssilby#include <vm/vm_kern.h>
68156321Sdamien#include <vm/vm_pageout.h>
69178354Ssam#include <vm/vm_page.h>
70156321Sdamien#include <vm/vm_object.h>
71178354Ssam#include <vm/vm_extern.h>
72178354Ssam#include <vm/vm_map.h>
73178354Ssam#include "opt_compat.h"
74178354Ssam#include "opt_directio.h"
75178354Ssam#include "opt_swap.h"
76178354Ssam
77178354Ssamstatic MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
78178354Ssam
79156321Sdamienstruct	bio_ops bioops;		/* I/O operation notification */
80178354Ssam
81178354Ssamstruct	buf_ops buf_ops_bio = {
82156321Sdamien	.bop_name	=	"buf_ops_bio",
83156321Sdamien	.bop_write	=	bufwrite,
84178354Ssam	.bop_strategy	=	bufstrategy,
85228621Sbschmidt	.bop_sync	=	bufsync,
86228621Sbschmidt	.bop_bdflush	=	bufbdflush,
87228621Sbschmidt};
88178354Ssam
89156321Sdamien/*
90156321Sdamien * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
91156321Sdamien * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
92156321Sdamien */
93156321Sdamienstruct buf *buf;		/* buffer header pool */
94156321Sdamien
95156321Sdamienstatic struct proc *bufdaemonproc;
96156321Sdamien
97156321Sdamienstatic int inmem(struct vnode *vp, daddr_t blkno);
98156321Sdamienstatic void vm_hold_free_pages(struct buf *bp, int newbsize);
99156321Sdamienstatic void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
100156321Sdamien		vm_offset_t to);
101156321Sdamienstatic void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
102156321Sdamienstatic void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
103178354Ssam		vm_page_t m);
104156321Sdamienstatic void vfs_drain_busy_pages(struct buf *bp);
105156321Sdamienstatic void vfs_clean_pages_dirty_buf(struct buf *bp);
106156321Sdamienstatic void vfs_setdirty_locked_object(struct buf *bp);
107156321Sdamienstatic void vfs_vmio_release(struct buf *bp);
108156321Sdamienstatic int vfs_bio_clcheck(struct vnode *vp, int size,
109156321Sdamien		daddr_t lblkno, daddr_t blkno);
110156321Sdamienstatic int buf_do_flush(struct vnode *vp);
111156321Sdamienstatic int flushbufqueues(struct vnode *, int, int);
112156321Sdamienstatic void buf_daemon(void);
113170530Ssamstatic void bremfreel(struct buf *bp);
114170530Ssam#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
115170530Ssam    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
116156321Sdamienstatic int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
117156321Sdamien#endif
118156321Sdamien
119156321Sdamienint vmiodirenable = TRUE;
120156321SdamienSYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
121156321Sdamien    "Use the VM system for directory writes");
122156321Sdamienlong runningbufspace;
123178354SsamSYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
124156321Sdamien    "Amount of presently outstanding async buffer io");
125178354Ssamstatic long bufspace;
126178354Ssam#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
127165352Sbms    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
128156321SdamienSYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
129156321Sdamien    &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
130156321Sdamien#else
131156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
132156321Sdamien    "Virtual memory used for buffers");
133156321Sdamien#endif
134156321Sdamienstatic long maxbufspace;
135156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
136156321Sdamien    "Maximum allowed value of bufspace (including buf_daemon)");
137156321Sdamienstatic long bufmallocspace;
138156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
139156321Sdamien    "Amount of malloced memory for buffers");
140156321Sdamienstatic long maxbufmallocspace;
141156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
142156321Sdamien    "Maximum amount of malloced memory for buffers");
143156321Sdamienstatic long lobufspace;
144156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
145156321Sdamien    "Minimum amount of buffers we want to have");
146156321Sdamienlong hibufspace;
147156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
148156321Sdamien    "Maximum allowed value of bufspace (excluding buf_daemon)");
149178354Ssamstatic int bufreusecnt;
150156321SdamienSYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
151156321Sdamien    "Number of times we have reused a buffer");
152156321Sdamienstatic int buffreekvacnt;
153178354SsamSYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
154190526Ssam    "Number of times we have freed the KVA space from some buffer");
155156321Sdamienstatic int bufdefragcnt;
156178354SsamSYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
157156321Sdamien    "Number of times we have had to repeat buffer allocation to defragment");
158178354Ssamstatic long lorunningspace;
159156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
160178354Ssam    "Minimum preferred space used for in-progress I/O");
161156321Sdamienstatic long hirunningspace;
162156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
163156321Sdamien    "Maximum amount of space to use for in-progress I/O");
164156321Sdamienint dirtybufferflushes;
165156321SdamienSYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
166178354Ssam    0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
167178354Ssamint bdwriteskip;
168156321SdamienSYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
169192468Ssam    0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
170156321Sdamienint altbufferflushes;
171156321SdamienSYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
172156321Sdamien    0, "Number of fsync flushes to limit dirty buffers");
173156321Sdamienstatic int recursiveflushes;
174156321SdamienSYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
175156321Sdamien    0, "Number of flushes skipped due to being recursive");
176156321Sdamienstatic int numdirtybuffers;
177156321SdamienSYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
178156321Sdamien    "Number of buffers that are dirty (has unwritten changes) at the moment");
179156321Sdamienstatic int lodirtybuffers;
180156321SdamienSYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
181156321Sdamien    "How many buffers we want to have free before bufdaemon can sleep");
182156321Sdamienstatic int hidirtybuffers;
183156321SdamienSYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
184156321Sdamien    "When the number of dirty buffers is considered severe");
185156321Sdamienint dirtybufthresh;
186156321SdamienSYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
187156321Sdamien    0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
188156321Sdamienstatic int numfreebuffers;
189156321SdamienSYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
190156321Sdamien    "Number of free buffers");
191156321Sdamienstatic int lofreebuffers;
192156321SdamienSYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
193156321Sdamien   "XXX Unused");
194156321Sdamienstatic int hifreebuffers;
195156321SdamienSYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
196156321Sdamien   "XXX Complicatedly unused");
197156321Sdamienstatic int getnewbufcalls;
198156321SdamienSYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
199178354Ssam   "Number of calls to getnewbuf");
200156321Sdamienstatic int getnewbufrestarts;
201156321SdamienSYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
202178354Ssam    "Number of times getnewbuf has had to restart a buffer aquisition");
203178354Ssamstatic int flushbufqtarget = 100;
204190526SsamSYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
205156321Sdamien    "Amount of work to do in flushbufqueues when helping bufdaemon");
206178354Ssamstatic long notbufdflashes;
207156321SdamienSYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, &notbufdflashes, 0,
208156321Sdamien    "Number of dirty buffer flushes done by the bufdaemon helpers");
209178354Ssam
210178354Ssam/*
211178354Ssam * Wakeup point for bufdaemon, as well as indicator of whether it is already
212178354Ssam * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
213178354Ssam * is idling.
214178354Ssam */
215178354Ssamstatic int bd_request;
216156321Sdamien
217156321Sdamien/*
218156321Sdamien * Request for the buf daemon to write more buffers than is indicated by
219165352Sbms * lodirtybuf.  This may be necessary to push out excess dependencies or
220156321Sdamien * defragment the address space where a simple count of the number of dirty
221156321Sdamien * buffers is insufficient to characterize the demand for flushing them.
222156321Sdamien */
223156321Sdamienstatic int bd_speedupreq;
224156321Sdamien
225156321Sdamien/*
226156321Sdamien * This lock synchronizes access to bd_request.
227156321Sdamien */
228156321Sdamienstatic struct mtx bdlock;
229156321Sdamien
230156321Sdamien/*
231156321Sdamien * bogus page -- for I/O to/from partially complete buffers
232156321Sdamien * this is a temporary solution to the problem, but it is not
233156321Sdamien * really that bad.  it would be better to split the buffer
234156321Sdamien * for input in the case of buffers partially already in memory,
235190526Ssam * but the code is intricate enough already.
236156321Sdamien */
237156321Sdamienvm_page_t bogus_page;
238156321Sdamien
239156321Sdamien/*
240156321Sdamien * Synchronization (sleep/wakeup) variable for active buffer space requests.
241156321Sdamien * Set when wait starts, cleared prior to wakeup().
242156321Sdamien * Used in runningbufwakeup() and waitrunningbufspace().
243156321Sdamien */
244156321Sdamienstatic int runningbufreq;
245156321Sdamien
246156321Sdamien/*
247156321Sdamien * This lock protects the runningbufreq and synchronizes runningbufwakeup and
248156321Sdamien * waitrunningbufspace().
249156321Sdamien */
250156321Sdamienstatic struct mtx rbreqlock;
251156321Sdamien
252156321Sdamien/*
253156321Sdamien * Synchronization (sleep/wakeup) variable for buffer requests.
254156321Sdamien * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
255156321Sdamien * by and/or.
256156321Sdamien * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
257156321Sdamien * getnewbuf(), and getblk().
258156321Sdamien */
259156321Sdamienstatic int needsbuffer;
260156321Sdamien
261156321Sdamien/*
262156321Sdamien * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
263156321Sdamien */
264156321Sdamienstatic struct mtx nblock;
265156321Sdamien
266156321Sdamien/*
267156321Sdamien * Definitions for the buffer free lists.
268156321Sdamien */
269156321Sdamien#define BUFFER_QUEUES	6	/* number of free buffer queues */
270156321Sdamien
271207554Ssobomax#define QUEUE_NONE	0	/* on no queue */
272207554Ssobomax#define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
273156321Sdamien#define QUEUE_DIRTY	2	/* B_DELWRI buffers */
274156321Sdamien#define QUEUE_DIRTY_GIANT 3	/* B_DELWRI buffers that need giant */
275156321Sdamien#define QUEUE_EMPTYKVA	4	/* empty buffer headers w/KVA assignment */
276178354Ssam#define QUEUE_EMPTY	5	/* empty buffer headers */
277156321Sdamien#define QUEUE_SENTINEL	1024	/* not an queue index, but mark for sentinel */
278156321Sdamien
279156321Sdamien/* Queues for free buffers with various properties */
280156321Sdamienstatic TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
281178957Ssam
282178957Ssam/* Lock for the bufqueues */
283178354Ssamstatic struct mtx bqlock;
284178354Ssam
285178354Ssam/*
286178354Ssam * Single global constant for BUF_WMESG, to avoid getting multiple references.
287195618Srpaulo * buf_wmesg is referred from macros.
288178354Ssam */
289178354Ssamconst char *buf_wmesg = BUF_WMESG;
290178354Ssam
291178354Ssam#define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
292156407Sdamien#define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
293178354Ssam#define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
294178354Ssam#define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
295156407Sdamien
296178354Ssam#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
297156321Sdamien    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
298170530Ssamstatic int
299170530Ssamsysctl_bufspace(SYSCTL_HANDLER_ARGS)
300170530Ssam{
301170530Ssam	long lvalue;
302170530Ssam	int ivalue;
303178354Ssam
304156321Sdamien	if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
305190526Ssam		return (sysctl_handle_long(oidp, arg1, arg2, req));
306178354Ssam	lvalue = *(long *)arg1;
307178354Ssam	if (lvalue > INT_MAX)
308178354Ssam		/* On overflow, still write out a long to trigger ENOMEM. */
309170530Ssam		return (sysctl_handle_long(oidp, &lvalue, 0, req));
310170530Ssam	ivalue = lvalue;
311170530Ssam	return (sysctl_handle_int(oidp, &ivalue, 0, req));
312156321Sdamien}
313178354Ssam#endif
314178354Ssam
315156321Sdamien#ifdef DIRECTIO
316178354Ssamextern void ffs_rawread_setup(void);
317178354Ssam#endif /* DIRECTIO */
318156321Sdamien/*
319192468Ssam *	numdirtywakeup:
320192468Ssam *
321192468Ssam *	If someone is blocked due to there being too many dirty buffers,
322192468Ssam *	and numdirtybuffers is now reasonable, wake them up.
323192468Ssam */
324178354Ssam
325178354Ssamstatic __inline void
326156321Sdamiennumdirtywakeup(int level)
327178354Ssam{
328178354Ssam
329178354Ssam	if (numdirtybuffers <= level) {
330156321Sdamien		mtx_lock(&nblock);
331156321Sdamien		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
332156321Sdamien			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
333156321Sdamien			wakeup(&needsbuffer);
334156321Sdamien		}
335156321Sdamien		mtx_unlock(&nblock);
336156321Sdamien	}
337156321Sdamien}
338156321Sdamien
339178354Ssam/*
340156321Sdamien *	bufspacewakeup:
341156321Sdamien *
342156321Sdamien *	Called when buffer space is potentially available for recovery.
343156321Sdamien *	getnewbuf() will block on this flag when it is unable to free
344156321Sdamien *	sufficient buffer space.  Buffer space becomes recoverable when
345156321Sdamien *	bp's get placed back in the queues.
346156321Sdamien */
347178354Ssam
348178354Ssamstatic __inline void
349170530Ssambufspacewakeup(void)
350178038Ssam{
351178038Ssam
352178038Ssam	/*
353156321Sdamien	 * If someone is waiting for BUF space, wake them up.  Even
354156321Sdamien	 * though we haven't freed the kva space yet, the waiting
355156321Sdamien	 * process will be able to now.
356156321Sdamien	 */
357156321Sdamien	mtx_lock(&nblock);
358156321Sdamien	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
359156321Sdamien		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
360156321Sdamien		wakeup(&needsbuffer);
361156321Sdamien	}
362156321Sdamien	mtx_unlock(&nblock);
363156321Sdamien}
364156321Sdamien
365156321Sdamien/*
366156321Sdamien * runningbufwakeup() - in-progress I/O accounting.
367156321Sdamien *
368156321Sdamien */
369156321Sdamienvoid
370178354Ssamrunningbufwakeup(struct buf *bp)
371228621Sbschmidt{
372228621Sbschmidt
373228621Sbschmidt	if (bp->b_runningbufspace) {
374228621Sbschmidt		atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
375178354Ssam		bp->b_runningbufspace = 0;
376178354Ssam		mtx_lock(&rbreqlock);
377178354Ssam		if (runningbufreq && runningbufspace <= lorunningspace) {
378178354Ssam			runningbufreq = 0;
379178354Ssam			wakeup(&runningbufreq);
380178354Ssam		}
381178354Ssam		mtx_unlock(&rbreqlock);
382178354Ssam	}
383178354Ssam}
384178354Ssam
385178354Ssam/*
386195618Srpaulo *	bufcountwakeup:
387195618Srpaulo *
388178354Ssam *	Called when a buffer has been added to one of the free queues to
389178354Ssam *	account for the buffer and to wakeup anyone waiting for free buffers.
390178354Ssam *	This typically occurs when large amounts of metadata are being handled
391178354Ssam *	by the buffer cache ( else buffer space runs out first, usually ).
392178354Ssam */
393178354Ssam
394178354Ssamstatic __inline void
395178354Ssambufcountwakeup(struct buf *bp)
396178354Ssam{
397178354Ssam	int old;
398178354Ssam
399178354Ssam	KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
400178354Ssam	    ("buf %p already counted as free", bp));
401178354Ssam	if (bp->b_bufobj != NULL)
402178354Ssam		mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
403178354Ssam	bp->b_vflags |= BV_INFREECNT;
404178354Ssam	old = atomic_fetchadd_int(&numfreebuffers, 1);
405178354Ssam	KASSERT(old >= 0 && old < nbuf,
406178354Ssam	    ("numfreebuffers climbed to %d", old + 1));
407178354Ssam	mtx_lock(&nblock);
408178354Ssam	if (needsbuffer) {
409178354Ssam		needsbuffer &= ~VFS_BIO_NEED_ANY;
410178354Ssam		if (numfreebuffers >= hifreebuffers)
411178354Ssam			needsbuffer &= ~VFS_BIO_NEED_FREE;
412178354Ssam		wakeup(&needsbuffer);
413178354Ssam	}
414178354Ssam	mtx_unlock(&nblock);
415178354Ssam}
416178354Ssam
417178354Ssam/*
418178354Ssam *	waitrunningbufspace()
419178354Ssam *
420178354Ssam *	runningbufspace is a measure of the amount of I/O currently
421178354Ssam *	running.  This routine is used in async-write situations to
422178354Ssam *	prevent creating huge backups of pending writes to a device.
423178354Ssam *	Only asynchronous writes are governed by this function.
424178354Ssam *
425178354Ssam *	Reads will adjust runningbufspace, but will not block based on it.
426206358Srpaulo *	The read load has a side effect of reducing the allowed write load.
427178354Ssam *
428178354Ssam *	This does NOT turn an async write into a sync write.  It waits
429178354Ssam *	for earlier writes to complete and generally returns before the
430178354Ssam *	caller's write has reached the device.
431178354Ssam */
432178354Ssamvoid
433178354Ssamwaitrunningbufspace(void)
434178354Ssam{
435178354Ssam
436178354Ssam	mtx_lock(&rbreqlock);
437178354Ssam	while (runningbufspace > hirunningspace) {
438178354Ssam		++runningbufreq;
439206358Srpaulo		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
440178354Ssam	}
441178354Ssam	mtx_unlock(&rbreqlock);
442178354Ssam}
443178354Ssam
444156321Sdamien
445156321Sdamien/*
446156321Sdamien *	vfs_buf_test_cache:
447156321Sdamien *
448156321Sdamien *	Called when a buffer is extended.  This function clears the B_CACHE
449156321Sdamien *	bit if the newly extended portion of the buffer does not contain
450156321Sdamien *	valid data.
451156321Sdamien */
452156321Sdamienstatic __inline
453156321Sdamienvoid
454156321Sdamienvfs_buf_test_cache(struct buf *bp,
455156321Sdamien		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
456156321Sdamien		  vm_page_t m)
457156321Sdamien{
458156321Sdamien
459156321Sdamien	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
460156321Sdamien	if (bp->b_flags & B_CACHE) {
461156321Sdamien		int base = (foff + off) & PAGE_MASK;
462156321Sdamien		if (vm_page_is_valid(m, base, size) == 0)
463156321Sdamien			bp->b_flags &= ~B_CACHE;
464178354Ssam	}
465156321Sdamien}
466178354Ssam
467178354Ssam/* Wake up the buffer daemon if necessary */
468156321Sdamienstatic __inline
469156321Sdamienvoid
470156321Sdamienbd_wakeup(int dirtybuflevel)
471156321Sdamien{
472156321Sdamien
473156321Sdamien	mtx_lock(&bdlock);
474156321Sdamien	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
475156321Sdamien		bd_request = 1;
476156321Sdamien		wakeup(&bd_request);
477156321Sdamien	}
478156321Sdamien	mtx_unlock(&bdlock);
479156321Sdamien}
480156321Sdamien
481156321Sdamien/*
482156321Sdamien * bd_speedup - speedup the buffer cache flushing code
483156321Sdamien */
484156321Sdamien
485156321Sdamienvoid
486156321Sdamienbd_speedup(void)
487156321Sdamien{
488156321Sdamien	int needwake;
489156321Sdamien
490156321Sdamien	mtx_lock(&bdlock);
491171535Skevlo	needwake = 0;
492171535Skevlo	if (bd_speedupreq == 0 || bd_request == 0)
493171535Skevlo		needwake = 1;
494171535Skevlo	bd_speedupreq = 1;
495156321Sdamien	bd_request = 1;
496156321Sdamien	if (needwake)
497156321Sdamien		wakeup(&bd_request);
498156321Sdamien	mtx_unlock(&bdlock);
499156321Sdamien}
500156321Sdamien
501156321Sdamien/*
502156321Sdamien * Calculating buffer cache scaling values and reserve space for buffer
503156321Sdamien * headers.  This is called during low level kernel initialization and
504156321Sdamien * may be called more then once.  We CANNOT write to the memory area
505156321Sdamien * being reserved at this time.
506156321Sdamien */
507156321Sdamiencaddr_t
508156321Sdamienkern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
509156321Sdamien{
510156321Sdamien	int tuned_nbuf;
511156321Sdamien	long maxbuf;
512156321Sdamien
513156321Sdamien	/*
514156321Sdamien	 * physmem_est is in pages.  Convert it to kilobytes (assumes
515156321Sdamien	 * PAGE_SIZE is >= 1K)
516156321Sdamien	 */
517156321Sdamien	physmem_est = physmem_est * (PAGE_SIZE / 1024);
518156321Sdamien
519156321Sdamien	/*
520156321Sdamien	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
521156321Sdamien	 * For the first 64MB of ram nominally allocate sufficient buffers to
522156321Sdamien	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
523171535Skevlo	 * buffers to cover 1/10 of our ram over 64MB.  When auto-sizing
524171535Skevlo	 * the buffer cache we limit the eventual kva reservation to
525171535Skevlo	 * maxbcache bytes.
526156321Sdamien	 *
527156321Sdamien	 * factor represents the 1/4 x ram conversion.
528156321Sdamien	 */
529156321Sdamien	if (nbuf == 0) {
530156321Sdamien		int factor = 4 * BKVASIZE / 1024;
531156321Sdamien
532156321Sdamien		nbuf = 50;
533156321Sdamien		if (physmem_est > 4096)
534156321Sdamien			nbuf += min((physmem_est - 4096) / factor,
535156321Sdamien			    65536 / factor);
536156321Sdamien		if (physmem_est > 65536)
537156321Sdamien			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
538156321Sdamien
539156321Sdamien		if (maxbcache && nbuf > maxbcache / BKVASIZE)
540156321Sdamien			nbuf = maxbcache / BKVASIZE;
541156321Sdamien		tuned_nbuf = 1;
542156321Sdamien	} else
543156321Sdamien		tuned_nbuf = 0;
544156321Sdamien
545156321Sdamien	/* XXX Avoid unsigned long overflows later on with maxbufspace. */
546156321Sdamien	maxbuf = (LONG_MAX / 3) / BKVASIZE;
547156321Sdamien	if (nbuf > maxbuf) {
548156321Sdamien		if (!tuned_nbuf)
549156321Sdamien			printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
550156321Sdamien			    maxbuf);
551156321Sdamien		nbuf = maxbuf;
552156321Sdamien	}
553156321Sdamien
554156321Sdamien	/*
555156321Sdamien	 * swbufs are used as temporary holders for I/O, such as paging I/O.
556156321Sdamien	 * We have no less then 16 and no more then 256.
557156321Sdamien	 */
558156321Sdamien	nswbuf = max(min(nbuf/4, 256), 16);
559156321Sdamien#ifdef NSWBUF_MIN
560156321Sdamien	if (nswbuf < NSWBUF_MIN)
561156321Sdamien		nswbuf = NSWBUF_MIN;
562156321Sdamien#endif
563156321Sdamien#ifdef DIRECTIO
564156321Sdamien	ffs_rawread_setup();
565156321Sdamien#endif
566156321Sdamien
567156321Sdamien	/*
568156321Sdamien	 * Reserve space for the buffer cache buffers
569156321Sdamien	 */
570156321Sdamien	swbuf = (void *)v;
571156321Sdamien	v = (caddr_t)(swbuf + nswbuf);
572156321Sdamien	buf = (void *)v;
573156321Sdamien	v = (caddr_t)(buf + nbuf);
574156321Sdamien
575156321Sdamien	return(v);
576156321Sdamien}
577156321Sdamien
578156321Sdamien/* Initialize the buffer subsystem.  Called before use of any buffers. */
579156321Sdamienvoid
580156321Sdamienbufinit(void)
581156321Sdamien{
582156321Sdamien	struct buf *bp;
583156321Sdamien	int i;
584156321Sdamien
585156321Sdamien	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
586156321Sdamien	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
587156321Sdamien	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
588156321Sdamien	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
589156321Sdamien
590156321Sdamien	/* next, make a null set of free lists */
591156321Sdamien	for (i = 0; i < BUFFER_QUEUES; i++)
592156321Sdamien		TAILQ_INIT(&bufqueues[i]);
593156321Sdamien
594156321Sdamien	/* finally, initialize each buffer header and stick on empty q */
595156321Sdamien	for (i = 0; i < nbuf; i++) {
596156321Sdamien		bp = &buf[i];
597156321Sdamien		bzero(bp, sizeof *bp);
598156321Sdamien		bp->b_flags = B_INVAL;	/* we're just an empty header */
599156321Sdamien		bp->b_rcred = NOCRED;
600156321Sdamien		bp->b_wcred = NOCRED;
601156321Sdamien		bp->b_qindex = QUEUE_EMPTY;
602156321Sdamien		bp->b_vflags = BV_INFREECNT;	/* buf is counted as free */
603156321Sdamien		bp->b_xflags = 0;
604156321Sdamien		LIST_INIT(&bp->b_dep);
605156321Sdamien		BUF_LOCKINIT(bp);
606156321Sdamien		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
607156321Sdamien	}
608156321Sdamien
609156321Sdamien	/*
610156321Sdamien	 * maxbufspace is the absolute maximum amount of buffer space we are
611156321Sdamien	 * allowed to reserve in KVM and in real terms.  The absolute maximum
612156321Sdamien	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
613156321Sdamien	 * used by most other processes.  The differential is required to
614156321Sdamien	 * ensure that buf_daemon is able to run when other processes might
615156321Sdamien	 * be blocked waiting for buffer space.
616156321Sdamien	 *
617156321Sdamien	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
618156321Sdamien	 * this may result in KVM fragmentation which is not handled optimally
619156321Sdamien	 * by the system.
620156321Sdamien	 */
621156321Sdamien	maxbufspace = (long)nbuf * BKVASIZE;
622156321Sdamien	hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
623156321Sdamien	lobufspace = hibufspace - MAXBSIZE;
624156321Sdamien
625156321Sdamien	/*
626156321Sdamien	 * Note: The 16 MiB upper limit for hirunningspace was chosen
627156321Sdamien	 * arbitrarily and may need further tuning. It corresponds to
628156321Sdamien	 * 128 outstanding write IO requests (if IO size is 128 KiB),
629156321Sdamien	 * which fits with many RAID controllers' tagged queuing limits.
630156321Sdamien	 * The lower 1 MiB limit is the historical upper limit for
631156321Sdamien	 * hirunningspace.
632171535Skevlo	 */
633171535Skevlo	hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
634171535Skevlo	    16 * 1024 * 1024), 1024 * 1024);
635171535Skevlo	lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
636156321Sdamien
637156321Sdamien/*
638156321Sdamien * Limit the amount of malloc memory since it is wired permanently into
639156321Sdamien * the kernel space.  Even though this is accounted for in the buffer
640156321Sdamien * allocation, we don't want the malloced region to grow uncontrolled.
641156321Sdamien * The malloc scheme improves memory utilization significantly on average
642156321Sdamien * (small) directories.
643156321Sdamien */
644156321Sdamien	maxbufmallocspace = hibufspace / 20;
645156321Sdamien
646156321Sdamien/*
647156321Sdamien * Reduce the chance of a deadlock occuring by limiting the number
648156321Sdamien * of delayed-write dirty buffers we allow to stack up.
649156321Sdamien */
650156321Sdamien	hidirtybuffers = nbuf / 4 + 20;
651156321Sdamien	dirtybufthresh = hidirtybuffers * 9 / 10;
652156321Sdamien	numdirtybuffers = 0;
653156321Sdamien/*
654156321Sdamien * To support extreme low-memory systems, make sure hidirtybuffers cannot
655156321Sdamien * eat up all available buffer space.  This occurs when our minimum cannot
656156321Sdamien * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
657156321Sdamien * BKVASIZE'd buffers.
658156321Sdamien */
659156321Sdamien	while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
660156321Sdamien		hidirtybuffers >>= 1;
661156321Sdamien	}
662156321Sdamien	lodirtybuffers = hidirtybuffers / 2;
663156321Sdamien
664156321Sdamien/*
665156321Sdamien * Try to keep the number of free buffers in the specified range,
666156321Sdamien * and give special processes (e.g. like buf_daemon) access to an
667171535Skevlo * emergency reserve.
668171535Skevlo */
669171535Skevlo	lofreebuffers = nbuf / 18 + 5;
670156321Sdamien	hifreebuffers = 2 * lofreebuffers;
671156321Sdamien	numfreebuffers = nbuf;
672156321Sdamien
673156321Sdamien	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
674156321Sdamien	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
675156321Sdamien}
676156321Sdamien
677156321Sdamien/*
678156321Sdamien * bfreekva() - free the kva allocation for a buffer.
679156321Sdamien *
680156321Sdamien *	Since this call frees up buffer space, we call bufspacewakeup().
681156321Sdamien */
682156321Sdamienstatic void
683156321Sdamienbfreekva(struct buf *bp)
684156321Sdamien{
685243857Sglebius
686156321Sdamien	if (bp->b_kvasize) {
687156321Sdamien		atomic_add_int(&buffreekvacnt, 1);
688156321Sdamien		atomic_subtract_long(&bufspace, bp->b_kvasize);
689156321Sdamien		vm_map_remove(buffer_map, (vm_offset_t) bp->b_kvabase,
690156321Sdamien		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize);
691156321Sdamien		bp->b_kvasize = 0;
692156321Sdamien		bufspacewakeup();
693156321Sdamien	}
694156321Sdamien}
695156321Sdamien
696156321Sdamien/*
697156321Sdamien *	bremfree:
698156321Sdamien *
699156321Sdamien *	Mark the buffer for removal from the appropriate free list in brelse.
700156321Sdamien *
701156321Sdamien */
702156321Sdamienvoid
703156321Sdamienbremfree(struct buf *bp)
704156321Sdamien{
705156321Sdamien	int old;
706156321Sdamien
707156321Sdamien	CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
708156321Sdamien	KASSERT((bp->b_flags & B_REMFREE) == 0,
709156321Sdamien	    ("bremfree: buffer %p already marked for delayed removal.", bp));
710156321Sdamien	KASSERT(bp->b_qindex != QUEUE_NONE,
711156321Sdamien	    ("bremfree: buffer %p not on a queue.", bp));
712156321Sdamien	BUF_ASSERT_HELD(bp);
713156321Sdamien
714156321Sdamien	bp->b_flags |= B_REMFREE;
715156321Sdamien	/* Fixup numfreebuffers count.  */
716156321Sdamien	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
717156321Sdamien		KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
718156321Sdamien		    ("buf %p not counted in numfreebuffers", bp));
719156321Sdamien		if (bp->b_bufobj != NULL)
720156321Sdamien			mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
721156321Sdamien		bp->b_vflags &= ~BV_INFREECNT;
722156321Sdamien		old = atomic_fetchadd_int(&numfreebuffers, -1);
723156321Sdamien		KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
724156321Sdamien	}
725156321Sdamien}
726156321Sdamien
727156321Sdamien/*
728156321Sdamien *	bremfreef:
729156321Sdamien *
730156321Sdamien *	Force an immediate removal from a free list.  Used only in nfs when
731156321Sdamien *	it abuses the b_freelist pointer.
732156321Sdamien */
733156321Sdamienvoid
734156321Sdamienbremfreef(struct buf *bp)
735156321Sdamien{
736156321Sdamien	mtx_lock(&bqlock);
737156321Sdamien	bremfreel(bp);
738156321Sdamien	mtx_unlock(&bqlock);
739156321Sdamien}
740156321Sdamien
741156321Sdamien/*
742156321Sdamien *	bremfreel:
743156321Sdamien *
744156321Sdamien *	Removes a buffer from the free list, must be called with the
745156321Sdamien *	bqlock held.
746156321Sdamien */
747156321Sdamienstatic void
748156321Sdamienbremfreel(struct buf *bp)
749156321Sdamien{
750156321Sdamien	int old;
751156321Sdamien
752156321Sdamien	CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
753156321Sdamien	    bp, bp->b_vp, bp->b_flags);
754156321Sdamien	KASSERT(bp->b_qindex != QUEUE_NONE,
755156321Sdamien	    ("bremfreel: buffer %p not on a queue.", bp));
756156321Sdamien	BUF_ASSERT_HELD(bp);
757156321Sdamien	mtx_assert(&bqlock, MA_OWNED);
758156321Sdamien
759156321Sdamien	TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
760156321Sdamien	bp->b_qindex = QUEUE_NONE;
761156321Sdamien	/*
762156321Sdamien	 * If this was a delayed bremfree() we only need to remove the buffer
763156321Sdamien	 * from the queue and return the stats are already done.
764156321Sdamien	 */
765156321Sdamien	if (bp->b_flags & B_REMFREE) {
766178354Ssam		bp->b_flags &= ~B_REMFREE;
767156321Sdamien		return;
768178354Ssam	}
769178354Ssam	/*
770156321Sdamien	 * Fixup numfreebuffers count.  If the buffer is invalid or not
771178354Ssam	 * delayed-write, the buffer was free and we must decrement
772156321Sdamien	 * numfreebuffers.
773178354Ssam	 */
774178354Ssam	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
775156321Sdamien		KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
776178354Ssam		    ("buf %p not counted in numfreebuffers", bp));
777178354Ssam		if (bp->b_bufobj != NULL)
778178354Ssam			mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
779178354Ssam		bp->b_vflags &= ~BV_INFREECNT;
780156321Sdamien		old = atomic_fetchadd_int(&numfreebuffers, -1);
781178354Ssam		KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
782156321Sdamien	}
783178354Ssam}
784178354Ssam
785178354Ssam
786178354Ssam/*
787156321Sdamien * Get a buffer with the specified data.  Look in the cache first.  We
788156321Sdamien * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
789156321Sdamien * is set, the buffer is valid and we do not have to do anything ( see
790156321Sdamien * getblk() ).  This is really just a special case of breadn().
791156321Sdamien */
792156321Sdamienint
793178354Ssambread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
794195618Srpaulo    struct buf **bpp)
795195618Srpaulo{
796178354Ssam
797178354Ssam	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
798178354Ssam}
799156321Sdamien
800184345Ssam/*
801156321Sdamien * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
802192468Ssam * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
803192468Ssam * the buffer is valid and we do not have to do anything.
804178354Ssam */
805178354Ssamvoid
806156321Sdamienbreada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
807156321Sdamien    int cnt, struct ucred * cred)
808156321Sdamien{
809156321Sdamien	struct buf *rabp;
810156321Sdamien	int i;
811156321Sdamien
812156321Sdamien	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
813156321Sdamien		if (inmem(vp, *rablkno))
814156321Sdamien			continue;
815156321Sdamien		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
816156321Sdamien
817156321Sdamien		if ((rabp->b_flags & B_CACHE) == 0) {
818156321Sdamien			if (!TD_IS_IDLETHREAD(curthread))
819156321Sdamien				curthread->td_ru.ru_inblock++;
820156321Sdamien			rabp->b_flags |= B_ASYNC;
821156321Sdamien			rabp->b_flags &= ~B_INVAL;
822156321Sdamien			rabp->b_ioflags &= ~BIO_ERROR;
823156321Sdamien			rabp->b_iocmd = BIO_READ;
824156321Sdamien			if (rabp->b_rcred == NOCRED && cred != NOCRED)
825156321Sdamien				rabp->b_rcred = crhold(cred);
826156321Sdamien			vfs_busy_pages(rabp, 0);
827156321Sdamien			BUF_KERNPROC(rabp);
828156321Sdamien			rabp->b_iooffset = dbtob(rabp->b_blkno);
829156321Sdamien			bstrategy(rabp);
830156321Sdamien		} else {
831156321Sdamien			brelse(rabp);
832156321Sdamien		}
833156321Sdamien	}
834156321Sdamien}
835156321Sdamien
836156321Sdamien/*
837156321Sdamien * Operates like bread, but also starts asynchronous I/O on
838156321Sdamien * read-ahead blocks.
839156321Sdamien */
840156321Sdamienint
841156321Sdamienbreadn(struct vnode * vp, daddr_t blkno, int size,
842156321Sdamien    daddr_t * rablkno, int *rabsize,
843156321Sdamien    int cnt, struct ucred * cred, struct buf **bpp)
844156321Sdamien{
845156321Sdamien	struct buf *bp;
846156321Sdamien	int rv = 0, readwait = 0;
847156321Sdamien
848156321Sdamien	CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
849156321Sdamien	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
850156321Sdamien
851156321Sdamien	/* if not found in cache, do some I/O */
852156321Sdamien	if ((bp->b_flags & B_CACHE) == 0) {
853156321Sdamien		if (!TD_IS_IDLETHREAD(curthread))
854156321Sdamien			curthread->td_ru.ru_inblock++;
855156321Sdamien		bp->b_iocmd = BIO_READ;
856156321Sdamien		bp->b_flags &= ~B_INVAL;
857156321Sdamien		bp->b_ioflags &= ~BIO_ERROR;
858156321Sdamien		if (bp->b_rcred == NOCRED && cred != NOCRED)
859156321Sdamien			bp->b_rcred = crhold(cred);
860156321Sdamien		vfs_busy_pages(bp, 0);
861156321Sdamien		bp->b_iooffset = dbtob(bp->b_blkno);
862156321Sdamien		bstrategy(bp);
863156321Sdamien		++readwait;
864156321Sdamien	}
865156321Sdamien
866156321Sdamien	breada(vp, rablkno, rabsize, cnt, cred);
867156321Sdamien
868156321Sdamien	if (readwait) {
869178354Ssam		rv = bufwait(bp);
870156321Sdamien	}
871156321Sdamien	return (rv);
872156321Sdamien}
873156321Sdamien
874206358Srpaulo/*
875156321Sdamien * Write, release buffer on completion.  (Done by iodone
876156321Sdamien * if async).  Do not bother writing anything if the buffer
877170530Ssam * is invalid.
878170530Ssam *
879170530Ssam * Note that we set B_CACHE here, indicating that buffer is
880156321Sdamien * fully valid and thus cacheable.  This is true even of NFS
881156321Sdamien * now so we set it generally.  This could be set either here
882156321Sdamien * or in biodone() since the I/O is synchronous.  We put it
883156321Sdamien * here.
884156321Sdamien */
885156321Sdamienint
886156321Sdamienbufwrite(struct buf *bp)
887156321Sdamien{
888156321Sdamien	int oldflags;
889156321Sdamien	struct vnode *vp;
890170530Ssam	int vp_md;
891170530Ssam
892170530Ssam	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
893170530Ssam	if (bp->b_flags & B_INVAL) {
894156321Sdamien		brelse(bp);
895159301Sfjoe		return (0);
896170530Ssam	}
897159301Sfjoe
898206371Srpaulo	oldflags = bp->b_flags;
899206371Srpaulo
900159301Sfjoe	BUF_ASSERT_HELD(bp);
901156321Sdamien
902156321Sdamien	if (bp->b_pin_count > 0)
903156321Sdamien		bunpin_wait(bp);
904156321Sdamien
905178354Ssam	KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
906178354Ssam	    ("FFS background buffer should not get here %p", bp));
907178354Ssam
908206358Srpaulo	vp = bp->b_vp;
909206358Srpaulo	if (vp)
910206358Srpaulo		vp_md = vp->v_vflag & VV_MD;
911156321Sdamien	else
912156321Sdamien		vp_md = 0;
913156321Sdamien
914156321Sdamien	/* Mark the buffer clean */
915178354Ssam	bundirty(bp);
916178354Ssam
917178354Ssam	bp->b_flags &= ~B_DONE;
918178354Ssam	bp->b_ioflags &= ~BIO_ERROR;
919178354Ssam	bp->b_flags |= B_CACHE;
920206358Srpaulo	bp->b_iocmd = BIO_WRITE;
921206358Srpaulo
922206358Srpaulo	bufobj_wref(bp->b_bufobj);
923156321Sdamien	vfs_busy_pages(bp, 1);
924156321Sdamien
925156321Sdamien	/*
926156321Sdamien	 * Normal bwrites pipeline writes
927156321Sdamien	 */
928156321Sdamien	bp->b_runningbufspace = bp->b_bufsize;
929156321Sdamien	atomic_add_long(&runningbufspace, bp->b_runningbufspace);
930156321Sdamien
931156321Sdamien	if (!TD_IS_IDLETHREAD(curthread))
932156321Sdamien		curthread->td_ru.ru_oublock++;
933178354Ssam	if (oldflags & B_ASYNC)
934156321Sdamien		BUF_KERNPROC(bp);
935156321Sdamien	bp->b_iooffset = dbtob(bp->b_blkno);
936156321Sdamien	bstrategy(bp);
937156321Sdamien
938170530Ssam	if ((oldflags & B_ASYNC) == 0) {
939170530Ssam		int rtval = bufwait(bp);
940170530Ssam		brelse(bp);
941170530Ssam		return (rtval);
942170530Ssam	} else {
943170530Ssam		/*
944156321Sdamien		 * don't allow the async write to saturate the I/O
945156321Sdamien		 * system.  We will not deadlock here because
946156321Sdamien		 * we are blocking waiting for I/O that is already in-progress
947156321Sdamien		 * to complete. We do not block here if it is the update
948178354Ssam		 * or syncer daemon trying to clean up as that can lead
949178354Ssam		 * to deadlock.
950156321Sdamien		 */
951156321Sdamien		if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
952156321Sdamien			waitrunningbufspace();
953156321Sdamien	}
954156321Sdamien
955156321Sdamien	return (0);
956156321Sdamien}
957156321Sdamien
958156321Sdamienvoid
959156321Sdamienbufbdflush(struct bufobj *bo, struct buf *bp)
960156321Sdamien{
961156321Sdamien	struct buf *nbp;
962156321Sdamien
963156321Sdamien	if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
964156321Sdamien		(void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
965156321Sdamien		altbufferflushes++;
966156321Sdamien	} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
967156321Sdamien		BO_LOCK(bo);
968156321Sdamien		/*
969156321Sdamien		 * Try to find a buffer to flush.
970156321Sdamien		 */
971156321Sdamien		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
972156321Sdamien			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
973156321Sdamien			    BUF_LOCK(nbp,
974156321Sdamien				     LK_EXCLUSIVE | LK_NOWAIT, NULL))
975178354Ssam				continue;
976156321Sdamien			if (bp == nbp)
977156321Sdamien				panic("bdwrite: found ourselves");
978156321Sdamien			BO_UNLOCK(bo);
979156321Sdamien			/* Don't countdeps with the bo lock held. */
980156321Sdamien			if (buf_countdeps(nbp, 0)) {
981156321Sdamien				BO_LOCK(bo);
982156321Sdamien				BUF_UNLOCK(nbp);
983156321Sdamien				continue;
984156321Sdamien			}
985156321Sdamien			if (nbp->b_flags & B_CLUSTEROK) {
986156321Sdamien				vfs_bio_awrite(nbp);
987178354Ssam			} else {
988178354Ssam				bremfree(nbp);
989156321Sdamien				bawrite(nbp);
990156321Sdamien			}
991156321Sdamien			dirtybufferflushes++;
992156321Sdamien			break;
993156321Sdamien		}
994156321Sdamien		if (nbp == NULL)
995156321Sdamien			BO_UNLOCK(bo);
996156321Sdamien	}
997156321Sdamien}
998156321Sdamien
999156321Sdamien/*
1000156321Sdamien * Delayed write. (Buffer is marked dirty).  Do not bother writing
1001192468Ssam * anything if the buffer is marked invalid.
1002170530Ssam *
1003156321Sdamien * Note that since the buffer must be completely valid, we can safely
1004156321Sdamien * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
1005156321Sdamien * biodone() in order to prevent getblk from writing the buffer
1006156321Sdamien * out synchronously.
1007156321Sdamien */
1008156321Sdamienvoid
1009156321Sdamienbdwrite(struct buf *bp)
1010156321Sdamien{
1011156321Sdamien	struct thread *td = curthread;
1012156321Sdamien	struct vnode *vp;
1013156321Sdamien	struct bufobj *bo;
1014156321Sdamien
1015178354Ssam	CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1016178354Ssam	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1017156321Sdamien	BUF_ASSERT_HELD(bp);
1018156321Sdamien
1019156321Sdamien	if (bp->b_flags & B_INVAL) {
1020156321Sdamien		brelse(bp);
1021156321Sdamien		return;
1022156321Sdamien	}
1023156321Sdamien
1024156321Sdamien	/*
1025156321Sdamien	 * If we have too many dirty buffers, don't create any more.
1026156321Sdamien	 * If we are wildly over our limit, then force a complete
1027156321Sdamien	 * cleanup. Otherwise, just keep the situation from getting
1028156321Sdamien	 * out of control. Note that we have to avoid a recursive
1029156321Sdamien	 * disaster and not try to clean up after our own cleanup!
1030156321Sdamien	 */
1031156321Sdamien	vp = bp->b_vp;
1032156321Sdamien	bo = bp->b_bufobj;
1033243857Sglebius	if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1034156321Sdamien		td->td_pflags |= TDP_INBDFLUSH;
1035156321Sdamien		BO_BDFLUSH(bo, bp);
1036156321Sdamien		td->td_pflags &= ~TDP_INBDFLUSH;
1037156321Sdamien	} else
1038156321Sdamien		recursiveflushes++;
1039156321Sdamien
1040156321Sdamien	bdirty(bp);
1041156321Sdamien	/*
1042156321Sdamien	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1043156321Sdamien	 * true even of NFS now.
1044156321Sdamien	 */
1045156321Sdamien	bp->b_flags |= B_CACHE;
1046156321Sdamien
1047156321Sdamien	/*
1048156321Sdamien	 * This bmap keeps the system from needing to do the bmap later,
1049156321Sdamien	 * perhaps when the system is attempting to do a sync.  Since it
1050156321Sdamien	 * is likely that the indirect block -- or whatever other datastructure
1051156321Sdamien	 * that the filesystem needs is still in memory now, it is a good
1052156321Sdamien	 * thing to do this.  Note also, that if the pageout daemon is
1053156321Sdamien	 * requesting a sync -- there might not be enough memory to do
1054156321Sdamien	 * the bmap then...  So, this is important to do.
1055156321Sdamien	 */
1056156321Sdamien	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1057156321Sdamien		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1058156321Sdamien	}
1059156321Sdamien
1060156321Sdamien	/*
1061156321Sdamien	 * Set the *dirty* buffer range based upon the VM system dirty
1062156321Sdamien	 * pages.
1063156321Sdamien	 *
1064156321Sdamien	 * Mark the buffer pages as clean.  We need to do this here to
1065156321Sdamien	 * satisfy the vnode_pager and the pageout daemon, so that it
1066156321Sdamien	 * thinks that the pages have been "cleaned".  Note that since
1067156321Sdamien	 * the pages are in a delayed write buffer -- the VFS layer
1068156321Sdamien	 * "will" see that the pages get written out on the next sync,
1069156321Sdamien	 * or perhaps the cluster will be completed.
1070156321Sdamien	 */
1071156321Sdamien	vfs_clean_pages_dirty_buf(bp);
1072156321Sdamien	bqrelse(bp);
1073156321Sdamien
1074156321Sdamien	/*
1075170530Ssam	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1076192468Ssam	 * buffers (midpoint between our recovery point and our stall
1077192468Ssam	 * point).
1078192468Ssam	 */
1079192468Ssam	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1080170530Ssam
1081192468Ssam	/*
1082156321Sdamien	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1083156321Sdamien	 * due to the softdep code.
1084156321Sdamien	 */
1085156321Sdamien}
1086156321Sdamien
1087156321Sdamien/*
1088156321Sdamien *	bdirty:
1089156321Sdamien *
1090156321Sdamien *	Turn buffer into delayed write request.  We must clear BIO_READ and
1091156321Sdamien *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1092178354Ssam *	itself to properly update it in the dirty/clean lists.  We mark it
1093178958Ssam *	B_DONE to ensure that any asynchronization of the buffer properly
1094178958Ssam *	clears B_DONE ( else a panic will occur later ).
1095192468Ssam *
1096192468Ssam *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1097156321Sdamien *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1098170530Ssam *	should only be called if the buffer is known-good.
1099170530Ssam *
1100156321Sdamien *	Since the buffer is not on a queue, we do not update the numfreebuffers
1101178354Ssam *	count.
1102178354Ssam *
1103156321Sdamien *	The buffer must be on QUEUE_NONE.
1104156321Sdamien */
1105178354Ssamvoid
1106192468Ssambdirty(struct buf *bp)
1107178354Ssam{
1108178354Ssam
1109192468Ssam	CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1110170530Ssam	    bp, bp->b_vp, bp->b_flags);
1111170530Ssam	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1112170530Ssam	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1113156321Sdamien	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1114156321Sdamien	BUF_ASSERT_HELD(bp);
1115156321Sdamien	bp->b_flags &= ~(B_RELBUF);
1116178354Ssam	bp->b_iocmd = BIO_WRITE;
1117156321Sdamien
1118156321Sdamien	if ((bp->b_flags & B_DELWRI) == 0) {
1119156321Sdamien		bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1120156321Sdamien		reassignbuf(bp);
1121156321Sdamien		atomic_add_int(&numdirtybuffers, 1);
1122156321Sdamien		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1123156321Sdamien	}
1124156321Sdamien}
1125156321Sdamien
1126156321Sdamien/*
1127156321Sdamien *	bundirty:
1128156321Sdamien *
1129156321Sdamien *	Clear B_DELWRI for buffer.
1130156321Sdamien *
1131156321Sdamien *	Since the buffer is not on a queue, we do not update the numfreebuffers
1132156321Sdamien *	count.
1133156321Sdamien *
1134156321Sdamien *	The buffer must be on QUEUE_NONE.
1135156321Sdamien */
1136156321Sdamien
1137156321Sdamienvoid
1138156321Sdamienbundirty(struct buf *bp)
1139156321Sdamien{
1140156321Sdamien
1141156321Sdamien	CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1142156321Sdamien	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1143156321Sdamien	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1144156321Sdamien	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1145156321Sdamien	BUF_ASSERT_HELD(bp);
1146156321Sdamien
1147156321Sdamien	if (bp->b_flags & B_DELWRI) {
1148156321Sdamien		bp->b_flags &= ~B_DELWRI;
1149156321Sdamien		reassignbuf(bp);
1150156321Sdamien		atomic_subtract_int(&numdirtybuffers, 1);
1151156321Sdamien		numdirtywakeup(lodirtybuffers);
1152156321Sdamien	}
1153156321Sdamien	/*
1154156321Sdamien	 * Since it is now being written, we can clear its deferred write flag.
1155156321Sdamien	 */
1156156975Sdamien	bp->b_flags &= ~B_DEFERRED;
1157156321Sdamien}
1158156321Sdamien
1159156321Sdamien/*
1160156321Sdamien *	bawrite:
1161156321Sdamien *
1162156321Sdamien *	Asynchronous write.  Start output on a buffer, but do not wait for
1163156321Sdamien *	it to complete.  The buffer is released when the output completes.
1164156321Sdamien *
1165156975Sdamien *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1166156975Sdamien *	B_INVAL buffers.  Not us.
1167156975Sdamien */
1168156975Sdamienvoid
1169156975Sdamienbawrite(struct buf *bp)
1170156975Sdamien{
1171156321Sdamien
1172156321Sdamien	bp->b_flags |= B_ASYNC;
1173156321Sdamien	(void) bwrite(bp);
1174156321Sdamien}
1175156321Sdamien
1176156321Sdamien/*
1177156321Sdamien *	bwillwrite:
1178156321Sdamien *
1179156321Sdamien *	Called prior to the locking of any vnodes when we are expecting to
1180156321Sdamien *	write.  We do not want to starve the buffer cache with too many
1181156321Sdamien *	dirty buffers so we block here.  By blocking prior to the locking
1182156321Sdamien *	of any vnodes we attempt to avoid the situation where a locked vnode
1183156321Sdamien *	prevents the various system daemons from flushing related buffers.
1184156321Sdamien */
1185156321Sdamien
1186156321Sdamienvoid
1187156321Sdamienbwillwrite(void)
1188156321Sdamien{
1189156321Sdamien
1190156321Sdamien	if (numdirtybuffers >= hidirtybuffers) {
1191156321Sdamien		mtx_lock(&nblock);
1192156321Sdamien		while (numdirtybuffers >= hidirtybuffers) {
1193156321Sdamien			bd_wakeup(1);
1194156321Sdamien			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1195156321Sdamien			msleep(&needsbuffer, &nblock,
1196156321Sdamien			    (PRIBIO + 4), "flswai", 0);
1197156321Sdamien		}
1198156321Sdamien		mtx_unlock(&nblock);
1199156321Sdamien	}
1200156321Sdamien}
1201156321Sdamien
1202156321Sdamien/*
1203156321Sdamien * Return true if we have too many dirty buffers.
1204156321Sdamien */
1205156321Sdamienint
1206156321Sdamienbuf_dirty_count_severe(void)
1207156321Sdamien{
1208156321Sdamien
1209156321Sdamien	return(numdirtybuffers >= hidirtybuffers);
1210156321Sdamien}
1211156321Sdamien
1212156321Sdamienstatic __noinline int
1213156321Sdamienbuf_vm_page_count_severe(void)
1214178958Ssam{
1215178958Ssam
1216178958Ssam	KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1217178958Ssam
1218178958Ssam	return vm_page_count_severe();
1219178958Ssam}
1220178958Ssam
1221178958Ssam/*
1222178958Ssam *	brelse:
1223178958Ssam *
1224178958Ssam *	Release a busy buffer and, if requested, free its resources.  The
1225178958Ssam *	buffer will be stashed in the appropriate bufqueue[] allowing it
1226178958Ssam *	to be accessed later as a cache entity or reused for other purposes.
1227178958Ssam */
1228178958Ssamvoid
1229178958Ssambrelse(struct buf *bp)
1230178958Ssam{
1231178958Ssam	CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1232178958Ssam	    bp, bp->b_vp, bp->b_flags);
1233178958Ssam	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1234178958Ssam	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1235178958Ssam
1236178958Ssam	if (bp->b_flags & B_MANAGED) {
1237156321Sdamien		bqrelse(bp);
1238156321Sdamien		return;
1239156321Sdamien	}
1240156321Sdamien
1241156321Sdamien	if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1242178354Ssam	    bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1243178354Ssam		/*
1244156321Sdamien		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1245156321Sdamien		 * pages from being scrapped.  If the error is anything
1246156321Sdamien		 * other than an I/O error (EIO), assume that retrying
1247156321Sdamien		 * is futile.
1248156321Sdamien		 */
1249156321Sdamien		bp->b_ioflags &= ~BIO_ERROR;
1250156321Sdamien		bdirty(bp);
1251156321Sdamien	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1252156321Sdamien	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1253156321Sdamien		/*
1254156321Sdamien		 * Either a failed I/O or we were asked to free or not
1255156321Sdamien		 * cache the buffer.
1256156321Sdamien		 */
1257156321Sdamien		bp->b_flags |= B_INVAL;
1258156321Sdamien		if (!LIST_EMPTY(&bp->b_dep))
1259156321Sdamien			buf_deallocate(bp);
1260156321Sdamien		if (bp->b_flags & B_DELWRI) {
1261156321Sdamien			atomic_subtract_int(&numdirtybuffers, 1);
1262156321Sdamien			numdirtywakeup(lodirtybuffers);
1263156321Sdamien		}
1264156321Sdamien		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1265156321Sdamien		if ((bp->b_flags & B_VMIO) == 0) {
1266156321Sdamien			if (bp->b_bufsize)
1267156321Sdamien				allocbuf(bp, 0);
1268178958Ssam			if (bp->b_vp)
1269156321Sdamien				brelvp(bp);
1270156321Sdamien		}
1271156321Sdamien	}
1272190532Ssam
1273156321Sdamien	/*
1274156321Sdamien	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1275156321Sdamien	 * is called with B_DELWRI set, the underlying pages may wind up
1276156321Sdamien	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1277156321Sdamien	 * because pages associated with a B_DELWRI bp are marked clean.
1278156321Sdamien	 *
1279156321Sdamien	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1280156321Sdamien	 * if B_DELWRI is set.
1281156321Sdamien	 *
1282156321Sdamien	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1283156321Sdamien	 * on pages to return pages to the VM page queues.
1284156321Sdamien	 */
1285156321Sdamien	if (bp->b_flags & B_DELWRI)
1286156321Sdamien		bp->b_flags &= ~B_RELBUF;
1287156321Sdamien	else if (buf_vm_page_count_severe()) {
1288156321Sdamien		/*
1289156321Sdamien		 * The locking of the BO_LOCK is not necessary since
1290156321Sdamien		 * BKGRDINPROG cannot be set while we hold the buf
1291156321Sdamien		 * lock, it can only be cleared if it is already
1292156321Sdamien		 * pending.
1293156321Sdamien		 */
1294156321Sdamien		if (bp->b_vp) {
1295156321Sdamien			if (!(bp->b_vflags & BV_BKGRDINPROG))
1296156321Sdamien				bp->b_flags |= B_RELBUF;
1297156321Sdamien		} else
1298156321Sdamien			bp->b_flags |= B_RELBUF;
1299156321Sdamien	}
1300156321Sdamien
1301156321Sdamien	/*
1302156321Sdamien	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1303178354Ssam	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1304178354Ssam	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1305156321Sdamien	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1306156321Sdamien	 *
1307156321Sdamien	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1308173386Skevlo	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1309156321Sdamien	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1310156321Sdamien	 *
1311156321Sdamien	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1312156321Sdamien	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1313156321Sdamien	 * the commit state and we cannot afford to lose the buffer. If the
1314156321Sdamien	 * buffer has a background write in progress, we need to keep it
1315156321Sdamien	 * around to prevent it from being reconstituted and starting a second
1316156321Sdamien	 * background write.
1317178354Ssam	 */
1318156321Sdamien	if ((bp->b_flags & B_VMIO)
1319173386Skevlo	    && !(bp->b_vp->v_mount != NULL &&
1320173386Skevlo		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1321262007Skevlo		 !vn_isdisk(bp->b_vp, NULL) &&
1322178354Ssam		 (bp->b_flags & B_DELWRI))
1323173386Skevlo	    ) {
1324173386Skevlo
1325173386Skevlo		int i, j, resid;
1326173386Skevlo		vm_page_t m;
1327173386Skevlo		off_t foff;
1328173386Skevlo		vm_pindex_t poff;
1329156321Sdamien		vm_object_t obj;
1330156321Sdamien
1331156321Sdamien		obj = bp->b_bufobj->bo_object;
1332156321Sdamien
1333156321Sdamien		/*
1334156321Sdamien		 * Get the base offset and length of the buffer.  Note that
1335156321Sdamien		 * in the VMIO case if the buffer block size is not
1336156321Sdamien		 * page-aligned then b_data pointer may not be page-aligned.
1337156321Sdamien		 * But our b_pages[] array *IS* page aligned.
1338192468Ssam		 *
1339156321Sdamien		 * block sizes less then DEV_BSIZE (usually 512) are not
1340156321Sdamien		 * supported due to the page granularity bits (m->valid,
1341156321Sdamien		 * m->dirty, etc...).
1342156321Sdamien		 *
1343156321Sdamien		 * See man buf(9) for more information
1344192468Ssam		 */
1345156321Sdamien		resid = bp->b_bufsize;
1346156321Sdamien		foff = bp->b_offset;
1347156321Sdamien		VM_OBJECT_LOCK(obj);
1348156321Sdamien		for (i = 0; i < bp->b_npages; i++) {
1349178354Ssam			int had_bogus = 0;
1350178354Ssam
1351156321Sdamien			m = bp->b_pages[i];
1352156321Sdamien
1353156321Sdamien			/*
1354156321Sdamien			 * If we hit a bogus page, fixup *all* the bogus pages
1355156321Sdamien			 * now.
1356156321Sdamien			 */
1357190532Ssam			if (m == bogus_page) {
1358178354Ssam				poff = OFF_TO_IDX(bp->b_offset);
1359156321Sdamien				had_bogus = 1;
1360156321Sdamien
1361156321Sdamien				for (j = i; j < bp->b_npages; j++) {
1362156321Sdamien					vm_page_t mtmp;
1363156321Sdamien					mtmp = bp->b_pages[j];
1364156321Sdamien					if (mtmp == bogus_page) {
1365156321Sdamien						mtmp = vm_page_lookup(obj, poff + j);
1366156321Sdamien						if (!mtmp) {
1367156321Sdamien							panic("brelse: page missing\n");
1368156321Sdamien						}
1369156321Sdamien						bp->b_pages[j] = mtmp;
1370156321Sdamien					}
1371156321Sdamien				}
1372156321Sdamien
1373156321Sdamien				if ((bp->b_flags & B_INVAL) == 0) {
1374156321Sdamien					pmap_qenter(
1375178354Ssam					    trunc_page((vm_offset_t)bp->b_data),
1376178354Ssam					    bp->b_pages, bp->b_npages);
1377156321Sdamien				}
1378156321Sdamien				m = bp->b_pages[i];
1379156321Sdamien			}
1380156321Sdamien			if ((bp->b_flags & B_NOCACHE) ||
1381156321Sdamien			    (bp->b_ioflags & BIO_ERROR &&
1382156321Sdamien			     bp->b_iocmd == BIO_READ)) {
1383156321Sdamien				int poffset = foff & PAGE_MASK;
1384156321Sdamien				int presid = resid > (PAGE_SIZE - poffset) ?
1385156321Sdamien					(PAGE_SIZE - poffset) : resid;
1386178354Ssam
1387178354Ssam				KASSERT(presid >= 0, ("brelse: extra page"));
1388178354Ssam				vm_page_set_invalid(m, poffset, presid);
1389156321Sdamien				if (had_bogus)
1390178354Ssam					printf("avoided corruption bug in bogus_page/brelse code\n");
1391178354Ssam			}
1392178354Ssam			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1393178354Ssam			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1394178354Ssam		}
1395178354Ssam		VM_OBJECT_UNLOCK(obj);
1396178354Ssam		if (bp->b_flags & (B_INVAL | B_RELBUF))
1397178354Ssam			vfs_vmio_release(bp);
1398178354Ssam
1399178354Ssam	} else if (bp->b_flags & B_VMIO) {
1400156321Sdamien
1401178354Ssam		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1402178354Ssam			vfs_vmio_release(bp);
1403178354Ssam		}
1404178354Ssam
1405178354Ssam	} else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1406178354Ssam		if (bp->b_bufsize != 0)
1407190532Ssam			allocbuf(bp, 0);
1408190532Ssam		if (bp->b_vp != NULL)
1409178354Ssam			brelvp(bp);
1410178354Ssam	}
1411190532Ssam
1412190532Ssam	if (BUF_LOCKRECURSED(bp)) {
1413178354Ssam		/* do not release to free list */
1414178354Ssam		BUF_UNLOCK(bp);
1415178354Ssam		return;
1416190532Ssam	}
1417178354Ssam
1418178354Ssam	/* enqueue */
1419178354Ssam	mtx_lock(&bqlock);
1420178354Ssam	/* Handle delayed bremfree() processing. */
1421156321Sdamien	if (bp->b_flags & B_REMFREE) {
1422178354Ssam		struct bufobj *bo;
1423178354Ssam
1424178354Ssam		bo = bp->b_bufobj;
1425178354Ssam		if (bo != NULL)
1426156321Sdamien			BO_LOCK(bo);
1427178354Ssam		bremfreel(bp);
1428178354Ssam		if (bo != NULL)
1429156321Sdamien			BO_UNLOCK(bo);
1430178354Ssam	}
1431178354Ssam	if (bp->b_qindex != QUEUE_NONE)
1432178354Ssam		panic("brelse: free buffer onto another queue???");
1433178354Ssam
1434178354Ssam	/*
1435178354Ssam	 * If the buffer has junk contents signal it and eventually
1436178354Ssam	 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1437178354Ssam	 * doesn't find it.
1438156321Sdamien	 */
1439178354Ssam	if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1440178354Ssam	    (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1441178354Ssam		bp->b_flags |= B_INVAL;
1442178354Ssam	if (bp->b_flags & B_INVAL) {
1443156321Sdamien		if (bp->b_flags & B_DELWRI)
1444178354Ssam			bundirty(bp);
1445178354Ssam		if (bp->b_vp)
1446178354Ssam			brelvp(bp);
1447178354Ssam	}
1448178354Ssam
1449178354Ssam	/* buffers with no memory */
1450178354Ssam	if (bp->b_bufsize == 0) {
1451178354Ssam		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1452178354Ssam		if (bp->b_vflags & BV_BKGRDINPROG)
1453178354Ssam			panic("losing buffer 1");
1454156321Sdamien		if (bp->b_kvasize) {
1455156321Sdamien			bp->b_qindex = QUEUE_EMPTYKVA;
1456156321Sdamien		} else {
1457156321Sdamien			bp->b_qindex = QUEUE_EMPTY;
1458156321Sdamien		}
1459156321Sdamien		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1460178354Ssam	/* buffers with junk contents */
1461178354Ssam	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1462178354Ssam	    (bp->b_ioflags & BIO_ERROR)) {
1463156321Sdamien		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1464156321Sdamien		if (bp->b_vflags & BV_BKGRDINPROG)
1465156321Sdamien			panic("losing buffer 2");
1466156321Sdamien		bp->b_qindex = QUEUE_CLEAN;
1467178354Ssam		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1468156321Sdamien	/* remaining buffers */
1469156321Sdamien	} else {
1470156321Sdamien		if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1471156321Sdamien		    (B_DELWRI|B_NEEDSGIANT))
1472156321Sdamien			bp->b_qindex = QUEUE_DIRTY_GIANT;
1473178354Ssam		else if (bp->b_flags & B_DELWRI)
1474156321Sdamien			bp->b_qindex = QUEUE_DIRTY;
1475156321Sdamien		else
1476156321Sdamien			bp->b_qindex = QUEUE_CLEAN;
1477156321Sdamien		if (bp->b_flags & B_AGE)
1478178354Ssam			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1479178354Ssam		else
1480178354Ssam			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1481178354Ssam	}
1482178354Ssam	mtx_unlock(&bqlock);
1483178354Ssam
1484178354Ssam	/*
1485156321Sdamien	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1486206358Srpaulo	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1487178354Ssam	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1488156321Sdamien	 * if B_INVAL is set ).
1489156321Sdamien	 */
1490156321Sdamien
1491156321Sdamien	if (!(bp->b_flags & B_DELWRI)) {
1492156321Sdamien		struct bufobj *bo;
1493156321Sdamien
1494156321Sdamien		bo = bp->b_bufobj;
1495156321Sdamien		if (bo != NULL)
1496262007Skevlo			BO_LOCK(bo);
1497178354Ssam		bufcountwakeup(bp);
1498156321Sdamien		if (bo != NULL)
1499156321Sdamien			BO_UNLOCK(bo);
1500156321Sdamien	}
1501156321Sdamien
1502156321Sdamien	/*
1503156321Sdamien	 * Something we can maybe free or reuse
1504156321Sdamien	 */
1505156321Sdamien	if (bp->b_bufsize || bp->b_kvasize)
1506156321Sdamien		bufspacewakeup();
1507178354Ssam
1508178354Ssam	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1509178354Ssam	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1510178354Ssam		panic("brelse: not dirty");
1511178354Ssam	/* unlock */
1512178354Ssam	BUF_UNLOCK(bp);
1513190532Ssam}
1514178354Ssam
1515178354Ssam/*
1516178354Ssam * Release a buffer back to the appropriate queue but do not try to free
1517178354Ssam * it.  The buffer is expected to be used again soon.
1518178354Ssam *
1519178354Ssam * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1520178354Ssam * biodone() to requeue an async I/O on completion.  It is also used when
1521178354Ssam * known good buffers need to be requeued but we think we may need the data
1522156321Sdamien * again soon.
1523156321Sdamien *
1524156321Sdamien * XXX we should be able to leave the B_RELBUF hint set on completion.
1525156321Sdamien */
1526156321Sdamienvoid
1527156321Sdamienbqrelse(struct buf *bp)
1528156321Sdamien{
1529156321Sdamien	struct bufobj *bo;
1530156321Sdamien
1531156321Sdamien	CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1532156321Sdamien	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1533156321Sdamien	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1534156321Sdamien
1535156321Sdamien	if (BUF_LOCKRECURSED(bp)) {
1536156321Sdamien		/* do not release to free list */
1537243857Sglebius		BUF_UNLOCK(bp);
1538156321Sdamien		return;
1539156321Sdamien	}
1540156321Sdamien
1541156321Sdamien	bo = bp->b_bufobj;
1542156321Sdamien	if (bp->b_flags & B_MANAGED) {
1543156321Sdamien		if (bp->b_flags & B_REMFREE) {
1544156321Sdamien			mtx_lock(&bqlock);
1545156321Sdamien			if (bo != NULL)
1546156321Sdamien				BO_LOCK(bo);
1547156321Sdamien			bremfreel(bp);
1548156321Sdamien			if (bo != NULL)
1549156321Sdamien				BO_UNLOCK(bo);
1550156321Sdamien			mtx_unlock(&bqlock);
1551156321Sdamien		}
1552156321Sdamien		bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1553156321Sdamien		BUF_UNLOCK(bp);
1554156321Sdamien		return;
1555156321Sdamien	}
1556156321Sdamien
1557156321Sdamien	mtx_lock(&bqlock);
1558156321Sdamien	/* Handle delayed bremfree() processing. */
1559192468Ssam	if (bp->b_flags & B_REMFREE) {
1560156321Sdamien		if (bo != NULL)
1561156321Sdamien			BO_LOCK(bo);
1562156321Sdamien		bremfreel(bp);
1563156321Sdamien		if (bo != NULL)
1564156321Sdamien			BO_UNLOCK(bo);
1565192468Ssam	}
1566156321Sdamien	if (bp->b_qindex != QUEUE_NONE)
1567156321Sdamien		panic("bqrelse: free buffer onto another queue???");
1568156321Sdamien	/* buffers with stale but valid contents */
1569156321Sdamien	if (bp->b_flags & B_DELWRI) {
1570156321Sdamien		if (bp->b_flags & B_NEEDSGIANT)
1571156321Sdamien			bp->b_qindex = QUEUE_DIRTY_GIANT;
1572178354Ssam		else
1573178354Ssam			bp->b_qindex = QUEUE_DIRTY;
1574178354Ssam		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1575178354Ssam	} else {
1576156321Sdamien		/*
1577178354Ssam		 * The locking of the BO_LOCK for checking of the
1578156321Sdamien		 * BV_BKGRDINPROG is not necessary since the
1579156321Sdamien		 * BV_BKGRDINPROG cannot be set while we hold the buf
1580156321Sdamien		 * lock, it can only be cleared if it is already
1581156321Sdamien		 * pending.
1582190532Ssam		 */
1583178354Ssam		if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1584156321Sdamien			bp->b_qindex = QUEUE_CLEAN;
1585156321Sdamien			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1586156321Sdamien			    b_freelist);
1587156321Sdamien		} else {
1588156321Sdamien			/*
1589156321Sdamien			 * We are too low on memory, we have to try to free
1590156321Sdamien			 * the buffer (most importantly: the wired pages
1591156321Sdamien			 * making up its backing store) *now*.
1592156321Sdamien			 */
1593178354Ssam			mtx_unlock(&bqlock);
1594178354Ssam			brelse(bp);
1595156321Sdamien			return;
1596156321Sdamien		}
1597156321Sdamien	}
1598156321Sdamien	mtx_unlock(&bqlock);
1599156321Sdamien
1600156321Sdamien	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) {
1601156321Sdamien		if (bo != NULL)
1602156321Sdamien			BO_LOCK(bo);
1603156321Sdamien		bufcountwakeup(bp);
1604156321Sdamien		if (bo != NULL)
1605178354Ssam			BO_UNLOCK(bo);
1606156321Sdamien	}
1607156321Sdamien
1608178354Ssam	/*
1609156321Sdamien	 * Something we can maybe free or reuse.
1610156321Sdamien	 */
1611156321Sdamien	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1612178354Ssam		bufspacewakeup();
1613156321Sdamien
1614156975Sdamien	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1615178354Ssam	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1616156975Sdamien		panic("bqrelse: not dirty");
1617156975Sdamien	/* unlock */
1618156321Sdamien	BUF_UNLOCK(bp);
1619178354Ssam}
1620178354Ssam
1621178354Ssam/* Give pages used by the bp back to the VM system (where possible) */
1622156321Sdamienstatic void
1623178354Ssamvfs_vmio_release(struct buf *bp)
1624178354Ssam{
1625178354Ssam	int i;
1626178354Ssam	vm_page_t m;
1627178354Ssam
1628178354Ssam	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1629178354Ssam	for (i = 0; i < bp->b_npages; i++) {
1630178354Ssam		m = bp->b_pages[i];
1631178354Ssam		bp->b_pages[i] = NULL;
1632178354Ssam		/*
1633178354Ssam		 * In order to keep page LRU ordering consistent, put
1634178354Ssam		 * everything on the inactive queue.
1635178354Ssam		 */
1636156321Sdamien		vm_page_lock(m);
1637178354Ssam		vm_page_unwire(m, 0);
1638178354Ssam		/*
1639178354Ssam		 * We don't mess with busy pages, it is
1640156321Sdamien		 * the responsibility of the process that
1641178354Ssam		 * busied the pages to deal with them.
1642178354Ssam		 */
1643178354Ssam		if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1644178354Ssam		    m->wire_count == 0) {
1645156321Sdamien			/*
1646178354Ssam			 * Might as well free the page if we can and it has
1647178354Ssam			 * no valid data.  We also free the page if the
1648178354Ssam			 * buffer was used for direct I/O
1649178354Ssam			 */
1650156321Sdamien			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1651178354Ssam				vm_page_free(m);
1652178354Ssam			} else if (bp->b_flags & B_DIRECT) {
1653178354Ssam				vm_page_try_to_free(m);
1654178354Ssam			} else if (buf_vm_page_count_severe()) {
1655178354Ssam				vm_page_try_to_cache(m);
1656178354Ssam			}
1657178354Ssam		}
1658156321Sdamien		vm_page_unlock(m);
1659178354Ssam	}
1660156321Sdamien	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1661178354Ssam	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1662178354Ssam
1663178354Ssam	if (bp->b_bufsize) {
1664178354Ssam		bufspacewakeup();
1665178354Ssam		bp->b_bufsize = 0;
1666178354Ssam	}
1667178354Ssam	bp->b_npages = 0;
1668178354Ssam	bp->b_flags &= ~B_VMIO;
1669178354Ssam	if (bp->b_vp)
1670178354Ssam		brelvp(bp);
1671178354Ssam}
1672178354Ssam
1673178354Ssam/*
1674178354Ssam * Check to see if a block at a particular lbn is available for a clustered
1675156321Sdamien * write.
1676178354Ssam */
1677156321Sdamienstatic int
1678178354Ssamvfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1679178354Ssam{
1680178354Ssam	struct buf *bpa;
1681178354Ssam	int match;
1682178354Ssam
1683178354Ssam	match = 0;
1684178354Ssam
1685178354Ssam	/* If the buf isn't in core skip it */
1686156321Sdamien	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1687178354Ssam		return (0);
1688156321Sdamien
1689178354Ssam	/* If the buf is busy we don't want to wait for it */
1690178354Ssam	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1691178354Ssam		return (0);
1692178354Ssam
1693156321Sdamien	/* Only cluster with valid clusterable delayed write buffers */
1694178354Ssam	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1695156321Sdamien	    (B_DELWRI | B_CLUSTEROK))
1696156321Sdamien		goto done;
1697156321Sdamien
1698165352Sbms	if (bpa->b_bufsize != size)
1699156321Sdamien		goto done;
1700165352Sbms
1701178354Ssam	/*
1702156321Sdamien	 * Check to see if it is in the expected place on disk and that the
1703178354Ssam	 * block has been mapped.
1704156321Sdamien	 */
1705178354Ssam	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1706156321Sdamien		match = 1;
1707178354Ssamdone:
1708178354Ssam	BUF_UNLOCK(bpa);
1709156321Sdamien	return (match);
1710178354Ssam}
1711178354Ssam
1712178354Ssam/*
1713178354Ssam *	vfs_bio_awrite:
1714178354Ssam *
1715178354Ssam *	Implement clustered async writes for clearing out B_DELWRI buffers.
1716178354Ssam *	This is much better then the old way of writing only one buffer at
1717178354Ssam *	a time.  Note that we may not be presented with the buffers in the
1718156321Sdamien *	correct order, so we search for the cluster in both directions.
1719156321Sdamien */
1720156321Sdamienint
1721156321Sdamienvfs_bio_awrite(struct buf *bp)
1722156321Sdamien{
1723156321Sdamien	struct bufobj *bo;
1724178354Ssam	int i;
1725178354Ssam	int j;
1726178354Ssam	daddr_t lblkno = bp->b_lblkno;
1727156321Sdamien	struct vnode *vp = bp->b_vp;
1728156321Sdamien	int ncl;
1729156321Sdamien	int nwritten;
1730178704Sthompsa	int size;
1731156321Sdamien	int maxcl;
1732178354Ssam
1733178354Ssam	bo = &vp->v_bufobj;
1734178354Ssam	/*
1735178354Ssam	 * right now we support clustered writing only to regular files.  If
1736178354Ssam	 * we find a clusterable block we could be in the middle of a cluster
1737156321Sdamien	 * rather then at the beginning.
1738156321Sdamien	 */
1739178354Ssam	if ((vp->v_type == VREG) &&
1740156321Sdamien	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1741178704Sthompsa	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1742178704Sthompsa
1743178704Sthompsa		size = vp->v_mount->mnt_stat.f_iosize;
1744156321Sdamien		maxcl = MAXPHYS / size;
1745178354Ssam
1746178354Ssam		BO_LOCK(bo);
1747178354Ssam		for (i = 1; i < maxcl; i++)
1748178704Sthompsa			if (vfs_bio_clcheck(vp, size, lblkno + i,
1749178354Ssam			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1750178354Ssam				break;
1751178704Sthompsa
1752178704Sthompsa		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1753178704Sthompsa			if (vfs_bio_clcheck(vp, size, lblkno - j,
1754156321Sdamien			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1755156321Sdamien				break;
1756156321Sdamien		BO_UNLOCK(bo);
1757156321Sdamien		--j;
1758156321Sdamien		ncl = i + j;
1759156321Sdamien		/*
1760156321Sdamien		 * this is a possible cluster write
1761156321Sdamien		 */
1762156321Sdamien		if (ncl != 1) {
1763156321Sdamien			BUF_UNLOCK(bp);
1764156321Sdamien			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1765156321Sdamien			return nwritten;
1766156321Sdamien		}
1767156321Sdamien	}
1768156321Sdamien	bremfree(bp);
1769156321Sdamien	bp->b_flags |= B_ASYNC;
1770156321Sdamien	/*
1771156321Sdamien	 * default (old) behavior, writing out only one block
1772156321Sdamien	 *
1773156321Sdamien	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1774156321Sdamien	 */
1775156321Sdamien	nwritten = bp->b_bufsize;
1776156321Sdamien	(void) bwrite(bp);
1777178354Ssam
1778156321Sdamien	return nwritten;
1779156321Sdamien}
1780156321Sdamien
1781156321Sdamien/*
1782156321Sdamien *	getnewbuf:
1783156321Sdamien *
1784156321Sdamien *	Find and initialize a new buffer header, freeing up existing buffers
1785156321Sdamien *	in the bufqueues as necessary.  The new buffer is returned locked.
1786156321Sdamien *
1787156321Sdamien *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1788156321Sdamien *	buffer away, the caller must set B_INVAL prior to calling brelse().
1789156321Sdamien *
1790156321Sdamien *	We block if:
1791156321Sdamien *		We have insufficient buffer headers
1792156321Sdamien *		We have insufficient buffer space
1793156321Sdamien *		buffer_map is too fragmented ( space reservation fails )
1794156321Sdamien *		If we have to flush dirty buffers ( but we try to avoid this )
1795156321Sdamien *
1796156321Sdamien *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1797156321Sdamien *	Instead we ask the buf daemon to do it for us.  We attempt to
1798156321Sdamien *	avoid piecemeal wakeups of the pageout daemon.
1799156321Sdamien */
1800156321Sdamien
1801156321Sdamienstatic struct buf *
1802156321Sdamiengetnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
1803156321Sdamien    int gbflags)
1804156321Sdamien{
1805156321Sdamien	struct thread *td;
1806156321Sdamien	struct buf *bp;
1807156321Sdamien	struct buf *nbp;
1808156321Sdamien	int defrag = 0;
1809156321Sdamien	int nqindex;
1810156321Sdamien	static int flushingbufs;
1811156321Sdamien
1812156321Sdamien	td = curthread;
1813156321Sdamien	/*
1814156321Sdamien	 * We can't afford to block since we might be holding a vnode lock,
1815156321Sdamien	 * which may prevent system daemons from running.  We deal with
1816156321Sdamien	 * low-memory situations by proactively returning memory and running
1817156321Sdamien	 * async I/O rather then sync I/O.
1818156321Sdamien	 */
1819156321Sdamien	atomic_add_int(&getnewbufcalls, 1);
1820156321Sdamien	atomic_subtract_int(&getnewbufrestarts, 1);
1821156321Sdamienrestart:
1822156321Sdamien	atomic_add_int(&getnewbufrestarts, 1);
1823156321Sdamien
1824156321Sdamien	/*
1825156321Sdamien	 * Setup for scan.  If we do not have enough free buffers,
1826156321Sdamien	 * we setup a degenerate case that immediately fails.  Note
1827156321Sdamien	 * that if we are specially marked process, we are allowed to
1828156321Sdamien	 * dip into our reserves.
1829156321Sdamien	 *
1830156321Sdamien	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1831156321Sdamien	 *
1832156321Sdamien	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1833178354Ssam	 * However, there are a number of cases (defragging, reusing, ...)
1834156321Sdamien	 * where we cannot backup.
1835156321Sdamien	 */
1836156321Sdamien	mtx_lock(&bqlock);
1837156321Sdamien	nqindex = QUEUE_EMPTYKVA;
1838156321Sdamien	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1839156321Sdamien
1840156321Sdamien	if (nbp == NULL) {
1841156321Sdamien		/*
1842156321Sdamien		 * If no EMPTYKVA buffers and we are either
1843156321Sdamien		 * defragging or reusing, locate a CLEAN buffer
1844156321Sdamien		 * to free or reuse.  If bufspace useage is low
1845156321Sdamien		 * skip this step so we can allocate a new buffer.
1846156321Sdamien		 */
1847156321Sdamien		if (defrag || bufspace >= lobufspace) {
1848156321Sdamien			nqindex = QUEUE_CLEAN;
1849156321Sdamien			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1850156321Sdamien		}
1851156321Sdamien
1852156321Sdamien		/*
1853156321Sdamien		 * If we could not find or were not allowed to reuse a
1854156321Sdamien		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1855156321Sdamien		 * buffer.  We can only use an EMPTY buffer if allocating
1856156321Sdamien		 * its KVA would not otherwise run us out of buffer space.
1857156321Sdamien		 */
1858156321Sdamien		if (nbp == NULL && defrag == 0 &&
1859156321Sdamien		    bufspace + maxsize < hibufspace) {
1860156321Sdamien			nqindex = QUEUE_EMPTY;
1861156321Sdamien			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1862156321Sdamien		}
1863156321Sdamien	}
1864156321Sdamien
1865156321Sdamien	/*
1866156321Sdamien	 * Run scan, possibly freeing data and/or kva mappings on the fly
1867156321Sdamien	 * depending.
1868156321Sdamien	 */
1869156321Sdamien
1870156321Sdamien	while ((bp = nbp) != NULL) {
1871156321Sdamien		int qindex = nqindex;
1872156321Sdamien
1873156321Sdamien		/*
1874156321Sdamien		 * Calculate next bp ( we can only use it if we do not block
1875156321Sdamien		 * or do other fancy things ).
1876156321Sdamien		 */
1877156321Sdamien		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1878156321Sdamien			switch(qindex) {
1879178354Ssam			case QUEUE_EMPTY:
1880178354Ssam				nqindex = QUEUE_EMPTYKVA;
1881156321Sdamien				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1882156321Sdamien					break;
1883156321Sdamien				/* FALLTHROUGH */
1884156321Sdamien			case QUEUE_EMPTYKVA:
1885156321Sdamien				nqindex = QUEUE_CLEAN;
1886178354Ssam				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1887156321Sdamien					break;
1888156321Sdamien				/* FALLTHROUGH */
1889156321Sdamien			case QUEUE_CLEAN:
1890156321Sdamien				/*
1891156321Sdamien				 * nbp is NULL.
1892156321Sdamien				 */
1893156321Sdamien				break;
1894156321Sdamien			}
1895156321Sdamien		}
1896178354Ssam		/*
1897178354Ssam		 * If we are defragging then we need a buffer with
1898156321Sdamien		 * b_kvasize != 0.  XXX this situation should no longer
1899156321Sdamien		 * occur, if defrag is non-zero the buffer's b_kvasize
1900156321Sdamien		 * should also be non-zero at this point.  XXX
1901156321Sdamien		 */
1902156321Sdamien		if (defrag && bp->b_kvasize == 0) {
1903178354Ssam			printf("Warning: defrag empty buffer %p\n", bp);
1904156321Sdamien			continue;
1905156321Sdamien		}
1906156321Sdamien
1907156321Sdamien		/*
1908156321Sdamien		 * Start freeing the bp.  This is somewhat involved.  nbp
1909156321Sdamien		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1910156321Sdamien		 */
1911156321Sdamien		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1912156321Sdamien			continue;
1913156321Sdamien		if (bp->b_vp) {
1914178354Ssam			BO_LOCK(bp->b_bufobj);
1915178354Ssam			if (bp->b_vflags & BV_BKGRDINPROG) {
1916156321Sdamien				BO_UNLOCK(bp->b_bufobj);
1917156321Sdamien				BUF_UNLOCK(bp);
1918220502Sbschmidt				continue;
1919156321Sdamien			}
1920156321Sdamien			BO_UNLOCK(bp->b_bufobj);
1921156321Sdamien		}
1922156321Sdamien		CTR6(KTR_BUF,
1923156321Sdamien		    "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1924156321Sdamien		    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1925156321Sdamien		    bp->b_kvasize, bp->b_bufsize, qindex);
1926252727Sadrian
1927156321Sdamien		/*
1928156321Sdamien		 * Sanity Checks
1929156321Sdamien		 */
1930156321Sdamien		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1931178354Ssam
1932156321Sdamien		/*
1933156321Sdamien		 * Note: we no longer distinguish between VMIO and non-VMIO
1934156321Sdamien		 * buffers.
1935156321Sdamien		 */
1936156321Sdamien
1937156321Sdamien		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1938156321Sdamien
1939156321Sdamien		if (bp->b_bufobj != NULL)
1940156321Sdamien			BO_LOCK(bp->b_bufobj);
1941156321Sdamien		bremfreel(bp);
1942156321Sdamien		if (bp->b_bufobj != NULL)
1943156321Sdamien			BO_UNLOCK(bp->b_bufobj);
1944156321Sdamien		mtx_unlock(&bqlock);
1945156321Sdamien
1946156321Sdamien		if (qindex == QUEUE_CLEAN) {
1947156321Sdamien			if (bp->b_flags & B_VMIO) {
1948156321Sdamien				bp->b_flags &= ~B_ASYNC;
1949156321Sdamien				vfs_vmio_release(bp);
1950156321Sdamien			}
1951156321Sdamien			if (bp->b_vp)
1952156321Sdamien				brelvp(bp);
1953156321Sdamien		}
1954156321Sdamien
1955156321Sdamien		/*
1956156321Sdamien		 * NOTE:  nbp is now entirely invalid.  We can only restart
1957156321Sdamien		 * the scan from this point on.
1958156321Sdamien		 *
1959156321Sdamien		 * Get the rest of the buffer freed up.  b_kva* is still
1960156321Sdamien		 * valid after this operation.
1961156321Sdamien		 */
1962156321Sdamien
1963156321Sdamien		if (bp->b_rcred != NOCRED) {
1964156321Sdamien			crfree(bp->b_rcred);
1965156321Sdamien			bp->b_rcred = NOCRED;
1966156321Sdamien		}
1967156321Sdamien		if (bp->b_wcred != NOCRED) {
1968156321Sdamien			crfree(bp->b_wcred);
1969156321Sdamien			bp->b_wcred = NOCRED;
1970156321Sdamien		}
1971156321Sdamien		if (!LIST_EMPTY(&bp->b_dep))
1972156321Sdamien			buf_deallocate(bp);
1973156321Sdamien		if (bp->b_vflags & BV_BKGRDINPROG)
1974156321Sdamien			panic("losing buffer 3");
1975156321Sdamien		KASSERT(bp->b_vp == NULL,
1976156321Sdamien		    ("bp: %p still has vnode %p.  qindex: %d",
1977156321Sdamien		    bp, bp->b_vp, qindex));
1978156321Sdamien		KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1979156321Sdamien		   ("bp: %p still on a buffer list. xflags %X",
1980156321Sdamien		    bp, bp->b_xflags));
1981156321Sdamien
1982156321Sdamien		if (bp->b_bufsize)
1983156321Sdamien			allocbuf(bp, 0);
1984178354Ssam
1985178354Ssam		bp->b_flags = 0;
1986156321Sdamien		bp->b_ioflags = 0;
1987156321Sdamien		bp->b_xflags = 0;
1988156321Sdamien		KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
1989156321Sdamien		    ("buf %p still counted as free?", bp));
1990156321Sdamien		bp->b_vflags = 0;
1991156321Sdamien		bp->b_vp = NULL;
1992178354Ssam		bp->b_blkno = bp->b_lblkno = 0;
1993156321Sdamien		bp->b_offset = NOOFFSET;
1994156321Sdamien		bp->b_iodone = 0;
1995156321Sdamien		bp->b_error = 0;
1996156321Sdamien		bp->b_resid = 0;
1997156321Sdamien		bp->b_bcount = 0;
1998156321Sdamien		bp->b_npages = 0;
1999156321Sdamien		bp->b_dirtyoff = bp->b_dirtyend = 0;
2000156321Sdamien		bp->b_bufobj = NULL;
2001156321Sdamien		bp->b_pin_count = 0;
2002156321Sdamien		bp->b_fsprivate1 = NULL;
2003156321Sdamien		bp->b_fsprivate2 = NULL;
2004156321Sdamien		bp->b_fsprivate3 = NULL;
2005156321Sdamien
2006156321Sdamien		LIST_INIT(&bp->b_dep);
2007156321Sdamien
2008156321Sdamien		/*
2009156321Sdamien		 * If we are defragging then free the buffer.
2010156321Sdamien		 */
2011156321Sdamien		if (defrag) {
2012156321Sdamien			bp->b_flags |= B_INVAL;
2013156321Sdamien			bfreekva(bp);
2014156321Sdamien			brelse(bp);
2015156321Sdamien			defrag = 0;
2016156321Sdamien			goto restart;
2017156321Sdamien		}
2018156321Sdamien
2019156321Sdamien		/*
2020156321Sdamien		 * Notify any waiters for the buffer lock about
2021156321Sdamien		 * identity change by freeing the buffer.
2022156321Sdamien		 */
2023156321Sdamien		if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2024156321Sdamien			bp->b_flags |= B_INVAL;
2025156321Sdamien			bfreekva(bp);
2026156321Sdamien			brelse(bp);
2027156321Sdamien			goto restart;
2028156321Sdamien		}
2029156321Sdamien
2030156321Sdamien		/*
2031156321Sdamien		 * If we are overcomitted then recover the buffer and its
2032156321Sdamien		 * KVM space.  This occurs in rare situations when multiple
2033156321Sdamien		 * processes are blocked in getnewbuf() or allocbuf().
2034156321Sdamien		 */
2035156321Sdamien		if (bufspace >= hibufspace)
2036156321Sdamien			flushingbufs = 1;
2037156321Sdamien		if (flushingbufs && bp->b_kvasize != 0) {
2038156321Sdamien			bp->b_flags |= B_INVAL;
2039156321Sdamien			bfreekva(bp);
2040156321Sdamien			brelse(bp);
2041156321Sdamien			goto restart;
2042156321Sdamien		}
2043156321Sdamien		if (bufspace < lobufspace)
2044156321Sdamien			flushingbufs = 0;
2045156321Sdamien		break;
2046156321Sdamien	}
2047156321Sdamien
2048156321Sdamien	/*
2049156321Sdamien	 * If we exhausted our list, sleep as appropriate.  We may have to
2050156321Sdamien	 * wakeup various daemons and write out some dirty buffers.
2051156321Sdamien	 *
2052156321Sdamien	 * Generally we are sleeping due to insufficient buffer space.
2053156321Sdamien	 */
2054156321Sdamien
2055156321Sdamien	if (bp == NULL) {
2056156321Sdamien		int flags, norunbuf;
2057156321Sdamien		char *waitmsg;
2058156321Sdamien		int fl;
2059156321Sdamien
2060156321Sdamien		if (defrag) {
2061156321Sdamien			flags = VFS_BIO_NEED_BUFSPACE;
2062156321Sdamien			waitmsg = "nbufkv";
2063156321Sdamien		} else if (bufspace >= hibufspace) {
2064156321Sdamien			waitmsg = "nbufbs";
2065156321Sdamien			flags = VFS_BIO_NEED_BUFSPACE;
2066156321Sdamien		} else {
2067156321Sdamien			waitmsg = "newbuf";
2068156321Sdamien			flags = VFS_BIO_NEED_ANY;
2069156321Sdamien		}
2070156321Sdamien		mtx_lock(&nblock);
2071156321Sdamien		needsbuffer |= flags;
2072156321Sdamien		mtx_unlock(&nblock);
2073156321Sdamien		mtx_unlock(&bqlock);
2074156321Sdamien
2075156321Sdamien		bd_speedup();	/* heeeelp */
2076156321Sdamien		if (gbflags & GB_NOWAIT_BD)
2077156321Sdamien			return (NULL);
2078156321Sdamien
2079156321Sdamien		mtx_lock(&nblock);
2080178354Ssam		while (needsbuffer & flags) {
2081156321Sdamien			if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2082178354Ssam				mtx_unlock(&nblock);
2083156321Sdamien				/*
2084156321Sdamien				 * getblk() is called with a vnode
2085156321Sdamien				 * locked, and some majority of the
2086156321Sdamien				 * dirty buffers may as well belong to
2087156321Sdamien				 * the vnode. Flushing the buffers
2088156321Sdamien				 * there would make a progress that
2089156321Sdamien				 * cannot be achieved by the
2090156321Sdamien				 * buf_daemon, that cannot lock the
2091156321Sdamien				 * vnode.
2092156321Sdamien				 */
2093178354Ssam				norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2094178354Ssam				    (td->td_pflags & TDP_NORUNNINGBUF);
2095156321Sdamien				/* play bufdaemon */
2096156321Sdamien				td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2097156321Sdamien				fl = buf_do_flush(vp);
2098156321Sdamien				td->td_pflags &= norunbuf;
2099156321Sdamien				mtx_lock(&nblock);
2100156321Sdamien				if (fl != 0)
2101156321Sdamien					continue;
2102156321Sdamien				if ((needsbuffer & flags) == 0)
2103156321Sdamien					break;
2104156321Sdamien			}
2105156321Sdamien			if (msleep(&needsbuffer, &nblock,
2106156321Sdamien			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2107156321Sdamien				mtx_unlock(&nblock);
2108156321Sdamien				return (NULL);
2109156321Sdamien			}
2110156321Sdamien		}
2111156321Sdamien		mtx_unlock(&nblock);
2112156321Sdamien	} else {
2113156321Sdamien		/*
2114156321Sdamien		 * We finally have a valid bp.  We aren't quite out of the
2115156321Sdamien		 * woods, we still have to reserve kva space.  In order
2116156321Sdamien		 * to keep fragmentation sane we only allocate kva in
2117156321Sdamien		 * BKVASIZE chunks.
2118156321Sdamien		 */
2119156321Sdamien		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2120156321Sdamien
2121156321Sdamien		if (maxsize != bp->b_kvasize) {
2122156321Sdamien			vm_offset_t addr = 0;
2123156321Sdamien
2124156321Sdamien			bfreekva(bp);
2125156321Sdamien
2126156321Sdamien			vm_map_lock(buffer_map);
2127156321Sdamien			if (vm_map_findspace(buffer_map,
2128156321Sdamien				vm_map_min(buffer_map), maxsize, &addr)) {
2129156321Sdamien				/*
2130156321Sdamien				 * Uh oh.  Buffer map is to fragmented.  We
2131156321Sdamien				 * must defragment the map.
2132156321Sdamien				 */
2133156321Sdamien				atomic_add_int(&bufdefragcnt, 1);
2134156321Sdamien				vm_map_unlock(buffer_map);
2135156321Sdamien				defrag = 1;
2136156321Sdamien				bp->b_flags |= B_INVAL;
2137156321Sdamien				brelse(bp);
2138156321Sdamien				goto restart;
2139156321Sdamien			}
2140156321Sdamien			if (addr) {
2141156321Sdamien				vm_map_insert(buffer_map, NULL, 0,
2142156321Sdamien					addr, addr + maxsize,
2143156321Sdamien					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2144156321Sdamien
2145156321Sdamien				bp->b_kvabase = (caddr_t) addr;
2146156321Sdamien				bp->b_kvasize = maxsize;
2147178354Ssam				atomic_add_long(&bufspace, bp->b_kvasize);
2148156321Sdamien				atomic_add_int(&bufreusecnt, 1);
2149156321Sdamien			}
2150156321Sdamien			vm_map_unlock(buffer_map);
2151156321Sdamien		}
2152156321Sdamien		bp->b_saveaddr = bp->b_kvabase;
2153156321Sdamien		bp->b_data = bp->b_saveaddr;
2154156321Sdamien	}
2155156321Sdamien	return(bp);
2156156321Sdamien}
2157156321Sdamien
2158156321Sdamien/*
2159156321Sdamien *	buf_daemon:
2160156321Sdamien *
2161156321Sdamien *	buffer flushing daemon.  Buffers are normally flushed by the
2162156321Sdamien *	update daemon but if it cannot keep up this process starts to
2163156321Sdamien *	take the load in an attempt to prevent getnewbuf() from blocking.
2164156321Sdamien */
2165156321Sdamien
2166156321Sdamienstatic struct kproc_desc buf_kp = {
2167156321Sdamien	"bufdaemon",
2168156321Sdamien	buf_daemon,
2169156321Sdamien	&bufdaemonproc
2170156321Sdamien};
2171190526SsamSYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2172156321Sdamien
2173156321Sdamienstatic int
2174156321Sdamienbuf_do_flush(struct vnode *vp)
2175156321Sdamien{
2176156321Sdamien	int flushed;
2177156321Sdamien
2178190526Ssam	flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2179190526Ssam	/* The list empty check here is slightly racy */
2180156321Sdamien	if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2181156321Sdamien		mtx_lock(&Giant);
2182190526Ssam		flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2183190526Ssam		mtx_unlock(&Giant);
2184156321Sdamien	}
2185156321Sdamien	if (flushed == 0) {
2186190526Ssam		/*
2187190526Ssam		 * Could not find any buffers without rollback
2188156321Sdamien		 * dependencies, so just write the first one
2189156321Sdamien		 * in the hopes of eventually making progress.
2190156321Sdamien		 */
2191156321Sdamien		flushbufqueues(vp, QUEUE_DIRTY, 1);
2192156321Sdamien		if (!TAILQ_EMPTY(
2193156321Sdamien			    &bufqueues[QUEUE_DIRTY_GIANT])) {
2194156321Sdamien			mtx_lock(&Giant);
2195156321Sdamien			flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2196156321Sdamien			mtx_unlock(&Giant);
2197178354Ssam		}
2198156321Sdamien	}
2199156321Sdamien	return (flushed);
2200156321Sdamien}
2201156321Sdamien
2202156321Sdamienstatic void
2203178354Ssambuf_daemon()
2204178354Ssam{
2205156321Sdamien	int lodirtysave;
2206156321Sdamien
2207156321Sdamien	/*
2208156321Sdamien	 * This process needs to be suspended prior to shutdown sync.
2209156321Sdamien	 */
2210170530Ssam	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2211170530Ssam	    SHUTDOWN_PRI_LAST);
2212170530Ssam
2213170530Ssam	/*
2214156321Sdamien	 * This process is allowed to take the buffer cache to the limit
2215156321Sdamien	 */
2216156321Sdamien	curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2217156321Sdamien	mtx_lock(&bdlock);
2218170530Ssam	for (;;) {
2219170530Ssam		bd_request = 0;
2220170530Ssam		mtx_unlock(&bdlock);
2221170530Ssam
2222156321Sdamien		kproc_suspend_check(bufdaemonproc);
2223156321Sdamien		lodirtysave = lodirtybuffers;
2224156321Sdamien		if (bd_speedupreq) {
2225156321Sdamien			lodirtybuffers = numdirtybuffers / 2;
2226156321Sdamien			bd_speedupreq = 0;
2227156321Sdamien		}
2228178354Ssam		/*
2229178354Ssam		 * Do the flush.  Limit the amount of in-transit I/O we
2230156321Sdamien		 * allow to build up, otherwise we would completely saturate
2231156321Sdamien		 * the I/O system.  Wakeup any waiting processes before we
2232156321Sdamien		 * normally would so they can run in parallel with our drain.
2233156321Sdamien		 */
2234156321Sdamien		while (numdirtybuffers > lodirtybuffers) {
2235156321Sdamien			if (buf_do_flush(NULL) == 0)
2236156321Sdamien				break;
2237178354Ssam			kern_yield(PRI_UNCHANGED);
2238156321Sdamien		}
2239156321Sdamien		lodirtybuffers = lodirtysave;
2240156321Sdamien
2241156321Sdamien		/*
2242156321Sdamien		 * Only clear bd_request if we have reached our low water
2243178354Ssam		 * mark.  The buf_daemon normally waits 1 second and
2244178354Ssam		 * then incrementally flushes any dirty buffers that have
2245156321Sdamien		 * built up, within reason.
2246178354Ssam		 *
2247178354Ssam		 * If we were unable to hit our low water mark and couldn't
2248156321Sdamien		 * find any flushable buffers, we sleep half a second.
2249156321Sdamien		 * Otherwise we loop immediately.
2250156321Sdamien		 */
2251156321Sdamien		mtx_lock(&bdlock);
2252156321Sdamien		if (numdirtybuffers <= lodirtybuffers) {
2253156321Sdamien			/*
2254156321Sdamien			 * We reached our low water mark, reset the
2255156321Sdamien			 * request and sleep until we are needed again.
2256156321Sdamien			 * The sleep is just so the suspend code works.
2257178354Ssam			 */
2258178354Ssam			bd_request = 0;
2259156321Sdamien			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2260156321Sdamien		} else {
2261156321Sdamien			/*
2262156321Sdamien			 * We couldn't find any flushable dirty buffers but
2263156321Sdamien			 * still have too many dirty buffers, we
2264156321Sdamien			 * have to sleep and try again.  (rare)
2265156321Sdamien			 */
2266156321Sdamien			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2267156321Sdamien		}
2268156321Sdamien	}
2269156321Sdamien}
2270156321Sdamien
2271156321Sdamien/*
2272156321Sdamien *	flushbufqueues:
2273156321Sdamien *
2274156321Sdamien *	Try to flush a buffer in the dirty queue.  We must be careful to
2275156321Sdamien *	free up B_INVAL buffers instead of write them, which NFS is
2276156321Sdamien *	particularly sensitive to.
2277156321Sdamien */
2278156321Sdamienstatic int flushwithdeps = 0;
2279156321SdamienSYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2280156321Sdamien    0, "Number of buffers flushed with dependecies that require rollbacks");
2281156321Sdamien
2282156321Sdamienstatic int
2283156321Sdamienflushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2284156321Sdamien{
2285156321Sdamien	struct buf *sentinel;
2286156321Sdamien	struct vnode *vp;
2287156321Sdamien	struct mount *mp;
2288156321Sdamien	struct buf *bp;
2289156321Sdamien	int hasdeps;
2290156321Sdamien	int flushed;
2291156321Sdamien	int target;
2292156321Sdamien
2293156321Sdamien	if (lvp == NULL) {
2294156321Sdamien		target = numdirtybuffers - lodirtybuffers;
2295156321Sdamien		if (flushdeps && target > 2)
2296156321Sdamien			target /= 2;
2297156321Sdamien	} else
2298156321Sdamien		target = flushbufqtarget;
2299178354Ssam	flushed = 0;
2300156321Sdamien	bp = NULL;
2301156321Sdamien	sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2302178354Ssam	sentinel->b_qindex = QUEUE_SENTINEL;
2303178354Ssam	mtx_lock(&bqlock);
2304156321Sdamien	TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2305178354Ssam	while (flushed != target) {
2306156321Sdamien		bp = TAILQ_NEXT(sentinel, b_freelist);
2307178354Ssam		if (bp != NULL) {
2308156975Sdamien			TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2309178354Ssam			TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2310178354Ssam			    b_freelist);
2311178354Ssam		} else
2312178354Ssam			break;
2313178354Ssam		/*
2314178354Ssam		 * Skip sentinels inserted by other invocations of the
2315178354Ssam		 * flushbufqueues(), taking care to not reorder them.
2316178354Ssam		 */
2317178354Ssam		if (bp->b_qindex == QUEUE_SENTINEL)
2318178354Ssam			continue;
2319178354Ssam		/*
2320170530Ssam		 * Only flush the buffers that belong to the
2321156321Sdamien		 * vnode locked by the curthread.
2322156321Sdamien		 */
2323156321Sdamien		if (lvp != NULL && bp->b_vp != lvp)
2324156321Sdamien			continue;
2325156321Sdamien		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2326156321Sdamien			continue;
2327156321Sdamien		if (bp->b_pin_count > 0) {
2328156321Sdamien			BUF_UNLOCK(bp);
2329156321Sdamien			continue;
2330156321Sdamien		}
2331156321Sdamien		BO_LOCK(bp->b_bufobj);
2332156321Sdamien		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2333156321Sdamien		    (bp->b_flags & B_DELWRI) == 0) {
2334156321Sdamien			BO_UNLOCK(bp->b_bufobj);
2335156321Sdamien			BUF_UNLOCK(bp);
2336156321Sdamien			continue;
2337156321Sdamien		}
2338156321Sdamien		BO_UNLOCK(bp->b_bufobj);
2339156321Sdamien		if (bp->b_flags & B_INVAL) {
2340156321Sdamien			bremfreel(bp);
2341156321Sdamien			mtx_unlock(&bqlock);
2342156321Sdamien			brelse(bp);
2343156321Sdamien			flushed++;
2344156321Sdamien			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2345156321Sdamien			mtx_lock(&bqlock);
2346156321Sdamien			continue;
2347156321Sdamien		}
2348156321Sdamien
2349156321Sdamien		if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2350156321Sdamien			if (flushdeps == 0) {
2351156321Sdamien				BUF_UNLOCK(bp);
2352156321Sdamien				continue;
2353156321Sdamien			}
2354156321Sdamien			hasdeps = 1;
2355156321Sdamien		} else
2356156321Sdamien			hasdeps = 0;
2357156321Sdamien		/*
2358156321Sdamien		 * We must hold the lock on a vnode before writing
2359156321Sdamien		 * one of its buffers. Otherwise we may confuse, or
2360156321Sdamien		 * in the case of a snapshot vnode, deadlock the
2361156321Sdamien		 * system.
2362156321Sdamien		 *
2363156321Sdamien		 * The lock order here is the reverse of the normal
2364156321Sdamien		 * of vnode followed by buf lock.  This is ok because
2365190526Ssam		 * the NOWAIT will prevent deadlock.
2366156321Sdamien		 */
2367156321Sdamien		vp = bp->b_vp;
2368156321Sdamien		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2369156321Sdamien			BUF_UNLOCK(bp);
2370156321Sdamien			continue;
2371156321Sdamien		}
2372156321Sdamien		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2373156321Sdamien			mtx_unlock(&bqlock);
2374156321Sdamien			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2375156321Sdamien			    bp, bp->b_vp, bp->b_flags);
2376156321Sdamien			if (curproc == bufdaemonproc)
2377156321Sdamien				vfs_bio_awrite(bp);
2378156321Sdamien			else {
2379170530Ssam				bremfree(bp);
2380156321Sdamien				bwrite(bp);
2381156321Sdamien				notbufdflashes++;
2382156321Sdamien			}
2383156321Sdamien			vn_finished_write(mp);
2384170530Ssam			VOP_UNLOCK(vp, 0);
2385156321Sdamien			flushwithdeps += hasdeps;
2386156321Sdamien			flushed++;
2387156321Sdamien
2388156321Sdamien			/*
2389156321Sdamien			 * Sleeping on runningbufspace while holding
2390156321Sdamien			 * vnode lock leads to deadlock.
2391156321Sdamien			 */
2392156321Sdamien			if (curproc == bufdaemonproc)
2393156321Sdamien				waitrunningbufspace();
2394156321Sdamien			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2395156321Sdamien			mtx_lock(&bqlock);
2396156321Sdamien			continue;
2397156321Sdamien		}
2398156321Sdamien		vn_finished_write(mp);
2399156321Sdamien		BUF_UNLOCK(bp);
2400156321Sdamien	}
2401195618Srpaulo	TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2402195618Srpaulo	mtx_unlock(&bqlock);
2403156321Sdamien	free(sentinel, M_TEMP);
2404156321Sdamien	return (flushed);
2405156321Sdamien}
2406156321Sdamien
2407156321Sdamien/*
2408156321Sdamien * Check to see if a block is currently memory resident.
2409156321Sdamien */
2410156321Sdamienstruct buf *
2411156321Sdamienincore(struct bufobj *bo, daddr_t blkno)
2412156321Sdamien{
2413156321Sdamien	struct buf *bp;
2414156321Sdamien
2415156321Sdamien	BO_LOCK(bo);
2416156321Sdamien	bp = gbincore(bo, blkno);
2417156321Sdamien	BO_UNLOCK(bo);
2418156321Sdamien	return (bp);
2419156321Sdamien}
2420156321Sdamien
2421156321Sdamien/*
2422156321Sdamien * Returns true if no I/O is needed to access the
2423156321Sdamien * associated VM object.  This is like incore except
2424156321Sdamien * it also hunts around in the VM system for the data.
2425156321Sdamien */
2426156321Sdamien
2427156321Sdamienstatic int
2428156321Sdamieninmem(struct vnode * vp, daddr_t blkno)
2429178354Ssam{
2430156975Sdamien	vm_object_t obj;
2431156321Sdamien	vm_offset_t toff, tinc, size;
2432156321Sdamien	vm_page_t m;
2433178354Ssam	vm_ooffset_t off;
2434178354Ssam
2435156321Sdamien	ASSERT_VOP_LOCKED(vp, "inmem");
2436156321Sdamien
2437178354Ssam	if (incore(&vp->v_bufobj, blkno))
2438178354Ssam		return 1;
2439170530Ssam	if (vp->v_mount == NULL)
2440170530Ssam		return 0;
2441178354Ssam	obj = vp->v_object;
2442170530Ssam	if (obj == NULL)
2443178354Ssam		return (0);
2444178931Sthompsa
2445178931Sthompsa	size = PAGE_SIZE;
2446170530Ssam	if (size > vp->v_mount->mnt_stat.f_iosize)
2447170530Ssam		size = vp->v_mount->mnt_stat.f_iosize;
2448170530Ssam	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2449170530Ssam
2450170530Ssam	VM_OBJECT_LOCK(obj);
2451178354Ssam	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2452156321Sdamien		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2453170530Ssam		if (!m)
2454156321Sdamien			goto notinmem;
2455178354Ssam		tinc = size;
2456170530Ssam		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2457156321Sdamien			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2458178354Ssam		if (vm_page_is_valid(m,
2459178354Ssam		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2460178354Ssam			goto notinmem;
2461170530Ssam	}
2462170530Ssam	VM_OBJECT_UNLOCK(obj);
2463178354Ssam	return 1;
2464170530Ssam
2465170530Ssamnotinmem:
2466170530Ssam	VM_OBJECT_UNLOCK(obj);
2467170530Ssam	return (0);
2468170530Ssam}
2469170530Ssam
2470170530Ssam/*
2471170530Ssam * Set the dirty range for a buffer based on the status of the dirty
2472170530Ssam * bits in the pages comprising the buffer.  The range is limited
2473170530Ssam * to the size of the buffer.
2474170530Ssam *
2475170530Ssam * Tell the VM system that the pages associated with this buffer
2476170530Ssam * are clean.  This is used for delayed writes where the data is
2477170530Ssam * going to go to disk eventually without additional VM intevention.
2478170530Ssam *
2479170530Ssam * Note that while we only really need to clean through to b_bcount, we
2480170530Ssam * just go ahead and clean through to b_bufsize.
2481170530Ssam */
2482170530Ssamstatic void
2483170530Ssamvfs_clean_pages_dirty_buf(struct buf *bp)
2484170530Ssam{
2485170530Ssam	vm_ooffset_t foff, noff, eoff;
2486170530Ssam	vm_page_t m;
2487170530Ssam	int i;
2488170530Ssam
2489170530Ssam	if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2490170530Ssam		return;
2491156321Sdamien
2492156321Sdamien	foff = bp->b_offset;
2493178354Ssam	KASSERT(bp->b_offset != NOOFFSET,
2494178354Ssam	    ("vfs_clean_pages_dirty_buf: no buffer offset"));
2495178354Ssam
2496178354Ssam	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2497178354Ssam	vfs_drain_busy_pages(bp);
2498178354Ssam	vfs_setdirty_locked_object(bp);
2499178354Ssam	for (i = 0; i < bp->b_npages; i++) {
2500178354Ssam		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2501178354Ssam		eoff = noff;
2502178354Ssam		if (eoff > bp->b_offset + bp->b_bufsize)
2503156321Sdamien			eoff = bp->b_offset + bp->b_bufsize;
2504178354Ssam		m = bp->b_pages[i];
2505156321Sdamien		vfs_page_set_validclean(bp, foff, m);
2506178354Ssam		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2507178354Ssam		foff = noff;
2508178354Ssam	}
2509178354Ssam	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2510156321Sdamien}
2511178354Ssam
2512178354Ssamstatic void
2513178354Ssamvfs_setdirty_locked_object(struct buf *bp)
2514178354Ssam{
2515178354Ssam	vm_object_t object;
2516178354Ssam	int i;
2517178354Ssam
2518178354Ssam	object = bp->b_bufobj->bo_object;
2519178354Ssam	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2520178354Ssam
2521178354Ssam	/*
2522178354Ssam	 * We qualify the scan for modified pages on whether the
2523178354Ssam	 * object has been flushed yet.
2524178354Ssam	 */
2525178354Ssam	if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2526178354Ssam		vm_offset_t boffset;
2527178354Ssam		vm_offset_t eoffset;
2528178354Ssam
2529178354Ssam		/*
2530178354Ssam		 * test the pages to see if they have been modified directly
2531178354Ssam		 * by users through the VM system.
2532178354Ssam		 */
2533178354Ssam		for (i = 0; i < bp->b_npages; i++)
2534178354Ssam			vm_page_test_dirty(bp->b_pages[i]);
2535156321Sdamien
2536156321Sdamien		/*
2537156321Sdamien		 * Calculate the encompassing dirty range, boffset and eoffset,
2538156321Sdamien		 * (eoffset - boffset) bytes.
2539156321Sdamien		 */
2540156321Sdamien
2541156321Sdamien		for (i = 0; i < bp->b_npages; i++) {
2542156321Sdamien			if (bp->b_pages[i]->dirty)
2543156321Sdamien				break;
2544156321Sdamien		}
2545178354Ssam		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2546156321Sdamien
2547156321Sdamien		for (i = bp->b_npages - 1; i >= 0; --i) {
2548156321Sdamien			if (bp->b_pages[i]->dirty) {
2549156321Sdamien				break;
2550156321Sdamien			}
2551156321Sdamien		}
2552156321Sdamien		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2553156321Sdamien
2554156321Sdamien		/*
2555156321Sdamien		 * Fit it to the buffer.
2556156321Sdamien		 */
2557156321Sdamien
2558178354Ssam		if (eoffset > bp->b_bcount)
2559178354Ssam			eoffset = bp->b_bcount;
2560178354Ssam
2561178354Ssam		/*
2562178354Ssam		 * If we have a good dirty range, merge with the existing
2563178354Ssam		 * dirty range.
2564178354Ssam		 */
2565178354Ssam
2566156321Sdamien		if (boffset < eoffset) {
2567156321Sdamien			if (bp->b_dirtyoff > boffset)
2568156321Sdamien				bp->b_dirtyoff = boffset;
2569156321Sdamien			if (bp->b_dirtyend < eoffset)
2570156321Sdamien				bp->b_dirtyend = eoffset;
2571156321Sdamien		}
2572156321Sdamien	}
2573156321Sdamien}
2574156321Sdamien
2575156321Sdamien/*
2576156321Sdamien *	getblk:
2577156321Sdamien *
2578156321Sdamien *	Get a block given a specified block and offset into a file/device.
2579156321Sdamien *	The buffers B_DONE bit will be cleared on return, making it almost
2580156321Sdamien * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2581156321Sdamien *	return.  The caller should clear B_INVAL prior to initiating a
2582156321Sdamien *	READ.
2583156321Sdamien *
2584156321Sdamien *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2585156321Sdamien *	an existing buffer.
2586156321Sdamien *
2587156321Sdamien *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2588156321Sdamien *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2589156321Sdamien *	and then cleared based on the backing VM.  If the previous buffer is
2590156321Sdamien *	non-0-sized but invalid, B_CACHE will be cleared.
2591156321Sdamien *
2592156321Sdamien *	If getblk() must create a new buffer, the new buffer is returned with
2593156321Sdamien *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2594156321Sdamien *	case it is returned with B_INVAL clear and B_CACHE set based on the
2595156321Sdamien *	backing VM.
2596156321Sdamien *
2597156321Sdamien *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2598156321Sdamien *	B_CACHE bit is clear.
2599156321Sdamien *
2600156321Sdamien *	What this means, basically, is that the caller should use B_CACHE to
2601156321Sdamien *	determine whether the buffer is fully valid or not and should clear
2602156321Sdamien *	B_INVAL prior to issuing a read.  If the caller intends to validate
2603156321Sdamien *	the buffer by loading its data area with something, the caller needs
2604156321Sdamien *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2605156321Sdamien *	the caller should set B_CACHE ( as an optimization ), else the caller
2606156321Sdamien *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2607156321Sdamien *	a write attempt or if it was a successfull read.  If the caller
2608156321Sdamien *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2609156321Sdamien *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2610156321Sdamien */
2611156321Sdamienstruct buf *
2612156321Sdamiengetblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2613156321Sdamien    int flags)
2614156321Sdamien{
2615156321Sdamien	struct buf *bp;
2616156321Sdamien	struct bufobj *bo;
2617156321Sdamien	int error;
2618156321Sdamien
2619156321Sdamien	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2620156321Sdamien	ASSERT_VOP_LOCKED(vp, "getblk");
2621156321Sdamien	if (size > MAXBSIZE)
2622156321Sdamien		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2623156321Sdamien
2624156321Sdamien	bo = &vp->v_bufobj;
2625156321Sdamienloop:
2626156321Sdamien	/*
2627156321Sdamien	 * Block if we are low on buffers.   Certain processes are allowed
2628156321Sdamien	 * to completely exhaust the buffer cache.
2629156321Sdamien         *
2630156321Sdamien         * If this check ever becomes a bottleneck it may be better to
2631156321Sdamien         * move it into the else, when gbincore() fails.  At the moment
2632156321Sdamien         * it isn't a problem.
2633156321Sdamien	 *
2634156321Sdamien	 * XXX remove if 0 sections (clean this up after its proven)
2635156321Sdamien         */
2636156321Sdamien	if (numfreebuffers == 0) {
2637156321Sdamien		if (TD_IS_IDLETHREAD(curthread))
2638156321Sdamien			return NULL;
2639156321Sdamien		mtx_lock(&nblock);
2640156321Sdamien		needsbuffer |= VFS_BIO_NEED_ANY;
2641156321Sdamien		mtx_unlock(&nblock);
2642156321Sdamien	}
2643156321Sdamien
2644156321Sdamien	BO_LOCK(bo);
2645156321Sdamien	bp = gbincore(bo, blkno);
2646156321Sdamien	if (bp != NULL) {
2647156321Sdamien		int lockflags;
2648156321Sdamien		/*
2649156321Sdamien		 * Buffer is in-core.  If the buffer is not busy, it must
2650156321Sdamien		 * be on a queue.
2651156321Sdamien		 */
2652156321Sdamien		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2653156321Sdamien
2654156321Sdamien		if (flags & GB_LOCK_NOWAIT)
2655156321Sdamien			lockflags |= LK_NOWAIT;
2656156321Sdamien
2657156321Sdamien		error = BUF_TIMELOCK(bp, lockflags,
2658156321Sdamien		    BO_MTX(bo), "getblk", slpflag, slptimeo);
2659156321Sdamien
2660156321Sdamien		/*
2661156321Sdamien		 * If we slept and got the lock we have to restart in case
2662156321Sdamien		 * the buffer changed identities.
2663156321Sdamien		 */
2664156321Sdamien		if (error == ENOLCK)
2665156321Sdamien			goto loop;
2666156321Sdamien		/* We timed out or were interrupted. */
2667156321Sdamien		else if (error)
2668156321Sdamien			return (NULL);
2669156321Sdamien
2670156321Sdamien		/*
2671156321Sdamien		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2672156321Sdamien		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2673156321Sdamien		 * and for a VMIO buffer B_CACHE is adjusted according to the
2674156321Sdamien		 * backing VM cache.
2675156321Sdamien		 */
2676156321Sdamien		if (bp->b_flags & B_INVAL)
2677156321Sdamien			bp->b_flags &= ~B_CACHE;
2678156321Sdamien		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2679156321Sdamien			bp->b_flags |= B_CACHE;
2680156321Sdamien		BO_LOCK(bo);
2681156321Sdamien		bremfree(bp);
2682156321Sdamien		BO_UNLOCK(bo);
2683156321Sdamien
2684156321Sdamien		/*
2685156321Sdamien		 * check for size inconsistancies for non-VMIO case.
2686156321Sdamien		 */
2687156321Sdamien
2688178354Ssam		if (bp->b_bcount != size) {
2689156321Sdamien			if ((bp->b_flags & B_VMIO) == 0 ||
2690178354Ssam			    (size > bp->b_kvasize)) {
2691156321Sdamien				if (bp->b_flags & B_DELWRI) {
2692156321Sdamien					/*
2693156321Sdamien					 * If buffer is pinned and caller does
2694156321Sdamien					 * not want sleep  waiting for it to be
2695156321Sdamien					 * unpinned, bail out
2696178354Ssam					 * */
2697156321Sdamien					if (bp->b_pin_count > 0) {
2698156321Sdamien						if (flags & GB_LOCK_NOWAIT) {
2699156321Sdamien							bqrelse(bp);
2700156321Sdamien							return (NULL);
2701156321Sdamien						} else {
2702156321Sdamien							bunpin_wait(bp);
2703178354Ssam						}
2704156321Sdamien					}
2705156321Sdamien					bp->b_flags |= B_NOCACHE;
2706156321Sdamien					bwrite(bp);
2707156321Sdamien				} else {
2708156321Sdamien					if (LIST_EMPTY(&bp->b_dep)) {
2709156321Sdamien						bp->b_flags |= B_RELBUF;
2710156321Sdamien						brelse(bp);
2711156321Sdamien					} else {
2712156321Sdamien						bp->b_flags |= B_NOCACHE;
2713156321Sdamien						bwrite(bp);
2714156321Sdamien					}
2715156321Sdamien				}
2716156321Sdamien				goto loop;
2717156321Sdamien			}
2718156321Sdamien		}
2719156321Sdamien
2720156321Sdamien		/*
2721156321Sdamien		 * If the size is inconsistant in the VMIO case, we can resize
2722156321Sdamien		 * the buffer.  This might lead to B_CACHE getting set or
2723156321Sdamien		 * cleared.  If the size has not changed, B_CACHE remains
2724156321Sdamien		 * unchanged from its previous state.
2725156321Sdamien		 */
2726156321Sdamien
2727178354Ssam		if (bp->b_bcount != size)
2728178354Ssam			allocbuf(bp, size);
2729178354Ssam
2730156321Sdamien		KASSERT(bp->b_offset != NOOFFSET,
2731156321Sdamien		    ("getblk: no buffer offset"));
2732178354Ssam
2733156321Sdamien		/*
2734156321Sdamien		 * A buffer with B_DELWRI set and B_CACHE clear must
2735156321Sdamien		 * be committed before we can return the buffer in
2736156321Sdamien		 * order to prevent the caller from issuing a read
2737156321Sdamien		 * ( due to B_CACHE not being set ) and overwriting
2738156321Sdamien		 * it.
2739156321Sdamien		 *
2740156321Sdamien		 * Most callers, including NFS and FFS, need this to
2741156321Sdamien		 * operate properly either because they assume they
2742156321Sdamien		 * can issue a read if B_CACHE is not set, or because
2743178354Ssam		 * ( for example ) an uncached B_DELWRI might loop due
2744156321Sdamien		 * to softupdates re-dirtying the buffer.  In the latter
2745156321Sdamien		 * case, B_CACHE is set after the first write completes,
2746178354Ssam		 * preventing further loops.
2747156321Sdamien		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2748156321Sdamien		 * above while extending the buffer, we cannot allow the
2749156321Sdamien		 * buffer to remain with B_CACHE set after the write
2750156321Sdamien		 * completes or it will represent a corrupt state.  To
2751156321Sdamien		 * deal with this we set B_NOCACHE to scrap the buffer
2752156321Sdamien		 * after the write.
2753156321Sdamien		 *
2754192468Ssam		 * We might be able to do something fancy, like setting
2755192468Ssam		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2756192468Ssam		 * so the below call doesn't set B_CACHE, but that gets real
2757192468Ssam		 * confusing.  This is much easier.
2758192468Ssam		 */
2759192468Ssam
2760192468Ssam		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2761192468Ssam			bp->b_flags |= B_NOCACHE;
2762156321Sdamien			bwrite(bp);
2763156321Sdamien			goto loop;
2764156321Sdamien		}
2765156321Sdamien		bp->b_flags &= ~B_DONE;
2766156321Sdamien	} else {
2767156321Sdamien		int bsize, maxsize, vmio;
2768156321Sdamien		off_t offset;
2769156321Sdamien
2770156321Sdamien		/*
2771156321Sdamien		 * Buffer is not in-core, create new buffer.  The buffer
2772156321Sdamien		 * returned by getnewbuf() is locked.  Note that the returned
2773156321Sdamien		 * buffer is also considered valid (not marked B_INVAL).
2774156321Sdamien		 */
2775170530Ssam		BO_UNLOCK(bo);
2776170530Ssam		/*
2777170530Ssam		 * If the user does not want us to create the buffer, bail out
2778170530Ssam		 * here.
2779170530Ssam		 */
2780170530Ssam		if (flags & GB_NOCREAT)
2781170530Ssam			return NULL;
2782170530Ssam		bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
2783170530Ssam		offset = blkno * bsize;
2784156321Sdamien		vmio = vp->v_object != NULL;
2785170530Ssam		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2786170530Ssam		maxsize = imax(maxsize, bsize);
2787156321Sdamien
2788156321Sdamien		bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
2789156321Sdamien		if (bp == NULL) {
2790156321Sdamien			if (slpflag || slptimeo)
2791156321Sdamien				return NULL;
2792156321Sdamien			goto loop;
2793156321Sdamien		}
2794156321Sdamien
2795156321Sdamien		/*
2796156321Sdamien		 * This code is used to make sure that a buffer is not
2797156321Sdamien		 * created while the getnewbuf routine is blocked.
2798156321Sdamien		 * This can be a problem whether the vnode is locked or not.
2799156321Sdamien		 * If the buffer is created out from under us, we have to
2800156321Sdamien		 * throw away the one we just created.
2801156321Sdamien		 *
2802156321Sdamien		 * Note: this must occur before we associate the buffer
2803156321Sdamien		 * with the vp especially considering limitations in
2804156321Sdamien		 * the splay tree implementation when dealing with duplicate
2805156321Sdamien		 * lblkno's.
2806156321Sdamien		 */
2807156321Sdamien		BO_LOCK(bo);
2808170530Ssam		if (gbincore(bo, blkno)) {
2809170530Ssam			BO_UNLOCK(bo);
2810170530Ssam			bp->b_flags |= B_INVAL;
2811170530Ssam			brelse(bp);
2812170530Ssam			goto loop;
2813170530Ssam		}
2814170530Ssam
2815170530Ssam		/*
2816170530Ssam		 * Insert the buffer into the hash, so that it can
2817170530Ssam		 * be found by incore.
2818170530Ssam		 */
2819170530Ssam		bp->b_blkno = bp->b_lblkno = blkno;
2820170530Ssam		bp->b_offset = offset;
2821170530Ssam		bgetvp(vp, bp);
2822170530Ssam		BO_UNLOCK(bo);
2823170530Ssam
2824170530Ssam		/*
2825170530Ssam		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2826170530Ssam		 * buffer size starts out as 0, B_CACHE will be set by
2827178354Ssam		 * allocbuf() for the VMIO case prior to it testing the
2828170530Ssam		 * backing store for validity.
2829170530Ssam		 */
2830170530Ssam
2831178354Ssam		if (vmio) {
2832170530Ssam			bp->b_flags |= B_VMIO;
2833170530Ssam			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2834170530Ssam			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2835170530Ssam			    bp, vp->v_object, bp->b_bufobj->bo_object));
2836170530Ssam		} else {
2837170530Ssam			bp->b_flags &= ~B_VMIO;
2838170530Ssam			KASSERT(bp->b_bufobj->bo_object == NULL,
2839170530Ssam			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2840170530Ssam			    bp, bp->b_bufobj->bo_object));
2841170530Ssam		}
2842170530Ssam
2843170530Ssam		allocbuf(bp, size);
2844170530Ssam		bp->b_flags &= ~B_DONE;
2845	}
2846	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2847	BUF_ASSERT_HELD(bp);
2848	KASSERT(bp->b_bufobj == bo,
2849	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2850	return (bp);
2851}
2852
2853/*
2854 * Get an empty, disassociated buffer of given size.  The buffer is initially
2855 * set to B_INVAL.
2856 */
2857struct buf *
2858geteblk(int size, int flags)
2859{
2860	struct buf *bp;
2861	int maxsize;
2862
2863	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2864	while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
2865		if ((flags & GB_NOWAIT_BD) &&
2866		    (curthread->td_pflags & TDP_BUFNEED) != 0)
2867			return (NULL);
2868	}
2869	allocbuf(bp, size);
2870	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2871	BUF_ASSERT_HELD(bp);
2872	return (bp);
2873}
2874
2875
2876/*
2877 * This code constitutes the buffer memory from either anonymous system
2878 * memory (in the case of non-VMIO operations) or from an associated
2879 * VM object (in the case of VMIO operations).  This code is able to
2880 * resize a buffer up or down.
2881 *
2882 * Note that this code is tricky, and has many complications to resolve
2883 * deadlock or inconsistant data situations.  Tread lightly!!!
2884 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2885 * the caller.  Calling this code willy nilly can result in the loss of data.
2886 *
2887 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2888 * B_CACHE for the non-VMIO case.
2889 */
2890
2891int
2892allocbuf(struct buf *bp, int size)
2893{
2894	int newbsize, mbsize;
2895	int i;
2896
2897	BUF_ASSERT_HELD(bp);
2898
2899	if (bp->b_kvasize < size)
2900		panic("allocbuf: buffer too small");
2901
2902	if ((bp->b_flags & B_VMIO) == 0) {
2903		caddr_t origbuf;
2904		int origbufsize;
2905		/*
2906		 * Just get anonymous memory from the kernel.  Don't
2907		 * mess with B_CACHE.
2908		 */
2909		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2910		if (bp->b_flags & B_MALLOC)
2911			newbsize = mbsize;
2912		else
2913			newbsize = round_page(size);
2914
2915		if (newbsize < bp->b_bufsize) {
2916			/*
2917			 * malloced buffers are not shrunk
2918			 */
2919			if (bp->b_flags & B_MALLOC) {
2920				if (newbsize) {
2921					bp->b_bcount = size;
2922				} else {
2923					free(bp->b_data, M_BIOBUF);
2924					if (bp->b_bufsize) {
2925						atomic_subtract_long(
2926						    &bufmallocspace,
2927						    bp->b_bufsize);
2928						bufspacewakeup();
2929						bp->b_bufsize = 0;
2930					}
2931					bp->b_saveaddr = bp->b_kvabase;
2932					bp->b_data = bp->b_saveaddr;
2933					bp->b_bcount = 0;
2934					bp->b_flags &= ~B_MALLOC;
2935				}
2936				return 1;
2937			}
2938			vm_hold_free_pages(bp, newbsize);
2939		} else if (newbsize > bp->b_bufsize) {
2940			/*
2941			 * We only use malloced memory on the first allocation.
2942			 * and revert to page-allocated memory when the buffer
2943			 * grows.
2944			 */
2945			/*
2946			 * There is a potential smp race here that could lead
2947			 * to bufmallocspace slightly passing the max.  It
2948			 * is probably extremely rare and not worth worrying
2949			 * over.
2950			 */
2951			if ( (bufmallocspace < maxbufmallocspace) &&
2952				(bp->b_bufsize == 0) &&
2953				(mbsize <= PAGE_SIZE/2)) {
2954
2955				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2956				bp->b_bufsize = mbsize;
2957				bp->b_bcount = size;
2958				bp->b_flags |= B_MALLOC;
2959				atomic_add_long(&bufmallocspace, mbsize);
2960				return 1;
2961			}
2962			origbuf = NULL;
2963			origbufsize = 0;
2964			/*
2965			 * If the buffer is growing on its other-than-first allocation,
2966			 * then we revert to the page-allocation scheme.
2967			 */
2968			if (bp->b_flags & B_MALLOC) {
2969				origbuf = bp->b_data;
2970				origbufsize = bp->b_bufsize;
2971				bp->b_data = bp->b_kvabase;
2972				if (bp->b_bufsize) {
2973					atomic_subtract_long(&bufmallocspace,
2974					    bp->b_bufsize);
2975					bufspacewakeup();
2976					bp->b_bufsize = 0;
2977				}
2978				bp->b_flags &= ~B_MALLOC;
2979				newbsize = round_page(newbsize);
2980			}
2981			vm_hold_load_pages(
2982			    bp,
2983			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2984			    (vm_offset_t) bp->b_data + newbsize);
2985			if (origbuf) {
2986				bcopy(origbuf, bp->b_data, origbufsize);
2987				free(origbuf, M_BIOBUF);
2988			}
2989		}
2990	} else {
2991		int desiredpages;
2992
2993		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2994		desiredpages = (size == 0) ? 0 :
2995			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2996
2997		if (bp->b_flags & B_MALLOC)
2998			panic("allocbuf: VMIO buffer can't be malloced");
2999		/*
3000		 * Set B_CACHE initially if buffer is 0 length or will become
3001		 * 0-length.
3002		 */
3003		if (size == 0 || bp->b_bufsize == 0)
3004			bp->b_flags |= B_CACHE;
3005
3006		if (newbsize < bp->b_bufsize) {
3007			/*
3008			 * DEV_BSIZE aligned new buffer size is less then the
3009			 * DEV_BSIZE aligned existing buffer size.  Figure out
3010			 * if we have to remove any pages.
3011			 */
3012			if (desiredpages < bp->b_npages) {
3013				vm_page_t m;
3014
3015				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3016				for (i = desiredpages; i < bp->b_npages; i++) {
3017					/*
3018					 * the page is not freed here -- it
3019					 * is the responsibility of
3020					 * vnode_pager_setsize
3021					 */
3022					m = bp->b_pages[i];
3023					KASSERT(m != bogus_page,
3024					    ("allocbuf: bogus page found"));
3025					while (vm_page_sleep_if_busy(m, TRUE,
3026					    "biodep"))
3027						continue;
3028
3029					bp->b_pages[i] = NULL;
3030					vm_page_lock(m);
3031					vm_page_unwire(m, 0);
3032					vm_page_unlock(m);
3033				}
3034				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3035				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3036				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
3037				bp->b_npages = desiredpages;
3038			}
3039		} else if (size > bp->b_bcount) {
3040			/*
3041			 * We are growing the buffer, possibly in a
3042			 * byte-granular fashion.
3043			 */
3044			vm_object_t obj;
3045			vm_offset_t toff;
3046			vm_offset_t tinc;
3047
3048			/*
3049			 * Step 1, bring in the VM pages from the object,
3050			 * allocating them if necessary.  We must clear
3051			 * B_CACHE if these pages are not valid for the
3052			 * range covered by the buffer.
3053			 */
3054
3055			obj = bp->b_bufobj->bo_object;
3056
3057			VM_OBJECT_LOCK(obj);
3058			while (bp->b_npages < desiredpages) {
3059				vm_page_t m;
3060
3061				/*
3062				 * We must allocate system pages since blocking
3063				 * here could intefere with paging I/O, no
3064				 * matter which process we are.
3065				 *
3066				 * We can only test VPO_BUSY here.  Blocking on
3067				 * m->busy might lead to a deadlock:
3068				 *  vm_fault->getpages->cluster_read->allocbuf
3069				 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3070				 */
3071				m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3072				    bp->b_npages, VM_ALLOC_NOBUSY |
3073				    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3074				    VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3075				    VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3076				if (m->valid == 0)
3077					bp->b_flags &= ~B_CACHE;
3078				bp->b_pages[bp->b_npages] = m;
3079				++bp->b_npages;
3080			}
3081
3082			/*
3083			 * Step 2.  We've loaded the pages into the buffer,
3084			 * we have to figure out if we can still have B_CACHE
3085			 * set.  Note that B_CACHE is set according to the
3086			 * byte-granular range ( bcount and size ), new the
3087			 * aligned range ( newbsize ).
3088			 *
3089			 * The VM test is against m->valid, which is DEV_BSIZE
3090			 * aligned.  Needless to say, the validity of the data
3091			 * needs to also be DEV_BSIZE aligned.  Note that this
3092			 * fails with NFS if the server or some other client
3093			 * extends the file's EOF.  If our buffer is resized,
3094			 * B_CACHE may remain set! XXX
3095			 */
3096
3097			toff = bp->b_bcount;
3098			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3099
3100			while ((bp->b_flags & B_CACHE) && toff < size) {
3101				vm_pindex_t pi;
3102
3103				if (tinc > (size - toff))
3104					tinc = size - toff;
3105
3106				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3107				    PAGE_SHIFT;
3108
3109				vfs_buf_test_cache(
3110				    bp,
3111				    bp->b_offset,
3112				    toff,
3113				    tinc,
3114				    bp->b_pages[pi]
3115				);
3116				toff += tinc;
3117				tinc = PAGE_SIZE;
3118			}
3119			VM_OBJECT_UNLOCK(obj);
3120
3121			/*
3122			 * Step 3, fixup the KVM pmap.  Remember that
3123			 * bp->b_data is relative to bp->b_offset, but
3124			 * bp->b_offset may be offset into the first page.
3125			 */
3126
3127			bp->b_data = (caddr_t)
3128			    trunc_page((vm_offset_t)bp->b_data);
3129			pmap_qenter(
3130			    (vm_offset_t)bp->b_data,
3131			    bp->b_pages,
3132			    bp->b_npages
3133			);
3134
3135			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3136			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
3137		}
3138	}
3139	if (newbsize < bp->b_bufsize)
3140		bufspacewakeup();
3141	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3142	bp->b_bcount = size;		/* requested buffer size	*/
3143	return 1;
3144}
3145
3146void
3147biodone(struct bio *bp)
3148{
3149	struct mtx *mtxp;
3150	void (*done)(struct bio *);
3151
3152	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3153	mtx_lock(mtxp);
3154	bp->bio_flags |= BIO_DONE;
3155	done = bp->bio_done;
3156	if (done == NULL)
3157		wakeup(bp);
3158	mtx_unlock(mtxp);
3159	if (done != NULL)
3160		done(bp);
3161}
3162
3163/*
3164 * Wait for a BIO to finish.
3165 *
3166 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3167 * case is not yet clear.
3168 */
3169int
3170biowait(struct bio *bp, const char *wchan)
3171{
3172	struct mtx *mtxp;
3173
3174	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3175	mtx_lock(mtxp);
3176	while ((bp->bio_flags & BIO_DONE) == 0)
3177		msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3178	mtx_unlock(mtxp);
3179	if (bp->bio_error != 0)
3180		return (bp->bio_error);
3181	if (!(bp->bio_flags & BIO_ERROR))
3182		return (0);
3183	return (EIO);
3184}
3185
3186void
3187biofinish(struct bio *bp, struct devstat *stat, int error)
3188{
3189
3190	if (error) {
3191		bp->bio_error = error;
3192		bp->bio_flags |= BIO_ERROR;
3193	}
3194	if (stat != NULL)
3195		devstat_end_transaction_bio(stat, bp);
3196	biodone(bp);
3197}
3198
3199/*
3200 *	bufwait:
3201 *
3202 *	Wait for buffer I/O completion, returning error status.  The buffer
3203 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3204 *	error and cleared.
3205 */
3206int
3207bufwait(struct buf *bp)
3208{
3209	if (bp->b_iocmd == BIO_READ)
3210		bwait(bp, PRIBIO, "biord");
3211	else
3212		bwait(bp, PRIBIO, "biowr");
3213	if (bp->b_flags & B_EINTR) {
3214		bp->b_flags &= ~B_EINTR;
3215		return (EINTR);
3216	}
3217	if (bp->b_ioflags & BIO_ERROR) {
3218		return (bp->b_error ? bp->b_error : EIO);
3219	} else {
3220		return (0);
3221	}
3222}
3223
3224 /*
3225  * Call back function from struct bio back up to struct buf.
3226  */
3227static void
3228bufdonebio(struct bio *bip)
3229{
3230	struct buf *bp;
3231
3232	bp = bip->bio_caller2;
3233	bp->b_resid = bp->b_bcount - bip->bio_completed;
3234	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3235	bp->b_ioflags = bip->bio_flags;
3236	bp->b_error = bip->bio_error;
3237	if (bp->b_error)
3238		bp->b_ioflags |= BIO_ERROR;
3239	bufdone(bp);
3240	g_destroy_bio(bip);
3241}
3242
3243void
3244dev_strategy(struct cdev *dev, struct buf *bp)
3245{
3246	struct cdevsw *csw;
3247	struct bio *bip;
3248	int ref;
3249
3250	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3251		panic("b_iocmd botch");
3252	for (;;) {
3253		bip = g_new_bio();
3254		if (bip != NULL)
3255			break;
3256		/* Try again later */
3257		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3258	}
3259	bip->bio_cmd = bp->b_iocmd;
3260	bip->bio_offset = bp->b_iooffset;
3261	bip->bio_length = bp->b_bcount;
3262	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3263	bip->bio_data = bp->b_data;
3264	bip->bio_done = bufdonebio;
3265	bip->bio_caller2 = bp;
3266	bip->bio_dev = dev;
3267	KASSERT(dev->si_refcount > 0,
3268	    ("dev_strategy on un-referenced struct cdev *(%s)",
3269	    devtoname(dev)));
3270	csw = dev_refthread(dev, &ref);
3271	if (csw == NULL) {
3272		g_destroy_bio(bip);
3273		bp->b_error = ENXIO;
3274		bp->b_ioflags = BIO_ERROR;
3275		bufdone(bp);
3276		return;
3277	}
3278	(*csw->d_strategy)(bip);
3279	dev_relthread(dev, ref);
3280}
3281
3282/*
3283 *	bufdone:
3284 *
3285 *	Finish I/O on a buffer, optionally calling a completion function.
3286 *	This is usually called from an interrupt so process blocking is
3287 *	not allowed.
3288 *
3289 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3290 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3291 *	assuming B_INVAL is clear.
3292 *
3293 *	For the VMIO case, we set B_CACHE if the op was a read and no
3294 *	read error occured, or if the op was a write.  B_CACHE is never
3295 *	set if the buffer is invalid or otherwise uncacheable.
3296 *
3297 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3298 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3299 *	in the biodone routine.
3300 */
3301void
3302bufdone(struct buf *bp)
3303{
3304	struct bufobj *dropobj;
3305	void    (*biodone)(struct buf *);
3306
3307	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3308	dropobj = NULL;
3309
3310	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3311	BUF_ASSERT_HELD(bp);
3312
3313	runningbufwakeup(bp);
3314	if (bp->b_iocmd == BIO_WRITE)
3315		dropobj = bp->b_bufobj;
3316	/* call optional completion function if requested */
3317	if (bp->b_iodone != NULL) {
3318		biodone = bp->b_iodone;
3319		bp->b_iodone = NULL;
3320		(*biodone) (bp);
3321		if (dropobj)
3322			bufobj_wdrop(dropobj);
3323		return;
3324	}
3325
3326	bufdone_finish(bp);
3327
3328	if (dropobj)
3329		bufobj_wdrop(dropobj);
3330}
3331
3332void
3333bufdone_finish(struct buf *bp)
3334{
3335	BUF_ASSERT_HELD(bp);
3336
3337	if (!LIST_EMPTY(&bp->b_dep))
3338		buf_complete(bp);
3339
3340	if (bp->b_flags & B_VMIO) {
3341		vm_ooffset_t foff;
3342		vm_page_t m;
3343		vm_object_t obj;
3344		struct vnode *vp;
3345		int bogus, i, iosize;
3346
3347		obj = bp->b_bufobj->bo_object;
3348		KASSERT(obj->paging_in_progress >= bp->b_npages,
3349		    ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3350		    obj->paging_in_progress, bp->b_npages));
3351
3352		vp = bp->b_vp;
3353		KASSERT(vp->v_holdcnt > 0,
3354		    ("biodone_finish: vnode %p has zero hold count", vp));
3355		KASSERT(vp->v_object != NULL,
3356		    ("biodone_finish: vnode %p has no vm_object", vp));
3357
3358		foff = bp->b_offset;
3359		KASSERT(bp->b_offset != NOOFFSET,
3360		    ("biodone_finish: bp %p has no buffer offset", bp));
3361
3362		/*
3363		 * Set B_CACHE if the op was a normal read and no error
3364		 * occured.  B_CACHE is set for writes in the b*write()
3365		 * routines.
3366		 */
3367		iosize = bp->b_bcount - bp->b_resid;
3368		if (bp->b_iocmd == BIO_READ &&
3369		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3370		    !(bp->b_ioflags & BIO_ERROR)) {
3371			bp->b_flags |= B_CACHE;
3372		}
3373		bogus = 0;
3374		VM_OBJECT_LOCK(obj);
3375		for (i = 0; i < bp->b_npages; i++) {
3376			int bogusflag = 0;
3377			int resid;
3378
3379			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3380			if (resid > iosize)
3381				resid = iosize;
3382
3383			/*
3384			 * cleanup bogus pages, restoring the originals
3385			 */
3386			m = bp->b_pages[i];
3387			if (m == bogus_page) {
3388				bogus = bogusflag = 1;
3389				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3390				if (m == NULL)
3391					panic("biodone: page disappeared!");
3392				bp->b_pages[i] = m;
3393			}
3394			KASSERT(OFF_TO_IDX(foff) == m->pindex,
3395			    ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3396			    (intmax_t)foff, (uintmax_t)m->pindex));
3397
3398			/*
3399			 * In the write case, the valid and clean bits are
3400			 * already changed correctly ( see bdwrite() ), so we
3401			 * only need to do this here in the read case.
3402			 */
3403			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3404				KASSERT((m->dirty & vm_page_bits(foff &
3405				    PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3406				    " page %p has unexpected dirty bits", m));
3407				vfs_page_set_valid(bp, foff, m);
3408			}
3409
3410			vm_page_io_finish(m);
3411			vm_object_pip_subtract(obj, 1);
3412			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3413			iosize -= resid;
3414		}
3415		vm_object_pip_wakeupn(obj, 0);
3416		VM_OBJECT_UNLOCK(obj);
3417		if (bogus)
3418			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3419			    bp->b_pages, bp->b_npages);
3420	}
3421
3422	/*
3423	 * For asynchronous completions, release the buffer now. The brelse
3424	 * will do a wakeup there if necessary - so no need to do a wakeup
3425	 * here in the async case. The sync case always needs to do a wakeup.
3426	 */
3427
3428	if (bp->b_flags & B_ASYNC) {
3429		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3430			brelse(bp);
3431		else
3432			bqrelse(bp);
3433	} else
3434		bdone(bp);
3435}
3436
3437/*
3438 * This routine is called in lieu of iodone in the case of
3439 * incomplete I/O.  This keeps the busy status for pages
3440 * consistant.
3441 */
3442void
3443vfs_unbusy_pages(struct buf *bp)
3444{
3445	int i;
3446	vm_object_t obj;
3447	vm_page_t m;
3448
3449	runningbufwakeup(bp);
3450	if (!(bp->b_flags & B_VMIO))
3451		return;
3452
3453	obj = bp->b_bufobj->bo_object;
3454	VM_OBJECT_LOCK(obj);
3455	for (i = 0; i < bp->b_npages; i++) {
3456		m = bp->b_pages[i];
3457		if (m == bogus_page) {
3458			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3459			if (!m)
3460				panic("vfs_unbusy_pages: page missing\n");
3461			bp->b_pages[i] = m;
3462			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3463			    bp->b_pages, bp->b_npages);
3464		}
3465		vm_object_pip_subtract(obj, 1);
3466		vm_page_io_finish(m);
3467	}
3468	vm_object_pip_wakeupn(obj, 0);
3469	VM_OBJECT_UNLOCK(obj);
3470}
3471
3472/*
3473 * vfs_page_set_valid:
3474 *
3475 *	Set the valid bits in a page based on the supplied offset.   The
3476 *	range is restricted to the buffer's size.
3477 *
3478 *	This routine is typically called after a read completes.
3479 */
3480static void
3481vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3482{
3483	vm_ooffset_t eoff;
3484
3485	/*
3486	 * Compute the end offset, eoff, such that [off, eoff) does not span a
3487	 * page boundary and eoff is not greater than the end of the buffer.
3488	 * The end of the buffer, in this case, is our file EOF, not the
3489	 * allocation size of the buffer.
3490	 */
3491	eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3492	if (eoff > bp->b_offset + bp->b_bcount)
3493		eoff = bp->b_offset + bp->b_bcount;
3494
3495	/*
3496	 * Set valid range.  This is typically the entire buffer and thus the
3497	 * entire page.
3498	 */
3499	if (eoff > off)
3500		vm_page_set_valid(m, off & PAGE_MASK, eoff - off);
3501}
3502
3503/*
3504 * vfs_page_set_validclean:
3505 *
3506 *	Set the valid bits and clear the dirty bits in a page based on the
3507 *	supplied offset.   The range is restricted to the buffer's size.
3508 */
3509static void
3510vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3511{
3512	vm_ooffset_t soff, eoff;
3513
3514	/*
3515	 * Start and end offsets in buffer.  eoff - soff may not cross a
3516	 * page boundry or cross the end of the buffer.  The end of the
3517	 * buffer, in this case, is our file EOF, not the allocation size
3518	 * of the buffer.
3519	 */
3520	soff = off;
3521	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3522	if (eoff > bp->b_offset + bp->b_bcount)
3523		eoff = bp->b_offset + bp->b_bcount;
3524
3525	/*
3526	 * Set valid range.  This is typically the entire buffer and thus the
3527	 * entire page.
3528	 */
3529	if (eoff > soff) {
3530		vm_page_set_validclean(
3531		    m,
3532		   (vm_offset_t) (soff & PAGE_MASK),
3533		   (vm_offset_t) (eoff - soff)
3534		);
3535	}
3536}
3537
3538/*
3539 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
3540 * any page is busy, drain the flag.
3541 */
3542static void
3543vfs_drain_busy_pages(struct buf *bp)
3544{
3545	vm_page_t m;
3546	int i, last_busied;
3547
3548	VM_OBJECT_LOCK_ASSERT(bp->b_bufobj->bo_object, MA_OWNED);
3549	last_busied = 0;
3550	for (i = 0; i < bp->b_npages; i++) {
3551		m = bp->b_pages[i];
3552		if ((m->oflags & VPO_BUSY) != 0) {
3553			for (; last_busied < i; last_busied++)
3554				vm_page_busy(bp->b_pages[last_busied]);
3555			while ((m->oflags & VPO_BUSY) != 0)
3556				vm_page_sleep(m, "vbpage");
3557		}
3558	}
3559	for (i = 0; i < last_busied; i++)
3560		vm_page_wakeup(bp->b_pages[i]);
3561}
3562
3563/*
3564 * This routine is called before a device strategy routine.
3565 * It is used to tell the VM system that paging I/O is in
3566 * progress, and treat the pages associated with the buffer
3567 * almost as being VPO_BUSY.  Also the object paging_in_progress
3568 * flag is handled to make sure that the object doesn't become
3569 * inconsistant.
3570 *
3571 * Since I/O has not been initiated yet, certain buffer flags
3572 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3573 * and should be ignored.
3574 */
3575void
3576vfs_busy_pages(struct buf *bp, int clear_modify)
3577{
3578	int i, bogus;
3579	vm_object_t obj;
3580	vm_ooffset_t foff;
3581	vm_page_t m;
3582
3583	if (!(bp->b_flags & B_VMIO))
3584		return;
3585
3586	obj = bp->b_bufobj->bo_object;
3587	foff = bp->b_offset;
3588	KASSERT(bp->b_offset != NOOFFSET,
3589	    ("vfs_busy_pages: no buffer offset"));
3590	VM_OBJECT_LOCK(obj);
3591	vfs_drain_busy_pages(bp);
3592	if (bp->b_bufsize != 0)
3593		vfs_setdirty_locked_object(bp);
3594	bogus = 0;
3595	for (i = 0; i < bp->b_npages; i++) {
3596		m = bp->b_pages[i];
3597
3598		if ((bp->b_flags & B_CLUSTER) == 0) {
3599			vm_object_pip_add(obj, 1);
3600			vm_page_io_start(m);
3601		}
3602		/*
3603		 * When readying a buffer for a read ( i.e
3604		 * clear_modify == 0 ), it is important to do
3605		 * bogus_page replacement for valid pages in
3606		 * partially instantiated buffers.  Partially
3607		 * instantiated buffers can, in turn, occur when
3608		 * reconstituting a buffer from its VM backing store
3609		 * base.  We only have to do this if B_CACHE is
3610		 * clear ( which causes the I/O to occur in the
3611		 * first place ).  The replacement prevents the read
3612		 * I/O from overwriting potentially dirty VM-backed
3613		 * pages.  XXX bogus page replacement is, uh, bogus.
3614		 * It may not work properly with small-block devices.
3615		 * We need to find a better way.
3616		 */
3617		if (clear_modify) {
3618			pmap_remove_write(m);
3619			vfs_page_set_validclean(bp, foff, m);
3620		} else if (m->valid == VM_PAGE_BITS_ALL &&
3621		    (bp->b_flags & B_CACHE) == 0) {
3622			bp->b_pages[i] = bogus_page;
3623			bogus++;
3624		}
3625		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3626	}
3627	VM_OBJECT_UNLOCK(obj);
3628	if (bogus)
3629		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3630		    bp->b_pages, bp->b_npages);
3631}
3632
3633/*
3634 *	vfs_bio_set_valid:
3635 *
3636 *	Set the range within the buffer to valid.  The range is
3637 *	relative to the beginning of the buffer, b_offset.  Note that
3638 *	b_offset itself may be offset from the beginning of the first
3639 *	page.
3640 */
3641void
3642vfs_bio_set_valid(struct buf *bp, int base, int size)
3643{
3644	int i, n;
3645	vm_page_t m;
3646
3647	if (!(bp->b_flags & B_VMIO))
3648		return;
3649
3650	/*
3651	 * Fixup base to be relative to beginning of first page.
3652	 * Set initial n to be the maximum number of bytes in the
3653	 * first page that can be validated.
3654	 */
3655	base += (bp->b_offset & PAGE_MASK);
3656	n = PAGE_SIZE - (base & PAGE_MASK);
3657
3658	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3659	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3660		m = bp->b_pages[i];
3661		if (n > size)
3662			n = size;
3663		vm_page_set_valid(m, base & PAGE_MASK, n);
3664		base += n;
3665		size -= n;
3666		n = PAGE_SIZE;
3667	}
3668	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3669}
3670
3671/*
3672 *	vfs_bio_clrbuf:
3673 *
3674 *	If the specified buffer is a non-VMIO buffer, clear the entire
3675 *	buffer.  If the specified buffer is a VMIO buffer, clear and
3676 *	validate only the previously invalid portions of the buffer.
3677 *	This routine essentially fakes an I/O, so we need to clear
3678 *	BIO_ERROR and B_INVAL.
3679 *
3680 *	Note that while we only theoretically need to clear through b_bcount,
3681 *	we go ahead and clear through b_bufsize.
3682 */
3683void
3684vfs_bio_clrbuf(struct buf *bp)
3685{
3686	int i, j, mask;
3687	caddr_t sa, ea;
3688
3689	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3690		clrbuf(bp);
3691		return;
3692	}
3693	bp->b_flags &= ~B_INVAL;
3694	bp->b_ioflags &= ~BIO_ERROR;
3695	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3696	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3697	    (bp->b_offset & PAGE_MASK) == 0) {
3698		if (bp->b_pages[0] == bogus_page)
3699			goto unlock;
3700		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3701		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3702		if ((bp->b_pages[0]->valid & mask) == mask)
3703			goto unlock;
3704		if ((bp->b_pages[0]->valid & mask) == 0) {
3705			bzero(bp->b_data, bp->b_bufsize);
3706			bp->b_pages[0]->valid |= mask;
3707			goto unlock;
3708		}
3709	}
3710	ea = sa = bp->b_data;
3711	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3712		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3713		ea = (caddr_t)(vm_offset_t)ulmin(
3714		    (u_long)(vm_offset_t)ea,
3715		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3716		if (bp->b_pages[i] == bogus_page)
3717			continue;
3718		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3719		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3720		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3721		if ((bp->b_pages[i]->valid & mask) == mask)
3722			continue;
3723		if ((bp->b_pages[i]->valid & mask) == 0)
3724			bzero(sa, ea - sa);
3725		else {
3726			for (; sa < ea; sa += DEV_BSIZE, j++) {
3727				if ((bp->b_pages[i]->valid & (1 << j)) == 0)
3728					bzero(sa, DEV_BSIZE);
3729			}
3730		}
3731		bp->b_pages[i]->valid |= mask;
3732	}
3733unlock:
3734	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3735	bp->b_resid = 0;
3736}
3737
3738/*
3739 * vm_hold_load_pages and vm_hold_free_pages get pages into
3740 * a buffers address space.  The pages are anonymous and are
3741 * not associated with a file object.
3742 */
3743static void
3744vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3745{
3746	vm_offset_t pg;
3747	vm_page_t p;
3748	int index;
3749
3750	to = round_page(to);
3751	from = round_page(from);
3752	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3753
3754	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3755tryagain:
3756		/*
3757		 * note: must allocate system pages since blocking here
3758		 * could interfere with paging I/O, no matter which
3759		 * process we are.
3760		 */
3761		p = vm_page_alloc(NULL, pg >> PAGE_SHIFT, VM_ALLOC_NOOBJ |
3762		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3763		    VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
3764		if (!p) {
3765			VM_WAIT;
3766			goto tryagain;
3767		}
3768		pmap_qenter(pg, &p, 1);
3769		bp->b_pages[index] = p;
3770	}
3771	bp->b_npages = index;
3772}
3773
3774/* Return pages associated with this buf to the vm system */
3775static void
3776vm_hold_free_pages(struct buf *bp, int newbsize)
3777{
3778	vm_offset_t from;
3779	vm_page_t p;
3780	int index, newnpages;
3781
3782	from = round_page((vm_offset_t)bp->b_data + newbsize);
3783	newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3784	if (bp->b_npages > newnpages)
3785		pmap_qremove(from, bp->b_npages - newnpages);
3786	for (index = newnpages; index < bp->b_npages; index++) {
3787		p = bp->b_pages[index];
3788		bp->b_pages[index] = NULL;
3789		if (p->busy != 0)
3790			printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3791			    (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
3792		p->wire_count--;
3793		vm_page_free(p);
3794		atomic_subtract_int(&cnt.v_wire_count, 1);
3795	}
3796	bp->b_npages = newnpages;
3797}
3798
3799/*
3800 * Map an IO request into kernel virtual address space.
3801 *
3802 * All requests are (re)mapped into kernel VA space.
3803 * Notice that we use b_bufsize for the size of the buffer
3804 * to be mapped.  b_bcount might be modified by the driver.
3805 *
3806 * Note that even if the caller determines that the address space should
3807 * be valid, a race or a smaller-file mapped into a larger space may
3808 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3809 * check the return value.
3810 */
3811int
3812vmapbuf(struct buf *bp)
3813{
3814	caddr_t kva;
3815	vm_prot_t prot;
3816	int pidx;
3817
3818	if (bp->b_bufsize < 0)
3819		return (-1);
3820	prot = VM_PROT_READ;
3821	if (bp->b_iocmd == BIO_READ)
3822		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3823	if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
3824	    (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
3825	    btoc(MAXPHYS))) < 0)
3826		return (-1);
3827	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3828
3829	kva = bp->b_saveaddr;
3830	bp->b_npages = pidx;
3831	bp->b_saveaddr = bp->b_data;
3832	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3833	return(0);
3834}
3835
3836/*
3837 * Free the io map PTEs associated with this IO operation.
3838 * We also invalidate the TLB entries and restore the original b_addr.
3839 */
3840void
3841vunmapbuf(struct buf *bp)
3842{
3843	int npages;
3844
3845	npages = bp->b_npages;
3846	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3847	vm_page_unhold_pages(bp->b_pages, npages);
3848
3849	bp->b_data = bp->b_saveaddr;
3850}
3851
3852void
3853bdone(struct buf *bp)
3854{
3855	struct mtx *mtxp;
3856
3857	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3858	mtx_lock(mtxp);
3859	bp->b_flags |= B_DONE;
3860	wakeup(bp);
3861	mtx_unlock(mtxp);
3862}
3863
3864void
3865bwait(struct buf *bp, u_char pri, const char *wchan)
3866{
3867	struct mtx *mtxp;
3868
3869	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3870	mtx_lock(mtxp);
3871	while ((bp->b_flags & B_DONE) == 0)
3872		msleep(bp, mtxp, pri, wchan, 0);
3873	mtx_unlock(mtxp);
3874}
3875
3876int
3877bufsync(struct bufobj *bo, int waitfor)
3878{
3879
3880	return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
3881}
3882
3883void
3884bufstrategy(struct bufobj *bo, struct buf *bp)
3885{
3886	int i = 0;
3887	struct vnode *vp;
3888
3889	vp = bp->b_vp;
3890	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3891	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3892	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3893	i = VOP_STRATEGY(vp, bp);
3894	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3895}
3896
3897void
3898bufobj_wrefl(struct bufobj *bo)
3899{
3900
3901	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3902	ASSERT_BO_LOCKED(bo);
3903	bo->bo_numoutput++;
3904}
3905
3906void
3907bufobj_wref(struct bufobj *bo)
3908{
3909
3910	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3911	BO_LOCK(bo);
3912	bo->bo_numoutput++;
3913	BO_UNLOCK(bo);
3914}
3915
3916void
3917bufobj_wdrop(struct bufobj *bo)
3918{
3919
3920	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3921	BO_LOCK(bo);
3922	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3923	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3924		bo->bo_flag &= ~BO_WWAIT;
3925		wakeup(&bo->bo_numoutput);
3926	}
3927	BO_UNLOCK(bo);
3928}
3929
3930int
3931bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3932{
3933	int error;
3934
3935	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3936	ASSERT_BO_LOCKED(bo);
3937	error = 0;
3938	while (bo->bo_numoutput) {
3939		bo->bo_flag |= BO_WWAIT;
3940		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3941		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3942		if (error)
3943			break;
3944	}
3945	return (error);
3946}
3947
3948void
3949bpin(struct buf *bp)
3950{
3951	struct mtx *mtxp;
3952
3953	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3954	mtx_lock(mtxp);
3955	bp->b_pin_count++;
3956	mtx_unlock(mtxp);
3957}
3958
3959void
3960bunpin(struct buf *bp)
3961{
3962	struct mtx *mtxp;
3963
3964	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3965	mtx_lock(mtxp);
3966	if (--bp->b_pin_count == 0)
3967		wakeup(bp);
3968	mtx_unlock(mtxp);
3969}
3970
3971void
3972bunpin_wait(struct buf *bp)
3973{
3974	struct mtx *mtxp;
3975
3976	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3977	mtx_lock(mtxp);
3978	while (bp->b_pin_count > 0)
3979		msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
3980	mtx_unlock(mtxp);
3981}
3982
3983#include "opt_ddb.h"
3984#ifdef DDB
3985#include <ddb/ddb.h>
3986
3987/* DDB command to show buffer data */
3988DB_SHOW_COMMAND(buffer, db_show_buffer)
3989{
3990	/* get args */
3991	struct buf *bp = (struct buf *)addr;
3992
3993	if (!have_addr) {
3994		db_printf("usage: show buffer <addr>\n");
3995		return;
3996	}
3997
3998	db_printf("buf at %p\n", bp);
3999	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4000	db_printf(
4001	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4002	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_dep = %p\n",
4003	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4004	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4005	    bp->b_dep.lh_first);
4006	if (bp->b_npages) {
4007		int i;
4008		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4009		for (i = 0; i < bp->b_npages; i++) {
4010			vm_page_t m;
4011			m = bp->b_pages[i];
4012			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4013			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4014			if ((i + 1) < bp->b_npages)
4015				db_printf(",");
4016		}
4017		db_printf("\n");
4018	}
4019	db_printf(" ");
4020	lockmgr_printinfo(&bp->b_lock);
4021}
4022
4023DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4024{
4025	struct buf *bp;
4026	int i;
4027
4028	for (i = 0; i < nbuf; i++) {
4029		bp = &buf[i];
4030		if (BUF_ISLOCKED(bp)) {
4031			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4032			db_printf("\n");
4033		}
4034	}
4035}
4036
4037DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4038{
4039	struct vnode *vp;
4040	struct buf *bp;
4041
4042	if (!have_addr) {
4043		db_printf("usage: show vnodebufs <addr>\n");
4044		return;
4045	}
4046	vp = (struct vnode *)addr;
4047	db_printf("Clean buffers:\n");
4048	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4049		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4050		db_printf("\n");
4051	}
4052	db_printf("Dirty buffers:\n");
4053	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4054		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4055		db_printf("\n");
4056	}
4057}
4058
4059DB_COMMAND(countfreebufs, db_coundfreebufs)
4060{
4061	struct buf *bp;
4062	int i, used = 0, nfree = 0;
4063
4064	if (have_addr) {
4065		db_printf("usage: countfreebufs\n");
4066		return;
4067	}
4068
4069	for (i = 0; i < nbuf; i++) {
4070		bp = &buf[i];
4071		if ((bp->b_vflags & BV_INFREECNT) != 0)
4072			nfree++;
4073		else
4074			used++;
4075	}
4076
4077	db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4078	    nfree + used);
4079	db_printf("numfreebuffers is %d\n", numfreebuffers);
4080}
4081#endif /* DDB */
4082