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