Home | History | Annotate | Line # | Download | only in kern
vfs_bio.c revision 1.282
      1 /*	$NetBSD: vfs_bio.c,v 1.282 2019/12/08 20:35:23 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.282 2019/12/08 20:35:23 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 		/* Wake anyone trying to busy the buffer via vnode's lists. */
    900 		cv_broadcast(&bp->b_busy);
    901 		mutex_exit(&bufcache_lock);
    902 	} else {
    903 		curlwp->l_ru.ru_oublock++;
    904 		mutex_enter(bp->b_objlock);
    905 		CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
    906 	}
    907 	if (vp != NULL)
    908 		vp->v_numoutput++;
    909 	mutex_exit(bp->b_objlock);
    910 
    911 	/* Initiate disk write. */
    912 	if (sync)
    913 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
    914 	else
    915 		BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
    916 
    917 	VOP_STRATEGY(vp, bp);
    918 
    919 	if (sync) {
    920 		/* If I/O was synchronous, wait for it to complete. */
    921 		rv = biowait(bp);
    922 
    923 		/* Release the buffer. */
    924 		brelse(bp, 0);
    925 
    926 		return (rv);
    927 	} else {
    928 		return (0);
    929 	}
    930 }
    931 
    932 int
    933 vn_bwrite(void *v)
    934 {
    935 	struct vop_bwrite_args *ap = v;
    936 
    937 	return (bwrite(ap->a_bp));
    938 }
    939 
    940 /*
    941  * Delayed write.
    942  *
    943  * The buffer is marked dirty, but is not queued for I/O.
    944  * This routine should be used when the buffer is expected
    945  * to be modified again soon, typically a small write that
    946  * partially fills a buffer.
    947  *
    948  * NB: magnetic tapes cannot be delayed; they must be
    949  * written in the order that the writes are requested.
    950  *
    951  * Described in Leffler, et al. (pp. 208-213).
    952  */
    953 void
    954 bdwrite(buf_t *bp)
    955 {
    956 
    957 	BIOHIST_FUNC(__func__); BIOHIST_CALLARGS(biohist, "bp=%#jx",
    958 	    (uintptr_t)bp, 0, 0, 0);
    959 
    960 	KASSERT(bp->b_vp == NULL || bp->b_vp->v_tag != VT_UFS ||
    961 	    bp->b_vp->v_type == VBLK || ISSET(bp->b_flags, B_COWDONE));
    962 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
    963 	KASSERT(!cv_has_waiters(&bp->b_done));
    964 
    965 	/* If this is a tape block, write the block now. */
    966 	if (bdev_type(bp->b_dev) == D_TAPE) {
    967 		bawrite(bp);
    968 		return;
    969 	}
    970 
    971 	if (wapbl_vphaswapbl(bp->b_vp)) {
    972 		struct mount *mp = wapbl_vptomp(bp->b_vp);
    973 
    974 		if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
    975 			WAPBL_ADD_BUF(mp, bp);
    976 		}
    977 	}
    978 
    979 	/*
    980 	 * If the block hasn't been seen before:
    981 	 *	(1) Mark it as having been seen,
    982 	 *	(2) Charge for the write,
    983 	 *	(3) Make sure it's on its vnode's correct block list.
    984 	 */
    985 	KASSERT(bp->b_vp == NULL || bp->b_objlock == bp->b_vp->v_interlock);
    986 
    987 	if (!ISSET(bp->b_oflags, BO_DELWRI)) {
    988 		mutex_enter(&bufcache_lock);
    989 		mutex_enter(bp->b_objlock);
    990 		SET(bp->b_oflags, BO_DELWRI);
    991 		curlwp->l_ru.ru_oublock++;
    992 		reassignbuf(bp, bp->b_vp);
    993 		/* Wake anyone trying to busy the buffer via vnode's lists. */
    994 		cv_broadcast(&bp->b_busy);
    995 		mutex_exit(&bufcache_lock);
    996 	} else {
    997 		mutex_enter(bp->b_objlock);
    998 	}
    999 	/* Otherwise, the "write" is done, so mark and release the buffer. */
   1000 	CLR(bp->b_oflags, BO_DONE);
   1001 	mutex_exit(bp->b_objlock);
   1002 
   1003 	brelse(bp, 0);
   1004 }
   1005 
   1006 /*
   1007  * Asynchronous block write; just an asynchronous bwrite().
   1008  */
   1009 void
   1010 bawrite(buf_t *bp)
   1011 {
   1012 
   1013 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
   1014 	KASSERT(bp->b_vp != NULL);
   1015 
   1016 	SET(bp->b_flags, B_ASYNC);
   1017 	VOP_BWRITE(bp->b_vp, bp);
   1018 }
   1019 
   1020 /*
   1021  * Release a buffer on to the free lists.
   1022  * Described in Bach (p. 46).
   1023  */
   1024 void
   1025 brelsel(buf_t *bp, int set)
   1026 {
   1027 	struct bqueue *bufq;
   1028 	struct vnode *vp;
   1029 
   1030 	KASSERT(bp != NULL);
   1031 	KASSERT(mutex_owned(&bufcache_lock));
   1032 	KASSERT(!cv_has_waiters(&bp->b_done));
   1033 	KASSERT(bp->b_refcnt > 0);
   1034 
   1035 	SET(bp->b_cflags, set);
   1036 
   1037 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
   1038 	KASSERT(bp->b_iodone == NULL);
   1039 
   1040 	/* Wake up any processes waiting for any buffer to become free. */
   1041 	cv_signal(&needbuffer_cv);
   1042 
   1043 	/* Wake up any proceeses waiting for _this_ buffer to become free */
   1044 	if (ISSET(bp->b_cflags, BC_WANTED))
   1045 		CLR(bp->b_cflags, BC_WANTED|BC_AGE);
   1046 
   1047 	/* If it's clean clear the copy-on-write flag. */
   1048 	if (ISSET(bp->b_flags, B_COWDONE)) {
   1049 		mutex_enter(bp->b_objlock);
   1050 		if (!ISSET(bp->b_oflags, BO_DELWRI))
   1051 			CLR(bp->b_flags, B_COWDONE);
   1052 		mutex_exit(bp->b_objlock);
   1053 	}
   1054 
   1055 	/*
   1056 	 * Determine which queue the buffer should be on, then put it there.
   1057 	 */
   1058 
   1059 	/* If it's locked, don't report an error; try again later. */
   1060 	if (ISSET(bp->b_flags, B_LOCKED))
   1061 		bp->b_error = 0;
   1062 
   1063 	/* If it's not cacheable, or an error, mark it invalid. */
   1064 	if (ISSET(bp->b_cflags, BC_NOCACHE) || bp->b_error != 0)
   1065 		SET(bp->b_cflags, BC_INVAL);
   1066 
   1067 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
   1068 		/*
   1069 		 * This is a delayed write buffer that was just flushed to
   1070 		 * disk.  It is still on the LRU queue.  If it's become
   1071 		 * invalid, then we need to move it to a different queue;
   1072 		 * otherwise leave it in its current position.
   1073 		 */
   1074 		CLR(bp->b_cflags, BC_VFLUSH);
   1075 		if (!ISSET(bp->b_cflags, BC_INVAL|BC_AGE) &&
   1076 		    !ISSET(bp->b_flags, B_LOCKED) && bp->b_error == 0) {
   1077 			KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 1));
   1078 			goto already_queued;
   1079 		} else {
   1080 			bremfree(bp);
   1081 		}
   1082 	}
   1083 
   1084 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_AGE], 0));
   1085 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 0));
   1086 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LOCKED], 0));
   1087 
   1088 	if ((bp->b_bufsize <= 0) || ISSET(bp->b_cflags, BC_INVAL)) {
   1089 		/*
   1090 		 * If it's invalid or empty, dissociate it from its vnode
   1091 		 * and put on the head of the appropriate queue.
   1092 		 */
   1093 		if (ISSET(bp->b_flags, B_LOCKED)) {
   1094 			if (wapbl_vphaswapbl(vp = bp->b_vp)) {
   1095 				struct mount *mp = wapbl_vptomp(vp);
   1096 
   1097 				KASSERT(bp->b_iodone
   1098 				    != mp->mnt_wapbl_op->wo_wapbl_biodone);
   1099 				WAPBL_REMOVE_BUF(mp, bp);
   1100 			}
   1101 		}
   1102 
   1103 		mutex_enter(bp->b_objlock);
   1104 		CLR(bp->b_oflags, BO_DONE|BO_DELWRI);
   1105 		if ((vp = bp->b_vp) != NULL) {
   1106 			KASSERT(bp->b_objlock == vp->v_interlock);
   1107 			reassignbuf(bp, bp->b_vp);
   1108 			brelvp(bp);
   1109 			mutex_exit(vp->v_interlock);
   1110 		} else {
   1111 			KASSERT(bp->b_objlock == &buffer_lock);
   1112 			mutex_exit(bp->b_objlock);
   1113 		}
   1114 		/* We want to dispose of the buffer, so wake everybody. */
   1115 		cv_broadcast(&bp->b_busy);
   1116 		if (bp->b_bufsize <= 0)
   1117 			/* no data */
   1118 			goto already_queued;
   1119 		else
   1120 			/* invalid data */
   1121 			bufq = &bufqueues[BQ_AGE];
   1122 		binsheadfree(bp, bufq);
   1123 	} else  {
   1124 		/*
   1125 		 * It has valid data.  Put it on the end of the appropriate
   1126 		 * queue, so that it'll stick around for as long as possible.
   1127 		 * If buf is AGE, but has dependencies, must put it on last
   1128 		 * bufqueue to be scanned, ie LRU. This protects against the
   1129 		 * livelock where BQ_AGE only has buffers with dependencies,
   1130 		 * and we thus never get to the dependent buffers in BQ_LRU.
   1131 		 */
   1132 		if (ISSET(bp->b_flags, B_LOCKED)) {
   1133 			/* locked in core */
   1134 			bufq = &bufqueues[BQ_LOCKED];
   1135 		} else if (!ISSET(bp->b_cflags, BC_AGE)) {
   1136 			/* valid data */
   1137 			bufq = &bufqueues[BQ_LRU];
   1138 		} else {
   1139 			/* stale but valid data */
   1140 			bufq = &bufqueues[BQ_AGE];
   1141 		}
   1142 		binstailfree(bp, bufq);
   1143 	}
   1144 already_queued:
   1145 	/* Unlock the buffer. */
   1146 	CLR(bp->b_cflags, BC_AGE|BC_BUSY|BC_NOCACHE);
   1147 	CLR(bp->b_flags, B_ASYNC);
   1148 	cv_signal(&bp->b_busy);
   1149 
   1150 	if (bp->b_bufsize <= 0)
   1151 		brele(bp);
   1152 }
   1153 
   1154 void
   1155 brelse(buf_t *bp, int set)
   1156 {
   1157 
   1158 	mutex_enter(&bufcache_lock);
   1159 	brelsel(bp, set);
   1160 	mutex_exit(&bufcache_lock);
   1161 }
   1162 
   1163 /*
   1164  * Determine if a block is in the cache.
   1165  * Just look on what would be its hash chain.  If it's there, return
   1166  * a pointer to it, unless it's marked invalid.  If it's marked invalid,
   1167  * we normally don't return the buffer, unless the caller explicitly
   1168  * wants us to.
   1169  */
   1170 buf_t *
   1171 incore(struct vnode *vp, daddr_t blkno)
   1172 {
   1173 	buf_t *bp;
   1174 
   1175 	KASSERT(mutex_owned(&bufcache_lock));
   1176 
   1177 	/* Search hash chain */
   1178 	LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
   1179 		if (bp->b_lblkno == blkno && bp->b_vp == vp &&
   1180 		    !ISSET(bp->b_cflags, BC_INVAL)) {
   1181 		    	KASSERT(bp->b_objlock == vp->v_interlock);
   1182 		    	return (bp);
   1183 		}
   1184 	}
   1185 
   1186 	return (NULL);
   1187 }
   1188 
   1189 /*
   1190  * Get a block of requested size that is associated with
   1191  * a given vnode and block offset. If it is found in the
   1192  * block cache, mark it as having been found, make it busy
   1193  * and return it. Otherwise, return an empty block of the
   1194  * correct size. It is up to the caller to insure that the
   1195  * cached blocks be of the correct size.
   1196  */
   1197 buf_t *
   1198 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo)
   1199 {
   1200 	int err, preserve;
   1201 	buf_t *bp;
   1202 
   1203 	mutex_enter(&bufcache_lock);
   1204  loop:
   1205 	bp = incore(vp, blkno);
   1206 	if (bp != NULL) {
   1207 		err = bbusy(bp, ((slpflag & PCATCH) != 0), slptimeo, NULL);
   1208 		if (err != 0) {
   1209 			if (err == EPASSTHROUGH)
   1210 				goto loop;
   1211 			mutex_exit(&bufcache_lock);
   1212 			return (NULL);
   1213 		}
   1214 		KASSERT(!cv_has_waiters(&bp->b_done));
   1215 #ifdef DIAGNOSTIC
   1216 		if (ISSET(bp->b_oflags, BO_DONE|BO_DELWRI) &&
   1217 		    bp->b_bcount < size && vp->v_type != VBLK)
   1218 			panic("getblk: block size invariant failed");
   1219 #endif
   1220 		bremfree(bp);
   1221 		preserve = 1;
   1222 	} else {
   1223 		if ((bp = getnewbuf(slpflag, slptimeo, 0)) == NULL)
   1224 			goto loop;
   1225 
   1226 		if (incore(vp, blkno) != NULL) {
   1227 			/* The block has come into memory in the meantime. */
   1228 			brelsel(bp, 0);
   1229 			goto loop;
   1230 		}
   1231 
   1232 		LIST_INSERT_HEAD(BUFHASH(vp, blkno), bp, b_hash);
   1233 		bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
   1234 		mutex_enter(vp->v_interlock);
   1235 		bgetvp(vp, bp);
   1236 		mutex_exit(vp->v_interlock);
   1237 		preserve = 0;
   1238 	}
   1239 	mutex_exit(&bufcache_lock);
   1240 
   1241 	/*
   1242 	 * LFS can't track total size of B_LOCKED buffer (locked_queue_bytes)
   1243 	 * if we re-size buffers here.
   1244 	 */
   1245 	if (ISSET(bp->b_flags, B_LOCKED)) {
   1246 		KASSERT(bp->b_bufsize >= size);
   1247 	} else {
   1248 		if (allocbuf(bp, size, preserve)) {
   1249 			mutex_enter(&bufcache_lock);
   1250 			LIST_REMOVE(bp, b_hash);
   1251 			brelsel(bp, BC_INVAL);
   1252 			mutex_exit(&bufcache_lock);
   1253 			return NULL;
   1254 		}
   1255 	}
   1256 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   1257 	return (bp);
   1258 }
   1259 
   1260 /*
   1261  * Get an empty, disassociated buffer of given size.
   1262  */
   1263 buf_t *
   1264 geteblk(int size)
   1265 {
   1266 	buf_t *bp;
   1267 	int error __diagused;
   1268 
   1269 	mutex_enter(&bufcache_lock);
   1270 	while ((bp = getnewbuf(0, 0, 0)) == NULL)
   1271 		;
   1272 
   1273 	SET(bp->b_cflags, BC_INVAL);
   1274 	LIST_INSERT_HEAD(&invalhash, bp, b_hash);
   1275 	mutex_exit(&bufcache_lock);
   1276 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   1277 	error = allocbuf(bp, size, 0);
   1278 	KASSERT(error == 0);
   1279 	return (bp);
   1280 }
   1281 
   1282 /*
   1283  * Expand or contract the actual memory allocated to a buffer.
   1284  *
   1285  * If the buffer shrinks, data is lost, so it's up to the
   1286  * caller to have written it out *first*; this routine will not
   1287  * start a write.  If the buffer grows, it's the callers
   1288  * responsibility to fill out the buffer's additional contents.
   1289  */
   1290 int
   1291 allocbuf(buf_t *bp, int size, int preserve)
   1292 {
   1293 	void *addr;
   1294 	vsize_t oldsize, desired_size;
   1295 	int oldcount;
   1296 	int delta;
   1297 
   1298 	desired_size = buf_roundsize(size);
   1299 	if (desired_size > MAXBSIZE)
   1300 		printf("allocbuf: buffer larger than MAXBSIZE requested");
   1301 
   1302 	oldcount = bp->b_bcount;
   1303 
   1304 	bp->b_bcount = size;
   1305 
   1306 	oldsize = bp->b_bufsize;
   1307 	if (oldsize == desired_size) {
   1308 		/*
   1309 		 * Do not short cut the WAPBL resize, as the buffer length
   1310 		 * could still have changed and this would corrupt the
   1311 		 * tracking of the transaction length.
   1312 		 */
   1313 		goto out;
   1314 	}
   1315 
   1316 	/*
   1317 	 * If we want a buffer of a different size, re-allocate the
   1318 	 * buffer's memory; copy old content only if needed.
   1319 	 */
   1320 	addr = buf_alloc(desired_size);
   1321 	if (addr == NULL)
   1322 		return ENOMEM;
   1323 	if (preserve)
   1324 		memcpy(addr, bp->b_data, MIN(oldsize,desired_size));
   1325 	if (bp->b_data != NULL)
   1326 		buf_mrelease(bp->b_data, oldsize);
   1327 	bp->b_data = addr;
   1328 	bp->b_bufsize = desired_size;
   1329 
   1330 	/*
   1331 	 * Update overall buffer memory counter (protected by bufcache_lock)
   1332 	 */
   1333 	delta = (long)desired_size - (long)oldsize;
   1334 
   1335 	mutex_enter(&bufcache_lock);
   1336 	if ((bufmem += delta) > bufmem_hiwater) {
   1337 		/*
   1338 		 * Need to trim overall memory usage.
   1339 		 */
   1340 		while (buf_canrelease()) {
   1341 			if (curcpu()->ci_schedstate.spc_flags &
   1342 			    SPCF_SHOULDYIELD) {
   1343 				mutex_exit(&bufcache_lock);
   1344 				preempt();
   1345 				mutex_enter(&bufcache_lock);
   1346 			}
   1347 			if (buf_trim() == 0)
   1348 				break;
   1349 		}
   1350 	}
   1351 	mutex_exit(&bufcache_lock);
   1352 
   1353  out:
   1354 	if (wapbl_vphaswapbl(bp->b_vp))
   1355 		WAPBL_RESIZE_BUF(wapbl_vptomp(bp->b_vp), bp, oldsize, oldcount);
   1356 
   1357 	return 0;
   1358 }
   1359 
   1360 /*
   1361  * Find a buffer which is available for use.
   1362  * Select something from a free list.
   1363  * Preference is to AGE list, then LRU list.
   1364  *
   1365  * Called with the buffer queues locked.
   1366  * Return buffer locked.
   1367  */
   1368 static buf_t *
   1369 getnewbuf(int slpflag, int slptimeo, int from_bufq)
   1370 {
   1371 	buf_t *bp;
   1372 	struct vnode *vp;
   1373 	struct mount *transmp = NULL;
   1374 
   1375  start:
   1376 	KASSERT(mutex_owned(&bufcache_lock));
   1377 
   1378 	/*
   1379 	 * Get a new buffer from the pool.
   1380 	 */
   1381 	if (!from_bufq && buf_lotsfree()) {
   1382 		mutex_exit(&bufcache_lock);
   1383 		bp = pool_cache_get(buf_cache, PR_NOWAIT);
   1384 		if (bp != NULL) {
   1385 			memset((char *)bp, 0, sizeof(*bp));
   1386 			buf_init(bp);
   1387 			SET(bp->b_cflags, BC_BUSY);	/* mark buffer busy */
   1388 			mutex_enter(&bufcache_lock);
   1389 #if defined(DIAGNOSTIC)
   1390 			bp->b_freelistindex = -1;
   1391 #endif /* defined(DIAGNOSTIC) */
   1392 			return (bp);
   1393 		}
   1394 		mutex_enter(&bufcache_lock);
   1395 	}
   1396 
   1397 	KASSERT(mutex_owned(&bufcache_lock));
   1398 	if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue)) != NULL) {
   1399 		KASSERT(!ISSET(bp->b_oflags, BO_DELWRI));
   1400 	} else {
   1401 		TAILQ_FOREACH(bp, &bufqueues[BQ_LRU].bq_queue, b_freelist) {
   1402 			if (ISSET(bp->b_cflags, BC_VFLUSH) ||
   1403 			    !ISSET(bp->b_oflags, BO_DELWRI))
   1404 				break;
   1405 			if (fstrans_start_nowait(bp->b_vp->v_mount) == 0) {
   1406 				KASSERT(transmp == NULL);
   1407 				transmp = bp->b_vp->v_mount;
   1408 				break;
   1409 			}
   1410 		}
   1411 	}
   1412 	if (bp != NULL) {
   1413 	    	KASSERT(!ISSET(bp->b_cflags, BC_BUSY) || ISSET(bp->b_cflags, BC_VFLUSH));
   1414 		bremfree(bp);
   1415 
   1416 		/* Buffer is no longer on free lists. */
   1417 		SET(bp->b_cflags, BC_BUSY);
   1418 
   1419 		/* Wake anyone trying to lock the old identity. */
   1420 		cv_broadcast(&bp->b_busy);
   1421 	} else {
   1422 		/*
   1423 		 * XXX: !from_bufq should be removed.
   1424 		 */
   1425 		if (!from_bufq || curlwp != uvm.pagedaemon_lwp) {
   1426 			/* wait for a free buffer of any kind */
   1427 			if ((slpflag & PCATCH) != 0)
   1428 				(void)cv_timedwait_sig(&needbuffer_cv,
   1429 				    &bufcache_lock, slptimeo);
   1430 			else
   1431 				(void)cv_timedwait(&needbuffer_cv,
   1432 				    &bufcache_lock, slptimeo);
   1433 		}
   1434 		return (NULL);
   1435 	}
   1436 
   1437 #ifdef DIAGNOSTIC
   1438 	if (bp->b_bufsize <= 0)
   1439 		panic("buffer %p: on queue but empty", bp);
   1440 #endif
   1441 
   1442 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
   1443 		/*
   1444 		 * This is a delayed write buffer being flushed to disk.  Make
   1445 		 * sure it gets aged out of the queue when it's finished, and
   1446 		 * leave it off the LRU queue.
   1447 		 */
   1448 		CLR(bp->b_cflags, BC_VFLUSH);
   1449 		SET(bp->b_cflags, BC_AGE);
   1450 		goto start;
   1451 	}
   1452 
   1453 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
   1454 	KASSERT(bp->b_refcnt > 0);
   1455     	KASSERT(!cv_has_waiters(&bp->b_done));
   1456 
   1457 	/*
   1458 	 * If buffer was a delayed write, start it and return NULL
   1459 	 * (since we might sleep while starting the write).
   1460 	 */
   1461 	if (ISSET(bp->b_oflags, BO_DELWRI)) {
   1462 		/*
   1463 		 * This buffer has gone through the LRU, so make sure it gets
   1464 		 * reused ASAP.
   1465 		 */
   1466 		SET(bp->b_cflags, BC_AGE);
   1467 		mutex_exit(&bufcache_lock);
   1468 		bawrite(bp);
   1469 		KASSERT(transmp != NULL);
   1470 		fstrans_done(transmp);
   1471 		mutex_enter(&bufcache_lock);
   1472 		return (NULL);
   1473 	}
   1474 
   1475 	KASSERT(transmp == NULL);
   1476 
   1477 	vp = bp->b_vp;
   1478 
   1479 	/* clear out various other fields */
   1480 	bp->b_cflags = BC_BUSY;
   1481 	bp->b_oflags = 0;
   1482 	bp->b_flags = 0;
   1483 	bp->b_dev = NODEV;
   1484 	bp->b_blkno = 0;
   1485 	bp->b_lblkno = 0;
   1486 	bp->b_rawblkno = 0;
   1487 	bp->b_iodone = 0;
   1488 	bp->b_error = 0;
   1489 	bp->b_resid = 0;
   1490 	bp->b_bcount = 0;
   1491 
   1492 	LIST_REMOVE(bp, b_hash);
   1493 
   1494 	/* Disassociate us from our vnode, if we had one... */
   1495 	if (vp != NULL) {
   1496 		mutex_enter(vp->v_interlock);
   1497 		brelvp(bp);
   1498 		mutex_exit(vp->v_interlock);
   1499 	}
   1500 
   1501 	return (bp);
   1502 }
   1503 
   1504 /*
   1505  * Attempt to free an aged buffer off the queues.
   1506  * Called with queue lock held.
   1507  * Returns the amount of buffer memory freed.
   1508  */
   1509 static int
   1510 buf_trim(void)
   1511 {
   1512 	buf_t *bp;
   1513 	long size;
   1514 
   1515 	KASSERT(mutex_owned(&bufcache_lock));
   1516 
   1517 	/* Instruct getnewbuf() to get buffers off the queues */
   1518 	if ((bp = getnewbuf(PCATCH, 1, 1)) == NULL)
   1519 		return 0;
   1520 
   1521 	KASSERT((bp->b_cflags & BC_WANTED) == 0);
   1522 	size = bp->b_bufsize;
   1523 	bufmem -= size;
   1524 	if (size > 0) {
   1525 		buf_mrelease(bp->b_data, size);
   1526 		bp->b_bcount = bp->b_bufsize = 0;
   1527 	}
   1528 	/* brelse() will return the buffer to the global buffer pool */
   1529 	brelsel(bp, 0);
   1530 	return size;
   1531 }
   1532 
   1533 int
   1534 buf_drain(int n)
   1535 {
   1536 	int size = 0, sz;
   1537 
   1538 	KASSERT(mutex_owned(&bufcache_lock));
   1539 
   1540 	while (size < n && bufmem > bufmem_lowater) {
   1541 		sz = buf_trim();
   1542 		if (sz <= 0)
   1543 			break;
   1544 		size += sz;
   1545 	}
   1546 
   1547 	return size;
   1548 }
   1549 
   1550 SDT_PROVIDER_DEFINE(io);
   1551 
   1552 SDT_PROBE_DEFINE1(io, kernel, , wait__start, "struct buf *"/*bp*/);
   1553 SDT_PROBE_DEFINE1(io, kernel, , wait__done, "struct buf *"/*bp*/);
   1554 
   1555 /*
   1556  * Wait for operations on the buffer to complete.
   1557  * When they do, extract and return the I/O's error value.
   1558  */
   1559 int
   1560 biowait(buf_t *bp)
   1561 {
   1562 
   1563 	BIOHIST_FUNC(__func__);
   1564 
   1565 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
   1566 	KASSERT(bp->b_refcnt > 0);
   1567 
   1568 	SDT_PROBE1(io, kernel, , wait__start, bp);
   1569 
   1570 	mutex_enter(bp->b_objlock);
   1571 
   1572 	BIOHIST_CALLARGS(biohist, "bp=%#jx, oflags=0x%jx, ret_addr=%#jx",
   1573 	    (uintptr_t)bp, bp->b_oflags,
   1574 	    (uintptr_t)__builtin_return_address(0), 0);
   1575 
   1576 	while (!ISSET(bp->b_oflags, BO_DONE | BO_DELWRI)) {
   1577 		BIOHIST_LOG(biohist, "waiting bp=%#jx", (uintptr_t)bp, 0, 0, 0);
   1578 		cv_wait(&bp->b_done, bp->b_objlock);
   1579 	}
   1580 	mutex_exit(bp->b_objlock);
   1581 
   1582 	SDT_PROBE1(io, kernel, , wait__done, bp);
   1583 
   1584 	BIOHIST_LOG(biohist, "return %jd", bp->b_error, 0, 0, 0);
   1585 
   1586 	return bp->b_error;
   1587 }
   1588 
   1589 /*
   1590  * Mark I/O complete on a buffer.
   1591  *
   1592  * If a callback has been requested, e.g. the pageout
   1593  * daemon, do so. Otherwise, awaken waiting processes.
   1594  *
   1595  * [ Leffler, et al., says on p.247:
   1596  *	"This routine wakes up the blocked process, frees the buffer
   1597  *	for an asynchronous write, or, for a request by the pagedaemon
   1598  *	process, invokes a procedure specified in the buffer structure" ]
   1599  *
   1600  * In real life, the pagedaemon (or other system processes) wants
   1601  * to do async stuff too, and doesn't want the buffer brelse()'d.
   1602  * (for swap pager, that puts swap buffers on the free lists (!!!),
   1603  * for the vn device, that puts allocated buffers on the free lists!)
   1604  */
   1605 void
   1606 biodone(buf_t *bp)
   1607 {
   1608 	int s;
   1609 
   1610 	BIOHIST_FUNC(__func__);
   1611 
   1612 	KASSERT(!ISSET(bp->b_oflags, BO_DONE));
   1613 
   1614 	if (cpu_intr_p()) {
   1615 		/* From interrupt mode: defer to a soft interrupt. */
   1616 		s = splvm();
   1617 		TAILQ_INSERT_TAIL(&curcpu()->ci_data.cpu_biodone, bp, b_actq);
   1618 
   1619 		BIOHIST_CALLARGS(biohist, "bp=%#jx, softint scheduled",
   1620 		    (uintptr_t)bp, 0, 0, 0);
   1621 		softint_schedule(biodone_sih);
   1622 		splx(s);
   1623 	} else {
   1624 		/* Process now - the buffer may be freed soon. */
   1625 		biodone2(bp);
   1626 	}
   1627 }
   1628 
   1629 SDT_PROBE_DEFINE1(io, kernel, , done, "struct buf *"/*bp*/);
   1630 
   1631 static void
   1632 biodone2(buf_t *bp)
   1633 {
   1634 	void (*callout)(buf_t *);
   1635 
   1636 	SDT_PROBE1(io, kernel, ,done, bp);
   1637 
   1638 	BIOHIST_FUNC(__func__);
   1639 	BIOHIST_CALLARGS(biohist, "bp=%#jx", (uintptr_t)bp, 0, 0, 0);
   1640 
   1641 	mutex_enter(bp->b_objlock);
   1642 	/* Note that the transfer is done. */
   1643 	if (ISSET(bp->b_oflags, BO_DONE))
   1644 		panic("biodone2 already");
   1645 	CLR(bp->b_flags, B_COWDONE);
   1646 	SET(bp->b_oflags, BO_DONE);
   1647 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   1648 
   1649 	/* Wake up waiting writers. */
   1650 	if (!ISSET(bp->b_flags, B_READ))
   1651 		vwakeup(bp);
   1652 
   1653 	if ((callout = bp->b_iodone) != NULL) {
   1654 		BIOHIST_LOG(biohist, "callout %#jx", (uintptr_t)callout,
   1655 		    0, 0, 0);
   1656 
   1657 		/* Note callout done, then call out. */
   1658 		KASSERT(!cv_has_waiters(&bp->b_done));
   1659 		KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1660 		bp->b_iodone = NULL;
   1661 		mutex_exit(bp->b_objlock);
   1662 		(*callout)(bp);
   1663 		KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1664 	} else if (ISSET(bp->b_flags, B_ASYNC)) {
   1665 		/* If async, release. */
   1666 		BIOHIST_LOG(biohist, "async", 0, 0, 0, 0);
   1667 		KASSERT(!cv_has_waiters(&bp->b_done));
   1668 		mutex_exit(bp->b_objlock);
   1669 		brelse(bp, 0);
   1670 	} else {
   1671 		/* Otherwise just wake up waiters in biowait(). */
   1672 		BIOHIST_LOG(biohist, "wake-up", 0, 0, 0, 0);
   1673 		cv_broadcast(&bp->b_done);
   1674 		mutex_exit(bp->b_objlock);
   1675 	}
   1676 }
   1677 
   1678 static void
   1679 biointr(void *cookie)
   1680 {
   1681 	struct cpu_info *ci;
   1682 	buf_t *bp;
   1683 	int s;
   1684 
   1685 	BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
   1686 
   1687 	ci = curcpu();
   1688 
   1689 	s = splvm();
   1690 	while (!TAILQ_EMPTY(&ci->ci_data.cpu_biodone)) {
   1691 		KASSERT(curcpu() == ci);
   1692 
   1693 		bp = TAILQ_FIRST(&ci->ci_data.cpu_biodone);
   1694 		TAILQ_REMOVE(&ci->ci_data.cpu_biodone, bp, b_actq);
   1695 		splx(s);
   1696 
   1697 		BIOHIST_LOG(biohist, "bp=%#jx", (uintptr_t)bp, 0, 0, 0);
   1698 		biodone2(bp);
   1699 
   1700 		s = splvm();
   1701 	}
   1702 	splx(s);
   1703 }
   1704 
   1705 /*
   1706  * Wait for all buffers to complete I/O
   1707  * Return the number of "stuck" buffers.
   1708  */
   1709 int
   1710 buf_syncwait(void)
   1711 {
   1712 	buf_t *bp;
   1713 	int iter, nbusy, nbusy_prev = 0, ihash;
   1714 
   1715 	BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
   1716 
   1717 	for (iter = 0; iter < 20;) {
   1718 		mutex_enter(&bufcache_lock);
   1719 		nbusy = 0;
   1720 		for (ihash = 0; ihash < bufhash+1; ihash++) {
   1721 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
   1722 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY)
   1723 				nbusy += ((bp->b_flags & B_READ) == 0);
   1724 		    }
   1725 		}
   1726 		mutex_exit(&bufcache_lock);
   1727 
   1728 		if (nbusy == 0)
   1729 			break;
   1730 		if (nbusy_prev == 0)
   1731 			nbusy_prev = nbusy;
   1732 		printf("%d ", nbusy);
   1733 		kpause("bflush", false, MAX(1, hz / 25 * iter), NULL);
   1734 		if (nbusy >= nbusy_prev) /* we didn't flush anything */
   1735 			iter++;
   1736 		else
   1737 			nbusy_prev = nbusy;
   1738 	}
   1739 
   1740 	if (nbusy) {
   1741 #if defined(DEBUG) || defined(DEBUG_HALT_BUSY)
   1742 		printf("giving up\nPrinting vnodes for busy buffers\n");
   1743 		for (ihash = 0; ihash < bufhash+1; ihash++) {
   1744 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
   1745 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY &&
   1746 			    (bp->b_flags & B_READ) == 0)
   1747 				vprint(NULL, bp->b_vp);
   1748 		    }
   1749 		}
   1750 #endif
   1751 	}
   1752 
   1753 	return nbusy;
   1754 }
   1755 
   1756 static void
   1757 sysctl_fillbuf(const buf_t *i, struct buf_sysctl *o)
   1758 {
   1759 	const bool allowaddr = get_expose_address(curproc);
   1760 
   1761 	memset(o, 0, sizeof(*o));
   1762 
   1763 	o->b_flags = i->b_flags | i->b_cflags | i->b_oflags;
   1764 	o->b_error = i->b_error;
   1765 	o->b_prio = i->b_prio;
   1766 	o->b_dev = i->b_dev;
   1767 	o->b_bufsize = i->b_bufsize;
   1768 	o->b_bcount = i->b_bcount;
   1769 	o->b_resid = i->b_resid;
   1770 	COND_SET_VALUE(o->b_addr, PTRTOUINT64(i->b_data), allowaddr);
   1771 	o->b_blkno = i->b_blkno;
   1772 	o->b_rawblkno = i->b_rawblkno;
   1773 	COND_SET_VALUE(o->b_iodone, PTRTOUINT64(i->b_iodone), allowaddr);
   1774 	COND_SET_VALUE(o->b_proc, PTRTOUINT64(i->b_proc), allowaddr);
   1775 	COND_SET_VALUE(o->b_vp, PTRTOUINT64(i->b_vp), allowaddr);
   1776 	COND_SET_VALUE(o->b_saveaddr, PTRTOUINT64(i->b_saveaddr), allowaddr);
   1777 	o->b_lblkno = i->b_lblkno;
   1778 }
   1779 
   1780 #define KERN_BUFSLOP 20
   1781 static int
   1782 sysctl_dobuf(SYSCTLFN_ARGS)
   1783 {
   1784 	buf_t *bp;
   1785 	struct buf_sysctl bs;
   1786 	struct bqueue *bq;
   1787 	char *dp;
   1788 	u_int i, op, arg;
   1789 	size_t len, needed, elem_size, out_size;
   1790 	int error, elem_count, retries;
   1791 
   1792 	if (namelen == 1 && name[0] == CTL_QUERY)
   1793 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   1794 
   1795 	if (namelen != 4)
   1796 		return (EINVAL);
   1797 
   1798 	retries = 100;
   1799  retry:
   1800 	dp = oldp;
   1801 	len = (oldp != NULL) ? *oldlenp : 0;
   1802 	op = name[0];
   1803 	arg = name[1];
   1804 	elem_size = name[2];
   1805 	elem_count = name[3];
   1806 	out_size = MIN(sizeof(bs), elem_size);
   1807 
   1808 	/*
   1809 	 * at the moment, these are just "placeholders" to make the
   1810 	 * API for retrieving kern.buf data more extensible in the
   1811 	 * future.
   1812 	 *
   1813 	 * XXX kern.buf currently has "netbsd32" issues.  hopefully
   1814 	 * these will be resolved at a later point.
   1815 	 */
   1816 	if (op != KERN_BUF_ALL || arg != KERN_BUF_ALL ||
   1817 	    elem_size < 1 || elem_count < 0)
   1818 		return (EINVAL);
   1819 
   1820 	error = 0;
   1821 	needed = 0;
   1822 	sysctl_unlock();
   1823 	mutex_enter(&bufcache_lock);
   1824 	for (i = 0; i < BQUEUES; i++) {
   1825 		bq = &bufqueues[i];
   1826 		TAILQ_FOREACH(bp, &bq->bq_queue, b_freelist) {
   1827 			bq->bq_marker = bp;
   1828 			if (len >= elem_size && elem_count > 0) {
   1829 				sysctl_fillbuf(bp, &bs);
   1830 				mutex_exit(&bufcache_lock);
   1831 				error = copyout(&bs, dp, out_size);
   1832 				mutex_enter(&bufcache_lock);
   1833 				if (error)
   1834 					break;
   1835 				if (bq->bq_marker != bp) {
   1836 					/*
   1837 					 * This sysctl node is only for
   1838 					 * statistics.  Retry; if the
   1839 					 * queue keeps changing, then
   1840 					 * bail out.
   1841 					 */
   1842 					if (retries-- == 0) {
   1843 						error = EAGAIN;
   1844 						break;
   1845 					}
   1846 					mutex_exit(&bufcache_lock);
   1847 					sysctl_relock();
   1848 					goto retry;
   1849 				}
   1850 				dp += elem_size;
   1851 				len -= elem_size;
   1852 			}
   1853 			needed += elem_size;
   1854 			if (elem_count > 0 && elem_count != INT_MAX)
   1855 				elem_count--;
   1856 		}
   1857 		if (error != 0)
   1858 			break;
   1859 	}
   1860 	mutex_exit(&bufcache_lock);
   1861 	sysctl_relock();
   1862 
   1863 	*oldlenp = needed;
   1864 	if (oldp == NULL)
   1865 		*oldlenp += KERN_BUFSLOP * sizeof(buf_t);
   1866 
   1867 	return (error);
   1868 }
   1869 
   1870 static int
   1871 sysctl_bufvm_update(SYSCTLFN_ARGS)
   1872 {
   1873 	int error, rv;
   1874 	struct sysctlnode node;
   1875 	unsigned int temp_bufcache;
   1876 	unsigned long temp_water;
   1877 
   1878 	/* Take a copy of the supplied node and its data */
   1879 	node = *rnode;
   1880 	if (node.sysctl_data == &bufcache) {
   1881 	    node.sysctl_data = &temp_bufcache;
   1882 	    temp_bufcache = *(unsigned int *)rnode->sysctl_data;
   1883 	} else {
   1884 	    node.sysctl_data = &temp_water;
   1885 	    temp_water = *(unsigned long *)rnode->sysctl_data;
   1886 	}
   1887 
   1888 	/* Update the copy */
   1889 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1890 	if (error || newp == NULL)
   1891 		return (error);
   1892 
   1893 	if (rnode->sysctl_data == &bufcache) {
   1894 		if (temp_bufcache > 100)
   1895 			return (EINVAL);
   1896 		bufcache = temp_bufcache;
   1897 		buf_setwm();
   1898 	} else if (rnode->sysctl_data == &bufmem_lowater) {
   1899 		if (bufmem_hiwater - temp_water < 16)
   1900 			return (EINVAL);
   1901 		bufmem_lowater = temp_water;
   1902 	} else if (rnode->sysctl_data == &bufmem_hiwater) {
   1903 		if (temp_water - bufmem_lowater < 16)
   1904 			return (EINVAL);
   1905 		bufmem_hiwater = temp_water;
   1906 	} else
   1907 		return (EINVAL);
   1908 
   1909 	/* Drain until below new high water mark */
   1910 	sysctl_unlock();
   1911 	mutex_enter(&bufcache_lock);
   1912 	while (bufmem > bufmem_hiwater) {
   1913 		rv = buf_drain((bufmem - bufmem_hiwater) / (2 * 1024));
   1914 		if (rv <= 0)
   1915 			break;
   1916 	}
   1917 	mutex_exit(&bufcache_lock);
   1918 	sysctl_relock();
   1919 
   1920 	return 0;
   1921 }
   1922 
   1923 static struct sysctllog *vfsbio_sysctllog;
   1924 
   1925 static void
   1926 sysctl_kern_buf_setup(void)
   1927 {
   1928 
   1929 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1930 		       CTLFLAG_PERMANENT,
   1931 		       CTLTYPE_NODE, "buf",
   1932 		       SYSCTL_DESCR("Kernel buffer cache information"),
   1933 		       sysctl_dobuf, 0, NULL, 0,
   1934 		       CTL_KERN, KERN_BUF, CTL_EOL);
   1935 }
   1936 
   1937 static void
   1938 sysctl_vm_buf_setup(void)
   1939 {
   1940 
   1941 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1942 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1943 		       CTLTYPE_INT, "bufcache",
   1944 		       SYSCTL_DESCR("Percentage of physical memory to use for "
   1945 				    "buffer cache"),
   1946 		       sysctl_bufvm_update, 0, &bufcache, 0,
   1947 		       CTL_VM, CTL_CREATE, CTL_EOL);
   1948 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1949 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
   1950 		       CTLTYPE_LONG, "bufmem",
   1951 		       SYSCTL_DESCR("Amount of kernel memory used by buffer "
   1952 				    "cache"),
   1953 		       NULL, 0, &bufmem, 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_lowater",
   1958 		       SYSCTL_DESCR("Minimum amount of kernel memory to "
   1959 				    "reserve for buffer cache"),
   1960 		       sysctl_bufvm_update, 0, &bufmem_lowater, 0,
   1961 		       CTL_VM, CTL_CREATE, CTL_EOL);
   1962 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
   1963 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1964 		       CTLTYPE_LONG, "bufmem_hiwater",
   1965 		       SYSCTL_DESCR("Maximum amount of kernel memory to use "
   1966 				    "for buffer cache"),
   1967 		       sysctl_bufvm_update, 0, &bufmem_hiwater, 0,
   1968 		       CTL_VM, CTL_CREATE, CTL_EOL);
   1969 }
   1970 
   1971 #ifdef DEBUG
   1972 /*
   1973  * Print out statistics on the current allocation of the buffer pool.
   1974  * Can be enabled to print out on every ``sync'' by setting "syncprt"
   1975  * in vfs_syscalls.c using sysctl.
   1976  */
   1977 void
   1978 vfs_bufstats(void)
   1979 {
   1980 	int i, j, count;
   1981 	buf_t *bp;
   1982 	struct bqueue *dp;
   1983 	int counts[MAXBSIZE / MIN_PAGE_SIZE + 1];
   1984 	static const char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE" };
   1985 
   1986 	for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
   1987 		count = 0;
   1988 		memset(counts, 0, sizeof(counts));
   1989 		TAILQ_FOREACH(bp, &dp->bq_queue, b_freelist) {
   1990 			counts[bp->b_bufsize / PAGE_SIZE]++;
   1991 			count++;
   1992 		}
   1993 		printf("%s: total-%d", bname[i], count);
   1994 		for (j = 0; j <= MAXBSIZE / PAGE_SIZE; j++)
   1995 			if (counts[j] != 0)
   1996 				printf(", %d-%d", j * PAGE_SIZE, counts[j]);
   1997 		printf("\n");
   1998 	}
   1999 }
   2000 #endif /* DEBUG */
   2001 
   2002 /* ------------------------------ */
   2003 
   2004 buf_t *
   2005 getiobuf(struct vnode *vp, bool waitok)
   2006 {
   2007 	buf_t *bp;
   2008 
   2009 	bp = pool_cache_get(bufio_cache, (waitok ? PR_WAITOK : PR_NOWAIT));
   2010 	if (bp == NULL)
   2011 		return bp;
   2012 
   2013 	buf_init(bp);
   2014 
   2015 	if ((bp->b_vp = vp) != NULL) {
   2016 		bp->b_objlock = vp->v_interlock;
   2017 	} else {
   2018 		KASSERT(bp->b_objlock == &buffer_lock);
   2019 	}
   2020 
   2021 	return bp;
   2022 }
   2023 
   2024 void
   2025 putiobuf(buf_t *bp)
   2026 {
   2027 
   2028 	buf_destroy(bp);
   2029 	pool_cache_put(bufio_cache, bp);
   2030 }
   2031 
   2032 /*
   2033  * nestiobuf_iodone: b_iodone callback for nested buffers.
   2034  */
   2035 
   2036 void
   2037 nestiobuf_iodone(buf_t *bp)
   2038 {
   2039 	buf_t *mbp = bp->b_private;
   2040 	int error;
   2041 	int donebytes;
   2042 
   2043 	KASSERT(bp->b_bcount <= bp->b_bufsize);
   2044 	KASSERT(mbp != bp);
   2045 
   2046 	error = bp->b_error;
   2047 	if (bp->b_error == 0 &&
   2048 	    (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
   2049 		/*
   2050 		 * Not all got transfered, raise an error. We have no way to
   2051 		 * propagate these conditions to mbp.
   2052 		 */
   2053 		error = EIO;
   2054 	}
   2055 
   2056 	donebytes = bp->b_bufsize;
   2057 
   2058 	putiobuf(bp);
   2059 	nestiobuf_done(mbp, donebytes, error);
   2060 }
   2061 
   2062 /*
   2063  * nestiobuf_setup: setup a "nested" buffer.
   2064  *
   2065  * => 'mbp' is a "master" buffer which is being divided into sub pieces.
   2066  * => 'bp' should be a buffer allocated by getiobuf.
   2067  * => 'offset' is a byte offset in the master buffer.
   2068  * => 'size' is a size in bytes of this nested buffer.
   2069  */
   2070 
   2071 void
   2072 nestiobuf_setup(buf_t *mbp, buf_t *bp, int offset, size_t size)
   2073 {
   2074 	const int b_pass = mbp->b_flags & (B_READ|B_MEDIA_FLAGS);
   2075 	struct vnode *vp = mbp->b_vp;
   2076 
   2077 	KASSERT(mbp->b_bcount >= offset + size);
   2078 	bp->b_vp = vp;
   2079 	bp->b_dev = mbp->b_dev;
   2080 	bp->b_objlock = mbp->b_objlock;
   2081 	bp->b_cflags = BC_BUSY;
   2082 	bp->b_flags = B_ASYNC | b_pass;
   2083 	bp->b_iodone = nestiobuf_iodone;
   2084 	bp->b_data = (char *)mbp->b_data + offset;
   2085 	bp->b_resid = bp->b_bcount = size;
   2086 	bp->b_bufsize = bp->b_bcount;
   2087 	bp->b_private = mbp;
   2088 	BIO_COPYPRIO(bp, mbp);
   2089 	if (BUF_ISWRITE(bp) && vp != NULL) {
   2090 		mutex_enter(vp->v_interlock);
   2091 		vp->v_numoutput++;
   2092 		mutex_exit(vp->v_interlock);
   2093 	}
   2094 }
   2095 
   2096 /*
   2097  * nestiobuf_done: propagate completion to the master buffer.
   2098  *
   2099  * => 'donebytes' specifies how many bytes in the 'mbp' is completed.
   2100  * => 'error' is an errno(2) that 'donebytes' has been completed with.
   2101  */
   2102 
   2103 void
   2104 nestiobuf_done(buf_t *mbp, int donebytes, int error)
   2105 {
   2106 
   2107 	if (donebytes == 0) {
   2108 		return;
   2109 	}
   2110 	mutex_enter(mbp->b_objlock);
   2111 	KASSERT(mbp->b_resid >= donebytes);
   2112 	mbp->b_resid -= donebytes;
   2113 	if (error)
   2114 		mbp->b_error = error;
   2115 	if (mbp->b_resid == 0) {
   2116 		if (mbp->b_error)
   2117 			mbp->b_resid = mbp->b_bcount;
   2118 		mutex_exit(mbp->b_objlock);
   2119 		biodone(mbp);
   2120 	} else
   2121 		mutex_exit(mbp->b_objlock);
   2122 }
   2123 
   2124 void
   2125 buf_init(buf_t *bp)
   2126 {
   2127 
   2128 	cv_init(&bp->b_busy, "biolock");
   2129 	cv_init(&bp->b_done, "biowait");
   2130 	bp->b_dev = NODEV;
   2131 	bp->b_error = 0;
   2132 	bp->b_flags = 0;
   2133 	bp->b_cflags = 0;
   2134 	bp->b_oflags = 0;
   2135 	bp->b_objlock = &buffer_lock;
   2136 	bp->b_iodone = NULL;
   2137 	bp->b_refcnt = 1;
   2138 	bp->b_dev = NODEV;
   2139 	bp->b_vnbufs.le_next = NOLIST;
   2140 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
   2141 }
   2142 
   2143 void
   2144 buf_destroy(buf_t *bp)
   2145 {
   2146 
   2147 	cv_destroy(&bp->b_done);
   2148 	cv_destroy(&bp->b_busy);
   2149 }
   2150 
   2151 int
   2152 bbusy(buf_t *bp, bool intr, int timo, kmutex_t *interlock)
   2153 {
   2154 	int error;
   2155 
   2156 	KASSERT(mutex_owned(&bufcache_lock));
   2157 
   2158 	if ((bp->b_cflags & BC_BUSY) != 0) {
   2159 		if (curlwp == uvm.pagedaemon_lwp)
   2160 			return EDEADLK;
   2161 		bp->b_cflags |= BC_WANTED;
   2162 		bref(bp);
   2163 		if (interlock != NULL)
   2164 			mutex_exit(interlock);
   2165 		if (intr) {
   2166 			error = cv_timedwait_sig(&bp->b_busy, &bufcache_lock,
   2167 			    timo);
   2168 		} else {
   2169 			error = cv_timedwait(&bp->b_busy, &bufcache_lock,
   2170 			    timo);
   2171 		}
   2172 		brele(bp);
   2173 		if (interlock != NULL)
   2174 			mutex_enter(interlock);
   2175 		if (error != 0)
   2176 			return error;
   2177 		return EPASSTHROUGH;
   2178 	}
   2179 	bp->b_cflags |= BC_BUSY;
   2180 
   2181 	return 0;
   2182 }
   2183 
   2184 /*
   2185  * Nothing outside this file should really need to know about nbuf,
   2186  * but a few things still want to read it, so give them a way to do that.
   2187  */
   2188 u_int
   2189 buf_nbuf(void)
   2190 {
   2191 
   2192 	return nbuf;
   2193 }
   2194