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