xref: /netbsd-src/sbin/fsck_lfs/bufcache.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /* $NetBSD: bufcache.c,v 1.7 2005/05/20 18:59:36 perseant Exp $ */
2 /*-
3  * Copyright (c) 2003 The NetBSD Foundation, Inc.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to The NetBSD Foundation
7  * by Konrad E. Schroder <perseant@hhhh.org>.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by the NetBSD
20  *	Foundation, Inc. and its contributors.
21  * 4. Neither the name of The NetBSD Foundation nor the names of its
22  *    contributors may be used to endorse or promote products derived
23  *    from this software without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/time.h>
41 #include <sys/buf.h>
42 #include <sys/queue.h>
43 #include <sys/mount.h>
44 
45 #include <assert.h>
46 #include <err.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 
52 #include "bufcache.h"
53 #include "vnode.h"
54 
55 /*
56  * Definitions for the buffer free lists.
57  */
58 #define	BQUEUES		3	/* number of free buffer queues */
59 
60 #define	BQ_LOCKED	0	/* super-blocks &c */
61 #define	BQ_LRU		1	/* lru, useful buffers */
62 #define	BQ_AGE		2	/* rubbish */
63 
64 TAILQ_HEAD(bqueues, ubuf) bufqueues[BQUEUES];
65 
66 struct bufhash_struct *bufhash;
67 
68 #define HASH_MAX 1024
69 int hashmax  = HASH_MAX;
70 int hashmask = (HASH_MAX - 1);
71 
72 int maxbufs = BUF_CACHE_SIZE;
73 int nbufs = 0;
74 int cachehits = 0;
75 int cachemisses = 0;
76 int max_depth = 0;
77 off_t locked_queue_bytes = 0;
78 int locked_queue_count = 0;
79 
80 /* Simple buffer hash function */
81 static int
82 vl_hash(struct uvnode * vp, daddr_t lbn)
83 {
84 	return (int)((unsigned long) vp + lbn) & hashmask;
85 }
86 
87 /* Initialize buffer cache */
88 void
89 bufinit(int max)
90 {
91 	int i;
92 
93 	if (max) {
94 		for (hashmax = 1; hashmax < max; hashmax <<= 1)
95 			;
96 		hashmask = hashmax - 1;
97 	}
98 
99 	for (i = 0; i < BQUEUES; i++) {
100 		TAILQ_INIT(&bufqueues[i]);
101 	}
102 	bufhash = (struct bufhash_struct *)malloc(hashmax * sizeof(*bufhash));
103 	for (i = 0; i < hashmax; i++)
104 		LIST_INIT(&bufhash[i]);
105 }
106 
107 /* Widen the hash table. */
108 void bufrehash(int max)
109 {
110 	int i, newhashmax, newhashmask;
111 	struct ubuf *bp, *nbp;
112 	struct bufhash_struct *np;
113 
114 	if (max < 0 || max < hashmax)
115 		return;
116 
117 	/* Round up to a power of two */
118 	for (newhashmax = 1; newhashmax < max; newhashmax <<= 1)
119 		;
120 	newhashmask = newhashmax - 1;
121 
122 	/* Allocate new empty hash table, if we can */
123 	np = (struct bufhash_struct *)malloc(newhashmax * sizeof(*bufhash));
124 		if (np == NULL)
125 			return;
126 	for (i = 0; i < newhashmax; i++)
127 		LIST_INIT(&np[i]);
128 
129 	/* Now reassign all existing buffers to their new hash chains. */
130 	for (i = 0; i < hashmax; i++) {
131 		bp = LIST_FIRST(&bufhash[i]);
132 		while(bp) {
133 			nbp = LIST_NEXT(bp, b_hash);
134 			LIST_REMOVE(bp, b_hash);
135 			bp->b_hashval = vl_hash(bp->b_vp, bp->b_lblkno);
136 			LIST_INSERT_HEAD(&np[bp->b_hashval], bp, b_hash);
137 			bp = nbp;
138 		}
139 	}
140 
141 	/* Switch over and clean up */
142 	free(bufhash);
143 	bufhash = np;
144 	hashmax = newhashmax;
145 	hashmask = newhashmask;
146 }
147 
148 /* Print statistics of buffer cache usage */
149 void
150 bufstats(void)
151 {
152 	printf("buffer cache: %d hits %d misses (%2.2f%%); hash width %d, depth %d\n",
153 	    cachehits, cachemisses,
154 	    (cachehits * 100.0) / (cachehits + cachemisses),
155 	    hashmax, max_depth);
156 }
157 
158 /*
159  * Remove a buffer from the cache.
160  * Caller must remove the buffer from its free list.
161  */
162 void
163 buf_destroy(struct ubuf * bp)
164 {
165 	bp->b_flags |= B_NEEDCOMMIT;
166 	LIST_REMOVE(bp, b_vnbufs);
167 	LIST_REMOVE(bp, b_hash);
168 	if (!(bp->b_flags & B_DONTFREE))
169 		free(bp->b_data);
170 	free(bp);
171 	--nbufs;
172 }
173 
174 /* Remove a buffer from its free list. */
175 void
176 bremfree(struct ubuf * bp)
177 {
178 	struct bqueues *dp = NULL;
179 
180 	/*
181 	 * We only calculate the head of the freelist when removing
182 	 * the last element of the list as that is the only time that
183 	 * it is needed (e.g. to reset the tail pointer).
184 	 *
185 	 * NB: This makes an assumption about how tailq's are implemented.
186 	 */
187 	if (bp->b_flags & B_LOCKED) {
188 		locked_queue_bytes -= bp->b_bcount;
189 		--locked_queue_count;
190 	}
191 	if (TAILQ_NEXT(bp, b_freelist) == NULL) {
192 		for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
193 			if (dp->tqh_last == &bp->b_freelist.tqe_next)
194 				break;
195 		if (dp == &bufqueues[BQUEUES])
196 			errx(1, "bremfree: lost tail");
197 	}
198 	++bp->b_vp->v_usecount;
199 	TAILQ_REMOVE(dp, bp, b_freelist);
200 }
201 
202 /* Return a buffer if it is in the cache, otherwise return NULL. */
203 struct ubuf *
204 incore(struct uvnode * vp, int lbn)
205 {
206 	struct ubuf *bp;
207 	int hash, depth;
208 
209 	hash = vl_hash(vp, lbn);
210 	/* XXX use a real hash instead. */
211 	depth = 0;
212 	LIST_FOREACH(bp, &bufhash[hash], b_hash) {
213 		if (++depth > max_depth)
214 			max_depth = depth;
215 		assert(depth <= nbufs);
216 		if (bp->b_vp == vp && bp->b_lblkno == lbn) {
217 			return bp;
218 		}
219 	}
220 	return NULL;
221 }
222 
223 /*
224  * Return a buffer of the given size, lbn and uvnode.
225  * If none is in core, make a new one.
226  */
227 struct ubuf *
228 getblk(struct uvnode * vp, daddr_t lbn, int size)
229 {
230 	struct ubuf *bp;
231 #ifdef DEBUG
232 	static int warned;
233 #endif
234 
235 	/*
236 	 * First check the buffer cache lists.
237 	 * We might sometimes need to resize a buffer.  If we are growing
238 	 * the buffer, its contents are invalid; but shrinking is okay.
239 	 */
240 	if ((bp = incore(vp, lbn)) != NULL) {
241 		assert(!(bp->b_flags & B_NEEDCOMMIT));
242 		assert(!(bp->b_flags & B_BUSY));
243 		bp->b_flags |= B_BUSY;
244 		bremfree(bp);
245 		if (bp->b_bcount == size)
246 			return bp;
247 		else if (bp->b_bcount > size) {
248 			assert(!(bp->b_flags & B_DELWRI));
249 			bp->b_bcount = size;
250 			bp->b_data = realloc(bp->b_data, size);
251 			return bp;
252 		}
253 
254 		buf_destroy(bp);
255 		bp = NULL;
256 	}
257 
258 	/*
259 	 * Not on the list.
260 	 * Get a new block of the appropriate size and use that.
261 	 * If not enough space, free blocks from the AGE and LRU lists
262 	 * to make room.
263 	 */
264 	while (nbufs >= maxbufs + locked_queue_count) {
265 		bp = TAILQ_FIRST(&bufqueues[BQ_AGE]);
266 		if (bp)
267 			TAILQ_REMOVE(&bufqueues[BQ_AGE], bp, b_freelist);
268 		if (bp == NULL) {
269 			bp = TAILQ_FIRST(&bufqueues[BQ_LRU]);
270 			if (bp)
271 				TAILQ_REMOVE(&bufqueues[BQ_LRU], bp,
272 				    b_freelist);
273 		}
274 		if (bp) {
275 			if (bp->b_flags & B_DELWRI)
276 				VOP_STRATEGY(bp);
277 			buf_destroy(bp);
278 			break;
279 		}
280 #ifdef DEBUG
281 		else if (!warned) {
282 			warnx("allocating more than %d buffers", maxbufs);
283 			++warned;
284 		}
285 #endif
286 		break;
287 	}
288 	++nbufs;
289 	bp = (struct ubuf *) malloc(sizeof(*bp));
290 	memset(bp, 0, sizeof(*bp));
291 	bp->b_data = malloc(size);
292 	memset(bp->b_data, 0, size);
293 
294 	bp->b_vp = vp;
295 	bp->b_blkno = bp->b_lblkno = lbn;
296 	bp->b_bcount = size;
297 	bp->b_hashval = vl_hash(vp, lbn);
298 	LIST_INSERT_HEAD(&bufhash[bp->b_hashval], bp, b_hash);
299 	LIST_INSERT_HEAD(&vp->v_cleanblkhd, bp, b_vnbufs);
300 	bp->b_flags = B_BUSY;
301 
302 	return bp;
303 }
304 
305 /* Write a buffer to disk according to its strategy routine. */
306 void
307 bwrite(struct ubuf * bp)
308 {
309 	bp->b_flags &= ~(B_READ | B_DONE | B_DELWRI | B_LOCKED);
310 	VOP_STRATEGY(bp);
311 	bp->b_flags |= B_DONE;
312 	reassignbuf(bp, bp->b_vp);
313 	brelse(bp);
314 }
315 
316 /* Put a buffer back on its free list, clear B_BUSY. */
317 void
318 brelse(struct ubuf * bp)
319 {
320 	int age;
321 
322 	assert(!(bp->b_flags & B_NEEDCOMMIT));
323 	assert(bp->b_flags & B_BUSY);
324 
325 	age = bp->b_flags & B_AGE;
326 	bp->b_flags &= ~(B_BUSY | B_AGE);
327 	if (bp->b_flags & B_INVAL) {
328 		buf_destroy(bp);
329 		return;
330 	}
331 	if (bp->b_flags & B_LOCKED) {
332 		locked_queue_bytes += bp->b_bcount;
333 		++locked_queue_count;
334 		TAILQ_INSERT_TAIL(&bufqueues[BQ_LOCKED], bp, b_freelist);
335 	} else if (age) {
336 		TAILQ_INSERT_TAIL(&bufqueues[BQ_AGE], bp, b_freelist);
337 	} else {
338 		TAILQ_INSERT_TAIL(&bufqueues[BQ_LRU], bp, b_freelist);
339 	}
340 	--bp->b_vp->v_usecount;
341 
342 	/* Move to the front of the hash chain */
343 	if (LIST_FIRST(&bufhash[bp->b_hashval]) != bp) {
344 		LIST_REMOVE(bp, b_hash);
345 		LIST_INSERT_HEAD(&bufhash[bp->b_hashval], bp, b_hash);
346 	}
347 }
348 
349 /* Read the given block from disk, return it B_BUSY. */
350 int
351 bread(struct uvnode * vp, daddr_t lbn, int size, struct ucred * unused,
352     struct ubuf ** bpp)
353 {
354 	struct ubuf *bp;
355 	daddr_t daddr;
356 	int error;
357 
358 	bp = getblk(vp, lbn, size);
359 	*bpp = bp;
360 	if (bp->b_flags & (B_DELWRI | B_DONE)) {
361 		++cachehits;
362 		return 0;
363 	}
364 	++cachemisses;
365 
366 	/*
367 	 * Not found.  Need to find that block's location on disk,
368 	 * and load it in.
369 	 */
370 	daddr = -1;
371 	error = VOP_BMAP(vp, lbn, &daddr);
372 	bp->b_blkno = daddr;
373 	if (daddr >= 0) {
374 		bp->b_flags |= B_READ;
375 		return VOP_STRATEGY(bp);
376 	}
377 	memset(bp->b_data, 0, bp->b_bcount);
378 	return 0;
379 }
380 
381 /* Move a buffer between dirty and clean block lists. */
382 void
383 reassignbuf(struct ubuf * bp, struct uvnode * vp)
384 {
385 	LIST_REMOVE(bp, b_vnbufs);
386 	if (bp->b_flags & B_DELWRI) {
387 		LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
388 	} else {
389 		LIST_INSERT_HEAD(&vp->v_cleanblkhd, bp, b_vnbufs);
390 	}
391 }
392 
393 #ifdef DEBUG
394 void
395 dump_free_lists(void)
396 {
397 	struct ubuf *bp;
398 	int i;
399 
400 	for (i = 0; i <= BQ_LOCKED; i++) {
401 		printf("==> free list %d:\n", i);
402 		TAILQ_FOREACH(bp, &bufqueues[i], b_freelist) {
403 			printf("vp %p lbn %" PRId64 " flags %lx\n",
404 				bp->b_vp, bp->b_lblkno, bp->b_flags);
405 		}
406 	}
407 }
408 #endif
409