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