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