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