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