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