home *** CD-ROM | disk | FTP | other *** search
/ Tools / WinSN5.0Ver.iso / NETSCAP.50 / WIN1998.ZIP / ns / dbm / src / h_page.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-04-08  |  30.5 KB  |  1,241 lines

  1. /*-
  2.  * Copyright (c) 1990, 1993, 1994
  3.  *    The Regents of the University of California.  All rights reserved.
  4.  *
  5.  * This code is derived from software contributed to Berkeley by
  6.  * Margo Seltzer.
  7.  *
  8.  * Redistribution and use in source and binary forms, with or without
  9.  * modification, are permitted provided that the following conditions
  10.  * are met:
  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.
  23.  *
  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
  34.  * SUCH DAMAGE.
  35.  */
  36.  
  37. #if defined(unix)
  38. #define MY_LSEEK lseek
  39. #else
  40. #define MY_LSEEK new_lseek
  41. extern long new_lseek(int fd, long pos, int start);
  42. #endif
  43.  
  44. #if defined(LIBC_SCCS) && !defined(lint)
  45. static char sccsid[] = "@(#)hash_page.c    8.7 (Berkeley) 8/16/94";
  46. #endif /* LIBC_SCCS and not lint */
  47.  
  48. #include "watcomfx.h"
  49.  
  50. /*
  51.  * PACKAGE:  hashing
  52.  *
  53.  * DESCRIPTION:
  54.  *    Page manipulation for hashing package.
  55.  *
  56.  * ROUTINES:
  57.  *
  58.  * External
  59.  *    __get_page
  60.  *    __add_ovflpage
  61.  * Internal
  62.  *    overflow_page
  63.  *    open_temp
  64.  */
  65. #ifndef macintosh
  66. #include <sys/types.h>
  67. #endif
  68.  
  69. #include <errno.h>
  70. #ifndef macintosh
  71. #include <fcntl.h>
  72. #endif
  73. #include <signal.h>
  74. #include <stdio.h>
  75. #include <stdlib.h>
  76. #include <string.h>
  77.  
  78. #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
  79. #include <unistd.h>
  80. #endif
  81.  
  82. #include <assert.h>
  83.  
  84. #include "mcom_db.h"
  85. #include "hash.h"
  86. #include "page.h"
  87. /* #include "extern.h" */
  88.  
  89. #ifndef NSPR20
  90. #if defined(__sun)
  91. # include "sunos4.h"
  92. #endif /* __sun */
  93. #endif /* NSPR20 */
  94.  
  95. static uint32    *fetch_bitmap __P((HTAB *, uint32));
  96. static uint32     first_free __P((uint32));
  97. static int     open_temp __P((HTAB *));
  98. static uint16     overflow_page __P((HTAB *));
  99. static void     squeeze_key __P((uint16 *, const DBT *, const DBT *));
  100. static int     ugly_split
  101.             __P((HTAB *, uint32, BUFHEAD *, BUFHEAD *, int, int));
  102.  
  103. #define    PAGE_INIT(P) { \
  104.     ((uint16 *)(P))[0] = 0; \
  105.     ((uint16 *)(P))[1] = hashp->BSIZE - 3 * sizeof(uint16); \
  106.     ((uint16 *)(P))[2] = hashp->BSIZE; \
  107. }
  108.  
  109. /* implement a new lseek using lseek that
  110.  * writes zero's when extending a file
  111.  * beyond the end.
  112.  */
  113. long new_lseek(int fd, long offset, int origin)
  114. {
  115.      long cur_pos;
  116.     long end_pos=0;
  117.     long seek_pos;
  118.  
  119.     if(origin == SEEK_CUR)
  120.       {    
  121.           if(offset < 1)                              
  122.             return(lseek(fd, offset, SEEK_CUR));
  123.  
  124.         cur_pos = lseek(fd, 0, SEEK_CUR);
  125.  
  126.         if(cur_pos < 0)
  127.             return(cur_pos);
  128.       }
  129.                                          
  130.     end_pos = lseek(fd, 0, SEEK_END);
  131.     if(end_pos < 0)
  132.         return(end_pos);
  133.  
  134.     if(origin == SEEK_SET)
  135.         seek_pos = offset;
  136.     else if(origin == SEEK_CUR)
  137.         seek_pos = cur_pos + offset;
  138.     else if(origin == SEEK_END)
  139.         seek_pos = end_pos + offset;
  140.      else
  141.       {
  142.           assert(0);
  143.         return(-1);
  144.       }
  145.  
  146.      /* the seek position desired is before the
  147.      * end of the file.  We don't need
  148.      * to do anything special except the seek.
  149.      */
  150.      if(seek_pos <= end_pos)
  151.          return(lseek(fd, seek_pos, SEEK_SET));
  152.          
  153.        /* the seek position is beyond the end of the
  154.         * file.  Write zero's to the end.
  155.         *
  156.        * we are already at the end of the file so
  157.        * we just need to "write()" zeros for the
  158.        * difference between seek_pos-end_pos and
  159.        * then seek to the position to finish
  160.        * the call
  161.         */
  162.        { 
  163.           char buffer[1024];
  164.            long len = seek_pos-end_pos;
  165.            memset(&buffer, 0, 1024);
  166.            while(len > 0)
  167.           {
  168.             write(fd, (char*)&buffer, (1024 > len ? len : 1024));
  169.             len -= 1024;
  170.           }
  171.         return(lseek(fd, seek_pos, SEEK_SET));
  172.       }        
  173.  
  174. }
  175.  
  176. /*
  177.  * This is called AFTER we have verified that there is room on the page for
  178.  * the pair (PAIRFITS has returned true) so we go right ahead and start moving
  179.  * stuff on.
  180.  */
  181. static void
  182. putpair(char *p, const DBT *key, DBT * val)
  183. {
  184.     register uint16 *bp, n, off;
  185.  
  186.     bp = (uint16 *)p;
  187.  
  188.     /* Enter the key first. */
  189.     n = bp[0];
  190.  
  191.     off = OFFSET(bp) - key->size;
  192.     memmove(p + off, key->data, key->size);
  193.     bp[++n] = off;
  194.  
  195.     /* Now the data. */
  196.     off -= val->size;
  197.     memmove(p + off, val->data, val->size);
  198.     bp[++n] = off;
  199.  
  200.     /* Adjust page info. */
  201.     bp[0] = n;
  202.     bp[n + 1] = off - ((n + 3) * sizeof(uint16));
  203.     bp[n + 2] = off;
  204. }
  205.  
  206. /*
  207.  * Returns:
  208.  *     0 OK
  209.  *    -1 error
  210.  */
  211. extern int
  212. __delpair(HTAB *hashp, BUFHEAD *bufp, int ndx)
  213. {
  214.     register uint16 *bp, newoff;
  215.     register int n;
  216.     uint16 pairlen;
  217.  
  218.     bp = (uint16 *)bufp->page;
  219.     n = bp[0];
  220.  
  221.     if (bp[ndx + 1] < REAL_KEY)
  222.         return (__big_delete(hashp, bufp));
  223.     if (ndx != 1)
  224.         newoff = bp[ndx - 1];
  225.     else
  226.         newoff = hashp->BSIZE;
  227.     pairlen = newoff - bp[ndx + 1];
  228.  
  229.     if (ndx != (n - 1)) {
  230.         /* Hard Case -- need to shuffle keys */
  231.         register int i;
  232.         register char *src = bufp->page + (int)OFFSET(bp);
  233.         uint32 dst_offset = (uint32)OFFSET(bp) + (uint32)pairlen;
  234.         register char *dst = bufp->page + dst_offset;
  235.         uint32 length = bp[ndx + 1] - OFFSET(bp);
  236.  
  237.         /*
  238.          * +-----------+XXX+---------+XXX+---------+---------> +infinity
  239.          * |           |             |             |
  240.          * 0           src_offset    dst_offset    BSIZE
  241.          *
  242.          * Dst_offset is > src_offset, so if src_offset were bad, dst_offset
  243.          * would be too, therefore we check only dst_offset.
  244.          *
  245.          * If dst_offset is >= BSIZE, either OFFSET(bp), or pairlen, or both
  246.          * is corrupted.
  247.          *
  248.          * Once we know dst_offset is < BSIZE, we can subtract it from BSIZE
  249.          * to get an upper bound on length.
  250.          */
  251.         if(dst_offset > (uint32)hashp->BSIZE)
  252.             return(DATABASE_CORRUPTED_ERROR);
  253.  
  254.         if(length > (uint32)(hashp->BSIZE - dst_offset))
  255.             return(DATABASE_CORRUPTED_ERROR);
  256.  
  257.         memmove(dst, src, length);
  258.  
  259.         /* Now adjust the pointers */
  260.         for (i = ndx + 2; i <= n; i += 2) {
  261.             if (bp[i + 1] == OVFLPAGE) {
  262.                 bp[i - 2] = bp[i];
  263.                 bp[i - 1] = bp[i + 1];
  264.             } else {
  265.                 bp[i - 2] = bp[i] + pairlen;
  266.                 bp[i - 1] = bp[i + 1] + pairlen;
  267.             }
  268.         }
  269.     }
  270.     /* Finally adjust the page data */
  271.     bp[n] = OFFSET(bp) + pairlen;
  272.     bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(uint16);
  273.     bp[0] = n - 2;
  274.     hashp->NKEYS--;
  275.  
  276.     bufp->flags |= BUF_MOD;
  277.     return (0);
  278. }
  279. /*
  280.  * Returns:
  281.  *     0 ==> OK
  282.  *    -1 ==> Error
  283.  */
  284. extern int
  285. __split_page(HTAB *hashp, uint32 obucket, uint32 nbucket)
  286. {
  287.     register BUFHEAD *new_bufp, *old_bufp;
  288.     register uint16 *ino;
  289.     register uint16 *tmp_uint16_array;
  290.     register char *np;
  291.     DBT key, val;
  292.     uint16 n, ndx;
  293.     int retval;
  294.     uint16 copyto, diff, off, moved;
  295.     char *op;
  296.  
  297.     copyto = (uint16)hashp->BSIZE;
  298.     off = (uint16)hashp->BSIZE;
  299.     old_bufp = __get_buf(hashp, obucket, NULL, 0);
  300.     if (old_bufp == NULL)
  301.         return (-1);
  302.     new_bufp = __get_buf(hashp, nbucket, NULL, 0);
  303.     if (new_bufp == NULL)
  304.         return (-1);
  305.  
  306.     old_bufp->flags |= (BUF_MOD | BUF_PIN);
  307.     new_bufp->flags |= (BUF_MOD | BUF_PIN);
  308.  
  309.     ino = (uint16 *)(op = old_bufp->page);
  310.     np = new_bufp->page;
  311.  
  312.     moved = 0;
  313.  
  314.     for (n = 1, ndx = 1; n < ino[0]; n += 2) {
  315.         if (ino[n + 1] < REAL_KEY) {
  316.             retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
  317.                 (int)copyto, (int)moved);
  318.             old_bufp->flags &= ~BUF_PIN;
  319.             new_bufp->flags &= ~BUF_PIN;
  320.             return (retval);
  321.  
  322.         }
  323.         key.data = (uint8 *)op + ino[n];
  324.  
  325.         /* check here for ino[n] being greater than
  326.          * off.  If it is then the database has
  327.          * been corrupted.
  328.          */
  329.         if(ino[n] > off)
  330.             return(DATABASE_CORRUPTED_ERROR);
  331.  
  332.         key.size = off - ino[n];
  333.  
  334. #ifdef DEBUG
  335.         /* make sure the size is positive */
  336.         assert(((int)key.size) > -1);
  337. #endif
  338.  
  339.         if (__call_hash(hashp, (char *)key.data, key.size) == obucket) {
  340.             /* Don't switch page */
  341.             diff = copyto - off;
  342.             if (diff) {
  343.                 copyto = ino[n + 1] + diff;
  344.                 memmove(op + copyto, op + ino[n + 1],
  345.                     off - ino[n + 1]);
  346.                 ino[ndx] = copyto + ino[n] - ino[n + 1];
  347.                 ino[ndx + 1] = copyto;
  348.             } else
  349.                 copyto = ino[n + 1];
  350.             ndx += 2;
  351.         } else {
  352.             /* Switch page */
  353.             val.data = (uint8 *)op + ino[n + 1];
  354.             val.size = ino[n] - ino[n + 1];
  355.  
  356.             /* if the pair doesn't fit something is horribly
  357.              * wrong.  LJM
  358.              */
  359.             tmp_uint16_array = (uint16*)np;
  360.             if(!PAIRFITS(tmp_uint16_array, &key, &val))
  361.                 return(DATABASE_CORRUPTED_ERROR);
  362.  
  363.             putpair(np, &key, &val);
  364.             moved += 2;
  365.         }
  366.  
  367.         off = ino[n + 1];
  368.     }
  369.  
  370.     /* Now clean up the page */
  371.     ino[0] -= moved;
  372.     FREESPACE(ino) = copyto - sizeof(uint16) * (ino[0] + 3);
  373.     OFFSET(ino) = copyto;
  374.  
  375. #ifdef DEBUG3
  376.     (void)fprintf(stderr, "split %d/%d\n",
  377.         ((uint16 *)np)[0] / 2,
  378.         ((uint16 *)op)[0] / 2);
  379. #endif
  380.     /* unpin both pages */
  381.     old_bufp->flags &= ~BUF_PIN;
  382.     new_bufp->flags &= ~BUF_PIN;
  383.     return (0);
  384. }
  385.  
  386. /*
  387.  * Called when we encounter an overflow or big key/data page during split
  388.  * handling.  This is special cased since we have to begin checking whether
  389.  * the key/data pairs fit on their respective pages and because we may need
  390.  * overflow pages for both the old and new pages.
  391.  *
  392.  * The first page might be a page with regular key/data pairs in which case
  393.  * we have a regular overflow condition and just need to go on to the next
  394.  * page or it might be a big key/data pair in which case we need to fix the
  395.  * big key/data pair.
  396.  *
  397.  * Returns:
  398.  *     0 ==> success
  399.  *    -1 ==> failure
  400.  */
  401.  
  402. /* the maximum number of loops we will allow UGLY split to chew
  403.  * on before we assume the database is corrupted and throw it
  404.  * away.
  405.  */
  406. #define MAX_UGLY_SPLIT_LOOPS 10000
  407.  
  408. static int
  409. ugly_split(HTAB *hashp, uint32 obucket, BUFHEAD *old_bufp,
  410.  BUFHEAD *new_bufp,/* Same as __split_page. */ int copyto, int moved)
  411.     /* int copyto;     First byte on page which contains key/data values. */
  412.     /* int moved;     Number of pairs moved to new page. */
  413. {
  414.     register BUFHEAD *bufp;    /* Buffer header for ino */
  415.     register uint16 *ino;    /* Page keys come off of */
  416.     register uint16 *np;    /* New page */
  417.     register uint16 *op;    /* Page keys go on to if they aren't moving */
  418.     uint32 loop_detection=0;
  419.  
  420.     BUFHEAD *last_bfp;    /* Last buf header OVFL needing to be freed */
  421.     DBT key, val;
  422.     SPLIT_RETURN ret;
  423.     uint16 n, off, ov_addr, scopyto;
  424.     char *cino;        /* Character value of ino */
  425.     int status;
  426.  
  427.     bufp = old_bufp;
  428.     ino = (uint16 *)old_bufp->page;
  429.     np = (uint16 *)new_bufp->page;
  430.     op = (uint16 *)old_bufp->page;
  431.     last_bfp = NULL;
  432.     scopyto = (uint16)copyto;    /* ANSI */
  433.  
  434.     n = ino[0] - 1;
  435.     while (n < ino[0]) {
  436.  
  437.  
  438.         /* this function goes nuts sometimes and never returns. 
  439.          * I havent found the problem yet but I need a solution
  440.          * so if we loop too often we assume a database curruption error
  441.          * :LJM
  442.          */
  443.         loop_detection++;
  444.  
  445.         if(loop_detection > MAX_UGLY_SPLIT_LOOPS)
  446.             return DATABASE_CORRUPTED_ERROR;
  447.  
  448.         if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
  449.             if ((status = __big_split(hashp, old_bufp,
  450.                 new_bufp, bufp, bufp->addr, obucket, &ret)))
  451.                 return (status);
  452.             old_bufp = ret.oldp;
  453.             if (!old_bufp)
  454.                 return (-1);
  455.             op = (uint16 *)old_bufp->page;
  456.             new_bufp = ret.newp;
  457.             if (!new_bufp)
  458.                 return (-1);
  459.             np = (uint16 *)new_bufp->page;
  460.             bufp = ret.nextp;
  461.             if (!bufp)
  462.                 return (0);
  463.             cino = (char *)bufp->page;
  464.             ino = (uint16 *)cino;
  465.             last_bfp = ret.nextp;
  466.         } else if (ino[n + 1] == OVFLPAGE) {
  467.             ov_addr = ino[n];
  468.             /*
  469.              * Fix up the old page -- the extra 2 are the fields
  470.              * which contained the overflow information.
  471.              */
  472.             ino[0] -= (moved + 2);
  473.             FREESPACE(ino) =
  474.                 scopyto - sizeof(uint16) * (ino[0] + 3);
  475.             OFFSET(ino) = scopyto;
  476.  
  477.             bufp = __get_buf(hashp, ov_addr, bufp, 0);
  478.             if (!bufp)
  479.                 return (-1);
  480.  
  481.             ino = (uint16 *)bufp->page;
  482.             n = 1;
  483.             scopyto = hashp->BSIZE;
  484.             moved = 0;
  485.  
  486.             if (last_bfp)
  487.                 __free_ovflpage(hashp, last_bfp);
  488.             last_bfp = bufp;
  489.         }
  490.         /* Move regular sized pairs of there are any */
  491.         off = hashp->BSIZE;
  492.         for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
  493.             cino = (char *)ino;
  494.             key.data = (uint8 *)cino + ino[n];
  495.             key.size = off - ino[n];
  496.             val.data = (uint8 *)cino + ino[n + 1];
  497.             val.size = ino[n] - ino[n + 1];
  498.             off = ino[n + 1];
  499.  
  500.             if (__call_hash(hashp, (char*)key.data, key.size) == obucket) {
  501.                 /* Keep on old page */
  502.                 if (PAIRFITS(op, (&key), (&val)))
  503.                     putpair((char *)op, &key, &val);
  504.                 else {
  505.                     old_bufp =
  506.                         __add_ovflpage(hashp, old_bufp);
  507.                     if (!old_bufp)
  508.                         return (-1);
  509.                     op = (uint16 *)old_bufp->page;
  510.                     putpair((char *)op, &key, &val);
  511.                 }
  512.                 old_bufp->flags |= BUF_MOD;
  513.             } else {
  514.                 /* Move to new page */
  515.                 if (PAIRFITS(np, (&key), (&val)))
  516.                     putpair((char *)np, &key, &val);
  517.                 else {
  518.                     new_bufp =
  519.                         __add_ovflpage(hashp, new_bufp);
  520.                     if (!new_bufp)
  521.                         return (-1);
  522.                     np = (uint16 *)new_bufp->page;
  523.                     putpair((char *)np, &key, &val);
  524.                 }
  525.                 new_bufp->flags |= BUF_MOD;
  526.             }
  527.         }
  528.     }
  529.     if (last_bfp)
  530.         __free_ovflpage(hashp, last_bfp);
  531.     return (0);
  532. }
  533.  
  534. /*
  535.  * Add the given pair to the page
  536.  *
  537.  * Returns:
  538.  *    0 ==> OK
  539.  *    1 ==> failure
  540.  */
  541. extern int
  542. __addel(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT * val)
  543. {
  544.     register uint16 *bp, *sop;
  545.     int do_expand;
  546.  
  547.     bp = (uint16 *)bufp->page;
  548.     do_expand = 0;
  549.     while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
  550.         /* Exception case */
  551.         if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
  552.             /* This is the last page of a big key/data pair
  553.                and we need to add another page */
  554.             break;
  555.         else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
  556.             bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
  557.             if (!bufp)
  558.               {
  559. #ifdef DEBUG
  560.                 assert(0);
  561. #endif
  562.                 return (-1);
  563.               }
  564.             bp = (uint16 *)bufp->page;
  565.         } else
  566.             /* Try to squeeze key on this page */
  567.             if (FREESPACE(bp) > PAIRSIZE(key, val)) {
  568.               {
  569.                 squeeze_key(bp, key, val);
  570.  
  571.                 /* LJM: I added this because I think it was
  572.                  * left out on accident.
  573.                  * if this isn't incremented nkeys will not
  574.                  * be the actual number of keys in the db.
  575.                  */
  576.                 hashp->NKEYS++;
  577.                 return (0);
  578.               }
  579.             } else {
  580.                 bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
  581.                 if (!bufp)
  582.                   {
  583. #ifdef DEBUG
  584.                     assert(0);
  585. #endif
  586.                     return (-1);
  587.                   }
  588.                 bp = (uint16 *)bufp->page;
  589.             }
  590.  
  591.     if (PAIRFITS(bp, key, val))
  592.         putpair(bufp->page, key, (DBT *)val);
  593.     else {
  594.         do_expand = 1;
  595.         bufp = __add_ovflpage(hashp, bufp);
  596.         if (!bufp)
  597.           {
  598. #ifdef DEBUG
  599.             assert(0);
  600. #endif
  601.             return (-1);
  602.           }
  603.         sop = (uint16 *)bufp->page;
  604.  
  605.         if (PAIRFITS(sop, key, val))
  606.             putpair((char *)sop, key, (DBT *)val);
  607.         else
  608.             if (__big_insert(hashp, bufp, key, val))
  609.               {
  610. #ifdef DEBUG
  611.                 assert(0);
  612. #endif
  613.                 return (-1);
  614.               }
  615.     }
  616.     bufp->flags |= BUF_MOD;
  617.     /*
  618.      * If the average number of keys per bucket exceeds the fill factor,
  619.      * expand the table.
  620.      */
  621.     hashp->NKEYS++;
  622.     if (do_expand ||
  623.         (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
  624.         return (__expand_table(hashp));
  625.     return (0);
  626. }
  627.  
  628. /*
  629.  *
  630.  * Returns:
  631.  *    pointer on success
  632.  *    NULL on error
  633.  */
  634. extern BUFHEAD *
  635. __add_ovflpage(HTAB *hashp, BUFHEAD *bufp)
  636. {
  637.     register uint16 *sp;
  638.     uint16 ndx, ovfl_num;
  639. #ifdef DEBUG1
  640.     int tmp1, tmp2;
  641. #endif
  642.     sp = (uint16 *)bufp->page;
  643.  
  644.     /* Check if we are dynamically determining the fill factor */
  645.     if (hashp->FFACTOR == DEF_FFACTOR) {
  646.         hashp->FFACTOR = sp[0] >> 1;
  647.         if (hashp->FFACTOR < MIN_FFACTOR)
  648.             hashp->FFACTOR = MIN_FFACTOR;
  649.     }
  650.     bufp->flags |= BUF_MOD;
  651.     ovfl_num = overflow_page(hashp);
  652. #ifdef DEBUG1
  653.     tmp1 = bufp->addr;
  654.     tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
  655. #endif
  656.     if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
  657.         return (NULL);
  658.     bufp->ovfl->flags |= BUF_MOD;
  659. #ifdef DEBUG1
  660.     (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
  661.         tmp1, tmp2, bufp->ovfl->addr);
  662. #endif
  663.     ndx = sp[0];
  664.     /*
  665.      * Since a pair is allocated on a page only if there's room to add
  666.      * an overflow page, we know that the OVFL information will fit on
  667.      * the page.
  668.      */
  669.     sp[ndx + 4] = OFFSET(sp);
  670.     sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
  671.     sp[ndx + 1] = ovfl_num;
  672.     sp[ndx + 2] = OVFLPAGE;
  673.     sp[0] = ndx + 2;
  674. #ifdef HASH_STATISTICS
  675.     hash_overflows++;
  676. #endif
  677.     return (bufp->ovfl);
  678. }
  679.  
  680. /*
  681.  * Returns:
  682.  *     0 indicates SUCCESS
  683.  *    -1 indicates FAILURE
  684.  */
  685. extern int
  686. __get_page(HTAB *hashp,
  687.     char * p,
  688.     uint32 bucket, 
  689.     int is_bucket, 
  690.     int is_disk, 
  691.     int is_bitmap)
  692. {
  693.     register int fd, page, size;
  694.     int rsize;
  695.     uint16 *bp;
  696.  
  697.     fd = hashp->fp;
  698.     size = hashp->BSIZE;
  699.  
  700.     if ((fd == -1) || !is_disk) {
  701.         PAGE_INIT(p);
  702.         return (0);
  703.     }
  704.     if (is_bucket)
  705.         page = BUCKET_TO_PAGE(bucket);
  706.     else
  707.         page = OADDR_TO_PAGE(bucket);
  708.     if ((MY_LSEEK(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
  709.         ((rsize = read(fd, p, size)) == -1))
  710.         return (-1);
  711.  
  712.     bp = (uint16 *)p;
  713.     if (!rsize)
  714.         bp[0] = 0;    /* We hit the EOF, so initialize a new page */
  715.     else
  716.         if (rsize != size) {
  717.             errno = EFTYPE;
  718.             return (-1);
  719.         }
  720.  
  721.     if (!is_bitmap && !bp[0]) {
  722.         PAGE_INIT(p);
  723.     } else {
  724.  
  725. #ifdef DEBUG
  726.         if(BYTE_ORDER == LITTLE_ENDIAN)
  727.           {
  728.             int is_little_endian;
  729.             is_little_endian = BYTE_ORDER;
  730.           }
  731.         else if(BYTE_ORDER == BIG_ENDIAN)
  732.           {
  733.             int is_big_endian;
  734.             is_big_endian = BYTE_ORDER;
  735.           }
  736.         else
  737.           {
  738.             assert(0);
  739.           }
  740. #endif
  741.  
  742.         if (hashp->LORDER != BYTE_ORDER) {
  743.             register int i, max;
  744.  
  745.             if (is_bitmap) {
  746.                 max = hashp->BSIZE >> 2; /* divide by 4 */
  747.                 for (i = 0; i < max; i++)
  748.                     M_32_SWAP(((int *)p)[i]);
  749.             } else {
  750.                 M_16_SWAP(bp[0]);
  751.                 max = bp[0] + 2;
  752.  
  753.                 /* bound the size of max by
  754.                   * the maximum number of entries
  755.                   * in the array
  756.                   */
  757.                 if(max > (size / sizeof(uint16)))
  758.                     return(DATABASE_CORRUPTED_ERROR);
  759.  
  760.                 /* do the byte order swap
  761.                  */
  762.                 for (i = 1; i <= max; i++)
  763.                     M_16_SWAP(bp[i]);
  764.             }
  765.         }
  766.  
  767.         /* check the validity of the page here
  768.          * (after doing byte order swaping if necessary)
  769.          */
  770.         if(!is_bitmap && bp[0] != 0)
  771.           {
  772.             uint16 num_keys = bp[0];
  773.             uint16 offset;
  774.             uint16 i;
  775.  
  776.             /* bp[0] is supposed to be the number of
  777.              * entries currently in the page.  If
  778.              * bp[0] is too large (larger than the whole
  779.              * page) then the page is corrupted
  780.              */
  781.             if(bp[0] > (size / sizeof(uint16)))
  782.                 return(DATABASE_CORRUPTED_ERROR);
  783.             
  784.             /* bound free space */
  785.             if(FREESPACE(bp) > size)
  786.                 return(DATABASE_CORRUPTED_ERROR);
  787.         
  788.             /* check each key and data offset to make
  789.               * sure they are all within bounds they
  790.               * should all be less than the previous
  791.               * offset as well.
  792.               */
  793.             offset = size;
  794.             for(i=1 ; i <= num_keys; i+=2)
  795.                 {
  796.                 /* ignore overflow pages etc. */
  797.                 if(bp[i+1] >= REAL_KEY)
  798.                     {
  799.                         
  800.                     if(bp[i] > offset || bp[i+1] > bp[i])            
  801.                         return(DATABASE_CORRUPTED_ERROR);
  802.             
  803.                     offset = bp[i+1];
  804.                     }
  805.                 else
  806.                     {
  807.                     /* there are no other valid keys after
  808.                       * seeing a non REAL_KEY
  809.                       */
  810.                     break;
  811.                     }
  812.                 }
  813.         }
  814.     }
  815.     return (0);
  816. }
  817.  
  818. /*
  819.  * Write page p to disk
  820.  *
  821.  * Returns:
  822.  *     0 ==> OK
  823.  *    -1 ==>failure
  824.  */
  825. extern int
  826. __put_page(HTAB *hashp, char *p, uint32 bucket, int is_bucket, int is_bitmap)
  827. {
  828.     register int fd, page, size;
  829.     int wsize;
  830.  
  831.     size = hashp->BSIZE;
  832.     if ((hashp->fp == -1) && open_temp(hashp))
  833.         return (-1);
  834.     fd = hashp->fp;
  835.  
  836.     if (hashp->LORDER != BYTE_ORDER) {
  837.         register int i;
  838.         register int max;
  839.  
  840.         if (is_bitmap) {
  841.             max = hashp->BSIZE >> 2;    /* divide by 4 */
  842.             for (i = 0; i < max; i++)
  843.                 M_32_SWAP(((int *)p)[i]);
  844.         } else {
  845.             max = ((uint16 *)p)[0] + 2;
  846.  
  847.             /* bound the size of max by
  848.              * the maximum number of entries
  849.              * in the array
  850.              */
  851.             if(max > (size / sizeof(uint16)))
  852.                 return(DATABASE_CORRUPTED_ERROR);
  853.  
  854.             for (i = 0; i <= max; i++)
  855.                 M_16_SWAP(((uint16 *)p)[i]);
  856.  
  857.         }
  858.     }
  859.  
  860.     if (is_bucket)
  861.         page = BUCKET_TO_PAGE(bucket);
  862.     else
  863.         page = OADDR_TO_PAGE(bucket);
  864.     if ((MY_LSEEK(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
  865.         ((wsize = write(fd, p, size)) == -1))
  866.         /* Errno is set */
  867.         return (-1);
  868.     if (wsize != size) {
  869.         errno = EFTYPE;
  870.         return (-1);
  871.     }
  872.  
  873.     /* put the page back the way it was so that it isn't byteswapped
  874.      * if it remains in memory - LJM
  875.      */
  876.     if (hashp->LORDER != BYTE_ORDER) {
  877.         register int i;
  878.         register int max;
  879.  
  880.         if (is_bitmap) {
  881.             max = hashp->BSIZE >> 2;    /* divide by 4 */
  882.             for (i = 0; i < max; i++)
  883.                 M_32_SWAP(((int *)p)[i]);
  884.         } else {
  885.             uint16 *bp = (uint16 *)p;
  886.  
  887.             M_16_SWAP(bp[0]);
  888.             max = bp[0] + 2;
  889.  
  890.             /* no need to bound the size if max again
  891.              * since it was done already above
  892.              */
  893.  
  894.             /* do the byte order re-swap
  895.              */
  896.             for (i = 1; i <= max; i++)
  897.                 M_16_SWAP(bp[i]);
  898.         }
  899.     }
  900.  
  901.     return (0);
  902. }
  903.  
  904. #define BYTE_MASK    ((1 << INT_BYTE_SHIFT) -1)
  905. /*
  906.  * Initialize a new bitmap page.  Bitmap pages are left in memory
  907.  * once they are read in.
  908.  */
  909. extern int
  910. __ibitmap(HTAB *hashp, int pnum, int nbits, int ndx)
  911. {
  912.     uint32 *ip;
  913.     int clearbytes, clearints;
  914.  
  915.     if ((ip = (uint32 *)malloc(hashp->BSIZE)) == NULL)
  916.         return (1);
  917.     hashp->nmaps++;
  918.     clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
  919.     clearbytes = clearints << INT_TO_BYTE;
  920.     (void)memset((char *)ip, 0, clearbytes);
  921.     (void)memset(((char *)ip) + clearbytes, 0xFF,
  922.         hashp->BSIZE - clearbytes);
  923.     ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
  924.     SETBIT(ip, 0);
  925.     hashp->BITMAPS[ndx] = (uint16)pnum;
  926.     hashp->mapp[ndx] = ip;
  927.     return (0);
  928. }
  929.  
  930. static uint32
  931. first_free(uint32 map)
  932. {
  933.     register uint32 i, mask;
  934.  
  935.     mask = 0x1;
  936.     for (i = 0; i < BITS_PER_MAP; i++) {
  937.         if (!(mask & map))
  938.             return (i);
  939.         mask = mask << 1;
  940.     }
  941.     return (i);
  942. }
  943.  
  944. static uint16
  945. overflow_page(HTAB *hashp)
  946. {
  947.     register uint32 *freep=NULL;
  948.     register int max_free, offset, splitnum;
  949.     uint16 addr;
  950.     uint32 i;
  951.     int bit, first_page, free_bit, free_page, in_use_bits, j;
  952. #ifdef DEBUG2
  953.     int tmp1, tmp2;
  954. #endif
  955.     splitnum = hashp->OVFL_POINT;
  956.     max_free = hashp->SPARES[splitnum];
  957.  
  958.     free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
  959.     free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
  960.  
  961.     /* Look through all the free maps to find the first free block */
  962.     first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
  963.     for ( i = first_page; i <= free_page; i++ ) {
  964.         if (!(freep = (uint32 *)hashp->mapp[i]) &&
  965.             !(freep = fetch_bitmap(hashp, i)))
  966.             return (0);
  967.         if (i == free_page)
  968.             in_use_bits = free_bit;
  969.         else
  970.             in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
  971.         
  972.         if (i == first_page) {
  973.             bit = hashp->LAST_FREED &
  974.                 ((hashp->BSIZE << BYTE_SHIFT) - 1);
  975.             j = bit / BITS_PER_MAP;
  976.             bit = bit & ~(BITS_PER_MAP - 1);
  977.         } else {
  978.             bit = 0;
  979.             j = 0;
  980.         }
  981.         for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
  982.             if (freep[j] != ALL_SET)
  983.                 goto found;
  984.     }
  985.  
  986.     /* No Free Page Found */
  987.     hashp->LAST_FREED = hashp->SPARES[splitnum];
  988.     hashp->SPARES[splitnum]++;
  989.     offset = hashp->SPARES[splitnum] -
  990.         (splitnum ? hashp->SPARES[splitnum - 1] : 0);
  991.  
  992. #define    OVMSG    "HASH: Out of overflow pages.  Increase page size\n"
  993.     if (offset > SPLITMASK) {
  994.         if (++splitnum >= NCACHED) {
  995. #ifndef macintosh
  996.             (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
  997. #endif
  998.             return (0);
  999.         }
  1000.         hashp->OVFL_POINT = splitnum;
  1001.         hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
  1002.         hashp->SPARES[splitnum-1]--;
  1003.         offset = 1;
  1004.     }
  1005.  
  1006.     /* Check if we need to allocate a new bitmap page */
  1007.     if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
  1008.         free_page++;
  1009.         if (free_page >= NCACHED) {
  1010. #ifndef macintosh
  1011.             (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
  1012. #endif
  1013.             return (0);
  1014.         }
  1015.         /*
  1016.          * This is tricky.  The 1 indicates that you want the new page
  1017.          * allocated with 1 clear bit.  Actually, you are going to
  1018.          * allocate 2 pages from this map.  The first is going to be
  1019.          * the map page, the second is the overflow page we were
  1020.          * looking for.  The init_bitmap routine automatically, sets
  1021.          * the first bit of itself to indicate that the bitmap itself
  1022.          * is in use.  We would explicitly set the second bit, but
  1023.          * don't have to if we tell init_bitmap not to leave it clear
  1024.          * in the first place.
  1025.          */
  1026.         if (__ibitmap(hashp,
  1027.             (int)OADDR_OF(splitnum, offset), 1, free_page))
  1028.             return (0);
  1029.         hashp->SPARES[splitnum]++;
  1030. #ifdef DEBUG2
  1031.         free_bit = 2;
  1032. #endif
  1033.         offset++;
  1034.         if (offset > SPLITMASK) {
  1035.             if (++splitnum >= NCACHED) {
  1036. #ifndef macintosh
  1037.                 (void)write(STDERR_FILENO, OVMSG,
  1038.                     sizeof(OVMSG) - 1);
  1039. #endif
  1040.                 return (0);
  1041.             }
  1042.             hashp->OVFL_POINT = splitnum;
  1043.             hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
  1044.             hashp->SPARES[splitnum-1]--;
  1045.             offset = 0;
  1046.         }
  1047.     } else {
  1048.         /*
  1049.          * Free_bit addresses the last used bit.  Bump it to address
  1050.          * the first available bit.
  1051.          */
  1052.         free_bit++;
  1053.         SETBIT(freep, free_bit);
  1054.     }
  1055.  
  1056.     /* Calculate address of the new overflow page */
  1057.     addr = OADDR_OF(splitnum, offset);
  1058. #ifdef DEBUG2
  1059.     (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
  1060.         addr, free_bit, free_page);
  1061. #endif
  1062.     return (addr);
  1063.  
  1064. found:
  1065.     bit = bit + first_free(freep[j]);
  1066.     SETBIT(freep, bit);
  1067. #ifdef DEBUG2
  1068.     tmp1 = bit;
  1069.     tmp2 = i;
  1070. #endif
  1071.     /*
  1072.      * Bits are addressed starting with 0, but overflow pages are addressed
  1073.      * beginning at 1. Bit is a bit addressnumber, so we need to increment
  1074.      * it to convert it to a page number.
  1075.      */
  1076.     bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
  1077.     if (bit >= hashp->LAST_FREED)
  1078.         hashp->LAST_FREED = bit - 1;
  1079.  
  1080.     /* Calculate the split number for this page */
  1081.     for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++) {}
  1082.     offset = (i ? bit - hashp->SPARES[i - 1] : bit);
  1083.     if (offset >= SPLITMASK)
  1084.         return (0);    /* Out of overflow pages */
  1085.     addr = OADDR_OF(i, offset);
  1086. #ifdef DEBUG2
  1087.     (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
  1088.         addr, tmp1, tmp2);
  1089. #endif
  1090.  
  1091.     /* Allocate and return the overflow page */
  1092.     return (addr);
  1093. }
  1094.  
  1095. /*
  1096.  * Mark this overflow page as free.
  1097.  */
  1098. extern void
  1099. __free_ovflpage(HTAB *hashp, BUFHEAD *obufp)
  1100. {
  1101.     uint16 addr;
  1102.     uint32 *freep;
  1103.     uint32 bit_address, free_page, free_bit;
  1104.     uint16 ndx;
  1105.  
  1106.     if(!obufp || !obufp->addr)
  1107.         return;
  1108.  
  1109.     addr = obufp->addr;
  1110. #ifdef DEBUG1
  1111.     (void)fprintf(stderr, "Freeing %d\n", addr);
  1112. #endif
  1113.     ndx = (((uint16)addr) >> SPLITSHIFT);
  1114.     bit_address =
  1115.         (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
  1116.      if (bit_address < hashp->LAST_FREED)
  1117.         hashp->LAST_FREED = bit_address;
  1118.     free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
  1119.     free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
  1120.  
  1121.     if (!(freep = hashp->mapp[free_page])) 
  1122.         freep = fetch_bitmap(hashp, free_page);
  1123.  
  1124. #ifdef DEBUG
  1125.     /*
  1126.      * This had better never happen.  It means we tried to read a bitmap
  1127.      * that has already had overflow pages allocated off it, and we
  1128.      * failed to read it from the file.
  1129.      */
  1130.     if (!freep)
  1131.       {
  1132.         assert(0);
  1133.         return;
  1134.       }
  1135. #endif
  1136.     CLRBIT(freep, free_bit);
  1137. #ifdef DEBUG2
  1138.     (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
  1139.         obufp->addr, free_bit, free_page);
  1140. #endif
  1141.     __reclaim_buf(hashp, obufp);
  1142. }
  1143.  
  1144. /*
  1145.  * Returns:
  1146.  *     0 success
  1147.  *    -1 failure
  1148.  */
  1149. static int
  1150. open_temp(HTAB *hashp)
  1151. {
  1152. #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
  1153.     sigset_t set, oset;
  1154. #endif
  1155.     static char namestr[] = "_hashXXXXXX";
  1156.  
  1157. #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
  1158.     /* Block signals; make sure file goes away at process exit. */
  1159.     (void)sigfillset(&set);
  1160.     (void)sigprocmask(SIG_BLOCK, &set, &oset);
  1161. #endif
  1162.  
  1163.     if ((hashp->fp = mkstemp(namestr)) != -1) {
  1164.         (void)unlink(namestr);
  1165. #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
  1166.         (void)fcntl(hashp->fp, F_SETFD, 1);
  1167. #endif                                      
  1168.     }
  1169.  
  1170. #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) 
  1171.     (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
  1172. #endif
  1173.     return (hashp->fp != -1 ? 0 : -1);
  1174. }
  1175.  
  1176. /*
  1177.  * We have to know that the key will fit, but the last entry on the page is
  1178.  * an overflow pair, so we need to shift things.
  1179.  */
  1180. static void
  1181. squeeze_key(uint16 *sp, const DBT * key, const DBT * val)
  1182. {
  1183.     register char *p;
  1184.     uint16 free_space, n, off, pageno;
  1185.  
  1186.     p = (char *)sp;
  1187.     n = sp[0];
  1188.     free_space = FREESPACE(sp);
  1189.     off = OFFSET(sp);
  1190.  
  1191.     pageno = sp[n - 1];
  1192.     off -= key->size;
  1193.     sp[n - 1] = off;
  1194.     memmove(p + off, key->data, key->size);
  1195.     off -= val->size;
  1196.     sp[n] = off;
  1197.     memmove(p + off, val->data, val->size);
  1198.     sp[0] = n + 2;
  1199.     sp[n + 1] = pageno;
  1200.     sp[n + 2] = OVFLPAGE;
  1201.     FREESPACE(sp) = free_space - PAIRSIZE(key, val);
  1202.     OFFSET(sp) = off;
  1203. }
  1204.  
  1205. static uint32 *
  1206. fetch_bitmap(HTAB *hashp, uint32 ndx)
  1207. {
  1208.     if (ndx >= hashp->nmaps)
  1209.         return (NULL);
  1210.     if ((hashp->mapp[ndx] = (uint32 *)malloc(hashp->BSIZE)) == NULL)
  1211.         return (NULL);
  1212.     if (__get_page(hashp,
  1213.         (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
  1214.         free(hashp->mapp[ndx]);
  1215.         hashp->mapp[ndx] = NULL; /* NEW: 9-11-95 */
  1216.         return (NULL);
  1217.     }                 
  1218.     return (hashp->mapp[ndx]);
  1219. }
  1220.  
  1221. #ifdef DEBUG4
  1222. int
  1223. print_chain(int addr)
  1224. {
  1225.     BUFHEAD *bufp;
  1226.     short *bp, oaddr;
  1227.  
  1228.     (void)fprintf(stderr, "%d ", addr);
  1229.     bufp = __get_buf(hashp, addr, NULL, 0);
  1230.     bp = (short *)bufp->page;
  1231.     while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
  1232.         ((bp[0] > 2) && bp[2] < REAL_KEY))) {
  1233.         oaddr = bp[bp[0] - 1];
  1234.         (void)fprintf(stderr, "%d ", (int)oaddr);
  1235.         bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
  1236.         bp = (short *)bufp->page;
  1237.     }
  1238.     (void)fprintf(stderr, "\n");
  1239. }
  1240. #endif
  1241.