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