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