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