Back to index

lightning-sunbird  0.9+nobinonly
h_page.c
Go to the documentation of this file.
00001 /*-
00002  * Copyright (c) 1990, 1993, 1994
00003  *     The Regents of the University of California.  All rights reserved.
00004  *
00005  * This code is derived from software contributed to Berkeley by
00006  * Margo Seltzer.
00007  *
00008  * Redistribution and use in source and binary forms, with or without
00009  * modification, are permitted provided that the following conditions
00010  * are met:
00011  * 1. Redistributions of source code must retain the above copyright
00012  *    notice, this list of conditions and the following disclaimer.
00013  * 2. Redistributions in binary form must reproduce the above copyright
00014  *    notice, this list of conditions and the following disclaimer in the
00015  *    documentation and/or other materials provided with the distribution.
00016  * 3. ***REMOVED*** - see 
00017  *    ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
00018  * 4. Neither the name of the University nor the names of its contributors
00019  *    may be used to endorse or promote products derived from this software
00020  *    without specific prior written permission.
00021  *
00022  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
00023  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00024  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00025  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
00026  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00027  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
00028  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
00029  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00030  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
00031  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
00032  * SUCH DAMAGE.
00033  */
00034 
00035 #if defined(unix)
00036 #define MY_LSEEK lseek
00037 #else
00038 #define MY_LSEEK new_lseek
00039 extern long new_lseek(int fd, long pos, int start);
00040 #endif
00041 
00042 #if defined(LIBC_SCCS) && !defined(lint)
00043 static char sccsid[] = "@(#)hash_page.c   8.7 (Berkeley) 8/16/94";
00044 #endif /* LIBC_SCCS and not lint */
00045 
00046 #include "watcomfx.h"
00047 
00048 /*
00049  * PACKAGE:  hashing
00050  *
00051  * DESCRIPTION:
00052  *     Page manipulation for hashing package.
00053  *
00054  * ROUTINES:
00055  *
00056  * External
00057  *     __get_page
00058  *     __add_ovflpage
00059  * Internal
00060  *     overflow_page
00061  *     open_temp
00062  */
00063 #ifndef macintosh
00064 #include <sys/types.h>
00065 #endif
00066 
00067 #if defined(macintosh)
00068 #include <unistd.h>
00069 #endif
00070 
00071 #include <errno.h>
00072 #include <fcntl.h>
00073 #if defined(_WIN32) || defined(_WINDOWS) 
00074 #include <io.h>
00075 #endif
00076 #include <signal.h>
00077 #include <stdio.h>
00078 #include <stdlib.h>
00079 #include <string.h>
00080 
00081 #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2_VACPP)
00082 #include <unistd.h>
00083 #endif
00084 
00085 #include <assert.h>
00086 
00087 #include "mcom_db.h"
00088 #include "hash.h"
00089 #include "page.h"
00090 /* #include "extern.h" */
00091 
00092 extern int mkstempflags(char *path, int extraFlags);
00093 
00094 static uint32 *fetch_bitmap __P((HTAB *, uint32));
00095 static uint32  first_free __P((uint32));
00096 static int     open_temp __P((HTAB *));
00097 static uint16  overflow_page __P((HTAB *));
00098 static void    squeeze_key __P((uint16 *, const DBT *, const DBT *));
00099 static int     ugly_split
00100                   __P((HTAB *, uint32, BUFHEAD *, BUFHEAD *, int, int));
00101 
00102 #define       PAGE_INIT(P) { \
00103        ((uint16 *)(P))[0] = 0; \
00104        ((uint16 *)(P))[1] = hashp->BSIZE - 3 * sizeof(uint16); \
00105        ((uint16 *)(P))[2] = hashp->BSIZE; \
00106 }
00107 
00108 /* implement a new lseek using lseek that
00109  * writes zero's when extending a file
00110  * beyond the end.
00111  */
00112 long new_lseek(int fd, long offset, int origin)
00113 {
00114        long cur_pos=0;
00115        long end_pos=0;
00116        long seek_pos=0;
00117 
00118        if(origin == SEEK_CUR)
00119       {       
00120        if(offset < 1)                                                   
00121               return(lseek(fd, offset, SEEK_CUR));
00122 
00123               cur_pos = lseek(fd, 0, SEEK_CUR);
00124 
00125               if(cur_pos < 0)
00126                      return(cur_pos);
00127          }
00128                                                                        
00129        end_pos = lseek(fd, 0, SEEK_END);
00130        if(end_pos < 0)
00131               return(end_pos);
00132 
00133        if(origin == SEEK_SET)
00134               seek_pos = offset;
00135        else if(origin == SEEK_CUR)
00136               seek_pos = cur_pos + offset;
00137        else if(origin == SEEK_END)
00138               seek_pos = end_pos + offset;
00139        else
00140          {
00141               assert(0);
00142               return(-1);
00143          }
00144 
00145        /* the seek position desired is before the
00146         * end of the file.  We don't need
00147         * to do anything special except the seek.
00148         */
00149        if(seek_pos <= end_pos)
00150               return(lseek(fd, seek_pos, SEEK_SET));
00151               
00152          /* the seek position is beyond the end of the
00153           * file.  Write zero's to the end.
00154           *
00155           * we are already at the end of the file so
00156           * we just need to "write()" zeros for the
00157           * difference between seek_pos-end_pos and
00158           * then seek to the position to finish
00159           * the call
00160           */
00161          { 
00162               char buffer[1024];
00163               long len = seek_pos-end_pos;
00164               memset(&buffer, 0, 1024);
00165               while(len > 0)
00166              {
00167                write(fd, (char*)&buffer, (size_t)(1024 > len ? len : 1024));
00168                   len -= 1024;
00169                 }
00170               return(lseek(fd, seek_pos, SEEK_SET));
00171          }           
00172 
00173 }
00174 
00175 /*
00176  * This is called AFTER we have verified that there is room on the page for
00177  * the pair (PAIRFITS has returned true) so we go right ahead and start moving
00178  * stuff on.
00179  */
00180 static void
00181 putpair(char *p, const DBT *key, DBT * val)
00182 {
00183        register uint16 *bp, n, off;
00184 
00185        bp = (uint16 *)p;
00186 
00187        /* Enter the key first. */
00188        n = bp[0];
00189 
00190        off = OFFSET(bp) - key->size;
00191        memmove(p + off, key->data, key->size);
00192        bp[++n] = off;
00193 
00194        /* Now the data. */
00195        off -= val->size;
00196        memmove(p + off, val->data, val->size);
00197        bp[++n] = off;
00198 
00199        /* Adjust page info. */
00200        bp[0] = n;
00201        bp[n + 1] = off - ((n + 3) * sizeof(uint16));
00202        bp[n + 2] = off;
00203 }
00204 
00205 /*
00206  * Returns:
00207  *      0 OK
00208  *     -1 error
00209  */
00210 extern int
00211 __delpair(HTAB *hashp, BUFHEAD *bufp, int ndx)
00212 {
00213        register uint16 *bp, newoff;
00214        register int n;
00215        uint16 pairlen;
00216 
00217        bp = (uint16 *)bufp->page;
00218        n = bp[0];
00219 
00220        if (bp[ndx + 1] < REAL_KEY)
00221               return (__big_delete(hashp, bufp));
00222        if (ndx != 1)
00223               newoff = bp[ndx - 1];
00224        else
00225               newoff = hashp->BSIZE;
00226        pairlen = newoff - bp[ndx + 1];
00227 
00228        if (ndx != (n - 1)) {
00229               /* Hard Case -- need to shuffle keys */
00230               register int i;
00231               register char *src = bufp->page + (int)OFFSET(bp);
00232               uint32 dst_offset = (uint32)OFFSET(bp) + (uint32)pairlen;
00233               register char *dst = bufp->page + dst_offset;
00234               uint32 length = bp[ndx + 1] - OFFSET(bp);
00235 
00236               /*
00237                * +-----------+XXX+---------+XXX+---------+---------> +infinity
00238                * |           |             |             |
00239                * 0           src_offset    dst_offset    BSIZE
00240                *
00241                * Dst_offset is > src_offset, so if src_offset were bad, dst_offset
00242                * would be too, therefore we check only dst_offset.
00243                *
00244                * If dst_offset is >= BSIZE, either OFFSET(bp), or pairlen, or both
00245                * is corrupted.
00246                *
00247                * Once we know dst_offset is < BSIZE, we can subtract it from BSIZE
00248                * to get an upper bound on length.
00249                */
00250               if(dst_offset > (uint32)hashp->BSIZE)
00251                      return(DATABASE_CORRUPTED_ERROR);
00252 
00253               if(length > (uint32)(hashp->BSIZE - dst_offset))
00254                      return(DATABASE_CORRUPTED_ERROR);
00255 
00256               memmove(dst, src, length);
00257 
00258               /* Now adjust the pointers */
00259               for (i = ndx + 2; i <= n; i += 2) {
00260                      if (bp[i + 1] == OVFLPAGE) {
00261                             bp[i - 2] = bp[i];
00262                             bp[i - 1] = bp[i + 1];
00263                      } else {
00264                             bp[i - 2] = bp[i] + pairlen;
00265                             bp[i - 1] = bp[i + 1] + pairlen;
00266                      }
00267               }
00268        }
00269        /* Finally adjust the page data */
00270        bp[n] = OFFSET(bp) + pairlen;
00271        bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(uint16);
00272        bp[0] = n - 2;
00273        hashp->NKEYS--;
00274 
00275        bufp->flags |= BUF_MOD;
00276        return (0);
00277 }
00278 /*
00279  * Returns:
00280  *      0 ==> OK
00281  *     -1 ==> Error
00282  */
00283 extern int
00284 __split_page(HTAB *hashp, uint32 obucket, uint32 nbucket)
00285 {
00286        register BUFHEAD *new_bufp, *old_bufp;
00287        register uint16 *ino;
00288        register uint16 *tmp_uint16_array;
00289        register char *np;
00290        DBT key, val;
00291     uint16 n, ndx;
00292        int retval;
00293        uint16 copyto, diff, moved;
00294        size_t off;
00295        char *op;
00296 
00297        copyto = (uint16)hashp->BSIZE;
00298        off = (uint16)hashp->BSIZE;
00299        old_bufp = __get_buf(hashp, obucket, NULL, 0);
00300        if (old_bufp == NULL)
00301               return (-1);
00302        new_bufp = __get_buf(hashp, nbucket, NULL, 0);
00303        if (new_bufp == NULL)
00304               return (-1);
00305 
00306        old_bufp->flags |= (BUF_MOD | BUF_PIN);
00307        new_bufp->flags |= (BUF_MOD | BUF_PIN);
00308 
00309        ino = (uint16 *)(op = old_bufp->page);
00310        np = new_bufp->page;
00311 
00312        moved = 0;
00313 
00314        for (n = 1, ndx = 1; n < ino[0]; n += 2) {
00315               if (ino[n + 1] < REAL_KEY) {
00316                      retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
00317                          (int)copyto, (int)moved);
00318                      old_bufp->flags &= ~BUF_PIN;
00319                      new_bufp->flags &= ~BUF_PIN;
00320                      return (retval);
00321 
00322               }
00323               key.data = (uint8 *)op + ino[n];
00324 
00325               /* check here for ino[n] being greater than
00326                * off.  If it is then the database has
00327                * been corrupted.
00328                */
00329               if(ino[n] > off)
00330                      return(DATABASE_CORRUPTED_ERROR);
00331 
00332               key.size = off - ino[n];
00333 
00334 #ifdef DEBUG
00335               /* make sure the size is positive */
00336               assert(((int)key.size) > -1);
00337 #endif
00338 
00339               if (__call_hash(hashp, (char *)key.data, key.size) == obucket) {
00340                      /* Don't switch page */
00341                      diff = copyto - off;
00342                      if (diff) {
00343                             copyto = ino[n + 1] + diff;
00344                             memmove(op + copyto, op + ino[n + 1],
00345                                 off - ino[n + 1]);
00346                             ino[ndx] = copyto + ino[n] - ino[n + 1];
00347                             ino[ndx + 1] = copyto;
00348                      } else
00349                             copyto = ino[n + 1];
00350                      ndx += 2;
00351               } else {
00352                      /* Switch page */
00353                      val.data = (uint8 *)op + ino[n + 1];
00354                      val.size = ino[n] - ino[n + 1];
00355 
00356                      /* if the pair doesn't fit something is horribly
00357                       * wrong.  LJM
00358                       */
00359                      tmp_uint16_array = (uint16*)np;
00360                      if(!PAIRFITS(tmp_uint16_array, &key, &val))
00361                             return(DATABASE_CORRUPTED_ERROR);
00362 
00363                      putpair(np, &key, &val);
00364                      moved += 2;
00365               }
00366 
00367               off = ino[n + 1];
00368        }
00369 
00370        /* Now clean up the page */
00371        ino[0] -= moved;
00372        FREESPACE(ino) = copyto - sizeof(uint16) * (ino[0] + 3);
00373        OFFSET(ino) = copyto;
00374 
00375 #ifdef DEBUG3
00376        (void)fprintf(stderr, "split %d/%d\n",
00377            ((uint16 *)np)[0] / 2,
00378            ((uint16 *)op)[0] / 2);
00379 #endif
00380        /* unpin both pages */
00381        old_bufp->flags &= ~BUF_PIN;
00382        new_bufp->flags &= ~BUF_PIN;
00383        return (0);
00384 }
00385 
00386 /*
00387  * Called when we encounter an overflow or big key/data page during split
00388  * handling.  This is special cased since we have to begin checking whether
00389  * the key/data pairs fit on their respective pages and because we may need
00390  * overflow pages for both the old and new pages.
00391  *
00392  * The first page might be a page with regular key/data pairs in which case
00393  * we have a regular overflow condition and just need to go on to the next
00394  * page or it might be a big key/data pair in which case we need to fix the
00395  * big key/data pair.
00396  *
00397  * Returns:
00398  *      0 ==> success
00399  *     -1 ==> failure
00400  */
00401 
00402 /* the maximum number of loops we will allow UGLY split to chew
00403  * on before we assume the database is corrupted and throw it
00404  * away.
00405  */
00406 #define MAX_UGLY_SPLIT_LOOPS 10000
00407 
00408 static int
00409 ugly_split(HTAB *hashp, uint32 obucket, BUFHEAD *old_bufp,
00410  BUFHEAD *new_bufp,/* Same as __split_page. */ int copyto, int moved)
00411        /* int copyto;        First byte on page which contains key/data values. */
00412        /* int moved;  Number of pairs moved to new page. */
00413 {
00414        register BUFHEAD *bufp;     /* Buffer header for ino */
00415        register uint16 *ino;       /* Page keys come off of */
00416        register uint16 *np; /* New page */
00417        register uint16 *op; /* Page keys go on to if they aren't moving */
00418     uint32 loop_detection=0;
00419 
00420        BUFHEAD *last_bfp;   /* Last buf header OVFL needing to be freed */
00421        DBT key, val;
00422        SPLIT_RETURN ret;
00423        uint16 n, off, ov_addr, scopyto;
00424        char *cino;          /* Character value of ino */
00425        int status;
00426 
00427        bufp = old_bufp;
00428        ino = (uint16 *)old_bufp->page;
00429        np = (uint16 *)new_bufp->page;
00430        op = (uint16 *)old_bufp->page;
00431        last_bfp = NULL;
00432        scopyto = (uint16)copyto;   /* ANSI */
00433 
00434        n = ino[0] - 1;
00435        while (n < ino[0]) {
00436 
00437 
00438         /* this function goes nuts sometimes and never returns. 
00439          * I havent found the problem yet but I need a solution
00440          * so if we loop too often we assume a database curruption error
00441          * :LJM
00442          */
00443         loop_detection++;
00444 
00445         if(loop_detection > MAX_UGLY_SPLIT_LOOPS)
00446             return DATABASE_CORRUPTED_ERROR;
00447 
00448               if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
00449                      if ((status = __big_split(hashp, old_bufp,
00450                          new_bufp, bufp, bufp->addr, obucket, &ret)))
00451                             return (status);
00452                      old_bufp = ret.oldp;
00453                      if (!old_bufp)
00454                             return (-1);
00455                      op = (uint16 *)old_bufp->page;
00456                      new_bufp = ret.newp;
00457                      if (!new_bufp)
00458                             return (-1);
00459                      np = (uint16 *)new_bufp->page;
00460                      bufp = ret.nextp;
00461                      if (!bufp)
00462                             return (0);
00463                      cino = (char *)bufp->page;
00464                      ino = (uint16 *)cino;
00465                      last_bfp = ret.nextp;
00466               } else if (ino[n + 1] == OVFLPAGE) {
00467                      ov_addr = ino[n];
00468                      /*
00469                       * Fix up the old page -- the extra 2 are the fields
00470                       * which contained the overflow information.
00471                       */
00472                      ino[0] -= (moved + 2);
00473                      FREESPACE(ino) =
00474                          scopyto - sizeof(uint16) * (ino[0] + 3);
00475                      OFFSET(ino) = scopyto;
00476 
00477                      bufp = __get_buf(hashp, ov_addr, bufp, 0);
00478                      if (!bufp)
00479                             return (-1);
00480 
00481                      ino = (uint16 *)bufp->page;
00482                      n = 1;
00483                      scopyto = hashp->BSIZE;
00484                      moved = 0;
00485 
00486                      if (last_bfp)
00487                             __free_ovflpage(hashp, last_bfp);
00488                      last_bfp = bufp;
00489               }
00490               /* Move regular sized pairs of there are any */
00491               off = hashp->BSIZE;
00492               for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
00493                      cino = (char *)ino;
00494                      key.data = (uint8 *)cino + ino[n];
00495                      key.size = off - ino[n];
00496                      val.data = (uint8 *)cino + ino[n + 1];
00497                      val.size = ino[n] - ino[n + 1];
00498                      off = ino[n + 1];
00499 
00500                      if (__call_hash(hashp, (char*)key.data, key.size) == obucket) {
00501                             /* Keep on old page */
00502                             if (PAIRFITS(op, (&key), (&val)))
00503                                    putpair((char *)op, &key, &val);
00504                             else {
00505                                    old_bufp =
00506                                        __add_ovflpage(hashp, old_bufp);
00507                                    if (!old_bufp)
00508                                           return (-1);
00509                                    op = (uint16 *)old_bufp->page;
00510                                    putpair((char *)op, &key, &val);
00511                             }
00512                             old_bufp->flags |= BUF_MOD;
00513                      } else {
00514                             /* Move to new page */
00515                             if (PAIRFITS(np, (&key), (&val)))
00516                                    putpair((char *)np, &key, &val);
00517                             else {
00518                                    new_bufp =
00519                                        __add_ovflpage(hashp, new_bufp);
00520                                    if (!new_bufp)
00521                                           return (-1);
00522                                    np = (uint16 *)new_bufp->page;
00523                                    putpair((char *)np, &key, &val);
00524                             }
00525                             new_bufp->flags |= BUF_MOD;
00526                      }
00527               }
00528        }
00529        if (last_bfp)
00530               __free_ovflpage(hashp, last_bfp);
00531        return (0);
00532 }
00533 
00534 /*
00535  * Add the given pair to the page
00536  *
00537  * Returns:
00538  *     0 ==> OK
00539  *     1 ==> failure
00540  */
00541 extern int
00542 __addel(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT * val)
00543 {
00544        register uint16 *bp, *sop;
00545        int do_expand;
00546 
00547        bp = (uint16 *)bufp->page;
00548        do_expand = 0;
00549        while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
00550               /* Exception case */
00551               if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
00552                      /* This is the last page of a big key/data pair
00553                         and we need to add another page */
00554                      break;
00555               else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
00556                      bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
00557                      if (!bufp)
00558                        {
00559 #ifdef DEBUG
00560                             assert(0);
00561 #endif
00562                             return (-1);
00563                        }
00564                      bp = (uint16 *)bufp->page;
00565               } else
00566                      /* Try to squeeze key on this page */
00567                      if (FREESPACE(bp) > PAIRSIZE(key, val)) {
00568                        {
00569                             squeeze_key(bp, key, val);
00570 
00571                             /* LJM: I added this because I think it was
00572                              * left out on accident.
00573                              * if this isn't incremented nkeys will not
00574                              * be the actual number of keys in the db.
00575                              */
00576                             hashp->NKEYS++;
00577                             return (0);
00578                        }
00579                      } else {
00580                             bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
00581                             if (!bufp)
00582                            {
00583 #ifdef DEBUG
00584                                 assert(0);
00585 #endif
00586                                    return (-1);
00587                               }
00588                             bp = (uint16 *)bufp->page;
00589                      }
00590 
00591        if (PAIRFITS(bp, key, val))
00592               putpair(bufp->page, key, (DBT *)val);
00593        else {
00594               do_expand = 1;
00595               bufp = __add_ovflpage(hashp, bufp);
00596               if (!bufp)
00597              {
00598 #ifdef DEBUG
00599                   assert(0);
00600 #endif
00601                      return (-1);
00602                 }
00603               sop = (uint16 *)bufp->page;
00604 
00605               if (PAIRFITS(sop, key, val))
00606                      putpair((char *)sop, key, (DBT *)val);
00607               else
00608                      if (__big_insert(hashp, bufp, key, val))
00609                  {
00610 #ifdef DEBUG
00611                       assert(0);
00612 #endif
00613                          return (-1);
00614                     }
00615        }
00616        bufp->flags |= BUF_MOD;
00617        /*
00618         * If the average number of keys per bucket exceeds the fill factor,
00619         * expand the table.
00620         */
00621        hashp->NKEYS++;
00622        if (do_expand ||
00623            (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
00624               return (__expand_table(hashp));
00625        return (0);
00626 }
00627 
00628 /*
00629  *
00630  * Returns:
00631  *     pointer on success
00632  *     NULL on error
00633  */
00634 extern BUFHEAD *
00635 __add_ovflpage(HTAB *hashp, BUFHEAD *bufp)
00636 {
00637        register uint16 *sp;
00638        uint16 ndx, ovfl_num;
00639 #ifdef DEBUG1
00640        int tmp1, tmp2;
00641 #endif
00642        sp = (uint16 *)bufp->page;
00643 
00644        /* Check if we are dynamically determining the fill factor */
00645        if (hashp->FFACTOR == DEF_FFACTOR) {
00646               hashp->FFACTOR = sp[0] >> 1;
00647               if (hashp->FFACTOR < MIN_FFACTOR)
00648                      hashp->FFACTOR = MIN_FFACTOR;
00649        }
00650        bufp->flags |= BUF_MOD;
00651        ovfl_num = overflow_page(hashp);
00652 #ifdef DEBUG1
00653        tmp1 = bufp->addr;
00654        tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
00655 #endif
00656        if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
00657               return (NULL);
00658        bufp->ovfl->flags |= BUF_MOD;
00659 #ifdef DEBUG1
00660        (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
00661            tmp1, tmp2, bufp->ovfl->addr);
00662 #endif
00663        ndx = sp[0];
00664        /*
00665         * Since a pair is allocated on a page only if there's room to add
00666         * an overflow page, we know that the OVFL information will fit on
00667         * the page.
00668         */
00669        sp[ndx + 4] = OFFSET(sp);
00670        sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
00671        sp[ndx + 1] = ovfl_num;
00672        sp[ndx + 2] = OVFLPAGE;
00673        sp[0] = ndx + 2;
00674 #ifdef HASH_STATISTICS
00675        hash_overflows++;
00676 #endif
00677        return (bufp->ovfl);
00678 }
00679 
00680 /*
00681  * Returns:
00682  *      0 indicates SUCCESS
00683  *     -1 indicates FAILURE
00684  */
00685 extern int
00686 __get_page(HTAB *hashp,
00687        char * p,
00688        uint32 bucket, 
00689        int is_bucket, 
00690        int is_disk, 
00691        int is_bitmap)
00692 {
00693        register int fd, page;
00694        size_t size;
00695        int rsize;
00696        uint16 *bp;
00697 
00698        fd = hashp->fp;
00699        size = hashp->BSIZE;
00700 
00701        if ((fd == -1) || !is_disk) {
00702               PAGE_INIT(p);
00703               return (0);
00704        }
00705        if (is_bucket)
00706               page = BUCKET_TO_PAGE(bucket);
00707        else
00708               page = OADDR_TO_PAGE(bucket);
00709        if ((MY_LSEEK(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
00710            ((rsize = read(fd, p, size)) == -1))
00711               return (-1);
00712 
00713        bp = (uint16 *)p;
00714        if (!rsize)
00715               bp[0] = 0;    /* We hit the EOF, so initialize a new page */
00716        else
00717               if ((unsigned)rsize != size) {
00718                      errno = EFTYPE;
00719                      return (-1);
00720               }
00721 
00722        if (!is_bitmap && !bp[0]) {
00723               PAGE_INIT(p);
00724        } else {
00725 
00726 #ifdef DEBUG
00727               if(BYTE_ORDER == LITTLE_ENDIAN)
00728                 {
00729                      int is_little_endian;
00730                      is_little_endian = BYTE_ORDER;
00731                 }
00732               else if(BYTE_ORDER == BIG_ENDIAN)
00733                 {
00734                      int is_big_endian;
00735                      is_big_endian = BYTE_ORDER;
00736                 }
00737               else
00738                 {
00739                      assert(0);
00740                 }
00741 #endif
00742 
00743               if (hashp->LORDER != BYTE_ORDER) {
00744                      register int i, max;
00745 
00746                      if (is_bitmap) {
00747                             max = hashp->BSIZE >> 2; /* divide by 4 */
00748                             for (i = 0; i < max; i++)
00749                                    M_32_SWAP(((int *)p)[i]);
00750                      } else {
00751                             M_16_SWAP(bp[0]);
00752                             max = bp[0] + 2;
00753 
00754                      /* bound the size of max by
00755                       * the maximum number of entries
00756                       * in the array
00757                       */
00758                             if((unsigned)max > (size / sizeof(uint16)))
00759                                    return(DATABASE_CORRUPTED_ERROR);
00760 
00761                             /* do the byte order swap
00762                              */
00763                             for (i = 1; i <= max; i++)
00764                                    M_16_SWAP(bp[i]);
00765                      }
00766               }
00767 
00768               /* check the validity of the page here
00769                * (after doing byte order swaping if necessary)
00770                */
00771               if(!is_bitmap && bp[0] != 0)
00772                 {
00773                      uint16 num_keys = bp[0];
00774                      uint16 offset;
00775                      uint16 i;
00776 
00777                      /* bp[0] is supposed to be the number of
00778                       * entries currently in the page.  If
00779                       * bp[0] is too large (larger than the whole
00780                       * page) then the page is corrupted
00781                       */
00782                      if(bp[0] > (size / sizeof(uint16)))
00783                             return(DATABASE_CORRUPTED_ERROR);
00784                      
00785                      /* bound free space */
00786                      if(FREESPACE(bp) > size)
00787                             return(DATABASE_CORRUPTED_ERROR);
00788               
00789                      /* check each key and data offset to make
00790                       * sure they are all within bounds they
00791                       * should all be less than the previous
00792                       * offset as well.
00793                       */
00794                      offset = size;
00795                      for(i=1 ; i <= num_keys; i+=2)
00796                        {
00797                             /* ignore overflow pages etc. */
00798                             if(bp[i+1] >= REAL_KEY)
00799                               {
00800                                           
00801                                    if(bp[i] > offset || bp[i+1] > bp[i])                   
00802                                           return(DATABASE_CORRUPTED_ERROR);
00803                      
00804                                    offset = bp[i+1];
00805                               }
00806                             else
00807                               {
00808                                    /* there are no other valid keys after
00809                                     * seeing a non REAL_KEY
00810                                     */
00811                                    break;
00812                               }
00813                        }
00814               }
00815        }
00816        return (0);
00817 }
00818 
00819 /*
00820  * Write page p to disk
00821  *
00822  * Returns:
00823  *      0 ==> OK
00824  *     -1 ==>failure
00825  */
00826 extern int
00827 __put_page(HTAB *hashp, char *p, uint32 bucket, int is_bucket, int is_bitmap)
00828 {
00829        register int fd, page;
00830        size_t size;
00831        int wsize;
00832        off_t offset;
00833 
00834        size = hashp->BSIZE;
00835        if ((hashp->fp == -1) && open_temp(hashp))
00836               return (-1);
00837        fd = hashp->fp;
00838 
00839        if (hashp->LORDER != BYTE_ORDER) {
00840               register int i;
00841               register int max;
00842 
00843               if (is_bitmap) {
00844                      max = hashp->BSIZE >> 2;    /* divide by 4 */
00845                      for (i = 0; i < max; i++)
00846                             M_32_SWAP(((int *)p)[i]);
00847               } else {
00848                      max = ((uint16 *)p)[0] + 2;
00849 
00850             /* bound the size of max by
00851              * the maximum number of entries
00852              * in the array
00853              */
00854             if((unsigned)max > (size / sizeof(uint16)))
00855                 return(DATABASE_CORRUPTED_ERROR);
00856 
00857                      for (i = 0; i <= max; i++)
00858                             M_16_SWAP(((uint16 *)p)[i]);
00859 
00860               }
00861        }
00862 
00863        if (is_bucket)
00864               page = BUCKET_TO_PAGE(bucket);
00865        else
00866               page = OADDR_TO_PAGE(bucket);
00867        offset = (off_t)page << hashp->BSHIFT;
00868        if ((MY_LSEEK(fd, offset, SEEK_SET) == -1) ||
00869            ((wsize = write(fd, p, size)) == -1))
00870               /* Errno is set */
00871               return (-1);
00872        if ((unsigned)wsize != size) {
00873               errno = EFTYPE;
00874               return (-1);
00875        }
00876 #if defined(_WIN32) || defined(_WINDOWS) 
00877        if (offset + size > hashp->file_size) {
00878               hashp->updateEOF = 1;
00879        }
00880 #endif
00881        /* put the page back the way it was so that it isn't byteswapped
00882         * if it remains in memory - LJM
00883         */
00884        if (hashp->LORDER != BYTE_ORDER) {
00885               register int i;
00886               register int max;
00887 
00888               if (is_bitmap) {
00889                      max = hashp->BSIZE >> 2;    /* divide by 4 */
00890                      for (i = 0; i < max; i++)
00891                             M_32_SWAP(((int *)p)[i]);
00892               } else {
00893               uint16 *bp = (uint16 *)p;
00894 
00895                      M_16_SWAP(bp[0]);
00896                      max = bp[0] + 2;
00897 
00898                      /* no need to bound the size if max again
00899                       * since it was done already above
00900                       */
00901 
00902                      /* do the byte order re-swap
00903                       */
00904                      for (i = 1; i <= max; i++)
00905                             M_16_SWAP(bp[i]);
00906               }
00907        }
00908 
00909        return (0);
00910 }
00911 
00912 #define BYTE_MASK    ((1 << INT_BYTE_SHIFT) -1)
00913 /*
00914  * Initialize a new bitmap page.  Bitmap pages are left in memory
00915  * once they are read in.
00916  */
00917 extern int
00918 __ibitmap(HTAB *hashp, int pnum, int nbits, int ndx)
00919 {
00920        uint32 *ip;
00921        size_t clearbytes, clearints;
00922 
00923        if ((ip = (uint32 *)malloc((size_t)hashp->BSIZE)) == NULL)
00924               return (1);
00925        hashp->nmaps++;
00926        clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
00927        clearbytes = clearints << INT_TO_BYTE;
00928        (void)memset((char *)ip, 0, clearbytes);
00929        (void)memset(((char *)ip) + clearbytes, 0xFF,
00930            hashp->BSIZE - clearbytes);
00931        ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
00932        SETBIT(ip, 0);
00933        hashp->BITMAPS[ndx] = (uint16)pnum;
00934        hashp->mapp[ndx] = ip;
00935        return (0);
00936 }
00937 
00938 static uint32
00939 first_free(uint32 map)
00940 {
00941        register uint32 i, mask;
00942 
00943        mask = 0x1;
00944        for (i = 0; i < BITS_PER_MAP; i++) {
00945               if (!(mask & map))
00946                      return (i);
00947               mask = mask << 1;
00948        }
00949        return (i);
00950 }
00951 
00952 static uint16
00953 overflow_page(HTAB *hashp)
00954 {
00955        register uint32 *freep=NULL;
00956        register int max_free, offset, splitnum;
00957        uint16 addr;
00958        uint32 i;
00959        int bit, first_page, free_bit, free_page, in_use_bits, j;
00960 #ifdef DEBUG2
00961        int tmp1, tmp2;
00962 #endif
00963        splitnum = hashp->OVFL_POINT;
00964        max_free = hashp->SPARES[splitnum];
00965 
00966        free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
00967        free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
00968 
00969        /* Look through all the free maps to find the first free block */
00970        first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
00971        for ( i = first_page; i <= (unsigned)free_page; i++ ) {
00972               if (!(freep = (uint32 *)hashp->mapp[i]) &&
00973                   !(freep = fetch_bitmap(hashp, i)))
00974                      return (0);
00975               if (i == (unsigned)free_page)
00976                      in_use_bits = free_bit;
00977               else
00978                      in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
00979               
00980               if (i == (unsigned)first_page) {
00981                      bit = hashp->LAST_FREED &
00982                          ((hashp->BSIZE << BYTE_SHIFT) - 1);
00983                      j = bit / BITS_PER_MAP;
00984                      bit = bit & ~(BITS_PER_MAP - 1);
00985               } else {
00986                      bit = 0;
00987                      j = 0;
00988               }
00989               for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
00990                      if (freep[j] != ALL_SET)
00991                             goto found;
00992        }
00993 
00994        /* No Free Page Found */
00995        hashp->LAST_FREED = hashp->SPARES[splitnum];
00996        hashp->SPARES[splitnum]++;
00997        offset = hashp->SPARES[splitnum] -
00998            (splitnum ? hashp->SPARES[splitnum - 1] : 0);
00999 
01000 #define       OVMSG  "HASH: Out of overflow pages.  Increase page size\n"
01001        if (offset > SPLITMASK) {
01002               if (++splitnum >= NCACHED) {
01003 #ifndef macintosh
01004                      (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
01005 #endif
01006                      return (0);
01007               }
01008               hashp->OVFL_POINT = splitnum;
01009               hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
01010               hashp->SPARES[splitnum-1]--;
01011               offset = 1;
01012        }
01013 
01014        /* Check if we need to allocate a new bitmap page */
01015        if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
01016               free_page++;
01017               if (free_page >= NCACHED) {
01018 #ifndef macintosh
01019                      (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
01020 #endif
01021                      return (0);
01022               }
01023               /*
01024                * This is tricky.  The 1 indicates that you want the new page
01025                * allocated with 1 clear bit.  Actually, you are going to
01026                * allocate 2 pages from this map.  The first is going to be
01027                * the map page, the second is the overflow page we were
01028                * looking for.  The init_bitmap routine automatically, sets
01029                * the first bit of itself to indicate that the bitmap itself
01030                * is in use.  We would explicitly set the second bit, but
01031                * don't have to if we tell init_bitmap not to leave it clear
01032                * in the first place.
01033                */
01034               if (__ibitmap(hashp,
01035                   (int)OADDR_OF(splitnum, offset), 1, free_page))
01036                      return (0);
01037               hashp->SPARES[splitnum]++;
01038 #ifdef DEBUG2
01039               free_bit = 2;
01040 #endif
01041               offset++;
01042               if (offset > SPLITMASK) {
01043                      if (++splitnum >= NCACHED) {
01044 #ifndef macintosh
01045                             (void)write(STDERR_FILENO, OVMSG,
01046                                 sizeof(OVMSG) - 1);
01047 #endif
01048                             return (0);
01049                      }
01050                      hashp->OVFL_POINT = splitnum;
01051                      hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
01052                      hashp->SPARES[splitnum-1]--;
01053                      offset = 0;
01054               }
01055        } else {
01056               /*
01057                * Free_bit addresses the last used bit.  Bump it to address
01058                * the first available bit.
01059                */
01060               free_bit++;
01061               SETBIT(freep, free_bit);
01062        }
01063 
01064        /* Calculate address of the new overflow page */
01065        addr = OADDR_OF(splitnum, offset);
01066 #ifdef DEBUG2
01067        (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
01068            addr, free_bit, free_page);
01069 #endif
01070        return (addr);
01071 
01072 found:
01073        bit = bit + first_free(freep[j]);
01074        SETBIT(freep, bit);
01075 #ifdef DEBUG2
01076        tmp1 = bit;
01077        tmp2 = i;
01078 #endif
01079        /*
01080         * Bits are addressed starting with 0, but overflow pages are addressed
01081         * beginning at 1. Bit is a bit addressnumber, so we need to increment
01082         * it to convert it to a page number.
01083         */
01084        bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
01085        if (bit >= hashp->LAST_FREED)
01086               hashp->LAST_FREED = bit - 1;
01087 
01088        /* Calculate the split number for this page */
01089        for (i = 0; (i < (unsigned)splitnum) && (bit > hashp->SPARES[i]); i++) {}
01090        offset = (i ? bit - hashp->SPARES[i - 1] : bit);
01091        if (offset >= SPLITMASK)
01092               return (0);   /* Out of overflow pages */
01093        addr = OADDR_OF(i, offset);
01094 #ifdef DEBUG2
01095        (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
01096            addr, tmp1, tmp2);
01097 #endif
01098 
01099        /* Allocate and return the overflow page */
01100        return (addr);
01101 }
01102 
01103 /*
01104  * Mark this overflow page as free.
01105  */
01106 extern void
01107 __free_ovflpage(HTAB *hashp, BUFHEAD *obufp)
01108 {
01109        uint16 addr;
01110        uint32 *freep;
01111        uint32 bit_address, free_page, free_bit;
01112        uint16 ndx;
01113 
01114        if(!obufp || !obufp->addr)
01115            return;
01116 
01117        addr = obufp->addr;
01118 #ifdef DEBUG1
01119        (void)fprintf(stderr, "Freeing %d\n", addr);
01120 #endif
01121        ndx = (((uint16)addr) >> SPLITSHIFT);
01122        bit_address =
01123            (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
01124        if (bit_address < (uint32)hashp->LAST_FREED)
01125               hashp->LAST_FREED = bit_address;
01126        free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
01127        free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
01128 
01129        if (!(freep = hashp->mapp[free_page])) 
01130               freep = fetch_bitmap(hashp, free_page);
01131 
01132 #ifdef DEBUG
01133        /*
01134         * This had better never happen.  It means we tried to read a bitmap
01135         * that has already had overflow pages allocated off it, and we
01136         * failed to read it from the file.
01137         */
01138        if (!freep)
01139          {
01140               assert(0);
01141               return;
01142          }
01143 #endif
01144        CLRBIT(freep, free_bit);
01145 #ifdef DEBUG2
01146        (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
01147            obufp->addr, free_bit, free_page);
01148 #endif
01149        __reclaim_buf(hashp, obufp);
01150 }
01151 
01152 /*
01153  * Returns:
01154  *      0 success
01155  *     -1 failure
01156  */
01157 static int
01158 open_temp(HTAB *hashp)
01159 {
01160 #ifdef XP_OS2
01161        hashp->fp = mkstemp(NULL);
01162 #else
01163 #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
01164        sigset_t set, oset;
01165 #endif
01166 #if !defined(macintosh)
01167        char * tmpdir;
01168        size_t len;
01169        char last;
01170 #endif
01171        static const char namestr[] = "/_hashXXXXXX";
01172        char filename[1024];
01173 
01174 #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
01175        /* Block signals; make sure file goes away at process exit. */
01176        (void)sigfillset(&set);
01177        (void)sigprocmask(SIG_BLOCK, &set, &oset);
01178 #endif
01179 
01180        filename[0] = 0;
01181 #if defined(macintosh)
01182        strcat(filename, namestr + 1);
01183 #else
01184        tmpdir = getenv("TMP");
01185        if (!tmpdir)
01186               tmpdir = getenv("TMPDIR");
01187        if (!tmpdir)
01188               tmpdir = getenv("TEMP");
01189        if (!tmpdir)
01190               tmpdir = ".";
01191        len = strlen(tmpdir);
01192        if (len && len < (sizeof filename - sizeof namestr)) {
01193               strcpy(filename, tmpdir);
01194        }
01195        len = strlen(filename);
01196        last = tmpdir[len - 1];
01197        strcat(filename, (last == '/' || last == '\\') ? namestr + 1 : namestr);
01198 #endif
01199 
01200 #if defined(_WIN32) || defined(_WINDOWS)
01201        if ((hashp->fp = mkstempflags(filename, _O_BINARY|_O_TEMPORARY)) != -1) {
01202               if (hashp->filename) {
01203                      free(hashp->filename);
01204               }
01205               hashp->filename = strdup(filename);
01206               hashp->is_temp = 1;
01207        }
01208 #else
01209        if ((hashp->fp = mkstemp(filename)) != -1) {
01210               (void)unlink(filename);
01211 #if !defined(macintosh)
01212               (void)fcntl(hashp->fp, F_SETFD, 1);
01213 #endif                                                           
01214        }
01215 #endif
01216 
01217 #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
01218        (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
01219 #endif
01220 #endif  /* !OS2 */
01221        return (hashp->fp != -1 ? 0 : -1);
01222 }
01223 
01224 /*
01225  * We have to know that the key will fit, but the last entry on the page is
01226  * an overflow pair, so we need to shift things.
01227  */
01228 static void
01229 squeeze_key(uint16 *sp, const DBT * key, const DBT * val)
01230 {
01231        register char *p;
01232        uint16 free_space, n, off, pageno;
01233 
01234        p = (char *)sp;
01235        n = sp[0];
01236        free_space = FREESPACE(sp);
01237        off = OFFSET(sp);
01238 
01239        pageno = sp[n - 1];
01240        off -= key->size;
01241        sp[n - 1] = off;
01242        memmove(p + off, key->data, key->size);
01243        off -= val->size;
01244        sp[n] = off;
01245        memmove(p + off, val->data, val->size);
01246        sp[0] = n + 2;
01247        sp[n + 1] = pageno;
01248        sp[n + 2] = OVFLPAGE;
01249        FREESPACE(sp) = free_space - PAIRSIZE(key, val);
01250        OFFSET(sp) = off;
01251 }
01252 
01253 static uint32 *
01254 fetch_bitmap(HTAB *hashp, uint32 ndx)
01255 {
01256        if (ndx >= (unsigned)hashp->nmaps)
01257               return (NULL);
01258        if ((hashp->mapp[ndx] = (uint32 *)malloc((size_t)hashp->BSIZE)) == NULL)
01259               return (NULL);
01260        if (__get_page(hashp,
01261            (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
01262               free(hashp->mapp[ndx]);
01263               hashp->mapp[ndx] = NULL; /* NEW: 9-11-95 */
01264               return (NULL);
01265        }                 
01266        return (hashp->mapp[ndx]);
01267 }
01268 
01269 #ifdef DEBUG4
01270 int
01271 print_chain(int addr)
01272 {
01273        BUFHEAD *bufp;
01274        short *bp, oaddr;
01275 
01276        (void)fprintf(stderr, "%d ", addr);
01277        bufp = __get_buf(hashp, addr, NULL, 0);
01278        bp = (short *)bufp->page;
01279        while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
01280               ((bp[0] > 2) && bp[2] < REAL_KEY))) {
01281               oaddr = bp[bp[0] - 1];
01282               (void)fprintf(stderr, "%d ", (int)oaddr);
01283               bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
01284               bp = (short *)bufp->page;
01285        }
01286        (void)fprintf(stderr, "\n");
01287 }
01288 #endif