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