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