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