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