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