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