Added filter function. Not much of effect on the small test set...
[idzebra-moved-to-github.git] / isamc / merge-d.c
1 /*
2  * Copyright (c) 1996-1998, Index Data.
3  * See the file LICENSE for details.
4  * Heikki Levanto
5  *
6  * $Id: merge-d.c,v 1.21 1999-09-21 17:36:43 heikki Exp $
7  *
8  * bugs
9  *   (none)
10  *
11  * missing
12  *
13  * optimize
14  *  - Input filter: Eliminate del-ins pairs, tell if only one entry (or none)
15  *  - single-entry optimizing (keep the one entry in the dict, no block)
16  *  - study and optimize block sizes (later)
17  *  - find a way to decide the size of an empty diffblock (after merge)
18  *  - On allocating more blocks (in append and merge), check the order of 
19  *    blocks, and if needed, swap them. 
20  *  - Write a routine to save/load indexes into a block, save only as many 
21  *    bytes as needed (size, diff, diffindexes)
22  *
23  *
24  * caveat
25  *  There is a confusion about the block addresses. cat or type is the category,
26  *  pos or block is the block number. pp structures keep these two separate,
27  *  and combine when saving the pp. The next pointer in the pp structure is
28  *  also a combined address, but needs to be combined every time it is needed,
29  *  and separated when the partss are needed... This is done with the isamd_
30  *  _block, _type, and _addr macros. The _addr takes block and type as args,
31  *  in that order. This conflicts with the order these are often mentioned in 
32  *  the debug log calls, and other places, leading to small mistakes here
33  *  and there. 
34  *
35  *  Needs cleaning! The way diff blocks are handled in append and reading is
36  *  quite different, and likely to give maintenance problems.
37  *
38  *  log levels (set isamddebug=x in zebra.cfg (or what ever cfg file you use) )
39  *    0 = no logging. Default
40  *    1 = no logging here. isamd logs overall statistics
41  *    2 = Each call to isamd_append with start address and no more
42  *    3 = Start and type of append, start of merge, and result of append
43  *    4 = Block allocations
44  *    5 = Block-level operations (read/write)
45  *    6 = Details about diff blocks etc.
46  *    7 = Log each record as it passes the system (once)
47  *    8 = Log raw and (de)coded data
48  *    9 = Anything else that may be useful
49  *   .. = Anything needed to hunt a specific bug
50  *  (note that all tests in the code are like debug>3, which means 4 or above!)
51  *
52  * Design for the new and improved isamd
53  * Key points:
54  *  - The first block is only diffs, no straight data
55  *  - Additional blocks are straight data
56  *  - When a diff block gets filled up, a data block is created by
57  *    merging the diffs with the data
58  *
59  * Structure
60  *  - Isamd_pp: buffer for diffs and for data
61  *              keep both pos, type, and combined address
62  *              routine to set the address
63  *  - diffbuf: lengths as short ints, or bytes for small blocks
64  *  - keys are of key_struct, not just a number of bytes.
65  *
66  * Routines
67  *  - isamd_append
68  *    - create_new_block if needed
69  *    - append_diffs
70  *      - load_diffs 
71  *      - get diffend, start encoding
72  *      - while input data
73  *        - encode it
74  *        - if no room, then realloc block in larger size
75  *        - if still no room, merge and exit
76  *        - append in the block
77  *
78  * - merge
79  *   - just as before, except that merges also input data directly
80  *   - writes into new data blocks
81  *       
82  *      
83  * - isamd.c: load firstpp, load datablock
84  *            save firstpp, save datablock
85  * - Readlength, writelength - handling right size of len fields
86  * - isamd_read_main_item: take also a merge input structure, and merge it too
87  * - prefilter: cache two inputs, and check if they cancel.
88  * - single-item optimization
89  * 
90  * questions: Should we realloc firstblocks in a different size as the main
91  * blocks. Makes a sideways seek, which is bound to be slowe. But saves some
92  * update time. Compromise: alloc the first one in the size of the datablock,
93  * but increase if necessary. Large blocks get a large diff, ok. Small ones
94  * may get an extra seek in read, but save merges.
95  */
96
97
98 #define NEW_ISAM_D 1  /* not yet ready to delete the old one! */
99
100 #include <stdlib.h>
101 #include <assert.h>
102 #include <string.h>
103 #include <stdio.h>
104 #include <log.h>
105 #include "../index/index.h"
106 #include "isamd-p.h"
107
108
109 struct ISAMD_DIFF_s {
110   int diffidx;
111   int maxidx;
112   struct it_key key;
113   void *decodeData;
114   int mode;
115   int difftype;  
116 };
117
118 #define DT_NONE 0 // no diff, marks end of sequence
119 #define DT_DIFF 1 // ordinarry diff
120 #define DT_MAIN 2 // main data
121 #define DT_INPU 3 // input data to be merged
122 #define DT_DONE 4 // done with all input here
123
124
125
126 /***************************************************************
127  * Input preprocess filter
128  ***************************************************************/
129
130
131 #define FILTER_NOTYET -1  /* no data read in yet, to be done */
132
133 struct ISAMD_FILTER_s {
134   ISAMD_I data;          /* where the data comes from */
135   ISAMD is;              /* for debug flags */
136   struct it_key k1;      /* the next item to be returned */
137   int           m1;      /* mode for k1 */
138   int           r1;      /* result for read of k1, or NOTYET */
139   struct it_key k2;      /* the one after that */
140   int           m2;
141   int           r2;
142 };
143
144 typedef struct ISAMD_FILTER_s *FILTER;
145
146
147 void filter_fill(FILTER F)
148 {
149   while ( (F->r1 == FILTER_NOTYET) || (F->r2 == FILTER_NOTYET) )
150   {
151      if (F->r1==FILTER_NOTYET) 
152      { /* move data forward in the filter */
153         F->k1 = F->k2;
154         F->m1 = F->m2;
155         F->r1 = F->r2;
156         if ( 0 != F->r1 ) /* not eof */
157           F->r2 = FILTER_NOTYET; /* say we want more */
158         if (F->is->method->debug > 9)  
159           logf(LOG_LOG,"filt_fill: shift %d.%d m=%d r=%d",
160              F->k1.sysno, 
161              F->k1.seqno, 
162              F->m1, F->r1);
163      }
164      if (F->r2==FILTER_NOTYET)
165      { /* read new bottom value */
166         char *k_ptr = (char*) &F->k2;
167         F->r2 = (F->data->read_item)(F->data->clientData, &k_ptr, &F->m2); 
168         if (F->is->method->debug > 9)
169           logf(LOG_LOG,"filt_fill: read %d.%d m=%d r=%d",
170              F->k2.sysno, F->k2.seqno, F->m2, F->r2);
171      }  
172      if ( (F->k1.sysno == F->k2.sysno) && 
173           (F->k1.seqno == F->k2.seqno) &&
174           (F->m1 != F->m2) &&
175           (F->r1 >0 ) && (F->r2 >0) )
176      { /* del-ins pair of same key (not eof) , ignore both */
177        if (F->is->method->debug > 9)
178          logf(LOG_LOG,"filt_fill: skipped %d.%d m=%d/%d r=%d/%d",
179             F->k1.sysno, F->k1.seqno, 
180             F->m1,F->m2, F->r1,F->r2);
181        F->r1 = FILTER_NOTYET;
182        F->r2 = FILTER_NOTYET;
183      }
184   } /* while */
185 } /* filter_fill */
186
187
188 FILTER filter_open( ISAMD is, ISAMD_I data )
189 {
190   FILTER F = (FILTER) xmalloc(sizeof(struct ISAMD_FILTER_s));
191   F->is = is;
192   F->data = data;
193   F->k1.sysno=0;
194   F->k1.seqno=0;
195   F->k2=F->k1; 
196   F->m1 = F->m2 = 0;
197   F->r1 = F->r2 = FILTER_NOTYET;
198   filter_fill(F);
199 }
200
201 static void filter_close (FILTER F)
202 {
203   xfree(F);
204 }
205
206 static int filter_read( FILTER F, 
207                         struct it_key *k,
208                         int *mode)
209 {
210   int res;
211   filter_fill(F);
212   if (F->is->method->debug > 9)
213     logf(LOG_LOG,"filt_read: reading %d.%d m=%d r=%d",
214        F->k1.sysno, F->k1.seqno, F->m1, F->r1);
215   res  = F->r1;
216   if(res) 
217   {
218     *k = F->k1;
219     *mode= F->m1;
220   }
221   F->r1 = FILTER_NOTYET;
222   return res;
223   
224 #ifdef SKIPTHIS
225   char *k_ptr = (char*) k;
226   int res = (F->data->read_item)(F->data->clientData, &k_ptr, mode); 
227   if (F->is->method->debug > 9)  
228     logf(LOG_LOG,"filt_read: start %d.%d m=%d r=%d",
229        k->sysno, k->seqno, *mode, res);
230   return res;
231 #endif
232 }
233
234 static int filter_empty(FILTER F)
235 {
236   return 0;
237 }
238
239 static int filter_only_one(FILTER F)
240 {
241   return 0;
242 }
243
244
245 /***************************************************************
246  * General support routines
247  ***************************************************************/
248
249
250
251 static char *hexdump(unsigned char *p, int len, char *buff) {
252   static char localbuff[128];
253   char bytebuff[8];
254   if (!buff) buff=localbuff;
255   *buff='\0';
256   while (len--) {
257     sprintf(bytebuff,"%02x",*p);
258     p++;
259     strcat(buff,bytebuff);
260     if (len) strcat(buff,",");
261   }
262   return buff;
263 }
264
265
266
267 static void isamd_reduceblock(ISAMD_PP pp)
268 /* takes a large block, and reduces its category if possible */
269 /* Presumably the first block in an isam-list */
270 {
271    if (pp->pos)
272       return; /* existing block, do not touch */
273       /* TODO: Probably we may touch anyway? */
274    if (pp->is->method->debug > 5)  
275      logf(LOG_LOG,"isamd_reduce: start p=%d c=%d sz=%d",
276        pp->pos, pp->cat, pp->size); 
277    while ( ( pp->cat > 0 ) && (!pp->next) && 
278            (pp->offset < pp->is->method->filecat[pp->cat-1].bsize ) )
279       pp->cat--;
280    pp->pos = isamd_alloc_block(pp->is, pp->cat);
281    if (pp->is->method->debug > 5) 
282      logf(LOG_LOG,"isamd_reduce:  got  p=%d c=%d sz=%d",
283        pp->pos, pp->cat, pp->size);    
284 } /* reduceblock */
285
286
287 static int save_first_pp ( ISAMD_PP firstpp)
288 {
289    isamd_buildfirstblock(firstpp);
290    isamd_write_block(firstpp->is,firstpp->cat,firstpp->pos,firstpp->buf);
291    return isamd_addr(firstpp->pos,firstpp->cat);
292 }
293
294  
295 static void save_last_pp (ISAMD_PP pp)
296 {
297    pp->next = 0;/* just to be sure */
298    isamd_buildlaterblock(pp);
299    isamd_write_block(pp->is,pp->cat,pp->pos,pp->buf);
300 }
301
302 #ifdef UNUSED
303 static int save_both_pps (ISAMD_PP firstpp, ISAMD_PP pp)
304 {
305    /* order of things: Better to save firstpp first, if there are just two */
306    /* blocks, but last if there are blocks in between, as these have already */
307    /* been saved... optimise later (that's why this is in its own func...*/
308    int retval = save_first_pp(firstpp);
309    if (firstpp!=pp){ 
310       save_last_pp(pp);
311       isamd_pp_close(pp);
312    }
313    isamd_pp_close(firstpp);
314    return retval;
315 } /* save_both_pps */
316 #endif
317
318
319
320 /***************************************************************
321  * Diffblock handling
322  ***************************************************************/
323
324 void isamd_free_diffs(ISAMD_PP pp)
325 {
326   int i;
327   if (pp->is->method->debug > 5)
328      logf(LOG_LOG,"isamd_free_diffs: pp=%p di=%p", pp, pp->diffinfo);
329   if (!pp->diffinfo) 
330     return;
331   for (i=0;pp->diffinfo[i].difftype!=DT_NONE;i++) 
332       if(pp->diffinfo[i].decodeData)
333       {
334           if (pp->is->method->debug > 8)
335              logf(LOG_LOG,"isamd_free_diffs [%d]=%p",i, 
336                            pp->diffinfo[i].decodeData);
337           (*pp->is->method->code_stop)(ISAMD_DECODE,pp->diffinfo[i].decodeData);
338       } 
339   xfree(pp->diffinfo);
340   if (pp->diffbuf != pp->buf)
341     xfree (pp->diffbuf);  
342   pp->diffbuf=0;
343   pp->diffinfo=0;
344 } /* isamd_free_diffs */
345
346
347 static void getDiffInfo(ISAMD_PP pp )
348 { /* builds the diff info structures from a diffblock */
349    int maxinfos = pp->is->method->filecat[pp->cat].bsize / 5 +2;
350     /* Each diff takes at least 5 bytes. Probably more, but this is safe */
351    int i=1;  /* [0] is used for the main data, [n+1] for merge inputs */
352    int diffsz= maxinfos * sizeof(struct ISAMD_DIFF_s);
353    int maxsz = pp->is->method->filecat[pp->is->max_cat].bsize;
354    int diffidx = ISAMD_BLOCK_OFFSET_1;
355
356    pp->diffinfo = xmalloc( diffsz ); 
357    pp->offset = pp->size+1; /* used this block up */
358    memset(pp->diffinfo,'\0',diffsz);
359    if (pp->is->method->debug > 5)   
360       logf(LOG_LOG,"isamd_getDiffInfo: %d=%d:%d->%d, ix=%d mx=%d",
361          isamd_addr(pp->pos, pp->cat), pp->cat, pp->pos, pp->next,
362          diffidx,maxinfos);
363    
364    /* duplicate the buffer for diffs */
365    /* (so that we can read the next real buffer(s) */
366    assert(0==pp->diffbuf);
367    pp->diffbuf=xmalloc(maxsz);
368    memcpy(pp->diffbuf, pp->buf, maxsz);
369    
370    pp->diffinfo[0].maxidx=-1; /* mark as special */
371    pp->diffinfo[0].difftype=DT_MAIN;
372
373    while (i<maxinfos) 
374    {  
375       if ( diffidx+sizeof(int) > pp->is->method->filecat[pp->cat].bsize )
376       {
377          if (pp->is->method->debug > 5)
378            logf(LOG_LOG,"isamd_getDiffInfo:Near end (no room for len) at ix=%d n=%d",
379                diffidx, i);
380          return; /* whole block done */
381       }
382       memcpy( &pp->diffinfo[i].maxidx, &pp->diffbuf[diffidx], sizeof(int) );
383       pp->diffinfo[i].difftype=DT_DIFF;
384       if (pp->is->method->debug > 5)
385         logf(LOG_LOG,"isamd_getDiffInfo: max=%d ix=%d dbuf=%p",
386           pp->diffinfo[i].maxidx, diffidx, pp->diffbuf);
387
388       if ( (pp->is->method->debug > 0) &&
389          (pp->diffinfo[i].maxidx > pp->is->method->filecat[pp->cat].bsize) )
390       { /* bug-hunting, this fails on some long runs that log too much */
391          logf(LOG_LOG,"Bad MaxIx!!! %s:%d: diffidx=%d", 
392                        __FILE__,__LINE__, diffidx);
393          logf(LOG_LOG,"i=%d maxix=%d bsz=%d", i, pp->diffinfo[i].maxidx,
394                        pp->is->method->filecat[pp->cat].bsize);
395          logf(LOG_LOG,"pp=%d=%d:%d  pp->nx=%d=%d:%d",
396                        isamd_addr(pp->pos,pp->cat), pp->pos, pp->cat,
397                        pp->next, isamd_type(pp->next), isamd_block(pp->next) );                      
398       }
399       assert(pp->diffinfo[i].maxidx <= pp->is->method->filecat[pp->cat].bsize+1);
400
401       if (0==pp->diffinfo[i].maxidx)
402       {
403          if (pp->is->method->debug > 5)  //!!! 4
404            logf(LOG_LOG,"isamd_getDiffInfo:End mark at ix=%d n=%d",
405                diffidx, i);
406          return; /* end marker */
407       }
408       diffidx += sizeof(int);
409       pp->diffinfo[i].decodeData = (*pp->is->method->code_start)(ISAMD_DECODE);
410       pp->diffinfo[i].diffidx = diffidx;
411       if (pp->is->method->debug > 5)
412         logf(LOG_LOG,"isamd_getDiff[%d]:%d-%d %s",
413           i,diffidx-sizeof(int),pp->diffinfo[i].maxidx,
414           hexdump((char *)&pp->diffbuf[diffidx-4],8,0) );
415       diffidx=pp->diffinfo[i].maxidx;
416       if ( diffidx > pp->is->method->filecat[pp->cat].bsize )
417         return; /* whole block done */
418       ++i;
419    }
420    assert (!"too many diff sequences in the block");
421 }
422
423 /***************************************************************
424  * Main block operations
425  ***************************************************************/
426
427
428 static ISAMD_PP get_new_main_block( ISAMD_PP firstpp, ISAMD_PP pp)
429 {  /* allocates a new block for the main data, and links it in */
430   int newblock;
431   if (0 == firstpp->next) 
432   {  /* special case, pp not yet allocated. */
433      /*Started as largest size, that's fine */
434      pp->pos = isamd_alloc_block(pp->is,pp->cat);
435      firstpp->next = isamd_addr(pp->pos,pp->cat);
436      if (pp->is->method->debug >3) 
437         logf(LOG_LOG,"isamd_build: Alloc 1. dblock  p=%d=%d:%d",
438            isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos);
439   }
440   newblock=isamd_alloc_block(pp->is,pp->cat);
441   pp->next=isamd_addr(newblock,pp->cat);
442   isamd_buildlaterblock(pp);
443   isamd_write_block(pp->is,pp->cat,pp->pos,pp->buf);
444   if (pp->is->method->debug >3) 
445      logf(LOG_LOG,"isamd_build: Alloc nxt %d=%d:%d -> %d=%d:%d",
446         isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos,
447         isamd_addr(newblock,pp->cat), pp->cat, newblock);
448   pp->next=0;
449   pp->pos=newblock;
450   pp->size=pp->offset=ISAMD_BLOCK_OFFSET_N;  
451   return pp;
452 } /* get_new_main_block */
453
454
455 static ISAMD_PP  append_main_item(ISAMD_PP firstpp, 
456                                   ISAMD_PP pp, 
457                                   struct it_key *i_key)
458 {  /* appends one item in the main data block, allocates new if needed */
459    char *i_item= (char *) i_key;  /* same as char */
460    char *i_ptr=i_item;
461    char codebuff[128];
462    char *c_ptr = codebuff;
463    int codelen;
464    char hexbuff[64];
465
466    int maxsize = pp->is->method->filecat[pp->is->max_cat].bsize; 
467
468    c_ptr=codebuff;
469    i_ptr=i_item;
470    (*pp->is->method->code_item)(ISAMD_ENCODE, pp->decodeClientData,
471                                 &c_ptr, &i_ptr);
472    codelen = c_ptr - codebuff;
473    assert ( (codelen<128) && (codelen>0));
474    if (pp->is->method->debug >7)
475       logf(LOG_LOG,"isamd:build: coded %s nk=%d,ofs=%d-%d",
476           hexdump(codebuff, c_ptr-codebuff,hexbuff), firstpp->numKeys+1,
477           pp->offset, pp->offset+codelen);
478
479    if (pp->offset + codelen > maxsize )
480    { /* oops, block full - get a new one */
481       pp =  get_new_main_block( firstpp, pp );
482       /* reset encoging and code again */
483       (*pp->is->method->code_reset)(pp->decodeClientData);
484       c_ptr=codebuff;
485       i_ptr=i_item;
486       (*pp->is->method->code_item)(ISAMD_ENCODE, pp->decodeClientData, 
487                                    &c_ptr, &i_ptr);
488       codelen = c_ptr - codebuff;
489       assert ( (codelen<128) && (codelen>0));
490       if (pp->is->method->debug >7)
491          logf(LOG_LOG,"isamd:build: recoded into %s  (nk=%d)",
492              hexdump(codebuff, c_ptr-codebuff,hexbuff), firstpp->numKeys+1);
493    } /* block full */    
494
495    assert (pp->offset + codelen <= maxsize );
496    
497    /* write the data into pp, now we must have room */ 
498    memcpy(&(pp->buf[pp->offset]),codebuff,codelen);
499    pp->offset += codelen;
500    pp->size += codelen;
501    firstpp->numKeys++;
502    /* clear the next 4 bytes in block, to avoid confusions with diff lens */
503    /* dirty, it should not be done here, but something slips somewhere, and */
504    /* I hope this fixes it...  - Heikki */
505    codelen = pp->offset;
506    while ( (codelen < maxsize ) && (codelen <= pp->offset+4) )
507      pp->buf[codelen++] = '\0';
508    return pp;    
509 } /* append_main_item */
510
511
512 /***************************************************************
513  * Read with merge
514  ***************************************************************/
515
516 /* Reads one item and corrects for the diffs, if any */
517 /* return 1 for ok, 0 for eof */
518 int isamd_read_item_merge (
519                      ISAMD_PP pp, 
520                      char **dst,
521                      struct it_key *p_key,  /* the data item that didn't fit*/
522               /*       ISAMD_I data)  */    /* more input data comes here */
523                      FILTER filt)           /* more input data comes here */
524 {                    /* The last two args can be null for ordinary reads */
525   char *keyptr;
526   char *codeptr;
527   char *codestart;
528   int winner=0; /* which diff holds the day */
529   int i; /* looping diffs */
530   int cmp;
531   int retry=1;
532   int oldoffs;
533   int rc;
534
535   if (!pp->diffinfo)  
536   { /* first time */
537      getDiffInfo(pp);
538
539      for(i=1; pp->diffinfo[i].difftype!=DT_NONE; i++)
540        ;  /* find last diff */
541      if (p_key)  
542      {  /* we have an extra item to inject into the merge */
543        if (pp->is->method->debug >9)  //!!!!!
544           logf(LOG_LOG,"isamd_read_item: going to merge with %d.%d",
545                p_key->sysno, p_key->seqno);
546        pp->diffinfo[i].key = *p_key;  /* the key merge could not handle */
547        pp->diffinfo[i].mode = pp->diffinfo[i].key.seqno & 1;
548        pp->diffinfo[i].key.seqno >>= 1;
549        pp->diffinfo[i].difftype=DT_INPU;
550        if (pp->is->method->debug > 7)
551          logf(LOG_LOG,"isamd_read_item: inpu key %d sys=%d  seq=%d=2*%d+%d",
552             i, p_key->sysno,
553             pp->diffinfo[i].key.seqno*2 + pp->diffinfo[1].mode,
554             pp->diffinfo[i].key.seqno,
555             pp->diffinfo[i].mode);
556        p_key->sysno=p_key->seqno=0;  /* used it up */
557      }
558
559      if (filt)
560      { /* we have a whole input stream to inject */
561        pp->diffinfo[i].difftype=DT_INPU;
562      }
563   } /* first time */ 
564         
565   while (retry)
566
567   {
568      retry=0;     
569      winner = 0;
570      for (i=0; (!retry) && (pp->diffinfo[i].difftype); i++)
571      {
572         if (0==pp->diffinfo[i].key.sysno)
573         {/* read a new one, if possible */
574            if ((pp->diffinfo[i].difftype==DT_DIFF) &&
575              (pp->diffinfo[i].diffidx < pp->diffinfo[i].maxidx))
576            { /* a normal kind of diff */
577               oldoffs=pp->diffinfo[i].diffidx;
578               codeptr= codestart = &(pp->diffbuf[pp->diffinfo[i].diffidx]);
579               keyptr=(char *)&(pp->diffinfo[i].key);
580               (*pp->is->method->code_item)(ISAMD_DECODE,
581                     pp->diffinfo[i].decodeData, &keyptr, &codeptr);
582               pp->diffinfo[i].diffidx += codeptr-codestart;
583               pp->diffinfo[i].mode = pp->diffinfo[i].key.seqno & 1;
584               pp->diffinfo[i].key.seqno = pp->diffinfo[i].key.seqno >>1 ;
585               if (pp->is->method->debug > 9)
586                 logf(LOG_LOG,"isamd_read_item: dif[%d] at %d-%d: %s",
587                   i,oldoffs, pp->diffinfo[i].diffidx,
588                   hexdump(pp->buf+oldoffs, pp->diffinfo[i].diffidx-oldoffs,0));
589               if (pp->is->method->debug > 7)
590                 logf(LOG_LOG,"isamd_read_item: rd dif[%d] %d.%d (%x.%x)",
591                   i,
592                   pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
593                   pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
594            }
595            else if ( pp->diffinfo[i].difftype==DT_MAIN)
596            { /* read a main item */
597               assert(i==0);  /* main data goes before any diffs */
598               oldoffs=pp->offset;
599               keyptr=(char*) &(pp->diffinfo[0].key);
600               rc= isamd_read_main_item(pp,&keyptr);
601               if (0==rc) 
602               { /* eof */
603                  if (pp->is->method->debug > 7)
604                    logf(LOG_LOG,"isamd_read_item: eof (rc=%d) main ",
605                            rc);
606                 pp->diffinfo[i].maxidx=-1;
607                 pp->diffinfo[i].key.sysno=0;
608                 pp->diffinfo[i].key.seqno=0;
609                 pp->diffinfo[i].difftype= DT_DONE;
610               } 
611               else
612               { /* not eof */
613                  pp->diffinfo[i].mode = 1;
614                  if (pp->is->method->debug > 7)
615                    logf(LOG_LOG,"isamd_read_item: rd main %d-%d %d.%d (%x.%x) m=%d",
616                      oldoffs,pp->offset,
617                      pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
618                      pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
619                      pp->diffinfo[i].mode);
620               } /* not eof */
621            }
622            else if (pp->diffinfo[i].difftype==DT_INPU)
623            {
624               keyptr = (char *) &pp->diffinfo[i].key;
625          /*     rc = (*data->read_item)(data->clientData, &keyptr, &pp->diffinfo[i].mode); */
626               rc = filter_read(filt, &pp->diffinfo[i].key, 
627                                      &pp->diffinfo[i].mode); 
628               if (!rc) 
629               {  /* did not get it */
630                  pp->diffinfo[i].key.sysno=0;
631                  pp->diffinfo[i].maxidx=0; /* signal the end */
632                  pp->diffinfo[i].difftype=DT_DONE;
633               }
634               if (pp->is->method->debug >7)
635                  logf(LOG_LOG,"merge: read inpu m=%d %d.%d (%x.%x)",
636                     pp->diffinfo[i].mode, 
637                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
638                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno );        
639            } /* read an input item */
640         } /* read a new one */
641         
642         if (pp->is->method->debug > 8)
643           logf(LOG_LOG,"isamd_read_item: considering d%d %d.%d ix=%d mx=%d",
644                i, pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
645                   pp->diffinfo[i].diffidx,   pp->diffinfo[i].maxidx);
646             
647         if ( 0!= pp->diffinfo[i].key.sysno)
648         { /* got a key, compare */
649           if (i!=winner)
650              cmp=key_compare(&pp->diffinfo[i].key, &pp->diffinfo[winner].key);
651           else
652              cmp=-1;
653           if (0==pp->diffinfo[winner].key.sysno)
654             cmp=-1; /* end of main sequence, take all diffs */
655           if (cmp<0)
656           {
657              if (pp->is->method->debug > 8)
658                logf(LOG_LOG,"isamd_read_item: ins [%d]%d.%d < [%d]%d.%d",
659                  i,  
660                  pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
661                  winner, 
662                  pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
663              if (pp->diffinfo[i].mode)  /* insert diff, should always be */
664                winner = i;
665              else
666              {
667                if (pp->is->method->debug > 1)
668                  logf(LOG_LOG,"delete diff for nonexisting item");
669                assert(!"delete diff for nonexisting item");  
670                /* is an assert too steep here? Not really.*/
671              }
672           } /* earlier key */
673           else if (cmp==0)
674           {
675              if (!pp->diffinfo[i].mode) /* delete diff. should always be */
676              {
677                 if (pp->is->method->debug > 8)
678                   logf(LOG_LOG,"isamd_read_item: del %d at%d %d.%d (%x.%x)",
679                     i, winner,
680                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
681                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
682                 pp->diffinfo[winner].key.sysno=0; /* delete it */
683              }
684              else
685                 if (pp->is->method->debug > 2)
686                   logf(LOG_LOG,"isamd_read_item: duplicate ins %d at%d %d.%d (%x.%x)",
687                     i, winner,
688                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
689                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
690                 /* skip the insert, since we already have it in the base */
691                 /* Should we fail an assertion here??? */
692              pp->diffinfo[i].key.sysno=0; /* done with the delete */
693              retry=1; /* start all over again */
694           } /* matching key */
695           /* else it is a later key, its turn will come */
696         } /* got a key */
697      } /* for each diff */
698   } /* not retry */
699
700   if ( pp->diffinfo[winner].key.sysno)
701   {
702     if (pp->is->method->debug > 7)
703       logf(LOG_LOG,"isamd_read_item: got %d  %d.%d (%x.%x)",
704         winner,
705         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno,
706         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
707     memcpy(*dst, &pp->diffinfo[winner].key, sizeof(struct it_key) );
708     *dst += sizeof(struct it_key);
709     pp->diffinfo[winner].key.sysno=0; /* used that one up */
710     cmp= 1;
711   } 
712   else 
713   {
714     if (pp->is->method->debug > 7)
715       logf(LOG_LOG,"isamd_read_item: eof w=%d  %d.%d (%x.%x)",
716         winner,
717         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno,
718         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
719     assert(winner==0); /* if nothing found, nothing comes from a diff */
720     cmp= 0; /* eof */
721   }
722   if (pp->is->method->debug >9)
723      logf(LOG_LOG,"mergeDB4: sysno[1]=%d", pp->diffinfo[1].key.sysno); /*!*/
724   return cmp;
725    
726 } /* isamd_read_item */
727
728
729 int isamd_read_item (ISAMD_PP pp, char **dst)
730 {
731   return isamd_read_item_merge(pp,dst,0,0);
732 }
733
734
735 /***************************************************************
736  * Merge
737  ***************************************************************/
738
739 static int merge ( ISAMD_PP firstpp,      /* first pp (with diffs) */
740                    struct it_key *p_key,  /* the data item that didn't fit*/
741               /*     ISAMD_I data) */     /* more input data comes here */
742                    FILTER filt)           /* more input data arriving here */
743 {
744   int diffidx;  
745   int killblk=0;
746   struct it_key r_key;
747   char * r_ptr;
748   int r_more = 1;
749   ISAMD_PP pp;
750   ISAMD_PP readpp=firstpp;
751   int retval=0;
752   int diffcat = firstpp->cat;  /* keep the category of the diffblock even */
753                                /* if it is going to be empty now. */
754                                /* Alternative: Make it the minimal, and */
755                                /* resize later. Saves disk, but will lead */
756                                /* into bad seeks. */
757   
758   ++(readpp->is->files[0].no_merges);
759      
760   /* set up diffs as they should be for reading */
761   diffidx = ISAMD_BLOCK_OFFSET_1; 
762   //readpp->diffbuf=readpp->buf;  // diffinfo has to duplicate it!
763   //getDiffInfo(readpp);  // first read will make the diffinfo, at init
764   
765   if (readpp->is->method->debug >4) 
766       logf(LOG_LOG,"isamd_merge: f=%d=%d:%d n=%d=%d:%d",
767         isamd_addr(firstpp->pos,firstpp->cat), firstpp->cat, firstpp->pos,
768         firstpp->next, isamd_type(firstpp->next), isamd_block(firstpp->next));  
769
770   /* release our data block. Do before reading, when pos is stable ! */
771   killblk=firstpp->pos;
772   if (killblk)
773   {
774       isamd_release_block(firstpp->is, firstpp->cat, killblk);
775       if (readpp->is->method->debug >3)   
776           logf(LOG_LOG,"isamd_merge: released old firstblock %d (%d:%d)",
777               isamd_addr(killblk,firstpp->cat), firstpp->cat, killblk );
778   }
779   
780
781   r_ptr= (char *) &r_key;
782 /*  r_more = isamd_read_item_merge( readpp, &r_ptr, p_key, data); */
783   r_more = isamd_read_item_merge( readpp, &r_ptr, p_key, filt);
784   if (!r_more)  
785   { /* oops, all data has been deleted! what to do??? */
786     /* never mind, we have at least one more delta to add to the block */
787     /* pray that is not a delete as well... */
788     r_key.sysno = 0;
789     r_key.seqno = 0;
790      if (readpp->is->method->debug >5) 
791          logf(LOG_LOG,"isamd_merge:all data has been deleted (nk=%d) ",
792             readpp->numKeys);
793     //assert (readpp->numKeys == 0);  /* no longer true! */
794   }
795
796
797   /* set up the new blocks for simple writing */
798   firstpp=isamd_pp_open(readpp->is,isamd_addr(0, diffcat));
799   firstpp->pos=isamd_alloc_block(firstpp->is,diffcat);
800   if (readpp->is->method->debug >3)   
801       logf(LOG_LOG,"isamd_merge: allocated new firstpp %d=%d:%d",
802           isamd_addr(firstpp->pos,firstpp->cat), firstpp->cat, firstpp->pos );
803   
804   pp=isamd_pp_open(readpp->is,isamd_addr(0,readpp->is->max_cat) );
805   pp->offset=pp->size=ISAMD_BLOCK_OFFSET_N;
806   
807   while (r_more)
808   {
809      if (readpp->is->method->debug >6) 
810          logf(LOG_LOG,"isamd_merge: got key %d.%d",
811            r_key.sysno, r_key.seqno );
812      pp= append_main_item(firstpp, pp, &r_key);
813
814      if ( (readpp->pos != killblk ) && (0!=readpp->pos) )
815      {  /* pos can get to 0 at end of main seq, if still diffs left...*/
816         if (readpp->is->method->debug >3)  
817             logf(LOG_LOG,"isamd_merge: released block %d (%d:%d) now %d=%d:%d",
818                 isamd_addr(killblk,readpp->cat), readpp->cat, killblk,
819                 isamd_addr(readpp->pos,readpp->cat),readpp->cat, readpp->pos );
820         isamd_release_block(readpp->is, readpp->cat, readpp->pos);
821         killblk=readpp->pos;
822      }
823
824      /* (try to) read next item */
825      r_ptr= (char *) &r_key;
826      r_more = isamd_read_item_merge( readpp, &r_ptr,0,filt);
827
828   } /* while read */
829   
830   
831 //  firstpp->diffs=0; 
832
833
834   isamd_reduceblock(pp);  /* reduce size if possible */
835   if (0==firstpp->next)
836     firstpp->next = isamd_addr(pp->pos,pp->cat);
837   save_last_pp(pp);
838   if (readpp->is->method->debug >4) 
839       logf(LOG_LOG,"isamd_merge: saved last block %d=%d:%d",
840             isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos);
841   isamd_pp_close(pp);
842
843   if (readpp->is->method->debug >5) 
844         logf(LOG_LOG,"isamd_merge: closing readpp %d=%d:%d di=%p",
845               isamd_addr(readpp->pos,readpp->cat), readpp->cat, readpp->pos,
846               readpp->diffinfo);
847   isamd_pp_close(readpp); /* pos is 0 by now, at eof. close works anyway */
848
849   if (readpp->is->method->debug >2)  
850       logf(LOG_LOG,"isamd_merge: merge ret f=%d=%d:%d pp=%d=%d:%d",
851             isamd_addr(firstpp->pos,pp->cat), firstpp->cat, firstpp->pos,
852             isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos);
853
854   firstpp->size = firstpp->offset = ISAMD_BLOCK_OFFSET_1;  /* nothing there */
855   memset(firstpp->buf,'\0',firstpp->is->method->filecat[firstpp->cat].bsize);
856   save_first_pp(firstpp);
857   retval = isamd_addr(firstpp->pos, firstpp->cat);
858   isamd_pp_close(firstpp);
859
860   return retval; 
861   
862 } /* merge */
863
864
865
866
867 /***************************************************************
868  * Appending diffs 
869  ***************************************************************/
870
871
872
873 static int append_diffs(
874       ISAMD is, 
875       ISAMD_P ipos, 
876       /*ISAMD_I data)*/
877       FILTER filt)
878 {
879    struct it_key i_key;    /* one input item */
880    char *i_item = (char *) &i_key;  /* same as chars */
881    char *i_ptr=i_item;
882    int i_more =1;
883    int i_mode;     /* 0 for delete, 1 for insert */ 
884
885    ISAMD_PP firstpp;
886    char hexbuff[64];
887    int diffidx=0;
888    int maxsize=0;
889    int difflenidx;
890    char codebuff[128];
891    char *c_ptr = codebuff;
892    int codelen;
893    int merge_rc;
894    int retval=0;
895
896    if (0==ipos)
897    {
898        firstpp=isamd_pp_open(is, isamd_addr(0,0) );
899        firstpp->size=firstpp->offset=ISAMD_BLOCK_OFFSET_1;
900          /* create in smallest category, will expand later */
901        ++(is->files[0].no_fbuilds);
902    } 
903    else
904    {
905        firstpp=isamd_pp_open(is, ipos);
906        ++(is->files[0].no_appds);
907    }
908
909    if (is->method->debug >2) 
910       logf(LOG_LOG,"isamd_appd: Start ipos=%d=%d:%d n=%d=%d:%d nk=%d",
911         ipos, isamd_type(ipos), isamd_block(ipos),
912         firstpp->next, isamd_type(firstpp->next), isamd_block(firstpp->next),
913         firstpp->numKeys);
914    maxsize = is->method->filecat[firstpp->cat].bsize; 
915    
916    difflenidx = diffidx = firstpp->size;
917    
918    diffidx+=sizeof(int);  /* difflen will be stored here */
919    
920    /* read first input */
921    //i_ptr = i_item;   //!!!
922    i_more = filter_read(filt, &i_key, &i_mode); 
923    /* i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); */
924
925    if (is->method->debug >6)
926       logf(LOG_LOG,"isamd_appd: start m=%d %d.%d=%x.%x: %d",
927          i_mode, 
928          i_key.sysno, i_key.seqno, 
929          i_key.sysno, i_key.seqno,
930          i_key.sysno*2+i_mode);
931
932    while (i_more)
933    {     
934       /* store the mode bit inside key */
935       assert( ((i_key.seqno<<1)>>1) == i_key.seqno); /* can spare the bit */
936       i_key.seqno = i_key.seqno * 2 + i_mode;  
937
938       c_ptr=codebuff;
939       i_ptr=i_item; 
940       (*is->method->code_item)(ISAMD_ENCODE, firstpp->decodeClientData, 
941                                &c_ptr, &i_ptr);
942       codelen = c_ptr - codebuff;
943       assert ( (codelen<128) && (codelen>0));
944       if (is->method->debug >7)
945          logf(LOG_LOG,"isamd_appd: coded %d: %s (nk=%d) (ix=%d)",
946              codelen, hexdump(codebuff, codelen,hexbuff), 
947              firstpp->numKeys,diffidx);
948
949       if (diffidx + codelen > maxsize )
950       { /* block full */
951          if (firstpp->cat < firstpp->is->max_cat)
952          { /* just increase the block size */
953              if (firstpp->pos > 0)  /* free the old block if allocated */
954                  isamd_release_block(is, firstpp->cat, firstpp->pos);
955              ++firstpp->cat;
956              maxsize = is->method->filecat[firstpp->cat].bsize; 
957              firstpp->pos=0; /* need to allocate it when saving */             
958              if (is->method->debug >3)
959                 logf(LOG_LOG,"isamd_appd: increased diff block to %d (%d)",
960                    firstpp->cat, maxsize);
961          }
962          else 
963          { /* max size already - can't help, need to merge it */
964              if (is->method->debug >7)
965                 logf(LOG_LOG,"isamd_appd: block full");
966              if (is->method->debug >9)  //!!!!!
967                 logf(LOG_LOG,"isamd_appd: going to merge with m=%d %d.%d",
968                      i_mode, i_key.sysno, i_key.seqno);
969              merge_rc = merge (firstpp, &i_key, filt);
970              if (0!=merge_rc)
971                return merge_rc;  /* merge handled them all ! */
972              assert(!"merge returned zero ??");
973          } /* need to merge */
974       } /* block full */
975       
976       assert ( diffidx+codelen <= maxsize );
977       
978       /* save the diff */ 
979       memcpy(&(firstpp->buf[diffidx]),codebuff,codelen);
980       diffidx += codelen;
981       firstpp->size = firstpp->offset = diffidx;
982       
983       if (i_mode)
984         firstpp->numKeys++; /* insert diff */
985       else
986         firstpp->numKeys--; /* delete diff */ 
987
988       /* update length of this diff run */
989       memcpy(&(firstpp->buf[difflenidx]),&diffidx,sizeof(diffidx));
990       
991       /* (try to) read the next input */
992       i_ptr = i_item;
993       i_more = filter_read(filt, &i_key, &i_mode); 
994     /*  i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); */
995       if ( (i_more) && (is->method->debug >6) )
996          logf(LOG_LOG,"isamd_appd: got m=%d %d.%d=%x.%x: %d",
997             i_mode, 
998             i_key.sysno, i_key.seqno, 
999             i_key.sysno, i_key.seqno,
1000             i_key.sysno*2+i_mode);
1001    } /* more loop */
1002
1003    /* clear the next difflen, if room for such */
1004    difflenidx = diffidx;
1005    while ( (difflenidx-diffidx<=sizeof(int)+1) && (difflenidx<maxsize))
1006      firstpp->buf[difflenidx++]='\0';
1007
1008    if (0==firstpp->pos)  /* need to (re)alloc the block */
1009       firstpp->pos = isamd_alloc_block(is, firstpp->cat);
1010
1011    retval = save_first_pp( firstpp );
1012    isamd_pp_close(firstpp);
1013     
1014    return retval;
1015 } /* append_diffs */
1016
1017
1018
1019
1020 /*************************************************************
1021  * isamd_append itself
1022  *************************************************************/
1023
1024 ISAMD_P isamd_append (ISAMD is, ISAMD_P ipos, ISAMD_I data)
1025 {
1026    FILTER F = filter_open(is,data);
1027    return append_diffs(is,ipos,F);
1028    filter_close(F);
1029 } /*  isamd_append */
1030
1031
1032
1033
1034
1035
1036
1037 /*
1038  * $Log: merge-d.c,v $
1039  * Revision 1.21  1999-09-21 17:36:43  heikki
1040  * Added filter function. Not much of effect on the small test set...
1041  *
1042  * Revision 1.20  1999/09/20 15:48:06  heikki
1043  * Small changes
1044  *
1045  * Revision 1.19  1999/09/13 13:28:28  heikki
1046  * isam-d optimizing: merging input data in the same go
1047  *
1048  * Revision 1.18  1999/08/25 18:09:24  heikki
1049  * Starting to optimize
1050  *
1051  * Revision 1.17  1999/08/24 13:17:42  heikki
1052  * Block sizes, comments
1053  *
1054  * Revision 1.16  1999/08/24 10:12:02  heikki
1055  * Comments about optimising
1056  *
1057  * Revision 1.15  1999/08/22 08:26:34  heikki
1058  * COmments
1059  *
1060  * Revision 1.14  1999/08/20 12:25:58  heikki
1061  * Statistics in isamd
1062  *
1063  * Revision 1.13  1999/08/18 13:59:19  heikki
1064  * Fixed another unlikely difflen bug
1065  *
1066  * Revision 1.12  1999/08/18 13:28:17  heikki
1067  * Set log levels to decent values
1068  *
1069  * Revision 1.11  1999/08/18 10:37:11  heikki
1070  * Fixed (another) difflen bug
1071  *
1072  * Revision 1.10  1999/08/18 09:13:31  heikki
1073  * Fixed a detail
1074  *
1075  * Revision 1.9  1999/08/17 19:46:53  heikki
1076  * Fixed a memory leak
1077  *
1078  * Revision 1.8  1999/08/07 11:30:59  heikki
1079  * Bug fixing (still a mem leak somewhere)
1080  *
1081  * Revision 1.7  1999/08/04 14:21:18  heikki
1082  * isam-d seems to be working.
1083  *
1084  * Revision 1.6  1999/07/23 15:43:05  heikki
1085  * Hunted a few bugs in isam-d. Still crashes on the long test run
1086  *
1087  * Revision 1.5  1999/07/23 13:58:52  heikki
1088  * merged closer to working, still fails on filling a separate, large block
1089  *
1090  * Revision 1.4  1999/07/21 14:53:55  heikki
1091  * isamd read and write functions work, except when block full
1092  * Merge missing still. Need to split some functions
1093  *
1094  * Revision 1.1  1999/07/14 13:14:47  heikki
1095  * Created empty
1096  *
1097  *
1098  */
1099
1100