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