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