singleton optimising
[idzebra-moved-to-github.git] / isamc / merge-d.c
1 /*
2  * Copyright (c) 1996-1998, Index Data.
3  * See the file LICENSE for details.
4  * Heikki Levanto
5  *
6  * $Id: merge-d.c,v 1.22 1999-09-23 18:01:18 heikki Exp $
7  *
8  * bugs
9  *   (none)
10  *
11  * missing
12  *
13  * optimize
14  *  - study and optimize block sizes (later)
15  *  - find a way to decide the size of an empty diffblock (after merge)
16  *  - On allocating more blocks (in append and merge), check the order of 
17  *    blocks, and if needed, swap them. 
18  *  - Write a routine to save/load indexes into a block, save only as many 
19  *    bytes as needed (size, diff, diffindexes)
20  *
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 isamddebug=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  * Design for the new and improved isamd
51  * Key points:
52  *  - The first block is only diffs, no straight data
53  *  - Additional blocks are straight data
54  *  - When a diff block gets filled up, a data block is created by
55  *    merging the diffs with the data
56  *
57  * Structure
58  *  - Isamd_pp: buffer for diffs and for data
59  *              keep both pos, type, and combined address
60  *              routine to set the address
61  *  - diffbuf: lengths as short ints, or bytes for small blocks
62  *  - keys are of key_struct, not just a number of bytes.
63  *
64  * Routines
65  *  - isamd_append
66  *    - create_new_block if needed
67  *    - append_diffs
68  *      - load_diffs 
69  *      - get diffend, start encoding
70  *      - while input data
71  *        - encode it
72  *        - if no room, then realloc block in larger size
73  *        - if still no room, merge and exit
74  *        - append in the block
75  *
76  * - merge
77  *   - just as before, except that merges also input data directly
78  *   - writes into new data blocks
79  *       
80  *      
81  * - isamd.c: load firstpp, load datablock
82  *            save firstpp, save datablock
83  * - Readlength, writelength - handling right size of len fields
84  * - isamd_read_main_item: take also a merge input structure, and merge it too
85  * - prefilter: cache two inputs, and check if they cancel.
86  * - single-item optimization
87  * 
88  * questions: Should we realloc firstblocks in a different size as the main
89  * blocks. Makes a sideways seek, which is bound to be slowe. But saves some
90  * update time. Compromise: alloc the first one in the size of the datablock,
91  * but increase if necessary. Large blocks get a large diff, ok. Small ones
92  * may get an extra seek in read, but save merges.
93  */
94
95
96 #define NEW_ISAM_D 1  /* not yet ready to delete the old one! */
97
98 #include <stdlib.h>
99 #include <assert.h>
100 #include <string.h>
101 #include <stdio.h>
102 #include <log.h>
103 #include "../index/index.h"
104 #include "isamd-p.h"
105
106
107 struct ISAMD_DIFF_s {
108   int diffidx;
109   int maxidx;
110   struct it_key key;
111   void *decodeData;
112   int mode;
113   int difftype;  
114 };
115
116 #define DT_NONE 0 // no diff, marks end of sequence
117 #define DT_DIFF 1 // ordinarry diff
118 #define DT_MAIN 2 // main data
119 #define DT_INPU 3 // input data to be merged
120 #define DT_DONE 4 // done with all input here
121
122
123
124 /***************************************************************
125  * Input preprocess filter
126  ***************************************************************/
127
128
129 #define FILTER_NOTYET -1  /* no data read in yet, to be done */
130
131 struct ISAMD_FILTER_s {
132   ISAMD_I data;          /* where the data comes from */
133   ISAMD is;              /* for debug flags */
134   struct it_key k1;      /* the next item to be returned */
135   int           m1;      /* mode for k1 */
136   int           r1;      /* result for read of k1, or NOTYET */
137   struct it_key k2;      /* the one after that */
138   int           m2;
139   int           r2;
140 };
141
142 typedef struct ISAMD_FILTER_s *FILTER;
143
144
145 void filter_fill(FILTER F)
146 {
147   while ( (F->r1 == FILTER_NOTYET) || (F->r2 == FILTER_NOTYET) )
148   {
149      if (F->r1==FILTER_NOTYET) 
150      { /* move data forward in the filter */
151         F->k1 = F->k2;
152         F->m1 = F->m2;
153         F->r1 = F->r2;
154         if ( 0 != F->r1 ) /* not eof */
155           F->r2 = FILTER_NOTYET; /* say we want more */
156         if (F->is->method->debug > 9)  
157           logf(LOG_LOG,"filt_fill: shift %d.%d m=%d r=%d",
158              F->k1.sysno, 
159              F->k1.seqno, 
160              F->m1, F->r1);
161      }
162      if (F->r2==FILTER_NOTYET)
163      { /* read new bottom value */
164         char *k_ptr = (char*) &F->k2;
165         F->r2 = (F->data->read_item)(F->data->clientData, &k_ptr, &F->m2); 
166         if (F->is->method->debug > 9)
167           logf(LOG_LOG,"filt_fill: read %d.%d m=%d r=%d",
168              F->k2.sysno, F->k2.seqno, F->m2, F->r2);
169      }  
170      if ( (F->k1.sysno == F->k2.sysno) && 
171           (F->k1.seqno == F->k2.seqno) &&
172           (F->m1 != F->m2) &&
173           (F->r1 >0 ) && (F->r2 >0) )
174      { /* del-ins pair of same key (not eof) , ignore both */
175        if (F->is->method->debug > 9)
176          logf(LOG_LOG,"filt_fill: skipped %d.%d m=%d/%d r=%d/%d",
177             F->k1.sysno, F->k1.seqno, 
178             F->m1,F->m2, F->r1,F->r2);
179        F->r1 = FILTER_NOTYET;
180        F->r2 = FILTER_NOTYET;
181      }
182   } /* while */
183 } /* filter_fill */
184
185
186 FILTER filter_open( ISAMD is, ISAMD_I data )
187 {
188   FILTER F = (FILTER) xmalloc(sizeof(struct ISAMD_FILTER_s));
189   F->is = is;
190   F->data = data;
191   F->k1.sysno=0;
192   F->k1.seqno=0;
193   F->k2=F->k1; 
194   F->m1 = F->m2 = 0;
195   F->r1 = F->r2 = FILTER_NOTYET;
196   filter_fill(F);
197   return F;
198 }
199
200 static void filter_close (FILTER F)
201 {
202   xfree(F);
203 }
204
205 static int filter_read( FILTER F, 
206                         struct it_key *k,
207                         int *mode)
208 {
209   int res;
210   filter_fill(F);
211   if (F->is->method->debug > 9)
212     logf(LOG_LOG,"filt_read: reading %d.%d m=%d r=%d",
213        F->k1.sysno, F->k1.seqno, F->m1, F->r1);
214   res  = F->r1;
215   if(res) 
216   {
217     *k = F->k1;
218     *mode= F->m1;
219   }
220   F->r1 = FILTER_NOTYET;
221   return res;
222 }
223
224 static int filter_isempty(FILTER F)
225 {
226   return ( (0 == F->r1) && (0 == F->r2)) ;
227 }
228
229 static int filter_only_one(FILTER F)
230 {
231   return ( (0 != F->r1) && (0 == F->r2));
232 }
233
234
235
236
237 /***************************************************************
238  * Singleton encoding
239  ***************************************************************/
240 /* When there is only a single item, we don't allocate a block
241  * for it, but code it in the directory entry directly, if it
242  * fits.
243  */
244
245 #define DEC_SYSBITS 15
246 #define DEC_SEQBITS 15
247 #define DEC_MASK(n) ((1<<(n))-1)
248
249 int is_singleton(ISAMD_P ipos)
250 {
251   return ( ipos != 0 ) && ( ipos & 1 );
252 }
253
254
255 int singleton_encode(struct it_key *k)
256 /* encodes the key into one int. If it does not fit, returns 0 */
257 {
258   if ( (k->sysno & DEC_MASK(DEC_SYSBITS) ) != k->sysno )
259     return 0;  /* no room dor sysno */
260   if ( (k->seqno & DEC_MASK(DEC_SYSBITS) ) != k->seqno )
261     return 0;  /* no room dor sysno */
262   return ( (k->sysno | (k->seqno << DEC_SYSBITS) ) << 1) | 1;
263 }
264  
265 void singleton_decode (int code, struct it_key *k)
266 {
267   assert ((code & 1) == 1 );
268   code = code >> 1; 
269   k->sysno = code & DEC_MASK(DEC_SYSBITS);
270   k->seqno = code >> DEC_SYSBITS ;
271
272  
273  
274 /***************************************************************
275  * General support routines
276  ***************************************************************/
277
278
279
280 static char *hexdump(unsigned char *p, int len, char *buff) {
281   static char localbuff[128];
282   char bytebuff[8];
283   if (!buff) buff=localbuff;
284   *buff='\0';
285   while (len--) {
286     sprintf(bytebuff,"%02x",*p);
287     p++;
288     strcat(buff,bytebuff);
289     if (len) strcat(buff,",");
290   }
291   return buff;
292 }
293
294
295
296 static void isamd_reduceblock(ISAMD_PP pp)
297 /* takes a large block, and reduces its category if possible */
298 /* Presumably the first block in an isam-list */
299 {
300    if (pp->pos)
301       return; /* existing block, do not touch */
302       /* TODO: Probably we may touch anyway? */
303    if (pp->is->method->debug > 5)  
304      logf(LOG_LOG,"isamd_reduce: start p=%d c=%d sz=%d",
305        pp->pos, pp->cat, pp->size); 
306    while ( ( pp->cat > 0 ) && (!pp->next) && 
307            (pp->offset < pp->is->method->filecat[pp->cat-1].bsize ) )
308       pp->cat--;
309    pp->pos = isamd_alloc_block(pp->is, pp->cat);
310    if (pp->is->method->debug > 5) 
311      logf(LOG_LOG,"isamd_reduce:  got  p=%d c=%d sz=%d",
312        pp->pos, pp->cat, pp->size);    
313 } /* reduceblock */
314
315
316 static int save_first_pp ( ISAMD_PP firstpp)
317 {
318    isamd_buildfirstblock(firstpp);
319    isamd_write_block(firstpp->is,firstpp->cat,firstpp->pos,firstpp->buf);
320    return isamd_addr(firstpp->pos,firstpp->cat);
321 }
322
323  
324 static void save_last_pp (ISAMD_PP pp)
325 {
326    pp->next = 0;/* just to be sure */
327    isamd_buildlaterblock(pp);
328    isamd_write_block(pp->is,pp->cat,pp->pos,pp->buf);
329 }
330
331 #ifdef UNUSED
332 static int save_both_pps (ISAMD_PP firstpp, ISAMD_PP pp)
333 {
334    /* order of things: Better to save firstpp first, if there are just two */
335    /* blocks, but last if there are blocks in between, as these have already */
336    /* been saved... optimise later (that's why this is in its own func...*/
337    int retval = save_first_pp(firstpp);
338    if (firstpp!=pp){ 
339       save_last_pp(pp);
340       isamd_pp_close(pp);
341    }
342    isamd_pp_close(firstpp);
343    return retval;
344 } /* save_both_pps */
345 #endif
346
347
348
349 /***************************************************************
350  * Diffblock handling
351  ***************************************************************/
352
353 void isamd_free_diffs(ISAMD_PP pp)
354 {
355   int i;
356   if (pp->is->method->debug > 5)
357      logf(LOG_LOG,"isamd_free_diffs: pp=%p di=%p", pp, pp->diffinfo);
358   if (!pp->diffinfo) 
359     return;
360   for (i=0;pp->diffinfo[i].difftype!=DT_NONE;i++) 
361       if(pp->diffinfo[i].decodeData)
362       {
363           if (pp->is->method->debug > 8)
364              logf(LOG_LOG,"isamd_free_diffs [%d]=%p",i, 
365                            pp->diffinfo[i].decodeData);
366           (*pp->is->method->code_stop)(ISAMD_DECODE,pp->diffinfo[i].decodeData);
367       } 
368   xfree(pp->diffinfo);
369   if (pp->diffbuf != pp->buf)
370     xfree (pp->diffbuf);  
371   pp->diffbuf=0;
372   pp->diffinfo=0;
373 } /* isamd_free_diffs */
374
375
376 static void getDiffInfo(ISAMD_PP pp )
377 { /* builds the diff info structures from a diffblock */
378    int maxinfos = pp->is->method->filecat[pp->cat].bsize / 5 +2;
379     /* Each diff takes at least 5 bytes. Probably more, but this is safe */
380    int i=1;  /* [0] is used for the main data, [n+1] for merge inputs */
381    int diffsz= maxinfos * sizeof(struct ISAMD_DIFF_s);
382    int maxsz = pp->is->method->filecat[pp->is->max_cat].bsize;
383    int diffidx = ISAMD_BLOCK_OFFSET_1;
384
385    pp->diffinfo = xmalloc( diffsz ); 
386    pp->offset = pp->size+1; /* used this block up */
387    memset(pp->diffinfo,'\0',diffsz);
388    if (pp->is->method->debug > 5)   
389       logf(LOG_LOG,"isamd_getDiffInfo: %d=%d:%d->%d, ix=%d mx=%d",
390          isamd_addr(pp->pos, pp->cat), pp->cat, pp->pos, pp->next,
391          diffidx,maxinfos);
392    
393    /* duplicate the buffer for diffs */
394    /* (so that we can read the next real buffer(s) */
395    assert(0==pp->diffbuf);
396    pp->diffbuf=xmalloc(maxsz);
397    memcpy(pp->diffbuf, pp->buf, maxsz);
398    
399    pp->diffinfo[0].maxidx=-1; /* mark as special */
400    pp->diffinfo[0].difftype=DT_MAIN;
401
402    while (i<maxinfos) 
403    {  
404       if ( diffidx+sizeof(int) > pp->is->method->filecat[pp->cat].bsize )
405       {
406          if (pp->is->method->debug > 5)
407            logf(LOG_LOG,"isamd_getDiffInfo:Near end (no room for len) at ix=%d n=%d",
408                diffidx, i);
409          return; /* whole block done */
410       }
411       memcpy( &pp->diffinfo[i].maxidx, &pp->diffbuf[diffidx], sizeof(int) );
412       pp->diffinfo[i].difftype=DT_DIFF;
413       if (pp->is->method->debug > 5)
414         logf(LOG_LOG,"isamd_getDiffInfo: max=%d ix=%d dbuf=%p",
415           pp->diffinfo[i].maxidx, diffidx, pp->diffbuf);
416
417       if ( (pp->is->method->debug > 0) &&
418          (pp->diffinfo[i].maxidx > pp->is->method->filecat[pp->cat].bsize) )
419       { 
420          logf(LOG_LOG,"Bad MaxIx!!! %s:%d: diffidx=%d", 
421                        __FILE__,__LINE__, diffidx);
422          logf(LOG_LOG,"i=%d maxix=%d bsz=%d", i, pp->diffinfo[i].maxidx,
423                        pp->is->method->filecat[pp->cat].bsize);
424          logf(LOG_LOG,"pp=%d=%d:%d  pp->nx=%d=%d:%d",
425                        isamd_addr(pp->pos,pp->cat), pp->pos, pp->cat,
426                        pp->next, isamd_type(pp->next), isamd_block(pp->next) );                      
427       }
428       assert(pp->diffinfo[i].maxidx <= pp->is->method->filecat[pp->cat].bsize+1);
429
430       if (0==pp->diffinfo[i].maxidx)
431       {
432          if (pp->is->method->debug > 5)  //!!! 4
433            logf(LOG_LOG,"isamd_getDiffInfo:End mark at ix=%d n=%d",
434                diffidx, i);
435          return; /* end marker */
436       }
437       diffidx += sizeof(int);
438       pp->diffinfo[i].decodeData = (*pp->is->method->code_start)(ISAMD_DECODE);
439       pp->diffinfo[i].diffidx = diffidx;
440       if (pp->is->method->debug > 5)
441         logf(LOG_LOG,"isamd_getDiff[%d]:%d-%d %s",
442           i,diffidx-sizeof(int),pp->diffinfo[i].maxidx,
443           hexdump((char *)&pp->diffbuf[diffidx-4],8,0) );
444       diffidx=pp->diffinfo[i].maxidx;
445       if ( diffidx > pp->is->method->filecat[pp->cat].bsize )
446         return; /* whole block done */
447       ++i;
448    }
449    assert (!"too many diff sequences in the block");
450 }
451
452 /***************************************************************
453  * Main block operations
454  ***************************************************************/
455
456
457 static ISAMD_PP get_new_main_block( ISAMD_PP firstpp, ISAMD_PP pp)
458 {  /* allocates a new block for the main data, and links it in */
459   int newblock;
460   if (0 == firstpp->next) 
461   {  /* special case, pp not yet allocated. */
462      /*Started as largest size, that's fine */
463      pp->pos = isamd_alloc_block(pp->is,pp->cat);
464      firstpp->next = isamd_addr(pp->pos,pp->cat);
465      if (pp->is->method->debug >3) 
466         logf(LOG_LOG,"isamd_build: Alloc 1. dblock  p=%d=%d:%d",
467            isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos);
468   }
469   newblock=isamd_alloc_block(pp->is,pp->cat);
470   pp->next=isamd_addr(newblock,pp->cat);
471   isamd_buildlaterblock(pp);
472   isamd_write_block(pp->is,pp->cat,pp->pos,pp->buf);
473   if (pp->is->method->debug >3) 
474      logf(LOG_LOG,"isamd_build: Alloc nxt %d=%d:%d -> %d=%d:%d",
475         isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos,
476         isamd_addr(newblock,pp->cat), pp->cat, newblock);
477   pp->next=0;
478   pp->pos=newblock;
479   pp->size=pp->offset=ISAMD_BLOCK_OFFSET_N;  
480   return pp;
481 } /* get_new_main_block */
482
483
484 static ISAMD_PP  append_main_item(ISAMD_PP firstpp, 
485                                   ISAMD_PP pp, 
486                                   struct it_key *i_key)
487 {  /* appends one item in the main data block, allocates new if needed */
488    char *i_item= (char *) i_key;  /* same as char */
489    char *i_ptr=i_item;
490    char codebuff[128];
491    char *c_ptr = codebuff;
492    int codelen;
493    char hexbuff[64];
494
495    int maxsize = pp->is->method->filecat[pp->is->max_cat].bsize; 
496
497    c_ptr=codebuff;
498    i_ptr=i_item;
499    (*pp->is->method->code_item)(ISAMD_ENCODE, pp->decodeClientData,
500                                 &c_ptr, &i_ptr);
501    codelen = c_ptr - codebuff;
502    assert ( (codelen<128) && (codelen>0));
503    if (pp->is->method->debug >7)
504       logf(LOG_LOG,"isamd:build: coded %s nk=%d,ofs=%d-%d",
505           hexdump(codebuff, c_ptr-codebuff,hexbuff), firstpp->numKeys+1,
506           pp->offset, pp->offset+codelen);
507
508    if (pp->offset + codelen > maxsize )
509    { /* oops, block full - get a new one */
510       pp =  get_new_main_block( firstpp, pp );
511       /* reset encoging and code again */
512       (*pp->is->method->code_reset)(pp->decodeClientData);
513       c_ptr=codebuff;
514       i_ptr=i_item;
515       (*pp->is->method->code_item)(ISAMD_ENCODE, pp->decodeClientData, 
516                                    &c_ptr, &i_ptr);
517       codelen = c_ptr - codebuff;
518       assert ( (codelen<128) && (codelen>0));
519       if (pp->is->method->debug >7)
520          logf(LOG_LOG,"isamd:build: recoded into %s  (nk=%d)",
521              hexdump(codebuff, c_ptr-codebuff,hexbuff), firstpp->numKeys+1);
522    } /* block full */    
523
524    assert (pp->offset + codelen <= maxsize );
525    
526    /* write the data into pp, now we must have room */ 
527    memcpy(&(pp->buf[pp->offset]),codebuff,codelen);
528    pp->offset += codelen;
529    pp->size += codelen;
530    firstpp->numKeys++;
531    /* clear the next 4 bytes in block, to avoid confusions with diff lens */
532    /* dirty, it should not be done here, but something slips somewhere, and */
533    /* I hope this fixes it...  - Heikki */
534    codelen = pp->offset;
535    while ( (codelen < maxsize ) && (codelen <= pp->offset+4) )
536      pp->buf[codelen++] = '\0';
537    return pp;    
538 } /* append_main_item */
539
540
541 /***************************************************************
542  * Read with merge
543  ***************************************************************/
544
545 /* Reads one item and corrects for the diffs, if any */
546 /* return 1 for ok, 0 for eof */
547 int isamd_read_item_merge (
548                      ISAMD_PP pp, 
549                      char **dst,
550                      struct it_key *p_key,  /* the data item that didn't fit*/
551               /*       ISAMD_I data)  */    /* more input data comes here */
552                      FILTER filt)           /* more input data comes here */
553 {                    /* The last two args can be null for ordinary reads */
554   char *keyptr;
555   char *codeptr;
556   char *codestart;
557   int winner=0; /* which diff holds the day */
558   int i; /* looping diffs */
559   int cmp;
560   int retry=1;
561   int oldoffs;
562   int rc;
563
564   if (!pp->diffinfo)  
565   { /* first time */
566      getDiffInfo(pp);
567
568      for(i=1; pp->diffinfo[i].difftype!=DT_NONE; i++)
569        ;  /* find last diff */
570      if (p_key)  
571      {  /* we have an extra item to inject into the merge */
572        if (pp->is->method->debug >9)  //!!!!!
573           logf(LOG_LOG,"isamd_read_item: going to merge with %d.%d",
574                p_key->sysno, p_key->seqno);
575        pp->diffinfo[i].key = *p_key;  /* the key merge could not handle */
576        pp->diffinfo[i].mode = pp->diffinfo[i].key.seqno & 1;
577        pp->diffinfo[i].key.seqno >>= 1;
578        pp->diffinfo[i].difftype=DT_INPU;
579        if (pp->is->method->debug > 7)
580          logf(LOG_LOG,"isamd_read_item: inpu key %d sys=%d  seq=%d=2*%d+%d",
581             i, p_key->sysno,
582             pp->diffinfo[i].key.seqno*2 + pp->diffinfo[1].mode,
583             pp->diffinfo[i].key.seqno,
584             pp->diffinfo[i].mode);
585        p_key->sysno=p_key->seqno=0;  /* used it up */
586      }
587
588      if (filt)
589      { /* we have a whole input stream to inject */
590        pp->diffinfo[i].difftype=DT_INPU;
591      }
592   } /* first time */ 
593         
594   while (retry)
595
596   {
597      retry=0;     
598      winner = 0;
599      for (i=0; (!retry) && (pp->diffinfo[i].difftype); i++)
600      {
601         if (0==pp->diffinfo[i].key.sysno)
602         {/* read a new one, if possible */
603            if ((pp->diffinfo[i].difftype==DT_DIFF) &&
604              (pp->diffinfo[i].diffidx < pp->diffinfo[i].maxidx))
605            { /* a normal kind of diff */
606               oldoffs=pp->diffinfo[i].diffidx;
607               codeptr= codestart = &(pp->diffbuf[pp->diffinfo[i].diffidx]);
608               keyptr=(char *)&(pp->diffinfo[i].key);
609               (*pp->is->method->code_item)(ISAMD_DECODE,
610                     pp->diffinfo[i].decodeData, &keyptr, &codeptr);
611               pp->diffinfo[i].diffidx += codeptr-codestart;
612               pp->diffinfo[i].mode = pp->diffinfo[i].key.seqno & 1;
613               pp->diffinfo[i].key.seqno = pp->diffinfo[i].key.seqno >>1 ;
614               if (pp->is->method->debug > 9)
615                 logf(LOG_LOG,"isamd_read_item: dif[%d] at %d-%d: %s",
616                   i,oldoffs, pp->diffinfo[i].diffidx,
617                   hexdump(pp->buf+oldoffs, pp->diffinfo[i].diffidx-oldoffs,0));
618               if (pp->is->method->debug > 7)
619                 logf(LOG_LOG,"isamd_read_item: rd dif[%d] %d.%d (%x.%x)",
620                   i,
621                   pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
622                   pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
623            }
624            else if ( pp->diffinfo[i].difftype==DT_MAIN)
625            { /* read a main item */
626               assert(i==0);  /* main data goes before any diffs */
627               oldoffs=pp->offset;
628               keyptr=(char*) &(pp->diffinfo[0].key);
629               rc= isamd_read_main_item(pp,&keyptr);
630               if (0==rc) 
631               { /* eof */
632                  if (pp->is->method->debug > 7)
633                    logf(LOG_LOG,"isamd_read_item: eof (rc=%d) main ",
634                            rc);
635                 pp->diffinfo[i].maxidx=-1;
636                 pp->diffinfo[i].key.sysno=0;
637                 pp->diffinfo[i].key.seqno=0;
638                 pp->diffinfo[i].difftype= DT_DONE;
639               } 
640               else
641               { /* not eof */
642                  pp->diffinfo[i].mode = 1;
643                  if (pp->is->method->debug > 7)
644                    logf(LOG_LOG,"isamd_read_item: rd main %d-%d %d.%d (%x.%x) m=%d",
645                      oldoffs,pp->offset,
646                      pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
647                      pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
648                      pp->diffinfo[i].mode);
649               } /* not eof */
650            }
651            else if (pp->diffinfo[i].difftype==DT_INPU)
652            {
653               keyptr = (char *) &pp->diffinfo[i].key;
654          /*     rc = (*data->read_item)(data->clientData, &keyptr, &pp->diffinfo[i].mode); */
655               rc = filter_read(filt, &pp->diffinfo[i].key, 
656                                      &pp->diffinfo[i].mode); 
657               if (!rc) 
658               {  /* did not get it */
659                  pp->diffinfo[i].key.sysno=0;
660                  pp->diffinfo[i].maxidx=0; /* signal the end */
661                  pp->diffinfo[i].difftype=DT_DONE;
662               }
663               if (pp->is->method->debug >7)
664                  logf(LOG_LOG,"merge: read inpu m=%d %d.%d (%x.%x)",
665                     pp->diffinfo[i].mode, 
666                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
667                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno );        
668            } /* read an input item */
669         } /* read a new one */
670         
671         if (pp->is->method->debug > 8)
672           logf(LOG_LOG,"isamd_read_item: considering d%d %d.%d ix=%d mx=%d",
673                i, pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
674                   pp->diffinfo[i].diffidx,   pp->diffinfo[i].maxidx);
675             
676         if ( 0!= pp->diffinfo[i].key.sysno)
677         { /* got a key, compare */
678           if (i!=winner)
679              cmp=key_compare(&pp->diffinfo[i].key, &pp->diffinfo[winner].key);
680           else
681              cmp=-1;
682           if (0==pp->diffinfo[winner].key.sysno)
683             cmp=-1; /* end of main sequence, take all diffs */
684           if (cmp<0)
685           {
686              if (pp->is->method->debug > 8)
687                logf(LOG_LOG,"isamd_read_item: ins [%d]%d.%d < [%d]%d.%d",
688                  i,  
689                  pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
690                  winner, 
691                  pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
692              if (pp->diffinfo[i].mode)  /* insert diff, should always be */
693                winner = i;
694              else
695              {
696                if (pp->is->method->debug > 1)
697                  logf(LOG_LOG,"delete diff for nonexisting item");
698                assert(!"delete diff for nonexisting item");  
699                /* is an assert too steep here? Not really.*/
700              }
701           } /* earlier key */
702           else if (cmp==0)
703           {
704              if (!pp->diffinfo[i].mode) /* delete diff. should always be */
705              {
706                 if (pp->is->method->debug > 8)
707                   logf(LOG_LOG,"isamd_read_item: del %d at%d %d.%d (%x.%x)",
708                     i, winner,
709                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
710                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
711                 pp->diffinfo[winner].key.sysno=0; /* delete it */
712              }
713              else
714                 if (pp->is->method->debug > 2)
715                   logf(LOG_LOG,"isamd_read_item: duplicate ins %d at%d %d.%d (%x.%x)",
716                     i, winner,
717                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
718                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
719                 /* skip the insert, since we already have it in the base */
720                 /* Should we fail an assertion here??? */
721              pp->diffinfo[i].key.sysno=0; /* done with the delete */
722              retry=1; /* start all over again */
723           } /* matching key */
724           /* else it is a later key, its turn will come */
725         } /* got a key */
726      } /* for each diff */
727   } /* not retry */
728
729   if ( pp->diffinfo[winner].key.sysno)
730   {
731     if (pp->is->method->debug > 7)
732       logf(LOG_LOG,"isamd_read_item: got %d  %d.%d (%x.%x)",
733         winner,
734         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno,
735         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
736     memcpy(*dst, &pp->diffinfo[winner].key, sizeof(struct it_key) );
737     *dst += sizeof(struct it_key);
738     pp->diffinfo[winner].key.sysno=0; /* used that one up */
739     cmp= 1;
740   } 
741   else 
742   {
743     if (pp->is->method->debug > 7)
744       logf(LOG_LOG,"isamd_read_item: eof w=%d  %d.%d (%x.%x)",
745         winner,
746         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno,
747         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
748     assert(winner==0); /* if nothing found, nothing comes from a diff */
749     cmp= 0; /* eof */
750   }
751   if (pp->is->method->debug >9)
752      logf(LOG_LOG,"mergeDB4: sysno[1]=%d", pp->diffinfo[1].key.sysno); /*!*/
753   return cmp;
754    
755 } /* isamd_read_item */
756
757
758 int isamd_read_item (ISAMD_PP pp, char **dst)
759 {
760   return isamd_read_item_merge(pp,dst,0,0);
761 }
762
763
764 /***************************************************************
765  * Merge
766  ***************************************************************/
767
768 static int merge ( ISAMD_PP firstpp,      /* first pp (with diffs) */
769                    struct it_key *p_key,  /* the data item that didn't fit*/
770               /*     ISAMD_I data) */     /* more input data comes here */
771                    FILTER filt)           /* more input data arriving here */
772 {
773   int diffidx;  
774   int killblk=0;
775   struct it_key r_key;
776   char * r_ptr;
777   int r_more = 1;
778   ISAMD_PP pp;
779   ISAMD_PP readpp=firstpp;
780   int retval=0;
781   int diffcat = firstpp->cat;  /* keep the category of the diffblock even */
782                                /* if it is going to be empty now. */
783                                /* Alternative: Make it the minimal, and */
784                                /* resize later. Saves disk, but will lead */
785                                /* into bad seeks. */
786   
787   ++(readpp->is->files[0].no_merges);
788      
789   /* set up diffs as they should be for reading */
790   diffidx = ISAMD_BLOCK_OFFSET_1; 
791   //readpp->diffbuf=readpp->buf;  // diffinfo has to duplicate it!
792   //getDiffInfo(readpp);  // first read will make the diffinfo, at init
793   
794   if (readpp->is->method->debug >4) 
795       logf(LOG_LOG,"isamd_merge: f=%d=%d:%d n=%d=%d:%d",
796         isamd_addr(firstpp->pos,firstpp->cat), firstpp->cat, firstpp->pos,
797         firstpp->next, isamd_type(firstpp->next), isamd_block(firstpp->next));  
798
799   /* release our data block. Do before reading, when pos is stable ! */
800   killblk=firstpp->pos;
801   if (killblk)
802   {
803       isamd_release_block(firstpp->is, firstpp->cat, killblk);
804       if (readpp->is->method->debug >3)   
805           logf(LOG_LOG,"isamd_merge: released old firstblock %d (%d:%d)",
806               isamd_addr(killblk,firstpp->cat), firstpp->cat, killblk );
807   }
808   
809
810   r_ptr= (char *) &r_key;
811 /*  r_more = isamd_read_item_merge( readpp, &r_ptr, p_key, data); */
812   r_more = isamd_read_item_merge( readpp, &r_ptr, p_key, filt);
813   if (!r_more)  
814   { /* oops, all data has been deleted! what to do??? */
815     /* never mind, we have at least one more delta to add to the block */
816     /* pray that is not a delete as well... */
817     r_key.sysno = 0;
818     r_key.seqno = 0;
819      if (readpp->is->method->debug >5) 
820          logf(LOG_LOG,"isamd_merge:all data has been deleted (nk=%d) ",
821             readpp->numKeys);
822     //assert (readpp->numKeys == 0);  /* no longer true! */
823   }
824
825
826   /* set up the new blocks for simple writing */
827   firstpp=isamd_pp_open(readpp->is,isamd_addr(0, diffcat));
828   firstpp->pos=isamd_alloc_block(firstpp->is,diffcat);
829   if (readpp->is->method->debug >3)   
830       logf(LOG_LOG,"isamd_merge: allocated new firstpp %d=%d:%d",
831           isamd_addr(firstpp->pos,firstpp->cat), firstpp->cat, firstpp->pos );
832   
833   pp=isamd_pp_open(readpp->is,isamd_addr(0,readpp->is->max_cat) );
834   pp->offset=pp->size=ISAMD_BLOCK_OFFSET_N;
835   
836   while (r_more)
837   {
838      if (readpp->is->method->debug >6) 
839          logf(LOG_LOG,"isamd_merge: got key %d.%d",
840            r_key.sysno, r_key.seqno );
841      pp= append_main_item(firstpp, pp, &r_key);
842
843      if ( (readpp->pos != killblk ) && (0!=readpp->pos) )
844      {  /* pos can get to 0 at end of main seq, if still diffs left...*/
845         if (readpp->is->method->debug >3)  
846             logf(LOG_LOG,"isamd_merge: released block %d (%d:%d) now %d=%d:%d",
847                 isamd_addr(killblk,readpp->cat), readpp->cat, killblk,
848                 isamd_addr(readpp->pos,readpp->cat),readpp->cat, readpp->pos );
849         isamd_release_block(readpp->is, readpp->cat, readpp->pos);
850         killblk=readpp->pos;
851      }
852
853      /* (try to) read next item */
854      r_ptr= (char *) &r_key;
855      r_more = isamd_read_item_merge( readpp, &r_ptr,0,filt);
856
857   } /* while read */
858   
859   
860 //  firstpp->diffs=0; 
861
862
863   isamd_reduceblock(pp);  /* reduce size if possible */
864   if (0==firstpp->next)
865     firstpp->next = isamd_addr(pp->pos,pp->cat);
866   save_last_pp(pp);
867   if (readpp->is->method->debug >4) 
868       logf(LOG_LOG,"isamd_merge: saved last block %d=%d:%d",
869             isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos);
870   isamd_pp_close(pp);
871
872   if (readpp->is->method->debug >5) 
873         logf(LOG_LOG,"isamd_merge: closing readpp %d=%d:%d di=%p",
874               isamd_addr(readpp->pos,readpp->cat), readpp->cat, readpp->pos,
875               readpp->diffinfo);
876   isamd_pp_close(readpp); /* pos is 0 by now, at eof. close works anyway */
877
878   if (readpp->is->method->debug >2)  
879       logf(LOG_LOG,"isamd_merge: merge ret f=%d=%d:%d pp=%d=%d:%d",
880             isamd_addr(firstpp->pos,pp->cat), firstpp->cat, firstpp->pos,
881             isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos);
882
883   firstpp->size = firstpp->offset = ISAMD_BLOCK_OFFSET_1;  /* nothing there */
884   memset(firstpp->buf,'\0',firstpp->is->method->filecat[firstpp->cat].bsize);
885   save_first_pp(firstpp);
886   retval = isamd_addr(firstpp->pos, firstpp->cat);
887   isamd_pp_close(firstpp);
888
889   return retval; 
890   
891 } /* merge */
892
893
894
895
896 /***************************************************************
897  * Appending diffs 
898  ***************************************************************/
899
900
901
902 static int append_diffs(
903       ISAMD is, 
904       ISAMD_P ipos, 
905       /*ISAMD_I data)*/
906       FILTER filt)
907 {
908    struct it_key i_key;    /* one input item */
909    char *i_item = (char *) &i_key;  /* same as chars */
910    char *i_ptr=i_item;
911    int i_more =1;
912    int i_mode;     /* 0 for delete, 1 for insert */ 
913
914    ISAMD_PP firstpp;
915    char hexbuff[64];
916    int diffidx=0;
917    int maxsize=0;
918    int difflenidx;
919    char codebuff[128];
920    char *c_ptr = codebuff;
921    int codelen;
922    int merge_rc;
923    int retval=0;
924
925    if (0==ipos)
926    {
927        firstpp=isamd_pp_open(is, isamd_addr(0,0) );
928        firstpp->size=firstpp->offset=ISAMD_BLOCK_OFFSET_1;
929          /* create in smallest category, will expand later */
930        ++(is->files[0].no_fbuilds);
931    } 
932    else
933    {
934        firstpp=isamd_pp_open(is, ipos);
935        ++(is->files[0].no_appds);
936    }
937
938    if (is->method->debug >2) 
939       logf(LOG_LOG,"isamd_appd: Start ipos=%d=%d:%d n=%d=%d:%d nk=%d",
940         ipos, isamd_type(ipos), isamd_block(ipos),
941         firstpp->next, isamd_type(firstpp->next), isamd_block(firstpp->next),
942         firstpp->numKeys);
943    maxsize = is->method->filecat[firstpp->cat].bsize; 
944    
945    difflenidx = diffidx = firstpp->size;
946    
947    diffidx+=sizeof(int);  /* difflen will be stored here */
948    
949    /* read first input */
950    //i_ptr = i_item;   //!!!
951    i_more = filter_read(filt, &i_key, &i_mode); 
952    /* i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); */
953
954    if (is->method->debug >6)
955       logf(LOG_LOG,"isamd_appd: start m=%d %d.%d=%x.%x: %d",
956          i_mode, 
957          i_key.sysno, i_key.seqno, 
958          i_key.sysno, i_key.seqno,
959          i_key.sysno*2+i_mode);
960
961    while (i_more)
962    {     
963       /* store the mode bit inside key */
964       assert( ((i_key.seqno<<1)>>1) == i_key.seqno); /* can spare the bit */
965       i_key.seqno = i_key.seqno * 2 + i_mode;  
966
967       c_ptr=codebuff;
968       i_ptr=i_item; 
969       (*is->method->code_item)(ISAMD_ENCODE, firstpp->decodeClientData, 
970                                &c_ptr, &i_ptr);
971       codelen = c_ptr - codebuff;
972       assert ( (codelen<128) && (codelen>0));
973       if (is->method->debug >7)
974          logf(LOG_LOG,"isamd_appd: coded %d: %s (nk=%d) (ix=%d)",
975              codelen, hexdump(codebuff, codelen,hexbuff), 
976              firstpp->numKeys,diffidx);
977
978       if (diffidx + codelen > maxsize )
979       { /* block full */
980          if (firstpp->cat < firstpp->is->max_cat)
981          { /* just increase the block size */
982              if (firstpp->pos > 0)  /* free the old block if allocated */
983                  isamd_release_block(is, firstpp->cat, firstpp->pos);
984              ++firstpp->cat;
985              maxsize = is->method->filecat[firstpp->cat].bsize; 
986              firstpp->pos=0; /* need to allocate it when saving */             
987              if (is->method->debug >3)
988                 logf(LOG_LOG,"isamd_appd: increased diff block to %d (%d)",
989                    firstpp->cat, maxsize);
990          }
991          else 
992          { /* max size already - can't help, need to merge it */
993              if (is->method->debug >7)
994                 logf(LOG_LOG,"isamd_appd: block full");
995              if (is->method->debug >9)  //!!!!!
996                 logf(LOG_LOG,"isamd_appd: going to merge with m=%d %d.%d",
997                      i_mode, i_key.sysno, i_key.seqno);
998              merge_rc = merge (firstpp, &i_key, filt);
999              if (0!=merge_rc)
1000                return merge_rc;  /* merge handled them all ! */
1001              assert(!"merge returned zero ??");
1002          } /* need to merge */
1003       } /* block full */
1004       
1005       assert ( diffidx+codelen <= maxsize );
1006       
1007       /* save the diff */ 
1008       memcpy(&(firstpp->buf[diffidx]),codebuff,codelen);
1009       diffidx += codelen;
1010       firstpp->size = firstpp->offset = diffidx;
1011       
1012       if (i_mode)
1013         firstpp->numKeys++; /* insert diff */
1014       else
1015         firstpp->numKeys--; /* delete diff */ 
1016
1017       /* update length of this diff run */
1018       memcpy(&(firstpp->buf[difflenidx]),&diffidx,sizeof(diffidx));
1019       
1020       /* (try to) read the next input */
1021       i_ptr = i_item;
1022       i_more = filter_read(filt, &i_key, &i_mode); 
1023     /*  i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); */
1024       if ( (i_more) && (is->method->debug >6) )
1025          logf(LOG_LOG,"isamd_appd: got m=%d %d.%d=%x.%x: %d",
1026             i_mode, 
1027             i_key.sysno, i_key.seqno, 
1028             i_key.sysno, i_key.seqno,
1029             i_key.sysno*2+i_mode);
1030    } /* more loop */
1031
1032    /* clear the next difflen, if room for such */
1033    difflenidx = diffidx;
1034    while ( (difflenidx-diffidx<=sizeof(int)+1) && (difflenidx<maxsize))
1035      firstpp->buf[difflenidx++]='\0';
1036
1037    if (0==firstpp->pos)  /* need to (re)alloc the block */
1038       firstpp->pos = isamd_alloc_block(is, firstpp->cat);
1039
1040    retval = save_first_pp( firstpp );
1041    isamd_pp_close(firstpp);
1042     
1043    return retval;
1044 } /* append_diffs */
1045
1046
1047
1048
1049 /*************************************************************
1050  * isamd_append itself
1051  *************************************************************/
1052
1053 ISAMD_P isamd_append (ISAMD is, ISAMD_P ipos, ISAMD_I data)
1054 {
1055    FILTER F = filter_open(is,data);
1056    ISAMD_P rc=0;
1057
1058    if ( filter_isempty(F) ) /* can be, if del-ins of the same */
1059    {
1060       if (is->method->debug >9) 
1061          logf(LOG_LOG,"isamd_appd: nothing to do");
1062       filter_close(F);
1063       return ipos; /* without doing anything at all */
1064    }
1065
1066    if ( ( 0==ipos) && filter_only_one(F) )
1067    {
1068       struct it_key k;
1069       int mode;
1070       filter_read(F,&k,&mode);     
1071       assert(mode); 
1072       rc = singleton_encode(&k);
1073       if (is->method->debug >9) 
1074          logf(LOG_LOG,"isamd_appd: singleton %d (%x)",
1075            rc,rc);
1076       assert ( (rc==0) || is_singleton(rc) );
1077    }
1078    if ( 0==rc) /* either not single, or it did not fit */
1079    {
1080       rc = append_diffs(is,ipos,F)<<1;  /* not singleton */
1081       assert ( ! is_singleton(rc) );  /*!*/
1082    }
1083    filter_close(F);
1084
1085    if (is->method->debug >9) 
1086       logf(LOG_LOG,"isamd_appd: ret %d=%x (%d=%x)",
1087         rc,rc,ipos,ipos);
1088
1089    return rc;
1090 } /*  isamd_append */
1091
1092
1093
1094
1095
1096
1097
1098 /*
1099  * $Log: merge-d.c,v $
1100  * Revision 1.22  1999-09-23 18:01:18  heikki
1101  * singleton optimising
1102  *
1103  * Revision 1.21  1999/09/21 17:36:43  heikki
1104  * Added filter function. Not much of effect on the small test set...
1105  *
1106  * Revision 1.20  1999/09/20 15:48:06  heikki
1107  * Small changes
1108  *
1109  * Revision 1.19  1999/09/13 13:28:28  heikki
1110  * isam-d optimizing: merging input data in the same go
1111  *
1112  * Revision 1.18  1999/08/25 18:09:24  heikki
1113  * Starting to optimize
1114  *
1115  * Revision 1.17  1999/08/24 13:17:42  heikki
1116  * Block sizes, comments
1117  *
1118  * Revision 1.16  1999/08/24 10:12:02  heikki
1119  * Comments about optimising
1120  *
1121  * Revision 1.15  1999/08/22 08:26:34  heikki
1122  * COmments
1123  *
1124  * Revision 1.14  1999/08/20 12:25:58  heikki
1125  * Statistics in isamd
1126  *
1127  * Revision 1.13  1999/08/18 13:59:19  heikki
1128  * Fixed another unlikely difflen bug
1129  *
1130  * Revision 1.12  1999/08/18 13:28:17  heikki
1131  * Set log levels to decent values
1132  *
1133  * Revision 1.11  1999/08/18 10:37:11  heikki
1134  * Fixed (another) difflen bug
1135  *
1136  * Revision 1.10  1999/08/18 09:13:31  heikki
1137  * Fixed a detail
1138  *
1139  * Revision 1.9  1999/08/17 19:46:53  heikki
1140  * Fixed a memory leak
1141  *
1142  * Revision 1.8  1999/08/07 11:30:59  heikki
1143  * Bug fixing (still a mem leak somewhere)
1144  *
1145  * Revision 1.7  1999/08/04 14:21:18  heikki
1146  * isam-d seems to be working.
1147  *
1148  * Revision 1.6  1999/07/23 15:43:05  heikki
1149  * Hunted a few bugs in isam-d. Still crashes on the long test run
1150  *
1151  * Revision 1.5  1999/07/23 13:58:52  heikki
1152  * merged closer to working, still fails on filling a separate, large block
1153  *
1154  * Revision 1.4  1999/07/21 14:53:55  heikki
1155  * isamd read and write functions work, except when block full
1156  * Merge missing still. Need to split some functions
1157  *
1158  * Revision 1.1  1999/07/14 13:14:47  heikki
1159  * Created empty
1160  *
1161  *
1162  */
1163
1164