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