Home | History | Annotate | Line # | Download | only in kern
vfs_bio.c revision 1.272
      1 /*	$NetBSD: vfs_bio.c,v 1.272 2017/04/05 20:15:49 jdolecek Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2007, 2008, 2009 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran, and by Wasabi Systems, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1982, 1986, 1989, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  * (c) UNIX System Laboratories, Inc.
     36  * All or some portions of this file are derived from material licensed
     37  * to the University of California by American Telephone and Telegraph
     38  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     39  * the permission of UNIX System Laboratories, Inc.
     40  *
     41  * Redistribution and use in source and binary forms, with or without
     42  * modification, are permitted provided that the following conditions
     43  * are met:
     44  * 1. Redistributions of source code must retain the above copyright
     45  *    notice, this list of conditions and the following disclaimer.
     46  * 2. Redistributions in binary form must reproduce the above copyright
     47  *    notice, this list of conditions and the following disclaimer in the
     48  *    documentation and/or other materials provided with the distribution.
     49  * 3. Neither the name of the University nor the names of its contributors
     50  *    may be used to endorse or promote products derived from this software
     51  *    without specific prior written permission.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  *
     65  *	@(#)vfs_bio.c	8.6 (Berkeley) 1/11/94
     66  */
     67 
     68 /*-
     69  * Copyright (c) 1994 Christopher G. Demetriou
     70  *
     71  * Redistribution and use in source and binary forms, with or without
     72  * modification, are permitted provided that the following conditions
     73  * are met:
     74  * 1. Redistributions of source code must retain the above copyright
     75  *    notice, this list of conditions and the following disclaimer.
     76  * 2. Redistributions in binary form must reproduce the above copyright
     77  *    notice, this list of conditions and the following disclaimer in the
     78  *    documentation and/or other materials provided with the distribution.
     79  * 3. All advertising materials mentioning features or use of this software
     80  *    must display the following acknowledgement:
     81  *	This product includes software developed by the University of
     82  *	California, Berkeley and its contributors.
     83  * 4. Neither the name of the University nor the names of its contributors
     84  *    may be used to endorse or promote products derived from this software
     85  *    without specific prior written permission.
     86  *
     87  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     88  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     89  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     90  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     91  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     92  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     93  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     94  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     95  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     96  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     97  * SUCH DAMAGE.
     98  *
     99  *	@(#)vfs_bio.c	8.6 (Berkeley) 1/11/94
    100  */
    101 
    102 /*
    103  * The buffer cache subsystem.
    104  *
    105  * Some references:
    106  *	Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
    107  *	Leffler, et al.: The Design and Implementation of the 4.3BSD
    108  *		UNIX Operating System (Addison Welley, 1989)
    109  *
    110  * Locking
    111  *
    112  * There are three locks:
    113  * - bufcache_lock: protects global buffer cache state.
    114  * - BC_BUSY: a long term per-buffer lock.
    115  * - buf_t::b_objlock: lock on completion (biowait vs biodone).
    116  *
    117  * For buffers associated with vnodes (a most common case) b_objlock points
    118  * to the vnode_t::v_interlock.  Otherwise, it points to generic buffer_lock.
    119  *
    120  * Lock order:
    121  *	bufcache_lock ->
    122  *		buf_t::b_objlock
    123  */
    124 
    125 #include <sys/cdefs.h>
    126 __KERNEL_RCSID(0, "$NetBSD: vfs_bio.c,v 1.272 2017/04/05 20:15:49 jdolecek Exp $");
    127 
    128 #ifdef _KERNEL_OPT
    129 #include "opt_bufcache.h"
    130 #include "opt_dtrace.h"
    131 #include "opt_biohist.h"
    132 #endif
    133 
    134 #include <sys/param.h>
    135 #include <sys/systm.h>
    136 #include <sys/kernel.h>
    137 #include <sys/proc.h>
    138 #include <sys/buf.h>
    139 #include <sys/vnode.h>
    140 #include <sys/mount.h>
    141 #include <sys/resourcevar.h>
    142 #include <sys/sysctl.h>
    143 #include <sys/conf.h>
    144 #include <sys/kauth.h>
    145 #include <sys/fstrans.h>
    146 #include <sys/intr.h>
    147 #include <sys/cpu.h>
    148 #include <sys/wapbl.h>
    149 #include <sys/bitops.h>
    150 #include <sys/cprng.h>
    151 #include <sys/sdt.h>
    152 
    153 #include <uvm/uvm.h>	/* extern struct uvm uvm */
    154 
    155 #include <miscfs/specfs/specdev.h>
    156 
    157 #ifndef	BUFPAGES
    158 # define BUFPAGES 0
    159 #endif
    160 
    161 #ifdef BUFCACHE
    162 # if (BUFCACHE < 5) || (BUFCACHE > 95)
    163 #  error BUFCACHE is not between 5 and 95
    164 # endif
    165 #else
    166 # define BUFCACHE 15
    167 #endif
    168 
    169 u_int	nbuf;			/* desired number of buffer headers */
    170 u_int	bufpages = BUFPAGES;	/* optional hardwired count */
    171 u_int	bufcache = BUFCACHE;	/* max % of RAM to use for buffer cache */
    172 
    173 /* Function prototypes */
    174 struct bqueue;
    175 
    176 static void buf_setwm(void);
    177 static int buf_trim(void);
    178 static void *bufpool_page_alloc(struct pool *, int);
    179 static void bufpool_page_free(struct pool *, void *);
    180 static buf_t *bio_doread(struct vnode *, daddr_t, int, int);
    181 static buf_t *getnewbuf(int, int, int);
    182 static int buf_lotsfree(void);
    183 static int buf_canrelease(void);
    184 static u_long buf_mempoolidx(u_long);
    185 static u_long buf_roundsize(u_long);
    186 static void *buf_alloc(size_t);
    187 static void buf_mrelease(void *, size_t);
    188 static void binsheadfree(buf_t *, struct bqueue *);
    189 static void binstailfree(buf_t *, struct bqueue *);
    190 #ifdef DEBUG
    191 static int checkfreelist(buf_t *, struct bqueue *, int);
    192 #endif
    193 static void biointr(void *);
    194 static void biodone2(buf_t *);
    195 static void bref(buf_t *);
    196 static void brele(buf_t *);
    197 static void sysctl_kern_buf_setup(void);
    198 static void sysctl_vm_buf_setup(void);
    199 
    200 /* Initialization for biohist */
    201 
    202 #include <sys/biohist.h>
    203 
    204 BIOHIST_DEFINE(biohist);
    205 
    206 void
    207 biohist_init(void)
    208 {
    209 
    210 	BIOHIST_INIT(biohist, BIOHIST_SIZE);
    211 }
    212 
    213 /*
    214  * Definitions for the buffer hash lists.
    215  */
    216 #define	BUFHASH(dvp, lbn)	\
    217 	(&bufhashtbl[(((long)(dvp) >> 8) + (int)(lbn)) & bufhash])
    218 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
    219 u_long	bufhash;
    220 struct bqueue bufqueues[BQUEUES];
    221 
    222 static kcondvar_t needbuffer_cv;
    223 
    224 /*
    225  * Buffer queue lock.
    226  */
    227 kmutex_t bufcache_lock;
    228 kmutex_t buffer_lock;
    229 
    230 /* Software ISR for completed transfers. */
    231 static void *biodone_sih;
    232 
    233 /* Buffer pool for I/O buffers. */
    234 static pool_cache_t buf_cache;
    235 static pool_cache_t bufio_cache;
    236 
    237 #define MEMPOOL_INDEX_OFFSET (ilog2(DEV_BSIZE))	/* smallest pool is 512 bytes */
    238 #define NMEMPOOLS (ilog2(MAXBSIZE) - MEMPOOL_INDEX_OFFSET + 1)
    239 __CTASSERT((1 << (NMEMPOOLS + MEMPOOL_INDEX_OFFSET - 1)) == MAXBSIZE);
    240 
    241 /* Buffer memory pools */
    242 static struct pool bmempools[NMEMPOOLS];
    243 
    244 static struct vm_map *buf_map;
    245 
    246 /*
    247  * Buffer memory pool allocator.
    248  */
    249 static void *
    250 bufpool_page_alloc(struct pool *pp, int flags)
    251 {
    252 
    253 	return (void *)uvm_km_alloc(buf_map,
    254 	    MAXBSIZE, MAXBSIZE,
    255 	    ((flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT|UVM_KMF_TRYLOCK)
    256 	    | UVM_KMF_WIRED);
    257 }
    258 
    259 static void
    260 bufpool_page_free(struct pool *pp, void *v)
    261 {
    262 
    263 	uvm_km_free(buf_map, (vaddr_t)v, MAXBSIZE, UVM_KMF_WIRED);
    264 }
    265 
    266 static struct pool_allocator bufmempool_allocator = {
    267 	.pa_alloc = bufpool_page_alloc,
    268 	.pa_free = bufpool_page_free,
    269 	.pa_pagesz = MAXBSIZE,
    270 };
    271 
    272 /* Buffer memory management variables */
    273 u_long bufmem_valimit;
    274 u_long bufmem_hiwater;
    275 u_long bufmem_lowater;
    276 u_long bufmem;
    277 
    278 /*
    279  * MD code can call this to set a hard limit on the amount
    280  * of virtual memory used by the buffer cache.
    281  */
    282 int
    283 buf_setvalimit(vsize_t sz)
    284 {
    285 
    286 	/* We need to accommodate at least NMEMPOOLS of MAXBSIZE each */
    287 	if (sz < NMEMPOOLS * MAXBSIZE)
    288 		return EINVAL;
    289 
    290 	bufmem_valimit = sz;
    291 	return 0;
    292 }
    293 
    294 static void
    295 buf_setwm(void)
    296 {
    297 
    298 	bufmem_hiwater = buf_memcalc();
    299 	/* lowater is approx. 2% of memory (with bufcache = 15) */
    300 #define	BUFMEM_WMSHIFT	3
    301 #define	BUFMEM_HIWMMIN	(64 * 1024 << BUFMEM_WMSHIFT)
    302 	if (bufmem_hiwater < BUFMEM_HIWMMIN)
    303 		/* Ensure a reasonable minimum value */
    304 		bufmem_hiwater = BUFMEM_HIWMMIN;
    305 	bufmem_lowater = bufmem_hiwater >> BUFMEM_WMSHIFT;
    306 }
    307 
    308 #ifdef DEBUG
    309 int debug_verify_freelist = 0;
    310 static int
    311 checkfreelist(buf_t *bp, struct bqueue *dp, int ison)
    312 {
    313 	buf_t *b;
    314 
    315 	if (!debug_verify_freelist)
    316 		return 1;
    317 
    318 	TAILQ_FOREACH(b, &dp->bq_queue, b_freelist) {
    319 		if (b == bp)
    320 			return ison ? 1 : 0;
    321 	}
    322 
    323 	return ison ? 0 : 1;
    324 }
    325 #endif
    326 
    327 /*
    328  * Insq/Remq for the buffer hash lists.
    329  * Call with buffer queue locked.
    330  */
    331 static void
    332 binsheadfree(buf_t *bp, struct bqueue *dp)
    333 {
    334 
    335 	KASSERT(mutex_owned(&bufcache_lock));
    336 	KASSERT(bp->b_freelistindex == -1);
    337 	TAILQ_INSERT_HEAD(&dp->bq_queue, bp, b_freelist);
    338 	dp->bq_bytes += bp->b_bufsize;
    339 	bp->b_freelistindex = dp - bufqueues;
    340 }
    341 
    342 static void
    343 binstailfree(buf_t *bp, struct bqueue *dp)
    344 {
    345 
    346 	KASSERT(mutex_owned(&bufcache_lock));
    347 	KASSERTMSG(bp->b_freelistindex == -1, "double free of buffer? "
    348 	    "bp=%p, b_freelistindex=%d\n", bp, bp->b_freelistindex);
    349 	TAILQ_INSERT_TAIL(&dp->bq_queue, bp, b_freelist);
    350 	dp->bq_bytes += bp->b_bufsize;
    351 	bp->b_freelistindex = dp - bufqueues;
    352 }
    353 
    354 void
    355 bremfree(buf_t *bp)
    356 {
    357 	struct bqueue *dp;
    358 	int bqidx = bp->b_freelistindex;
    359 
    360 	KASSERT(mutex_owned(&bufcache_lock));
    361 
    362 	KASSERT(bqidx != -1);
    363 	dp = &bufqueues[bqidx];
    364 	KDASSERT(checkfreelist(bp, dp, 1));
    365 	KASSERT(dp->bq_bytes >= bp->b_bufsize);
    366 	TAILQ_REMOVE(&dp->bq_queue, bp, b_freelist);
    367 	dp->bq_bytes -= bp->b_bufsize;
    368 
    369 	/* For the sysctl helper. */
    370 	if (bp == dp->bq_marker)
    371 		dp->bq_marker = NULL;
    372 
    373 #if defined(DIAGNOSTIC)
    374 	bp->b_freelistindex = -1;
    375 #endif /* defined(DIAGNOSTIC) */
    376 }
    377 
    378 /*
    379  * Add a reference to an buffer structure that came from buf_cache.
    380  */
    381 static inline void
    382 bref(buf_t *bp)
    383 {
    384 
    385 	KASSERT(mutex_owned(&bufcache_lock));
    386 	KASSERT(bp->b_refcnt > 0);
    387 
    388 	bp->b_refcnt++;
    389 }
    390 
    391 /*
    392  * Free an unused buffer structure that came from buf_cache.
    393  */
    394 static inline void
    395 brele(buf_t *bp)
    396 {
    397 
    398 	KASSERT(mutex_owned(&bufcache_lock));
    399 	KASSERT(bp->b_refcnt > 0);
    400 
    401 	if (bp->b_refcnt-- == 1) {
    402 		buf_destroy(bp);
    403 #ifdef DEBUG
    404 		memset((char *)bp, 0, sizeof(*bp));
    405 #endif
    406 		pool_cache_put(buf_cache, bp);
    407 	}
    408 }
    409 
    410 /*
    411  * note that for some ports this is used by pmap bootstrap code to
    412  * determine kva size.
    413  */
    414 u_long
    415 buf_memcalc(void)
    416 {
    417 	u_long n;
    418 	vsize_t mapsz = 0;
    419 
    420 	/*
    421 	 * Determine the upper bound of memory to use for buffers.
    422 	 *
    423 	 *	- If bufpages is specified, use that as the number
    424 	 *	  pages.
    425 	 *
    426 	 *	- Otherwise, use bufcache as the percentage of
    427 	 *	  physical memory.
    428 	 */
    429 	if (bufpages != 0) {
    430 		n = bufpages;
    431 	} else {
    432 		if (bufcache < 5) {
    433 			printf("forcing bufcache %d -> 5", bufcache);
    434 			bufcache = 5;
    435 		}
    436 		if (bufcache > 95) {
    437 			printf("forcing bufcache %d -> 95", bufcache);
    438 			bufcache = 95;
    439 		}
    440 		if (buf_map != NULL)
    441 			mapsz = vm_map_max(buf_map) - vm_map_min(buf_map);
    442 		n = calc_cache_size(mapsz, bufcache,
    443 		    (buf_map != kernel_map) ? 100 : BUFCACHE_VA_MAXPCT)
    444 		    / PAGE_SIZE;
    445 	}
    446 
    447 	n <<= PAGE_SHIFT;
    448 	if (bufmem_valimit != 0 && n > bufmem_valimit)
    449 		n = bufmem_valimit;
    450 
    451 	return (n);
    452 }
    453 
    454 /*
    455  * Initialize buffers and hash links for buffers.
    456  */
    457 void
    458 bufinit(void)
    459 {
    460 	struct bqueue *dp;
    461 	int use_std;
    462 	u_int i;
    463 
    464 	biodone_vfs = biodone;
    465 
    466 	mutex_init(&bufcache_lock, MUTEX_DEFAULT, IPL_NONE);
    467 	mutex_init(&buffer_lock, MUTEX_DEFAULT, IPL_NONE);
    468 	cv_init(&needbuffer_cv, "needbuf");
    469 
    470 	if (bufmem_valimit != 0) {
    471 		vaddr_t minaddr = 0, maxaddr;
    472 		buf_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr,
    473 					  bufmem_valimit, 0, false, 0);
    474 		if (buf_map == NULL)
    475 			panic("bufinit: cannot allocate submap");
    476 	} else
    477 		buf_map = kernel_map;
    478 
    479 	/*
    480 	 * Initialize buffer cache memory parameters.
    481 	 */
    482 	bufmem = 0;
    483 	buf_setwm();
    484 
    485 	/* On "small" machines use small pool page sizes where possible */
    486 	use_std = (physmem < atop(16*1024*1024));
    487 
    488 	/*
    489 	 * Also use them on systems that can map the pool pages using
    490 	 * a direct-mapped segment.
    491 	 */
    492 #ifdef PMAP_MAP_POOLPAGE
    493 	use_std = 1;
    494 #endif
    495 
    496 	buf_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
    497 	    "bufpl", NULL, IPL_SOFTBIO, NULL, NULL, NULL);
    498 	bufio_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
    499 	    "biopl", NULL, IPL_BIO, NULL, NULL, NULL);
    500 
    501 	for (i = 0; i < NMEMPOOLS; i++) {
    502 		struct pool_allocator *pa;
    503 		struct pool *pp = &bmempools[i];
    504 		u_int size = 1 << (i + MEMPOOL_INDEX_OFFSET);
    505 		char *name = kmem_alloc(8, KM_SLEEP); /* XXX: never freed */
    506 		if (__predict_false(size >= 1048576))
    507 			(void)snprintf(name, 8, "buf%um", size / 1048576);
    508 		else if (__predict_true(size >= 1024))
    509 			(void)snprintf(name, 8, "buf%uk", size / 1024);
    510 		else
    511 			(void)snprintf(name, 8, "buf%ub", size);
    512 		pa = (size <= PAGE_SIZE && use_std)
    513 			? &pool_allocator_nointr
    514 			: &bufmempool_allocator;
    515 		pool_init(pp, size, 0, 0, 0, name, pa, IPL_NONE);
    516 		pool_setlowat(pp, 1);
    517 		pool_sethiwat(pp, 1);
    518 	}
    519 
    520 	/* Initialize the buffer queues */
    521 	for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++) {
    522 		TAILQ_INIT(&dp->bq_queue);
    523 		dp->bq_bytes = 0;
    524 	}
    525 
    526 	/*
    527 	 * Estimate hash table size based on the amount of memory we
    528 	 * intend to use for the buffer cache. The average buffer
    529 	 * size is dependent on our clients (i.e. filesystems).
    530 	 *
    531 	 * For now, use an empirical 3K per buffer.
    532 	 */
    533 	nbuf = (bufmem_hiwater / 1024) / 3;
    534 	bufhashtbl = hashinit(nbuf, HASH_LIST, true, &bufhash);
    535 
    536 	sysctl_kern_buf_setup();
    537 	sysctl_vm_buf_setup();
    538 }
    539 
    540 void
    541 bufinit2(void)
    542 {
    543 
    544 	biodone_sih = softint_establish(SOFTINT_BIO | SOFTINT_MPSAFE, biointr,
    545 	    NULL);
    546 	if (biodone_sih == NULL)
    547 		panic("bufinit2: can't establish soft interrupt");
    548 }
    549 
    550 static int
    551 buf_lotsfree(void)
    552 {
    553 	u_long guess;
    554 
    555 	/* Always allocate if less than the low water mark. */
    556 	if (bufmem < bufmem_lowater)
    557 		return 1;
    558 
    559 	/* Never allocate if greater than the high water mark. */
    560 	if (bufmem > bufmem_hiwater)
    561 		return 0;
    562 
    563 	/* If there's anything on the AGE list, it should be eaten. */
    564 	if (TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue) != NULL)
    565 		return 0;
    566 
    567 	/*
    568 	 * The probabily of getting a new allocation is inversely
    569 	 * proportional  to the current size of the cache above
    570 	 * the low water mark.  Divide the total first to avoid overflows
    571 	 * in the product.
    572 	 */
    573 	guess = cprng_fast32() % 16;
    574 
    575 	if ((bufmem_hiwater - bufmem_lowater) / 16 * guess >=
    576 	    (bufmem - bufmem_lowater))
    577 		return 1;
    578 
    579 	/* Otherwise don't allocate. */
    580 	return 0;
    581 }
    582 
    583 /*
    584  * Return estimate of bytes we think need to be
    585  * released to help resolve low memory conditions.
    586  *
    587  * => called with bufcache_lock held.
    588  */
    589 static int
    590 buf_canrelease(void)
    591 {
    592 	int pagedemand, ninvalid = 0;
    593 
    594 	KASSERT(mutex_owned(&bufcache_lock));
    595 
    596 	if (bufmem < bufmem_lowater)
    597 		return 0;
    598 
    599 	if (bufmem > bufmem_hiwater)
    600 		return bufmem - bufmem_hiwater;
    601 
    602 	ninvalid += bufqueues[BQ_AGE].bq_bytes;
    603 
    604 	pagedemand = uvmexp.freetarg - uvmexp.free;
    605 	if (pagedemand < 0)
    606 		return ninvalid;
    607 	return MAX(ninvalid, MIN(2 * MAXBSIZE,
    608 	    MIN((bufmem - bufmem_lowater) / 16, pagedemand * PAGE_SIZE)));
    609 }
    610 
    611 /*
    612  * Buffer memory allocation helper functions
    613  */
    614 static u_long
    615 buf_mempoolidx(u_long size)
    616 {
    617 	u_int n = 0;
    618 
    619 	size -= 1;
    620 	size >>= MEMPOOL_INDEX_OFFSET;
    621 	while (size) {
    622 		size >>= 1;
    623 		n += 1;
    624 	}
    625 	if (n >= NMEMPOOLS)
    626 		panic("buf mem pool index %d", n);
    627 	return n;
    628 }
    629 
    630 static u_long
    631 buf_roundsize(u_long size)
    632 {
    633 	/* Round up to nearest power of 2 */
    634 	return (1 << (buf_mempoolidx(size) + MEMPOOL_INDEX_OFFSET));
    635 }
    636 
    637 static void *
    638 buf_alloc(size_t size)
    639 {
    640 	u_int n = buf_mempoolidx(size);
    641 	void *addr;
    642 
    643 	while (1) {
    644 		addr = pool_get(&bmempools[n], PR_NOWAIT);
    645 		if (addr != NULL)
    646 			break;
    647 
    648 		/* No memory, see if we can free some. If so, try again */
    649 		mutex_enter(&bufcache_lock);
    650 		if (buf_drain(1) > 0) {
    651 			mutex_exit(&bufcache_lock);
    652 			continue;
    653 		}
    654 
    655 		if (curlwp == uvm.pagedaemon_lwp) {
    656 			mutex_exit(&bufcache_lock);
    657 			return NULL;
    658 		}
    659 
    660 		/* Wait for buffers to arrive on the LRU queue */
    661 		cv_timedwait(&needbuffer_cv, &bufcache_lock, hz / 4);
    662 		mutex_exit(&bufcache_lock);
    663 	}
    664 
    665 	return addr;
    666 }
    667 
    668 static void
    669 buf_mrelease(void *addr, size_t size)
    670 {
    671 
    672 	pool_put(&bmempools[buf_mempoolidx(size)], addr);
    673 }
    674 
    675 /*
    676  * bread()/breadn() helper.
    677  */
    678 static buf_t *
    679 bio_doread(struct vnode *vp, daddr_t blkno, int size, int async)
    680 {
    681 	buf_t *bp;
    682 	struct mount *mp;
    683 
    684 	bp = getblk(vp, blkno, size, 0, 0);
    685 
    686 	/*
    687 	 * getblk() may return NULL if we are the pagedaemon.
    688 	 */
    689 	if (bp == NULL) {
    690 		KASSERT(curlwp == uvm.pagedaemon_lwp);
    691 		return NULL;
    692 	}
    693 
    694 	/*
    695 	 * If buffer does not have data valid, start a read.
    696 	 * Note that if buffer is BC_INVAL, getblk() won't return it.
    697 	 * Therefore, it's valid if its I/O has completed or been delayed.
    698 	 */
    699 	if (!ISSET(bp->b_oflags, (BO_DONE | BO_DELWRI))) {
    700 		/* Start I/O for the buffer. */
    701 		SET(bp->b_flags, B_READ | async);
    702 		if (async)
    703 			BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
    704 		else
    705 			BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
    706 		VOP_STRATEGY(vp, bp);
    707 
    708 		/* Pay for the read. */
    709 		curlwp->l_ru.ru_inblock++;
    710 	} else if (async)
    711 		brelse(bp, 0);
    712 
    713 	if (vp->v_type == VBLK)
    714 		mp = spec_node_getmountedfs(vp);
    715 	else
    716 		mp = vp->v_mount;
    717 
    718 	/*
    719 	 * Collect statistics on synchronous and asynchronous reads.
    720 	 * Reads from block devices are charged to their associated
    721 	 * filesystem (if any).
    722 	 */
    723 	if (mp != NULL) {
    724 		if (async == 0)
    725 			mp->mnt_stat.f_syncreads++;
    726 		else
    727 			mp->mnt_stat.f_asyncreads++;
    728 	}
    729 
    730 	return (bp);
    731 }
    732 
    733 /*
    734  * Read a disk block.
    735  * This algorithm described in Bach (p.54).
    736  */
    737 int
    738 bread(struct vnode *vp, daddr_t blkno, int size, int flags, buf_t **bpp)
    739 {
    740 	buf_t *bp;
    741 	int error;
    742 
    743 	BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
    744 
    745 	/* Get buffer for block. */
    746 	bp = *bpp = bio_doread(vp, blkno, size, 0);
    747 	if (bp == NULL)
    748 		return ENOMEM;
    749 
    750 	/* Wait for the read to complete, and return result. */
    751 	error = biowait(bp);
    752 	if (error == 0 && (flags & B_MODIFY) != 0)
    753 		error = fscow_run(bp, true);
    754 	if (error) {
    755 		brelse(bp, 0);
    756 		*bpp = NULL;
    757 	}
    758 
    759 	return error;
    760 }
    761 
    762 /*
    763  * Read-ahead multiple disk blocks. The first is sync, the rest async.
    764  * Trivial modification to the breada algorithm presented in Bach (p.55).
    765  */
    766 int
    767 breadn(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablks,
    768     int *rasizes, int nrablks, int flags, buf_t **bpp)
    769 {
    770 	buf_t *bp;
    771 	int error, i;
    772 
    773 	BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
    774 
    775 	bp = *bpp = bio_doread(vp, blkno, size, 0);
    776 	if (bp == NULL)
    777 		return ENOMEM;
    778 
    779 	/*
    780 	 * For each of the read-ahead blocks, start a read, if necessary.
    781 	 */
    782 	mutex_enter(&bufcache_lock);
    783 	for (i = 0; i < nrablks; i++) {
    784 		/* If it's in the cache, just go on to next one. */
    785 		if (incore(vp, rablks[i]))
    786 			continue;
    787 
    788 		/* Get a buffer for the read-ahead block */
    789 		mutex_exit(&bufcache_lock);
    790 		(void) bio_doread(vp, rablks[i], rasizes[i], B_ASYNC);
    791 		mutex_enter(&bufcache_lock);
    792 	}
    793 	mutex_exit(&bufcache_lock);
    794 
    795 	/* Otherwise, we had to start a read for it; wait until it's valid. */
    796 	error = biowait(bp);
    797 	if (error == 0 && (flags & B_MODIFY) != 0)
    798 		error = fscow_run(bp, true);
    799 	if (error) {
    800 		brelse(bp, 0);
    801 		*bpp = NULL;
    802 	}
    803 
    804 	return error;
    805 }
    806 
    807 /*
    808  * Block write.  Described in Bach (p.56)
    809  */
    810 int
    811 bwrite(buf_t *bp)
    812 {
    813 	int rv, sync, wasdelayed;
    814 	struct vnode *vp;
    815 	struct mount *mp;
    816 
    817 	BIOHIST_FUNC(__func__); BIOHIST_CALLARGS(biohist, "bp=%p",
    818 	    bp, 0, 0, 0);
    819 
    820 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
    821 	KASSERT(!cv_has_waiters(&bp->b_done));
    822 
    823 	vp = bp->b_vp;
    824 
    825 	/*
    826 	 * dholland 20160728 AFAICT vp==NULL must be impossible as it
    827 	 * will crash upon reaching VOP_STRATEGY below... see further
    828 	 * analysis on tech-kern.
    829 	 */
    830 	KASSERTMSG(vp != NULL, "bwrite given buffer with null vnode");
    831 
    832 	if (vp != NULL) {
    833 		KASSERT(bp->b_objlock == vp->v_interlock);
    834 		if (vp->v_type == VBLK)
    835 			mp = spec_node_getmountedfs(vp);
    836 		else
    837 			mp = vp->v_mount;
    838 	} else {
    839 		mp = NULL;
    840 	}
    841 
    842 	if (mp && mp->mnt_wapbl) {
    843 		if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
    844 			bdwrite(bp);
    845 			return 0;
    846 		}
    847 	}
    848 
    849 	/*
    850 	 * Remember buffer type, to switch on it later.  If the write was
    851 	 * synchronous, but the file system was mounted with MNT_ASYNC,
    852 	 * convert it to a delayed write.
    853 	 * XXX note that this relies on delayed tape writes being converted
    854 	 * to async, not sync writes (which is safe, but ugly).
    855 	 */
    856 	sync = !ISSET(bp->b_flags, B_ASYNC);
    857 	if (sync && mp != NULL && ISSET(mp->mnt_flag, MNT_ASYNC)) {
    858 		bdwrite(bp);
    859 		return (0);
    860 	}
    861 
    862 	/*
    863 	 * Collect statistics on synchronous and asynchronous writes.
    864 	 * Writes to block devices are charged to their associated
    865 	 * filesystem (if any).
    866 	 */
    867 	if (mp != NULL) {
    868 		if (sync)
    869 			mp->mnt_stat.f_syncwrites++;
    870 		else
    871 			mp->mnt_stat.f_asyncwrites++;
    872 	}
    873 
    874 	/*
    875 	 * Pay for the I/O operation and make sure the buf is on the correct
    876 	 * vnode queue.
    877 	 */
    878 	bp->b_error = 0;
    879 	wasdelayed = ISSET(bp->b_oflags, BO_DELWRI);
    880 	CLR(bp->b_flags, B_READ);
    881 	if (wasdelayed) {
    882 		mutex_enter(&bufcache_lock);
    883 		mutex_enter(bp->b_objlock);
    884 		CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
    885 		reassignbuf(bp, bp->b_vp);
    886 		mutex_exit(&bufcache_lock);
    887 	} else {
    888 		curlwp->l_ru.ru_oublock++;
    889 		mutex_enter(bp->b_objlock);
    890 		CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
    891 	}
    892 	if (vp != NULL)
    893 		vp->v_numoutput++;
    894 	mutex_exit(bp->b_objlock);
    895 
    896 	/* Initiate disk write. */
    897 	if (sync)
    898 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
    899 	else
    900 		BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
    901 
    902 	VOP_STRATEGY(vp, bp);
    903 
    904 	if (sync) {
    905 		/* If I/O was synchronous, wait for it to complete. */
    906 		rv = biowait(bp);
    907 
    908 		/* Release the buffer. */
    909 		brelse(bp, 0);
    910 
    911 		return (rv);
    912 	} else {
    913 		return (0);
    914 	}
    915 }
    916 
    917 int
    918 vn_bwrite(void *v)
    919 {
    920 	struct vop_bwrite_args *ap = v;
    921 
    922 	return (bwrite(ap->a_bp));
    923 }
    924 
    925 /*
    926  * Delayed write.
    927  *
    928  * The buffer is marked dirty, but is not queued for I/O.
    929  * This routine should be used when the buffer is expected
    930  * to be modified again soon, typically a small write that
    931  * partially fills a buffer.
    932  *
    933  * NB: magnetic tapes cannot be delayed; they must be
    934  * written in the order that the writes are requested.
    935  *
    936  * Described in Leffler, et al. (pp. 208-213).
    937  */
    938 void
    939 bdwrite(buf_t *bp)
    940 {
    941 
    942 	BIOHIST_FUNC(__func__); BIOHIST_CALLARGS(biohist, "bp=%p",
    943 	    bp, 0, 0, 0);
    944 
    945 	KASSERT(bp->b_vp == NULL || bp->b_vp->v_tag != VT_UFS ||
    946 	    bp->b_vp->v_type == VBLK || ISSET(bp->b_flags, B_COWDONE));
    947 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
    948 	KASSERT(!cv_has_waiters(&bp->b_done));
    949 
    950 	/* If this is a tape block, write the block now. */
    951 	if (bdev_type(bp->b_dev) == D_TAPE) {
    952 		bawrite(bp);
    953 		return;
    954 	}
    955 
    956 	if (wapbl_vphaswapbl(bp->b_vp)) {
    957 		struct mount *mp = wapbl_vptomp(bp->b_vp);
    958 
    959 		if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
    960 			WAPBL_ADD_BUF(mp, bp);
    961 		}
    962 	}
    963 
    964 	/*
    965 	 * If the block hasn't been seen before:
    966 	 *	(1) Mark it as having been seen,
    967 	 *	(2) Charge for the write,
    968 	 *	(3) Make sure it's on its vnode's correct block list.
    969 	 */
    970 	KASSERT(bp->b_vp == NULL || bp->b_objlock == bp->b_vp->v_interlock);
    971 
    972 	if (!ISSET(bp->b_oflags, BO_DELWRI)) {
    973 		mutex_enter(&bufcache_lock);
    974 		mutex_enter(bp->b_objlock);
    975 		SET(bp->b_oflags, BO_DELWRI);
    976 		curlwp->l_ru.ru_oublock++;
    977 		reassignbuf(bp, bp->b_vp);
    978 		mutex_exit(&bufcache_lock);
    979 	} else {
    980 		mutex_enter(bp->b_objlock);
    981 	}
    982 	/* Otherwise, the "write" is done, so mark and release the buffer. */
    983 	CLR(bp->b_oflags, BO_DONE);
    984 	mutex_exit(bp->b_objlock);
    985 
    986 	brelse(bp, 0);
    987 }
    988 
    989 /*
    990  * Asynchronous block write; just an asynchronous bwrite().
    991  */
    992 void
    993 bawrite(buf_t *bp)
    994 {
    995 
    996 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
    997 	KASSERT(bp->b_vp != NULL);
    998 
    999 	SET(bp->b_flags, B_ASYNC);
   1000 	VOP_BWRITE(bp->b_vp, bp);
   1001 }
   1002 
   1003 /*
   1004  * Release a buffer on to the free lists.
   1005  * Described in Bach (p. 46).
   1006  */
   1007 void
   1008 brelsel(buf_t *bp, int set)
   1009 {
   1010 	struct bqueue *bufq;
   1011 	struct vnode *vp;
   1012 
   1013 	KASSERT(bp != NULL);
   1014 	KASSERT(mutex_owned(&bufcache_lock));
   1015 	KASSERT(!cv_has_waiters(&bp->b_done));
   1016 	KASSERT(bp->b_refcnt > 0);
   1017 
   1018 	SET(bp->b_cflags, set);
   1019 
   1020 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
   1021 	KASSERT(bp->b_iodone == NULL);
   1022 
   1023 	/* Wake up any processes waiting for any buffer to become free. */
   1024 	cv_signal(&needbuffer_cv);
   1025 
   1026 	/* Wake up any proceeses waiting for _this_ buffer to become free */
   1027 	if (ISSET(bp->b_cflags, BC_WANTED))
   1028 		CLR(bp->b_cflags, BC_WANTED|BC_AGE);
   1029 
   1030 	/* If it's clean clear the copy-on-write flag. */
   1031 	if (ISSET(bp->b_flags, B_COWDONE)) {
   1032 		mutex_enter(bp->b_objlock);
   1033 		if (!ISSET(bp->b_oflags, BO_DELWRI))
   1034 			CLR(bp->b_flags, B_COWDONE);
   1035 		mutex_exit(bp->b_objlock);
   1036 	}
   1037 
   1038 	/*
   1039 	 * Determine which queue the buffer should be on, then put it there.
   1040 	 */
   1041 
   1042 	/* If it's locked, don't report an error; try again later. */
   1043 	if (ISSET(bp->b_flags, B_LOCKED))
   1044 		bp->b_error = 0;
   1045 
   1046 	/* If it's not cacheable, or an error, mark it invalid. */
   1047 	if (ISSET(bp->b_cflags, BC_NOCACHE) || bp->b_error != 0)
   1048 		SET(bp->b_cflags, BC_INVAL);
   1049 
   1050 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
   1051 		/*
   1052 		 * This is a delayed write buffer that was just flushed to
   1053 		 * disk.  It is still on the LRU queue.  If it's become
   1054 		 * invalid, then we need to move it to a different queue;
   1055 		 * otherwise leave it in its current position.
   1056 		 */
   1057 		CLR(bp->b_cflags, BC_VFLUSH);
   1058 		if (!ISSET(bp->b_cflags, BC_INVAL|BC_AGE) &&
   1059 		    !ISSET(bp->b_flags, B_LOCKED) && bp->b_error == 0) {
   1060 			KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 1));
   1061 			goto already_queued;
   1062 		} else {
   1063 			bremfree(bp);
   1064 		}
   1065 	}
   1066 
   1067 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_AGE], 0));
   1068 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 0));
   1069 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LOCKED], 0));
   1070 
   1071 	if ((bp->b_bufsize <= 0) || ISSET(bp->b_cflags, BC_INVAL)) {
   1072 		/*
   1073 		 * If it's invalid or empty, dissociate it from its vnode
   1074 		 * and put on the head of the appropriate queue.
   1075 		 */
   1076 		if (ISSET(bp->b_flags, B_LOCKED)) {
   1077 			if (wapbl_vphaswapbl(vp = bp->b_vp)) {
   1078 				struct mount *mp = wapbl_vptomp(vp);
   1079 
   1080 				KASSERT(bp->b_iodone
   1081 				    != mp->mnt_wapbl_op->wo_wapbl_biodone);
   1082 				WAPBL_REMOVE_BUF(mp, bp);
   1083 			}
   1084 		}
   1085 
   1086 		mutex_enter(bp->b_objlock);
   1087 		CLR(bp->b_oflags, BO_DONE|BO_DELWRI);
   1088 		if ((vp = bp->b_vp) != NULL) {
   1089 			KASSERT(bp->b_objlock == vp->v_interlock);
   1090 			reassignbuf(bp, bp->b_vp);
   1091 			brelvp(bp);
   1092 			mutex_exit(vp->v_interlock);
   1093 		} else {
   1094 			KASSERT(bp->b_objlock == &buffer_lock);
   1095 			mutex_exit(bp->b_objlock);
   1096 		}
   1097 
   1098 		if (bp->b_bufsize <= 0)
   1099 			/* no data */
   1100 			goto already_queued;
   1101 		else
   1102 			/* invalid data */
   1103 			bufq = &bufqueues[BQ_AGE];
   1104 		binsheadfree(bp, bufq);
   1105 	} else  {
   1106 		/*
   1107 		 * It has valid data.  Put it on the end of the appropriate
   1108 		 * queue, so that it'll stick around for as long as possible.
   1109 		 * If buf is AGE, but has dependencies, must put it on last
   1110 		 * bufqueue to be scanned, ie LRU. This protects against the
   1111 		 * livelock where BQ_AGE only has buffers with dependencies,
   1112 		 * and we thus never get to the dependent buffers in BQ_LRU.
   1113 		 */
   1114 		if (ISSET(bp->b_flags, B_LOCKED)) {
   1115 			/* locked in core */
   1116 			bufq = &bufqueues[BQ_LOCKED];
   1117 		} else if (!ISSET(bp->b_cflags, BC_AGE)) {
   1118 			/* valid data */
   1119 			bufq = &bufqueues[BQ_LRU];
   1120 		} else {
   1121 			/* stale but valid data */
   1122 			bufq = &bufqueues[BQ_AGE];
   1123 		}
   1124 		binstailfree(bp, bufq);
   1125 	}
   1126 already_queued:
   1127 	/* Unlock the buffer. */
   1128 	CLR(bp->b_cflags, BC_AGE|BC_BUSY|BC_NOCACHE);
   1129 	CLR(bp->b_flags, B_ASYNC);
   1130 	cv_broadcast(&bp->b_busy);
   1131 
   1132 	if (bp->b_bufsize <= 0)
   1133 		brele(bp);
   1134 }
   1135 
   1136 void
   1137 brelse(buf_t *bp, int set)
   1138 {
   1139 
   1140 	mutex_enter(&bufcache_lock);
   1141 	brelsel(bp, set);
   1142 	mutex_exit(&bufcache_lock);
   1143 }
   1144 
   1145 /*
   1146  * Determine if a block is in the cache.
   1147  * Just look on what would be its hash chain.  If it's there, return
   1148  * a pointer to it, unless it's marked invalid.  If it's marked invalid,
   1149  * we normally don't return the buffer, unless the caller explicitly
   1150  * wants us to.
   1151  */
   1152 buf_t *
   1153 incore(struct vnode *vp, daddr_t blkno)
   1154 {
   1155 	buf_t *bp;
   1156 
   1157 	KASSERT(mutex_owned(&bufcache_lock));
   1158 
   1159 	/* Search hash chain */
   1160 	LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
   1161 		if (bp->b_lblkno == blkno && bp->b_vp == vp &&
   1162 		    !ISSET(bp->b_cflags, BC_INVAL)) {
   1163 		    	KASSERT(bp->b_objlock == vp->v_interlock);
   1164 		    	return (bp);
   1165 		}
   1166 	}
   1167 
   1168 	return (NULL);
   1169 }
   1170 
   1171 /*
   1172  * Get a block of requested size that is associated with
   1173  * a given vnode and block offset. If it is found in the
   1174  * block cache, mark it as having been found, make it busy
   1175  * and return it. Otherwise, return an empty block of the
   1176  * correct size. It is up to the caller to insure that the
   1177  * cached blocks be of the correct size.
   1178  */
   1179 buf_t *
   1180 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo)
   1181 {
   1182 	int err, preserve;
   1183 	buf_t *bp;
   1184 
   1185 	mutex_enter(&bufcache_lock);
   1186  loop:
   1187 	bp = incore(vp, blkno);
   1188 	if (bp != NULL) {
   1189 		err = bbusy(bp, ((slpflag & PCATCH) != 0), slptimeo, NULL);
   1190 		if (err != 0) {
   1191 			if (err == EPASSTHROUGH)
   1192 				goto loop;
   1193 			mutex_exit(&bufcache_lock);
   1194 			return (NULL);
   1195 		}
   1196 		KASSERT(!cv_has_waiters(&bp->b_done));
   1197 #ifdef DIAGNOSTIC
   1198 		if (ISSET(bp->b_oflags, BO_DONE|BO_DELWRI) &&
   1199 		    bp->b_bcount < size && vp->v_type != VBLK)
   1200 			panic("getblk: block size invariant failed");
   1201 #endif
   1202 		bremfree(bp);
   1203 		preserve = 1;
   1204 	} else {
   1205 		if ((bp = getnewbuf(slpflag, slptimeo, 0)) == NULL)
   1206 			goto loop;
   1207 
   1208 		if (incore(vp, blkno) != NULL) {
   1209 			/* The block has come into memory in the meantime. */
   1210 			brelsel(bp, 0);
   1211 			goto loop;
   1212 		}
   1213 
   1214 		LIST_INSERT_HEAD(BUFHASH(vp, blkno), bp, b_hash);
   1215 		bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
   1216 		mutex_enter(vp->v_interlock);
   1217 		bgetvp(vp, bp);
   1218 		mutex_exit(vp->v_interlock);
   1219 		preserve = 0;
   1220 	}
   1221 	mutex_exit(&bufcache_lock);
   1222 
   1223 	/*
   1224 	 * LFS can't track total size of B_LOCKED buffer (locked_queue_bytes)
   1225 	 * if we re-size buffers here.
   1226 	 */
   1227 	if (ISSET(bp->b_flags, B_LOCKED)) {
   1228 		KASSERT(bp->b_bufsize >= size);
   1229 	} else {
   1230 		if (allocbuf(bp, size, preserve)) {
   1231 			mutex_enter(&bufcache_lock);
   1232 			LIST_REMOVE(bp, b_hash);
   1233 			brelsel(bp, BC_INVAL);
   1234 			mutex_exit(&bufcache_lock);
   1235 			return NULL;
   1236 		}
   1237 	}
   1238 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   1239 	return (bp);
   1240 }
   1241 
   1242 /*
   1243  * Get an empty, disassociated buffer of given size.
   1244  */
   1245 buf_t *
   1246 geteblk(int size)
   1247 {
   1248 	buf_t *bp;
   1249 	int error __diagused;
   1250 
   1251 	mutex_enter(&bufcache_lock);
   1252 	while ((bp = getnewbuf(0, 0, 0)) == NULL)
   1253 		;
   1254 
   1255 	SET(bp->b_cflags, BC_INVAL);
   1256 	LIST_INSERT_HEAD(&invalhash, bp, b_hash);
   1257 	mutex_exit(&bufcache_lock);
   1258 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   1259 	error = allocbuf(bp, size, 0);
   1260 	KASSERT(error == 0);
   1261 	return (bp);
   1262 }
   1263 
   1264 /*
   1265  * Expand or contract the actual memory allocated to a buffer.
   1266  *
   1267  * If the buffer shrinks, data is lost, so it's up to the
   1268  * caller to have written it out *first*; this routine will not
   1269  * start a write.  If the buffer grows, it's the callers
   1270  * responsibility to fill out the buffer's additional contents.
   1271  */
   1272 int
   1273 allocbuf(buf_t *bp, int size, int preserve)
   1274 {
   1275 	void *addr;
   1276 	vsize_t oldsize, desired_size;
   1277 	int oldcount;
   1278 	int delta;
   1279 
   1280 	desired_size = buf_roundsize(size);
   1281 	if (desired_size > MAXBSIZE)
   1282 		printf("allocbuf: buffer larger than MAXBSIZE requested");
   1283 
   1284 	oldcount = bp->b_bcount;
   1285 
   1286 	bp->b_bcount = size;
   1287 
   1288 	oldsize = bp->b_bufsize;
   1289 	if (oldsize == desired_size) {
   1290 		/*
   1291 		 * Do not short cut the WAPBL resize, as the buffer length
   1292 		 * could still have changed and this would corrupt the
   1293 		 * tracking of the transaction length.
   1294 		 */
   1295 		goto out;
   1296 	}
   1297 
   1298 	/*
   1299 	 * If we want a buffer of a different size, re-allocate the
   1300 	 * buffer's memory; copy old content only if needed.
   1301 	 */
   1302 	addr = buf_alloc(desired_size);
   1303 	if (addr == NULL)
   1304 		return ENOMEM;
   1305 	if (preserve)
   1306 		memcpy(addr, bp->b_data, MIN(oldsize,desired_size));
   1307 	if (bp->b_data != NULL)
   1308 		buf_mrelease(bp->b_data, oldsize);
   1309 	bp->b_data = addr;
   1310 	bp->b_bufsize = desired_size;
   1311 
   1312 	/*
   1313 	 * Update overall buffer memory counter (protected by bufcache_lock)
   1314 	 */
   1315 	delta = (long)desired_size - (long)oldsize;
   1316 
   1317 	mutex_enter(&bufcache_lock);
   1318 	if ((bufmem += delta) > bufmem_hiwater) {
   1319 		/*
   1320 		 * Need to trim overall memory usage.
   1321 		 */
   1322 		while (buf_canrelease()) {
   1323 			if (curcpu()->ci_schedstate.spc_flags &
   1324 			    SPCF_SHOULDYIELD) {
   1325 				mutex_exit(&bufcache_lock);
   1326 				preempt();
   1327 				mutex_enter(&bufcache_lock);
   1328 			}
   1329 			if (buf_trim() == 0)
   1330 				break;
   1331 		}
   1332 	}
   1333 	mutex_exit(&bufcache_lock);
   1334 
   1335  out:
   1336 	if (wapbl_vphaswapbl(bp->b_vp))
   1337 		WAPBL_RESIZE_BUF(wapbl_vptomp(bp->b_vp), bp, oldsize, oldcount);
   1338 
   1339 	return 0;
   1340 }
   1341 
   1342 /*
   1343  * Find a buffer which is available for use.
   1344  * Select something from a free list.
   1345  * Preference is to AGE list, then LRU list.
   1346  *
   1347  * Called with the buffer queues locked.
   1348  * Return buffer locked.
   1349  */
   1350 buf_t *
   1351 getnewbuf(int slpflag, int slptimeo, int from_bufq)
   1352 {
   1353 	buf_t *bp;
   1354 	struct vnode *vp;
   1355 
   1356  start:
   1357 	KASSERT(mutex_owned(&bufcache_lock));
   1358 
   1359 	/*
   1360 	 * Get a new buffer from the pool.
   1361 	 */
   1362 	if (!from_bufq && buf_lotsfree()) {
   1363 		mutex_exit(&bufcache_lock);
   1364 		bp = pool_cache_get(buf_cache, PR_NOWAIT);
   1365 		if (bp != NULL) {
   1366 			memset((char *)bp, 0, sizeof(*bp));
   1367 			buf_init(bp);
   1368 			SET(bp->b_cflags, BC_BUSY);	/* mark buffer busy */
   1369 			mutex_enter(&bufcache_lock);
   1370 #if defined(DIAGNOSTIC)
   1371 			bp->b_freelistindex = -1;
   1372 #endif /* defined(DIAGNOSTIC) */
   1373 			return (bp);
   1374 		}
   1375 		mutex_enter(&bufcache_lock);
   1376 	}
   1377 
   1378 	KASSERT(mutex_owned(&bufcache_lock));
   1379 	if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue)) != NULL ||
   1380 	    (bp = TAILQ_FIRST(&bufqueues[BQ_LRU].bq_queue)) != NULL) {
   1381 	    	KASSERT(!ISSET(bp->b_cflags, BC_BUSY) || ISSET(bp->b_cflags, BC_VFLUSH));
   1382 		bremfree(bp);
   1383 
   1384 		/* Buffer is no longer on free lists. */
   1385 		SET(bp->b_cflags, BC_BUSY);
   1386 	} else {
   1387 		/*
   1388 		 * XXX: !from_bufq should be removed.
   1389 		 */
   1390 		if (!from_bufq || curlwp != uvm.pagedaemon_lwp) {
   1391 			/* wait for a free buffer of any kind */
   1392 			if ((slpflag & PCATCH) != 0)
   1393 				(void)cv_timedwait_sig(&needbuffer_cv,
   1394 				    &bufcache_lock, slptimeo);
   1395 			else
   1396 				(void)cv_timedwait(&needbuffer_cv,
   1397 				    &bufcache_lock, slptimeo);
   1398 		}
   1399 		return (NULL);
   1400 	}
   1401 
   1402 #ifdef DIAGNOSTIC
   1403 	if (bp->b_bufsize <= 0)
   1404 		panic("buffer %p: on queue but empty", bp);
   1405 #endif
   1406 
   1407 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
   1408 		/*
   1409 		 * This is a delayed write buffer being flushed to disk.  Make
   1410 		 * sure it gets aged out of the queue when it's finished, and
   1411 		 * leave it off the LRU queue.
   1412 		 */
   1413 		CLR(bp->b_cflags, BC_VFLUSH);
   1414 		SET(bp->b_cflags, BC_AGE);
   1415 		goto start;
   1416 	}
   1417 
   1418 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
   1419 	KASSERT(bp->b_refcnt > 0);
   1420     	KASSERT(!cv_has_waiters(&bp->b_done));
   1421 
   1422 	/*
   1423 	 * If buffer was a delayed write, start it and return NULL
   1424 	 * (since we might sleep while starting the write).
   1425 	 */
   1426 	if (ISSET(bp->b_oflags, BO_DELWRI)) {
   1427 		/*
   1428 		 * This buffer has gone through the LRU, so make sure it gets
   1429 		 * reused ASAP.
   1430 		 */
   1431 		SET(bp->b_cflags, BC_AGE);
   1432 		mutex_exit(&bufcache_lock);
   1433 		bawrite(bp);
   1434 		mutex_enter(&bufcache_lock);
   1435 		return (NULL);
   1436 	}
   1437 
   1438 	vp = bp->b_vp;
   1439 
   1440 	/* clear out various other fields */
   1441 	bp->b_cflags = BC_BUSY;
   1442 	bp->b_oflags = 0;
   1443 	bp->b_flags = 0;
   1444 	bp->b_dev = NODEV;
   1445 	bp->b_blkno = 0;
   1446 	bp->b_lblkno = 0;
   1447 	bp->b_rawblkno = 0;
   1448 	bp->b_iodone = 0;
   1449 	bp->b_error = 0;
   1450 	bp->b_resid = 0;
   1451 	bp->b_bcount = 0;
   1452 
   1453 	LIST_REMOVE(bp, b_hash);
   1454 
   1455 	/* Disassociate us from our vnode, if we had one... */
   1456 	if (vp != NULL) {
   1457 		mutex_enter(vp->v_interlock);
   1458 		brelvp(bp);
   1459 		mutex_exit(vp->v_interlock);
   1460 	}
   1461 
   1462 	return (bp);
   1463 }
   1464 
   1465 /*
   1466  * Attempt to free an aged buffer off the queues.
   1467  * Called with queue lock held.
   1468  * Returns the amount of buffer memory freed.
   1469  */
   1470 static int
   1471 buf_trim(void)
   1472 {
   1473 	buf_t *bp;
   1474 	long size;
   1475 
   1476 	KASSERT(mutex_owned(&bufcache_lock));
   1477 
   1478 	/* Instruct getnewbuf() to get buffers off the queues */
   1479 	if ((bp = getnewbuf(PCATCH, 1, 1)) == NULL)
   1480 		return 0;
   1481 
   1482 	KASSERT((bp->b_cflags & BC_WANTED) == 0);
   1483 	size = bp->b_bufsize;
   1484 	bufmem -= size;
   1485 	if (size > 0) {
   1486 		buf_mrelease(bp->b_data, size);
   1487 		bp->b_bcount = bp->b_bufsize = 0;
   1488 	}
   1489 	/* brelse() will return the buffer to the global buffer pool */
   1490 	brelsel(bp, 0);
   1491 	return size;
   1492 }
   1493 
   1494 int
   1495 buf_drain(int n)
   1496 {
   1497 	int size = 0, sz;
   1498 
   1499 	KASSERT(mutex_owned(&bufcache_lock));
   1500 
   1501 	while (size < n && bufmem > bufmem_lowater) {
   1502 		sz = buf_trim();
   1503 		if (sz <= 0)
   1504 			break;
   1505 		size += sz;
   1506 	}
   1507 
   1508 	return size;
   1509 }
   1510 
   1511 SDT_PROVIDER_DEFINE(io);
   1512 
   1513 SDT_PROBE_DEFINE1(io, kernel, , wait__start, "struct buf *"/*bp*/);
   1514 SDT_PROBE_DEFINE1(io, kernel, , wait__done, "struct buf *"/*bp*/);
   1515 
   1516 /*
   1517  * Wait for operations on the buffer to complete.
   1518  * When they do, extract and return the I/O's error value.
   1519  */
   1520 int
   1521 biowait(buf_t *bp)
   1522 {
   1523 
   1524 	BIOHIST_FUNC(__func__);
   1525 
   1526 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
   1527 	KASSERT(bp->b_refcnt > 0);
   1528 
   1529 	SDT_PROBE1(io, kernel, , wait__start, bp);
   1530 
   1531 	mutex_enter(bp->b_objlock);
   1532 
   1533 	BIOHIST_CALLARGS(biohist, "bp=%p, oflags=0x%x",
   1534 	    bp, bp->b_oflags, 0, 0);
   1535 
   1536 	while (!ISSET(bp->b_oflags, BO_DONE | BO_DELWRI)) {
   1537 		BIOHIST_LOG(biohist, "waiting bp=%p", bp, 0, 0, 0);
   1538 		cv_wait(&bp->b_done, bp->b_objlock);
   1539 	}
   1540 	mutex_exit(bp->b_objlock);
   1541 
   1542 	SDT_PROBE1(io, kernel, , wait__done, bp);
   1543 
   1544 	BIOHIST_LOG(biohist, "return %d", bp->b_error, 0, 0, 0);
   1545 
   1546 	return bp->b_error;
   1547 }
   1548 
   1549 /*
   1550  * Mark I/O complete on a buffer.
   1551  *
   1552  * If a callback has been requested, e.g. the pageout
   1553  * daemon, do so. Otherwise, awaken waiting processes.
   1554  *
   1555  * [ Leffler, et al., says on p.247:
   1556  *	"This routine wakes up the blocked process, frees the buffer
   1557  *	for an asynchronous write, or, for a request by the pagedaemon
   1558  *	process, invokes a procedure specified in the buffer structure" ]
   1559  *
   1560  * In real life, the pagedaemon (or other system processes) wants
   1561  * to do async stuff too, and doesn't want the buffer brelse()'d.
   1562  * (for swap pager, that puts swap buffers on the free lists (!!!),
   1563  * for the vn device, that puts allocated buffers on the free lists!)
   1564  */
   1565 void
   1566 biodone(buf_t *bp)
   1567 {
   1568 	int s;
   1569 
   1570 	BIOHIST_FUNC(__func__);
   1571 
   1572 	KASSERT(!ISSET(bp->b_oflags, BO_DONE));
   1573 
   1574 	if (cpu_intr_p()) {
   1575 		/* From interrupt mode: defer to a soft interrupt. */
   1576 		s = splvm();
   1577 		TAILQ_INSERT_TAIL(&curcpu()->ci_data.cpu_biodone, bp, b_actq);
   1578 
   1579 		BIOHIST_CALLARGS(biohist, "bp=%p, softint scheduled",
   1580 		    bp, 0, 0, 0);
   1581 		softint_schedule(biodone_sih);
   1582 		splx(s);
   1583 	} else {
   1584 		/* Process now - the buffer may be freed soon. */
   1585 		biodone2(bp);
   1586 	}
   1587 }
   1588 
   1589 SDT_PROBE_DEFINE1(io, kernel, , done, "struct buf *"/*bp*/);
   1590 
   1591 static void
   1592 biodone2(buf_t *bp)
   1593 {
   1594 	void (*callout)(buf_t *);
   1595 
   1596 	SDT_PROBE1(io, kernel, ,done, bp);
   1597 
   1598 	BIOHIST_FUNC(__func__);
   1599 	BIOHIST_CALLARGS(biohist, "bp=%p", bp, 0, 0, 0);
   1600 
   1601 	mutex_enter(bp->b_objlock);
   1602 	/* Note that the transfer is done. */
   1603 	if (ISSET(bp->b_oflags, BO_DONE))
   1604 		panic("biodone2 already");
   1605 	CLR(bp->b_flags, B_COWDONE);
   1606 	SET(bp->b_oflags, BO_DONE);
   1607 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   1608 
   1609 	/* Wake up waiting writers. */
   1610 	if (!ISSET(bp->b_flags, B_READ))
   1611 		vwakeup(bp);
   1612 
   1613 	if ((callout = bp->b_iodone) != NULL) {
   1614 		BIOHIST_LOG(biohist, "callout %p", callout, 0, 0, 0);
   1615 
   1616 		/* Note callout done, then call out. */
   1617 		KASSERT(!cv_has_waiters(&bp->b_done));
   1618 		KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1619 		bp->b_iodone = NULL;
   1620 		mutex_exit(bp->b_objlock);
   1621 		(*callout)(bp);
   1622 		KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1623 	} else if (ISSET(bp->b_flags, B_ASYNC)) {
   1624 		/* If async, release. */
   1625 		BIOHIST_LOG(biohist, "async", 0, 0, 0, 0);
   1626 		KASSERT(!cv_has_waiters(&bp->b_done));
   1627 		mutex_exit(bp->b_objlock);
   1628 		brelse(bp, 0);
   1629 	} else {
   1630 		/* Otherwise just wake up waiters in biowait(). */
   1631 		BIOHIST_LOG(biohist, "wake-up", 0, 0, 0, 0);
   1632 		cv_broadcast(&bp->b_done);
   1633 		mutex_exit(bp->b_objlock);
   1634 	}
   1635 }
   1636 
   1637 static void
   1638 biointr(void *cookie)
   1639 {
   1640 	struct cpu_info *ci;
   1641 	buf_t *bp;
   1642 	int s;
   1643 
   1644 	BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
   1645 
   1646 	ci = curcpu();
   1647 
   1648 	s = splvm();
   1649 	while (!TAILQ_EMPTY(&ci->ci_data.cpu_biodone)) {
   1650 		KASSERT(curcpu() == ci);
   1651 
   1652 		bp = TAILQ_FIRST(&ci->ci_data.cpu_biodone);
   1653 		TAILQ_REMOVE(&ci->ci_data.cpu_biodone, bp, b_actq);
   1654 		splx(s);
   1655 
   1656 		BIOHIST_LOG(biohist, "bp=%p", bp, 0, 0, 0);
   1657 		biodone2(bp);
   1658 
   1659 		s = splvm();
   1660 	}
   1661 	splx(s);
   1662 }
   1663 
   1664 /*
   1665  * Wait for all buffers to complete I/O
   1666  * Return the number of "stuck" buffers.
   1667  */
   1668 int
   1669 buf_syncwait(void)
   1670 {
   1671 	buf_t *bp;
   1672 	int iter, nbusy, nbusy_prev = 0, ihash;
   1673 
   1674 	BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
   1675 
   1676 	for (iter = 0; iter < 20;) {
   1677 		mutex_enter(&bufcache_lock);
   1678 		nbusy = 0;
   1679 		for (ihash = 0; ihash < bufhash+1; ihash++) {
   1680 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
   1681 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY)
   1682 				nbusy += ((bp->b_flags & B_READ) == 0);
   1683 		    }
   1684 		}
   1685 		mutex_exit(&bufcache_lock);
   1686 
   1687 		if (nbusy == 0)
   1688 			break;
   1689 		if (nbusy_prev == 0)
   1690 			nbusy_prev = nbusy;
   1691 		printf("%d ", nbusy);
   1692 		kpause("bflush", false, MAX(1, hz / 25 * iter), NULL);
   1693 		if (nbusy >= nbusy_prev) /* we didn't flush anything */
   1694 			iter++;
   1695 		else
   1696 			nbusy_prev = nbusy;
   1697 	}
   1698 
   1699 	if (nbusy) {
   1700 #if defined(DEBUG) || defined(DEBUG_HALT_BUSY)
   1701 		printf("giving up\nPrinting vnodes for busy buffers\n");
   1702 		for (ihash = 0; ihash < bufhash+1; ihash++) {
   1703 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
   1704 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY &&
   1705 			    (bp->b_flags & B_READ) == 0)
   1706 				vprint(NULL, bp->b_vp);
   1707 		    }
   1708 		}
   1709 #endif
   1710 	}
   1711 
   1712 	return nbusy;
   1713 }
   1714 
   1715 static void
   1716 sysctl_fillbuf(buf_t *i, struct buf_sysctl *o)
   1717 {
   1718 
   1719 	o->b_flags = i->b_flags | i->b_cflags | i->b_oflags;
   1720 	o->b_error = i->b_error;
   1721 	o->b_prio = i->b_prio;
   1722 	o->b_dev = i->b_dev;
   1723 	o->b_bufsize = i->b_bufsize;
   1724 	o->b_bcount = i->b_bcount;
   1725 	o->b_resid = i->b_resid;
   1726 	o->b_addr = PTRTOUINT64(i->b_data);
   1727 	o->b_blkno = i->b_blkno;
   1728 	o->b_rawblkno = i->b_rawblkno;
   1729 	o->b_iodone = PTRTOUINT64(i->b_iodone);
   1730 	o->b_proc = PTRTOUINT64(i->b_proc);
   1731 	o->b_vp = PTRTOUINT64(i->b_vp);
   1732 	o->b_saveaddr = PTRTOUINT64(i->b_saveaddr);
   1733 	o->b_lblkno = i->b_lblkno;
   1734 }
   1735 
   1736 #define KERN_BUFSLOP 20
   1737 static int
   1738 sysctl_dobuf(SYSCTLFN_ARGS)
   1739 {
   1740 	buf_t *bp;
   1741 	struct buf_sysctl bs;
   1742 	struct bqueue *bq;
   1743 	char *dp;
   1744 	u_int i, op, arg;
   1745 	size_t len, needed, elem_size, out_size;
   1746 	int error, elem_count, retries;
   1747 
   1748 	if (namelen == 1 && name[0] == CTL_QUERY)
   1749 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   1750 
   1751 	if (namelen != 4)
   1752 		return (EINVAL);
   1753 
   1754 	retries = 100;
   1755  retry:
   1756 	dp = oldp;
   1757 	len = (oldp != NULL) ? *oldlenp : 0;
   1758 	op = name[0];
   1759 	arg = name[1];
   1760 	elem_size = name[2];
   1761 	elem_count = name[3];
   1762 	out_size = MIN(sizeof(bs), elem_size);
   1763 
   1764 	/*
   1765 	 * at the moment, these are just "placeholders" to make the
   1766 	 * API for retrieving kern.buf data more extensible in the
   1767 	 * future.
   1768 	 *
   1769 	 * XXX kern.buf currently has "netbsd32" issues.  hopefully
   1770 	 * these will be resolved at a later point.
   1771 	 */
   1772 	if (op != KERN_BUF_ALL || arg != KERN_BUF_ALL ||
   1773 	    elem_size < 1 || elem_count < 0)
   1774 		return (EINVAL);
   1775 
   1776 	error = 0;
   1777 	needed = 0;
   1778 	sysctl_unlock();
   1779 	mutex_enter(&bufcache_lock);
   1780 	for (i = 0; i < BQUEUES; i++) {
   1781 		bq = &bufqueues[i];
   1782 		TAILQ_FOREACH(bp, &bq->bq_queue, b_freelist) {
   1783 			bq->bq_marker = bp;
   1784 			if (len >= elem_size && elem_count > 0) {
   1785 				sysctl_fillbuf(bp, &bs);
   1786 				mutex_exit(&bufcache_lock);
   1787 				error = copyout(&bs, dp, out_size);
   1788 				mutex_enter(&bufcache_lock);
   1789 				if (error)
   1790 					break;
   1791 				if (bq->bq_marker != bp) {
   1792 					/*
   1793 					 * This sysctl node is only for
   1794 					 * statistics.  Retry; if the
   1795 					 * queue keeps changing, then
   1796 					 * bail out.
   1797 					 */
   1798 					if (retries-- == 0) {
   1799 						error = EAGAIN;
   1800 						break;
   1801 					}
   1802 					mutex_exit(&bufcache_lock);
   1803 					sysctl_relock();
   1804 					goto retry;
   1805 				}
   1806 				dp += elem_size;
   1807 				len -= elem_size;
   1808 			}
   1809 			needed += elem_size;
   1810 			if (elem_count > 0 && elem_count != INT_MAX)
   1811 				elem_count--;
   1812 		}
   1813 		if (error != 0)
   1814 			break;
   1815 	}
   1816 	mutex_exit(&bufcache_lock);
   1817 	sysctl_relock();
   1818 
   1819 	*oldlenp = needed;
   1820 	if (oldp == NULL)
   1821 		*oldlenp += KERN_BUFSLOP * sizeof(buf_t);
   1822 
   1823 	return (error);
   1824 }
   1825 
   1826 static int
   1827 sysctl_bufvm_update(SYSCTLFN_ARGS)
   1828 {
   1829 	int error, rv;
   1830 	struct sysctlnode node;
   1831 	unsigned int temp_bufcache;
   1832 	unsigned long temp_water;
   1833 
   1834 	/* Take a copy of the supplied node and its data */
   1835 	node = *rnode;
   1836 	if (node.sysctl_data == &bufcache) {
   1837 	    node.sysctl_data = &temp_bufcache;
   1838 	    temp_bufcache = *(unsigned int *)rnode->sysctl_data;
   1839 	} else {
   1840 	    node.sysctl_data = &temp_water;
   1841 	    temp_water = *(unsigned long *)rnode->sysctl_data;
   1842 	}
   1843 
   1844 	/* Update the copy */
   1845 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1846 	if (error || newp == NULL)
   1847 		return (error);
   1848 
   1849 	if (rnode->sysctl_data == &bufcache) {
   1850 		if (temp_bufcache > 100)
   1851 			return (EINVAL);
   1852 		bufcache = temp_bufcache;
   1853 		buf_setwm();
   1854 	} else if (rnode->sysctl_data == &bufmem_lowater) {
   1855 		if (bufmem_hiwater - temp_water < 16)
   1856 			return (EINVAL);
   1857 		bufmem_lowater = temp_water;
   1858 	} else if (rnode->sysctl_data == &bufmem_hiwater) {
   1859 		if (temp_water - bufmem_lowater < 16)
   1860 			return (EINVAL);
   1861 		bufmem_hiwater = temp_water;
   1862 	} else
   1863 		return (EINVAL);
   1864 
   1865 	/* Drain until below new high water mark */
   1866 	sysctl_unlock();
   1867 	mutex_enter(&bufcache_lock);
   1868 	while (bufmem > bufmem_hiwater) {
   1869 		rv = buf_drain((bufmem - bufmem_hiwater) / (2 * 1024));
   1870 		if (rv <= 0)
   1871 			break;
   1872 	}
   1873 	mutex_exit(&bufcache_lock);
   1874 	sysctl_relock();
   1875 
   1876 	return 0;
   1877 }
   1878 
   1879 static struct sysctllog *vfsbio_sysctllog;
   1880 
   1881 static void
   1882 sysctl_kern_buf_setup(void)
   1883 {
   1884 
   1885 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1886 		       CTLFLAG_PERMANENT,
   1887 		       CTLTYPE_NODE, "buf",
   1888 		       SYSCTL_DESCR("Kernel buffer cache information"),
   1889 		       sysctl_dobuf, 0, NULL, 0,
   1890 		       CTL_KERN, KERN_BUF, CTL_EOL);
   1891 }
   1892 
   1893 static void
   1894 sysctl_vm_buf_setup(void)
   1895 {
   1896 
   1897 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1898 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1899 		       CTLTYPE_INT, "bufcache",
   1900 		       SYSCTL_DESCR("Percentage of physical memory to use for "
   1901 				    "buffer cache"),
   1902 		       sysctl_bufvm_update, 0, &bufcache, 0,
   1903 		       CTL_VM, CTL_CREATE, CTL_EOL);
   1904 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1905 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
   1906 		       CTLTYPE_LONG, "bufmem",
   1907 		       SYSCTL_DESCR("Amount of kernel memory used by buffer "
   1908 				    "cache"),
   1909 		       NULL, 0, &bufmem, 0,
   1910 		       CTL_VM, CTL_CREATE, CTL_EOL);
   1911 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1912 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1913 		       CTLTYPE_LONG, "bufmem_lowater",
   1914 		       SYSCTL_DESCR("Minimum amount of kernel memory to "
   1915 				    "reserve for buffer cache"),
   1916 		       sysctl_bufvm_update, 0, &bufmem_lowater, 0,
   1917 		       CTL_VM, CTL_CREATE, CTL_EOL);
   1918 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1919 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1920 		       CTLTYPE_LONG, "bufmem_hiwater",
   1921 		       SYSCTL_DESCR("Maximum amount of kernel memory to use "
   1922 				    "for buffer cache"),
   1923 		       sysctl_bufvm_update, 0, &bufmem_hiwater, 0,
   1924 		       CTL_VM, CTL_CREATE, CTL_EOL);
   1925 }
   1926 
   1927 #ifdef DEBUG
   1928 /*
   1929  * Print out statistics on the current allocation of the buffer pool.
   1930  * Can be enabled to print out on every ``sync'' by setting "syncprt"
   1931  * in vfs_syscalls.c using sysctl.
   1932  */
   1933 void
   1934 vfs_bufstats(void)
   1935 {
   1936 	int i, j, count;
   1937 	buf_t *bp;
   1938 	struct bqueue *dp;
   1939 	int counts[MAXBSIZE / MIN_PAGE_SIZE + 1];
   1940 	static const char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE" };
   1941 
   1942 	for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
   1943 		count = 0;
   1944 		memset(counts, 0, sizeof(counts));
   1945 		TAILQ_FOREACH(bp, &dp->bq_queue, b_freelist) {
   1946 			counts[bp->b_bufsize / PAGE_SIZE]++;
   1947 			count++;
   1948 		}
   1949 		printf("%s: total-%d", bname[i], count);
   1950 		for (j = 0; j <= MAXBSIZE / PAGE_SIZE; j++)
   1951 			if (counts[j] != 0)
   1952 				printf(", %d-%d", j * PAGE_SIZE, counts[j]);
   1953 		printf("\n");
   1954 	}
   1955 }
   1956 #endif /* DEBUG */
   1957 
   1958 /* ------------------------------ */
   1959 
   1960 buf_t *
   1961 getiobuf(struct vnode *vp, bool waitok)
   1962 {
   1963 	buf_t *bp;
   1964 
   1965 	bp = pool_cache_get(bufio_cache, (waitok ? PR_WAITOK : PR_NOWAIT));
   1966 	if (bp == NULL)
   1967 		return bp;
   1968 
   1969 	buf_init(bp);
   1970 
   1971 	if ((bp->b_vp = vp) != NULL) {
   1972 		bp->b_objlock = vp->v_interlock;
   1973 	} else {
   1974 		KASSERT(bp->b_objlock == &buffer_lock);
   1975 	}
   1976 
   1977 	return bp;
   1978 }
   1979 
   1980 void
   1981 putiobuf(buf_t *bp)
   1982 {
   1983 
   1984 	buf_destroy(bp);
   1985 	pool_cache_put(bufio_cache, bp);
   1986 }
   1987 
   1988 /*
   1989  * nestiobuf_iodone: b_iodone callback for nested buffers.
   1990  */
   1991 
   1992 void
   1993 nestiobuf_iodone(buf_t *bp)
   1994 {
   1995 	buf_t *mbp = bp->b_private;
   1996 	int error;
   1997 	int donebytes;
   1998 
   1999 	KASSERT(bp->b_bcount <= bp->b_bufsize);
   2000 	KASSERT(mbp != bp);
   2001 
   2002 	error = bp->b_error;
   2003 	if (bp->b_error == 0 &&
   2004 	    (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
   2005 		/*
   2006 		 * Not all got transfered, raise an error. We have no way to
   2007 		 * propagate these conditions to mbp.
   2008 		 */
   2009 		error = EIO;
   2010 	}
   2011 
   2012 	donebytes = bp->b_bufsize;
   2013 
   2014 	putiobuf(bp);
   2015 	nestiobuf_done(mbp, donebytes, error);
   2016 }
   2017 
   2018 /*
   2019  * nestiobuf_setup: setup a "nested" buffer.
   2020  *
   2021  * => 'mbp' is a "master" buffer which is being divided into sub pieces.
   2022  * => 'bp' should be a buffer allocated by getiobuf.
   2023  * => 'offset' is a byte offset in the master buffer.
   2024  * => 'size' is a size in bytes of this nested buffer.
   2025  */
   2026 
   2027 void
   2028 nestiobuf_setup(buf_t *mbp, buf_t *bp, int offset, size_t size)
   2029 {
   2030 	const int b_pass = mbp->b_flags & (B_READ|B_MEDIA_FLAGS);
   2031 	struct vnode *vp = mbp->b_vp;
   2032 
   2033 	KASSERT(mbp->b_bcount >= offset + size);
   2034 	bp->b_vp = vp;
   2035 	bp->b_dev = mbp->b_dev;
   2036 	bp->b_objlock = mbp->b_objlock;
   2037 	bp->b_cflags = BC_BUSY;
   2038 	bp->b_flags = B_ASYNC | b_pass;
   2039 	bp->b_iodone = nestiobuf_iodone;
   2040 	bp->b_data = (char *)mbp->b_data + offset;
   2041 	bp->b_resid = bp->b_bcount = size;
   2042 	bp->b_bufsize = bp->b_bcount;
   2043 	bp->b_private = mbp;
   2044 	BIO_COPYPRIO(bp, mbp);
   2045 	if (BUF_ISWRITE(bp) && vp != NULL) {
   2046 		mutex_enter(vp->v_interlock);
   2047 		vp->v_numoutput++;
   2048 		mutex_exit(vp->v_interlock);
   2049 	}
   2050 }
   2051 
   2052 /*
   2053  * nestiobuf_done: propagate completion to the master buffer.
   2054  *
   2055  * => 'donebytes' specifies how many bytes in the 'mbp' is completed.
   2056  * => 'error' is an errno(2) that 'donebytes' has been completed with.
   2057  */
   2058 
   2059 void
   2060 nestiobuf_done(buf_t *mbp, int donebytes, int error)
   2061 {
   2062 
   2063 	if (donebytes == 0) {
   2064 		return;
   2065 	}
   2066 	mutex_enter(mbp->b_objlock);
   2067 	KASSERT(mbp->b_resid >= donebytes);
   2068 	mbp->b_resid -= donebytes;
   2069 	if (error)
   2070 		mbp->b_error = error;
   2071 	if (mbp->b_resid == 0) {
   2072 		if (mbp->b_error)
   2073 			mbp->b_resid = mbp->b_bcount;
   2074 		mutex_exit(mbp->b_objlock);
   2075 		biodone(mbp);
   2076 	} else
   2077 		mutex_exit(mbp->b_objlock);
   2078 }
   2079 
   2080 void
   2081 buf_init(buf_t *bp)
   2082 {
   2083 
   2084 	cv_init(&bp->b_busy, "biolock");
   2085 	cv_init(&bp->b_done, "biowait");
   2086 	bp->b_dev = NODEV;
   2087 	bp->b_error = 0;
   2088 	bp->b_flags = 0;
   2089 	bp->b_cflags = 0;
   2090 	bp->b_oflags = 0;
   2091 	bp->b_objlock = &buffer_lock;
   2092 	bp->b_iodone = NULL;
   2093 	bp->b_refcnt = 1;
   2094 	bp->b_dev = NODEV;
   2095 	bp->b_vnbufs.le_next = NOLIST;
   2096 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   2097 }
   2098 
   2099 void
   2100 buf_destroy(buf_t *bp)
   2101 {
   2102 
   2103 	cv_destroy(&bp->b_done);
   2104 	cv_destroy(&bp->b_busy);
   2105 }
   2106 
   2107 int
   2108 bbusy(buf_t *bp, bool intr, int timo, kmutex_t *interlock)
   2109 {
   2110 	int error;
   2111 
   2112 	KASSERT(mutex_owned(&bufcache_lock));
   2113 
   2114 	if ((bp->b_cflags & BC_BUSY) != 0) {
   2115 		if (curlwp == uvm.pagedaemon_lwp)
   2116 			return EDEADLK;
   2117 		bp->b_cflags |= BC_WANTED;
   2118 		bref(bp);
   2119 		if (interlock != NULL)
   2120 			mutex_exit(interlock);
   2121 		if (intr) {
   2122 			error = cv_timedwait_sig(&bp->b_busy, &bufcache_lock,
   2123 			    timo);
   2124 		} else {
   2125 			error = cv_timedwait(&bp->b_busy, &bufcache_lock,
   2126 			    timo);
   2127 		}
   2128 		brele(bp);
   2129 		if (interlock != NULL)
   2130 			mutex_enter(interlock);
   2131 		if (error != 0)
   2132 			return error;
   2133 		return EPASSTHROUGH;
   2134 	}
   2135 	bp->b_cflags |= BC_BUSY;
   2136 
   2137 	return 0;
   2138 }
   2139