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