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