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