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