2 * Copyright (c) 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
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 $
39 * @(#)hash_page.c 8.7 (Berkeley) 8/16/94
46 * Page manipulation for hashing package.
58 #include "namespace.h"
59 #include <sys/types.h>
71 #include "un-namespace.h"
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 *);
85 (HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int);
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; \
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
101 const DBT *key, *val;
103 u_int16_t *bp, n, off;
107 /* Enter the key first. */
110 off = OFFSET(bp) - key->size;
111 memmove(p + off, key->data, key->size);
116 memmove(p + off, val->data, val->size);
119 /* Adjust page info. */
121 bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t));
131 __delpair(hashp, bufp, ndx)
136 u_int16_t *bp, newoff;
140 bp = (u_int16_t *)bufp->page;
143 if (bp[ndx + 1] < REAL_KEY)
144 return (__big_delete(hashp, bufp));
146 newoff = bp[ndx - 1];
148 newoff = hashp->BSIZE;
149 pairlen = newoff - bp[ndx + 1];
151 if (ndx != (n - 1)) {
152 /* Hard Case -- need to shuffle keys */
154 char *src = bufp->page + (int)OFFSET(bp);
155 char *dst = src + (int)pairlen;
156 memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
158 /* Now adjust the pointers */
159 for (i = ndx + 2; i <= n; i += 2) {
160 if (bp[i + 1] == OVFLPAGE) {
162 bp[i - 1] = bp[i + 1];
164 bp[i - 2] = bp[i] + pairlen;
165 bp[i - 1] = bp[i + 1] + pairlen;
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);
175 bufp->flags |= BUF_MOD;
184 __split_page(hashp, obucket, nbucket)
186 u_int32_t obucket, nbucket;
188 BUFHEAD *new_bufp, *old_bufp;
193 u_int16_t copyto, diff, off, moved;
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)
201 new_bufp = __get_buf(hashp, nbucket, NULL, 0);
202 if (new_bufp == NULL)
205 old_bufp->flags |= (BUF_MOD | BUF_PIN);
206 new_bufp->flags |= (BUF_MOD | BUF_PIN);
208 ino = (u_int16_t *)(op = old_bufp->page);
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;
222 key.data = (u_char *)op + ino[n];
223 key.size = off - ino[n];
225 if (__call_hash(hashp, key.data, key.size) == obucket) {
226 /* Don't switch page */
229 copyto = ino[n + 1] + diff;
230 memmove(op + copyto, op + ino[n + 1],
232 ino[ndx] = copyto + ino[n] - ino[n + 1];
233 ino[ndx + 1] = copyto;
239 val.data = (u_char *)op + ino[n + 1];
240 val.size = ino[n] - ino[n + 1];
241 putpair(np, &key, &val);
248 /* Now clean up the page */
250 FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3);
251 OFFSET(ino) = copyto;
254 (void)fprintf(stderr, "split %d/%d\n",
255 ((u_int16_t *)np)[0] / 2,
256 ((u_int16_t *)op)[0] / 2);
258 /* unpin both pages */
259 old_bufp->flags &= ~BUF_PIN;
260 new_bufp->flags &= ~BUF_PIN;
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.
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
280 ugly_split(hashp, obucket, old_bufp, new_bufp, copyto, moved)
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. */
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 */
292 BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */
295 u_int16_t n, off, ov_addr, scopyto;
296 char *cino; /* Character value of ino */
299 ino = (u_int16_t *)old_bufp->page;
300 np = (u_int16_t *)new_bufp->page;
301 op = (u_int16_t *)old_bufp->page;
303 scopyto = (u_int16_t)copyto; /* ANSI */
307 if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
308 if (__big_split(hashp, old_bufp,
309 new_bufp, bufp, bufp->addr, obucket, &ret))
314 op = (u_int16_t *)old_bufp->page;
318 np = (u_int16_t *)new_bufp->page;
322 cino = (char *)bufp->page;
323 ino = (u_int16_t *)cino;
324 last_bfp = ret.nextp;
325 } else if (ino[n + 1] == OVFLPAGE) {
328 * Fix up the old page -- the extra 2 are the fields
329 * which contained the overflow information.
331 ino[0] -= (moved + 2);
333 scopyto - sizeof(u_int16_t) * (ino[0] + 3);
334 OFFSET(ino) = scopyto;
336 bufp = __get_buf(hashp, ov_addr, bufp, 0);
340 ino = (u_int16_t *)bufp->page;
342 scopyto = hashp->BSIZE;
346 __free_ovflpage(hashp, last_bfp);
349 /* Move regular sized pairs of there are any */
351 for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
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];
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);
365 __add_ovflpage(hashp, old_bufp);
368 op = (u_int16_t *)old_bufp->page;
369 putpair((char *)op, &key, &val);
371 old_bufp->flags |= BUF_MOD;
373 /* Move to new page */
374 if (PAIRFITS(np, (&key), (&val)))
375 putpair((char *)np, &key, &val);
378 __add_ovflpage(hashp, new_bufp);
381 np = (u_int16_t *)new_bufp->page;
382 putpair((char *)np, &key, &val);
384 new_bufp->flags |= BUF_MOD;
389 __free_ovflpage(hashp, last_bfp);
394 * Add the given pair to the page
401 __addel(hashp, bufp, key, val)
404 const DBT *key, *val;
409 bp = (u_int16_t *)bufp->page;
411 while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
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 */
417 else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
418 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
421 bp = (u_int16_t *)bufp->page;
423 /* Try to squeeze key on this page */
424 if (FREESPACE(bp) > PAIRSIZE(key, val)) {
425 squeeze_key(bp, key, val);
428 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
431 bp = (u_int16_t *)bufp->page;
434 if (PAIRFITS(bp, key, val))
435 putpair(bufp->page, key, val);
438 bufp = __add_ovflpage(hashp, bufp);
441 sop = (u_int16_t *)bufp->page;
443 if (PAIRFITS(sop, key, val))
444 putpair((char *)sop, key, val);
446 if (__big_insert(hashp, bufp, key, val))
449 bufp->flags |= BUF_MOD;
451 * If the average number of keys per bucket exceeds the fill factor,
456 (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
457 return (__expand_table(hashp));
468 __add_ovflpage(hashp, bufp)
473 u_int16_t ndx, ovfl_num;
477 sp = (u_int16_t *)bufp->page;
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;
485 bufp->flags |= BUF_MOD;
486 ovfl_num = overflow_page(hashp);
489 tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
491 if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
493 bufp->ovfl->flags |= BUF_MOD;
495 (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
496 tmp1, tmp2, bufp->ovfl->addr);
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
504 sp[ndx + 4] = OFFSET(sp);
505 sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
506 sp[ndx + 1] = ovfl_num;
507 sp[ndx + 2] = OVFLPAGE;
509 #ifdef HASH_STATISTICS
517 * 0 indicates SUCCESS
518 * -1 indicates FAILURE
521 __get_page(hashp, p, bucket, is_bucket, is_disk, is_bitmap)
525 int is_bucket, is_disk, is_bitmap;
534 if ((fd == -1) || !is_disk) {
539 page = BUCKET_TO_PAGE(bucket);
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))
547 bp[0] = 0; /* We hit the EOF, so initialize a new page */
553 if (!is_bitmap && !bp[0]) {
556 if (hashp->LORDER != BYTE_ORDER) {
560 max = hashp->BSIZE >> 2; /* divide by 4 */
561 for (i = 0; i < max; i++)
562 M_32_SWAP(((int *)p)[i]);
566 for (i = 1; i <= max; i++)
574 * Write page p to disk
581 __put_page(hashp, p, bucket, is_bucket, is_bitmap)
585 int is_bucket, is_bitmap;
591 if ((hashp->fp == -1) && open_temp(hashp))
595 if (hashp->LORDER != BYTE_ORDER) {
600 max = hashp->BSIZE >> 2; /* divide by 4 */
601 for (i = 0; i < max; i++)
602 M_32_SWAP(((int *)p)[i]);
604 max = ((u_int16_t *)p)[0] + 2;
605 for (i = 0; i <= max; i++)
606 M_16_SWAP(((u_int16_t *)p)[i]);
610 page = BUCKET_TO_PAGE(bucket);
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))
624 #define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1)
626 * Initialize a new bitmap page. Bitmap pages are left in memory
627 * once they are read in.
630 __ibitmap(hashp, pnum, nbits, ndx)
632 int pnum, nbits, ndx;
635 int clearbytes, clearints;
637 if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
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);
647 hashp->BITMAPS[ndx] = (u_int16_t)pnum;
648 hashp->mapp[ndx] = ip;
659 for (i = 0; i < BITS_PER_MAP; i++) {
672 int max_free, offset, splitnum;
674 int bit, first_page, free_bit, free_page, i, in_use_bits, j;
678 splitnum = hashp->OVFL_POINT;
679 max_free = hashp->SPARES[splitnum];
681 free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
682 free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
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)))
691 in_use_bits = free_bit;
693 in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
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);
704 for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
705 if (freep[j] != ALL_SET)
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);
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);
721 hashp->OVFL_POINT = splitnum;
722 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
723 hashp->SPARES[splitnum-1]--;
727 /* Check if we need to allocate a new bitmap page */
728 if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
730 if (free_page >= NCACHED) {
731 (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
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.
746 (int)OADDR_OF(splitnum, offset), 1, free_page))
748 hashp->SPARES[splitnum]++;
753 if (offset > SPLITMASK) {
754 if (++splitnum >= NCACHED) {
755 (void)_write(STDERR_FILENO, OVMSG,
759 hashp->OVFL_POINT = splitnum;
760 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
761 hashp->SPARES[splitnum-1]--;
766 * Free_bit addresses the last used bit. Bump it to address
767 * the first available bit.
770 SETBIT(freep, free_bit);
773 /* Calculate address of the new overflow page */
774 addr = OADDR_OF(splitnum, offset);
776 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
777 addr, free_bit, free_page);
782 bit = bit + first_free(freep[j]);
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.
793 bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
794 if (bit >= hashp->LAST_FREED)
795 hashp->LAST_FREED = bit - 1;
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);
804 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
808 /* Allocate and return the overflow page */
813 * Mark this overflow page as free.
816 __free_ovflpage(hashp, obufp)
822 int bit_address, free_page, free_bit;
827 (void)fprintf(stderr, "Freeing %d\n", addr);
829 ndx = (((u_int16_t)addr) >> SPLITSHIFT);
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);
837 if (!(freep = hashp->mapp[free_page]))
838 freep = fetch_bitmap(hashp, free_page);
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.
848 CLRBIT(freep, free_bit);
850 (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
851 obufp->addr, free_bit, free_page);
853 __reclaim_buf(hashp, obufp);
866 static char namestr[] = "_hashXXXXXX";
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);
875 (void)_sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
876 return (hashp->fp != -1 ? 0 : -1);
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.
884 squeeze_key(sp, key, val)
886 const DBT *key, *val;
889 u_int16_t free_space, n, off, pageno;
893 free_space = FREESPACE(sp);
899 memmove(p + off, key->data, key->size);
902 memmove(p + off, val->data, val->size);
905 sp[n + 2] = OVFLPAGE;
906 FREESPACE(sp) = free_space - PAIRSIZE(key, val);
911 fetch_bitmap(hashp, ndx)
915 if (ndx >= hashp->nmaps)
917 if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
919 if (__get_page(hashp,
920 (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
921 free(hashp->mapp[ndx]);
924 return (hashp->mapp[ndx]);
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;
945 (void)fprintf(stderr, "\n");