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