vfs_bio.c revision 140721
1169689Skan/*-
2169689Skan * Copyright (c) 2004 Poul-Henning Kamp
3169689Skan * Copyright (c) 1994,1997 John S. Dyson
4169689Skan * All rights reserved.
5169689Skan *
6169689Skan * Redistribution and use in source and binary forms, with or without
7169689Skan * modification, are permitted provided that the following conditions
8169689Skan * are met:
9169689Skan * 1. Redistributions of source code must retain the above copyright
10169689Skan *    notice, this list of conditions and the following disclaimer.
11169689Skan * 2. Redistributions in binary form must reproduce the above copyright
12169689Skan *    notice, this list of conditions and the following disclaimer in the
13169689Skan *    documentation and/or other materials provided with the distribution.
14169689Skan *
15169689Skan * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16169689Skan * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17169689Skan * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18169689Skan * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19169689Skan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20169689Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21169689Skan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22169689Skan * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23169689Skan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24169689Skan * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25169689Skan * SUCH DAMAGE.
26169689Skan */
27169689Skan
28132718Skan/*
2990075Sobrien * this file contains a new buffer I/O scheme implementing a coherent
3090075Sobrien * VM object and buffer cache scheme.  Pains have been taken to make
3190075Sobrien * sure that the performance degradation associated with schemes such
3290075Sobrien * as this is not realized.
3390075Sobrien *
3490075Sobrien * Author:  John S. Dyson
35132718Skan * Significant help during the development and debugging phases
36132718Skan * had been provided by David Greenman, also of the FreeBSD core team.
3790075Sobrien *
3890075Sobrien * see man buf(9) for more info.
3990075Sobrien */
40132718Skan
4190075Sobrien#include <sys/cdefs.h>
42132718Skan__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 140721 2005-01-24 10:47:04Z jeff $");
43132718Skan
4490075Sobrien#include <sys/param.h>
4590075Sobrien#include <sys/systm.h>
4690075Sobrien#include <sys/bio.h>
4790075Sobrien#include <sys/conf.h>
4890075Sobrien#include <sys/buf.h>
4990075Sobrien#include <sys/devicestat.h>
5090075Sobrien#include <sys/eventhandler.h>
5190075Sobrien#include <sys/lock.h>
5290075Sobrien#include <sys/malloc.h>
5390075Sobrien#include <sys/mount.h>
5490075Sobrien#include <sys/mutex.h>
5590075Sobrien#include <sys/kernel.h>
5690075Sobrien#include <sys/kthread.h>
5790075Sobrien#include <sys/proc.h>
5890075Sobrien#include <sys/resourcevar.h>
5990075Sobrien#include <sys/sysctl.h>
6090075Sobrien#include <sys/vmmeter.h>
6190075Sobrien#include <sys/vnode.h>
6290075Sobrien#include <geom/geom.h>
6390075Sobrien#include <vm/vm.h>
6490075Sobrien#include <vm/vm_param.h>
6590075Sobrien#include <vm/vm_kern.h>
6690075Sobrien#include <vm/vm_pageout.h>
6790075Sobrien#include <vm/vm_page.h>
6890075Sobrien#include <vm/vm_object.h>
6990075Sobrien#include <vm/vm_extern.h>
7090075Sobrien#include <vm/vm_map.h>
71132718Skan#include "opt_directio.h"
7290075Sobrien#include "opt_swap.h"
7390075Sobrien
7490075Sobrienstatic MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
7590075Sobrien
7690075Sobrienstruct	bio_ops bioops;		/* I/O operation notification */
7790075Sobrien
7890075Sobrienstruct	buf_ops buf_ops_bio = {
7990075Sobrien	.bop_name	=	"buf_ops_bio",
8090075Sobrien	.bop_write	=	bufwrite,
8190075Sobrien	.bop_strategy	=	bufstrategy,
8290075Sobrien	.bop_sync	=	bufsync,
8390075Sobrien};
8490075Sobrien
8590075Sobrien/*
8690075Sobrien * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
8790075Sobrien * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
8890075Sobrien */
8990075Sobrienstruct buf *buf;		/* buffer header pool */
9090075Sobrien
9190075Sobrienstatic struct proc *bufdaemonproc;
9290075Sobrien
9390075Sobrienstatic int inmem(struct vnode *vp, daddr_t blkno);
9490075Sobrienstatic void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
9590075Sobrien		vm_offset_t to);
9690075Sobrienstatic void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
9790075Sobrien		vm_offset_t to);
9890075Sobrienstatic void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
9990075Sobrien			       int pageno, vm_page_t m);
10090075Sobrienstatic void vfs_clean_pages(struct buf *bp);
10190075Sobrienstatic void vfs_setdirty(struct buf *bp);
10290075Sobrienstatic void vfs_vmio_release(struct buf *bp);
10390075Sobrienstatic void vfs_backgroundwritedone(struct buf *bp);
10490075Sobrienstatic int vfs_bio_clcheck(struct vnode *vp, int size,
10590075Sobrien		daddr_t lblkno, daddr_t blkno);
10690075Sobrienstatic int flushbufqueues(int flushdeps);
10790075Sobrienstatic void buf_daemon(void);
10890075Sobrienvoid bremfreel(struct buf *bp);
10990075Sobrien
11090075Sobrienint vmiodirenable = TRUE;
11190075SobrienSYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
11290075Sobrien    "Use the VM system for directory writes");
11390075Sobrienint runningbufspace;
11490075SobrienSYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
11590075Sobrien    "Amount of presently outstanding async buffer io");
11690075Sobrienstatic int bufspace;
11790075SobrienSYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
11890075Sobrien    "KVA memory used for bufs");
11990075Sobrienstatic int maxbufspace;
12090075SobrienSYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
12190075Sobrien    "Maximum allowed value of bufspace (including buf_daemon)");
12290075Sobrienstatic int bufmallocspace;
12390075SobrienSYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
12490075Sobrien    "Amount of malloced memory for buffers");
12590075Sobrienstatic int maxbufmallocspace;
12690075SobrienSYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
12790075Sobrien    "Maximum amount of malloced memory for buffers");
12890075Sobrienstatic int lobufspace;
12990075SobrienSYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
13090075Sobrien    "Minimum amount of buffers we want to have");
13190075Sobrienstatic int hibufspace;
13290075SobrienSYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
13390075Sobrien    "Maximum allowed value of bufspace (excluding buf_daemon)");
13490075Sobrienstatic int bufreusecnt;
13590075SobrienSYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
13690075Sobrien    "Number of times we have reused a buffer");
13790075Sobrienstatic int buffreekvacnt;
13890075SobrienSYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
13990075Sobrien    "Number of times we have freed the KVA space from some buffer");
14090075Sobrienstatic int bufdefragcnt;
14190075SobrienSYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
14290075Sobrien    "Number of times we have had to repeat buffer allocation to defragment");
14390075Sobrienstatic int lorunningspace;
14490075SobrienSYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
14590075Sobrien    "Minimum preferred space used for in-progress I/O");
14690075Sobrienstatic int hirunningspace;
14790075SobrienSYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
14890075Sobrien    "Maximum amount of space to use for in-progress I/O");
14990075Sobrienstatic int dirtybufferflushes;
15090075SobrienSYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
15190075Sobrien    0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
15290075Sobrienstatic int altbufferflushes;
15390075SobrienSYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
15490075Sobrien    0, "Number of fsync flushes to limit dirty buffers");
15590075Sobrienstatic int recursiveflushes;
15690075SobrienSYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
15790075Sobrien    0, "Number of flushes skipped due to being recursive");
15890075Sobrienstatic int numdirtybuffers;
15990075SobrienSYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
16090075Sobrien    "Number of buffers that are dirty (has unwritten changes) at the moment");
16190075Sobrienstatic int lodirtybuffers;
16290075SobrienSYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
16390075Sobrien    "How many buffers we want to have free before bufdaemon can sleep");
16490075Sobrienstatic int hidirtybuffers;
16590075SobrienSYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
16690075Sobrien    "When the number of dirty buffers is considered severe");
16790075Sobrienstatic int dirtybufthresh;
16890075SobrienSYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
169169689Skan    0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
170169689Skanstatic int numfreebuffers;
17190075SobrienSYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
17290075Sobrien    "Number of free buffers");
17390075Sobrienstatic int lofreebuffers;
17490075SobrienSYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
175169689Skan   "XXX Unused");
17690075Sobrienstatic int hifreebuffers;
17790075SobrienSYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
17890075Sobrien   "XXX Complicatedly unused");
17990075Sobrienstatic int getnewbufcalls;
18090075SobrienSYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
18190075Sobrien   "Number of calls to getnewbuf");
18290075Sobrienstatic int getnewbufrestarts;
18390075SobrienSYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
18490075Sobrien    "Number of times getnewbuf has had to restart a buffer aquisition");
18590075Sobrienstatic int dobkgrdwrite = 1;
18690075SobrienSYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
18790075Sobrien    "Do background writes (honoring the BV_BKGRDWRITE flag)?");
18890075Sobrien
18990075Sobrien/*
19090075Sobrien * Wakeup point for bufdaemon, as well as indicator of whether it is already
19190075Sobrien * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
19290075Sobrien * is idling.
19390075Sobrien */
19490075Sobrienstatic int bd_request;
19590075Sobrien
19690075Sobrien/*
19790075Sobrien * This lock synchronizes access to bd_request.
19890075Sobrien */
19990075Sobrienstatic struct mtx bdlock;
20090075Sobrien
20190075Sobrien/*
20290075Sobrien * bogus page -- for I/O to/from partially complete buffers
20390075Sobrien * this is a temporary solution to the problem, but it is not
20490075Sobrien * really that bad.  it would be better to split the buffer
20590075Sobrien * for input in the case of buffers partially already in memory,
20690075Sobrien * but the code is intricate enough already.
20790075Sobrien */
20890075Sobrienvm_page_t bogus_page;
20990075Sobrien
21090075Sobrien/*
21190075Sobrien * Synchronization (sleep/wakeup) variable for active buffer space requests.
21290075Sobrien * Set when wait starts, cleared prior to wakeup().
21390075Sobrien * Used in runningbufwakeup() and waitrunningbufspace().
21490075Sobrien */
21590075Sobrienstatic int runningbufreq;
21690075Sobrien
21790075Sobrien/*
21890075Sobrien * This lock protects the runningbufreq and synchronizes runningbufwakeup and
21990075Sobrien * waitrunningbufspace().
22090075Sobrien */
22190075Sobrienstatic struct mtx rbreqlock;
222169689Skan
223169689Skan/*
22490075Sobrien * Synchronization (sleep/wakeup) variable for buffer requests.
22590075Sobrien * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
22690075Sobrien * by and/or.
22790075Sobrien * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
228169689Skan * getnewbuf(), and getblk().
22990075Sobrien */
23090075Sobrienstatic int needsbuffer;
23190075Sobrien
23290075Sobrien/*
23390075Sobrien * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
23490075Sobrien */
23590075Sobrienstatic struct mtx nblock;
23690075Sobrien
23790075Sobrien/*
23890075Sobrien * Lock that protects against bwait()/bdone()/B_DONE races.
23990075Sobrien */
24090075Sobrien
24190075Sobrienstatic struct mtx bdonelock;
24290075Sobrien
24390075Sobrien/*
24490075Sobrien * Definitions for the buffer free lists.
24590075Sobrien */
24690075Sobrien#define BUFFER_QUEUES	5	/* number of free buffer queues */
24790075Sobrien
24890075Sobrien#define QUEUE_NONE	0	/* on no queue */
24990075Sobrien#define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
25090075Sobrien#define QUEUE_DIRTY	2	/* B_DELWRI buffers */
25190075Sobrien#define QUEUE_EMPTYKVA	3	/* empty buffer headers w/KVA assignment */
25290075Sobrien#define QUEUE_EMPTY	4	/* empty buffer headers */
25390075Sobrien
25490075Sobrien/* Queues for free buffers with various properties */
25590075Sobrienstatic TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
25690075Sobrien
25790075Sobrien/* Lock for the bufqueues */
25890075Sobrienstatic struct mtx bqlock;
25990075Sobrien
26090075Sobrien/*
26190075Sobrien * Single global constant for BUF_WMESG, to avoid getting multiple references.
26290075Sobrien * buf_wmesg is referred from macros.
26390075Sobrien */
26490075Sobrienconst char *buf_wmesg = BUF_WMESG;
26590075Sobrien
26690075Sobrien#define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
26790075Sobrien#define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
26890075Sobrien#define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
26990075Sobrien#define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
27090075Sobrien
27190075Sobrien#ifdef DIRECTIO
27290075Sobrienextern void ffs_rawread_setup(void);
27390075Sobrien#endif /* DIRECTIO */
27490075Sobrien/*
27590075Sobrien *	numdirtywakeup:
27690075Sobrien *
27790075Sobrien *	If someone is blocked due to there being too many dirty buffers,
27890075Sobrien *	and numdirtybuffers is now reasonable, wake them up.
279169689Skan */
280169689Skan
28190075Sobrienstatic __inline void
28290075Sobriennumdirtywakeup(int level)
28390075Sobrien{
28490075Sobrien
285169689Skan	if (numdirtybuffers <= level) {
28690075Sobrien		mtx_lock(&nblock);
28790075Sobrien		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
28890075Sobrien			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
28990075Sobrien			wakeup(&needsbuffer);
29090075Sobrien		}
29190075Sobrien		mtx_unlock(&nblock);
29290075Sobrien	}
29390075Sobrien}
29490075Sobrien
29590075Sobrien/*
29690075Sobrien *	bufspacewakeup:
29790075Sobrien *
29890075Sobrien *	Called when buffer space is potentially available for recovery.
29990075Sobrien *	getnewbuf() will block on this flag when it is unable to free
30090075Sobrien *	sufficient buffer space.  Buffer space becomes recoverable when
30190075Sobrien *	bp's get placed back in the queues.
30290075Sobrien */
30390075Sobrien
30490075Sobrienstatic __inline void
30590075Sobrienbufspacewakeup(void)
30690075Sobrien{
30790075Sobrien
30890075Sobrien	/*
30990075Sobrien	 * If someone is waiting for BUF space, wake them up.  Even
31090075Sobrien	 * though we haven't freed the kva space yet, the waiting
31190075Sobrien	 * process will be able to now.
31290075Sobrien	 */
31390075Sobrien	mtx_lock(&nblock);
31490075Sobrien	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
31590075Sobrien		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
31690075Sobrien		wakeup(&needsbuffer);
31790075Sobrien	}
31890075Sobrien	mtx_unlock(&nblock);
31990075Sobrien}
32090075Sobrien
32190075Sobrien/*
32290075Sobrien * runningbufwakeup() - in-progress I/O accounting.
32390075Sobrien *
32490075Sobrien */
32590075Sobrienstatic __inline void
32690075Sobrienrunningbufwakeup(struct buf *bp)
32790075Sobrien{
32890075Sobrien
32990075Sobrien	if (bp->b_runningbufspace) {
33090075Sobrien		atomic_subtract_int(&runningbufspace, bp->b_runningbufspace);
33190075Sobrien		bp->b_runningbufspace = 0;
332169689Skan		mtx_lock(&rbreqlock);
333169689Skan		if (runningbufreq && runningbufspace <= lorunningspace) {
33490075Sobrien			runningbufreq = 0;
33590075Sobrien			wakeup(&runningbufreq);
33690075Sobrien		}
33790075Sobrien		mtx_unlock(&rbreqlock);
338169689Skan	}
33990075Sobrien}
34090075Sobrien
34190075Sobrien/*
34290075Sobrien *	bufcountwakeup:
34390075Sobrien *
34490075Sobrien *	Called when a buffer has been added to one of the free queues to
34590075Sobrien *	account for the buffer and to wakeup anyone waiting for free buffers.
34690075Sobrien *	This typically occurs when large amounts of metadata are being handled
34790075Sobrien *	by the buffer cache ( else buffer space runs out first, usually ).
34890075Sobrien */
34990075Sobrien
35090075Sobrienstatic __inline void
35190075Sobrienbufcountwakeup(void)
35290075Sobrien{
35390075Sobrien
35490075Sobrien	atomic_add_int(&numfreebuffers, 1);
35590075Sobrien	mtx_lock(&nblock);
35690075Sobrien	if (needsbuffer) {
35790075Sobrien		needsbuffer &= ~VFS_BIO_NEED_ANY;
35890075Sobrien		if (numfreebuffers >= hifreebuffers)
35990075Sobrien			needsbuffer &= ~VFS_BIO_NEED_FREE;
36090075Sobrien		wakeup(&needsbuffer);
36190075Sobrien	}
36290075Sobrien	mtx_unlock(&nblock);
36390075Sobrien}
36490075Sobrien
36590075Sobrien/*
36690075Sobrien *	waitrunningbufspace()
36790075Sobrien *
36890075Sobrien *	runningbufspace is a measure of the amount of I/O currently
36990075Sobrien *	running.  This routine is used in async-write situations to
37090075Sobrien *	prevent creating huge backups of pending writes to a device.
37190075Sobrien *	Only asynchronous writes are governed by this function.
37290075Sobrien *
37390075Sobrien *	Reads will adjust runningbufspace, but will not block based on it.
37490075Sobrien *	The read load has a side effect of reducing the allowed write load.
37590075Sobrien *
37690075Sobrien *	This does NOT turn an async write into a sync write.  It waits
37790075Sobrien *	for earlier writes to complete and generally returns before the
37890075Sobrien *	caller's write has reached the device.
37990075Sobrien */
38090075Sobrienstatic __inline void
38190075Sobrienwaitrunningbufspace(void)
38290075Sobrien{
38390075Sobrien
38490075Sobrien	mtx_lock(&rbreqlock);
38590075Sobrien	while (runningbufspace > hirunningspace) {
38690075Sobrien		++runningbufreq;
387169689Skan		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
388169689Skan	}
38990075Sobrien	mtx_unlock(&rbreqlock);
39090075Sobrien}
39190075Sobrien
39290075Sobrien
39390075Sobrien/*
394169689Skan *	vfs_buf_test_cache:
39590075Sobrien *
39690075Sobrien *	Called when a buffer is extended.  This function clears the B_CACHE
39790075Sobrien *	bit if the newly extended portion of the buffer does not contain
39890075Sobrien *	valid data.
39990075Sobrien */
40090075Sobrienstatic __inline
40190075Sobrienvoid
40290075Sobrienvfs_buf_test_cache(struct buf *bp,
40390075Sobrien		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
40490075Sobrien		  vm_page_t m)
40590075Sobrien{
40690075Sobrien
40790075Sobrien	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
40890075Sobrien	if (bp->b_flags & B_CACHE) {
40990075Sobrien		int base = (foff + off) & PAGE_MASK;
41090075Sobrien		if (vm_page_is_valid(m, base, size) == 0)
41190075Sobrien			bp->b_flags &= ~B_CACHE;
41290075Sobrien	}
41390075Sobrien}
41490075Sobrien
41590075Sobrien/* Wake up the buffer deamon if necessary */
41690075Sobrienstatic __inline
41790075Sobrienvoid
41890075Sobrienbd_wakeup(int dirtybuflevel)
41990075Sobrien{
42090075Sobrien
42190075Sobrien	mtx_lock(&bdlock);
42290075Sobrien	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
42390075Sobrien		bd_request = 1;
42490075Sobrien		wakeup(&bd_request);
42590075Sobrien	}
42690075Sobrien	mtx_unlock(&bdlock);
42790075Sobrien}
42890075Sobrien
42990075Sobrien/*
43090075Sobrien * bd_speedup - speedup the buffer cache flushing code
43190075Sobrien */
43290075Sobrien
43390075Sobrienstatic __inline
43490075Sobrienvoid
43590075Sobrienbd_speedup(void)
43690075Sobrien{
43790075Sobrien
43890075Sobrien	bd_wakeup(1);
439169689Skan}
440169689Skan
44190075Sobrien/*
44290075Sobrien * Calculating buffer cache scaling values and reserve space for buffer
44390075Sobrien * headers.  This is called during low level kernel initialization and
44490075Sobrien * may be called more then once.  We CANNOT write to the memory area
44590075Sobrien * being reserved at this time.
44690075Sobrien */
44790075Sobriencaddr_t
448169689Skankern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
44990075Sobrien{
45090075Sobrien
45190075Sobrien	/*
45290075Sobrien	 * physmem_est is in pages.  Convert it to kilobytes (assumes
45390075Sobrien	 * PAGE_SIZE is >= 1K)
45490075Sobrien	 */
45590075Sobrien	physmem_est = physmem_est * (PAGE_SIZE / 1024);
45690075Sobrien
45790075Sobrien	/*
45890075Sobrien	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
45990075Sobrien	 * For the first 64MB of ram nominally allocate sufficient buffers to
46090075Sobrien	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
46190075Sobrien	 * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
46290075Sobrien	 * the buffer cache we limit the eventual kva reservation to
46390075Sobrien	 * maxbcache bytes.
46490075Sobrien	 *
46590075Sobrien	 * factor represents the 1/4 x ram conversion.
46690075Sobrien	 */
46790075Sobrien	if (nbuf == 0) {
46890075Sobrien		int factor = 4 * BKVASIZE / 1024;
46990075Sobrien
47090075Sobrien		nbuf = 50;
47190075Sobrien		if (physmem_est > 4096)
47290075Sobrien			nbuf += min((physmem_est - 4096) / factor,
47390075Sobrien			    65536 / factor);
47490075Sobrien		if (physmem_est > 65536)
47590075Sobrien			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
47690075Sobrien
47790075Sobrien		if (maxbcache && nbuf > maxbcache / BKVASIZE)
47890075Sobrien			nbuf = maxbcache / BKVASIZE;
47990075Sobrien	}
48090075Sobrien
48190075Sobrien#if 0
48290075Sobrien	/*
48390075Sobrien	 * Do not allow the buffer_map to be more then 1/2 the size of the
48490075Sobrien	 * kernel_map.
48590075Sobrien	 */
48690075Sobrien	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
48790075Sobrien	    (BKVASIZE * 2)) {
48890075Sobrien		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
489169689Skan		    (BKVASIZE * 2);
490169689Skan		printf("Warning: nbufs capped at %d\n", nbuf);
49190075Sobrien	}
49290075Sobrien#endif
49390075Sobrien
494169689Skan	/*
49590075Sobrien	 * swbufs are used as temporary holders for I/O, such as paging I/O.
49690075Sobrien	 * We have no less then 16 and no more then 256.
49790075Sobrien	 */
49890075Sobrien	nswbuf = max(min(nbuf/4, 256), 16);
49990075Sobrien#ifdef NSWBUF_MIN
50090075Sobrien	if (nswbuf < NSWBUF_MIN)
50190075Sobrien		nswbuf = NSWBUF_MIN;
50290075Sobrien#endif
50390075Sobrien#ifdef DIRECTIO
50490075Sobrien	ffs_rawread_setup();
50590075Sobrien#endif
50690075Sobrien
50790075Sobrien	/*
50890075Sobrien	 * Reserve space for the buffer cache buffers
50990075Sobrien	 */
51090075Sobrien	swbuf = (void *)v;
51190075Sobrien	v = (caddr_t)(swbuf + nswbuf);
51290075Sobrien	buf = (void *)v;
51390075Sobrien	v = (caddr_t)(buf + nbuf);
51490075Sobrien
51590075Sobrien	return(v);
51690075Sobrien}
51790075Sobrien
51890075Sobrien/* Initialize the buffer subsystem.  Called before use of any buffers. */
51990075Sobrienvoid
52090075Sobrienbufinit(void)
52190075Sobrien{
52290075Sobrien	struct buf *bp;
52390075Sobrien	int i;
52490075Sobrien
52590075Sobrien	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
52690075Sobrien	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
52790075Sobrien	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
52890075Sobrien	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
52990075Sobrien	mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
53090075Sobrien
53190075Sobrien	/* next, make a null set of free lists */
53290075Sobrien	for (i = 0; i < BUFFER_QUEUES; i++)
53390075Sobrien		TAILQ_INIT(&bufqueues[i]);
53490075Sobrien
535169689Skan	/* finally, initialize each buffer header and stick on empty q */
536169689Skan	for (i = 0; i < nbuf; i++) {
53790075Sobrien		bp = &buf[i];
53890075Sobrien		bzero(bp, sizeof *bp);
53990075Sobrien		bp->b_flags = B_INVAL;	/* we're just an empty header */
54090075Sobrien		bp->b_rcred = NOCRED;
54190075Sobrien		bp->b_wcred = NOCRED;
54290075Sobrien		bp->b_qindex = QUEUE_EMPTY;
54390075Sobrien		bp->b_vflags = 0;
544169689Skan		bp->b_xflags = 0;
54590075Sobrien		LIST_INIT(&bp->b_dep);
54690075Sobrien		BUF_LOCKINIT(bp);
54790075Sobrien		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
54890075Sobrien	}
54990075Sobrien
55090075Sobrien	/*
55190075Sobrien	 * maxbufspace is the absolute maximum amount of buffer space we are
55290075Sobrien	 * allowed to reserve in KVM and in real terms.  The absolute maximum
55390075Sobrien	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
55490075Sobrien	 * used by most other processes.  The differential is required to
55590075Sobrien	 * ensure that buf_daemon is able to run when other processes might
55690075Sobrien	 * be blocked waiting for buffer space.
55790075Sobrien	 *
55890075Sobrien	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
55990075Sobrien	 * this may result in KVM fragmentation which is not handled optimally
56090075Sobrien	 * by the system.
56190075Sobrien	 */
56290075Sobrien	maxbufspace = nbuf * BKVASIZE;
56390075Sobrien	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
56490075Sobrien	lobufspace = hibufspace - MAXBSIZE;
56590075Sobrien
56690075Sobrien	lorunningspace = 512 * 1024;
56790075Sobrien	hirunningspace = 1024 * 1024;
56890075Sobrien
56990075Sobrien/*
57090075Sobrien * Limit the amount of malloc memory since it is wired permanently into
57190075Sobrien * the kernel space.  Even though this is accounted for in the buffer
57290075Sobrien * allocation, we don't want the malloced region to grow uncontrolled.
57390075Sobrien * The malloc scheme improves memory utilization significantly on average
57490075Sobrien * (small) directories.
57590075Sobrien */
57690075Sobrien	maxbufmallocspace = hibufspace / 20;
57790075Sobrien
57890075Sobrien/*
57990075Sobrien * Reduce the chance of a deadlock occuring by limiting the number
58090075Sobrien * of delayed-write dirty buffers we allow to stack up.
58190075Sobrien */
58290075Sobrien	hidirtybuffers = nbuf / 4 + 20;
58390075Sobrien	dirtybufthresh = hidirtybuffers * 9 / 10;
58490075Sobrien	numdirtybuffers = 0;
58590075Sobrien/*
58690075Sobrien * To support extreme low-memory systems, make sure hidirtybuffers cannot
58790075Sobrien * eat up all available buffer space.  This occurs when our minimum cannot
58890075Sobrien * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
58990075Sobrien * BKVASIZE'd (8K) buffers.
59090075Sobrien */
59190075Sobrien	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
59290075Sobrien		hidirtybuffers >>= 1;
59390075Sobrien	}
59490075Sobrien	lodirtybuffers = hidirtybuffers / 2;
59590075Sobrien
59690075Sobrien/*
59790075Sobrien * Try to keep the number of free buffers in the specified range,
59890075Sobrien * and give special processes (e.g. like buf_daemon) access to an
59990075Sobrien * emergency reserve.
60090075Sobrien */
60190075Sobrien	lofreebuffers = nbuf / 18 + 5;
60290075Sobrien	hifreebuffers = 2 * lofreebuffers;
60390075Sobrien	numfreebuffers = nbuf;
60490075Sobrien
60590075Sobrien/*
60690075Sobrien * Maximum number of async ops initiated per buf_daemon loop.  This is
60790075Sobrien * somewhat of a hack at the moment, we really need to limit ourselves
60890075Sobrien * based on the number of bytes of I/O in-transit that were initiated
60990075Sobrien * from buf_daemon.
61090075Sobrien */
61190075Sobrien
61290075Sobrien	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
61390075Sobrien	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
61490075Sobrien}
61590075Sobrien
61690075Sobrien/*
61790075Sobrien * bfreekva() - free the kva allocation for a buffer.
61890075Sobrien *
61990075Sobrien *	Must be called at splbio() or higher as this is the only locking for
62090075Sobrien *	buffer_map.
62190075Sobrien *
62290075Sobrien *	Since this call frees up buffer space, we call bufspacewakeup().
62390075Sobrien */
62490075Sobrienstatic void
62590075Sobrienbfreekva(struct buf *bp)
62690075Sobrien{
62790075Sobrien
62890075Sobrien	if (bp->b_kvasize) {
62990075Sobrien		atomic_add_int(&buffreekvacnt, 1);
63090075Sobrien		atomic_subtract_int(&bufspace, bp->b_kvasize);
63190075Sobrien		vm_map_delete(buffer_map,
63290075Sobrien		    (vm_offset_t) bp->b_kvabase,
63390075Sobrien		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
63490075Sobrien		);
63590075Sobrien		bp->b_kvasize = 0;
63690075Sobrien		bufspacewakeup();
63790075Sobrien	}
63890075Sobrien}
63990075Sobrien
64090075Sobrien/*
64190075Sobrien *	bremfree:
64290075Sobrien *
64390075Sobrien *	Mark the buffer for removal from the appropriate free list in brelse.
64490075Sobrien *
64590075Sobrien */
64690075Sobrienvoid
64790075Sobrienbremfree(struct buf *bp)
64890075Sobrien{
64990075Sobrien
65090075Sobrien	CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
65190075Sobrien	KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked."));
65290075Sobrien	KASSERT((bp->b_flags & B_REMFREE) == 0 && bp->b_qindex != QUEUE_NONE,
65390075Sobrien	    ("bremfree: buffer %p not on a queue.", bp));
65490075Sobrien
65590075Sobrien	bp->b_flags |= B_REMFREE;
65690075Sobrien	/* Fixup numfreebuffers count.  */
65790075Sobrien	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
65890075Sobrien		atomic_subtract_int(&numfreebuffers, 1);
65990075Sobrien}
66090075Sobrien
66190075Sobrien/*
66290075Sobrien *	bremfreef:
66390075Sobrien *
66490075Sobrien *	Force an immediate removal from a free list.  Used only in nfs when
66590075Sobrien *	it abuses the b_freelist pointer.
66690075Sobrien */
66790075Sobrienvoid
66890075Sobrienbremfreef(struct buf *bp)
66990075Sobrien{
67090075Sobrien	mtx_lock(&bqlock);
67190075Sobrien	bremfreel(bp);
67290075Sobrien	mtx_unlock(&bqlock);
67390075Sobrien}
67490075Sobrien
67590075Sobrien/*
67690075Sobrien *	bremfreel:
67790075Sobrien *
67890075Sobrien *	Removes a buffer from the free list, must be called with the
67990075Sobrien *	bqlock held.
68090075Sobrien */
68190075Sobrienvoid
68290075Sobrienbremfreel(struct buf *bp)
68390075Sobrien{
68490075Sobrien	int s = splbio();
68590075Sobrien
68690075Sobrien	CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
68790075Sobrien	    bp, bp->b_vp, bp->b_flags);
68890075Sobrien	KASSERT(BUF_REFCNT(bp), ("bremfreel: buffer %p not locked.", bp));
68990075Sobrien	KASSERT(bp->b_qindex != QUEUE_NONE,
69090075Sobrien	    ("bremfreel: buffer %p not on a queue.", bp));
69190075Sobrien	mtx_assert(&bqlock, MA_OWNED);
69290075Sobrien
69390075Sobrien	TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
69490075Sobrien	bp->b_qindex = QUEUE_NONE;
69590075Sobrien	/*
69690075Sobrien	 * If this was a delayed bremfree() we only need to remove the buffer
69790075Sobrien	 * from the queue and return the stats are already done.
69890075Sobrien	 */
69990075Sobrien	if (bp->b_flags & B_REMFREE) {
70090075Sobrien		bp->b_flags &= ~B_REMFREE;
70190075Sobrien		splx(s);
70290075Sobrien		return;
70390075Sobrien	}
70490075Sobrien	/*
70590075Sobrien	 * Fixup numfreebuffers count.  If the buffer is invalid or not
70690075Sobrien	 * delayed-write, the buffer was free and we must decrement
70790075Sobrien	 * numfreebuffers.
70890075Sobrien	 */
70990075Sobrien	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
71090075Sobrien		atomic_subtract_int(&numfreebuffers, 1);
71190075Sobrien	splx(s);
71290075Sobrien}
71390075Sobrien
71490075Sobrien
71590075Sobrien/*
71690075Sobrien * Get a buffer with the specified data.  Look in the cache first.  We
71790075Sobrien * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
71890075Sobrien * is set, the buffer is valid and we do not have to do anything ( see
71990075Sobrien * getblk() ).  This is really just a special case of breadn().
72090075Sobrien */
72190075Sobrienint
72290075Sobrienbread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
72390075Sobrien    struct buf **bpp)
72490075Sobrien{
72590075Sobrien
72690075Sobrien	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
72790075Sobrien}
72890075Sobrien
72990075Sobrien/*
73090075Sobrien * Operates like bread, but also starts asynchronous I/O on
73190075Sobrien * read-ahead blocks.  We must clear BIO_ERROR and B_INVAL prior
73290075Sobrien * to initiating I/O . If B_CACHE is set, the buffer is valid
73390075Sobrien * and we do not have to do anything.
73490075Sobrien */
73590075Sobrienint
73690075Sobrienbreadn(struct vnode * vp, daddr_t blkno, int size,
73790075Sobrien    daddr_t * rablkno, int *rabsize,
73890075Sobrien    int cnt, struct ucred * cred, struct buf **bpp)
73990075Sobrien{
74090075Sobrien	struct buf *bp, *rabp;
74190075Sobrien	int i;
74290075Sobrien	int rv = 0, readwait = 0;
74390075Sobrien
74490075Sobrien	CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
74590075Sobrien	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
74690075Sobrien
74790075Sobrien	/* if not found in cache, do some I/O */
74890075Sobrien	if ((bp->b_flags & B_CACHE) == 0) {
74990075Sobrien		if (curthread != PCPU_GET(idlethread))
75090075Sobrien			curthread->td_proc->p_stats->p_ru.ru_inblock++;
75190075Sobrien		bp->b_iocmd = BIO_READ;
75290075Sobrien		bp->b_flags &= ~B_INVAL;
75390075Sobrien		bp->b_ioflags &= ~BIO_ERROR;
75490075Sobrien		if (bp->b_rcred == NOCRED && cred != NOCRED)
75590075Sobrien			bp->b_rcred = crhold(cred);
75690075Sobrien		vfs_busy_pages(bp, 0);
75790075Sobrien		bp->b_iooffset = dbtob(bp->b_blkno);
75890075Sobrien		bstrategy(bp);
759132718Skan		++readwait;
760132718Skan	}
761169689Skan
762132718Skan	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
763132718Skan		if (inmem(vp, *rablkno))
764132718Skan			continue;
765132718Skan		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
766132718Skan
767132718Skan		if ((rabp->b_flags & B_CACHE) == 0) {
768132718Skan			if (curthread != PCPU_GET(idlethread))
769132718Skan				curthread->td_proc->p_stats->p_ru.ru_inblock++;
770132718Skan			rabp->b_flags |= B_ASYNC;
771132718Skan			rabp->b_flags &= ~B_INVAL;
772169689Skan			rabp->b_ioflags &= ~BIO_ERROR;
773169689Skan			rabp->b_iocmd = BIO_READ;
774132718Skan			if (rabp->b_rcred == NOCRED && cred != NOCRED)
775132718Skan				rabp->b_rcred = crhold(cred);
776132718Skan			vfs_busy_pages(rabp, 0);
777132718Skan			BUF_KERNPROC(rabp);
778132718Skan			rabp->b_iooffset = dbtob(rabp->b_blkno);
779132718Skan			bstrategy(rabp);
780132718Skan		} else {
781132718Skan			brelse(rabp);
782132718Skan		}
783169689Skan	}
784169689Skan
785132718Skan	if (readwait) {
786132718Skan		rv = bufwait(bp);
787132718Skan	}
788132718Skan	return (rv);
789132718Skan}
790132718Skan
791132718Skan/*
792132718Skan * Write, release buffer on completion.  (Done by iodone
793132718Skan * if async).  Do not bother writing anything if the buffer
794132718Skan * is invalid.
795 *
796 * Note that we set B_CACHE here, indicating that buffer is
797 * fully valid and thus cacheable.  This is true even of NFS
798 * now so we set it generally.  This could be set either here
799 * or in biodone() since the I/O is synchronous.  We put it
800 * here.
801 */
802int
803bufwrite(struct buf *bp)
804{
805	int oldflags, s;
806	struct buf *newbp;
807
808	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
809	if (bp->b_flags & B_INVAL) {
810		brelse(bp);
811		return (0);
812	}
813
814	oldflags = bp->b_flags;
815
816	if (BUF_REFCNT(bp) == 0)
817		panic("bufwrite: buffer is not busy???");
818	s = splbio();
819	/*
820	 * If a background write is already in progress, delay
821	 * writing this block if it is asynchronous. Otherwise
822	 * wait for the background write to complete.
823	 */
824	BO_LOCK(bp->b_bufobj);
825	if (bp->b_vflags & BV_BKGRDINPROG) {
826		if (bp->b_flags & B_ASYNC) {
827			BO_UNLOCK(bp->b_bufobj);
828			splx(s);
829			bdwrite(bp);
830			return (0);
831		}
832		bp->b_vflags |= BV_BKGRDWAIT;
833		msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj), PRIBIO, "bwrbg", 0);
834		if (bp->b_vflags & BV_BKGRDINPROG)
835			panic("bufwrite: still writing");
836	}
837	BO_UNLOCK(bp->b_bufobj);
838
839	/* Mark the buffer clean */
840	bundirty(bp);
841
842	/*
843	 * If this buffer is marked for background writing and we
844	 * do not have to wait for it, make a copy and write the
845	 * copy so as to leave this buffer ready for further use.
846	 *
847	 * This optimization eats a lot of memory.  If we have a page
848	 * or buffer shortfall we can't do it.
849	 */
850	if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) &&
851	    (bp->b_flags & B_ASYNC) &&
852	    !vm_page_count_severe() &&
853	    !buf_dirty_count_severe()) {
854		KASSERT(bp->b_iodone == NULL,
855		    ("bufwrite: needs chained iodone (%p)", bp->b_iodone));
856
857		/* get a new block */
858		newbp = geteblk(bp->b_bufsize);
859
860		/*
861		 * set it to be identical to the old block.  We have to
862		 * set b_lblkno and BKGRDMARKER before calling bgetvp()
863		 * to avoid confusing the splay tree and gbincore().
864		 */
865		memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
866		newbp->b_lblkno = bp->b_lblkno;
867		newbp->b_xflags |= BX_BKGRDMARKER;
868		BO_LOCK(bp->b_bufobj);
869		bp->b_vflags |= BV_BKGRDINPROG;
870		bgetvp(bp->b_vp, newbp);
871		BO_UNLOCK(bp->b_bufobj);
872		newbp->b_bufobj = &bp->b_vp->v_bufobj;
873		newbp->b_blkno = bp->b_blkno;
874		newbp->b_offset = bp->b_offset;
875		newbp->b_iodone = vfs_backgroundwritedone;
876		newbp->b_flags |= B_ASYNC;
877		newbp->b_flags &= ~B_INVAL;
878
879		/* move over the dependencies */
880		if (LIST_FIRST(&bp->b_dep) != NULL)
881			buf_movedeps(bp, newbp);
882
883		/*
884		 * Initiate write on the copy, release the original to
885		 * the B_LOCKED queue so that it cannot go away until
886		 * the background write completes. If not locked it could go
887		 * away and then be reconstituted while it was being written.
888		 * If the reconstituted buffer were written, we could end up
889		 * with two background copies being written at the same time.
890		 */
891		bqrelse(bp);
892		bp = newbp;
893	}
894
895	bp->b_flags &= ~B_DONE;
896	bp->b_ioflags &= ~BIO_ERROR;
897	bp->b_flags |= B_CACHE;
898	bp->b_iocmd = BIO_WRITE;
899
900	bufobj_wref(bp->b_bufobj);
901	vfs_busy_pages(bp, 1);
902
903	/*
904	 * Normal bwrites pipeline writes
905	 */
906	bp->b_runningbufspace = bp->b_bufsize;
907	atomic_add_int(&runningbufspace, bp->b_runningbufspace);
908
909	if (curthread != PCPU_GET(idlethread))
910		curthread->td_proc->p_stats->p_ru.ru_oublock++;
911	splx(s);
912	if (oldflags & B_ASYNC)
913		BUF_KERNPROC(bp);
914	bp->b_iooffset = dbtob(bp->b_blkno);
915	bstrategy(bp);
916
917	if ((oldflags & B_ASYNC) == 0) {
918		int rtval = bufwait(bp);
919		brelse(bp);
920		return (rtval);
921	} else {
922		/*
923		 * don't allow the async write to saturate the I/O
924		 * system.  We will not deadlock here because
925		 * we are blocking waiting for I/O that is already in-progress
926		 * to complete. We do not block here if it is the update
927		 * or syncer daemon trying to clean up as that can lead
928		 * to deadlock.
929		 */
930		if (curthread->td_proc != bufdaemonproc &&
931		    curthread->td_proc != updateproc)
932			waitrunningbufspace();
933	}
934
935	return (0);
936}
937
938/*
939 * Complete a background write started from bwrite.
940 */
941static void
942vfs_backgroundwritedone(struct buf *bp)
943{
944	struct buf *origbp;
945
946	/*
947	 * Find the original buffer that we are writing.
948	 */
949	BO_LOCK(bp->b_bufobj);
950	if ((origbp = gbincore(bp->b_bufobj, bp->b_lblkno)) == NULL)
951		panic("backgroundwritedone: lost buffer");
952
953	/*
954	 * Clear the BV_BKGRDINPROG flag in the original buffer
955	 * and awaken it if it is waiting for the write to complete.
956	 * If BV_BKGRDINPROG is not set in the original buffer it must
957	 * have been released and re-instantiated - which is not legal.
958	 */
959	KASSERT((origbp->b_vflags & BV_BKGRDINPROG),
960	    ("backgroundwritedone: lost buffer2"));
961	origbp->b_vflags &= ~BV_BKGRDINPROG;
962	if (origbp->b_vflags & BV_BKGRDWAIT) {
963		origbp->b_vflags &= ~BV_BKGRDWAIT;
964		wakeup(&origbp->b_xflags);
965	}
966	BO_UNLOCK(bp->b_bufobj);
967	/*
968	 * Process dependencies then return any unfinished ones.
969	 */
970	if (LIST_FIRST(&bp->b_dep) != NULL)
971		buf_complete(bp);
972	if (LIST_FIRST(&bp->b_dep) != NULL)
973		buf_movedeps(bp, origbp);
974
975	/*
976	 * This buffer is marked B_NOCACHE, so when it is released
977	 * by biodone, it will be tossed. We mark it with BIO_READ
978	 * to avoid biodone doing a second bufobj_wdrop.
979	 */
980	bp->b_flags |= B_NOCACHE;
981	bp->b_iocmd = BIO_READ;
982	bp->b_flags &= ~(B_CACHE | B_DONE);
983	bp->b_iodone = 0;
984	bufdone(bp);
985}
986
987/*
988 * Delayed write. (Buffer is marked dirty).  Do not bother writing
989 * anything if the buffer is marked invalid.
990 *
991 * Note that since the buffer must be completely valid, we can safely
992 * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
993 * biodone() in order to prevent getblk from writing the buffer
994 * out synchronously.
995 */
996void
997bdwrite(struct buf *bp)
998{
999	struct thread *td = curthread;
1000	struct vnode *vp;
1001	struct buf *nbp;
1002	struct bufobj *bo;
1003
1004	CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1005	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1006	KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy"));
1007
1008	if (bp->b_flags & B_INVAL) {
1009		brelse(bp);
1010		return;
1011	}
1012
1013	/*
1014	 * If we have too many dirty buffers, don't create any more.
1015	 * If we are wildly over our limit, then force a complete
1016	 * cleanup. Otherwise, just keep the situation from getting
1017	 * out of control. Note that we have to avoid a recursive
1018	 * disaster and not try to clean up after our own cleanup!
1019	 */
1020	vp = bp->b_vp;
1021	bo = bp->b_bufobj;
1022	if ((td->td_pflags & TDP_COWINPROGRESS) == 0) {
1023		BO_LOCK(bo);
1024		if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1025			BO_UNLOCK(bo);
1026			(void) VOP_FSYNC(vp, MNT_NOWAIT, td);
1027			altbufferflushes++;
1028		} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1029			/*
1030			 * Try to find a buffer to flush.
1031			 */
1032			TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1033				if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1034				    BUF_LOCK(nbp,
1035				    LK_EXCLUSIVE | LK_NOWAIT, NULL))
1036					continue;
1037				if (bp == nbp)
1038					panic("bdwrite: found ourselves");
1039				BO_UNLOCK(bo);
1040				/* Don't countdeps with the bo lock held. */
1041				if (buf_countdeps(nbp, 0)) {
1042					BO_LOCK(bo);
1043					BUF_UNLOCK(nbp);
1044					continue;
1045				}
1046				if (nbp->b_flags & B_CLUSTEROK) {
1047					vfs_bio_awrite(nbp);
1048				} else {
1049					bremfree(nbp);
1050					bawrite(nbp);
1051				}
1052				dirtybufferflushes++;
1053				break;
1054			}
1055			if (nbp == NULL)
1056				BO_UNLOCK(bo);
1057		} else
1058			BO_UNLOCK(bo);
1059	} else
1060		recursiveflushes++;
1061
1062	bdirty(bp);
1063	/*
1064	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1065	 * true even of NFS now.
1066	 */
1067	bp->b_flags |= B_CACHE;
1068
1069	/*
1070	 * This bmap keeps the system from needing to do the bmap later,
1071	 * perhaps when the system is attempting to do a sync.  Since it
1072	 * is likely that the indirect block -- or whatever other datastructure
1073	 * that the filesystem needs is still in memory now, it is a good
1074	 * thing to do this.  Note also, that if the pageout daemon is
1075	 * requesting a sync -- there might not be enough memory to do
1076	 * the bmap then...  So, this is important to do.
1077	 */
1078	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1079		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1080	}
1081
1082	/*
1083	 * Set the *dirty* buffer range based upon the VM system dirty pages.
1084	 */
1085	vfs_setdirty(bp);
1086
1087	/*
1088	 * We need to do this here to satisfy the vnode_pager and the
1089	 * pageout daemon, so that it thinks that the pages have been
1090	 * "cleaned".  Note that since the pages are in a delayed write
1091	 * buffer -- the VFS layer "will" see that the pages get written
1092	 * out on the next sync, or perhaps the cluster will be completed.
1093	 */
1094	vfs_clean_pages(bp);
1095	bqrelse(bp);
1096
1097	/*
1098	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1099	 * buffers (midpoint between our recovery point and our stall
1100	 * point).
1101	 */
1102	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1103
1104	/*
1105	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1106	 * due to the softdep code.
1107	 */
1108}
1109
1110/*
1111 *	bdirty:
1112 *
1113 *	Turn buffer into delayed write request.  We must clear BIO_READ and
1114 *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1115 *	itself to properly update it in the dirty/clean lists.  We mark it
1116 *	B_DONE to ensure that any asynchronization of the buffer properly
1117 *	clears B_DONE ( else a panic will occur later ).
1118 *
1119 *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1120 *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1121 *	should only be called if the buffer is known-good.
1122 *
1123 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1124 *	count.
1125 *
1126 *	Must be called at splbio().
1127 *	The buffer must be on QUEUE_NONE.
1128 */
1129void
1130bdirty(struct buf *bp)
1131{
1132
1133	CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1134	    bp, bp->b_vp, bp->b_flags);
1135	KASSERT(BUF_REFCNT(bp) == 1, ("bdirty: bp %p not locked",bp));
1136	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1137	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1138	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1139	bp->b_flags &= ~(B_RELBUF);
1140	bp->b_iocmd = BIO_WRITE;
1141
1142	if ((bp->b_flags & B_DELWRI) == 0) {
1143		bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1144		reassignbuf(bp);
1145		atomic_add_int(&numdirtybuffers, 1);
1146		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1147	}
1148}
1149
1150/*
1151 *	bundirty:
1152 *
1153 *	Clear B_DELWRI for buffer.
1154 *
1155 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1156 *	count.
1157 *
1158 *	Must be called at splbio().
1159 *	The buffer must be on QUEUE_NONE.
1160 */
1161
1162void
1163bundirty(struct buf *bp)
1164{
1165
1166	CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1167	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1168	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1169	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1170	KASSERT(BUF_REFCNT(bp) == 1, ("bundirty: bp %p not locked",bp));
1171
1172	if (bp->b_flags & B_DELWRI) {
1173		bp->b_flags &= ~B_DELWRI;
1174		reassignbuf(bp);
1175		atomic_subtract_int(&numdirtybuffers, 1);
1176		numdirtywakeup(lodirtybuffers);
1177	}
1178	/*
1179	 * Since it is now being written, we can clear its deferred write flag.
1180	 */
1181	bp->b_flags &= ~B_DEFERRED;
1182}
1183
1184/*
1185 *	bawrite:
1186 *
1187 *	Asynchronous write.  Start output on a buffer, but do not wait for
1188 *	it to complete.  The buffer is released when the output completes.
1189 *
1190 *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1191 *	B_INVAL buffers.  Not us.
1192 */
1193void
1194bawrite(struct buf *bp)
1195{
1196
1197	bp->b_flags |= B_ASYNC;
1198	(void) bwrite(bp);
1199}
1200
1201/*
1202 *	bwillwrite:
1203 *
1204 *	Called prior to the locking of any vnodes when we are expecting to
1205 *	write.  We do not want to starve the buffer cache with too many
1206 *	dirty buffers so we block here.  By blocking prior to the locking
1207 *	of any vnodes we attempt to avoid the situation where a locked vnode
1208 *	prevents the various system daemons from flushing related buffers.
1209 */
1210
1211void
1212bwillwrite(void)
1213{
1214
1215	if (numdirtybuffers >= hidirtybuffers) {
1216		int s;
1217
1218		s = splbio();
1219		mtx_lock(&nblock);
1220		while (numdirtybuffers >= hidirtybuffers) {
1221			bd_wakeup(1);
1222			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1223			msleep(&needsbuffer, &nblock,
1224			    (PRIBIO + 4), "flswai", 0);
1225		}
1226		splx(s);
1227		mtx_unlock(&nblock);
1228	}
1229}
1230
1231/*
1232 * Return true if we have too many dirty buffers.
1233 */
1234int
1235buf_dirty_count_severe(void)
1236{
1237
1238	return(numdirtybuffers >= hidirtybuffers);
1239}
1240
1241/*
1242 *	brelse:
1243 *
1244 *	Release a busy buffer and, if requested, free its resources.  The
1245 *	buffer will be stashed in the appropriate bufqueue[] allowing it
1246 *	to be accessed later as a cache entity or reused for other purposes.
1247 */
1248void
1249brelse(struct buf *bp)
1250{
1251	int s;
1252
1253	CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1254	    bp, bp->b_vp, bp->b_flags);
1255	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1256	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1257
1258	s = splbio();
1259
1260	if (bp->b_iocmd == BIO_WRITE &&
1261	    (bp->b_ioflags & BIO_ERROR) &&
1262	    !(bp->b_flags & B_INVAL)) {
1263		/*
1264		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1265		 * pages from being scrapped.  If B_INVAL is set then
1266		 * this case is not run and the next case is run to
1267		 * destroy the buffer.  B_INVAL can occur if the buffer
1268		 * is outside the range supported by the underlying device.
1269		 */
1270		bp->b_ioflags &= ~BIO_ERROR;
1271		bdirty(bp);
1272	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1273	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1274		/*
1275		 * Either a failed I/O or we were asked to free or not
1276		 * cache the buffer.
1277		 */
1278		bp->b_flags |= B_INVAL;
1279		if (LIST_FIRST(&bp->b_dep) != NULL)
1280			buf_deallocate(bp);
1281		if (bp->b_flags & B_DELWRI) {
1282			atomic_subtract_int(&numdirtybuffers, 1);
1283			numdirtywakeup(lodirtybuffers);
1284		}
1285		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1286		if ((bp->b_flags & B_VMIO) == 0) {
1287			if (bp->b_bufsize)
1288				allocbuf(bp, 0);
1289			if (bp->b_vp)
1290				brelvp(bp);
1291		}
1292	}
1293
1294	/*
1295	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1296	 * is called with B_DELWRI set, the underlying pages may wind up
1297	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1298	 * because pages associated with a B_DELWRI bp are marked clean.
1299	 *
1300	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1301	 * if B_DELWRI is set.
1302	 *
1303	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1304	 * on pages to return pages to the VM page queues.
1305	 */
1306	if (bp->b_flags & B_DELWRI)
1307		bp->b_flags &= ~B_RELBUF;
1308	else if (vm_page_count_severe()) {
1309		/*
1310		 * XXX This lock may not be necessary since BKGRDINPROG
1311		 * cannot be set while we hold the buf lock, it can only be
1312		 * cleared if it is already pending.
1313		 */
1314		if (bp->b_vp) {
1315			BO_LOCK(bp->b_bufobj);
1316			if (!(bp->b_vflags & BV_BKGRDINPROG))
1317				bp->b_flags |= B_RELBUF;
1318			BO_UNLOCK(bp->b_bufobj);
1319		} else
1320			bp->b_flags |= B_RELBUF;
1321	}
1322
1323	/*
1324	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1325	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1326	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1327	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1328	 *
1329	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1330	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1331	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1332	 *
1333	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1334	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1335	 * the commit state and we cannot afford to lose the buffer. If the
1336	 * buffer has a background write in progress, we need to keep it
1337	 * around to prevent it from being reconstituted and starting a second
1338	 * background write.
1339	 */
1340	if ((bp->b_flags & B_VMIO)
1341	    && !(bp->b_vp->v_mount != NULL &&
1342		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1343		 !vn_isdisk(bp->b_vp, NULL) &&
1344		 (bp->b_flags & B_DELWRI))
1345	    ) {
1346
1347		int i, j, resid;
1348		vm_page_t m;
1349		off_t foff;
1350		vm_pindex_t poff;
1351		vm_object_t obj;
1352
1353		obj = bp->b_bufobj->bo_object;
1354
1355		/*
1356		 * Get the base offset and length of the buffer.  Note that
1357		 * in the VMIO case if the buffer block size is not
1358		 * page-aligned then b_data pointer may not be page-aligned.
1359		 * But our b_pages[] array *IS* page aligned.
1360		 *
1361		 * block sizes less then DEV_BSIZE (usually 512) are not
1362		 * supported due to the page granularity bits (m->valid,
1363		 * m->dirty, etc...).
1364		 *
1365		 * See man buf(9) for more information
1366		 */
1367		resid = bp->b_bufsize;
1368		foff = bp->b_offset;
1369		VM_OBJECT_LOCK(obj);
1370		for (i = 0; i < bp->b_npages; i++) {
1371			int had_bogus = 0;
1372
1373			m = bp->b_pages[i];
1374
1375			/*
1376			 * If we hit a bogus page, fixup *all* the bogus pages
1377			 * now.
1378			 */
1379			if (m == bogus_page) {
1380				poff = OFF_TO_IDX(bp->b_offset);
1381				had_bogus = 1;
1382
1383				for (j = i; j < bp->b_npages; j++) {
1384					vm_page_t mtmp;
1385					mtmp = bp->b_pages[j];
1386					if (mtmp == bogus_page) {
1387						mtmp = vm_page_lookup(obj, poff + j);
1388						if (!mtmp) {
1389							panic("brelse: page missing\n");
1390						}
1391						bp->b_pages[j] = mtmp;
1392					}
1393				}
1394
1395				if ((bp->b_flags & B_INVAL) == 0) {
1396					pmap_qenter(
1397					    trunc_page((vm_offset_t)bp->b_data),
1398					    bp->b_pages, bp->b_npages);
1399				}
1400				m = bp->b_pages[i];
1401			}
1402			if ((bp->b_flags & B_NOCACHE) ||
1403			    (bp->b_ioflags & BIO_ERROR)) {
1404				int poffset = foff & PAGE_MASK;
1405				int presid = resid > (PAGE_SIZE - poffset) ?
1406					(PAGE_SIZE - poffset) : resid;
1407
1408				KASSERT(presid >= 0, ("brelse: extra page"));
1409				vm_page_lock_queues();
1410				vm_page_set_invalid(m, poffset, presid);
1411				vm_page_unlock_queues();
1412				if (had_bogus)
1413					printf("avoided corruption bug in bogus_page/brelse code\n");
1414			}
1415			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1416			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1417		}
1418		VM_OBJECT_UNLOCK(obj);
1419		if (bp->b_flags & (B_INVAL | B_RELBUF))
1420			vfs_vmio_release(bp);
1421
1422	} else if (bp->b_flags & B_VMIO) {
1423
1424		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1425			vfs_vmio_release(bp);
1426		}
1427
1428	}
1429
1430	if (BUF_REFCNT(bp) > 1) {
1431		/* do not release to free list */
1432		BUF_UNLOCK(bp);
1433		splx(s);
1434		return;
1435	}
1436
1437	/* enqueue */
1438	mtx_lock(&bqlock);
1439	/* Handle delayed bremfree() processing. */
1440	if (bp->b_flags & B_REMFREE)
1441		bremfreel(bp);
1442	if (bp->b_qindex != QUEUE_NONE)
1443		panic("brelse: free buffer onto another queue???");
1444
1445	/* buffers with no memory */
1446	if (bp->b_bufsize == 0) {
1447		bp->b_flags |= B_INVAL;
1448		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1449		if (bp->b_vflags & BV_BKGRDINPROG)
1450			panic("losing buffer 1");
1451		if (bp->b_kvasize) {
1452			bp->b_qindex = QUEUE_EMPTYKVA;
1453		} else {
1454			bp->b_qindex = QUEUE_EMPTY;
1455		}
1456		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1457	/* buffers with junk contents */
1458	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1459	    (bp->b_ioflags & BIO_ERROR)) {
1460		bp->b_flags |= B_INVAL;
1461		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1462		if (bp->b_vflags & BV_BKGRDINPROG)
1463			panic("losing buffer 2");
1464		bp->b_qindex = QUEUE_CLEAN;
1465		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1466	/* remaining buffers */
1467	} else {
1468		if (bp->b_flags & B_DELWRI)
1469			bp->b_qindex = QUEUE_DIRTY;
1470		else
1471			bp->b_qindex = QUEUE_CLEAN;
1472		if (bp->b_flags & B_AGE)
1473			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1474		else
1475			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1476	}
1477	mtx_unlock(&bqlock);
1478
1479	/*
1480	 * If B_INVAL and B_DELWRI is set, clear B_DELWRI.  We have already
1481	 * placed the buffer on the correct queue.  We must also disassociate
1482	 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1483	 * find it.
1484	 */
1485	if (bp->b_flags & B_INVAL) {
1486		if (bp->b_flags & B_DELWRI)
1487			bundirty(bp);
1488		if (bp->b_vp)
1489			brelvp(bp);
1490	}
1491
1492	/*
1493	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1494	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1495	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1496	 * if B_INVAL is set ).
1497	 */
1498
1499	if (!(bp->b_flags & B_DELWRI))
1500		bufcountwakeup();
1501
1502	/*
1503	 * Something we can maybe free or reuse
1504	 */
1505	if (bp->b_bufsize || bp->b_kvasize)
1506		bufspacewakeup();
1507
1508	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1509	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1510		panic("brelse: not dirty");
1511	/* unlock */
1512	BUF_UNLOCK(bp);
1513	splx(s);
1514}
1515
1516/*
1517 * Release a buffer back to the appropriate queue but do not try to free
1518 * it.  The buffer is expected to be used again soon.
1519 *
1520 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1521 * biodone() to requeue an async I/O on completion.  It is also used when
1522 * known good buffers need to be requeued but we think we may need the data
1523 * again soon.
1524 *
1525 * XXX we should be able to leave the B_RELBUF hint set on completion.
1526 */
1527void
1528bqrelse(struct buf *bp)
1529{
1530	int s;
1531
1532	s = splbio();
1533
1534	CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1535	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1536	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1537
1538	if (BUF_REFCNT(bp) > 1) {
1539		/* do not release to free list */
1540		BUF_UNLOCK(bp);
1541		splx(s);
1542		return;
1543	}
1544	mtx_lock(&bqlock);
1545	/* Handle delayed bremfree() processing. */
1546	if (bp->b_flags & B_REMFREE)
1547		bremfreel(bp);
1548	if (bp->b_qindex != QUEUE_NONE)
1549		panic("bqrelse: free buffer onto another queue???");
1550	/* buffers with stale but valid contents */
1551	if (bp->b_flags & B_DELWRI) {
1552		bp->b_qindex = QUEUE_DIRTY;
1553		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1554	} else {
1555		/*
1556		 * XXX This lock may not be necessary since BKGRDINPROG
1557		 * cannot be set while we hold the buf lock, it can only be
1558		 * cleared if it is already pending.
1559		 */
1560		BO_LOCK(bp->b_bufobj);
1561		if (!vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) {
1562			BO_UNLOCK(bp->b_bufobj);
1563			bp->b_qindex = QUEUE_CLEAN;
1564			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1565			    b_freelist);
1566		} else {
1567			/*
1568			 * We are too low on memory, we have to try to free
1569			 * the buffer (most importantly: the wired pages
1570			 * making up its backing store) *now*.
1571			 */
1572			BO_UNLOCK(bp->b_bufobj);
1573			mtx_unlock(&bqlock);
1574			splx(s);
1575			brelse(bp);
1576			return;
1577		}
1578	}
1579	mtx_unlock(&bqlock);
1580
1581	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1582		bufcountwakeup();
1583
1584	/*
1585	 * Something we can maybe free or reuse.
1586	 */
1587	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1588		bufspacewakeup();
1589
1590	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1591	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1592		panic("bqrelse: not dirty");
1593	/* unlock */
1594	BUF_UNLOCK(bp);
1595	splx(s);
1596}
1597
1598/* Give pages used by the bp back to the VM system (where possible) */
1599static void
1600vfs_vmio_release(struct buf *bp)
1601{
1602	int i;
1603	vm_page_t m;
1604
1605	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1606	vm_page_lock_queues();
1607	for (i = 0; i < bp->b_npages; i++) {
1608		m = bp->b_pages[i];
1609		bp->b_pages[i] = NULL;
1610		/*
1611		 * In order to keep page LRU ordering consistent, put
1612		 * everything on the inactive queue.
1613		 */
1614		vm_page_unwire(m, 0);
1615		/*
1616		 * We don't mess with busy pages, it is
1617		 * the responsibility of the process that
1618		 * busied the pages to deal with them.
1619		 */
1620		if ((m->flags & PG_BUSY) || (m->busy != 0))
1621			continue;
1622
1623		if (m->wire_count == 0) {
1624			/*
1625			 * Might as well free the page if we can and it has
1626			 * no valid data.  We also free the page if the
1627			 * buffer was used for direct I/O
1628			 */
1629			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1630			    m->hold_count == 0) {
1631				pmap_remove_all(m);
1632				vm_page_free(m);
1633			} else if (bp->b_flags & B_DIRECT) {
1634				vm_page_try_to_free(m);
1635			} else if (vm_page_count_severe()) {
1636				vm_page_try_to_cache(m);
1637			}
1638		}
1639	}
1640	vm_page_unlock_queues();
1641	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1642	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1643
1644	if (bp->b_bufsize) {
1645		bufspacewakeup();
1646		bp->b_bufsize = 0;
1647	}
1648	bp->b_npages = 0;
1649	bp->b_flags &= ~B_VMIO;
1650	if (bp->b_vp)
1651		brelvp(bp);
1652}
1653
1654/*
1655 * Check to see if a block at a particular lbn is available for a clustered
1656 * write.
1657 */
1658static int
1659vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1660{
1661	struct buf *bpa;
1662	int match;
1663
1664	match = 0;
1665
1666	/* If the buf isn't in core skip it */
1667	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1668		return (0);
1669
1670	/* If the buf is busy we don't want to wait for it */
1671	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1672		return (0);
1673
1674	/* Only cluster with valid clusterable delayed write buffers */
1675	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1676	    (B_DELWRI | B_CLUSTEROK))
1677		goto done;
1678
1679	if (bpa->b_bufsize != size)
1680		goto done;
1681
1682	/*
1683	 * Check to see if it is in the expected place on disk and that the
1684	 * block has been mapped.
1685	 */
1686	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1687		match = 1;
1688done:
1689	BUF_UNLOCK(bpa);
1690	return (match);
1691}
1692
1693/*
1694 *	vfs_bio_awrite:
1695 *
1696 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1697 *	This is much better then the old way of writing only one buffer at
1698 *	a time.  Note that we may not be presented with the buffers in the
1699 *	correct order, so we search for the cluster in both directions.
1700 */
1701int
1702vfs_bio_awrite(struct buf *bp)
1703{
1704	int i;
1705	int j;
1706	daddr_t lblkno = bp->b_lblkno;
1707	struct vnode *vp = bp->b_vp;
1708	int s;
1709	int ncl;
1710	int nwritten;
1711	int size;
1712	int maxcl;
1713
1714	s = splbio();
1715	/*
1716	 * right now we support clustered writing only to regular files.  If
1717	 * we find a clusterable block we could be in the middle of a cluster
1718	 * rather then at the beginning.
1719	 */
1720	if ((vp->v_type == VREG) &&
1721	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1722	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1723
1724		size = vp->v_mount->mnt_stat.f_iosize;
1725		maxcl = MAXPHYS / size;
1726
1727		VI_LOCK(vp);
1728		for (i = 1; i < maxcl; i++)
1729			if (vfs_bio_clcheck(vp, size, lblkno + i,
1730			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1731				break;
1732
1733		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1734			if (vfs_bio_clcheck(vp, size, lblkno - j,
1735			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1736				break;
1737
1738		VI_UNLOCK(vp);
1739		--j;
1740		ncl = i + j;
1741		/*
1742		 * this is a possible cluster write
1743		 */
1744		if (ncl != 1) {
1745			BUF_UNLOCK(bp);
1746			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1747			splx(s);
1748			return nwritten;
1749		}
1750	}
1751
1752	bremfree(bp);
1753	bp->b_flags |= B_ASYNC;
1754
1755	splx(s);
1756	/*
1757	 * default (old) behavior, writing out only one block
1758	 *
1759	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1760	 */
1761	nwritten = bp->b_bufsize;
1762	(void) bwrite(bp);
1763
1764	return nwritten;
1765}
1766
1767/*
1768 *	getnewbuf:
1769 *
1770 *	Find and initialize a new buffer header, freeing up existing buffers
1771 *	in the bufqueues as necessary.  The new buffer is returned locked.
1772 *
1773 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1774 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1775 *
1776 *	We block if:
1777 *		We have insufficient buffer headers
1778 *		We have insufficient buffer space
1779 *		buffer_map is too fragmented ( space reservation fails )
1780 *		If we have to flush dirty buffers ( but we try to avoid this )
1781 *
1782 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1783 *	Instead we ask the buf daemon to do it for us.  We attempt to
1784 *	avoid piecemeal wakeups of the pageout daemon.
1785 */
1786
1787static struct buf *
1788getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1789{
1790	struct buf *bp;
1791	struct buf *nbp;
1792	int defrag = 0;
1793	int nqindex;
1794	static int flushingbufs;
1795
1796	/*
1797	 * We can't afford to block since we might be holding a vnode lock,
1798	 * which may prevent system daemons from running.  We deal with
1799	 * low-memory situations by proactively returning memory and running
1800	 * async I/O rather then sync I/O.
1801	 */
1802
1803	atomic_add_int(&getnewbufcalls, 1);
1804	atomic_subtract_int(&getnewbufrestarts, 1);
1805restart:
1806	atomic_add_int(&getnewbufrestarts, 1);
1807
1808	/*
1809	 * Setup for scan.  If we do not have enough free buffers,
1810	 * we setup a degenerate case that immediately fails.  Note
1811	 * that if we are specially marked process, we are allowed to
1812	 * dip into our reserves.
1813	 *
1814	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1815	 *
1816	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1817	 * However, there are a number of cases (defragging, reusing, ...)
1818	 * where we cannot backup.
1819	 */
1820	mtx_lock(&bqlock);
1821	nqindex = QUEUE_EMPTYKVA;
1822	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1823
1824	if (nbp == NULL) {
1825		/*
1826		 * If no EMPTYKVA buffers and we are either
1827		 * defragging or reusing, locate a CLEAN buffer
1828		 * to free or reuse.  If bufspace useage is low
1829		 * skip this step so we can allocate a new buffer.
1830		 */
1831		if (defrag || bufspace >= lobufspace) {
1832			nqindex = QUEUE_CLEAN;
1833			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1834		}
1835
1836		/*
1837		 * If we could not find or were not allowed to reuse a
1838		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1839		 * buffer.  We can only use an EMPTY buffer if allocating
1840		 * its KVA would not otherwise run us out of buffer space.
1841		 */
1842		if (nbp == NULL && defrag == 0 &&
1843		    bufspace + maxsize < hibufspace) {
1844			nqindex = QUEUE_EMPTY;
1845			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1846		}
1847	}
1848
1849	/*
1850	 * Run scan, possibly freeing data and/or kva mappings on the fly
1851	 * depending.
1852	 */
1853
1854	while ((bp = nbp) != NULL) {
1855		int qindex = nqindex;
1856
1857		/*
1858		 * Calculate next bp ( we can only use it if we do not block
1859		 * or do other fancy things ).
1860		 */
1861		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1862			switch(qindex) {
1863			case QUEUE_EMPTY:
1864				nqindex = QUEUE_EMPTYKVA;
1865				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1866					break;
1867				/* FALLTHROUGH */
1868			case QUEUE_EMPTYKVA:
1869				nqindex = QUEUE_CLEAN;
1870				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1871					break;
1872				/* FALLTHROUGH */
1873			case QUEUE_CLEAN:
1874				/*
1875				 * nbp is NULL.
1876				 */
1877				break;
1878			}
1879		}
1880		/*
1881		 * If we are defragging then we need a buffer with
1882		 * b_kvasize != 0.  XXX this situation should no longer
1883		 * occur, if defrag is non-zero the buffer's b_kvasize
1884		 * should also be non-zero at this point.  XXX
1885		 */
1886		if (defrag && bp->b_kvasize == 0) {
1887			printf("Warning: defrag empty buffer %p\n", bp);
1888			continue;
1889		}
1890
1891		/*
1892		 * Start freeing the bp.  This is somewhat involved.  nbp
1893		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1894		 */
1895		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1896			continue;
1897		if (bp->b_vp) {
1898			BO_LOCK(bp->b_bufobj);
1899			if (bp->b_vflags & BV_BKGRDINPROG) {
1900				BO_UNLOCK(bp->b_bufobj);
1901				BUF_UNLOCK(bp);
1902				continue;
1903			}
1904			BO_UNLOCK(bp->b_bufobj);
1905		}
1906		CTR3(KTR_BUF, "getnewbuf(%p) vp %p flags %X (recycling)",
1907		    bp, bp->b_vp, bp->b_flags);
1908
1909		/*
1910		 * Sanity Checks
1911		 */
1912		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1913
1914		/*
1915		 * Note: we no longer distinguish between VMIO and non-VMIO
1916		 * buffers.
1917		 */
1918
1919		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1920
1921		bremfreel(bp);
1922		mtx_unlock(&bqlock);
1923
1924		if (qindex == QUEUE_CLEAN) {
1925			if (bp->b_flags & B_VMIO) {
1926				bp->b_flags &= ~B_ASYNC;
1927				vfs_vmio_release(bp);
1928			}
1929			if (bp->b_vp)
1930				brelvp(bp);
1931		}
1932
1933		/*
1934		 * NOTE:  nbp is now entirely invalid.  We can only restart
1935		 * the scan from this point on.
1936		 *
1937		 * Get the rest of the buffer freed up.  b_kva* is still
1938		 * valid after this operation.
1939		 */
1940
1941		if (bp->b_rcred != NOCRED) {
1942			crfree(bp->b_rcred);
1943			bp->b_rcred = NOCRED;
1944		}
1945		if (bp->b_wcred != NOCRED) {
1946			crfree(bp->b_wcred);
1947			bp->b_wcred = NOCRED;
1948		}
1949		if (LIST_FIRST(&bp->b_dep) != NULL)
1950			buf_deallocate(bp);
1951		if (bp->b_vflags & BV_BKGRDINPROG)
1952			panic("losing buffer 3");
1953
1954		if (bp->b_bufsize)
1955			allocbuf(bp, 0);
1956
1957		bp->b_flags = 0;
1958		bp->b_ioflags = 0;
1959		bp->b_xflags = 0;
1960		bp->b_vflags = 0;
1961		bp->b_vp = NULL;
1962		bp->b_blkno = bp->b_lblkno = 0;
1963		bp->b_offset = NOOFFSET;
1964		bp->b_iodone = 0;
1965		bp->b_error = 0;
1966		bp->b_resid = 0;
1967		bp->b_bcount = 0;
1968		bp->b_npages = 0;
1969		bp->b_dirtyoff = bp->b_dirtyend = 0;
1970		bp->b_bufobj = NULL;
1971
1972		LIST_INIT(&bp->b_dep);
1973
1974		/*
1975		 * If we are defragging then free the buffer.
1976		 */
1977		if (defrag) {
1978			bp->b_flags |= B_INVAL;
1979			bfreekva(bp);
1980			brelse(bp);
1981			defrag = 0;
1982			goto restart;
1983		}
1984
1985		/*
1986		 * If we are overcomitted then recover the buffer and its
1987		 * KVM space.  This occurs in rare situations when multiple
1988		 * processes are blocked in getnewbuf() or allocbuf().
1989		 */
1990		if (bufspace >= hibufspace)
1991			flushingbufs = 1;
1992		if (flushingbufs && bp->b_kvasize != 0) {
1993			bp->b_flags |= B_INVAL;
1994			bfreekva(bp);
1995			brelse(bp);
1996			goto restart;
1997		}
1998		if (bufspace < lobufspace)
1999			flushingbufs = 0;
2000		break;
2001	}
2002
2003	/*
2004	 * If we exhausted our list, sleep as appropriate.  We may have to
2005	 * wakeup various daemons and write out some dirty buffers.
2006	 *
2007	 * Generally we are sleeping due to insufficient buffer space.
2008	 */
2009
2010	if (bp == NULL) {
2011		int flags;
2012		char *waitmsg;
2013
2014		mtx_unlock(&bqlock);
2015		if (defrag) {
2016			flags = VFS_BIO_NEED_BUFSPACE;
2017			waitmsg = "nbufkv";
2018		} else if (bufspace >= hibufspace) {
2019			waitmsg = "nbufbs";
2020			flags = VFS_BIO_NEED_BUFSPACE;
2021		} else {
2022			waitmsg = "newbuf";
2023			flags = VFS_BIO_NEED_ANY;
2024		}
2025
2026		bd_speedup();	/* heeeelp */
2027
2028		mtx_lock(&nblock);
2029		needsbuffer |= flags;
2030		while (needsbuffer & flags) {
2031			if (msleep(&needsbuffer, &nblock,
2032			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2033				mtx_unlock(&nblock);
2034				return (NULL);
2035			}
2036		}
2037		mtx_unlock(&nblock);
2038	} else {
2039		/*
2040		 * We finally have a valid bp.  We aren't quite out of the
2041		 * woods, we still have to reserve kva space.  In order
2042		 * to keep fragmentation sane we only allocate kva in
2043		 * BKVASIZE chunks.
2044		 */
2045		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2046
2047		if (maxsize != bp->b_kvasize) {
2048			vm_offset_t addr = 0;
2049
2050			bfreekva(bp);
2051
2052			if (vm_map_findspace(buffer_map,
2053				vm_map_min(buffer_map), maxsize, &addr)) {
2054				/*
2055				 * Uh oh.  Buffer map is to fragmented.  We
2056				 * must defragment the map.
2057				 */
2058				atomic_add_int(&bufdefragcnt, 1);
2059				defrag = 1;
2060				bp->b_flags |= B_INVAL;
2061				brelse(bp);
2062				goto restart;
2063			}
2064			if (addr) {
2065				vm_map_insert(buffer_map, NULL, 0,
2066					addr, addr + maxsize,
2067					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2068
2069				bp->b_kvabase = (caddr_t) addr;
2070				bp->b_kvasize = maxsize;
2071				atomic_add_int(&bufspace, bp->b_kvasize);
2072				atomic_add_int(&bufreusecnt, 1);
2073			}
2074		}
2075		bp->b_saveaddr = bp->b_kvabase;
2076		bp->b_data = bp->b_saveaddr;
2077	}
2078	return(bp);
2079}
2080
2081/*
2082 *	buf_daemon:
2083 *
2084 *	buffer flushing daemon.  Buffers are normally flushed by the
2085 *	update daemon but if it cannot keep up this process starts to
2086 *	take the load in an attempt to prevent getnewbuf() from blocking.
2087 */
2088
2089static struct kproc_desc buf_kp = {
2090	"bufdaemon",
2091	buf_daemon,
2092	&bufdaemonproc
2093};
2094SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2095
2096static void
2097buf_daemon()
2098{
2099	int s;
2100
2101	mtx_lock(&Giant);
2102
2103	/*
2104	 * This process needs to be suspended prior to shutdown sync.
2105	 */
2106	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2107	    SHUTDOWN_PRI_LAST);
2108
2109	/*
2110	 * This process is allowed to take the buffer cache to the limit
2111	 */
2112	s = splbio();
2113	mtx_lock(&bdlock);
2114
2115	for (;;) {
2116		bd_request = 0;
2117		mtx_unlock(&bdlock);
2118
2119		kthread_suspend_check(bufdaemonproc);
2120
2121		/*
2122		 * Do the flush.  Limit the amount of in-transit I/O we
2123		 * allow to build up, otherwise we would completely saturate
2124		 * the I/O system.  Wakeup any waiting processes before we
2125		 * normally would so they can run in parallel with our drain.
2126		 */
2127		while (numdirtybuffers > lodirtybuffers) {
2128			if (flushbufqueues(0) == 0) {
2129				/*
2130				 * Could not find any buffers without rollback
2131				 * dependencies, so just write the first one
2132				 * in the hopes of eventually making progress.
2133				 */
2134				flushbufqueues(1);
2135				break;
2136			}
2137			waitrunningbufspace();
2138			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2139		}
2140
2141		/*
2142		 * Only clear bd_request if we have reached our low water
2143		 * mark.  The buf_daemon normally waits 1 second and
2144		 * then incrementally flushes any dirty buffers that have
2145		 * built up, within reason.
2146		 *
2147		 * If we were unable to hit our low water mark and couldn't
2148		 * find any flushable buffers, we sleep half a second.
2149		 * Otherwise we loop immediately.
2150		 */
2151		mtx_lock(&bdlock);
2152		if (numdirtybuffers <= lodirtybuffers) {
2153			/*
2154			 * We reached our low water mark, reset the
2155			 * request and sleep until we are needed again.
2156			 * The sleep is just so the suspend code works.
2157			 */
2158			bd_request = 0;
2159			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2160		} else {
2161			/*
2162			 * We couldn't find any flushable dirty buffers but
2163			 * still have too many dirty buffers, we
2164			 * have to sleep and try again.  (rare)
2165			 */
2166			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2167		}
2168	}
2169}
2170
2171/*
2172 *	flushbufqueues:
2173 *
2174 *	Try to flush a buffer in the dirty queue.  We must be careful to
2175 *	free up B_INVAL buffers instead of write them, which NFS is
2176 *	particularly sensitive to.
2177 */
2178int flushwithdeps = 0;
2179SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2180    0, "Number of buffers flushed with dependecies that require rollbacks");
2181
2182static int
2183flushbufqueues(int flushdeps)
2184{
2185	struct thread *td = curthread;
2186	struct vnode *vp;
2187	struct mount *mp;
2188	struct buf *bp;
2189	int hasdeps;
2190
2191	mtx_lock(&bqlock);
2192	TAILQ_FOREACH(bp, &bufqueues[QUEUE_DIRTY], b_freelist) {
2193		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2194			continue;
2195		BO_LOCK(bp->b_bufobj);
2196		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2197		    (bp->b_flags & B_DELWRI) == 0) {
2198			BO_UNLOCK(bp->b_bufobj);
2199			BUF_UNLOCK(bp);
2200			continue;
2201		}
2202		BO_UNLOCK(bp->b_bufobj);
2203		if (bp->b_flags & B_INVAL) {
2204			bremfreel(bp);
2205			mtx_unlock(&bqlock);
2206			brelse(bp);
2207			return (1);
2208		}
2209
2210		if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2211			if (flushdeps == 0) {
2212				BUF_UNLOCK(bp);
2213				continue;
2214			}
2215			hasdeps = 1;
2216		} else
2217			hasdeps = 0;
2218		/*
2219		 * We must hold the lock on a vnode before writing
2220		 * one of its buffers. Otherwise we may confuse, or
2221		 * in the case of a snapshot vnode, deadlock the
2222		 * system.
2223		 *
2224		 * The lock order here is the reverse of the normal
2225		 * of vnode followed by buf lock.  This is ok because
2226		 * the NOWAIT will prevent deadlock.
2227		 */
2228		vp = bp->b_vp;
2229		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2230			BUF_UNLOCK(bp);
2231			continue;
2232		}
2233		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2234			mtx_unlock(&bqlock);
2235			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2236			    bp, bp->b_vp, bp->b_flags);
2237			vfs_bio_awrite(bp);
2238			vn_finished_write(mp);
2239			VOP_UNLOCK(vp, 0, td);
2240			flushwithdeps += hasdeps;
2241			return (1);
2242		}
2243		vn_finished_write(mp);
2244		BUF_UNLOCK(bp);
2245	}
2246	mtx_unlock(&bqlock);
2247	return (0);
2248}
2249
2250/*
2251 * Check to see if a block is currently memory resident.
2252 */
2253struct buf *
2254incore(struct bufobj *bo, daddr_t blkno)
2255{
2256	struct buf *bp;
2257
2258	int s = splbio();
2259	BO_LOCK(bo);
2260	bp = gbincore(bo, blkno);
2261	BO_UNLOCK(bo);
2262	splx(s);
2263	return (bp);
2264}
2265
2266/*
2267 * Returns true if no I/O is needed to access the
2268 * associated VM object.  This is like incore except
2269 * it also hunts around in the VM system for the data.
2270 */
2271
2272static int
2273inmem(struct vnode * vp, daddr_t blkno)
2274{
2275	vm_object_t obj;
2276	vm_offset_t toff, tinc, size;
2277	vm_page_t m;
2278	vm_ooffset_t off;
2279
2280	ASSERT_VOP_LOCKED(vp, "inmem");
2281
2282	if (incore(&vp->v_bufobj, blkno))
2283		return 1;
2284	if (vp->v_mount == NULL)
2285		return 0;
2286	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_vflag & VV_OBJBUF) == 0)
2287		return 0;
2288
2289	size = PAGE_SIZE;
2290	if (size > vp->v_mount->mnt_stat.f_iosize)
2291		size = vp->v_mount->mnt_stat.f_iosize;
2292	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2293
2294	VM_OBJECT_LOCK(obj);
2295	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2296		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2297		if (!m)
2298			goto notinmem;
2299		tinc = size;
2300		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2301			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2302		if (vm_page_is_valid(m,
2303		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2304			goto notinmem;
2305	}
2306	VM_OBJECT_UNLOCK(obj);
2307	return 1;
2308
2309notinmem:
2310	VM_OBJECT_UNLOCK(obj);
2311	return (0);
2312}
2313
2314/*
2315 *	vfs_setdirty:
2316 *
2317 *	Sets the dirty range for a buffer based on the status of the dirty
2318 *	bits in the pages comprising the buffer.
2319 *
2320 *	The range is limited to the size of the buffer.
2321 *
2322 *	This routine is primarily used by NFS, but is generalized for the
2323 *	B_VMIO case.
2324 */
2325static void
2326vfs_setdirty(struct buf *bp)
2327{
2328	int i;
2329	vm_object_t object;
2330
2331	/*
2332	 * Degenerate case - empty buffer
2333	 */
2334
2335	if (bp->b_bufsize == 0)
2336		return;
2337
2338	/*
2339	 * We qualify the scan for modified pages on whether the
2340	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2341	 * is not cleared simply by protecting pages off.
2342	 */
2343
2344	if ((bp->b_flags & B_VMIO) == 0)
2345		return;
2346
2347	object = bp->b_pages[0]->object;
2348	VM_OBJECT_LOCK(object);
2349	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2350		printf("Warning: object %p writeable but not mightbedirty\n", object);
2351	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2352		printf("Warning: object %p mightbedirty but not writeable\n", object);
2353
2354	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2355		vm_offset_t boffset;
2356		vm_offset_t eoffset;
2357
2358		vm_page_lock_queues();
2359		/*
2360		 * test the pages to see if they have been modified directly
2361		 * by users through the VM system.
2362		 */
2363		for (i = 0; i < bp->b_npages; i++)
2364			vm_page_test_dirty(bp->b_pages[i]);
2365
2366		/*
2367		 * Calculate the encompassing dirty range, boffset and eoffset,
2368		 * (eoffset - boffset) bytes.
2369		 */
2370
2371		for (i = 0; i < bp->b_npages; i++) {
2372			if (bp->b_pages[i]->dirty)
2373				break;
2374		}
2375		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2376
2377		for (i = bp->b_npages - 1; i >= 0; --i) {
2378			if (bp->b_pages[i]->dirty) {
2379				break;
2380			}
2381		}
2382		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2383
2384		vm_page_unlock_queues();
2385		/*
2386		 * Fit it to the buffer.
2387		 */
2388
2389		if (eoffset > bp->b_bcount)
2390			eoffset = bp->b_bcount;
2391
2392		/*
2393		 * If we have a good dirty range, merge with the existing
2394		 * dirty range.
2395		 */
2396
2397		if (boffset < eoffset) {
2398			if (bp->b_dirtyoff > boffset)
2399				bp->b_dirtyoff = boffset;
2400			if (bp->b_dirtyend < eoffset)
2401				bp->b_dirtyend = eoffset;
2402		}
2403	}
2404	VM_OBJECT_UNLOCK(object);
2405}
2406
2407/*
2408 *	getblk:
2409 *
2410 *	Get a block given a specified block and offset into a file/device.
2411 *	The buffers B_DONE bit will be cleared on return, making it almost
2412 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2413 *	return.  The caller should clear B_INVAL prior to initiating a
2414 *	READ.
2415 *
2416 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2417 *	an existing buffer.
2418 *
2419 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2420 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2421 *	and then cleared based on the backing VM.  If the previous buffer is
2422 *	non-0-sized but invalid, B_CACHE will be cleared.
2423 *
2424 *	If getblk() must create a new buffer, the new buffer is returned with
2425 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2426 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2427 *	backing VM.
2428 *
2429 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2430 *	B_CACHE bit is clear.
2431 *
2432 *	What this means, basically, is that the caller should use B_CACHE to
2433 *	determine whether the buffer is fully valid or not and should clear
2434 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2435 *	the buffer by loading its data area with something, the caller needs
2436 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2437 *	the caller should set B_CACHE ( as an optimization ), else the caller
2438 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2439 *	a write attempt or if it was a successfull read.  If the caller
2440 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2441 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2442 */
2443struct buf *
2444getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2445    int flags)
2446{
2447	struct buf *bp;
2448	struct bufobj *bo;
2449	int s;
2450	int error;
2451	struct vm_object *vmo;
2452
2453	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2454	ASSERT_VOP_LOCKED(vp, "getblk");
2455	if (size > MAXBSIZE)
2456		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2457
2458	bo = &vp->v_bufobj;
2459	s = splbio();
2460loop:
2461	/*
2462	 * Block if we are low on buffers.   Certain processes are allowed
2463	 * to completely exhaust the buffer cache.
2464         *
2465         * If this check ever becomes a bottleneck it may be better to
2466         * move it into the else, when gbincore() fails.  At the moment
2467         * it isn't a problem.
2468	 *
2469	 * XXX remove if 0 sections (clean this up after its proven)
2470         */
2471	if (numfreebuffers == 0) {
2472		if (curthread == PCPU_GET(idlethread))
2473			return NULL;
2474		mtx_lock(&nblock);
2475		needsbuffer |= VFS_BIO_NEED_ANY;
2476		mtx_unlock(&nblock);
2477	}
2478
2479	VI_LOCK(vp);
2480	bp = gbincore(bo, blkno);
2481	if (bp != NULL) {
2482		int lockflags;
2483		/*
2484		 * Buffer is in-core.  If the buffer is not busy, it must
2485		 * be on a queue.
2486		 */
2487		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2488
2489		if (flags & GB_LOCK_NOWAIT)
2490			lockflags |= LK_NOWAIT;
2491
2492		error = BUF_TIMELOCK(bp, lockflags,
2493		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2494
2495		/*
2496		 * If we slept and got the lock we have to restart in case
2497		 * the buffer changed identities.
2498		 */
2499		if (error == ENOLCK)
2500			goto loop;
2501		/* We timed out or were interrupted. */
2502		else if (error)
2503			return (NULL);
2504
2505		/*
2506		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2507		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2508		 * and for a VMIO buffer B_CACHE is adjusted according to the
2509		 * backing VM cache.
2510		 */
2511		if (bp->b_flags & B_INVAL)
2512			bp->b_flags &= ~B_CACHE;
2513		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2514			bp->b_flags |= B_CACHE;
2515		bremfree(bp);
2516
2517		/*
2518		 * check for size inconsistancies for non-VMIO case.
2519		 */
2520
2521		if (bp->b_bcount != size) {
2522			if ((bp->b_flags & B_VMIO) == 0 ||
2523			    (size > bp->b_kvasize)) {
2524				if (bp->b_flags & B_DELWRI) {
2525					bp->b_flags |= B_NOCACHE;
2526					bwrite(bp);
2527				} else {
2528					if ((bp->b_flags & B_VMIO) &&
2529					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2530						bp->b_flags |= B_RELBUF;
2531						brelse(bp);
2532					} else {
2533						bp->b_flags |= B_NOCACHE;
2534						bwrite(bp);
2535					}
2536				}
2537				goto loop;
2538			}
2539		}
2540
2541		/*
2542		 * If the size is inconsistant in the VMIO case, we can resize
2543		 * the buffer.  This might lead to B_CACHE getting set or
2544		 * cleared.  If the size has not changed, B_CACHE remains
2545		 * unchanged from its previous state.
2546		 */
2547
2548		if (bp->b_bcount != size)
2549			allocbuf(bp, size);
2550
2551		KASSERT(bp->b_offset != NOOFFSET,
2552		    ("getblk: no buffer offset"));
2553
2554		/*
2555		 * A buffer with B_DELWRI set and B_CACHE clear must
2556		 * be committed before we can return the buffer in
2557		 * order to prevent the caller from issuing a read
2558		 * ( due to B_CACHE not being set ) and overwriting
2559		 * it.
2560		 *
2561		 * Most callers, including NFS and FFS, need this to
2562		 * operate properly either because they assume they
2563		 * can issue a read if B_CACHE is not set, or because
2564		 * ( for example ) an uncached B_DELWRI might loop due
2565		 * to softupdates re-dirtying the buffer.  In the latter
2566		 * case, B_CACHE is set after the first write completes,
2567		 * preventing further loops.
2568		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2569		 * above while extending the buffer, we cannot allow the
2570		 * buffer to remain with B_CACHE set after the write
2571		 * completes or it will represent a corrupt state.  To
2572		 * deal with this we set B_NOCACHE to scrap the buffer
2573		 * after the write.
2574		 *
2575		 * We might be able to do something fancy, like setting
2576		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2577		 * so the below call doesn't set B_CACHE, but that gets real
2578		 * confusing.  This is much easier.
2579		 */
2580
2581		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2582			bp->b_flags |= B_NOCACHE;
2583			bwrite(bp);
2584			goto loop;
2585		}
2586
2587		splx(s);
2588		bp->b_flags &= ~B_DONE;
2589	} else {
2590		int bsize, maxsize, vmio;
2591		off_t offset;
2592
2593		/*
2594		 * Buffer is not in-core, create new buffer.  The buffer
2595		 * returned by getnewbuf() is locked.  Note that the returned
2596		 * buffer is also considered valid (not marked B_INVAL).
2597		 */
2598		VI_UNLOCK(vp);
2599		/*
2600		 * If the user does not want us to create the buffer, bail out
2601		 * here.
2602		 */
2603		if (flags & GB_NOCREAT) {
2604			splx(s);
2605			return NULL;
2606		}
2607
2608		bsize = bo->bo_bsize;
2609		offset = blkno * bsize;
2610		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) &&
2611		    (vp->v_vflag & VV_OBJBUF);
2612		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2613		maxsize = imax(maxsize, bsize);
2614
2615		bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2616		if (bp == NULL) {
2617			if (slpflag || slptimeo) {
2618				splx(s);
2619				return NULL;
2620			}
2621			goto loop;
2622		}
2623
2624		/*
2625		 * This code is used to make sure that a buffer is not
2626		 * created while the getnewbuf routine is blocked.
2627		 * This can be a problem whether the vnode is locked or not.
2628		 * If the buffer is created out from under us, we have to
2629		 * throw away the one we just created.  There is now window
2630		 * race because we are safely running at splbio() from the
2631		 * point of the duplicate buffer creation through to here,
2632		 * and we've locked the buffer.
2633		 *
2634		 * Note: this must occur before we associate the buffer
2635		 * with the vp especially considering limitations in
2636		 * the splay tree implementation when dealing with duplicate
2637		 * lblkno's.
2638		 */
2639		BO_LOCK(bo);
2640		if (gbincore(bo, blkno)) {
2641			BO_UNLOCK(bo);
2642			bp->b_flags |= B_INVAL;
2643			brelse(bp);
2644			goto loop;
2645		}
2646
2647		/*
2648		 * Insert the buffer into the hash, so that it can
2649		 * be found by incore.
2650		 */
2651		bp->b_blkno = bp->b_lblkno = blkno;
2652		bp->b_offset = offset;
2653
2654		bgetvp(vp, bp);
2655		BO_UNLOCK(bo);
2656
2657		/*
2658		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2659		 * buffer size starts out as 0, B_CACHE will be set by
2660		 * allocbuf() for the VMIO case prior to it testing the
2661		 * backing store for validity.
2662		 */
2663
2664		if (vmio) {
2665			bp->b_flags |= B_VMIO;
2666#if defined(VFS_BIO_DEBUG)
2667			if (vn_canvmio(vp) != TRUE)
2668				printf("getblk: VMIO on vnode type %d\n",
2669					vp->v_type);
2670#endif
2671			VOP_GETVOBJECT(vp, &vmo);
2672			KASSERT(vmo == bp->b_bufobj->bo_object,
2673			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2674			    bp, vmo, bp->b_bufobj->bo_object));
2675		} else {
2676			bp->b_flags &= ~B_VMIO;
2677			KASSERT(bp->b_bufobj->bo_object == NULL,
2678			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2679			    bp, bp->b_bufobj->bo_object));
2680		}
2681
2682		allocbuf(bp, size);
2683
2684		splx(s);
2685		bp->b_flags &= ~B_DONE;
2686	}
2687	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2688	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2689	KASSERT(bp->b_bufobj == bo,
2690	    ("wrong b_bufobj %p should be %p", bp->b_bufobj, bo));
2691	return (bp);
2692}
2693
2694/*
2695 * Get an empty, disassociated buffer of given size.  The buffer is initially
2696 * set to B_INVAL.
2697 */
2698struct buf *
2699geteblk(int size)
2700{
2701	struct buf *bp;
2702	int s;
2703	int maxsize;
2704
2705	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2706
2707	s = splbio();
2708	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2709		continue;
2710	splx(s);
2711	allocbuf(bp, size);
2712	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2713	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2714	return (bp);
2715}
2716
2717
2718/*
2719 * This code constitutes the buffer memory from either anonymous system
2720 * memory (in the case of non-VMIO operations) or from an associated
2721 * VM object (in the case of VMIO operations).  This code is able to
2722 * resize a buffer up or down.
2723 *
2724 * Note that this code is tricky, and has many complications to resolve
2725 * deadlock or inconsistant data situations.  Tread lightly!!!
2726 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2727 * the caller.  Calling this code willy nilly can result in the loss of data.
2728 *
2729 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2730 * B_CACHE for the non-VMIO case.
2731 */
2732
2733int
2734allocbuf(struct buf *bp, int size)
2735{
2736	int newbsize, mbsize;
2737	int i;
2738
2739	if (BUF_REFCNT(bp) == 0)
2740		panic("allocbuf: buffer not busy");
2741
2742	if (bp->b_kvasize < size)
2743		panic("allocbuf: buffer too small");
2744
2745	if ((bp->b_flags & B_VMIO) == 0) {
2746		caddr_t origbuf;
2747		int origbufsize;
2748		/*
2749		 * Just get anonymous memory from the kernel.  Don't
2750		 * mess with B_CACHE.
2751		 */
2752		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2753		if (bp->b_flags & B_MALLOC)
2754			newbsize = mbsize;
2755		else
2756			newbsize = round_page(size);
2757
2758		if (newbsize < bp->b_bufsize) {
2759			/*
2760			 * malloced buffers are not shrunk
2761			 */
2762			if (bp->b_flags & B_MALLOC) {
2763				if (newbsize) {
2764					bp->b_bcount = size;
2765				} else {
2766					free(bp->b_data, M_BIOBUF);
2767					if (bp->b_bufsize) {
2768						atomic_subtract_int(
2769						    &bufmallocspace,
2770						    bp->b_bufsize);
2771						bufspacewakeup();
2772						bp->b_bufsize = 0;
2773					}
2774					bp->b_saveaddr = bp->b_kvabase;
2775					bp->b_data = bp->b_saveaddr;
2776					bp->b_bcount = 0;
2777					bp->b_flags &= ~B_MALLOC;
2778				}
2779				return 1;
2780			}
2781			vm_hold_free_pages(
2782			    bp,
2783			    (vm_offset_t) bp->b_data + newbsize,
2784			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2785		} else if (newbsize > bp->b_bufsize) {
2786			/*
2787			 * We only use malloced memory on the first allocation.
2788			 * and revert to page-allocated memory when the buffer
2789			 * grows.
2790			 */
2791			/*
2792			 * There is a potential smp race here that could lead
2793			 * to bufmallocspace slightly passing the max.  It
2794			 * is probably extremely rare and not worth worrying
2795			 * over.
2796			 */
2797			if ( (bufmallocspace < maxbufmallocspace) &&
2798				(bp->b_bufsize == 0) &&
2799				(mbsize <= PAGE_SIZE/2)) {
2800
2801				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2802				bp->b_bufsize = mbsize;
2803				bp->b_bcount = size;
2804				bp->b_flags |= B_MALLOC;
2805				atomic_add_int(&bufmallocspace, mbsize);
2806				return 1;
2807			}
2808			origbuf = NULL;
2809			origbufsize = 0;
2810			/*
2811			 * If the buffer is growing on its other-than-first allocation,
2812			 * then we revert to the page-allocation scheme.
2813			 */
2814			if (bp->b_flags & B_MALLOC) {
2815				origbuf = bp->b_data;
2816				origbufsize = bp->b_bufsize;
2817				bp->b_data = bp->b_kvabase;
2818				if (bp->b_bufsize) {
2819					atomic_subtract_int(&bufmallocspace,
2820					    bp->b_bufsize);
2821					bufspacewakeup();
2822					bp->b_bufsize = 0;
2823				}
2824				bp->b_flags &= ~B_MALLOC;
2825				newbsize = round_page(newbsize);
2826			}
2827			vm_hold_load_pages(
2828			    bp,
2829			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2830			    (vm_offset_t) bp->b_data + newbsize);
2831			if (origbuf) {
2832				bcopy(origbuf, bp->b_data, origbufsize);
2833				free(origbuf, M_BIOBUF);
2834			}
2835		}
2836	} else {
2837		int desiredpages;
2838
2839		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2840		desiredpages = (size == 0) ? 0 :
2841			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2842
2843		if (bp->b_flags & B_MALLOC)
2844			panic("allocbuf: VMIO buffer can't be malloced");
2845		/*
2846		 * Set B_CACHE initially if buffer is 0 length or will become
2847		 * 0-length.
2848		 */
2849		if (size == 0 || bp->b_bufsize == 0)
2850			bp->b_flags |= B_CACHE;
2851
2852		if (newbsize < bp->b_bufsize) {
2853			/*
2854			 * DEV_BSIZE aligned new buffer size is less then the
2855			 * DEV_BSIZE aligned existing buffer size.  Figure out
2856			 * if we have to remove any pages.
2857			 */
2858			if (desiredpages < bp->b_npages) {
2859				vm_page_t m;
2860
2861				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2862				vm_page_lock_queues();
2863				for (i = desiredpages; i < bp->b_npages; i++) {
2864					/*
2865					 * the page is not freed here -- it
2866					 * is the responsibility of
2867					 * vnode_pager_setsize
2868					 */
2869					m = bp->b_pages[i];
2870					KASSERT(m != bogus_page,
2871					    ("allocbuf: bogus page found"));
2872					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2873						vm_page_lock_queues();
2874
2875					bp->b_pages[i] = NULL;
2876					vm_page_unwire(m, 0);
2877				}
2878				vm_page_unlock_queues();
2879				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2880				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2881				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2882				bp->b_npages = desiredpages;
2883			}
2884		} else if (size > bp->b_bcount) {
2885			/*
2886			 * We are growing the buffer, possibly in a
2887			 * byte-granular fashion.
2888			 */
2889			struct vnode *vp;
2890			vm_object_t obj;
2891			vm_offset_t toff;
2892			vm_offset_t tinc;
2893
2894			/*
2895			 * Step 1, bring in the VM pages from the object,
2896			 * allocating them if necessary.  We must clear
2897			 * B_CACHE if these pages are not valid for the
2898			 * range covered by the buffer.
2899			 */
2900
2901			vp = bp->b_vp;
2902			obj = bp->b_bufobj->bo_object;
2903
2904			VM_OBJECT_LOCK(obj);
2905			while (bp->b_npages < desiredpages) {
2906				vm_page_t m;
2907				vm_pindex_t pi;
2908
2909				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2910				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2911					/*
2912					 * note: must allocate system pages
2913					 * since blocking here could intefere
2914					 * with paging I/O, no matter which
2915					 * process we are.
2916					 */
2917					m = vm_page_alloc(obj, pi,
2918					    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2919					    VM_ALLOC_WIRED);
2920					if (m == NULL) {
2921						atomic_add_int(&vm_pageout_deficit,
2922						    desiredpages - bp->b_npages);
2923						VM_OBJECT_UNLOCK(obj);
2924						VM_WAIT;
2925						VM_OBJECT_LOCK(obj);
2926					} else {
2927						bp->b_flags &= ~B_CACHE;
2928						bp->b_pages[bp->b_npages] = m;
2929						++bp->b_npages;
2930					}
2931					continue;
2932				}
2933
2934				/*
2935				 * We found a page.  If we have to sleep on it,
2936				 * retry because it might have gotten freed out
2937				 * from under us.
2938				 *
2939				 * We can only test PG_BUSY here.  Blocking on
2940				 * m->busy might lead to a deadlock:
2941				 *
2942				 *  vm_fault->getpages->cluster_read->allocbuf
2943				 *
2944				 */
2945				vm_page_lock_queues();
2946				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2947					continue;
2948
2949				/*
2950				 * We have a good page.  Should we wakeup the
2951				 * page daemon?
2952				 */
2953				if ((curproc != pageproc) &&
2954				    ((m->queue - m->pc) == PQ_CACHE) &&
2955				    ((cnt.v_free_count + cnt.v_cache_count) <
2956					(cnt.v_free_min + cnt.v_cache_min))) {
2957					pagedaemon_wakeup();
2958				}
2959				vm_page_wire(m);
2960				vm_page_unlock_queues();
2961				bp->b_pages[bp->b_npages] = m;
2962				++bp->b_npages;
2963			}
2964
2965			/*
2966			 * Step 2.  We've loaded the pages into the buffer,
2967			 * we have to figure out if we can still have B_CACHE
2968			 * set.  Note that B_CACHE is set according to the
2969			 * byte-granular range ( bcount and size ), new the
2970			 * aligned range ( newbsize ).
2971			 *
2972			 * The VM test is against m->valid, which is DEV_BSIZE
2973			 * aligned.  Needless to say, the validity of the data
2974			 * needs to also be DEV_BSIZE aligned.  Note that this
2975			 * fails with NFS if the server or some other client
2976			 * extends the file's EOF.  If our buffer is resized,
2977			 * B_CACHE may remain set! XXX
2978			 */
2979
2980			toff = bp->b_bcount;
2981			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2982
2983			while ((bp->b_flags & B_CACHE) && toff < size) {
2984				vm_pindex_t pi;
2985
2986				if (tinc > (size - toff))
2987					tinc = size - toff;
2988
2989				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2990				    PAGE_SHIFT;
2991
2992				vfs_buf_test_cache(
2993				    bp,
2994				    bp->b_offset,
2995				    toff,
2996				    tinc,
2997				    bp->b_pages[pi]
2998				);
2999				toff += tinc;
3000				tinc = PAGE_SIZE;
3001			}
3002			VM_OBJECT_UNLOCK(obj);
3003
3004			/*
3005			 * Step 3, fixup the KVM pmap.  Remember that
3006			 * bp->b_data is relative to bp->b_offset, but
3007			 * bp->b_offset may be offset into the first page.
3008			 */
3009
3010			bp->b_data = (caddr_t)
3011			    trunc_page((vm_offset_t)bp->b_data);
3012			pmap_qenter(
3013			    (vm_offset_t)bp->b_data,
3014			    bp->b_pages,
3015			    bp->b_npages
3016			);
3017
3018			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3019			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
3020		}
3021	}
3022	if (newbsize < bp->b_bufsize)
3023		bufspacewakeup();
3024	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3025	bp->b_bcount = size;		/* requested buffer size	*/
3026	return 1;
3027}
3028
3029void
3030biodone(struct bio *bp)
3031{
3032
3033	mtx_lock(&bdonelock);
3034	bp->bio_flags |= BIO_DONE;
3035	if (bp->bio_done == NULL)
3036		wakeup(bp);
3037	mtx_unlock(&bdonelock);
3038	if (bp->bio_done != NULL)
3039		bp->bio_done(bp);
3040}
3041
3042/*
3043 * Wait for a BIO to finish.
3044 *
3045 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3046 * case is not yet clear.
3047 */
3048int
3049biowait(struct bio *bp, const char *wchan)
3050{
3051
3052	mtx_lock(&bdonelock);
3053	while ((bp->bio_flags & BIO_DONE) == 0)
3054		msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
3055	mtx_unlock(&bdonelock);
3056	if (bp->bio_error != 0)
3057		return (bp->bio_error);
3058	if (!(bp->bio_flags & BIO_ERROR))
3059		return (0);
3060	return (EIO);
3061}
3062
3063void
3064biofinish(struct bio *bp, struct devstat *stat, int error)
3065{
3066
3067	if (error) {
3068		bp->bio_error = error;
3069		bp->bio_flags |= BIO_ERROR;
3070	}
3071	if (stat != NULL)
3072		devstat_end_transaction_bio(stat, bp);
3073	biodone(bp);
3074}
3075
3076/*
3077 *	bufwait:
3078 *
3079 *	Wait for buffer I/O completion, returning error status.  The buffer
3080 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3081 *	error and cleared.
3082 */
3083int
3084bufwait(struct buf *bp)
3085{
3086	int s;
3087
3088	s = splbio();
3089	if (bp->b_iocmd == BIO_READ)
3090		bwait(bp, PRIBIO, "biord");
3091	else
3092		bwait(bp, PRIBIO, "biowr");
3093	splx(s);
3094	if (bp->b_flags & B_EINTR) {
3095		bp->b_flags &= ~B_EINTR;
3096		return (EINTR);
3097	}
3098	if (bp->b_ioflags & BIO_ERROR) {
3099		return (bp->b_error ? bp->b_error : EIO);
3100	} else {
3101		return (0);
3102	}
3103}
3104
3105 /*
3106  * Call back function from struct bio back up to struct buf.
3107  */
3108static void
3109bufdonebio(struct bio *bip)
3110{
3111	struct buf *bp;
3112
3113	bp = bip->bio_caller2;
3114	bp->b_resid = bp->b_bcount - bip->bio_completed;
3115	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3116	bp->b_ioflags = bip->bio_flags;
3117	bp->b_error = bip->bio_error;
3118	if (bp->b_error)
3119		bp->b_ioflags |= BIO_ERROR;
3120	bufdone(bp);
3121	g_destroy_bio(bip);
3122}
3123
3124void
3125dev_strategy(struct cdev *dev, struct buf *bp)
3126{
3127	struct cdevsw *csw;
3128	struct bio *bip;
3129
3130	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3131		panic("b_iocmd botch");
3132	for (;;) {
3133		bip = g_new_bio();
3134		if (bip != NULL)
3135			break;
3136		/* Try again later */
3137		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3138	}
3139	bip->bio_cmd = bp->b_iocmd;
3140	bip->bio_offset = bp->b_iooffset;
3141	bip->bio_length = bp->b_bcount;
3142	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3143	bip->bio_data = bp->b_data;
3144	bip->bio_done = bufdonebio;
3145	bip->bio_caller2 = bp;
3146	bip->bio_dev = dev;
3147	KASSERT(dev->si_refcount > 0,
3148	    ("dev_strategy on un-referenced struct cdev *(%s)",
3149	    devtoname(dev)));
3150	csw = dev_refthread(dev);
3151	if (csw == NULL) {
3152		bp->b_error = ENXIO;
3153		bp->b_ioflags = BIO_ERROR;
3154		bufdone(bp);
3155		return;
3156	}
3157	(*csw->d_strategy)(bip);
3158	dev_relthread(dev);
3159}
3160
3161/*
3162 *	bufdone:
3163 *
3164 *	Finish I/O on a buffer, optionally calling a completion function.
3165 *	This is usually called from an interrupt so process blocking is
3166 *	not allowed.
3167 *
3168 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3169 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3170 *	assuming B_INVAL is clear.
3171 *
3172 *	For the VMIO case, we set B_CACHE if the op was a read and no
3173 *	read error occured, or if the op was a write.  B_CACHE is never
3174 *	set if the buffer is invalid or otherwise uncacheable.
3175 *
3176 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3177 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3178 *	in the biodone routine.
3179 */
3180void
3181bufdone(struct buf *bp)
3182{
3183	int s;
3184	void    (*biodone)(struct buf *);
3185
3186
3187	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3188	s = splbio();
3189
3190	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
3191	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3192
3193	runningbufwakeup(bp);
3194
3195	if (bp->b_iocmd == BIO_WRITE && bp->b_bufobj != NULL)
3196		bufobj_wdrop(bp->b_bufobj);
3197
3198	/* call optional completion function if requested */
3199	if (bp->b_iodone != NULL) {
3200		biodone = bp->b_iodone;
3201		bp->b_iodone = NULL;
3202		/*
3203		 * Device drivers may or may not hold giant, hold it here
3204		 * if we're calling into unknown code.
3205		 */
3206		mtx_lock(&Giant);
3207		bp->b_flags |= B_DONE;	/* XXX Should happen after biodone? */
3208		(*biodone) (bp);
3209		mtx_unlock(&Giant);
3210		splx(s);
3211		return;
3212	}
3213	if (LIST_FIRST(&bp->b_dep) != NULL)
3214		buf_complete(bp);
3215
3216	if (bp->b_flags & B_VMIO) {
3217		int i;
3218		vm_ooffset_t foff;
3219		vm_page_t m;
3220		vm_object_t obj;
3221		int iosize;
3222		struct vnode *vp = bp->b_vp;
3223
3224		obj = bp->b_bufobj->bo_object;
3225
3226#if defined(VFS_BIO_DEBUG)
3227		mp_fixme("usecount and vflag accessed without locks.");
3228		if (vp->v_usecount == 0) {
3229			panic("biodone: zero vnode ref count");
3230		}
3231
3232		if ((vp->v_vflag & VV_OBJBUF) == 0) {
3233			panic("biodone: vnode is not setup for merged cache");
3234		}
3235#endif
3236
3237		foff = bp->b_offset;
3238		KASSERT(bp->b_offset != NOOFFSET,
3239		    ("biodone: no buffer offset"));
3240
3241		VM_OBJECT_LOCK(obj);
3242#if defined(VFS_BIO_DEBUG)
3243		if (obj->paging_in_progress < bp->b_npages) {
3244			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3245			    obj->paging_in_progress, bp->b_npages);
3246		}
3247#endif
3248
3249		/*
3250		 * Set B_CACHE if the op was a normal read and no error
3251		 * occured.  B_CACHE is set for writes in the b*write()
3252		 * routines.
3253		 */
3254		iosize = bp->b_bcount - bp->b_resid;
3255		if (bp->b_iocmd == BIO_READ &&
3256		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3257		    !(bp->b_ioflags & BIO_ERROR)) {
3258			bp->b_flags |= B_CACHE;
3259		}
3260		vm_page_lock_queues();
3261		for (i = 0; i < bp->b_npages; i++) {
3262			int bogusflag = 0;
3263			int resid;
3264
3265			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3266			if (resid > iosize)
3267				resid = iosize;
3268
3269			/*
3270			 * cleanup bogus pages, restoring the originals
3271			 */
3272			m = bp->b_pages[i];
3273			if (m == bogus_page) {
3274				bogusflag = 1;
3275				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3276				if (m == NULL)
3277					panic("biodone: page disappeared!");
3278				bp->b_pages[i] = m;
3279				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3280			}
3281#if defined(VFS_BIO_DEBUG)
3282			if (OFF_TO_IDX(foff) != m->pindex) {
3283				printf(
3284"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3285				    (intmax_t)foff, (uintmax_t)m->pindex);
3286			}
3287#endif
3288
3289			/*
3290			 * In the write case, the valid and clean bits are
3291			 * already changed correctly ( see bdwrite() ), so we
3292			 * only need to do this here in the read case.
3293			 */
3294			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3295				vfs_page_set_valid(bp, foff, i, m);
3296			}
3297
3298			/*
3299			 * when debugging new filesystems or buffer I/O methods, this
3300			 * is the most common error that pops up.  if you see this, you
3301			 * have not set the page busy flag correctly!!!
3302			 */
3303			if (m->busy == 0) {
3304				printf("biodone: page busy < 0, "
3305				    "pindex: %d, foff: 0x(%x,%x), "
3306				    "resid: %d, index: %d\n",
3307				    (int) m->pindex, (int)(foff >> 32),
3308						(int) foff & 0xffffffff, resid, i);
3309				if (!vn_isdisk(vp, NULL))
3310					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3311					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3312					    (intmax_t) bp->b_lblkno,
3313					    bp->b_flags, bp->b_npages);
3314				else
3315					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3316					    (intmax_t) bp->b_lblkno,
3317					    bp->b_flags, bp->b_npages);
3318				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3319				    (u_long)m->valid, (u_long)m->dirty,
3320				    m->wire_count);
3321				panic("biodone: page busy < 0\n");
3322			}
3323			vm_page_io_finish(m);
3324			vm_object_pip_subtract(obj, 1);
3325			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3326			iosize -= resid;
3327		}
3328		vm_page_unlock_queues();
3329		vm_object_pip_wakeupn(obj, 0);
3330		VM_OBJECT_UNLOCK(obj);
3331	}
3332
3333	/*
3334	 * For asynchronous completions, release the buffer now. The brelse
3335	 * will do a wakeup there if necessary - so no need to do a wakeup
3336	 * here in the async case. The sync case always needs to do a wakeup.
3337	 */
3338
3339	if (bp->b_flags & B_ASYNC) {
3340		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3341			brelse(bp);
3342		else
3343			bqrelse(bp);
3344	} else {
3345		bdone(bp);
3346	}
3347	splx(s);
3348}
3349
3350/*
3351 * This routine is called in lieu of iodone in the case of
3352 * incomplete I/O.  This keeps the busy status for pages
3353 * consistant.
3354 */
3355void
3356vfs_unbusy_pages(struct buf *bp)
3357{
3358	int i;
3359	vm_object_t obj;
3360	vm_page_t m;
3361
3362	runningbufwakeup(bp);
3363	if (!(bp->b_flags & B_VMIO))
3364		return;
3365
3366	obj = bp->b_bufobj->bo_object;
3367	VM_OBJECT_LOCK(obj);
3368	vm_page_lock_queues();
3369	for (i = 0; i < bp->b_npages; i++) {
3370		m = bp->b_pages[i];
3371		if (m == bogus_page) {
3372			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3373			if (!m)
3374				panic("vfs_unbusy_pages: page missing\n");
3375			bp->b_pages[i] = m;
3376			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3377			    bp->b_pages, bp->b_npages);
3378		}
3379		vm_object_pip_subtract(obj, 1);
3380		vm_page_io_finish(m);
3381	}
3382	vm_page_unlock_queues();
3383	vm_object_pip_wakeupn(obj, 0);
3384	VM_OBJECT_UNLOCK(obj);
3385}
3386
3387/*
3388 * vfs_page_set_valid:
3389 *
3390 *	Set the valid bits in a page based on the supplied offset.   The
3391 *	range is restricted to the buffer's size.
3392 *
3393 *	This routine is typically called after a read completes.
3394 */
3395static void
3396vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3397{
3398	vm_ooffset_t soff, eoff;
3399
3400	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3401	/*
3402	 * Start and end offsets in buffer.  eoff - soff may not cross a
3403	 * page boundry or cross the end of the buffer.  The end of the
3404	 * buffer, in this case, is our file EOF, not the allocation size
3405	 * of the buffer.
3406	 */
3407	soff = off;
3408	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3409	if (eoff > bp->b_offset + bp->b_bcount)
3410		eoff = bp->b_offset + bp->b_bcount;
3411
3412	/*
3413	 * Set valid range.  This is typically the entire buffer and thus the
3414	 * entire page.
3415	 */
3416	if (eoff > soff) {
3417		vm_page_set_validclean(
3418		    m,
3419		   (vm_offset_t) (soff & PAGE_MASK),
3420		   (vm_offset_t) (eoff - soff)
3421		);
3422	}
3423}
3424
3425/*
3426 * This routine is called before a device strategy routine.
3427 * It is used to tell the VM system that paging I/O is in
3428 * progress, and treat the pages associated with the buffer
3429 * almost as being PG_BUSY.  Also the object paging_in_progress
3430 * flag is handled to make sure that the object doesn't become
3431 * inconsistant.
3432 *
3433 * Since I/O has not been initiated yet, certain buffer flags
3434 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3435 * and should be ignored.
3436 */
3437void
3438vfs_busy_pages(struct buf *bp, int clear_modify)
3439{
3440	int i, bogus;
3441	vm_object_t obj;
3442	vm_ooffset_t foff;
3443	vm_page_t m;
3444
3445	if (!(bp->b_flags & B_VMIO))
3446		return;
3447
3448	obj = bp->b_bufobj->bo_object;
3449	foff = bp->b_offset;
3450	KASSERT(bp->b_offset != NOOFFSET,
3451	    ("vfs_busy_pages: no buffer offset"));
3452	vfs_setdirty(bp);
3453	VM_OBJECT_LOCK(obj);
3454retry:
3455	vm_page_lock_queues();
3456	for (i = 0; i < bp->b_npages; i++) {
3457		m = bp->b_pages[i];
3458
3459		if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3460			goto retry;
3461	}
3462	bogus = 0;
3463	for (i = 0; i < bp->b_npages; i++) {
3464		m = bp->b_pages[i];
3465
3466		if ((bp->b_flags & B_CLUSTER) == 0) {
3467			vm_object_pip_add(obj, 1);
3468			vm_page_io_start(m);
3469		}
3470		/*
3471		 * When readying a buffer for a read ( i.e
3472		 * clear_modify == 0 ), it is important to do
3473		 * bogus_page replacement for valid pages in
3474		 * partially instantiated buffers.  Partially
3475		 * instantiated buffers can, in turn, occur when
3476		 * reconstituting a buffer from its VM backing store
3477		 * base.  We only have to do this if B_CACHE is
3478		 * clear ( which causes the I/O to occur in the
3479		 * first place ).  The replacement prevents the read
3480		 * I/O from overwriting potentially dirty VM-backed
3481		 * pages.  XXX bogus page replacement is, uh, bogus.
3482		 * It may not work properly with small-block devices.
3483		 * We need to find a better way.
3484		 */
3485		pmap_remove_all(m);
3486		if (clear_modify)
3487			vfs_page_set_valid(bp, foff, i, m);
3488		else if (m->valid == VM_PAGE_BITS_ALL &&
3489		    (bp->b_flags & B_CACHE) == 0) {
3490			bp->b_pages[i] = bogus_page;
3491			bogus++;
3492		}
3493		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3494	}
3495	vm_page_unlock_queues();
3496	VM_OBJECT_UNLOCK(obj);
3497	if (bogus)
3498		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3499		    bp->b_pages, bp->b_npages);
3500}
3501
3502/*
3503 * Tell the VM system that the pages associated with this buffer
3504 * are clean.  This is used for delayed writes where the data is
3505 * going to go to disk eventually without additional VM intevention.
3506 *
3507 * Note that while we only really need to clean through to b_bcount, we
3508 * just go ahead and clean through to b_bufsize.
3509 */
3510static void
3511vfs_clean_pages(struct buf *bp)
3512{
3513	int i;
3514	vm_ooffset_t foff, noff, eoff;
3515	vm_page_t m;
3516
3517	if (!(bp->b_flags & B_VMIO))
3518		return;
3519
3520	foff = bp->b_offset;
3521	KASSERT(bp->b_offset != NOOFFSET,
3522	    ("vfs_clean_pages: no buffer offset"));
3523	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3524	vm_page_lock_queues();
3525	for (i = 0; i < bp->b_npages; i++) {
3526		m = bp->b_pages[i];
3527		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3528		eoff = noff;
3529
3530		if (eoff > bp->b_offset + bp->b_bufsize)
3531			eoff = bp->b_offset + bp->b_bufsize;
3532		vfs_page_set_valid(bp, foff, i, m);
3533		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3534		foff = noff;
3535	}
3536	vm_page_unlock_queues();
3537	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3538}
3539
3540/*
3541 *	vfs_bio_set_validclean:
3542 *
3543 *	Set the range within the buffer to valid and clean.  The range is
3544 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3545 *	itself may be offset from the beginning of the first page.
3546 *
3547 */
3548
3549void
3550vfs_bio_set_validclean(struct buf *bp, int base, int size)
3551{
3552	int i, n;
3553	vm_page_t m;
3554
3555	if (!(bp->b_flags & B_VMIO))
3556		return;
3557	/*
3558	 * Fixup base to be relative to beginning of first page.
3559	 * Set initial n to be the maximum number of bytes in the
3560	 * first page that can be validated.
3561	 */
3562
3563	base += (bp->b_offset & PAGE_MASK);
3564	n = PAGE_SIZE - (base & PAGE_MASK);
3565
3566	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3567	vm_page_lock_queues();
3568	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3569		m = bp->b_pages[i];
3570		if (n > size)
3571			n = size;
3572		vm_page_set_validclean(m, base & PAGE_MASK, n);
3573		base += n;
3574		size -= n;
3575		n = PAGE_SIZE;
3576	}
3577	vm_page_unlock_queues();
3578	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3579}
3580
3581/*
3582 *	vfs_bio_clrbuf:
3583 *
3584 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3585 *	to clear BIO_ERROR and B_INVAL.
3586 *
3587 *	Note that while we only theoretically need to clear through b_bcount,
3588 *	we go ahead and clear through b_bufsize.
3589 */
3590
3591void
3592vfs_bio_clrbuf(struct buf *bp)
3593{
3594	int i, j, mask = 0;
3595	caddr_t sa, ea;
3596
3597	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3598		clrbuf(bp);
3599		return;
3600	}
3601
3602	bp->b_flags &= ~B_INVAL;
3603	bp->b_ioflags &= ~BIO_ERROR;
3604	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3605	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3606	    (bp->b_offset & PAGE_MASK) == 0) {
3607		if (bp->b_pages[0] == bogus_page)
3608			goto unlock;
3609		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3610		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3611		if ((bp->b_pages[0]->valid & mask) == mask)
3612			goto unlock;
3613		if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3614		    ((bp->b_pages[0]->valid & mask) == 0)) {
3615			bzero(bp->b_data, bp->b_bufsize);
3616			bp->b_pages[0]->valid |= mask;
3617			goto unlock;
3618		}
3619	}
3620	ea = sa = bp->b_data;
3621	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3622		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3623		ea = (caddr_t)(vm_offset_t)ulmin(
3624		    (u_long)(vm_offset_t)ea,
3625		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3626		if (bp->b_pages[i] == bogus_page)
3627			continue;
3628		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3629		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3630		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3631		if ((bp->b_pages[i]->valid & mask) == mask)
3632			continue;
3633		if ((bp->b_pages[i]->valid & mask) == 0) {
3634			if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3635				bzero(sa, ea - sa);
3636		} else {
3637			for (; sa < ea; sa += DEV_BSIZE, j++) {
3638				if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3639				    (bp->b_pages[i]->valid & (1 << j)) == 0)
3640					bzero(sa, DEV_BSIZE);
3641			}
3642		}
3643		bp->b_pages[i]->valid |= mask;
3644	}
3645unlock:
3646	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3647	bp->b_resid = 0;
3648}
3649
3650/*
3651 * vm_hold_load_pages and vm_hold_free_pages get pages into
3652 * a buffers address space.  The pages are anonymous and are
3653 * not associated with a file object.
3654 */
3655static void
3656vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3657{
3658	vm_offset_t pg;
3659	vm_page_t p;
3660	int index;
3661
3662	to = round_page(to);
3663	from = round_page(from);
3664	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3665
3666	VM_OBJECT_LOCK(kernel_object);
3667	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3668tryagain:
3669		/*
3670		 * note: must allocate system pages since blocking here
3671		 * could intefere with paging I/O, no matter which
3672		 * process we are.
3673		 */
3674		p = vm_page_alloc(kernel_object,
3675			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3676		    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3677		if (!p) {
3678			atomic_add_int(&vm_pageout_deficit,
3679			    (to - pg) >> PAGE_SHIFT);
3680			VM_OBJECT_UNLOCK(kernel_object);
3681			VM_WAIT;
3682			VM_OBJECT_LOCK(kernel_object);
3683			goto tryagain;
3684		}
3685		p->valid = VM_PAGE_BITS_ALL;
3686		pmap_qenter(pg, &p, 1);
3687		bp->b_pages[index] = p;
3688	}
3689	VM_OBJECT_UNLOCK(kernel_object);
3690	bp->b_npages = index;
3691}
3692
3693/* Return pages associated with this buf to the vm system */
3694static void
3695vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3696{
3697	vm_offset_t pg;
3698	vm_page_t p;
3699	int index, newnpages;
3700
3701	from = round_page(from);
3702	to = round_page(to);
3703	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3704
3705	VM_OBJECT_LOCK(kernel_object);
3706	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3707		p = bp->b_pages[index];
3708		if (p && (index < bp->b_npages)) {
3709			if (p->busy) {
3710				printf(
3711			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3712				    (intmax_t)bp->b_blkno,
3713				    (intmax_t)bp->b_lblkno);
3714			}
3715			bp->b_pages[index] = NULL;
3716			pmap_qremove(pg, 1);
3717			vm_page_lock_queues();
3718			vm_page_unwire(p, 0);
3719			vm_page_free(p);
3720			vm_page_unlock_queues();
3721		}
3722	}
3723	VM_OBJECT_UNLOCK(kernel_object);
3724	bp->b_npages = newnpages;
3725}
3726
3727/*
3728 * Map an IO request into kernel virtual address space.
3729 *
3730 * All requests are (re)mapped into kernel VA space.
3731 * Notice that we use b_bufsize for the size of the buffer
3732 * to be mapped.  b_bcount might be modified by the driver.
3733 *
3734 * Note that even if the caller determines that the address space should
3735 * be valid, a race or a smaller-file mapped into a larger space may
3736 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3737 * check the return value.
3738 */
3739int
3740vmapbuf(struct buf *bp)
3741{
3742	caddr_t addr, kva;
3743	vm_prot_t prot;
3744	int pidx, i;
3745	struct vm_page *m;
3746	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3747
3748	if (bp->b_bufsize < 0)
3749		return (-1);
3750	prot = VM_PROT_READ;
3751	if (bp->b_iocmd == BIO_READ)
3752		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3753	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3754	     addr < bp->b_data + bp->b_bufsize;
3755	     addr += PAGE_SIZE, pidx++) {
3756		/*
3757		 * Do the vm_fault if needed; do the copy-on-write thing
3758		 * when reading stuff off device into memory.
3759		 *
3760		 * NOTE! Must use pmap_extract() because addr may be in
3761		 * the userland address space, and kextract is only guarenteed
3762		 * to work for the kernland address space (see: sparc64 port).
3763		 */
3764retry:
3765		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3766		    prot) < 0) {
3767			vm_page_lock_queues();
3768			for (i = 0; i < pidx; ++i) {
3769				vm_page_unhold(bp->b_pages[i]);
3770				bp->b_pages[i] = NULL;
3771			}
3772			vm_page_unlock_queues();
3773			return(-1);
3774		}
3775		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3776		if (m == NULL)
3777			goto retry;
3778		bp->b_pages[pidx] = m;
3779	}
3780	if (pidx > btoc(MAXPHYS))
3781		panic("vmapbuf: mapped more than MAXPHYS");
3782	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3783
3784	kva = bp->b_saveaddr;
3785	bp->b_npages = pidx;
3786	bp->b_saveaddr = bp->b_data;
3787	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3788	return(0);
3789}
3790
3791/*
3792 * Free the io map PTEs associated with this IO operation.
3793 * We also invalidate the TLB entries and restore the original b_addr.
3794 */
3795void
3796vunmapbuf(struct buf *bp)
3797{
3798	int pidx;
3799	int npages;
3800
3801	npages = bp->b_npages;
3802	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3803	vm_page_lock_queues();
3804	for (pidx = 0; pidx < npages; pidx++)
3805		vm_page_unhold(bp->b_pages[pidx]);
3806	vm_page_unlock_queues();
3807
3808	bp->b_data = bp->b_saveaddr;
3809}
3810
3811void
3812bdone(struct buf *bp)
3813{
3814
3815	mtx_lock(&bdonelock);
3816	bp->b_flags |= B_DONE;
3817	wakeup(bp);
3818	mtx_unlock(&bdonelock);
3819}
3820
3821void
3822bwait(struct buf *bp, u_char pri, const char *wchan)
3823{
3824
3825	mtx_lock(&bdonelock);
3826	while ((bp->b_flags & B_DONE) == 0)
3827		msleep(bp, &bdonelock, pri, wchan, 0);
3828	mtx_unlock(&bdonelock);
3829}
3830
3831int
3832bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3833{
3834
3835	return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3836}
3837
3838void
3839bufstrategy(struct bufobj *bo, struct buf *bp)
3840{
3841	int i = 0;
3842	struct vnode *vp;
3843
3844	vp = bp->b_vp;
3845	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3846	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3847	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3848	i = VOP_STRATEGY(vp, bp);
3849	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3850}
3851
3852void
3853bufobj_wref(struct bufobj *bo)
3854{
3855
3856	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3857	BO_LOCK(bo);
3858	bo->bo_numoutput++;
3859	BO_UNLOCK(bo);
3860}
3861
3862void
3863bufobj_wdrop(struct bufobj *bo)
3864{
3865
3866	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3867	BO_LOCK(bo);
3868	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3869	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3870		bo->bo_flag &= ~BO_WWAIT;
3871		wakeup(&bo->bo_numoutput);
3872	}
3873	BO_UNLOCK(bo);
3874}
3875
3876int
3877bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3878{
3879	int error;
3880
3881	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3882	ASSERT_BO_LOCKED(bo);
3883	error = 0;
3884	while (bo->bo_numoutput) {
3885		bo->bo_flag |= BO_WWAIT;
3886		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3887		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3888		if (error)
3889			break;
3890	}
3891	return (error);
3892}
3893
3894#include "opt_ddb.h"
3895#ifdef DDB
3896#include <ddb/ddb.h>
3897
3898/* DDB command to show buffer data */
3899DB_SHOW_COMMAND(buffer, db_show_buffer)
3900{
3901	/* get args */
3902	struct buf *bp = (struct buf *)addr;
3903
3904	if (!have_addr) {
3905		db_printf("usage: show buffer <addr>\n");
3906		return;
3907	}
3908
3909	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3910	db_printf(
3911	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3912	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n",
3913	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3914	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno);
3915	if (bp->b_npages) {
3916		int i;
3917		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3918		for (i = 0; i < bp->b_npages; i++) {
3919			vm_page_t m;
3920			m = bp->b_pages[i];
3921			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3922			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3923			if ((i + 1) < bp->b_npages)
3924				db_printf(",");
3925		}
3926		db_printf("\n");
3927	}
3928}
3929#endif /* DDB */
3930