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.3 2003/11/12 20:21:23 eirikn Exp $
39 * @(#)hash_page.c 8.7 (Berkeley) 8/16/94
46 * Page manipulation for hashing package.
58 #include <sys/types.h>
76 static u_int32_t *fetch_bitmap (HTAB *, int);
77 static u_int32_t first_free (u_int32_t);
78 static int open_temp (HTAB *);
79 static u_int16_t overflow_page (HTAB *);
80 static void putpair (char *, const DBT *, const DBT *);
81 static void squeeze_key (u_int16_t *, const DBT *, const DBT *);
83 (HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int);
85 #define PAGE_INIT(P) { \
86 ((u_int16_t *)(P))[0] = 0; \
87 ((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \
88 ((u_int16_t *)(P))[2] = hashp->BSIZE; \
92 * This is called AFTER we have verified that there is room on the page for
93 * the pair (PAIRFITS has returned true) so we go right ahead and start moving
101 register u_int16_t *bp, n, off;
105 /* Enter the key first. */
108 off = OFFSET(bp) - key->size;
109 memmove(p + off, key->data, key->size);
114 memmove(p + off, val->data, val->size);
117 /* Adjust page info. */
119 bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t));
129 __delpair(hashp, bufp, ndx)
134 register u_int16_t *bp, newoff;
138 bp = (u_int16_t *)bufp->page;
141 if (bp[ndx + 1] < REAL_KEY)
142 return (__big_delete(hashp, bufp));
144 newoff = bp[ndx - 1];
146 newoff = hashp->BSIZE;
147 pairlen = newoff - bp[ndx + 1];
149 if (ndx != (n - 1)) {
150 /* Hard Case -- need to shuffle keys */
152 register char *src = bufp->page + (int)OFFSET(bp);
153 register char *dst = src + (int)pairlen;
154 memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
156 /* Now adjust the pointers */
157 for (i = ndx + 2; i <= n; i += 2) {
158 if (bp[i + 1] == OVFLPAGE) {
160 bp[i - 1] = bp[i + 1];
162 bp[i - 2] = bp[i] + pairlen;
163 bp[i - 1] = bp[i + 1] + pairlen;
167 /* Finally adjust the page data */
168 bp[n] = OFFSET(bp) + pairlen;
169 bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t);
173 bufp->flags |= BUF_MOD;
182 __split_page(hashp, obucket, nbucket)
184 u_int32_t obucket, nbucket;
186 register BUFHEAD *new_bufp, *old_bufp;
187 register u_int16_t *ino;
191 u_int16_t copyto, diff, off, moved;
194 copyto = (u_int16_t)hashp->BSIZE;
195 off = (u_int16_t)hashp->BSIZE;
196 old_bufp = __get_buf(hashp, obucket, NULL, 0);
197 if (old_bufp == NULL)
199 new_bufp = __get_buf(hashp, nbucket, NULL, 0);
200 if (new_bufp == NULL)
203 old_bufp->flags |= (BUF_MOD | BUF_PIN);
204 new_bufp->flags |= (BUF_MOD | BUF_PIN);
206 ino = (u_int16_t *)(op = old_bufp->page);
211 for (n = 1, ndx = 1; n < ino[0]; n += 2) {
212 if (ino[n + 1] < REAL_KEY) {
213 retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
214 (int)copyto, (int)moved);
215 old_bufp->flags &= ~BUF_PIN;
216 new_bufp->flags &= ~BUF_PIN;
220 key.data = (u_char *)op + ino[n];
221 key.size = off - ino[n];
223 if (__call_hash(hashp, key.data, key.size) == obucket) {
224 /* Don't switch page */
227 copyto = ino[n + 1] + diff;
228 memmove(op + copyto, op + ino[n + 1],
230 ino[ndx] = copyto + ino[n] - ino[n + 1];
231 ino[ndx + 1] = copyto;
237 val.data = (u_char *)op + ino[n + 1];
238 val.size = ino[n] - ino[n + 1];
239 putpair(np, &key, &val);
246 /* Now clean up the page */
248 FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3);
249 OFFSET(ino) = copyto;
252 (void)fprintf(stderr, "split %d/%d\n",
253 ((u_int16_t *)np)[0] / 2,
254 ((u_int16_t *)op)[0] / 2);
256 /* unpin both pages */
257 old_bufp->flags &= ~BUF_PIN;
258 new_bufp->flags &= ~BUF_PIN;
263 * Called when we encounter an overflow or big key/data page during split
264 * handling. This is special cased since we have to begin checking whether
265 * the key/data pairs fit on their respective pages and because we may need
266 * overflow pages for both the old and new pages.
268 * The first page might be a page with regular key/data pairs in which case
269 * we have a regular overflow condition and just need to go on to the next
270 * page or it might be a big key/data pair in which case we need to fix the
278 ugly_split(hashp, obucket, old_bufp, new_bufp, copyto, moved)
280 u_int32_t obucket; /* Same as __split_page. */
281 BUFHEAD *old_bufp, *new_bufp;
282 int copyto; /* First byte on page which contains key/data values. */
283 int moved; /* Number of pairs moved to new page. */
285 register BUFHEAD *bufp; /* Buffer header for ino */
286 register u_int16_t *ino; /* Page keys come off of */
287 register u_int16_t *np; /* New page */
288 register u_int16_t *op; /* Page keys go on to if they aren't moving */
290 BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */
293 u_int16_t n, off, ov_addr, scopyto;
294 char *cino; /* Character value of ino */
297 ino = (u_int16_t *)old_bufp->page;
298 np = (u_int16_t *)new_bufp->page;
299 op = (u_int16_t *)old_bufp->page;
301 scopyto = (u_int16_t)copyto; /* ANSI */
305 if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
306 if (__big_split(hashp, old_bufp,
307 new_bufp, bufp, bufp->addr, obucket, &ret))
312 op = (u_int16_t *)old_bufp->page;
316 np = (u_int16_t *)new_bufp->page;
320 cino = (char *)bufp->page;
321 ino = (u_int16_t *)cino;
322 last_bfp = ret.nextp;
323 } else if (ino[n + 1] == OVFLPAGE) {
326 * Fix up the old page -- the extra 2 are the fields
327 * which contained the overflow information.
329 ino[0] -= (moved + 2);
331 scopyto - sizeof(u_int16_t) * (ino[0] + 3);
332 OFFSET(ino) = scopyto;
334 bufp = __get_buf(hashp, ov_addr, bufp, 0);
338 ino = (u_int16_t *)bufp->page;
340 scopyto = hashp->BSIZE;
344 __free_ovflpage(hashp, last_bfp);
347 /* Move regular sized pairs of there are any */
349 for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
351 key.data = (u_char *)cino + ino[n];
352 key.size = off - ino[n];
353 val.data = (u_char *)cino + ino[n + 1];
354 val.size = ino[n] - ino[n + 1];
357 if (__call_hash(hashp, key.data, key.size) == obucket) {
358 /* Keep on old page */
359 if (PAIRFITS(op, (&key), (&val)))
360 putpair((char *)op, &key, &val);
363 __add_ovflpage(hashp, old_bufp);
366 op = (u_int16_t *)old_bufp->page;
367 putpair((char *)op, &key, &val);
369 old_bufp->flags |= BUF_MOD;
371 /* Move to new page */
372 if (PAIRFITS(np, (&key), (&val)))
373 putpair((char *)np, &key, &val);
376 __add_ovflpage(hashp, new_bufp);
379 np = (u_int16_t *)new_bufp->page;
380 putpair((char *)np, &key, &val);
382 new_bufp->flags |= BUF_MOD;
387 __free_ovflpage(hashp, last_bfp);
392 * Add the given pair to the page
399 __addel(hashp, bufp, key, val)
402 const DBT *key, *val;
404 register u_int16_t *bp, *sop;
407 bp = (u_int16_t *)bufp->page;
409 while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
411 if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
412 /* This is the last page of a big key/data pair
413 and we need to add another page */
415 else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
416 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
419 bp = (u_int16_t *)bufp->page;
421 /* Try to squeeze key on this page */
422 if (FREESPACE(bp) > PAIRSIZE(key, val)) {
423 squeeze_key(bp, key, val);
426 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
429 bp = (u_int16_t *)bufp->page;
432 if (PAIRFITS(bp, key, val))
433 putpair(bufp->page, key, val);
436 bufp = __add_ovflpage(hashp, bufp);
439 sop = (u_int16_t *)bufp->page;
441 if (PAIRFITS(sop, key, val))
442 putpair((char *)sop, key, val);
444 if (__big_insert(hashp, bufp, key, val))
447 bufp->flags |= BUF_MOD;
449 * If the average number of keys per bucket exceeds the fill factor,
454 (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
455 return (__expand_table(hashp));
466 __add_ovflpage(hashp, bufp)
470 register u_int16_t *sp;
471 u_int16_t ndx, ovfl_num;
475 sp = (u_int16_t *)bufp->page;
477 /* Check if we are dynamically determining the fill factor */
478 if (hashp->FFACTOR == DEF_FFACTOR) {
479 hashp->FFACTOR = sp[0] >> 1;
480 if (hashp->FFACTOR < MIN_FFACTOR)
481 hashp->FFACTOR = MIN_FFACTOR;
483 bufp->flags |= BUF_MOD;
484 ovfl_num = overflow_page(hashp);
487 tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
489 if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
491 bufp->ovfl->flags |= BUF_MOD;
493 (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
494 tmp1, tmp2, bufp->ovfl->addr);
498 * Since a pair is allocated on a page only if there's room to add
499 * an overflow page, we know that the OVFL information will fit on
502 sp[ndx + 4] = OFFSET(sp);
503 sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
504 sp[ndx + 1] = ovfl_num;
505 sp[ndx + 2] = OVFLPAGE;
507 #ifdef HASH_STATISTICS
515 * 0 indicates SUCCESS
516 * -1 indicates FAILURE
519 __get_page(hashp, p, bucket, is_bucket, is_disk, is_bitmap)
523 int is_bucket, is_disk, is_bitmap;
525 register int fd, page, size;
532 if ((fd == -1) || !is_disk) {
537 page = BUCKET_TO_PAGE(bucket);
539 page = OADDR_TO_PAGE(bucket);
540 if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
541 ((rsize = _read(fd, p, size)) == -1))
545 bp[0] = 0; /* We hit the EOF, so initialize a new page */
551 if (!is_bitmap && !bp[0]) {
554 if (hashp->LORDER != BYTE_ORDER) {
558 max = hashp->BSIZE >> 2; /* divide by 4 */
559 for (i = 0; i < max; i++)
560 M_32_SWAP(((int *)p)[i]);
564 for (i = 1; i <= max; i++)
572 * Write page p to disk
579 __put_page(hashp, p, bucket, is_bucket, is_bitmap)
583 int is_bucket, is_bitmap;
585 register int fd, page, size;
589 if ((hashp->fp == -1) && open_temp(hashp))
593 if (hashp->LORDER != BYTE_ORDER) {
598 max = hashp->BSIZE >> 2; /* divide by 4 */
599 for (i = 0; i < max; i++)
600 M_32_SWAP(((int *)p)[i]);
602 max = ((u_int16_t *)p)[0] + 2;
603 for (i = 0; i <= max; i++)
604 M_16_SWAP(((u_int16_t *)p)[i]);
608 page = BUCKET_TO_PAGE(bucket);
610 page = OADDR_TO_PAGE(bucket);
611 if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
612 ((wsize = _write(fd, p, size)) == -1))
622 #define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1)
624 * Initialize a new bitmap page. Bitmap pages are left in memory
625 * once they are read in.
628 __ibitmap(hashp, pnum, nbits, ndx)
630 int pnum, nbits, ndx;
633 int clearbytes, clearints;
635 if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
638 clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
639 clearbytes = clearints << INT_TO_BYTE;
640 (void)memset((char *)ip, 0, clearbytes);
641 (void)memset(((char *)ip) + clearbytes, 0xFF,
642 hashp->BSIZE - clearbytes);
643 ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
645 hashp->BITMAPS[ndx] = (u_int16_t)pnum;
646 hashp->mapp[ndx] = ip;
654 register u_int32_t i, mask;
657 for (i = 0; i < BITS_PER_MAP; i++) {
669 register u_int32_t *freep;
670 register int max_free, offset, splitnum;
672 int bit, first_page, free_bit, free_page, i, in_use_bits, j;
676 splitnum = hashp->OVFL_POINT;
677 max_free = hashp->SPARES[splitnum];
679 free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
680 free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
682 /* Look through all the free maps to find the first free block */
683 first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
684 for ( i = first_page; i <= free_page; i++ ) {
685 if (!(freep = (u_int32_t *)hashp->mapp[i]) &&
686 !(freep = fetch_bitmap(hashp, i)))
689 in_use_bits = free_bit;
691 in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
693 if (i == first_page) {
694 bit = hashp->LAST_FREED &
695 ((hashp->BSIZE << BYTE_SHIFT) - 1);
696 j = bit / BITS_PER_MAP;
697 bit = bit & ~(BITS_PER_MAP - 1);
702 for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
703 if (freep[j] != ALL_SET)
707 /* No Free Page Found */
708 hashp->LAST_FREED = hashp->SPARES[splitnum];
709 hashp->SPARES[splitnum]++;
710 offset = hashp->SPARES[splitnum] -
711 (splitnum ? hashp->SPARES[splitnum - 1] : 0);
713 #define OVMSG "HASH: Out of overflow pages. Increase page size\n"
714 if (offset > SPLITMASK) {
715 if (++splitnum >= NCACHED) {
716 (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
719 hashp->OVFL_POINT = splitnum;
720 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
721 hashp->SPARES[splitnum-1]--;
725 /* Check if we need to allocate a new bitmap page */
726 if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
728 if (free_page >= NCACHED) {
729 (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
733 * This is tricky. The 1 indicates that you want the new page
734 * allocated with 1 clear bit. Actually, you are going to
735 * allocate 2 pages from this map. The first is going to be
736 * the map page, the second is the overflow page we were
737 * looking for. The init_bitmap routine automatically, sets
738 * the first bit of itself to indicate that the bitmap itself
739 * is in use. We would explicitly set the second bit, but
740 * don't have to if we tell init_bitmap not to leave it clear
741 * in the first place.
744 (int)OADDR_OF(splitnum, offset), 1, free_page))
746 hashp->SPARES[splitnum]++;
751 if (offset > SPLITMASK) {
752 if (++splitnum >= NCACHED) {
753 (void)_write(STDERR_FILENO, OVMSG,
757 hashp->OVFL_POINT = splitnum;
758 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
759 hashp->SPARES[splitnum-1]--;
764 * Free_bit addresses the last used bit. Bump it to address
765 * the first available bit.
768 SETBIT(freep, free_bit);
771 /* Calculate address of the new overflow page */
772 addr = OADDR_OF(splitnum, offset);
774 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
775 addr, free_bit, free_page);
780 bit = bit + first_free(freep[j]);
787 * Bits are addressed starting with 0, but overflow pages are addressed
788 * beginning at 1. Bit is a bit addressnumber, so we need to increment
789 * it to convert it to a page number.
791 bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
792 if (bit >= hashp->LAST_FREED)
793 hashp->LAST_FREED = bit - 1;
795 /* Calculate the split number for this page */
796 for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
797 offset = (i ? bit - hashp->SPARES[i - 1] : bit);
798 if (offset >= SPLITMASK)
799 return (0); /* Out of overflow pages */
800 addr = OADDR_OF(i, offset);
802 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
806 /* Allocate and return the overflow page */
811 * Mark this overflow page as free.
814 __free_ovflpage(hashp, obufp)
818 register u_int16_t addr;
820 int bit_address, free_page, free_bit;
825 (void)fprintf(stderr, "Freeing %d\n", addr);
827 ndx = (((u_int16_t)addr) >> SPLITSHIFT);
829 (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
830 if (bit_address < hashp->LAST_FREED)
831 hashp->LAST_FREED = bit_address;
832 free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
833 free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
835 if (!(freep = hashp->mapp[free_page]))
836 freep = fetch_bitmap(hashp, free_page);
839 * This had better never happen. It means we tried to read a bitmap
840 * that has already had overflow pages allocated off it, and we
841 * failed to read it from the file.
846 CLRBIT(freep, free_bit);
848 (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
849 obufp->addr, free_bit, free_page);
851 __reclaim_buf(hashp, obufp);
864 static char namestr[] = "_hashXXXXXX";
866 /* Block signals; make sure file goes away at process exit. */
867 (void)sigfillset(&set);
868 (void)sigprocmask(SIG_BLOCK, &set, &oset);
869 if ((hashp->fp = mkstemp(namestr)) != -1) {
870 (void)unlink(namestr);
871 (void)_fcntl(hashp->fp, F_SETFD, 1);
873 (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
874 return (hashp->fp != -1 ? 0 : -1);
878 * We have to know that the key will fit, but the last entry on the page is
879 * an overflow pair, so we need to shift things.
882 squeeze_key(sp, key, val)
884 const DBT *key, *val;
887 u_int16_t free_space, n, off, pageno;
891 free_space = FREESPACE(sp);
897 memmove(p + off, key->data, key->size);
900 memmove(p + off, val->data, val->size);
903 sp[n + 2] = OVFLPAGE;
904 FREESPACE(sp) = free_space - PAIRSIZE(key, val);
909 fetch_bitmap(hashp, ndx)
913 if (ndx >= hashp->nmaps)
915 if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
917 if (__get_page(hashp,
918 (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
919 free(hashp->mapp[ndx]);
922 return (hashp->mapp[ndx]);
933 (void)fprintf(stderr, "%d ", addr);
934 bufp = __get_buf(hashp, addr, NULL, 0);
935 bp = (short *)bufp->page;
936 while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
937 ((bp[0] > 2) && bp[2] < REAL_KEY))) {
938 oaddr = bp[bp[0] - 1];
939 (void)fprintf(stderr, "%d ", (int)oaddr);
940 bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
941 bp = (short *)bufp->page;
943 (void)fprintf(stderr, "\n");