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