home *** CD-ROM | disk | FTP | other *** search
/ ftp.uv.es / 2014.11.ftp.uv.es.tar / ftp.uv.es / pub / unix / elm-2.4-pl20.tar.Z / elm-2.4-pl20.tar / lib / ndbz.c < prev    next >
C/C++ Source or Header  |  1993-01-12  |  37KB  |  1,425 lines

  1. static char rcsid[] = "@(#)$Id: ndbz.c,v 5.3 1992/12/12 01:29:26 syd Exp $";
  2.  
  3. /*******************************************************************************
  4.  *  The Elm Mail System  -  $Revision: 5.3 $   $State: Exp $
  5.  *
  6.  *            Copyright (c) 1988-1992 USENET Community Trust
  7.  *            Copyright (c) 1986,1987 Dave Taylor
  8.  *******************************************************************************
  9.  * Bug reports, patches, comments, suggestions should be sent to:
  10.  *
  11.  *    Syd Weinstein, Elm Coordinator
  12.  *    elm@DSI.COM            dsinc!elm
  13.  *
  14.  *******************************************************************************
  15.  * $Log: ndbz.c,v $
  16.  * Revision 5.3  1992/12/12  01:29:26  syd
  17.  * Fix double inclusion of sys/types.h
  18.  * From: Tom Moore <tmoore@wnas.DaytonOH.NCR.COM>
  19.  *
  20.  * Revision 5.2  1992/10/11  01:46:35  syd
  21.  * change dbm name to dbz to avoid conflicts with partial call
  22.  * ins from shared librarys, and from mixing code with yp code.
  23.  * From: Syd via prompt from Jess Anderson
  24.  *
  25.  * Revision 5.1  1992/10/03  22:41:36  syd
  26.  * Initial checkin as of 2.4 Release at PL0
  27.  *
  28.  *
  29.  ******************************************************************************/
  30.  
  31. /** 
  32.     multi-database dbm replacement
  33.  
  34. **/
  35.  
  36. /*
  37.  
  38. ndbz.c  V1.0
  39. Syd Weinstein <syd@dsi.com>
  40. Based on dbz.c from the C News distribution
  41. Modified to support multiple DBZ files.
  42.  
  43. Copyright 1988 Jon Zeeff (zeeff@b-tech.ann-arbor.mi.us)
  44. You can use this code in any manner, as long as you leave my name on it
  45. and don't hold me responsible for any problems with it.
  46.  
  47. Hacked on by gdb@ninja.UUCP (David Butler); Sun Jun  5 00:27:08 CDT 1988
  48.  
  49. Various improvments + INCORE by moraes@ai.toronto.edu (Mark Moraes)
  50.  
  51. Major reworking by Henry Spencer as part of the C News project.
  52.  
  53. These routines replace dbm as used by the usenet news software
  54. (it's not a full dbm replacement by any means).  It's fast and
  55. simple.  It contains no AT&T code.
  56.  
  57. In general, dbz's files are 1/20 the size of dbm's.  Lookup performance
  58. is somewhat better, while file creation is spectacularly faster, especially
  59. if the incore facility is used.
  60.  
  61. */
  62.  
  63. #include "headers.h"
  64. #include <ctype.h>
  65. #include <errno.h>
  66. #ifndef ANSI_C
  67. extern int errno;
  68. #endif
  69.  
  70. /*
  71.  * #ifdef index.  "LIA" = "leave it alone unless you know what you're doing".
  72.  *
  73.  * FUNNYSEEKS    SEEK_SET is not 0, get it from <unistd.h>
  74.  * INDEX_SIZE    backward compatibility with old dbz; avoid using this
  75.  * NMEMORY    number of days of memory for use in sizing new table (LIA)
  76.  * INCORE    backward compatibility with old dbz; use dbzincore() instead
  77.  * DEFSIZE    default table size (not as critical as in old dbz)
  78.  * NOTAGS    fseek offsets are strange, do not do tagging (see below)
  79.  * NPAGBUF    size of .pag buffer, in longs (LIA)
  80.  * SHISTBUF    size of ASCII-file buffer, in bytes (LIA)
  81.  * MAXRUN    length of run which shifts to next table (see below) (LIA)
  82.  * OVERFLOW    long-int arithmetic overflow must be avoided, will trap
  83.  * NOBUFFER    do not buffer hash-table i/o, B News locking is defective
  84.  */
  85.  
  86. #ifdef FUNNYSEEKS
  87. #include <unistd.h>
  88. #else
  89. #define    SEEK_SET    0
  90. #endif
  91. #ifdef OVERFLOW
  92. #include <limits.h>
  93. #endif
  94.  
  95. static int dbzversion = 3;    /* for validating .dir file format */
  96.  
  97. /*
  98.  * The dbz database exploits the fact that when news stores a <key,value>
  99.  * tuple, the `value' part is a seek offset into a text file, pointing to
  100.  * a copy of the `key' part.  This avoids the need to store a copy of
  101.  * the key in the dbz files.  However, the text file *must* exist and be
  102.  * consistent with the dbz files, or things will fail.
  103.  *
  104.  * The basic format of the database is a simple hash table containing the
  105.  * values.  A value is stored by indexing into the table using a hash value
  106.  * computed from the key; collisions are resolved by linear probing (just
  107.  * search forward for an empty slot, wrapping around to the beginning of
  108.  * the table if necessary).  Linear probing is a performance disaster when
  109.  * the table starts to get full, so a complication is introduced.  The
  110.  * database is actually one *or more* tables, stored sequentially in the
  111.  * .pag file, and the length of linear-probe sequences is limited.  The
  112.  * search (for an existing item or an empty slot) always starts in the
  113.  * first table, and whenever MAXRUN probes have been done in table N,
  114.  * probing continues in table N+1.  This behaves reasonably well even in
  115.  * cases of massive overflow.  There are some other small complications
  116.  * added, see comments below.
  117.  *
  118.  * The table size is fixed for any particular database, but is determined
  119.  * dynamically when a database is rebuilt.  The strategy is to try to pick
  120.  * the size so the first table will be no more than 2/3 full, that being
  121.  * slightly before the point where performance starts to degrade.  (It is
  122.  * desirable to be a bit conservative because the overflow strategy tends
  123.  * to produce files with holes in them, which is a nuisance.)
  124.  */
  125.  
  126. /*
  127.  * The following is for backward compatibility.
  128.  */
  129. #ifdef INDEX_SIZE
  130. #define    DEFSIZE    INDEX_SIZE
  131. #endif
  132. #include "ndbz.h"
  133.  
  134. /*
  135.  * We assume that unused areas of a binary file are zeros, and that the
  136.  * bit pattern of `(of_t)0' is all zeros.  The alternative is rather
  137.  * painful file initialization.  Note that okayvalue(), if OVERFLOW is
  138.  * defined, knows what value of an offset would cause overflow.
  139.  */
  140. #define    VACANT        ((of_t)0)
  141. #define    BIAS(o)        ((o)+1)        /* make any valid of_t non-VACANT */
  142. #define    UNBIAS(o)    ((o)-1)        /* reverse BIAS() effect */
  143.  
  144. /*
  145.  * In a Unix implementation, or indeed any in which an of_t is a byte
  146.  * count, there are a bunch of high bits free in an of_t.  There is a
  147.  * use for them.  Checking a possible hit by looking it up in the base
  148.  * file is relatively expensive, and the cost can be dramatically reduced
  149.  * by using some of those high bits to tag the value with a few more bits
  150.  * of the key's hash.  This detects most false hits without the overhead of
  151.  * seek+read+strcmp.  We use the top bit to indicate whether the value is
  152.  * tagged or not, and don't tag a value which is using the tag bits itself.
  153.  * We're in trouble if the of_t representation wants to use the top bit.
  154.  * The actual bitmasks and offset come from the configuration stuff,
  155.  * which permits fiddling with them as necessary, and also suppressing
  156.  * them completely (by defining the masks to 0).  We build pre-shifted
  157.  * versions of the masks for efficiency.
  158.  */
  159. #define    HASTAG(o)    ((o)&db->dbz_taghere)
  160. #define    TAG(o)        ((o)&db->dbz_tagbits)
  161. #define    NOTAG(o)    ((o)&~db->dbz_tagboth)
  162. #define    CANTAG(o)    (((o)&db->dbz_tagboth) == 0)
  163. #define    MKTAG(v)    (((v)<<db->dbz_conf.tagshift)&db->dbz_tagbits)
  164.  
  165. /*
  166.  * A new, from-scratch database, not built as a rebuild of an old one,
  167.  * needs to know table size and tagging.  Normally
  168.  * the user supplies this info, but there have to be defaults.
  169.  */
  170. #ifndef DEFSIZE
  171. #define    DEFSIZE    120011        /* 300007 might be better */
  172. #endif
  173. #ifndef NOTAGS
  174. #define    TAGENB    0x80        /* tag enable is top bit, tag is next 7 */
  175. #define    TAGMASK    0x7f
  176. #define    TAGSHIFT    24
  177. #else
  178. #define    TAGENB    0        /* no tags */
  179. #define    TAGMASK    0
  180. #define    TAGSHIFT    0
  181. #endif
  182.  
  183. static int getconf();
  184. static long getno();
  185. static int putconf();
  186. static void mybytemap();
  187. static of_t bytemap();
  188.  
  189. /* 
  190.  * For a program that makes many, many references to the database, it
  191.  * is a large performance win to keep the table in core, if it will fit.
  192.  * Note that this does hurt robustness in the event of crashes, and
  193.  * dbz_close() *must* be called to flush the in-core database to disk.
  194.  * The code is prepared to deal with the possibility that there isn't
  195.  * enough memory.  There *is* an assumption that a size_t is big enough
  196.  * to hold the size (in bytes) of one table, so dbz_open() tries to figure
  197.  * out whether this is possible first.
  198.  *
  199.  * The preferred way to ask for an in-core table is to do dbzincore(1)
  200.  * before dbz_open().  The default is not to do it, although -DINCORE
  201.  * overrides this for backward compatibility with old dbz.
  202.  *
  203.  * We keep only the first table in core.  This greatly simplifies the
  204.  * code, and bounds memory demand.  Furthermore, doing this is a large
  205.  * performance win even in the event of massive overflow.
  206.  */
  207. #ifdef INCORE
  208. static int default_incore = 1;
  209. #else
  210. static int default_incore = 0;
  211. #endif
  212.  
  213. #        ifndef MAXRUN
  214. #        define    MAXRUN    100
  215. #        endif
  216. static void start();
  217. #define    FRESH    ((struct searcher *)NULL)
  218. static of_t search();
  219. #define    NOTFOUND    ((of_t)-1)
  220. static int okayvalue();
  221. static int set();
  222.  
  223. /*
  224.  * Arguably the searcher struct for a given routine ought to be local to
  225.  * it, but a dbz_fetch() is very often immediately followed by a dbz_store(), and
  226.  * in some circumstances it is a useful performance win to remember where
  227.  * the dbz_fetch() completed.  So we use a global struct and remember whether
  228.  * it is current.
  229.  */
  230.  
  231. /* byte-ordering stuff */
  232. #define    MAPIN(o)    ((db->dbz_bytesame) ? (o) : bytemap((o), db->dbz_conf.bytemap, db->dbz_mybmap))
  233. #define    MAPOUT(o)    ((db->dbz_bytesame) ? (o) : bytemap((o), db->dbz_mybmap, db->dbz_conf.bytemap))
  234.  
  235. /* externals used */
  236. extern int atoi();
  237. extern long atol();
  238.  
  239. /* misc. forwards */
  240. static long hash();
  241. static void crcinit();
  242. static int isprime();
  243. static FILE *latebase();
  244.  
  245. /* file-naming stuff */
  246. static char dir[] = ".dir";
  247. static char pag[] = ".pag";
  248. static char *enstring();
  249.  
  250. /* central data structures */
  251. static of_t *getcore();
  252. static int putcore();
  253.  
  254. /*
  255.  - dbz_fresh - set up a new database, no historical info
  256.  */
  257. DBZ *                /* NULL for failure, !NULL for success */
  258. dbz_fresh(name, size, fs, tagmask)
  259. char *name;            /* base name; .dir and .pag must exist */
  260. long size;            /* table size (0 means default) */
  261. int fs;                /* field-separator character in base file */
  262. of_t tagmask;            /* 0 default, 1 no tags */
  263. {
  264.     register char *fn;
  265.     struct dbzconfig c;
  266.     register of_t m;
  267.     register FILE *f;
  268.  
  269.     if (size != 0 && size < 2) {
  270.         dprint(5, (debugfile, "dbz_fresh: preposterous size (%ld)\n", size));
  271.         return(NULL);
  272.     }
  273.  
  274.     /* get default configuration */
  275.     if (getconf((FILE *)NULL, (FILE *)NULL, &c) < 0)
  276.         return(NULL);    /* "can't happen" */
  277.  
  278.     /* and mess with it as specified */
  279.     if (size != 0)
  280.         c.tsize = size;
  281.     c.fieldsep = fs;
  282.     switch (tagmask) {
  283.     case 0:            /* default */
  284.         break;
  285.     case 1:            /* no tags */
  286.         c.tagshift = 0;
  287.         c.tagmask = 0;
  288.         c.tagenb = 0;
  289.         break;
  290.     default:
  291.         m = tagmask;
  292.         c.tagshift = 0;
  293.         while (!(m&01)) {
  294.             m >>= 1;
  295.             c.tagshift++;
  296.         }
  297.         c.tagmask = m;
  298.         c.tagenb = (m << 1) & ~m;
  299.         break;
  300.     }
  301.  
  302.     /* write it out */
  303.     fn = enstring(name, dir);
  304.     if (fn == NULL)
  305.         return(NULL);
  306.     f = fopen(fn, "w");
  307.     free(fn);
  308.     if (f == NULL) {
  309.         dprint(5, (debugfile, "dbz_fresh: unable to write config\n"));
  310.         return(NULL);
  311.     }
  312.     if (putconf(f, &c) < 0) {
  313.         (void) fclose(f);
  314.         return(NULL);
  315.     }
  316.     if (fclose(f) == EOF) {
  317.         dprint(5, (debugfile, "dbz_fresh: fclose failure\n"));
  318.         return(NULL);
  319.     }
  320.  
  321.     /* create/truncate .pag */
  322.     fn = enstring(name, pag);
  323.     if (fn == NULL)
  324.         return(NULL);
  325.     f = fopen(fn, "w");
  326.     free(fn);
  327.     if (f == NULL) {
  328.         dprint(5, (debugfile, "dbz_fresh: unable to create/truncate .pag file\n"));
  329.         return(NULL);
  330.     } else
  331.         (void) fclose(f);
  332.  
  333.     /* and punt to dbz_open for the hard work */
  334.     return(dbz_open(name, O_RDWR, 0));
  335. }
  336.  
  337. /*
  338.  - dbz_size - what's a good table size to hold this many entries?
  339.  */
  340. long
  341. dbzsize(contents)
  342. long contents;            /* 0 means what's the default */
  343. {
  344.     register long n;
  345.  
  346.     if (contents <= 0) {    /* foulup or default inquiry */
  347.         dprint(5, (debugfile, "dbzsize: preposterous input (%ld)\n", contents));
  348.         return(DEFSIZE);
  349.     }
  350.     n = (contents/2)*3;    /* try to keep table at most 2/3 full */
  351.     if (!(n&01))        /* make it odd */
  352.         n++;
  353.     dprint(5, (debugfile, "dbzsize: tentative size %ld\n", n));
  354.     while (!isprime(n))    /* and look for a prime */
  355.         n += 2;
  356.     dprint(5, (debugfile, "dbzsize: final size %ld\n", n));
  357.  
  358.     return(n);
  359. }
  360.  
  361. /*
  362.  - isprime - is a number prime?
  363.  *
  364.  * This is not a terribly efficient approach.
  365.  */
  366. static int            /* predicate */
  367. isprime(x)
  368. register long x;
  369. {
  370.     static int quick[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 0 };
  371.     register int *ip;
  372.     register long div;
  373.     register long stop;
  374.  
  375.     /* hit the first few primes quickly to eliminate easy ones */
  376.     /* this incidentally prevents ridiculously small tables */
  377.     for (ip = quick; (div = *ip) != 0; ip++)
  378.         if (x%div == 0) {
  379.             dprint(5, (debugfile, "isprime: quick result on %ld\n", (long)x));
  380.             return(0);
  381.         }
  382.  
  383.     /* approximate square root of x */
  384.     for (stop = x; x/stop < stop; stop >>= 1)
  385.         continue;
  386.     stop <<= 1;
  387.  
  388.     /* try odd numbers up to stop */
  389.     for (div = *--ip; div < stop; div += 2)
  390.         if (x%div == 0)
  391.             return(0);
  392.  
  393.     return(1);
  394. }
  395.  
  396. /*
  397.  - dbz_again - set up a new database to be a rebuild of an old one
  398.  */
  399. DBZ *                /* NULL for failure, !NULL for success */
  400. dbz_again(name, oldname)
  401. char *name;            /* base name; .dir and .pag must exist */
  402. char *oldname;            /* base name; all must exist */
  403. {
  404.     register char *fn;
  405.     struct dbzconfig c;
  406.     register int i;
  407.     register long top;
  408.     register FILE *f;
  409.     register int newtable;
  410.     register of_t newsize;
  411.  
  412.     /* pick up the old configuration */
  413.     fn = enstring(oldname, dir);
  414.     if (fn == NULL)
  415.         return(NULL);
  416.     f = fopen(fn, "r");
  417.     free(fn);
  418.     if (f == NULL) {
  419.         dprint(5, (debugfile, "dbz_again: cannot open old .dir file\n"));
  420.         return(NULL);
  421.     }
  422.     i = getconf(f, (FILE *)NULL, &c);
  423.     (void) fclose(f);
  424.     if (i < 0) {
  425.         dprint(5, (debugfile, "dbz_again: getconf failed\n"));
  426.         return(NULL);
  427.     }
  428.  
  429.     /* tinker with it */
  430.     top = 0;
  431.     newtable = 0;
  432.     for (i = 0; i < NUSEDS; i++) {
  433.         if (top < c.used[i])
  434.             top = c.used[i];
  435.         if (c.used[i] == 0)
  436.             newtable = 1;    /* hasn't got full usage history yet */
  437.     }
  438.     if (top == 0) {
  439.         dprint(5, (debugfile, "dbz_again: old table has no contents!\n"));
  440.         newtable = 1;
  441.     }
  442.     for (i = NUSEDS-1; i > 0; i--)
  443.         c.used[i] = c.used[i-1];
  444.     c.used[0] = 0;
  445.     newsize = dbzsize(top);
  446.     if (!newtable || newsize > c.tsize)    /* don't shrink new table */
  447.         c.tsize = newsize;
  448.  
  449.     /* write it out */
  450.     fn = enstring(name, dir);
  451.     if (fn == NULL)
  452.         return(NULL);
  453.     f = fopen(fn, "w");
  454.     free(fn);
  455.     if (f == NULL) {
  456.         dprint(5, (debugfile, "dbz_again: unable to write new .dir\n"));
  457.         return(NULL);
  458.     }
  459.     i = putconf(f, &c);
  460.     (void) fclose(f);
  461.     if (i < 0) {
  462.         dprint(5, (debugfile, "dbz_again: putconf failed\n"));
  463.         return(NULL);
  464.     }
  465.  
  466.     /* create/truncate .pag */
  467.     fn = enstring(name, pag);
  468.     if (fn == NULL)
  469.         return(NULL);
  470.     f = fopen(fn, "w");
  471.     free(fn);
  472.     if (f == NULL) {
  473.         dprint(5, (debugfile, "dbz_again: unable to create/truncate .pag file\n"));
  474.         return(NULL);
  475.     } else
  476.         (void) fclose(f);
  477.  
  478.     /* and let dbz_open do the work */
  479.     return(dbz_open(name, O_RDWR, 0));
  480. }
  481.  
  482. /*
  483.  - dbz_open - open a database, creating it (using defaults) if necessary
  484.  *
  485.  * We try to leave errno set plausibly, to the extent that underlying
  486.  * functions permit this, since many people consult it if dbz_open() fails.
  487.  */
  488. DBZ *                /* NULL for failure, !NULL for success */
  489. dbz_open(name, mode, flags)
  490. char *name;
  491. int mode, flags;
  492. {
  493.     register int i;
  494.     register size_t s;
  495.     register DBZ  *db;
  496.     register char *dirfname;
  497.     register char *pagfname;
  498.  
  499.     if ((db = (DBZ *) calloc(sizeof(DBZ), 1)) == NULL) {
  500.         dprint(5, (debugfile, "dbz_open: no room for DBZ structure\n"));
  501.         return(NULL);
  502.     }
  503.     /* open the .dir file */
  504.     dirfname = enstring(name, dir);
  505.     if (dirfname == NULL)
  506.         return(NULL);
  507.  
  508.     if (mode == O_RDONLY) {
  509.         db->dbz_dirf = fopen(dirfname, "r");
  510.         db->dbz_dirronly = 1;
  511.     } else
  512.         db->dbz_dirf = fopen(dirfname, "r+");
  513.     free(dirfname);
  514.     if (db->dbz_dirf == NULL) {
  515.         dprint(5, (debugfile, "dbz_open: can't open .dir file\n"));
  516.         return(NULL);
  517.     }
  518.  
  519.     /* open the .pag file */
  520.     pagfname = enstring(name, pag);
  521.     if (pagfname == NULL) {
  522.         (void) fclose(db->dbz_dirf);
  523.         return(NULL);
  524.     }
  525.     if (mode == O_RDONLY) {
  526.         db->dbz_pagf = fopen(pagfname, "rb");
  527.         db->dbz_pagronly = 1;
  528.     } else
  529.         db->dbz_pagf = fopen(pagfname, "r+b");
  530.  
  531.     if (db->dbz_pagf == NULL) {
  532.         dprint(5, (debugfile, "dbz_open: .pag open failed\n"));
  533.         (void) fclose(db->dbz_dirf);
  534.         free(pagfname);
  535.         return(NULL);
  536.     }
  537. #ifdef NOBUFFER
  538.     /*
  539.      * B News does not do adequate locking on its database accesses.
  540.      * Why it doesn't get into trouble using dbm is a mystery.  In any
  541.      * case, doing unbuffered i/o does not cure the problem, but does
  542.      * enormously reduce its incidence.
  543.      */
  544.     (void) setbuf(db->dbz_pagf, (char *)NULL);
  545. #else
  546. #ifdef _IOFBF
  547.     (void) setvbuf(db->dbz_pagf, (char *)db->dbz_pagbuf, _IOFBF, sizeof(db->dbz_pagbuf));
  548. #endif
  549. #endif
  550.     db->dbz_pagpos = -1;
  551.     /* don't free pagfname, need it below */
  552.  
  553.     /* open the base file */
  554.     db->dbz_basef = fopen(name, "r");
  555.     if (db->dbz_basef == NULL) {
  556.         dprint(5, (debugfile, "dbz_open: basefile open failed\n"));
  557.         db->dbz_basefname = enstring(name, "");
  558.         if (db->dbz_basefname == NULL) {
  559.             (void) fclose(db->dbz_pagf);
  560.             (void) fclose(db->dbz_dirf);
  561.             free(pagfname);
  562.             return(NULL);
  563.         }
  564.     } else
  565.         db->dbz_basefname = NULL;
  566. #ifdef _IOFBF
  567.     if (db->dbz_basef != NULL)
  568.         (void) setvbuf(db->dbz_basef, db->dbz_basebuf, _IOFBF, sizeof(db->dbz_basebuf));
  569. #endif
  570.  
  571.     /* pick up configuration */
  572.     if (getconf(db->dbz_dirf, db->dbz_pagf, &db->dbz_conf) < 0) {
  573.         dprint(5, (debugfile, "dbz_open: getconf failure\n"));
  574.         (void) fclose(db->dbz_basef);
  575.         (void) fclose(db->dbz_pagf);
  576.         (void) fclose(db->dbz_basef);
  577.         (void) fclose(db->dbz_dirf);
  578.         free(pagfname);
  579.         errno = EDOM;    /* kind of a kludge, but very portable */
  580.         return(NULL);
  581.     }
  582.     db->dbz_tagbits = db->dbz_conf.tagmask << db->dbz_conf.tagshift;
  583.     db->dbz_taghere = db->dbz_conf.tagenb << db->dbz_conf.tagshift;
  584.     db->dbz_tagboth = db->dbz_tagbits | db->dbz_taghere;
  585.     mybytemap(db->dbz_mybmap);
  586.     db->dbz_bytesame = 1;
  587.     for (i = 0; i < SOF; i++)
  588.         if (db->dbz_mybmap[i] != db->dbz_conf.bytemap[i])
  589.             db->dbz_bytesame = 0;
  590.  
  591.     /* get first table into core, if it looks desirable and feasible */
  592.     s = (size_t)db->dbz_conf.tsize * SOF;
  593.     db->dbz_incore = default_incore;
  594.     if (db->dbz_incore && (of_t)(s/SOF) == db->dbz_conf.tsize) {
  595.         db->dbz_bufpagf = fopen(pagfname, (db->dbz_pagronly) ? "rb" : "r+b");
  596.         if (db->dbz_bufpagf != NULL)
  597.             db->dbz_corepag = getcore(db);
  598.     } else {
  599.         db->dbz_bufpagf = NULL;
  600.         db->dbz_corepag = NULL;
  601.     }
  602.     free(pagfname);
  603.  
  604.     /* misc. setup */
  605.     crcinit();
  606.     db->dbz_written = 0;
  607.     db->dbz_prevp = FRESH;
  608.     dprint(5, (debugfile, "dbz_open: succeeded\n"));
  609.     return(db);
  610. }
  611.  
  612. /*
  613.  - enstring - concatenate two strings into a malloced area
  614.  */
  615. static char *            /* NULL if malloc fails */
  616. enstring(s1, s2)
  617. char *s1;
  618. char *s2;
  619. {
  620.     register char *p;
  621.  
  622.     p = malloc((size_t)strlen(s1) + (size_t)strlen(s2) + 1);
  623.     if (p != NULL) {
  624.         (void) strcpy(p, s1);
  625.         (void) strcat(p, s2);
  626.     } else {
  627.         dprint(5, (debugfile, "enstring(%s, %s) out of memory\n", s1, s2));
  628.     }
  629.     return(p);
  630. }
  631.  
  632. /*
  633.  - dbz_close - close a database
  634.  */
  635. int
  636. dbz_close(db)
  637. register DBZ *db;
  638. {
  639.     register int ret = 0;
  640.  
  641.     if (db->dbz_pagf == NULL) {
  642.         dprint(5, (debugfile, "dbz_close: not opened!\n"));
  643.         return(-1);
  644.     }
  645.  
  646.     if (fclose(db->dbz_pagf) == EOF) {
  647.         dprint(5, (debugfile, "dbz_close: fclose(pagf) failed\n"));
  648.         ret = -1;
  649.     }
  650.     if (dbz_sync(db) < 0)
  651.         ret = -1;
  652.     if (db->dbz_bufpagf != NULL && fclose(db->dbz_bufpagf) == EOF) {
  653.         dprint(5, (debugfile, "dbz_close: fclose(bufpagf) failed\n"));
  654.         ret = -1;
  655.     }
  656.     if (db->dbz_corepag != NULL)
  657.         free((char *)db->dbz_corepag);
  658.     db->dbz_corepag = NULL;
  659.     if (fclose(db->dbz_basef) == EOF) {
  660.         dprint(5, (debugfile, "dbz_close: fclose(basef) failed\n"));
  661.         ret = -1;
  662.     }
  663.     if (db->dbz_basefname != NULL)
  664.         free(db->dbz_basefname);
  665.     db->dbz_basef = NULL;
  666.     db->dbz_pagf = NULL;
  667.     if (fclose(db->dbz_dirf) == EOF) {
  668.         dprint(5, (debugfile, "dbz_close: fclose(dirf) failed\n"));
  669.         ret = -1;
  670.     }
  671.  
  672.     free((char *) db);
  673.  
  674.     dprint(5, (debugfile, "dbz_close: %s\n", (ret == 0) ? "succeeded" : "failed"));
  675.     return(ret);
  676. }
  677.  
  678. /*
  679.  - dbz_sync - push all in-core data out to disk
  680.  */
  681. int
  682. dbz_sync(db)
  683. register DBZ *db;
  684. {
  685.     register int ret = 0;
  686.  
  687.     if (db->dbz_pagf == NULL) {
  688.         dprint(5, (debugfile, "dbzsync: not opened!\n"));
  689.         return(-1);
  690.     }
  691.     if (!db->dbz_written)
  692.         return(0);
  693.  
  694.     if (db->dbz_corepag != NULL) {
  695.         if (putcore(db) < 0) {
  696.             dprint(5, (debugfile, "dbzsync: putcore failed\n"));
  697.             ret = -1;
  698.         }
  699.     }
  700.     if (!db->dbz_conf.olddbz)
  701.         if (putconf(db->dbz_dirf, &db->dbz_conf) < 0)
  702.             ret = -1;
  703.  
  704.     dprint(5, (debugfile, "dbzsync: %s\n", (ret == 0) ? "succeeded" : "failed"));
  705.     return(ret);
  706. }
  707.  
  708. /*
  709.  - dbzcancel - cancel writing of in-core data
  710.  * Mostly for use from child processes.
  711.  * Note that we don't need to futz around with stdio buffers, because we
  712.  * always fflush them immediately anyway and so they never have stale data.
  713.  */
  714. int
  715. dbz_cancel(db)
  716. register DBZ *db;
  717. {
  718.     if (db->dbz_pagf == NULL) {
  719.         dprint(5, (debugfile, "dbz_cancel: not opened!\n"));
  720.         return(-1);
  721.     }
  722.  
  723.     db->dbz_written = 0;
  724.     return(0);
  725. }
  726.  
  727. /*
  728.  - dbz_fetch - get an entry from the database
  729.  *
  730.  * Disgusting fine point, in the name of backward compatibility:  if the
  731.  * last character of "key" is a NUL, that character is (effectively) not
  732.  * part of the comparison against the stored keys.
  733.  */
  734. datum                /* dptr NULL, dsize 0 means failure */
  735. dbz_fetch(db, key)
  736. register DBZ *db;
  737. datum key;
  738. {
  739.     char buffer[DBZMAXKEY + 1];
  740.     static of_t key_ptr;        /* return value points here */
  741.     datum output;
  742.     register size_t keysize;
  743.     register size_t cmplen;
  744.     register char *sepp;
  745.  
  746.     dprint(5, (debugfile, "dbz_fetch: (%s)\n", key.dptr));
  747.     output.dptr = NULL;
  748.     output.dsize = 0;
  749.     db->dbz_prevp = FRESH;
  750.  
  751.     /* Key is supposed to be less than DBZMAXKEY */
  752.     keysize = key.dsize;
  753.     if (keysize >= DBZMAXKEY) {
  754.         keysize = DBZMAXKEY;
  755.         dprint(5, (debugfile, "keysize is %d - truncated to %d\n", key.dsize, DBZMAXKEY));
  756.     }
  757.  
  758.     if (db->dbz_pagf == NULL) {
  759.         dprint(5, (debugfile, "dbz_fetch: database not open!\n"));
  760.         return(output);
  761.     } else if (db->dbz_basef == NULL) {    /* basef didn't exist yet */
  762.         db->dbz_basef = latebase(db);
  763.         if (db->dbz_basef == NULL)
  764.             return(output);
  765.     }
  766.  
  767.     cmplen = keysize;
  768.     sepp = &db->dbz_conf.fieldsep;
  769.     if (key.dptr[keysize-1] == '\0') {
  770.         cmplen--;
  771.         sepp = &buffer[keysize-1];
  772.     }
  773.     start(db, &key, FRESH);
  774.     while ((key_ptr = search(db)) != NOTFOUND) {
  775.         dprint(5, (debugfile, "got 0x%lx\n", key_ptr));
  776.  
  777.         /* fetch the key */
  778.         if (fseek(db->dbz_basef, key_ptr, SEEK_SET) != 0) {
  779.             dprint(5, (debugfile, "dbz_fetch: seek failed\n"));
  780.             return(output);
  781.         }
  782.         if (fread(buffer, 1, keysize, db->dbz_basef) != keysize) {
  783.             dprint(5, (debugfile, "dbz_fetch: read failed\n"));
  784.             return(output);
  785.         }
  786.  
  787.         /* try it */
  788.         buffer[keysize] = '\0';        /* terminated for DEBUG */
  789.         dprint(5, (debugfile, "dbz_fetch: buffer (%s) looking for (%s) size = %d\n", 
  790.                         buffer, key.dptr, keysize));
  791.         if (bcmp(key.dptr, buffer, cmplen) == 0 &&
  792.                 (*sepp == db->dbz_conf.fieldsep || *sepp == '\0')) {
  793.             /* we found it */
  794.             output.dptr = (char *)&key_ptr;
  795.             output.dsize = SOF;
  796.             dprint(5, (debugfile, "dbz_fetch: successful\n"));
  797.             return(output);
  798.         }
  799.     }
  800.  
  801.     /* we didn't find it */
  802.     dprint(5, (debugfile, "dbz_fetch: failed\n"));
  803.     db->dbz_prevp = &db->dbz_srch;            /* remember where we stopped */
  804.     return(output);
  805. }
  806.  
  807. /*
  808.  - latebase - try to open a base file that wasn't there at the start
  809.  */
  810. static FILE *
  811. latebase(db)
  812. register DBZ *db;
  813. {
  814.     register FILE *it;
  815.  
  816.     if (db->dbz_basefname == NULL) {
  817.         dprint(5, (debugfile, "latebase: name foulup\n"));
  818.         return(NULL);
  819.     }
  820.     it = fopen(db->dbz_basefname, "r");
  821.     if (it == NULL) {
  822.         dprint(5, (debugfile, "latebase: still can't open base\n"));
  823.     } else {
  824.         dprint(5, (debugfile, "latebase: late open succeeded\n"));
  825.         free(db->dbz_basefname);
  826.         db->dbz_basefname = NULL;
  827. #ifdef _IOFBF
  828.         (void) setvbuf(it, db->dbz_basebuf, _IOFBF, sizeof(db->dbz_basebuf));
  829. #endif
  830.     }
  831.     return(it);
  832. }
  833.  
  834. /*
  835.  - dbz_store - add an entry to the database
  836.  */
  837. int                /* 0 success, -1 failure */
  838. dbz_store(db, key, data)
  839. register DBZ *db;
  840. datum key;
  841. datum data;
  842. {
  843.     of_t value;
  844.  
  845.     if (db->dbz_pagf == NULL) {
  846.         dprint(5, (debugfile, "dbz_store: database not open!\n"));
  847.         return(-1);
  848.     } else if (db->dbz_basef == NULL) {    /* basef didn't exist yet */
  849.         db->dbz_basef = latebase(db);
  850.         if (db->dbz_basef == NULL)
  851.             return(-1);
  852.     }
  853.     if (db->dbz_pagronly) {
  854.         dprint(5, (debugfile, "dbz_store: database open read-only\n"));
  855.         return(-1);
  856.     }
  857.     if (data.dsize != SOF) {
  858.         dprint(5, (debugfile, "dbz_store: value size wrong (%d)\n", data.dsize));
  859.         return(-1);
  860.     }
  861.     if (key.dsize >= DBZMAXKEY) {
  862.         dprint(5, (debugfile, "dbz_store: key size too big (%d)\n", key.dsize));
  863.         return(-1);
  864.     }
  865.  
  866.     /* copy the value in to ensure alignment */
  867.     (void) bcopy(data.dptr, (char *)&value, SOF);
  868.     dprint(5, (debugfile, "dbz_store: (%s, %ld)\n", key.dptr, (long)value));
  869.     if (!okayvalue(db, value)) {
  870.         dprint(5, (debugfile, "dbz_store: reserved bit or overflow in 0x%lx\n", value));
  871.         return(-1);
  872.     }
  873.  
  874.     /* find the place, exploiting previous search if possible */
  875.     start(db, &key, db->dbz_prevp);
  876.     while (search(db) != NOTFOUND)
  877.         continue;
  878.  
  879.     db->dbz_prevp = FRESH;
  880.     db->dbz_conf.used[0]++;
  881.     dprint(5, (debugfile, "dbz_store: used count %ld\n", db->dbz_conf.used[0]));
  882.     db->dbz_written = 1;
  883.     return(set(db, value));
  884. }
  885.  
  886. /*
  887.  - dbz_incore - control attempts to keep .pag file in core
  888.  */
  889. int                /* old setting */
  890. dbz_incore(value)
  891. int value;
  892. {
  893.     register int old = default_incore;
  894.  
  895.     default_incore = value;
  896.     return(old);
  897. }
  898.  
  899. /*
  900.  - getconf - get configuration from .dir file
  901.  */
  902. static int            /* 0 success, -1 failure */
  903. getconf(df, pf, cp)
  904. register FILE *df;        /* NULL means just give me the default */
  905. register FILE *pf;        /* NULL means don't care about .pag */
  906. register struct dbzconfig *cp;
  907. {
  908.     register int c;
  909.     register int i;
  910.     int err = 0;
  911.  
  912.     c = (df != NULL) ? getc(df) : EOF;
  913.     if (c == EOF) {        /* empty file, no configuration known */
  914.         cp->olddbz = 0;
  915.         if (df != NULL && pf != NULL && getc(pf) != EOF)
  916.             cp->olddbz = 1;
  917.         cp->tsize = DEFSIZE;
  918.         cp->fieldsep = '\t';
  919.         for (i = 0; i < NUSEDS; i++)
  920.             cp->used[i] = 0;
  921.         cp->valuesize = SOF;
  922.         mybytemap(cp->bytemap);
  923.         cp->tagenb = TAGENB;
  924.         cp->tagmask = TAGMASK;
  925.         cp->tagshift = TAGSHIFT;
  926.         dprint(5, (debugfile, "getconf: defaults (%ld, (0x%lx/0x%lx<<%d))\n",
  927.             cp->tsize, cp->tagenb, cp->tagmask, cp->tagshift));
  928.         return(0);
  929.     }
  930.     (void) ungetc(c, df);
  931.  
  932.     /* first line, the vital stuff */
  933.     if (getc(df) != 'd' || getc(df) != 'b' || getc(df) != 'z')
  934.         err = -1;
  935.     if (getno(df, &err) != dbzversion)
  936.         err = -1;
  937.     cp->tsize = getno(df, &err);
  938.     cp->fieldsep = getno(df, &err);
  939.     while ((c = getc(df)) == ' ')
  940.         continue;
  941.     cp->tagenb = getno(df, &err);
  942.     cp->tagmask = getno(df, &err);
  943.     cp->tagshift = getno(df, &err);
  944.     cp->valuesize = getno(df, &err);
  945.     if (cp->valuesize != SOF) {
  946.         dprint(5, (debugfile, "getconf: wrong of_t size (%d)\n", cp->valuesize));
  947.         err = -1;
  948.         cp->valuesize = SOF;    /* to protect the loops below */
  949.     }
  950.     for (i = 0; i < cp->valuesize; i++)
  951.         cp->bytemap[i] = getno(df, &err);
  952.     if (getc(df) != '\n')
  953.         err = -1;
  954.     dprint(5, (debugfile, "size %ld, sep %d, tags 0x%lx/0x%lx<<%d, ", cp->tsize,
  955.             cp->fieldsep, cp->tagenb, cp->tagmask, cp->tagshift));
  956.     dprint(5, (debugfile, "bytemap (%d)", cp->valuesize));
  957.     for (i = 0; i < cp->valuesize; i++) {
  958.         dprint(5, (debugfile, " %d", cp->bytemap[i]));
  959.     }
  960.     dprint(5, (debugfile, "\n"));
  961.  
  962.     /* second line, the usages */
  963.     for (i = 0; i < NUSEDS; i++)
  964.         cp->used[i] = getno(df, &err);
  965.     if (getc(df) != '\n')
  966.         err = -1;
  967.     dprint(5, (debugfile, "used %ld %ld %ld...\n", cp->used[0], cp->used[1], cp->used[2]));
  968.  
  969.     if (err < 0) {
  970.         dprint(5, (debugfile, "getconf error\n"));
  971.         return(-1);
  972.     }
  973.     return(0);
  974. }
  975.  
  976. /*
  977.  - getno - get a long
  978.  */
  979. static long
  980. getno(f, ep)
  981. FILE *f;
  982. int *ep;
  983. {
  984.     register char *p;
  985. #    define    MAXN    50
  986.     char getbuf[MAXN];
  987.     register int c;
  988.  
  989.     while ((c = getc(f)) == ' ')
  990.         continue;
  991.     if (c == EOF || c == '\n') {
  992.         dprint(5, (debugfile, "getno: missing number\n"));
  993.         *ep = -1;
  994.         return(0);
  995.     }
  996.     p = getbuf;
  997.     *p++ = c;
  998.     while ((c = getc(f)) != EOF && c != '\n' && c != ' ')
  999.         if (p < &getbuf[MAXN-1])
  1000.             *p++ = c;
  1001.     if (c == EOF) {
  1002.         dprint(5, (debugfile, "getno: EOF\n"));
  1003.         *ep = -1;
  1004.     } else
  1005.         (void) ungetc(c, f);
  1006.     *p = '\0';
  1007.  
  1008.     if (strspn(getbuf, "-1234567890") != strlen(getbuf)) {
  1009.         dprint(5, (debugfile, "getno: `%s' non-numeric\n", getbuf));
  1010.         *ep = -1;
  1011.     }
  1012.     return(atol(getbuf));
  1013. }
  1014.  
  1015. /*
  1016.  - putconf - write configuration to .dir file
  1017.  */
  1018. static int            /* 0 success, -1 failure */
  1019. putconf(f, cp)
  1020. register FILE *f;
  1021. register struct dbzconfig *cp;
  1022. {
  1023.     register int i;
  1024.     register int ret = 0;
  1025.  
  1026.     if (fseek(f, (of_t)0, SEEK_SET) != 0) {
  1027.         dprint(5, (debugfile, "fseek failure in putconf\n"));
  1028.         ret = -1;
  1029.     }
  1030.     fprintf(f, "dbz %d %ld %d %ld %ld %d %d", dbzversion, cp->tsize,
  1031.                 cp->fieldsep, cp->tagenb,
  1032.                 cp->tagmask, cp->tagshift, cp->valuesize);
  1033.     for (i = 0; i < cp->valuesize; i++)
  1034.         fprintf(f, " %d", cp->bytemap[i]);
  1035.     fprintf(f, "\n");
  1036.     for (i = 0; i < NUSEDS; i++)
  1037.         fprintf(f, "%ld%c", cp->used[i], (i < NUSEDS-1) ? ' ' : '\n');
  1038.  
  1039.     (void) fflush(f);
  1040.     if (ferror(f))
  1041.         ret = -1;
  1042.  
  1043.     dprint(5, (debugfile, "putconf status %d\n", ret));
  1044.     return(ret);
  1045. }
  1046.  
  1047. /*
  1048.  - getcore - try to set up an in-core copy of .pag file
  1049.  */
  1050. static of_t *            /* pointer to copy, or NULL */
  1051. getcore(db)
  1052. register DBZ *db;
  1053. {
  1054.     register of_t *p;
  1055.     register size_t i;
  1056.     register size_t nread;
  1057.     register char *it;
  1058.  
  1059.     it = malloc((size_t)db->dbz_conf.tsize * SOF);
  1060.     if (it == NULL) {
  1061.         dprint(5, (debugfile, "getcore: malloc failed\n"));
  1062.         return(NULL);
  1063.     }
  1064.  
  1065.     nread = fread(it, SOF, (size_t)db->dbz_conf.tsize, db->dbz_bufpagf);
  1066.     if (ferror(db->dbz_bufpagf)) {
  1067.         dprint(5, (debugfile, "getcore: read failed\n"));
  1068.         free(it);
  1069.         return(NULL);
  1070.     }
  1071.  
  1072.     p = (of_t *)it + nread;
  1073.     i = (size_t)db->dbz_conf.tsize - nread;
  1074.     while (i-- > 0)
  1075.         *p++ = VACANT;
  1076.     return((of_t *)it);
  1077. }
  1078.  
  1079. /*
  1080.  - putcore - try to rewrite an in-core table
  1081.  */
  1082. static int            /* 0 okay, -1 fail */
  1083. putcore(db)
  1084. register DBZ *db;
  1085. {
  1086.     if (fseek(db->dbz_bufpagf, (of_t)0, SEEK_SET) != 0) {
  1087.         dprint(5, (debugfile, "fseek failure in putcore\n"));
  1088.         return(-1);
  1089.     }
  1090.     (void) fwrite((char *)db->dbz_corepag, SOF, (size_t)db->dbz_conf.tsize, db->dbz_bufpagf);
  1091.     (void) fflush(db->dbz_bufpagf);
  1092.     return((ferror(db->dbz_bufpagf)) ? -1 : 0);
  1093. }
  1094.  
  1095. /*
  1096.  - start - set up to start or restart a search
  1097.  */
  1098. static void
  1099. start(db, kp, osp)
  1100. register DBZ *db;
  1101. register datum *kp;
  1102. register struct searcher *osp;        /* may be FRESH, i.e. NULL */
  1103. {
  1104.     register struct searcher *sp = &db->dbz_srch;
  1105.     register long h;
  1106.  
  1107.     h = hash(kp->dptr, kp->dsize);
  1108.     if (osp != FRESH && osp->hash == h) {
  1109.         if (sp != osp)
  1110.             *sp = *osp;
  1111.         dprint(5, (debugfile, "search restarted\n"));
  1112.     } else {
  1113.         sp->hash = h;
  1114.         sp->tag = MKTAG(h / db->dbz_conf.tsize);
  1115.         dprint(5, (debugfile, "tag 0x%lx\n", sp->tag));
  1116.         sp->place = h % db->dbz_conf.tsize;
  1117.         sp->tabno = 0;
  1118.         sp->run = (db->dbz_conf.olddbz) ? db->dbz_conf.tsize : MAXRUN;
  1119.         sp->aborted = 0;
  1120.     }
  1121.     sp->seen = 0;
  1122. }
  1123.  
  1124. /*
  1125.  - search - conduct part of a search
  1126.  */
  1127. static of_t            /* NOTFOUND if we hit VACANT or error */
  1128. search(db)
  1129. register DBZ *db;
  1130. {
  1131.     register struct searcher *sp = &db->dbz_srch;
  1132.     register of_t dest;
  1133.     register of_t value;
  1134.     of_t val;        /* buffer for value (can't fread register) */
  1135.     register of_t place;
  1136.  
  1137.     if (sp->aborted)
  1138.         return(NOTFOUND);
  1139.  
  1140.     for (;;) {
  1141.         /* determine location to be examined */
  1142.         place = sp->place;
  1143.         if (sp->seen) {
  1144.             /* go to next location */
  1145.             if (--sp->run <= 0) {
  1146.                 sp->tabno++;
  1147.                 sp->run = MAXRUN;
  1148.             }
  1149.             place = (place+1)%db->dbz_conf.tsize + sp->tabno*db->dbz_conf.tsize;
  1150.             sp->place = place;
  1151.         } else
  1152.             sp->seen = 1;    /* now looking at current location */
  1153.         dprint(5, (debugfile, "search @ %ld\n", place));
  1154.  
  1155.         /* get the tagged value */
  1156.         if (db->dbz_corepag != NULL && place < db->dbz_conf.tsize) {
  1157.             dprint(5, (debugfile, "search: in core\n"));
  1158.             value = MAPIN(db->dbz_corepag[place]);
  1159.         } else {
  1160.             /* seek, if necessary */
  1161.             dest = place * SOF;
  1162.             if (db->dbz_pagpos != dest) {
  1163.                 if (fseek(db->dbz_pagf, dest, SEEK_SET) != 0) {
  1164.                     dprint(5, (debugfile, "search: seek failed\n"));
  1165.                     db->dbz_pagpos = -1;
  1166.                     sp->aborted = 1;
  1167.                     return(NOTFOUND);
  1168.                 }
  1169.                 db->dbz_pagpos = dest;
  1170.             }
  1171.  
  1172.             /* read it */
  1173.             if (fread((char *)&val, sizeof(val), 1, db->dbz_pagf) == 1)
  1174.                 value = MAPIN(val);
  1175.             else if (ferror(db->dbz_pagf)) {
  1176.                 dprint(5, (debugfile, "search: read failed\n"));
  1177.                 db->dbz_pagpos = -1;
  1178.                 sp->aborted = 1;
  1179.                 return(NOTFOUND);
  1180.             } else
  1181.                 value = VACANT;
  1182.  
  1183.             /* and finish up */
  1184.             db->dbz_pagpos += sizeof(val);
  1185.         }
  1186.  
  1187.         /* vacant slot is always cause to return */
  1188.         if (value == VACANT) {
  1189.             dprint(5, (debugfile, "search: empty slot\n"));
  1190.             return(NOTFOUND);
  1191.         };
  1192.  
  1193.         /* check the tag */
  1194.         value = UNBIAS(value);
  1195.         dprint(5, (debugfile, "got 0x%lx\n", value));
  1196.         if (!HASTAG(value)) {
  1197.             dprint(5, (debugfile, "tagless\n"));
  1198.             return(value);
  1199.         } else if (TAG(value) == sp->tag | db->dbz_taghere) {
  1200.             dprint(5, (debugfile, "match\n"));
  1201.             return(NOTAG(value));
  1202.         } else {
  1203.             dprint(5, (debugfile, "mismatch 0x%lx\n", TAG(value)));
  1204.         }
  1205.     }
  1206.     /* NOTREACHED */
  1207. }
  1208.  
  1209. /*
  1210.  - okayvalue - check that a value can be stored
  1211.  */
  1212. static int            /* predicate */
  1213. okayvalue(db, value)
  1214. register DBZ *db;
  1215. of_t value;
  1216. {
  1217.     if (HASTAG(value))
  1218.         return(0);
  1219. #ifdef OVERFLOW
  1220.     if (value == LONG_MAX)    /* BIAS() and UNBIAS() will overflow */
  1221.         return(0);
  1222. #endif
  1223.     return(1);
  1224. }
  1225.  
  1226. /*
  1227.  - set - store a value into a location previously found by search
  1228.  */
  1229. static int            /* 0 success, -1 failure */
  1230. set(db, value)
  1231. register DBZ *db;
  1232. of_t value;
  1233. {
  1234.     register struct searcher *sp  = &db->dbz_srch;
  1235.     register of_t place = sp->place;
  1236.     register of_t v = value;
  1237.  
  1238.     if (sp->aborted)
  1239.         return(-1);
  1240.  
  1241.     if (CANTAG(v) && !db->dbz_conf.olddbz) {
  1242.         v |= sp->tag | db->dbz_taghere;
  1243.         if (v != UNBIAS(VACANT))    /* BIAS(v) won't look VACANT */
  1244. #ifdef OVERFLOW
  1245.             if (v != LONG_MAX)    /* and it won't overflow */
  1246. #endif
  1247.             value = v;
  1248.     }
  1249.     dprint(5, (debugfile, "tagged value is 0x%lx\n", value));
  1250.     value = BIAS(value);
  1251.     value = MAPOUT(value);
  1252.  
  1253.     /* If we have the index file in memory, use it */
  1254.     if (db->dbz_corepag != NULL && place < db->dbz_conf.tsize) {
  1255.         db->dbz_corepag[place] = value;
  1256.         dprint(5, (debugfile, "set: incore\n"));
  1257.         return(0);
  1258.     }
  1259.  
  1260.     /* seek to spot */
  1261.     db->dbz_pagpos = -1;        /* invalidate position memory */
  1262.     if (fseek(db->dbz_pagf, place * SOF, SEEK_SET) != 0) {
  1263.         dprint(5, (debugfile, "set: seek failed\n"));
  1264.         sp->aborted = 1;
  1265.         return(-1);
  1266.     }
  1267.  
  1268.     /* write in data */
  1269.     if (fwrite((char *)&value, SOF, 1, db->dbz_pagf) != 1) {
  1270.         dprint(5, (debugfile, "set: write failed\n"));
  1271.         sp->aborted = 1;
  1272.         return(-1);
  1273.     }
  1274.     /* fflush improves robustness, and buffer re-use is rare anyway */
  1275.     if (fflush(db->dbz_pagf) == EOF) {
  1276.         dprint(5, (debugfile, "set: fflush failed\n"));
  1277.         sp->aborted = 1;
  1278.         return(-1);
  1279.     }
  1280.  
  1281.     dprint(5, (debugfile, "set: succeeded\n"));
  1282.     return(0);
  1283. }
  1284.  
  1285. /*
  1286.  - mybytemap - determine this machine's byte map
  1287.  *
  1288.  * A byte map is an array of ints, sizeof(of_t) of them.  The 0th int
  1289.  * is the byte number of the high-order byte in my of_t, and so forth.
  1290.  */
  1291. static void
  1292. mybytemap(map)
  1293. int map[];            /* -> int[SOF] */
  1294. {
  1295.     union {
  1296.         of_t o;
  1297.         char c[SOF];
  1298.     } u;
  1299.     register int *mp = &map[SOF];
  1300.     register int ntodo;
  1301.     register int i;
  1302.  
  1303.     u.o = 1;
  1304.     for (ntodo = (int)SOF; ntodo > 0; ntodo--) {
  1305.         for (i = 0; i < SOF; i++)
  1306.             if (u.c[i] != 0)
  1307.                 break;
  1308.         if (i == SOF) {
  1309.             /* trouble -- set it to *something* consistent */
  1310.             dprint(5, (debugfile, "mybytemap: nonexistent byte %d!!!\n", ntodo));
  1311.             for (i = 0; i < SOF; i++)
  1312.                 map[i] = i;
  1313.             return;
  1314.         }
  1315.         dprint(5, (debugfile, "mybytemap: byte %d\n", i));
  1316.         *--mp = i;
  1317.         while (u.c[i] != 0)
  1318.             u.o <<= 1;
  1319.     }
  1320. }
  1321.  
  1322. /*
  1323.  - bytemap - transform an of_t from byte ordering map1 to map2
  1324.  */
  1325. static of_t            /* transformed result */
  1326. bytemap(ino, map1, map2)
  1327. of_t ino;
  1328. int *map1;
  1329. int *map2;
  1330. {
  1331.     union oc {
  1332.         of_t o;
  1333.         char c[SOF];
  1334.     };
  1335.     union oc in;
  1336.     union oc out;
  1337.     register int i;
  1338.  
  1339.     in.o = ino;
  1340.     for (i = 0; i < SOF; i++)
  1341.         out.c[map2[i]] = in.c[map1[i]];
  1342.     return(out.o);
  1343. }
  1344.  
  1345. /*
  1346.  * This is a simplified version of the pathalias hashing function.
  1347.  * Thanks to Steve Belovin and Peter Honeyman
  1348.  *
  1349.  * hash a string into a long int.  31 bit crc (from andrew appel).
  1350.  * the crc table is computed at run time by crcinit() -- we could
  1351.  * precompute, but it takes 1 clock tick on a 750.
  1352.  *
  1353.  * This fast table calculation works only if POLY is a prime polynomial
  1354.  * in the field of integers modulo 2.  Since the coefficients of a
  1355.  * 32-bit polynomial won't fit in a 32-bit word, the high-order bit is
  1356.  * implicit.  IT MUST ALSO BE THE CASE that the coefficients of orders
  1357.  * 31 down to 25 are zero.  Happily, we have candidates, from
  1358.  * E. J.  Watson, "Primitive Polynomials (Mod 2)", Math. Comp. 16 (1962):
  1359.  *    x^32 + x^7 + x^5 + x^3 + x^2 + x^1 + x^0
  1360.  *    x^31 + x^3 + x^0
  1361.  *
  1362.  * We reverse the bits to get:
  1363.  *    111101010000000000000000000000001 but drop the last 1
  1364.  *         f   5   0   0   0   0   0   0
  1365.  *    010010000000000000000000000000001 ditto, for 31-bit crc
  1366.  *       4   8   0   0   0   0   0   0
  1367.  */
  1368.  
  1369. #define POLY 0x48000000L    /* 31-bit polynomial (avoids sign problems) */
  1370.  
  1371. static long CrcTable[128];
  1372.  
  1373. /*
  1374.  - crcinit - initialize tables for hash function
  1375.  */
  1376. static void
  1377. crcinit()
  1378. {
  1379.     register int i, j;
  1380.     register long sum;
  1381.  
  1382.     for (i = 0; i < 128; ++i) {
  1383.         sum = 0L;
  1384.         for (j = 7 - 1; j >= 0; --j)
  1385.             if (i & (1 << j))
  1386.                 sum ^= POLY >> j;
  1387.         CrcTable[i] = sum;
  1388.     }
  1389.     dprint(5, (debugfile, "crcinit: done\n"));
  1390. }
  1391.  
  1392. /*
  1393.  - hash - Honeyman's nice hashing function
  1394.  */
  1395. static long
  1396. hash(name, size)
  1397. register char *name;
  1398. register int size;
  1399. {
  1400.     register long sum = 0L;
  1401.  
  1402.     while (size--) {
  1403.         sum = (sum >> 7) ^ CrcTable[(sum ^ (*name++)) & 0x7f];
  1404.     }
  1405.     dprint(5, (debugfile, "hash: returns (%ld)\n", sum));
  1406.     return(sum);
  1407. }
  1408.  
  1409. /*
  1410.  - dbzdebug - control dbz debugging at run time
  1411.  */
  1412. int                /* old value */
  1413. dbzdebug(value)
  1414. int value;
  1415. {
  1416. #ifdef DBZDEBUG
  1417.     register int old = debug;
  1418.  
  1419.     debug = value;
  1420.     return(old);
  1421. #else
  1422.     return(-1);
  1423. #endif
  1424. }
  1425.