vfs_bio.c revision 260354
11573Srgrimes/*-
21573Srgrimes * Copyright (c) 2004 Poul-Henning Kamp
31573Srgrimes * Copyright (c) 1994,1997 John S. Dyson
41573Srgrimes * Copyright (c) 2013 The FreeBSD Foundation
51573Srgrimes * All rights reserved.
61573Srgrimes *
71573Srgrimes * Portions of this software were developed by Konstantin Belousov
81573Srgrimes * under sponsorship from the FreeBSD Foundation.
91573Srgrimes *
101573Srgrimes * Redistribution and use in source and binary forms, with or without
111573Srgrimes * modification, are permitted provided that the following conditions
121573Srgrimes * are met:
131573Srgrimes * 1. Redistributions of source code must retain the above copyright
141573Srgrimes *    notice, this list of conditions and the following disclaimer.
151573Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
161573Srgrimes *    notice, this list of conditions and the following disclaimer in the
171573Srgrimes *    documentation and/or other materials provided with the distribution.
181573Srgrimes *
191573Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
201573Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
211573Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
221573Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
231573Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
241573Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
251573Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
261573Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
271573Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
281573Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
291573Srgrimes * SUCH DAMAGE.
301573Srgrimes */
311573Srgrimes
321573Srgrimes/*
331573Srgrimes * this file contains a new buffer I/O scheme implementing a coherent
341573Srgrimes * VM object and buffer cache scheme.  Pains have been taken to make
351573Srgrimes * sure that the performance degradation associated with schemes such
3692986Sobrien * as this is not realized.
3792986Sobrien *
3892986Sobrien * Author:  John S. Dyson
391573Srgrimes * Significant help during the development and debugging phases
401573Srgrimes * had been provided by David Greenman, also of the FreeBSD core team.
411573Srgrimes *
421573Srgrimes * see man buf(9) for more info.
431573Srgrimes */
441573Srgrimes
451573Srgrimes#include <sys/cdefs.h>
461573Srgrimes__FBSDID("$FreeBSD: stable/10/sys/kern/vfs_bio.c 260354 2014-01-05 23:00:38Z mav $");
471573Srgrimes
481573Srgrimes#include <sys/param.h>
491573Srgrimes#include <sys/systm.h>
501573Srgrimes#include <sys/bio.h>
511573Srgrimes#include <sys/conf.h>
521573Srgrimes#include <sys/buf.h>
531573Srgrimes#include <sys/devicestat.h>
541573Srgrimes#include <sys/eventhandler.h>
551573Srgrimes#include <sys/fail.h>
561573Srgrimes#include <sys/limits.h>
571573Srgrimes#include <sys/lock.h>
581573Srgrimes#include <sys/malloc.h>
591573Srgrimes#include <sys/mount.h>
601573Srgrimes#include <sys/mutex.h>
611573Srgrimes#include <sys/kernel.h>
621573Srgrimes#include <sys/kthread.h>
631573Srgrimes#include <sys/proc.h>
641573Srgrimes#include <sys/resourcevar.h>
651573Srgrimes#include <sys/rwlock.h>
661573Srgrimes#include <sys/sysctl.h>
671573Srgrimes#include <sys/vmem.h>
68132019Stjr#include <sys/vmmeter.h>
69132019Stjr#include <sys/vnode.h>
70132019Stjr#include <geom/geom.h>
71132019Stjr#include <vm/vm.h>
72132019Stjr#include <vm/vm_param.h>
73132019Stjr#include <vm/vm_kern.h>
74132019Stjr#include <vm/vm_pageout.h>
75132019Stjr#include <vm/vm_page.h>
76132019Stjr#include <vm/vm_object.h>
77132019Stjr#include <vm/vm_extern.h>
78132019Stjr#include <vm/vm_map.h>
791573Srgrimes#include "opt_compat.h"
801573Srgrimes#include "opt_directio.h"
811573Srgrimes#include "opt_swap.h"
821573Srgrimes
831573Srgrimesstatic MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
841573Srgrimes
851573Srgrimesstruct	bio_ops bioops;		/* I/O operation notification */
861573Srgrimes
871573Srgrimesstruct	buf_ops buf_ops_bio = {
881573Srgrimes	.bop_name	=	"buf_ops_bio",
891573Srgrimes	.bop_write	=	bufwrite,
901573Srgrimes	.bop_strategy	=	bufstrategy,
911573Srgrimes	.bop_sync	=	bufsync,
921573Srgrimes	.bop_bdflush	=	bufbdflush,
931573Srgrimes};
941573Srgrimes
95132019Stjr/*
961573Srgrimes * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
971573Srgrimes * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
981573Srgrimes */
991573Srgrimesstruct buf *buf;		/* buffer header pool */
1001573Srgrimescaddr_t unmapped_buf;
1011573Srgrimes
1021573Srgrimesstatic struct proc *bufdaemonproc;
1031573Srgrimes
10492905Sobrienstatic int inmem(struct vnode *vp, daddr_t blkno);
10592905Sobrienstatic void vm_hold_free_pages(struct buf *bp, int newbsize);
106167222Sdelphijstatic void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
10792905Sobrien		vm_offset_t to);
10892905Sobrienstatic void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
109132019Stjrstatic void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
110167222Sdelphij		vm_page_t m);
111132019Stjrstatic void vfs_clean_pages_dirty_buf(struct buf *bp);
112132019Stjrstatic void vfs_setdirty_locked_object(struct buf *bp);
113132019Stjrstatic void vfs_vmio_release(struct buf *bp);
114132019Stjrstatic int vfs_bio_clcheck(struct vnode *vp, int size,
115132019Stjr		daddr_t lblkno, daddr_t blkno);
116132019Stjrstatic int buf_flush(int);
117132019Stjrstatic int flushbufqueues(int, int);
118132019Stjrstatic void buf_daemon(void);
1191573Srgrimesstatic void bremfreel(struct buf *bp);
12092905Sobrienstatic __inline void bd_wakeup(void);
1211573Srgrimes#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
1221573Srgrimes    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
12392905Sobrienstatic int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
1241573Srgrimes#endif
1251573Srgrimes
12692905Sobrienint vmiodirenable = TRUE;
1271573SrgrimesSYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
1281573Srgrimes    "Use the VM system for directory writes");
1291573Srgrimeslong runningbufspace;
1301573SrgrimesSYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
1311573Srgrimes    "Amount of presently outstanding async buffer io");
1321573Srgrimesstatic long bufspace;
1331573Srgrimes#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
1341573Srgrimes    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
1351573SrgrimesSYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
1361573Srgrimes    &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
1371573Srgrimes#else
1381573SrgrimesSYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
1391573Srgrimes    "Virtual memory used for buffers");
1401573Srgrimes#endif
1411573Srgrimesstatic long unmapped_bufspace;
1421573SrgrimesSYSCTL_LONG(_vfs, OID_AUTO, unmapped_bufspace, CTLFLAG_RD,
1431573Srgrimes    &unmapped_bufspace, 0,
1441573Srgrimes    "Amount of unmapped buffers, inclusive in the bufspace");
1451573Srgrimesstatic long maxbufspace;
14692889SobrienSYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
1471573Srgrimes    "Maximum allowed value of bufspace (including buf_daemon)");
1481573Srgrimesstatic long bufmallocspace;
1491573SrgrimesSYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
1501573Srgrimes    "Amount of malloced memory for buffers");
15192889Sobrienstatic long maxbufmallocspace;
1521573SrgrimesSYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
1531573Srgrimes    "Maximum amount of malloced memory for buffers");
1541573Srgrimesstatic long lobufspace;
1551573SrgrimesSYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
1561573Srgrimes    "Minimum amount of buffers we want to have");
15792889Sobrienlong hibufspace;
15892889SobrienSYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
1591573Srgrimes    "Maximum allowed value of bufspace (excluding buf_daemon)");
16092889Sobrienstatic int bufreusecnt;
16192889SobrienSYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
16292889Sobrien    "Number of times we have reused a buffer");
16392889Sobrienstatic int buffreekvacnt;
1641573SrgrimesSYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
1651573Srgrimes    "Number of times we have freed the KVA space from some buffer");
16662232Sdcsstatic int bufdefragcnt;
16792889SobrienSYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
16862232Sdcs    "Number of times we have had to repeat buffer allocation to defragment");
16992889Sobrienstatic long lorunningspace;
17092889SobrienSYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
17192889Sobrien    "Minimum preferred space used for in-progress I/O");
17292889Sobrienstatic long hirunningspace;
1731573SrgrimesSYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
1741573Srgrimes    "Maximum amount of space to use for in-progress I/O");
1751573Srgrimesint dirtybufferflushes;
1761573SrgrimesSYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
1771573Srgrimes    0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
1781573Srgrimesint bdwriteskip;
1791573SrgrimesSYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
1801573Srgrimes    0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
1811573Srgrimesint altbufferflushes;
1821573SrgrimesSYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
1831573Srgrimes    0, "Number of fsync flushes to limit dirty buffers");
1841573Srgrimesstatic int recursiveflushes;
1851573SrgrimesSYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
1861573Srgrimes    0, "Number of flushes skipped due to being recursive");
1871573Srgrimesstatic int numdirtybuffers;
1881573SrgrimesSYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
18962391Sdcs    "Number of buffers that are dirty (has unwritten changes) at the moment");
19062232Sdcsstatic int lodirtybuffers;
19162232SdcsSYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
19262232Sdcs    "How many buffers we want to have free before bufdaemon can sleep");
19362232Sdcsstatic int hidirtybuffers;
19462232SdcsSYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
19562754Sdcs    "When the number of dirty buffers is considered severe");
19662232Sdcsint dirtybufthresh;
197111010SnectarSYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
198111010Snectar    0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
19962232Sdcsstatic int numfreebuffers;
20062754SdcsSYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
20162232Sdcs    "Number of free buffers");
20262232Sdcsstatic int lofreebuffers;
20362232SdcsSYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
20462232Sdcs   "XXX Unused");
20562232Sdcsstatic int hifreebuffers;
20662232SdcsSYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
20762754Sdcs   "XXX Complicatedly unused");
20862232Sdcsstatic int getnewbufcalls;
20962754SdcsSYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
21062232Sdcs   "Number of calls to getnewbuf");
21162232Sdcsstatic int getnewbufrestarts;
21262232SdcsSYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
21362232Sdcs    "Number of times getnewbuf has had to restart a buffer aquisition");
214111010Snectarstatic int mappingrestarts;
21562754SdcsSYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
21662754Sdcs    "Number of times getblk has had to restart a buffer mapping for "
21762232Sdcs    "unmapped buffer");
21862391Sdcsstatic int flushbufqtarget = 100;
21962232SdcsSYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
22062232Sdcs    "Amount of work to do in flushbufqueues when helping bufdaemon");
22162232Sdcsstatic long notbufdflushes;
22262232SdcsSYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, &notbufdflushes, 0,
22362232Sdcs    "Number of dirty buffer flushes done by the bufdaemon helpers");
22462232Sdcsstatic long barrierwrites;
22562232SdcsSYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
22662232Sdcs    "Number of barrier writes");
22762232SdcsSYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
22862232Sdcs    &unmapped_buf_allowed, 0,
2291573Srgrimes    "Permit the use of the unmapped i/o");
2301573Srgrimes
2311573Srgrimes/*
2321573Srgrimes * Lock for the non-dirty bufqueues
2331573Srgrimes */
2341573Srgrimesstatic struct mtx_padalign bqclean;
2351573Srgrimes
2361573Srgrimes/*
2371573Srgrimes * Lock for the dirty queue.
2381573Srgrimes */
2391573Srgrimesstatic struct mtx_padalign bqdirty;
2401573Srgrimes
2411573Srgrimes/*
2421573Srgrimes * This lock synchronizes access to bd_request.
2431573Srgrimes */
2441573Srgrimesstatic struct mtx_padalign bdlock;
245132019Stjr
2461573Srgrimes/*
24762391Sdcs * This lock protects the runningbufreq and synchronizes runningbufwakeup and
24862391Sdcs * waitrunningbufspace().
24962854Sdcs */
25062391Sdcsstatic struct mtx_padalign rbreqlock;
2511573Srgrimes
2521573Srgrimes/*
2531573Srgrimes * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
2541573Srgrimes */
255139437Sddsstatic struct mtx_padalign nblock;
256139437Sdds
257139437Sdds/*
258139437Sdds * Lock that protects bdirtywait.
2591573Srgrimes */
2601573Srgrimesstatic struct mtx_padalign bdirtylock;
2611573Srgrimes
2621573Srgrimes/*
2631573Srgrimes * Wakeup point for bufdaemon, as well as indicator of whether it is already
2641573Srgrimes * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
2651573Srgrimes * is idling.
2661573Srgrimes */
2671573Srgrimesstatic int bd_request;
2681573Srgrimes
2691573Srgrimes/*
2701573Srgrimes * Request for the buf daemon to write more buffers than is indicated by
2711573Srgrimes * lodirtybuf.  This may be necessary to push out excess dependencies or
2721573Srgrimes * defragment the address space where a simple count of the number of dirty
273132019Stjr * buffers is insufficient to characterize the demand for flushing them.
274132019Stjr */
2751573Srgrimesstatic int bd_speedupreq;
2761573Srgrimes
2771573Srgrimes/*
2781573Srgrimes * bogus page -- for I/O to/from partially complete buffers
2791573Srgrimes * this is a temporary solution to the problem, but it is not
2801573Srgrimes * really that bad.  it would be better to split the buffer
2811573Srgrimes * for input in the case of buffers partially already in memory,
2821573Srgrimes * but the code is intricate enough already.
2831573Srgrimes */
2841573Srgrimesvm_page_t bogus_page;
2851573Srgrimes
2861573Srgrimes/*
2871573Srgrimes * Synchronization (sleep/wakeup) variable for active buffer space requests.
2881573Srgrimes * Set when wait starts, cleared prior to wakeup().
2891573Srgrimes * Used in runningbufwakeup() and waitrunningbufspace().
2901573Srgrimes */
2911573Srgrimesstatic int runningbufreq;
2921573Srgrimes
2931573Srgrimes/*
2941573Srgrimes * Synchronization (sleep/wakeup) variable for buffer requests.
2951573Srgrimes * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
2961573Srgrimes * by and/or.
2971573Srgrimes * Used in numdirtywakeup(), bufspacewakeup(), bufcountadd(), bwillwrite(),
2981573Srgrimes * getnewbuf(), and getblk().
2991573Srgrimes */
3001573Srgrimesstatic int needsbuffer;
3011573Srgrimes
302167222Sdelphij/*
3031573Srgrimes * Synchronization for bwillwrite() waiters.
3041573Srgrimes */
3051573Srgrimesstatic int bdirtywait;
3061573Srgrimes
3071573Srgrimes/*
3081573Srgrimes * Definitions for the buffer free lists.
3091573Srgrimes */
3101573Srgrimes#define BUFFER_QUEUES	5	/* number of free buffer queues */
3111573Srgrimes
3121573Srgrimes#define QUEUE_NONE	0	/* on no queue */
3131573Srgrimes#define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
3141573Srgrimes#define QUEUE_DIRTY	2	/* B_DELWRI buffers */
3151573Srgrimes#define QUEUE_EMPTYKVA	3	/* empty buffer headers w/KVA assignment */
3161573Srgrimes#define QUEUE_EMPTY	4	/* empty buffer headers */
3171573Srgrimes#define QUEUE_SENTINEL	1024	/* not an queue index, but mark for sentinel */
3181573Srgrimes
3191573Srgrimes/* Queues for free buffers with various properties */
3201573Srgrimesstatic TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
3211573Srgrimes#ifdef INVARIANTS
3221573Srgrimesstatic int bq_len[BUFFER_QUEUES];
3231573Srgrimes#endif
3241573Srgrimes
325167222Sdelphij/*
3261573Srgrimes * Single global constant for BUF_WMESG, to avoid getting multiple references.
3271573Srgrimes * buf_wmesg is referred from macros.
3281573Srgrimes */
3291573Srgrimesconst char *buf_wmesg = BUF_WMESG;
3301573Srgrimes
3311573Srgrimes#define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
3321573Srgrimes#define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
333132019Stjr#define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
334132019Stjr
335137959Stjr#if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
3361573Srgrimes    defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
3371573Srgrimesstatic int
3381573Srgrimessysctl_bufspace(SYSCTL_HANDLER_ARGS)
3391573Srgrimes{
3401573Srgrimes	long lvalue;
3411573Srgrimes	int ivalue;
3421573Srgrimes
3431573Srgrimes	if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
3441573Srgrimes		return (sysctl_handle_long(oidp, arg1, arg2, req));
3451573Srgrimes	lvalue = *(long *)arg1;
3461573Srgrimes	if (lvalue > INT_MAX)
3471573Srgrimes		/* On overflow, still write out a long to trigger ENOMEM. */
3481573Srgrimes		return (sysctl_handle_long(oidp, &lvalue, 0, req));
3491573Srgrimes	ivalue = lvalue;
3501573Srgrimes	return (sysctl_handle_int(oidp, &ivalue, 0, req));
3511573Srgrimes}
3521573Srgrimes#endif
3531573Srgrimes
3541573Srgrimes#ifdef DIRECTIO
3551573Srgrimesextern void ffs_rawread_setup(void);
3561573Srgrimes#endif /* DIRECTIO */
3571573Srgrimes
3581573Srgrimes/*
3591573Srgrimes *	bqlock:
3601573Srgrimes *
3611573Srgrimes *	Return the appropriate queue lock based on the index.
3621573Srgrimes */
3631573Srgrimesstatic inline struct mtx *
3641573Srgrimesbqlock(int qindex)
36592889Sobrien{
3661573Srgrimes
3671573Srgrimes	if (qindex == QUEUE_DIRTY)
3681573Srgrimes		return (struct mtx *)(&bqdirty);
3691573Srgrimes	return (struct mtx *)(&bqclean);
37092889Sobrien}
3711573Srgrimes
3721573Srgrimes/*
3731573Srgrimes *	bdirtywakeup:
3741573Srgrimes *
3751573Srgrimes *	Wakeup any bwillwrite() waiters.
37692889Sobrien */
37792889Sobrienstatic void
37892889Sobrienbdirtywakeup(void)
37992889Sobrien{
38092889Sobrien	mtx_lock(&bdirtylock);
38192889Sobrien	if (bdirtywait) {
38292889Sobrien		bdirtywait = 0;
38392889Sobrien		wakeup(&bdirtywait);
38492889Sobrien	}
38592889Sobrien	mtx_unlock(&bdirtylock);
38692889Sobrien}
38792889Sobrien
38892889Sobrien/*
3891573Srgrimes *	bdirtysub:
3901573Srgrimes *
3911573Srgrimes *	Decrement the numdirtybuffers count by one and wakeup any
3921573Srgrimes *	threads blocked in bwillwrite().
3931573Srgrimes */
3941573Srgrimesstatic void
3951573Srgrimesbdirtysub(void)
3961573Srgrimes{
3971573Srgrimes
3981573Srgrimes	if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
3991573Srgrimes	    (lodirtybuffers + hidirtybuffers) / 2)
4001573Srgrimes		bdirtywakeup();
4011573Srgrimes}
4021573Srgrimes
4031573Srgrimes/*
4041573Srgrimes *	bdirtyadd:
4051573Srgrimes *
4061573Srgrimes *	Increment the numdirtybuffers count by one and wakeup the buf
4071573Srgrimes *	daemon if needed.
4081573Srgrimes */
4091573Srgrimesstatic void
4101573Srgrimesbdirtyadd(void)
4111573Srgrimes{
4121573Srgrimes
413132019Stjr	/*
4141573Srgrimes	 * Only do the wakeup once as we cross the boundary.  The
4151573Srgrimes	 * buf daemon will keep running until the condition clears.
4161573Srgrimes	 */
4171573Srgrimes	if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
4181573Srgrimes	    (lodirtybuffers + hidirtybuffers) / 2)
4191573Srgrimes		bd_wakeup();
4201573Srgrimes}
4211573Srgrimes
422132019Stjr/*
4231573Srgrimes *	bufspacewakeup:
4241573Srgrimes *
4251573Srgrimes *	Called when buffer space is potentially available for recovery.
4261573Srgrimes *	getnewbuf() will block on this flag when it is unable to free
4271573Srgrimes *	sufficient buffer space.  Buffer space becomes recoverable when
4281573Srgrimes *	bp's get placed back in the queues.
4291573Srgrimes */
4301573Srgrimes
4311573Srgrimesstatic __inline void
4321573Srgrimesbufspacewakeup(void)
4331573Srgrimes{
4341573Srgrimes
4351573Srgrimes	/*
4361573Srgrimes	 * If someone is waiting for BUF space, wake them up.  Even
4371573Srgrimes	 * though we haven't freed the kva space yet, the waiting
4381573Srgrimes	 * process will be able to now.
4391573Srgrimes	 */
4401573Srgrimes	mtx_lock(&nblock);
4411573Srgrimes	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
4421573Srgrimes		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
4431573Srgrimes		wakeup(&needsbuffer);
4441573Srgrimes	}
4451573Srgrimes	mtx_unlock(&nblock);
4461573Srgrimes}
4471573Srgrimes
4481573Srgrimes/*
4491573Srgrimes *	runningwakeup:
4501573Srgrimes *
4511573Srgrimes *	Wake up processes that are waiting on asynchronous writes to fall
4521573Srgrimes *	below lorunningspace.
4531573Srgrimes */
4541573Srgrimesstatic void
4551573Srgrimesrunningwakeup(void)
4561573Srgrimes{
4571573Srgrimes
4581573Srgrimes	mtx_lock(&rbreqlock);
4591573Srgrimes	if (runningbufreq) {
4601573Srgrimes		runningbufreq = 0;
4611573Srgrimes		wakeup(&runningbufreq);
4621573Srgrimes	}
4631573Srgrimes	mtx_unlock(&rbreqlock);
4641573Srgrimes}
4651573Srgrimes
4661573Srgrimes/*
4671573Srgrimes *	runningbufwakeup:
4681573Srgrimes *
4691573Srgrimes *	Decrement the outstanding write count according.
4701573Srgrimes */
4711573Srgrimesvoid
4721573Srgrimesrunningbufwakeup(struct buf *bp)
4731573Srgrimes{
4741573Srgrimes	long space, bspace;
4751573Srgrimes
4761573Srgrimes	bspace = bp->b_runningbufspace;
4771573Srgrimes	if (bspace == 0)
4781573Srgrimes		return;
4791573Srgrimes	space = atomic_fetchadd_long(&runningbufspace, -bspace);
4801573Srgrimes	KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
4811573Srgrimes	    space, bspace));
4821573Srgrimes	bp->b_runningbufspace = 0;
4831573Srgrimes	/*
4841573Srgrimes	 * Only acquire the lock and wakeup on the transition from exceeding
4851573Srgrimes	 * the threshold to falling below it.
4861573Srgrimes	 */
4871573Srgrimes	if (space < lorunningspace)
4881573Srgrimes		return;
4891573Srgrimes	if (space - bspace > lorunningspace)
4901573Srgrimes		return;
4911573Srgrimes	runningwakeup();
4921573Srgrimes}
4931573Srgrimes
4941573Srgrimes/*
4951573Srgrimes *	bufcountadd:
4961573Srgrimes *
4971573Srgrimes *	Called when a buffer has been added to one of the free queues to
4981573Srgrimes *	account for the buffer and to wakeup anyone waiting for free buffers.
4991573Srgrimes *	This typically occurs when large amounts of metadata are being handled
5001573Srgrimes *	by the buffer cache ( else buffer space runs out first, usually ).
5011573Srgrimes */
5021573Srgrimesstatic __inline void
5031573Srgrimesbufcountadd(struct buf *bp)
5041573Srgrimes{
5051573Srgrimes	int old;
5061573Srgrimes
5071573Srgrimes	KASSERT((bp->b_flags & B_INFREECNT) == 0,
5081573Srgrimes	    ("buf %p already counted as free", bp));
5091573Srgrimes	bp->b_flags |= B_INFREECNT;
5101573Srgrimes	old = atomic_fetchadd_int(&numfreebuffers, 1);
5111573Srgrimes	KASSERT(old >= 0 && old < nbuf,
5121573Srgrimes	    ("numfreebuffers climbed to %d", old + 1));
5131573Srgrimes	mtx_lock(&nblock);
5141573Srgrimes	if (needsbuffer) {
5151573Srgrimes		needsbuffer &= ~VFS_BIO_NEED_ANY;
5161573Srgrimes		if (numfreebuffers >= hifreebuffers)
5171573Srgrimes			needsbuffer &= ~VFS_BIO_NEED_FREE;
5181573Srgrimes		wakeup(&needsbuffer);
5191573Srgrimes	}
5201573Srgrimes	mtx_unlock(&nblock);
5211573Srgrimes}
5221573Srgrimes
5231573Srgrimes/*
5241573Srgrimes *	bufcountsub:
5251573Srgrimes *
5261573Srgrimes *	Decrement the numfreebuffers count as needed.
5271573Srgrimes */
5281573Srgrimesstatic void
5291573Srgrimesbufcountsub(struct buf *bp)
5301573Srgrimes{
5311573Srgrimes	int old;
5321573Srgrimes
5331573Srgrimes	/*
5341573Srgrimes	 * Fixup numfreebuffers count.  If the buffer is invalid or not
5351573Srgrimes	 * delayed-write, the buffer was free and we must decrement
5361573Srgrimes	 * numfreebuffers.
5371573Srgrimes	 */
5381573Srgrimes	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
5391573Srgrimes		KASSERT((bp->b_flags & B_INFREECNT) != 0,
5401573Srgrimes		    ("buf %p not counted in numfreebuffers", bp));
5411573Srgrimes		bp->b_flags &= ~B_INFREECNT;
5421573Srgrimes		old = atomic_fetchadd_int(&numfreebuffers, -1);
5431573Srgrimes		KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
5441573Srgrimes	}
5451573Srgrimes}
5461573Srgrimes
5471573Srgrimes/*
5481573Srgrimes *	waitrunningbufspace()
5491573Srgrimes *
5501573Srgrimes *	runningbufspace is a measure of the amount of I/O currently
5511573Srgrimes *	running.  This routine is used in async-write situations to
5521573Srgrimes *	prevent creating huge backups of pending writes to a device.
55392889Sobrien *	Only asynchronous writes are governed by this function.
5541573Srgrimes *
5551573Srgrimes *	This does NOT turn an async write into a sync write.  It waits
5561573Srgrimes *	for earlier writes to complete and generally returns before the
557167222Sdelphij *	caller's write has reached the device.
55892889Sobrien */
5591573Srgrimesvoid
5601573Srgrimeswaitrunningbufspace(void)
5611573Srgrimes{
5621573Srgrimes
5631573Srgrimes	mtx_lock(&rbreqlock);
564167222Sdelphij	while (runningbufspace > hirunningspace) {
5651573Srgrimes		runningbufreq = 1;
56692889Sobrien		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
56792889Sobrien	}
56892889Sobrien	mtx_unlock(&rbreqlock);
56992889Sobrien}
57092889Sobrien
57192889Sobrien
57292889Sobrien/*
57392889Sobrien *	vfs_buf_test_cache:
57492889Sobrien *
57592889Sobrien *	Called when a buffer is extended.  This function clears the B_CACHE
57692889Sobrien *	bit if the newly extended portion of the buffer does not contain
57792889Sobrien *	valid data.
578132019Stjr */
5791573Srgrimesstatic __inline
5801573Srgrimesvoid
5811573Srgrimesvfs_buf_test_cache(struct buf *bp,
5821573Srgrimes		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
5831573Srgrimes		  vm_page_t m)
5841573Srgrimes{
5851573Srgrimes
5861573Srgrimes	VM_OBJECT_ASSERT_LOCKED(m->object);
5871573Srgrimes	if (bp->b_flags & B_CACHE) {
588132019Stjr		int base = (foff + off) & PAGE_MASK;
5891573Srgrimes		if (vm_page_is_valid(m, base, size) == 0)
590132019Stjr			bp->b_flags &= ~B_CACHE;
591132019Stjr	}
592132019Stjr}
5931573Srgrimes
5941573Srgrimes/* Wake up the buffer daemon if necessary */
5951573Srgrimesstatic __inline void
5961573Srgrimesbd_wakeup(void)
597132019Stjr{
598132019Stjr
599132019Stjr	mtx_lock(&bdlock);
6001573Srgrimes	if (bd_request == 0) {
6011573Srgrimes		bd_request = 1;
602132019Stjr		wakeup(&bd_request);
603132019Stjr	}
6041573Srgrimes	mtx_unlock(&bdlock);
605132019Stjr}
606132019Stjr
6071573Srgrimes/*
6081573Srgrimes * bd_speedup - speedup the buffer cache flushing code
6091573Srgrimes */
6101573Srgrimesvoid
6111573Srgrimesbd_speedup(void)
6121573Srgrimes{
6131573Srgrimes	int needwake;
6141573Srgrimes
6151573Srgrimes	mtx_lock(&bdlock);
6161573Srgrimes	needwake = 0;
6171573Srgrimes	if (bd_speedupreq == 0 || bd_request == 0)
6181573Srgrimes		needwake = 1;
6191573Srgrimes	bd_speedupreq = 1;
6201573Srgrimes	bd_request = 1;
6211573Srgrimes	if (needwake)
6221573Srgrimes		wakeup(&bd_request);
6231573Srgrimes	mtx_unlock(&bdlock);
6241573Srgrimes}
6251573Srgrimes
6261573Srgrimes#ifdef __i386__
6271573Srgrimes#define	TRANSIENT_DENOM	5
6281573Srgrimes#else
6291573Srgrimes#define	TRANSIENT_DENOM 10
6301573Srgrimes#endif
6311573Srgrimes
6321573Srgrimes/*
6331573Srgrimes * Calculating buffer cache scaling values and reserve space for buffer
6341573Srgrimes * headers.  This is called during low level kernel initialization and
6351573Srgrimes * may be called more then once.  We CANNOT write to the memory area
6361573Srgrimes * being reserved at this time.
6371573Srgrimes */
6381573Srgrimescaddr_t
6391573Srgrimeskern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
6401573Srgrimes{
6411573Srgrimes	int tuned_nbuf;
6421573Srgrimes	long maxbuf, maxbuf_sz, buf_sz,	biotmap_sz;
6431573Srgrimes
6441573Srgrimes	/*
6451573Srgrimes	 * physmem_est is in pages.  Convert it to kilobytes (assumes
6461573Srgrimes	 * PAGE_SIZE is >= 1K)
6471573Srgrimes	 */
6481573Srgrimes	physmem_est = physmem_est * (PAGE_SIZE / 1024);
6491573Srgrimes
6501573Srgrimes	/*
6511573Srgrimes	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
6521573Srgrimes	 * For the first 64MB of ram nominally allocate sufficient buffers to
6531573Srgrimes	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
6541573Srgrimes	 * buffers to cover 1/10 of our ram over 64MB.  When auto-sizing
6551573Srgrimes	 * the buffer cache we limit the eventual kva reservation to
6561573Srgrimes	 * maxbcache bytes.
6571573Srgrimes	 *
6581573Srgrimes	 * factor represents the 1/4 x ram conversion.
6591573Srgrimes	 */
6601573Srgrimes	if (nbuf == 0) {
6611573Srgrimes		int factor = 4 * BKVASIZE / 1024;
6621573Srgrimes
6631573Srgrimes		nbuf = 50;
6641573Srgrimes		if (physmem_est > 4096)
6651573Srgrimes			nbuf += min((physmem_est - 4096) / factor,
6661573Srgrimes			    65536 / factor);
6671573Srgrimes		if (physmem_est > 65536)
6681573Srgrimes			nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
6691573Srgrimes			    32 * 1024 * 1024 / (factor * 5));
6701573Srgrimes
6711573Srgrimes		if (maxbcache && nbuf > maxbcache / BKVASIZE)
6721573Srgrimes			nbuf = maxbcache / BKVASIZE;
6731573Srgrimes		tuned_nbuf = 1;
6741573Srgrimes	} else
6751573Srgrimes		tuned_nbuf = 0;
6761573Srgrimes
6771573Srgrimes	/* XXX Avoid unsigned long overflows later on with maxbufspace. */
6781573Srgrimes	maxbuf = (LONG_MAX / 3) / BKVASIZE;
679167222Sdelphij	if (nbuf > maxbuf) {
680167216Sdelphij		if (!tuned_nbuf)
6811573Srgrimes			printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
6821573Srgrimes			    maxbuf);
6831573Srgrimes		nbuf = maxbuf;
6841573Srgrimes	}
6851573Srgrimes
6861573Srgrimes	/*
6871573Srgrimes	 * Ideal allocation size for the transient bio submap if 10%
6881573Srgrimes	 * of the maximal space buffer map.  This roughly corresponds
689167222Sdelphij	 * to the amount of the buffer mapped for typical UFS load.
6901573Srgrimes	 *
6911573Srgrimes	 * Clip the buffer map to reserve space for the transient
692167222Sdelphij	 * BIOs, if its extent is bigger than 90% (80% on i386) of the
6931573Srgrimes	 * maximum buffer map extent on the platform.
6941573Srgrimes	 *
695167222Sdelphij	 * The fall-back to the maxbuf in case of maxbcache unset,
6961573Srgrimes	 * allows to not trim the buffer KVA for the architectures
6971573Srgrimes	 * with ample KVA space.
6981573Srgrimes	 */
6991573Srgrimes	if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
7001573Srgrimes		maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
701167222Sdelphij		buf_sz = (long)nbuf * BKVASIZE;
7021573Srgrimes		if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
7031573Srgrimes		    (TRANSIENT_DENOM - 1)) {
7041573Srgrimes			/*
705167222Sdelphij			 * There is more KVA than memory.  Do not
7061573Srgrimes			 * adjust buffer map size, and assign the rest
7071573Srgrimes			 * of maxbuf to transient map.
708167222Sdelphij			 */
7091573Srgrimes			biotmap_sz = maxbuf_sz - buf_sz;
710167222Sdelphij		} else {
7111573Srgrimes			/*
7121573Srgrimes			 * Buffer map spans all KVA we could afford on
7131573Srgrimes			 * this platform.  Give 10% (20% on i386) of
7141573Srgrimes			 * the buffer map to the transient bio map.
7151573Srgrimes			 */
7161573Srgrimes			biotmap_sz = buf_sz / TRANSIENT_DENOM;
7171573Srgrimes			buf_sz -= biotmap_sz;
7181573Srgrimes		}
719167222Sdelphij		if (biotmap_sz / INT_MAX > MAXPHYS)
7201573Srgrimes			bio_transient_maxcnt = INT_MAX;
7211573Srgrimes		else
7221573Srgrimes			bio_transient_maxcnt = biotmap_sz / MAXPHYS;
7231573Srgrimes		/*
7241573Srgrimes		 * Artifically limit to 1024 simultaneous in-flight I/Os
7251573Srgrimes		 * using the transient mapping.
7261573Srgrimes		 */
7271573Srgrimes		if (bio_transient_maxcnt > 1024)
7281573Srgrimes			bio_transient_maxcnt = 1024;
7291573Srgrimes		if (tuned_nbuf)
7301573Srgrimes			nbuf = buf_sz / BKVASIZE;
7311573Srgrimes	}
7321573Srgrimes
7331573Srgrimes	/*
7341573Srgrimes	 * swbufs are used as temporary holders for I/O, such as paging I/O.
7351573Srgrimes	 * We have no less then 16 and no more then 256.
7361573Srgrimes	 */
7371573Srgrimes	nswbuf = max(min(nbuf/4, 256), 16);
7381573Srgrimes#ifdef NSWBUF_MIN
7391573Srgrimes	if (nswbuf < NSWBUF_MIN)
740167222Sdelphij		nswbuf = NSWBUF_MIN;
7411573Srgrimes#endif
7421573Srgrimes#ifdef DIRECTIO
7431573Srgrimes	ffs_rawread_setup();
7441573Srgrimes#endif
7451573Srgrimes
7461573Srgrimes	/*
7471573Srgrimes	 * Reserve space for the buffer cache buffers
7481573Srgrimes	 */
7491573Srgrimes	swbuf = (void *)v;
7501573Srgrimes	v = (caddr_t)(swbuf + nswbuf);
751167222Sdelphij	buf = (void *)v;
7521573Srgrimes	v = (caddr_t)(buf + nbuf);
7531573Srgrimes
7541573Srgrimes	return(v);
7551573Srgrimes}
7561573Srgrimes
7571573Srgrimes/* Initialize the buffer subsystem.  Called before use of any buffers. */
7581573Srgrimesvoid
7591573Srgrimesbufinit(void)
7601573Srgrimes{
7611573Srgrimes	struct buf *bp;
7621573Srgrimes	int i;
7631573Srgrimes
7641573Srgrimes	mtx_init(&bqclean, "bufq clean lock", NULL, MTX_DEF);
76511664Sphk	mtx_init(&bqdirty, "bufq dirty lock", NULL, MTX_DEF);
7661573Srgrimes	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
7671573Srgrimes	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
7681573Srgrimes	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
7691573Srgrimes	mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
77092889Sobrien
7711573Srgrimes	/* next, make a null set of free lists */
7721573Srgrimes	for (i = 0; i < BUFFER_QUEUES; i++)
7731573Srgrimes		TAILQ_INIT(&bufqueues[i]);
7741573Srgrimes
77592889Sobrien	/* finally, initialize each buffer header and stick on empty q */
7761573Srgrimes	for (i = 0; i < nbuf; i++) {
7771573Srgrimes		bp = &buf[i];
7781573Srgrimes		bzero(bp, sizeof *bp);
7791573Srgrimes		bp->b_flags = B_INVAL | B_INFREECNT;
7801573Srgrimes		bp->b_rcred = NOCRED;
78192889Sobrien		bp->b_wcred = NOCRED;
78292889Sobrien		bp->b_qindex = QUEUE_EMPTY;
78392889Sobrien		bp->b_xflags = 0;
78492889Sobrien		LIST_INIT(&bp->b_dep);
785132019Stjr		BUF_LOCKINIT(bp);
786132019Stjr		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
787132019Stjr#ifdef INVARIANTS
78892889Sobrien		bq_len[QUEUE_EMPTY]++;
78992889Sobrien#endif
790132019Stjr	}
7911573Srgrimes
7921573Srgrimes	/*
7931573Srgrimes	 * maxbufspace is the absolute maximum amount of buffer space we are
7941573Srgrimes	 * allowed to reserve in KVM and in real terms.  The absolute maximum
7951573Srgrimes	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
7961573Srgrimes	 * used by most other processes.  The differential is required to
7971573Srgrimes	 * ensure that buf_daemon is able to run when other processes might
798132019Stjr	 * be blocked waiting for buffer space.
799132019Stjr	 *
800132019Stjr	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
801132019Stjr	 * this may result in KVM fragmentation which is not handled optimally
802132019Stjr	 * by the system.
803132019Stjr	 */
804132019Stjr	maxbufspace = (long)nbuf * BKVASIZE;
805132019Stjr	hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
806132019Stjr	lobufspace = hibufspace - MAXBSIZE;
807132019Stjr
8081573Srgrimes	/*
8091573Srgrimes	 * Note: The 16 MiB upper limit for hirunningspace was chosen
8101573Srgrimes	 * arbitrarily and may need further tuning. It corresponds to
811149180Stjr	 * 128 outstanding write IO requests (if IO size is 128 KiB),
812149180Stjr	 * which fits with many RAID controllers' tagged queuing limits.
813132019Stjr	 * The lower 1 MiB limit is the historical upper limit for
814149180Stjr	 * hirunningspace.
815149180Stjr	 */
8161573Srgrimes	hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
8171573Srgrimes	    16 * 1024 * 1024), 1024 * 1024);
8181573Srgrimes	lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
8191573Srgrimes
8201573Srgrimes/*
8211573Srgrimes * Limit the amount of malloc memory since it is wired permanently into
8221573Srgrimes * the kernel space.  Even though this is accounted for in the buffer
8231573Srgrimes * allocation, we don't want the malloced region to grow uncontrolled.
8241573Srgrimes * The malloc scheme improves memory utilization significantly on average
8251573Srgrimes * (small) directories.
8261573Srgrimes */
8271573Srgrimes	maxbufmallocspace = hibufspace / 20;
8281573Srgrimes
8291573Srgrimes/*
8301573Srgrimes * Reduce the chance of a deadlock occuring by limiting the number
8311573Srgrimes * of delayed-write dirty buffers we allow to stack up.
8321573Srgrimes */
8331573Srgrimes	hidirtybuffers = nbuf / 4 + 20;
8341573Srgrimes	dirtybufthresh = hidirtybuffers * 9 / 10;
8351573Srgrimes	numdirtybuffers = 0;
8361573Srgrimes/*
8371573Srgrimes * To support extreme low-memory systems, make sure hidirtybuffers cannot
8381573Srgrimes * eat up all available buffer space.  This occurs when our minimum cannot
8391573Srgrimes * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
8401573Srgrimes * BKVASIZE'd buffers.
8411573Srgrimes */
8421573Srgrimes	while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
8431573Srgrimes		hidirtybuffers >>= 1;
8441573Srgrimes	}
8451573Srgrimes	lodirtybuffers = hidirtybuffers / 2;
8461573Srgrimes
8471573Srgrimes/*
8481573Srgrimes * Try to keep the number of free buffers in the specified range,
8491573Srgrimes * and give special processes (e.g. like buf_daemon) access to an
8501573Srgrimes * emergency reserve.
8511573Srgrimes */
8521573Srgrimes	lofreebuffers = nbuf / 18 + 5;
853149180Stjr	hifreebuffers = 2 * lofreebuffers;
8541573Srgrimes	numfreebuffers = nbuf;
8551573Srgrimes
8561573Srgrimes	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
8571573Srgrimes	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
8581573Srgrimes	unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
8591573Srgrimes}
8601573Srgrimes
8611573Srgrimes#ifdef INVARIANTS
8621573Srgrimesstatic inline void
863132019Stjrvfs_buf_check_mapped(struct buf *bp)
8641573Srgrimes{
8651573Srgrimes
8661573Srgrimes	KASSERT((bp->b_flags & B_UNMAPPED) == 0,
8671573Srgrimes	    ("mapped buf %p %x", bp, bp->b_flags));
8681573Srgrimes	KASSERT(bp->b_kvabase != unmapped_buf,
869137959Stjr	    ("mapped buf: b_kvabase was not updated %p", bp));
8701573Srgrimes	KASSERT(bp->b_data != unmapped_buf,
8711573Srgrimes	    ("mapped buf: b_data was not updated %p", bp));
8721573Srgrimes}
8731573Srgrimes
8741573Srgrimesstatic inline void
8751573Srgrimesvfs_buf_check_unmapped(struct buf *bp)
87692889Sobrien{
8771573Srgrimes
8781573Srgrimes	KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
8791573Srgrimes	    ("unmapped buf %p %x", bp, bp->b_flags));
8801573Srgrimes	KASSERT(bp->b_kvabase == unmapped_buf,
88192889Sobrien	    ("unmapped buf: corrupted b_kvabase %p", bp));
8821573Srgrimes	KASSERT(bp->b_data == unmapped_buf,
8831573Srgrimes	    ("unmapped buf: corrupted b_data %p", bp));
8841573Srgrimes}
8851573Srgrimes
8861573Srgrimes#define	BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
88792889Sobrien#define	BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
88892889Sobrien#else
88992889Sobrien#define	BUF_CHECK_MAPPED(bp) do {} while (0)
89092889Sobrien#define	BUF_CHECK_UNMAPPED(bp) do {} while (0)
891132019Stjr#endif
892132019Stjr
893132019Stjrstatic void
89492889Sobrienbpmap_qenter(struct buf *bp)
89592889Sobrien{
896132019Stjr
8971573Srgrimes	BUF_CHECK_MAPPED(bp);
8981573Srgrimes
8991573Srgrimes	/*
9001573Srgrimes	 * bp->b_data is relative to bp->b_offset, but
9011573Srgrimes	 * bp->b_offset may be offset into the first page.
9021573Srgrimes	 */
9031573Srgrimes	bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
904132019Stjr	pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
905132019Stjr	bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
906132019Stjr	    (vm_offset_t)(bp->b_offset & PAGE_MASK));
907132019Stjr}
908132019Stjr
909132019Stjr/*
910132019Stjr * bfreekva() - free the kva allocation for a buffer.
911132019Stjr *
912132019Stjr *	Since this call frees up buffer space, we call bufspacewakeup().
913132019Stjr */
9141573Srgrimesstatic void
9151573Srgrimesbfreekva(struct buf *bp)
9161573Srgrimes{
917132019Stjr
918132019Stjr	if (bp->b_kvasize == 0)
919132019Stjr		return;
920132019Stjr
921149180Stjr	atomic_add_int(&buffreekvacnt, 1);
9221573Srgrimes	atomic_subtract_long(&bufspace, bp->b_kvasize);
9231573Srgrimes	if ((bp->b_flags & B_UNMAPPED) == 0) {
9241573Srgrimes		BUF_CHECK_MAPPED(bp);
9251573Srgrimes		vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase,
9261573Srgrimes		    bp->b_kvasize);
9271573Srgrimes	} else {
9281573Srgrimes		BUF_CHECK_UNMAPPED(bp);
9291573Srgrimes		if ((bp->b_flags & B_KVAALLOC) != 0) {
9301573Srgrimes			vmem_free(buffer_arena, (vm_offset_t)bp->b_kvaalloc,
9311573Srgrimes			    bp->b_kvasize);
9321573Srgrimes		}
9331573Srgrimes		atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
9341573Srgrimes		bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
9351573Srgrimes	}
9361573Srgrimes	bp->b_kvasize = 0;
9371573Srgrimes	bufspacewakeup();
9381573Srgrimes}
9391573Srgrimes
9401573Srgrimes/*
9411573Srgrimes *	binsfree:
9421573Srgrimes *
9431573Srgrimes *	Insert the buffer into the appropriate free list.
9441573Srgrimes */
9451573Srgrimesstatic void
9461573Srgrimesbinsfree(struct buf *bp, int qindex)
9471573Srgrimes{
9481573Srgrimes	struct mtx *olock, *nlock;
9491573Srgrimes
9501573Srgrimes	BUF_ASSERT_XLOCKED(bp);
9511573Srgrimes
9521573Srgrimes	olock = bqlock(bp->b_qindex);
9531573Srgrimes	nlock = bqlock(qindex);
9541573Srgrimes	mtx_lock(olock);
9551573Srgrimes	/* Handle delayed bremfree() processing. */
9561573Srgrimes	if (bp->b_flags & B_REMFREE)
9571573Srgrimes		bremfreel(bp);
9581573Srgrimes
959149180Stjr	if (bp->b_qindex != QUEUE_NONE)
9601573Srgrimes		panic("binsfree: free buffer onto another queue???");
9611573Srgrimes
9621573Srgrimes	bp->b_qindex = qindex;
9631573Srgrimes	if (olock != nlock) {
9641573Srgrimes		mtx_unlock(olock);
9651573Srgrimes		mtx_lock(nlock);
9661573Srgrimes	}
9671573Srgrimes	if (bp->b_flags & B_AGE)
9681573Srgrimes		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
969132019Stjr	else
9701573Srgrimes		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
9711573Srgrimes#ifdef INVARIANTS
9721573Srgrimes	bq_len[bp->b_qindex]++;
9731573Srgrimes#endif
9741573Srgrimes	mtx_unlock(nlock);
9751573Srgrimes
9761573Srgrimes	/*
9771573Srgrimes	 * Something we can maybe free or reuse.
97892889Sobrien	 */
97992889Sobrien	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
980132019Stjr		bufspacewakeup();
981132019Stjr
982132019Stjr	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
983132019Stjr		bufcountadd(bp);
984132019Stjr}
985132019Stjr
986132019Stjr/*
987132019Stjr *	bremfree:
9881573Srgrimes *
9891573Srgrimes *	Mark the buffer for removal from the appropriate free list.
9901573Srgrimes *
99192889Sobrien */
9921573Srgrimesvoid
9931573Srgrimesbremfree(struct buf *bp)
99492889Sobrien{
995132019Stjr
99692889Sobrien	CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
9971573Srgrimes	KASSERT((bp->b_flags & B_REMFREE) == 0,
99892889Sobrien	    ("bremfree: buffer %p already marked for delayed removal.", bp));
99992889Sobrien	KASSERT(bp->b_qindex != QUEUE_NONE,
100092889Sobrien	    ("bremfree: buffer %p not on a queue.", bp));
100192889Sobrien	BUF_ASSERT_XLOCKED(bp);
100292889Sobrien
100392889Sobrien	bp->b_flags |= B_REMFREE;
10041573Srgrimes	bufcountsub(bp);
10051573Srgrimes}
10061573Srgrimes
10071573Srgrimes/*
10081573Srgrimes *	bremfreef:
10091573Srgrimes *
10101573Srgrimes *	Force an immediate removal from a free list.  Used only in nfs when
10111573Srgrimes *	it abuses the b_freelist pointer.
10121573Srgrimes */
1013132019Stjrvoid
1014132019Stjrbremfreef(struct buf *bp)
10151573Srgrimes{
10161573Srgrimes	struct mtx *qlock;
10171573Srgrimes
10181573Srgrimes	qlock = bqlock(bp->b_qindex);
10191573Srgrimes	mtx_lock(qlock);
10201573Srgrimes	bremfreel(bp);
10211573Srgrimes	mtx_unlock(qlock);
10221573Srgrimes}
10231573Srgrimes
10241573Srgrimes/*
10251573Srgrimes *	bremfreel:
10261573Srgrimes *
10271573Srgrimes *	Removes a buffer from the free list, must be called with the
10281573Srgrimes *	correct qlock held.
10291573Srgrimes */
10301573Srgrimesstatic void
10311573Srgrimesbremfreel(struct buf *bp)
10321573Srgrimes{
10331573Srgrimes
10341573Srgrimes	CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
10351573Srgrimes	    bp, bp->b_vp, bp->b_flags);
10361573Srgrimes	KASSERT(bp->b_qindex != QUEUE_NONE,
10371573Srgrimes	    ("bremfreel: buffer %p not on a queue.", bp));
10381573Srgrimes	BUF_ASSERT_XLOCKED(bp);
10391573Srgrimes	mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
10401573Srgrimes
10411573Srgrimes	TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
10421573Srgrimes#ifdef INVARIANTS
10431573Srgrimes	KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
10441573Srgrimes	    bp->b_qindex));
10451573Srgrimes	bq_len[bp->b_qindex]--;
10461573Srgrimes#endif
10471573Srgrimes	bp->b_qindex = QUEUE_NONE;
10481573Srgrimes	/*
10491573Srgrimes	 * If this was a delayed bremfree() we only need to remove the buffer
10501573Srgrimes	 * from the queue and return the stats are already done.
10511573Srgrimes	 */
10521573Srgrimes	if (bp->b_flags & B_REMFREE) {
10531573Srgrimes		bp->b_flags &= ~B_REMFREE;
10541573Srgrimes		return;
10551573Srgrimes	}
10561573Srgrimes	bufcountsub(bp);
10571573Srgrimes}
10581573Srgrimes
10591573Srgrimes/*
10601573Srgrimes * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
10611573Srgrimes * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
10621573Srgrimes * the buffer is valid and we do not have to do anything.
10631573Srgrimes */
10641573Srgrimesvoid
10651573Srgrimesbreada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
10661573Srgrimes    int cnt, struct ucred * cred)
10671573Srgrimes{
10681573Srgrimes	struct buf *rabp;
10691573Srgrimes	int i;
10701573Srgrimes
10711573Srgrimes	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
10721573Srgrimes		if (inmem(vp, *rablkno))
10731573Srgrimes			continue;
10741573Srgrimes		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
10751573Srgrimes
10761573Srgrimes		if ((rabp->b_flags & B_CACHE) == 0) {
10771573Srgrimes			if (!TD_IS_IDLETHREAD(curthread))
10781573Srgrimes				curthread->td_ru.ru_inblock++;
10791573Srgrimes			rabp->b_flags |= B_ASYNC;
10801573Srgrimes			rabp->b_flags &= ~B_INVAL;
10811573Srgrimes			rabp->b_ioflags &= ~BIO_ERROR;
10821573Srgrimes			rabp->b_iocmd = BIO_READ;
10831573Srgrimes			if (rabp->b_rcred == NOCRED && cred != NOCRED)
10841573Srgrimes				rabp->b_rcred = crhold(cred);
10851573Srgrimes			vfs_busy_pages(rabp, 0);
10861573Srgrimes			BUF_KERNPROC(rabp);
10871573Srgrimes			rabp->b_iooffset = dbtob(rabp->b_blkno);
10881573Srgrimes			bstrategy(rabp);
10891573Srgrimes		} else {
10901573Srgrimes			brelse(rabp);
10911573Srgrimes		}
10921573Srgrimes	}
10931573Srgrimes}
10941573Srgrimes
10951573Srgrimes/*
10961573Srgrimes * Entry point for bread() and breadn() via #defines in sys/buf.h.
10971573Srgrimes *
10981573Srgrimes * Get a buffer with the specified data.  Look in the cache first.  We
10991573Srgrimes * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
11001573Srgrimes * is set, the buffer is valid and we do not have to do anything, see
11011573Srgrimes * getblk(). Also starts asynchronous I/O on read-ahead blocks.
11021573Srgrimes */
11031573Srgrimesint
11041573Srgrimesbreadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
11051573Srgrimes    int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
11061573Srgrimes{
11071573Srgrimes	struct buf *bp;
11081573Srgrimes	int rv = 0, readwait = 0;
11091573Srgrimes
11101573Srgrimes	CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
11111573Srgrimes	/*
11121573Srgrimes	 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
11131573Srgrimes	 */
11141573Srgrimes	*bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
11151573Srgrimes	if (bp == NULL)
11161573Srgrimes		return (EBUSY);
11171573Srgrimes
11181573Srgrimes	/* if not found in cache, do some I/O */
111992889Sobrien	if ((bp->b_flags & B_CACHE) == 0) {
112092889Sobrien		if (!TD_IS_IDLETHREAD(curthread))
112192889Sobrien			curthread->td_ru.ru_inblock++;
11221573Srgrimes		bp->b_iocmd = BIO_READ;
11231573Srgrimes		bp->b_flags &= ~B_INVAL;
11241573Srgrimes		bp->b_ioflags &= ~BIO_ERROR;
11251573Srgrimes		if (bp->b_rcred == NOCRED && cred != NOCRED)
11261573Srgrimes			bp->b_rcred = crhold(cred);
11271573Srgrimes		vfs_busy_pages(bp, 0);
11281573Srgrimes		bp->b_iooffset = dbtob(bp->b_blkno);
11291573Srgrimes		bstrategy(bp);
11301573Srgrimes		++readwait;
11311573Srgrimes	}
11321573Srgrimes
11331573Srgrimes	breada(vp, rablkno, rabsize, cnt, cred);
11341573Srgrimes
11351573Srgrimes	if (readwait) {
11361573Srgrimes		rv = bufwait(bp);
11378870Srgrimes	}
11381573Srgrimes	return (rv);
11391573Srgrimes}
11401573Srgrimes
11411573Srgrimes/*
11421573Srgrimes * Write, release buffer on completion.  (Done by iodone
11431573Srgrimes * if async).  Do not bother writing anything if the buffer
11441573Srgrimes * is invalid.
11451573Srgrimes *
11461573Srgrimes * Note that we set B_CACHE here, indicating that buffer is
11471573Srgrimes * fully valid and thus cacheable.  This is true even of NFS
11481573Srgrimes * now so we set it generally.  This could be set either here
11491573Srgrimes * or in biodone() since the I/O is synchronous.  We put it
11501573Srgrimes * here.
11511573Srgrimes */
11521573Srgrimesint
11531573Srgrimesbufwrite(struct buf *bp)
11541573Srgrimes{
11551573Srgrimes	int oldflags;
11561573Srgrimes	struct vnode *vp;
11571573Srgrimes	long space;
11581573Srgrimes	int vp_md;
11591573Srgrimes
11601573Srgrimes	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
11611573Srgrimes	if (bp->b_flags & B_INVAL) {
11621573Srgrimes		brelse(bp);
11631573Srgrimes		return (0);
11641573Srgrimes	}
11651573Srgrimes
11661573Srgrimes	if (bp->b_flags & B_BARRIER)
11671573Srgrimes		barrierwrites++;
11681573Srgrimes
11691573Srgrimes	oldflags = bp->b_flags;
11701573Srgrimes
11711573Srgrimes	BUF_ASSERT_HELD(bp);
11721573Srgrimes
11731573Srgrimes	if (bp->b_pin_count > 0)
11741573Srgrimes		bunpin_wait(bp);
11751573Srgrimes
11761573Srgrimes	KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
11771573Srgrimes	    ("FFS background buffer should not get here %p", bp));
11781573Srgrimes
11791573Srgrimes	vp = bp->b_vp;
118017508Sache	if (vp)
11811573Srgrimes		vp_md = vp->v_vflag & VV_MD;
11821573Srgrimes	else
11831573Srgrimes		vp_md = 0;
11841573Srgrimes
11851573Srgrimes	/*
11861573Srgrimes	 * Mark the buffer clean.  Increment the bufobj write count
11871573Srgrimes	 * before bundirty() call, to prevent other thread from seeing
11881573Srgrimes	 * empty dirty list and zero counter for writes in progress,
11891573Srgrimes	 * falsely indicating that the bufobj is clean.
11901573Srgrimes	 */
11911573Srgrimes	bufobj_wref(bp->b_bufobj);
11921573Srgrimes	bundirty(bp);
11931573Srgrimes
11941573Srgrimes	bp->b_flags &= ~B_DONE;
11951573Srgrimes	bp->b_ioflags &= ~BIO_ERROR;
11961573Srgrimes	bp->b_flags |= B_CACHE;
11971573Srgrimes	bp->b_iocmd = BIO_WRITE;
1198
1199	vfs_busy_pages(bp, 1);
1200
1201	/*
1202	 * Normal bwrites pipeline writes
1203	 */
1204	bp->b_runningbufspace = bp->b_bufsize;
1205	space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1206
1207	if (!TD_IS_IDLETHREAD(curthread))
1208		curthread->td_ru.ru_oublock++;
1209	if (oldflags & B_ASYNC)
1210		BUF_KERNPROC(bp);
1211	bp->b_iooffset = dbtob(bp->b_blkno);
1212	bstrategy(bp);
1213
1214	if ((oldflags & B_ASYNC) == 0) {
1215		int rtval = bufwait(bp);
1216		brelse(bp);
1217		return (rtval);
1218	} else if (space > hirunningspace) {
1219		/*
1220		 * don't allow the async write to saturate the I/O
1221		 * system.  We will not deadlock here because
1222		 * we are blocking waiting for I/O that is already in-progress
1223		 * to complete. We do not block here if it is the update
1224		 * or syncer daemon trying to clean up as that can lead
1225		 * to deadlock.
1226		 */
1227		if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1228			waitrunningbufspace();
1229	}
1230
1231	return (0);
1232}
1233
1234void
1235bufbdflush(struct bufobj *bo, struct buf *bp)
1236{
1237	struct buf *nbp;
1238
1239	if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1240		(void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1241		altbufferflushes++;
1242	} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1243		BO_LOCK(bo);
1244		/*
1245		 * Try to find a buffer to flush.
1246		 */
1247		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1248			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1249			    BUF_LOCK(nbp,
1250				     LK_EXCLUSIVE | LK_NOWAIT, NULL))
1251				continue;
1252			if (bp == nbp)
1253				panic("bdwrite: found ourselves");
1254			BO_UNLOCK(bo);
1255			/* Don't countdeps with the bo lock held. */
1256			if (buf_countdeps(nbp, 0)) {
1257				BO_LOCK(bo);
1258				BUF_UNLOCK(nbp);
1259				continue;
1260			}
1261			if (nbp->b_flags & B_CLUSTEROK) {
1262				vfs_bio_awrite(nbp);
1263			} else {
1264				bremfree(nbp);
1265				bawrite(nbp);
1266			}
1267			dirtybufferflushes++;
1268			break;
1269		}
1270		if (nbp == NULL)
1271			BO_UNLOCK(bo);
1272	}
1273}
1274
1275/*
1276 * Delayed write. (Buffer is marked dirty).  Do not bother writing
1277 * anything if the buffer is marked invalid.
1278 *
1279 * Note that since the buffer must be completely valid, we can safely
1280 * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
1281 * biodone() in order to prevent getblk from writing the buffer
1282 * out synchronously.
1283 */
1284void
1285bdwrite(struct buf *bp)
1286{
1287	struct thread *td = curthread;
1288	struct vnode *vp;
1289	struct bufobj *bo;
1290
1291	CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1292	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1293	KASSERT((bp->b_flags & B_BARRIER) == 0,
1294	    ("Barrier request in delayed write %p", bp));
1295	BUF_ASSERT_HELD(bp);
1296
1297	if (bp->b_flags & B_INVAL) {
1298		brelse(bp);
1299		return;
1300	}
1301
1302	/*
1303	 * If we have too many dirty buffers, don't create any more.
1304	 * If we are wildly over our limit, then force a complete
1305	 * cleanup. Otherwise, just keep the situation from getting
1306	 * out of control. Note that we have to avoid a recursive
1307	 * disaster and not try to clean up after our own cleanup!
1308	 */
1309	vp = bp->b_vp;
1310	bo = bp->b_bufobj;
1311	if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1312		td->td_pflags |= TDP_INBDFLUSH;
1313		BO_BDFLUSH(bo, bp);
1314		td->td_pflags &= ~TDP_INBDFLUSH;
1315	} else
1316		recursiveflushes++;
1317
1318	bdirty(bp);
1319	/*
1320	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1321	 * true even of NFS now.
1322	 */
1323	bp->b_flags |= B_CACHE;
1324
1325	/*
1326	 * This bmap keeps the system from needing to do the bmap later,
1327	 * perhaps when the system is attempting to do a sync.  Since it
1328	 * is likely that the indirect block -- or whatever other datastructure
1329	 * that the filesystem needs is still in memory now, it is a good
1330	 * thing to do this.  Note also, that if the pageout daemon is
1331	 * requesting a sync -- there might not be enough memory to do
1332	 * the bmap then...  So, this is important to do.
1333	 */
1334	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1335		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1336	}
1337
1338	/*
1339	 * Set the *dirty* buffer range based upon the VM system dirty
1340	 * pages.
1341	 *
1342	 * Mark the buffer pages as clean.  We need to do this here to
1343	 * satisfy the vnode_pager and the pageout daemon, so that it
1344	 * thinks that the pages have been "cleaned".  Note that since
1345	 * the pages are in a delayed write buffer -- the VFS layer
1346	 * "will" see that the pages get written out on the next sync,
1347	 * or perhaps the cluster will be completed.
1348	 */
1349	vfs_clean_pages_dirty_buf(bp);
1350	bqrelse(bp);
1351
1352	/*
1353	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1354	 * due to the softdep code.
1355	 */
1356}
1357
1358/*
1359 *	bdirty:
1360 *
1361 *	Turn buffer into delayed write request.  We must clear BIO_READ and
1362 *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1363 *	itself to properly update it in the dirty/clean lists.  We mark it
1364 *	B_DONE to ensure that any asynchronization of the buffer properly
1365 *	clears B_DONE ( else a panic will occur later ).
1366 *
1367 *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1368 *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1369 *	should only be called if the buffer is known-good.
1370 *
1371 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1372 *	count.
1373 *
1374 *	The buffer must be on QUEUE_NONE.
1375 */
1376void
1377bdirty(struct buf *bp)
1378{
1379
1380	CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1381	    bp, bp->b_vp, bp->b_flags);
1382	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1383	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1384	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1385	BUF_ASSERT_HELD(bp);
1386	bp->b_flags &= ~(B_RELBUF);
1387	bp->b_iocmd = BIO_WRITE;
1388
1389	if ((bp->b_flags & B_DELWRI) == 0) {
1390		bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1391		reassignbuf(bp);
1392		bdirtyadd();
1393	}
1394}
1395
1396/*
1397 *	bundirty:
1398 *
1399 *	Clear B_DELWRI for buffer.
1400 *
1401 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1402 *	count.
1403 *
1404 *	The buffer must be on QUEUE_NONE.
1405 */
1406
1407void
1408bundirty(struct buf *bp)
1409{
1410
1411	CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1412	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1413	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1414	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1415	BUF_ASSERT_HELD(bp);
1416
1417	if (bp->b_flags & B_DELWRI) {
1418		bp->b_flags &= ~B_DELWRI;
1419		reassignbuf(bp);
1420		bdirtysub();
1421	}
1422	/*
1423	 * Since it is now being written, we can clear its deferred write flag.
1424	 */
1425	bp->b_flags &= ~B_DEFERRED;
1426}
1427
1428/*
1429 *	bawrite:
1430 *
1431 *	Asynchronous write.  Start output on a buffer, but do not wait for
1432 *	it to complete.  The buffer is released when the output completes.
1433 *
1434 *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1435 *	B_INVAL buffers.  Not us.
1436 */
1437void
1438bawrite(struct buf *bp)
1439{
1440
1441	bp->b_flags |= B_ASYNC;
1442	(void) bwrite(bp);
1443}
1444
1445/*
1446 *	babarrierwrite:
1447 *
1448 *	Asynchronous barrier write.  Start output on a buffer, but do not
1449 *	wait for it to complete.  Place a write barrier after this write so
1450 *	that this buffer and all buffers written before it are committed to
1451 *	the disk before any buffers written after this write are committed
1452 *	to the disk.  The buffer is released when the output completes.
1453 */
1454void
1455babarrierwrite(struct buf *bp)
1456{
1457
1458	bp->b_flags |= B_ASYNC | B_BARRIER;
1459	(void) bwrite(bp);
1460}
1461
1462/*
1463 *	bbarrierwrite:
1464 *
1465 *	Synchronous barrier write.  Start output on a buffer and wait for
1466 *	it to complete.  Place a write barrier after this write so that
1467 *	this buffer and all buffers written before it are committed to
1468 *	the disk before any buffers written after this write are committed
1469 *	to the disk.  The buffer is released when the output completes.
1470 */
1471int
1472bbarrierwrite(struct buf *bp)
1473{
1474
1475	bp->b_flags |= B_BARRIER;
1476	return (bwrite(bp));
1477}
1478
1479/*
1480 *	bwillwrite:
1481 *
1482 *	Called prior to the locking of any vnodes when we are expecting to
1483 *	write.  We do not want to starve the buffer cache with too many
1484 *	dirty buffers so we block here.  By blocking prior to the locking
1485 *	of any vnodes we attempt to avoid the situation where a locked vnode
1486 *	prevents the various system daemons from flushing related buffers.
1487 */
1488void
1489bwillwrite(void)
1490{
1491
1492	if (numdirtybuffers >= hidirtybuffers) {
1493		mtx_lock(&bdirtylock);
1494		while (numdirtybuffers >= hidirtybuffers) {
1495			bdirtywait = 1;
1496			msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
1497			    "flswai", 0);
1498		}
1499		mtx_unlock(&bdirtylock);
1500	}
1501}
1502
1503/*
1504 * Return true if we have too many dirty buffers.
1505 */
1506int
1507buf_dirty_count_severe(void)
1508{
1509
1510	return(numdirtybuffers >= hidirtybuffers);
1511}
1512
1513static __noinline int
1514buf_vm_page_count_severe(void)
1515{
1516
1517	KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1518
1519	return vm_page_count_severe();
1520}
1521
1522/*
1523 *	brelse:
1524 *
1525 *	Release a busy buffer and, if requested, free its resources.  The
1526 *	buffer will be stashed in the appropriate bufqueue[] allowing it
1527 *	to be accessed later as a cache entity or reused for other purposes.
1528 */
1529void
1530brelse(struct buf *bp)
1531{
1532	int qindex;
1533
1534	CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1535	    bp, bp->b_vp, bp->b_flags);
1536	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1537	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1538
1539	if (BUF_LOCKRECURSED(bp)) {
1540		/*
1541		 * Do not process, in particular, do not handle the
1542		 * B_INVAL/B_RELBUF and do not release to free list.
1543		 */
1544		BUF_UNLOCK(bp);
1545		return;
1546	}
1547
1548	if (bp->b_flags & B_MANAGED) {
1549		bqrelse(bp);
1550		return;
1551	}
1552
1553	if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1554	    bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1555		/*
1556		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1557		 * pages from being scrapped.  If the error is anything
1558		 * other than an I/O error (EIO), assume that retrying
1559		 * is futile.
1560		 */
1561		bp->b_ioflags &= ~BIO_ERROR;
1562		bdirty(bp);
1563	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1564	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1565		/*
1566		 * Either a failed I/O or we were asked to free or not
1567		 * cache the buffer.
1568		 */
1569		bp->b_flags |= B_INVAL;
1570		if (!LIST_EMPTY(&bp->b_dep))
1571			buf_deallocate(bp);
1572		if (bp->b_flags & B_DELWRI)
1573			bdirtysub();
1574		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1575		if ((bp->b_flags & B_VMIO) == 0) {
1576			if (bp->b_bufsize)
1577				allocbuf(bp, 0);
1578			if (bp->b_vp)
1579				brelvp(bp);
1580		}
1581	}
1582
1583	/*
1584	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1585	 * is called with B_DELWRI set, the underlying pages may wind up
1586	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1587	 * because pages associated with a B_DELWRI bp are marked clean.
1588	 *
1589	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1590	 * if B_DELWRI is set.
1591	 *
1592	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1593	 * on pages to return pages to the VM page queues.
1594	 */
1595	if (bp->b_flags & B_DELWRI)
1596		bp->b_flags &= ~B_RELBUF;
1597	else if (buf_vm_page_count_severe()) {
1598		/*
1599		 * BKGRDINPROG can only be set with the buf and bufobj
1600		 * locks both held.  We tolerate a race to clear it here.
1601		 */
1602		if (!(bp->b_vflags & BV_BKGRDINPROG))
1603			bp->b_flags |= B_RELBUF;
1604	}
1605
1606	/*
1607	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1608	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1609	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1610	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1611	 *
1612	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1613	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1614	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1615	 *
1616	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1617	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1618	 * the commit state and we cannot afford to lose the buffer. If the
1619	 * buffer has a background write in progress, we need to keep it
1620	 * around to prevent it from being reconstituted and starting a second
1621	 * background write.
1622	 */
1623	if ((bp->b_flags & B_VMIO)
1624	    && !(bp->b_vp->v_mount != NULL &&
1625		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1626		 !vn_isdisk(bp->b_vp, NULL) &&
1627		 (bp->b_flags & B_DELWRI))
1628	    ) {
1629
1630		int i, j, resid;
1631		vm_page_t m;
1632		off_t foff;
1633		vm_pindex_t poff;
1634		vm_object_t obj;
1635
1636		obj = bp->b_bufobj->bo_object;
1637
1638		/*
1639		 * Get the base offset and length of the buffer.  Note that
1640		 * in the VMIO case if the buffer block size is not
1641		 * page-aligned then b_data pointer may not be page-aligned.
1642		 * But our b_pages[] array *IS* page aligned.
1643		 *
1644		 * block sizes less then DEV_BSIZE (usually 512) are not
1645		 * supported due to the page granularity bits (m->valid,
1646		 * m->dirty, etc...).
1647		 *
1648		 * See man buf(9) for more information
1649		 */
1650		resid = bp->b_bufsize;
1651		foff = bp->b_offset;
1652		for (i = 0; i < bp->b_npages; i++) {
1653			int had_bogus = 0;
1654
1655			m = bp->b_pages[i];
1656
1657			/*
1658			 * If we hit a bogus page, fixup *all* the bogus pages
1659			 * now.
1660			 */
1661			if (m == bogus_page) {
1662				poff = OFF_TO_IDX(bp->b_offset);
1663				had_bogus = 1;
1664
1665				VM_OBJECT_RLOCK(obj);
1666				for (j = i; j < bp->b_npages; j++) {
1667					vm_page_t mtmp;
1668					mtmp = bp->b_pages[j];
1669					if (mtmp == bogus_page) {
1670						mtmp = vm_page_lookup(obj, poff + j);
1671						if (!mtmp) {
1672							panic("brelse: page missing\n");
1673						}
1674						bp->b_pages[j] = mtmp;
1675					}
1676				}
1677				VM_OBJECT_RUNLOCK(obj);
1678
1679				if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1680					BUF_CHECK_MAPPED(bp);
1681					pmap_qenter(
1682					    trunc_page((vm_offset_t)bp->b_data),
1683					    bp->b_pages, bp->b_npages);
1684				}
1685				m = bp->b_pages[i];
1686			}
1687			if ((bp->b_flags & B_NOCACHE) ||
1688			    (bp->b_ioflags & BIO_ERROR &&
1689			     bp->b_iocmd == BIO_READ)) {
1690				int poffset = foff & PAGE_MASK;
1691				int presid = resid > (PAGE_SIZE - poffset) ?
1692					(PAGE_SIZE - poffset) : resid;
1693
1694				KASSERT(presid >= 0, ("brelse: extra page"));
1695				VM_OBJECT_WLOCK(obj);
1696				while (vm_page_xbusied(m)) {
1697					vm_page_lock(m);
1698					VM_OBJECT_WUNLOCK(obj);
1699					vm_page_busy_sleep(m, "mbncsh");
1700					VM_OBJECT_WLOCK(obj);
1701				}
1702				if (pmap_page_wired_mappings(m) == 0)
1703					vm_page_set_invalid(m, poffset, presid);
1704				VM_OBJECT_WUNLOCK(obj);
1705				if (had_bogus)
1706					printf("avoided corruption bug in bogus_page/brelse code\n");
1707			}
1708			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1709			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1710		}
1711		if (bp->b_flags & (B_INVAL | B_RELBUF))
1712			vfs_vmio_release(bp);
1713
1714	} else if (bp->b_flags & B_VMIO) {
1715
1716		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1717			vfs_vmio_release(bp);
1718		}
1719
1720	} else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1721		if (bp->b_bufsize != 0)
1722			allocbuf(bp, 0);
1723		if (bp->b_vp != NULL)
1724			brelvp(bp);
1725	}
1726
1727	/*
1728	 * If the buffer has junk contents signal it and eventually
1729	 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1730	 * doesn't find it.
1731	 */
1732	if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1733	    (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1734		bp->b_flags |= B_INVAL;
1735	if (bp->b_flags & B_INVAL) {
1736		if (bp->b_flags & B_DELWRI)
1737			bundirty(bp);
1738		if (bp->b_vp)
1739			brelvp(bp);
1740	}
1741
1742	/* buffers with no memory */
1743	if (bp->b_bufsize == 0) {
1744		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1745		if (bp->b_vflags & BV_BKGRDINPROG)
1746			panic("losing buffer 1");
1747		if (bp->b_kvasize)
1748			qindex = QUEUE_EMPTYKVA;
1749		else
1750			qindex = QUEUE_EMPTY;
1751		bp->b_flags |= B_AGE;
1752	/* buffers with junk contents */
1753	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1754	    (bp->b_ioflags & BIO_ERROR)) {
1755		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1756		if (bp->b_vflags & BV_BKGRDINPROG)
1757			panic("losing buffer 2");
1758		qindex = QUEUE_CLEAN;
1759		bp->b_flags |= B_AGE;
1760	/* remaining buffers */
1761	} else if (bp->b_flags & B_DELWRI)
1762		qindex = QUEUE_DIRTY;
1763	else
1764		qindex = QUEUE_CLEAN;
1765
1766	binsfree(bp, qindex);
1767
1768	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1769	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1770		panic("brelse: not dirty");
1771	/* unlock */
1772	BUF_UNLOCK(bp);
1773}
1774
1775/*
1776 * Release a buffer back to the appropriate queue but do not try to free
1777 * it.  The buffer is expected to be used again soon.
1778 *
1779 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1780 * biodone() to requeue an async I/O on completion.  It is also used when
1781 * known good buffers need to be requeued but we think we may need the data
1782 * again soon.
1783 *
1784 * XXX we should be able to leave the B_RELBUF hint set on completion.
1785 */
1786void
1787bqrelse(struct buf *bp)
1788{
1789	int qindex;
1790
1791	CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1792	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1793	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1794
1795	if (BUF_LOCKRECURSED(bp)) {
1796		/* do not release to free list */
1797		BUF_UNLOCK(bp);
1798		return;
1799	}
1800	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1801
1802	if (bp->b_flags & B_MANAGED) {
1803		if (bp->b_flags & B_REMFREE)
1804			bremfreef(bp);
1805		goto out;
1806	}
1807
1808	/* buffers with stale but valid contents */
1809	if (bp->b_flags & B_DELWRI) {
1810		qindex = QUEUE_DIRTY;
1811	} else {
1812		if ((bp->b_flags & B_DELWRI) == 0 &&
1813		    (bp->b_xflags & BX_VNDIRTY))
1814			panic("bqrelse: not dirty");
1815		/*
1816		 * BKGRDINPROG can only be set with the buf and bufobj
1817		 * locks both held.  We tolerate a race to clear it here.
1818		 */
1819		if (buf_vm_page_count_severe() &&
1820		    (bp->b_vflags & BV_BKGRDINPROG) == 0) {
1821			/*
1822			 * We are too low on memory, we have to try to free
1823			 * the buffer (most importantly: the wired pages
1824			 * making up its backing store) *now*.
1825			 */
1826			brelse(bp);
1827			return;
1828		}
1829		qindex = QUEUE_CLEAN;
1830	}
1831	binsfree(bp, qindex);
1832
1833out:
1834	/* unlock */
1835	BUF_UNLOCK(bp);
1836}
1837
1838/* Give pages used by the bp back to the VM system (where possible) */
1839static void
1840vfs_vmio_release(struct buf *bp)
1841{
1842	int i;
1843	vm_page_t m;
1844
1845	if ((bp->b_flags & B_UNMAPPED) == 0) {
1846		BUF_CHECK_MAPPED(bp);
1847		pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1848	} else
1849		BUF_CHECK_UNMAPPED(bp);
1850	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1851	for (i = 0; i < bp->b_npages; i++) {
1852		m = bp->b_pages[i];
1853		bp->b_pages[i] = NULL;
1854		/*
1855		 * In order to keep page LRU ordering consistent, put
1856		 * everything on the inactive queue.
1857		 */
1858		vm_page_lock(m);
1859		vm_page_unwire(m, 0);
1860
1861		/*
1862		 * Might as well free the page if we can and it has
1863		 * no valid data.  We also free the page if the
1864		 * buffer was used for direct I/O
1865		 */
1866		if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1867			if (m->wire_count == 0 && !vm_page_busied(m))
1868				vm_page_free(m);
1869		} else if (bp->b_flags & B_DIRECT)
1870			vm_page_try_to_free(m);
1871		else if (buf_vm_page_count_severe())
1872			vm_page_try_to_cache(m);
1873		vm_page_unlock(m);
1874	}
1875	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1876
1877	if (bp->b_bufsize) {
1878		bufspacewakeup();
1879		bp->b_bufsize = 0;
1880	}
1881	bp->b_npages = 0;
1882	bp->b_flags &= ~B_VMIO;
1883	if (bp->b_vp)
1884		brelvp(bp);
1885}
1886
1887/*
1888 * Check to see if a block at a particular lbn is available for a clustered
1889 * write.
1890 */
1891static int
1892vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1893{
1894	struct buf *bpa;
1895	int match;
1896
1897	match = 0;
1898
1899	/* If the buf isn't in core skip it */
1900	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1901		return (0);
1902
1903	/* If the buf is busy we don't want to wait for it */
1904	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1905		return (0);
1906
1907	/* Only cluster with valid clusterable delayed write buffers */
1908	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1909	    (B_DELWRI | B_CLUSTEROK))
1910		goto done;
1911
1912	if (bpa->b_bufsize != size)
1913		goto done;
1914
1915	/*
1916	 * Check to see if it is in the expected place on disk and that the
1917	 * block has been mapped.
1918	 */
1919	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1920		match = 1;
1921done:
1922	BUF_UNLOCK(bpa);
1923	return (match);
1924}
1925
1926/*
1927 *	vfs_bio_awrite:
1928 *
1929 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1930 *	This is much better then the old way of writing only one buffer at
1931 *	a time.  Note that we may not be presented with the buffers in the
1932 *	correct order, so we search for the cluster in both directions.
1933 */
1934int
1935vfs_bio_awrite(struct buf *bp)
1936{
1937	struct bufobj *bo;
1938	int i;
1939	int j;
1940	daddr_t lblkno = bp->b_lblkno;
1941	struct vnode *vp = bp->b_vp;
1942	int ncl;
1943	int nwritten;
1944	int size;
1945	int maxcl;
1946	int gbflags;
1947
1948	bo = &vp->v_bufobj;
1949	gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1950	/*
1951	 * right now we support clustered writing only to regular files.  If
1952	 * we find a clusterable block we could be in the middle of a cluster
1953	 * rather then at the beginning.
1954	 */
1955	if ((vp->v_type == VREG) &&
1956	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1957	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1958
1959		size = vp->v_mount->mnt_stat.f_iosize;
1960		maxcl = MAXPHYS / size;
1961
1962		BO_RLOCK(bo);
1963		for (i = 1; i < maxcl; i++)
1964			if (vfs_bio_clcheck(vp, size, lblkno + i,
1965			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1966				break;
1967
1968		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1969			if (vfs_bio_clcheck(vp, size, lblkno - j,
1970			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1971				break;
1972		BO_RUNLOCK(bo);
1973		--j;
1974		ncl = i + j;
1975		/*
1976		 * this is a possible cluster write
1977		 */
1978		if (ncl != 1) {
1979			BUF_UNLOCK(bp);
1980			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
1981			    gbflags);
1982			return (nwritten);
1983		}
1984	}
1985	bremfree(bp);
1986	bp->b_flags |= B_ASYNC;
1987	/*
1988	 * default (old) behavior, writing out only one block
1989	 *
1990	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1991	 */
1992	nwritten = bp->b_bufsize;
1993	(void) bwrite(bp);
1994
1995	return (nwritten);
1996}
1997
1998static void
1999setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
2000{
2001
2002	KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2003	    bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
2004	if ((gbflags & GB_UNMAPPED) == 0) {
2005		bp->b_kvabase = (caddr_t)addr;
2006	} else if ((gbflags & GB_KVAALLOC) != 0) {
2007		KASSERT((gbflags & GB_UNMAPPED) != 0,
2008		    ("GB_KVAALLOC without GB_UNMAPPED"));
2009		bp->b_kvaalloc = (caddr_t)addr;
2010		bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2011		atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2012	}
2013	bp->b_kvasize = maxsize;
2014}
2015
2016/*
2017 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2018 * needed.
2019 */
2020static int
2021allocbufkva(struct buf *bp, int maxsize, int gbflags)
2022{
2023	vm_offset_t addr;
2024
2025	bfreekva(bp);
2026	addr = 0;
2027
2028	if (vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr)) {
2029		/*
2030		 * Buffer map is too fragmented.  Request the caller
2031		 * to defragment the map.
2032		 */
2033		atomic_add_int(&bufdefragcnt, 1);
2034		return (1);
2035	}
2036	setbufkva(bp, addr, maxsize, gbflags);
2037	atomic_add_long(&bufspace, bp->b_kvasize);
2038	return (0);
2039}
2040
2041/*
2042 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2043 * locked vnode is supplied.
2044 */
2045static void
2046getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2047    int defrag)
2048{
2049	struct thread *td;
2050	char *waitmsg;
2051	int cnt, error, flags, norunbuf, wait;
2052
2053	mtx_assert(&bqclean, MA_OWNED);
2054
2055	if (defrag) {
2056		flags = VFS_BIO_NEED_BUFSPACE;
2057		waitmsg = "nbufkv";
2058	} else if (bufspace >= hibufspace) {
2059		waitmsg = "nbufbs";
2060		flags = VFS_BIO_NEED_BUFSPACE;
2061	} else {
2062		waitmsg = "newbuf";
2063		flags = VFS_BIO_NEED_ANY;
2064	}
2065	mtx_lock(&nblock);
2066	needsbuffer |= flags;
2067	mtx_unlock(&nblock);
2068	mtx_unlock(&bqclean);
2069
2070	bd_speedup();	/* heeeelp */
2071	if ((gbflags & GB_NOWAIT_BD) != 0)
2072		return;
2073
2074	td = curthread;
2075	cnt = 0;
2076	wait = MNT_NOWAIT;
2077	mtx_lock(&nblock);
2078	while (needsbuffer & flags) {
2079		if (vp != NULL && vp->v_type != VCHR &&
2080		    (td->td_pflags & TDP_BUFNEED) == 0) {
2081			mtx_unlock(&nblock);
2082
2083			/*
2084			 * getblk() is called with a vnode locked, and
2085			 * some majority of the dirty buffers may as
2086			 * well belong to the vnode.  Flushing the
2087			 * buffers there would make a progress that
2088			 * cannot be achieved by the buf_daemon, that
2089			 * cannot lock the vnode.
2090			 */
2091			if (cnt++ > 2)
2092				wait = MNT_WAIT;
2093			ASSERT_VOP_LOCKED(vp, "bufd_helper");
2094			error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
2095			    vn_lock(vp, LK_TRYUPGRADE);
2096			if (error == 0) {
2097				/* play bufdaemon */
2098				norunbuf = curthread_pflags_set(TDP_BUFNEED |
2099				    TDP_NORUNNINGBUF);
2100				VOP_FSYNC(vp, wait, td);
2101				atomic_add_long(&notbufdflushes, 1);
2102				curthread_pflags_restore(norunbuf);
2103			}
2104			mtx_lock(&nblock);
2105			if ((needsbuffer & flags) == 0)
2106				break;
2107		}
2108		if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2109		    waitmsg, slptimeo))
2110			break;
2111	}
2112	mtx_unlock(&nblock);
2113}
2114
2115static void
2116getnewbuf_reuse_bp(struct buf *bp, int qindex)
2117{
2118
2119	CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2120	    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2121	     bp->b_kvasize, bp->b_bufsize, qindex);
2122	mtx_assert(&bqclean, MA_NOTOWNED);
2123
2124	/*
2125	 * Note: we no longer distinguish between VMIO and non-VMIO
2126	 * buffers.
2127	 */
2128	KASSERT((bp->b_flags & B_DELWRI) == 0,
2129	    ("delwri buffer %p found in queue %d", bp, qindex));
2130
2131	if (qindex == QUEUE_CLEAN) {
2132		if (bp->b_flags & B_VMIO) {
2133			bp->b_flags &= ~B_ASYNC;
2134			vfs_vmio_release(bp);
2135		}
2136		if (bp->b_vp != NULL)
2137			brelvp(bp);
2138	}
2139
2140	/*
2141	 * Get the rest of the buffer freed up.  b_kva* is still valid
2142	 * after this operation.
2143	 */
2144
2145	if (bp->b_rcred != NOCRED) {
2146		crfree(bp->b_rcred);
2147		bp->b_rcred = NOCRED;
2148	}
2149	if (bp->b_wcred != NOCRED) {
2150		crfree(bp->b_wcred);
2151		bp->b_wcred = NOCRED;
2152	}
2153	if (!LIST_EMPTY(&bp->b_dep))
2154		buf_deallocate(bp);
2155	if (bp->b_vflags & BV_BKGRDINPROG)
2156		panic("losing buffer 3");
2157	KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p.  qindex: %d",
2158	    bp, bp->b_vp, qindex));
2159	KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2160	    ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2161
2162	if (bp->b_bufsize)
2163		allocbuf(bp, 0);
2164
2165	bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2166	bp->b_ioflags = 0;
2167	bp->b_xflags = 0;
2168	KASSERT((bp->b_flags & B_INFREECNT) == 0,
2169	    ("buf %p still counted as free?", bp));
2170	bp->b_vflags = 0;
2171	bp->b_vp = NULL;
2172	bp->b_blkno = bp->b_lblkno = 0;
2173	bp->b_offset = NOOFFSET;
2174	bp->b_iodone = 0;
2175	bp->b_error = 0;
2176	bp->b_resid = 0;
2177	bp->b_bcount = 0;
2178	bp->b_npages = 0;
2179	bp->b_dirtyoff = bp->b_dirtyend = 0;
2180	bp->b_bufobj = NULL;
2181	bp->b_pin_count = 0;
2182	bp->b_fsprivate1 = NULL;
2183	bp->b_fsprivate2 = NULL;
2184	bp->b_fsprivate3 = NULL;
2185
2186	LIST_INIT(&bp->b_dep);
2187}
2188
2189static int flushingbufs;
2190
2191static struct buf *
2192getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2193{
2194	struct buf *bp, *nbp;
2195	int nqindex, qindex, pass;
2196
2197	KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2198
2199	pass = 1;
2200restart:
2201	atomic_add_int(&getnewbufrestarts, 1);
2202
2203	/*
2204	 * Setup for scan.  If we do not have enough free buffers,
2205	 * we setup a degenerate case that immediately fails.  Note
2206	 * that if we are specially marked process, we are allowed to
2207	 * dip into our reserves.
2208	 *
2209	 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2210	 * for the allocation of the mapped buffer.  For unmapped, the
2211	 * easiest is to start with EMPTY outright.
2212	 *
2213	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
2214	 * However, there are a number of cases (defragging, reusing, ...)
2215	 * where we cannot backup.
2216	 */
2217	nbp = NULL;
2218	mtx_lock(&bqclean);
2219	if (!defrag && unmapped) {
2220		nqindex = QUEUE_EMPTY;
2221		nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2222	}
2223	if (nbp == NULL) {
2224		nqindex = QUEUE_EMPTYKVA;
2225		nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2226	}
2227
2228	/*
2229	 * If no EMPTYKVA buffers and we are either defragging or
2230	 * reusing, locate a CLEAN buffer to free or reuse.  If
2231	 * bufspace useage is low skip this step so we can allocate a
2232	 * new buffer.
2233	 */
2234	if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2235		nqindex = QUEUE_CLEAN;
2236		nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2237	}
2238
2239	/*
2240	 * If we could not find or were not allowed to reuse a CLEAN
2241	 * buffer, check to see if it is ok to use an EMPTY buffer.
2242	 * We can only use an EMPTY buffer if allocating its KVA would
2243	 * not otherwise run us out of buffer space.  No KVA is needed
2244	 * for the unmapped allocation.
2245	 */
2246	if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2247	    metadata)) {
2248		nqindex = QUEUE_EMPTY;
2249		nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2250	}
2251
2252	/*
2253	 * All available buffers might be clean, retry ignoring the
2254	 * lobufspace as the last resort.
2255	 */
2256	if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2257		nqindex = QUEUE_CLEAN;
2258		nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2259	}
2260
2261	/*
2262	 * Run scan, possibly freeing data and/or kva mappings on the fly
2263	 * depending.
2264	 */
2265	while ((bp = nbp) != NULL) {
2266		qindex = nqindex;
2267
2268		/*
2269		 * Calculate next bp (we can only use it if we do not
2270		 * block or do other fancy things).
2271		 */
2272		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2273			switch (qindex) {
2274			case QUEUE_EMPTY:
2275				nqindex = QUEUE_EMPTYKVA;
2276				nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2277				if (nbp != NULL)
2278					break;
2279				/* FALLTHROUGH */
2280			case QUEUE_EMPTYKVA:
2281				nqindex = QUEUE_CLEAN;
2282				nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2283				if (nbp != NULL)
2284					break;
2285				/* FALLTHROUGH */
2286			case QUEUE_CLEAN:
2287				if (metadata && pass == 1) {
2288					pass = 2;
2289					nqindex = QUEUE_EMPTY;
2290					nbp = TAILQ_FIRST(
2291					    &bufqueues[QUEUE_EMPTY]);
2292				}
2293				/*
2294				 * nbp is NULL.
2295				 */
2296				break;
2297			}
2298		}
2299		/*
2300		 * If we are defragging then we need a buffer with
2301		 * b_kvasize != 0.  XXX this situation should no longer
2302		 * occur, if defrag is non-zero the buffer's b_kvasize
2303		 * should also be non-zero at this point.  XXX
2304		 */
2305		if (defrag && bp->b_kvasize == 0) {
2306			printf("Warning: defrag empty buffer %p\n", bp);
2307			continue;
2308		}
2309
2310		/*
2311		 * Start freeing the bp.  This is somewhat involved.  nbp
2312		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2313		 */
2314		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2315			continue;
2316		/*
2317		 * BKGRDINPROG can only be set with the buf and bufobj
2318		 * locks both held.  We tolerate a race to clear it here.
2319		 */
2320		if (bp->b_vflags & BV_BKGRDINPROG) {
2321			BUF_UNLOCK(bp);
2322			continue;
2323		}
2324
2325		KASSERT(bp->b_qindex == qindex,
2326		    ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2327
2328		bremfreel(bp);
2329		mtx_unlock(&bqclean);
2330		/*
2331		 * NOTE:  nbp is now entirely invalid.  We can only restart
2332		 * the scan from this point on.
2333		 */
2334
2335		getnewbuf_reuse_bp(bp, qindex);
2336		mtx_assert(&bqclean, MA_NOTOWNED);
2337
2338		/*
2339		 * If we are defragging then free the buffer.
2340		 */
2341		if (defrag) {
2342			bp->b_flags |= B_INVAL;
2343			bfreekva(bp);
2344			brelse(bp);
2345			defrag = 0;
2346			goto restart;
2347		}
2348
2349		/*
2350		 * Notify any waiters for the buffer lock about
2351		 * identity change by freeing the buffer.
2352		 */
2353		if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2354			bp->b_flags |= B_INVAL;
2355			bfreekva(bp);
2356			brelse(bp);
2357			goto restart;
2358		}
2359
2360		if (metadata)
2361			break;
2362
2363		/*
2364		 * If we are overcomitted then recover the buffer and its
2365		 * KVM space.  This occurs in rare situations when multiple
2366		 * processes are blocked in getnewbuf() or allocbuf().
2367		 */
2368		if (bufspace >= hibufspace)
2369			flushingbufs = 1;
2370		if (flushingbufs && bp->b_kvasize != 0) {
2371			bp->b_flags |= B_INVAL;
2372			bfreekva(bp);
2373			brelse(bp);
2374			goto restart;
2375		}
2376		if (bufspace < lobufspace)
2377			flushingbufs = 0;
2378		break;
2379	}
2380	return (bp);
2381}
2382
2383/*
2384 *	getnewbuf:
2385 *
2386 *	Find and initialize a new buffer header, freeing up existing buffers
2387 *	in the bufqueues as necessary.  The new buffer is returned locked.
2388 *
2389 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
2390 *	buffer away, the caller must set B_INVAL prior to calling brelse().
2391 *
2392 *	We block if:
2393 *		We have insufficient buffer headers
2394 *		We have insufficient buffer space
2395 *		buffer_arena is too fragmented ( space reservation fails )
2396 *		If we have to flush dirty buffers ( but we try to avoid this )
2397 */
2398static struct buf *
2399getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2400    int gbflags)
2401{
2402	struct buf *bp;
2403	int defrag, metadata;
2404
2405	KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2406	    ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2407	if (!unmapped_buf_allowed)
2408		gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2409
2410	defrag = 0;
2411	if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2412	    vp->v_type == VCHR)
2413		metadata = 1;
2414	else
2415		metadata = 0;
2416	/*
2417	 * We can't afford to block since we might be holding a vnode lock,
2418	 * which may prevent system daemons from running.  We deal with
2419	 * low-memory situations by proactively returning memory and running
2420	 * async I/O rather then sync I/O.
2421	 */
2422	atomic_add_int(&getnewbufcalls, 1);
2423	atomic_subtract_int(&getnewbufrestarts, 1);
2424restart:
2425	bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2426	    GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2427	if (bp != NULL)
2428		defrag = 0;
2429
2430	/*
2431	 * If we exhausted our list, sleep as appropriate.  We may have to
2432	 * wakeup various daemons and write out some dirty buffers.
2433	 *
2434	 * Generally we are sleeping due to insufficient buffer space.
2435	 */
2436	if (bp == NULL) {
2437		mtx_assert(&bqclean, MA_OWNED);
2438		getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2439		mtx_assert(&bqclean, MA_NOTOWNED);
2440	} else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2441		mtx_assert(&bqclean, MA_NOTOWNED);
2442
2443		bfreekva(bp);
2444		bp->b_flags |= B_UNMAPPED;
2445		bp->b_kvabase = bp->b_data = unmapped_buf;
2446		bp->b_kvasize = maxsize;
2447		atomic_add_long(&bufspace, bp->b_kvasize);
2448		atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2449		atomic_add_int(&bufreusecnt, 1);
2450	} else {
2451		mtx_assert(&bqclean, MA_NOTOWNED);
2452
2453		/*
2454		 * We finally have a valid bp.  We aren't quite out of the
2455		 * woods, we still have to reserve kva space.  In order
2456		 * to keep fragmentation sane we only allocate kva in
2457		 * BKVASIZE chunks.
2458		 */
2459		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2460
2461		if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2462		    B_KVAALLOC)) == B_UNMAPPED) {
2463			if (allocbufkva(bp, maxsize, gbflags)) {
2464				defrag = 1;
2465				bp->b_flags |= B_INVAL;
2466				brelse(bp);
2467				goto restart;
2468			}
2469			atomic_add_int(&bufreusecnt, 1);
2470		} else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2471		    (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2472			/*
2473			 * If the reused buffer has KVA allocated,
2474			 * reassign b_kvaalloc to b_kvabase.
2475			 */
2476			bp->b_kvabase = bp->b_kvaalloc;
2477			bp->b_flags &= ~B_KVAALLOC;
2478			atomic_subtract_long(&unmapped_bufspace,
2479			    bp->b_kvasize);
2480			atomic_add_int(&bufreusecnt, 1);
2481		} else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2482		    (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2483		    GB_KVAALLOC)) {
2484			/*
2485			 * The case of reused buffer already have KVA
2486			 * mapped, but the request is for unmapped
2487			 * buffer with KVA allocated.
2488			 */
2489			bp->b_kvaalloc = bp->b_kvabase;
2490			bp->b_data = bp->b_kvabase = unmapped_buf;
2491			bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2492			atomic_add_long(&unmapped_bufspace,
2493			    bp->b_kvasize);
2494			atomic_add_int(&bufreusecnt, 1);
2495		}
2496		if ((gbflags & GB_UNMAPPED) == 0) {
2497			bp->b_saveaddr = bp->b_kvabase;
2498			bp->b_data = bp->b_saveaddr;
2499			bp->b_flags &= ~B_UNMAPPED;
2500			BUF_CHECK_MAPPED(bp);
2501		}
2502	}
2503	return (bp);
2504}
2505
2506/*
2507 *	buf_daemon:
2508 *
2509 *	buffer flushing daemon.  Buffers are normally flushed by the
2510 *	update daemon but if it cannot keep up this process starts to
2511 *	take the load in an attempt to prevent getnewbuf() from blocking.
2512 */
2513
2514static struct kproc_desc buf_kp = {
2515	"bufdaemon",
2516	buf_daemon,
2517	&bufdaemonproc
2518};
2519SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2520
2521static int
2522buf_flush(int target)
2523{
2524	int flushed;
2525
2526	flushed = flushbufqueues(target, 0);
2527	if (flushed == 0) {
2528		/*
2529		 * Could not find any buffers without rollback
2530		 * dependencies, so just write the first one
2531		 * in the hopes of eventually making progress.
2532		 */
2533		flushed = flushbufqueues(target, 1);
2534	}
2535	return (flushed);
2536}
2537
2538static void
2539buf_daemon()
2540{
2541	int lodirty;
2542
2543	/*
2544	 * This process needs to be suspended prior to shutdown sync.
2545	 */
2546	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2547	    SHUTDOWN_PRI_LAST);
2548
2549	/*
2550	 * This process is allowed to take the buffer cache to the limit
2551	 */
2552	curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2553	mtx_lock(&bdlock);
2554	for (;;) {
2555		bd_request = 0;
2556		mtx_unlock(&bdlock);
2557
2558		kproc_suspend_check(bufdaemonproc);
2559		lodirty = lodirtybuffers;
2560		if (bd_speedupreq) {
2561			lodirty = numdirtybuffers / 2;
2562			bd_speedupreq = 0;
2563		}
2564		/*
2565		 * Do the flush.  Limit the amount of in-transit I/O we
2566		 * allow to build up, otherwise we would completely saturate
2567		 * the I/O system.
2568		 */
2569		while (numdirtybuffers > lodirty) {
2570			if (buf_flush(numdirtybuffers - lodirty) == 0)
2571				break;
2572			kern_yield(PRI_USER);
2573		}
2574
2575		/*
2576		 * Only clear bd_request if we have reached our low water
2577		 * mark.  The buf_daemon normally waits 1 second and
2578		 * then incrementally flushes any dirty buffers that have
2579		 * built up, within reason.
2580		 *
2581		 * If we were unable to hit our low water mark and couldn't
2582		 * find any flushable buffers, we sleep for a short period
2583		 * to avoid endless loops on unlockable buffers.
2584		 */
2585		mtx_lock(&bdlock);
2586		if (numdirtybuffers <= lodirtybuffers) {
2587			/*
2588			 * We reached our low water mark, reset the
2589			 * request and sleep until we are needed again.
2590			 * The sleep is just so the suspend code works.
2591			 */
2592			bd_request = 0;
2593			/*
2594			 * Do an extra wakeup in case dirty threshold
2595			 * changed via sysctl and the explicit transition
2596			 * out of shortfall was missed.
2597			 */
2598			bdirtywakeup();
2599			if (runningbufspace <= lorunningspace)
2600				runningwakeup();
2601			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2602		} else {
2603			/*
2604			 * We couldn't find any flushable dirty buffers but
2605			 * still have too many dirty buffers, we
2606			 * have to sleep and try again.  (rare)
2607			 */
2608			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2609		}
2610	}
2611}
2612
2613/*
2614 *	flushbufqueues:
2615 *
2616 *	Try to flush a buffer in the dirty queue.  We must be careful to
2617 *	free up B_INVAL buffers instead of write them, which NFS is
2618 *	particularly sensitive to.
2619 */
2620static int flushwithdeps = 0;
2621SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2622    0, "Number of buffers flushed with dependecies that require rollbacks");
2623
2624static int
2625flushbufqueues(int target, int flushdeps)
2626{
2627	struct buf *sentinel;
2628	struct vnode *vp;
2629	struct mount *mp;
2630	struct buf *bp;
2631	int hasdeps;
2632	int flushed;
2633	int queue;
2634	int error;
2635
2636	flushed = 0;
2637	queue = QUEUE_DIRTY;
2638	bp = NULL;
2639	sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2640	sentinel->b_qindex = QUEUE_SENTINEL;
2641	mtx_lock(&bqdirty);
2642	TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2643	mtx_unlock(&bqdirty);
2644	while (flushed != target) {
2645		maybe_yield();
2646		mtx_lock(&bqdirty);
2647		bp = TAILQ_NEXT(sentinel, b_freelist);
2648		if (bp != NULL) {
2649			TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2650			TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2651			    b_freelist);
2652		} else {
2653			mtx_unlock(&bqdirty);
2654			break;
2655		}
2656		KASSERT(bp->b_qindex != QUEUE_SENTINEL,
2657		    ("parallel calls to flushbufqueues() bp %p", bp));
2658		error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
2659		mtx_unlock(&bqdirty);
2660		if (error != 0)
2661			continue;
2662		if (bp->b_pin_count > 0) {
2663			BUF_UNLOCK(bp);
2664			continue;
2665		}
2666		/*
2667		 * BKGRDINPROG can only be set with the buf and bufobj
2668		 * locks both held.  We tolerate a race to clear it here.
2669		 */
2670		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2671		    (bp->b_flags & B_DELWRI) == 0) {
2672			BUF_UNLOCK(bp);
2673			continue;
2674		}
2675		if (bp->b_flags & B_INVAL) {
2676			bremfreef(bp);
2677			brelse(bp);
2678			flushed++;
2679			continue;
2680		}
2681
2682		if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2683			if (flushdeps == 0) {
2684				BUF_UNLOCK(bp);
2685				continue;
2686			}
2687			hasdeps = 1;
2688		} else
2689			hasdeps = 0;
2690		/*
2691		 * We must hold the lock on a vnode before writing
2692		 * one of its buffers. Otherwise we may confuse, or
2693		 * in the case of a snapshot vnode, deadlock the
2694		 * system.
2695		 *
2696		 * The lock order here is the reverse of the normal
2697		 * of vnode followed by buf lock.  This is ok because
2698		 * the NOWAIT will prevent deadlock.
2699		 */
2700		vp = bp->b_vp;
2701		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2702			BUF_UNLOCK(bp);
2703			continue;
2704		}
2705		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
2706		if (error == 0) {
2707			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2708			    bp, bp->b_vp, bp->b_flags);
2709			vfs_bio_awrite(bp);
2710			vn_finished_write(mp);
2711			VOP_UNLOCK(vp, 0);
2712			flushwithdeps += hasdeps;
2713			flushed++;
2714			if (runningbufspace > hirunningspace)
2715				waitrunningbufspace();
2716			continue;
2717		}
2718		vn_finished_write(mp);
2719		BUF_UNLOCK(bp);
2720	}
2721	mtx_lock(&bqdirty);
2722	TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2723	mtx_unlock(&bqdirty);
2724	free(sentinel, M_TEMP);
2725	return (flushed);
2726}
2727
2728/*
2729 * Check to see if a block is currently memory resident.
2730 */
2731struct buf *
2732incore(struct bufobj *bo, daddr_t blkno)
2733{
2734	struct buf *bp;
2735
2736	BO_RLOCK(bo);
2737	bp = gbincore(bo, blkno);
2738	BO_RUNLOCK(bo);
2739	return (bp);
2740}
2741
2742/*
2743 * Returns true if no I/O is needed to access the
2744 * associated VM object.  This is like incore except
2745 * it also hunts around in the VM system for the data.
2746 */
2747
2748static int
2749inmem(struct vnode * vp, daddr_t blkno)
2750{
2751	vm_object_t obj;
2752	vm_offset_t toff, tinc, size;
2753	vm_page_t m;
2754	vm_ooffset_t off;
2755
2756	ASSERT_VOP_LOCKED(vp, "inmem");
2757
2758	if (incore(&vp->v_bufobj, blkno))
2759		return 1;
2760	if (vp->v_mount == NULL)
2761		return 0;
2762	obj = vp->v_object;
2763	if (obj == NULL)
2764		return (0);
2765
2766	size = PAGE_SIZE;
2767	if (size > vp->v_mount->mnt_stat.f_iosize)
2768		size = vp->v_mount->mnt_stat.f_iosize;
2769	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2770
2771	VM_OBJECT_RLOCK(obj);
2772	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2773		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2774		if (!m)
2775			goto notinmem;
2776		tinc = size;
2777		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2778			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2779		if (vm_page_is_valid(m,
2780		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2781			goto notinmem;
2782	}
2783	VM_OBJECT_RUNLOCK(obj);
2784	return 1;
2785
2786notinmem:
2787	VM_OBJECT_RUNLOCK(obj);
2788	return (0);
2789}
2790
2791/*
2792 * Set the dirty range for a buffer based on the status of the dirty
2793 * bits in the pages comprising the buffer.  The range is limited
2794 * to the size of the buffer.
2795 *
2796 * Tell the VM system that the pages associated with this buffer
2797 * are clean.  This is used for delayed writes where the data is
2798 * going to go to disk eventually without additional VM intevention.
2799 *
2800 * Note that while we only really need to clean through to b_bcount, we
2801 * just go ahead and clean through to b_bufsize.
2802 */
2803static void
2804vfs_clean_pages_dirty_buf(struct buf *bp)
2805{
2806	vm_ooffset_t foff, noff, eoff;
2807	vm_page_t m;
2808	int i;
2809
2810	if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2811		return;
2812
2813	foff = bp->b_offset;
2814	KASSERT(bp->b_offset != NOOFFSET,
2815	    ("vfs_clean_pages_dirty_buf: no buffer offset"));
2816
2817	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2818	vfs_drain_busy_pages(bp);
2819	vfs_setdirty_locked_object(bp);
2820	for (i = 0; i < bp->b_npages; i++) {
2821		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2822		eoff = noff;
2823		if (eoff > bp->b_offset + bp->b_bufsize)
2824			eoff = bp->b_offset + bp->b_bufsize;
2825		m = bp->b_pages[i];
2826		vfs_page_set_validclean(bp, foff, m);
2827		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2828		foff = noff;
2829	}
2830	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2831}
2832
2833static void
2834vfs_setdirty_locked_object(struct buf *bp)
2835{
2836	vm_object_t object;
2837	int i;
2838
2839	object = bp->b_bufobj->bo_object;
2840	VM_OBJECT_ASSERT_WLOCKED(object);
2841
2842	/*
2843	 * We qualify the scan for modified pages on whether the
2844	 * object has been flushed yet.
2845	 */
2846	if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2847		vm_offset_t boffset;
2848		vm_offset_t eoffset;
2849
2850		/*
2851		 * test the pages to see if they have been modified directly
2852		 * by users through the VM system.
2853		 */
2854		for (i = 0; i < bp->b_npages; i++)
2855			vm_page_test_dirty(bp->b_pages[i]);
2856
2857		/*
2858		 * Calculate the encompassing dirty range, boffset and eoffset,
2859		 * (eoffset - boffset) bytes.
2860		 */
2861
2862		for (i = 0; i < bp->b_npages; i++) {
2863			if (bp->b_pages[i]->dirty)
2864				break;
2865		}
2866		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2867
2868		for (i = bp->b_npages - 1; i >= 0; --i) {
2869			if (bp->b_pages[i]->dirty) {
2870				break;
2871			}
2872		}
2873		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2874
2875		/*
2876		 * Fit it to the buffer.
2877		 */
2878
2879		if (eoffset > bp->b_bcount)
2880			eoffset = bp->b_bcount;
2881
2882		/*
2883		 * If we have a good dirty range, merge with the existing
2884		 * dirty range.
2885		 */
2886
2887		if (boffset < eoffset) {
2888			if (bp->b_dirtyoff > boffset)
2889				bp->b_dirtyoff = boffset;
2890			if (bp->b_dirtyend < eoffset)
2891				bp->b_dirtyend = eoffset;
2892		}
2893	}
2894}
2895
2896/*
2897 * Allocate the KVA mapping for an existing buffer. It handles the
2898 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2899 * KVA which is not mapped (B_KVAALLOC).
2900 */
2901static void
2902bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2903{
2904	struct buf *scratch_bp;
2905	int bsize, maxsize, need_mapping, need_kva;
2906	off_t offset;
2907
2908	need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2909	    (gbflags & GB_UNMAPPED) == 0;
2910	need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2911	    (gbflags & GB_KVAALLOC) != 0;
2912	if (!need_mapping && !need_kva)
2913		return;
2914
2915	BUF_CHECK_UNMAPPED(bp);
2916
2917	if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2918		/*
2919		 * Buffer is not mapped, but the KVA was already
2920		 * reserved at the time of the instantiation.  Use the
2921		 * allocated space.
2922		 */
2923		bp->b_flags &= ~B_KVAALLOC;
2924		KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2925		bp->b_kvabase = bp->b_kvaalloc;
2926		atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2927		goto has_addr;
2928	}
2929
2930	/*
2931	 * Calculate the amount of the address space we would reserve
2932	 * if the buffer was mapped.
2933	 */
2934	bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2935	offset = blkno * bsize;
2936	maxsize = size + (offset & PAGE_MASK);
2937	maxsize = imax(maxsize, bsize);
2938
2939mapping_loop:
2940	if (allocbufkva(bp, maxsize, gbflags)) {
2941		/*
2942		 * Request defragmentation. getnewbuf() returns us the
2943		 * allocated space by the scratch buffer KVA.
2944		 */
2945		scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2946		    (GB_UNMAPPED | GB_KVAALLOC));
2947		if (scratch_bp == NULL) {
2948			if ((gbflags & GB_NOWAIT_BD) != 0) {
2949				/*
2950				 * XXXKIB: defragmentation cannot
2951				 * succeed, not sure what else to do.
2952				 */
2953				panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2954			}
2955			atomic_add_int(&mappingrestarts, 1);
2956			goto mapping_loop;
2957		}
2958		KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
2959		    ("scratch bp !B_KVAALLOC %p", scratch_bp));
2960		setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
2961		    scratch_bp->b_kvasize, gbflags);
2962
2963		/* Get rid of the scratch buffer. */
2964		scratch_bp->b_kvasize = 0;
2965		scratch_bp->b_flags |= B_INVAL;
2966		scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
2967		brelse(scratch_bp);
2968	}
2969	if (!need_mapping)
2970		return;
2971
2972has_addr:
2973	bp->b_saveaddr = bp->b_kvabase;
2974	bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
2975	bp->b_flags &= ~B_UNMAPPED;
2976	BUF_CHECK_MAPPED(bp);
2977	bpmap_qenter(bp);
2978}
2979
2980/*
2981 *	getblk:
2982 *
2983 *	Get a block given a specified block and offset into a file/device.
2984 *	The buffers B_DONE bit will be cleared on return, making it almost
2985 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2986 *	return.  The caller should clear B_INVAL prior to initiating a
2987 *	READ.
2988 *
2989 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2990 *	an existing buffer.
2991 *
2992 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2993 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2994 *	and then cleared based on the backing VM.  If the previous buffer is
2995 *	non-0-sized but invalid, B_CACHE will be cleared.
2996 *
2997 *	If getblk() must create a new buffer, the new buffer is returned with
2998 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2999 *	case it is returned with B_INVAL clear and B_CACHE set based on the
3000 *	backing VM.
3001 *
3002 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
3003 *	B_CACHE bit is clear.
3004 *
3005 *	What this means, basically, is that the caller should use B_CACHE to
3006 *	determine whether the buffer is fully valid or not and should clear
3007 *	B_INVAL prior to issuing a read.  If the caller intends to validate
3008 *	the buffer by loading its data area with something, the caller needs
3009 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
3010 *	the caller should set B_CACHE ( as an optimization ), else the caller
3011 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
3012 *	a write attempt or if it was a successfull read.  If the caller
3013 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3014 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
3015 */
3016struct buf *
3017getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3018    int flags)
3019{
3020	struct buf *bp;
3021	struct bufobj *bo;
3022	int bsize, error, maxsize, vmio;
3023	off_t offset;
3024
3025	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3026	KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3027	    ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3028	ASSERT_VOP_LOCKED(vp, "getblk");
3029	if (size > MAXBSIZE)
3030		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3031	if (!unmapped_buf_allowed)
3032		flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3033
3034	bo = &vp->v_bufobj;
3035loop:
3036	BO_RLOCK(bo);
3037	bp = gbincore(bo, blkno);
3038	if (bp != NULL) {
3039		int lockflags;
3040		/*
3041		 * Buffer is in-core.  If the buffer is not busy nor managed,
3042		 * it must be on a queue.
3043		 */
3044		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3045
3046		if (flags & GB_LOCK_NOWAIT)
3047			lockflags |= LK_NOWAIT;
3048
3049		error = BUF_TIMELOCK(bp, lockflags,
3050		    BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3051
3052		/*
3053		 * If we slept and got the lock we have to restart in case
3054		 * the buffer changed identities.
3055		 */
3056		if (error == ENOLCK)
3057			goto loop;
3058		/* We timed out or were interrupted. */
3059		else if (error)
3060			return (NULL);
3061		/* If recursed, assume caller knows the rules. */
3062		else if (BUF_LOCKRECURSED(bp))
3063			goto end;
3064
3065		/*
3066		 * The buffer is locked.  B_CACHE is cleared if the buffer is
3067		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
3068		 * and for a VMIO buffer B_CACHE is adjusted according to the
3069		 * backing VM cache.
3070		 */
3071		if (bp->b_flags & B_INVAL)
3072			bp->b_flags &= ~B_CACHE;
3073		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3074			bp->b_flags |= B_CACHE;
3075		if (bp->b_flags & B_MANAGED)
3076			MPASS(bp->b_qindex == QUEUE_NONE);
3077		else
3078			bremfree(bp);
3079
3080		/*
3081		 * check for size inconsistencies for non-VMIO case.
3082		 */
3083		if (bp->b_bcount != size) {
3084			if ((bp->b_flags & B_VMIO) == 0 ||
3085			    (size > bp->b_kvasize)) {
3086				if (bp->b_flags & B_DELWRI) {
3087					/*
3088					 * If buffer is pinned and caller does
3089					 * not want sleep  waiting for it to be
3090					 * unpinned, bail out
3091					 * */
3092					if (bp->b_pin_count > 0) {
3093						if (flags & GB_LOCK_NOWAIT) {
3094							bqrelse(bp);
3095							return (NULL);
3096						} else {
3097							bunpin_wait(bp);
3098						}
3099					}
3100					bp->b_flags |= B_NOCACHE;
3101					bwrite(bp);
3102				} else {
3103					if (LIST_EMPTY(&bp->b_dep)) {
3104						bp->b_flags |= B_RELBUF;
3105						brelse(bp);
3106					} else {
3107						bp->b_flags |= B_NOCACHE;
3108						bwrite(bp);
3109					}
3110				}
3111				goto loop;
3112			}
3113		}
3114
3115		/*
3116		 * Handle the case of unmapped buffer which should
3117		 * become mapped, or the buffer for which KVA
3118		 * reservation is requested.
3119		 */
3120		bp_unmapped_get_kva(bp, blkno, size, flags);
3121
3122		/*
3123		 * If the size is inconsistant in the VMIO case, we can resize
3124		 * the buffer.  This might lead to B_CACHE getting set or
3125		 * cleared.  If the size has not changed, B_CACHE remains
3126		 * unchanged from its previous state.
3127		 */
3128		if (bp->b_bcount != size)
3129			allocbuf(bp, size);
3130
3131		KASSERT(bp->b_offset != NOOFFSET,
3132		    ("getblk: no buffer offset"));
3133
3134		/*
3135		 * A buffer with B_DELWRI set and B_CACHE clear must
3136		 * be committed before we can return the buffer in
3137		 * order to prevent the caller from issuing a read
3138		 * ( due to B_CACHE not being set ) and overwriting
3139		 * it.
3140		 *
3141		 * Most callers, including NFS and FFS, need this to
3142		 * operate properly either because they assume they
3143		 * can issue a read if B_CACHE is not set, or because
3144		 * ( for example ) an uncached B_DELWRI might loop due
3145		 * to softupdates re-dirtying the buffer.  In the latter
3146		 * case, B_CACHE is set after the first write completes,
3147		 * preventing further loops.
3148		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
3149		 * above while extending the buffer, we cannot allow the
3150		 * buffer to remain with B_CACHE set after the write
3151		 * completes or it will represent a corrupt state.  To
3152		 * deal with this we set B_NOCACHE to scrap the buffer
3153		 * after the write.
3154		 *
3155		 * We might be able to do something fancy, like setting
3156		 * B_CACHE in bwrite() except if B_DELWRI is already set,
3157		 * so the below call doesn't set B_CACHE, but that gets real
3158		 * confusing.  This is much easier.
3159		 */
3160
3161		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3162			bp->b_flags |= B_NOCACHE;
3163			bwrite(bp);
3164			goto loop;
3165		}
3166		bp->b_flags &= ~B_DONE;
3167	} else {
3168		/*
3169		 * Buffer is not in-core, create new buffer.  The buffer
3170		 * returned by getnewbuf() is locked.  Note that the returned
3171		 * buffer is also considered valid (not marked B_INVAL).
3172		 */
3173		BO_RUNLOCK(bo);
3174		/*
3175		 * If the user does not want us to create the buffer, bail out
3176		 * here.
3177		 */
3178		if (flags & GB_NOCREAT)
3179			return NULL;
3180		if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3181			return NULL;
3182
3183		bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3184		offset = blkno * bsize;
3185		vmio = vp->v_object != NULL;
3186		if (vmio) {
3187			maxsize = size + (offset & PAGE_MASK);
3188		} else {
3189			maxsize = size;
3190			/* Do not allow non-VMIO notmapped buffers. */
3191			flags &= ~GB_UNMAPPED;
3192		}
3193		maxsize = imax(maxsize, bsize);
3194
3195		bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3196		if (bp == NULL) {
3197			if (slpflag || slptimeo)
3198				return NULL;
3199			goto loop;
3200		}
3201
3202		/*
3203		 * This code is used to make sure that a buffer is not
3204		 * created while the getnewbuf routine is blocked.
3205		 * This can be a problem whether the vnode is locked or not.
3206		 * If the buffer is created out from under us, we have to
3207		 * throw away the one we just created.
3208		 *
3209		 * Note: this must occur before we associate the buffer
3210		 * with the vp especially considering limitations in
3211		 * the splay tree implementation when dealing with duplicate
3212		 * lblkno's.
3213		 */
3214		BO_LOCK(bo);
3215		if (gbincore(bo, blkno)) {
3216			BO_UNLOCK(bo);
3217			bp->b_flags |= B_INVAL;
3218			brelse(bp);
3219			goto loop;
3220		}
3221
3222		/*
3223		 * Insert the buffer into the hash, so that it can
3224		 * be found by incore.
3225		 */
3226		bp->b_blkno = bp->b_lblkno = blkno;
3227		bp->b_offset = offset;
3228		bgetvp(vp, bp);
3229		BO_UNLOCK(bo);
3230
3231		/*
3232		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
3233		 * buffer size starts out as 0, B_CACHE will be set by
3234		 * allocbuf() for the VMIO case prior to it testing the
3235		 * backing store for validity.
3236		 */
3237
3238		if (vmio) {
3239			bp->b_flags |= B_VMIO;
3240			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3241			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3242			    bp, vp->v_object, bp->b_bufobj->bo_object));
3243		} else {
3244			bp->b_flags &= ~B_VMIO;
3245			KASSERT(bp->b_bufobj->bo_object == NULL,
3246			    ("ARGH! has b_bufobj->bo_object %p %p\n",
3247			    bp, bp->b_bufobj->bo_object));
3248			BUF_CHECK_MAPPED(bp);
3249		}
3250
3251		allocbuf(bp, size);
3252		bp->b_flags &= ~B_DONE;
3253	}
3254	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3255	BUF_ASSERT_HELD(bp);
3256end:
3257	KASSERT(bp->b_bufobj == bo,
3258	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3259	return (bp);
3260}
3261
3262/*
3263 * Get an empty, disassociated buffer of given size.  The buffer is initially
3264 * set to B_INVAL.
3265 */
3266struct buf *
3267geteblk(int size, int flags)
3268{
3269	struct buf *bp;
3270	int maxsize;
3271
3272	maxsize = (size + BKVAMASK) & ~BKVAMASK;
3273	while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3274		if ((flags & GB_NOWAIT_BD) &&
3275		    (curthread->td_pflags & TDP_BUFNEED) != 0)
3276			return (NULL);
3277	}
3278	allocbuf(bp, size);
3279	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
3280	BUF_ASSERT_HELD(bp);
3281	return (bp);
3282}
3283
3284
3285/*
3286 * This code constitutes the buffer memory from either anonymous system
3287 * memory (in the case of non-VMIO operations) or from an associated
3288 * VM object (in the case of VMIO operations).  This code is able to
3289 * resize a buffer up or down.
3290 *
3291 * Note that this code is tricky, and has many complications to resolve
3292 * deadlock or inconsistant data situations.  Tread lightly!!!
3293 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3294 * the caller.  Calling this code willy nilly can result in the loss of data.
3295 *
3296 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
3297 * B_CACHE for the non-VMIO case.
3298 */
3299
3300int
3301allocbuf(struct buf *bp, int size)
3302{
3303	int newbsize, mbsize;
3304	int i;
3305
3306	BUF_ASSERT_HELD(bp);
3307
3308	if (bp->b_kvasize < size)
3309		panic("allocbuf: buffer too small");
3310
3311	if ((bp->b_flags & B_VMIO) == 0) {
3312		caddr_t origbuf;
3313		int origbufsize;
3314		/*
3315		 * Just get anonymous memory from the kernel.  Don't
3316		 * mess with B_CACHE.
3317		 */
3318		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3319		if (bp->b_flags & B_MALLOC)
3320			newbsize = mbsize;
3321		else
3322			newbsize = round_page(size);
3323
3324		if (newbsize < bp->b_bufsize) {
3325			/*
3326			 * malloced buffers are not shrunk
3327			 */
3328			if (bp->b_flags & B_MALLOC) {
3329				if (newbsize) {
3330					bp->b_bcount = size;
3331				} else {
3332					free(bp->b_data, M_BIOBUF);
3333					if (bp->b_bufsize) {
3334						atomic_subtract_long(
3335						    &bufmallocspace,
3336						    bp->b_bufsize);
3337						bufspacewakeup();
3338						bp->b_bufsize = 0;
3339					}
3340					bp->b_saveaddr = bp->b_kvabase;
3341					bp->b_data = bp->b_saveaddr;
3342					bp->b_bcount = 0;
3343					bp->b_flags &= ~B_MALLOC;
3344				}
3345				return 1;
3346			}
3347			vm_hold_free_pages(bp, newbsize);
3348		} else if (newbsize > bp->b_bufsize) {
3349			/*
3350			 * We only use malloced memory on the first allocation.
3351			 * and revert to page-allocated memory when the buffer
3352			 * grows.
3353			 */
3354			/*
3355			 * There is a potential smp race here that could lead
3356			 * to bufmallocspace slightly passing the max.  It
3357			 * is probably extremely rare and not worth worrying
3358			 * over.
3359			 */
3360			if ( (bufmallocspace < maxbufmallocspace) &&
3361				(bp->b_bufsize == 0) &&
3362				(mbsize <= PAGE_SIZE/2)) {
3363
3364				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3365				bp->b_bufsize = mbsize;
3366				bp->b_bcount = size;
3367				bp->b_flags |= B_MALLOC;
3368				atomic_add_long(&bufmallocspace, mbsize);
3369				return 1;
3370			}
3371			origbuf = NULL;
3372			origbufsize = 0;
3373			/*
3374			 * If the buffer is growing on its other-than-first allocation,
3375			 * then we revert to the page-allocation scheme.
3376			 */
3377			if (bp->b_flags & B_MALLOC) {
3378				origbuf = bp->b_data;
3379				origbufsize = bp->b_bufsize;
3380				bp->b_data = bp->b_kvabase;
3381				if (bp->b_bufsize) {
3382					atomic_subtract_long(&bufmallocspace,
3383					    bp->b_bufsize);
3384					bufspacewakeup();
3385					bp->b_bufsize = 0;
3386				}
3387				bp->b_flags &= ~B_MALLOC;
3388				newbsize = round_page(newbsize);
3389			}
3390			vm_hold_load_pages(
3391			    bp,
3392			    (vm_offset_t) bp->b_data + bp->b_bufsize,
3393			    (vm_offset_t) bp->b_data + newbsize);
3394			if (origbuf) {
3395				bcopy(origbuf, bp->b_data, origbufsize);
3396				free(origbuf, M_BIOBUF);
3397			}
3398		}
3399	} else {
3400		int desiredpages;
3401
3402		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3403		desiredpages = (size == 0) ? 0 :
3404			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3405
3406		if (bp->b_flags & B_MALLOC)
3407			panic("allocbuf: VMIO buffer can't be malloced");
3408		/*
3409		 * Set B_CACHE initially if buffer is 0 length or will become
3410		 * 0-length.
3411		 */
3412		if (size == 0 || bp->b_bufsize == 0)
3413			bp->b_flags |= B_CACHE;
3414
3415		if (newbsize < bp->b_bufsize) {
3416			/*
3417			 * DEV_BSIZE aligned new buffer size is less then the
3418			 * DEV_BSIZE aligned existing buffer size.  Figure out
3419			 * if we have to remove any pages.
3420			 */
3421			if (desiredpages < bp->b_npages) {
3422				vm_page_t m;
3423
3424				if ((bp->b_flags & B_UNMAPPED) == 0) {
3425					BUF_CHECK_MAPPED(bp);
3426					pmap_qremove((vm_offset_t)trunc_page(
3427					    (vm_offset_t)bp->b_data) +
3428					    (desiredpages << PAGE_SHIFT),
3429					    (bp->b_npages - desiredpages));
3430				} else
3431					BUF_CHECK_UNMAPPED(bp);
3432				VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3433				for (i = desiredpages; i < bp->b_npages; i++) {
3434					/*
3435					 * the page is not freed here -- it
3436					 * is the responsibility of
3437					 * vnode_pager_setsize
3438					 */
3439					m = bp->b_pages[i];
3440					KASSERT(m != bogus_page,
3441					    ("allocbuf: bogus page found"));
3442					while (vm_page_sleep_if_busy(m,
3443					    "biodep"))
3444						continue;
3445
3446					bp->b_pages[i] = NULL;
3447					vm_page_lock(m);
3448					vm_page_unwire(m, 0);
3449					vm_page_unlock(m);
3450				}
3451				VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3452				bp->b_npages = desiredpages;
3453			}
3454		} else if (size > bp->b_bcount) {
3455			/*
3456			 * We are growing the buffer, possibly in a
3457			 * byte-granular fashion.
3458			 */
3459			vm_object_t obj;
3460			vm_offset_t toff;
3461			vm_offset_t tinc;
3462
3463			/*
3464			 * Step 1, bring in the VM pages from the object,
3465			 * allocating them if necessary.  We must clear
3466			 * B_CACHE if these pages are not valid for the
3467			 * range covered by the buffer.
3468			 */
3469
3470			obj = bp->b_bufobj->bo_object;
3471
3472			VM_OBJECT_WLOCK(obj);
3473			while (bp->b_npages < desiredpages) {
3474				vm_page_t m;
3475
3476				/*
3477				 * We must allocate system pages since blocking
3478				 * here could interfere with paging I/O, no
3479				 * matter which process we are.
3480				 *
3481				 * Only exclusive busy can be tested here.
3482				 * Blocking on shared busy might lead to
3483				 * deadlocks once allocbuf() is called after
3484				 * pages are vfs_busy_pages().
3485				 */
3486				m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3487				    bp->b_npages, VM_ALLOC_NOBUSY |
3488				    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3489				    VM_ALLOC_IGN_SBUSY |
3490				    VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3491				if (m->valid == 0)
3492					bp->b_flags &= ~B_CACHE;
3493				bp->b_pages[bp->b_npages] = m;
3494				++bp->b_npages;
3495			}
3496
3497			/*
3498			 * Step 2.  We've loaded the pages into the buffer,
3499			 * we have to figure out if we can still have B_CACHE
3500			 * set.  Note that B_CACHE is set according to the
3501			 * byte-granular range ( bcount and size ), new the
3502			 * aligned range ( newbsize ).
3503			 *
3504			 * The VM test is against m->valid, which is DEV_BSIZE
3505			 * aligned.  Needless to say, the validity of the data
3506			 * needs to also be DEV_BSIZE aligned.  Note that this
3507			 * fails with NFS if the server or some other client
3508			 * extends the file's EOF.  If our buffer is resized,
3509			 * B_CACHE may remain set! XXX
3510			 */
3511
3512			toff = bp->b_bcount;
3513			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3514
3515			while ((bp->b_flags & B_CACHE) && toff < size) {
3516				vm_pindex_t pi;
3517
3518				if (tinc > (size - toff))
3519					tinc = size - toff;
3520
3521				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3522				    PAGE_SHIFT;
3523
3524				vfs_buf_test_cache(
3525				    bp,
3526				    bp->b_offset,
3527				    toff,
3528				    tinc,
3529				    bp->b_pages[pi]
3530				);
3531				toff += tinc;
3532				tinc = PAGE_SIZE;
3533			}
3534			VM_OBJECT_WUNLOCK(obj);
3535
3536			/*
3537			 * Step 3, fixup the KVM pmap.
3538			 */
3539			if ((bp->b_flags & B_UNMAPPED) == 0)
3540				bpmap_qenter(bp);
3541			else
3542				BUF_CHECK_UNMAPPED(bp);
3543		}
3544	}
3545	if (newbsize < bp->b_bufsize)
3546		bufspacewakeup();
3547	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3548	bp->b_bcount = size;		/* requested buffer size	*/
3549	return 1;
3550}
3551
3552extern int inflight_transient_maps;
3553
3554void
3555biodone(struct bio *bp)
3556{
3557	struct mtx *mtxp;
3558	void (*done)(struct bio *);
3559	vm_offset_t start, end;
3560	int transient;
3561
3562	if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3563		start = trunc_page((vm_offset_t)bp->bio_data);
3564		end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3565		transient = 1;
3566	} else {
3567		transient = 0;
3568		start = end = 0;
3569	}
3570	done = bp->bio_done;
3571	if (done == NULL) {
3572		mtxp = mtx_pool_find(mtxpool_sleep, bp);
3573		mtx_lock(mtxp);
3574		bp->bio_flags |= BIO_DONE;
3575		wakeup(bp);
3576		mtx_unlock(mtxp);
3577	} else {
3578		bp->bio_flags |= BIO_DONE;
3579		done(bp);
3580	}
3581	if (transient) {
3582		pmap_qremove(start, OFF_TO_IDX(end - start));
3583		vmem_free(transient_arena, start, end - start);
3584		atomic_add_int(&inflight_transient_maps, -1);
3585	}
3586}
3587
3588/*
3589 * Wait for a BIO to finish.
3590 */
3591int
3592biowait(struct bio *bp, const char *wchan)
3593{
3594	struct mtx *mtxp;
3595
3596	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3597	mtx_lock(mtxp);
3598	while ((bp->bio_flags & BIO_DONE) == 0)
3599		msleep(bp, mtxp, PRIBIO, wchan, 0);
3600	mtx_unlock(mtxp);
3601	if (bp->bio_error != 0)
3602		return (bp->bio_error);
3603	if (!(bp->bio_flags & BIO_ERROR))
3604		return (0);
3605	return (EIO);
3606}
3607
3608void
3609biofinish(struct bio *bp, struct devstat *stat, int error)
3610{
3611
3612	if (error) {
3613		bp->bio_error = error;
3614		bp->bio_flags |= BIO_ERROR;
3615	}
3616	if (stat != NULL)
3617		devstat_end_transaction_bio(stat, bp);
3618	biodone(bp);
3619}
3620
3621/*
3622 *	bufwait:
3623 *
3624 *	Wait for buffer I/O completion, returning error status.  The buffer
3625 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3626 *	error and cleared.
3627 */
3628int
3629bufwait(struct buf *bp)
3630{
3631	if (bp->b_iocmd == BIO_READ)
3632		bwait(bp, PRIBIO, "biord");
3633	else
3634		bwait(bp, PRIBIO, "biowr");
3635	if (bp->b_flags & B_EINTR) {
3636		bp->b_flags &= ~B_EINTR;
3637		return (EINTR);
3638	}
3639	if (bp->b_ioflags & BIO_ERROR) {
3640		return (bp->b_error ? bp->b_error : EIO);
3641	} else {
3642		return (0);
3643	}
3644}
3645
3646 /*
3647  * Call back function from struct bio back up to struct buf.
3648  */
3649static void
3650bufdonebio(struct bio *bip)
3651{
3652	struct buf *bp;
3653
3654	bp = bip->bio_caller2;
3655	bp->b_resid = bp->b_bcount - bip->bio_completed;
3656	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3657	bp->b_ioflags = bip->bio_flags;
3658	bp->b_error = bip->bio_error;
3659	if (bp->b_error)
3660		bp->b_ioflags |= BIO_ERROR;
3661	bufdone(bp);
3662	g_destroy_bio(bip);
3663}
3664
3665void
3666dev_strategy(struct cdev *dev, struct buf *bp)
3667{
3668	struct cdevsw *csw;
3669	int ref;
3670
3671	KASSERT(dev->si_refcount > 0,
3672	    ("dev_strategy on un-referenced struct cdev *(%s) %p",
3673	    devtoname(dev), dev));
3674
3675	csw = dev_refthread(dev, &ref);
3676	dev_strategy_csw(dev, csw, bp);
3677	dev_relthread(dev, ref);
3678}
3679
3680void
3681dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3682{
3683	struct bio *bip;
3684
3685	KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3686	    ("b_iocmd botch"));
3687	KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3688	    dev->si_threadcount > 0,
3689	    ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3690	    dev));
3691	if (csw == NULL) {
3692		bp->b_error = ENXIO;
3693		bp->b_ioflags = BIO_ERROR;
3694		bufdone(bp);
3695		return;
3696	}
3697	for (;;) {
3698		bip = g_new_bio();
3699		if (bip != NULL)
3700			break;
3701		/* Try again later */
3702		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3703	}
3704	bip->bio_cmd = bp->b_iocmd;
3705	bip->bio_offset = bp->b_iooffset;
3706	bip->bio_length = bp->b_bcount;
3707	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3708	bdata2bio(bp, bip);
3709	bip->bio_done = bufdonebio;
3710	bip->bio_caller2 = bp;
3711	bip->bio_dev = dev;
3712	(*csw->d_strategy)(bip);
3713}
3714
3715/*
3716 *	bufdone:
3717 *
3718 *	Finish I/O on a buffer, optionally calling a completion function.
3719 *	This is usually called from an interrupt so process blocking is
3720 *	not allowed.
3721 *
3722 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3723 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3724 *	assuming B_INVAL is clear.
3725 *
3726 *	For the VMIO case, we set B_CACHE if the op was a read and no
3727 *	read error occured, or if the op was a write.  B_CACHE is never
3728 *	set if the buffer is invalid or otherwise uncacheable.
3729 *
3730 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3731 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3732 *	in the biodone routine.
3733 */
3734void
3735bufdone(struct buf *bp)
3736{
3737	struct bufobj *dropobj;
3738	void    (*biodone)(struct buf *);
3739
3740	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3741	dropobj = NULL;
3742
3743	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3744	BUF_ASSERT_HELD(bp);
3745
3746	runningbufwakeup(bp);
3747	if (bp->b_iocmd == BIO_WRITE)
3748		dropobj = bp->b_bufobj;
3749	/* call optional completion function if requested */
3750	if (bp->b_iodone != NULL) {
3751		biodone = bp->b_iodone;
3752		bp->b_iodone = NULL;
3753		(*biodone) (bp);
3754		if (dropobj)
3755			bufobj_wdrop(dropobj);
3756		return;
3757	}
3758
3759	bufdone_finish(bp);
3760
3761	if (dropobj)
3762		bufobj_wdrop(dropobj);
3763}
3764
3765void
3766bufdone_finish(struct buf *bp)
3767{
3768	BUF_ASSERT_HELD(bp);
3769
3770	if (!LIST_EMPTY(&bp->b_dep))
3771		buf_complete(bp);
3772
3773	if (bp->b_flags & B_VMIO) {
3774		vm_ooffset_t foff;
3775		vm_page_t m;
3776		vm_object_t obj;
3777		struct vnode *vp;
3778		int bogus, i, iosize;
3779
3780		obj = bp->b_bufobj->bo_object;
3781		KASSERT(obj->paging_in_progress >= bp->b_npages,
3782		    ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3783		    obj->paging_in_progress, bp->b_npages));
3784
3785		vp = bp->b_vp;
3786		KASSERT(vp->v_holdcnt > 0,
3787		    ("biodone_finish: vnode %p has zero hold count", vp));
3788		KASSERT(vp->v_object != NULL,
3789		    ("biodone_finish: vnode %p has no vm_object", vp));
3790
3791		foff = bp->b_offset;
3792		KASSERT(bp->b_offset != NOOFFSET,
3793		    ("biodone_finish: bp %p has no buffer offset", bp));
3794
3795		/*
3796		 * Set B_CACHE if the op was a normal read and no error
3797		 * occured.  B_CACHE is set for writes in the b*write()
3798		 * routines.
3799		 */
3800		iosize = bp->b_bcount - bp->b_resid;
3801		if (bp->b_iocmd == BIO_READ &&
3802		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3803		    !(bp->b_ioflags & BIO_ERROR)) {
3804			bp->b_flags |= B_CACHE;
3805		}
3806		bogus = 0;
3807		VM_OBJECT_WLOCK(obj);
3808		for (i = 0; i < bp->b_npages; i++) {
3809			int bogusflag = 0;
3810			int resid;
3811
3812			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3813			if (resid > iosize)
3814				resid = iosize;
3815
3816			/*
3817			 * cleanup bogus pages, restoring the originals
3818			 */
3819			m = bp->b_pages[i];
3820			if (m == bogus_page) {
3821				bogus = bogusflag = 1;
3822				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3823				if (m == NULL)
3824					panic("biodone: page disappeared!");
3825				bp->b_pages[i] = m;
3826			}
3827			KASSERT(OFF_TO_IDX(foff) == m->pindex,
3828			    ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3829			    (intmax_t)foff, (uintmax_t)m->pindex));
3830
3831			/*
3832			 * In the write case, the valid and clean bits are
3833			 * already changed correctly ( see bdwrite() ), so we
3834			 * only need to do this here in the read case.
3835			 */
3836			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3837				KASSERT((m->dirty & vm_page_bits(foff &
3838				    PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3839				    " page %p has unexpected dirty bits", m));
3840				vfs_page_set_valid(bp, foff, m);
3841			}
3842
3843			vm_page_sunbusy(m);
3844			vm_object_pip_subtract(obj, 1);
3845			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3846			iosize -= resid;
3847		}
3848		vm_object_pip_wakeupn(obj, 0);
3849		VM_OBJECT_WUNLOCK(obj);
3850		if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3851			BUF_CHECK_MAPPED(bp);
3852			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3853			    bp->b_pages, bp->b_npages);
3854		}
3855	}
3856
3857	/*
3858	 * For asynchronous completions, release the buffer now. The brelse
3859	 * will do a wakeup there if necessary - so no need to do a wakeup
3860	 * here in the async case. The sync case always needs to do a wakeup.
3861	 */
3862
3863	if (bp->b_flags & B_ASYNC) {
3864		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3865			brelse(bp);
3866		else
3867			bqrelse(bp);
3868	} else
3869		bdone(bp);
3870}
3871
3872/*
3873 * This routine is called in lieu of iodone in the case of
3874 * incomplete I/O.  This keeps the busy status for pages
3875 * consistant.
3876 */
3877void
3878vfs_unbusy_pages(struct buf *bp)
3879{
3880	int i;
3881	vm_object_t obj;
3882	vm_page_t m;
3883
3884	runningbufwakeup(bp);
3885	if (!(bp->b_flags & B_VMIO))
3886		return;
3887
3888	obj = bp->b_bufobj->bo_object;
3889	VM_OBJECT_WLOCK(obj);
3890	for (i = 0; i < bp->b_npages; i++) {
3891		m = bp->b_pages[i];
3892		if (m == bogus_page) {
3893			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3894			if (!m)
3895				panic("vfs_unbusy_pages: page missing\n");
3896			bp->b_pages[i] = m;
3897			if ((bp->b_flags & B_UNMAPPED) == 0) {
3898				BUF_CHECK_MAPPED(bp);
3899				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3900				    bp->b_pages, bp->b_npages);
3901			} else
3902				BUF_CHECK_UNMAPPED(bp);
3903		}
3904		vm_object_pip_subtract(obj, 1);
3905		vm_page_sunbusy(m);
3906	}
3907	vm_object_pip_wakeupn(obj, 0);
3908	VM_OBJECT_WUNLOCK(obj);
3909}
3910
3911/*
3912 * vfs_page_set_valid:
3913 *
3914 *	Set the valid bits in a page based on the supplied offset.   The
3915 *	range is restricted to the buffer's size.
3916 *
3917 *	This routine is typically called after a read completes.
3918 */
3919static void
3920vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3921{
3922	vm_ooffset_t eoff;
3923
3924	/*
3925	 * Compute the end offset, eoff, such that [off, eoff) does not span a
3926	 * page boundary and eoff is not greater than the end of the buffer.
3927	 * The end of the buffer, in this case, is our file EOF, not the
3928	 * allocation size of the buffer.
3929	 */
3930	eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3931	if (eoff > bp->b_offset + bp->b_bcount)
3932		eoff = bp->b_offset + bp->b_bcount;
3933
3934	/*
3935	 * Set valid range.  This is typically the entire buffer and thus the
3936	 * entire page.
3937	 */
3938	if (eoff > off)
3939		vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3940}
3941
3942/*
3943 * vfs_page_set_validclean:
3944 *
3945 *	Set the valid bits and clear the dirty bits in a page based on the
3946 *	supplied offset.   The range is restricted to the buffer's size.
3947 */
3948static void
3949vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3950{
3951	vm_ooffset_t soff, eoff;
3952
3953	/*
3954	 * Start and end offsets in buffer.  eoff - soff may not cross a
3955	 * page boundry or cross the end of the buffer.  The end of the
3956	 * buffer, in this case, is our file EOF, not the allocation size
3957	 * of the buffer.
3958	 */
3959	soff = off;
3960	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3961	if (eoff > bp->b_offset + bp->b_bcount)
3962		eoff = bp->b_offset + bp->b_bcount;
3963
3964	/*
3965	 * Set valid range.  This is typically the entire buffer and thus the
3966	 * entire page.
3967	 */
3968	if (eoff > soff) {
3969		vm_page_set_validclean(
3970		    m,
3971		   (vm_offset_t) (soff & PAGE_MASK),
3972		   (vm_offset_t) (eoff - soff)
3973		);
3974	}
3975}
3976
3977/*
3978 * Ensure that all buffer pages are not exclusive busied.  If any page is
3979 * exclusive busy, drain it.
3980 */
3981void
3982vfs_drain_busy_pages(struct buf *bp)
3983{
3984	vm_page_t m;
3985	int i, last_busied;
3986
3987	VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
3988	last_busied = 0;
3989	for (i = 0; i < bp->b_npages; i++) {
3990		m = bp->b_pages[i];
3991		if (vm_page_xbusied(m)) {
3992			for (; last_busied < i; last_busied++)
3993				vm_page_sbusy(bp->b_pages[last_busied]);
3994			while (vm_page_xbusied(m)) {
3995				vm_page_lock(m);
3996				VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3997				vm_page_busy_sleep(m, "vbpage");
3998				VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3999			}
4000		}
4001	}
4002	for (i = 0; i < last_busied; i++)
4003		vm_page_sunbusy(bp->b_pages[i]);
4004}
4005
4006/*
4007 * This routine is called before a device strategy routine.
4008 * It is used to tell the VM system that paging I/O is in
4009 * progress, and treat the pages associated with the buffer
4010 * almost as being exclusive busy.  Also the object paging_in_progress
4011 * flag is handled to make sure that the object doesn't become
4012 * inconsistant.
4013 *
4014 * Since I/O has not been initiated yet, certain buffer flags
4015 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4016 * and should be ignored.
4017 */
4018void
4019vfs_busy_pages(struct buf *bp, int clear_modify)
4020{
4021	int i, bogus;
4022	vm_object_t obj;
4023	vm_ooffset_t foff;
4024	vm_page_t m;
4025
4026	if (!(bp->b_flags & B_VMIO))
4027		return;
4028
4029	obj = bp->b_bufobj->bo_object;
4030	foff = bp->b_offset;
4031	KASSERT(bp->b_offset != NOOFFSET,
4032	    ("vfs_busy_pages: no buffer offset"));
4033	VM_OBJECT_WLOCK(obj);
4034	vfs_drain_busy_pages(bp);
4035	if (bp->b_bufsize != 0)
4036		vfs_setdirty_locked_object(bp);
4037	bogus = 0;
4038	for (i = 0; i < bp->b_npages; i++) {
4039		m = bp->b_pages[i];
4040
4041		if ((bp->b_flags & B_CLUSTER) == 0) {
4042			vm_object_pip_add(obj, 1);
4043			vm_page_sbusy(m);
4044		}
4045		/*
4046		 * When readying a buffer for a read ( i.e
4047		 * clear_modify == 0 ), it is important to do
4048		 * bogus_page replacement for valid pages in
4049		 * partially instantiated buffers.  Partially
4050		 * instantiated buffers can, in turn, occur when
4051		 * reconstituting a buffer from its VM backing store
4052		 * base.  We only have to do this if B_CACHE is
4053		 * clear ( which causes the I/O to occur in the
4054		 * first place ).  The replacement prevents the read
4055		 * I/O from overwriting potentially dirty VM-backed
4056		 * pages.  XXX bogus page replacement is, uh, bogus.
4057		 * It may not work properly with small-block devices.
4058		 * We need to find a better way.
4059		 */
4060		if (clear_modify) {
4061			pmap_remove_write(m);
4062			vfs_page_set_validclean(bp, foff, m);
4063		} else if (m->valid == VM_PAGE_BITS_ALL &&
4064		    (bp->b_flags & B_CACHE) == 0) {
4065			bp->b_pages[i] = bogus_page;
4066			bogus++;
4067		}
4068		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4069	}
4070	VM_OBJECT_WUNLOCK(obj);
4071	if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4072		BUF_CHECK_MAPPED(bp);
4073		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4074		    bp->b_pages, bp->b_npages);
4075	}
4076}
4077
4078/*
4079 *	vfs_bio_set_valid:
4080 *
4081 *	Set the range within the buffer to valid.  The range is
4082 *	relative to the beginning of the buffer, b_offset.  Note that
4083 *	b_offset itself may be offset from the beginning of the first
4084 *	page.
4085 */
4086void
4087vfs_bio_set_valid(struct buf *bp, int base, int size)
4088{
4089	int i, n;
4090	vm_page_t m;
4091
4092	if (!(bp->b_flags & B_VMIO))
4093		return;
4094
4095	/*
4096	 * Fixup base to be relative to beginning of first page.
4097	 * Set initial n to be the maximum number of bytes in the
4098	 * first page that can be validated.
4099	 */
4100	base += (bp->b_offset & PAGE_MASK);
4101	n = PAGE_SIZE - (base & PAGE_MASK);
4102
4103	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4104	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4105		m = bp->b_pages[i];
4106		if (n > size)
4107			n = size;
4108		vm_page_set_valid_range(m, base & PAGE_MASK, n);
4109		base += n;
4110		size -= n;
4111		n = PAGE_SIZE;
4112	}
4113	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4114}
4115
4116/*
4117 *	vfs_bio_clrbuf:
4118 *
4119 *	If the specified buffer is a non-VMIO buffer, clear the entire
4120 *	buffer.  If the specified buffer is a VMIO buffer, clear and
4121 *	validate only the previously invalid portions of the buffer.
4122 *	This routine essentially fakes an I/O, so we need to clear
4123 *	BIO_ERROR and B_INVAL.
4124 *
4125 *	Note that while we only theoretically need to clear through b_bcount,
4126 *	we go ahead and clear through b_bufsize.
4127 */
4128void
4129vfs_bio_clrbuf(struct buf *bp)
4130{
4131	int i, j, mask, sa, ea, slide;
4132
4133	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4134		clrbuf(bp);
4135		return;
4136	}
4137	bp->b_flags &= ~B_INVAL;
4138	bp->b_ioflags &= ~BIO_ERROR;
4139	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4140	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4141	    (bp->b_offset & PAGE_MASK) == 0) {
4142		if (bp->b_pages[0] == bogus_page)
4143			goto unlock;
4144		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4145		VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4146		if ((bp->b_pages[0]->valid & mask) == mask)
4147			goto unlock;
4148		if ((bp->b_pages[0]->valid & mask) == 0) {
4149			pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4150			bp->b_pages[0]->valid |= mask;
4151			goto unlock;
4152		}
4153	}
4154	sa = bp->b_offset & PAGE_MASK;
4155	slide = 0;
4156	for (i = 0; i < bp->b_npages; i++, sa = 0) {
4157		slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4158		ea = slide & PAGE_MASK;
4159		if (ea == 0)
4160			ea = PAGE_SIZE;
4161		if (bp->b_pages[i] == bogus_page)
4162			continue;
4163		j = sa / DEV_BSIZE;
4164		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4165		VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4166		if ((bp->b_pages[i]->valid & mask) == mask)
4167			continue;
4168		if ((bp->b_pages[i]->valid & mask) == 0)
4169			pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4170		else {
4171			for (; sa < ea; sa += DEV_BSIZE, j++) {
4172				if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4173					pmap_zero_page_area(bp->b_pages[i],
4174					    sa, DEV_BSIZE);
4175				}
4176			}
4177		}
4178		bp->b_pages[i]->valid |= mask;
4179	}
4180unlock:
4181	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4182	bp->b_resid = 0;
4183}
4184
4185void
4186vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4187{
4188	vm_page_t m;
4189	int i, n;
4190
4191	if ((bp->b_flags & B_UNMAPPED) == 0) {
4192		BUF_CHECK_MAPPED(bp);
4193		bzero(bp->b_data + base, size);
4194	} else {
4195		BUF_CHECK_UNMAPPED(bp);
4196		n = PAGE_SIZE - (base & PAGE_MASK);
4197		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4198			m = bp->b_pages[i];
4199			if (n > size)
4200				n = size;
4201			pmap_zero_page_area(m, base & PAGE_MASK, n);
4202			base += n;
4203			size -= n;
4204			n = PAGE_SIZE;
4205		}
4206	}
4207}
4208
4209/*
4210 * vm_hold_load_pages and vm_hold_free_pages get pages into
4211 * a buffers address space.  The pages are anonymous and are
4212 * not associated with a file object.
4213 */
4214static void
4215vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4216{
4217	vm_offset_t pg;
4218	vm_page_t p;
4219	int index;
4220
4221	BUF_CHECK_MAPPED(bp);
4222
4223	to = round_page(to);
4224	from = round_page(from);
4225	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4226
4227	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4228tryagain:
4229		/*
4230		 * note: must allocate system pages since blocking here
4231		 * could interfere with paging I/O, no matter which
4232		 * process we are.
4233		 */
4234		p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4235		    VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4236		if (p == NULL) {
4237			VM_WAIT;
4238			goto tryagain;
4239		}
4240		pmap_qenter(pg, &p, 1);
4241		bp->b_pages[index] = p;
4242	}
4243	bp->b_npages = index;
4244}
4245
4246/* Return pages associated with this buf to the vm system */
4247static void
4248vm_hold_free_pages(struct buf *bp, int newbsize)
4249{
4250	vm_offset_t from;
4251	vm_page_t p;
4252	int index, newnpages;
4253
4254	BUF_CHECK_MAPPED(bp);
4255
4256	from = round_page((vm_offset_t)bp->b_data + newbsize);
4257	newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4258	if (bp->b_npages > newnpages)
4259		pmap_qremove(from, bp->b_npages - newnpages);
4260	for (index = newnpages; index < bp->b_npages; index++) {
4261		p = bp->b_pages[index];
4262		bp->b_pages[index] = NULL;
4263		if (vm_page_sbusied(p))
4264			printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4265			    (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4266		p->wire_count--;
4267		vm_page_free(p);
4268		atomic_subtract_int(&cnt.v_wire_count, 1);
4269	}
4270	bp->b_npages = newnpages;
4271}
4272
4273/*
4274 * Map an IO request into kernel virtual address space.
4275 *
4276 * All requests are (re)mapped into kernel VA space.
4277 * Notice that we use b_bufsize for the size of the buffer
4278 * to be mapped.  b_bcount might be modified by the driver.
4279 *
4280 * Note that even if the caller determines that the address space should
4281 * be valid, a race or a smaller-file mapped into a larger space may
4282 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4283 * check the return value.
4284 */
4285int
4286vmapbuf(struct buf *bp, int mapbuf)
4287{
4288	caddr_t kva;
4289	vm_prot_t prot;
4290	int pidx;
4291
4292	if (bp->b_bufsize < 0)
4293		return (-1);
4294	prot = VM_PROT_READ;
4295	if (bp->b_iocmd == BIO_READ)
4296		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
4297	if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4298	    (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4299	    btoc(MAXPHYS))) < 0)
4300		return (-1);
4301	bp->b_npages = pidx;
4302	if (mapbuf || !unmapped_buf_allowed) {
4303		pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4304		kva = bp->b_saveaddr;
4305		bp->b_saveaddr = bp->b_data;
4306		bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4307		bp->b_flags &= ~B_UNMAPPED;
4308	} else {
4309		bp->b_flags |= B_UNMAPPED;
4310		bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4311		bp->b_saveaddr = bp->b_data;
4312		bp->b_data = unmapped_buf;
4313	}
4314	return(0);
4315}
4316
4317/*
4318 * Free the io map PTEs associated with this IO operation.
4319 * We also invalidate the TLB entries and restore the original b_addr.
4320 */
4321void
4322vunmapbuf(struct buf *bp)
4323{
4324	int npages;
4325
4326	npages = bp->b_npages;
4327	if (bp->b_flags & B_UNMAPPED)
4328		bp->b_flags &= ~B_UNMAPPED;
4329	else
4330		pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4331	vm_page_unhold_pages(bp->b_pages, npages);
4332
4333	bp->b_data = bp->b_saveaddr;
4334}
4335
4336void
4337bdone(struct buf *bp)
4338{
4339	struct mtx *mtxp;
4340
4341	mtxp = mtx_pool_find(mtxpool_sleep, bp);
4342	mtx_lock(mtxp);
4343	bp->b_flags |= B_DONE;
4344	wakeup(bp);
4345	mtx_unlock(mtxp);
4346}
4347
4348void
4349bwait(struct buf *bp, u_char pri, const char *wchan)
4350{
4351	struct mtx *mtxp;
4352
4353	mtxp = mtx_pool_find(mtxpool_sleep, bp);
4354	mtx_lock(mtxp);
4355	while ((bp->b_flags & B_DONE) == 0)
4356		msleep(bp, mtxp, pri, wchan, 0);
4357	mtx_unlock(mtxp);
4358}
4359
4360int
4361bufsync(struct bufobj *bo, int waitfor)
4362{
4363
4364	return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4365}
4366
4367void
4368bufstrategy(struct bufobj *bo, struct buf *bp)
4369{
4370	int i = 0;
4371	struct vnode *vp;
4372
4373	vp = bp->b_vp;
4374	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4375	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4376	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4377	i = VOP_STRATEGY(vp, bp);
4378	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4379}
4380
4381void
4382bufobj_wrefl(struct bufobj *bo)
4383{
4384
4385	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4386	ASSERT_BO_WLOCKED(bo);
4387	bo->bo_numoutput++;
4388}
4389
4390void
4391bufobj_wref(struct bufobj *bo)
4392{
4393
4394	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4395	BO_LOCK(bo);
4396	bo->bo_numoutput++;
4397	BO_UNLOCK(bo);
4398}
4399
4400void
4401bufobj_wdrop(struct bufobj *bo)
4402{
4403
4404	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4405	BO_LOCK(bo);
4406	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4407	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4408		bo->bo_flag &= ~BO_WWAIT;
4409		wakeup(&bo->bo_numoutput);
4410	}
4411	BO_UNLOCK(bo);
4412}
4413
4414int
4415bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4416{
4417	int error;
4418
4419	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4420	ASSERT_BO_WLOCKED(bo);
4421	error = 0;
4422	while (bo->bo_numoutput) {
4423		bo->bo_flag |= BO_WWAIT;
4424		error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4425		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4426		if (error)
4427			break;
4428	}
4429	return (error);
4430}
4431
4432void
4433bpin(struct buf *bp)
4434{
4435	struct mtx *mtxp;
4436
4437	mtxp = mtx_pool_find(mtxpool_sleep, bp);
4438	mtx_lock(mtxp);
4439	bp->b_pin_count++;
4440	mtx_unlock(mtxp);
4441}
4442
4443void
4444bunpin(struct buf *bp)
4445{
4446	struct mtx *mtxp;
4447
4448	mtxp = mtx_pool_find(mtxpool_sleep, bp);
4449	mtx_lock(mtxp);
4450	if (--bp->b_pin_count == 0)
4451		wakeup(bp);
4452	mtx_unlock(mtxp);
4453}
4454
4455void
4456bunpin_wait(struct buf *bp)
4457{
4458	struct mtx *mtxp;
4459
4460	mtxp = mtx_pool_find(mtxpool_sleep, bp);
4461	mtx_lock(mtxp);
4462	while (bp->b_pin_count > 0)
4463		msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4464	mtx_unlock(mtxp);
4465}
4466
4467/*
4468 * Set bio_data or bio_ma for struct bio from the struct buf.
4469 */
4470void
4471bdata2bio(struct buf *bp, struct bio *bip)
4472{
4473
4474	if ((bp->b_flags & B_UNMAPPED) != 0) {
4475		KASSERT(unmapped_buf_allowed, ("unmapped"));
4476		bip->bio_ma = bp->b_pages;
4477		bip->bio_ma_n = bp->b_npages;
4478		bip->bio_data = unmapped_buf;
4479		bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4480		bip->bio_flags |= BIO_UNMAPPED;
4481		KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4482		    PAGE_SIZE == bp->b_npages,
4483		    ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4484		    (long long)bip->bio_length, bip->bio_ma_n));
4485	} else {
4486		bip->bio_data = bp->b_data;
4487		bip->bio_ma = NULL;
4488	}
4489}
4490
4491#include "opt_ddb.h"
4492#ifdef DDB
4493#include <ddb/ddb.h>
4494
4495/* DDB command to show buffer data */
4496DB_SHOW_COMMAND(buffer, db_show_buffer)
4497{
4498	/* get args */
4499	struct buf *bp = (struct buf *)addr;
4500
4501	if (!have_addr) {
4502		db_printf("usage: show buffer <addr>\n");
4503		return;
4504	}
4505
4506	db_printf("buf at %p\n", bp);
4507	db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4508	    (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4509	    PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4510	db_printf(
4511	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4512	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4513	    "b_dep = %p\n",
4514	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4515	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4516	    (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4517	if (bp->b_npages) {
4518		int i;
4519		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4520		for (i = 0; i < bp->b_npages; i++) {
4521			vm_page_t m;
4522			m = bp->b_pages[i];
4523			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4524			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4525			if ((i + 1) < bp->b_npages)
4526				db_printf(",");
4527		}
4528		db_printf("\n");
4529	}
4530	db_printf(" ");
4531	BUF_LOCKPRINTINFO(bp);
4532}
4533
4534DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4535{
4536	struct buf *bp;
4537	int i;
4538
4539	for (i = 0; i < nbuf; i++) {
4540		bp = &buf[i];
4541		if (BUF_ISLOCKED(bp)) {
4542			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4543			db_printf("\n");
4544		}
4545	}
4546}
4547
4548DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4549{
4550	struct vnode *vp;
4551	struct buf *bp;
4552
4553	if (!have_addr) {
4554		db_printf("usage: show vnodebufs <addr>\n");
4555		return;
4556	}
4557	vp = (struct vnode *)addr;
4558	db_printf("Clean buffers:\n");
4559	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4560		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4561		db_printf("\n");
4562	}
4563	db_printf("Dirty buffers:\n");
4564	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4565		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4566		db_printf("\n");
4567	}
4568}
4569
4570DB_COMMAND(countfreebufs, db_coundfreebufs)
4571{
4572	struct buf *bp;
4573	int i, used = 0, nfree = 0;
4574
4575	if (have_addr) {
4576		db_printf("usage: countfreebufs\n");
4577		return;
4578	}
4579
4580	for (i = 0; i < nbuf; i++) {
4581		bp = &buf[i];
4582		if ((bp->b_flags & B_INFREECNT) != 0)
4583			nfree++;
4584		else
4585			used++;
4586	}
4587
4588	db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4589	    nfree + used);
4590	db_printf("numfreebuffers is %d\n", numfreebuffers);
4591}
4592#endif /* DDB */
4593