Merge from vendor branch GPERF:
[dragonfly.git] / lib / libc / db / hash / hash_page.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_page.c,v 1.5 2000/01/27 23:06:08 jasone Exp $
37  * $DragonFly: src/lib/libc/db/hash/hash_page.c,v 1.5 2005/01/31 22:29:09 dillon Exp $
38  *
39  * @(#)hash_page.c      8.7 (Berkeley) 8/16/94
40  */
41
42 /*
43  * PACKAGE:  hashing
44  *
45  * DESCRIPTION:
46  *      Page manipulation for hashing package.
47  *
48  * ROUTINES:
49  *
50  * External
51  *      __get_page
52  *      __add_ovflpage
53  * Internal
54  *      overflow_page
55  *      open_temp
56  */
57
58 #include "namespace.h"
59 #include <sys/types.h>
60
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <signal.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #ifdef DEBUG
69 #include <assert.h>
70 #endif
71 #include "un-namespace.h"
72
73 #include <db.h>
74 #include "hash.h"
75 #include "page.h"
76 #include "extern.h"
77
78 static u_int32_t        *fetch_bitmap (HTAB *, int);
79 static u_int32_t         first_free (u_int32_t);
80 static int       open_temp (HTAB *);
81 static u_int16_t         overflow_page (HTAB *);
82 static void      putpair (char *, const DBT *, const DBT *);
83 static void      squeeze_key (u_int16_t *, const DBT *, const DBT *);
84 static int       ugly_split
85                     (HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int);
86
87 #define PAGE_INIT(P) { \
88         ((u_int16_t *)(P))[0] = 0; \
89         ((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \
90         ((u_int16_t *)(P))[2] = hashp->BSIZE; \
91 }
92
93 /*
94  * This is called AFTER we have verified that there is room on the page for
95  * the pair (PAIRFITS has returned true) so we go right ahead and start moving
96  * stuff on.
97  */
98 static void
99 putpair(p, key, val)
100         char *p;
101         const DBT *key, *val;
102 {
103         u_int16_t *bp, n, off;
104
105         bp = (u_int16_t *)p;
106
107         /* Enter the key first. */
108         n = bp[0];
109
110         off = OFFSET(bp) - key->size;
111         memmove(p + off, key->data, key->size);
112         bp[++n] = off;
113
114         /* Now the data. */
115         off -= val->size;
116         memmove(p + off, val->data, val->size);
117         bp[++n] = off;
118
119         /* Adjust page info. */
120         bp[0] = n;
121         bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t));
122         bp[n + 2] = off;
123 }
124
125 /*
126  * Returns:
127  *       0 OK
128  *      -1 error
129  */
130 extern int
131 __delpair(hashp, bufp, ndx)
132         HTAB *hashp;
133         BUFHEAD *bufp;
134         int ndx;
135 {
136         u_int16_t *bp, newoff;
137         int n;
138         u_int16_t pairlen;
139
140         bp = (u_int16_t *)bufp->page;
141         n = bp[0];
142
143         if (bp[ndx + 1] < REAL_KEY)
144                 return (__big_delete(hashp, bufp));
145         if (ndx != 1)
146                 newoff = bp[ndx - 1];
147         else
148                 newoff = hashp->BSIZE;
149         pairlen = newoff - bp[ndx + 1];
150
151         if (ndx != (n - 1)) {
152                 /* Hard Case -- need to shuffle keys */
153                 int i;
154                 char *src = bufp->page + (int)OFFSET(bp);
155                 char *dst = src + (int)pairlen;
156                 memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
157
158                 /* Now adjust the pointers */
159                 for (i = ndx + 2; i <= n; i += 2) {
160                         if (bp[i + 1] == OVFLPAGE) {
161                                 bp[i - 2] = bp[i];
162                                 bp[i - 1] = bp[i + 1];
163                         } else {
164                                 bp[i - 2] = bp[i] + pairlen;
165                                 bp[i - 1] = bp[i + 1] + pairlen;
166                         }
167                 }
168         }
169         /* Finally adjust the page data */
170         bp[n] = OFFSET(bp) + pairlen;
171         bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t);
172         bp[0] = n - 2;
173         hashp->NKEYS--;
174
175         bufp->flags |= BUF_MOD;
176         return (0);
177 }
178 /*
179  * Returns:
180  *       0 ==> OK
181  *      -1 ==> Error
182  */
183 extern int
184 __split_page(hashp, obucket, nbucket)
185         HTAB *hashp;
186         u_int32_t obucket, nbucket;
187 {
188         BUFHEAD *new_bufp, *old_bufp;
189         u_int16_t *ino;
190         char *np;
191         DBT key, val;
192         int n, ndx, retval;
193         u_int16_t copyto, diff, off, moved;
194         char *op;
195
196         copyto = (u_int16_t)hashp->BSIZE;
197         off = (u_int16_t)hashp->BSIZE;
198         old_bufp = __get_buf(hashp, obucket, NULL, 0);
199         if (old_bufp == NULL)
200                 return (-1);
201         new_bufp = __get_buf(hashp, nbucket, NULL, 0);
202         if (new_bufp == NULL)
203                 return (-1);
204
205         old_bufp->flags |= (BUF_MOD | BUF_PIN);
206         new_bufp->flags |= (BUF_MOD | BUF_PIN);
207
208         ino = (u_int16_t *)(op = old_bufp->page);
209         np = new_bufp->page;
210
211         moved = 0;
212
213         for (n = 1, ndx = 1; n < ino[0]; n += 2) {
214                 if (ino[n + 1] < REAL_KEY) {
215                         retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
216                             (int)copyto, (int)moved);
217                         old_bufp->flags &= ~BUF_PIN;
218                         new_bufp->flags &= ~BUF_PIN;
219                         return (retval);
220
221                 }
222                 key.data = (u_char *)op + ino[n];
223                 key.size = off - ino[n];
224
225                 if (__call_hash(hashp, key.data, key.size) == obucket) {
226                         /* Don't switch page */
227                         diff = copyto - off;
228                         if (diff) {
229                                 copyto = ino[n + 1] + diff;
230                                 memmove(op + copyto, op + ino[n + 1],
231                                     off - ino[n + 1]);
232                                 ino[ndx] = copyto + ino[n] - ino[n + 1];
233                                 ino[ndx + 1] = copyto;
234                         } else
235                                 copyto = ino[n + 1];
236                         ndx += 2;
237                 } else {
238                         /* Switch page */
239                         val.data = (u_char *)op + ino[n + 1];
240                         val.size = ino[n] - ino[n + 1];
241                         putpair(np, &key, &val);
242                         moved += 2;
243                 }
244
245                 off = ino[n + 1];
246         }
247
248         /* Now clean up the page */
249         ino[0] -= moved;
250         FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3);
251         OFFSET(ino) = copyto;
252
253 #ifdef DEBUG3
254         (void)fprintf(stderr, "split %d/%d\n",
255             ((u_int16_t *)np)[0] / 2,
256             ((u_int16_t *)op)[0] / 2);
257 #endif
258         /* unpin both pages */
259         old_bufp->flags &= ~BUF_PIN;
260         new_bufp->flags &= ~BUF_PIN;
261         return (0);
262 }
263
264 /*
265  * Called when we encounter an overflow or big key/data page during split
266  * handling.  This is special cased since we have to begin checking whether
267  * the key/data pairs fit on their respective pages and because we may need
268  * overflow pages for both the old and new pages.
269  *
270  * The first page might be a page with regular key/data pairs in which case
271  * we have a regular overflow condition and just need to go on to the next
272  * page or it might be a big key/data pair in which case we need to fix the
273  * big key/data pair.
274  *
275  * Returns:
276  *       0 ==> success
277  *      -1 ==> failure
278  */
279 static int
280 ugly_split(hashp, obucket, old_bufp, new_bufp, copyto, moved)
281         HTAB *hashp;
282         u_int32_t obucket;      /* Same as __split_page. */
283         BUFHEAD *old_bufp, *new_bufp;
284         int copyto;     /* First byte on page which contains key/data values. */
285         int moved;      /* Number of pairs moved to new page. */
286 {
287         BUFHEAD *bufp;  /* Buffer header for ino */
288         u_int16_t *ino; /* Page keys come off of */
289         u_int16_t *np;  /* New page */
290         u_int16_t *op;  /* Page keys go on to if they aren't moving */
291
292         BUFHEAD *last_bfp;      /* Last buf header OVFL needing to be freed */
293         DBT key, val;
294         SPLIT_RETURN ret;
295         u_int16_t n, off, ov_addr, scopyto;
296         char *cino;             /* Character value of ino */
297
298         bufp = old_bufp;
299         ino = (u_int16_t *)old_bufp->page;
300         np = (u_int16_t *)new_bufp->page;
301         op = (u_int16_t *)old_bufp->page;
302         last_bfp = NULL;
303         scopyto = (u_int16_t)copyto;    /* ANSI */
304
305         n = ino[0] - 1;
306         while (n < ino[0]) {
307                 if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
308                         if (__big_split(hashp, old_bufp,
309                             new_bufp, bufp, bufp->addr, obucket, &ret))
310                                 return (-1);
311                         old_bufp = ret.oldp;
312                         if (!old_bufp)
313                                 return (-1);
314                         op = (u_int16_t *)old_bufp->page;
315                         new_bufp = ret.newp;
316                         if (!new_bufp)
317                                 return (-1);
318                         np = (u_int16_t *)new_bufp->page;
319                         bufp = ret.nextp;
320                         if (!bufp)
321                                 return (0);
322                         cino = (char *)bufp->page;
323                         ino = (u_int16_t *)cino;
324                         last_bfp = ret.nextp;
325                 } else if (ino[n + 1] == OVFLPAGE) {
326                         ov_addr = ino[n];
327                         /*
328                          * Fix up the old page -- the extra 2 are the fields
329                          * which contained the overflow information.
330                          */
331                         ino[0] -= (moved + 2);
332                         FREESPACE(ino) =
333                             scopyto - sizeof(u_int16_t) * (ino[0] + 3);
334                         OFFSET(ino) = scopyto;
335
336                         bufp = __get_buf(hashp, ov_addr, bufp, 0);
337                         if (!bufp)
338                                 return (-1);
339
340                         ino = (u_int16_t *)bufp->page;
341                         n = 1;
342                         scopyto = hashp->BSIZE;
343                         moved = 0;
344
345                         if (last_bfp)
346                                 __free_ovflpage(hashp, last_bfp);
347                         last_bfp = bufp;
348                 }
349                 /* Move regular sized pairs of there are any */
350                 off = hashp->BSIZE;
351                 for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
352                         cino = (char *)ino;
353                         key.data = (u_char *)cino + ino[n];
354                         key.size = off - ino[n];
355                         val.data = (u_char *)cino + ino[n + 1];
356                         val.size = ino[n] - ino[n + 1];
357                         off = ino[n + 1];
358
359                         if (__call_hash(hashp, key.data, key.size) == obucket) {
360                                 /* Keep on old page */
361                                 if (PAIRFITS(op, (&key), (&val)))
362                                         putpair((char *)op, &key, &val);
363                                 else {
364                                         old_bufp =
365                                             __add_ovflpage(hashp, old_bufp);
366                                         if (!old_bufp)
367                                                 return (-1);
368                                         op = (u_int16_t *)old_bufp->page;
369                                         putpair((char *)op, &key, &val);
370                                 }
371                                 old_bufp->flags |= BUF_MOD;
372                         } else {
373                                 /* Move to new page */
374                                 if (PAIRFITS(np, (&key), (&val)))
375                                         putpair((char *)np, &key, &val);
376                                 else {
377                                         new_bufp =
378                                             __add_ovflpage(hashp, new_bufp);
379                                         if (!new_bufp)
380                                                 return (-1);
381                                         np = (u_int16_t *)new_bufp->page;
382                                         putpair((char *)np, &key, &val);
383                                 }
384                                 new_bufp->flags |= BUF_MOD;
385                         }
386                 }
387         }
388         if (last_bfp)
389                 __free_ovflpage(hashp, last_bfp);
390         return (0);
391 }
392
393 /*
394  * Add the given pair to the page
395  *
396  * Returns:
397  *      0 ==> OK
398  *      1 ==> failure
399  */
400 extern int
401 __addel(hashp, bufp, key, val)
402         HTAB *hashp;
403         BUFHEAD *bufp;
404         const DBT *key, *val;
405 {
406         u_int16_t *bp, *sop;
407         int do_expand;
408
409         bp = (u_int16_t *)bufp->page;
410         do_expand = 0;
411         while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
412                 /* Exception case */
413                 if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
414                         /* This is the last page of a big key/data pair
415                            and we need to add another page */
416                         break;
417                 else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
418                         bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
419                         if (!bufp)
420                                 return (-1);
421                         bp = (u_int16_t *)bufp->page;
422                 } else
423                         /* Try to squeeze key on this page */
424                         if (FREESPACE(bp) > PAIRSIZE(key, val)) {
425                                 squeeze_key(bp, key, val);
426                                 return (0);
427                         } else {
428                                 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
429                                 if (!bufp)
430                                         return (-1);
431                                 bp = (u_int16_t *)bufp->page;
432                         }
433
434         if (PAIRFITS(bp, key, val))
435                 putpair(bufp->page, key, val);
436         else {
437                 do_expand = 1;
438                 bufp = __add_ovflpage(hashp, bufp);
439                 if (!bufp)
440                         return (-1);
441                 sop = (u_int16_t *)bufp->page;
442
443                 if (PAIRFITS(sop, key, val))
444                         putpair((char *)sop, key, val);
445                 else
446                         if (__big_insert(hashp, bufp, key, val))
447                                 return (-1);
448         }
449         bufp->flags |= BUF_MOD;
450         /*
451          * If the average number of keys per bucket exceeds the fill factor,
452          * expand the table.
453          */
454         hashp->NKEYS++;
455         if (do_expand ||
456             (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
457                 return (__expand_table(hashp));
458         return (0);
459 }
460
461 /*
462  *
463  * Returns:
464  *      pointer on success
465  *      NULL on error
466  */
467 extern BUFHEAD *
468 __add_ovflpage(hashp, bufp)
469         HTAB *hashp;
470         BUFHEAD *bufp;
471 {
472         u_int16_t *sp;
473         u_int16_t ndx, ovfl_num;
474 #ifdef DEBUG1
475         int tmp1, tmp2;
476 #endif
477         sp = (u_int16_t *)bufp->page;
478
479         /* Check if we are dynamically determining the fill factor */
480         if (hashp->FFACTOR == DEF_FFACTOR) {
481                 hashp->FFACTOR = sp[0] >> 1;
482                 if (hashp->FFACTOR < MIN_FFACTOR)
483                         hashp->FFACTOR = MIN_FFACTOR;
484         }
485         bufp->flags |= BUF_MOD;
486         ovfl_num = overflow_page(hashp);
487 #ifdef DEBUG1
488         tmp1 = bufp->addr;
489         tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
490 #endif
491         if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
492                 return (NULL);
493         bufp->ovfl->flags |= BUF_MOD;
494 #ifdef DEBUG1
495         (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
496             tmp1, tmp2, bufp->ovfl->addr);
497 #endif
498         ndx = sp[0];
499         /*
500          * Since a pair is allocated on a page only if there's room to add
501          * an overflow page, we know that the OVFL information will fit on
502          * the page.
503          */
504         sp[ndx + 4] = OFFSET(sp);
505         sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
506         sp[ndx + 1] = ovfl_num;
507         sp[ndx + 2] = OVFLPAGE;
508         sp[0] = ndx + 2;
509 #ifdef HASH_STATISTICS
510         hash_overflows++;
511 #endif
512         return (bufp->ovfl);
513 }
514
515 /*
516  * Returns:
517  *       0 indicates SUCCESS
518  *      -1 indicates FAILURE
519  */
520 extern int
521 __get_page(hashp, p, bucket, is_bucket, is_disk, is_bitmap)
522         HTAB *hashp;
523         char *p;
524         u_int32_t bucket;
525         int is_bucket, is_disk, is_bitmap;
526 {
527         int fd, page, size;
528         int rsize;
529         u_int16_t *bp;
530
531         fd = hashp->fp;
532         size = hashp->BSIZE;
533
534         if ((fd == -1) || !is_disk) {
535                 PAGE_INIT(p);
536                 return (0);
537         }
538         if (is_bucket)
539                 page = BUCKET_TO_PAGE(bucket);
540         else
541                 page = OADDR_TO_PAGE(bucket);
542         if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
543             ((rsize = _read(fd, p, size)) == -1))
544                 return (-1);
545         bp = (u_int16_t *)p;
546         if (!rsize)
547                 bp[0] = 0;      /* We hit the EOF, so initialize a new page */
548         else
549                 if (rsize != size) {
550                         errno = EFTYPE;
551                         return (-1);
552                 }
553         if (!is_bitmap && !bp[0]) {
554                 PAGE_INIT(p);
555         } else
556                 if (hashp->LORDER != BYTE_ORDER) {
557                         int i, max;
558
559                         if (is_bitmap) {
560                                 max = hashp->BSIZE >> 2; /* divide by 4 */
561                                 for (i = 0; i < max; i++)
562                                         M_32_SWAP(((int *)p)[i]);
563                         } else {
564                                 M_16_SWAP(bp[0]);
565                                 max = bp[0] + 2;
566                                 for (i = 1; i <= max; i++)
567                                         M_16_SWAP(bp[i]);
568                         }
569                 }
570         return (0);
571 }
572
573 /*
574  * Write page p to disk
575  *
576  * Returns:
577  *       0 ==> OK
578  *      -1 ==>failure
579  */
580 extern int
581 __put_page(hashp, p, bucket, is_bucket, is_bitmap)
582         HTAB *hashp;
583         char *p;
584         u_int32_t bucket;
585         int is_bucket, is_bitmap;
586 {
587         int fd, page, size;
588         int wsize;
589
590         size = hashp->BSIZE;
591         if ((hashp->fp == -1) && open_temp(hashp))
592                 return (-1);
593         fd = hashp->fp;
594
595         if (hashp->LORDER != BYTE_ORDER) {
596                 int i;
597                 int max;
598
599                 if (is_bitmap) {
600                         max = hashp->BSIZE >> 2;        /* divide by 4 */
601                         for (i = 0; i < max; i++)
602                                 M_32_SWAP(((int *)p)[i]);
603                 } else {
604                         max = ((u_int16_t *)p)[0] + 2;
605                         for (i = 0; i <= max; i++)
606                                 M_16_SWAP(((u_int16_t *)p)[i]);
607                 }
608         }
609         if (is_bucket)
610                 page = BUCKET_TO_PAGE(bucket);
611         else
612                 page = OADDR_TO_PAGE(bucket);
613         if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
614             ((wsize = _write(fd, p, size)) == -1))
615                 /* Errno is set */
616                 return (-1);
617         if (wsize != size) {
618                 errno = EFTYPE;
619                 return (-1);
620         }
621         return (0);
622 }
623
624 #define BYTE_MASK       ((1 << INT_BYTE_SHIFT) -1)
625 /*
626  * Initialize a new bitmap page.  Bitmap pages are left in memory
627  * once they are read in.
628  */
629 extern int
630 __ibitmap(hashp, pnum, nbits, ndx)
631         HTAB *hashp;
632         int pnum, nbits, ndx;
633 {
634         u_int32_t *ip;
635         int clearbytes, clearints;
636
637         if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
638                 return (1);
639         hashp->nmaps++;
640         clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
641         clearbytes = clearints << INT_TO_BYTE;
642         (void)memset((char *)ip, 0, clearbytes);
643         (void)memset(((char *)ip) + clearbytes, 0xFF,
644             hashp->BSIZE - clearbytes);
645         ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
646         SETBIT(ip, 0);
647         hashp->BITMAPS[ndx] = (u_int16_t)pnum;
648         hashp->mapp[ndx] = ip;
649         return (0);
650 }
651
652 static u_int32_t
653 first_free(map)
654         u_int32_t map;
655 {
656         u_int32_t i, mask;
657
658         mask = 0x1;
659         for (i = 0; i < BITS_PER_MAP; i++) {
660                 if (!(mask & map))
661                         return (i);
662                 mask = mask << 1;
663         }
664         return (i);
665 }
666
667 static u_int16_t
668 overflow_page(hashp)
669         HTAB *hashp;
670 {
671         u_int32_t *freep;
672         int max_free, offset, splitnum;
673         u_int16_t addr;
674         int bit, first_page, free_bit, free_page, i, in_use_bits, j;
675 #ifdef DEBUG2
676         int tmp1, tmp2;
677 #endif
678         splitnum = hashp->OVFL_POINT;
679         max_free = hashp->SPARES[splitnum];
680
681         free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
682         free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
683
684         /* Look through all the free maps to find the first free block */
685         first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
686         for ( i = first_page; i <= free_page; i++ ) {
687                 if (!(freep = (u_int32_t *)hashp->mapp[i]) &&
688                     !(freep = fetch_bitmap(hashp, i)))
689                         return (0);
690                 if (i == free_page)
691                         in_use_bits = free_bit;
692                 else
693                         in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
694
695                 if (i == first_page) {
696                         bit = hashp->LAST_FREED &
697                             ((hashp->BSIZE << BYTE_SHIFT) - 1);
698                         j = bit / BITS_PER_MAP;
699                         bit = bit & ~(BITS_PER_MAP - 1);
700                 } else {
701                         bit = 0;
702                         j = 0;
703                 }
704                 for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
705                         if (freep[j] != ALL_SET)
706                                 goto found;
707         }
708
709         /* No Free Page Found */
710         hashp->LAST_FREED = hashp->SPARES[splitnum];
711         hashp->SPARES[splitnum]++;
712         offset = hashp->SPARES[splitnum] -
713             (splitnum ? hashp->SPARES[splitnum - 1] : 0);
714
715 #define OVMSG   "HASH: Out of overflow pages.  Increase page size\n"
716         if (offset > SPLITMASK) {
717                 if (++splitnum >= NCACHED) {
718                         (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
719                         return (0);
720                 }
721                 hashp->OVFL_POINT = splitnum;
722                 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
723                 hashp->SPARES[splitnum-1]--;
724                 offset = 1;
725         }
726
727         /* Check if we need to allocate a new bitmap page */
728         if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
729                 free_page++;
730                 if (free_page >= NCACHED) {
731                         (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
732                         return (0);
733                 }
734                 /*
735                  * This is tricky.  The 1 indicates that you want the new page
736                  * allocated with 1 clear bit.  Actually, you are going to
737                  * allocate 2 pages from this map.  The first is going to be
738                  * the map page, the second is the overflow page we were
739                  * looking for.  The init_bitmap routine automatically, sets
740                  * the first bit of itself to indicate that the bitmap itself
741                  * is in use.  We would explicitly set the second bit, but
742                  * don't have to if we tell init_bitmap not to leave it clear
743                  * in the first place.
744                  */
745                 if (__ibitmap(hashp,
746                     (int)OADDR_OF(splitnum, offset), 1, free_page))
747                         return (0);
748                 hashp->SPARES[splitnum]++;
749 #ifdef DEBUG2
750                 free_bit = 2;
751 #endif
752                 offset++;
753                 if (offset > SPLITMASK) {
754                         if (++splitnum >= NCACHED) {
755                                 (void)_write(STDERR_FILENO, OVMSG,
756                                     sizeof(OVMSG) - 1);
757                                 return (0);
758                         }
759                         hashp->OVFL_POINT = splitnum;
760                         hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
761                         hashp->SPARES[splitnum-1]--;
762                         offset = 0;
763                 }
764         } else {
765                 /*
766                  * Free_bit addresses the last used bit.  Bump it to address
767                  * the first available bit.
768                  */
769                 free_bit++;
770                 SETBIT(freep, free_bit);
771         }
772
773         /* Calculate address of the new overflow page */
774         addr = OADDR_OF(splitnum, offset);
775 #ifdef DEBUG2
776         (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
777             addr, free_bit, free_page);
778 #endif
779         return (addr);
780
781 found:
782         bit = bit + first_free(freep[j]);
783         SETBIT(freep, bit);
784 #ifdef DEBUG2
785         tmp1 = bit;
786         tmp2 = i;
787 #endif
788         /*
789          * Bits are addressed starting with 0, but overflow pages are addressed
790          * beginning at 1. Bit is a bit addressnumber, so we need to increment
791          * it to convert it to a page number.
792          */
793         bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
794         if (bit >= hashp->LAST_FREED)
795                 hashp->LAST_FREED = bit - 1;
796
797         /* Calculate the split number for this page */
798         for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
799         offset = (i ? bit - hashp->SPARES[i - 1] : bit);
800         if (offset >= SPLITMASK)
801                 return (0);     /* Out of overflow pages */
802         addr = OADDR_OF(i, offset);
803 #ifdef DEBUG2
804         (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
805             addr, tmp1, tmp2);
806 #endif
807
808         /* Allocate and return the overflow page */
809         return (addr);
810 }
811
812 /*
813  * Mark this overflow page as free.
814  */
815 extern void
816 __free_ovflpage(hashp, obufp)
817         HTAB *hashp;
818         BUFHEAD *obufp;
819 {
820         u_int16_t addr;
821         u_int32_t *freep;
822         int bit_address, free_page, free_bit;
823         u_int16_t ndx;
824
825         addr = obufp->addr;
826 #ifdef DEBUG1
827         (void)fprintf(stderr, "Freeing %d\n", addr);
828 #endif
829         ndx = (((u_int16_t)addr) >> SPLITSHIFT);
830         bit_address =
831             (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
832          if (bit_address < hashp->LAST_FREED)
833                 hashp->LAST_FREED = bit_address;
834         free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
835         free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
836
837         if (!(freep = hashp->mapp[free_page]))
838                 freep = fetch_bitmap(hashp, free_page);
839 #ifdef DEBUG
840         /*
841          * This had better never happen.  It means we tried to read a bitmap
842          * that has already had overflow pages allocated off it, and we
843          * failed to read it from the file.
844          */
845         if (!freep)
846                 assert(0);
847 #endif
848         CLRBIT(freep, free_bit);
849 #ifdef DEBUG2
850         (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
851             obufp->addr, free_bit, free_page);
852 #endif
853         __reclaim_buf(hashp, obufp);
854 }
855
856 /*
857  * Returns:
858  *       0 success
859  *      -1 failure
860  */
861 static int
862 open_temp(hashp)
863         HTAB *hashp;
864 {
865         sigset_t set, oset;
866         static char namestr[] = "_hashXXXXXX";
867
868         /* Block signals; make sure file goes away at process exit. */
869         (void)sigfillset(&set);
870         (void)_sigprocmask(SIG_BLOCK, &set, &oset);
871         if ((hashp->fp = mkstemp(namestr)) != -1) {
872                 (void)unlink(namestr);
873                 (void)_fcntl(hashp->fp, F_SETFD, 1);
874         }
875         (void)_sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
876         return (hashp->fp != -1 ? 0 : -1);
877 }
878
879 /*
880  * We have to know that the key will fit, but the last entry on the page is
881  * an overflow pair, so we need to shift things.
882  */
883 static void
884 squeeze_key(sp, key, val)
885         u_int16_t *sp;
886         const DBT *key, *val;
887 {
888         char *p;
889         u_int16_t free_space, n, off, pageno;
890
891         p = (char *)sp;
892         n = sp[0];
893         free_space = FREESPACE(sp);
894         off = OFFSET(sp);
895
896         pageno = sp[n - 1];
897         off -= key->size;
898         sp[n - 1] = off;
899         memmove(p + off, key->data, key->size);
900         off -= val->size;
901         sp[n] = off;
902         memmove(p + off, val->data, val->size);
903         sp[0] = n + 2;
904         sp[n + 1] = pageno;
905         sp[n + 2] = OVFLPAGE;
906         FREESPACE(sp) = free_space - PAIRSIZE(key, val);
907         OFFSET(sp) = off;
908 }
909
910 static u_int32_t *
911 fetch_bitmap(hashp, ndx)
912         HTAB *hashp;
913         int ndx;
914 {
915         if (ndx >= hashp->nmaps)
916                 return (NULL);
917         if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
918                 return (NULL);
919         if (__get_page(hashp,
920             (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
921                 free(hashp->mapp[ndx]);
922                 return (NULL);
923         }
924         return (hashp->mapp[ndx]);
925 }
926
927 #ifdef DEBUG4
928 int
929 print_chain(addr)
930         int addr;
931 {
932         BUFHEAD *bufp;
933         short *bp, oaddr;
934
935         (void)fprintf(stderr, "%d ", addr);
936         bufp = __get_buf(hashp, addr, NULL, 0);
937         bp = (short *)bufp->page;
938         while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
939                 ((bp[0] > 2) && bp[2] < REAL_KEY))) {
940                 oaddr = bp[bp[0] - 1];
941                 (void)fprintf(stderr, "%d ", (int)oaddr);
942                 bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
943                 bp = (short *)bufp->page;
944         }
945         (void)fprintf(stderr, "\n");
946 }
947 #endif