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