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