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