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 $
39 #if defined(LIBC_SCCS) && !defined(lint)
40 static char sccsid[] = "@(#)hash_page.c 8.7 (Berkeley) 8/16/94";
41 #endif /* LIBC_SCCS and not lint */
47 * Page manipulation for hashing package.
59 #include <sys/types.h>
77 static u_int32_t *fetch_bitmap __P((HTAB *, int));
78 static u_int32_t first_free __P((u_int32_t));
79 static int open_temp __P((HTAB *));
80 static u_int16_t overflow_page __P((HTAB *));
81 static void putpair __P((char *, const DBT *, const DBT *));
82 static void squeeze_key __P((u_int16_t *, const DBT *, const DBT *));
84 __P((HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int));
86 #define PAGE_INIT(P) { \
87 ((u_int16_t *)(P))[0] = 0; \
88 ((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \
89 ((u_int16_t *)(P))[2] = hashp->BSIZE; \
93 * This is called AFTER we have verified that there is room on the page for
94 * the pair (PAIRFITS has returned true) so we go right ahead and start moving
100 const DBT *key, *val;
102 register u_int16_t *bp, n, off;
106 /* Enter the key first. */
109 off = OFFSET(bp) - key->size;
110 memmove(p + off, key->data, key->size);
115 memmove(p + off, val->data, val->size);
118 /* Adjust page info. */
120 bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t));
130 __delpair(hashp, bufp, ndx)
135 register u_int16_t *bp, newoff;
139 bp = (u_int16_t *)bufp->page;
142 if (bp[ndx + 1] < REAL_KEY)
143 return (__big_delete(hashp, bufp));
145 newoff = bp[ndx - 1];
147 newoff = hashp->BSIZE;
148 pairlen = newoff - bp[ndx + 1];
150 if (ndx != (n - 1)) {
151 /* Hard Case -- need to shuffle keys */
153 register char *src = bufp->page + (int)OFFSET(bp);
154 register char *dst = src + (int)pairlen;
155 memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
157 /* Now adjust the pointers */
158 for (i = ndx + 2; i <= n; i += 2) {
159 if (bp[i + 1] == OVFLPAGE) {
161 bp[i - 1] = bp[i + 1];
163 bp[i - 2] = bp[i] + pairlen;
164 bp[i - 1] = bp[i + 1] + pairlen;
168 /* Finally adjust the page data */
169 bp[n] = OFFSET(bp) + pairlen;
170 bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t);
174 bufp->flags |= BUF_MOD;
183 __split_page(hashp, obucket, nbucket)
185 u_int32_t obucket, nbucket;
187 register BUFHEAD *new_bufp, *old_bufp;
188 register u_int16_t *ino;
192 u_int16_t copyto, diff, off, moved;
195 copyto = (u_int16_t)hashp->BSIZE;
196 off = (u_int16_t)hashp->BSIZE;
197 old_bufp = __get_buf(hashp, obucket, NULL, 0);
198 if (old_bufp == NULL)
200 new_bufp = __get_buf(hashp, nbucket, NULL, 0);
201 if (new_bufp == NULL)
204 old_bufp->flags |= (BUF_MOD | BUF_PIN);
205 new_bufp->flags |= (BUF_MOD | BUF_PIN);
207 ino = (u_int16_t *)(op = old_bufp->page);
212 for (n = 1, ndx = 1; n < ino[0]; n += 2) {
213 if (ino[n + 1] < REAL_KEY) {
214 retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
215 (int)copyto, (int)moved);
216 old_bufp->flags &= ~BUF_PIN;
217 new_bufp->flags &= ~BUF_PIN;
221 key.data = (u_char *)op + ino[n];
222 key.size = off - ino[n];
224 if (__call_hash(hashp, key.data, key.size) == obucket) {
225 /* Don't switch page */
228 copyto = ino[n + 1] + diff;
229 memmove(op + copyto, op + ino[n + 1],
231 ino[ndx] = copyto + ino[n] - ino[n + 1];
232 ino[ndx + 1] = copyto;
238 val.data = (u_char *)op + ino[n + 1];
239 val.size = ino[n] - ino[n + 1];
240 putpair(np, &key, &val);
247 /* Now clean up the page */
249 FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3);
250 OFFSET(ino) = copyto;
253 (void)fprintf(stderr, "split %d/%d\n",
254 ((u_int16_t *)np)[0] / 2,
255 ((u_int16_t *)op)[0] / 2);
257 /* unpin both pages */
258 old_bufp->flags &= ~BUF_PIN;
259 new_bufp->flags &= ~BUF_PIN;
264 * Called when we encounter an overflow or big key/data page during split
265 * handling. This is special cased since we have to begin checking whether
266 * the key/data pairs fit on their respective pages and because we may need
267 * overflow pages for both the old and new pages.
269 * The first page might be a page with regular key/data pairs in which case
270 * we have a regular overflow condition and just need to go on to the next
271 * page or it might be a big key/data pair in which case we need to fix the
279 ugly_split(hashp, obucket, old_bufp, new_bufp, copyto, moved)
281 u_int32_t obucket; /* Same as __split_page. */
282 BUFHEAD *old_bufp, *new_bufp;
283 int copyto; /* First byte on page which contains key/data values. */
284 int moved; /* Number of pairs moved to new page. */
286 register BUFHEAD *bufp; /* Buffer header for ino */
287 register u_int16_t *ino; /* Page keys come off of */
288 register u_int16_t *np; /* New page */
289 register u_int16_t *op; /* Page keys go on to if they aren't moving */
291 BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */
294 u_int16_t n, off, ov_addr, scopyto;
295 char *cino; /* Character value of ino */
298 ino = (u_int16_t *)old_bufp->page;
299 np = (u_int16_t *)new_bufp->page;
300 op = (u_int16_t *)old_bufp->page;
302 scopyto = (u_int16_t)copyto; /* ANSI */
306 if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
307 if (__big_split(hashp, old_bufp,
308 new_bufp, bufp, bufp->addr, obucket, &ret))
313 op = (u_int16_t *)old_bufp->page;
317 np = (u_int16_t *)new_bufp->page;
321 cino = (char *)bufp->page;
322 ino = (u_int16_t *)cino;
323 last_bfp = ret.nextp;
324 } else if (ino[n + 1] == OVFLPAGE) {
327 * Fix up the old page -- the extra 2 are the fields
328 * which contained the overflow information.
330 ino[0] -= (moved + 2);
332 scopyto - sizeof(u_int16_t) * (ino[0] + 3);
333 OFFSET(ino) = scopyto;
335 bufp = __get_buf(hashp, ov_addr, bufp, 0);
339 ino = (u_int16_t *)bufp->page;
341 scopyto = hashp->BSIZE;
345 __free_ovflpage(hashp, last_bfp);
348 /* Move regular sized pairs of there are any */
350 for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
352 key.data = (u_char *)cino + ino[n];
353 key.size = off - ino[n];
354 val.data = (u_char *)cino + ino[n + 1];
355 val.size = ino[n] - ino[n + 1];
358 if (__call_hash(hashp, key.data, key.size) == obucket) {
359 /* Keep on old page */
360 if (PAIRFITS(op, (&key), (&val)))
361 putpair((char *)op, &key, &val);
364 __add_ovflpage(hashp, old_bufp);
367 op = (u_int16_t *)old_bufp->page;
368 putpair((char *)op, &key, &val);
370 old_bufp->flags |= BUF_MOD;
372 /* Move to new page */
373 if (PAIRFITS(np, (&key), (&val)))
374 putpair((char *)np, &key, &val);
377 __add_ovflpage(hashp, new_bufp);
380 np = (u_int16_t *)new_bufp->page;
381 putpair((char *)np, &key, &val);
383 new_bufp->flags |= BUF_MOD;
388 __free_ovflpage(hashp, last_bfp);
393 * Add the given pair to the page
400 __addel(hashp, bufp, key, val)
403 const DBT *key, *val;
405 register u_int16_t *bp, *sop;
408 bp = (u_int16_t *)bufp->page;
410 while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
412 if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
413 /* This is the last page of a big key/data pair
414 and we need to add another page */
416 else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
417 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
420 bp = (u_int16_t *)bufp->page;
422 /* Try to squeeze key on this page */
423 if (FREESPACE(bp) > PAIRSIZE(key, val)) {
424 squeeze_key(bp, key, val);
427 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
430 bp = (u_int16_t *)bufp->page;
433 if (PAIRFITS(bp, key, val))
434 putpair(bufp->page, key, val);
437 bufp = __add_ovflpage(hashp, bufp);
440 sop = (u_int16_t *)bufp->page;
442 if (PAIRFITS(sop, key, val))
443 putpair((char *)sop, key, val);
445 if (__big_insert(hashp, bufp, key, val))
448 bufp->flags |= BUF_MOD;
450 * If the average number of keys per bucket exceeds the fill factor,
455 (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
456 return (__expand_table(hashp));
467 __add_ovflpage(hashp, bufp)
471 register u_int16_t *sp;
472 u_int16_t ndx, ovfl_num;
476 sp = (u_int16_t *)bufp->page;
478 /* Check if we are dynamically determining the fill factor */
479 if (hashp->FFACTOR == DEF_FFACTOR) {
480 hashp->FFACTOR = sp[0] >> 1;
481 if (hashp->FFACTOR < MIN_FFACTOR)
482 hashp->FFACTOR = MIN_FFACTOR;
484 bufp->flags |= BUF_MOD;
485 ovfl_num = overflow_page(hashp);
488 tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
490 if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
492 bufp->ovfl->flags |= BUF_MOD;
494 (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
495 tmp1, tmp2, bufp->ovfl->addr);
499 * Since a pair is allocated on a page only if there's room to add
500 * an overflow page, we know that the OVFL information will fit on
503 sp[ndx + 4] = OFFSET(sp);
504 sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
505 sp[ndx + 1] = ovfl_num;
506 sp[ndx + 2] = OVFLPAGE;
508 #ifdef HASH_STATISTICS
516 * 0 indicates SUCCESS
517 * -1 indicates FAILURE
520 __get_page(hashp, p, bucket, is_bucket, is_disk, is_bitmap)
524 int is_bucket, is_disk, is_bitmap;
526 register int fd, page, size;
533 if ((fd == -1) || !is_disk) {
538 page = BUCKET_TO_PAGE(bucket);
540 page = OADDR_TO_PAGE(bucket);
541 if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
542 ((rsize = _read(fd, p, size)) == -1))
546 bp[0] = 0; /* We hit the EOF, so initialize a new page */
552 if (!is_bitmap && !bp[0]) {
555 if (hashp->LORDER != BYTE_ORDER) {
559 max = hashp->BSIZE >> 2; /* divide by 4 */
560 for (i = 0; i < max; i++)
561 M_32_SWAP(((int *)p)[i]);
565 for (i = 1; i <= max; i++)
573 * Write page p to disk
580 __put_page(hashp, p, bucket, is_bucket, is_bitmap)
584 int is_bucket, is_bitmap;
586 register int fd, page, size;
590 if ((hashp->fp == -1) && open_temp(hashp))
594 if (hashp->LORDER != BYTE_ORDER) {
599 max = hashp->BSIZE >> 2; /* divide by 4 */
600 for (i = 0; i < max; i++)
601 M_32_SWAP(((int *)p)[i]);
603 max = ((u_int16_t *)p)[0] + 2;
604 for (i = 0; i <= max; i++)
605 M_16_SWAP(((u_int16_t *)p)[i]);
609 page = BUCKET_TO_PAGE(bucket);
611 page = OADDR_TO_PAGE(bucket);
612 if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
613 ((wsize = _write(fd, p, size)) == -1))
623 #define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1)
625 * Initialize a new bitmap page. Bitmap pages are left in memory
626 * once they are read in.
629 __ibitmap(hashp, pnum, nbits, ndx)
631 int pnum, nbits, ndx;
634 int clearbytes, clearints;
636 if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
639 clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
640 clearbytes = clearints << INT_TO_BYTE;
641 (void)memset((char *)ip, 0, clearbytes);
642 (void)memset(((char *)ip) + clearbytes, 0xFF,
643 hashp->BSIZE - clearbytes);
644 ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
646 hashp->BITMAPS[ndx] = (u_int16_t)pnum;
647 hashp->mapp[ndx] = ip;
655 register u_int32_t i, mask;
658 for (i = 0; i < BITS_PER_MAP; i++) {
670 register u_int32_t *freep;
671 register int max_free, offset, splitnum;
673 int bit, first_page, free_bit, free_page, i, in_use_bits, j;
677 splitnum = hashp->OVFL_POINT;
678 max_free = hashp->SPARES[splitnum];
680 free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
681 free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
683 /* Look through all the free maps to find the first free block */
684 first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
685 for ( i = first_page; i <= free_page; i++ ) {
686 if (!(freep = (u_int32_t *)hashp->mapp[i]) &&
687 !(freep = fetch_bitmap(hashp, i)))
690 in_use_bits = free_bit;
692 in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
694 if (i == first_page) {
695 bit = hashp->LAST_FREED &
696 ((hashp->BSIZE << BYTE_SHIFT) - 1);
697 j = bit / BITS_PER_MAP;
698 bit = bit & ~(BITS_PER_MAP - 1);
703 for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
704 if (freep[j] != ALL_SET)
708 /* No Free Page Found */
709 hashp->LAST_FREED = hashp->SPARES[splitnum];
710 hashp->SPARES[splitnum]++;
711 offset = hashp->SPARES[splitnum] -
712 (splitnum ? hashp->SPARES[splitnum - 1] : 0);
714 #define OVMSG "HASH: Out of overflow pages. Increase page size\n"
715 if (offset > SPLITMASK) {
716 if (++splitnum >= NCACHED) {
717 (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
720 hashp->OVFL_POINT = splitnum;
721 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
722 hashp->SPARES[splitnum-1]--;
726 /* Check if we need to allocate a new bitmap page */
727 if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
729 if (free_page >= NCACHED) {
730 (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
734 * This is tricky. The 1 indicates that you want the new page
735 * allocated with 1 clear bit. Actually, you are going to
736 * allocate 2 pages from this map. The first is going to be
737 * the map page, the second is the overflow page we were
738 * looking for. The init_bitmap routine automatically, sets
739 * the first bit of itself to indicate that the bitmap itself
740 * is in use. We would explicitly set the second bit, but
741 * don't have to if we tell init_bitmap not to leave it clear
742 * in the first place.
745 (int)OADDR_OF(splitnum, offset), 1, free_page))
747 hashp->SPARES[splitnum]++;
752 if (offset > SPLITMASK) {
753 if (++splitnum >= NCACHED) {
754 (void)_write(STDERR_FILENO, OVMSG,
758 hashp->OVFL_POINT = splitnum;
759 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
760 hashp->SPARES[splitnum-1]--;
765 * Free_bit addresses the last used bit. Bump it to address
766 * the first available bit.
769 SETBIT(freep, free_bit);
772 /* Calculate address of the new overflow page */
773 addr = OADDR_OF(splitnum, offset);
775 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
776 addr, free_bit, free_page);
781 bit = bit + first_free(freep[j]);
788 * Bits are addressed starting with 0, but overflow pages are addressed
789 * beginning at 1. Bit is a bit addressnumber, so we need to increment
790 * it to convert it to a page number.
792 bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
793 if (bit >= hashp->LAST_FREED)
794 hashp->LAST_FREED = bit - 1;
796 /* Calculate the split number for this page */
797 for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
798 offset = (i ? bit - hashp->SPARES[i - 1] : bit);
799 if (offset >= SPLITMASK)
800 return (0); /* Out of overflow pages */
801 addr = OADDR_OF(i, offset);
803 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
807 /* Allocate and return the overflow page */
812 * Mark this overflow page as free.
815 __free_ovflpage(hashp, obufp)
819 register u_int16_t addr;
821 int bit_address, free_page, free_bit;
826 (void)fprintf(stderr, "Freeing %d\n", addr);
828 ndx = (((u_int16_t)addr) >> SPLITSHIFT);
830 (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
831 if (bit_address < hashp->LAST_FREED)
832 hashp->LAST_FREED = bit_address;
833 free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
834 free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
836 if (!(freep = hashp->mapp[free_page]))
837 freep = fetch_bitmap(hashp, free_page);
840 * This had better never happen. It means we tried to read a bitmap
841 * that has already had overflow pages allocated off it, and we
842 * failed to read it from the file.
847 CLRBIT(freep, free_bit);
849 (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
850 obufp->addr, free_bit, free_page);
852 __reclaim_buf(hashp, obufp);
865 static char namestr[] = "_hashXXXXXX";
867 /* Block signals; make sure file goes away at process exit. */
868 (void)sigfillset(&set);
869 (void)sigprocmask(SIG_BLOCK, &set, &oset);
870 if ((hashp->fp = mkstemp(namestr)) != -1) {
871 (void)unlink(namestr);
872 (void)_fcntl(hashp->fp, F_SETFD, 1);
874 (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
875 return (hashp->fp != -1 ? 0 : -1);
879 * We have to know that the key will fit, but the last entry on the page is
880 * an overflow pair, so we need to shift things.
883 squeeze_key(sp, key, val)
885 const DBT *key, *val;
888 u_int16_t free_space, n, off, pageno;
892 free_space = FREESPACE(sp);
898 memmove(p + off, key->data, key->size);
901 memmove(p + off, val->data, val->size);
904 sp[n + 2] = OVFLPAGE;
905 FREESPACE(sp) = free_space - PAIRSIZE(key, val);
910 fetch_bitmap(hashp, ndx)
914 if (ndx >= hashp->nmaps)
916 if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
918 if (__get_page(hashp,
919 (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
920 free(hashp->mapp[ndx]);
923 return (hashp->mapp[ndx]);
934 (void)fprintf(stderr, "%d ", addr);
935 bufp = __get_buf(hashp, addr, NULL, 0);
936 bp = (short *)bufp->page;
937 while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
938 ((bp[0] > 2) && bp[2] < REAL_KEY))) {
939 oaddr = bp[bp[0] - 1];
940 (void)fprintf(stderr, "%d ", (int)oaddr);
941 bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
942 bp = (short *)bufp->page;
944 (void)fprintf(stderr, "\n");