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