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