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