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