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