Cygwin: mmap: allow remapping part of an existing anonymous mapping
[newlib-cygwin.git] / newlib / libc / search / hash.c
blobf242337f5b65e9a501c96a0ea0812c6e77b52718
1 /*-
2 * Copyright (c) 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Margo Seltzer.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #include <sys/param.h>
34 #if defined(LIBC_SCCS) && !defined(lint)
35 static char sccsid[] = "@(#)hash.c 8.9 (Berkeley) 6/16/94";
36 #endif /* LIBC_SCCS and not lint */
37 #include <sys/cdefs.h>
38 #include <sys/types.h>
40 #include <sys/stat.h>
42 #include <reent.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #ifdef DEBUG
50 #include <assert.h>
51 #endif
53 #define __DBINTERFACE_PRIVATE /* activate prototypes from db_local.h */
54 #include "db_local.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 *, u_int);
64 static int hash_fd(const DB *);
65 static int hash_get(const DB *, const DBT *, DBT *, u_int);
66 static int hash_put(const DB *, DBT *, const DBT *, u_int);
67 static void *hash_realloc(SEGMENT **, int, int);
68 static int hash_seq(const DB *, DBT *, DBT *, u_int);
69 static int hash_sync(const DB *, u_int);
70 static int hdestroy(HTAB *);
71 static HTAB *init_hash(HTAB *, const char *, const HASHINFO *);
72 static int init_htab(HTAB *, int);
73 #if (BYTE_ORDER == LITTLE_ENDIAN)
74 static void swap_header(HTAB *);
75 static void swap_header_copy(HASHHDR *, HASHHDR *);
76 #endif
78 /* Macros for min/max. */
79 #ifndef MIN
80 #define MIN(a,b) (((a)<(b))?(a):(b))
81 #endif
82 #ifndef MAX
83 #define MAX(a,b) (((a)>(b))?(a):(b))
84 #endif
86 /* Fast arithmetic, relying on powers of 2, */
87 #define MOD(x, y) ((x) & ((y) - 1))
89 #define RETURN_ERROR(ERR, LOC) { save_errno = ERR; goto LOC; }
91 /* Return values */
92 #define SUCCESS (0)
93 #define ERROR (-1)
94 #define ABNORMAL (1)
96 #ifdef HASH_STATISTICS
97 int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
98 #endif
100 /************************** INTERFACE ROUTINES ***************************/
101 /* OPEN/CLOSE */
103 extern DB *
104 __hash_open (const char *file,
105 int flags,
106 int mode,
107 int dflags,
108 const HASHINFO *info) /* Special directives for create */
110 HTAB *hashp;
112 #ifdef __USE_INTERNAL_STAT64
113 struct stat64 statbuf;
114 #else
115 struct stat statbuf;
116 #endif
117 DB *dbp;
118 int bpages, hdrsize, new_table, nsegs, save_errno;
120 if ((flags & O_ACCMODE) == O_WRONLY) {
121 errno = EINVAL;
122 return (NULL);
125 if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
126 return (NULL);
127 hashp->fp = -1;
130 * Even if user wants write only, we need to be able to read
131 * the actual file, so we need to open it read/write. But, the
132 * field in the hashp structure needs to be accurate so that
133 * we can check accesses.
135 hashp->flags = flags;
137 new_table = 0;
138 if (!file || (flags & O_TRUNC) ||
139 #ifdef __USE_INTERNAL_STAT64
140 (_stat64_r(_REENT, file, &statbuf) && (errno == ENOENT))) {
141 #else
142 (_stat_r(_REENT, file, &statbuf) && (errno == ENOENT))) {
143 #endif
144 if (errno == ENOENT)
145 errno = 0; /* Just in case someone looks at errno */
146 new_table = 1;
148 if (file) {
149 if ((hashp->fp = open(file, flags, mode)) == -1)
150 RETURN_ERROR(errno, error0);
152 /* if the .db file is empty, and we had permission to create
153 a new .db file, then reinitialize the database */
154 if ((flags & O_CREAT) &&
155 #ifdef __USE_INTERNAL_STAT64
156 _fstat64_r(_REENT, hashp->fp, &statbuf) == 0 && statbuf.st_size == 0)
157 #else
158 _fstat_r(_REENT, hashp->fp, &statbuf) == 0 && statbuf.st_size == 0)
159 #endif
160 new_table = 1;
162 #ifdef HAVE_FCNTL
163 (void)fcntl(hashp->fp, F_SETFD, 1);
164 #endif
166 if (new_table) {
167 if (!(hashp = init_hash(hashp, file, (HASHINFO *)info)))
168 RETURN_ERROR(errno, error1);
169 } else {
170 /* Table already exists */
171 if (info && info->hash)
172 hashp->hash = info->hash;
173 else
174 hashp->hash = __default_hash;
176 hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
177 #if (BYTE_ORDER == LITTLE_ENDIAN)
178 swap_header(hashp);
179 #endif
180 if (hdrsize == -1)
181 RETURN_ERROR(errno, error1);
182 if (hdrsize != sizeof(HASHHDR))
183 RETURN_ERROR(EFTYPE, error1);
184 /* Verify file type, versions and hash function */
185 if (hashp->MAGIC != HASHMAGIC)
186 RETURN_ERROR(EFTYPE, error1);
187 #define OLDHASHVERSION 1
188 if (hashp->HASH_VERSION != HASHVERSION &&
189 hashp->HASH_VERSION != OLDHASHVERSION)
190 RETURN_ERROR(EFTYPE, error1);
191 if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
192 RETURN_ERROR(EFTYPE, error1);
193 /* Check bucket size isn't too big for target int. */
194 if (hashp->BSIZE > INT_MAX)
195 RETURN_ERROR(EFTYPE, error1);
197 * Figure out how many segments we need. Max_Bucket is the
198 * maximum bucket number, so the number of buckets is
199 * max_bucket + 1.
201 nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
202 hashp->SGSIZE;
203 hashp->nsegs = 0;
204 if (alloc_segs(hashp, nsegs))
206 * If alloc_segs fails, table will have been destroyed
207 * and errno will have been set.
209 return (NULL);
210 /* Read in bitmaps */
211 bpages = (hashp->SPARES[hashp->OVFL_POINT] +
212 (hashp->BSIZE << BYTE_SHIFT) - 1) >>
213 (hashp->BSHIFT + BYTE_SHIFT);
215 hashp->nmaps = bpages;
216 (void)memset(&hashp->mapp[0], 0, bpages * sizeof(__uint32_t *));
219 /* Initialize Buffer Manager */
220 if (info && info->cachesize)
221 __buf_init(hashp, info->cachesize);
222 else
223 __buf_init(hashp, DEF_BUFSIZE);
225 hashp->new_file = new_table;
226 hashp->save_file = file && (hashp->flags & O_RDWR);
227 hashp->cbucket = -1;
228 if (!(dbp = (DB *)malloc(sizeof(DB)))) {
229 save_errno = errno;
230 hdestroy(hashp);
231 errno = save_errno;
232 return (NULL);
234 dbp->internal = hashp;
235 dbp->close = hash_close;
236 dbp->del = hash_delete;
237 dbp->fd = hash_fd;
238 dbp->get = hash_get;
239 dbp->put = hash_put;
240 dbp->seq = hash_seq;
241 dbp->sync = hash_sync;
242 dbp->type = DB_HASH;
244 #ifdef DEBUG
245 (void)fprintf(stderr,
246 "%s\n%s%x\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
247 "init_htab:",
248 "TABLE POINTER ", hashp,
249 "BUCKET SIZE ", hashp->BSIZE,
250 "BUCKET SHIFT ", hashp->BSHIFT,
251 "DIRECTORY SIZE ", hashp->DSIZE,
252 "SEGMENT SIZE ", hashp->SGSIZE,
253 "SEGMENT SHIFT ", hashp->SSHIFT,
254 "FILL FACTOR ", hashp->FFACTOR,
255 "MAX BUCKET ", hashp->MAX_BUCKET,
256 "OVFL POINT ", hashp->OVFL_POINT,
257 "LAST FREED ", hashp->LAST_FREED,
258 "HIGH MASK ", hashp->HIGH_MASK,
259 "LOW MASK ", hashp->LOW_MASK,
260 "NSEGS ", hashp->nsegs,
261 "NKEYS ", hashp->NKEYS);
262 #endif
263 #ifdef HASH_STATISTICS
264 hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
265 #endif
266 return (dbp);
268 error1:
269 if (hashp != NULL)
270 (void)close(hashp->fp);
272 error0:
273 free(hashp);
274 errno = save_errno;
275 return (NULL);
278 static int
279 hash_close(
280 DB *dbp
283 HTAB *hashp;
284 int retval;
286 if (!dbp)
287 return (ERROR);
289 hashp = (HTAB *)dbp->internal;
290 retval = hdestroy(hashp);
291 free(dbp);
292 return (retval);
295 static int
296 hash_fd(
297 const DB *dbp
300 HTAB *hashp;
302 if (!dbp)
303 return (ERROR);
305 hashp = (HTAB *)dbp->internal;
306 if (hashp->fp == -1) {
307 errno = ENOENT;
308 return (-1);
310 return (hashp->fp);
313 /************************** LOCAL CREATION ROUTINES **********************/
314 static HTAB *
315 init_hash(
316 HTAB *hashp,
317 const char *file,
318 const HASHINFO *info
321 #ifdef __USE_INTERNAL_STAT64
322 struct stat64 statbuf;
323 #else
324 struct stat statbuf;
325 #endif
326 int nelem;
328 nelem = 1;
329 hashp->NKEYS = 0;
330 hashp->LORDER = DB_BYTE_ORDER;
331 hashp->BSIZE = DEF_BUCKET_SIZE;
332 hashp->BSHIFT = DEF_BUCKET_SHIFT;
333 hashp->SGSIZE = DEF_SEGSIZE;
334 hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
335 hashp->DSIZE = DEF_DIRSIZE;
336 hashp->FFACTOR = DEF_FFACTOR;
337 hashp->hash = __default_hash;
338 memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
339 memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
341 /* Fix bucket size to be optimal for file system */
342 if (file != NULL) {
343 #ifdef __USE_INTERNAL_STAT64
344 if (_stat64_r(_REENT, file, &statbuf))
345 #else
346 if (_stat_r(_REENT, file, &statbuf))
347 #endif
348 return (NULL);
349 hashp->BSIZE = MIN(statbuf.st_blksize, MAX_BSIZE);
350 hashp->BSHIFT = __log2(hashp->BSIZE);
353 if (info) {
354 if (info->bsize) {
355 /* Round pagesize up to power of 2 */
356 hashp->BSHIFT = __log2(info->bsize);
357 hashp->BSIZE = 1 << hashp->BSHIFT;
358 if (hashp->BSIZE > MAX_BSIZE) {
359 errno = EINVAL;
360 return (NULL);
363 if (info->ffactor)
364 hashp->FFACTOR = info->ffactor;
365 if (info->hash)
366 hashp->hash = info->hash;
367 if (info->nelem)
368 nelem = info->nelem;
369 if (info->lorder) {
370 if (info->lorder != DB_BIG_ENDIAN &&
371 info->lorder != DB_LITTLE_ENDIAN) {
372 errno = EINVAL;
373 return (NULL);
375 hashp->LORDER = info->lorder;
378 /* init_htab should destroy the table and set errno if it fails */
379 if (init_htab(hashp, nelem))
380 return (NULL);
381 else
382 return (hashp);
385 * This calls alloc_segs which may run out of memory. Alloc_segs will destroy
386 * the table and set errno, so we just pass the error information along.
388 * Returns 0 on No Error
390 static int
391 init_htab(
392 HTAB *hashp,
393 int nelem
396 int nbuckets, nsegs;
397 int l2;
400 * Divide number of elements by the fill factor and determine a
401 * desired number of buckets. Allocate space for the next greater
402 * power of two number of buckets.
404 nelem = (nelem - 1) / hashp->FFACTOR + 1;
406 l2 = __log2(MAX(nelem, 2));
407 nbuckets = 1 << l2;
409 hashp->SPARES[l2] = l2 + 1;
410 hashp->SPARES[l2 + 1] = l2 + 1;
411 hashp->OVFL_POINT = l2;
412 hashp->LAST_FREED = 2;
414 /* First bitmap page is at: splitpoint l2 page offset 1 */
415 if (__ibitmap(hashp, OADDR_OF(l2, 1), l2 + 1, 0))
416 return (-1);
418 hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
419 hashp->HIGH_MASK = (nbuckets << 1) - 1;
420 hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
421 hashp->BSHIFT) + 1;
423 nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
424 nsegs = 1 << __log2(nsegs);
426 if (nsegs > hashp->DSIZE)
427 hashp->DSIZE = nsegs;
428 return (alloc_segs(hashp, nsegs));
431 /********************** DESTROY/CLOSE ROUTINES ************************/
434 * Flushes any changes to the file if necessary and destroys the hashp
435 * structure, freeing all allocated space.
437 static int
438 hdestroy(
439 HTAB *hashp
442 int i, save_errno;
444 save_errno = 0;
446 #ifdef HASH_STATISTICS
447 (void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n",
448 hash_accesses, hash_collisions);
449 (void)fprintf(stderr, "hdestroy: expansions %ld\n",
450 hash_expansions);
451 (void)fprintf(stderr, "hdestroy: overflows %ld\n",
452 hash_overflows);
453 (void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n",
454 hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
456 for (i = 0; i < NCACHED; i++)
457 (void)fprintf(stderr,
458 "spares[%d] = %d\n", i, hashp->SPARES[i]);
459 #endif
461 * Call on buffer manager to free buffers, and if required,
462 * write them to disk.
464 if (__buf_free(hashp, 1, hashp->save_file))
465 save_errno = errno;
466 if (hashp->dir) {
467 free(*hashp->dir); /* Free initial segments */
468 /* Free extra segments */
469 while (hashp->exsegs--)
470 free(hashp->dir[--hashp->nsegs]);
471 free(hashp->dir);
473 if (flush_meta(hashp) && !save_errno)
474 save_errno = errno;
475 /* Free Bigmaps */
476 for (i = 0; i < hashp->nmaps; i++)
477 if (hashp->mapp[i])
478 free(hashp->mapp[i]);
480 if (hashp->fp != -1)
481 (void)close(hashp->fp);
483 free(hashp);
485 if (save_errno) {
486 errno = save_errno;
487 return (ERROR);
489 return (SUCCESS);
492 * Write modified pages to disk
494 * Returns:
495 * 0 == OK
496 * -1 ERROR
498 static int
499 hash_sync(
500 const DB *dbp,
501 u_int flags
504 HTAB *hashp;
506 if (flags != 0) {
507 errno = EINVAL;
508 return (ERROR);
511 if (!dbp)
512 return (ERROR);
514 hashp = (HTAB *)dbp->internal;
515 if (!hashp->save_file)
516 return (0);
517 if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
518 return (ERROR);
519 hashp->new_file = 0;
520 return (0);
524 * Returns:
525 * 0 == OK
526 * -1 indicates that errno should be set
528 static int
529 flush_meta(
530 HTAB *hashp
533 HASHHDR *whdrp;
534 #if (BYTE_ORDER == LITTLE_ENDIAN)
535 HASHHDR whdr;
536 #endif
537 int fp, i, wsize;
539 if (!hashp->save_file)
540 return (0);
541 hashp->MAGIC = HASHMAGIC;
542 hashp->HASH_VERSION = HASHVERSION;
543 hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
545 fp = hashp->fp;
546 whdrp = &hashp->hdr;
547 #if (BYTE_ORDER == LITTLE_ENDIAN)
548 whdrp = &whdr;
549 swap_header_copy(&hashp->hdr, whdrp);
550 #endif
551 if ((lseek(fp, (off_t)0, SEEK_SET) == -1) ||
552 ((wsize = write(fp, whdrp, sizeof(HASHHDR))) == -1))
553 return (-1);
554 else
555 if (wsize != sizeof(HASHHDR)) {
556 errno = EFTYPE;
557 hashp->error = errno;
558 return (-1);
560 for (i = 0; i < NCACHED; i++)
561 if (hashp->mapp[i])
562 if (__put_page(hashp, (char *)hashp->mapp[i],
563 hashp->BITMAPS[i], 0, 1))
564 return (-1);
565 return (0);
568 /*******************************SEARCH ROUTINES *****************************/
570 * All the access routines return
572 * Returns:
573 * 0 on SUCCESS
574 * 1 to indicate an external ERROR (i.e. key not found, etc)
575 * -1 to indicate an internal ERROR (i.e. out of memory, etc)
577 static int
578 hash_get(
579 const DB *dbp,
580 const DBT *key,
581 DBT *data,
582 u_int flag
585 HTAB *hashp;
587 hashp = (HTAB *)dbp->internal;
588 if (flag) {
589 hashp->error = errno = EINVAL;
590 return (ERROR);
592 return (hash_access(hashp, HASH_GET, (DBT *)key, data));
595 static int
596 hash_put(
597 const DB *dbp,
598 DBT *key,
599 const DBT *data,
600 u_int flag
603 HTAB *hashp;
605 hashp = (HTAB *)dbp->internal;
606 if (flag && flag != R_NOOVERWRITE) {
607 hashp->error = EINVAL;
608 errno = EINVAL;
609 return (ERROR);
611 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
612 hashp->error = errno = EPERM;
613 return (ERROR);
615 return (hash_access(hashp, flag == R_NOOVERWRITE ?
616 HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
619 static int
620 hash_delete(
621 const DB *dbp,
622 const DBT *key,
623 u_int flag /* Ignored */
626 HTAB *hashp;
628 hashp = (HTAB *)dbp->internal;
629 if (flag && flag != R_CURSOR) {
630 hashp->error = errno = EINVAL;
631 return (ERROR);
633 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
634 hashp->error = errno = EPERM;
635 return (ERROR);
637 return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
641 * Assume that hashp has been set in wrapper routine.
643 static int
644 hash_access(
645 HTAB *hashp,
646 ACTION action,
647 DBT *key,
648 DBT *val
651 BUFHEAD *rbufp;
652 BUFHEAD *bufp, *save_bufp;
653 __uint16_t *bp;
654 int n, ndx, off, size;
655 char *kp;
656 __uint16_t pageno;
658 #ifdef HASH_STATISTICS
659 hash_accesses++;
660 #endif
662 off = hashp->BSIZE;
663 size = key->size;
664 kp = (char *)key->data;
665 rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
666 if (!rbufp)
667 return (ERROR);
668 save_bufp = rbufp;
670 /* Pin the bucket chain */
671 rbufp->flags |= BUF_PIN;
672 for (bp = (__uint16_t *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
673 if (bp[1] >= REAL_KEY) {
674 /* Real key/data pair */
675 if (size == off - *bp &&
676 memcmp(kp, rbufp->page + *bp, size) == 0)
677 goto found;
678 off = bp[1];
679 #ifdef HASH_STATISTICS
680 hash_collisions++;
681 #endif
682 bp += 2;
683 ndx += 2;
684 } else if (bp[1] == OVFLPAGE) {
685 rbufp = __get_buf(hashp, *bp, rbufp, 0);
686 if (!rbufp) {
687 save_bufp->flags &= ~BUF_PIN;
688 return (ERROR);
690 /* FOR LOOP INIT */
691 bp = (__uint16_t *)rbufp->page;
692 n = *bp++;
693 ndx = 1;
694 off = hashp->BSIZE;
695 } else if (bp[1] < REAL_KEY) {
696 if ((ndx =
697 __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
698 goto found;
699 if (ndx == -2) {
700 bufp = rbufp;
701 if (!(pageno =
702 __find_last_page(hashp, &bufp))) {
703 ndx = 0;
704 rbufp = bufp;
705 break; /* FOR */
707 rbufp = __get_buf(hashp, pageno, bufp, 0);
708 if (!rbufp) {
709 save_bufp->flags &= ~BUF_PIN;
710 return (ERROR);
712 /* FOR LOOP INIT */
713 bp = (__uint16_t *)rbufp->page;
714 n = *bp++;
715 ndx = 1;
716 off = hashp->BSIZE;
717 } else {
718 save_bufp->flags &= ~BUF_PIN;
719 return (ERROR);
723 /* Not found */
724 switch (action) {
725 case HASH_PUT:
726 case HASH_PUTNEW:
727 if (__addel(hashp, rbufp, key, val)) {
728 save_bufp->flags &= ~BUF_PIN;
729 return (ERROR);
730 } else {
731 save_bufp->flags &= ~BUF_PIN;
732 return (SUCCESS);
734 case HASH_GET:
735 case HASH_DELETE:
736 default:
737 save_bufp->flags &= ~BUF_PIN;
738 return (ABNORMAL);
741 found:
742 switch (action) {
743 case HASH_PUTNEW:
744 save_bufp->flags &= ~BUF_PIN;
745 return (ABNORMAL);
746 case HASH_GET:
747 bp = (__uint16_t *)rbufp->page;
748 if (bp[ndx + 1] < REAL_KEY) {
749 if (__big_return(hashp, rbufp, ndx, val, 0))
750 return (ERROR);
751 } else {
752 val->data = (u_char *)rbufp->page + (int)bp[ndx + 1];
753 val->size = bp[ndx] - bp[ndx + 1];
755 break;
756 case HASH_PUT:
757 if ((__delpair(hashp, rbufp, ndx)) ||
758 (__addel(hashp, rbufp, key, val))) {
759 save_bufp->flags &= ~BUF_PIN;
760 return (ERROR);
762 break;
763 case HASH_DELETE:
764 if (__delpair(hashp, rbufp, ndx))
765 return (ERROR);
766 break;
767 default:
768 abort();
770 save_bufp->flags &= ~BUF_PIN;
771 return (SUCCESS);
774 static int
775 hash_seq(
776 const DB *dbp,
777 DBT *key,
778 DBT *data,
779 u_int flag
782 __uint32_t bucket;
783 BUFHEAD *bufp;
784 HTAB *hashp;
785 __uint16_t *bp, ndx;
787 hashp = (HTAB *)dbp->internal;
788 if (flag && flag != R_FIRST && flag != R_NEXT) {
789 hashp->error = errno = EINVAL;
790 return (ERROR);
792 #ifdef HASH_STATISTICS
793 hash_accesses++;
794 #endif
795 if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
796 hashp->cbucket = 0;
797 hashp->cndx = 1;
798 hashp->cpage = NULL;
801 for (bp = NULL; !bp || !bp[0]; ) {
802 if (!(bufp = hashp->cpage)) {
803 for (bucket = hashp->cbucket;
804 bucket <= hashp->MAX_BUCKET;
805 bucket++, hashp->cndx = 1) {
806 bufp = __get_buf(hashp, bucket, NULL, 0);
807 if (!bufp)
808 return (ERROR);
809 hashp->cpage = bufp;
810 bp = (__uint16_t *)bufp->page;
811 if (bp[0])
812 break;
814 hashp->cbucket = bucket;
815 if (hashp->cbucket > hashp->MAX_BUCKET) {
816 hashp->cbucket = -1;
817 return (ABNORMAL);
819 } else
820 bp = (__uint16_t *)hashp->cpage->page;
822 #ifdef DEBUG
823 assert(bp);
824 assert(bufp);
825 #endif
826 while (bp[hashp->cndx + 1] == OVFLPAGE) {
827 bufp = hashp->cpage =
828 __get_buf(hashp, bp[hashp->cndx], bufp, 0);
829 if (!bufp)
830 return (ERROR);
831 bp = (__uint16_t *)(bufp->page);
832 hashp->cndx = 1;
834 if (!bp[0]) {
835 hashp->cpage = NULL;
836 ++hashp->cbucket;
839 ndx = hashp->cndx;
840 if (bp[ndx + 1] < REAL_KEY) {
841 if (__big_keydata(hashp, bufp, key, data, 1))
842 return (ERROR);
843 } else {
844 key->data = (u_char *)hashp->cpage->page + bp[ndx];
845 key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
846 data->data = (u_char *)hashp->cpage->page + bp[ndx + 1];
847 data->size = bp[ndx] - bp[ndx + 1];
848 ndx += 2;
849 if (ndx > bp[0]) {
850 hashp->cpage = NULL;
851 hashp->cbucket++;
852 hashp->cndx = 1;
853 } else
854 hashp->cndx = ndx;
856 return (SUCCESS);
859 /********************************* UTILITIES ************************/
862 * Returns:
863 * 0 ==> OK
864 * -1 ==> Error
866 extern int
867 __expand_table(
868 HTAB *hashp
871 __uint32_t old_bucket, new_bucket;
872 int dirsize, new_segnum, spare_ndx;
874 #ifdef HASH_STATISTICS
875 hash_expansions++;
876 #endif
877 new_bucket = ++hashp->MAX_BUCKET;
878 old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
880 new_segnum = new_bucket >> hashp->SSHIFT;
882 /* Check if we need a new segment */
883 if (new_segnum >= hashp->nsegs) {
884 /* Check if we need to expand directory */
885 if (new_segnum >= hashp->DSIZE) {
886 /* Reallocate directory */
887 dirsize = hashp->DSIZE * sizeof(SEGMENT *);
888 if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
889 return (-1);
890 hashp->DSIZE = dirsize << 1;
892 if ((hashp->dir[new_segnum] =
893 (SEGMENT)calloc(hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
894 return (-1);
895 hashp->exsegs++;
896 hashp->nsegs++;
899 * If the split point is increasing (MAX_BUCKET's log base 2
900 * * increases), we need to copy the current contents of the spare
901 * split bucket to the next bucket.
903 spare_ndx = __log2(hashp->MAX_BUCKET + 1);
904 if (spare_ndx > hashp->OVFL_POINT) {
905 hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
906 hashp->OVFL_POINT = spare_ndx;
909 if (new_bucket > hashp->HIGH_MASK) {
910 /* Starting a new doubling */
911 hashp->LOW_MASK = hashp->HIGH_MASK;
912 hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
914 /* Relocate records to the new bucket */
915 return (__split_page(hashp, old_bucket, new_bucket));
919 * If realloc guarantees that the pointer is not destroyed if the realloc
920 * fails, then this routine can go away.
922 static void *
923 hash_realloc(
924 SEGMENT **p_ptr,
925 int oldsize,
926 int newsize
929 void *p;
931 if ( (p = malloc(newsize)) ) {
932 memmove(p, *p_ptr, oldsize);
933 memset((char *)p + oldsize, 0, newsize - oldsize);
934 free(*p_ptr);
935 *p_ptr = p;
937 return (p);
940 extern __uint32_t
941 __call_hash(
942 HTAB *hashp,
943 char *k,
944 int len
947 int n, bucket;
949 n = hashp->hash(k, len);
950 bucket = n & hashp->HIGH_MASK;
951 if (bucket > hashp->MAX_BUCKET)
952 bucket = bucket & hashp->LOW_MASK;
953 return (bucket);
957 * Allocate segment table. On error, destroy the table and set errno.
959 * Returns 0 on success
961 static int
962 alloc_segs(
963 HTAB *hashp,
964 int nsegs
967 int i;
968 SEGMENT store;
970 int save_errno;
972 if ((hashp->dir =
973 (SEGMENT *)calloc(hashp->DSIZE, sizeof(SEGMENT *))) == NULL) {
974 save_errno = errno;
975 (void)hdestroy(hashp);
976 errno = save_errno;
977 return (-1);
979 /* Allocate segments */
980 if ((store =
981 (SEGMENT)calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT))) == NULL) {
982 save_errno = errno;
983 (void)hdestroy(hashp);
984 errno = save_errno;
985 return (-1);
987 for (i = 0; i < nsegs; i++, hashp->nsegs++)
988 hashp->dir[i] = &store[i << hashp->SSHIFT];
989 return (0);
992 #if (BYTE_ORDER == LITTLE_ENDIAN)
994 * Hashp->hdr needs to be byteswapped.
996 static void
997 swap_header_copy(
998 HASHHDR *srcp,
999 HASHHDR *destp
1002 int i;
1004 P_32_COPY(srcp->magic, destp->magic);
1005 P_32_COPY(srcp->version, destp->version);
1006 P_32_COPY(srcp->lorder, destp->lorder);
1007 P_32_COPY(srcp->bsize, destp->bsize);
1008 P_32_COPY(srcp->bshift, destp->bshift);
1009 P_32_COPY(srcp->dsize, destp->dsize);
1010 P_32_COPY(srcp->ssize, destp->ssize);
1011 P_32_COPY(srcp->sshift, destp->sshift);
1012 P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
1013 P_32_COPY(srcp->last_freed, destp->last_freed);
1014 P_32_COPY(srcp->max_bucket, destp->max_bucket);
1015 P_32_COPY(srcp->high_mask, destp->high_mask);
1016 P_32_COPY(srcp->low_mask, destp->low_mask);
1017 P_32_COPY(srcp->ffactor, destp->ffactor);
1018 P_32_COPY(srcp->nkeys, destp->nkeys);
1019 P_32_COPY(srcp->hdrpages, destp->hdrpages);
1020 P_32_COPY(srcp->h_charkey, destp->h_charkey);
1021 for (i = 0; i < NCACHED; i++) {
1022 P_32_COPY(srcp->spares[i], destp->spares[i]);
1023 P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
1027 static void
1028 swap_header(
1029 HTAB *hashp
1032 HASHHDR *hdrp;
1033 int i;
1035 hdrp = &hashp->hdr;
1037 M_32_SWAP(hdrp->magic);
1038 M_32_SWAP(hdrp->version);
1039 M_32_SWAP(hdrp->lorder);
1040 M_32_SWAP(hdrp->bsize);
1041 M_32_SWAP(hdrp->bshift);
1042 M_32_SWAP(hdrp->dsize);
1043 M_32_SWAP(hdrp->ssize);
1044 M_32_SWAP(hdrp->sshift);
1045 M_32_SWAP(hdrp->ovfl_point);
1046 M_32_SWAP(hdrp->last_freed);
1047 M_32_SWAP(hdrp->max_bucket);
1048 M_32_SWAP(hdrp->high_mask);
1049 M_32_SWAP(hdrp->low_mask);
1050 M_32_SWAP(hdrp->ffactor);
1051 M_32_SWAP(hdrp->nkeys);
1052 M_32_SWAP(hdrp->hdrpages);
1053 M_32_SWAP(hdrp->h_charkey);
1054 for (i = 0; i < NCACHED; i++) {
1055 M_32_SWAP(hdrp->spares[i]);
1056 M_16_SWAP(hdrp->bitmaps[i]);
1059 #endif