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