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