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