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