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