add opendir alias
[minix.git] / lib / libc / db / hash / hash.c
blob79cb812d532fe200d51ba148213e10b593a56769
1 /* $NetBSD: hash.c,v 1.32 2012/03/13 21:13:32 christos Exp $ */
3 /*-
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Margo Seltzer.
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.
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.
35 #if HAVE_NBTOOL_CONFIG_H
36 #include "nbtool_config.h"
37 #endif
39 #include <sys/cdefs.h>
40 __RCSID("$NetBSD: hash.c,v 1.32 2012/03/13 21:13:32 christos Exp $");
42 #include "namespace.h"
43 #include <sys/param.h>
44 #include <sys/stat.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <assert.h>
54 #include <db.h>
55 #include "hash.h"
56 #include "page.h"
57 #include "extern.h"
59 static int alloc_segs(HTAB *, int);
60 static int flush_meta(HTAB *);
61 static int hash_access(HTAB *, ACTION, DBT *, DBT *);
62 static int hash_close(DB *);
63 static int hash_delete(const DB *, const DBT *, uint32_t);
64 static int hash_fd(const DB *);
65 static int hash_get(const DB *, const DBT *, DBT *, uint32_t);
66 static int hash_put(const DB *, DBT *, const DBT *, uint32_t);
67 static void *hash_realloc(SEGMENT **, size_t, size_t);
68 static int hash_seq(const DB *, DBT *, DBT *, uint32_t);
69 static int hash_sync(const DB *, uint32_t);
70 static int hdestroy(HTAB *);
71 static HTAB *init_hash(HTAB *, const char *, const HASHINFO *);
72 static int init_htab(HTAB *, size_t);
73 #if BYTE_ORDER == LITTLE_ENDIAN
74 static void swap_header(HTAB *);
75 static void swap_header_copy(HASHHDR *, HASHHDR *);
76 #endif
78 /* Fast arithmetic, relying on powers of 2, */
79 #define MOD(x, y) ((x) & ((y) - 1))
81 #define RETURN_ERROR(ERR, LOC) { save_errno = ERR; goto LOC; }
83 /* Return values */
84 #define SUCCESS (0)
85 #define ERROR (-1)
86 #define ABNORMAL (1)
88 #ifdef HASH_STATISTICS
89 int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
90 #endif
92 /************************** INTERFACE ROUTINES ***************************/
93 /* OPEN/CLOSE */
95 /* ARGSUSED */
96 DB *
97 __hash_open(const char *file, int flags, mode_t mode, const HASHINFO *info,
98 int dflags)
100 HTAB *hashp;
101 struct stat statbuf;
102 DB *dbp;
103 int bpages, new_table, nsegs, save_errno;
104 ssize_t hdrsize;
106 if ((flags & O_ACCMODE) == O_WRONLY) {
107 errno = EINVAL;
108 return (NULL);
111 if (!(hashp = calloc(1, sizeof(HTAB))))
112 return (NULL);
113 hashp->fp = -1;
116 * Even if user wants write only, we need to be able to read
117 * the actual file, so we need to open it read/write. But, the
118 * field in the hashp structure needs to be accurate so that
119 * we can check accesses.
121 hashp->flags = flags;
123 new_table = 0;
124 if (!file || (flags & O_TRUNC) ||
125 (stat(file, &statbuf) && (errno == ENOENT))) {
126 if (errno == ENOENT)
127 errno = 0; /* Just in case someone looks at errno */
128 new_table = 1;
130 if (file) {
131 if ((hashp->fp = open(file, flags, mode)) == -1)
132 RETURN_ERROR(errno, error0);
133 if (fcntl(hashp->fp, F_SETFD, FD_CLOEXEC) == -1)
134 RETURN_ERROR(errno, error1);
135 if (fstat(hashp->fp, &statbuf) == -1)
136 RETURN_ERROR(errno, error1);
137 new_table |= statbuf.st_size == 0;
139 if (new_table) {
140 if (!(hashp = init_hash(hashp, file, info)))
141 RETURN_ERROR(errno, error1);
142 } else {
143 /* Table already exists */
144 if (info && info->hash)
145 hashp->hash = info->hash;
146 else
147 hashp->hash = __default_hash;
149 hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
150 #if BYTE_ORDER == LITTLE_ENDIAN
151 swap_header(hashp);
152 #endif
153 if (hdrsize == -1)
154 RETURN_ERROR(errno, error1);
155 if (hdrsize != sizeof(HASHHDR))
156 RETURN_ERROR(EFTYPE, error1);
157 /* Verify file type, versions and hash function */
158 if (hashp->MAGIC != HASHMAGIC)
159 RETURN_ERROR(EFTYPE, error1);
160 #define OLDHASHVERSION 1
161 if (hashp->VERSION != HASHVERSION &&
162 hashp->VERSION != OLDHASHVERSION)
163 RETURN_ERROR(EFTYPE, error1);
164 if (hashp->hash(CHARKEY, sizeof(CHARKEY)) !=
165 (uint32_t)hashp->H_CHARKEY)
166 RETURN_ERROR(EFTYPE, error1);
168 * Figure out how many segments we need. Max_Bucket is the
169 * maximum bucket number, so the number of buckets is
170 * max_bucket + 1.
172 nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
173 hashp->SGSIZE;
174 hashp->nsegs = 0;
175 if (alloc_segs(hashp, nsegs))
177 * If alloc_segs fails, table will have been destroyed
178 * and errno will have been set.
180 return (NULL);
181 /* Read in bitmaps */
182 bpages = (hashp->SPARES[hashp->OVFL_POINT] +
183 (unsigned int)(hashp->BSIZE << BYTE_SHIFT) - 1) >>
184 (hashp->BSHIFT + BYTE_SHIFT);
186 hashp->nmaps = bpages;
187 (void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32_t *));
190 /* Initialize Buffer Manager */
191 if (info && info->cachesize)
192 __buf_init(hashp, info->cachesize);
193 else
194 __buf_init(hashp, DEF_BUFSIZE);
196 hashp->new_file = new_table;
197 hashp->save_file = file && (hashp->flags & O_RDWR);
198 hashp->cbucket = -1;
199 if (!(dbp = malloc(sizeof(DB)))) {
200 save_errno = errno;
201 hdestroy(hashp);
202 errno = save_errno;
203 return (NULL);
205 dbp->internal = hashp;
206 dbp->close = hash_close;
207 dbp->del = hash_delete;
208 dbp->fd = hash_fd;
209 dbp->get = hash_get;
210 dbp->put = hash_put;
211 dbp->seq = hash_seq;
212 dbp->sync = hash_sync;
213 dbp->type = DB_HASH;
215 #ifdef DEBUG1
216 (void)fprintf(stderr,
217 "%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",
218 "init_htab:",
219 "TABLE POINTER ", hashp,
220 "BUCKET SIZE ", hashp->BSIZE,
221 "BUCKET SHIFT ", hashp->BSHIFT,
222 "DIRECTORY SIZE ", hashp->DSIZE,
223 "SEGMENT SIZE ", hashp->SGSIZE,
224 "SEGMENT SHIFT ", hashp->SSHIFT,
225 "FILL FACTOR ", hashp->FFACTOR,
226 "MAX BUCKET ", hashp->MAX_BUCKET,
227 "OVFL POINT ", hashp->OVFL_POINT,
228 "LAST FREED ", hashp->LAST_FREED,
229 "HIGH MASK ", hashp->HIGH_MASK,
230 "LOW MASK ", hashp->LOW_MASK,
231 "NSEGS ", hashp->nsegs,
232 "NKEYS ", hashp->NKEYS);
233 #endif
234 #ifdef HASH_STATISTICS
235 hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
236 #endif
237 return (dbp);
239 error1:
240 if (hashp != NULL)
241 (void)close(hashp->fp);
243 error0:
244 free(hashp);
245 errno = save_errno;
246 return (NULL);
249 static int
250 hash_close(DB *dbp)
252 HTAB *hashp;
253 int retval;
255 if (!dbp)
256 return (ERROR);
258 hashp = dbp->internal;
259 retval = hdestroy(hashp);
260 free(dbp);
261 return (retval);
264 static int
265 hash_fd(const DB *dbp)
267 HTAB *hashp;
269 if (!dbp)
270 return (ERROR);
272 hashp = dbp->internal;
273 if (hashp->fp == -1) {
274 errno = ENOENT;
275 return (-1);
277 return (hashp->fp);
280 /************************** LOCAL CREATION ROUTINES **********************/
281 static HTAB *
282 init_hash(HTAB *hashp, const char *file, const HASHINFO *info)
284 struct stat statbuf;
285 int nelem;
287 nelem = 1;
288 hashp->NKEYS = 0;
289 hashp->LORDER = BYTE_ORDER;
290 hashp->BSIZE = DEF_BUCKET_SIZE;
291 hashp->BSHIFT = DEF_BUCKET_SHIFT;
292 hashp->SGSIZE = DEF_SEGSIZE;
293 hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
294 hashp->DSIZE = DEF_DIRSIZE;
295 hashp->FFACTOR = DEF_FFACTOR;
296 hashp->hash = __default_hash;
297 memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
298 memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
300 /* Fix bucket size to be optimal for file system */
301 if (file != NULL) {
302 if (stat(file, &statbuf))
303 return (NULL);
304 #ifdef __minix
305 if (statbuf.st_blksize == 0) {
306 /* 0 in 2 cases: upgrade from old to new struct stat or
307 * there is a bug in underlying fs.
309 hashp->BSIZE = MIN(MINIX_ST_BLKSIZE, MAX_BSIZE);
310 } else
311 #endif
312 hashp->BSIZE = MIN(statbuf.st_blksize, MAX_BSIZE);
313 hashp->BSHIFT = __log2((uint32_t)hashp->BSIZE);
316 if (info) {
317 if (info->bsize) {
318 /* Round pagesize up to power of 2 */
319 hashp->BSHIFT = __log2(info->bsize);
320 hashp->BSIZE = 1 << hashp->BSHIFT;
321 if (hashp->BSIZE > MAX_BSIZE) {
322 errno = EINVAL;
323 return (NULL);
326 if (info->ffactor)
327 hashp->FFACTOR = info->ffactor;
328 if (info->hash)
329 hashp->hash = info->hash;
330 if (info->nelem)
331 nelem = info->nelem;
332 if (info->lorder) {
333 if (info->lorder != BIG_ENDIAN &&
334 info->lorder != LITTLE_ENDIAN) {
335 errno = EINVAL;
336 return (NULL);
338 hashp->LORDER = info->lorder;
341 /* init_htab should destroy the table and set errno if it fails */
342 if (init_htab(hashp, (size_t)nelem))
343 return (NULL);
344 else
345 return (hashp);
348 * This calls alloc_segs which may run out of memory. Alloc_segs will destroy
349 * the table and set errno, so we just pass the error information along.
351 * Returns 0 on No Error
353 static int
354 init_htab(HTAB *hashp, size_t nelem)
356 int nbuckets;
357 uint32_t nsegs;
358 int l2;
361 * Divide number of elements by the fill factor and determine a
362 * desired number of buckets. Allocate space for the next greater
363 * power of two number of buckets.
365 nelem = (nelem - 1) / hashp->FFACTOR + 1;
367 _DBFIT(nelem, uint32_t);
368 l2 = __log2(MAX((uint32_t)nelem, 2));
369 nbuckets = 1 << l2;
371 hashp->SPARES[l2] = l2 + 1;
372 hashp->SPARES[l2 + 1] = l2 + 1;
373 hashp->OVFL_POINT = l2;
374 hashp->LAST_FREED = 2;
376 /* First bitmap page is at: splitpoint l2 page offset 1 */
377 if (__ibitmap(hashp, (int)OADDR_OF(l2, 1), l2 + 1, 0))
378 return (-1);
380 hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
381 hashp->HIGH_MASK = (nbuckets << 1) - 1;
382 /* LINTED constant in conditional context */
383 hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
384 hashp->BSHIFT) + 1;
386 nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
387 nsegs = 1 << __log2(nsegs);
389 if (nsegs > (uint32_t)hashp->DSIZE)
390 hashp->DSIZE = nsegs;
391 return (alloc_segs(hashp, (int)nsegs));
394 /********************** DESTROY/CLOSE ROUTINES ************************/
397 * Flushes any changes to the file if necessary and destroys the hashp
398 * structure, freeing all allocated space.
400 static int
401 hdestroy(HTAB *hashp)
403 int i, save_errno;
405 save_errno = 0;
407 #ifdef HASH_STATISTICS
408 (void)fprintf(stderr, "hdestroy: accesses %d collisions %d\n",
409 hash_accesses, hash_collisions);
410 (void)fprintf(stderr, "hdestroy: expansions %d\n",
411 hash_expansions);
412 (void)fprintf(stderr, "hdestroy: overflows %d\n",
413 hash_overflows);
414 (void)fprintf(stderr, "keys %d maxp %d segmentcount %d\n",
415 hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
417 for (i = 0; i < NCACHED; i++)
418 (void)fprintf(stderr,
419 "spares[%d] = %d\n", i, hashp->SPARES[i]);
420 #endif
422 * Call on buffer manager to free buffers, and if required,
423 * write them to disk.
425 if (__buf_free(hashp, 1, hashp->save_file))
426 save_errno = errno;
427 if (hashp->dir) {
428 free(*hashp->dir); /* Free initial segments */
429 /* Free extra segments */
430 while (hashp->exsegs--)
431 free(hashp->dir[--hashp->nsegs]);
432 free(hashp->dir);
434 if (flush_meta(hashp) && !save_errno)
435 save_errno = errno;
436 /* Free Bigmaps */
437 for (i = 0; i < hashp->nmaps; i++)
438 if (hashp->mapp[i])
439 free(hashp->mapp[i]);
441 if (hashp->fp != -1)
442 (void)close(hashp->fp);
444 free(hashp);
446 if (save_errno) {
447 errno = save_errno;
448 return (ERROR);
450 return (SUCCESS);
453 * Write modified pages to disk
455 * Returns:
456 * 0 == OK
457 * -1 ERROR
459 static int
460 hash_sync(const DB *dbp, uint32_t flags)
462 HTAB *hashp;
464 if (flags != 0) {
465 errno = EINVAL;
466 return (ERROR);
469 if (!dbp)
470 return (ERROR);
472 hashp = dbp->internal;
473 if (!hashp->save_file)
474 return (0);
475 if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
476 return (ERROR);
477 hashp->new_file = 0;
478 return (0);
482 * Returns:
483 * 0 == OK
484 * -1 indicates that errno should be set
486 static int
487 flush_meta(HTAB *hashp)
489 HASHHDR *whdrp;
490 #if BYTE_ORDER == LITTLE_ENDIAN
491 HASHHDR whdr;
492 #endif
493 int fp, i;
494 ssize_t wsize;
496 if (!hashp->save_file)
497 return (0);
498 hashp->MAGIC = HASHMAGIC;
499 hashp->VERSION = HASHVERSION;
500 hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
502 fp = hashp->fp;
503 whdrp = &hashp->hdr;
504 #if BYTE_ORDER == LITTLE_ENDIAN
505 whdrp = &whdr;
506 swap_header_copy(&hashp->hdr, whdrp);
507 #endif
508 if ((wsize = pwrite(fp, whdrp, sizeof(HASHHDR), (off_t)0)) == -1)
509 return (-1);
510 else
511 if (wsize != sizeof(HASHHDR)) {
512 errno = EFTYPE;
513 hashp->err = errno;
514 return (-1);
516 for (i = 0; i < NCACHED; i++)
517 if (hashp->mapp[i])
518 if (__put_page(hashp, (char *)(void *)hashp->mapp[i],
519 (u_int)hashp->BITMAPS[i], 0, 1))
520 return (-1);
521 return (0);
524 /*******************************SEARCH ROUTINES *****************************/
526 * All the access routines return
528 * Returns:
529 * 0 on SUCCESS
530 * 1 to indicate an external ERROR (i.e. key not found, etc)
531 * -1 to indicate an internal ERROR (i.e. out of memory, etc)
533 static int
534 hash_get(const DB *dbp, const DBT *key, DBT *data, uint32_t flag)
536 HTAB *hashp;
538 hashp = dbp->internal;
539 if (flag) {
540 hashp->err = errno = EINVAL;
541 return (ERROR);
543 return (hash_access(hashp, HASH_GET, __UNCONST(key), data));
546 static int
547 hash_put(const DB *dbp, DBT *key, const DBT *data, uint32_t flag)
549 HTAB *hashp;
551 hashp = dbp->internal;
552 if (flag && flag != R_NOOVERWRITE) {
553 hashp->err = errno = EINVAL;
554 return (ERROR);
556 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
557 hashp->err = errno = EPERM;
558 return (ERROR);
560 /* LINTED const castaway */
561 return (hash_access(hashp, flag == R_NOOVERWRITE ?
562 HASH_PUTNEW : HASH_PUT, __UNCONST(key), __UNCONST(data)));
565 static int
566 hash_delete(const DB *dbp, const DBT *key, uint32_t flag)
568 HTAB *hashp;
570 hashp = dbp->internal;
571 if (flag && flag != R_CURSOR) {
572 hashp->err = errno = EINVAL;
573 return (ERROR);
575 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
576 hashp->err = errno = EPERM;
577 return (ERROR);
579 return hash_access(hashp, HASH_DELETE, __UNCONST(key), NULL);
583 * Assume that hashp has been set in wrapper routine.
585 static int
586 hash_access(HTAB *hashp, ACTION action, DBT *key, DBT *val)
588 BUFHEAD *rbufp;
589 BUFHEAD *bufp, *save_bufp;
590 uint16_t *bp;
591 int n, ndx, off;
592 size_t size;
593 char *kp;
594 uint16_t pageno;
596 #ifdef HASH_STATISTICS
597 hash_accesses++;
598 #endif
600 off = hashp->BSIZE;
601 size = key->size;
602 kp = (char *)key->data;
603 rbufp = __get_buf(hashp, __call_hash(hashp, kp, (int)size), NULL, 0);
604 if (!rbufp)
605 return (ERROR);
606 save_bufp = rbufp;
608 /* Pin the bucket chain */
609 rbufp->flags |= BUF_PIN;
610 for (bp = (uint16_t *)(void *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
611 if (bp[1] >= REAL_KEY) {
612 /* Real key/data pair */
613 if (size == (size_t)(off - *bp) &&
614 memcmp(kp, rbufp->page + *bp, size) == 0)
615 goto found;
616 off = bp[1];
617 #ifdef HASH_STATISTICS
618 hash_collisions++;
619 #endif
620 bp += 2;
621 ndx += 2;
622 } else if (bp[1] == OVFLPAGE) {
623 rbufp = __get_buf(hashp, (uint32_t)*bp, rbufp, 0);
624 if (!rbufp) {
625 save_bufp->flags &= ~BUF_PIN;
626 return (ERROR);
628 /* FOR LOOP INIT */
629 bp = (uint16_t *)(void *)rbufp->page;
630 n = *bp++;
631 ndx = 1;
632 off = hashp->BSIZE;
633 } else if (bp[1] < REAL_KEY) {
634 if ((ndx =
635 __find_bigpair(hashp, rbufp, ndx, kp, (int)size)) > 0)
636 goto found;
637 if (ndx == -2) {
638 bufp = rbufp;
639 if (!(pageno =
640 __find_last_page(hashp, &bufp))) {
641 ndx = 0;
642 rbufp = bufp;
643 break; /* FOR */
645 rbufp = __get_buf(hashp, (uint32_t)pageno,
646 bufp, 0);
647 if (!rbufp) {
648 save_bufp->flags &= ~BUF_PIN;
649 return (ERROR);
651 /* FOR LOOP INIT */
652 bp = (uint16_t *)(void *)rbufp->page;
653 n = *bp++;
654 ndx = 1;
655 off = hashp->BSIZE;
656 } else {
657 save_bufp->flags &= ~BUF_PIN;
658 return (ERROR);
662 /* Not found */
663 switch (action) {
664 case HASH_PUT:
665 case HASH_PUTNEW:
666 if (__addel(hashp, rbufp, key, val)) {
667 save_bufp->flags &= ~BUF_PIN;
668 return (ERROR);
669 } else {
670 save_bufp->flags &= ~BUF_PIN;
671 return (SUCCESS);
673 case HASH_GET:
674 case HASH_DELETE:
675 default:
676 save_bufp->flags &= ~BUF_PIN;
677 return (ABNORMAL);
680 found:
681 switch (action) {
682 case HASH_PUTNEW:
683 save_bufp->flags &= ~BUF_PIN;
684 return (ABNORMAL);
685 case HASH_GET:
686 bp = (uint16_t *)(void *)rbufp->page;
687 if (bp[ndx + 1] < REAL_KEY) {
688 if (__big_return(hashp, rbufp, ndx, val, 0))
689 return (ERROR);
690 } else {
691 val->data = (uint8_t *)rbufp->page + (int)bp[ndx + 1];
692 val->size = bp[ndx] - bp[ndx + 1];
694 break;
695 case HASH_PUT:
696 if ((__delpair(hashp, rbufp, ndx)) ||
697 (__addel(hashp, rbufp, key, val))) {
698 save_bufp->flags &= ~BUF_PIN;
699 return (ERROR);
701 break;
702 case HASH_DELETE:
703 if (__delpair(hashp, rbufp, ndx))
704 return (ERROR);
705 break;
706 default:
707 abort();
709 save_bufp->flags &= ~BUF_PIN;
710 return (SUCCESS);
713 static int
714 hash_seq(const DB *dbp, DBT *key, DBT *data, uint32_t flag)
716 uint32_t bucket;
717 BUFHEAD *bufp = NULL; /* XXX: gcc */
718 HTAB *hashp;
719 uint16_t *bp, ndx;
721 hashp = dbp->internal;
722 if (flag && flag != R_FIRST && flag != R_NEXT) {
723 hashp->err = errno = EINVAL;
724 return (ERROR);
726 #ifdef HASH_STATISTICS
727 hash_accesses++;
728 #endif
729 if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
730 hashp->cbucket = 0;
731 hashp->cndx = 1;
732 hashp->cpage = NULL;
735 for (bp = NULL; !bp || !bp[0]; ) {
736 if (!(bufp = hashp->cpage)) {
737 for (bucket = hashp->cbucket;
738 bucket <= (uint32_t)hashp->MAX_BUCKET;
739 bucket++, hashp->cndx = 1) {
740 bufp = __get_buf(hashp, bucket, NULL, 0);
741 if (!bufp)
742 return (ERROR);
743 hashp->cpage = bufp;
744 bp = (uint16_t *)(void *)bufp->page;
745 if (bp[0])
746 break;
748 hashp->cbucket = bucket;
749 if (hashp->cbucket > hashp->MAX_BUCKET) {
750 hashp->cbucket = -1;
751 return (ABNORMAL);
753 } else
754 bp = (uint16_t *)(void *)hashp->cpage->page;
756 _DIAGASSERT(bp != NULL);
757 _DIAGASSERT(bufp != NULL);
758 while (bp[hashp->cndx + 1] == OVFLPAGE) {
759 bufp = hashp->cpage =
760 __get_buf(hashp, (uint32_t)bp[hashp->cndx], bufp,
762 if (!bufp)
763 return (ERROR);
764 bp = (uint16_t *)(void *)(bufp->page);
765 hashp->cndx = 1;
767 if (!bp[0]) {
768 hashp->cpage = NULL;
769 ++hashp->cbucket;
772 ndx = hashp->cndx;
773 if (bp[ndx + 1] < REAL_KEY) {
774 if (__big_keydata(hashp, bufp, key, data, 1))
775 return (ERROR);
776 } else {
777 if (hashp->cpage == NULL)
778 return (ERROR);
779 key->data = (uint8_t *)hashp->cpage->page + bp[ndx];
780 key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
781 data->data = (uint8_t *)hashp->cpage->page + bp[ndx + 1];
782 data->size = bp[ndx] - bp[ndx + 1];
783 ndx += 2;
784 if (ndx > bp[0]) {
785 hashp->cpage = NULL;
786 hashp->cbucket++;
787 hashp->cndx = 1;
788 } else
789 hashp->cndx = ndx;
791 return (SUCCESS);
794 /********************************* UTILITIES ************************/
797 * Returns:
798 * 0 ==> OK
799 * -1 ==> Error
802 __expand_table(HTAB *hashp)
804 uint32_t old_bucket, new_bucket;
805 int new_segnum, spare_ndx;
806 size_t dirsize;
808 #ifdef HASH_STATISTICS
809 hash_expansions++;
810 #endif
811 new_bucket = ++hashp->MAX_BUCKET;
812 old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
814 new_segnum = new_bucket >> hashp->SSHIFT;
816 /* Check if we need a new segment */
817 if (new_segnum >= hashp->nsegs) {
818 /* Check if we need to expand directory */
819 if (new_segnum >= hashp->DSIZE) {
820 /* Reallocate directory */
821 dirsize = hashp->DSIZE * sizeof(SEGMENT *);
822 if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
823 return (-1);
824 dirsize <<= 1;
825 _DBFIT(dirsize, uint32_t);
826 hashp->DSIZE = (uint32_t)dirsize;
828 if ((hashp->dir[new_segnum] =
829 calloc((size_t)hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
830 return (-1);
831 hashp->exsegs++;
832 hashp->nsegs++;
835 * If the split point is increasing (MAX_BUCKET's log base 2
836 * * increases), we need to copy the current contents of the spare
837 * split bucket to the next bucket.
839 spare_ndx = __log2((uint32_t)(hashp->MAX_BUCKET + 1));
840 if (spare_ndx > hashp->OVFL_POINT) {
841 hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
842 hashp->OVFL_POINT = spare_ndx;
845 if (new_bucket > (uint32_t)hashp->HIGH_MASK) {
846 /* Starting a new doubling */
847 hashp->LOW_MASK = hashp->HIGH_MASK;
848 hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
850 /* Relocate records to the new bucket */
851 return (__split_page(hashp, old_bucket, new_bucket));
855 * If realloc guarantees that the pointer is not destroyed if the realloc
856 * fails, then this routine can go away.
858 static void *
859 hash_realloc(SEGMENT **p_ptr, size_t oldsize, size_t newsize)
861 void *p;
863 if ((p = malloc(newsize)) != NULL) {
864 memmove(p, *p_ptr, oldsize);
865 memset((char *)p + oldsize, 0, newsize - oldsize);
866 free(*p_ptr);
867 *p_ptr = p;
869 return (p);
872 uint32_t
873 __call_hash(HTAB *hashp, char *k, int len)
875 int n, bucket;
877 n = hashp->hash(k, (size_t)len);
878 bucket = n & hashp->HIGH_MASK;
879 if (bucket > hashp->MAX_BUCKET)
880 bucket = bucket & hashp->LOW_MASK;
881 return (bucket);
885 * Allocate segment table. On error, destroy the table and set errno.
887 * Returns 0 on success
889 static int
890 alloc_segs(HTAB *hashp, int nsegs)
892 int i;
893 SEGMENT store;
895 int save_errno;
897 hashp->dir = calloc((size_t)hashp->DSIZE, sizeof(SEGMENT *));
898 if (hashp->dir == NULL) {
899 save_errno = errno;
900 (void)hdestroy(hashp);
901 errno = save_errno;
902 return (-1);
904 hashp->nsegs = nsegs;
905 if (nsegs == 0)
906 return 0;
907 /* Allocate segments */
908 store = calloc((size_t)(nsegs << hashp->SSHIFT), sizeof(SEGMENT));
909 if (store == NULL) {
910 save_errno = errno;
911 (void)hdestroy(hashp);
912 errno = save_errno;
913 return (-1);
915 for (i = 0; i < nsegs; i++)
916 hashp->dir[i] = &store[i << hashp->SSHIFT];
917 return (0);
920 #if BYTE_ORDER == LITTLE_ENDIAN
922 * Hashp->hdr needs to be byteswapped.
924 static void
925 swap_header_copy(HASHHDR *srcp, HASHHDR *destp)
927 size_t i;
929 P_32_COPY(srcp->magic, destp->magic);
930 P_32_COPY(srcp->version, destp->version);
931 P_32_COPY(srcp->lorder, destp->lorder);
932 P_32_COPY(srcp->bsize, destp->bsize);
933 P_32_COPY(srcp->bshift, destp->bshift);
934 P_32_COPY(srcp->dsize, destp->dsize);
935 P_32_COPY(srcp->ssize, destp->ssize);
936 P_32_COPY(srcp->sshift, destp->sshift);
937 P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
938 P_32_COPY(srcp->last_freed, destp->last_freed);
939 P_32_COPY(srcp->max_bucket, destp->max_bucket);
940 P_32_COPY(srcp->high_mask, destp->high_mask);
941 P_32_COPY(srcp->low_mask, destp->low_mask);
942 P_32_COPY(srcp->ffactor, destp->ffactor);
943 P_32_COPY(srcp->nkeys, destp->nkeys);
944 P_32_COPY(srcp->hdrpages, destp->hdrpages);
945 P_32_COPY(srcp->h_charkey, destp->h_charkey);
946 for (i = 0; i < NCACHED; i++) {
947 P_32_COPY(srcp->spares[i], destp->spares[i]);
948 P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
952 static void
953 swap_header(HTAB *hashp)
955 HASHHDR *hdrp;
956 size_t i;
958 hdrp = &hashp->hdr;
960 M_32_SWAP(hdrp->magic);
961 M_32_SWAP(hdrp->version);
962 M_32_SWAP(hdrp->lorder);
963 M_32_SWAP(hdrp->bsize);
964 M_32_SWAP(hdrp->bshift);
965 M_32_SWAP(hdrp->dsize);
966 M_32_SWAP(hdrp->ssize);
967 M_32_SWAP(hdrp->sshift);
968 M_32_SWAP(hdrp->ovfl_point);
969 M_32_SWAP(hdrp->last_freed);
970 M_32_SWAP(hdrp->max_bucket);
971 M_32_SWAP(hdrp->high_mask);
972 M_32_SWAP(hdrp->low_mask);
973 M_32_SWAP(hdrp->ffactor);
974 M_32_SWAP(hdrp->nkeys);
975 M_32_SWAP(hdrp->hdrpages);
976 M_32_SWAP(hdrp->h_charkey);
977 for (i = 0; i < NCACHED; i++) {
978 M_32_SWAP(hdrp->spares[i]);
979 M_16_SWAP(hdrp->bitmaps[i]);
982 #endif