xref: /freebsd/lib/libc/db/hash/hash.c (revision 8655c70597b0e0918c82114b1186df5669b83eb6)
1 /*-
2  * Copyright (c) 1990, 1993, 1994
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)hash.c	8.9 (Berkeley) 6/16/94";
35 #endif /* LIBC_SCCS and not lint */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include "namespace.h"
40 #include <sys/param.h>
41 #include <sys/stat.h>
42 
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #ifdef DEBUG
50 #include <assert.h>
51 #endif
52 #include "un-namespace.h"
53 
54 #include <db.h>
55 #include "hash.h"
56 #include "page.h"
57 #include "extern.h"
58 
59 static int   alloc_segs(HTAB *, int);
60 static int   flush_meta(HTAB *);
61 static int   hash_access(HTAB *, ACTION, DBT *, DBT *);
62 static int   hash_close(DB *);
63 static int   hash_delete(const DB *, const DBT *, u_int32_t);
64 static int   hash_fd(const DB *);
65 static int   hash_get(const DB *, const DBT *, DBT *, u_int32_t);
66 static int   hash_put(const DB *, DBT *, const DBT *, u_int32_t);
67 static void *hash_realloc(SEGMENT **, int, int);
68 static int   hash_seq(const DB *, DBT *, DBT *, u_int32_t);
69 static int   hash_sync(const DB *, u_int32_t);
70 static int   hdestroy(HTAB *);
71 static HTAB *init_hash(HTAB *, const char *, const HASHINFO *);
72 static int   init_htab(HTAB *, int);
73 #if BYTE_ORDER == LITTLE_ENDIAN
74 static void  swap_header(HTAB *);
75 static void  swap_header_copy(HASHHDR *, HASHHDR *);
76 #endif
77 
78 /* Fast arithmetic, relying on powers of 2, */
79 #define MOD(x, y)		((x) & ((y) - 1))
80 
81 #define RETURN_ERROR(ERR, LOC)	{ save_errno = ERR; goto LOC; }
82 
83 /* Return values */
84 #define	SUCCESS	 (0)
85 #define	ERROR	(-1)
86 #define	ABNORMAL (1)
87 
88 #ifdef HASH_STATISTICS
89 int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
90 #endif
91 
92 /************************** INTERFACE ROUTINES ***************************/
93 /* OPEN/CLOSE */
94 
95 /* ARGSUSED */
96 DB *
97 __hash_open(const char *file, int flags, int mode,
98     const HASHINFO *info,	/* Special directives for create */
99     int dflags)
100 {
101 	HTAB *hashp;
102 	struct stat statbuf;
103 	DB *dbp;
104 	int bpages, hdrsize, new_table, nsegs, save_errno;
105 
106 	if ((flags & O_ACCMODE) == O_WRONLY) {
107 		errno = EINVAL;
108 		return (NULL);
109 	}
110 
111 	if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
112 		return (NULL);
113 	hashp->fp = -1;
114 
115 	/*
116 	 * Even if user wants write only, we need to be able to read
117 	 * the actual file, so we need to open it read/write. But, the
118 	 * field in the hashp structure needs to be accurate so that
119 	 * we can check accesses.
120 	 */
121 	hashp->flags = 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 
134 		/* if the .db file is empty, and we had permission to create
135 		   a new .db file, then reinitialize the database */
136 		if ((flags & O_CREAT) &&
137 		     _fstat(hashp->fp, &statbuf) == 0 && statbuf.st_size == 0)
138 			new_table = 1;
139 
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 		    (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(DB *dbp)
253 {
254 	HTAB *hashp;
255 	int retval;
256 
257 	if (!dbp)
258 		return (ERROR);
259 
260 	hashp = (HTAB *)dbp->internal;
261 	retval = hdestroy(hashp);
262 	free(dbp);
263 	return (retval);
264 }
265 
266 static int
267 hash_fd(const DB *dbp)
268 {
269 	HTAB *hashp;
270 
271 	if (!dbp)
272 		return (ERROR);
273 
274 	hashp = (HTAB *)dbp->internal;
275 	if (hashp->fp == -1) {
276 		errno = ENOENT;
277 		return (-1);
278 	}
279 	return (hashp->fp);
280 }
281 
282 /************************** LOCAL CREATION ROUTINES **********************/
283 static HTAB *
284 init_hash(HTAB *hashp, const char *file, const HASHINFO *info)
285 {
286 	struct stat statbuf;
287 	int nelem;
288 
289 	nelem = 1;
290 	hashp->NKEYS = 0;
291 	hashp->LORDER = BYTE_ORDER;
292 	hashp->BSIZE = DEF_BUCKET_SIZE;
293 	hashp->BSHIFT = DEF_BUCKET_SHIFT;
294 	hashp->SGSIZE = DEF_SEGSIZE;
295 	hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
296 	hashp->DSIZE = DEF_DIRSIZE;
297 	hashp->FFACTOR = DEF_FFACTOR;
298 	hashp->hash = __default_hash;
299 	memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
300 	memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
301 
302 	/* Fix bucket size to be optimal for file system */
303 	if (file != NULL) {
304 		if (stat(file, &statbuf))
305 			return (NULL);
306 		hashp->BSIZE = statbuf.st_blksize;
307 		hashp->BSHIFT = __log2(hashp->BSIZE);
308 	}
309 
310 	if (info) {
311 		if (info->bsize) {
312 			/* Round pagesize up to power of 2 */
313 			hashp->BSHIFT = __log2(info->bsize);
314 			hashp->BSIZE = 1 << hashp->BSHIFT;
315 			if (hashp->BSIZE > MAX_BSIZE) {
316 				errno = EINVAL;
317 				return (NULL);
318 			}
319 		}
320 		if (info->ffactor)
321 			hashp->FFACTOR = info->ffactor;
322 		if (info->hash)
323 			hashp->hash = info->hash;
324 		if (info->nelem)
325 			nelem = info->nelem;
326 		if (info->lorder) {
327 			if (info->lorder != BIG_ENDIAN &&
328 			    info->lorder != LITTLE_ENDIAN) {
329 				errno = EINVAL;
330 				return (NULL);
331 			}
332 			hashp->LORDER = info->lorder;
333 		}
334 	}
335 	/* init_htab should destroy the table and set errno if it fails */
336 	if (init_htab(hashp, nelem))
337 		return (NULL);
338 	else
339 		return (hashp);
340 }
341 /*
342  * This calls alloc_segs which may run out of memory.  Alloc_segs will destroy
343  * the table and set errno, so we just pass the error information along.
344  *
345  * Returns 0 on No Error
346  */
347 static int
348 init_htab(HTAB *hashp, int nelem)
349 {
350 	int nbuckets, nsegs;
351 	int l2;
352 
353 	/*
354 	 * Divide number of elements by the fill factor and determine a
355 	 * desired number of buckets.  Allocate space for the next greater
356 	 * power of two number of buckets.
357 	 */
358 	nelem = (nelem - 1) / hashp->FFACTOR + 1;
359 
360 	l2 = __log2(MAX(nelem, 2));
361 	nbuckets = 1 << l2;
362 
363 	hashp->SPARES[l2] = l2 + 1;
364 	hashp->SPARES[l2 + 1] = l2 + 1;
365 	hashp->OVFL_POINT = l2;
366 	hashp->LAST_FREED = 2;
367 
368 	/* First bitmap page is at: splitpoint l2 page offset 1 */
369 	if (__ibitmap(hashp, OADDR_OF(l2, 1), l2 + 1, 0))
370 		return (-1);
371 
372 	hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
373 	hashp->HIGH_MASK = (nbuckets << 1) - 1;
374 	hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
375 	    hashp->BSHIFT) + 1;
376 
377 	nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
378 	nsegs = 1 << __log2(nsegs);
379 
380 	if (nsegs > hashp->DSIZE)
381 		hashp->DSIZE = nsegs;
382 	return (alloc_segs(hashp, nsegs));
383 }
384 
385 /********************** DESTROY/CLOSE ROUTINES ************************/
386 
387 /*
388  * Flushes any changes to the file if necessary and destroys the hashp
389  * structure, freeing all allocated space.
390  */
391 static int
392 hdestroy(HTAB *hashp)
393 {
394 	int i, save_errno;
395 
396 	save_errno = 0;
397 
398 #ifdef HASH_STATISTICS
399 	(void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n",
400 	    hash_accesses, hash_collisions);
401 	(void)fprintf(stderr, "hdestroy: expansions %ld\n",
402 	    hash_expansions);
403 	(void)fprintf(stderr, "hdestroy: overflows %ld\n",
404 	    hash_overflows);
405 	(void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n",
406 	    hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
407 
408 	for (i = 0; i < NCACHED; i++)
409 		(void)fprintf(stderr,
410 		    "spares[%d] = %d\n", i, hashp->SPARES[i]);
411 #endif
412 	/*
413 	 * Call on buffer manager to free buffers, and if required,
414 	 * write them to disk.
415 	 */
416 	if (__buf_free(hashp, 1, hashp->save_file))
417 		save_errno = errno;
418 	if (hashp->dir) {
419 		free(*hashp->dir);	/* Free initial segments */
420 		/* Free extra segments */
421 		while (hashp->exsegs--)
422 			free(hashp->dir[--hashp->nsegs]);
423 		free(hashp->dir);
424 	}
425 	if (flush_meta(hashp) && !save_errno)
426 		save_errno = errno;
427 	/* Free Bigmaps */
428 	for (i = 0; i < hashp->nmaps; i++)
429 		if (hashp->mapp[i])
430 			free(hashp->mapp[i]);
431 
432 	if (hashp->fp != -1)
433 		(void)_close(hashp->fp);
434 
435 	free(hashp);
436 
437 	if (save_errno) {
438 		errno = save_errno;
439 		return (ERROR);
440 	}
441 	return (SUCCESS);
442 }
443 /*
444  * Write modified pages to disk
445  *
446  * Returns:
447  *	 0 == OK
448  *	-1 ERROR
449  */
450 static int
451 hash_sync(const DB *dbp, u_int32_t flags)
452 {
453 	HTAB *hashp;
454 
455 	if (flags != 0) {
456 		errno = EINVAL;
457 		return (ERROR);
458 	}
459 
460 	if (!dbp)
461 		return (ERROR);
462 
463 	hashp = (HTAB *)dbp->internal;
464 	if (!hashp->save_file)
465 		return (0);
466 	if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
467 		return (ERROR);
468 	hashp->new_file = 0;
469 	return (0);
470 }
471 
472 /*
473  * Returns:
474  *	 0 == OK
475  *	-1 indicates that errno should be set
476  */
477 static int
478 flush_meta(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->error = 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(const DB *dbp, const DBT *key, DBT *data, u_int32_t flag)
526 {
527 	HTAB *hashp;
528 
529 	hashp = (HTAB *)dbp->internal;
530 	if (flag) {
531 		hashp->error = errno = EINVAL;
532 		return (ERROR);
533 	}
534 	return (hash_access(hashp, HASH_GET, (DBT *)key, data));
535 }
536 
537 static int
538 hash_put(const DB *dbp, DBT *key, const DBT *data, u_int32_t flag)
539 {
540 	HTAB *hashp;
541 
542 	hashp = (HTAB *)dbp->internal;
543 	if (flag && flag != R_NOOVERWRITE) {
544 		hashp->error = EINVAL;
545 		errno = EINVAL;
546 		return (ERROR);
547 	}
548 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
549 		hashp->error = errno = EPERM;
550 		return (ERROR);
551 	}
552 	return (hash_access(hashp, flag == R_NOOVERWRITE ?
553 	    HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
554 }
555 
556 static int
557 hash_delete(const DB *dbp, const DBT *key,
558     u_int32_t flag)		/* Ignored */
559 {
560 	HTAB *hashp;
561 
562 	hashp = (HTAB *)dbp->internal;
563 	if (flag && flag != R_CURSOR) {
564 		hashp->error = errno = EINVAL;
565 		return (ERROR);
566 	}
567 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
568 		hashp->error = errno = EPERM;
569 		return (ERROR);
570 	}
571 	return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
572 }
573 
574 /*
575  * Assume that hashp has been set in wrapper routine.
576  */
577 static int
578 hash_access(HTAB *hashp, ACTION action, DBT *key, DBT *val)
579 {
580 	BUFHEAD *rbufp;
581 	BUFHEAD *bufp, *save_bufp;
582 	u_int16_t *bp;
583 	int n, ndx, off, size;
584 	char *kp;
585 	u_int16_t pageno;
586 
587 #ifdef HASH_STATISTICS
588 	hash_accesses++;
589 #endif
590 
591 	off = hashp->BSIZE;
592 	size = key->size;
593 	kp = (char *)key->data;
594 	rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
595 	if (!rbufp)
596 		return (ERROR);
597 	save_bufp = rbufp;
598 
599 	/* Pin the bucket chain */
600 	rbufp->flags |= BUF_PIN;
601 	for (bp = (u_int16_t *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
602 		if (bp[1] >= REAL_KEY) {
603 			/* Real key/data pair */
604 			if (size == off - *bp &&
605 			    memcmp(kp, rbufp->page + *bp, size) == 0)
606 				goto found;
607 			off = bp[1];
608 #ifdef HASH_STATISTICS
609 			hash_collisions++;
610 #endif
611 			bp += 2;
612 			ndx += 2;
613 		} else if (bp[1] == OVFLPAGE) {
614 			rbufp = __get_buf(hashp, *bp, rbufp, 0);
615 			if (!rbufp) {
616 				save_bufp->flags &= ~BUF_PIN;
617 				return (ERROR);
618 			}
619 			/* FOR LOOP INIT */
620 			bp = (u_int16_t *)rbufp->page;
621 			n = *bp++;
622 			ndx = 1;
623 			off = hashp->BSIZE;
624 		} else if (bp[1] < REAL_KEY) {
625 			if ((ndx =
626 			    __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
627 				goto found;
628 			if (ndx == -2) {
629 				bufp = rbufp;
630 				if (!(pageno =
631 				    __find_last_page(hashp, &bufp))) {
632 					ndx = 0;
633 					rbufp = bufp;
634 					break;	/* FOR */
635 				}
636 				rbufp = __get_buf(hashp, pageno, bufp, 0);
637 				if (!rbufp) {
638 					save_bufp->flags &= ~BUF_PIN;
639 					return (ERROR);
640 				}
641 				/* FOR LOOP INIT */
642 				bp = (u_int16_t *)rbufp->page;
643 				n = *bp++;
644 				ndx = 1;
645 				off = hashp->BSIZE;
646 			} else {
647 				save_bufp->flags &= ~BUF_PIN;
648 				return (ERROR);
649 			}
650 		}
651 
652 	/* Not found */
653 	switch (action) {
654 	case HASH_PUT:
655 	case HASH_PUTNEW:
656 		if (__addel(hashp, rbufp, key, val)) {
657 			save_bufp->flags &= ~BUF_PIN;
658 			return (ERROR);
659 		} else {
660 			save_bufp->flags &= ~BUF_PIN;
661 			return (SUCCESS);
662 		}
663 	case HASH_GET:
664 	case HASH_DELETE:
665 	default:
666 		save_bufp->flags &= ~BUF_PIN;
667 		return (ABNORMAL);
668 	}
669 
670 found:
671 	switch (action) {
672 	case HASH_PUTNEW:
673 		save_bufp->flags &= ~BUF_PIN;
674 		return (ABNORMAL);
675 	case HASH_GET:
676 		bp = (u_int16_t *)rbufp->page;
677 		if (bp[ndx + 1] < REAL_KEY) {
678 			if (__big_return(hashp, rbufp, ndx, val, 0))
679 				return (ERROR);
680 		} else {
681 			val->data = (u_char *)rbufp->page + (int)bp[ndx + 1];
682 			val->size = bp[ndx] - bp[ndx + 1];
683 		}
684 		break;
685 	case HASH_PUT:
686 		if ((__delpair(hashp, rbufp, ndx)) ||
687 		    (__addel(hashp, rbufp, key, val))) {
688 			save_bufp->flags &= ~BUF_PIN;
689 			return (ERROR);
690 		}
691 		break;
692 	case HASH_DELETE:
693 		if (__delpair(hashp, rbufp, ndx))
694 			return (ERROR);
695 		break;
696 	default:
697 		abort();
698 	}
699 	save_bufp->flags &= ~BUF_PIN;
700 	return (SUCCESS);
701 }
702 
703 static int
704 hash_seq(const DB *dbp, DBT *key, DBT *data, u_int32_t flag)
705 {
706 	u_int32_t bucket;
707 	BUFHEAD *bufp;
708 	HTAB *hashp;
709 	u_int16_t *bp, ndx;
710 
711 	hashp = (HTAB *)dbp->internal;
712 	if (flag && flag != R_FIRST && flag != R_NEXT) {
713 		hashp->error = errno = EINVAL;
714 		return (ERROR);
715 	}
716 #ifdef HASH_STATISTICS
717 	hash_accesses++;
718 #endif
719 	if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
720 		hashp->cbucket = 0;
721 		hashp->cndx = 1;
722 		hashp->cpage = NULL;
723 	}
724 
725 	for (bp = NULL; !bp || !bp[0]; ) {
726 		if (!(bufp = hashp->cpage)) {
727 			for (bucket = hashp->cbucket;
728 			    bucket <= hashp->MAX_BUCKET;
729 			    bucket++, hashp->cndx = 1) {
730 				bufp = __get_buf(hashp, bucket, NULL, 0);
731 				if (!bufp)
732 					return (ERROR);
733 				hashp->cpage = bufp;
734 				bp = (u_int16_t *)bufp->page;
735 				if (bp[0])
736 					break;
737 			}
738 			hashp->cbucket = bucket;
739 			if (hashp->cbucket > hashp->MAX_BUCKET) {
740 				hashp->cbucket = -1;
741 				return (ABNORMAL);
742 			}
743 		} else
744 			bp = (u_int16_t *)hashp->cpage->page;
745 
746 #ifdef DEBUG
747 		assert(bp);
748 		assert(bufp);
749 #endif
750 		while (bp[hashp->cndx + 1] == OVFLPAGE) {
751 			bufp = hashp->cpage =
752 			    __get_buf(hashp, bp[hashp->cndx], bufp, 0);
753 			if (!bufp)
754 				return (ERROR);
755 			bp = (u_int16_t *)(bufp->page);
756 			hashp->cndx = 1;
757 		}
758 		if (!bp[0]) {
759 			hashp->cpage = NULL;
760 			++hashp->cbucket;
761 		}
762 	}
763 	ndx = hashp->cndx;
764 	if (bp[ndx + 1] < REAL_KEY) {
765 		if (__big_keydata(hashp, bufp, key, data, 1))
766 			return (ERROR);
767 	} else {
768 		key->data = (u_char *)hashp->cpage->page + bp[ndx];
769 		key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
770 		data->data = (u_char *)hashp->cpage->page + bp[ndx + 1];
771 		data->size = bp[ndx] - bp[ndx + 1];
772 		ndx += 2;
773 		if (ndx > bp[0]) {
774 			hashp->cpage = NULL;
775 			hashp->cbucket++;
776 			hashp->cndx = 1;
777 		} else
778 			hashp->cndx = ndx;
779 	}
780 	return (SUCCESS);
781 }
782 
783 /********************************* UTILITIES ************************/
784 
785 /*
786  * Returns:
787  *	 0 ==> OK
788  *	-1 ==> Error
789  */
790 int
791 __expand_table(HTAB *hashp)
792 {
793 	u_int32_t old_bucket, new_bucket;
794 	int dirsize, new_segnum, spare_ndx;
795 
796 #ifdef HASH_STATISTICS
797 	hash_expansions++;
798 #endif
799 	new_bucket = ++hashp->MAX_BUCKET;
800 	old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
801 
802 	new_segnum = new_bucket >> hashp->SSHIFT;
803 
804 	/* Check if we need a new segment */
805 	if (new_segnum >= hashp->nsegs) {
806 		/* Check if we need to expand directory */
807 		if (new_segnum >= hashp->DSIZE) {
808 			/* Reallocate directory */
809 			dirsize = hashp->DSIZE * sizeof(SEGMENT *);
810 			if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
811 				return (-1);
812 			hashp->DSIZE = dirsize << 1;
813 		}
814 		if ((hashp->dir[new_segnum] =
815 		    (SEGMENT)calloc(hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
816 			return (-1);
817 		hashp->exsegs++;
818 		hashp->nsegs++;
819 	}
820 	/*
821 	 * If the split point is increasing (MAX_BUCKET's log base 2
822 	 * * increases), we need to copy the current contents of the spare
823 	 * split bucket to the next bucket.
824 	 */
825 	spare_ndx = __log2(hashp->MAX_BUCKET + 1);
826 	if (spare_ndx > hashp->OVFL_POINT) {
827 		hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
828 		hashp->OVFL_POINT = spare_ndx;
829 	}
830 
831 	if (new_bucket > hashp->HIGH_MASK) {
832 		/* Starting a new doubling */
833 		hashp->LOW_MASK = hashp->HIGH_MASK;
834 		hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
835 	}
836 	/* Relocate records to the new bucket */
837 	return (__split_page(hashp, old_bucket, new_bucket));
838 }
839 
840 /*
841  * If realloc guarantees that the pointer is not destroyed if the realloc
842  * fails, then this routine can go away.
843  */
844 static void *
845 hash_realloc(SEGMENT **p_ptr, int oldsize, int newsize)
846 {
847 	void *p;
848 
849 	if ( (p = malloc(newsize)) ) {
850 		memmove(p, *p_ptr, oldsize);
851 		memset((char *)p + oldsize, 0, newsize - oldsize);
852 		free(*p_ptr);
853 		*p_ptr = p;
854 	}
855 	return (p);
856 }
857 
858 u_int32_t
859 __call_hash(HTAB *hashp, char *k, int len)
860 {
861 	int n, bucket;
862 
863 	n = hashp->hash(k, len);
864 	bucket = n & hashp->HIGH_MASK;
865 	if (bucket > hashp->MAX_BUCKET)
866 		bucket = bucket & hashp->LOW_MASK;
867 	return (bucket);
868 }
869 
870 /*
871  * Allocate segment table.  On error, destroy the table and set errno.
872  *
873  * Returns 0 on success
874  */
875 static int
876 alloc_segs(HTAB *hashp, int nsegs)
877 {
878 	int i;
879 	SEGMENT store;
880 
881 	int save_errno;
882 
883 	if ((hashp->dir =
884 	    (SEGMENT *)calloc(hashp->DSIZE, sizeof(SEGMENT *))) == NULL) {
885 		save_errno = errno;
886 		(void)hdestroy(hashp);
887 		errno = save_errno;
888 		return (-1);
889 	}
890 	/* Allocate segments */
891 	if ((store =
892 	    (SEGMENT)calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT))) == NULL) {
893 		save_errno = errno;
894 		(void)hdestroy(hashp);
895 		errno = save_errno;
896 		return (-1);
897 	}
898 	for (i = 0; i < nsegs; i++, hashp->nsegs++)
899 		hashp->dir[i] = &store[i << hashp->SSHIFT];
900 	return (0);
901 }
902 
903 #if BYTE_ORDER == LITTLE_ENDIAN
904 /*
905  * Hashp->hdr needs to be byteswapped.
906  */
907 static void
908 swap_header_copy(HASHHDR *srcp, HASHHDR *destp)
909 {
910 	int i;
911 
912 	P_32_COPY(srcp->magic, destp->magic);
913 	P_32_COPY(srcp->version, destp->version);
914 	P_32_COPY(srcp->lorder, destp->lorder);
915 	P_32_COPY(srcp->bsize, destp->bsize);
916 	P_32_COPY(srcp->bshift, destp->bshift);
917 	P_32_COPY(srcp->dsize, destp->dsize);
918 	P_32_COPY(srcp->ssize, destp->ssize);
919 	P_32_COPY(srcp->sshift, destp->sshift);
920 	P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
921 	P_32_COPY(srcp->last_freed, destp->last_freed);
922 	P_32_COPY(srcp->max_bucket, destp->max_bucket);
923 	P_32_COPY(srcp->high_mask, destp->high_mask);
924 	P_32_COPY(srcp->low_mask, destp->low_mask);
925 	P_32_COPY(srcp->ffactor, destp->ffactor);
926 	P_32_COPY(srcp->nkeys, destp->nkeys);
927 	P_32_COPY(srcp->hdrpages, destp->hdrpages);
928 	P_32_COPY(srcp->h_charkey, destp->h_charkey);
929 	for (i = 0; i < NCACHED; i++) {
930 		P_32_COPY(srcp->spares[i], destp->spares[i]);
931 		P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
932 	}
933 }
934 
935 static void
936 swap_header(HTAB *hashp)
937 {
938 	HASHHDR *hdrp;
939 	int i;
940 
941 	hdrp = &hashp->hdr;
942 
943 	M_32_SWAP(hdrp->magic);
944 	M_32_SWAP(hdrp->version);
945 	M_32_SWAP(hdrp->lorder);
946 	M_32_SWAP(hdrp->bsize);
947 	M_32_SWAP(hdrp->bshift);
948 	M_32_SWAP(hdrp->dsize);
949 	M_32_SWAP(hdrp->ssize);
950 	M_32_SWAP(hdrp->sshift);
951 	M_32_SWAP(hdrp->ovfl_point);
952 	M_32_SWAP(hdrp->last_freed);
953 	M_32_SWAP(hdrp->max_bucket);
954 	M_32_SWAP(hdrp->high_mask);
955 	M_32_SWAP(hdrp->low_mask);
956 	M_32_SWAP(hdrp->ffactor);
957 	M_32_SWAP(hdrp->nkeys);
958 	M_32_SWAP(hdrp->hdrpages);
959 	M_32_SWAP(hdrp->h_charkey);
960 	for (i = 0; i < NCACHED; i++) {
961 		M_32_SWAP(hdrp->spares[i]);
962 		M_16_SWAP(hdrp->bitmaps[i]);
963 	}
964 }
965 #endif
966