]> git.saurik.com Git - apple/libc.git/blob - db/hash/hash.c
b22f1c6fd79202db34b307a01fcb99870aa147ac
[apple/libc.git] / db / hash / hash.c
1 /*
2 * Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 /*-
24 * Copyright (c) 1990, 1993, 1994
25 * The Regents of the University of California. All rights reserved.
26 *
27 * This code is derived from software contributed to Berkeley by
28 * Margo Seltzer.
29 *
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38 * 3. All advertising materials mentioning features or use of this software
39 * must display the following acknowledgement:
40 * This product includes software developed by the University of
41 * California, Berkeley and its contributors.
42 * 4. Neither the name of the University nor the names of its contributors
43 * may be used to endorse or promote products derived from this software
44 * without specific prior written permission.
45 *
46 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56 * SUCH DAMAGE.
57 */
58
59 #if defined(LIBC_SCCS) && !defined(lint)
60 static char sccsid[] = "@(#)hash.c 8.9 (Berkeley) 6/16/94";
61 #endif /* LIBC_SCCS and not lint */
62 #include <sys/cdefs.h>
63
64 #include <sys/param.h>
65 #include <sys/stat.h>
66
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 #ifdef DEBUG
74 #include <assert.h>
75 #endif
76
77 #include <db.h>
78 #include "hash.h"
79 #include "page.h"
80 #include "extern.h"
81
82 static int alloc_segs(HTAB *, int);
83 static int flush_meta(HTAB *);
84 static int hash_access(HTAB *, ACTION, DBT *, DBT *);
85 static int hash_close(DB *);
86 static int hash_delete(const DB *, const DBT *, u_int32_t);
87 static int hash_fd(const DB *);
88 static int hash_get(const DB *, const DBT *, DBT *, u_int32_t);
89 static int hash_put(const DB *, DBT *, const DBT *, u_int32_t);
90 static void *hash_realloc(SEGMENT **, int, int);
91 static int hash_seq(const DB *, DBT *, DBT *, u_int32_t);
92 static int hash_sync(const DB *, u_int32_t);
93 static int hdestroy(HTAB *);
94 static HTAB *init_hash(HTAB *, const char *, HASHINFO *);
95 static int init_htab(HTAB *, int);
96 #if BYTE_ORDER == LITTLE_ENDIAN
97 static void swap_header(HTAB *);
98 static void swap_header_copy(HASHHDR *, HASHHDR *);
99 #endif
100
101 /* Fast arithmetic, relying on powers of 2, */
102 #define MOD(x, y) ((x) & ((y) - 1))
103
104 #define RETURN_ERROR(ERR, LOC) { save_errno = ERR; goto LOC; }
105
106 /* Return values */
107 #define SUCCESS (0)
108 #define ERROR (-1)
109 #define ABNORMAL (1)
110
111 #ifdef HASH_STATISTICS
112 int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
113 #endif
114
115 /************************** INTERFACE ROUTINES ***************************/
116 /* OPEN/CLOSE */
117
118 extern DB *
119 __hash_open(file, flags, mode, info, dflags)
120 const char *file;
121 int flags, mode, dflags;
122 const HASHINFO *info; /* Special directives for create */
123 {
124 HTAB *hashp;
125 struct stat statbuf;
126 DB *dbp;
127 int bpages, hdrsize, new_table, nsegs, save_errno;
128
129 if ((flags & O_ACCMODE) == O_WRONLY) {
130 errno = EINVAL;
131 return (NULL);
132 }
133
134 if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
135 return (NULL);
136 hashp->fp = -1;
137
138 /*
139 * Even if user wants write only, we need to be able to read
140 * the actual file, so we need to open it read/write. But, the
141 * field in the hashp structure needs to be accurate so that
142 * we can check accesses.
143 */
144 hashp->flags = flags;
145
146 new_table = 0;
147 if (!file || (flags & O_TRUNC) ||
148 (stat(file, &statbuf) && (errno == ENOENT))) {
149 if (errno == ENOENT)
150 errno = 0; /* Just in case someone looks at errno */
151 new_table = 1;
152 }
153 if (file) {
154 if ((hashp->fp = open(file, flags, mode)) == -1)
155 RETURN_ERROR(errno, error0);
156
157 /* if the .db file is empty, and we had permission to create
158 a new .db file, then reinitialize the database */
159 if ((flags & O_CREAT) &&
160 fstat(hashp->fp, &statbuf) == 0 && statbuf.st_size == 0)
161 new_table = 1;
162
163 (void)fcntl(hashp->fp, F_SETFD, 1);
164 }
165 if (new_table) {
166 if (!(hashp = init_hash(hashp, file, (HASHINFO *)info)))
167 RETURN_ERROR(errno, error1);
168 } else {
169 /* Table already exists */
170 if (info && info->hash)
171 hashp->hash = info->hash;
172 else
173 hashp->hash = __default_hash;
174
175 hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
176 #if BYTE_ORDER == LITTLE_ENDIAN
177 swap_header(hashp);
178 #endif
179 if (hdrsize == -1)
180 RETURN_ERROR(errno, error1);
181 if (hdrsize != sizeof(HASHHDR))
182 RETURN_ERROR(EFTYPE, error1);
183 /* Verify file type, versions and hash function */
184 if (hashp->MAGIC != HASHMAGIC)
185 RETURN_ERROR(EFTYPE, error1);
186 #define OLDHASHVERSION 1
187 if (hashp->VERSION != HASHVERSION &&
188 hashp->VERSION != OLDHASHVERSION)
189 RETURN_ERROR(EFTYPE, error1);
190 if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
191 RETURN_ERROR(EFTYPE, error1);
192 /*
193 * Figure out how many segments we need. Max_Bucket is the
194 * maximum bucket number, so the number of buckets is
195 * max_bucket + 1.
196 */
197 nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
198 hashp->SGSIZE;
199 hashp->nsegs = 0;
200 if (alloc_segs(hashp, nsegs))
201 /*
202 * If alloc_segs fails, table will have been destroyed
203 * and errno will have been set.
204 */
205 return (NULL);
206 /* Read in bitmaps */
207 bpages = (hashp->SPARES[hashp->OVFL_POINT] +
208 (hashp->BSIZE << BYTE_SHIFT) - 1) >>
209 (hashp->BSHIFT + BYTE_SHIFT);
210
211 hashp->nmaps = bpages;
212 (void)memset(&hashp->mapp[0], 0, bpages * sizeof(u_int32_t *));
213 }
214
215 /* Initialize Buffer Manager */
216 if (info && info->cachesize)
217 __buf_init(hashp, info->cachesize);
218 else
219 __buf_init(hashp, DEF_BUFSIZE);
220
221 hashp->new_file = new_table;
222 hashp->save_file = file && (hashp->flags & O_RDWR);
223 hashp->cbucket = -1;
224 if (!(dbp = (DB *)malloc(sizeof(DB)))) {
225 save_errno = errno;
226 hdestroy(hashp);
227 errno = save_errno;
228 return (NULL);
229 }
230 dbp->internal = hashp;
231 dbp->close = hash_close;
232 dbp->del = hash_delete;
233 dbp->fd = hash_fd;
234 dbp->get = hash_get;
235 dbp->put = hash_put;
236 dbp->seq = hash_seq;
237 dbp->sync = hash_sync;
238 dbp->type = DB_HASH;
239
240 #ifdef DEBUG
241 (void)fprintf(stderr,
242 "%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",
243 "init_htab:",
244 "TABLE POINTER ", hashp,
245 "BUCKET SIZE ", hashp->BSIZE,
246 "BUCKET SHIFT ", hashp->BSHIFT,
247 "DIRECTORY SIZE ", hashp->DSIZE,
248 "SEGMENT SIZE ", hashp->SGSIZE,
249 "SEGMENT SHIFT ", hashp->SSHIFT,
250 "FILL FACTOR ", hashp->FFACTOR,
251 "MAX BUCKET ", hashp->MAX_BUCKET,
252 "OVFL POINT ", hashp->OVFL_POINT,
253 "LAST FREED ", hashp->LAST_FREED,
254 "HIGH MASK ", hashp->HIGH_MASK,
255 "LOW MASK ", hashp->LOW_MASK,
256 "NSEGS ", hashp->nsegs,
257 "NKEYS ", hashp->NKEYS);
258 #endif
259 #ifdef HASH_STATISTICS
260 hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
261 #endif
262 return (dbp);
263
264 error1:
265 if (hashp != NULL)
266 (void)close(hashp->fp);
267
268 error0:
269 free(hashp);
270 errno = save_errno;
271 return (NULL);
272 }
273
274 static int
275 hash_close(dbp)
276 DB *dbp;
277 {
278 HTAB *hashp;
279 int retval;
280
281 if (!dbp)
282 return (ERROR);
283
284 hashp = (HTAB *)dbp->internal;
285 retval = hdestroy(hashp);
286 free(dbp);
287 return (retval);
288 }
289
290 static int
291 hash_fd(dbp)
292 const DB *dbp;
293 {
294 HTAB *hashp;
295
296 if (!dbp)
297 return (ERROR);
298
299 hashp = (HTAB *)dbp->internal;
300 if (hashp->fp == -1) {
301 errno = ENOENT;
302 return (-1);
303 }
304 return (hashp->fp);
305 }
306
307 /************************** LOCAL CREATION ROUTINES **********************/
308 static HTAB *
309 init_hash(hashp, file, info)
310 HTAB *hashp;
311 const char *file;
312 HASHINFO *info;
313 {
314 struct stat statbuf;
315 int nelem;
316
317 nelem = 1;
318 hashp->NKEYS = 0;
319 hashp->LORDER = BYTE_ORDER;
320 hashp->BSIZE = DEF_BUCKET_SIZE;
321 hashp->BSHIFT = DEF_BUCKET_SHIFT;
322 hashp->SGSIZE = DEF_SEGSIZE;
323 hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
324 hashp->DSIZE = DEF_DIRSIZE;
325 hashp->FFACTOR = DEF_FFACTOR;
326 hashp->hash = __default_hash;
327 memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
328 memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
329
330 /* Fix bucket size to be optimal for file system */
331 if (file != NULL) {
332 if (stat(file, &statbuf))
333 return (NULL);
334 hashp->BSIZE = statbuf.st_blksize;
335 hashp->BSHIFT = __log2(hashp->BSIZE);
336 }
337
338 if (info) {
339 if (info->bsize) {
340 /* Round pagesize up to power of 2 */
341 hashp->BSHIFT = __log2(info->bsize);
342 hashp->BSIZE = 1 << hashp->BSHIFT;
343 if (hashp->BSIZE > MAX_BSIZE) {
344 errno = EINVAL;
345 return (NULL);
346 }
347 }
348 if (info->ffactor)
349 hashp->FFACTOR = info->ffactor;
350 if (info->hash)
351 hashp->hash = info->hash;
352 if (info->nelem)
353 nelem = info->nelem;
354 if (info->lorder) {
355 if (info->lorder != BIG_ENDIAN &&
356 info->lorder != LITTLE_ENDIAN) {
357 errno = EINVAL;
358 return (NULL);
359 }
360 hashp->LORDER = info->lorder;
361 }
362 }
363 /* init_htab should destroy the table and set errno if it fails */
364 if (init_htab(hashp, nelem))
365 return (NULL);
366 else
367 return (hashp);
368 }
369 /*
370 * This calls alloc_segs which may run out of memory. Alloc_segs will destroy
371 * the table and set errno, so we just pass the error information along.
372 *
373 * Returns 0 on No Error
374 */
375 static int
376 init_htab(hashp, nelem)
377 HTAB *hashp;
378 int nelem;
379 {
380 int nbuckets, nsegs;
381 int l2;
382
383 /*
384 * Divide number of elements by the fill factor and determine a
385 * desired number of buckets. Allocate space for the next greater
386 * power of two number of buckets.
387 */
388 nelem = (nelem - 1) / hashp->FFACTOR + 1;
389
390 l2 = __log2(MAX(nelem, 2));
391 nbuckets = 1 << l2;
392
393 hashp->SPARES[l2] = l2 + 1;
394 hashp->SPARES[l2 + 1] = l2 + 1;
395 hashp->OVFL_POINT = l2;
396 hashp->LAST_FREED = 2;
397
398 /* First bitmap page is at: splitpoint l2 page offset 1 */
399 if (__ibitmap(hashp, OADDR_OF(l2, 1), l2 + 1, 0))
400 return (-1);
401
402 hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
403 hashp->HIGH_MASK = (nbuckets << 1) - 1;
404 hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
405 hashp->BSHIFT) + 1;
406
407 nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
408 nsegs = 1 << __log2(nsegs);
409
410 if (nsegs > hashp->DSIZE)
411 hashp->DSIZE = nsegs;
412 return (alloc_segs(hashp, nsegs));
413 }
414
415 /********************** DESTROY/CLOSE ROUTINES ************************/
416
417 /*
418 * Flushes any changes to the file if necessary and destroys the hashp
419 * structure, freeing all allocated space.
420 */
421 static int
422 hdestroy(hashp)
423 HTAB *hashp;
424 {
425 int i, save_errno;
426
427 save_errno = 0;
428
429 #ifdef HASH_STATISTICS
430 (void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n",
431 hash_accesses, hash_collisions);
432 (void)fprintf(stderr, "hdestroy: expansions %ld\n",
433 hash_expansions);
434 (void)fprintf(stderr, "hdestroy: overflows %ld\n",
435 hash_overflows);
436 (void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n",
437 hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
438
439 for (i = 0; i < NCACHED; i++)
440 (void)fprintf(stderr,
441 "spares[%d] = %d\n", i, hashp->SPARES[i]);
442 #endif
443 /*
444 * Call on buffer manager to free buffers, and if required,
445 * write them to disk.
446 */
447 if (__buf_free(hashp, 1, hashp->save_file))
448 save_errno = errno;
449 if (hashp->dir) {
450 free(*hashp->dir); /* Free initial segments */
451 /* Free extra segments */
452 while (hashp->exsegs--)
453 free(hashp->dir[--hashp->nsegs]);
454 free(hashp->dir);
455 }
456 if (flush_meta(hashp) && !save_errno)
457 save_errno = errno;
458 /* Free Bigmaps */
459 for (i = 0; i < hashp->nmaps; i++)
460 if (hashp->mapp[i])
461 free(hashp->mapp[i]);
462
463 if (hashp->fp != -1)
464 (void)close(hashp->fp);
465
466 free(hashp);
467
468 if (save_errno) {
469 errno = save_errno;
470 return (ERROR);
471 }
472 return (SUCCESS);
473 }
474 /*
475 * Write modified pages to disk
476 *
477 * Returns:
478 * 0 == OK
479 * -1 ERROR
480 */
481 static int
482 hash_sync(dbp, flags)
483 const DB *dbp;
484 u_int32_t flags;
485 {
486 HTAB *hashp;
487
488 if (flags != 0) {
489 errno = EINVAL;
490 return (ERROR);
491 }
492
493 if (!dbp)
494 return (ERROR);
495
496 hashp = (HTAB *)dbp->internal;
497 if (!hashp->save_file)
498 return (0);
499 if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
500 return (ERROR);
501 hashp->new_file = 0;
502 return (0);
503 }
504
505 /*
506 * Returns:
507 * 0 == OK
508 * -1 indicates that errno should be set
509 */
510 static int
511 flush_meta(hashp)
512 HTAB *hashp;
513 {
514 HASHHDR *whdrp;
515 #if BYTE_ORDER == LITTLE_ENDIAN
516 HASHHDR whdr;
517 #endif
518 int fp, i, wsize;
519
520 if (!hashp->save_file)
521 return (0);
522 hashp->MAGIC = HASHMAGIC;
523 hashp->VERSION = HASHVERSION;
524 hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
525
526 fp = hashp->fp;
527 whdrp = &hashp->hdr;
528 #if BYTE_ORDER == LITTLE_ENDIAN
529 whdrp = &whdr;
530 swap_header_copy(&hashp->hdr, whdrp);
531 #endif
532 if ((lseek(fp, (off_t)0, SEEK_SET) == -1) ||
533 ((wsize = write(fp, whdrp, sizeof(HASHHDR))) == -1))
534 return (-1);
535 else
536 if (wsize != sizeof(HASHHDR)) {
537 errno = EFTYPE;
538 hashp->error = errno;
539 return (-1);
540 }
541 for (i = 0; i < NCACHED; i++)
542 if (hashp->mapp[i])
543 if (__put_page(hashp, (char *)hashp->mapp[i],
544 hashp->BITMAPS[i], 0, 1))
545 return (-1);
546 return (0);
547 }
548
549 /*******************************SEARCH ROUTINES *****************************/
550 /*
551 * All the access routines return
552 *
553 * Returns:
554 * 0 on SUCCESS
555 * 1 to indicate an external ERROR (i.e. key not found, etc)
556 * -1 to indicate an internal ERROR (i.e. out of memory, etc)
557 */
558 static int
559 hash_get(dbp, key, data, flag)
560 const DB *dbp;
561 const DBT *key;
562 DBT *data;
563 u_int32_t flag;
564 {
565 HTAB *hashp;
566
567 hashp = (HTAB *)dbp->internal;
568 if (flag) {
569 hashp->error = errno = EINVAL;
570 return (ERROR);
571 }
572 return (hash_access(hashp, HASH_GET, (DBT *)key, data));
573 }
574
575 static int
576 hash_put(dbp, key, data, flag)
577 const DB *dbp;
578 DBT *key;
579 const DBT *data;
580 u_int32_t flag;
581 {
582 HTAB *hashp;
583
584 hashp = (HTAB *)dbp->internal;
585 if (flag && flag != R_NOOVERWRITE) {
586 hashp->error = EINVAL;
587 errno = EINVAL;
588 return (ERROR);
589 }
590 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
591 hashp->error = errno = EPERM;
592 return (ERROR);
593 }
594 return (hash_access(hashp, flag == R_NOOVERWRITE ?
595 HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
596 }
597
598 static int
599 hash_delete(dbp, key, flag)
600 const DB *dbp;
601 const DBT *key;
602 u_int32_t flag; /* Ignored */
603 {
604 HTAB *hashp;
605
606 hashp = (HTAB *)dbp->internal;
607 if (flag && flag != R_CURSOR) {
608 hashp->error = errno = EINVAL;
609 return (ERROR);
610 }
611 if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
612 hashp->error = errno = EPERM;
613 return (ERROR);
614 }
615 return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
616 }
617
618 /*
619 * Assume that hashp has been set in wrapper routine.
620 */
621 static int
622 hash_access(hashp, action, key, val)
623 HTAB *hashp;
624 ACTION action;
625 DBT *key, *val;
626 {
627 BUFHEAD *rbufp;
628 BUFHEAD *bufp, *save_bufp;
629 u_int16_t *bp;
630 int n, ndx, off, size;
631 char *kp;
632 u_int16_t pageno;
633
634 #ifdef HASH_STATISTICS
635 hash_accesses++;
636 #endif
637
638 off = hashp->BSIZE;
639 size = key->size;
640 kp = (char *)key->data;
641 rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
642 if (!rbufp)
643 return (ERROR);
644 save_bufp = rbufp;
645
646 /* Pin the bucket chain */
647 rbufp->flags |= BUF_PIN;
648 for (bp = (u_int16_t *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
649 if (bp[1] >= REAL_KEY) {
650 /* Real key/data pair */
651 if (size == off - *bp &&
652 memcmp(kp, rbufp->page + *bp, size) == 0)
653 goto found;
654 off = bp[1];
655 #ifdef HASH_STATISTICS
656 hash_collisions++;
657 #endif
658 bp += 2;
659 ndx += 2;
660 } else if (bp[1] == OVFLPAGE) {
661 rbufp = __get_buf(hashp, *bp, rbufp, 0);
662 if (!rbufp) {
663 save_bufp->flags &= ~BUF_PIN;
664 return (ERROR);
665 }
666 /* FOR LOOP INIT */
667 bp = (u_int16_t *)rbufp->page;
668 n = *bp++;
669 ndx = 1;
670 off = hashp->BSIZE;
671 } else if (bp[1] < REAL_KEY) {
672 if ((ndx =
673 __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
674 goto found;
675 if (ndx == -2) {
676 bufp = rbufp;
677 if (!(pageno =
678 __find_last_page(hashp, &bufp))) {
679 ndx = 0;
680 rbufp = bufp;
681 break; /* FOR */
682 }
683 rbufp = __get_buf(hashp, pageno, bufp, 0);
684 if (!rbufp) {
685 save_bufp->flags &= ~BUF_PIN;
686 return (ERROR);
687 }
688 /* FOR LOOP INIT */
689 bp = (u_int16_t *)rbufp->page;
690 n = *bp++;
691 ndx = 1;
692 off = hashp->BSIZE;
693 } else {
694 save_bufp->flags &= ~BUF_PIN;
695 return (ERROR);
696 }
697 }
698
699 /* Not found */
700 switch (action) {
701 case HASH_PUT:
702 case HASH_PUTNEW:
703 if (__addel(hashp, rbufp, key, val)) {
704 save_bufp->flags &= ~BUF_PIN;
705 return (ERROR);
706 } else {
707 save_bufp->flags &= ~BUF_PIN;
708 return (SUCCESS);
709 }
710 case HASH_GET:
711 case HASH_DELETE:
712 default:
713 save_bufp->flags &= ~BUF_PIN;
714 return (ABNORMAL);
715 }
716
717 found:
718 switch (action) {
719 case HASH_PUTNEW:
720 save_bufp->flags &= ~BUF_PIN;
721 return (ABNORMAL);
722 case HASH_GET:
723 bp = (u_int16_t *)rbufp->page;
724 if (bp[ndx + 1] < REAL_KEY) {
725 if (__big_return(hashp, rbufp, ndx, val, 0))
726 return (ERROR);
727 } else {
728 val->data = (u_char *)rbufp->page + (int)bp[ndx + 1];
729 val->size = bp[ndx] - bp[ndx + 1];
730 }
731 break;
732 case HASH_PUT:
733 if ((__delpair(hashp, rbufp, ndx)) ||
734 (__addel(hashp, rbufp, key, val))) {
735 save_bufp->flags &= ~BUF_PIN;
736 return (ERROR);
737 }
738 break;
739 case HASH_DELETE:
740 if (__delpair(hashp, rbufp, ndx))
741 return (ERROR);
742 break;
743 default:
744 abort();
745 }
746 save_bufp->flags &= ~BUF_PIN;
747 return (SUCCESS);
748 }
749
750 static int
751 hash_seq(dbp, key, data, flag)
752 const DB *dbp;
753 DBT *key, *data;
754 u_int32_t flag;
755 {
756 u_int32_t bucket;
757 BUFHEAD *bufp;
758 HTAB *hashp;
759 u_int16_t *bp, ndx;
760
761 hashp = (HTAB *)dbp->internal;
762 if (flag && flag != R_FIRST && flag != R_NEXT) {
763 hashp->error = errno = EINVAL;
764 return (ERROR);
765 }
766 #ifdef HASH_STATISTICS
767 hash_accesses++;
768 #endif
769 if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
770 hashp->cbucket = 0;
771 hashp->cndx = 1;
772 hashp->cpage = NULL;
773 }
774
775 for (bp = NULL; !bp || !bp[0]; ) {
776 if (!(bufp = hashp->cpage)) {
777 for (bucket = hashp->cbucket;
778 bucket <= hashp->MAX_BUCKET;
779 bucket++, hashp->cndx = 1) {
780 bufp = __get_buf(hashp, bucket, NULL, 0);
781 if (!bufp)
782 return (ERROR);
783 hashp->cpage = bufp;
784 bp = (u_int16_t *)bufp->page;
785 if (bp[0])
786 break;
787 }
788 hashp->cbucket = bucket;
789 if (hashp->cbucket > hashp->MAX_BUCKET) {
790 hashp->cbucket = -1;
791 return (ABNORMAL);
792 }
793 } else
794 bp = (u_int16_t *)hashp->cpage->page;
795
796 #ifdef DEBUG
797 assert(bp);
798 assert(bufp);
799 #endif
800 while (bp[hashp->cndx + 1] == OVFLPAGE) {
801 bufp = hashp->cpage =
802 __get_buf(hashp, bp[hashp->cndx], bufp, 0);
803 if (!bufp)
804 return (ERROR);
805 bp = (u_int16_t *)(bufp->page);
806 hashp->cndx = 1;
807 }
808 if (!bp[0]) {
809 hashp->cpage = NULL;
810 ++hashp->cbucket;
811 }
812 }
813 ndx = hashp->cndx;
814 if (bp[ndx + 1] < REAL_KEY) {
815 if (__big_keydata(hashp, bufp, key, data, 1))
816 return (ERROR);
817 } else {
818 key->data = (u_char *)hashp->cpage->page + bp[ndx];
819 key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
820 data->data = (u_char *)hashp->cpage->page + bp[ndx + 1];
821 data->size = bp[ndx] - bp[ndx + 1];
822 ndx += 2;
823 if (ndx > bp[0]) {
824 hashp->cpage = NULL;
825 hashp->cbucket++;
826 hashp->cndx = 1;
827 } else
828 hashp->cndx = ndx;
829 }
830 return (SUCCESS);
831 }
832
833 /********************************* UTILITIES ************************/
834
835 /*
836 * Returns:
837 * 0 ==> OK
838 * -1 ==> Error
839 */
840 extern int
841 __expand_table(hashp)
842 HTAB *hashp;
843 {
844 u_int32_t old_bucket, new_bucket;
845 int dirsize, new_segnum, spare_ndx;
846
847 #ifdef HASH_STATISTICS
848 hash_expansions++;
849 #endif
850 new_bucket = ++hashp->MAX_BUCKET;
851 old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
852
853 new_segnum = new_bucket >> hashp->SSHIFT;
854
855 /* Check if we need a new segment */
856 if (new_segnum >= hashp->nsegs) {
857 /* Check if we need to expand directory */
858 if (new_segnum >= hashp->DSIZE) {
859 /* Reallocate directory */
860 dirsize = hashp->DSIZE * sizeof(SEGMENT *);
861 if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
862 return (-1);
863 hashp->DSIZE = dirsize << 1;
864 }
865 if ((hashp->dir[new_segnum] =
866 (SEGMENT)calloc(hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
867 return (-1);
868 hashp->exsegs++;
869 hashp->nsegs++;
870 }
871 /*
872 * If the split point is increasing (MAX_BUCKET's log base 2
873 * * increases), we need to copy the current contents of the spare
874 * split bucket to the next bucket.
875 */
876 spare_ndx = __log2(hashp->MAX_BUCKET + 1);
877 if (spare_ndx > hashp->OVFL_POINT) {
878 hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
879 hashp->OVFL_POINT = spare_ndx;
880 }
881
882 if (new_bucket > hashp->HIGH_MASK) {
883 /* Starting a new doubling */
884 hashp->LOW_MASK = hashp->HIGH_MASK;
885 hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
886 }
887 /* Relocate records to the new bucket */
888 return (__split_page(hashp, old_bucket, new_bucket));
889 }
890
891 /*
892 * If realloc guarantees that the pointer is not destroyed if the realloc
893 * fails, then this routine can go away.
894 */
895 static void *
896 hash_realloc(p_ptr, oldsize, newsize)
897 SEGMENT **p_ptr;
898 int oldsize, newsize;
899 {
900 void *p;
901
902 if ( (p = malloc(newsize)) ) {
903 memmove(p, *p_ptr, oldsize);
904 memset((char *)p + oldsize, 0, newsize - oldsize);
905 free(*p_ptr);
906 *p_ptr = p;
907 }
908 return (p);
909 }
910
911 extern u_int32_t
912 __call_hash(hashp, k, len)
913 HTAB *hashp;
914 char *k;
915 int len;
916 {
917 int n, bucket;
918
919 n = hashp->hash(k, len);
920 bucket = n & hashp->HIGH_MASK;
921 if (bucket > hashp->MAX_BUCKET)
922 bucket = bucket & hashp->LOW_MASK;
923 return (bucket);
924 }
925
926 /*
927 * Allocate segment table. On error, destroy the table and set errno.
928 *
929 * Returns 0 on success
930 */
931 static int
932 alloc_segs(hashp, nsegs)
933 HTAB *hashp;
934 int nsegs;
935 {
936 int i;
937 SEGMENT store;
938
939 int save_errno;
940
941 if ((hashp->dir =
942 (SEGMENT *)calloc(hashp->DSIZE, sizeof(SEGMENT *))) == NULL) {
943 save_errno = errno;
944 (void)hdestroy(hashp);
945 errno = save_errno;
946 return (-1);
947 }
948 /* Allocate segments */
949 if ((store =
950 (SEGMENT)calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT))) == NULL) {
951 save_errno = errno;
952 (void)hdestroy(hashp);
953 errno = save_errno;
954 return (-1);
955 }
956 for (i = 0; i < nsegs; i++, hashp->nsegs++)
957 hashp->dir[i] = &store[i << hashp->SSHIFT];
958 return (0);
959 }
960
961 #if BYTE_ORDER == LITTLE_ENDIAN
962 /*
963 * Hashp->hdr needs to be byteswapped.
964 */
965 static void
966 swap_header_copy(srcp, destp)
967 HASHHDR *srcp, *destp;
968 {
969 int i;
970
971 P_32_COPY(srcp->magic, destp->magic);
972 P_32_COPY(srcp->version, destp->version);
973 P_32_COPY(srcp->lorder, destp->lorder);
974 P_32_COPY(srcp->bsize, destp->bsize);
975 P_32_COPY(srcp->bshift, destp->bshift);
976 P_32_COPY(srcp->dsize, destp->dsize);
977 P_32_COPY(srcp->ssize, destp->ssize);
978 P_32_COPY(srcp->sshift, destp->sshift);
979 P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
980 P_32_COPY(srcp->last_freed, destp->last_freed);
981 P_32_COPY(srcp->max_bucket, destp->max_bucket);
982 P_32_COPY(srcp->high_mask, destp->high_mask);
983 P_32_COPY(srcp->low_mask, destp->low_mask);
984 P_32_COPY(srcp->ffactor, destp->ffactor);
985 P_32_COPY(srcp->nkeys, destp->nkeys);
986 P_32_COPY(srcp->hdrpages, destp->hdrpages);
987 P_32_COPY(srcp->h_charkey, destp->h_charkey);
988 for (i = 0; i < NCACHED; i++) {
989 P_32_COPY(srcp->spares[i], destp->spares[i]);
990 P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
991 }
992 }
993
994 static void
995 swap_header(hashp)
996 HTAB *hashp;
997 {
998 HASHHDR *hdrp;
999 int i;
1000
1001 hdrp = &hashp->hdr;
1002
1003 M_32_SWAP(hdrp->magic);
1004 M_32_SWAP(hdrp->version);
1005 M_32_SWAP(hdrp->lorder);
1006 M_32_SWAP(hdrp->bsize);
1007 M_32_SWAP(hdrp->bshift);
1008 M_32_SWAP(hdrp->dsize);
1009 M_32_SWAP(hdrp->ssize);
1010 M_32_SWAP(hdrp->sshift);
1011 M_32_SWAP(hdrp->ovfl_point);
1012 M_32_SWAP(hdrp->last_freed);
1013 M_32_SWAP(hdrp->max_bucket);
1014 M_32_SWAP(hdrp->high_mask);
1015 M_32_SWAP(hdrp->low_mask);
1016 M_32_SWAP(hdrp->ffactor);
1017 M_32_SWAP(hdrp->nkeys);
1018 M_32_SWAP(hdrp->hdrpages);
1019 M_32_SWAP(hdrp->h_charkey);
1020 for (i = 0; i < NCACHED; i++) {
1021 M_32_SWAP(hdrp->spares[i]);
1022 M_16_SWAP(hdrp->bitmaps[i]);
1023 }
1024 }
1025 #endif