Home | History | Annotate | Line # | Download | only in kern
vfs_bio.c revision 1.88
      1 /*	$NetBSD: vfs_bio.c,v 1.88 2003/02/06 09:46:46 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.88 2003/02/06 09:46:46 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  * Call at splbio() and with the buffer interlock locked.
    480  * Note: called only from biodone() through ffs softdep's bioops.io_complete()
    481  */
    482 void
    483 bdirty(bp)
    484 	struct buf *bp;
    485 {
    486 	struct lwp *l  = (curlwp != NULL ? curlwp : &lwp0);	/* XXX */
    487 	struct proc *p = l->l_proc;
    488 
    489 	KASSERT(ISSET(bp->b_flags, B_BUSY));
    490 	LOCK_ASSERT(simple_lock_held(&bp->b_interlock));
    491 
    492 	CLR(bp->b_flags, B_AGE);
    493 
    494 	if (!ISSET(bp->b_flags, B_DELWRI)) {
    495 		SET(bp->b_flags, B_DELWRI);
    496 		p->p_stats->p_ru.ru_oublock++;
    497 		reassignbuf(bp, bp->b_vp);
    498 	}
    499 }
    500 
    501 /*
    502  * Release a buffer on to the free lists.
    503  * Described in Bach (p. 46).
    504  */
    505 void
    506 brelse(bp)
    507 	struct buf *bp;
    508 {
    509 	struct bqueues *bufq;
    510 	int s;
    511 
    512 	KASSERT(ISSET(bp->b_flags, B_BUSY));
    513 
    514 	/* Block disk interrupts. */
    515 	s = splbio();
    516 	simple_lock(&bqueue_slock);
    517 	simple_lock(&bp->b_interlock);
    518 
    519 	/* Wake up any processes waiting for any buffer to become free. */
    520 	if (needbuffer) {
    521 		needbuffer = 0;
    522 		wakeup(&needbuffer);
    523 	}
    524 
    525 	/* Wake up any proceeses waiting for _this_ buffer to become free. */
    526 	if (ISSET(bp->b_flags, B_WANTED)) {
    527 		CLR(bp->b_flags, B_WANTED|B_AGE);
    528 		wakeup(bp);
    529 	}
    530 
    531 	/*
    532 	 * Determine which queue the buffer should be on, then put it there.
    533 	 */
    534 
    535 	/* If it's locked, don't report an error; try again later. */
    536 	if (ISSET(bp->b_flags, (B_LOCKED|B_ERROR)) == (B_LOCKED|B_ERROR))
    537 		CLR(bp->b_flags, B_ERROR);
    538 
    539 	/* If it's not cacheable, or an error, mark it invalid. */
    540 	if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
    541 		SET(bp->b_flags, B_INVAL);
    542 
    543 	if (ISSET(bp->b_flags, B_VFLUSH)) {
    544 		/*
    545 		 * This is a delayed write buffer that was just flushed to
    546 		 * disk.  It is still on the LRU queue.  If it's become
    547 		 * invalid, then we need to move it to a different queue;
    548 		 * otherwise leave it in its current position.
    549 		 */
    550 		CLR(bp->b_flags, B_VFLUSH);
    551 		if (!ISSET(bp->b_flags, B_ERROR|B_INVAL|B_LOCKED|B_AGE))
    552 			goto already_queued;
    553 		else
    554 			bremfree(bp);
    555 	}
    556 
    557 	if ((bp->b_bufsize <= 0) || ISSET(bp->b_flags, B_INVAL)) {
    558 		/*
    559 		 * If it's invalid or empty, dissociate it from its vnode
    560 		 * and put on the head of the appropriate queue.
    561 		 */
    562 		if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
    563 			(*bioops.io_deallocate)(bp);
    564 		CLR(bp->b_flags, B_DONE|B_DELWRI);
    565 		if (bp->b_vp) {
    566 			reassignbuf(bp, bp->b_vp);
    567 			brelvp(bp);
    568 		}
    569 		if (bp->b_bufsize <= 0)
    570 			/* no data */
    571 			bufq = &bufqueues[BQ_EMPTY];
    572 		else
    573 			/* invalid data */
    574 			bufq = &bufqueues[BQ_AGE];
    575 		binsheadfree(bp, bufq);
    576 	} else {
    577 		/*
    578 		 * It has valid data.  Put it on the end of the appropriate
    579 		 * queue, so that it'll stick around for as long as possible.
    580 		 * If buf is AGE, but has dependencies, must put it on last
    581 		 * bufqueue to be scanned, ie LRU. This protects against the
    582 		 * livelock where BQ_AGE only has buffers with dependencies,
    583 		 * and we thus never get to the dependent buffers in BQ_LRU.
    584 		 */
    585 		if (ISSET(bp->b_flags, B_LOCKED))
    586 			/* locked in core */
    587 			bufq = &bufqueues[BQ_LOCKED];
    588 		else if (!ISSET(bp->b_flags, B_AGE))
    589 			/* valid data */
    590 			bufq = &bufqueues[BQ_LRU];
    591 		else {
    592 			/* stale but valid data */
    593 			int has_deps;
    594 
    595 			if (LIST_FIRST(&bp->b_dep) != NULL &&
    596 			    bioops.io_countdeps)
    597 				has_deps = (*bioops.io_countdeps)(bp, 0);
    598 			else
    599 				has_deps = 0;
    600 			bufq = has_deps ? &bufqueues[BQ_LRU] :
    601 			    &bufqueues[BQ_AGE];
    602 		}
    603 		binstailfree(bp, bufq);
    604 	}
    605 
    606 already_queued:
    607 	/* Unlock the buffer. */
    608 	CLR(bp->b_flags, B_AGE|B_ASYNC|B_BUSY|B_NOCACHE);
    609 	SET(bp->b_flags, B_CACHE);
    610 
    611 	/* Allow disk interrupts. */
    612 	simple_unlock(&bp->b_interlock);
    613 	simple_unlock(&bqueue_slock);
    614 	splx(s);
    615 }
    616 
    617 /*
    618  * Determine if a block is in the cache.
    619  * Just look on what would be its hash chain.  If it's there, return
    620  * a pointer to it, unless it's marked invalid.  If it's marked invalid,
    621  * we normally don't return the buffer, unless the caller explicitly
    622  * wants us to.
    623  */
    624 struct buf *
    625 incore(vp, blkno)
    626 	struct vnode *vp;
    627 	daddr_t blkno;
    628 {
    629 	struct buf *bp;
    630 
    631 	/* Search hash chain */
    632 	LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
    633 		if (bp->b_lblkno == blkno && bp->b_vp == vp &&
    634 		    !ISSET(bp->b_flags, B_INVAL))
    635 		return (bp);
    636 	}
    637 
    638 	return (NULL);
    639 }
    640 
    641 /*
    642  * Get a block of requested size that is associated with
    643  * a given vnode and block offset. If it is found in the
    644  * block cache, mark it as having been found, make it busy
    645  * and return it. Otherwise, return an empty block of the
    646  * correct size. It is up to the caller to insure that the
    647  * cached blocks be of the correct size.
    648  */
    649 struct buf *
    650 getblk(vp, blkno, size, slpflag, slptimeo)
    651 	struct vnode *vp;
    652 	daddr_t blkno;
    653 	int size, slpflag, slptimeo;
    654 {
    655 	struct buf *bp;
    656 	int s, err;
    657 
    658 start:
    659 	s = splbio();
    660 	simple_lock(&bqueue_slock);
    661 	bp = incore(vp, blkno);
    662 	if (bp != NULL) {
    663 		simple_lock(&bp->b_interlock);
    664 		if (ISSET(bp->b_flags, B_BUSY)) {
    665 			simple_unlock(&bqueue_slock);
    666 			if (curproc == uvm.pagedaemon_proc) {
    667 				simple_unlock(&bp->b_interlock);
    668 				splx(s);
    669 				return NULL;
    670 			}
    671 			SET(bp->b_flags, B_WANTED);
    672 			err = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
    673 					"getblk", slptimeo, &bp->b_interlock);
    674 			splx(s);
    675 			if (err)
    676 				return (NULL);
    677 			goto start;
    678 		}
    679 #ifdef DIAGNOSTIC
    680 		if (ISSET(bp->b_flags, B_DONE|B_DELWRI) &&
    681 		    bp->b_bcount < size && vp->v_type != VBLK)
    682 			panic("getblk: block size invariant failed");
    683 #endif
    684 		SET(bp->b_flags, B_BUSY);
    685 		bremfree(bp);
    686 	} else {
    687 		if ((bp = getnewbuf(slpflag, slptimeo)) == NULL) {
    688 			simple_unlock(&bqueue_slock);
    689 			splx(s);
    690 			goto start;
    691 		}
    692 
    693 		binshash(bp, BUFHASH(vp, blkno));
    694 		bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
    695 		bgetvp(vp, bp);
    696 	}
    697 	simple_unlock(&bp->b_interlock);
    698 	simple_unlock(&bqueue_slock);
    699 	splx(s);
    700 	allocbuf(bp, size);
    701 	return (bp);
    702 }
    703 
    704 /*
    705  * Get an empty, disassociated buffer of given size.
    706  */
    707 struct buf *
    708 geteblk(size)
    709 	int size;
    710 {
    711 	struct buf *bp;
    712 	int s;
    713 
    714 	s = splbio();
    715 	simple_lock(&bqueue_slock);
    716 	while ((bp = getnewbuf(0, 0)) == 0)
    717 		;
    718 
    719 	SET(bp->b_flags, B_INVAL);
    720 	binshash(bp, &invalhash);
    721 	simple_unlock(&bqueue_slock);
    722 	simple_unlock(&bp->b_interlock);
    723 	splx(s);
    724 	allocbuf(bp, size);
    725 	return (bp);
    726 }
    727 
    728 /*
    729  * Expand or contract the actual memory allocated to a buffer.
    730  *
    731  * If the buffer shrinks, data is lost, so it's up to the
    732  * caller to have written it out *first*; this routine will not
    733  * start a write.  If the buffer grows, it's the callers
    734  * responsibility to fill out the buffer's additional contents.
    735  */
    736 void
    737 allocbuf(bp, size)
    738 	struct buf *bp;
    739 	int size;
    740 {
    741 	struct buf *nbp;
    742 	vsize_t desired_size;
    743 	int s;
    744 
    745 	desired_size = round_page((vsize_t)size);
    746 	if (desired_size > MAXBSIZE)
    747 		panic("allocbuf: buffer larger than MAXBSIZE requested");
    748 
    749 	if (bp->b_bufsize == desired_size)
    750 		goto out;
    751 
    752 	/*
    753 	 * If the buffer is smaller than the desired size, we need to snarf
    754 	 * it from other buffers.  Get buffers (via getnewbuf()), and
    755 	 * steal their pages.
    756 	 */
    757 	while (bp->b_bufsize < desired_size) {
    758 		int amt;
    759 
    760 		/* find a buffer */
    761 		s = splbio();
    762 		simple_lock(&bqueue_slock);
    763 		while ((nbp = getnewbuf(0, 0)) == NULL)
    764 			;
    765 
    766 		SET(nbp->b_flags, B_INVAL);
    767 		binshash(nbp, &invalhash);
    768 
    769 		simple_unlock(&nbp->b_interlock);
    770 		simple_unlock(&bqueue_slock);
    771 		splx(s);
    772 
    773 		/* and steal its pages, up to the amount we need */
    774 		amt = min(nbp->b_bufsize, (desired_size - bp->b_bufsize));
    775 		pagemove((nbp->b_data + nbp->b_bufsize - amt),
    776 			 bp->b_data + bp->b_bufsize, amt);
    777 		bp->b_bufsize += amt;
    778 		nbp->b_bufsize -= amt;
    779 
    780 		/* reduce transfer count if we stole some data */
    781 		if (nbp->b_bcount > nbp->b_bufsize)
    782 			nbp->b_bcount = nbp->b_bufsize;
    783 
    784 #ifdef DIAGNOSTIC
    785 		if (nbp->b_bufsize < 0)
    786 			panic("allocbuf: negative bufsize");
    787 #endif
    788 		brelse(nbp);
    789 	}
    790 
    791 	/*
    792 	 * If we want a buffer smaller than the current size,
    793 	 * shrink this buffer.  Grab a buf head from the EMPTY queue,
    794 	 * move a page onto it, and put it on front of the AGE queue.
    795 	 * If there are no free buffer headers, leave the buffer alone.
    796 	 */
    797 	if (bp->b_bufsize > desired_size) {
    798 		s = splbio();
    799 		simple_lock(&bqueue_slock);
    800 		if ((nbp = TAILQ_FIRST(&bufqueues[BQ_EMPTY])) == NULL) {
    801 			/* No free buffer head */
    802 			simple_unlock(&bqueue_slock);
    803 			splx(s);
    804 			goto out;
    805 		}
    806 		/* No need to lock nbp since it came from the empty queue */
    807 		bremfree(nbp);
    808 		SET(nbp->b_flags, B_BUSY | B_INVAL);
    809 		simple_unlock(&bqueue_slock);
    810 		splx(s);
    811 
    812 		/* move the page to it and note this change */
    813 		pagemove(bp->b_data + desired_size,
    814 		    nbp->b_data, bp->b_bufsize - desired_size);
    815 		nbp->b_bufsize = bp->b_bufsize - desired_size;
    816 		bp->b_bufsize = desired_size;
    817 		nbp->b_bcount = 0;
    818 
    819 		/* release the newly-filled buffer and leave */
    820 		brelse(nbp);
    821 	}
    822 
    823 out:
    824 	bp->b_bcount = size;
    825 }
    826 
    827 /*
    828  * Find a buffer which is available for use.
    829  * Select something from a free list.
    830  * Preference is to AGE list, then LRU list.
    831  *
    832  * Called with buffer queues locked.
    833  * Return buffer locked.
    834  */
    835 struct buf *
    836 getnewbuf(slpflag, slptimeo)
    837 	int slpflag, slptimeo;
    838 {
    839 	struct buf *bp;
    840 
    841 start:
    842 	LOCK_ASSERT(simple_lock_held(&bqueue_slock));
    843 
    844 	if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE])) != NULL ||
    845 	    (bp = TAILQ_FIRST(&bufqueues[BQ_LRU])) != NULL) {
    846 		simple_lock(&bp->b_interlock);
    847 		bremfree(bp);
    848 	} else {
    849 		/* wait for a free buffer of any kind */
    850 		needbuffer = 1;
    851 		ltsleep(&needbuffer, slpflag|(PRIBIO+1),
    852 			"getnewbuf", slptimeo, &bqueue_slock);
    853 		return (NULL);
    854 	}
    855 
    856 	if (ISSET(bp->b_flags, B_VFLUSH)) {
    857 		/*
    858 		 * This is a delayed write buffer being flushed to disk.  Make
    859 		 * sure it gets aged out of the queue when it's finished, and
    860 		 * leave it off the LRU queue.
    861 		 */
    862 		CLR(bp->b_flags, B_VFLUSH);
    863 		SET(bp->b_flags, B_AGE);
    864 		simple_unlock(&bp->b_interlock);
    865 		goto start;
    866 	}
    867 
    868 	/* Buffer is no longer on free lists. */
    869 	SET(bp->b_flags, B_BUSY);
    870 
    871 	/*
    872 	 * If buffer was a delayed write, start it and return NULL
    873 	 * (since we might sleep while starting the write).
    874 	 */
    875 	if (ISSET(bp->b_flags, B_DELWRI)) {
    876 		/*
    877 		 * This buffer has gone through the LRU, so make sure it gets
    878 		 * reused ASAP.
    879 		 */
    880 		SET(bp->b_flags, B_AGE);
    881 		simple_unlock(&bp->b_interlock);
    882 		bawrite(bp);
    883 		return (NULL);
    884 	}
    885 
    886 	/* disassociate us from our vnode, if we had one... */
    887 	if (bp->b_vp)
    888 		brelvp(bp);
    889 
    890 	if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
    891 		(*bioops.io_deallocate)(bp);
    892 
    893 	/* clear out various other fields */
    894 	bp->b_flags = B_BUSY;
    895 	bp->b_dev = NODEV;
    896 	bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = 0;
    897 	bp->b_iodone = 0;
    898 	bp->b_error = 0;
    899 	bp->b_resid = 0;
    900 	bp->b_bcount = 0;
    901 
    902 	bremhash(bp);
    903 	return (bp);
    904 }
    905 
    906 /*
    907  * Wait for operations on the buffer to complete.
    908  * When they do, extract and return the I/O's error value.
    909  */
    910 int
    911 biowait(bp)
    912 	struct buf *bp;
    913 {
    914 	int s, error;
    915 
    916 	s = splbio();
    917 	simple_lock(&bp->b_interlock);
    918 	while (!ISSET(bp->b_flags, B_DONE | B_DELWRI))
    919 		ltsleep(bp, PRIBIO + 1, "biowait", 0, &bp->b_interlock);
    920 
    921 	/* check for interruption of I/O (e.g. via NFS), then errors. */
    922 	if (ISSET(bp->b_flags, B_EINTR)) {
    923 		CLR(bp->b_flags, B_EINTR);
    924 		error = EINTR;
    925 	} else if (ISSET(bp->b_flags, B_ERROR))
    926 		error = bp->b_error ? bp->b_error : EIO;
    927 	else
    928 		error = 0;
    929 
    930 	simple_unlock(&bp->b_interlock);
    931 	splx(s);
    932 	return (error);
    933 }
    934 
    935 /*
    936  * Mark I/O complete on a buffer.
    937  *
    938  * If a callback has been requested, e.g. the pageout
    939  * daemon, do so. Otherwise, awaken waiting processes.
    940  *
    941  * [ Leffler, et al., says on p.247:
    942  *	"This routine wakes up the blocked process, frees the buffer
    943  *	for an asynchronous write, or, for a request by the pagedaemon
    944  *	process, invokes a procedure specified in the buffer structure" ]
    945  *
    946  * In real life, the pagedaemon (or other system processes) wants
    947  * to do async stuff to, and doesn't want the buffer brelse()'d.
    948  * (for swap pager, that puts swap buffers on the free lists (!!!),
    949  * for the vn device, that puts malloc'd buffers on the free lists!)
    950  */
    951 void
    952 biodone(bp)
    953 	struct buf *bp;
    954 {
    955 	int s = splbio();
    956 
    957 	simple_lock(&bp->b_interlock);
    958 	if (ISSET(bp->b_flags, B_DONE))
    959 		panic("biodone already");
    960 	SET(bp->b_flags, B_DONE);		/* note that it's done */
    961 
    962 	if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
    963 		(*bioops.io_complete)(bp);
    964 
    965 	if (!ISSET(bp->b_flags, B_READ))	/* wake up reader */
    966 		vwakeup(bp);
    967 
    968 	/*
    969 	 * If necessary, call out.  Unlock the buffer before calling
    970 	 * iodone() as the buffer isn't valid any more when it return.
    971 	 */
    972 	if (ISSET(bp->b_flags, B_CALL)) {
    973 		CLR(bp->b_flags, B_CALL);	/* but note callout done */
    974 		simple_unlock(&bp->b_interlock);
    975 		(*bp->b_iodone)(bp);
    976 	} else {
    977 		if (ISSET(bp->b_flags, B_ASYNC)) {	/* if async, release */
    978 			simple_unlock(&bp->b_interlock);
    979 			brelse(bp);
    980 		} else {			/* or just wakeup the buffer */
    981 			CLR(bp->b_flags, B_WANTED);
    982 			wakeup(bp);
    983 			simple_unlock(&bp->b_interlock);
    984 		}
    985 	}
    986 
    987 	splx(s);
    988 }
    989 
    990 /*
    991  * Return a count of buffers on the "locked" queue.
    992  */
    993 int
    994 count_lock_queue()
    995 {
    996 	struct buf *bp;
    997 	int n = 0;
    998 
    999 	simple_lock(&bqueue_slock);
   1000 	TAILQ_FOREACH(bp, &bufqueues[BQ_LOCKED], b_freelist)
   1001 		n++;
   1002 	simple_unlock(&bqueue_slock);
   1003 	return (n);
   1004 }
   1005 
   1006 #ifdef DEBUG
   1007 /*
   1008  * Print out statistics on the current allocation of the buffer pool.
   1009  * Can be enabled to print out on every ``sync'' by setting "syncprt"
   1010  * in vfs_syscalls.c using sysctl.
   1011  */
   1012 void
   1013 vfs_bufstats()
   1014 {
   1015 	int s, i, j, count;
   1016 	struct buf *bp;
   1017 	struct bqueues *dp;
   1018 	int counts[(MAXBSIZE / PAGE_SIZE) + 1];
   1019 	static char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE", "EMPTY" };
   1020 
   1021 	for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
   1022 		count = 0;
   1023 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
   1024 			counts[j] = 0;
   1025 		s = splbio();
   1026 		TAILQ_FOREACH(bp, dp, b_freelist) {
   1027 			counts[bp->b_bufsize/PAGE_SIZE]++;
   1028 			count++;
   1029 		}
   1030 		splx(s);
   1031 		printf("%s: total-%d", bname[i], count);
   1032 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
   1033 			if (counts[j] != 0)
   1034 				printf(", %d-%d", j * PAGE_SIZE, counts[j]);
   1035 		printf("\n");
   1036 	}
   1037 }
   1038 #endif /* DEBUG */
   1039