vfs_bio.c revision 191135
1251034Sed/*-
2251034Sed * Copyright (c) 2004 Poul-Henning Kamp
3353358Sdim * Copyright (c) 1994,1997 John S. Dyson
4353358Sdim * All rights reserved.
5353358Sdim *
6251034Sed * Redistribution and use in source and binary forms, with or without
7251034Sed * modification, are permitted provided that the following conditions
8251034Sed * are met:
9251034Sed * 1. Redistributions of source code must retain the above copyright
10251034Sed *    notice, this list of conditions and the following disclaimer.
11251034Sed * 2. Redistributions in binary form must reproduce the above copyright
12251034Sed *    notice, this list of conditions and the following disclaimer in the
13251034Sed *    documentation and/or other materials provided with the distribution.
14251034Sed *
15251034Sed * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16251034Sed * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17274201Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18251034Sed * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19251034Sed * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20251034Sed * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21288943Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22251034Sed * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23251034Sed * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24353358Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25353358Sdim * SUCH DAMAGE.
26321369Sdim */
27321369Sdim
28321369Sdim/*
29327952Sdim * this file contains a new buffer I/O scheme implementing a coherent
30327952Sdim * VM object and buffer cache scheme.  Pains have been taken to make
31327952Sdim * sure that the performance degradation associated with schemes such
32321369Sdim * as this is not realized.
33321369Sdim *
34321369Sdim * Author:  John S. Dyson
35321369Sdim * Significant help during the development and debugging phases
36251034Sed * had been provided by David Greenman, also of the FreeBSD core team.
37321369Sdim *
38321369Sdim * see man buf(9) for more info.
39321369Sdim */
40321369Sdim
41321369Sdim#include <sys/cdefs.h>
42321369Sdim__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 191135 2009-04-16 09:33:52Z kib $");
43353358Sdim
44353358Sdim#include <sys/param.h>
45251034Sed#include <sys/systm.h>
46251034Sed#include <sys/bio.h>
47251034Sed#include <sys/conf.h>
48251034Sed#include <sys/buf.h>
49280031Sdim#include <sys/devicestat.h>
50280031Sdim#include <sys/eventhandler.h>
51341825Sdim#include <sys/limits.h>
52309124Sdim#include <sys/lock.h>
53280031Sdim#include <sys/malloc.h>
54280031Sdim#include <sys/mount.h>
55251034Sed#include <sys/mutex.h>
56251034Sed#include <sys/kernel.h>
57251034Sed#include <sys/kthread.h>
58251034Sed#include <sys/proc.h>
59251034Sed#include <sys/resourcevar.h>
60251034Sed#include <sys/sysctl.h>
61274201Sdim#include <sys/vmmeter.h>
62274201Sdim#include <sys/vnode.h>
63251034Sed#include <geom/geom.h>
64251034Sed#include <vm/vm.h>
65321369Sdim#include <vm/vm_param.h>
66321369Sdim#include <vm/vm_kern.h>
67251034Sed#include <vm/vm_pageout.h>
68280031Sdim#include <vm/vm_page.h>
69280031Sdim#include <vm/vm_object.h>
70280031Sdim#include <vm/vm_extern.h>
71280031Sdim#include <vm/vm_map.h>
72280031Sdim#include "opt_compat.h"
73251034Sed#include "opt_directio.h"
74251034Sed#include "opt_swap.h"
75251034Sed
76251034Sedstatic MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
77251034Sed
78251034Sedstruct	bio_ops bioops;		/* I/O operation notification */
79251034Sed
80280031Sdimstruct	buf_ops buf_ops_bio = {
81251034Sed	.bop_name	=	"buf_ops_bio",
82251034Sed	.bop_write	=	bufwrite,
83276789Sdim	.bop_strategy	=	bufstrategy,
84251034Sed	.bop_sync	=	bufsync,
85251034Sed	.bop_bdflush	=	bufbdflush,
86251034Sed};
87251034Sed
88274201Sdim/*
89251034Sed * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
90251034Sed * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
91276789Sdim */
92276789Sdimstruct buf *buf;		/* buffer header pool */
93276789Sdim
94276789Sdimstatic struct proc *bufdaemonproc;
95276789Sdim
96276789Sdimstatic int inmem(struct vnode *vp, daddr_t blkno);
97251034Sedstatic void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
98251034Sed		vm_offset_t to);
99251034Sedstatic void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
100341825Sdim		vm_offset_t to);
101276789Sdimstatic void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
102276789Sdim		vm_page_t m);
103276789Sdimstatic void vfs_clean_pages(struct buf *bp);
104251034Sedstatic void vfs_setdirty(struct buf *bp);
105276789Sdimstatic void vfs_setdirty_locked_object(struct buf *bp);
106276789Sdimstatic void vfs_vmio_release(struct buf *bp);
107276789Sdimstatic int vfs_bio_clcheck(struct vnode *vp, int size,
108251034Sed		daddr_t lblkno, daddr_t blkno);
109276789Sdimstatic int buf_do_flush(struct vnode *vp);
110276789Sdimstatic int flushbufqueues(struct vnode *, int, int);
111276789Sdimstatic void buf_daemon(void);
112341825Sdimstatic void bremfreel(struct buf *bp);
113274201Sdim#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
114276789Sdim    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
115251034Sedstatic int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
116251034Sed#endif
117274201Sdim
118274201Sdimint vmiodirenable = TRUE;
119251034SedSYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
120251034Sed    "Use the VM system for directory writes");
121274201Sdimlong runningbufspace;
122274201SdimSYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
123321369Sdim    "Amount of presently outstanding async buffer io");
124321369Sdimstatic long bufspace;
125321369Sdim#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
126321369Sdim    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
127321369SdimSYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
128321369Sdim    &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
129321369Sdim#else
130321369SdimSYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
131321369Sdim    "Virtual memory used for buffers");
132360784Sdim#endif
133360784Sdimstatic long maxbufspace;
134360784SdimSYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
135251034Sed    "Maximum allowed value of bufspace (including buf_daemon)");
136274201Sdimstatic long bufmallocspace;
137274201SdimSYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
138251034Sed    "Amount of malloced memory for buffers");
139321369Sdimstatic long maxbufmallocspace;
140251034SedSYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
141274201Sdim    "Maximum amount of malloced memory for buffers");
142274201Sdimstatic long lobufspace;
143274201SdimSYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
144274201Sdim    "Minimum amount of buffers we want to have");
145251034Sedlong hibufspace;
146251034SedSYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
147274201Sdim    "Maximum allowed value of bufspace (excluding buf_daemon)");
148327952Sdimstatic int bufreusecnt;
149280031SdimSYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
150274201Sdim    "Number of times we have reused a buffer");
151327952Sdimstatic int buffreekvacnt;
152321369SdimSYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
153274201Sdim    "Number of times we have freed the KVA space from some buffer");
154251034Sedstatic int bufdefragcnt;
155309124SdimSYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
156309124Sdim    "Number of times we have had to repeat buffer allocation to defragment");
157309124Sdimstatic long lorunningspace;
158309124SdimSYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
159309124Sdim    "Minimum preferred space used for in-progress I/O");
160309124Sdimstatic long hirunningspace;
161309124SdimSYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
162309124Sdim    "Maximum amount of space to use for in-progress I/O");
163309124Sdimint dirtybufferflushes;
164309124SdimSYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
165321369Sdim    0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
166321369Sdimint bdwriteskip;
167321369SdimSYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
168321369Sdim    0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
169321369Sdimint altbufferflushes;
170321369SdimSYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
171321369Sdim    0, "Number of fsync flushes to limit dirty buffers");
172321369Sdimstatic int recursiveflushes;
173321369SdimSYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
174321369Sdim    0, "Number of flushes skipped due to being recursive");
175321369Sdimstatic int numdirtybuffers;
176321369SdimSYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
177321369Sdim    "Number of buffers that are dirty (has unwritten changes) at the moment");
178321369Sdimstatic int lodirtybuffers;
179321369SdimSYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
180321369Sdim    "How many buffers we want to have free before bufdaemon can sleep");
181321369Sdimstatic int hidirtybuffers;
182321369SdimSYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
183321369Sdim    "When the number of dirty buffers is considered severe");
184276789Sdimint dirtybufthresh;
185321369SdimSYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
186321369Sdim    0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
187321369Sdimstatic int numfreebuffers;
188276789SdimSYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
189276789Sdim    "Number of free buffers");
190321369Sdimstatic int lofreebuffers;
191321369SdimSYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
192321369Sdim   "XXX Unused");
193321369Sdimstatic int hifreebuffers;
194321369SdimSYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
195276789Sdim   "XXX Complicatedly unused");
196276789Sdimstatic int getnewbufcalls;
197251034SedSYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
198251034Sed   "Number of calls to getnewbuf");
199274201Sdimstatic int getnewbufrestarts;
200274201SdimSYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
201251034Sed    "Number of times getnewbuf has had to restart a buffer aquisition");
202251034Sedstatic int flushbufqtarget = 100;
203251034SedSYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
204251034Sed    "Amount of work to do in flushbufqueues when helping bufdaemon");
205276789Sdimstatic long notbufdflashes;
206276789SdimSYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, &notbufdflashes, 0,
207251034Sed    "Number of dirty buffer flushes done by the bufdaemon helpers");
208251034Sed
209251034Sed/*
210341825Sdim * Wakeup point for bufdaemon, as well as indicator of whether it is already
211321369Sdim * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
212309124Sdim * is idling.
213309124Sdim */
214321369Sdimstatic int bd_request;
215274201Sdim
216274201Sdim/*
217274201Sdim * This lock synchronizes access to bd_request.
218274201Sdim */
219274201Sdimstatic struct mtx bdlock;
220274201Sdim
221274201Sdim/*
222274201Sdim * bogus page -- for I/O to/from partially complete buffers
223274201Sdim * this is a temporary solution to the problem, but it is not
224274201Sdim * really that bad.  it would be better to split the buffer
225274201Sdim * for input in the case of buffers partially already in memory,
226274201Sdim * but the code is intricate enough already.
227274201Sdim */
228274201Sdimvm_page_t bogus_page;
229274201Sdim
230321369Sdim/*
231321369Sdim * Synchronization (sleep/wakeup) variable for active buffer space requests.
232321369Sdim * Set when wait starts, cleared prior to wakeup().
233321369Sdim * Used in runningbufwakeup() and waitrunningbufspace().
234321369Sdim */
235321369Sdimstatic int runningbufreq;
236321369Sdim
237321369Sdim/*
238321369Sdim * This lock protects the runningbufreq and synchronizes runningbufwakeup and
239321369Sdim * waitrunningbufspace().
240251034Sed */
241251034Sedstatic struct mtx rbreqlock;
242251034Sed
243274201Sdim/*
244274201Sdim * Synchronization (sleep/wakeup) variable for buffer requests.
245251034Sed * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
246251034Sed * by and/or.
247251034Sed * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
248251034Sed * getnewbuf(), and getblk().
249251034Sed */
250251034Sedstatic int needsbuffer;
251251034Sed
252251034Sed/*
253251034Sed * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
254251034Sed */
255251034Sedstatic struct mtx nblock;
256274201Sdim
257274201Sdim/*
258327952Sdim * Definitions for the buffer free lists.
259327952Sdim */
260327952Sdim#define BUFFER_QUEUES	6	/* number of free buffer queues */
261274201Sdim
262274201Sdim#define QUEUE_NONE	0	/* on no queue */
263274201Sdim#define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
264274201Sdim#define QUEUE_DIRTY	2	/* B_DELWRI buffers */
265274201Sdim#define QUEUE_DIRTY_GIANT 3	/* B_DELWRI buffers that need giant */
266274201Sdim#define QUEUE_EMPTYKVA	4	/* empty buffer headers w/KVA assignment */
267251034Sed#define QUEUE_EMPTY	5	/* empty buffer headers */
268#define QUEUE_SENTINEL	1024	/* not an queue index, but mark for sentinel */
269
270/* Queues for free buffers with various properties */
271static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
272
273/* Lock for the bufqueues */
274static struct mtx bqlock;
275
276/*
277 * Single global constant for BUF_WMESG, to avoid getting multiple references.
278 * buf_wmesg is referred from macros.
279 */
280const char *buf_wmesg = BUF_WMESG;
281
282#define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
283#define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
284#define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
285#define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
286
287#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
288    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
289static int
290sysctl_bufspace(SYSCTL_HANDLER_ARGS)
291{
292	long lvalue;
293	int ivalue;
294
295	if (sizeof(int) == sizeof(long) || req->oldlen == sizeof(long))
296		return (sysctl_handle_long(oidp, arg1, arg2, req));
297	lvalue = *(long *)arg1;
298	if (lvalue > INT_MAX)
299		/* On overflow, still write out a long to trigger ENOMEM. */
300		return (sysctl_handle_long(oidp, &lvalue, 0, req));
301	ivalue = lvalue;
302	return (sysctl_handle_int(oidp, &ivalue, 0, req));
303}
304#endif
305
306#ifdef DIRECTIO
307extern void ffs_rawread_setup(void);
308#endif /* DIRECTIO */
309/*
310 *	numdirtywakeup:
311 *
312 *	If someone is blocked due to there being too many dirty buffers,
313 *	and numdirtybuffers is now reasonable, wake them up.
314 */
315
316static __inline void
317numdirtywakeup(int level)
318{
319
320	if (numdirtybuffers <= level) {
321		mtx_lock(&nblock);
322		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
323			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
324			wakeup(&needsbuffer);
325		}
326		mtx_unlock(&nblock);
327	}
328}
329
330/*
331 *	bufspacewakeup:
332 *
333 *	Called when buffer space is potentially available for recovery.
334 *	getnewbuf() will block on this flag when it is unable to free
335 *	sufficient buffer space.  Buffer space becomes recoverable when
336 *	bp's get placed back in the queues.
337 */
338
339static __inline void
340bufspacewakeup(void)
341{
342
343	/*
344	 * If someone is waiting for BUF space, wake them up.  Even
345	 * though we haven't freed the kva space yet, the waiting
346	 * process will be able to now.
347	 */
348	mtx_lock(&nblock);
349	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
350		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
351		wakeup(&needsbuffer);
352	}
353	mtx_unlock(&nblock);
354}
355
356/*
357 * runningbufwakeup() - in-progress I/O accounting.
358 *
359 */
360void
361runningbufwakeup(struct buf *bp)
362{
363
364	if (bp->b_runningbufspace) {
365		atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
366		bp->b_runningbufspace = 0;
367		mtx_lock(&rbreqlock);
368		if (runningbufreq && runningbufspace <= lorunningspace) {
369			runningbufreq = 0;
370			wakeup(&runningbufreq);
371		}
372		mtx_unlock(&rbreqlock);
373	}
374}
375
376/*
377 *	bufcountwakeup:
378 *
379 *	Called when a buffer has been added to one of the free queues to
380 *	account for the buffer and to wakeup anyone waiting for free buffers.
381 *	This typically occurs when large amounts of metadata are being handled
382 *	by the buffer cache ( else buffer space runs out first, usually ).
383 */
384
385static __inline void
386bufcountwakeup(void)
387{
388
389	atomic_add_int(&numfreebuffers, 1);
390	mtx_lock(&nblock);
391	if (needsbuffer) {
392		needsbuffer &= ~VFS_BIO_NEED_ANY;
393		if (numfreebuffers >= hifreebuffers)
394			needsbuffer &= ~VFS_BIO_NEED_FREE;
395		wakeup(&needsbuffer);
396	}
397	mtx_unlock(&nblock);
398}
399
400/*
401 *	waitrunningbufspace()
402 *
403 *	runningbufspace is a measure of the amount of I/O currently
404 *	running.  This routine is used in async-write situations to
405 *	prevent creating huge backups of pending writes to a device.
406 *	Only asynchronous writes are governed by this function.
407 *
408 *	Reads will adjust runningbufspace, but will not block based on it.
409 *	The read load has a side effect of reducing the allowed write load.
410 *
411 *	This does NOT turn an async write into a sync write.  It waits
412 *	for earlier writes to complete and generally returns before the
413 *	caller's write has reached the device.
414 */
415void
416waitrunningbufspace(void)
417{
418
419	mtx_lock(&rbreqlock);
420	while (runningbufspace > hirunningspace) {
421		++runningbufreq;
422		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
423	}
424	mtx_unlock(&rbreqlock);
425}
426
427
428/*
429 *	vfs_buf_test_cache:
430 *
431 *	Called when a buffer is extended.  This function clears the B_CACHE
432 *	bit if the newly extended portion of the buffer does not contain
433 *	valid data.
434 */
435static __inline
436void
437vfs_buf_test_cache(struct buf *bp,
438		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
439		  vm_page_t m)
440{
441
442	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
443	if (bp->b_flags & B_CACHE) {
444		int base = (foff + off) & PAGE_MASK;
445		if (vm_page_is_valid(m, base, size) == 0)
446			bp->b_flags &= ~B_CACHE;
447	}
448}
449
450/* Wake up the buffer daemon if necessary */
451static __inline
452void
453bd_wakeup(int dirtybuflevel)
454{
455
456	mtx_lock(&bdlock);
457	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
458		bd_request = 1;
459		wakeup(&bd_request);
460	}
461	mtx_unlock(&bdlock);
462}
463
464/*
465 * bd_speedup - speedup the buffer cache flushing code
466 */
467
468static __inline
469void
470bd_speedup(void)
471{
472
473	bd_wakeup(1);
474}
475
476/*
477 * Calculating buffer cache scaling values and reserve space for buffer
478 * headers.  This is called during low level kernel initialization and
479 * may be called more then once.  We CANNOT write to the memory area
480 * being reserved at this time.
481 */
482caddr_t
483kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
484{
485	int tuned_nbuf;
486	long maxbuf;
487
488	/*
489	 * physmem_est is in pages.  Convert it to kilobytes (assumes
490	 * PAGE_SIZE is >= 1K)
491	 */
492	physmem_est = physmem_est * (PAGE_SIZE / 1024);
493
494	/*
495	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
496	 * For the first 64MB of ram nominally allocate sufficient buffers to
497	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
498	 * buffers to cover 1/10 of our ram over 64MB.  When auto-sizing
499	 * the buffer cache we limit the eventual kva reservation to
500	 * maxbcache bytes.
501	 *
502	 * factor represents the 1/4 x ram conversion.
503	 */
504	if (nbuf == 0) {
505		int factor = 4 * BKVASIZE / 1024;
506
507		nbuf = 50;
508		if (physmem_est > 4096)
509			nbuf += min((physmem_est - 4096) / factor,
510			    65536 / factor);
511		if (physmem_est > 65536)
512			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
513
514		if (maxbcache && nbuf > maxbcache / BKVASIZE)
515			nbuf = maxbcache / BKVASIZE;
516		tuned_nbuf = 1;
517	} else
518		tuned_nbuf = 0;
519
520	/* XXX Avoid unsigned long overflows later on with maxbufspace. */
521	maxbuf = (LONG_MAX / 3) / BKVASIZE;
522	if (nbuf > maxbuf) {
523		if (!tuned_nbuf)
524			printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
525			    maxbuf);
526		nbuf = maxbuf;
527	}
528
529	/*
530	 * swbufs are used as temporary holders for I/O, such as paging I/O.
531	 * We have no less then 16 and no more then 256.
532	 */
533	nswbuf = max(min(nbuf/4, 256), 16);
534#ifdef NSWBUF_MIN
535	if (nswbuf < NSWBUF_MIN)
536		nswbuf = NSWBUF_MIN;
537#endif
538#ifdef DIRECTIO
539	ffs_rawread_setup();
540#endif
541
542	/*
543	 * Reserve space for the buffer cache buffers
544	 */
545	swbuf = (void *)v;
546	v = (caddr_t)(swbuf + nswbuf);
547	buf = (void *)v;
548	v = (caddr_t)(buf + nbuf);
549
550	return(v);
551}
552
553/* Initialize the buffer subsystem.  Called before use of any buffers. */
554void
555bufinit(void)
556{
557	struct buf *bp;
558	int i;
559
560	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
561	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
562	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
563	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
564
565	/* next, make a null set of free lists */
566	for (i = 0; i < BUFFER_QUEUES; i++)
567		TAILQ_INIT(&bufqueues[i]);
568
569	/* finally, initialize each buffer header and stick on empty q */
570	for (i = 0; i < nbuf; i++) {
571		bp = &buf[i];
572		bzero(bp, sizeof *bp);
573		bp->b_flags = B_INVAL;	/* we're just an empty header */
574		bp->b_rcred = NOCRED;
575		bp->b_wcred = NOCRED;
576		bp->b_qindex = QUEUE_EMPTY;
577		bp->b_vflags = 0;
578		bp->b_xflags = 0;
579		LIST_INIT(&bp->b_dep);
580		BUF_LOCKINIT(bp);
581		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
582	}
583
584	/*
585	 * maxbufspace is the absolute maximum amount of buffer space we are
586	 * allowed to reserve in KVM and in real terms.  The absolute maximum
587	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
588	 * used by most other processes.  The differential is required to
589	 * ensure that buf_daemon is able to run when other processes might
590	 * be blocked waiting for buffer space.
591	 *
592	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
593	 * this may result in KVM fragmentation which is not handled optimally
594	 * by the system.
595	 */
596	maxbufspace = (long)nbuf * BKVASIZE;
597	hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
598	lobufspace = hibufspace - MAXBSIZE;
599
600	lorunningspace = 512 * 1024;
601	hirunningspace = 1024 * 1024;
602
603/*
604 * Limit the amount of malloc memory since it is wired permanently into
605 * the kernel space.  Even though this is accounted for in the buffer
606 * allocation, we don't want the malloced region to grow uncontrolled.
607 * The malloc scheme improves memory utilization significantly on average
608 * (small) directories.
609 */
610	maxbufmallocspace = hibufspace / 20;
611
612/*
613 * Reduce the chance of a deadlock occuring by limiting the number
614 * of delayed-write dirty buffers we allow to stack up.
615 */
616	hidirtybuffers = nbuf / 4 + 20;
617	dirtybufthresh = hidirtybuffers * 9 / 10;
618	numdirtybuffers = 0;
619/*
620 * To support extreme low-memory systems, make sure hidirtybuffers cannot
621 * eat up all available buffer space.  This occurs when our minimum cannot
622 * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
623 * BKVASIZE'd (8K) buffers.
624 */
625	while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
626		hidirtybuffers >>= 1;
627	}
628	lodirtybuffers = hidirtybuffers / 2;
629
630/*
631 * Try to keep the number of free buffers in the specified range,
632 * and give special processes (e.g. like buf_daemon) access to an
633 * emergency reserve.
634 */
635	lofreebuffers = nbuf / 18 + 5;
636	hifreebuffers = 2 * lofreebuffers;
637	numfreebuffers = nbuf;
638
639/*
640 * Maximum number of async ops initiated per buf_daemon loop.  This is
641 * somewhat of a hack at the moment, we really need to limit ourselves
642 * based on the number of bytes of I/O in-transit that were initiated
643 * from buf_daemon.
644 */
645
646	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
647	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
648}
649
650/*
651 * bfreekva() - free the kva allocation for a buffer.
652 *
653 *	Since this call frees up buffer space, we call bufspacewakeup().
654 */
655static void
656bfreekva(struct buf *bp)
657{
658
659	if (bp->b_kvasize) {
660		atomic_add_int(&buffreekvacnt, 1);
661		atomic_subtract_long(&bufspace, bp->b_kvasize);
662		vm_map_remove(buffer_map, (vm_offset_t) bp->b_kvabase,
663		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize);
664		bp->b_kvasize = 0;
665		bufspacewakeup();
666	}
667}
668
669/*
670 *	bremfree:
671 *
672 *	Mark the buffer for removal from the appropriate free list in brelse.
673 *
674 */
675void
676bremfree(struct buf *bp)
677{
678
679	CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
680	KASSERT((bp->b_flags & B_REMFREE) == 0,
681	    ("bremfree: buffer %p already marked for delayed removal.", bp));
682	KASSERT(bp->b_qindex != QUEUE_NONE,
683	    ("bremfree: buffer %p not on a queue.", bp));
684	BUF_ASSERT_HELD(bp);
685
686	bp->b_flags |= B_REMFREE;
687	/* Fixup numfreebuffers count.  */
688	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
689		atomic_subtract_int(&numfreebuffers, 1);
690}
691
692/*
693 *	bremfreef:
694 *
695 *	Force an immediate removal from a free list.  Used only in nfs when
696 *	it abuses the b_freelist pointer.
697 */
698void
699bremfreef(struct buf *bp)
700{
701	mtx_lock(&bqlock);
702	bremfreel(bp);
703	mtx_unlock(&bqlock);
704}
705
706/*
707 *	bremfreel:
708 *
709 *	Removes a buffer from the free list, must be called with the
710 *	bqlock held.
711 */
712static void
713bremfreel(struct buf *bp)
714{
715	CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
716	    bp, bp->b_vp, bp->b_flags);
717	KASSERT(bp->b_qindex != QUEUE_NONE,
718	    ("bremfreel: buffer %p not on a queue.", bp));
719	BUF_ASSERT_HELD(bp);
720	mtx_assert(&bqlock, MA_OWNED);
721
722	TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
723	bp->b_qindex = QUEUE_NONE;
724	/*
725	 * If this was a delayed bremfree() we only need to remove the buffer
726	 * from the queue and return the stats are already done.
727	 */
728	if (bp->b_flags & B_REMFREE) {
729		bp->b_flags &= ~B_REMFREE;
730		return;
731	}
732	/*
733	 * Fixup numfreebuffers count.  If the buffer is invalid or not
734	 * delayed-write, the buffer was free and we must decrement
735	 * numfreebuffers.
736	 */
737	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
738		atomic_subtract_int(&numfreebuffers, 1);
739}
740
741
742/*
743 * Get a buffer with the specified data.  Look in the cache first.  We
744 * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
745 * is set, the buffer is valid and we do not have to do anything ( see
746 * getblk() ).  This is really just a special case of breadn().
747 */
748int
749bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
750    struct buf **bpp)
751{
752
753	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
754}
755
756/*
757 * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
758 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
759 * the buffer is valid and we do not have to do anything.
760 */
761void
762breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
763    int cnt, struct ucred * cred)
764{
765	struct buf *rabp;
766	int i;
767
768	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
769		if (inmem(vp, *rablkno))
770			continue;
771		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
772
773		if ((rabp->b_flags & B_CACHE) == 0) {
774			if (!TD_IS_IDLETHREAD(curthread))
775				curthread->td_ru.ru_inblock++;
776			rabp->b_flags |= B_ASYNC;
777			rabp->b_flags &= ~B_INVAL;
778			rabp->b_ioflags &= ~BIO_ERROR;
779			rabp->b_iocmd = BIO_READ;
780			if (rabp->b_rcred == NOCRED && cred != NOCRED)
781				rabp->b_rcred = crhold(cred);
782			vfs_busy_pages(rabp, 0);
783			BUF_KERNPROC(rabp);
784			rabp->b_iooffset = dbtob(rabp->b_blkno);
785			bstrategy(rabp);
786		} else {
787			brelse(rabp);
788		}
789	}
790}
791
792/*
793 * Operates like bread, but also starts asynchronous I/O on
794 * read-ahead blocks.
795 */
796int
797breadn(struct vnode * vp, daddr_t blkno, int size,
798    daddr_t * rablkno, int *rabsize,
799    int cnt, struct ucred * cred, struct buf **bpp)
800{
801	struct buf *bp;
802	int rv = 0, readwait = 0;
803
804	CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
805	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
806
807	/* if not found in cache, do some I/O */
808	if ((bp->b_flags & B_CACHE) == 0) {
809		if (!TD_IS_IDLETHREAD(curthread))
810			curthread->td_ru.ru_inblock++;
811		bp->b_iocmd = BIO_READ;
812		bp->b_flags &= ~B_INVAL;
813		bp->b_ioflags &= ~BIO_ERROR;
814		if (bp->b_rcred == NOCRED && cred != NOCRED)
815			bp->b_rcred = crhold(cred);
816		vfs_busy_pages(bp, 0);
817		bp->b_iooffset = dbtob(bp->b_blkno);
818		bstrategy(bp);
819		++readwait;
820	}
821
822	breada(vp, rablkno, rabsize, cnt, cred);
823
824	if (readwait) {
825		rv = bufwait(bp);
826	}
827	return (rv);
828}
829
830/*
831 * Write, release buffer on completion.  (Done by iodone
832 * if async).  Do not bother writing anything if the buffer
833 * is invalid.
834 *
835 * Note that we set B_CACHE here, indicating that buffer is
836 * fully valid and thus cacheable.  This is true even of NFS
837 * now so we set it generally.  This could be set either here
838 * or in biodone() since the I/O is synchronous.  We put it
839 * here.
840 */
841int
842bufwrite(struct buf *bp)
843{
844	int oldflags;
845	struct vnode *vp;
846	int vp_md;
847
848	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
849	if (bp->b_flags & B_INVAL) {
850		brelse(bp);
851		return (0);
852	}
853
854	oldflags = bp->b_flags;
855
856	BUF_ASSERT_HELD(bp);
857
858	if (bp->b_pin_count > 0)
859		bunpin_wait(bp);
860
861	KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
862	    ("FFS background buffer should not get here %p", bp));
863
864	vp = bp->b_vp;
865	if (vp)
866		vp_md = vp->v_vflag & VV_MD;
867	else
868		vp_md = 0;
869
870	/* Mark the buffer clean */
871	bundirty(bp);
872
873	bp->b_flags &= ~B_DONE;
874	bp->b_ioflags &= ~BIO_ERROR;
875	bp->b_flags |= B_CACHE;
876	bp->b_iocmd = BIO_WRITE;
877
878	bufobj_wref(bp->b_bufobj);
879	vfs_busy_pages(bp, 1);
880
881	/*
882	 * Normal bwrites pipeline writes
883	 */
884	bp->b_runningbufspace = bp->b_bufsize;
885	atomic_add_long(&runningbufspace, bp->b_runningbufspace);
886
887	if (!TD_IS_IDLETHREAD(curthread))
888		curthread->td_ru.ru_oublock++;
889	if (oldflags & B_ASYNC)
890		BUF_KERNPROC(bp);
891	bp->b_iooffset = dbtob(bp->b_blkno);
892	bstrategy(bp);
893
894	if ((oldflags & B_ASYNC) == 0) {
895		int rtval = bufwait(bp);
896		brelse(bp);
897		return (rtval);
898	} else {
899		/*
900		 * don't allow the async write to saturate the I/O
901		 * system.  We will not deadlock here because
902		 * we are blocking waiting for I/O that is already in-progress
903		 * to complete. We do not block here if it is the update
904		 * or syncer daemon trying to clean up as that can lead
905		 * to deadlock.
906		 */
907		if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
908			waitrunningbufspace();
909	}
910
911	return (0);
912}
913
914void
915bufbdflush(struct bufobj *bo, struct buf *bp)
916{
917	struct buf *nbp;
918
919	if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
920		(void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
921		altbufferflushes++;
922	} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
923		BO_LOCK(bo);
924		/*
925		 * Try to find a buffer to flush.
926		 */
927		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
928			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
929			    BUF_LOCK(nbp,
930				     LK_EXCLUSIVE | LK_NOWAIT, NULL))
931				continue;
932			if (bp == nbp)
933				panic("bdwrite: found ourselves");
934			BO_UNLOCK(bo);
935			/* Don't countdeps with the bo lock held. */
936			if (buf_countdeps(nbp, 0)) {
937				BO_LOCK(bo);
938				BUF_UNLOCK(nbp);
939				continue;
940			}
941			if (nbp->b_flags & B_CLUSTEROK) {
942				vfs_bio_awrite(nbp);
943			} else {
944				bremfree(nbp);
945				bawrite(nbp);
946			}
947			dirtybufferflushes++;
948			break;
949		}
950		if (nbp == NULL)
951			BO_UNLOCK(bo);
952	}
953}
954
955/*
956 * Delayed write. (Buffer is marked dirty).  Do not bother writing
957 * anything if the buffer is marked invalid.
958 *
959 * Note that since the buffer must be completely valid, we can safely
960 * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
961 * biodone() in order to prevent getblk from writing the buffer
962 * out synchronously.
963 */
964void
965bdwrite(struct buf *bp)
966{
967	struct thread *td = curthread;
968	struct vnode *vp;
969	struct bufobj *bo;
970
971	CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
972	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
973	BUF_ASSERT_HELD(bp);
974
975	if (bp->b_flags & B_INVAL) {
976		brelse(bp);
977		return;
978	}
979
980	/*
981	 * If we have too many dirty buffers, don't create any more.
982	 * If we are wildly over our limit, then force a complete
983	 * cleanup. Otherwise, just keep the situation from getting
984	 * out of control. Note that we have to avoid a recursive
985	 * disaster and not try to clean up after our own cleanup!
986	 */
987	vp = bp->b_vp;
988	bo = bp->b_bufobj;
989	if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
990		td->td_pflags |= TDP_INBDFLUSH;
991		BO_BDFLUSH(bo, bp);
992		td->td_pflags &= ~TDP_INBDFLUSH;
993	} else
994		recursiveflushes++;
995
996	bdirty(bp);
997	/*
998	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
999	 * true even of NFS now.
1000	 */
1001	bp->b_flags |= B_CACHE;
1002
1003	/*
1004	 * This bmap keeps the system from needing to do the bmap later,
1005	 * perhaps when the system is attempting to do a sync.  Since it
1006	 * is likely that the indirect block -- or whatever other datastructure
1007	 * that the filesystem needs is still in memory now, it is a good
1008	 * thing to do this.  Note also, that if the pageout daemon is
1009	 * requesting a sync -- there might not be enough memory to do
1010	 * the bmap then...  So, this is important to do.
1011	 */
1012	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1013		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1014	}
1015
1016	/*
1017	 * Set the *dirty* buffer range based upon the VM system dirty pages.
1018	 */
1019	vfs_setdirty(bp);
1020
1021	/*
1022	 * We need to do this here to satisfy the vnode_pager and the
1023	 * pageout daemon, so that it thinks that the pages have been
1024	 * "cleaned".  Note that since the pages are in a delayed write
1025	 * buffer -- the VFS layer "will" see that the pages get written
1026	 * out on the next sync, or perhaps the cluster will be completed.
1027	 */
1028	vfs_clean_pages(bp);
1029	bqrelse(bp);
1030
1031	/*
1032	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1033	 * buffers (midpoint between our recovery point and our stall
1034	 * point).
1035	 */
1036	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1037
1038	/*
1039	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1040	 * due to the softdep code.
1041	 */
1042}
1043
1044/*
1045 *	bdirty:
1046 *
1047 *	Turn buffer into delayed write request.  We must clear BIO_READ and
1048 *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1049 *	itself to properly update it in the dirty/clean lists.  We mark it
1050 *	B_DONE to ensure that any asynchronization of the buffer properly
1051 *	clears B_DONE ( else a panic will occur later ).
1052 *
1053 *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1054 *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1055 *	should only be called if the buffer is known-good.
1056 *
1057 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1058 *	count.
1059 *
1060 *	The buffer must be on QUEUE_NONE.
1061 */
1062void
1063bdirty(struct buf *bp)
1064{
1065
1066	CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1067	    bp, bp->b_vp, bp->b_flags);
1068	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1069	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1070	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1071	BUF_ASSERT_HELD(bp);
1072	bp->b_flags &= ~(B_RELBUF);
1073	bp->b_iocmd = BIO_WRITE;
1074
1075	if ((bp->b_flags & B_DELWRI) == 0) {
1076		bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1077		reassignbuf(bp);
1078		atomic_add_int(&numdirtybuffers, 1);
1079		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1080	}
1081}
1082
1083/*
1084 *	bundirty:
1085 *
1086 *	Clear B_DELWRI for buffer.
1087 *
1088 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1089 *	count.
1090 *
1091 *	The buffer must be on QUEUE_NONE.
1092 */
1093
1094void
1095bundirty(struct buf *bp)
1096{
1097
1098	CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1099	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1100	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1101	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1102	BUF_ASSERT_HELD(bp);
1103
1104	if (bp->b_flags & B_DELWRI) {
1105		bp->b_flags &= ~B_DELWRI;
1106		reassignbuf(bp);
1107		atomic_subtract_int(&numdirtybuffers, 1);
1108		numdirtywakeup(lodirtybuffers);
1109	}
1110	/*
1111	 * Since it is now being written, we can clear its deferred write flag.
1112	 */
1113	bp->b_flags &= ~B_DEFERRED;
1114}
1115
1116/*
1117 *	bawrite:
1118 *
1119 *	Asynchronous write.  Start output on a buffer, but do not wait for
1120 *	it to complete.  The buffer is released when the output completes.
1121 *
1122 *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1123 *	B_INVAL buffers.  Not us.
1124 */
1125void
1126bawrite(struct buf *bp)
1127{
1128
1129	bp->b_flags |= B_ASYNC;
1130	(void) bwrite(bp);
1131}
1132
1133/*
1134 *	bwillwrite:
1135 *
1136 *	Called prior to the locking of any vnodes when we are expecting to
1137 *	write.  We do not want to starve the buffer cache with too many
1138 *	dirty buffers so we block here.  By blocking prior to the locking
1139 *	of any vnodes we attempt to avoid the situation where a locked vnode
1140 *	prevents the various system daemons from flushing related buffers.
1141 */
1142
1143void
1144bwillwrite(void)
1145{
1146
1147	if (numdirtybuffers >= hidirtybuffers) {
1148		mtx_lock(&nblock);
1149		while (numdirtybuffers >= hidirtybuffers) {
1150			bd_wakeup(1);
1151			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1152			msleep(&needsbuffer, &nblock,
1153			    (PRIBIO + 4), "flswai", 0);
1154		}
1155		mtx_unlock(&nblock);
1156	}
1157}
1158
1159/*
1160 * Return true if we have too many dirty buffers.
1161 */
1162int
1163buf_dirty_count_severe(void)
1164{
1165
1166	return(numdirtybuffers >= hidirtybuffers);
1167}
1168
1169/*
1170 *	brelse:
1171 *
1172 *	Release a busy buffer and, if requested, free its resources.  The
1173 *	buffer will be stashed in the appropriate bufqueue[] allowing it
1174 *	to be accessed later as a cache entity or reused for other purposes.
1175 */
1176void
1177brelse(struct buf *bp)
1178{
1179	CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1180	    bp, bp->b_vp, bp->b_flags);
1181	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1182	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1183
1184	if (bp->b_flags & B_MANAGED) {
1185		bqrelse(bp);
1186		return;
1187	}
1188
1189	if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1190	    bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1191		/*
1192		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1193		 * pages from being scrapped.  If the error is anything
1194		 * other than an I/O error (EIO), assume that retryingi
1195		 * is futile.
1196		 */
1197		bp->b_ioflags &= ~BIO_ERROR;
1198		bdirty(bp);
1199	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1200	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1201		/*
1202		 * Either a failed I/O or we were asked to free or not
1203		 * cache the buffer.
1204		 */
1205		bp->b_flags |= B_INVAL;
1206		if (!LIST_EMPTY(&bp->b_dep))
1207			buf_deallocate(bp);
1208		if (bp->b_flags & B_DELWRI) {
1209			atomic_subtract_int(&numdirtybuffers, 1);
1210			numdirtywakeup(lodirtybuffers);
1211		}
1212		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1213		if ((bp->b_flags & B_VMIO) == 0) {
1214			if (bp->b_bufsize)
1215				allocbuf(bp, 0);
1216			if (bp->b_vp)
1217				brelvp(bp);
1218		}
1219	}
1220
1221	/*
1222	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1223	 * is called with B_DELWRI set, the underlying pages may wind up
1224	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1225	 * because pages associated with a B_DELWRI bp are marked clean.
1226	 *
1227	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1228	 * if B_DELWRI is set.
1229	 *
1230	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1231	 * on pages to return pages to the VM page queues.
1232	 */
1233	if (bp->b_flags & B_DELWRI)
1234		bp->b_flags &= ~B_RELBUF;
1235	else if (vm_page_count_severe()) {
1236		/*
1237		 * The locking of the BO_LOCK is not necessary since
1238		 * BKGRDINPROG cannot be set while we hold the buf
1239		 * lock, it can only be cleared if it is already
1240		 * pending.
1241		 */
1242		if (bp->b_vp) {
1243			if (!(bp->b_vflags & BV_BKGRDINPROG))
1244				bp->b_flags |= B_RELBUF;
1245		} else
1246			bp->b_flags |= B_RELBUF;
1247	}
1248
1249	/*
1250	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1251	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1252	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1253	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1254	 *
1255	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1256	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1257	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1258	 *
1259	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1260	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1261	 * the commit state and we cannot afford to lose the buffer. If the
1262	 * buffer has a background write in progress, we need to keep it
1263	 * around to prevent it from being reconstituted and starting a second
1264	 * background write.
1265	 */
1266	if ((bp->b_flags & B_VMIO)
1267	    && !(bp->b_vp->v_mount != NULL &&
1268		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1269		 !vn_isdisk(bp->b_vp, NULL) &&
1270		 (bp->b_flags & B_DELWRI))
1271	    ) {
1272
1273		int i, j, resid;
1274		vm_page_t m;
1275		off_t foff;
1276		vm_pindex_t poff;
1277		vm_object_t obj;
1278
1279		obj = bp->b_bufobj->bo_object;
1280
1281		/*
1282		 * Get the base offset and length of the buffer.  Note that
1283		 * in the VMIO case if the buffer block size is not
1284		 * page-aligned then b_data pointer may not be page-aligned.
1285		 * But our b_pages[] array *IS* page aligned.
1286		 *
1287		 * block sizes less then DEV_BSIZE (usually 512) are not
1288		 * supported due to the page granularity bits (m->valid,
1289		 * m->dirty, etc...).
1290		 *
1291		 * See man buf(9) for more information
1292		 */
1293		resid = bp->b_bufsize;
1294		foff = bp->b_offset;
1295		VM_OBJECT_LOCK(obj);
1296		for (i = 0; i < bp->b_npages; i++) {
1297			int had_bogus = 0;
1298
1299			m = bp->b_pages[i];
1300
1301			/*
1302			 * If we hit a bogus page, fixup *all* the bogus pages
1303			 * now.
1304			 */
1305			if (m == bogus_page) {
1306				poff = OFF_TO_IDX(bp->b_offset);
1307				had_bogus = 1;
1308
1309				for (j = i; j < bp->b_npages; j++) {
1310					vm_page_t mtmp;
1311					mtmp = bp->b_pages[j];
1312					if (mtmp == bogus_page) {
1313						mtmp = vm_page_lookup(obj, poff + j);
1314						if (!mtmp) {
1315							panic("brelse: page missing\n");
1316						}
1317						bp->b_pages[j] = mtmp;
1318					}
1319				}
1320
1321				if ((bp->b_flags & B_INVAL) == 0) {
1322					pmap_qenter(
1323					    trunc_page((vm_offset_t)bp->b_data),
1324					    bp->b_pages, bp->b_npages);
1325				}
1326				m = bp->b_pages[i];
1327			}
1328			if ((bp->b_flags & B_NOCACHE) ||
1329			    (bp->b_ioflags & BIO_ERROR)) {
1330				int poffset = foff & PAGE_MASK;
1331				int presid = resid > (PAGE_SIZE - poffset) ?
1332					(PAGE_SIZE - poffset) : resid;
1333
1334				KASSERT(presid >= 0, ("brelse: extra page"));
1335				vm_page_lock_queues();
1336				vm_page_set_invalid(m, poffset, presid);
1337				vm_page_unlock_queues();
1338				if (had_bogus)
1339					printf("avoided corruption bug in bogus_page/brelse code\n");
1340			}
1341			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1342			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1343		}
1344		VM_OBJECT_UNLOCK(obj);
1345		if (bp->b_flags & (B_INVAL | B_RELBUF))
1346			vfs_vmio_release(bp);
1347
1348	} else if (bp->b_flags & B_VMIO) {
1349
1350		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1351			vfs_vmio_release(bp);
1352		}
1353
1354	} else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1355		if (bp->b_bufsize != 0)
1356			allocbuf(bp, 0);
1357		if (bp->b_vp != NULL)
1358			brelvp(bp);
1359	}
1360
1361	if (BUF_LOCKRECURSED(bp)) {
1362		/* do not release to free list */
1363		BUF_UNLOCK(bp);
1364		return;
1365	}
1366
1367	/* enqueue */
1368	mtx_lock(&bqlock);
1369	/* Handle delayed bremfree() processing. */
1370	if (bp->b_flags & B_REMFREE)
1371		bremfreel(bp);
1372	if (bp->b_qindex != QUEUE_NONE)
1373		panic("brelse: free buffer onto another queue???");
1374
1375	/*
1376	 * If the buffer has junk contents signal it and eventually
1377	 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1378	 * doesn't find it.
1379	 */
1380	if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1381	    (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1382		bp->b_flags |= B_INVAL;
1383	if (bp->b_flags & B_INVAL) {
1384		if (bp->b_flags & B_DELWRI)
1385			bundirty(bp);
1386		if (bp->b_vp)
1387			brelvp(bp);
1388	}
1389
1390	/* buffers with no memory */
1391	if (bp->b_bufsize == 0) {
1392		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1393		if (bp->b_vflags & BV_BKGRDINPROG)
1394			panic("losing buffer 1");
1395		if (bp->b_kvasize) {
1396			bp->b_qindex = QUEUE_EMPTYKVA;
1397		} else {
1398			bp->b_qindex = QUEUE_EMPTY;
1399		}
1400		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1401	/* buffers with junk contents */
1402	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1403	    (bp->b_ioflags & BIO_ERROR)) {
1404		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1405		if (bp->b_vflags & BV_BKGRDINPROG)
1406			panic("losing buffer 2");
1407		bp->b_qindex = QUEUE_CLEAN;
1408		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1409	/* remaining buffers */
1410	} else {
1411		if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1412		    (B_DELWRI|B_NEEDSGIANT))
1413			bp->b_qindex = QUEUE_DIRTY_GIANT;
1414		else if (bp->b_flags & B_DELWRI)
1415			bp->b_qindex = QUEUE_DIRTY;
1416		else
1417			bp->b_qindex = QUEUE_CLEAN;
1418		if (bp->b_flags & B_AGE)
1419			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1420		else
1421			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1422	}
1423	mtx_unlock(&bqlock);
1424
1425	/*
1426	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1427	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1428	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1429	 * if B_INVAL is set ).
1430	 */
1431
1432	if (!(bp->b_flags & B_DELWRI))
1433		bufcountwakeup();
1434
1435	/*
1436	 * Something we can maybe free or reuse
1437	 */
1438	if (bp->b_bufsize || bp->b_kvasize)
1439		bufspacewakeup();
1440
1441	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1442	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1443		panic("brelse: not dirty");
1444	/* unlock */
1445	BUF_UNLOCK(bp);
1446}
1447
1448/*
1449 * Release a buffer back to the appropriate queue but do not try to free
1450 * it.  The buffer is expected to be used again soon.
1451 *
1452 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1453 * biodone() to requeue an async I/O on completion.  It is also used when
1454 * known good buffers need to be requeued but we think we may need the data
1455 * again soon.
1456 *
1457 * XXX we should be able to leave the B_RELBUF hint set on completion.
1458 */
1459void
1460bqrelse(struct buf *bp)
1461{
1462	CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1463	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1464	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1465
1466	if (BUF_LOCKRECURSED(bp)) {
1467		/* do not release to free list */
1468		BUF_UNLOCK(bp);
1469		return;
1470	}
1471
1472	if (bp->b_flags & B_MANAGED) {
1473		if (bp->b_flags & B_REMFREE) {
1474			mtx_lock(&bqlock);
1475			bremfreel(bp);
1476			mtx_unlock(&bqlock);
1477		}
1478		bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1479		BUF_UNLOCK(bp);
1480		return;
1481	}
1482
1483	mtx_lock(&bqlock);
1484	/* Handle delayed bremfree() processing. */
1485	if (bp->b_flags & B_REMFREE)
1486		bremfreel(bp);
1487	if (bp->b_qindex != QUEUE_NONE)
1488		panic("bqrelse: free buffer onto another queue???");
1489	/* buffers with stale but valid contents */
1490	if (bp->b_flags & B_DELWRI) {
1491		if (bp->b_flags & B_NEEDSGIANT)
1492			bp->b_qindex = QUEUE_DIRTY_GIANT;
1493		else
1494			bp->b_qindex = QUEUE_DIRTY;
1495		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1496	} else {
1497		/*
1498		 * The locking of the BO_LOCK for checking of the
1499		 * BV_BKGRDINPROG is not necessary since the
1500		 * BV_BKGRDINPROG cannot be set while we hold the buf
1501		 * lock, it can only be cleared if it is already
1502		 * pending.
1503		 */
1504		if (!vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1505			bp->b_qindex = QUEUE_CLEAN;
1506			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1507			    b_freelist);
1508		} else {
1509			/*
1510			 * We are too low on memory, we have to try to free
1511			 * the buffer (most importantly: the wired pages
1512			 * making up its backing store) *now*.
1513			 */
1514			mtx_unlock(&bqlock);
1515			brelse(bp);
1516			return;
1517		}
1518	}
1519	mtx_unlock(&bqlock);
1520
1521	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1522		bufcountwakeup();
1523
1524	/*
1525	 * Something we can maybe free or reuse.
1526	 */
1527	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1528		bufspacewakeup();
1529
1530	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1531	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1532		panic("bqrelse: not dirty");
1533	/* unlock */
1534	BUF_UNLOCK(bp);
1535}
1536
1537/* Give pages used by the bp back to the VM system (where possible) */
1538static void
1539vfs_vmio_release(struct buf *bp)
1540{
1541	int i;
1542	vm_page_t m;
1543
1544	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1545	vm_page_lock_queues();
1546	for (i = 0; i < bp->b_npages; i++) {
1547		m = bp->b_pages[i];
1548		bp->b_pages[i] = NULL;
1549		/*
1550		 * In order to keep page LRU ordering consistent, put
1551		 * everything on the inactive queue.
1552		 */
1553		vm_page_unwire(m, 0);
1554		/*
1555		 * We don't mess with busy pages, it is
1556		 * the responsibility of the process that
1557		 * busied the pages to deal with them.
1558		 */
1559		if ((m->oflags & VPO_BUSY) || (m->busy != 0))
1560			continue;
1561
1562		if (m->wire_count == 0) {
1563			/*
1564			 * Might as well free the page if we can and it has
1565			 * no valid data.  We also free the page if the
1566			 * buffer was used for direct I/O
1567			 */
1568			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1569			    m->hold_count == 0) {
1570				vm_page_free(m);
1571			} else if (bp->b_flags & B_DIRECT) {
1572				vm_page_try_to_free(m);
1573			} else if (vm_page_count_severe()) {
1574				vm_page_try_to_cache(m);
1575			}
1576		}
1577	}
1578	vm_page_unlock_queues();
1579	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1580	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1581
1582	if (bp->b_bufsize) {
1583		bufspacewakeup();
1584		bp->b_bufsize = 0;
1585	}
1586	bp->b_npages = 0;
1587	bp->b_flags &= ~B_VMIO;
1588	if (bp->b_vp)
1589		brelvp(bp);
1590}
1591
1592/*
1593 * Check to see if a block at a particular lbn is available for a clustered
1594 * write.
1595 */
1596static int
1597vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1598{
1599	struct buf *bpa;
1600	int match;
1601
1602	match = 0;
1603
1604	/* If the buf isn't in core skip it */
1605	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1606		return (0);
1607
1608	/* If the buf is busy we don't want to wait for it */
1609	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1610		return (0);
1611
1612	/* Only cluster with valid clusterable delayed write buffers */
1613	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1614	    (B_DELWRI | B_CLUSTEROK))
1615		goto done;
1616
1617	if (bpa->b_bufsize != size)
1618		goto done;
1619
1620	/*
1621	 * Check to see if it is in the expected place on disk and that the
1622	 * block has been mapped.
1623	 */
1624	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1625		match = 1;
1626done:
1627	BUF_UNLOCK(bpa);
1628	return (match);
1629}
1630
1631/*
1632 *	vfs_bio_awrite:
1633 *
1634 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1635 *	This is much better then the old way of writing only one buffer at
1636 *	a time.  Note that we may not be presented with the buffers in the
1637 *	correct order, so we search for the cluster in both directions.
1638 */
1639int
1640vfs_bio_awrite(struct buf *bp)
1641{
1642	struct bufobj *bo;
1643	int i;
1644	int j;
1645	daddr_t lblkno = bp->b_lblkno;
1646	struct vnode *vp = bp->b_vp;
1647	int ncl;
1648	int nwritten;
1649	int size;
1650	int maxcl;
1651
1652	bo = &vp->v_bufobj;
1653	/*
1654	 * right now we support clustered writing only to regular files.  If
1655	 * we find a clusterable block we could be in the middle of a cluster
1656	 * rather then at the beginning.
1657	 */
1658	if ((vp->v_type == VREG) &&
1659	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1660	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1661
1662		size = vp->v_mount->mnt_stat.f_iosize;
1663		maxcl = MAXPHYS / size;
1664
1665		BO_LOCK(bo);
1666		for (i = 1; i < maxcl; i++)
1667			if (vfs_bio_clcheck(vp, size, lblkno + i,
1668			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1669				break;
1670
1671		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1672			if (vfs_bio_clcheck(vp, size, lblkno - j,
1673			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1674				break;
1675		BO_UNLOCK(bo);
1676		--j;
1677		ncl = i + j;
1678		/*
1679		 * this is a possible cluster write
1680		 */
1681		if (ncl != 1) {
1682			BUF_UNLOCK(bp);
1683			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1684			return nwritten;
1685		}
1686	}
1687	bremfree(bp);
1688	bp->b_flags |= B_ASYNC;
1689	/*
1690	 * default (old) behavior, writing out only one block
1691	 *
1692	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1693	 */
1694	nwritten = bp->b_bufsize;
1695	(void) bwrite(bp);
1696
1697	return nwritten;
1698}
1699
1700/*
1701 *	getnewbuf:
1702 *
1703 *	Find and initialize a new buffer header, freeing up existing buffers
1704 *	in the bufqueues as necessary.  The new buffer is returned locked.
1705 *
1706 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1707 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1708 *
1709 *	We block if:
1710 *		We have insufficient buffer headers
1711 *		We have insufficient buffer space
1712 *		buffer_map is too fragmented ( space reservation fails )
1713 *		If we have to flush dirty buffers ( but we try to avoid this )
1714 *
1715 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1716 *	Instead we ask the buf daemon to do it for us.  We attempt to
1717 *	avoid piecemeal wakeups of the pageout daemon.
1718 */
1719
1720static struct buf *
1721getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
1722    int gbflags)
1723{
1724	struct thread *td;
1725	struct buf *bp;
1726	struct buf *nbp;
1727	int defrag = 0;
1728	int nqindex;
1729	static int flushingbufs;
1730
1731	td = curthread;
1732	/*
1733	 * We can't afford to block since we might be holding a vnode lock,
1734	 * which may prevent system daemons from running.  We deal with
1735	 * low-memory situations by proactively returning memory and running
1736	 * async I/O rather then sync I/O.
1737	 */
1738	atomic_add_int(&getnewbufcalls, 1);
1739	atomic_subtract_int(&getnewbufrestarts, 1);
1740restart:
1741	atomic_add_int(&getnewbufrestarts, 1);
1742
1743	/*
1744	 * Setup for scan.  If we do not have enough free buffers,
1745	 * we setup a degenerate case that immediately fails.  Note
1746	 * that if we are specially marked process, we are allowed to
1747	 * dip into our reserves.
1748	 *
1749	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1750	 *
1751	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1752	 * However, there are a number of cases (defragging, reusing, ...)
1753	 * where we cannot backup.
1754	 */
1755	mtx_lock(&bqlock);
1756	nqindex = QUEUE_EMPTYKVA;
1757	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1758
1759	if (nbp == NULL) {
1760		/*
1761		 * If no EMPTYKVA buffers and we are either
1762		 * defragging or reusing, locate a CLEAN buffer
1763		 * to free or reuse.  If bufspace useage is low
1764		 * skip this step so we can allocate a new buffer.
1765		 */
1766		if (defrag || bufspace >= lobufspace) {
1767			nqindex = QUEUE_CLEAN;
1768			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1769		}
1770
1771		/*
1772		 * If we could not find or were not allowed to reuse a
1773		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1774		 * buffer.  We can only use an EMPTY buffer if allocating
1775		 * its KVA would not otherwise run us out of buffer space.
1776		 */
1777		if (nbp == NULL && defrag == 0 &&
1778		    bufspace + maxsize < hibufspace) {
1779			nqindex = QUEUE_EMPTY;
1780			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1781		}
1782	}
1783
1784	/*
1785	 * Run scan, possibly freeing data and/or kva mappings on the fly
1786	 * depending.
1787	 */
1788
1789	while ((bp = nbp) != NULL) {
1790		int qindex = nqindex;
1791
1792		/*
1793		 * Calculate next bp ( we can only use it if we do not block
1794		 * or do other fancy things ).
1795		 */
1796		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1797			switch(qindex) {
1798			case QUEUE_EMPTY:
1799				nqindex = QUEUE_EMPTYKVA;
1800				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1801					break;
1802				/* FALLTHROUGH */
1803			case QUEUE_EMPTYKVA:
1804				nqindex = QUEUE_CLEAN;
1805				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1806					break;
1807				/* FALLTHROUGH */
1808			case QUEUE_CLEAN:
1809				/*
1810				 * nbp is NULL.
1811				 */
1812				break;
1813			}
1814		}
1815		/*
1816		 * If we are defragging then we need a buffer with
1817		 * b_kvasize != 0.  XXX this situation should no longer
1818		 * occur, if defrag is non-zero the buffer's b_kvasize
1819		 * should also be non-zero at this point.  XXX
1820		 */
1821		if (defrag && bp->b_kvasize == 0) {
1822			printf("Warning: defrag empty buffer %p\n", bp);
1823			continue;
1824		}
1825
1826		/*
1827		 * Start freeing the bp.  This is somewhat involved.  nbp
1828		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1829		 */
1830		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1831			continue;
1832		if (bp->b_vp) {
1833			BO_LOCK(bp->b_bufobj);
1834			if (bp->b_vflags & BV_BKGRDINPROG) {
1835				BO_UNLOCK(bp->b_bufobj);
1836				BUF_UNLOCK(bp);
1837				continue;
1838			}
1839			BO_UNLOCK(bp->b_bufobj);
1840		}
1841		CTR6(KTR_BUF,
1842		    "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1843		    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1844		    bp->b_kvasize, bp->b_bufsize, qindex);
1845
1846		/*
1847		 * Sanity Checks
1848		 */
1849		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1850
1851		/*
1852		 * Note: we no longer distinguish between VMIO and non-VMIO
1853		 * buffers.
1854		 */
1855
1856		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1857
1858		bremfreel(bp);
1859		mtx_unlock(&bqlock);
1860
1861		if (qindex == QUEUE_CLEAN) {
1862			if (bp->b_flags & B_VMIO) {
1863				bp->b_flags &= ~B_ASYNC;
1864				vfs_vmio_release(bp);
1865			}
1866			if (bp->b_vp)
1867				brelvp(bp);
1868		}
1869
1870		/*
1871		 * NOTE:  nbp is now entirely invalid.  We can only restart
1872		 * the scan from this point on.
1873		 *
1874		 * Get the rest of the buffer freed up.  b_kva* is still
1875		 * valid after this operation.
1876		 */
1877
1878		if (bp->b_rcred != NOCRED) {
1879			crfree(bp->b_rcred);
1880			bp->b_rcred = NOCRED;
1881		}
1882		if (bp->b_wcred != NOCRED) {
1883			crfree(bp->b_wcred);
1884			bp->b_wcred = NOCRED;
1885		}
1886		if (!LIST_EMPTY(&bp->b_dep))
1887			buf_deallocate(bp);
1888		if (bp->b_vflags & BV_BKGRDINPROG)
1889			panic("losing buffer 3");
1890		KASSERT(bp->b_vp == NULL,
1891		    ("bp: %p still has vnode %p.  qindex: %d",
1892		    bp, bp->b_vp, qindex));
1893		KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1894		   ("bp: %p still on a buffer list. xflags %X",
1895		    bp, bp->b_xflags));
1896
1897		if (bp->b_bufsize)
1898			allocbuf(bp, 0);
1899
1900		bp->b_flags = 0;
1901		bp->b_ioflags = 0;
1902		bp->b_xflags = 0;
1903		bp->b_vflags = 0;
1904		bp->b_vp = NULL;
1905		bp->b_blkno = bp->b_lblkno = 0;
1906		bp->b_offset = NOOFFSET;
1907		bp->b_iodone = 0;
1908		bp->b_error = 0;
1909		bp->b_resid = 0;
1910		bp->b_bcount = 0;
1911		bp->b_npages = 0;
1912		bp->b_dirtyoff = bp->b_dirtyend = 0;
1913		bp->b_bufobj = NULL;
1914		bp->b_pin_count = 0;
1915		bp->b_fsprivate1 = NULL;
1916		bp->b_fsprivate2 = NULL;
1917		bp->b_fsprivate3 = NULL;
1918
1919		LIST_INIT(&bp->b_dep);
1920
1921		/*
1922		 * If we are defragging then free the buffer.
1923		 */
1924		if (defrag) {
1925			bp->b_flags |= B_INVAL;
1926			bfreekva(bp);
1927			brelse(bp);
1928			defrag = 0;
1929			goto restart;
1930		}
1931
1932		/*
1933		 * Notify any waiters for the buffer lock about
1934		 * identity change by freeing the buffer.
1935		 */
1936		if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
1937			bp->b_flags |= B_INVAL;
1938			bfreekva(bp);
1939			brelse(bp);
1940			goto restart;
1941		}
1942
1943		/*
1944		 * If we are overcomitted then recover the buffer and its
1945		 * KVM space.  This occurs in rare situations when multiple
1946		 * processes are blocked in getnewbuf() or allocbuf().
1947		 */
1948		if (bufspace >= hibufspace)
1949			flushingbufs = 1;
1950		if (flushingbufs && bp->b_kvasize != 0) {
1951			bp->b_flags |= B_INVAL;
1952			bfreekva(bp);
1953			brelse(bp);
1954			goto restart;
1955		}
1956		if (bufspace < lobufspace)
1957			flushingbufs = 0;
1958		break;
1959	}
1960
1961	/*
1962	 * If we exhausted our list, sleep as appropriate.  We may have to
1963	 * wakeup various daemons and write out some dirty buffers.
1964	 *
1965	 * Generally we are sleeping due to insufficient buffer space.
1966	 */
1967
1968	if (bp == NULL) {
1969		int flags, norunbuf;
1970		char *waitmsg;
1971		int fl;
1972
1973		if (defrag) {
1974			flags = VFS_BIO_NEED_BUFSPACE;
1975			waitmsg = "nbufkv";
1976		} else if (bufspace >= hibufspace) {
1977			waitmsg = "nbufbs";
1978			flags = VFS_BIO_NEED_BUFSPACE;
1979		} else {
1980			waitmsg = "newbuf";
1981			flags = VFS_BIO_NEED_ANY;
1982		}
1983		mtx_lock(&nblock);
1984		needsbuffer |= flags;
1985		mtx_unlock(&nblock);
1986		mtx_unlock(&bqlock);
1987
1988		bd_speedup();	/* heeeelp */
1989		if (gbflags & GB_NOWAIT_BD)
1990			return (NULL);
1991
1992		mtx_lock(&nblock);
1993		while (needsbuffer & flags) {
1994			if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
1995				mtx_unlock(&nblock);
1996				/*
1997				 * getblk() is called with a vnode
1998				 * locked, and some majority of the
1999				 * dirty buffers may as well belong to
2000				 * the vnode. Flushing the buffers
2001				 * there would make a progress that
2002				 * cannot be achieved by the
2003				 * buf_daemon, that cannot lock the
2004				 * vnode.
2005				 */
2006				norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2007				    (td->td_pflags & TDP_NORUNNINGBUF);
2008				/* play bufdaemon */
2009				td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2010				fl = buf_do_flush(vp);
2011				td->td_pflags &= norunbuf;
2012				mtx_lock(&nblock);
2013				if (fl != 0)
2014					continue;
2015				if ((needsbuffer & flags) == 0)
2016					break;
2017			}
2018			if (msleep(&needsbuffer, &nblock,
2019			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2020				mtx_unlock(&nblock);
2021				return (NULL);
2022			}
2023		}
2024		mtx_unlock(&nblock);
2025	} else {
2026		/*
2027		 * We finally have a valid bp.  We aren't quite out of the
2028		 * woods, we still have to reserve kva space.  In order
2029		 * to keep fragmentation sane we only allocate kva in
2030		 * BKVASIZE chunks.
2031		 */
2032		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2033
2034		if (maxsize != bp->b_kvasize) {
2035			vm_offset_t addr = 0;
2036
2037			bfreekva(bp);
2038
2039			vm_map_lock(buffer_map);
2040			if (vm_map_findspace(buffer_map,
2041				vm_map_min(buffer_map), maxsize, &addr)) {
2042				/*
2043				 * Uh oh.  Buffer map is to fragmented.  We
2044				 * must defragment the map.
2045				 */
2046				atomic_add_int(&bufdefragcnt, 1);
2047				vm_map_unlock(buffer_map);
2048				defrag = 1;
2049				bp->b_flags |= B_INVAL;
2050				brelse(bp);
2051				goto restart;
2052			}
2053			if (addr) {
2054				vm_map_insert(buffer_map, NULL, 0,
2055					addr, addr + maxsize,
2056					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2057
2058				bp->b_kvabase = (caddr_t) addr;
2059				bp->b_kvasize = maxsize;
2060				atomic_add_long(&bufspace, bp->b_kvasize);
2061				atomic_add_int(&bufreusecnt, 1);
2062			}
2063			vm_map_unlock(buffer_map);
2064		}
2065		bp->b_saveaddr = bp->b_kvabase;
2066		bp->b_data = bp->b_saveaddr;
2067	}
2068	return(bp);
2069}
2070
2071/*
2072 *	buf_daemon:
2073 *
2074 *	buffer flushing daemon.  Buffers are normally flushed by the
2075 *	update daemon but if it cannot keep up this process starts to
2076 *	take the load in an attempt to prevent getnewbuf() from blocking.
2077 */
2078
2079static struct kproc_desc buf_kp = {
2080	"bufdaemon",
2081	buf_daemon,
2082	&bufdaemonproc
2083};
2084SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2085
2086static int
2087buf_do_flush(struct vnode *vp)
2088{
2089	int flushed;
2090
2091	flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2092	/* The list empty check here is slightly racy */
2093	if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2094		mtx_lock(&Giant);
2095		flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2096		mtx_unlock(&Giant);
2097	}
2098	if (flushed == 0) {
2099		/*
2100		 * Could not find any buffers without rollback
2101		 * dependencies, so just write the first one
2102		 * in the hopes of eventually making progress.
2103		 */
2104		flushbufqueues(vp, QUEUE_DIRTY, 1);
2105		if (!TAILQ_EMPTY(
2106			    &bufqueues[QUEUE_DIRTY_GIANT])) {
2107			mtx_lock(&Giant);
2108			flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2109			mtx_unlock(&Giant);
2110		}
2111	}
2112	return (flushed);
2113}
2114
2115static void
2116buf_daemon()
2117{
2118
2119	/*
2120	 * This process needs to be suspended prior to shutdown sync.
2121	 */
2122	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2123	    SHUTDOWN_PRI_LAST);
2124
2125	/*
2126	 * This process is allowed to take the buffer cache to the limit
2127	 */
2128	curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2129	mtx_lock(&bdlock);
2130	for (;;) {
2131		bd_request = 0;
2132		mtx_unlock(&bdlock);
2133
2134		kproc_suspend_check(bufdaemonproc);
2135
2136		/*
2137		 * Do the flush.  Limit the amount of in-transit I/O we
2138		 * allow to build up, otherwise we would completely saturate
2139		 * the I/O system.  Wakeup any waiting processes before we
2140		 * normally would so they can run in parallel with our drain.
2141		 */
2142		while (numdirtybuffers > lodirtybuffers) {
2143			if (buf_do_flush(NULL) == 0)
2144				break;
2145			uio_yield();
2146		}
2147
2148		/*
2149		 * Only clear bd_request if we have reached our low water
2150		 * mark.  The buf_daemon normally waits 1 second and
2151		 * then incrementally flushes any dirty buffers that have
2152		 * built up, within reason.
2153		 *
2154		 * If we were unable to hit our low water mark and couldn't
2155		 * find any flushable buffers, we sleep half a second.
2156		 * Otherwise we loop immediately.
2157		 */
2158		mtx_lock(&bdlock);
2159		if (numdirtybuffers <= lodirtybuffers) {
2160			/*
2161			 * We reached our low water mark, reset the
2162			 * request and sleep until we are needed again.
2163			 * The sleep is just so the suspend code works.
2164			 */
2165			bd_request = 0;
2166			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2167		} else {
2168			/*
2169			 * We couldn't find any flushable dirty buffers but
2170			 * still have too many dirty buffers, we
2171			 * have to sleep and try again.  (rare)
2172			 */
2173			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2174		}
2175	}
2176}
2177
2178/*
2179 *	flushbufqueues:
2180 *
2181 *	Try to flush a buffer in the dirty queue.  We must be careful to
2182 *	free up B_INVAL buffers instead of write them, which NFS is
2183 *	particularly sensitive to.
2184 */
2185static int flushwithdeps = 0;
2186SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2187    0, "Number of buffers flushed with dependecies that require rollbacks");
2188
2189static int
2190flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2191{
2192	struct buf sentinel;
2193	struct vnode *vp;
2194	struct mount *mp;
2195	struct buf *bp;
2196	int hasdeps;
2197	int flushed;
2198	int target;
2199
2200	if (lvp == NULL) {
2201		target = numdirtybuffers - lodirtybuffers;
2202		if (flushdeps && target > 2)
2203			target /= 2;
2204	} else
2205		target = flushbufqtarget;
2206	flushed = 0;
2207	bp = NULL;
2208	sentinel.b_qindex = QUEUE_SENTINEL;
2209	mtx_lock(&bqlock);
2210	TAILQ_INSERT_HEAD(&bufqueues[queue], &sentinel, b_freelist);
2211	while (flushed != target) {
2212		bp = TAILQ_NEXT(&sentinel, b_freelist);
2213		if (bp != NULL) {
2214			TAILQ_REMOVE(&bufqueues[queue], &sentinel, b_freelist);
2215			TAILQ_INSERT_AFTER(&bufqueues[queue], bp, &sentinel,
2216			    b_freelist);
2217		} else
2218			break;
2219		/*
2220		 * Skip sentinels inserted by other invocations of the
2221		 * flushbufqueues(), taking care to not reorder them.
2222		 */
2223		if (bp->b_qindex == QUEUE_SENTINEL)
2224			continue;
2225		/*
2226		 * Only flush the buffers that belong to the
2227		 * vnode locked by the curthread.
2228		 */
2229		if (lvp != NULL && bp->b_vp != lvp)
2230			continue;
2231		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2232			continue;
2233		if (bp->b_pin_count > 0) {
2234			BUF_UNLOCK(bp);
2235			continue;
2236		}
2237		BO_LOCK(bp->b_bufobj);
2238		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2239		    (bp->b_flags & B_DELWRI) == 0) {
2240			BO_UNLOCK(bp->b_bufobj);
2241			BUF_UNLOCK(bp);
2242			continue;
2243		}
2244		BO_UNLOCK(bp->b_bufobj);
2245		if (bp->b_flags & B_INVAL) {
2246			bremfreel(bp);
2247			mtx_unlock(&bqlock);
2248			brelse(bp);
2249			flushed++;
2250			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2251			mtx_lock(&bqlock);
2252			continue;
2253		}
2254
2255		if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2256			if (flushdeps == 0) {
2257				BUF_UNLOCK(bp);
2258				continue;
2259			}
2260			hasdeps = 1;
2261		} else
2262			hasdeps = 0;
2263		/*
2264		 * We must hold the lock on a vnode before writing
2265		 * one of its buffers. Otherwise we may confuse, or
2266		 * in the case of a snapshot vnode, deadlock the
2267		 * system.
2268		 *
2269		 * The lock order here is the reverse of the normal
2270		 * of vnode followed by buf lock.  This is ok because
2271		 * the NOWAIT will prevent deadlock.
2272		 */
2273		vp = bp->b_vp;
2274		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2275			BUF_UNLOCK(bp);
2276			continue;
2277		}
2278		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2279			mtx_unlock(&bqlock);
2280			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2281			    bp, bp->b_vp, bp->b_flags);
2282			if (curproc == bufdaemonproc)
2283				vfs_bio_awrite(bp);
2284			else {
2285				bremfree(bp);
2286				bwrite(bp);
2287				notbufdflashes++;
2288			}
2289			vn_finished_write(mp);
2290			VOP_UNLOCK(vp, 0);
2291			flushwithdeps += hasdeps;
2292			flushed++;
2293
2294			/*
2295			 * Sleeping on runningbufspace while holding
2296			 * vnode lock leads to deadlock.
2297			 */
2298			if (curproc == bufdaemonproc)
2299				waitrunningbufspace();
2300			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2301			mtx_lock(&bqlock);
2302			continue;
2303		}
2304		vn_finished_write(mp);
2305		BUF_UNLOCK(bp);
2306	}
2307	TAILQ_REMOVE(&bufqueues[queue], &sentinel, b_freelist);
2308	mtx_unlock(&bqlock);
2309	return (flushed);
2310}
2311
2312/*
2313 * Check to see if a block is currently memory resident.
2314 */
2315struct buf *
2316incore(struct bufobj *bo, daddr_t blkno)
2317{
2318	struct buf *bp;
2319
2320	BO_LOCK(bo);
2321	bp = gbincore(bo, blkno);
2322	BO_UNLOCK(bo);
2323	return (bp);
2324}
2325
2326/*
2327 * Returns true if no I/O is needed to access the
2328 * associated VM object.  This is like incore except
2329 * it also hunts around in the VM system for the data.
2330 */
2331
2332static int
2333inmem(struct vnode * vp, daddr_t blkno)
2334{
2335	vm_object_t obj;
2336	vm_offset_t toff, tinc, size;
2337	vm_page_t m;
2338	vm_ooffset_t off;
2339
2340	ASSERT_VOP_LOCKED(vp, "inmem");
2341
2342	if (incore(&vp->v_bufobj, blkno))
2343		return 1;
2344	if (vp->v_mount == NULL)
2345		return 0;
2346	obj = vp->v_object;
2347	if (obj == NULL)
2348		return (0);
2349
2350	size = PAGE_SIZE;
2351	if (size > vp->v_mount->mnt_stat.f_iosize)
2352		size = vp->v_mount->mnt_stat.f_iosize;
2353	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2354
2355	VM_OBJECT_LOCK(obj);
2356	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2357		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2358		if (!m)
2359			goto notinmem;
2360		tinc = size;
2361		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2362			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2363		if (vm_page_is_valid(m,
2364		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2365			goto notinmem;
2366	}
2367	VM_OBJECT_UNLOCK(obj);
2368	return 1;
2369
2370notinmem:
2371	VM_OBJECT_UNLOCK(obj);
2372	return (0);
2373}
2374
2375/*
2376 *	vfs_setdirty:
2377 *
2378 *	Sets the dirty range for a buffer based on the status of the dirty
2379 *	bits in the pages comprising the buffer.
2380 *
2381 *	The range is limited to the size of the buffer.
2382 *
2383 *	This routine is primarily used by NFS, but is generalized for the
2384 *	B_VMIO case.
2385 */
2386static void
2387vfs_setdirty(struct buf *bp)
2388{
2389
2390	/*
2391	 * Degenerate case - empty buffer
2392	 */
2393
2394	if (bp->b_bufsize == 0)
2395		return;
2396
2397	/*
2398	 * We qualify the scan for modified pages on whether the
2399	 * object has been flushed yet.
2400	 */
2401
2402	if ((bp->b_flags & B_VMIO) == 0)
2403		return;
2404
2405	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2406	vfs_setdirty_locked_object(bp);
2407	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2408}
2409
2410static void
2411vfs_setdirty_locked_object(struct buf *bp)
2412{
2413	vm_object_t object;
2414	int i;
2415
2416	object = bp->b_bufobj->bo_object;
2417	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2418	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2419		vm_offset_t boffset;
2420		vm_offset_t eoffset;
2421
2422		vm_page_lock_queues();
2423		/*
2424		 * test the pages to see if they have been modified directly
2425		 * by users through the VM system.
2426		 */
2427		for (i = 0; i < bp->b_npages; i++)
2428			vm_page_test_dirty(bp->b_pages[i]);
2429
2430		/*
2431		 * Calculate the encompassing dirty range, boffset and eoffset,
2432		 * (eoffset - boffset) bytes.
2433		 */
2434
2435		for (i = 0; i < bp->b_npages; i++) {
2436			if (bp->b_pages[i]->dirty)
2437				break;
2438		}
2439		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2440
2441		for (i = bp->b_npages - 1; i >= 0; --i) {
2442			if (bp->b_pages[i]->dirty) {
2443				break;
2444			}
2445		}
2446		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2447
2448		vm_page_unlock_queues();
2449		/*
2450		 * Fit it to the buffer.
2451		 */
2452
2453		if (eoffset > bp->b_bcount)
2454			eoffset = bp->b_bcount;
2455
2456		/*
2457		 * If we have a good dirty range, merge with the existing
2458		 * dirty range.
2459		 */
2460
2461		if (boffset < eoffset) {
2462			if (bp->b_dirtyoff > boffset)
2463				bp->b_dirtyoff = boffset;
2464			if (bp->b_dirtyend < eoffset)
2465				bp->b_dirtyend = eoffset;
2466		}
2467	}
2468}
2469
2470/*
2471 *	getblk:
2472 *
2473 *	Get a block given a specified block and offset into a file/device.
2474 *	The buffers B_DONE bit will be cleared on return, making it almost
2475 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2476 *	return.  The caller should clear B_INVAL prior to initiating a
2477 *	READ.
2478 *
2479 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2480 *	an existing buffer.
2481 *
2482 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2483 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2484 *	and then cleared based on the backing VM.  If the previous buffer is
2485 *	non-0-sized but invalid, B_CACHE will be cleared.
2486 *
2487 *	If getblk() must create a new buffer, the new buffer is returned with
2488 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2489 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2490 *	backing VM.
2491 *
2492 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2493 *	B_CACHE bit is clear.
2494 *
2495 *	What this means, basically, is that the caller should use B_CACHE to
2496 *	determine whether the buffer is fully valid or not and should clear
2497 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2498 *	the buffer by loading its data area with something, the caller needs
2499 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2500 *	the caller should set B_CACHE ( as an optimization ), else the caller
2501 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2502 *	a write attempt or if it was a successfull read.  If the caller
2503 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2504 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2505 */
2506struct buf *
2507getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2508    int flags)
2509{
2510	struct buf *bp;
2511	struct bufobj *bo;
2512	int error;
2513
2514	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2515	ASSERT_VOP_LOCKED(vp, "getblk");
2516	if (size > MAXBSIZE)
2517		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2518
2519	bo = &vp->v_bufobj;
2520loop:
2521	/*
2522	 * Block if we are low on buffers.   Certain processes are allowed
2523	 * to completely exhaust the buffer cache.
2524         *
2525         * If this check ever becomes a bottleneck it may be better to
2526         * move it into the else, when gbincore() fails.  At the moment
2527         * it isn't a problem.
2528	 *
2529	 * XXX remove if 0 sections (clean this up after its proven)
2530         */
2531	if (numfreebuffers == 0) {
2532		if (TD_IS_IDLETHREAD(curthread))
2533			return NULL;
2534		mtx_lock(&nblock);
2535		needsbuffer |= VFS_BIO_NEED_ANY;
2536		mtx_unlock(&nblock);
2537	}
2538
2539	BO_LOCK(bo);
2540	bp = gbincore(bo, blkno);
2541	if (bp != NULL) {
2542		int lockflags;
2543		/*
2544		 * Buffer is in-core.  If the buffer is not busy, it must
2545		 * be on a queue.
2546		 */
2547		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2548
2549		if (flags & GB_LOCK_NOWAIT)
2550			lockflags |= LK_NOWAIT;
2551
2552		error = BUF_TIMELOCK(bp, lockflags,
2553		    BO_MTX(bo), "getblk", slpflag, slptimeo);
2554
2555		/*
2556		 * If we slept and got the lock we have to restart in case
2557		 * the buffer changed identities.
2558		 */
2559		if (error == ENOLCK)
2560			goto loop;
2561		/* We timed out or were interrupted. */
2562		else if (error)
2563			return (NULL);
2564
2565		/*
2566		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2567		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2568		 * and for a VMIO buffer B_CACHE is adjusted according to the
2569		 * backing VM cache.
2570		 */
2571		if (bp->b_flags & B_INVAL)
2572			bp->b_flags &= ~B_CACHE;
2573		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2574			bp->b_flags |= B_CACHE;
2575		bremfree(bp);
2576
2577		/*
2578		 * check for size inconsistancies for non-VMIO case.
2579		 */
2580
2581		if (bp->b_bcount != size) {
2582			if ((bp->b_flags & B_VMIO) == 0 ||
2583			    (size > bp->b_kvasize)) {
2584				if (bp->b_flags & B_DELWRI) {
2585					/*
2586					 * If buffer is pinned and caller does
2587					 * not want sleep  waiting for it to be
2588					 * unpinned, bail out
2589					 * */
2590					if (bp->b_pin_count > 0) {
2591						if (flags & GB_LOCK_NOWAIT) {
2592							bqrelse(bp);
2593							return (NULL);
2594						} else {
2595							bunpin_wait(bp);
2596						}
2597					}
2598					bp->b_flags |= B_NOCACHE;
2599					bwrite(bp);
2600				} else {
2601					if (LIST_EMPTY(&bp->b_dep)) {
2602						bp->b_flags |= B_RELBUF;
2603						brelse(bp);
2604					} else {
2605						bp->b_flags |= B_NOCACHE;
2606						bwrite(bp);
2607					}
2608				}
2609				goto loop;
2610			}
2611		}
2612
2613		/*
2614		 * If the size is inconsistant in the VMIO case, we can resize
2615		 * the buffer.  This might lead to B_CACHE getting set or
2616		 * cleared.  If the size has not changed, B_CACHE remains
2617		 * unchanged from its previous state.
2618		 */
2619
2620		if (bp->b_bcount != size)
2621			allocbuf(bp, size);
2622
2623		KASSERT(bp->b_offset != NOOFFSET,
2624		    ("getblk: no buffer offset"));
2625
2626		/*
2627		 * A buffer with B_DELWRI set and B_CACHE clear must
2628		 * be committed before we can return the buffer in
2629		 * order to prevent the caller from issuing a read
2630		 * ( due to B_CACHE not being set ) and overwriting
2631		 * it.
2632		 *
2633		 * Most callers, including NFS and FFS, need this to
2634		 * operate properly either because they assume they
2635		 * can issue a read if B_CACHE is not set, or because
2636		 * ( for example ) an uncached B_DELWRI might loop due
2637		 * to softupdates re-dirtying the buffer.  In the latter
2638		 * case, B_CACHE is set after the first write completes,
2639		 * preventing further loops.
2640		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2641		 * above while extending the buffer, we cannot allow the
2642		 * buffer to remain with B_CACHE set after the write
2643		 * completes or it will represent a corrupt state.  To
2644		 * deal with this we set B_NOCACHE to scrap the buffer
2645		 * after the write.
2646		 *
2647		 * We might be able to do something fancy, like setting
2648		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2649		 * so the below call doesn't set B_CACHE, but that gets real
2650		 * confusing.  This is much easier.
2651		 */
2652
2653		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2654			bp->b_flags |= B_NOCACHE;
2655			bwrite(bp);
2656			goto loop;
2657		}
2658		bp->b_flags &= ~B_DONE;
2659	} else {
2660		int bsize, maxsize, vmio;
2661		off_t offset;
2662
2663		/*
2664		 * Buffer is not in-core, create new buffer.  The buffer
2665		 * returned by getnewbuf() is locked.  Note that the returned
2666		 * buffer is also considered valid (not marked B_INVAL).
2667		 */
2668		BO_UNLOCK(bo);
2669		/*
2670		 * If the user does not want us to create the buffer, bail out
2671		 * here.
2672		 */
2673		if (flags & GB_NOCREAT)
2674			return NULL;
2675		bsize = bo->bo_bsize;
2676		offset = blkno * bsize;
2677		vmio = vp->v_object != NULL;
2678		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2679		maxsize = imax(maxsize, bsize);
2680
2681		bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
2682		if (bp == NULL) {
2683			if (slpflag || slptimeo)
2684				return NULL;
2685			goto loop;
2686		}
2687
2688		/*
2689		 * This code is used to make sure that a buffer is not
2690		 * created while the getnewbuf routine is blocked.
2691		 * This can be a problem whether the vnode is locked or not.
2692		 * If the buffer is created out from under us, we have to
2693		 * throw away the one we just created.
2694		 *
2695		 * Note: this must occur before we associate the buffer
2696		 * with the vp especially considering limitations in
2697		 * the splay tree implementation when dealing with duplicate
2698		 * lblkno's.
2699		 */
2700		BO_LOCK(bo);
2701		if (gbincore(bo, blkno)) {
2702			BO_UNLOCK(bo);
2703			bp->b_flags |= B_INVAL;
2704			brelse(bp);
2705			goto loop;
2706		}
2707
2708		/*
2709		 * Insert the buffer into the hash, so that it can
2710		 * be found by incore.
2711		 */
2712		bp->b_blkno = bp->b_lblkno = blkno;
2713		bp->b_offset = offset;
2714		bgetvp(vp, bp);
2715		BO_UNLOCK(bo);
2716
2717		/*
2718		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2719		 * buffer size starts out as 0, B_CACHE will be set by
2720		 * allocbuf() for the VMIO case prior to it testing the
2721		 * backing store for validity.
2722		 */
2723
2724		if (vmio) {
2725			bp->b_flags |= B_VMIO;
2726#if defined(VFS_BIO_DEBUG)
2727			if (vn_canvmio(vp) != TRUE)
2728				printf("getblk: VMIO on vnode type %d\n",
2729					vp->v_type);
2730#endif
2731			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2732			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2733			    bp, vp->v_object, bp->b_bufobj->bo_object));
2734		} else {
2735			bp->b_flags &= ~B_VMIO;
2736			KASSERT(bp->b_bufobj->bo_object == NULL,
2737			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2738			    bp, bp->b_bufobj->bo_object));
2739		}
2740
2741		allocbuf(bp, size);
2742		bp->b_flags &= ~B_DONE;
2743	}
2744	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2745	BUF_ASSERT_HELD(bp);
2746	KASSERT(bp->b_bufobj == bo,
2747	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2748	return (bp);
2749}
2750
2751/*
2752 * Get an empty, disassociated buffer of given size.  The buffer is initially
2753 * set to B_INVAL.
2754 */
2755struct buf *
2756geteblk(int size, int flags)
2757{
2758	struct buf *bp;
2759	int maxsize;
2760
2761	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2762	while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
2763		if ((flags & GB_NOWAIT_BD) &&
2764		    (curthread->td_pflags & TDP_BUFNEED) != 0)
2765			return (NULL);
2766	}
2767	allocbuf(bp, size);
2768	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2769	BUF_ASSERT_HELD(bp);
2770	return (bp);
2771}
2772
2773
2774/*
2775 * This code constitutes the buffer memory from either anonymous system
2776 * memory (in the case of non-VMIO operations) or from an associated
2777 * VM object (in the case of VMIO operations).  This code is able to
2778 * resize a buffer up or down.
2779 *
2780 * Note that this code is tricky, and has many complications to resolve
2781 * deadlock or inconsistant data situations.  Tread lightly!!!
2782 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2783 * the caller.  Calling this code willy nilly can result in the loss of data.
2784 *
2785 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2786 * B_CACHE for the non-VMIO case.
2787 */
2788
2789int
2790allocbuf(struct buf *bp, int size)
2791{
2792	int newbsize, mbsize;
2793	int i;
2794
2795	BUF_ASSERT_HELD(bp);
2796
2797	if (bp->b_kvasize < size)
2798		panic("allocbuf: buffer too small");
2799
2800	if ((bp->b_flags & B_VMIO) == 0) {
2801		caddr_t origbuf;
2802		int origbufsize;
2803		/*
2804		 * Just get anonymous memory from the kernel.  Don't
2805		 * mess with B_CACHE.
2806		 */
2807		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2808		if (bp->b_flags & B_MALLOC)
2809			newbsize = mbsize;
2810		else
2811			newbsize = round_page(size);
2812
2813		if (newbsize < bp->b_bufsize) {
2814			/*
2815			 * malloced buffers are not shrunk
2816			 */
2817			if (bp->b_flags & B_MALLOC) {
2818				if (newbsize) {
2819					bp->b_bcount = size;
2820				} else {
2821					free(bp->b_data, M_BIOBUF);
2822					if (bp->b_bufsize) {
2823						atomic_subtract_long(
2824						    &bufmallocspace,
2825						    bp->b_bufsize);
2826						bufspacewakeup();
2827						bp->b_bufsize = 0;
2828					}
2829					bp->b_saveaddr = bp->b_kvabase;
2830					bp->b_data = bp->b_saveaddr;
2831					bp->b_bcount = 0;
2832					bp->b_flags &= ~B_MALLOC;
2833				}
2834				return 1;
2835			}
2836			vm_hold_free_pages(
2837			    bp,
2838			    (vm_offset_t) bp->b_data + newbsize,
2839			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2840		} else if (newbsize > bp->b_bufsize) {
2841			/*
2842			 * We only use malloced memory on the first allocation.
2843			 * and revert to page-allocated memory when the buffer
2844			 * grows.
2845			 */
2846			/*
2847			 * There is a potential smp race here that could lead
2848			 * to bufmallocspace slightly passing the max.  It
2849			 * is probably extremely rare and not worth worrying
2850			 * over.
2851			 */
2852			if ( (bufmallocspace < maxbufmallocspace) &&
2853				(bp->b_bufsize == 0) &&
2854				(mbsize <= PAGE_SIZE/2)) {
2855
2856				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2857				bp->b_bufsize = mbsize;
2858				bp->b_bcount = size;
2859				bp->b_flags |= B_MALLOC;
2860				atomic_add_long(&bufmallocspace, mbsize);
2861				return 1;
2862			}
2863			origbuf = NULL;
2864			origbufsize = 0;
2865			/*
2866			 * If the buffer is growing on its other-than-first allocation,
2867			 * then we revert to the page-allocation scheme.
2868			 */
2869			if (bp->b_flags & B_MALLOC) {
2870				origbuf = bp->b_data;
2871				origbufsize = bp->b_bufsize;
2872				bp->b_data = bp->b_kvabase;
2873				if (bp->b_bufsize) {
2874					atomic_subtract_long(&bufmallocspace,
2875					    bp->b_bufsize);
2876					bufspacewakeup();
2877					bp->b_bufsize = 0;
2878				}
2879				bp->b_flags &= ~B_MALLOC;
2880				newbsize = round_page(newbsize);
2881			}
2882			vm_hold_load_pages(
2883			    bp,
2884			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2885			    (vm_offset_t) bp->b_data + newbsize);
2886			if (origbuf) {
2887				bcopy(origbuf, bp->b_data, origbufsize);
2888				free(origbuf, M_BIOBUF);
2889			}
2890		}
2891	} else {
2892		int desiredpages;
2893
2894		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2895		desiredpages = (size == 0) ? 0 :
2896			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2897
2898		if (bp->b_flags & B_MALLOC)
2899			panic("allocbuf: VMIO buffer can't be malloced");
2900		/*
2901		 * Set B_CACHE initially if buffer is 0 length or will become
2902		 * 0-length.
2903		 */
2904		if (size == 0 || bp->b_bufsize == 0)
2905			bp->b_flags |= B_CACHE;
2906
2907		if (newbsize < bp->b_bufsize) {
2908			/*
2909			 * DEV_BSIZE aligned new buffer size is less then the
2910			 * DEV_BSIZE aligned existing buffer size.  Figure out
2911			 * if we have to remove any pages.
2912			 */
2913			if (desiredpages < bp->b_npages) {
2914				vm_page_t m;
2915
2916				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2917				vm_page_lock_queues();
2918				for (i = desiredpages; i < bp->b_npages; i++) {
2919					/*
2920					 * the page is not freed here -- it
2921					 * is the responsibility of
2922					 * vnode_pager_setsize
2923					 */
2924					m = bp->b_pages[i];
2925					KASSERT(m != bogus_page,
2926					    ("allocbuf: bogus page found"));
2927					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2928						vm_page_lock_queues();
2929
2930					bp->b_pages[i] = NULL;
2931					vm_page_unwire(m, 0);
2932				}
2933				vm_page_unlock_queues();
2934				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2935				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2936				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2937				bp->b_npages = desiredpages;
2938			}
2939		} else if (size > bp->b_bcount) {
2940			/*
2941			 * We are growing the buffer, possibly in a
2942			 * byte-granular fashion.
2943			 */
2944			struct vnode *vp;
2945			vm_object_t obj;
2946			vm_offset_t toff;
2947			vm_offset_t tinc;
2948
2949			/*
2950			 * Step 1, bring in the VM pages from the object,
2951			 * allocating them if necessary.  We must clear
2952			 * B_CACHE if these pages are not valid for the
2953			 * range covered by the buffer.
2954			 */
2955
2956			vp = bp->b_vp;
2957			obj = bp->b_bufobj->bo_object;
2958
2959			VM_OBJECT_LOCK(obj);
2960			while (bp->b_npages < desiredpages) {
2961				vm_page_t m;
2962				vm_pindex_t pi;
2963
2964				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2965				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2966					/*
2967					 * note: must allocate system pages
2968					 * since blocking here could intefere
2969					 * with paging I/O, no matter which
2970					 * process we are.
2971					 */
2972					m = vm_page_alloc(obj, pi,
2973					    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2974					    VM_ALLOC_WIRED);
2975					if (m == NULL) {
2976						atomic_add_int(&vm_pageout_deficit,
2977						    desiredpages - bp->b_npages);
2978						VM_OBJECT_UNLOCK(obj);
2979						VM_WAIT;
2980						VM_OBJECT_LOCK(obj);
2981					} else {
2982						if (m->valid == 0)
2983							bp->b_flags &= ~B_CACHE;
2984						bp->b_pages[bp->b_npages] = m;
2985						++bp->b_npages;
2986					}
2987					continue;
2988				}
2989
2990				/*
2991				 * We found a page.  If we have to sleep on it,
2992				 * retry because it might have gotten freed out
2993				 * from under us.
2994				 *
2995				 * We can only test VPO_BUSY here.  Blocking on
2996				 * m->busy might lead to a deadlock:
2997				 *
2998				 *  vm_fault->getpages->cluster_read->allocbuf
2999				 *
3000				 */
3001				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
3002					continue;
3003
3004				/*
3005				 * We have a good page.
3006				 */
3007				vm_page_lock_queues();
3008				vm_page_wire(m);
3009				vm_page_unlock_queues();
3010				bp->b_pages[bp->b_npages] = m;
3011				++bp->b_npages;
3012			}
3013
3014			/*
3015			 * Step 2.  We've loaded the pages into the buffer,
3016			 * we have to figure out if we can still have B_CACHE
3017			 * set.  Note that B_CACHE is set according to the
3018			 * byte-granular range ( bcount and size ), new the
3019			 * aligned range ( newbsize ).
3020			 *
3021			 * The VM test is against m->valid, which is DEV_BSIZE
3022			 * aligned.  Needless to say, the validity of the data
3023			 * needs to also be DEV_BSIZE aligned.  Note that this
3024			 * fails with NFS if the server or some other client
3025			 * extends the file's EOF.  If our buffer is resized,
3026			 * B_CACHE may remain set! XXX
3027			 */
3028
3029			toff = bp->b_bcount;
3030			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3031
3032			while ((bp->b_flags & B_CACHE) && toff < size) {
3033				vm_pindex_t pi;
3034
3035				if (tinc > (size - toff))
3036					tinc = size - toff;
3037
3038				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3039				    PAGE_SHIFT;
3040
3041				vfs_buf_test_cache(
3042				    bp,
3043				    bp->b_offset,
3044				    toff,
3045				    tinc,
3046				    bp->b_pages[pi]
3047				);
3048				toff += tinc;
3049				tinc = PAGE_SIZE;
3050			}
3051			VM_OBJECT_UNLOCK(obj);
3052
3053			/*
3054			 * Step 3, fixup the KVM pmap.  Remember that
3055			 * bp->b_data is relative to bp->b_offset, but
3056			 * bp->b_offset may be offset into the first page.
3057			 */
3058
3059			bp->b_data = (caddr_t)
3060			    trunc_page((vm_offset_t)bp->b_data);
3061			pmap_qenter(
3062			    (vm_offset_t)bp->b_data,
3063			    bp->b_pages,
3064			    bp->b_npages
3065			);
3066
3067			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3068			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
3069		}
3070	}
3071	if (newbsize < bp->b_bufsize)
3072		bufspacewakeup();
3073	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3074	bp->b_bcount = size;		/* requested buffer size	*/
3075	return 1;
3076}
3077
3078void
3079biodone(struct bio *bp)
3080{
3081	struct mtx *mtxp;
3082	void (*done)(struct bio *);
3083
3084	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3085	mtx_lock(mtxp);
3086	bp->bio_flags |= BIO_DONE;
3087	done = bp->bio_done;
3088	if (done == NULL)
3089		wakeup(bp);
3090	mtx_unlock(mtxp);
3091	if (done != NULL)
3092		done(bp);
3093}
3094
3095/*
3096 * Wait for a BIO to finish.
3097 *
3098 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3099 * case is not yet clear.
3100 */
3101int
3102biowait(struct bio *bp, const char *wchan)
3103{
3104	struct mtx *mtxp;
3105
3106	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3107	mtx_lock(mtxp);
3108	while ((bp->bio_flags & BIO_DONE) == 0)
3109		msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3110	mtx_unlock(mtxp);
3111	if (bp->bio_error != 0)
3112		return (bp->bio_error);
3113	if (!(bp->bio_flags & BIO_ERROR))
3114		return (0);
3115	return (EIO);
3116}
3117
3118void
3119biofinish(struct bio *bp, struct devstat *stat, int error)
3120{
3121
3122	if (error) {
3123		bp->bio_error = error;
3124		bp->bio_flags |= BIO_ERROR;
3125	}
3126	if (stat != NULL)
3127		devstat_end_transaction_bio(stat, bp);
3128	biodone(bp);
3129}
3130
3131/*
3132 *	bufwait:
3133 *
3134 *	Wait for buffer I/O completion, returning error status.  The buffer
3135 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3136 *	error and cleared.
3137 */
3138int
3139bufwait(struct buf *bp)
3140{
3141	if (bp->b_iocmd == BIO_READ)
3142		bwait(bp, PRIBIO, "biord");
3143	else
3144		bwait(bp, PRIBIO, "biowr");
3145	if (bp->b_flags & B_EINTR) {
3146		bp->b_flags &= ~B_EINTR;
3147		return (EINTR);
3148	}
3149	if (bp->b_ioflags & BIO_ERROR) {
3150		return (bp->b_error ? bp->b_error : EIO);
3151	} else {
3152		return (0);
3153	}
3154}
3155
3156 /*
3157  * Call back function from struct bio back up to struct buf.
3158  */
3159static void
3160bufdonebio(struct bio *bip)
3161{
3162	struct buf *bp;
3163
3164	bp = bip->bio_caller2;
3165	bp->b_resid = bp->b_bcount - bip->bio_completed;
3166	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3167	bp->b_ioflags = bip->bio_flags;
3168	bp->b_error = bip->bio_error;
3169	if (bp->b_error)
3170		bp->b_ioflags |= BIO_ERROR;
3171	bufdone(bp);
3172	g_destroy_bio(bip);
3173}
3174
3175void
3176dev_strategy(struct cdev *dev, struct buf *bp)
3177{
3178	struct cdevsw *csw;
3179	struct bio *bip;
3180
3181	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3182		panic("b_iocmd botch");
3183	for (;;) {
3184		bip = g_new_bio();
3185		if (bip != NULL)
3186			break;
3187		/* Try again later */
3188		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3189	}
3190	bip->bio_cmd = bp->b_iocmd;
3191	bip->bio_offset = bp->b_iooffset;
3192	bip->bio_length = bp->b_bcount;
3193	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3194	bip->bio_data = bp->b_data;
3195	bip->bio_done = bufdonebio;
3196	bip->bio_caller2 = bp;
3197	bip->bio_dev = dev;
3198	KASSERT(dev->si_refcount > 0,
3199	    ("dev_strategy on un-referenced struct cdev *(%s)",
3200	    devtoname(dev)));
3201	csw = dev_refthread(dev);
3202	if (csw == NULL) {
3203		g_destroy_bio(bip);
3204		bp->b_error = ENXIO;
3205		bp->b_ioflags = BIO_ERROR;
3206		bufdone(bp);
3207		return;
3208	}
3209	(*csw->d_strategy)(bip);
3210	dev_relthread(dev);
3211}
3212
3213/*
3214 *	bufdone:
3215 *
3216 *	Finish I/O on a buffer, optionally calling a completion function.
3217 *	This is usually called from an interrupt so process blocking is
3218 *	not allowed.
3219 *
3220 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3221 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3222 *	assuming B_INVAL is clear.
3223 *
3224 *	For the VMIO case, we set B_CACHE if the op was a read and no
3225 *	read error occured, or if the op was a write.  B_CACHE is never
3226 *	set if the buffer is invalid or otherwise uncacheable.
3227 *
3228 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3229 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3230 *	in the biodone routine.
3231 */
3232void
3233bufdone(struct buf *bp)
3234{
3235	struct bufobj *dropobj;
3236	void    (*biodone)(struct buf *);
3237
3238	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3239	dropobj = NULL;
3240
3241	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3242	BUF_ASSERT_HELD(bp);
3243
3244	runningbufwakeup(bp);
3245	if (bp->b_iocmd == BIO_WRITE)
3246		dropobj = bp->b_bufobj;
3247	/* call optional completion function if requested */
3248	if (bp->b_iodone != NULL) {
3249		biodone = bp->b_iodone;
3250		bp->b_iodone = NULL;
3251		(*biodone) (bp);
3252		if (dropobj)
3253			bufobj_wdrop(dropobj);
3254		return;
3255	}
3256
3257	bufdone_finish(bp);
3258
3259	if (dropobj)
3260		bufobj_wdrop(dropobj);
3261}
3262
3263void
3264bufdone_finish(struct buf *bp)
3265{
3266	BUF_ASSERT_HELD(bp);
3267
3268	if (!LIST_EMPTY(&bp->b_dep))
3269		buf_complete(bp);
3270
3271	if (bp->b_flags & B_VMIO) {
3272		int i;
3273		vm_ooffset_t foff;
3274		vm_page_t m;
3275		vm_object_t obj;
3276		int iosize;
3277		struct vnode *vp = bp->b_vp;
3278		boolean_t are_queues_locked;
3279
3280		obj = bp->b_bufobj->bo_object;
3281
3282#if defined(VFS_BIO_DEBUG)
3283		mp_fixme("usecount and vflag accessed without locks.");
3284		if (vp->v_usecount == 0) {
3285			panic("biodone: zero vnode ref count");
3286		}
3287
3288		KASSERT(vp->v_object != NULL,
3289			("biodone: vnode %p has no vm_object", vp));
3290#endif
3291
3292		foff = bp->b_offset;
3293		KASSERT(bp->b_offset != NOOFFSET,
3294		    ("biodone: no buffer offset"));
3295
3296		VM_OBJECT_LOCK(obj);
3297#if defined(VFS_BIO_DEBUG)
3298		if (obj->paging_in_progress < bp->b_npages) {
3299			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3300			    obj->paging_in_progress, bp->b_npages);
3301		}
3302#endif
3303
3304		/*
3305		 * Set B_CACHE if the op was a normal read and no error
3306		 * occured.  B_CACHE is set for writes in the b*write()
3307		 * routines.
3308		 */
3309		iosize = bp->b_bcount - bp->b_resid;
3310		if (bp->b_iocmd == BIO_READ &&
3311		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3312		    !(bp->b_ioflags & BIO_ERROR)) {
3313			bp->b_flags |= B_CACHE;
3314		}
3315		if (bp->b_iocmd == BIO_READ) {
3316			vm_page_lock_queues();
3317			are_queues_locked = TRUE;
3318		} else
3319			are_queues_locked = FALSE;
3320		for (i = 0; i < bp->b_npages; i++) {
3321			int bogusflag = 0;
3322			int resid;
3323
3324			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3325			if (resid > iosize)
3326				resid = iosize;
3327
3328			/*
3329			 * cleanup bogus pages, restoring the originals
3330			 */
3331			m = bp->b_pages[i];
3332			if (m == bogus_page) {
3333				bogusflag = 1;
3334				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3335				if (m == NULL)
3336					panic("biodone: page disappeared!");
3337				bp->b_pages[i] = m;
3338				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3339				    bp->b_pages, bp->b_npages);
3340			}
3341#if defined(VFS_BIO_DEBUG)
3342			if (OFF_TO_IDX(foff) != m->pindex) {
3343				printf(
3344"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3345				    (intmax_t)foff, (uintmax_t)m->pindex);
3346			}
3347#endif
3348
3349			/*
3350			 * In the write case, the valid and clean bits are
3351			 * already changed correctly ( see bdwrite() ), so we
3352			 * only need to do this here in the read case.
3353			 */
3354			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3355				vfs_page_set_valid(bp, foff, m);
3356			}
3357
3358			/*
3359			 * when debugging new filesystems or buffer I/O methods, this
3360			 * is the most common error that pops up.  if you see this, you
3361			 * have not set the page busy flag correctly!!!
3362			 */
3363			if (m->busy == 0) {
3364				printf("biodone: page busy < 0, "
3365				    "pindex: %d, foff: 0x(%x,%x), "
3366				    "resid: %d, index: %d\n",
3367				    (int) m->pindex, (int)(foff >> 32),
3368						(int) foff & 0xffffffff, resid, i);
3369				if (!vn_isdisk(vp, NULL))
3370					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3371					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3372					    (intmax_t) bp->b_lblkno,
3373					    bp->b_flags, bp->b_npages);
3374				else
3375					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3376					    (intmax_t) bp->b_lblkno,
3377					    bp->b_flags, bp->b_npages);
3378				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3379				    (u_long)m->valid, (u_long)m->dirty,
3380				    m->wire_count);
3381				panic("biodone: page busy < 0\n");
3382			}
3383			vm_page_io_finish(m);
3384			vm_object_pip_subtract(obj, 1);
3385			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3386			iosize -= resid;
3387		}
3388		if (are_queues_locked)
3389			vm_page_unlock_queues();
3390		vm_object_pip_wakeupn(obj, 0);
3391		VM_OBJECT_UNLOCK(obj);
3392	}
3393
3394	/*
3395	 * For asynchronous completions, release the buffer now. The brelse
3396	 * will do a wakeup there if necessary - so no need to do a wakeup
3397	 * here in the async case. The sync case always needs to do a wakeup.
3398	 */
3399
3400	if (bp->b_flags & B_ASYNC) {
3401		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3402			brelse(bp);
3403		else
3404			bqrelse(bp);
3405	} else
3406		bdone(bp);
3407}
3408
3409/*
3410 * This routine is called in lieu of iodone in the case of
3411 * incomplete I/O.  This keeps the busy status for pages
3412 * consistant.
3413 */
3414void
3415vfs_unbusy_pages(struct buf *bp)
3416{
3417	int i;
3418	vm_object_t obj;
3419	vm_page_t m;
3420
3421	runningbufwakeup(bp);
3422	if (!(bp->b_flags & B_VMIO))
3423		return;
3424
3425	obj = bp->b_bufobj->bo_object;
3426	VM_OBJECT_LOCK(obj);
3427	for (i = 0; i < bp->b_npages; i++) {
3428		m = bp->b_pages[i];
3429		if (m == bogus_page) {
3430			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3431			if (!m)
3432				panic("vfs_unbusy_pages: page missing\n");
3433			bp->b_pages[i] = m;
3434			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3435			    bp->b_pages, bp->b_npages);
3436		}
3437		vm_object_pip_subtract(obj, 1);
3438		vm_page_io_finish(m);
3439	}
3440	vm_object_pip_wakeupn(obj, 0);
3441	VM_OBJECT_UNLOCK(obj);
3442}
3443
3444/*
3445 * vfs_page_set_valid:
3446 *
3447 *	Set the valid bits in a page based on the supplied offset.   The
3448 *	range is restricted to the buffer's size.
3449 *
3450 *	This routine is typically called after a read completes.
3451 */
3452static void
3453vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3454{
3455	vm_ooffset_t soff, eoff;
3456
3457	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3458	/*
3459	 * Start and end offsets in buffer.  eoff - soff may not cross a
3460	 * page boundry or cross the end of the buffer.  The end of the
3461	 * buffer, in this case, is our file EOF, not the allocation size
3462	 * of the buffer.
3463	 */
3464	soff = off;
3465	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3466	if (eoff > bp->b_offset + bp->b_bcount)
3467		eoff = bp->b_offset + bp->b_bcount;
3468
3469	/*
3470	 * Set valid range.  This is typically the entire buffer and thus the
3471	 * entire page.
3472	 */
3473	if (eoff > soff) {
3474		vm_page_set_validclean(
3475		    m,
3476		   (vm_offset_t) (soff & PAGE_MASK),
3477		   (vm_offset_t) (eoff - soff)
3478		);
3479	}
3480}
3481
3482/*
3483 * This routine is called before a device strategy routine.
3484 * It is used to tell the VM system that paging I/O is in
3485 * progress, and treat the pages associated with the buffer
3486 * almost as being VPO_BUSY.  Also the object paging_in_progress
3487 * flag is handled to make sure that the object doesn't become
3488 * inconsistant.
3489 *
3490 * Since I/O has not been initiated yet, certain buffer flags
3491 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3492 * and should be ignored.
3493 */
3494void
3495vfs_busy_pages(struct buf *bp, int clear_modify)
3496{
3497	int i, bogus;
3498	vm_object_t obj;
3499	vm_ooffset_t foff;
3500	vm_page_t m;
3501
3502	if (!(bp->b_flags & B_VMIO))
3503		return;
3504
3505	obj = bp->b_bufobj->bo_object;
3506	foff = bp->b_offset;
3507	KASSERT(bp->b_offset != NOOFFSET,
3508	    ("vfs_busy_pages: no buffer offset"));
3509	VM_OBJECT_LOCK(obj);
3510	if (bp->b_bufsize != 0)
3511		vfs_setdirty_locked_object(bp);
3512retry:
3513	for (i = 0; i < bp->b_npages; i++) {
3514		m = bp->b_pages[i];
3515
3516		if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3517			goto retry;
3518	}
3519	bogus = 0;
3520	vm_page_lock_queues();
3521	for (i = 0; i < bp->b_npages; i++) {
3522		m = bp->b_pages[i];
3523
3524		if ((bp->b_flags & B_CLUSTER) == 0) {
3525			vm_object_pip_add(obj, 1);
3526			vm_page_io_start(m);
3527		}
3528		/*
3529		 * When readying a buffer for a read ( i.e
3530		 * clear_modify == 0 ), it is important to do
3531		 * bogus_page replacement for valid pages in
3532		 * partially instantiated buffers.  Partially
3533		 * instantiated buffers can, in turn, occur when
3534		 * reconstituting a buffer from its VM backing store
3535		 * base.  We only have to do this if B_CACHE is
3536		 * clear ( which causes the I/O to occur in the
3537		 * first place ).  The replacement prevents the read
3538		 * I/O from overwriting potentially dirty VM-backed
3539		 * pages.  XXX bogus page replacement is, uh, bogus.
3540		 * It may not work properly with small-block devices.
3541		 * We need to find a better way.
3542		 */
3543		pmap_remove_all(m);
3544		if (clear_modify)
3545			vfs_page_set_valid(bp, foff, m);
3546		else if (m->valid == VM_PAGE_BITS_ALL &&
3547		    (bp->b_flags & B_CACHE) == 0) {
3548			bp->b_pages[i] = bogus_page;
3549			bogus++;
3550		}
3551		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3552	}
3553	vm_page_unlock_queues();
3554	VM_OBJECT_UNLOCK(obj);
3555	if (bogus)
3556		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3557		    bp->b_pages, bp->b_npages);
3558}
3559
3560/*
3561 * Tell the VM system that the pages associated with this buffer
3562 * are clean.  This is used for delayed writes where the data is
3563 * going to go to disk eventually without additional VM intevention.
3564 *
3565 * Note that while we only really need to clean through to b_bcount, we
3566 * just go ahead and clean through to b_bufsize.
3567 */
3568static void
3569vfs_clean_pages(struct buf *bp)
3570{
3571	int i;
3572	vm_ooffset_t foff, noff, eoff;
3573	vm_page_t m;
3574
3575	if (!(bp->b_flags & B_VMIO))
3576		return;
3577
3578	foff = bp->b_offset;
3579	KASSERT(bp->b_offset != NOOFFSET,
3580	    ("vfs_clean_pages: no buffer offset"));
3581	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3582	vm_page_lock_queues();
3583	for (i = 0; i < bp->b_npages; i++) {
3584		m = bp->b_pages[i];
3585		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3586		eoff = noff;
3587
3588		if (eoff > bp->b_offset + bp->b_bufsize)
3589			eoff = bp->b_offset + bp->b_bufsize;
3590		vfs_page_set_valid(bp, foff, m);
3591		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3592		foff = noff;
3593	}
3594	vm_page_unlock_queues();
3595	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3596}
3597
3598/*
3599 *	vfs_bio_set_validclean:
3600 *
3601 *	Set the range within the buffer to valid and clean.  The range is
3602 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3603 *	itself may be offset from the beginning of the first page.
3604 *
3605 */
3606
3607void
3608vfs_bio_set_validclean(struct buf *bp, int base, int size)
3609{
3610	int i, n;
3611	vm_page_t m;
3612
3613	if (!(bp->b_flags & B_VMIO))
3614		return;
3615	/*
3616	 * Fixup base to be relative to beginning of first page.
3617	 * Set initial n to be the maximum number of bytes in the
3618	 * first page that can be validated.
3619	 */
3620
3621	base += (bp->b_offset & PAGE_MASK);
3622	n = PAGE_SIZE - (base & PAGE_MASK);
3623
3624	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3625	vm_page_lock_queues();
3626	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3627		m = bp->b_pages[i];
3628		if (n > size)
3629			n = size;
3630		vm_page_set_validclean(m, base & PAGE_MASK, n);
3631		base += n;
3632		size -= n;
3633		n = PAGE_SIZE;
3634	}
3635	vm_page_unlock_queues();
3636	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3637}
3638
3639/*
3640 *	vfs_bio_clrbuf:
3641 *
3642 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3643 *	to clear BIO_ERROR and B_INVAL.
3644 *
3645 *	Note that while we only theoretically need to clear through b_bcount,
3646 *	we go ahead and clear through b_bufsize.
3647 */
3648
3649void
3650vfs_bio_clrbuf(struct buf *bp)
3651{
3652	int i, j, mask = 0;
3653	caddr_t sa, ea;
3654
3655	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3656		clrbuf(bp);
3657		return;
3658	}
3659
3660	bp->b_flags &= ~B_INVAL;
3661	bp->b_ioflags &= ~BIO_ERROR;
3662	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3663	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3664	    (bp->b_offset & PAGE_MASK) == 0) {
3665		if (bp->b_pages[0] == bogus_page)
3666			goto unlock;
3667		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3668		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3669		if ((bp->b_pages[0]->valid & mask) == mask)
3670			goto unlock;
3671		if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3672		    ((bp->b_pages[0]->valid & mask) == 0)) {
3673			bzero(bp->b_data, bp->b_bufsize);
3674			bp->b_pages[0]->valid |= mask;
3675			goto unlock;
3676		}
3677	}
3678	ea = sa = bp->b_data;
3679	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3680		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3681		ea = (caddr_t)(vm_offset_t)ulmin(
3682		    (u_long)(vm_offset_t)ea,
3683		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3684		if (bp->b_pages[i] == bogus_page)
3685			continue;
3686		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3687		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3688		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3689		if ((bp->b_pages[i]->valid & mask) == mask)
3690			continue;
3691		if ((bp->b_pages[i]->valid & mask) == 0) {
3692			if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3693				bzero(sa, ea - sa);
3694		} else {
3695			for (; sa < ea; sa += DEV_BSIZE, j++) {
3696				if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3697				    (bp->b_pages[i]->valid & (1 << j)) == 0)
3698					bzero(sa, DEV_BSIZE);
3699			}
3700		}
3701		bp->b_pages[i]->valid |= mask;
3702	}
3703unlock:
3704	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3705	bp->b_resid = 0;
3706}
3707
3708/*
3709 * vm_hold_load_pages and vm_hold_free_pages get pages into
3710 * a buffers address space.  The pages are anonymous and are
3711 * not associated with a file object.
3712 */
3713static void
3714vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3715{
3716	vm_offset_t pg;
3717	vm_page_t p;
3718	int index;
3719
3720	to = round_page(to);
3721	from = round_page(from);
3722	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3723
3724	VM_OBJECT_LOCK(kernel_object);
3725	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3726tryagain:
3727		/*
3728		 * note: must allocate system pages since blocking here
3729		 * could intefere with paging I/O, no matter which
3730		 * process we are.
3731		 */
3732		p = vm_page_alloc(kernel_object,
3733			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3734		    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3735		if (!p) {
3736			atomic_add_int(&vm_pageout_deficit,
3737			    (to - pg) >> PAGE_SHIFT);
3738			VM_OBJECT_UNLOCK(kernel_object);
3739			VM_WAIT;
3740			VM_OBJECT_LOCK(kernel_object);
3741			goto tryagain;
3742		}
3743		p->valid = VM_PAGE_BITS_ALL;
3744		pmap_qenter(pg, &p, 1);
3745		bp->b_pages[index] = p;
3746	}
3747	VM_OBJECT_UNLOCK(kernel_object);
3748	bp->b_npages = index;
3749}
3750
3751/* Return pages associated with this buf to the vm system */
3752static void
3753vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3754{
3755	vm_offset_t pg;
3756	vm_page_t p;
3757	int index, newnpages;
3758
3759	from = round_page(from);
3760	to = round_page(to);
3761	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3762
3763	VM_OBJECT_LOCK(kernel_object);
3764	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3765		p = bp->b_pages[index];
3766		if (p && (index < bp->b_npages)) {
3767			if (p->busy) {
3768				printf(
3769			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3770				    (intmax_t)bp->b_blkno,
3771				    (intmax_t)bp->b_lblkno);
3772			}
3773			bp->b_pages[index] = NULL;
3774			pmap_qremove(pg, 1);
3775			vm_page_lock_queues();
3776			vm_page_unwire(p, 0);
3777			vm_page_free(p);
3778			vm_page_unlock_queues();
3779		}
3780	}
3781	VM_OBJECT_UNLOCK(kernel_object);
3782	bp->b_npages = newnpages;
3783}
3784
3785/*
3786 * Map an IO request into kernel virtual address space.
3787 *
3788 * All requests are (re)mapped into kernel VA space.
3789 * Notice that we use b_bufsize for the size of the buffer
3790 * to be mapped.  b_bcount might be modified by the driver.
3791 *
3792 * Note that even if the caller determines that the address space should
3793 * be valid, a race or a smaller-file mapped into a larger space may
3794 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3795 * check the return value.
3796 */
3797int
3798vmapbuf(struct buf *bp)
3799{
3800	caddr_t addr, kva;
3801	vm_prot_t prot;
3802	int pidx, i;
3803	struct vm_page *m;
3804	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3805
3806	if (bp->b_bufsize < 0)
3807		return (-1);
3808	prot = VM_PROT_READ;
3809	if (bp->b_iocmd == BIO_READ)
3810		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3811	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3812	     addr < bp->b_data + bp->b_bufsize;
3813	     addr += PAGE_SIZE, pidx++) {
3814		/*
3815		 * Do the vm_fault if needed; do the copy-on-write thing
3816		 * when reading stuff off device into memory.
3817		 *
3818		 * NOTE! Must use pmap_extract() because addr may be in
3819		 * the userland address space, and kextract is only guarenteed
3820		 * to work for the kernland address space (see: sparc64 port).
3821		 */
3822retry:
3823		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3824		    prot) < 0) {
3825			vm_page_lock_queues();
3826			for (i = 0; i < pidx; ++i) {
3827				vm_page_unhold(bp->b_pages[i]);
3828				bp->b_pages[i] = NULL;
3829			}
3830			vm_page_unlock_queues();
3831			return(-1);
3832		}
3833		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3834		if (m == NULL)
3835			goto retry;
3836		bp->b_pages[pidx] = m;
3837	}
3838	if (pidx > btoc(MAXPHYS))
3839		panic("vmapbuf: mapped more than MAXPHYS");
3840	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3841
3842	kva = bp->b_saveaddr;
3843	bp->b_npages = pidx;
3844	bp->b_saveaddr = bp->b_data;
3845	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3846	return(0);
3847}
3848
3849/*
3850 * Free the io map PTEs associated with this IO operation.
3851 * We also invalidate the TLB entries and restore the original b_addr.
3852 */
3853void
3854vunmapbuf(struct buf *bp)
3855{
3856	int pidx;
3857	int npages;
3858
3859	npages = bp->b_npages;
3860	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3861	vm_page_lock_queues();
3862	for (pidx = 0; pidx < npages; pidx++)
3863		vm_page_unhold(bp->b_pages[pidx]);
3864	vm_page_unlock_queues();
3865
3866	bp->b_data = bp->b_saveaddr;
3867}
3868
3869void
3870bdone(struct buf *bp)
3871{
3872	struct mtx *mtxp;
3873
3874	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3875	mtx_lock(mtxp);
3876	bp->b_flags |= B_DONE;
3877	wakeup(bp);
3878	mtx_unlock(mtxp);
3879}
3880
3881void
3882bwait(struct buf *bp, u_char pri, const char *wchan)
3883{
3884	struct mtx *mtxp;
3885
3886	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3887	mtx_lock(mtxp);
3888	while ((bp->b_flags & B_DONE) == 0)
3889		msleep(bp, mtxp, pri, wchan, 0);
3890	mtx_unlock(mtxp);
3891}
3892
3893int
3894bufsync(struct bufobj *bo, int waitfor)
3895{
3896
3897	return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
3898}
3899
3900void
3901bufstrategy(struct bufobj *bo, struct buf *bp)
3902{
3903	int i = 0;
3904	struct vnode *vp;
3905
3906	vp = bp->b_vp;
3907	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3908	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3909	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3910	i = VOP_STRATEGY(vp, bp);
3911	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3912}
3913
3914void
3915bufobj_wrefl(struct bufobj *bo)
3916{
3917
3918	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3919	ASSERT_BO_LOCKED(bo);
3920	bo->bo_numoutput++;
3921}
3922
3923void
3924bufobj_wref(struct bufobj *bo)
3925{
3926
3927	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3928	BO_LOCK(bo);
3929	bo->bo_numoutput++;
3930	BO_UNLOCK(bo);
3931}
3932
3933void
3934bufobj_wdrop(struct bufobj *bo)
3935{
3936
3937	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3938	BO_LOCK(bo);
3939	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3940	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3941		bo->bo_flag &= ~BO_WWAIT;
3942		wakeup(&bo->bo_numoutput);
3943	}
3944	BO_UNLOCK(bo);
3945}
3946
3947int
3948bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3949{
3950	int error;
3951
3952	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3953	ASSERT_BO_LOCKED(bo);
3954	error = 0;
3955	while (bo->bo_numoutput) {
3956		bo->bo_flag |= BO_WWAIT;
3957		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3958		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3959		if (error)
3960			break;
3961	}
3962	return (error);
3963}
3964
3965void
3966bpin(struct buf *bp)
3967{
3968	struct mtx *mtxp;
3969
3970	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3971	mtx_lock(mtxp);
3972	bp->b_pin_count++;
3973	mtx_unlock(mtxp);
3974}
3975
3976void
3977bunpin(struct buf *bp)
3978{
3979	struct mtx *mtxp;
3980
3981	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3982	mtx_lock(mtxp);
3983	if (--bp->b_pin_count == 0)
3984		wakeup(bp);
3985	mtx_unlock(mtxp);
3986}
3987
3988void
3989bunpin_wait(struct buf *bp)
3990{
3991	struct mtx *mtxp;
3992
3993	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3994	mtx_lock(mtxp);
3995	while (bp->b_pin_count > 0)
3996		msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
3997	mtx_unlock(mtxp);
3998}
3999
4000#include "opt_ddb.h"
4001#ifdef DDB
4002#include <ddb/ddb.h>
4003
4004/* DDB command to show buffer data */
4005DB_SHOW_COMMAND(buffer, db_show_buffer)
4006{
4007	/* get args */
4008	struct buf *bp = (struct buf *)addr;
4009
4010	if (!have_addr) {
4011		db_printf("usage: show buffer <addr>\n");
4012		return;
4013	}
4014
4015	db_printf("buf at %p\n", bp);
4016	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4017	db_printf(
4018	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4019	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_dep = %p\n",
4020	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4021	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4022	    bp->b_dep.lh_first);
4023	if (bp->b_npages) {
4024		int i;
4025		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4026		for (i = 0; i < bp->b_npages; i++) {
4027			vm_page_t m;
4028			m = bp->b_pages[i];
4029			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4030			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4031			if ((i + 1) < bp->b_npages)
4032				db_printf(",");
4033		}
4034		db_printf("\n");
4035	}
4036	db_printf(" ");
4037	lockmgr_printinfo(&bp->b_lock);
4038}
4039
4040DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4041{
4042	struct buf *bp;
4043	int i;
4044
4045	for (i = 0; i < nbuf; i++) {
4046		bp = &buf[i];
4047		if (BUF_ISLOCKED(bp)) {
4048			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4049			db_printf("\n");
4050		}
4051	}
4052}
4053
4054DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4055{
4056	struct vnode *vp;
4057	struct buf *bp;
4058
4059	if (!have_addr) {
4060		db_printf("usage: show vnodebufs <addr>\n");
4061		return;
4062	}
4063	vp = (struct vnode *)addr;
4064	db_printf("Clean buffers:\n");
4065	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4066		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4067		db_printf("\n");
4068	}
4069	db_printf("Dirty buffers:\n");
4070	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4071		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4072		db_printf("\n");
4073	}
4074}
4075#endif /* DDB */
4076