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