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