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