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. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * $FreeBSD: src/lib/libc/db/hash/hash_page.c,v 1.5 2000/01/27 23:06:08 jasone Exp $
33 * $DragonFly: src/lib/libc/db/hash/hash_page.c,v 1.8 2005/11/19 20:46:32 swildner Exp $
35 * @(#)hash_page.c 8.7 (Berkeley) 8/16/94
42 * Page manipulation for hashing package.
54 #include "namespace.h"
55 #include <sys/types.h>
67 #include "un-namespace.h"
74 static u_int32_t *fetch_bitmap (HTAB *, int);
75 static u_int32_t first_free (u_int32_t);
76 static int open_temp (HTAB *);
77 static u_int16_t overflow_page (HTAB *);
78 static void putpair (char *, const DBT *, const DBT *);
79 static void squeeze_key (u_int16_t *, const DBT *, const DBT *);
81 (HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int);
83 #define PAGE_INIT(P) { \
84 ((u_int16_t *)(P))[0] = 0; \
85 ((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \
86 ((u_int16_t *)(P))[2] = hashp->BSIZE; \
90 * This is called AFTER we have verified that there is room on the page for
91 * the pair (PAIRFITS has returned true) so we go right ahead and start moving
95 putpair(char *p, const DBT *key, const DBT *val)
97 u_int16_t *bp, n, off;
101 /* Enter the key first. */
104 off = OFFSET(bp) - key->size;
105 memmove(p + off, key->data, key->size);
110 memmove(p + off, val->data, val->size);
113 /* Adjust page info. */
115 bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t));
125 __delpair(HTAB *hashp, BUFHEAD *bufp, int ndx)
127 u_int16_t *bp, newoff;
131 bp = (u_int16_t *)bufp->page;
134 if (bp[ndx + 1] < REAL_KEY)
135 return (__big_delete(hashp, bufp));
137 newoff = bp[ndx - 1];
139 newoff = hashp->BSIZE;
140 pairlen = newoff - bp[ndx + 1];
142 if (ndx != (n - 1)) {
143 /* Hard Case -- need to shuffle keys */
145 char *src = bufp->page + (int)OFFSET(bp);
146 char *dst = src + (int)pairlen;
147 memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
149 /* Now adjust the pointers */
150 for (i = ndx + 2; i <= n; i += 2) {
151 if (bp[i + 1] == OVFLPAGE) {
153 bp[i - 1] = bp[i + 1];
155 bp[i - 2] = bp[i] + pairlen;
156 bp[i - 1] = bp[i + 1] + pairlen;
160 /* Finally adjust the page data */
161 bp[n] = OFFSET(bp) + pairlen;
162 bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t);
166 bufp->flags |= BUF_MOD;
175 __split_page(HTAB *hashp, u_int32_t obucket, u_int32_t nbucket)
177 BUFHEAD *new_bufp, *old_bufp;
182 u_int16_t copyto, diff, off, moved;
185 copyto = (u_int16_t)hashp->BSIZE;
186 off = (u_int16_t)hashp->BSIZE;
187 old_bufp = __get_buf(hashp, obucket, NULL, 0);
188 if (old_bufp == NULL)
190 new_bufp = __get_buf(hashp, nbucket, NULL, 0);
191 if (new_bufp == NULL)
194 old_bufp->flags |= (BUF_MOD | BUF_PIN);
195 new_bufp->flags |= (BUF_MOD | BUF_PIN);
197 ino = (u_int16_t *)(op = old_bufp->page);
202 for (n = 1, ndx = 1; n < ino[0]; n += 2) {
203 if (ino[n + 1] < REAL_KEY) {
204 retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
205 (int)copyto, (int)moved);
206 old_bufp->flags &= ~BUF_PIN;
207 new_bufp->flags &= ~BUF_PIN;
211 key.data = (u_char *)op + ino[n];
212 key.size = off - ino[n];
214 if (__call_hash(hashp, key.data, key.size) == obucket) {
215 /* Don't switch page */
218 copyto = ino[n + 1] + diff;
219 memmove(op + copyto, op + ino[n + 1],
221 ino[ndx] = copyto + ino[n] - ino[n + 1];
222 ino[ndx + 1] = copyto;
228 val.data = (u_char *)op + ino[n + 1];
229 val.size = ino[n] - ino[n + 1];
230 putpair(np, &key, &val);
237 /* Now clean up the page */
239 FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3);
240 OFFSET(ino) = copyto;
243 fprintf(stderr, "split %d/%d\n",
244 ((u_int16_t *)np)[0] / 2,
245 ((u_int16_t *)op)[0] / 2);
247 /* unpin both pages */
248 old_bufp->flags &= ~BUF_PIN;
249 new_bufp->flags &= ~BUF_PIN;
254 * Called when we encounter an overflow or big key/data page during split
255 * handling. This is special cased since we have to begin checking whether
256 * the key/data pairs fit on their respective pages and because we may need
257 * overflow pages for both the old and new pages.
259 * The first page might be a page with regular key/data pairs in which case
260 * we have a regular overflow condition and just need to go on to the next
261 * page or it might be a big key/data pair in which case we need to fix the
265 * obucket - Same as __split_page
266 * copyto - First byte on page which contains key/data values
267 * moved - Number of pairs moved to new page
273 ugly_split(HTAB *hashp, u_int32_t obucket, BUFHEAD *old_bufp,
274 BUFHEAD *new_bufp, int copyto, int moved)
276 BUFHEAD *bufp; /* Buffer header for ino */
277 u_int16_t *ino; /* Page keys come off of */
278 u_int16_t *np; /* New page */
279 u_int16_t *op; /* Page keys go on to if they aren't moving */
281 BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */
284 u_int16_t n, off, ov_addr, scopyto;
285 char *cino; /* Character value of ino */
288 ino = (u_int16_t *)old_bufp->page;
289 np = (u_int16_t *)new_bufp->page;
290 op = (u_int16_t *)old_bufp->page;
292 scopyto = (u_int16_t)copyto; /* ANSI */
296 if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
297 if (__big_split(hashp, old_bufp,
298 new_bufp, bufp, bufp->addr, obucket, &ret))
303 op = (u_int16_t *)old_bufp->page;
307 np = (u_int16_t *)new_bufp->page;
311 cino = (char *)bufp->page;
312 ino = (u_int16_t *)cino;
313 last_bfp = ret.nextp;
314 } else if (ino[n + 1] == OVFLPAGE) {
317 * Fix up the old page -- the extra 2 are the fields
318 * which contained the overflow information.
320 ino[0] -= (moved + 2);
322 scopyto - sizeof(u_int16_t) * (ino[0] + 3);
323 OFFSET(ino) = scopyto;
325 bufp = __get_buf(hashp, ov_addr, bufp, 0);
329 ino = (u_int16_t *)bufp->page;
331 scopyto = hashp->BSIZE;
335 __free_ovflpage(hashp, last_bfp);
338 /* Move regular sized pairs of there are any */
340 for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
342 key.data = (u_char *)cino + ino[n];
343 key.size = off - ino[n];
344 val.data = (u_char *)cino + ino[n + 1];
345 val.size = ino[n] - ino[n + 1];
348 if (__call_hash(hashp, key.data, key.size) == obucket) {
349 /* Keep on old page */
350 if (PAIRFITS(op, (&key), (&val)))
351 putpair((char *)op, &key, &val);
354 __add_ovflpage(hashp, old_bufp);
357 op = (u_int16_t *)old_bufp->page;
358 putpair((char *)op, &key, &val);
360 old_bufp->flags |= BUF_MOD;
362 /* Move to new page */
363 if (PAIRFITS(np, (&key), (&val)))
364 putpair((char *)np, &key, &val);
367 __add_ovflpage(hashp, new_bufp);
370 np = (u_int16_t *)new_bufp->page;
371 putpair((char *)np, &key, &val);
373 new_bufp->flags |= BUF_MOD;
378 __free_ovflpage(hashp, last_bfp);
383 * Add the given pair to the page
390 __addel(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT *val)
395 bp = (u_int16_t *)bufp->page;
397 while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
399 if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
400 /* This is the last page of a big key/data pair
401 and we need to add another page */
403 else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
404 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
407 bp = (u_int16_t *)bufp->page;
409 /* Try to squeeze key on this page */
410 if (FREESPACE(bp) > PAIRSIZE(key, val)) {
411 squeeze_key(bp, key, val);
414 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
417 bp = (u_int16_t *)bufp->page;
420 if (PAIRFITS(bp, key, val))
421 putpair(bufp->page, key, val);
424 bufp = __add_ovflpage(hashp, bufp);
427 sop = (u_int16_t *)bufp->page;
429 if (PAIRFITS(sop, key, val))
430 putpair((char *)sop, key, val);
432 if (__big_insert(hashp, bufp, key, val))
435 bufp->flags |= BUF_MOD;
437 * If the average number of keys per bucket exceeds the fill factor,
442 (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
443 return (__expand_table(hashp));
454 __add_ovflpage(HTAB *hashp, BUFHEAD *bufp)
457 u_int16_t ndx, ovfl_num;
461 sp = (u_int16_t *)bufp->page;
463 /* Check if we are dynamically determining the fill factor */
464 if (hashp->FFACTOR == DEF_FFACTOR) {
465 hashp->FFACTOR = sp[0] >> 1;
466 if (hashp->FFACTOR < MIN_FFACTOR)
467 hashp->FFACTOR = MIN_FFACTOR;
469 bufp->flags |= BUF_MOD;
470 ovfl_num = overflow_page(hashp);
473 tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
475 if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
477 bufp->ovfl->flags |= BUF_MOD;
479 fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
480 tmp1, tmp2, bufp->ovfl->addr);
484 * Since a pair is allocated on a page only if there's room to add
485 * an overflow page, we know that the OVFL information will fit on
488 sp[ndx + 4] = OFFSET(sp);
489 sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
490 sp[ndx + 1] = ovfl_num;
491 sp[ndx + 2] = OVFLPAGE;
493 #ifdef HASH_STATISTICS
501 * 0 indicates SUCCESS
502 * -1 indicates FAILURE
505 __get_page(HTAB *hashp, char *p, u_int32_t bucket, int is_bucket, int is_disk,
515 if ((fd == -1) || !is_disk) {
520 page = BUCKET_TO_PAGE(bucket);
522 page = OADDR_TO_PAGE(bucket);
523 if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
524 ((rsize = _read(fd, p, size)) == -1))
528 bp[0] = 0; /* We hit the EOF, so initialize a new page */
534 if (!is_bitmap && !bp[0]) {
537 if (hashp->LORDER != BYTE_ORDER) {
541 max = hashp->BSIZE >> 2; /* divide by 4 */
542 for (i = 0; i < max; i++)
543 M_32_SWAP(((int *)p)[i]);
547 for (i = 1; i <= max; i++)
555 * Write page p to disk
562 __put_page(HTAB *hashp, char *p, u_int32_t bucket, int is_bucket, int is_bitmap)
568 if ((hashp->fp == -1) && open_temp(hashp))
572 if (hashp->LORDER != BYTE_ORDER) {
577 max = hashp->BSIZE >> 2; /* divide by 4 */
578 for (i = 0; i < max; i++)
579 M_32_SWAP(((int *)p)[i]);
581 max = ((u_int16_t *)p)[0] + 2;
582 for (i = 0; i <= max; i++)
583 M_16_SWAP(((u_int16_t *)p)[i]);
587 page = BUCKET_TO_PAGE(bucket);
589 page = OADDR_TO_PAGE(bucket);
590 if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
591 ((wsize = _write(fd, p, size)) == -1))
601 #define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1)
603 * Initialize a new bitmap page. Bitmap pages are left in memory
604 * once they are read in.
607 __ibitmap(HTAB *hashp, int pnum, int nbits, int ndx)
610 int clearbytes, clearints;
612 if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
615 clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
616 clearbytes = clearints << INT_TO_BYTE;
617 memset((char *)ip, 0, clearbytes);
618 memset(((char *)ip) + clearbytes, 0xFF,
619 hashp->BSIZE - clearbytes);
620 ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
622 hashp->BITMAPS[ndx] = (u_int16_t)pnum;
623 hashp->mapp[ndx] = ip;
628 first_free(u_int32_t map)
633 for (i = 0; i < BITS_PER_MAP; i++) {
642 overflow_page(HTAB *hashp)
645 int max_free, offset, splitnum;
647 int bit, first_page, free_bit, free_page, i, in_use_bits, j;
652 splitnum = hashp->OVFL_POINT;
653 max_free = hashp->SPARES[splitnum];
655 free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
656 free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
658 /* Look through all the free maps to find the first free block */
659 first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
660 for ( i = first_page; i <= free_page; i++ ) {
661 if (!(freep = (u_int32_t *)hashp->mapp[i]) &&
662 !(freep = fetch_bitmap(hashp, i)))
665 in_use_bits = free_bit;
667 in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
669 if (i == first_page) {
670 bit = hashp->LAST_FREED &
671 ((hashp->BSIZE << BYTE_SHIFT) - 1);
672 j = bit / BITS_PER_MAP;
673 bit = bit & ~(BITS_PER_MAP - 1);
678 for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
679 if (freep[j] != ALL_SET)
683 /* No Free Page Found */
684 hashp->LAST_FREED = hashp->SPARES[splitnum];
685 hashp->SPARES[splitnum]++;
686 offset = hashp->SPARES[splitnum] -
687 (splitnum ? hashp->SPARES[splitnum - 1] : 0);
689 #define OVMSG "HASH: Out of overflow pages. Increase page size\n"
690 if (offset > SPLITMASK) {
691 if (++splitnum >= NCACHED) {
692 _write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
695 hashp->OVFL_POINT = splitnum;
696 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
697 hashp->SPARES[splitnum-1]--;
701 /* Check if we need to allocate a new bitmap page */
702 if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
704 if (free_page >= NCACHED) {
705 _write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
709 * This is tricky. The 1 indicates that you want the new page
710 * allocated with 1 clear bit. Actually, you are going to
711 * allocate 2 pages from this map. The first is going to be
712 * the map page, the second is the overflow page we were
713 * looking for. The init_bitmap routine automatically, sets
714 * the first bit of itself to indicate that the bitmap itself
715 * is in use. We would explicitly set the second bit, but
716 * don't have to if we tell init_bitmap not to leave it clear
717 * in the first place.
720 (int)OADDR_OF(splitnum, offset), 1, free_page))
722 hashp->SPARES[splitnum]++;
727 if (offset > SPLITMASK) {
728 if (++splitnum >= NCACHED) {
729 _write(STDERR_FILENO, OVMSG,
733 hashp->OVFL_POINT = splitnum;
734 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
735 hashp->SPARES[splitnum-1]--;
740 * Free_bit addresses the last used bit. Bump it to address
741 * the first available bit.
744 SETBIT(freep, free_bit);
747 /* Calculate address of the new overflow page */
748 addr = OADDR_OF(splitnum, offset);
750 fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
751 addr, free_bit, free_page);
756 bit = bit + first_free(freep[j]);
763 * Bits are addressed starting with 0, but overflow pages are addressed
764 * beginning at 1. Bit is a bit addressnumber, so we need to increment
765 * it to convert it to a page number.
767 bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
768 if (bit >= hashp->LAST_FREED)
769 hashp->LAST_FREED = bit - 1;
771 /* Calculate the split number for this page */
772 for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
773 offset = (i ? bit - hashp->SPARES[i - 1] : bit);
774 if (offset >= SPLITMASK)
775 return (0); /* Out of overflow pages */
776 addr = OADDR_OF(i, offset);
778 fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
782 /* Allocate and return the overflow page */
787 * Mark this overflow page as free.
790 __free_ovflpage(HTAB *hashp, BUFHEAD *obufp)
794 int bit_address, free_page, free_bit;
799 fprintf(stderr, "Freeing %d\n", addr);
801 ndx = (((u_int16_t)addr) >> SPLITSHIFT);
803 (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
804 if (bit_address < hashp->LAST_FREED)
805 hashp->LAST_FREED = bit_address;
806 free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
807 free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
809 if (!(freep = hashp->mapp[free_page]))
810 freep = fetch_bitmap(hashp, free_page);
813 * This had better never happen. It means we tried to read a bitmap
814 * that has already had overflow pages allocated off it, and we
815 * failed to read it from the file.
820 CLRBIT(freep, free_bit);
822 fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
823 obufp->addr, free_bit, free_page);
825 __reclaim_buf(hashp, obufp);
834 open_temp(HTAB *hashp)
837 static char namestr[] = "_hashXXXXXX";
839 /* Block signals; make sure file goes away at process exit. */
841 _sigprocmask(SIG_BLOCK, &set, &oset);
842 if ((hashp->fp = mkstemp(namestr)) != -1) {
844 _fcntl(hashp->fp, F_SETFD, 1);
846 _sigprocmask(SIG_SETMASK, &oset, NULL);
847 return (hashp->fp != -1 ? 0 : -1);
851 * We have to know that the key will fit, but the last entry on the page is
852 * an overflow pair, so we need to shift things.
855 squeeze_key(u_int16_t *sp, const DBT *key, const DBT *val)
858 u_int16_t free_space, n, off, pageno;
862 free_space = FREESPACE(sp);
868 memmove(p + off, key->data, key->size);
871 memmove(p + off, val->data, val->size);
874 sp[n + 2] = OVFLPAGE;
875 FREESPACE(sp) = free_space - PAIRSIZE(key, val);
880 fetch_bitmap(HTAB *hashp, int ndx)
882 if (ndx >= hashp->nmaps)
884 if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
886 if (__get_page(hashp,
887 (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
888 free(hashp->mapp[ndx]);
891 return (hashp->mapp[ndx]);
896 print_chain(int addr)
901 fprintf(stderr, "%d ", addr);
902 bufp = __get_buf(hashp, addr, NULL, 0);
903 bp = (short *)bufp->page;
904 while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
905 ((bp[0] > 2) && bp[2] < REAL_KEY))) {
906 oaddr = bp[bp[0] - 1];
907 fprintf(stderr, "%d ", (int)oaddr);
908 bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
909 bp = (short *)bufp->page;
911 fprintf(stderr, "\n");