Home | History | Annotate | Line # | Download | only in hash
hash.c revision 1.30
      1 /*	$NetBSD: hash.c,v 1.30 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.c,v 1.30 2008/09/11 12:58:00 joerg Exp $");
     41 
     42 #include "namespace.h"
     43 #include <sys/param.h>
     44 #include <sys/stat.h>
     45 
     46 #include <errno.h>
     47 #include <fcntl.h>
     48 #include <stdio.h>
     49 #include <stdlib.h>
     50 #include <string.h>
     51 #include <unistd.h>
     52 #include <assert.h>
     53 
     54 #include <db.h>
     55 #include "hash.h"
     56 #include "page.h"
     57 #include "extern.h"
     58 
     59 static int   alloc_segs(HTAB *, int);
     60 static int   flush_meta(HTAB *);
     61 static int   hash_access(HTAB *, ACTION, DBT *, DBT *);
     62 static int   hash_close(DB *);
     63 static int   hash_delete(const DB *, const DBT *, uint32_t);
     64 static int   hash_fd(const DB *);
     65 static int   hash_get(const DB *, const DBT *, DBT *, uint32_t);
     66 static int   hash_put(const DB *, DBT *, const DBT *, uint32_t);
     67 static void *hash_realloc(SEGMENT **, size_t, size_t);
     68 static int   hash_seq(const DB *, DBT *, DBT *, uint32_t);
     69 static int   hash_sync(const DB *, uint32_t);
     70 static int   hdestroy(HTAB *);
     71 static HTAB *init_hash(HTAB *, const char *, const HASHINFO *);
     72 static int   init_htab(HTAB *, size_t);
     73 #if BYTE_ORDER == LITTLE_ENDIAN
     74 static void  swap_header(HTAB *);
     75 static void  swap_header_copy(HASHHDR *, HASHHDR *);
     76 #endif
     77 
     78 /* Fast arithmetic, relying on powers of 2, */
     79 #define MOD(x, y)		((x) & ((y) - 1))
     80 
     81 #define RETURN_ERROR(ERR, LOC)	{ save_errno = ERR; goto LOC; }
     82 
     83 /* Return values */
     84 #define	SUCCESS	 (0)
     85 #define	ERROR	(-1)
     86 #define	ABNORMAL (1)
     87 
     88 #ifdef HASH_STATISTICS
     89 int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
     90 #endif
     91 
     92 /************************** INTERFACE ROUTINES ***************************/
     93 /* OPEN/CLOSE */
     94 
     95 /* ARGSUSED */
     96 DB *
     97 __hash_open(const char *file, int flags, mode_t mode, const HASHINFO *info,
     98     int dflags)
     99 {
    100 	HTAB *hashp;
    101 	struct stat statbuf;
    102 	DB *dbp;
    103 	int bpages, new_table, nsegs, save_errno;
    104 	ssize_t hdrsize;
    105 
    106 	if ((flags & O_ACCMODE) == O_WRONLY) {
    107 		errno = EINVAL;
    108 		return (NULL);
    109 	}
    110 
    111 	if (!(hashp = calloc(1, sizeof(HTAB))))
    112 		return (NULL);
    113 	hashp->fp = -1;
    114 
    115 	/*
    116 	 * Even if user wants write only, we need to be able to read
    117 	 * the actual file, so we need to open it read/write. But, the
    118 	 * field in the hashp structure needs to be accurate so that
    119 	 * we can check accesses.
    120 	 */
    121 	hashp->flags = flags;
    122 
    123 	new_table = 0;
    124 	if (!file || (flags & O_TRUNC) ||
    125 	    (stat(file, &statbuf) && (errno == ENOENT))) {
    126 		if (errno == ENOENT)
    127 			errno = 0; /* Just in case someone looks at errno */
    128 		new_table = 1;
    129 	}
    130 	if (file) {
    131 		if ((hashp->fp = open(file, flags, mode)) == -1)
    132 			RETURN_ERROR(errno, error0);
    133 		if (fcntl(hashp->fp, F_SETFD, FD_CLOEXEC) == -1)
    134 			RETURN_ERROR(errno, error1);
    135 		if (fstat(hashp->fp, &statbuf) == -1)
    136 			RETURN_ERROR(errno, error1);
    137 		new_table |= statbuf.st_size == 0;
    138 	}
    139 	if (new_table) {
    140 		if (!(hashp = init_hash(hashp, file, info)))
    141 			RETURN_ERROR(errno, error1);
    142 	} else {
    143 		/* Table already exists */
    144 		if (info && info->hash)
    145 			hashp->hash = info->hash;
    146 		else
    147 			hashp->hash = __default_hash;
    148 
    149 		hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
    150 #if BYTE_ORDER == LITTLE_ENDIAN
    151 		swap_header(hashp);
    152 #endif
    153 		if (hdrsize == -1)
    154 			RETURN_ERROR(errno, error1);
    155 		if (hdrsize != sizeof(HASHHDR))
    156 			RETURN_ERROR(EFTYPE, error1);
    157 		/* Verify file type, versions and hash function */
    158 		if (hashp->MAGIC != HASHMAGIC)
    159 			RETURN_ERROR(EFTYPE, error1);
    160 #define	OLDHASHVERSION	1
    161 		if (hashp->VERSION != HASHVERSION &&
    162 		    hashp->VERSION != OLDHASHVERSION)
    163 			RETURN_ERROR(EFTYPE, error1);
    164 		if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
    165 			RETURN_ERROR(EFTYPE, error1);
    166 		/*
    167 		 * Figure out how many segments we need.  Max_Bucket is the
    168 		 * maximum bucket number, so the number of buckets is
    169 		 * max_bucket + 1.
    170 		 */
    171 		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
    172 			 hashp->SGSIZE;
    173 		hashp->nsegs = 0;
    174 		if (alloc_segs(hashp, nsegs))
    175 			/*
    176 			 * If alloc_segs fails, table will have been destroyed
    177 			 * and errno will have been set.
    178 			 */
    179 			return (NULL);
    180 		/* Read in bitmaps */
    181 		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
    182 		    (unsigned int)(hashp->BSIZE << BYTE_SHIFT) - 1) >>
    183 		    (hashp->BSHIFT + BYTE_SHIFT);
    184 
    185 		hashp->nmaps = bpages;
    186 		(void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32_t *));
    187 	}
    188 
    189 	/* Initialize Buffer Manager */
    190 	if (info && info->cachesize)
    191 		__buf_init(hashp, info->cachesize);
    192 	else
    193 		__buf_init(hashp, DEF_BUFSIZE);
    194 
    195 	hashp->new_file = new_table;
    196 	hashp->save_file = file && (hashp->flags & O_RDWR);
    197 	hashp->cbucket = -1;
    198 	if (!(dbp = malloc(sizeof(DB)))) {
    199 		save_errno = errno;
    200 		hdestroy(hashp);
    201 		errno = save_errno;
    202 		return (NULL);
    203 	}
    204 	dbp->internal = hashp;
    205 	dbp->close = hash_close;
    206 	dbp->del = hash_delete;
    207 	dbp->fd = hash_fd;
    208 	dbp->get = hash_get;
    209 	dbp->put = hash_put;
    210 	dbp->seq = hash_seq;
    211 	dbp->sync = hash_sync;
    212 	dbp->type = DB_HASH;
    213 
    214 #ifdef DEBUG
    215 	(void)fprintf(stderr,
    216 "%s\n%s%p\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
    217 	    "init_htab:",
    218 	    "TABLE POINTER   ", hashp,
    219 	    "BUCKET SIZE     ", hashp->BSIZE,
    220 	    "BUCKET SHIFT    ", hashp->BSHIFT,
    221 	    "DIRECTORY SIZE  ", hashp->DSIZE,
    222 	    "SEGMENT SIZE    ", hashp->SGSIZE,
    223 	    "SEGMENT SHIFT   ", hashp->SSHIFT,
    224 	    "FILL FACTOR     ", hashp->FFACTOR,
    225 	    "MAX BUCKET      ", hashp->MAX_BUCKET,
    226 	    "OVFL POINT	     ", hashp->OVFL_POINT,
    227 	    "LAST FREED      ", hashp->LAST_FREED,
    228 	    "HIGH MASK       ", hashp->HIGH_MASK,
    229 	    "LOW  MASK       ", hashp->LOW_MASK,
    230 	    "NSEGS           ", hashp->nsegs,
    231 	    "NKEYS           ", hashp->NKEYS);
    232 #endif
    233 #ifdef HASH_STATISTICS
    234 	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
    235 #endif
    236 	return (dbp);
    237 
    238 error1:
    239 	if (hashp != NULL)
    240 		(void)close(hashp->fp);
    241 
    242 error0:
    243 	free(hashp);
    244 	errno = save_errno;
    245 	return (NULL);
    246 }
    247 
    248 static int
    249 hash_close(DB *dbp)
    250 {
    251 	HTAB *hashp;
    252 	int retval;
    253 
    254 	if (!dbp)
    255 		return (ERROR);
    256 
    257 	hashp = dbp->internal;
    258 	retval = hdestroy(hashp);
    259 	free(dbp);
    260 	return (retval);
    261 }
    262 
    263 static int
    264 hash_fd(const DB *dbp)
    265 {
    266 	HTAB *hashp;
    267 
    268 	if (!dbp)
    269 		return (ERROR);
    270 
    271 	hashp = dbp->internal;
    272 	if (hashp->fp == -1) {
    273 		errno = ENOENT;
    274 		return (-1);
    275 	}
    276 	return (hashp->fp);
    277 }
    278 
    279 /************************** LOCAL CREATION ROUTINES **********************/
    280 static HTAB *
    281 init_hash(HTAB *hashp, const char *file, const HASHINFO *info)
    282 {
    283 	struct stat statbuf;
    284 	int nelem;
    285 
    286 	nelem = 1;
    287 	hashp->NKEYS = 0;
    288 	hashp->LORDER = BYTE_ORDER;
    289 	hashp->BSIZE = DEF_BUCKET_SIZE;
    290 	hashp->BSHIFT = DEF_BUCKET_SHIFT;
    291 	hashp->SGSIZE = DEF_SEGSIZE;
    292 	hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
    293 	hashp->DSIZE = DEF_DIRSIZE;
    294 	hashp->FFACTOR = DEF_FFACTOR;
    295 	hashp->hash = __default_hash;
    296 	memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
    297 	memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
    298 
    299 	/* Fix bucket size to be optimal for file system */
    300 	if (file != NULL) {
    301 		if (stat(file, &statbuf))
    302 			return (NULL);
    303 		hashp->BSIZE = MIN(statbuf.st_blksize, MAX_BSIZE);
    304 		hashp->BSHIFT = __log2((uint32_t)hashp->BSIZE);
    305 	}
    306 
    307 	if (info) {
    308 		if (info->bsize) {
    309 			/* Round pagesize up to power of 2 */
    310 			hashp->BSHIFT = __log2(info->bsize);
    311 			hashp->BSIZE = 1 << hashp->BSHIFT;
    312 			if (hashp->BSIZE > MAX_BSIZE) {
    313 				errno = EINVAL;
    314 				return (NULL);
    315 			}
    316 		}
    317 		if (info->ffactor)
    318 			hashp->FFACTOR = info->ffactor;
    319 		if (info->hash)
    320 			hashp->hash = info->hash;
    321 		if (info->nelem)
    322 			nelem = info->nelem;
    323 		if (info->lorder) {
    324 			if (info->lorder != BIG_ENDIAN &&
    325 			    info->lorder != LITTLE_ENDIAN) {
    326 				errno = EINVAL;
    327 				return (NULL);
    328 			}
    329 			hashp->LORDER = info->lorder;
    330 		}
    331 	}
    332 	/* init_htab should destroy the table and set errno if it fails */
    333 	if (init_htab(hashp, (size_t)nelem))
    334 		return (NULL);
    335 	else
    336 		return (hashp);
    337 }
    338 /*
    339  * This calls alloc_segs which may run out of memory.  Alloc_segs will destroy
    340  * the table and set errno, so we just pass the error information along.
    341  *
    342  * Returns 0 on No Error
    343  */
    344 static int
    345 init_htab(HTAB *hashp, size_t nelem)
    346 {
    347 	int nbuckets;
    348 	uint32_t nsegs;
    349 	int l2;
    350 
    351 	/*
    352 	 * Divide number of elements by the fill factor and determine a
    353 	 * desired number of buckets.  Allocate space for the next greater
    354 	 * power of two number of buckets.
    355 	 */
    356 	nelem = (nelem - 1) / hashp->FFACTOR + 1;
    357 
    358 	_DBFIT(nelem, uint32_t);
    359 	l2 = __log2(MAX((uint32_t)nelem, 2));
    360 	nbuckets = 1 << l2;
    361 
    362 	hashp->SPARES[l2] = l2 + 1;
    363 	hashp->SPARES[l2 + 1] = l2 + 1;
    364 	hashp->OVFL_POINT = l2;
    365 	hashp->LAST_FREED = 2;
    366 
    367 	/* First bitmap page is at: splitpoint l2 page offset 1 */
    368 	if (__ibitmap(hashp, (int)OADDR_OF(l2, 1), l2 + 1, 0))
    369 		return (-1);
    370 
    371 	hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
    372 	hashp->HIGH_MASK = (nbuckets << 1) - 1;
    373 	/* LINTED constant in conditional context */
    374 	hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
    375 	    hashp->BSHIFT) + 1;
    376 
    377 	nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
    378 	nsegs = 1 << __log2(nsegs);
    379 
    380 	if (nsegs > hashp->DSIZE)
    381 		hashp->DSIZE = nsegs;
    382 	return (alloc_segs(hashp, (int)nsegs));
    383 }
    384 
    385 /********************** DESTROY/CLOSE ROUTINES ************************/
    386 
    387 /*
    388  * Flushes any changes to the file if necessary and destroys the hashp
    389  * structure, freeing all allocated space.
    390  */
    391 static int
    392 hdestroy(HTAB *hashp)
    393 {
    394 	int i, save_errno;
    395 
    396 	save_errno = 0;
    397 
    398 #ifdef HASH_STATISTICS
    399 	(void)fprintf(stderr, "hdestroy: accesses %d collisions %d\n",
    400 	    hash_accesses, hash_collisions);
    401 	(void)fprintf(stderr, "hdestroy: expansions %d\n",
    402 	    hash_expansions);
    403 	(void)fprintf(stderr, "hdestroy: overflows %d\n",
    404 	    hash_overflows);
    405 	(void)fprintf(stderr, "keys %d maxp %d segmentcount %d\n",
    406 	    hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
    407 
    408 	for (i = 0; i < NCACHED; i++)
    409 		(void)fprintf(stderr,
    410 		    "spares[%d] = %d\n", i, hashp->SPARES[i]);
    411 #endif
    412 	/*
    413 	 * Call on buffer manager to free buffers, and if required,
    414 	 * write them to disk.
    415 	 */
    416 	if (__buf_free(hashp, 1, hashp->save_file))
    417 		save_errno = errno;
    418 	if (hashp->dir) {
    419 		free(*hashp->dir);	/* Free initial segments */
    420 		/* Free extra segments */
    421 		while (hashp->exsegs--)
    422 			free(hashp->dir[--hashp->nsegs]);
    423 		free(hashp->dir);
    424 	}
    425 	if (flush_meta(hashp) && !save_errno)
    426 		save_errno = errno;
    427 	/* Free Bigmaps */
    428 	for (i = 0; i < hashp->nmaps; i++)
    429 		if (hashp->mapp[i])
    430 			free(hashp->mapp[i]);
    431 
    432 	if (hashp->fp != -1)
    433 		(void)close(hashp->fp);
    434 
    435 	free(hashp);
    436 
    437 	if (save_errno) {
    438 		errno = save_errno;
    439 		return (ERROR);
    440 	}
    441 	return (SUCCESS);
    442 }
    443 /*
    444  * Write modified pages to disk
    445  *
    446  * Returns:
    447  *	 0 == OK
    448  *	-1 ERROR
    449  */
    450 static int
    451 hash_sync(const DB *dbp, uint32_t flags)
    452 {
    453 	HTAB *hashp;
    454 
    455 	if (flags != 0) {
    456 		errno = EINVAL;
    457 		return (ERROR);
    458 	}
    459 
    460 	if (!dbp)
    461 		return (ERROR);
    462 
    463 	hashp = dbp->internal;
    464 	if (!hashp->save_file)
    465 		return (0);
    466 	if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
    467 		return (ERROR);
    468 	hashp->new_file = 0;
    469 	return (0);
    470 }
    471 
    472 /*
    473  * Returns:
    474  *	 0 == OK
    475  *	-1 indicates that errno should be set
    476  */
    477 static int
    478 flush_meta(HTAB *hashp)
    479 {
    480 	HASHHDR *whdrp;
    481 #if BYTE_ORDER == LITTLE_ENDIAN
    482 	HASHHDR whdr;
    483 #endif
    484 	int fp, i;
    485 	ssize_t wsize;
    486 
    487 	if (!hashp->save_file)
    488 		return (0);
    489 	hashp->MAGIC = HASHMAGIC;
    490 	hashp->VERSION = HASHVERSION;
    491 	hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
    492 
    493 	fp = hashp->fp;
    494 	whdrp = &hashp->hdr;
    495 #if BYTE_ORDER == LITTLE_ENDIAN
    496 	whdrp = &whdr;
    497 	swap_header_copy(&hashp->hdr, whdrp);
    498 #endif
    499 	if ((wsize = pwrite(fp, whdrp, sizeof(HASHHDR), (off_t)0)) == -1)
    500 		return (-1);
    501 	else
    502 		if (wsize != sizeof(HASHHDR)) {
    503 			errno = EFTYPE;
    504 			hashp->err = errno;
    505 			return (-1);
    506 		}
    507 	for (i = 0; i < NCACHED; i++)
    508 		if (hashp->mapp[i])
    509 			if (__put_page(hashp, (char *)(void *)hashp->mapp[i],
    510 				(u_int)hashp->BITMAPS[i], 0, 1))
    511 				return (-1);
    512 	return (0);
    513 }
    514 
    515 /*******************************SEARCH ROUTINES *****************************/
    516 /*
    517  * All the access routines return
    518  *
    519  * Returns:
    520  *	 0 on SUCCESS
    521  *	 1 to indicate an external ERROR (i.e. key not found, etc)
    522  *	-1 to indicate an internal ERROR (i.e. out of memory, etc)
    523  */
    524 static int
    525 hash_get(const DB *dbp, const DBT *key, DBT *data, uint32_t flag)
    526 {
    527 	HTAB *hashp;
    528 
    529 	hashp = dbp->internal;
    530 	if (flag) {
    531 		hashp->err = errno = EINVAL;
    532 		return (ERROR);
    533 	}
    534 	return (hash_access(hashp, HASH_GET, __UNCONST(key), data));
    535 }
    536 
    537 static int
    538 hash_put(const DB *dbp, DBT *key, const DBT *data, uint32_t flag)
    539 {
    540 	HTAB *hashp;
    541 
    542 	hashp = dbp->internal;
    543 	if (flag && flag != R_NOOVERWRITE) {
    544 		hashp->err = errno = EINVAL;
    545 		return (ERROR);
    546 	}
    547 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
    548 		hashp->err = errno = EPERM;
    549 		return (ERROR);
    550 	}
    551 	/* LINTED const castaway */
    552 	return (hash_access(hashp, flag == R_NOOVERWRITE ?
    553 	    HASH_PUTNEW : HASH_PUT, __UNCONST(key), __UNCONST(data)));
    554 }
    555 
    556 static int
    557 hash_delete(const DB *dbp, const DBT *key, uint32_t flag)
    558 {
    559 	HTAB *hashp;
    560 
    561 	hashp = dbp->internal;
    562 	if (flag && flag != R_CURSOR) {
    563 		hashp->err = errno = EINVAL;
    564 		return (ERROR);
    565 	}
    566 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
    567 		hashp->err = errno = EPERM;
    568 		return (ERROR);
    569 	}
    570 	return hash_access(hashp, HASH_DELETE, __UNCONST(key), NULL);
    571 }
    572 
    573 /*
    574  * Assume that hashp has been set in wrapper routine.
    575  */
    576 static int
    577 hash_access(HTAB *hashp, ACTION action, DBT *key, DBT *val)
    578 {
    579 	BUFHEAD *rbufp;
    580 	BUFHEAD *bufp, *save_bufp;
    581 	uint16_t *bp;
    582 	int n, ndx, off;
    583 	size_t size;
    584 	char *kp;
    585 	uint16_t pageno;
    586 
    587 #ifdef HASH_STATISTICS
    588 	hash_accesses++;
    589 #endif
    590 
    591 	off = hashp->BSIZE;
    592 	size = key->size;
    593 	kp = (char *)key->data;
    594 	rbufp = __get_buf(hashp, __call_hash(hashp, kp, (int)size), NULL, 0);
    595 	if (!rbufp)
    596 		return (ERROR);
    597 	save_bufp = rbufp;
    598 
    599 	/* Pin the bucket chain */
    600 	rbufp->flags |= BUF_PIN;
    601 	for (bp = (uint16_t *)(void *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
    602 		if (bp[1] >= REAL_KEY) {
    603 			/* Real key/data pair */
    604 			if (size == off - *bp &&
    605 			    memcmp(kp, rbufp->page + *bp, size) == 0)
    606 				goto found;
    607 			off = bp[1];
    608 #ifdef HASH_STATISTICS
    609 			hash_collisions++;
    610 #endif
    611 			bp += 2;
    612 			ndx += 2;
    613 		} else if (bp[1] == OVFLPAGE) {
    614 			rbufp = __get_buf(hashp, (uint32_t)*bp, rbufp, 0);
    615 			if (!rbufp) {
    616 				save_bufp->flags &= ~BUF_PIN;
    617 				return (ERROR);
    618 			}
    619 			/* FOR LOOP INIT */
    620 			bp = (uint16_t *)(void *)rbufp->page;
    621 			n = *bp++;
    622 			ndx = 1;
    623 			off = hashp->BSIZE;
    624 		} else if (bp[1] < REAL_KEY) {
    625 			if ((ndx =
    626 			    __find_bigpair(hashp, rbufp, ndx, kp, (int)size)) > 0)
    627 				goto found;
    628 			if (ndx == -2) {
    629 				bufp = rbufp;
    630 				if (!(pageno =
    631 				    __find_last_page(hashp, &bufp))) {
    632 					ndx = 0;
    633 					rbufp = bufp;
    634 					break;	/* FOR */
    635 				}
    636 				rbufp = __get_buf(hashp, (uint32_t)pageno,
    637 				    bufp, 0);
    638 				if (!rbufp) {
    639 					save_bufp->flags &= ~BUF_PIN;
    640 					return (ERROR);
    641 				}
    642 				/* FOR LOOP INIT */
    643 				bp = (uint16_t *)(void *)rbufp->page;
    644 				n = *bp++;
    645 				ndx = 1;
    646 				off = hashp->BSIZE;
    647 			} else {
    648 				save_bufp->flags &= ~BUF_PIN;
    649 				return (ERROR);
    650 			}
    651 		}
    652 
    653 	/* Not found */
    654 	switch (action) {
    655 	case HASH_PUT:
    656 	case HASH_PUTNEW:
    657 		if (__addel(hashp, rbufp, key, val)) {
    658 			save_bufp->flags &= ~BUF_PIN;
    659 			return (ERROR);
    660 		} else {
    661 			save_bufp->flags &= ~BUF_PIN;
    662 			return (SUCCESS);
    663 		}
    664 	case HASH_GET:
    665 	case HASH_DELETE:
    666 	default:
    667 		save_bufp->flags &= ~BUF_PIN;
    668 		return (ABNORMAL);
    669 	}
    670 
    671 found:
    672 	switch (action) {
    673 	case HASH_PUTNEW:
    674 		save_bufp->flags &= ~BUF_PIN;
    675 		return (ABNORMAL);
    676 	case HASH_GET:
    677 		bp = (uint16_t *)(void *)rbufp->page;
    678 		if (bp[ndx + 1] < REAL_KEY) {
    679 			if (__big_return(hashp, rbufp, ndx, val, 0))
    680 				return (ERROR);
    681 		} else {
    682 			val->data = (uint8_t *)rbufp->page + (int)bp[ndx + 1];
    683 			val->size = bp[ndx] - bp[ndx + 1];
    684 		}
    685 		break;
    686 	case HASH_PUT:
    687 		if ((__delpair(hashp, rbufp, ndx)) ||
    688 		    (__addel(hashp, rbufp, key, val))) {
    689 			save_bufp->flags &= ~BUF_PIN;
    690 			return (ERROR);
    691 		}
    692 		break;
    693 	case HASH_DELETE:
    694 		if (__delpair(hashp, rbufp, ndx))
    695 			return (ERROR);
    696 		break;
    697 	default:
    698 		abort();
    699 	}
    700 	save_bufp->flags &= ~BUF_PIN;
    701 	return (SUCCESS);
    702 }
    703 
    704 static int
    705 hash_seq(const DB *dbp, DBT *key, DBT *data, uint32_t flag)
    706 {
    707 	uint32_t bucket;
    708 	BUFHEAD *bufp = NULL; /* XXX: gcc */
    709 	HTAB *hashp;
    710 	uint16_t *bp, ndx;
    711 
    712 	hashp = dbp->internal;
    713 	if (flag && flag != R_FIRST && flag != R_NEXT) {
    714 		hashp->err = errno = EINVAL;
    715 		return (ERROR);
    716 	}
    717 #ifdef HASH_STATISTICS
    718 	hash_accesses++;
    719 #endif
    720 	if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
    721 		hashp->cbucket = 0;
    722 		hashp->cndx = 1;
    723 		hashp->cpage = NULL;
    724 	}
    725 
    726 	for (bp = NULL; !bp || !bp[0]; ) {
    727 		if (!(bufp = hashp->cpage)) {
    728 			for (bucket = hashp->cbucket;
    729 			    bucket <= hashp->MAX_BUCKET;
    730 			    bucket++, hashp->cndx = 1) {
    731 				bufp = __get_buf(hashp, bucket, NULL, 0);
    732 				if (!bufp)
    733 					return (ERROR);
    734 				hashp->cpage = bufp;
    735 				bp = (uint16_t *)(void *)bufp->page;
    736 				if (bp[0])
    737 					break;
    738 			}
    739 			hashp->cbucket = bucket;
    740 			if (hashp->cbucket > hashp->MAX_BUCKET) {
    741 				hashp->cbucket = -1;
    742 				return (ABNORMAL);
    743 			}
    744 		} else
    745 			bp = (uint16_t *)(void *)hashp->cpage->page;
    746 
    747 		_DIAGASSERT(bp != NULL);
    748 		_DIAGASSERT(bufp != NULL);
    749 		while (bp[hashp->cndx + 1] == OVFLPAGE) {
    750 			bufp = hashp->cpage =
    751 			    __get_buf(hashp, (uint32_t)bp[hashp->cndx], bufp,
    752 				0);
    753 			if (!bufp)
    754 				return (ERROR);
    755 			bp = (uint16_t *)(void *)(bufp->page);
    756 			hashp->cndx = 1;
    757 		}
    758 		if (!bp[0]) {
    759 			hashp->cpage = NULL;
    760 			++hashp->cbucket;
    761 		}
    762 	}
    763 	ndx = hashp->cndx;
    764 	if (bp[ndx + 1] < REAL_KEY) {
    765 		if (__big_keydata(hashp, bufp, key, data, 1))
    766 			return (ERROR);
    767 	} else {
    768 		if (hashp->cpage == NULL)
    769 			return (ERROR);
    770 		key->data = (uint8_t *)hashp->cpage->page + bp[ndx];
    771 		key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
    772 		data->data = (uint8_t *)hashp->cpage->page + bp[ndx + 1];
    773 		data->size = bp[ndx] - bp[ndx + 1];
    774 		ndx += 2;
    775 		if (ndx > bp[0]) {
    776 			hashp->cpage = NULL;
    777 			hashp->cbucket++;
    778 			hashp->cndx = 1;
    779 		} else
    780 			hashp->cndx = ndx;
    781 	}
    782 	return (SUCCESS);
    783 }
    784 
    785 /********************************* UTILITIES ************************/
    786 
    787 /*
    788  * Returns:
    789  *	 0 ==> OK
    790  *	-1 ==> Error
    791  */
    792 int
    793 __expand_table(HTAB *hashp)
    794 {
    795 	uint32_t old_bucket, new_bucket;
    796 	int new_segnum, spare_ndx;
    797 	size_t dirsize;
    798 
    799 #ifdef HASH_STATISTICS
    800 	hash_expansions++;
    801 #endif
    802 	new_bucket = ++hashp->MAX_BUCKET;
    803 	old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
    804 
    805 	new_segnum = new_bucket >> hashp->SSHIFT;
    806 
    807 	/* Check if we need a new segment */
    808 	if (new_segnum >= hashp->nsegs) {
    809 		/* Check if we need to expand directory */
    810 		if (new_segnum >= hashp->DSIZE) {
    811 			/* Reallocate directory */
    812 			dirsize = hashp->DSIZE * sizeof(SEGMENT *);
    813 			if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
    814 				return (-1);
    815 			hashp->DSIZE = dirsize << 1;
    816 		}
    817 		if ((hashp->dir[new_segnum] =
    818 		    calloc((size_t)hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
    819 			return (-1);
    820 		hashp->exsegs++;
    821 		hashp->nsegs++;
    822 	}
    823 	/*
    824 	 * If the split point is increasing (MAX_BUCKET's log base 2
    825 	 * * increases), we need to copy the current contents of the spare
    826 	 * split bucket to the next bucket.
    827 	 */
    828 	spare_ndx = __log2((uint32_t)(hashp->MAX_BUCKET + 1));
    829 	if (spare_ndx > hashp->OVFL_POINT) {
    830 		hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
    831 		hashp->OVFL_POINT = spare_ndx;
    832 	}
    833 
    834 	if (new_bucket > hashp->HIGH_MASK) {
    835 		/* Starting a new doubling */
    836 		hashp->LOW_MASK = hashp->HIGH_MASK;
    837 		hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
    838 	}
    839 	/* Relocate records to the new bucket */
    840 	return (__split_page(hashp, old_bucket, new_bucket));
    841 }
    842 
    843 /*
    844  * If realloc guarantees that the pointer is not destroyed if the realloc
    845  * fails, then this routine can go away.
    846  */
    847 static void *
    848 hash_realloc(SEGMENT **p_ptr, size_t oldsize, size_t newsize)
    849 {
    850 	void *p;
    851 
    852 	if ((p = malloc(newsize)) != NULL) {
    853 		memmove(p, *p_ptr, oldsize);
    854 		memset((char *)p + oldsize, 0, newsize - oldsize);
    855 		free(*p_ptr);
    856 		*p_ptr = p;
    857 	}
    858 	return (p);
    859 }
    860 
    861 uint32_t
    862 __call_hash(HTAB *hashp, char *k, int len)
    863 {
    864 	int n, bucket;
    865 
    866 	n = hashp->hash(k, (size_t)len);
    867 	bucket = n & hashp->HIGH_MASK;
    868 	if (bucket > hashp->MAX_BUCKET)
    869 		bucket = bucket & hashp->LOW_MASK;
    870 	return (bucket);
    871 }
    872 
    873 /*
    874  * Allocate segment table.  On error, destroy the table and set errno.
    875  *
    876  * Returns 0 on success
    877  */
    878 static int
    879 alloc_segs(HTAB *hashp, int nsegs)
    880 {
    881 	int i;
    882 	SEGMENT store;
    883 
    884 	int save_errno;
    885 
    886 	hashp->dir = calloc((size_t)hashp->DSIZE, sizeof(SEGMENT *));
    887 	if (hashp->dir == NULL) {
    888 		save_errno = errno;
    889 		(void)hdestroy(hashp);
    890 		errno = save_errno;
    891 		return (-1);
    892 	}
    893 	hashp->nsegs = nsegs;
    894 	if (nsegs == 0)
    895 		return 0;
    896 	/* Allocate segments */
    897 	store = calloc((size_t)(nsegs << hashp->SSHIFT), sizeof(SEGMENT));
    898 	if (store == NULL) {
    899 		save_errno = errno;
    900 		(void)hdestroy(hashp);
    901 		errno = save_errno;
    902 		return (-1);
    903 	}
    904 	for (i = 0; i < nsegs; i++)
    905 		hashp->dir[i] = &store[i << hashp->SSHIFT];
    906 	return (0);
    907 }
    908 
    909 #if BYTE_ORDER == LITTLE_ENDIAN
    910 /*
    911  * Hashp->hdr needs to be byteswapped.
    912  */
    913 static void
    914 swap_header_copy(HASHHDR *srcp, HASHHDR *destp)
    915 {
    916 	size_t i;
    917 
    918 	P_32_COPY(srcp->magic, destp->magic);
    919 	P_32_COPY(srcp->version, destp->version);
    920 	P_32_COPY(srcp->lorder, destp->lorder);
    921 	P_32_COPY(srcp->bsize, destp->bsize);
    922 	P_32_COPY(srcp->bshift, destp->bshift);
    923 	P_32_COPY(srcp->dsize, destp->dsize);
    924 	P_32_COPY(srcp->ssize, destp->ssize);
    925 	P_32_COPY(srcp->sshift, destp->sshift);
    926 	P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
    927 	P_32_COPY(srcp->last_freed, destp->last_freed);
    928 	P_32_COPY(srcp->max_bucket, destp->max_bucket);
    929 	P_32_COPY(srcp->high_mask, destp->high_mask);
    930 	P_32_COPY(srcp->low_mask, destp->low_mask);
    931 	P_32_COPY(srcp->ffactor, destp->ffactor);
    932 	P_32_COPY(srcp->nkeys, destp->nkeys);
    933 	P_32_COPY(srcp->hdrpages, destp->hdrpages);
    934 	P_32_COPY(srcp->h_charkey, destp->h_charkey);
    935 	for (i = 0; i < NCACHED; i++) {
    936 		P_32_COPY(srcp->spares[i], destp->spares[i]);
    937 		P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
    938 	}
    939 }
    940 
    941 static void
    942 swap_header(HTAB *hashp)
    943 {
    944 	HASHHDR *hdrp;
    945 	size_t i;
    946 
    947 	hdrp = &hashp->hdr;
    948 
    949 	M_32_SWAP(hdrp->magic);
    950 	M_32_SWAP(hdrp->version);
    951 	M_32_SWAP(hdrp->lorder);
    952 	M_32_SWAP(hdrp->bsize);
    953 	M_32_SWAP(hdrp->bshift);
    954 	M_32_SWAP(hdrp->dsize);
    955 	M_32_SWAP(hdrp->ssize);
    956 	M_32_SWAP(hdrp->sshift);
    957 	M_32_SWAP(hdrp->ovfl_point);
    958 	M_32_SWAP(hdrp->last_freed);
    959 	M_32_SWAP(hdrp->max_bucket);
    960 	M_32_SWAP(hdrp->high_mask);
    961 	M_32_SWAP(hdrp->low_mask);
    962 	M_32_SWAP(hdrp->ffactor);
    963 	M_32_SWAP(hdrp->nkeys);
    964 	M_32_SWAP(hdrp->hdrpages);
    965 	M_32_SWAP(hdrp->h_charkey);
    966 	for (i = 0; i < NCACHED; i++) {
    967 		M_32_SWAP(hdrp->spares[i]);
    968 		M_16_SWAP(hdrp->bitmaps[i]);
    969 	}
    970 }
    971 #endif
    972