xref: /dragonfly/lib/libc/db/hash/hash.c (revision 2c81fb9c)
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  * 3. 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  * @(#)hash.c	8.9 (Berkeley) 6/16/94
33  * $FreeBSD: head/lib/libc/db/hash/hash.c 206178 2010-04-05 10:12:21Z avg $
34  */
35 
36 #include "namespace.h"
37 #include <sys/param.h>
38 #include <sys/stat.h>
39 
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #ifdef DEBUG
47 #include <assert.h>
48 #endif
49 #include "un-namespace.h"
50 
51 #include <db.h>
52 #include "hash.h"
53 #include "page.h"
54 #include "extern.h"
55 
56 static int   alloc_segs(HTAB *, int);
57 static int   flush_meta(HTAB *);
58 static int   hash_access(HTAB *, ACTION, DBT *, DBT *);
59 static int   hash_close(DB *);
60 static int   hash_delete(const DB *, const DBT *, uint32_t);
61 static int   hash_fd(const DB *);
62 static int   hash_get(const DB *, const DBT *, DBT *, uint32_t);
63 static int   hash_put(const DB *, DBT *, const DBT *, uint32_t);
64 static void *hash_realloc(SEGMENT **, int, int);
65 static int   hash_seq(const DB *, DBT *, DBT *, uint32_t);
66 static int   hash_sync(const DB *, uint32_t);
67 static int   hdestroy(HTAB *);
68 static HTAB *init_hash(HTAB *, const char *, const HASHINFO *);
69 static int   init_htab(HTAB *, int);
70 #if BYTE_ORDER == LITTLE_ENDIAN
71 static void  swap_header(HTAB *);
72 static void  swap_header_copy(HASHHDR *, HASHHDR *);
73 #endif
74 
75 /* Fast arithmetic, relying on powers of 2, */
76 #define MOD(x, y)		((x) & ((y) - 1))
77 
78 #define RETURN_ERROR(ERR, LOC)	{ save_errno = ERR; goto LOC; }
79 
80 /* Return values */
81 #define	SUCCESS	 (0)
82 #define	ERROR	(-1)
83 #define	ABNORMAL (1)
84 
85 #ifdef HASH_STATISTICS
86 int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
87 #endif
88 
89 /************************** INTERFACE ROUTINES ***************************/
90 /* OPEN/CLOSE */
91 
92 /* ARGSUSED */
93 DB *
94 __hash_open(const char *file, int flags, mode_t mode,
95     const HASHINFO *info,	/* Special directives for create */
96     __unused int dflags)
97 {
98 	HTAB *hashp;
99 	struct stat statbuf;
100 	DB *dbp;
101 	int bpages, hdrsize, new_table, nsegs, save_errno;
102 
103 	if ((flags & O_ACCMODE) == O_WRONLY) {
104 		errno = EINVAL;
105 		return (NULL);
106 	}
107 
108 	if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
109 		return (NULL);
110 	hashp->fp = -1;
111 
112 	/*
113 	 * Even if user wants write only, we need to be able to read
114 	 * the actual file, so we need to open it read/write. But, the
115 	 * field in the hashp structure needs to be accurate so that
116 	 * we can check accesses.
117 	 */
118 	hashp->flags = flags;
119 
120 	if (file) {
121 		if ((hashp->fp = _open(file, flags | O_CLOEXEC, mode)) == -1)
122 			RETURN_ERROR(errno, error0);
123 		_fcntl(hashp->fp, F_SETFD, 1);
124 		new_table = _fstat(hashp->fp, &statbuf) == 0 &&
125 		    statbuf.st_size == 0 && (flags & O_ACCMODE) != O_RDONLY;
126 	} else
127 		new_table = 1;
128 
129 	if (new_table) {
130 		if (!(hashp = init_hash(hashp, file, info)))
131 			RETURN_ERROR(errno, error1);
132 	} else {
133 		/* Table already exists */
134 		if (info && info->hash)
135 			hashp->hash = info->hash;
136 		else
137 			hashp->hash = __default_hash;
138 
139 		hdrsize = _read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
140 #if BYTE_ORDER == LITTLE_ENDIAN
141 		swap_header(hashp);
142 #endif
143 		if (hdrsize == -1)
144 			RETURN_ERROR(errno, error1);
145 		if (hdrsize != sizeof(HASHHDR))
146 			RETURN_ERROR(EFTYPE, error1);
147 		/* Verify file type, versions and hash function */
148 		if (hashp->MAGIC != HASHMAGIC)
149 			RETURN_ERROR(EFTYPE, error1);
150 #define	OLDHASHVERSION	1
151 		if (hashp->VERSION != HASHVERSION &&
152 		    hashp->VERSION != OLDHASHVERSION)
153 			RETURN_ERROR(EFTYPE, error1);
154 		if ((int32_t)hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
155 			RETURN_ERROR(EFTYPE, error1);
156 		/*
157 		 * Figure out how many segments we need.  Max_Bucket is the
158 		 * maximum bucket number, so the number of buckets is
159 		 * max_bucket + 1.
160 		 */
161 		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
162 			 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 		memset(&hashp->mapp[0], 0, bpages * sizeof(uint32_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 	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 		_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 = NOM_BSIZE;
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 	fprintf(stderr, "hdestroy: accesses %d collisions %d\n",
387 	    hash_accesses, hash_collisions);
388 	fprintf(stderr, "hdestroy: expansions %d\n",
389 	    hash_expansions);
390 	fprintf(stderr, "hdestroy: overflows %d\n",
391 	    hash_overflows);
392 	fprintf(stderr, "keys %d maxp %d segmentcount %d\n",
393 	    hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
394 
395 	for (i = 0; i < NCACHED; i++)
396 		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 		_close(hashp->fp);
425 
426 	free(hashp);
427 
428 	if (save_errno) {
429 		errno = save_errno;
430 		return (ERROR);
431 	}
432 	return (SUCCESS);
433 }
434 /*
435  * Write modified pages to disk
436  *
437  * Returns:
438  *	 0 == OK
439  *	-1 ERROR
440  */
441 static int
442 hash_sync(const DB *dbp, uint32_t flags)
443 {
444 	HTAB *hashp;
445 
446 	if (flags != 0) {
447 		errno = EINVAL;
448 		return (ERROR);
449 	}
450 
451 	if (!dbp)
452 		return (ERROR);
453 
454 	hashp = (HTAB *)dbp->internal;
455 	if (!hashp->save_file)
456 		return (0);
457 	if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
458 		return (ERROR);
459 	hashp->new_file = 0;
460 	return (0);
461 }
462 
463 /*
464  * Returns:
465  *	 0 == OK
466  *	-1 indicates that errno should be set
467  */
468 static int
469 flush_meta(HTAB *hashp)
470 {
471 	HASHHDR *whdrp;
472 #if BYTE_ORDER == LITTLE_ENDIAN
473 	HASHHDR whdr;
474 #endif
475 	int fp, i, wsize;
476 
477 	if (!hashp->save_file)
478 		return (0);
479 	hashp->MAGIC = HASHMAGIC;
480 	hashp->VERSION = HASHVERSION;
481 	hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
482 
483 	fp = hashp->fp;
484 	whdrp = &hashp->hdr;
485 #if BYTE_ORDER == LITTLE_ENDIAN
486 	whdrp = &whdr;
487 	swap_header_copy(&hashp->hdr, whdrp);
488 #endif
489 	if ((wsize = pwrite(fp, whdrp, sizeof(HASHHDR), (off_t)0)) == -1)
490 		return (-1);
491 	else
492 		if (wsize != sizeof(HASHHDR)) {
493 			errno = EFTYPE;
494 			hashp->error = errno;
495 			return (-1);
496 		}
497 	for (i = 0; i < NCACHED; i++)
498 		if (hashp->mapp[i])
499 			if (__put_page(hashp, (char *)hashp->mapp[i],
500 				hashp->BITMAPS[i], 0, 1))
501 				return (-1);
502 	return (0);
503 }
504 
505 /*******************************SEARCH ROUTINES *****************************/
506 /*
507  * All the access routines return
508  *
509  * Returns:
510  *	 0 on SUCCESS
511  *	 1 to indicate an external ERROR (i.e. key not found, etc)
512  *	-1 to indicate an internal ERROR (i.e. out of memory, etc)
513  */
514 static int
515 hash_get(const DB *dbp, const DBT *key, DBT *data, uint32_t flag)
516 {
517 	HTAB *hashp;
518 
519 	hashp = (HTAB *)dbp->internal;
520 	if (flag) {
521 		hashp->error = errno = EINVAL;
522 		return (ERROR);
523 	}
524 	return (hash_access(hashp, HASH_GET, (DBT *)key, data));
525 }
526 
527 static int
528 hash_put(const DB *dbp, DBT *key, const DBT *data, uint32_t flag)
529 {
530 	HTAB *hashp;
531 
532 	hashp = (HTAB *)dbp->internal;
533 	if (flag && flag != R_NOOVERWRITE) {
534 		hashp->error = errno = EINVAL;
535 		return (ERROR);
536 	}
537 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
538 		hashp->error = errno = EPERM;
539 		return (ERROR);
540 	}
541 	return (hash_access(hashp, flag == R_NOOVERWRITE ?
542 	    HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
543 }
544 
545 static int
546 hash_delete(const DB *dbp, const DBT *key,
547     uint32_t flag)		/* Ignored */
548 {
549 	HTAB *hashp;
550 
551 	hashp = (HTAB *)dbp->internal;
552 	if (flag && flag != R_CURSOR) {
553 		hashp->error = errno = EINVAL;
554 		return (ERROR);
555 	}
556 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
557 		hashp->error = errno = EPERM;
558 		return (ERROR);
559 	}
560 	return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
561 }
562 
563 /*
564  * Assume that hashp has been set in wrapper routine.
565  */
566 static int
567 hash_access(HTAB *hashp, ACTION action, DBT *key, DBT *val)
568 {
569 	BUFHEAD *rbufp;
570 	BUFHEAD *bufp, *save_bufp;
571 	uint16_t *bp;
572 	int n, ndx, off, size;
573 	char *kp;
574 	uint16_t pageno;
575 
576 #ifdef HASH_STATISTICS
577 	hash_accesses++;
578 #endif
579 
580 	off = hashp->BSIZE;
581 	size = key->size;
582 	kp = (char *)key->data;
583 	rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
584 	if (!rbufp)
585 		return (ERROR);
586 	save_bufp = rbufp;
587 
588 	/* Pin the bucket chain */
589 	rbufp->flags |= BUF_PIN;
590 	for (bp = (uint16_t *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
591 		if (bp[1] >= REAL_KEY) {
592 			/* Real key/data pair */
593 			if (size == off - *bp &&
594 			    memcmp(kp, rbufp->page + *bp, size) == 0)
595 				goto found;
596 			off = bp[1];
597 #ifdef HASH_STATISTICS
598 			hash_collisions++;
599 #endif
600 			bp += 2;
601 			ndx += 2;
602 		} else if (bp[1] == OVFLPAGE) {
603 			rbufp = __get_buf(hashp, *bp, rbufp, 0);
604 			if (!rbufp) {
605 				save_bufp->flags &= ~BUF_PIN;
606 				return (ERROR);
607 			}
608 			/* FOR LOOP INIT */
609 			bp = (uint16_t *)rbufp->page;
610 			n = *bp++;
611 			ndx = 1;
612 			off = hashp->BSIZE;
613 		} else if (bp[1] < REAL_KEY) {
614 			if ((ndx =
615 			    __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
616 				goto found;
617 			if (ndx == -2) {
618 				bufp = rbufp;
619 				if (!(pageno =
620 				    __find_last_page(hashp, &bufp))) {
621 					ndx = 0;
622 					rbufp = bufp;
623 					break;	/* FOR */
624 				}
625 				rbufp = __get_buf(hashp, pageno, bufp, 0);
626 				if (!rbufp) {
627 					save_bufp->flags &= ~BUF_PIN;
628 					return (ERROR);
629 				}
630 				/* FOR LOOP INIT */
631 				bp = (uint16_t *)rbufp->page;
632 				n = *bp++;
633 				ndx = 1;
634 				off = hashp->BSIZE;
635 			} else {
636 				save_bufp->flags &= ~BUF_PIN;
637 				return (ERROR);
638 			}
639 		}
640 
641 	/* Not found */
642 	switch (action) {
643 	case HASH_PUT:
644 	case HASH_PUTNEW:
645 		if (__addel(hashp, rbufp, key, val)) {
646 			save_bufp->flags &= ~BUF_PIN;
647 			return (ERROR);
648 		} else {
649 			save_bufp->flags &= ~BUF_PIN;
650 			return (SUCCESS);
651 		}
652 	case HASH_GET:
653 	case HASH_DELETE:
654 	default:
655 		save_bufp->flags &= ~BUF_PIN;
656 		return (ABNORMAL);
657 	}
658 
659 found:
660 	switch (action) {
661 	case HASH_PUTNEW:
662 		save_bufp->flags &= ~BUF_PIN;
663 		return (ABNORMAL);
664 	case HASH_GET:
665 		bp = (uint16_t *)rbufp->page;
666 		if (bp[ndx + 1] < REAL_KEY) {
667 			if (__big_return(hashp, rbufp, ndx, val, 0))
668 				return (ERROR);
669 		} else {
670 			val->data = (unsigned char *)rbufp->page +
671 			    (int)bp[ndx + 1];
672 			val->size = bp[ndx] - bp[ndx + 1];
673 		}
674 		break;
675 	case HASH_PUT:
676 		if ((__delpair(hashp, rbufp, ndx)) ||
677 		    (__addel(hashp, rbufp, key, val))) {
678 			save_bufp->flags &= ~BUF_PIN;
679 			return (ERROR);
680 		}
681 		break;
682 	case HASH_DELETE:
683 		if (__delpair(hashp, rbufp, ndx))
684 			return (ERROR);
685 		break;
686 	default:
687 		abort();
688 	}
689 	save_bufp->flags &= ~BUF_PIN;
690 	return (SUCCESS);
691 }
692 
693 static int
694 hash_seq(const DB *dbp, DBT *key, DBT *data, uint32_t flag)
695 {
696 	uint32_t bucket;
697 	BUFHEAD *bufp;
698 	HTAB *hashp;
699 	uint16_t *bp, ndx;
700 
701 	hashp = (HTAB *)dbp->internal;
702 	if (flag && flag != R_FIRST && flag != R_NEXT) {
703 		hashp->error = errno = EINVAL;
704 		return (ERROR);
705 	}
706 #ifdef HASH_STATISTICS
707 	hash_accesses++;
708 #endif
709 	if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
710 		hashp->cbucket = 0;
711 		hashp->cndx = 1;
712 		hashp->cpage = NULL;
713 	}
714 next_bucket:
715 	for (bp = NULL; !bp || !bp[0]; ) {
716 		if (!(bufp = hashp->cpage)) {
717 			for (bucket = hashp->cbucket;
718 			    bucket <= hashp->MAX_BUCKET;
719 			    bucket++, hashp->cndx = 1) {
720 				bufp = __get_buf(hashp, bucket, NULL, 0);
721 				if (!bufp)
722 					return (ERROR);
723 				hashp->cpage = bufp;
724 				bp = (uint16_t *)bufp->page;
725 				if (bp[0])
726 					break;
727 			}
728 			hashp->cbucket = bucket;
729 			if ((uint32_t)hashp->cbucket > hashp->MAX_BUCKET) {
730 				hashp->cbucket = -1;
731 				return (ABNORMAL);
732 			}
733 		} else {
734 			bp = (uint16_t *)hashp->cpage->page;
735 			if (flag == R_NEXT || flag == 0) {
736 				hashp->cndx += 2;
737 				if (hashp->cndx > bp[0]) {
738 					hashp->cpage = NULL;
739 					hashp->cbucket++;
740 					hashp->cndx = 1;
741 					goto next_bucket;
742 				}
743 			}
744 		}
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 = (uint16_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 		if (hashp->cpage == 0)
769 			return (ERROR);
770 		key->data = (unsigned char *)hashp->cpage->page + bp[ndx];
771 		key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
772 		data->data = (unsigned char *)hashp->cpage->page + bp[ndx + 1];
773 		data->size = bp[ndx] - bp[ndx + 1];
774 	}
775 	return (SUCCESS);
776 }
777 
778 /********************************* UTILITIES ************************/
779 
780 /*
781  * Returns:
782  *	 0 ==> OK
783  *	-1 ==> Error
784  */
785 int
786 __expand_table(HTAB *hashp)
787 {
788 	uint32_t old_bucket, new_bucket;
789 	int dirsize, new_segnum, spare_ndx;
790 
791 #ifdef HASH_STATISTICS
792 	hash_expansions++;
793 #endif
794 	new_bucket = ++hashp->MAX_BUCKET;
795 	old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
796 
797 	new_segnum = new_bucket >> hashp->SSHIFT;
798 
799 	/* Check if we need a new segment */
800 	if (new_segnum >= hashp->nsegs) {
801 		/* Check if we need to expand directory */
802 		if (new_segnum >= hashp->DSIZE) {
803 			/* Reallocate directory */
804 			dirsize = hashp->DSIZE * sizeof(SEGMENT *);
805 			if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
806 				return (-1);
807 			hashp->DSIZE = dirsize << 1;
808 		}
809 		if ((hashp->dir[new_segnum] =
810 		    (SEGMENT)calloc(hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
811 			return (-1);
812 		hashp->exsegs++;
813 		hashp->nsegs++;
814 	}
815 	/*
816 	 * If the split point is increasing (MAX_BUCKET's log base 2
817 	 * * increases), we need to copy the current contents of the spare
818 	 * split bucket to the next bucket.
819 	 */
820 	spare_ndx = __log2(hashp->MAX_BUCKET + 1);
821 	if (spare_ndx > hashp->OVFL_POINT) {
822 		hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
823 		hashp->OVFL_POINT = spare_ndx;
824 	}
825 
826 	if (new_bucket > hashp->HIGH_MASK) {
827 		/* Starting a new doubling */
828 		hashp->LOW_MASK = hashp->HIGH_MASK;
829 		hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
830 	}
831 	/* Relocate records to the new bucket */
832 	return (__split_page(hashp, old_bucket, new_bucket));
833 }
834 
835 /*
836  * If realloc guarantees that the pointer is not destroyed if the realloc
837  * fails, then this routine can go away.
838  */
839 static void *
840 hash_realloc(SEGMENT **p_ptr, int oldsize, int newsize)
841 {
842 	void *p;
843 
844 	if ( (p = malloc(newsize)) ) {
845 		memmove(p, *p_ptr, oldsize);
846 		memset((char *)p + oldsize, 0, newsize - oldsize);
847 		free(*p_ptr);
848 		*p_ptr = p;
849 	}
850 	return (p);
851 }
852 
853 uint32_t
854 __call_hash(HTAB *hashp, char *k, int len)
855 {
856 	unsigned int n, bucket;
857 
858 	n = hashp->hash(k, len);
859 	bucket = n & hashp->HIGH_MASK;
860 	if (bucket > hashp->MAX_BUCKET)
861 		bucket = bucket & hashp->LOW_MASK;
862 	return (bucket);
863 }
864 
865 /*
866  * Allocate segment table.  On error, destroy the table and set errno.
867  *
868  * Returns 0 on success
869  */
870 static int
871 alloc_segs(HTAB *hashp, int nsegs)
872 {
873 	int i;
874 	SEGMENT store;
875 
876 	int save_errno;
877 
878 	if ((hashp->dir =
879 	    (SEGMENT *)calloc(hashp->DSIZE, sizeof(SEGMENT *))) == NULL) {
880 		save_errno = errno;
881 		hdestroy(hashp);
882 		errno = save_errno;
883 		return (-1);
884 	}
885 	hashp->nsegs = nsegs;
886 	if (nsegs == 0)
887 		return (0);
888 	/* Allocate segments */
889 	if ((store = (SEGMENT)calloc(nsegs << hashp->SSHIFT,
890 	    sizeof(SEGMENT))) == NULL) {
891 		save_errno = errno;
892 		hdestroy(hashp);
893 		errno = save_errno;
894 		return (-1);
895 	}
896 	for (i = 0; i < nsegs; i++)
897 		hashp->dir[i] = &store[i << hashp->SSHIFT];
898 	return (0);
899 }
900 
901 #if BYTE_ORDER == LITTLE_ENDIAN
902 /*
903  * Hashp->hdr needs to be byteswapped.
904  */
905 static void
906 swap_header_copy(HASHHDR *srcp, HASHHDR *destp)
907 {
908 	int i;
909 
910 	P_32_COPY(srcp->magic, destp->magic);
911 	P_32_COPY(srcp->version, destp->version);
912 	P_32_COPY(srcp->lorder, destp->lorder);
913 	P_32_COPY(srcp->bsize, destp->bsize);
914 	P_32_COPY(srcp->bshift, destp->bshift);
915 	P_32_COPY(srcp->dsize, destp->dsize);
916 	P_32_COPY(srcp->ssize, destp->ssize);
917 	P_32_COPY(srcp->sshift, destp->sshift);
918 	P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
919 	P_32_COPY(srcp->last_freed, destp->last_freed);
920 	P_32_COPY(srcp->max_bucket, destp->max_bucket);
921 	P_32_COPY(srcp->high_mask, destp->high_mask);
922 	P_32_COPY(srcp->low_mask, destp->low_mask);
923 	P_32_COPY(srcp->ffactor, destp->ffactor);
924 	P_32_COPY(srcp->nkeys, destp->nkeys);
925 	P_32_COPY(srcp->hdrpages, destp->hdrpages);
926 	P_32_COPY(srcp->h_charkey, destp->h_charkey);
927 	for (i = 0; i < NCACHED; i++) {
928 		P_32_COPY(srcp->spares[i], destp->spares[i]);
929 		P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
930 	}
931 }
932 
933 static void
934 swap_header(HTAB *hashp)
935 {
936 	HASHHDR *hdrp;
937 	int i;
938 
939 	hdrp = &hashp->hdr;
940 
941 	M_32_SWAP(hdrp->magic);
942 	M_32_SWAP(hdrp->version);
943 	M_32_SWAP(hdrp->lorder);
944 	M_32_SWAP(hdrp->bsize);
945 	M_32_SWAP(hdrp->bshift);
946 	M_32_SWAP(hdrp->dsize);
947 	M_32_SWAP(hdrp->ssize);
948 	M_32_SWAP(hdrp->sshift);
949 	M_32_SWAP(hdrp->ovfl_point);
950 	M_32_SWAP(hdrp->last_freed);
951 	M_32_SWAP(hdrp->max_bucket);
952 	M_32_SWAP(hdrp->high_mask);
953 	M_32_SWAP(hdrp->low_mask);
954 	M_32_SWAP(hdrp->ffactor);
955 	M_32_SWAP(hdrp->nkeys);
956 	M_32_SWAP(hdrp->hdrpages);
957 	M_32_SWAP(hdrp->h_charkey);
958 	for (i = 0; i < NCACHED; i++) {
959 		M_32_SWAP(hdrp->spares[i]);
960 		M_16_SWAP(hdrp->bitmaps[i]);
961 	}
962 }
963 #endif
964