include: reduce default stack size
[minix.git] / lib / libc / db / hash / hash.c
blob5e69e4cfe1eeefa8acd9a541d6fdd521cc329b87
1 /* $NetBSD: hash.c,v 1.31 2009/02/12 06:35:54 lukem 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.31 2009/02/12 06:35:54 lukem 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 DEBUG
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);
314 hashp->BSHIFT = __log2((uint32_t)hashp->BSIZE);
317 if (info) {
318 if (info->bsize) {
319 /* Round pagesize up to power of 2 */
320 hashp->BSHIFT = __log2(info->bsize);
321 hashp->BSIZE = 1 << hashp->BSHIFT;
322 if (hashp->BSIZE > MAX_BSIZE) {
323 errno = EINVAL;
324 return (NULL);
327 if (info->ffactor)
328 hashp->FFACTOR = info->ffactor;
329 if (info->hash)
330 hashp->hash = info->hash;
331 if (info->nelem)
332 nelem = info->nelem;
333 if (info->lorder) {
334 if (info->lorder != BIG_ENDIAN &&
335 info->lorder != LITTLE_ENDIAN) {
336 errno = EINVAL;
337 return (NULL);
339 hashp->LORDER = info->lorder;
342 /* init_htab should destroy the table and set errno if it fails */
343 if (init_htab(hashp, (size_t)nelem))
344 return (NULL);
345 else
346 return (hashp);
349 * This calls alloc_segs which may run out of memory. Alloc_segs will destroy
350 * the table and set errno, so we just pass the error information along.
352 * Returns 0 on No Error
354 static int
355 init_htab(HTAB *hashp, size_t nelem)
357 int nbuckets;
358 uint32_t nsegs;
359 int l2;
362 * Divide number of elements by the fill factor and determine a
363 * desired number of buckets. Allocate space for the next greater
364 * power of two number of buckets.
366 nelem = (nelem - 1) / hashp->FFACTOR + 1;
368 _DBFIT(nelem, uint32_t);
369 l2 = __log2(MAX((uint32_t)nelem, 2));
370 nbuckets = 1 << l2;
372 hashp->SPARES[l2] = l2 + 1;
373 hashp->SPARES[l2 + 1] = l2 + 1;
374 hashp->OVFL_POINT = l2;
375 hashp->LAST_FREED = 2;
377 /* First bitmap page is at: splitpoint l2 page offset 1 */
378 if (__ibitmap(hashp, (int)OADDR_OF(l2, 1), l2 + 1, 0))
379 return (-1);
381 hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
382 hashp->HIGH_MASK = (nbuckets << 1) - 1;
383 /* LINTED constant in conditional context */
384 hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
385 hashp->BSHIFT) + 1;
387 nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
388 nsegs = 1 << __log2(nsegs);
390 if (nsegs > (uint32_t)hashp->DSIZE)
391 hashp->DSIZE = nsegs;
392 return (alloc_segs(hashp, (int)nsegs));
395 /********************** DESTROY/CLOSE ROUTINES ************************/
398 * Flushes any changes to the file if necessary and destroys the hashp
399 * structure, freeing all allocated space.
401 static int
402 hdestroy(HTAB *hashp)
404 int i, save_errno;
406 save_errno = 0;
408 #ifdef HASH_STATISTICS
409 (void)fprintf(stderr, "hdestroy: accesses %d collisions %d\n",
410 hash_accesses, hash_collisions);
411 (void)fprintf(stderr, "hdestroy: expansions %d\n",
412 hash_expansions);
413 (void)fprintf(stderr, "hdestroy: overflows %d\n",
414 hash_overflows);
415 (void)fprintf(stderr, "keys %d maxp %d segmentcount %d\n",
416 hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
418 for (i = 0; i < NCACHED; i++)
419 (void)fprintf(stderr,
420 "spares[%d] = %d\n", i, hashp->SPARES[i]);
421 #endif
423 * Call on buffer manager to free buffers, and if required,
424 * write them to disk.
426 if (__buf_free(hashp, 1, hashp->save_file))
427 save_errno = errno;
428 if (hashp->dir) {
429 free(*hashp->dir); /* Free initial segments */
430 /* Free extra segments */
431 while (hashp->exsegs--)
432 free(hashp->dir[--hashp->nsegs]);
433 free(hashp->dir);
435 if (flush_meta(hashp) && !save_errno)
436 save_errno = errno;
437 /* Free Bigmaps */
438 for (i = 0; i < hashp->nmaps; i++)
439 if (hashp->mapp[i])
440 free(hashp->mapp[i]);
442 if (hashp->fp != -1)
443 (void)close(hashp->fp);
445 free(hashp);
447 if (save_errno) {
448 errno = save_errno;
449 return (ERROR);
451 return (SUCCESS);
454 * Write modified pages to disk
456 * Returns:
457 * 0 == OK
458 * -1 ERROR
460 static int
461 hash_sync(const DB *dbp, uint32_t flags)
463 HTAB *hashp;
465 if (flags != 0) {
466 errno = EINVAL;
467 return (ERROR);
470 if (!dbp)
471 return (ERROR);
473 hashp = dbp->internal;
474 if (!hashp->save_file)
475 return (0);
476 if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
477 return (ERROR);
478 hashp->new_file = 0;
479 return (0);
483 * Returns:
484 * 0 == OK
485 * -1 indicates that errno should be set
487 static int
488 flush_meta(HTAB *hashp)
490 HASHHDR *whdrp;
491 #if BYTE_ORDER == LITTLE_ENDIAN
492 HASHHDR whdr;
493 #endif
494 int fp, i;
495 ssize_t wsize;
497 if (!hashp->save_file)
498 return (0);
499 hashp->MAGIC = HASHMAGIC;
500 hashp->VERSION = HASHVERSION;
501 hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
503 fp = hashp->fp;
504 whdrp = &hashp->hdr;
505 #if BYTE_ORDER == LITTLE_ENDIAN
506 whdrp = &whdr;
507 swap_header_copy(&hashp->hdr, whdrp);
508 #endif
509 if ((wsize = pwrite(fp, whdrp, sizeof(HASHHDR), (off_t)0)) == -1)
510 return (-1);
511 else
512 if (wsize != sizeof(HASHHDR)) {
513 errno = EFTYPE;
514 hashp->err = errno;
515 return (-1);
517 for (i = 0; i < NCACHED; i++)
518 if (hashp->mapp[i])
519 if (__put_page(hashp, (char *)(void *)hashp->mapp[i],
520 (u_int)hashp->BITMAPS[i], 0, 1))
521 return (-1);
522 return (0);
525 /*******************************SEARCH ROUTINES *****************************/
527 * All the access routines return
529 * Returns:
530 * 0 on SUCCESS
531 * 1 to indicate an external ERROR (i.e. key not found, etc)
532 * -1 to indicate an internal ERROR (i.e. out of memory, etc)
534 static int
535 hash_get(const DB *dbp, const DBT *key, DBT *data, uint32_t flag)
537 HTAB *hashp;
539 hashp = dbp->internal;
540 if (flag) {
541 hashp->err = errno = EINVAL;
542 return (ERROR);
544 return (hash_access(hashp, HASH_GET, __UNCONST(key), data));
547 static int
548 hash_put(const DB *dbp, DBT *key, const DBT *data, uint32_t flag)
550 HTAB *hashp;
552 hashp = dbp->internal;
553 if (flag && flag != R_NOOVERWRITE) {
554 hashp->err = errno = EINVAL;
555 return (ERROR);
557 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
558 hashp->err = errno = EPERM;
559 return (ERROR);
561 /* LINTED const castaway */
562 return (hash_access(hashp, flag == R_NOOVERWRITE ?
563 HASH_PUTNEW : HASH_PUT, __UNCONST(key), __UNCONST(data)));
566 static int
567 hash_delete(const DB *dbp, const DBT *key, uint32_t flag)
569 HTAB *hashp;
571 hashp = dbp->internal;
572 if (flag && flag != R_CURSOR) {
573 hashp->err = errno = EINVAL;
574 return (ERROR);
576 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
577 hashp->err = errno = EPERM;
578 return (ERROR);
580 return hash_access(hashp, HASH_DELETE, __UNCONST(key), NULL);
584 * Assume that hashp has been set in wrapper routine.
586 static int
587 hash_access(HTAB *hashp, ACTION action, DBT *key, DBT *val)
589 BUFHEAD *rbufp;
590 BUFHEAD *bufp, *save_bufp;
591 uint16_t *bp;
592 int n, ndx, off;
593 size_t size;
594 char *kp;
595 uint16_t pageno;
597 #ifdef HASH_STATISTICS
598 hash_accesses++;
599 #endif
601 off = hashp->BSIZE;
602 size = key->size;
603 kp = (char *)key->data;
604 rbufp = __get_buf(hashp, __call_hash(hashp, kp, (int)size), NULL, 0);
605 if (!rbufp)
606 return (ERROR);
607 save_bufp = rbufp;
609 /* Pin the bucket chain */
610 rbufp->flags |= BUF_PIN;
611 for (bp = (uint16_t *)(void *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
612 if (bp[1] >= REAL_KEY) {
613 /* Real key/data pair */
614 if (size == (size_t)(off - *bp) &&
615 memcmp(kp, rbufp->page + *bp, size) == 0)
616 goto found;
617 off = bp[1];
618 #ifdef HASH_STATISTICS
619 hash_collisions++;
620 #endif
621 bp += 2;
622 ndx += 2;
623 } else if (bp[1] == OVFLPAGE) {
624 rbufp = __get_buf(hashp, (uint32_t)*bp, rbufp, 0);
625 if (!rbufp) {
626 save_bufp->flags &= ~BUF_PIN;
627 return (ERROR);
629 /* FOR LOOP INIT */
630 bp = (uint16_t *)(void *)rbufp->page;
631 n = *bp++;
632 ndx = 1;
633 off = hashp->BSIZE;
634 } else if (bp[1] < REAL_KEY) {
635 if ((ndx =
636 __find_bigpair(hashp, rbufp, ndx, kp, (int)size)) > 0)
637 goto found;
638 if (ndx == -2) {
639 bufp = rbufp;
640 if (!(pageno =
641 __find_last_page(hashp, &bufp))) {
642 ndx = 0;
643 rbufp = bufp;
644 break; /* FOR */
646 rbufp = __get_buf(hashp, (uint32_t)pageno,
647 bufp, 0);
648 if (!rbufp) {
649 save_bufp->flags &= ~BUF_PIN;
650 return (ERROR);
652 /* FOR LOOP INIT */
653 bp = (uint16_t *)(void *)rbufp->page;
654 n = *bp++;
655 ndx = 1;
656 off = hashp->BSIZE;
657 } else {
658 save_bufp->flags &= ~BUF_PIN;
659 return (ERROR);
663 /* Not found */
664 switch (action) {
665 case HASH_PUT:
666 case HASH_PUTNEW:
667 if (__addel(hashp, rbufp, key, val)) {
668 save_bufp->flags &= ~BUF_PIN;
669 return (ERROR);
670 } else {
671 save_bufp->flags &= ~BUF_PIN;
672 return (SUCCESS);
674 case HASH_GET:
675 case HASH_DELETE:
676 default:
677 save_bufp->flags &= ~BUF_PIN;
678 return (ABNORMAL);
681 found:
682 switch (action) {
683 case HASH_PUTNEW:
684 save_bufp->flags &= ~BUF_PIN;
685 return (ABNORMAL);
686 case HASH_GET:
687 bp = (uint16_t *)(void *)rbufp->page;
688 if (bp[ndx + 1] < REAL_KEY) {
689 if (__big_return(hashp, rbufp, ndx, val, 0))
690 return (ERROR);
691 } else {
692 val->data = (uint8_t *)rbufp->page + (int)bp[ndx + 1];
693 val->size = bp[ndx] - bp[ndx + 1];
695 break;
696 case HASH_PUT:
697 if ((__delpair(hashp, rbufp, ndx)) ||
698 (__addel(hashp, rbufp, key, val))) {
699 save_bufp->flags &= ~BUF_PIN;
700 return (ERROR);
702 break;
703 case HASH_DELETE:
704 if (__delpair(hashp, rbufp, ndx))
705 return (ERROR);
706 break;
707 default:
708 abort();
710 save_bufp->flags &= ~BUF_PIN;
711 return (SUCCESS);
714 static int
715 hash_seq(const DB *dbp, DBT *key, DBT *data, uint32_t flag)
717 uint32_t bucket;
718 BUFHEAD *bufp = NULL; /* XXX: gcc */
719 HTAB *hashp;
720 uint16_t *bp, ndx;
722 hashp = dbp->internal;
723 if (flag && flag != R_FIRST && flag != R_NEXT) {
724 hashp->err = errno = EINVAL;
725 return (ERROR);
727 #ifdef HASH_STATISTICS
728 hash_accesses++;
729 #endif
730 if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
731 hashp->cbucket = 0;
732 hashp->cndx = 1;
733 hashp->cpage = NULL;
736 for (bp = NULL; !bp || !bp[0]; ) {
737 if (!(bufp = hashp->cpage)) {
738 for (bucket = hashp->cbucket;
739 bucket <= (uint32_t)hashp->MAX_BUCKET;
740 bucket++, hashp->cndx = 1) {
741 bufp = __get_buf(hashp, bucket, NULL, 0);
742 if (!bufp)
743 return (ERROR);
744 hashp->cpage = bufp;
745 bp = (uint16_t *)(void *)bufp->page;
746 if (bp[0])
747 break;
749 hashp->cbucket = bucket;
750 if (hashp->cbucket > hashp->MAX_BUCKET) {
751 hashp->cbucket = -1;
752 return (ABNORMAL);
754 } else
755 bp = (uint16_t *)(void *)hashp->cpage->page;
757 _DIAGASSERT(bp != NULL);
758 _DIAGASSERT(bufp != NULL);
759 while (bp[hashp->cndx + 1] == OVFLPAGE) {
760 bufp = hashp->cpage =
761 __get_buf(hashp, (uint32_t)bp[hashp->cndx], bufp,
763 if (!bufp)
764 return (ERROR);
765 bp = (uint16_t *)(void *)(bufp->page);
766 hashp->cndx = 1;
768 if (!bp[0]) {
769 hashp->cpage = NULL;
770 ++hashp->cbucket;
773 ndx = hashp->cndx;
774 if (bp[ndx + 1] < REAL_KEY) {
775 if (__big_keydata(hashp, bufp, key, data, 1))
776 return (ERROR);
777 } else {
778 if (hashp->cpage == NULL)
779 return (ERROR);
780 key->data = (uint8_t *)hashp->cpage->page + bp[ndx];
781 key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
782 data->data = (uint8_t *)hashp->cpage->page + bp[ndx + 1];
783 data->size = bp[ndx] - bp[ndx + 1];
784 ndx += 2;
785 if (ndx > bp[0]) {
786 hashp->cpage = NULL;
787 hashp->cbucket++;
788 hashp->cndx = 1;
789 } else
790 hashp->cndx = ndx;
792 return (SUCCESS);
795 /********************************* UTILITIES ************************/
798 * Returns:
799 * 0 ==> OK
800 * -1 ==> Error
803 __expand_table(HTAB *hashp)
805 uint32_t old_bucket, new_bucket;
806 int new_segnum, spare_ndx;
807 size_t dirsize;
809 #ifdef HASH_STATISTICS
810 hash_expansions++;
811 #endif
812 new_bucket = ++hashp->MAX_BUCKET;
813 old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
815 new_segnum = new_bucket >> hashp->SSHIFT;
817 /* Check if we need a new segment */
818 if (new_segnum >= hashp->nsegs) {
819 /* Check if we need to expand directory */
820 if (new_segnum >= hashp->DSIZE) {
821 /* Reallocate directory */
822 dirsize = hashp->DSIZE * sizeof(SEGMENT *);
823 if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
824 return (-1);
825 hashp->DSIZE = dirsize << 1;
827 if ((hashp->dir[new_segnum] =
828 calloc((size_t)hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
829 return (-1);
830 hashp->exsegs++;
831 hashp->nsegs++;
834 * If the split point is increasing (MAX_BUCKET's log base 2
835 * * increases), we need to copy the current contents of the spare
836 * split bucket to the next bucket.
838 spare_ndx = __log2((uint32_t)(hashp->MAX_BUCKET + 1));
839 if (spare_ndx > hashp->OVFL_POINT) {
840 hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
841 hashp->OVFL_POINT = spare_ndx;
844 if (new_bucket > (uint32_t)hashp->HIGH_MASK) {
845 /* Starting a new doubling */
846 hashp->LOW_MASK = hashp->HIGH_MASK;
847 hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
849 /* Relocate records to the new bucket */
850 return (__split_page(hashp, old_bucket, new_bucket));
854 * If realloc guarantees that the pointer is not destroyed if the realloc
855 * fails, then this routine can go away.
857 static void *
858 hash_realloc(SEGMENT **p_ptr, size_t oldsize, size_t newsize)
860 void *p;
862 if ((p = malloc(newsize)) != NULL) {
863 memmove(p, *p_ptr, oldsize);
864 memset((char *)p + oldsize, 0, newsize - oldsize);
865 free(*p_ptr);
866 *p_ptr = p;
868 return (p);
871 uint32_t
872 __call_hash(HTAB *hashp, char *k, int len)
874 int n, bucket;
876 n = hashp->hash(k, (size_t)len);
877 bucket = n & hashp->HIGH_MASK;
878 if (bucket > hashp->MAX_BUCKET)
879 bucket = bucket & hashp->LOW_MASK;
880 return (bucket);
884 * Allocate segment table. On error, destroy the table and set errno.
886 * Returns 0 on success
888 static int
889 alloc_segs(HTAB *hashp, int nsegs)
891 int i;
892 SEGMENT store;
894 int save_errno;
896 hashp->dir = calloc((size_t)hashp->DSIZE, sizeof(SEGMENT *));
897 if (hashp->dir == NULL) {
898 save_errno = errno;
899 (void)hdestroy(hashp);
900 errno = save_errno;
901 return (-1);
903 hashp->nsegs = nsegs;
904 if (nsegs == 0)
905 return 0;
906 /* Allocate segments */
907 store = calloc((size_t)(nsegs << hashp->SSHIFT), sizeof(SEGMENT));
908 if (store == NULL) {
909 save_errno = errno;
910 (void)hdestroy(hashp);
911 errno = save_errno;
912 return (-1);
914 for (i = 0; i < nsegs; i++)
915 hashp->dir[i] = &store[i << hashp->SSHIFT];
916 return (0);
919 #if BYTE_ORDER == LITTLE_ENDIAN
921 * Hashp->hdr needs to be byteswapped.
923 static void
924 swap_header_copy(HASHHDR *srcp, HASHHDR *destp)
926 size_t i;
928 P_32_COPY(srcp->magic, destp->magic);
929 P_32_COPY(srcp->version, destp->version);
930 P_32_COPY(srcp->lorder, destp->lorder);
931 P_32_COPY(srcp->bsize, destp->bsize);
932 P_32_COPY(srcp->bshift, destp->bshift);
933 P_32_COPY(srcp->dsize, destp->dsize);
934 P_32_COPY(srcp->ssize, destp->ssize);
935 P_32_COPY(srcp->sshift, destp->sshift);
936 P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
937 P_32_COPY(srcp->last_freed, destp->last_freed);
938 P_32_COPY(srcp->max_bucket, destp->max_bucket);
939 P_32_COPY(srcp->high_mask, destp->high_mask);
940 P_32_COPY(srcp->low_mask, destp->low_mask);
941 P_32_COPY(srcp->ffactor, destp->ffactor);
942 P_32_COPY(srcp->nkeys, destp->nkeys);
943 P_32_COPY(srcp->hdrpages, destp->hdrpages);
944 P_32_COPY(srcp->h_charkey, destp->h_charkey);
945 for (i = 0; i < NCACHED; i++) {
946 P_32_COPY(srcp->spares[i], destp->spares[i]);
947 P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
951 static void
952 swap_header(HTAB *hashp)
954 HASHHDR *hdrp;
955 size_t i;
957 hdrp = &hashp->hdr;
959 M_32_SWAP(hdrp->magic);
960 M_32_SWAP(hdrp->version);
961 M_32_SWAP(hdrp->lorder);
962 M_32_SWAP(hdrp->bsize);
963 M_32_SWAP(hdrp->bshift);
964 M_32_SWAP(hdrp->dsize);
965 M_32_SWAP(hdrp->ssize);
966 M_32_SWAP(hdrp->sshift);
967 M_32_SWAP(hdrp->ovfl_point);
968 M_32_SWAP(hdrp->last_freed);
969 M_32_SWAP(hdrp->max_bucket);
970 M_32_SWAP(hdrp->high_mask);
971 M_32_SWAP(hdrp->low_mask);
972 M_32_SWAP(hdrp->ffactor);
973 M_32_SWAP(hdrp->nkeys);
974 M_32_SWAP(hdrp->hdrpages);
975 M_32_SWAP(hdrp->h_charkey);
976 for (i = 0; i < NCACHED; i++) {
977 M_32_SWAP(hdrp->spares[i]);
978 M_16_SWAP(hdrp->bitmaps[i]);
981 #endif