Home | History | Annotate | Line # | Download | only in kern
vfs_bio.c revision 1.87
      1 /*	$NetBSD: vfs_bio.c,v 1.87 2003/02/05 21:38:42 pk Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1994 Christopher G. Demetriou
      5  * Copyright (c) 1982, 1986, 1989, 1993
      6  *	The Regents of the University of California.  All rights reserved.
      7  * (c) UNIX System Laboratories, Inc.
      8  * All or some portions of this file are derived from material licensed
      9  * to the University of California by American Telephone and Telegraph
     10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     11  * the permission of UNIX System Laboratories, Inc.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  * 3. All advertising materials mentioning features or use of this software
     22  *    must display the following acknowledgement:
     23  *	This product includes software developed by the University of
     24  *	California, Berkeley and its contributors.
     25  * 4. Neither the name of the University nor the names of its contributors
     26  *    may be used to endorse or promote products derived from this software
     27  *    without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     39  * SUCH DAMAGE.
     40  *
     41  *	@(#)vfs_bio.c	8.6 (Berkeley) 1/11/94
     42  */
     43 
     44 /*
     45  * Some references:
     46  *	Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
     47  *	Leffler, et al.: The Design and Implementation of the 4.3BSD
     48  *		UNIX Operating System (Addison Welley, 1989)
     49  */
     50 
     51 #include "opt_softdep.h"
     52 
     53 #include <sys/cdefs.h>
     54 __KERNEL_RCSID(0, "$NetBSD: vfs_bio.c,v 1.87 2003/02/05 21:38:42 pk Exp $");
     55 
     56 #include <sys/param.h>
     57 #include <sys/systm.h>
     58 #include <sys/proc.h>
     59 #include <sys/buf.h>
     60 #include <sys/vnode.h>
     61 #include <sys/mount.h>
     62 #include <sys/malloc.h>
     63 #include <sys/resourcevar.h>
     64 #include <sys/conf.h>
     65 
     66 #include <uvm/uvm.h>
     67 
     68 #include <miscfs/specfs/specdev.h>
     69 
     70 /* Macros to clear/set/test flags. */
     71 #define	SET(t, f)	(t) |= (f)
     72 #define	CLR(t, f)	(t) &= ~(f)
     73 #define	ISSET(t, f)	((t) & (f))
     74 
     75 /*
     76  * Definitions for the buffer hash lists.
     77  */
     78 #define	BUFHASH(dvp, lbn)	\
     79 	(&bufhashtbl[(((long)(dvp) >> 8) + (int)(lbn)) & bufhash])
     80 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
     81 u_long	bufhash;
     82 #ifndef SOFTDEP
     83 struct bio_ops bioops;	/* I/O operation notification */
     84 #endif
     85 
     86 /*
     87  * Insq/Remq for the buffer hash lists.
     88  */
     89 #define	binshash(bp, dp)	LIST_INSERT_HEAD(dp, bp, b_hash)
     90 #define	bremhash(bp)		LIST_REMOVE(bp, b_hash)
     91 
     92 /*
     93  * Definitions for the buffer free lists.
     94  */
     95 #define	BQUEUES		4		/* number of free buffer queues */
     96 
     97 #define	BQ_LOCKED	0		/* super-blocks &c */
     98 #define	BQ_LRU		1		/* lru, useful buffers */
     99 #define	BQ_AGE		2		/* rubbish */
    100 #define	BQ_EMPTY	3		/* buffer headers with no memory */
    101 
    102 TAILQ_HEAD(bqueues, buf) bufqueues[BQUEUES];
    103 int needbuffer;
    104 
    105 /*
    106  * Buffer queue lock.
    107  * Take this lock first if also taking some buffer's b_interlock.
    108  */
    109 struct simplelock bqueue_slock = SIMPLELOCK_INITIALIZER;
    110 
    111 /*
    112  * Buffer pool for I/O buffers.
    113  */
    114 struct pool bufpool;
    115 
    116 /*
    117  * bread()/breadn() helper.
    118  */
    119 static __inline struct buf *bio_doread(struct vnode *, daddr_t, int,
    120 					struct ucred *, int);
    121 int count_lock_queue(void);
    122 
    123 /*
    124  * Insq/Remq for the buffer free lists.
    125  * Call with buffer queue locked.
    126  */
    127 #define	binsheadfree(bp, dp)	TAILQ_INSERT_HEAD(dp, bp, b_freelist)
    128 #define	binstailfree(bp, dp)	TAILQ_INSERT_TAIL(dp, bp, b_freelist)
    129 
    130 void
    131 bremfree(bp)
    132 	struct buf *bp;
    133 {
    134 	struct bqueues *dp = NULL;
    135 
    136 	/*
    137 	 * We only calculate the head of the freelist when removing
    138 	 * the last element of the list as that is the only time that
    139 	 * it is needed (e.g. to reset the tail pointer).
    140 	 *
    141 	 * NB: This makes an assumption about how tailq's are implemented.
    142 	 */
    143 	if (TAILQ_NEXT(bp, b_freelist) == NULL) {
    144 		for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
    145 			if (dp->tqh_last == &bp->b_freelist.tqe_next)
    146 				break;
    147 		if (dp == &bufqueues[BQUEUES])
    148 			panic("bremfree: lost tail");
    149 	}
    150 	TAILQ_REMOVE(dp, bp, b_freelist);
    151 }
    152 
    153 /*
    154  * Initialize buffers and hash links for buffers.
    155  */
    156 void
    157 bufinit()
    158 {
    159 	struct buf *bp;
    160 	struct bqueues *dp;
    161 	u_int i, base, residual;
    162 
    163 	/*
    164 	 * Initialize the buffer pool.  This pool is used for buffers
    165 	 * which are strictly I/O control blocks, not buffer cache
    166 	 * buffers.
    167 	 */
    168 	pool_init(&bufpool, sizeof(struct buf), 0, 0, 0, "bufpl", NULL);
    169 
    170 	for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
    171 		TAILQ_INIT(dp);
    172 	bufhashtbl = hashinit(nbuf, HASH_LIST, M_CACHE, M_WAITOK, &bufhash);
    173 	base = bufpages / nbuf;
    174 	residual = bufpages % nbuf;
    175 	for (i = 0; i < nbuf; i++) {
    176 		bp = &buf[i];
    177 		memset((char *)bp, 0, sizeof(*bp));
    178 		simple_lock_init(&bp->b_interlock);
    179 		bp->b_dev = NODEV;
    180 		bp->b_vnbufs.le_next = NOLIST;
    181 		LIST_INIT(&bp->b_dep);
    182 		bp->b_data = buffers + i * MAXBSIZE;
    183 		if (i < residual)
    184 			bp->b_bufsize = (base + 1) * PAGE_SIZE;
    185 		else
    186 			bp->b_bufsize = base * PAGE_SIZE;
    187 		bp->b_flags = B_INVAL;
    188 		dp = bp->b_bufsize ? &bufqueues[BQ_AGE] : &bufqueues[BQ_EMPTY];
    189 		binsheadfree(bp, dp);
    190 		binshash(bp, &invalhash);
    191 	}
    192 }
    193 
    194 static __inline struct buf *
    195 bio_doread(vp, blkno, size, cred, async)
    196 	struct vnode *vp;
    197 	daddr_t blkno;
    198 	int size;
    199 	struct ucred *cred;
    200 	int async;
    201 {
    202 	struct buf *bp;
    203 	struct lwp *l  = (curlwp != NULL ? curlwp : &lwp0);	/* XXX */
    204 	struct proc *p = l->l_proc;
    205 
    206 	bp = getblk(vp, blkno, size, 0, 0);
    207 
    208 #ifdef DIAGNOSTIC
    209 	if (bp == NULL) {
    210 		panic("bio_doread: no such buf");
    211 	}
    212 #endif
    213 
    214 	/*
    215 	 * If buffer does not have data valid, start a read.
    216 	 * Note that if buffer is B_INVAL, getblk() won't return it.
    217 	 * Therefore, it's valid if its I/O has completed or been delayed.
    218 	 */
    219 	if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
    220 		/* Start I/O for the buffer. */
    221 		SET(bp->b_flags, B_READ | async);
    222 		VOP_STRATEGY(bp);
    223 
    224 		/* Pay for the read. */
    225 		p->p_stats->p_ru.ru_inblock++;
    226 	} else if (async) {
    227 		brelse(bp);
    228 	}
    229 
    230 	return (bp);
    231 }
    232 
    233 /*
    234  * Read a disk block.
    235  * This algorithm described in Bach (p.54).
    236  */
    237 int
    238 bread(vp, blkno, size, cred, bpp)
    239 	struct vnode *vp;
    240 	daddr_t blkno;
    241 	int size;
    242 	struct ucred *cred;
    243 	struct buf **bpp;
    244 {
    245 	struct buf *bp;
    246 
    247 	/* Get buffer for block. */
    248 	bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
    249 
    250 	/* Wait for the read to complete, and return result. */
    251 	return (biowait(bp));
    252 }
    253 
    254 /*
    255  * Read-ahead multiple disk blocks. The first is sync, the rest async.
    256  * Trivial modification to the breada algorithm presented in Bach (p.55).
    257  */
    258 int
    259 breadn(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp)
    260 	struct vnode *vp;
    261 	daddr_t blkno; int size;
    262 	daddr_t rablks[]; int rasizes[];
    263 	int nrablks;
    264 	struct ucred *cred;
    265 	struct buf **bpp;
    266 {
    267 	struct buf *bp;
    268 	int i;
    269 
    270 	bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
    271 
    272 	/*
    273 	 * For each of the read-ahead blocks, start a read, if necessary.
    274 	 */
    275 	for (i = 0; i < nrablks; i++) {
    276 		/* If it's in the cache, just go on to next one. */
    277 		if (incore(vp, rablks[i]))
    278 			continue;
    279 
    280 		/* Get a buffer for the read-ahead block */
    281 		(void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC);
    282 	}
    283 
    284 	/* Otherwise, we had to start a read for it; wait until it's valid. */
    285 	return (biowait(bp));
    286 }
    287 
    288 /*
    289  * Read with single-block read-ahead.  Defined in Bach (p.55), but
    290  * implemented as a call to breadn().
    291  * XXX for compatibility with old file systems.
    292  */
    293 int
    294 breada(vp, blkno, size, rablkno, rabsize, cred, bpp)
    295 	struct vnode *vp;
    296 	daddr_t blkno; int size;
    297 	daddr_t rablkno; int rabsize;
    298 	struct ucred *cred;
    299 	struct buf **bpp;
    300 {
    301 
    302 	return (breadn(vp, blkno, size, &rablkno, &rabsize, 1, cred, bpp));
    303 }
    304 
    305 /*
    306  * Block write.  Described in Bach (p.56)
    307  */
    308 int
    309 bwrite(bp)
    310 	struct buf *bp;
    311 {
    312 	int rv, sync, wasdelayed, s;
    313 	struct lwp *l  = (curlwp != NULL ? curlwp : &lwp0);	/* XXX */
    314 	struct proc *p = l->l_proc;
    315 	struct vnode *vp;
    316 	struct mount *mp;
    317 
    318 	KASSERT(ISSET(bp->b_flags, B_BUSY));
    319 
    320 	vp = bp->b_vp;
    321 	if (vp != NULL) {
    322 		if (vp->v_type == VBLK)
    323 			mp = vp->v_specmountpoint;
    324 		else
    325 			mp = vp->v_mount;
    326 	} else {
    327 		mp = NULL;
    328 	}
    329 
    330 	/*
    331 	 * Remember buffer type, to switch on it later.  If the write was
    332 	 * synchronous, but the file system was mounted with MNT_ASYNC,
    333 	 * convert it to a delayed write.
    334 	 * XXX note that this relies on delayed tape writes being converted
    335 	 * to async, not sync writes (which is safe, but ugly).
    336 	 */
    337 	sync = !ISSET(bp->b_flags, B_ASYNC);
    338 	if (sync && mp != NULL && ISSET(mp->mnt_flag, MNT_ASYNC)) {
    339 		bdwrite(bp);
    340 		return (0);
    341 	}
    342 
    343 	/*
    344 	 * Collect statistics on synchronous and asynchronous writes.
    345 	 * Writes to block devices are charged to their associated
    346 	 * filesystem (if any).
    347 	 */
    348 	if (mp != NULL) {
    349 		if (sync)
    350 			mp->mnt_stat.f_syncwrites++;
    351 		else
    352 			mp->mnt_stat.f_asyncwrites++;
    353 	}
    354 
    355 	wasdelayed = ISSET(bp->b_flags, B_DELWRI);
    356 
    357 	s = splbio();
    358 	simple_lock(&bp->b_interlock);
    359 
    360 	CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
    361 
    362 	/*
    363 	 * Pay for the I/O operation and make sure the buf is on the correct
    364 	 * vnode queue.
    365 	 */
    366 	if (wasdelayed)
    367 		reassignbuf(bp, bp->b_vp);
    368 	else
    369 		p->p_stats->p_ru.ru_oublock++;
    370 
    371 	/* Initiate disk write.  Make sure the appropriate party is charged. */
    372 	V_INCR_NUMOUTPUT(bp->b_vp);
    373 	simple_unlock(&bp->b_interlock);
    374 	splx(s);
    375 
    376 	VOP_STRATEGY(bp);
    377 
    378 	if (sync) {
    379 		/* If I/O was synchronous, wait for it to complete. */
    380 		rv = biowait(bp);
    381 
    382 		/* Release the buffer. */
    383 		brelse(bp);
    384 
    385 		return (rv);
    386 	} else {
    387 		return (0);
    388 	}
    389 }
    390 
    391 int
    392 vn_bwrite(v)
    393 	void *v;
    394 {
    395 	struct vop_bwrite_args *ap = v;
    396 
    397 	return (bwrite(ap->a_bp));
    398 }
    399 
    400 /*
    401  * Delayed write.
    402  *
    403  * The buffer is marked dirty, but is not queued for I/O.
    404  * This routine should be used when the buffer is expected
    405  * to be modified again soon, typically a small write that
    406  * partially fills a buffer.
    407  *
    408  * NB: magnetic tapes cannot be delayed; they must be
    409  * written in the order that the writes are requested.
    410  *
    411  * Described in Leffler, et al. (pp. 208-213).
    412  */
    413 void
    414 bdwrite(bp)
    415 	struct buf *bp;
    416 {
    417 	struct lwp *l  = (curlwp != NULL ? curlwp : &lwp0);	/* XXX */
    418 	struct proc *p = l->l_proc;
    419 	const struct bdevsw *bdev;
    420 	int s;
    421 
    422 	KASSERT(ISSET(bp->b_flags, B_BUSY));
    423 
    424 	/* If this is a tape block, write the block now. */
    425 	/* XXX NOTE: the memory filesystem usurpes major device */
    426 	/* XXX       number 4095, which is a bad idea.		*/
    427 	if (bp->b_dev != NODEV && major(bp->b_dev) != 4095) {
    428 		bdev = bdevsw_lookup(bp->b_dev);
    429 		if (bdev != NULL && bdev->d_type == D_TAPE) {
    430 			bawrite(bp);
    431 			return;
    432 		}
    433 	}
    434 
    435 	/*
    436 	 * If the block hasn't been seen before:
    437 	 *	(1) Mark it as having been seen,
    438 	 *	(2) Charge for the write,
    439 	 *	(3) Make sure it's on its vnode's correct block list.
    440 	 */
    441 	s = splbio();
    442 	simple_lock(&bp->b_interlock);
    443 
    444 	if (!ISSET(bp->b_flags, B_DELWRI)) {
    445 		SET(bp->b_flags, B_DELWRI);
    446 		p->p_stats->p_ru.ru_oublock++;
    447 		reassignbuf(bp, bp->b_vp);
    448 	}
    449 
    450 	/* Otherwise, the "write" is done, so mark and release the buffer. */
    451 	CLR(bp->b_flags, B_NEEDCOMMIT|B_DONE);
    452 	simple_unlock(&bp->b_interlock);
    453 	splx(s);
    454 
    455 	brelse(bp);
    456 }
    457 
    458 /*
    459  * Asynchronous block write; just an asynchronous bwrite().
    460  */
    461 void
    462 bawrite(bp)
    463 	struct buf *bp;
    464 {
    465 	int s;
    466 
    467 	KASSERT(ISSET(bp->b_flags, B_BUSY));
    468 
    469 	s = splbio();
    470 	simple_lock(&bp->b_interlock);
    471 	SET(bp->b_flags, B_ASYNC);
    472 	simple_unlock(&bp->b_interlock);
    473 	splx(s);
    474 	VOP_BWRITE(bp);
    475 }
    476 
    477 /*
    478  * Same as first half of bdwrite, mark buffer dirty, but do not release it.
    479  */
    480 void
    481 bdirty(bp)
    482 	struct buf *bp;
    483 {
    484 	struct lwp *l  = (curlwp != NULL ? curlwp : &lwp0);	/* XXX */
    485 	struct proc *p = l->l_proc;
    486 	int s;
    487 
    488 	KASSERT(ISSET(bp->b_flags, B_BUSY));
    489 
    490 	s = splbio();
    491 	simple_lock(&bp->b_interlock);
    492 
    493 	CLR(bp->b_flags, B_AGE);
    494 
    495 	if (!ISSET(bp->b_flags, B_DELWRI)) {
    496 		SET(bp->b_flags, B_DELWRI);
    497 		p->p_stats->p_ru.ru_oublock++;
    498 		reassignbuf(bp, bp->b_vp);
    499 	}
    500 
    501 	simple_unlock(&bp->b_interlock);
    502 	splx(s);
    503 }
    504 
    505 /*
    506  * Release a buffer on to the free lists.
    507  * Described in Bach (p. 46).
    508  */
    509 void
    510 brelse(bp)
    511 	struct buf *bp;
    512 {
    513 	struct bqueues *bufq;
    514 	int s;
    515 
    516 	KASSERT(ISSET(bp->b_flags, B_BUSY));
    517 
    518 	/* Block disk interrupts. */
    519 	s = splbio();
    520 	simple_lock(&bqueue_slock);
    521 	simple_lock(&bp->b_interlock);
    522 
    523 	/* Wake up any processes waiting for any buffer to become free. */
    524 	if (needbuffer) {
    525 		needbuffer = 0;
    526 		wakeup(&needbuffer);
    527 	}
    528 
    529 	/* Wake up any proceeses waiting for _this_ buffer to become free. */
    530 	if (ISSET(bp->b_flags, B_WANTED)) {
    531 		CLR(bp->b_flags, B_WANTED|B_AGE);
    532 		wakeup(bp);
    533 	}
    534 
    535 	/*
    536 	 * Determine which queue the buffer should be on, then put it there.
    537 	 */
    538 
    539 	/* If it's locked, don't report an error; try again later. */
    540 	if (ISSET(bp->b_flags, (B_LOCKED|B_ERROR)) == (B_LOCKED|B_ERROR))
    541 		CLR(bp->b_flags, B_ERROR);
    542 
    543 	/* If it's not cacheable, or an error, mark it invalid. */
    544 	if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
    545 		SET(bp->b_flags, B_INVAL);
    546 
    547 	if (ISSET(bp->b_flags, B_VFLUSH)) {
    548 		/*
    549 		 * This is a delayed write buffer that was just flushed to
    550 		 * disk.  It is still on the LRU queue.  If it's become
    551 		 * invalid, then we need to move it to a different queue;
    552 		 * otherwise leave it in its current position.
    553 		 */
    554 		CLR(bp->b_flags, B_VFLUSH);
    555 		if (!ISSET(bp->b_flags, B_ERROR|B_INVAL|B_LOCKED|B_AGE))
    556 			goto already_queued;
    557 		else
    558 			bremfree(bp);
    559 	}
    560 
    561 	if ((bp->b_bufsize <= 0) || ISSET(bp->b_flags, B_INVAL)) {
    562 		/*
    563 		 * If it's invalid or empty, dissociate it from its vnode
    564 		 * and put on the head of the appropriate queue.
    565 		 */
    566 		if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
    567 			(*bioops.io_deallocate)(bp);
    568 		CLR(bp->b_flags, B_DONE|B_DELWRI);
    569 		if (bp->b_vp) {
    570 			reassignbuf(bp, bp->b_vp);
    571 			brelvp(bp);
    572 		}
    573 		if (bp->b_bufsize <= 0)
    574 			/* no data */
    575 			bufq = &bufqueues[BQ_EMPTY];
    576 		else
    577 			/* invalid data */
    578 			bufq = &bufqueues[BQ_AGE];
    579 		binsheadfree(bp, bufq);
    580 	} else {
    581 		/*
    582 		 * It has valid data.  Put it on the end of the appropriate
    583 		 * queue, so that it'll stick around for as long as possible.
    584 		 * If buf is AGE, but has dependencies, must put it on last
    585 		 * bufqueue to be scanned, ie LRU. This protects against the
    586 		 * livelock where BQ_AGE only has buffers with dependencies,
    587 		 * and we thus never get to the dependent buffers in BQ_LRU.
    588 		 */
    589 		if (ISSET(bp->b_flags, B_LOCKED))
    590 			/* locked in core */
    591 			bufq = &bufqueues[BQ_LOCKED];
    592 		else if (!ISSET(bp->b_flags, B_AGE))
    593 			/* valid data */
    594 			bufq = &bufqueues[BQ_LRU];
    595 		else {
    596 			/* stale but valid data */
    597 			int has_deps;
    598 
    599 			if (LIST_FIRST(&bp->b_dep) != NULL &&
    600 			    bioops.io_countdeps)
    601 				has_deps = (*bioops.io_countdeps)(bp, 0);
    602 			else
    603 				has_deps = 0;
    604 			bufq = has_deps ? &bufqueues[BQ_LRU] :
    605 			    &bufqueues[BQ_AGE];
    606 		}
    607 		binstailfree(bp, bufq);
    608 	}
    609 
    610 already_queued:
    611 	/* Unlock the buffer. */
    612 	CLR(bp->b_flags, B_AGE|B_ASYNC|B_BUSY|B_NOCACHE);
    613 	SET(bp->b_flags, B_CACHE);
    614 
    615 	/* Allow disk interrupts. */
    616 	simple_unlock(&bp->b_interlock);
    617 	simple_unlock(&bqueue_slock);
    618 	splx(s);
    619 }
    620 
    621 /*
    622  * Determine if a block is in the cache.
    623  * Just look on what would be its hash chain.  If it's there, return
    624  * a pointer to it, unless it's marked invalid.  If it's marked invalid,
    625  * we normally don't return the buffer, unless the caller explicitly
    626  * wants us to.
    627  */
    628 struct buf *
    629 incore(vp, blkno)
    630 	struct vnode *vp;
    631 	daddr_t blkno;
    632 {
    633 	struct buf *bp;
    634 
    635 	/* Search hash chain */
    636 	LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
    637 		if (bp->b_lblkno == blkno && bp->b_vp == vp &&
    638 		    !ISSET(bp->b_flags, B_INVAL))
    639 		return (bp);
    640 	}
    641 
    642 	return (NULL);
    643 }
    644 
    645 /*
    646  * Get a block of requested size that is associated with
    647  * a given vnode and block offset. If it is found in the
    648  * block cache, mark it as having been found, make it busy
    649  * and return it. Otherwise, return an empty block of the
    650  * correct size. It is up to the caller to insure that the
    651  * cached blocks be of the correct size.
    652  */
    653 struct buf *
    654 getblk(vp, blkno, size, slpflag, slptimeo)
    655 	struct vnode *vp;
    656 	daddr_t blkno;
    657 	int size, slpflag, slptimeo;
    658 {
    659 	struct buf *bp;
    660 	int s, err;
    661 
    662 start:
    663 	s = splbio();
    664 	simple_lock(&bqueue_slock);
    665 	bp = incore(vp, blkno);
    666 	if (bp != NULL) {
    667 		simple_lock(&bp->b_interlock);
    668 		if (ISSET(bp->b_flags, B_BUSY)) {
    669 			simple_unlock(&bqueue_slock);
    670 			if (curproc == uvm.pagedaemon_proc) {
    671 				simple_unlock(&bp->b_interlock);
    672 				splx(s);
    673 				return NULL;
    674 			}
    675 			SET(bp->b_flags, B_WANTED);
    676 			err = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
    677 					"getblk", slptimeo, &bp->b_interlock);
    678 			splx(s);
    679 			if (err)
    680 				return (NULL);
    681 			goto start;
    682 		}
    683 #ifdef DIAGNOSTIC
    684 		if (ISSET(bp->b_flags, B_DONE|B_DELWRI) &&
    685 		    bp->b_bcount < size && vp->v_type != VBLK)
    686 			panic("getblk: block size invariant failed");
    687 #endif
    688 		SET(bp->b_flags, B_BUSY);
    689 		bremfree(bp);
    690 	} else {
    691 		if ((bp = getnewbuf(slpflag, slptimeo)) == NULL) {
    692 			simple_unlock(&bqueue_slock);
    693 			splx(s);
    694 			goto start;
    695 		}
    696 
    697 		binshash(bp, BUFHASH(vp, blkno));
    698 		bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
    699 		bgetvp(vp, bp);
    700 	}
    701 	simple_unlock(&bp->b_interlock);
    702 	simple_unlock(&bqueue_slock);
    703 	splx(s);
    704 	allocbuf(bp, size);
    705 	return (bp);
    706 }
    707 
    708 /*
    709  * Get an empty, disassociated buffer of given size.
    710  */
    711 struct buf *
    712 geteblk(size)
    713 	int size;
    714 {
    715 	struct buf *bp;
    716 	int s;
    717 
    718 	s = splbio();
    719 	simple_lock(&bqueue_slock);
    720 	while ((bp = getnewbuf(0, 0)) == 0)
    721 		;
    722 
    723 	SET(bp->b_flags, B_INVAL);
    724 	binshash(bp, &invalhash);
    725 	simple_unlock(&bqueue_slock);
    726 	simple_unlock(&bp->b_interlock);
    727 	splx(s);
    728 	allocbuf(bp, size);
    729 	return (bp);
    730 }
    731 
    732 /*
    733  * Expand or contract the actual memory allocated to a buffer.
    734  *
    735  * If the buffer shrinks, data is lost, so it's up to the
    736  * caller to have written it out *first*; this routine will not
    737  * start a write.  If the buffer grows, it's the callers
    738  * responsibility to fill out the buffer's additional contents.
    739  */
    740 void
    741 allocbuf(bp, size)
    742 	struct buf *bp;
    743 	int size;
    744 {
    745 	struct buf *nbp;
    746 	vsize_t desired_size;
    747 	int s;
    748 
    749 	desired_size = round_page((vsize_t)size);
    750 	if (desired_size > MAXBSIZE)
    751 		panic("allocbuf: buffer larger than MAXBSIZE requested");
    752 
    753 	if (bp->b_bufsize == desired_size)
    754 		goto out;
    755 
    756 	/*
    757 	 * If the buffer is smaller than the desired size, we need to snarf
    758 	 * it from other buffers.  Get buffers (via getnewbuf()), and
    759 	 * steal their pages.
    760 	 */
    761 	while (bp->b_bufsize < desired_size) {
    762 		int amt;
    763 
    764 		/* find a buffer */
    765 		s = splbio();
    766 		simple_lock(&bqueue_slock);
    767 		while ((nbp = getnewbuf(0, 0)) == NULL)
    768 			;
    769 
    770 		SET(nbp->b_flags, B_INVAL);
    771 		binshash(nbp, &invalhash);
    772 
    773 		simple_unlock(&nbp->b_interlock);
    774 		simple_unlock(&bqueue_slock);
    775 		splx(s);
    776 
    777 		/* and steal its pages, up to the amount we need */
    778 		amt = min(nbp->b_bufsize, (desired_size - bp->b_bufsize));
    779 		pagemove((nbp->b_data + nbp->b_bufsize - amt),
    780 			 bp->b_data + bp->b_bufsize, amt);
    781 		bp->b_bufsize += amt;
    782 		nbp->b_bufsize -= amt;
    783 
    784 		/* reduce transfer count if we stole some data */
    785 		if (nbp->b_bcount > nbp->b_bufsize)
    786 			nbp->b_bcount = nbp->b_bufsize;
    787 
    788 #ifdef DIAGNOSTIC
    789 		if (nbp->b_bufsize < 0)
    790 			panic("allocbuf: negative bufsize");
    791 #endif
    792 		brelse(nbp);
    793 	}
    794 
    795 	/*
    796 	 * If we want a buffer smaller than the current size,
    797 	 * shrink this buffer.  Grab a buf head from the EMPTY queue,
    798 	 * move a page onto it, and put it on front of the AGE queue.
    799 	 * If there are no free buffer headers, leave the buffer alone.
    800 	 */
    801 	if (bp->b_bufsize > desired_size) {
    802 		s = splbio();
    803 		simple_lock(&bqueue_slock);
    804 		if ((nbp = TAILQ_FIRST(&bufqueues[BQ_EMPTY])) == NULL) {
    805 			/* No free buffer head */
    806 			simple_unlock(&bqueue_slock);
    807 			splx(s);
    808 			goto out;
    809 		}
    810 		/* No need to lock nbp since it came from the empty queue */
    811 		bremfree(nbp);
    812 		SET(nbp->b_flags, B_BUSY | B_INVAL);
    813 		simple_unlock(&bqueue_slock);
    814 		splx(s);
    815 
    816 		/* move the page to it and note this change */
    817 		pagemove(bp->b_data + desired_size,
    818 		    nbp->b_data, bp->b_bufsize - desired_size);
    819 		nbp->b_bufsize = bp->b_bufsize - desired_size;
    820 		bp->b_bufsize = desired_size;
    821 		nbp->b_bcount = 0;
    822 
    823 		/* release the newly-filled buffer and leave */
    824 		brelse(nbp);
    825 	}
    826 
    827 out:
    828 	bp->b_bcount = size;
    829 }
    830 
    831 /*
    832  * Find a buffer which is available for use.
    833  * Select something from a free list.
    834  * Preference is to AGE list, then LRU list.
    835  *
    836  * Called with buffer queues locked.
    837  * Return buffer locked.
    838  */
    839 struct buf *
    840 getnewbuf(slpflag, slptimeo)
    841 	int slpflag, slptimeo;
    842 {
    843 	struct buf *bp;
    844 
    845 start:
    846 	LOCK_ASSERT(simple_lock_held(&bqueue_slock));
    847 
    848 	if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE])) != NULL ||
    849 	    (bp = TAILQ_FIRST(&bufqueues[BQ_LRU])) != NULL) {
    850 		simple_lock(&bp->b_interlock);
    851 		bremfree(bp);
    852 	} else {
    853 		/* wait for a free buffer of any kind */
    854 		needbuffer = 1;
    855 		ltsleep(&needbuffer, slpflag|(PRIBIO+1),
    856 			"getnewbuf", slptimeo, &bqueue_slock);
    857 		return (NULL);
    858 	}
    859 
    860 	if (ISSET(bp->b_flags, B_VFLUSH)) {
    861 		/*
    862 		 * This is a delayed write buffer being flushed to disk.  Make
    863 		 * sure it gets aged out of the queue when it's finished, and
    864 		 * leave it off the LRU queue.
    865 		 */
    866 		CLR(bp->b_flags, B_VFLUSH);
    867 		SET(bp->b_flags, B_AGE);
    868 		simple_unlock(&bp->b_interlock);
    869 		goto start;
    870 	}
    871 
    872 	/* Buffer is no longer on free lists. */
    873 	SET(bp->b_flags, B_BUSY);
    874 
    875 	/*
    876 	 * If buffer was a delayed write, start it and return NULL
    877 	 * (since we might sleep while starting the write).
    878 	 */
    879 	if (ISSET(bp->b_flags, B_DELWRI)) {
    880 		/*
    881 		 * This buffer has gone through the LRU, so make sure it gets
    882 		 * reused ASAP.
    883 		 */
    884 		SET(bp->b_flags, B_AGE);
    885 		simple_unlock(&bp->b_interlock);
    886 		bawrite(bp);
    887 		return (NULL);
    888 	}
    889 
    890 	/* disassociate us from our vnode, if we had one... */
    891 	if (bp->b_vp)
    892 		brelvp(bp);
    893 
    894 	if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
    895 		(*bioops.io_deallocate)(bp);
    896 
    897 	/* clear out various other fields */
    898 	bp->b_flags = B_BUSY;
    899 	bp->b_dev = NODEV;
    900 	bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = 0;
    901 	bp->b_iodone = 0;
    902 	bp->b_error = 0;
    903 	bp->b_resid = 0;
    904 	bp->b_bcount = 0;
    905 
    906 	bremhash(bp);
    907 	return (bp);
    908 }
    909 
    910 /*
    911  * Wait for operations on the buffer to complete.
    912  * When they do, extract and return the I/O's error value.
    913  */
    914 int
    915 biowait(bp)
    916 	struct buf *bp;
    917 {
    918 	int s, error;
    919 
    920 	s = splbio();
    921 	simple_lock(&bp->b_interlock);
    922 	while (!ISSET(bp->b_flags, B_DONE | B_DELWRI))
    923 		ltsleep(bp, PRIBIO + 1, "biowait", 0, &bp->b_interlock);
    924 
    925 	/* check for interruption of I/O (e.g. via NFS), then errors. */
    926 	if (ISSET(bp->b_flags, B_EINTR)) {
    927 		CLR(bp->b_flags, B_EINTR);
    928 		error = EINTR;
    929 	} else if (ISSET(bp->b_flags, B_ERROR))
    930 		error = bp->b_error ? bp->b_error : EIO;
    931 	else
    932 		error = 0;
    933 
    934 	simple_unlock(&bp->b_interlock);
    935 	splx(s);
    936 	return (error);
    937 }
    938 
    939 /*
    940  * Mark I/O complete on a buffer.
    941  *
    942  * If a callback has been requested, e.g. the pageout
    943  * daemon, do so. Otherwise, awaken waiting processes.
    944  *
    945  * [ Leffler, et al., says on p.247:
    946  *	"This routine wakes up the blocked process, frees the buffer
    947  *	for an asynchronous write, or, for a request by the pagedaemon
    948  *	process, invokes a procedure specified in the buffer structure" ]
    949  *
    950  * In real life, the pagedaemon (or other system processes) wants
    951  * to do async stuff to, and doesn't want the buffer brelse()'d.
    952  * (for swap pager, that puts swap buffers on the free lists (!!!),
    953  * for the vn device, that puts malloc'd buffers on the free lists!)
    954  */
    955 void
    956 biodone(bp)
    957 	struct buf *bp;
    958 {
    959 	int s = splbio();
    960 
    961 	simple_lock(&bp->b_interlock);
    962 	if (ISSET(bp->b_flags, B_DONE))
    963 		panic("biodone already");
    964 	SET(bp->b_flags, B_DONE);		/* note that it's done */
    965 
    966 	if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
    967 		(*bioops.io_complete)(bp);
    968 
    969 	if (!ISSET(bp->b_flags, B_READ))	/* wake up reader */
    970 		vwakeup(bp);
    971 
    972 	/*
    973 	 * If necessary, call out.  Unlock the buffer before calling
    974 	 * iodone() as the buffer isn't valid any more when it return.
    975 	 */
    976 	if (ISSET(bp->b_flags, B_CALL)) {
    977 		CLR(bp->b_flags, B_CALL);	/* but note callout done */
    978 		simple_unlock(&bp->b_interlock);
    979 		(*bp->b_iodone)(bp);
    980 	} else {
    981 		if (ISSET(bp->b_flags, B_ASYNC)) {	/* if async, release */
    982 			simple_unlock(&bp->b_interlock);
    983 			brelse(bp);
    984 		} else {			/* or just wakeup the buffer */
    985 			CLR(bp->b_flags, B_WANTED);
    986 			wakeup(bp);
    987 			simple_unlock(&bp->b_interlock);
    988 		}
    989 	}
    990 
    991 	splx(s);
    992 }
    993 
    994 /*
    995  * Return a count of buffers on the "locked" queue.
    996  */
    997 int
    998 count_lock_queue()
    999 {
   1000 	struct buf *bp;
   1001 	int n = 0;
   1002 
   1003 	simple_lock(&bqueue_slock);
   1004 	TAILQ_FOREACH(bp, &bufqueues[BQ_LOCKED], b_freelist)
   1005 		n++;
   1006 	simple_unlock(&bqueue_slock);
   1007 	return (n);
   1008 }
   1009 
   1010 #ifdef DEBUG
   1011 /*
   1012  * Print out statistics on the current allocation of the buffer pool.
   1013  * Can be enabled to print out on every ``sync'' by setting "syncprt"
   1014  * in vfs_syscalls.c using sysctl.
   1015  */
   1016 void
   1017 vfs_bufstats()
   1018 {
   1019 	int s, i, j, count;
   1020 	struct buf *bp;
   1021 	struct bqueues *dp;
   1022 	int counts[(MAXBSIZE / PAGE_SIZE) + 1];
   1023 	static char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE", "EMPTY" };
   1024 
   1025 	for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
   1026 		count = 0;
   1027 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
   1028 			counts[j] = 0;
   1029 		s = splbio();
   1030 		TAILQ_FOREACH(bp, dp, b_freelist) {
   1031 			counts[bp->b_bufsize/PAGE_SIZE]++;
   1032 			count++;
   1033 		}
   1034 		splx(s);
   1035 		printf("%s: total-%d", bname[i], count);
   1036 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
   1037 			if (counts[j] != 0)
   1038 				printf(", %d-%d", j * PAGE_SIZE, counts[j]);
   1039 		printf("\n");
   1040 	}
   1041 }
   1042 #endif /* DEBUG */
   1043