xref: /original-bsd/lib/libc/db/hash/hash.c (revision 37861f82)
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.34 (Berkeley) 05/16/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 *, u_int));
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, flags)
393 	const DB *dbp;
394 	u_int flags;
395 {
396 	HTAB *hashp;
397 
398 	if (flags != 0) {
399 		errno = EINVAL;
400 		return (ERROR);
401 	}
402 
403 	if (!dbp)
404 		return (ERROR);
405 
406 	hashp = (HTAB *)dbp->internal;
407 	if (!hashp->save_file)
408 		return (0);
409 	if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
410 		return (ERROR);
411 	hashp->new_file = 0;
412 	return (0);
413 }
414 
415 /*
416  * Returns:
417  *	 0 == OK
418  *	-1 indicates that errno should be set
419  */
420 static int
421 flush_meta(hashp)
422 	HTAB *hashp;
423 {
424 	HASHHDR *whdrp;
425 #if BYTE_ORDER == LITTLE_ENDIAN
426 	HASHHDR whdr;
427 #endif
428 	int fp, i, wsize;
429 
430 	if (!hashp->save_file)
431 		return (0);
432 	hashp->MAGIC = HASHMAGIC;
433 	hashp->VERSION = HASHVERSION;
434 	hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
435 
436 	fp = hashp->fp;
437 	whdrp = &hashp->hdr;
438 #if BYTE_ORDER == LITTLE_ENDIAN
439 	whdrp = &whdr;
440 	swap_header_copy(&hashp->hdr, whdrp);
441 #endif
442 	if ((lseek(fp, (off_t)0, SEEK_SET) == -1) ||
443 	    ((wsize = write(fp, whdrp, sizeof(HASHHDR))) == -1))
444 		return (-1);
445 	else
446 		if (wsize != sizeof(HASHHDR)) {
447 			errno = EFTYPE;
448 			hashp->errno = errno;
449 			return (-1);
450 		}
451 	for (i = 0; i < NCACHED; i++)
452 		if (hashp->mapp[i])
453 			if (__put_page(hashp, (char *)hashp->mapp[i],
454 				hashp->BITMAPS[i], 0, 1))
455 				return (-1);
456 	return (0);
457 }
458 
459 /*******************************SEARCH ROUTINES *****************************/
460 /*
461  * All the access routines return
462  *
463  * Returns:
464  *	 0 on SUCCESS
465  *	 1 to indicate an external ERROR (i.e. key not found, etc)
466  *	-1 to indicate an internal ERROR (i.e. out of memory, etc)
467  */
468 static int
469 hash_get(dbp, key, data, flag)
470 	const DB *dbp;
471 	const DBT *key;
472 	DBT *data;
473 	u_int flag;
474 {
475 	HTAB *hashp;
476 
477 	hashp = (HTAB *)dbp->internal;
478 	if (flag) {
479 		hashp->errno = errno = EINVAL;
480 		return (ERROR);
481 	}
482 	return (hash_access(hashp, HASH_GET, (DBT *)key, data));
483 }
484 
485 static int
486 hash_put(dbp, key, data, flag)
487 	const DB *dbp;
488 	DBT *key;
489 	const DBT *data;
490 	u_int flag;
491 {
492 	HTAB *hashp;
493 
494 	hashp = (HTAB *)dbp->internal;
495 	if (flag && flag != R_NOOVERWRITE) {
496 		hashp->errno = errno = EINVAL;
497 		return (ERROR);
498 	}
499 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
500 		hashp->errno = errno = EPERM;
501 		return (ERROR);
502 	}
503 	return (hash_access(hashp, flag == R_NOOVERWRITE ?
504 	    HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
505 }
506 
507 static int
508 hash_delete(dbp, key, flag)
509 	const DB *dbp;
510 	const DBT *key;
511 	u_int flag;		/* Ignored */
512 {
513 	HTAB *hashp;
514 
515 	hashp = (HTAB *)dbp->internal;
516 	if (flag && flag != R_CURSOR) {
517 		hashp->errno = errno = EINVAL;
518 		return (ERROR);
519 	}
520 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
521 		hashp->errno = errno = EPERM;
522 		return (ERROR);
523 	}
524 	return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
525 }
526 
527 /*
528  * Assume that hashp has been set in wrapper routine.
529  */
530 static int
531 hash_access(hashp, action, key, val)
532 	HTAB *hashp;
533 	ACTION action;
534 	DBT *key, *val;
535 {
536 	register BUFHEAD *rbufp;
537 	BUFHEAD *bufp, *save_bufp;
538 	register u_short *bp;
539 	register int n, ndx, off, size;
540 	register char *kp;
541 	u_short pageno;
542 
543 #ifdef HASH_STATISTICS
544 	hash_accesses++;
545 #endif
546 
547 	off = hashp->BSIZE;
548 	size = key->size;
549 	kp = (char *)key->data;
550 	rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
551 	if (!rbufp)
552 		return (ERROR);
553 	save_bufp = rbufp;
554 
555 	/* Pin the bucket chain */
556 	rbufp->flags |= BUF_PIN;
557 	for (bp = (u_short *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
558 		if (bp[1] >= REAL_KEY) {
559 			/* Real key/data pair */
560 			if (size == off - *bp &&
561 			    memcmp(kp, rbufp->page + *bp, size) == 0)
562 				goto found;
563 			off = bp[1];
564 #ifdef HASH_STATISTICS
565 			hash_collisions++;
566 #endif
567 			bp += 2;
568 			ndx += 2;
569 		} else if (bp[1] == OVFLPAGE) {
570 			rbufp = __get_buf(hashp, *bp, rbufp, 0);
571 			if (!rbufp) {
572 				save_bufp->flags &= ~BUF_PIN;
573 				return (ERROR);
574 			}
575 			/* FOR LOOP INIT */
576 			bp = (u_short *)rbufp->page;
577 			n = *bp++;
578 			ndx = 1;
579 			off = hashp->BSIZE;
580 		} else if (bp[1] < REAL_KEY) {
581 			if ((ndx =
582 			    __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
583 				goto found;
584 			if (ndx == -2) {
585 				bufp = rbufp;
586 				if (!(pageno =
587 				    __find_last_page(hashp, &bufp))) {
588 					ndx = 0;
589 					rbufp = bufp;
590 					break;	/* FOR */
591 				}
592 				rbufp = __get_buf(hashp, pageno, bufp, 0);
593 				if (!rbufp) {
594 					save_bufp->flags &= ~BUF_PIN;
595 					return (ERROR);
596 				}
597 				/* FOR LOOP INIT */
598 				bp = (u_short *)rbufp->page;
599 				n = *bp++;
600 				ndx = 1;
601 				off = hashp->BSIZE;
602 			} else {
603 				save_bufp->flags &= ~BUF_PIN;
604 				return (ERROR);
605 			}
606 		}
607 
608 	/* Not found */
609 	switch (action) {
610 	case HASH_PUT:
611 	case HASH_PUTNEW:
612 		if (__addel(hashp, rbufp, key, val)) {
613 			save_bufp->flags &= ~BUF_PIN;
614 			return (ERROR);
615 		} else {
616 			save_bufp->flags &= ~BUF_PIN;
617 			return (SUCCESS);
618 		}
619 	case HASH_GET:
620 	case HASH_DELETE:
621 	default:
622 		save_bufp->flags &= ~BUF_PIN;
623 		return (ABNORMAL);
624 	}
625 
626 found:
627 	switch (action) {
628 	case HASH_PUTNEW:
629 		save_bufp->flags &= ~BUF_PIN;
630 		return (ABNORMAL);
631 	case HASH_GET:
632 		bp = (u_short *)rbufp->page;
633 		if (bp[ndx + 1] < REAL_KEY) {
634 			if (__big_return(hashp, rbufp, ndx, val, 0))
635 				return (ERROR);
636 		} else {
637 			val->data = (u_char *)rbufp->page + (int)bp[ndx + 1];
638 			val->size = bp[ndx] - bp[ndx + 1];
639 		}
640 		break;
641 	case HASH_PUT:
642 		if ((__delpair(hashp, rbufp, ndx)) ||
643 		    (__addel(hashp, rbufp, key, val))) {
644 			save_bufp->flags &= ~BUF_PIN;
645 			return (ERROR);
646 		}
647 		break;
648 	case HASH_DELETE:
649 		if (__delpair(hashp, rbufp, ndx))
650 			return (ERROR);
651 		break;
652 	default:
653 		abort();
654 	}
655 	save_bufp->flags &= ~BUF_PIN;
656 	return (SUCCESS);
657 }
658 
659 static int
660 hash_seq(dbp, key, data, flag)
661 	const DB *dbp;
662 	DBT *key, *data;
663 	u_int flag;
664 {
665 	register u_int bucket;
666 	register BUFHEAD *bufp;
667 	HTAB *hashp;
668 	u_short *bp, ndx;
669 
670 	hashp = (HTAB *)dbp->internal;
671 	if (flag && flag != R_FIRST && flag != R_NEXT) {
672 		hashp->errno = errno = EINVAL;
673 		return (ERROR);
674 	}
675 #ifdef HASH_STATISTICS
676 	hash_accesses++;
677 #endif
678 	if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
679 		hashp->cbucket = 0;
680 		hashp->cndx = 1;
681 		hashp->cpage = NULL;
682 	}
683 
684 	for (bp = NULL; !bp || !bp[0]; ) {
685 		if (!(bufp = hashp->cpage)) {
686 			for (bucket = hashp->cbucket;
687 			    bucket <= hashp->MAX_BUCKET;
688 			    bucket++, hashp->cndx = 1) {
689 				bufp = __get_buf(hashp, bucket, NULL, 0);
690 				if (!bufp)
691 					return (ERROR);
692 				hashp->cpage = bufp;
693 				bp = (u_short *)bufp->page;
694 				if (bp[0])
695 					break;
696 			}
697 			hashp->cbucket = bucket;
698 			if (hashp->cbucket > hashp->MAX_BUCKET) {
699 				hashp->cbucket = -1;
700 				return (ABNORMAL);
701 			}
702 		} else
703 			bp = (u_short *)hashp->cpage->page;
704 
705 #ifdef DEBUG
706 		assert(bp);
707 		assert(bufp);
708 #endif
709 		while (bp[hashp->cndx + 1] == OVFLPAGE) {
710 			bufp = hashp->cpage =
711 			    __get_buf(hashp, bp[hashp->cndx], bufp, 0);
712 			if (!bufp)
713 				return (ERROR);
714 			bp = (u_short *)(bufp->page);
715 			hashp->cndx = 1;
716 		}
717 		if (!bp[0]) {
718 			hashp->cpage = NULL;
719 			++hashp->cbucket;
720 		}
721 	}
722 	ndx = hashp->cndx;
723 	if (bp[ndx + 1] < REAL_KEY) {
724 		if (__big_keydata(hashp, bufp, key, data, 1))
725 			return (ERROR);
726 	} else {
727 		key->data = (u_char *)hashp->cpage->page + bp[ndx];
728 		key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
729 		data->data = (u_char *)hashp->cpage->page + bp[ndx + 1];
730 		data->size = bp[ndx] - bp[ndx + 1];
731 		ndx += 2;
732 		if (ndx > bp[0]) {
733 			hashp->cpage = NULL;
734 			hashp->cbucket++;
735 			hashp->cndx = 1;
736 		} else
737 			hashp->cndx = ndx;
738 	}
739 	return (SUCCESS);
740 }
741 
742 /********************************* UTILITIES ************************/
743 
744 /*
745  * Returns:
746  *	 0 ==> OK
747  *	-1 ==> Error
748  */
749 extern int
750 __expand_table(hashp)
751 	HTAB *hashp;
752 {
753 	u_int old_bucket, new_bucket;
754 	int dirsize, new_segnum, spare_ndx;
755 
756 #ifdef HASH_STATISTICS
757 	hash_expansions++;
758 #endif
759 	new_bucket = ++hashp->MAX_BUCKET;
760 	old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
761 
762 	new_segnum = new_bucket >> hashp->SSHIFT;
763 
764 	/* Check if we need a new segment */
765 	if (new_segnum >= hashp->nsegs) {
766 		/* Check if we need to expand directory */
767 		if (new_segnum >= hashp->DSIZE) {
768 			/* Reallocate directory */
769 			dirsize = hashp->DSIZE * sizeof(SEGMENT *);
770 			if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
771 				return (-1);
772 			hashp->DSIZE = dirsize << 1;
773 		}
774 		if (!(hashp->dir[new_segnum] =
775 			calloc(hashp->SGSIZE, sizeof(SEGMENT))))
776 			return (-1);
777 		hashp->exsegs++;
778 		hashp->nsegs++;
779 	}
780 	/*
781 	 * If the split point is increasing (MAX_BUCKET's log base 2
782 	 * * increases), we need to copy the current contents of the spare
783 	 * split bucket to the next bucket.
784 	 */
785 	spare_ndx = __log2(hashp->MAX_BUCKET + 1);
786 	if (spare_ndx > hashp->OVFL_POINT) {
787 		hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
788 		hashp->OVFL_POINT = spare_ndx;
789 	}
790 
791 	if (new_bucket > hashp->HIGH_MASK) {
792 		/* Starting a new doubling */
793 		hashp->LOW_MASK = hashp->HIGH_MASK;
794 		hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
795 	}
796 	/* Relocate records to the new bucket */
797 	return (__split_page(hashp, old_bucket, new_bucket));
798 }
799 
800 /*
801  * If realloc guarantees that the pointer is not destroyed if the realloc
802  * fails, then this routine can go away.
803  */
804 static void *
805 hash_realloc(p_ptr, oldsize, newsize)
806 	SEGMENT **p_ptr;
807 	int oldsize, newsize;
808 {
809 	register void *p;
810 
811 	if (p = malloc(newsize)) {
812 		memmove(p, *p_ptr, oldsize);
813 		memset(*p_ptr + oldsize, 0, newsize - oldsize);
814 		free(*p_ptr);
815 		*p_ptr = p;
816 	}
817 	return (p);
818 }
819 
820 extern u_int
821 __call_hash(hashp, k, len)
822 	HTAB *hashp;
823 	char *k;
824 	int len;
825 {
826 	int n, bucket;
827 
828 	n = hashp->hash(k, len);
829 	bucket = n & hashp->HIGH_MASK;
830 	if (bucket > hashp->MAX_BUCKET)
831 		bucket = bucket & hashp->LOW_MASK;
832 	return (bucket);
833 }
834 
835 /*
836  * Allocate segment table.  On error, destroy the table and set errno.
837  *
838  * Returns 0 on success
839  */
840 static int
841 alloc_segs(hashp, nsegs)
842 	HTAB *hashp;
843 	int nsegs;
844 {
845 	register int i;
846 	register SEGMENT store;
847 
848 	int save_errno;
849 
850 	if (!(hashp->dir = calloc(hashp->DSIZE, sizeof(SEGMENT *)))) {
851 		save_errno = errno;
852 		(void)hdestroy(hashp);
853 		errno = save_errno;
854 		return (-1);
855 	}
856 	/* Allocate segments */
857 	store = calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT));
858 	if (!store) {
859 		save_errno = errno;
860 		(void)hdestroy(hashp);
861 		errno = save_errno;
862 		return (-1);
863 	}
864 	for (i = 0; i < nsegs; i++, hashp->nsegs++)
865 		hashp->dir[i] = &store[i << hashp->SSHIFT];
866 	return (0);
867 }
868 
869 #if BYTE_ORDER == LITTLE_ENDIAN
870 /*
871  * Hashp->hdr needs to be byteswapped.
872  */
873 static void
874 swap_header_copy(srcp, destp)
875 	HASHHDR *srcp, *destp;
876 {
877 	int i;
878 
879 	BLSWAP_COPY(srcp->magic, destp->magic);
880 	BLSWAP_COPY(srcp->version, destp->version);
881 	BLSWAP_COPY(srcp->lorder, destp->lorder);
882 	BLSWAP_COPY(srcp->bsize, destp->bsize);
883 	BLSWAP_COPY(srcp->bshift, destp->bshift);
884 	BLSWAP_COPY(srcp->dsize, destp->dsize);
885 	BLSWAP_COPY(srcp->ssize, destp->ssize);
886 	BLSWAP_COPY(srcp->sshift, destp->sshift);
887 	BLSWAP_COPY(srcp->ovfl_point, destp->ovfl_point);
888 	BLSWAP_COPY(srcp->last_freed, destp->last_freed);
889 	BLSWAP_COPY(srcp->max_bucket, destp->max_bucket);
890 	BLSWAP_COPY(srcp->high_mask, destp->high_mask);
891 	BLSWAP_COPY(srcp->low_mask, destp->low_mask);
892 	BLSWAP_COPY(srcp->ffactor, destp->ffactor);
893 	BLSWAP_COPY(srcp->nkeys, destp->nkeys);
894 	BLSWAP_COPY(srcp->hdrpages, destp->hdrpages);
895 	BLSWAP_COPY(srcp->h_charkey, destp->h_charkey);
896 	for (i = 0; i < NCACHED; i++) {
897 		BLSWAP_COPY(srcp->spares[i], destp->spares[i]);
898 		BSSWAP_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
899 	}
900 }
901 
902 static void
903 swap_header(hashp)
904 	HTAB *hashp;
905 {
906 	HASHHDR *hdrp;
907 	int i;
908 
909 	hdrp = &hashp->hdr;
910 
911 	BLSWAP(hdrp->magic);
912 	BLSWAP(hdrp->version);
913 	BLSWAP(hdrp->lorder);
914 	BLSWAP(hdrp->bsize);
915 	BLSWAP(hdrp->bshift);
916 	BLSWAP(hdrp->dsize);
917 	BLSWAP(hdrp->ssize);
918 	BLSWAP(hdrp->sshift);
919 	BLSWAP(hdrp->ovfl_point);
920 	BLSWAP(hdrp->last_freed);
921 	BLSWAP(hdrp->max_bucket);
922 	BLSWAP(hdrp->high_mask);
923 	BLSWAP(hdrp->low_mask);
924 	BLSWAP(hdrp->ffactor);
925 	BLSWAP(hdrp->nkeys);
926 	BLSWAP(hdrp->hdrpages);
927 	BLSWAP(hdrp->h_charkey);
928 	for (i = 0; i < NCACHED; i++) {
929 		BLSWAP(hdrp->spares[i]);
930 		BSSWAP(hdrp->bitmaps[i]);
931 	}
932 }
933 #endif
934