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