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