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