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