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