1 /* $OpenBSD: hash_page.c,v 1.19 2008/05/11 22:21:25 millert Exp $ */
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * Page manipulation for hashing package.
51 #include <sys/param.h>
69 static u_int32_t *fetch_bitmap(HTAB *, int);
70 static u_int32_t first_free(u_int32_t);
71 static int open_temp(HTAB *);
72 static u_int16_t overflow_page(HTAB *);
73 static void putpair(char *, const DBT *, const DBT *);
74 static void squeeze_key(u_int16_t *, const DBT *, const DBT *);
75 static int ugly_split(HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int);
77 #define PAGE_INIT(P) { \
78 ((u_int16_t *)(P))[0] = 0; \
79 ((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \
80 ((u_int16_t *)(P))[2] = hashp->BSIZE; \
84 * This is called AFTER we have verified that there is room on the page for
85 * the pair (PAIRFITS has returned true) so we go right ahead and start moving
89 putpair(char *p, const DBT *key, const DBT *val)
91 u_int16_t *bp, n, off;
95 /* Enter the key first. */
98 off = OFFSET(bp) - key->size;
99 memmove(p + off, key->data, key->size);
104 memmove(p + off, val->data, val->size);
107 /* Adjust page info. */
109 bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t));
119 __delpair(HTAB *hashp, BUFHEAD *bufp, int ndx)
121 u_int16_t *bp, newoff, pairlen;
124 bp = (u_int16_t *)bufp->page;
127 if (bp[ndx + 1] < REAL_KEY)
128 return (__big_delete(hashp, bufp));
130 newoff = bp[ndx - 1];
132 newoff = hashp->BSIZE;
133 pairlen = newoff - bp[ndx + 1];
135 if (ndx != (n - 1)) {
136 /* Hard Case -- need to shuffle keys */
138 char *src = bufp->page + (int)OFFSET(bp);
139 char *dst = src + (int)pairlen;
140 memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
142 /* Now adjust the pointers */
143 for (i = ndx + 2; i <= n; i += 2) {
144 if (bp[i + 1] == OVFLPAGE) {
146 bp[i - 1] = bp[i + 1];
148 bp[i - 2] = bp[i] + pairlen;
149 bp[i - 1] = bp[i + 1] + pairlen;
152 if (ndx == hashp->cndx) {
154 * We just removed pair we were "pointing" to.
155 * By moving back the cndx we ensure subsequent
156 * hash_seq() calls won't skip over any entries.
161 /* Finally adjust the page data */
162 bp[n] = OFFSET(bp) + pairlen;
163 bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t);
167 bufp->flags |= BUF_MOD;
176 __split_page(HTAB *hashp, u_int32_t obucket, u_int32_t nbucket)
178 BUFHEAD *new_bufp, *old_bufp;
183 u_int16_t copyto, diff, off, moved;
186 copyto = (u_int16_t)hashp->BSIZE;
187 off = (u_int16_t)hashp->BSIZE;
188 old_bufp = __get_buf(hashp, obucket, NULL, 0);
189 if (old_bufp == NULL)
191 new_bufp = __get_buf(hashp, nbucket, NULL, 0);
192 if (new_bufp == NULL)
195 old_bufp->flags |= (BUF_MOD | BUF_PIN);
196 new_bufp->flags |= (BUF_MOD | BUF_PIN);
198 ino = (u_int16_t *)(op = old_bufp->page);
203 for (n = 1, ndx = 1; n < ino[0]; n += 2) {
204 if (ino[n + 1] < REAL_KEY) {
205 retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
206 (int)copyto, (int)moved);
207 old_bufp->flags &= ~BUF_PIN;
208 new_bufp->flags &= ~BUF_PIN;
212 key.data = (u_char *)op + ino[n];
213 key.size = off - ino[n];
215 if (__call_hash(hashp, key.data, key.size) == obucket) {
216 /* Don't switch page */
219 copyto = ino[n + 1] + diff;
220 memmove(op + copyto, op + ino[n + 1],
222 ino[ndx] = copyto + ino[n] - ino[n + 1];
223 ino[ndx + 1] = copyto;
229 val.data = (u_char *)op + ino[n + 1];
230 val.size = ino[n] - ino[n + 1];
231 putpair(np, &key, &val);
238 /* Now clean up the page */
240 FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3);
241 OFFSET(ino) = copyto;
244 (void)fprintf(stderr, "split %d/%d\n",
245 ((u_int16_t *)np)[0] / 2,
246 ((u_int16_t *)op)[0] / 2);
248 /* unpin both pages */
249 old_bufp->flags &= ~BUF_PIN;
250 new_bufp->flags &= ~BUF_PIN;
255 * Called when we encounter an overflow or big key/data page during split
256 * handling. This is special cased since we have to begin checking whether
257 * the key/data pairs fit on their respective pages and because we may need
258 * overflow pages for both the old and new pages.
260 * The first page might be a page with regular key/data pairs in which case
261 * we have a regular overflow condition and just need to go on to the next
262 * page or it might be a big key/data pair in which case we need to fix the
270 ugly_split(HTAB *hashp,
271 u_int32_t obucket, /* Same as __split_page. */
274 int copyto, /* First byte on page which contains key/data values. */
275 int moved) /* Number of pairs moved to new page. */
277 BUFHEAD *bufp; /* Buffer header for ino */
278 u_int16_t *ino; /* Page keys come off of */
279 u_int16_t *np; /* New page */
280 u_int16_t *op; /* Page keys go on to if they aren't moving */
282 BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */
285 u_int16_t n, off, ov_addr, scopyto;
286 char *cino; /* Character value of ino */
289 ino = (u_int16_t *)old_bufp->page;
290 np = (u_int16_t *)new_bufp->page;
291 op = (u_int16_t *)old_bufp->page;
293 scopyto = (u_int16_t)copyto; /* ANSI */
297 if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
298 if (__big_split(hashp, old_bufp,
299 new_bufp, bufp, bufp->addr, obucket, &ret))
304 op = (u_int16_t *)old_bufp->page;
308 np = (u_int16_t *)new_bufp->page;
312 cino = (char *)bufp->page;
313 ino = (u_int16_t *)cino;
314 last_bfp = ret.nextp;
315 } else if (ino[n + 1] == OVFLPAGE) {
318 * Fix up the old page -- the extra 2 are the fields
319 * which contained the overflow information.
321 ino[0] -= (moved + 2);
323 scopyto - sizeof(u_int16_t) * (ino[0] + 3);
324 OFFSET(ino) = scopyto;
326 bufp = __get_buf(hashp, ov_addr, bufp, 0);
330 ino = (u_int16_t *)bufp->page;
332 scopyto = hashp->BSIZE;
336 __free_ovflpage(hashp, last_bfp);
339 /* Move regular sized pairs of there are any */
341 for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
343 key.data = (u_char *)cino + ino[n];
344 key.size = off - ino[n];
345 val.data = (u_char *)cino + ino[n + 1];
346 val.size = ino[n] - ino[n + 1];
349 if (__call_hash(hashp, key.data, key.size) == obucket) {
350 /* Keep on old page */
351 if (PAIRFITS(op, (&key), (&val)))
352 putpair((char *)op, &key, &val);
355 __add_ovflpage(hashp, old_bufp);
358 op = (u_int16_t *)old_bufp->page;
359 putpair((char *)op, &key, &val);
361 old_bufp->flags |= BUF_MOD;
363 /* Move to new page */
364 if (PAIRFITS(np, (&key), (&val)))
365 putpair((char *)np, &key, &val);
368 __add_ovflpage(hashp, new_bufp);
371 np = (u_int16_t *)new_bufp->page;
372 putpair((char *)np, &key, &val);
374 new_bufp->flags |= BUF_MOD;
379 __free_ovflpage(hashp, last_bfp);
384 * Add the given pair to the page
391 __addel(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT *val)
396 bp = (u_int16_t *)bufp->page;
398 while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
400 if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
401 /* This is the last page of a big key/data pair
402 and we need to add another page */
404 else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
405 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
408 bp = (u_int16_t *)bufp->page;
409 } else if (bp[bp[0]] != OVFLPAGE) {
410 /* Short key/data pairs, no more pages */
413 /* Try to squeeze key on this page */
414 if (bp[2] >= REAL_KEY &&
415 FREESPACE(bp) >= PAIRSIZE(key, val)) {
416 squeeze_key(bp, key, val);
419 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
422 bp = (u_int16_t *)bufp->page;
426 if (PAIRFITS(bp, key, val))
427 putpair(bufp->page, key, val);
430 bufp = __add_ovflpage(hashp, bufp);
433 sop = (u_int16_t *)bufp->page;
435 if (PAIRFITS(sop, key, val))
436 putpair((char *)sop, key, val);
438 if (__big_insert(hashp, bufp, key, val))
442 bufp->flags |= BUF_MOD;
444 * If the average number of keys per bucket exceeds the fill factor,
449 (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
450 return (__expand_table(hashp));
461 __add_ovflpage(HTAB *hashp, BUFHEAD *bufp)
463 u_int16_t *sp, ndx, ovfl_num;
467 sp = (u_int16_t *)bufp->page;
469 /* Check if we are dynamically determining the fill factor */
470 if (hashp->FFACTOR == DEF_FFACTOR) {
471 hashp->FFACTOR = sp[0] >> 1;
472 if (hashp->FFACTOR < MIN_FFACTOR)
473 hashp->FFACTOR = MIN_FFACTOR;
475 bufp->flags |= BUF_MOD;
476 ovfl_num = overflow_page(hashp);
479 tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
481 if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
483 bufp->ovfl->flags |= BUF_MOD;
485 (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
486 tmp1, tmp2, bufp->ovfl->addr);
490 * Since a pair is allocated on a page only if there's room to add
491 * an overflow page, we know that the OVFL information will fit on
494 sp[ndx + 4] = OFFSET(sp);
495 sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
496 sp[ndx + 1] = ovfl_num;
497 sp[ndx + 2] = OVFLPAGE;
499 #ifdef HASH_STATISTICS
507 * 0 indicates SUCCESS
508 * -1 indicates FAILURE
511 __get_page(HTAB *hashp, char *p, u_int32_t bucket, int is_bucket, int is_disk,
514 int fd, page, size, rsize;
520 if ((fd == -1) || !is_disk) {
525 page = BUCKET_TO_PAGE(bucket);
527 page = OADDR_TO_PAGE(bucket);
528 if ((rsize = pread(fd, p, size, (off_t)page << hashp->BSHIFT)) == -1)
532 bp[0] = 0; /* We hit the EOF, so initialize a new page */
538 if (!is_bitmap && !bp[0]) {
541 if (hashp->LORDER != BYTE_ORDER) {
545 max = hashp->BSIZE >> 2; /* divide by 4 */
546 for (i = 0; i < max; i++)
547 M_32_SWAP(((int *)p)[i]);
551 for (i = 1; i <= max; i++)
559 * Write page p to disk
566 __put_page(HTAB *hashp, char *p, u_int32_t bucket, int is_bucket, int is_bitmap)
568 int fd, page, size, wsize;
571 if ((hashp->fp == -1) && open_temp(hashp))
575 if (hashp->LORDER != BYTE_ORDER) {
579 max = hashp->BSIZE >> 2; /* divide by 4 */
580 for (i = 0; i < max; i++)
581 M_32_SWAP(((int *)p)[i]);
583 max = ((u_int16_t *)p)[0] + 2;
584 for (i = 0; i <= max; i++)
585 M_16_SWAP(((u_int16_t *)p)[i]);
589 page = BUCKET_TO_PAGE(bucket);
591 page = OADDR_TO_PAGE(bucket);
592 if ((wsize = pwrite(fd, p, size, (off_t)page << hashp->BSHIFT)) == -1)
602 #define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1)
604 * Initialize a new bitmap page. Bitmap pages are left in memory
605 * once they are read in.
608 __ibitmap(HTAB *hashp, int pnum, int nbits, int ndx)
611 int clearbytes, clearints;
613 if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
616 clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
617 clearbytes = clearints << INT_TO_BYTE;
618 (void)memset((char *)ip, 0, clearbytes);
619 (void)memset(((char *)ip) + clearbytes, 0xFF,
620 hashp->BSIZE - clearbytes);
621 ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
623 hashp->BITMAPS[ndx] = (u_int16_t)pnum;
624 hashp->mapp[ndx] = ip;
629 first_free(u_int32_t map)
634 for (i = 0; i < BITS_PER_MAP; i++) {
643 overflow_page(HTAB *hashp)
646 int max_free, offset, splitnum;
648 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 (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
696 hashp->OVFL_POINT = splitnum;
697 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
698 hashp->SPARES[splitnum-1]--;
702 /* Check if we need to allocate a new bitmap page */
703 if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
705 if (free_page >= NCACHED) {
706 (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
711 * This is tricky. The 1 indicates that you want the new page
712 * allocated with 1 clear bit. Actually, you are going to
713 * allocate 2 pages from this map. The first is going to be
714 * the map page, the second is the overflow page we were
715 * looking for. The init_bitmap routine automatically, sets
716 * the first bit of itself to indicate that the bitmap itself
717 * is in use. We would explicitly set the second bit, but
718 * don't have to if we tell init_bitmap not to leave it clear
719 * in the first place.
722 (int)OADDR_OF(splitnum, offset), 1, free_page))
724 hashp->SPARES[splitnum]++;
729 if (offset > SPLITMASK) {
730 if (++splitnum >= NCACHED) {
731 (void)write(STDERR_FILENO, OVMSG,
736 hashp->OVFL_POINT = splitnum;
737 hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
738 hashp->SPARES[splitnum-1]--;
743 * Free_bit addresses the last used bit. Bump it to address
744 * the first available bit.
747 SETBIT(freep, free_bit);
750 /* Calculate address of the new overflow page */
751 addr = OADDR_OF(splitnum, offset);
753 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
754 addr, free_bit, free_page);
759 bit = bit + first_free(freep[j]);
766 * Bits are addressed starting with 0, but overflow pages are addressed
767 * beginning at 1. Bit is a bit addressnumber, so we need to increment
768 * it to convert it to a page number.
770 bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
771 if (bit >= hashp->LAST_FREED)
772 hashp->LAST_FREED = bit - 1;
774 /* Calculate the split number for this page */
775 for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
776 offset = (i ? bit - hashp->SPARES[i - 1] : bit);
777 if (offset >= SPLITMASK) {
778 (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
780 return (0); /* Out of overflow pages */
782 addr = OADDR_OF(i, offset);
784 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
788 /* Allocate and return the overflow page */
793 * Mark this overflow page as free.
796 __free_ovflpage(HTAB *hashp, BUFHEAD *obufp)
800 int bit_address, free_page, free_bit;
805 (void)fprintf(stderr, "Freeing %d\n", addr);
807 ndx = (((u_int16_t)addr) >> SPLITSHIFT);
809 (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
810 if (bit_address < hashp->LAST_FREED)
811 hashp->LAST_FREED = bit_address;
812 free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
813 free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
815 if (!(freep = hashp->mapp[free_page]))
816 freep = fetch_bitmap(hashp, free_page);
819 * This had better never happen. It means we tried to read a bitmap
820 * that has already had overflow pages allocated off it, and we
821 * failed to read it from the file.
826 CLRBIT(freep, free_bit);
828 (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
829 obufp->addr, free_bit, free_page);
831 __reclaim_buf(hashp, obufp);
840 open_temp(HTAB *hashp)
845 char path[MAXPATHLEN];
847 if (issetugid() == 0)
848 envtmp = getenv("TMPDIR");
850 sizeof(path), "%s/_hash.XXXXXX", envtmp ? envtmp : "/tmp");
851 if (len < 0 || len >= sizeof(path)) {
852 errno = ENAMETOOLONG;
856 /* Block signals; make sure file goes away at process exit. */
857 (void)sigfillset(&set);
858 (void)sigprocmask(SIG_BLOCK, &set, &oset);
859 if ((hashp->fp = mkstemp(path)) != -1) {
861 (void)fcntl(hashp->fp, F_SETFD, 1);
863 (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
864 return (hashp->fp != -1 ? 0 : -1);
868 * We have to know that the key will fit, but the last entry on the page is
869 * an overflow pair, so we need to shift things.
872 squeeze_key(u_int16_t *sp, const DBT *key, const DBT *val)
875 u_int16_t free_space, n, off, pageno;
879 free_space = FREESPACE(sp);
885 memmove(p + off, key->data, key->size);
888 memmove(p + off, val->data, val->size);
891 sp[n + 2] = OVFLPAGE;
892 FREESPACE(sp) = free_space - PAIRSIZE(key, val);
897 fetch_bitmap(HTAB *hashp, int ndx)
899 if (ndx >= hashp->nmaps)
901 if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL)
903 if (__get_page(hashp,
904 (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
905 free(hashp->mapp[ndx]);
908 return (hashp->mapp[ndx]);
913 print_chain(int addr)
918 (void)fprintf(stderr, "%d ", addr);
919 bufp = __get_buf(hashp, addr, NULL, 0);
920 bp = (short *)bufp->page;
921 while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
922 ((bp[0] > 2) && bp[2] < REAL_KEY))) {
923 oaddr = bp[bp[0] - 1];
924 (void)fprintf(stderr, "%d ", (int)oaddr);
925 bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
926 bp = (short *)bufp->page;
928 (void)fprintf(stderr, "\n");