vfs_bio.c revision 232192
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 232192 2012-02-26 19:10:14Z 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 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	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1629	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1630	for (i = 0; i < bp->b_npages; i++) {
1631		m = bp->b_pages[i];
1632		bp->b_pages[i] = NULL;
1633		/*
1634		 * In order to keep page LRU ordering consistent, put
1635		 * everything on the inactive queue.
1636		 */
1637		vm_page_lock(m);
1638		vm_page_unwire(m, 0);
1639		/*
1640		 * We don't mess with busy pages, it is
1641		 * the responsibility of the process that
1642		 * busied the pages to deal with them.
1643		 */
1644		if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1645		    m->wire_count == 0) {
1646			/*
1647			 * Might as well free the page if we can and it has
1648			 * no valid data.  We also free the page if the
1649			 * buffer was used for direct I/O
1650			 */
1651			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
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
1663	if (bp->b_bufsize) {
1664		bufspacewakeup();
1665		bp->b_bufsize = 0;
1666	}
1667	bp->b_npages = 0;
1668	bp->b_flags &= ~B_VMIO;
1669	if (bp->b_vp)
1670		brelvp(bp);
1671}
1672
1673/*
1674 * Check to see if a block at a particular lbn is available for a clustered
1675 * write.
1676 */
1677static int
1678vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1679{
1680	struct buf *bpa;
1681	int match;
1682
1683	match = 0;
1684
1685	/* If the buf isn't in core skip it */
1686	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1687		return (0);
1688
1689	/* If the buf is busy we don't want to wait for it */
1690	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1691		return (0);
1692
1693	/* Only cluster with valid clusterable delayed write buffers */
1694	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1695	    (B_DELWRI | B_CLUSTEROK))
1696		goto done;
1697
1698	if (bpa->b_bufsize != size)
1699		goto done;
1700
1701	/*
1702	 * Check to see if it is in the expected place on disk and that the
1703	 * block has been mapped.
1704	 */
1705	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1706		match = 1;
1707done:
1708	BUF_UNLOCK(bpa);
1709	return (match);
1710}
1711
1712/*
1713 *	vfs_bio_awrite:
1714 *
1715 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1716 *	This is much better then the old way of writing only one buffer at
1717 *	a time.  Note that we may not be presented with the buffers in the
1718 *	correct order, so we search for the cluster in both directions.
1719 */
1720int
1721vfs_bio_awrite(struct buf *bp)
1722{
1723	struct bufobj *bo;
1724	int i;
1725	int j;
1726	daddr_t lblkno = bp->b_lblkno;
1727	struct vnode *vp = bp->b_vp;
1728	int ncl;
1729	int nwritten;
1730	int size;
1731	int maxcl;
1732
1733	bo = &vp->v_bufobj;
1734	/*
1735	 * right now we support clustered writing only to regular files.  If
1736	 * we find a clusterable block we could be in the middle of a cluster
1737	 * rather then at the beginning.
1738	 */
1739	if ((vp->v_type == VREG) &&
1740	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1741	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1742
1743		size = vp->v_mount->mnt_stat.f_iosize;
1744		maxcl = MAXPHYS / size;
1745
1746		BO_LOCK(bo);
1747		for (i = 1; i < maxcl; i++)
1748			if (vfs_bio_clcheck(vp, size, lblkno + i,
1749			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1750				break;
1751
1752		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1753			if (vfs_bio_clcheck(vp, size, lblkno - j,
1754			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1755				break;
1756		BO_UNLOCK(bo);
1757		--j;
1758		ncl = i + j;
1759		/*
1760		 * this is a possible cluster write
1761		 */
1762		if (ncl != 1) {
1763			BUF_UNLOCK(bp);
1764			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1765			return nwritten;
1766		}
1767	}
1768	bremfree(bp);
1769	bp->b_flags |= B_ASYNC;
1770	/*
1771	 * default (old) behavior, writing out only one block
1772	 *
1773	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1774	 */
1775	nwritten = bp->b_bufsize;
1776	(void) bwrite(bp);
1777
1778	return nwritten;
1779}
1780
1781/*
1782 *	getnewbuf:
1783 *
1784 *	Find and initialize a new buffer header, freeing up existing buffers
1785 *	in the bufqueues as necessary.  The new buffer is returned locked.
1786 *
1787 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1788 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1789 *
1790 *	We block if:
1791 *		We have insufficient buffer headers
1792 *		We have insufficient buffer space
1793 *		buffer_map is too fragmented ( space reservation fails )
1794 *		If we have to flush dirty buffers ( but we try to avoid this )
1795 *
1796 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1797 *	Instead we ask the buf daemon to do it for us.  We attempt to
1798 *	avoid piecemeal wakeups of the pageout daemon.
1799 */
1800
1801static struct buf *
1802getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
1803    int gbflags)
1804{
1805	struct thread *td;
1806	struct buf *bp;
1807	struct buf *nbp;
1808	int defrag = 0;
1809	int nqindex;
1810	static int flushingbufs;
1811
1812	td = curthread;
1813	/*
1814	 * We can't afford to block since we might be holding a vnode lock,
1815	 * which may prevent system daemons from running.  We deal with
1816	 * low-memory situations by proactively returning memory and running
1817	 * async I/O rather then sync I/O.
1818	 */
1819	atomic_add_int(&getnewbufcalls, 1);
1820	atomic_subtract_int(&getnewbufrestarts, 1);
1821restart:
1822	atomic_add_int(&getnewbufrestarts, 1);
1823
1824	/*
1825	 * Setup for scan.  If we do not have enough free buffers,
1826	 * we setup a degenerate case that immediately fails.  Note
1827	 * that if we are specially marked process, we are allowed to
1828	 * dip into our reserves.
1829	 *
1830	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1831	 *
1832	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1833	 * However, there are a number of cases (defragging, reusing, ...)
1834	 * where we cannot backup.
1835	 */
1836	mtx_lock(&bqlock);
1837	nqindex = QUEUE_EMPTYKVA;
1838	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1839
1840	if (nbp == NULL) {
1841		/*
1842		 * If no EMPTYKVA buffers and we are either
1843		 * defragging or reusing, locate a CLEAN buffer
1844		 * to free or reuse.  If bufspace useage is low
1845		 * skip this step so we can allocate a new buffer.
1846		 */
1847		if (defrag || bufspace >= lobufspace) {
1848			nqindex = QUEUE_CLEAN;
1849			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1850		}
1851
1852		/*
1853		 * If we could not find or were not allowed to reuse a
1854		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1855		 * buffer.  We can only use an EMPTY buffer if allocating
1856		 * its KVA would not otherwise run us out of buffer space.
1857		 */
1858		if (nbp == NULL && defrag == 0 &&
1859		    bufspace + maxsize < hibufspace) {
1860			nqindex = QUEUE_EMPTY;
1861			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1862		}
1863	}
1864
1865	/*
1866	 * Run scan, possibly freeing data and/or kva mappings on the fly
1867	 * depending.
1868	 */
1869
1870	while ((bp = nbp) != NULL) {
1871		int qindex = nqindex;
1872
1873		/*
1874		 * Calculate next bp ( we can only use it if we do not block
1875		 * or do other fancy things ).
1876		 */
1877		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1878			switch(qindex) {
1879			case QUEUE_EMPTY:
1880				nqindex = QUEUE_EMPTYKVA;
1881				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1882					break;
1883				/* FALLTHROUGH */
1884			case QUEUE_EMPTYKVA:
1885				nqindex = QUEUE_CLEAN;
1886				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1887					break;
1888				/* FALLTHROUGH */
1889			case QUEUE_CLEAN:
1890				/*
1891				 * nbp is NULL.
1892				 */
1893				break;
1894			}
1895		}
1896		/*
1897		 * If we are defragging then we need a buffer with
1898		 * b_kvasize != 0.  XXX this situation should no longer
1899		 * occur, if defrag is non-zero the buffer's b_kvasize
1900		 * should also be non-zero at this point.  XXX
1901		 */
1902		if (defrag && bp->b_kvasize == 0) {
1903			printf("Warning: defrag empty buffer %p\n", bp);
1904			continue;
1905		}
1906
1907		/*
1908		 * Start freeing the bp.  This is somewhat involved.  nbp
1909		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1910		 */
1911		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1912			continue;
1913		if (bp->b_vp) {
1914			BO_LOCK(bp->b_bufobj);
1915			if (bp->b_vflags & BV_BKGRDINPROG) {
1916				BO_UNLOCK(bp->b_bufobj);
1917				BUF_UNLOCK(bp);
1918				continue;
1919			}
1920			BO_UNLOCK(bp->b_bufobj);
1921		}
1922		CTR6(KTR_BUF,
1923		    "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1924		    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1925		    bp->b_kvasize, bp->b_bufsize, qindex);
1926
1927		/*
1928		 * Sanity Checks
1929		 */
1930		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1931
1932		/*
1933		 * Note: we no longer distinguish between VMIO and non-VMIO
1934		 * buffers.
1935		 */
1936
1937		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1938
1939		if (bp->b_bufobj != NULL)
1940			BO_LOCK(bp->b_bufobj);
1941		bremfreel(bp);
1942		if (bp->b_bufobj != NULL)
1943			BO_UNLOCK(bp->b_bufobj);
1944		mtx_unlock(&bqlock);
1945
1946		if (qindex == QUEUE_CLEAN) {
1947			if (bp->b_flags & B_VMIO) {
1948				bp->b_flags &= ~B_ASYNC;
1949				vfs_vmio_release(bp);
1950			}
1951			if (bp->b_vp)
1952				brelvp(bp);
1953		}
1954
1955		/*
1956		 * NOTE:  nbp is now entirely invalid.  We can only restart
1957		 * the scan from this point on.
1958		 *
1959		 * Get the rest of the buffer freed up.  b_kva* is still
1960		 * valid after this operation.
1961		 */
1962
1963		if (bp->b_rcred != NOCRED) {
1964			crfree(bp->b_rcred);
1965			bp->b_rcred = NOCRED;
1966		}
1967		if (bp->b_wcred != NOCRED) {
1968			crfree(bp->b_wcred);
1969			bp->b_wcred = NOCRED;
1970		}
1971		if (!LIST_EMPTY(&bp->b_dep))
1972			buf_deallocate(bp);
1973		if (bp->b_vflags & BV_BKGRDINPROG)
1974			panic("losing buffer 3");
1975		KASSERT(bp->b_vp == NULL,
1976		    ("bp: %p still has vnode %p.  qindex: %d",
1977		    bp, bp->b_vp, qindex));
1978		KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1979		   ("bp: %p still on a buffer list. xflags %X",
1980		    bp, bp->b_xflags));
1981
1982		if (bp->b_bufsize)
1983			allocbuf(bp, 0);
1984
1985		bp->b_flags = 0;
1986		bp->b_ioflags = 0;
1987		bp->b_xflags = 0;
1988		KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
1989		    ("buf %p still counted as free?", bp));
1990		bp->b_vflags = 0;
1991		bp->b_vp = NULL;
1992		bp->b_blkno = bp->b_lblkno = 0;
1993		bp->b_offset = NOOFFSET;
1994		bp->b_iodone = 0;
1995		bp->b_error = 0;
1996		bp->b_resid = 0;
1997		bp->b_bcount = 0;
1998		bp->b_npages = 0;
1999		bp->b_dirtyoff = bp->b_dirtyend = 0;
2000		bp->b_bufobj = NULL;
2001		bp->b_pin_count = 0;
2002		bp->b_fsprivate1 = NULL;
2003		bp->b_fsprivate2 = NULL;
2004		bp->b_fsprivate3 = NULL;
2005
2006		LIST_INIT(&bp->b_dep);
2007
2008		/*
2009		 * If we are defragging then free the buffer.
2010		 */
2011		if (defrag) {
2012			bp->b_flags |= B_INVAL;
2013			bfreekva(bp);
2014			brelse(bp);
2015			defrag = 0;
2016			goto restart;
2017		}
2018
2019		/*
2020		 * Notify any waiters for the buffer lock about
2021		 * identity change by freeing the buffer.
2022		 */
2023		if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2024			bp->b_flags |= B_INVAL;
2025			bfreekva(bp);
2026			brelse(bp);
2027			goto restart;
2028		}
2029
2030		/*
2031		 * If we are overcomitted then recover the buffer and its
2032		 * KVM space.  This occurs in rare situations when multiple
2033		 * processes are blocked in getnewbuf() or allocbuf().
2034		 */
2035		if (bufspace >= hibufspace)
2036			flushingbufs = 1;
2037		if (flushingbufs && bp->b_kvasize != 0) {
2038			bp->b_flags |= B_INVAL;
2039			bfreekva(bp);
2040			brelse(bp);
2041			goto restart;
2042		}
2043		if (bufspace < lobufspace)
2044			flushingbufs = 0;
2045		break;
2046	}
2047
2048	/*
2049	 * If we exhausted our list, sleep as appropriate.  We may have to
2050	 * wakeup various daemons and write out some dirty buffers.
2051	 *
2052	 * Generally we are sleeping due to insufficient buffer space.
2053	 */
2054
2055	if (bp == NULL) {
2056		int flags, norunbuf;
2057		char *waitmsg;
2058		int fl;
2059
2060		if (defrag) {
2061			flags = VFS_BIO_NEED_BUFSPACE;
2062			waitmsg = "nbufkv";
2063		} else if (bufspace >= hibufspace) {
2064			waitmsg = "nbufbs";
2065			flags = VFS_BIO_NEED_BUFSPACE;
2066		} else {
2067			waitmsg = "newbuf";
2068			flags = VFS_BIO_NEED_ANY;
2069		}
2070		mtx_lock(&nblock);
2071		needsbuffer |= flags;
2072		mtx_unlock(&nblock);
2073		mtx_unlock(&bqlock);
2074
2075		bd_speedup();	/* heeeelp */
2076		if (gbflags & GB_NOWAIT_BD)
2077			return (NULL);
2078
2079		mtx_lock(&nblock);
2080		while (needsbuffer & flags) {
2081			if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2082				mtx_unlock(&nblock);
2083				/*
2084				 * getblk() is called with a vnode
2085				 * locked, and some majority of the
2086				 * dirty buffers may as well belong to
2087				 * the vnode. Flushing the buffers
2088				 * there would make a progress that
2089				 * cannot be achieved by the
2090				 * buf_daemon, that cannot lock the
2091				 * vnode.
2092				 */
2093				norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2094				    (td->td_pflags & TDP_NORUNNINGBUF);
2095				/* play bufdaemon */
2096				td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2097				fl = buf_do_flush(vp);
2098				td->td_pflags &= norunbuf;
2099				mtx_lock(&nblock);
2100				if (fl != 0)
2101					continue;
2102				if ((needsbuffer & flags) == 0)
2103					break;
2104			}
2105			if (msleep(&needsbuffer, &nblock,
2106			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2107				mtx_unlock(&nblock);
2108				return (NULL);
2109			}
2110		}
2111		mtx_unlock(&nblock);
2112	} else {
2113		/*
2114		 * We finally have a valid bp.  We aren't quite out of the
2115		 * woods, we still have to reserve kva space.  In order
2116		 * to keep fragmentation sane we only allocate kva in
2117		 * BKVASIZE chunks.
2118		 */
2119		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2120
2121		if (maxsize != bp->b_kvasize) {
2122			vm_offset_t addr = 0;
2123
2124			bfreekva(bp);
2125
2126			vm_map_lock(buffer_map);
2127			if (vm_map_findspace(buffer_map,
2128				vm_map_min(buffer_map), maxsize, &addr)) {
2129				/*
2130				 * Uh oh.  Buffer map is to fragmented.  We
2131				 * must defragment the map.
2132				 */
2133				atomic_add_int(&bufdefragcnt, 1);
2134				vm_map_unlock(buffer_map);
2135				defrag = 1;
2136				bp->b_flags |= B_INVAL;
2137				brelse(bp);
2138				goto restart;
2139			}
2140			if (addr) {
2141				vm_map_insert(buffer_map, NULL, 0,
2142					addr, addr + maxsize,
2143					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2144
2145				bp->b_kvabase = (caddr_t) addr;
2146				bp->b_kvasize = maxsize;
2147				atomic_add_long(&bufspace, bp->b_kvasize);
2148				atomic_add_int(&bufreusecnt, 1);
2149			}
2150			vm_map_unlock(buffer_map);
2151		}
2152		bp->b_saveaddr = bp->b_kvabase;
2153		bp->b_data = bp->b_saveaddr;
2154	}
2155	return(bp);
2156}
2157
2158/*
2159 *	buf_daemon:
2160 *
2161 *	buffer flushing daemon.  Buffers are normally flushed by the
2162 *	update daemon but if it cannot keep up this process starts to
2163 *	take the load in an attempt to prevent getnewbuf() from blocking.
2164 */
2165
2166static struct kproc_desc buf_kp = {
2167	"bufdaemon",
2168	buf_daemon,
2169	&bufdaemonproc
2170};
2171SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2172
2173static int
2174buf_do_flush(struct vnode *vp)
2175{
2176	int flushed;
2177
2178	flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2179	/* The list empty check here is slightly racy */
2180	if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2181		mtx_lock(&Giant);
2182		flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2183		mtx_unlock(&Giant);
2184	}
2185	if (flushed == 0) {
2186		/*
2187		 * Could not find any buffers without rollback
2188		 * dependencies, so just write the first one
2189		 * in the hopes of eventually making progress.
2190		 */
2191		flushbufqueues(vp, QUEUE_DIRTY, 1);
2192		if (!TAILQ_EMPTY(
2193			    &bufqueues[QUEUE_DIRTY_GIANT])) {
2194			mtx_lock(&Giant);
2195			flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2196			mtx_unlock(&Giant);
2197		}
2198	}
2199	return (flushed);
2200}
2201
2202static void
2203buf_daemon()
2204{
2205	int lodirtysave;
2206
2207	/*
2208	 * This process needs to be suspended prior to shutdown sync.
2209	 */
2210	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2211	    SHUTDOWN_PRI_LAST);
2212
2213	/*
2214	 * This process is allowed to take the buffer cache to the limit
2215	 */
2216	curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2217	mtx_lock(&bdlock);
2218	for (;;) {
2219		bd_request = 0;
2220		mtx_unlock(&bdlock);
2221
2222		kproc_suspend_check(bufdaemonproc);
2223		lodirtysave = lodirtybuffers;
2224		if (bd_speedupreq) {
2225			lodirtybuffers = numdirtybuffers / 2;
2226			bd_speedupreq = 0;
2227		}
2228		/*
2229		 * Do the flush.  Limit the amount of in-transit I/O we
2230		 * allow to build up, otherwise we would completely saturate
2231		 * the I/O system.  Wakeup any waiting processes before we
2232		 * normally would so they can run in parallel with our drain.
2233		 */
2234		while (numdirtybuffers > lodirtybuffers) {
2235			if (buf_do_flush(NULL) == 0)
2236				break;
2237			kern_yield(PRI_UNCHANGED);
2238		}
2239		lodirtybuffers = lodirtysave;
2240
2241		/*
2242		 * Only clear bd_request if we have reached our low water
2243		 * mark.  The buf_daemon normally waits 1 second and
2244		 * then incrementally flushes any dirty buffers that have
2245		 * built up, within reason.
2246		 *
2247		 * If we were unable to hit our low water mark and couldn't
2248		 * find any flushable buffers, we sleep half a second.
2249		 * Otherwise we loop immediately.
2250		 */
2251		mtx_lock(&bdlock);
2252		if (numdirtybuffers <= lodirtybuffers) {
2253			/*
2254			 * We reached our low water mark, reset the
2255			 * request and sleep until we are needed again.
2256			 * The sleep is just so the suspend code works.
2257			 */
2258			bd_request = 0;
2259			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2260		} else {
2261			/*
2262			 * We couldn't find any flushable dirty buffers but
2263			 * still have too many dirty buffers, we
2264			 * have to sleep and try again.  (rare)
2265			 */
2266			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2267		}
2268	}
2269}
2270
2271/*
2272 *	flushbufqueues:
2273 *
2274 *	Try to flush a buffer in the dirty queue.  We must be careful to
2275 *	free up B_INVAL buffers instead of write them, which NFS is
2276 *	particularly sensitive to.
2277 */
2278static int flushwithdeps = 0;
2279SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2280    0, "Number of buffers flushed with dependecies that require rollbacks");
2281
2282static int
2283flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2284{
2285	struct buf *sentinel;
2286	struct vnode *vp;
2287	struct mount *mp;
2288	struct buf *bp;
2289	int hasdeps;
2290	int flushed;
2291	int target;
2292
2293	if (lvp == NULL) {
2294		target = numdirtybuffers - lodirtybuffers;
2295		if (flushdeps && target > 2)
2296			target /= 2;
2297	} else
2298		target = flushbufqtarget;
2299	flushed = 0;
2300	bp = NULL;
2301	sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2302	sentinel->b_qindex = QUEUE_SENTINEL;
2303	mtx_lock(&bqlock);
2304	TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2305	while (flushed != target) {
2306		bp = TAILQ_NEXT(sentinel, b_freelist);
2307		if (bp != NULL) {
2308			TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2309			TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2310			    b_freelist);
2311		} else
2312			break;
2313		/*
2314		 * Skip sentinels inserted by other invocations of the
2315		 * flushbufqueues(), taking care to not reorder them.
2316		 */
2317		if (bp->b_qindex == QUEUE_SENTINEL)
2318			continue;
2319		/*
2320		 * Only flush the buffers that belong to the
2321		 * vnode locked by the curthread.
2322		 */
2323		if (lvp != NULL && bp->b_vp != lvp)
2324			continue;
2325		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2326			continue;
2327		if (bp->b_pin_count > 0) {
2328			BUF_UNLOCK(bp);
2329			continue;
2330		}
2331		BO_LOCK(bp->b_bufobj);
2332		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2333		    (bp->b_flags & B_DELWRI) == 0) {
2334			BO_UNLOCK(bp->b_bufobj);
2335			BUF_UNLOCK(bp);
2336			continue;
2337		}
2338		BO_UNLOCK(bp->b_bufobj);
2339		if (bp->b_flags & B_INVAL) {
2340			bremfreel(bp);
2341			mtx_unlock(&bqlock);
2342			brelse(bp);
2343			flushed++;
2344			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2345			mtx_lock(&bqlock);
2346			continue;
2347		}
2348
2349		if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2350			if (flushdeps == 0) {
2351				BUF_UNLOCK(bp);
2352				continue;
2353			}
2354			hasdeps = 1;
2355		} else
2356			hasdeps = 0;
2357		/*
2358		 * We must hold the lock on a vnode before writing
2359		 * one of its buffers. Otherwise we may confuse, or
2360		 * in the case of a snapshot vnode, deadlock the
2361		 * system.
2362		 *
2363		 * The lock order here is the reverse of the normal
2364		 * of vnode followed by buf lock.  This is ok because
2365		 * the NOWAIT will prevent deadlock.
2366		 */
2367		vp = bp->b_vp;
2368		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2369			BUF_UNLOCK(bp);
2370			continue;
2371		}
2372		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2373			mtx_unlock(&bqlock);
2374			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2375			    bp, bp->b_vp, bp->b_flags);
2376			if (curproc == bufdaemonproc)
2377				vfs_bio_awrite(bp);
2378			else {
2379				bremfree(bp);
2380				bwrite(bp);
2381				notbufdflashes++;
2382			}
2383			vn_finished_write(mp);
2384			VOP_UNLOCK(vp, 0);
2385			flushwithdeps += hasdeps;
2386			flushed++;
2387
2388			/*
2389			 * Sleeping on runningbufspace while holding
2390			 * vnode lock leads to deadlock.
2391			 */
2392			if (curproc == bufdaemonproc)
2393				waitrunningbufspace();
2394			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2395			mtx_lock(&bqlock);
2396			continue;
2397		}
2398		vn_finished_write(mp);
2399		BUF_UNLOCK(bp);
2400	}
2401	TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2402	mtx_unlock(&bqlock);
2403	free(sentinel, M_TEMP);
2404	return (flushed);
2405}
2406
2407/*
2408 * Check to see if a block is currently memory resident.
2409 */
2410struct buf *
2411incore(struct bufobj *bo, daddr_t blkno)
2412{
2413	struct buf *bp;
2414
2415	BO_LOCK(bo);
2416	bp = gbincore(bo, blkno);
2417	BO_UNLOCK(bo);
2418	return (bp);
2419}
2420
2421/*
2422 * Returns true if no I/O is needed to access the
2423 * associated VM object.  This is like incore except
2424 * it also hunts around in the VM system for the data.
2425 */
2426
2427static int
2428inmem(struct vnode * vp, daddr_t blkno)
2429{
2430	vm_object_t obj;
2431	vm_offset_t toff, tinc, size;
2432	vm_page_t m;
2433	vm_ooffset_t off;
2434
2435	ASSERT_VOP_LOCKED(vp, "inmem");
2436
2437	if (incore(&vp->v_bufobj, blkno))
2438		return 1;
2439	if (vp->v_mount == NULL)
2440		return 0;
2441	obj = vp->v_object;
2442	if (obj == NULL)
2443		return (0);
2444
2445	size = PAGE_SIZE;
2446	if (size > vp->v_mount->mnt_stat.f_iosize)
2447		size = vp->v_mount->mnt_stat.f_iosize;
2448	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2449
2450	VM_OBJECT_LOCK(obj);
2451	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2452		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2453		if (!m)
2454			goto notinmem;
2455		tinc = size;
2456		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2457			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2458		if (vm_page_is_valid(m,
2459		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2460			goto notinmem;
2461	}
2462	VM_OBJECT_UNLOCK(obj);
2463	return 1;
2464
2465notinmem:
2466	VM_OBJECT_UNLOCK(obj);
2467	return (0);
2468}
2469
2470/*
2471 * Set the dirty range for a buffer based on the status of the dirty
2472 * bits in the pages comprising the buffer.  The range is limited
2473 * to the size of the buffer.
2474 *
2475 * Tell the VM system that the pages associated with this buffer
2476 * are clean.  This is used for delayed writes where the data is
2477 * going to go to disk eventually without additional VM intevention.
2478 *
2479 * Note that while we only really need to clean through to b_bcount, we
2480 * just go ahead and clean through to b_bufsize.
2481 */
2482static void
2483vfs_clean_pages_dirty_buf(struct buf *bp)
2484{
2485	vm_ooffset_t foff, noff, eoff;
2486	vm_page_t m;
2487	int i;
2488
2489	if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2490		return;
2491
2492	foff = bp->b_offset;
2493	KASSERT(bp->b_offset != NOOFFSET,
2494	    ("vfs_clean_pages_dirty_buf: no buffer offset"));
2495
2496	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2497	vfs_drain_busy_pages(bp);
2498	vfs_setdirty_locked_object(bp);
2499	for (i = 0; i < bp->b_npages; i++) {
2500		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2501		eoff = noff;
2502		if (eoff > bp->b_offset + bp->b_bufsize)
2503			eoff = bp->b_offset + bp->b_bufsize;
2504		m = bp->b_pages[i];
2505		vfs_page_set_validclean(bp, foff, m);
2506		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2507		foff = noff;
2508	}
2509	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2510}
2511
2512static void
2513vfs_setdirty_locked_object(struct buf *bp)
2514{
2515	vm_object_t object;
2516	int i;
2517
2518	object = bp->b_bufobj->bo_object;
2519	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2520
2521	/*
2522	 * We qualify the scan for modified pages on whether the
2523	 * object has been flushed yet.
2524	 */
2525	if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2526		vm_offset_t boffset;
2527		vm_offset_t eoffset;
2528
2529		/*
2530		 * test the pages to see if they have been modified directly
2531		 * by users through the VM system.
2532		 */
2533		for (i = 0; i < bp->b_npages; i++)
2534			vm_page_test_dirty(bp->b_pages[i]);
2535
2536		/*
2537		 * Calculate the encompassing dirty range, boffset and eoffset,
2538		 * (eoffset - boffset) bytes.
2539		 */
2540
2541		for (i = 0; i < bp->b_npages; i++) {
2542			if (bp->b_pages[i]->dirty)
2543				break;
2544		}
2545		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2546
2547		for (i = bp->b_npages - 1; i >= 0; --i) {
2548			if (bp->b_pages[i]->dirty) {
2549				break;
2550			}
2551		}
2552		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2553
2554		/*
2555		 * Fit it to the buffer.
2556		 */
2557
2558		if (eoffset > bp->b_bcount)
2559			eoffset = bp->b_bcount;
2560
2561		/*
2562		 * If we have a good dirty range, merge with the existing
2563		 * dirty range.
2564		 */
2565
2566		if (boffset < eoffset) {
2567			if (bp->b_dirtyoff > boffset)
2568				bp->b_dirtyoff = boffset;
2569			if (bp->b_dirtyend < eoffset)
2570				bp->b_dirtyend = eoffset;
2571		}
2572	}
2573}
2574
2575/*
2576 *	getblk:
2577 *
2578 *	Get a block given a specified block and offset into a file/device.
2579 *	The buffers B_DONE bit will be cleared on return, making it almost
2580 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2581 *	return.  The caller should clear B_INVAL prior to initiating a
2582 *	READ.
2583 *
2584 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2585 *	an existing buffer.
2586 *
2587 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2588 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2589 *	and then cleared based on the backing VM.  If the previous buffer is
2590 *	non-0-sized but invalid, B_CACHE will be cleared.
2591 *
2592 *	If getblk() must create a new buffer, the new buffer is returned with
2593 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2594 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2595 *	backing VM.
2596 *
2597 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2598 *	B_CACHE bit is clear.
2599 *
2600 *	What this means, basically, is that the caller should use B_CACHE to
2601 *	determine whether the buffer is fully valid or not and should clear
2602 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2603 *	the buffer by loading its data area with something, the caller needs
2604 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2605 *	the caller should set B_CACHE ( as an optimization ), else the caller
2606 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2607 *	a write attempt or if it was a successfull read.  If the caller
2608 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2609 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2610 */
2611struct buf *
2612getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2613    int flags)
2614{
2615	struct buf *bp;
2616	struct bufobj *bo;
2617	int error;
2618
2619	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2620	ASSERT_VOP_LOCKED(vp, "getblk");
2621	if (size > MAXBSIZE)
2622		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2623
2624	bo = &vp->v_bufobj;
2625loop:
2626	/*
2627	 * Block if we are low on buffers.   Certain processes are allowed
2628	 * to completely exhaust the buffer cache.
2629         *
2630         * If this check ever becomes a bottleneck it may be better to
2631         * move it into the else, when gbincore() fails.  At the moment
2632         * it isn't a problem.
2633	 *
2634	 * XXX remove if 0 sections (clean this up after its proven)
2635         */
2636	if (numfreebuffers == 0) {
2637		if (TD_IS_IDLETHREAD(curthread))
2638			return NULL;
2639		mtx_lock(&nblock);
2640		needsbuffer |= VFS_BIO_NEED_ANY;
2641		mtx_unlock(&nblock);
2642	}
2643
2644	BO_LOCK(bo);
2645	bp = gbincore(bo, blkno);
2646	if (bp != NULL) {
2647		int lockflags;
2648		/*
2649		 * Buffer is in-core.  If the buffer is not busy, it must
2650		 * be on a queue.
2651		 */
2652		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2653
2654		if (flags & GB_LOCK_NOWAIT)
2655			lockflags |= LK_NOWAIT;
2656
2657		error = BUF_TIMELOCK(bp, lockflags,
2658		    BO_MTX(bo), "getblk", slpflag, slptimeo);
2659
2660		/*
2661		 * If we slept and got the lock we have to restart in case
2662		 * the buffer changed identities.
2663		 */
2664		if (error == ENOLCK)
2665			goto loop;
2666		/* We timed out or were interrupted. */
2667		else if (error)
2668			return (NULL);
2669
2670		/*
2671		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2672		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2673		 * and for a VMIO buffer B_CACHE is adjusted according to the
2674		 * backing VM cache.
2675		 */
2676		if (bp->b_flags & B_INVAL)
2677			bp->b_flags &= ~B_CACHE;
2678		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2679			bp->b_flags |= B_CACHE;
2680		BO_LOCK(bo);
2681		bremfree(bp);
2682		BO_UNLOCK(bo);
2683
2684		/*
2685		 * check for size inconsistancies for non-VMIO case.
2686		 */
2687
2688		if (bp->b_bcount != size) {
2689			if ((bp->b_flags & B_VMIO) == 0 ||
2690			    (size > bp->b_kvasize)) {
2691				if (bp->b_flags & B_DELWRI) {
2692					/*
2693					 * If buffer is pinned and caller does
2694					 * not want sleep  waiting for it to be
2695					 * unpinned, bail out
2696					 * */
2697					if (bp->b_pin_count > 0) {
2698						if (flags & GB_LOCK_NOWAIT) {
2699							bqrelse(bp);
2700							return (NULL);
2701						} else {
2702							bunpin_wait(bp);
2703						}
2704					}
2705					bp->b_flags |= B_NOCACHE;
2706					bwrite(bp);
2707				} else {
2708					if (LIST_EMPTY(&bp->b_dep)) {
2709						bp->b_flags |= B_RELBUF;
2710						brelse(bp);
2711					} else {
2712						bp->b_flags |= B_NOCACHE;
2713						bwrite(bp);
2714					}
2715				}
2716				goto loop;
2717			}
2718		}
2719
2720		/*
2721		 * If the size is inconsistant in the VMIO case, we can resize
2722		 * the buffer.  This might lead to B_CACHE getting set or
2723		 * cleared.  If the size has not changed, B_CACHE remains
2724		 * unchanged from its previous state.
2725		 */
2726
2727		if (bp->b_bcount != size)
2728			allocbuf(bp, size);
2729
2730		KASSERT(bp->b_offset != NOOFFSET,
2731		    ("getblk: no buffer offset"));
2732
2733		/*
2734		 * A buffer with B_DELWRI set and B_CACHE clear must
2735		 * be committed before we can return the buffer in
2736		 * order to prevent the caller from issuing a read
2737		 * ( due to B_CACHE not being set ) and overwriting
2738		 * it.
2739		 *
2740		 * Most callers, including NFS and FFS, need this to
2741		 * operate properly either because they assume they
2742		 * can issue a read if B_CACHE is not set, or because
2743		 * ( for example ) an uncached B_DELWRI might loop due
2744		 * to softupdates re-dirtying the buffer.  In the latter
2745		 * case, B_CACHE is set after the first write completes,
2746		 * preventing further loops.
2747		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2748		 * above while extending the buffer, we cannot allow the
2749		 * buffer to remain with B_CACHE set after the write
2750		 * completes or it will represent a corrupt state.  To
2751		 * deal with this we set B_NOCACHE to scrap the buffer
2752		 * after the write.
2753		 *
2754		 * We might be able to do something fancy, like setting
2755		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2756		 * so the below call doesn't set B_CACHE, but that gets real
2757		 * confusing.  This is much easier.
2758		 */
2759
2760		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2761			bp->b_flags |= B_NOCACHE;
2762			bwrite(bp);
2763			goto loop;
2764		}
2765		bp->b_flags &= ~B_DONE;
2766	} else {
2767		int bsize, maxsize, vmio;
2768		off_t offset;
2769
2770		/*
2771		 * Buffer is not in-core, create new buffer.  The buffer
2772		 * returned by getnewbuf() is locked.  Note that the returned
2773		 * buffer is also considered valid (not marked B_INVAL).
2774		 */
2775		BO_UNLOCK(bo);
2776		/*
2777		 * If the user does not want us to create the buffer, bail out
2778		 * here.
2779		 */
2780		if (flags & GB_NOCREAT)
2781			return NULL;
2782		bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
2783		offset = blkno * bsize;
2784		vmio = vp->v_object != NULL;
2785		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2786		maxsize = imax(maxsize, bsize);
2787
2788		bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
2789		if (bp == NULL) {
2790			if (slpflag || slptimeo)
2791				return NULL;
2792			goto loop;
2793		}
2794
2795		/*
2796		 * This code is used to make sure that a buffer is not
2797		 * created while the getnewbuf routine is blocked.
2798		 * This can be a problem whether the vnode is locked or not.
2799		 * If the buffer is created out from under us, we have to
2800		 * throw away the one we just created.
2801		 *
2802		 * Note: this must occur before we associate the buffer
2803		 * with the vp especially considering limitations in
2804		 * the splay tree implementation when dealing with duplicate
2805		 * lblkno's.
2806		 */
2807		BO_LOCK(bo);
2808		if (gbincore(bo, blkno)) {
2809			BO_UNLOCK(bo);
2810			bp->b_flags |= B_INVAL;
2811			brelse(bp);
2812			goto loop;
2813		}
2814
2815		/*
2816		 * Insert the buffer into the hash, so that it can
2817		 * be found by incore.
2818		 */
2819		bp->b_blkno = bp->b_lblkno = blkno;
2820		bp->b_offset = offset;
2821		bgetvp(vp, bp);
2822		BO_UNLOCK(bo);
2823
2824		/*
2825		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2826		 * buffer size starts out as 0, B_CACHE will be set by
2827		 * allocbuf() for the VMIO case prior to it testing the
2828		 * backing store for validity.
2829		 */
2830
2831		if (vmio) {
2832			bp->b_flags |= B_VMIO;
2833			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2834			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2835			    bp, vp->v_object, bp->b_bufobj->bo_object));
2836		} else {
2837			bp->b_flags &= ~B_VMIO;
2838			KASSERT(bp->b_bufobj->bo_object == NULL,
2839			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2840			    bp, bp->b_bufobj->bo_object));
2841		}
2842
2843		allocbuf(bp, size);
2844		bp->b_flags &= ~B_DONE;
2845	}
2846	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2847	BUF_ASSERT_HELD(bp);
2848	KASSERT(bp->b_bufobj == bo,
2849	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2850	return (bp);
2851}
2852
2853/*
2854 * Get an empty, disassociated buffer of given size.  The buffer is initially
2855 * set to B_INVAL.
2856 */
2857struct buf *
2858geteblk(int size, int flags)
2859{
2860	struct buf *bp;
2861	int maxsize;
2862
2863	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2864	while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
2865		if ((flags & GB_NOWAIT_BD) &&
2866		    (curthread->td_pflags & TDP_BUFNEED) != 0)
2867			return (NULL);
2868	}
2869	allocbuf(bp, size);
2870	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2871	BUF_ASSERT_HELD(bp);
2872	return (bp);
2873}
2874
2875
2876/*
2877 * This code constitutes the buffer memory from either anonymous system
2878 * memory (in the case of non-VMIO operations) or from an associated
2879 * VM object (in the case of VMIO operations).  This code is able to
2880 * resize a buffer up or down.
2881 *
2882 * Note that this code is tricky, and has many complications to resolve
2883 * deadlock or inconsistant data situations.  Tread lightly!!!
2884 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2885 * the caller.  Calling this code willy nilly can result in the loss of data.
2886 *
2887 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2888 * B_CACHE for the non-VMIO case.
2889 */
2890
2891int
2892allocbuf(struct buf *bp, int size)
2893{
2894	int newbsize, mbsize;
2895	int i;
2896
2897	BUF_ASSERT_HELD(bp);
2898
2899	if (bp->b_kvasize < size)
2900		panic("allocbuf: buffer too small");
2901
2902	if ((bp->b_flags & B_VMIO) == 0) {
2903		caddr_t origbuf;
2904		int origbufsize;
2905		/*
2906		 * Just get anonymous memory from the kernel.  Don't
2907		 * mess with B_CACHE.
2908		 */
2909		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2910		if (bp->b_flags & B_MALLOC)
2911			newbsize = mbsize;
2912		else
2913			newbsize = round_page(size);
2914
2915		if (newbsize < bp->b_bufsize) {
2916			/*
2917			 * malloced buffers are not shrunk
2918			 */
2919			if (bp->b_flags & B_MALLOC) {
2920				if (newbsize) {
2921					bp->b_bcount = size;
2922				} else {
2923					free(bp->b_data, M_BIOBUF);
2924					if (bp->b_bufsize) {
2925						atomic_subtract_long(
2926						    &bufmallocspace,
2927						    bp->b_bufsize);
2928						bufspacewakeup();
2929						bp->b_bufsize = 0;
2930					}
2931					bp->b_saveaddr = bp->b_kvabase;
2932					bp->b_data = bp->b_saveaddr;
2933					bp->b_bcount = 0;
2934					bp->b_flags &= ~B_MALLOC;
2935				}
2936				return 1;
2937			}
2938			vm_hold_free_pages(bp, newbsize);
2939		} else if (newbsize > bp->b_bufsize) {
2940			/*
2941			 * We only use malloced memory on the first allocation.
2942			 * and revert to page-allocated memory when the buffer
2943			 * grows.
2944			 */
2945			/*
2946			 * There is a potential smp race here that could lead
2947			 * to bufmallocspace slightly passing the max.  It
2948			 * is probably extremely rare and not worth worrying
2949			 * over.
2950			 */
2951			if ( (bufmallocspace < maxbufmallocspace) &&
2952				(bp->b_bufsize == 0) &&
2953				(mbsize <= PAGE_SIZE/2)) {
2954
2955				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2956				bp->b_bufsize = mbsize;
2957				bp->b_bcount = size;
2958				bp->b_flags |= B_MALLOC;
2959				atomic_add_long(&bufmallocspace, mbsize);
2960				return 1;
2961			}
2962			origbuf = NULL;
2963			origbufsize = 0;
2964			/*
2965			 * If the buffer is growing on its other-than-first allocation,
2966			 * then we revert to the page-allocation scheme.
2967			 */
2968			if (bp->b_flags & B_MALLOC) {
2969				origbuf = bp->b_data;
2970				origbufsize = bp->b_bufsize;
2971				bp->b_data = bp->b_kvabase;
2972				if (bp->b_bufsize) {
2973					atomic_subtract_long(&bufmallocspace,
2974					    bp->b_bufsize);
2975					bufspacewakeup();
2976					bp->b_bufsize = 0;
2977				}
2978				bp->b_flags &= ~B_MALLOC;
2979				newbsize = round_page(newbsize);
2980			}
2981			vm_hold_load_pages(
2982			    bp,
2983			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2984			    (vm_offset_t) bp->b_data + newbsize);
2985			if (origbuf) {
2986				bcopy(origbuf, bp->b_data, origbufsize);
2987				free(origbuf, M_BIOBUF);
2988			}
2989		}
2990	} else {
2991		int desiredpages;
2992
2993		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2994		desiredpages = (size == 0) ? 0 :
2995			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2996
2997		if (bp->b_flags & B_MALLOC)
2998			panic("allocbuf: VMIO buffer can't be malloced");
2999		/*
3000		 * Set B_CACHE initially if buffer is 0 length or will become
3001		 * 0-length.
3002		 */
3003		if (size == 0 || bp->b_bufsize == 0)
3004			bp->b_flags |= B_CACHE;
3005
3006		if (newbsize < bp->b_bufsize) {
3007			/*
3008			 * DEV_BSIZE aligned new buffer size is less then the
3009			 * DEV_BSIZE aligned existing buffer size.  Figure out
3010			 * if we have to remove any pages.
3011			 */
3012			if (desiredpages < bp->b_npages) {
3013				vm_page_t m;
3014
3015				pmap_qremove((vm_offset_t)trunc_page(
3016				    (vm_offset_t)bp->b_data) +
3017				    (desiredpages << PAGE_SHIFT),
3018				    (bp->b_npages - desiredpages));
3019				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3020				for (i = desiredpages; i < bp->b_npages; i++) {
3021					/*
3022					 * the page is not freed here -- it
3023					 * is the responsibility of
3024					 * vnode_pager_setsize
3025					 */
3026					m = bp->b_pages[i];
3027					KASSERT(m != bogus_page,
3028					    ("allocbuf: bogus page found"));
3029					while (vm_page_sleep_if_busy(m, TRUE,
3030					    "biodep"))
3031						continue;
3032
3033					bp->b_pages[i] = NULL;
3034					vm_page_lock(m);
3035					vm_page_unwire(m, 0);
3036					vm_page_unlock(m);
3037				}
3038				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3039				bp->b_npages = desiredpages;
3040			}
3041		} else if (size > bp->b_bcount) {
3042			/*
3043			 * We are growing the buffer, possibly in a
3044			 * byte-granular fashion.
3045			 */
3046			vm_object_t obj;
3047			vm_offset_t toff;
3048			vm_offset_t tinc;
3049
3050			/*
3051			 * Step 1, bring in the VM pages from the object,
3052			 * allocating them if necessary.  We must clear
3053			 * B_CACHE if these pages are not valid for the
3054			 * range covered by the buffer.
3055			 */
3056
3057			obj = bp->b_bufobj->bo_object;
3058
3059			VM_OBJECT_LOCK(obj);
3060			while (bp->b_npages < desiredpages) {
3061				vm_page_t m;
3062
3063				/*
3064				 * We must allocate system pages since blocking
3065				 * here could interfere with paging I/O, no
3066				 * matter which process we are.
3067				 *
3068				 * We can only test VPO_BUSY here.  Blocking on
3069				 * m->busy might lead to a deadlock:
3070				 *  vm_fault->getpages->cluster_read->allocbuf
3071				 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3072				 */
3073				m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3074				    bp->b_npages, VM_ALLOC_NOBUSY |
3075				    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3076				    VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3077				    VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3078				if (m->valid == 0)
3079					bp->b_flags &= ~B_CACHE;
3080				bp->b_pages[bp->b_npages] = m;
3081				++bp->b_npages;
3082			}
3083
3084			/*
3085			 * Step 2.  We've loaded the pages into the buffer,
3086			 * we have to figure out if we can still have B_CACHE
3087			 * set.  Note that B_CACHE is set according to the
3088			 * byte-granular range ( bcount and size ), new the
3089			 * aligned range ( newbsize ).
3090			 *
3091			 * The VM test is against m->valid, which is DEV_BSIZE
3092			 * aligned.  Needless to say, the validity of the data
3093			 * needs to also be DEV_BSIZE aligned.  Note that this
3094			 * fails with NFS if the server or some other client
3095			 * extends the file's EOF.  If our buffer is resized,
3096			 * B_CACHE may remain set! XXX
3097			 */
3098
3099			toff = bp->b_bcount;
3100			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3101
3102			while ((bp->b_flags & B_CACHE) && toff < size) {
3103				vm_pindex_t pi;
3104
3105				if (tinc > (size - toff))
3106					tinc = size - toff;
3107
3108				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3109				    PAGE_SHIFT;
3110
3111				vfs_buf_test_cache(
3112				    bp,
3113				    bp->b_offset,
3114				    toff,
3115				    tinc,
3116				    bp->b_pages[pi]
3117				);
3118				toff += tinc;
3119				tinc = PAGE_SIZE;
3120			}
3121			VM_OBJECT_UNLOCK(obj);
3122
3123			/*
3124			 * Step 3, fixup the KVM pmap.  Remember that
3125			 * bp->b_data is relative to bp->b_offset, but
3126			 * bp->b_offset may be offset into the first page.
3127			 */
3128
3129			bp->b_data = (caddr_t)
3130			    trunc_page((vm_offset_t)bp->b_data);
3131			pmap_qenter(
3132			    (vm_offset_t)bp->b_data,
3133			    bp->b_pages,
3134			    bp->b_npages
3135			);
3136
3137			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3138			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
3139		}
3140	}
3141	if (newbsize < bp->b_bufsize)
3142		bufspacewakeup();
3143	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3144	bp->b_bcount = size;		/* requested buffer size	*/
3145	return 1;
3146}
3147
3148void
3149biodone(struct bio *bp)
3150{
3151	struct mtx *mtxp;
3152	void (*done)(struct bio *);
3153
3154	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3155	mtx_lock(mtxp);
3156	bp->bio_flags |= BIO_DONE;
3157	done = bp->bio_done;
3158	if (done == NULL)
3159		wakeup(bp);
3160	mtx_unlock(mtxp);
3161	if (done != NULL)
3162		done(bp);
3163}
3164
3165/*
3166 * Wait for a BIO to finish.
3167 *
3168 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3169 * case is not yet clear.
3170 */
3171int
3172biowait(struct bio *bp, const char *wchan)
3173{
3174	struct mtx *mtxp;
3175
3176	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3177	mtx_lock(mtxp);
3178	while ((bp->bio_flags & BIO_DONE) == 0)
3179		msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3180	mtx_unlock(mtxp);
3181	if (bp->bio_error != 0)
3182		return (bp->bio_error);
3183	if (!(bp->bio_flags & BIO_ERROR))
3184		return (0);
3185	return (EIO);
3186}
3187
3188void
3189biofinish(struct bio *bp, struct devstat *stat, int error)
3190{
3191
3192	if (error) {
3193		bp->bio_error = error;
3194		bp->bio_flags |= BIO_ERROR;
3195	}
3196	if (stat != NULL)
3197		devstat_end_transaction_bio(stat, bp);
3198	biodone(bp);
3199}
3200
3201/*
3202 *	bufwait:
3203 *
3204 *	Wait for buffer I/O completion, returning error status.  The buffer
3205 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3206 *	error and cleared.
3207 */
3208int
3209bufwait(struct buf *bp)
3210{
3211	if (bp->b_iocmd == BIO_READ)
3212		bwait(bp, PRIBIO, "biord");
3213	else
3214		bwait(bp, PRIBIO, "biowr");
3215	if (bp->b_flags & B_EINTR) {
3216		bp->b_flags &= ~B_EINTR;
3217		return (EINTR);
3218	}
3219	if (bp->b_ioflags & BIO_ERROR) {
3220		return (bp->b_error ? bp->b_error : EIO);
3221	} else {
3222		return (0);
3223	}
3224}
3225
3226 /*
3227  * Call back function from struct bio back up to struct buf.
3228  */
3229static void
3230bufdonebio(struct bio *bip)
3231{
3232	struct buf *bp;
3233
3234	bp = bip->bio_caller2;
3235	bp->b_resid = bp->b_bcount - bip->bio_completed;
3236	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3237	bp->b_ioflags = bip->bio_flags;
3238	bp->b_error = bip->bio_error;
3239	if (bp->b_error)
3240		bp->b_ioflags |= BIO_ERROR;
3241	bufdone(bp);
3242	g_destroy_bio(bip);
3243}
3244
3245void
3246dev_strategy(struct cdev *dev, struct buf *bp)
3247{
3248	struct cdevsw *csw;
3249	struct bio *bip;
3250	int ref;
3251
3252	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3253		panic("b_iocmd botch");
3254	for (;;) {
3255		bip = g_new_bio();
3256		if (bip != NULL)
3257			break;
3258		/* Try again later */
3259		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3260	}
3261	bip->bio_cmd = bp->b_iocmd;
3262	bip->bio_offset = bp->b_iooffset;
3263	bip->bio_length = bp->b_bcount;
3264	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3265	bip->bio_data = bp->b_data;
3266	bip->bio_done = bufdonebio;
3267	bip->bio_caller2 = bp;
3268	bip->bio_dev = dev;
3269	KASSERT(dev->si_refcount > 0,
3270	    ("dev_strategy on un-referenced struct cdev *(%s)",
3271	    devtoname(dev)));
3272	csw = dev_refthread(dev, &ref);
3273	if (csw == NULL) {
3274		g_destroy_bio(bip);
3275		bp->b_error = ENXIO;
3276		bp->b_ioflags = BIO_ERROR;
3277		bufdone(bp);
3278		return;
3279	}
3280	(*csw->d_strategy)(bip);
3281	dev_relthread(dev, ref);
3282}
3283
3284/*
3285 *	bufdone:
3286 *
3287 *	Finish I/O on a buffer, optionally calling a completion function.
3288 *	This is usually called from an interrupt so process blocking is
3289 *	not allowed.
3290 *
3291 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3292 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3293 *	assuming B_INVAL is clear.
3294 *
3295 *	For the VMIO case, we set B_CACHE if the op was a read and no
3296 *	read error occured, or if the op was a write.  B_CACHE is never
3297 *	set if the buffer is invalid or otherwise uncacheable.
3298 *
3299 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3300 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3301 *	in the biodone routine.
3302 */
3303void
3304bufdone(struct buf *bp)
3305{
3306	struct bufobj *dropobj;
3307	void    (*biodone)(struct buf *);
3308
3309	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3310	dropobj = NULL;
3311
3312	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3313	BUF_ASSERT_HELD(bp);
3314
3315	runningbufwakeup(bp);
3316	if (bp->b_iocmd == BIO_WRITE)
3317		dropobj = bp->b_bufobj;
3318	/* call optional completion function if requested */
3319	if (bp->b_iodone != NULL) {
3320		biodone = bp->b_iodone;
3321		bp->b_iodone = NULL;
3322		(*biodone) (bp);
3323		if (dropobj)
3324			bufobj_wdrop(dropobj);
3325		return;
3326	}
3327
3328	bufdone_finish(bp);
3329
3330	if (dropobj)
3331		bufobj_wdrop(dropobj);
3332}
3333
3334void
3335bufdone_finish(struct buf *bp)
3336{
3337	BUF_ASSERT_HELD(bp);
3338
3339	if (!LIST_EMPTY(&bp->b_dep))
3340		buf_complete(bp);
3341
3342	if (bp->b_flags & B_VMIO) {
3343		vm_ooffset_t foff;
3344		vm_page_t m;
3345		vm_object_t obj;
3346		struct vnode *vp;
3347		int bogus, i, iosize;
3348
3349		obj = bp->b_bufobj->bo_object;
3350		KASSERT(obj->paging_in_progress >= bp->b_npages,
3351		    ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3352		    obj->paging_in_progress, bp->b_npages));
3353
3354		vp = bp->b_vp;
3355		KASSERT(vp->v_holdcnt > 0,
3356		    ("biodone_finish: vnode %p has zero hold count", vp));
3357		KASSERT(vp->v_object != NULL,
3358		    ("biodone_finish: vnode %p has no vm_object", vp));
3359
3360		foff = bp->b_offset;
3361		KASSERT(bp->b_offset != NOOFFSET,
3362		    ("biodone_finish: bp %p has no buffer offset", bp));
3363
3364		/*
3365		 * Set B_CACHE if the op was a normal read and no error
3366		 * occured.  B_CACHE is set for writes in the b*write()
3367		 * routines.
3368		 */
3369		iosize = bp->b_bcount - bp->b_resid;
3370		if (bp->b_iocmd == BIO_READ &&
3371		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3372		    !(bp->b_ioflags & BIO_ERROR)) {
3373			bp->b_flags |= B_CACHE;
3374		}
3375		bogus = 0;
3376		VM_OBJECT_LOCK(obj);
3377		for (i = 0; i < bp->b_npages; i++) {
3378			int bogusflag = 0;
3379			int resid;
3380
3381			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3382			if (resid > iosize)
3383				resid = iosize;
3384
3385			/*
3386			 * cleanup bogus pages, restoring the originals
3387			 */
3388			m = bp->b_pages[i];
3389			if (m == bogus_page) {
3390				bogus = bogusflag = 1;
3391				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3392				if (m == NULL)
3393					panic("biodone: page disappeared!");
3394				bp->b_pages[i] = m;
3395			}
3396			KASSERT(OFF_TO_IDX(foff) == m->pindex,
3397			    ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3398			    (intmax_t)foff, (uintmax_t)m->pindex));
3399
3400			/*
3401			 * In the write case, the valid and clean bits are
3402			 * already changed correctly ( see bdwrite() ), so we
3403			 * only need to do this here in the read case.
3404			 */
3405			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3406				KASSERT((m->dirty & vm_page_bits(foff &
3407				    PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3408				    " page %p has unexpected dirty bits", m));
3409				vfs_page_set_valid(bp, foff, m);
3410			}
3411
3412			vm_page_io_finish(m);
3413			vm_object_pip_subtract(obj, 1);
3414			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3415			iosize -= resid;
3416		}
3417		vm_object_pip_wakeupn(obj, 0);
3418		VM_OBJECT_UNLOCK(obj);
3419		if (bogus)
3420			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3421			    bp->b_pages, bp->b_npages);
3422	}
3423
3424	/*
3425	 * For asynchronous completions, release the buffer now. The brelse
3426	 * will do a wakeup there if necessary - so no need to do a wakeup
3427	 * here in the async case. The sync case always needs to do a wakeup.
3428	 */
3429
3430	if (bp->b_flags & B_ASYNC) {
3431		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3432			brelse(bp);
3433		else
3434			bqrelse(bp);
3435	} else
3436		bdone(bp);
3437}
3438
3439/*
3440 * This routine is called in lieu of iodone in the case of
3441 * incomplete I/O.  This keeps the busy status for pages
3442 * consistant.
3443 */
3444void
3445vfs_unbusy_pages(struct buf *bp)
3446{
3447	int i;
3448	vm_object_t obj;
3449	vm_page_t m;
3450
3451	runningbufwakeup(bp);
3452	if (!(bp->b_flags & B_VMIO))
3453		return;
3454
3455	obj = bp->b_bufobj->bo_object;
3456	VM_OBJECT_LOCK(obj);
3457	for (i = 0; i < bp->b_npages; i++) {
3458		m = bp->b_pages[i];
3459		if (m == bogus_page) {
3460			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3461			if (!m)
3462				panic("vfs_unbusy_pages: page missing\n");
3463			bp->b_pages[i] = m;
3464			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3465			    bp->b_pages, bp->b_npages);
3466		}
3467		vm_object_pip_subtract(obj, 1);
3468		vm_page_io_finish(m);
3469	}
3470	vm_object_pip_wakeupn(obj, 0);
3471	VM_OBJECT_UNLOCK(obj);
3472}
3473
3474/*
3475 * vfs_page_set_valid:
3476 *
3477 *	Set the valid bits in a page based on the supplied offset.   The
3478 *	range is restricted to the buffer's size.
3479 *
3480 *	This routine is typically called after a read completes.
3481 */
3482static void
3483vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3484{
3485	vm_ooffset_t eoff;
3486
3487	/*
3488	 * Compute the end offset, eoff, such that [off, eoff) does not span a
3489	 * page boundary and eoff is not greater than the end of the buffer.
3490	 * The end of the buffer, in this case, is our file EOF, not the
3491	 * allocation size of the buffer.
3492	 */
3493	eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3494	if (eoff > bp->b_offset + bp->b_bcount)
3495		eoff = bp->b_offset + bp->b_bcount;
3496
3497	/*
3498	 * Set valid range.  This is typically the entire buffer and thus the
3499	 * entire page.
3500	 */
3501	if (eoff > off)
3502		vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3503}
3504
3505/*
3506 * vfs_page_set_validclean:
3507 *
3508 *	Set the valid bits and clear the dirty bits in a page based on the
3509 *	supplied offset.   The range is restricted to the buffer's size.
3510 */
3511static void
3512vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3513{
3514	vm_ooffset_t soff, eoff;
3515
3516	/*
3517	 * Start and end offsets in buffer.  eoff - soff may not cross a
3518	 * page boundry or cross the end of the buffer.  The end of the
3519	 * buffer, in this case, is our file EOF, not the allocation size
3520	 * of the buffer.
3521	 */
3522	soff = off;
3523	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3524	if (eoff > bp->b_offset + bp->b_bcount)
3525		eoff = bp->b_offset + bp->b_bcount;
3526
3527	/*
3528	 * Set valid range.  This is typically the entire buffer and thus the
3529	 * entire page.
3530	 */
3531	if (eoff > soff) {
3532		vm_page_set_validclean(
3533		    m,
3534		   (vm_offset_t) (soff & PAGE_MASK),
3535		   (vm_offset_t) (eoff - soff)
3536		);
3537	}
3538}
3539
3540/*
3541 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
3542 * any page is busy, drain the flag.
3543 */
3544static void
3545vfs_drain_busy_pages(struct buf *bp)
3546{
3547	vm_page_t m;
3548	int i, last_busied;
3549
3550	VM_OBJECT_LOCK_ASSERT(bp->b_bufobj->bo_object, MA_OWNED);
3551	last_busied = 0;
3552	for (i = 0; i < bp->b_npages; i++) {
3553		m = bp->b_pages[i];
3554		if ((m->oflags & VPO_BUSY) != 0) {
3555			for (; last_busied < i; last_busied++)
3556				vm_page_busy(bp->b_pages[last_busied]);
3557			while ((m->oflags & VPO_BUSY) != 0)
3558				vm_page_sleep(m, "vbpage");
3559		}
3560	}
3561	for (i = 0; i < last_busied; i++)
3562		vm_page_wakeup(bp->b_pages[i]);
3563}
3564
3565/*
3566 * This routine is called before a device strategy routine.
3567 * It is used to tell the VM system that paging I/O is in
3568 * progress, and treat the pages associated with the buffer
3569 * almost as being VPO_BUSY.  Also the object paging_in_progress
3570 * flag is handled to make sure that the object doesn't become
3571 * inconsistant.
3572 *
3573 * Since I/O has not been initiated yet, certain buffer flags
3574 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3575 * and should be ignored.
3576 */
3577void
3578vfs_busy_pages(struct buf *bp, int clear_modify)
3579{
3580	int i, bogus;
3581	vm_object_t obj;
3582	vm_ooffset_t foff;
3583	vm_page_t m;
3584
3585	if (!(bp->b_flags & B_VMIO))
3586		return;
3587
3588	obj = bp->b_bufobj->bo_object;
3589	foff = bp->b_offset;
3590	KASSERT(bp->b_offset != NOOFFSET,
3591	    ("vfs_busy_pages: no buffer offset"));
3592	VM_OBJECT_LOCK(obj);
3593	vfs_drain_busy_pages(bp);
3594	if (bp->b_bufsize != 0)
3595		vfs_setdirty_locked_object(bp);
3596	bogus = 0;
3597	for (i = 0; i < bp->b_npages; i++) {
3598		m = bp->b_pages[i];
3599
3600		if ((bp->b_flags & B_CLUSTER) == 0) {
3601			vm_object_pip_add(obj, 1);
3602			vm_page_io_start(m);
3603		}
3604		/*
3605		 * When readying a buffer for a read ( i.e
3606		 * clear_modify == 0 ), it is important to do
3607		 * bogus_page replacement for valid pages in
3608		 * partially instantiated buffers.  Partially
3609		 * instantiated buffers can, in turn, occur when
3610		 * reconstituting a buffer from its VM backing store
3611		 * base.  We only have to do this if B_CACHE is
3612		 * clear ( which causes the I/O to occur in the
3613		 * first place ).  The replacement prevents the read
3614		 * I/O from overwriting potentially dirty VM-backed
3615		 * pages.  XXX bogus page replacement is, uh, bogus.
3616		 * It may not work properly with small-block devices.
3617		 * We need to find a better way.
3618		 */
3619		if (clear_modify) {
3620			pmap_remove_write(m);
3621			vfs_page_set_validclean(bp, foff, m);
3622		} else if (m->valid == VM_PAGE_BITS_ALL &&
3623		    (bp->b_flags & B_CACHE) == 0) {
3624			bp->b_pages[i] = bogus_page;
3625			bogus++;
3626		}
3627		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3628	}
3629	VM_OBJECT_UNLOCK(obj);
3630	if (bogus)
3631		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3632		    bp->b_pages, bp->b_npages);
3633}
3634
3635/*
3636 *	vfs_bio_set_valid:
3637 *
3638 *	Set the range within the buffer to valid.  The range is
3639 *	relative to the beginning of the buffer, b_offset.  Note that
3640 *	b_offset itself may be offset from the beginning of the first
3641 *	page.
3642 */
3643void
3644vfs_bio_set_valid(struct buf *bp, int base, int size)
3645{
3646	int i, n;
3647	vm_page_t m;
3648
3649	if (!(bp->b_flags & B_VMIO))
3650		return;
3651
3652	/*
3653	 * Fixup base to be relative to beginning of first page.
3654	 * Set initial n to be the maximum number of bytes in the
3655	 * first page that can be validated.
3656	 */
3657	base += (bp->b_offset & PAGE_MASK);
3658	n = PAGE_SIZE - (base & PAGE_MASK);
3659
3660	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3661	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3662		m = bp->b_pages[i];
3663		if (n > size)
3664			n = size;
3665		vm_page_set_valid_range(m, base & PAGE_MASK, n);
3666		base += n;
3667		size -= n;
3668		n = PAGE_SIZE;
3669	}
3670	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3671}
3672
3673/*
3674 *	vfs_bio_clrbuf:
3675 *
3676 *	If the specified buffer is a non-VMIO buffer, clear the entire
3677 *	buffer.  If the specified buffer is a VMIO buffer, clear and
3678 *	validate only the previously invalid portions of the buffer.
3679 *	This routine essentially fakes an I/O, so we need to clear
3680 *	BIO_ERROR and B_INVAL.
3681 *
3682 *	Note that while we only theoretically need to clear through b_bcount,
3683 *	we go ahead and clear through b_bufsize.
3684 */
3685void
3686vfs_bio_clrbuf(struct buf *bp)
3687{
3688	int i, j, mask;
3689	caddr_t sa, ea;
3690
3691	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3692		clrbuf(bp);
3693		return;
3694	}
3695	bp->b_flags &= ~B_INVAL;
3696	bp->b_ioflags &= ~BIO_ERROR;
3697	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3698	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3699	    (bp->b_offset & PAGE_MASK) == 0) {
3700		if (bp->b_pages[0] == bogus_page)
3701			goto unlock;
3702		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3703		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3704		if ((bp->b_pages[0]->valid & mask) == mask)
3705			goto unlock;
3706		if ((bp->b_pages[0]->valid & mask) == 0) {
3707			bzero(bp->b_data, bp->b_bufsize);
3708			bp->b_pages[0]->valid |= mask;
3709			goto unlock;
3710		}
3711	}
3712	ea = sa = bp->b_data;
3713	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3714		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3715		ea = (caddr_t)(vm_offset_t)ulmin(
3716		    (u_long)(vm_offset_t)ea,
3717		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3718		if (bp->b_pages[i] == bogus_page)
3719			continue;
3720		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3721		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3722		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3723		if ((bp->b_pages[i]->valid & mask) == mask)
3724			continue;
3725		if ((bp->b_pages[i]->valid & mask) == 0)
3726			bzero(sa, ea - sa);
3727		else {
3728			for (; sa < ea; sa += DEV_BSIZE, j++) {
3729				if ((bp->b_pages[i]->valid & (1 << j)) == 0)
3730					bzero(sa, DEV_BSIZE);
3731			}
3732		}
3733		bp->b_pages[i]->valid |= mask;
3734	}
3735unlock:
3736	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3737	bp->b_resid = 0;
3738}
3739
3740/*
3741 * vm_hold_load_pages and vm_hold_free_pages get pages into
3742 * a buffers address space.  The pages are anonymous and are
3743 * not associated with a file object.
3744 */
3745static void
3746vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3747{
3748	vm_offset_t pg;
3749	vm_page_t p;
3750	int index;
3751
3752	to = round_page(to);
3753	from = round_page(from);
3754	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3755
3756	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3757tryagain:
3758		/*
3759		 * note: must allocate system pages since blocking here
3760		 * could interfere with paging I/O, no matter which
3761		 * process we are.
3762		 */
3763		p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
3764		    VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
3765		if (p == NULL) {
3766			VM_WAIT;
3767			goto tryagain;
3768		}
3769		pmap_qenter(pg, &p, 1);
3770		bp->b_pages[index] = p;
3771	}
3772	bp->b_npages = index;
3773}
3774
3775/* Return pages associated with this buf to the vm system */
3776static void
3777vm_hold_free_pages(struct buf *bp, int newbsize)
3778{
3779	vm_offset_t from;
3780	vm_page_t p;
3781	int index, newnpages;
3782
3783	from = round_page((vm_offset_t)bp->b_data + newbsize);
3784	newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3785	if (bp->b_npages > newnpages)
3786		pmap_qremove(from, bp->b_npages - newnpages);
3787	for (index = newnpages; index < bp->b_npages; index++) {
3788		p = bp->b_pages[index];
3789		bp->b_pages[index] = NULL;
3790		if (p->busy != 0)
3791			printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3792			    (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
3793		p->wire_count--;
3794		vm_page_free(p);
3795		atomic_subtract_int(&cnt.v_wire_count, 1);
3796	}
3797	bp->b_npages = newnpages;
3798}
3799
3800/*
3801 * Map an IO request into kernel virtual address space.
3802 *
3803 * All requests are (re)mapped into kernel VA space.
3804 * Notice that we use b_bufsize for the size of the buffer
3805 * to be mapped.  b_bcount might be modified by the driver.
3806 *
3807 * Note that even if the caller determines that the address space should
3808 * be valid, a race or a smaller-file mapped into a larger space may
3809 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3810 * check the return value.
3811 */
3812int
3813vmapbuf(struct buf *bp)
3814{
3815	caddr_t kva;
3816	vm_prot_t prot;
3817	int pidx;
3818
3819	if (bp->b_bufsize < 0)
3820		return (-1);
3821	prot = VM_PROT_READ;
3822	if (bp->b_iocmd == BIO_READ)
3823		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3824	if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
3825	    (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
3826	    btoc(MAXPHYS))) < 0)
3827		return (-1);
3828	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3829
3830	kva = bp->b_saveaddr;
3831	bp->b_npages = pidx;
3832	bp->b_saveaddr = bp->b_data;
3833	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3834	return(0);
3835}
3836
3837/*
3838 * Free the io map PTEs associated with this IO operation.
3839 * We also invalidate the TLB entries and restore the original b_addr.
3840 */
3841void
3842vunmapbuf(struct buf *bp)
3843{
3844	int npages;
3845
3846	npages = bp->b_npages;
3847	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3848	vm_page_unhold_pages(bp->b_pages, npages);
3849
3850	bp->b_data = bp->b_saveaddr;
3851}
3852
3853void
3854bdone(struct buf *bp)
3855{
3856	struct mtx *mtxp;
3857
3858	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3859	mtx_lock(mtxp);
3860	bp->b_flags |= B_DONE;
3861	wakeup(bp);
3862	mtx_unlock(mtxp);
3863}
3864
3865void
3866bwait(struct buf *bp, u_char pri, const char *wchan)
3867{
3868	struct mtx *mtxp;
3869
3870	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3871	mtx_lock(mtxp);
3872	while ((bp->b_flags & B_DONE) == 0)
3873		msleep(bp, mtxp, pri, wchan, 0);
3874	mtx_unlock(mtxp);
3875}
3876
3877int
3878bufsync(struct bufobj *bo, int waitfor)
3879{
3880
3881	return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
3882}
3883
3884void
3885bufstrategy(struct bufobj *bo, struct buf *bp)
3886{
3887	int i = 0;
3888	struct vnode *vp;
3889
3890	vp = bp->b_vp;
3891	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3892	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3893	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3894	i = VOP_STRATEGY(vp, bp);
3895	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3896}
3897
3898void
3899bufobj_wrefl(struct bufobj *bo)
3900{
3901
3902	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3903	ASSERT_BO_LOCKED(bo);
3904	bo->bo_numoutput++;
3905}
3906
3907void
3908bufobj_wref(struct bufobj *bo)
3909{
3910
3911	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3912	BO_LOCK(bo);
3913	bo->bo_numoutput++;
3914	BO_UNLOCK(bo);
3915}
3916
3917void
3918bufobj_wdrop(struct bufobj *bo)
3919{
3920
3921	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3922	BO_LOCK(bo);
3923	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3924	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3925		bo->bo_flag &= ~BO_WWAIT;
3926		wakeup(&bo->bo_numoutput);
3927	}
3928	BO_UNLOCK(bo);
3929}
3930
3931int
3932bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3933{
3934	int error;
3935
3936	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3937	ASSERT_BO_LOCKED(bo);
3938	error = 0;
3939	while (bo->bo_numoutput) {
3940		bo->bo_flag |= BO_WWAIT;
3941		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3942		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3943		if (error)
3944			break;
3945	}
3946	return (error);
3947}
3948
3949void
3950bpin(struct buf *bp)
3951{
3952	struct mtx *mtxp;
3953
3954	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3955	mtx_lock(mtxp);
3956	bp->b_pin_count++;
3957	mtx_unlock(mtxp);
3958}
3959
3960void
3961bunpin(struct buf *bp)
3962{
3963	struct mtx *mtxp;
3964
3965	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3966	mtx_lock(mtxp);
3967	if (--bp->b_pin_count == 0)
3968		wakeup(bp);
3969	mtx_unlock(mtxp);
3970}
3971
3972void
3973bunpin_wait(struct buf *bp)
3974{
3975	struct mtx *mtxp;
3976
3977	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3978	mtx_lock(mtxp);
3979	while (bp->b_pin_count > 0)
3980		msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
3981	mtx_unlock(mtxp);
3982}
3983
3984#include "opt_ddb.h"
3985#ifdef DDB
3986#include <ddb/ddb.h>
3987
3988/* DDB command to show buffer data */
3989DB_SHOW_COMMAND(buffer, db_show_buffer)
3990{
3991	/* get args */
3992	struct buf *bp = (struct buf *)addr;
3993
3994	if (!have_addr) {
3995		db_printf("usage: show buffer <addr>\n");
3996		return;
3997	}
3998
3999	db_printf("buf at %p\n", bp);
4000	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4001	db_printf(
4002	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4003	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4004	    "b_dep = %p\n",
4005	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4006	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4007	    (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4008	if (bp->b_npages) {
4009		int i;
4010		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4011		for (i = 0; i < bp->b_npages; i++) {
4012			vm_page_t m;
4013			m = bp->b_pages[i];
4014			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4015			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4016			if ((i + 1) < bp->b_npages)
4017				db_printf(",");
4018		}
4019		db_printf("\n");
4020	}
4021	db_printf(" ");
4022	BUF_LOCKPRINTINFO(bp);
4023}
4024
4025DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4026{
4027	struct buf *bp;
4028	int i;
4029
4030	for (i = 0; i < nbuf; i++) {
4031		bp = &buf[i];
4032		if (BUF_ISLOCKED(bp)) {
4033			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4034			db_printf("\n");
4035		}
4036	}
4037}
4038
4039DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4040{
4041	struct vnode *vp;
4042	struct buf *bp;
4043
4044	if (!have_addr) {
4045		db_printf("usage: show vnodebufs <addr>\n");
4046		return;
4047	}
4048	vp = (struct vnode *)addr;
4049	db_printf("Clean buffers:\n");
4050	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4051		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4052		db_printf("\n");
4053	}
4054	db_printf("Dirty buffers:\n");
4055	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4056		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4057		db_printf("\n");
4058	}
4059}
4060
4061DB_COMMAND(countfreebufs, db_coundfreebufs)
4062{
4063	struct buf *bp;
4064	int i, used = 0, nfree = 0;
4065
4066	if (have_addr) {
4067		db_printf("usage: countfreebufs\n");
4068		return;
4069	}
4070
4071	for (i = 0; i < nbuf; i++) {
4072		bp = &buf[i];
4073		if ((bp->b_vflags & BV_INFREECNT) != 0)
4074			nfree++;
4075		else
4076			used++;
4077	}
4078
4079	db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4080	    nfree + used);
4081	db_printf("numfreebuffers is %d\n", numfreebuffers);
4082}
4083#endif /* DDB */
4084