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