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