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