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