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