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