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