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