xref: /netbsd-src/lib/libc/db/mpool/mpool.c (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1 /*	$NetBSD: mpool.c,v 1.16 2007/02/03 23:46:09 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 #if 0
35 static char sccsid[] = "@(#)mpool.c	8.5 (Berkeley) 7/26/94";
36 #else
37 __RCSID("$NetBSD: mpool.c,v 1.16 2007/02/03 23:46:09 christos Exp $");
38 #endif
39 #endif /* LIBC_SCCS and not lint */
40 
41 #include "namespace.h"
42 #include <sys/queue.h>
43 #include <sys/stat.h>
44 
45 #include <errno.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include <db.h>
52 
53 #define	__MPOOLINTERFACE_PRIVATE
54 #include <mpool.h>
55 
56 #ifdef __weak_alias
57 __weak_alias(mpool_close,_mpool_close)
58 __weak_alias(mpool_filter,_mpool_filter)
59 __weak_alias(mpool_get,_mpool_get)
60 __weak_alias(mpool_new,_mpool_new)
61 __weak_alias(mpool_open,_mpool_open)
62 __weak_alias(mpool_put,_mpool_put)
63 __weak_alias(mpool_sync,_mpool_sync)
64 #endif
65 
66 static BKT *mpool_bkt(MPOOL *);
67 static BKT *mpool_look(MPOOL *, pgno_t);
68 static int  mpool_write(MPOOL *, BKT *);
69 
70 /*
71  * mpool_open --
72  *	Initialize a memory pool.
73  */
74 /*ARGSUSED*/
75 MPOOL *
76 mpool_open(void *key, int fd, pgno_t pagesize, pgno_t maxcache)
77 {
78 	struct stat sb;
79 	MPOOL *mp;
80 	int entry;
81 
82 	/*
83 	 * Get information about the file.
84 	 *
85 	 * XXX
86 	 * We don't currently handle pipes, although we should.
87 	 */
88 	if (fstat(fd, &sb))
89 		return (NULL);
90 	if (!S_ISREG(sb.st_mode)) {
91 		errno = ESPIPE;
92 		return (NULL);
93 	}
94 
95 	/* Allocate and initialize the MPOOL cookie. */
96 	if ((mp = (MPOOL *)calloc(1, sizeof(MPOOL))) == NULL)
97 		return (NULL);
98 	CIRCLEQ_INIT(&mp->lqh);
99 	for (entry = 0; entry < HASHSIZE; ++entry)
100 		CIRCLEQ_INIT(&mp->hqh[entry]);
101 	mp->maxcache = maxcache;
102 	mp->npages = (pgno_t)(sb.st_size / pagesize);
103 	mp->pagesize = pagesize;
104 	mp->fd = fd;
105 	return (mp);
106 }
107 
108 /*
109  * mpool_filter --
110  *	Initialize input/output filters.
111  */
112 void
113 mpool_filter(MPOOL *mp, void (*pgin)(void *, pgno_t, void *),
114     void (*pgout)(void *, pgno_t, void *), void *pgcookie)
115 {
116 	mp->pgin = pgin;
117 	mp->pgout = pgout;
118 	mp->pgcookie = pgcookie;
119 }
120 
121 /*
122  * mpool_new --
123  *	Get a new page of memory.
124  */
125 void *
126 mpool_new( MPOOL *mp, pgno_t *pgnoaddr)
127 {
128 	struct _hqh *head;
129 	BKT *bp;
130 
131 	if (mp->npages == MAX_PAGE_NUMBER) {
132 		(void)fprintf(stderr, "mpool_new: page allocation overflow.\n");
133 		abort();
134 	}
135 #ifdef STATISTICS
136 	++mp->pagenew;
137 #endif
138 	/*
139 	 * Get a BKT from the cache.  Assign a new page number, attach
140 	 * it to the head of the hash chain, the tail of the lru chain,
141 	 * and return.
142 	 */
143 	if ((bp = mpool_bkt(mp)) == NULL)
144 		return (NULL);
145 	*pgnoaddr = bp->pgno = mp->npages++;
146 	bp->flags = MPOOL_PINNED;
147 
148 	head = &mp->hqh[HASHKEY(bp->pgno)];
149 	CIRCLEQ_INSERT_HEAD(head, bp, hq);
150 	CIRCLEQ_INSERT_TAIL(&mp->lqh, bp, q);
151 	return (bp->page);
152 }
153 
154 /*
155  * mpool_get
156  *	Get a page.
157  */
158 /*ARGSUSED*/
159 void *
160 mpool_get(MPOOL *mp, pgno_t pgno, u_int flags)
161 {
162 	struct _hqh *head;
163 	BKT *bp;
164 	off_t off;
165 	ssize_t nr;
166 
167 	/* Check for attempt to retrieve a non-existent page. */
168 	if (pgno >= mp->npages) {
169 		errno = EINVAL;
170 		return (NULL);
171 	}
172 
173 #ifdef STATISTICS
174 	++mp->pageget;
175 #endif
176 
177 	/* Check for a page that is cached. */
178 	if ((bp = mpool_look(mp, pgno)) != NULL) {
179 #ifdef DEBUG
180 		if (bp->flags & MPOOL_PINNED) {
181 			(void)fprintf(stderr,
182 			    "mpool_get: page %d already pinned\n", bp->pgno);
183 			abort();
184 		}
185 #endif
186 		/*
187 		 * Move the page to the head of the hash chain and the tail
188 		 * of the lru chain.
189 		 */
190 		head = &mp->hqh[HASHKEY(bp->pgno)];
191 		CIRCLEQ_REMOVE(head, bp, hq);
192 		CIRCLEQ_INSERT_HEAD(head, bp, hq);
193 		CIRCLEQ_REMOVE(&mp->lqh, bp, q);
194 		CIRCLEQ_INSERT_TAIL(&mp->lqh, bp, q);
195 
196 		/* Return a pinned page. */
197 		bp->flags |= MPOOL_PINNED;
198 		return (bp->page);
199 	}
200 
201 	/* Get a page from the cache. */
202 	if ((bp = mpool_bkt(mp)) == NULL)
203 		return (NULL);
204 
205 	/* Read in the contents. */
206 #ifdef STATISTICS
207 	++mp->pageread;
208 #endif
209 	off = mp->pagesize * pgno;
210 	if ((nr = pread(mp->fd, bp->page, (size_t)mp->pagesize, off)) != (int)mp->pagesize) {
211 		if (nr >= 0)
212 			errno = EFTYPE;
213 		return (NULL);
214 	}
215 
216 	/* Set the page number, pin the page. */
217 	bp->pgno = pgno;
218 	bp->flags = MPOOL_PINNED;
219 
220 	/*
221 	 * Add the page to the head of the hash chain and the tail
222 	 * of the lru chain.
223 	 */
224 	head = &mp->hqh[HASHKEY(bp->pgno)];
225 	CIRCLEQ_INSERT_HEAD(head, bp, hq);
226 	CIRCLEQ_INSERT_TAIL(&mp->lqh, bp, q);
227 
228 	/* Run through the user's filter. */
229 	if (mp->pgin != NULL)
230 		(mp->pgin)(mp->pgcookie, bp->pgno, bp->page);
231 
232 	return (bp->page);
233 }
234 
235 /*
236  * mpool_put
237  *	Return a page.
238  */
239 /*ARGSUSED*/
240 int
241 mpool_put(MPOOL *mp, void *page, u_int flags)
242 {
243 	BKT *bp;
244 
245 #ifdef STATISTICS
246 	++mp->pageput;
247 #endif
248 	bp = (BKT *)(void *)((char *)page - sizeof(BKT));
249 #ifdef DEBUG
250 	if (!(bp->flags & MPOOL_PINNED)) {
251 		(void)fprintf(stderr,
252 		    "mpool_put: page %d not pinned\n", bp->pgno);
253 		abort();
254 	}
255 #endif
256 	bp->flags &= ~MPOOL_PINNED;
257 	bp->flags |= flags & MPOOL_DIRTY;
258 	return (RET_SUCCESS);
259 }
260 
261 /*
262  * mpool_close
263  *	Close the buffer pool.
264  */
265 int
266 mpool_close(MPOOL *mp)
267 {
268 	BKT *bp;
269 
270 	/* Free up any space allocated to the lru pages. */
271 	while ((bp = mp->lqh.cqh_first) != (void *)&mp->lqh) {
272 		CIRCLEQ_REMOVE(&mp->lqh, mp->lqh.cqh_first, q);
273 		free(bp);
274 	}
275 
276 	/* Free the MPOOL cookie. */
277 	free(mp);
278 	return (RET_SUCCESS);
279 }
280 
281 /*
282  * mpool_sync
283  *	Sync the pool to disk.
284  */
285 int
286 mpool_sync(MPOOL *mp)
287 {
288 	BKT *bp;
289 
290 	/* Walk the lru chain, flushing any dirty pages to disk. */
291 	for (bp = mp->lqh.cqh_first;
292 	    bp != (void *)&mp->lqh; bp = bp->q.cqe_next)
293 		if (bp->flags & MPOOL_DIRTY &&
294 		    mpool_write(mp, bp) == RET_ERROR)
295 			return (RET_ERROR);
296 
297 	/* Sync the file descriptor. */
298 	return (fsync(mp->fd) ? RET_ERROR : RET_SUCCESS);
299 }
300 
301 /*
302  * mpool_bkt
303  *	Get a page from the cache (or create one).
304  */
305 static BKT *
306 mpool_bkt(MPOOL *mp)
307 {
308 	struct _hqh *head;
309 	BKT *bp;
310 
311 	/* If under the max cached, always create a new page. */
312 	if (mp->curcache < mp->maxcache)
313 		goto new;
314 
315 	/*
316 	 * If the cache is max'd out, walk the lru list for a buffer we
317 	 * can flush.  If we find one, write it (if necessary) and take it
318 	 * off any lists.  If we don't find anything we grow the cache anyway.
319 	 * The cache never shrinks.
320 	 */
321 	for (bp = mp->lqh.cqh_first;
322 	    bp != (void *)&mp->lqh; bp = bp->q.cqe_next)
323 		if (!(bp->flags & MPOOL_PINNED)) {
324 			/* Flush if dirty. */
325 			if (bp->flags & MPOOL_DIRTY &&
326 			    mpool_write(mp, bp) == RET_ERROR)
327 				return (NULL);
328 #ifdef STATISTICS
329 			++mp->pageflush;
330 #endif
331 			/* Remove from the hash and lru queues. */
332 			head = &mp->hqh[HASHKEY(bp->pgno)];
333 			CIRCLEQ_REMOVE(head, bp, hq);
334 			CIRCLEQ_REMOVE(&mp->lqh, bp, q);
335 #ifdef DEBUG
336 			{
337 				void *spage = bp->page;
338 				(void)memset(bp, 0xff,
339 				    (size_t)(sizeof(BKT) + mp->pagesize));
340 				bp->page = spage;
341 			}
342 #endif
343 			return (bp);
344 		}
345 
346 new:	if ((bp = (BKT *)malloc((size_t)(sizeof(BKT) + mp->pagesize))) == NULL)
347 		return (NULL);
348 #ifdef STATISTICS
349 	++mp->pagealloc;
350 #endif
351 #if defined(DEBUG) || defined(PURIFY)
352 	(void)memset(bp, 0xff, (size_t)(sizeof(BKT) + mp->pagesize));
353 #endif
354 	bp->page = (char *)(void *)bp + sizeof(BKT);
355 	++mp->curcache;
356 	return (bp);
357 }
358 
359 /*
360  * mpool_write
361  *	Write a page to disk.
362  */
363 static int
364 mpool_write(MPOOL *mp, BKT *bp)
365 {
366 	off_t off;
367 
368 #ifdef STATISTICS
369 	++mp->pagewrite;
370 #endif
371 
372 	/* Run through the user's filter. */
373 	if (mp->pgout)
374 		(mp->pgout)(mp->pgcookie, bp->pgno, bp->page);
375 
376 	off = mp->pagesize * bp->pgno;
377 	if (pwrite(mp->fd, bp->page, (size_t)mp->pagesize, off) != (int)mp->pagesize)
378 		return (RET_ERROR);
379 
380 	/*
381 	 * Re-run through the input filter since this page may soon be
382 	 * accessed via the cache, and whatever the user's output filter
383 	 * did may screw things up if we don't let the input filter
384 	 * restore the in-core copy.
385 	 */
386 	if (mp->pgin)
387 		(mp->pgin)(mp->pgcookie, bp->pgno, bp->page);
388 
389 	bp->flags &= ~MPOOL_DIRTY;
390 	return (RET_SUCCESS);
391 }
392 
393 /*
394  * mpool_look
395  *	Lookup a page in the cache.
396  */
397 static BKT *
398 mpool_look(MPOOL *mp, pgno_t pgno)
399 {
400 	struct _hqh *head;
401 	BKT *bp;
402 
403 	head = &mp->hqh[HASHKEY(pgno)];
404 	for (bp = head->cqh_first; bp != (void *)head; bp = bp->hq.cqe_next)
405 		if (bp->pgno == pgno) {
406 #ifdef STATISTICS
407 			++mp->cachehit;
408 #endif
409 			return (bp);
410 		}
411 #ifdef STATISTICS
412 	++mp->cachemiss;
413 #endif
414 	return (NULL);
415 }
416 
417 #ifdef STATISTICS
418 /*
419  * mpool_stat
420  *	Print out cache statistics.
421  */
422 void
423 mpool_stat(mp)
424 	MPOOL *mp;
425 {
426 	BKT *bp;
427 	int cnt;
428 	const char *sep;
429 
430 	(void)fprintf(stderr, "%lu pages in the file\n", (u_long)mp->npages);
431 	(void)fprintf(stderr,
432 	    "page size %lu, cacheing %lu pages of %lu page max cache\n",
433 	    (u_long)mp->pagesize, (u_long)mp->curcache, (u_long)mp->maxcache);
434 	(void)fprintf(stderr, "%lu page puts, %lu page gets, %lu page new\n",
435 	    mp->pageput, mp->pageget, mp->pagenew);
436 	(void)fprintf(stderr, "%lu page allocs, %lu page flushes\n",
437 	    mp->pagealloc, mp->pageflush);
438 	if (mp->cachehit + mp->cachemiss)
439 		(void)fprintf(stderr,
440 		    "%.0f%% cache hit rate (%lu hits, %lu misses)\n",
441 		    ((double)mp->cachehit / (mp->cachehit + mp->cachemiss))
442 		    * 100, mp->cachehit, mp->cachemiss);
443 	(void)fprintf(stderr, "%lu page reads, %lu page writes\n",
444 	    mp->pageread, mp->pagewrite);
445 
446 	sep = "";
447 	cnt = 0;
448 	for (bp = mp->lqh.cqh_first;
449 	    bp != (void *)&mp->lqh; bp = bp->q.cqe_next) {
450 		(void)fprintf(stderr, "%s%d", sep, bp->pgno);
451 		if (bp->flags & MPOOL_DIRTY)
452 			(void)fprintf(stderr, "d");
453 		if (bp->flags & MPOOL_PINNED)
454 			(void)fprintf(stderr, "P");
455 		if (++cnt == 10) {
456 			sep = "\n";
457 			cnt = 0;
458 		} else
459 			sep = ", ";
460 
461 	}
462 	(void)fprintf(stderr, "\n");
463 }
464 #endif
465