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