xref: /dragonfly/lib/libc/db/hash/hash_page.c (revision e3146d3a)
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Margo Seltzer.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $FreeBSD: src/lib/libc/db/hash/hash_page.c,v 1.5 2000/01/27 23:06:08 jasone Exp $
33  * $DragonFly: src/lib/libc/db/hash/hash_page.c,v 1.6 2005/09/19 09:20:37 asmodai Exp $
34  *
35  * @(#)hash_page.c	8.7 (Berkeley) 8/16/94
36  */
37 
38 /*
39  * PACKAGE:  hashing
40  *
41  * DESCRIPTION:
42  *	Page manipulation for hashing package.
43  *
44  * ROUTINES:
45  *
46  * External
47  *	__get_page
48  *	__add_ovflpage
49  * Internal
50  *	overflow_page
51  *	open_temp
52  */
53 
54 #include "namespace.h"
55 #include <sys/types.h>
56 
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 #ifdef DEBUG
65 #include <assert.h>
66 #endif
67 #include "un-namespace.h"
68 
69 #include <db.h>
70 #include "hash.h"
71 #include "page.h"
72 #include "extern.h"
73 
74 static u_int32_t	*fetch_bitmap (HTAB *, int);
75 static u_int32_t	 first_free (u_int32_t);
76 static int	 open_temp (HTAB *);
77 static u_int16_t	 overflow_page (HTAB *);
78 static void	 putpair (char *, const DBT *, const DBT *);
79 static void	 squeeze_key (u_int16_t *, const DBT *, const DBT *);
80 static int	 ugly_split
81 		    (HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int);
82 
83 #define	PAGE_INIT(P) { \
84 	((u_int16_t *)(P))[0] = 0; \
85 	((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \
86 	((u_int16_t *)(P))[2] = hashp->BSIZE; \
87 }
88 
89 /*
90  * This is called AFTER we have verified that there is room on the page for
91  * the pair (PAIRFITS has returned true) so we go right ahead and start moving
92  * stuff on.
93  */
94 static void
95 putpair(p, key, val)
96 	char *p;
97 	const DBT *key, *val;
98 {
99 	u_int16_t *bp, n, off;
100 
101 	bp = (u_int16_t *)p;
102 
103 	/* Enter the key first. */
104 	n = bp[0];
105 
106 	off = OFFSET(bp) - key->size;
107 	memmove(p + off, key->data, key->size);
108 	bp[++n] = off;
109 
110 	/* Now the data. */
111 	off -= val->size;
112 	memmove(p + off, val->data, val->size);
113 	bp[++n] = off;
114 
115 	/* Adjust page info. */
116 	bp[0] = n;
117 	bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t));
118 	bp[n + 2] = off;
119 }
120 
121 /*
122  * Returns:
123  *	 0 OK
124  *	-1 error
125  */
126 extern int
127 __delpair(hashp, bufp, ndx)
128 	HTAB *hashp;
129 	BUFHEAD *bufp;
130 	int ndx;
131 {
132 	u_int16_t *bp, newoff;
133 	int n;
134 	u_int16_t pairlen;
135 
136 	bp = (u_int16_t *)bufp->page;
137 	n = bp[0];
138 
139 	if (bp[ndx + 1] < REAL_KEY)
140 		return (__big_delete(hashp, bufp));
141 	if (ndx != 1)
142 		newoff = bp[ndx - 1];
143 	else
144 		newoff = hashp->BSIZE;
145 	pairlen = newoff - bp[ndx + 1];
146 
147 	if (ndx != (n - 1)) {
148 		/* Hard Case -- need to shuffle keys */
149 		int i;
150 		char *src = bufp->page + (int)OFFSET(bp);
151 		char *dst = src + (int)pairlen;
152 		memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
153 
154 		/* Now adjust the pointers */
155 		for (i = ndx + 2; i <= n; i += 2) {
156 			if (bp[i + 1] == OVFLPAGE) {
157 				bp[i - 2] = bp[i];
158 				bp[i - 1] = bp[i + 1];
159 			} else {
160 				bp[i - 2] = bp[i] + pairlen;
161 				bp[i - 1] = bp[i + 1] + pairlen;
162 			}
163 		}
164 	}
165 	/* Finally adjust the page data */
166 	bp[n] = OFFSET(bp) + pairlen;
167 	bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t);
168 	bp[0] = n - 2;
169 	hashp->NKEYS--;
170 
171 	bufp->flags |= BUF_MOD;
172 	return (0);
173 }
174 /*
175  * Returns:
176  *	 0 ==> OK
177  *	-1 ==> Error
178  */
179 extern int
180 __split_page(hashp, obucket, nbucket)
181 	HTAB *hashp;
182 	u_int32_t obucket, nbucket;
183 {
184 	BUFHEAD *new_bufp, *old_bufp;
185 	u_int16_t *ino;
186 	char *np;
187 	DBT key, val;
188 	int n, ndx, retval;
189 	u_int16_t copyto, diff, off, moved;
190 	char *op;
191 
192 	copyto = (u_int16_t)hashp->BSIZE;
193 	off = (u_int16_t)hashp->BSIZE;
194 	old_bufp = __get_buf(hashp, obucket, NULL, 0);
195 	if (old_bufp == NULL)
196 		return (-1);
197 	new_bufp = __get_buf(hashp, nbucket, NULL, 0);
198 	if (new_bufp == NULL)
199 		return (-1);
200 
201 	old_bufp->flags |= (BUF_MOD | BUF_PIN);
202 	new_bufp->flags |= (BUF_MOD | BUF_PIN);
203 
204 	ino = (u_int16_t *)(op = old_bufp->page);
205 	np = new_bufp->page;
206 
207 	moved = 0;
208 
209 	for (n = 1, ndx = 1; n < ino[0]; n += 2) {
210 		if (ino[n + 1] < REAL_KEY) {
211 			retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
212 			    (int)copyto, (int)moved);
213 			old_bufp->flags &= ~BUF_PIN;
214 			new_bufp->flags &= ~BUF_PIN;
215 			return (retval);
216 
217 		}
218 		key.data = (u_char *)op + ino[n];
219 		key.size = off - ino[n];
220 
221 		if (__call_hash(hashp, key.data, key.size) == obucket) {
222 			/* Don't switch page */
223 			diff = copyto - off;
224 			if (diff) {
225 				copyto = ino[n + 1] + diff;
226 				memmove(op + copyto, op + ino[n + 1],
227 				    off - ino[n + 1]);
228 				ino[ndx] = copyto + ino[n] - ino[n + 1];
229 				ino[ndx + 1] = copyto;
230 			} else
231 				copyto = ino[n + 1];
232 			ndx += 2;
233 		} else {
234 			/* Switch page */
235 			val.data = (u_char *)op + ino[n + 1];
236 			val.size = ino[n] - ino[n + 1];
237 			putpair(np, &key, &val);
238 			moved += 2;
239 		}
240 
241 		off = ino[n + 1];
242 	}
243 
244 	/* Now clean up the page */
245 	ino[0] -= moved;
246 	FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3);
247 	OFFSET(ino) = copyto;
248 
249 #ifdef DEBUG3
250 	(void)fprintf(stderr, "split %d/%d\n",
251 	    ((u_int16_t *)np)[0] / 2,
252 	    ((u_int16_t *)op)[0] / 2);
253 #endif
254 	/* unpin both pages */
255 	old_bufp->flags &= ~BUF_PIN;
256 	new_bufp->flags &= ~BUF_PIN;
257 	return (0);
258 }
259 
260 /*
261  * Called when we encounter an overflow or big key/data page during split
262  * handling.  This is special cased since we have to begin checking whether
263  * the key/data pairs fit on their respective pages and because we may need
264  * overflow pages for both the old and new pages.
265  *
266  * The first page might be a page with regular key/data pairs in which case
267  * we have a regular overflow condition and just need to go on to the next
268  * page or it might be a big key/data pair in which case we need to fix the
269  * big key/data pair.
270  *
271  * Returns:
272  *	 0 ==> success
273  *	-1 ==> failure
274  */
275 static int
276 ugly_split(hashp, obucket, old_bufp, new_bufp, copyto, moved)
277 	HTAB *hashp;
278 	u_int32_t obucket;	/* Same as __split_page. */
279 	BUFHEAD *old_bufp, *new_bufp;
280 	int copyto;	/* First byte on page which contains key/data values. */
281 	int moved;	/* Number of pairs moved to new page. */
282 {
283 	BUFHEAD *bufp;	/* Buffer header for ino */
284 	u_int16_t *ino;	/* Page keys come off of */
285 	u_int16_t *np;	/* New page */
286 	u_int16_t *op;	/* Page keys go on to if they aren't moving */
287 
288 	BUFHEAD *last_bfp;	/* Last buf header OVFL needing to be freed */
289 	DBT key, val;
290 	SPLIT_RETURN ret;
291 	u_int16_t n, off, ov_addr, scopyto;
292 	char *cino;		/* Character value of ino */
293 
294 	bufp = old_bufp;
295 	ino = (u_int16_t *)old_bufp->page;
296 	np = (u_int16_t *)new_bufp->page;
297 	op = (u_int16_t *)old_bufp->page;
298 	last_bfp = NULL;
299 	scopyto = (u_int16_t)copyto;	/* ANSI */
300 
301 	n = ino[0] - 1;
302 	while (n < ino[0]) {
303 		if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
304 			if (__big_split(hashp, old_bufp,
305 			    new_bufp, bufp, bufp->addr, obucket, &ret))
306 				return (-1);
307 			old_bufp = ret.oldp;
308 			if (!old_bufp)
309 				return (-1);
310 			op = (u_int16_t *)old_bufp->page;
311 			new_bufp = ret.newp;
312 			if (!new_bufp)
313 				return (-1);
314 			np = (u_int16_t *)new_bufp->page;
315 			bufp = ret.nextp;
316 			if (!bufp)
317 				return (0);
318 			cino = (char *)bufp->page;
319 			ino = (u_int16_t *)cino;
320 			last_bfp = ret.nextp;
321 		} else if (ino[n + 1] == OVFLPAGE) {
322 			ov_addr = ino[n];
323 			/*
324 			 * Fix up the old page -- the extra 2 are the fields
325 			 * which contained the overflow information.
326 			 */
327 			ino[0] -= (moved + 2);
328 			FREESPACE(ino) =
329 			    scopyto - sizeof(u_int16_t) * (ino[0] + 3);
330 			OFFSET(ino) = scopyto;
331 
332 			bufp = __get_buf(hashp, ov_addr, bufp, 0);
333 			if (!bufp)
334 				return (-1);
335 
336 			ino = (u_int16_t *)bufp->page;
337 			n = 1;
338 			scopyto = hashp->BSIZE;
339 			moved = 0;
340 
341 			if (last_bfp)
342 				__free_ovflpage(hashp, last_bfp);
343 			last_bfp = bufp;
344 		}
345 		/* Move regular sized pairs of there are any */
346 		off = hashp->BSIZE;
347 		for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
348 			cino = (char *)ino;
349 			key.data = (u_char *)cino + ino[n];
350 			key.size = off - ino[n];
351 			val.data = (u_char *)cino + ino[n + 1];
352 			val.size = ino[n] - ino[n + 1];
353 			off = ino[n + 1];
354 
355 			if (__call_hash(hashp, key.data, key.size) == obucket) {
356 				/* Keep on old page */
357 				if (PAIRFITS(op, (&key), (&val)))
358 					putpair((char *)op, &key, &val);
359 				else {
360 					old_bufp =
361 					    __add_ovflpage(hashp, old_bufp);
362 					if (!old_bufp)
363 						return (-1);
364 					op = (u_int16_t *)old_bufp->page;
365 					putpair((char *)op, &key, &val);
366 				}
367 				old_bufp->flags |= BUF_MOD;
368 			} else {
369 				/* Move to new page */
370 				if (PAIRFITS(np, (&key), (&val)))
371 					putpair((char *)np, &key, &val);
372 				else {
373 					new_bufp =
374 					    __add_ovflpage(hashp, new_bufp);
375 					if (!new_bufp)
376 						return (-1);
377 					np = (u_int16_t *)new_bufp->page;
378 					putpair((char *)np, &key, &val);
379 				}
380 				new_bufp->flags |= BUF_MOD;
381 			}
382 		}
383 	}
384 	if (last_bfp)
385 		__free_ovflpage(hashp, last_bfp);
386 	return (0);
387 }
388 
389 /*
390  * Add the given pair to the page
391  *
392  * Returns:
393  *	0 ==> OK
394  *	1 ==> failure
395  */
396 extern int
397 __addel(hashp, bufp, key, val)
398 	HTAB *hashp;
399 	BUFHEAD *bufp;
400 	const DBT *key, *val;
401 {
402 	u_int16_t *bp, *sop;
403 	int do_expand;
404 
405 	bp = (u_int16_t *)bufp->page;
406 	do_expand = 0;
407 	while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
408 		/* Exception case */
409 		if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
410 			/* This is the last page of a big key/data pair
411 			   and we need to add another page */
412 			break;
413 		else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
414 			bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
415 			if (!bufp)
416 				return (-1);
417 			bp = (u_int16_t *)bufp->page;
418 		} else
419 			/* Try to squeeze key on this page */
420 			if (FREESPACE(bp) > PAIRSIZE(key, val)) {
421 				squeeze_key(bp, key, val);
422 				return (0);
423 			} else {
424 				bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
425 				if (!bufp)
426 					return (-1);
427 				bp = (u_int16_t *)bufp->page;
428 			}
429 
430 	if (PAIRFITS(bp, key, val))
431 		putpair(bufp->page, key, val);
432 	else {
433 		do_expand = 1;
434 		bufp = __add_ovflpage(hashp, bufp);
435 		if (!bufp)
436 			return (-1);
437 		sop = (u_int16_t *)bufp->page;
438 
439 		if (PAIRFITS(sop, key, val))
440 			putpair((char *)sop, key, val);
441 		else
442 			if (__big_insert(hashp, bufp, key, val))
443 				return (-1);
444 	}
445 	bufp->flags |= BUF_MOD;
446 	/*
447 	 * If the average number of keys per bucket exceeds the fill factor,
448 	 * expand the table.
449 	 */
450 	hashp->NKEYS++;
451 	if (do_expand ||
452 	    (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
453 		return (__expand_table(hashp));
454 	return (0);
455 }
456 
457 /*
458  *
459  * Returns:
460  *	pointer on success
461  *	NULL on error
462  */
463 extern BUFHEAD *
464 __add_ovflpage(hashp, bufp)
465 	HTAB *hashp;
466 	BUFHEAD *bufp;
467 {
468 	u_int16_t *sp;
469 	u_int16_t ndx, ovfl_num;
470 #ifdef DEBUG1
471 	int tmp1, tmp2;
472 #endif
473 	sp = (u_int16_t *)bufp->page;
474 
475 	/* Check if we are dynamically determining the fill factor */
476 	if (hashp->FFACTOR == DEF_FFACTOR) {
477 		hashp->FFACTOR = sp[0] >> 1;
478 		if (hashp->FFACTOR < MIN_FFACTOR)
479 			hashp->FFACTOR = MIN_FFACTOR;
480 	}
481 	bufp->flags |= BUF_MOD;
482 	ovfl_num = overflow_page(hashp);
483 #ifdef DEBUG1
484 	tmp1 = bufp->addr;
485 	tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
486 #endif
487 	if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
488 		return (NULL);
489 	bufp->ovfl->flags |= BUF_MOD;
490 #ifdef DEBUG1
491 	(void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
492 	    tmp1, tmp2, bufp->ovfl->addr);
493 #endif
494 	ndx = sp[0];
495 	/*
496 	 * Since a pair is allocated on a page only if there's room to add
497 	 * an overflow page, we know that the OVFL information will fit on
498 	 * the page.
499 	 */
500 	sp[ndx + 4] = OFFSET(sp);
501 	sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
502 	sp[ndx + 1] = ovfl_num;
503 	sp[ndx + 2] = OVFLPAGE;
504 	sp[0] = ndx + 2;
505 #ifdef HASH_STATISTICS
506 	hash_overflows++;
507 #endif
508 	return (bufp->ovfl);
509 }
510 
511 /*
512  * Returns:
513  *	 0 indicates SUCCESS
514  *	-1 indicates FAILURE
515  */
516 extern int
517 __get_page(hashp, p, bucket, is_bucket, is_disk, is_bitmap)
518 	HTAB *hashp;
519 	char *p;
520 	u_int32_t bucket;
521 	int is_bucket, is_disk, is_bitmap;
522 {
523 	int fd, page, size;
524 	int rsize;
525 	u_int16_t *bp;
526 
527 	fd = hashp->fp;
528 	size = hashp->BSIZE;
529 
530 	if ((fd == -1) || !is_disk) {
531 		PAGE_INIT(p);
532 		return (0);
533 	}
534 	if (is_bucket)
535 		page = BUCKET_TO_PAGE(bucket);
536 	else
537 		page = OADDR_TO_PAGE(bucket);
538 	if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
539 	    ((rsize = _read(fd, p, size)) == -1))
540 		return (-1);
541 	bp = (u_int16_t *)p;
542 	if (!rsize)
543 		bp[0] = 0;	/* We hit the EOF, so initialize a new page */
544 	else
545 		if (rsize != size) {
546 			errno = EFTYPE;
547 			return (-1);
548 		}
549 	if (!is_bitmap && !bp[0]) {
550 		PAGE_INIT(p);
551 	} else
552 		if (hashp->LORDER != BYTE_ORDER) {
553 			int i, max;
554 
555 			if (is_bitmap) {
556 				max = hashp->BSIZE >> 2; /* divide by 4 */
557 				for (i = 0; i < max; i++)
558 					M_32_SWAP(((int *)p)[i]);
559 			} else {
560 				M_16_SWAP(bp[0]);
561 				max = bp[0] + 2;
562 				for (i = 1; i <= max; i++)
563 					M_16_SWAP(bp[i]);
564 			}
565 		}
566 	return (0);
567 }
568 
569 /*
570  * Write page p to disk
571  *
572  * Returns:
573  *	 0 ==> OK
574  *	-1 ==>failure
575  */
576 extern int
577 __put_page(hashp, p, bucket, is_bucket, is_bitmap)
578 	HTAB *hashp;
579 	char *p;
580 	u_int32_t bucket;
581 	int is_bucket, is_bitmap;
582 {
583 	int fd, page, size;
584 	int wsize;
585 
586 	size = hashp->BSIZE;
587 	if ((hashp->fp == -1) && open_temp(hashp))
588 		return (-1);
589 	fd = hashp->fp;
590 
591 	if (hashp->LORDER != BYTE_ORDER) {
592 		int i;
593 		int max;
594 
595 		if (is_bitmap) {
596 			max = hashp->BSIZE >> 2;	/* divide by 4 */
597 			for (i = 0; i < max; i++)
598 				M_32_SWAP(((int *)p)[i]);
599 		} else {
600 			max = ((u_int16_t *)p)[0] + 2;
601 			for (i = 0; i <= max; i++)
602 				M_16_SWAP(((u_int16_t *)p)[i]);
603 		}
604 	}
605 	if (is_bucket)
606 		page = BUCKET_TO_PAGE(bucket);
607 	else
608 		page = OADDR_TO_PAGE(bucket);
609 	if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
610 	    ((wsize = _write(fd, p, size)) == -1))
611 		/* Errno is set */
612 		return (-1);
613 	if (wsize != size) {
614 		errno = EFTYPE;
615 		return (-1);
616 	}
617 	return (0);
618 }
619 
620 #define BYTE_MASK	((1 << INT_BYTE_SHIFT) -1)
621 /*
622  * Initialize a new bitmap page.  Bitmap pages are left in memory
623  * once they are read in.
624  */
625 extern int
626 __ibitmap(hashp, pnum, nbits, ndx)
627 	HTAB *hashp;
628 	int pnum, nbits, ndx;
629 {
630 	u_int32_t *ip;
631 	int clearbytes, clearints;
632 
633 	if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
634 		return (1);
635 	hashp->nmaps++;
636 	clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
637 	clearbytes = clearints << INT_TO_BYTE;
638 	(void)memset((char *)ip, 0, clearbytes);
639 	(void)memset(((char *)ip) + clearbytes, 0xFF,
640 	    hashp->BSIZE - clearbytes);
641 	ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
642 	SETBIT(ip, 0);
643 	hashp->BITMAPS[ndx] = (u_int16_t)pnum;
644 	hashp->mapp[ndx] = ip;
645 	return (0);
646 }
647 
648 static u_int32_t
649 first_free(map)
650 	u_int32_t map;
651 {
652 	u_int32_t i, mask;
653 
654 	mask = 0x1;
655 	for (i = 0; i < BITS_PER_MAP; i++) {
656 		if (!(mask & map))
657 			return (i);
658 		mask = mask << 1;
659 	}
660 	return (i);
661 }
662 
663 static u_int16_t
664 overflow_page(hashp)
665 	HTAB *hashp;
666 {
667 	u_int32_t *freep;
668 	int max_free, offset, splitnum;
669 	u_int16_t addr;
670 	int bit, first_page, free_bit, free_page, i, in_use_bits, j;
671 #ifdef DEBUG2
672 	int tmp1, tmp2;
673 #endif
674 	splitnum = hashp->OVFL_POINT;
675 	max_free = hashp->SPARES[splitnum];
676 
677 	free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
678 	free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
679 
680 	/* Look through all the free maps to find the first free block */
681 	first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
682 	for ( i = first_page; i <= free_page; i++ ) {
683 		if (!(freep = (u_int32_t *)hashp->mapp[i]) &&
684 		    !(freep = fetch_bitmap(hashp, i)))
685 			return (0);
686 		if (i == free_page)
687 			in_use_bits = free_bit;
688 		else
689 			in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
690 
691 		if (i == first_page) {
692 			bit = hashp->LAST_FREED &
693 			    ((hashp->BSIZE << BYTE_SHIFT) - 1);
694 			j = bit / BITS_PER_MAP;
695 			bit = bit & ~(BITS_PER_MAP - 1);
696 		} else {
697 			bit = 0;
698 			j = 0;
699 		}
700 		for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
701 			if (freep[j] != ALL_SET)
702 				goto found;
703 	}
704 
705 	/* No Free Page Found */
706 	hashp->LAST_FREED = hashp->SPARES[splitnum];
707 	hashp->SPARES[splitnum]++;
708 	offset = hashp->SPARES[splitnum] -
709 	    (splitnum ? hashp->SPARES[splitnum - 1] : 0);
710 
711 #define	OVMSG	"HASH: Out of overflow pages.  Increase page size\n"
712 	if (offset > SPLITMASK) {
713 		if (++splitnum >= NCACHED) {
714 			(void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
715 			return (0);
716 		}
717 		hashp->OVFL_POINT = splitnum;
718 		hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
719 		hashp->SPARES[splitnum-1]--;
720 		offset = 1;
721 	}
722 
723 	/* Check if we need to allocate a new bitmap page */
724 	if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
725 		free_page++;
726 		if (free_page >= NCACHED) {
727 			(void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
728 			return (0);
729 		}
730 		/*
731 		 * This is tricky.  The 1 indicates that you want the new page
732 		 * allocated with 1 clear bit.  Actually, you are going to
733 		 * allocate 2 pages from this map.  The first is going to be
734 		 * the map page, the second is the overflow page we were
735 		 * looking for.  The init_bitmap routine automatically, sets
736 		 * the first bit of itself to indicate that the bitmap itself
737 		 * is in use.  We would explicitly set the second bit, but
738 		 * don't have to if we tell init_bitmap not to leave it clear
739 		 * in the first place.
740 		 */
741 		if (__ibitmap(hashp,
742 		    (int)OADDR_OF(splitnum, offset), 1, free_page))
743 			return (0);
744 		hashp->SPARES[splitnum]++;
745 #ifdef DEBUG2
746 		free_bit = 2;
747 #endif
748 		offset++;
749 		if (offset > SPLITMASK) {
750 			if (++splitnum >= NCACHED) {
751 				(void)_write(STDERR_FILENO, OVMSG,
752 				    sizeof(OVMSG) - 1);
753 				return (0);
754 			}
755 			hashp->OVFL_POINT = splitnum;
756 			hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
757 			hashp->SPARES[splitnum-1]--;
758 			offset = 0;
759 		}
760 	} else {
761 		/*
762 		 * Free_bit addresses the last used bit.  Bump it to address
763 		 * the first available bit.
764 		 */
765 		free_bit++;
766 		SETBIT(freep, free_bit);
767 	}
768 
769 	/* Calculate address of the new overflow page */
770 	addr = OADDR_OF(splitnum, offset);
771 #ifdef DEBUG2
772 	(void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
773 	    addr, free_bit, free_page);
774 #endif
775 	return (addr);
776 
777 found:
778 	bit = bit + first_free(freep[j]);
779 	SETBIT(freep, bit);
780 #ifdef DEBUG2
781 	tmp1 = bit;
782 	tmp2 = i;
783 #endif
784 	/*
785 	 * Bits are addressed starting with 0, but overflow pages are addressed
786 	 * beginning at 1. Bit is a bit addressnumber, so we need to increment
787 	 * it to convert it to a page number.
788 	 */
789 	bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
790 	if (bit >= hashp->LAST_FREED)
791 		hashp->LAST_FREED = bit - 1;
792 
793 	/* Calculate the split number for this page */
794 	for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
795 	offset = (i ? bit - hashp->SPARES[i - 1] : bit);
796 	if (offset >= SPLITMASK)
797 		return (0);	/* Out of overflow pages */
798 	addr = OADDR_OF(i, offset);
799 #ifdef DEBUG2
800 	(void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
801 	    addr, tmp1, tmp2);
802 #endif
803 
804 	/* Allocate and return the overflow page */
805 	return (addr);
806 }
807 
808 /*
809  * Mark this overflow page as free.
810  */
811 extern void
812 __free_ovflpage(hashp, obufp)
813 	HTAB *hashp;
814 	BUFHEAD *obufp;
815 {
816 	u_int16_t addr;
817 	u_int32_t *freep;
818 	int bit_address, free_page, free_bit;
819 	u_int16_t ndx;
820 
821 	addr = obufp->addr;
822 #ifdef DEBUG1
823 	(void)fprintf(stderr, "Freeing %d\n", addr);
824 #endif
825 	ndx = (((u_int16_t)addr) >> SPLITSHIFT);
826 	bit_address =
827 	    (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
828 	 if (bit_address < hashp->LAST_FREED)
829 		hashp->LAST_FREED = bit_address;
830 	free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
831 	free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
832 
833 	if (!(freep = hashp->mapp[free_page]))
834 		freep = fetch_bitmap(hashp, free_page);
835 #ifdef DEBUG
836 	/*
837 	 * This had better never happen.  It means we tried to read a bitmap
838 	 * that has already had overflow pages allocated off it, and we
839 	 * failed to read it from the file.
840 	 */
841 	if (!freep)
842 		assert(0);
843 #endif
844 	CLRBIT(freep, free_bit);
845 #ifdef DEBUG2
846 	(void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
847 	    obufp->addr, free_bit, free_page);
848 #endif
849 	__reclaim_buf(hashp, obufp);
850 }
851 
852 /*
853  * Returns:
854  *	 0 success
855  *	-1 failure
856  */
857 static int
858 open_temp(hashp)
859 	HTAB *hashp;
860 {
861 	sigset_t set, oset;
862 	static char namestr[] = "_hashXXXXXX";
863 
864 	/* Block signals; make sure file goes away at process exit. */
865 	(void)sigfillset(&set);
866 	(void)_sigprocmask(SIG_BLOCK, &set, &oset);
867 	if ((hashp->fp = mkstemp(namestr)) != -1) {
868 		(void)unlink(namestr);
869 		(void)_fcntl(hashp->fp, F_SETFD, 1);
870 	}
871 	(void)_sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
872 	return (hashp->fp != -1 ? 0 : -1);
873 }
874 
875 /*
876  * We have to know that the key will fit, but the last entry on the page is
877  * an overflow pair, so we need to shift things.
878  */
879 static void
880 squeeze_key(sp, key, val)
881 	u_int16_t *sp;
882 	const DBT *key, *val;
883 {
884 	char *p;
885 	u_int16_t free_space, n, off, pageno;
886 
887 	p = (char *)sp;
888 	n = sp[0];
889 	free_space = FREESPACE(sp);
890 	off = OFFSET(sp);
891 
892 	pageno = sp[n - 1];
893 	off -= key->size;
894 	sp[n - 1] = off;
895 	memmove(p + off, key->data, key->size);
896 	off -= val->size;
897 	sp[n] = off;
898 	memmove(p + off, val->data, val->size);
899 	sp[0] = n + 2;
900 	sp[n + 1] = pageno;
901 	sp[n + 2] = OVFLPAGE;
902 	FREESPACE(sp) = free_space - PAIRSIZE(key, val);
903 	OFFSET(sp) = off;
904 }
905 
906 static u_int32_t *
907 fetch_bitmap(hashp, ndx)
908 	HTAB *hashp;
909 	int ndx;
910 {
911 	if (ndx >= hashp->nmaps)
912 		return (NULL);
913 	if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
914 		return (NULL);
915 	if (__get_page(hashp,
916 	    (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
917 		free(hashp->mapp[ndx]);
918 		return (NULL);
919 	}
920 	return (hashp->mapp[ndx]);
921 }
922 
923 #ifdef DEBUG4
924 int
925 print_chain(addr)
926 	int addr;
927 {
928 	BUFHEAD *bufp;
929 	short *bp, oaddr;
930 
931 	(void)fprintf(stderr, "%d ", addr);
932 	bufp = __get_buf(hashp, addr, NULL, 0);
933 	bp = (short *)bufp->page;
934 	while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
935 		((bp[0] > 2) && bp[2] < REAL_KEY))) {
936 		oaddr = bp[bp[0] - 1];
937 		(void)fprintf(stderr, "%d ", (int)oaddr);
938 		bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
939 		bp = (short *)bufp->page;
940 	}
941 	(void)fprintf(stderr, "\n");
942 }
943 #endif
944