Fixed memory leaks.
[idzebra-moved-to-github.git] / isam / isam.c
1 /*
2  * Copyright (C) 1994-1997, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: isam.c,v $
7  * Revision 1.24  1997-10-27 14:25:39  adam
8  * Fixed memory leaks.
9  *
10  * Revision 1.23  1997/09/17 12:19:20  adam
11  * Zebra version corresponds to YAZ version 1.4.
12  * Changed Zebra server so that it doesn't depend on global common_resource.
13  *
14  * Revision 1.22  1996/10/29 13:56:53  adam
15  * Include of zebrautl.h instead of alexutil.h.
16  *
17  * Revision 1.21  1996/03/29 14:11:47  quinn
18  * Change to is_merge
19  *
20  * Revision 1.20  1996/03/19  13:14:57  quinn
21  * Moved an xfree()
22  *
23  * Revision 1.19  1996/02/10  12:20:56  quinn
24  * *** empty log message ***
25  *
26  * Revision 1.18  1996/02/06  10:19:56  quinn
27  * Attempt at fixing bug. Not all blocks were read before they were unlinked
28  * prior to a remap operation.
29  *
30  * Revision 1.17  1995/12/06  15:48:44  quinn
31  * Fixed update-problem.
32  *
33  * Revision 1.16  1995/12/06  14:48:26  quinn
34  * Fixed some strange bugs.
35  *
36  * Revision 1.15  1995/12/06  09:59:45  quinn
37  * Fixed memory-consumption bug in memory.c
38  * Added more blocksizes to the default ISAM configuration.
39  *
40  * Revision 1.14  1995/11/24  17:26:19  quinn
41  * Mostly about making some ISAM stuff in the config file optional.
42  *
43  * Revision 1.13  1995/10/17  18:03:15  adam
44  * Commented out qsort in is_merge.
45  *
46  * Revision 1.12  1995/09/06  16:11:41  adam
47  * Keysize parameter to is_open (if non-zero).
48  *
49  * Revision 1.11  1995/09/04  12:33:46  adam
50  * Various cleanup. YAZ util used instead.
51  *
52  * Revision 1.10  1994/09/28  16:58:32  quinn
53  * Small mod.
54  *
55  * Revision 1.9  1994/09/28  12:56:15  quinn
56  * Added access functions (ISPT)
57  *
58  * Revision 1.8  1994/09/28  12:32:17  quinn
59  * Trivial
60  *
61  * Revision 1.7  1994/09/28  11:56:25  quinn
62  * Added sort of input to is_merge
63  *
64  * Revision 1.6  1994/09/28  11:29:33  quinn
65  * Added cmp parameter.
66  *
67  * Revision 1.5  1994/09/27  20:03:50  quinn
68  * Seems relatively bug-free.
69  *
70  * Revision 1.4  1994/09/26  17:11:29  quinn
71  * Trivial
72  *
73  * Revision 1.3  1994/09/26  17:06:35  quinn
74  * Back again...
75  *
76  * Revision 1.1  1994/09/12  08:02:13  quinn
77  * Not functional yet
78  *
79  */
80
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <ctype.h>
85
86 #include <zebrautl.h>
87 #include <bfile.h>
88 #include <isam.h>
89 #include "isutil.h"
90 #include "rootblk.h"
91 #include "keyops.h"
92
93 static ispt_struct *ispt_freelist = 0;
94
95 static struct
96 {
97     int total_merge_operations;
98     int total_items;
99     int dub_items_removed;
100     int new_items;
101     int failed_deletes;
102     int skipped_inserts;
103     int delete_insert_noop;
104     int delete_replace;
105     int delete;
106     int remaps;
107     int block_jumps;
108     int tab_deletes;
109     int new_tables;
110 } statistics;
111
112 static ISPT ispt_alloc()
113 {
114     ISPT p;
115
116     if (ispt_freelist)
117     {
118         p = ispt_freelist;
119         ispt_freelist = ispt_freelist->next;
120     }
121     else
122         p = xmalloc(sizeof(ispt_struct));
123     return p;
124 }
125
126 static void ispt_free(ISPT pt)
127 {
128     pt->next = ispt_freelist;
129     ispt_freelist = pt;
130 }
131
132 static int splitargs(const char *s, char *bf[], int max)
133 {
134     int ct = 0;
135     for (;;)
136     {
137         while (*s && isspace(*s))
138             s++;
139         bf[ct] = (char *) s;
140         if (!*s)
141                 return ct;
142         ct++;
143         if (ct > max)
144         {
145             logf (LOG_WARN, "Ignoring extra args to is resource");
146             bf[ct] = '\0';
147             return(ct - 1);
148         }
149         while (*s && !isspace(*s))
150             s++;
151     }
152 }
153
154 /*
155  * Open isam file.
156  * Process resources.
157  */
158 ISAM is_open(BFiles bfs, const char *name,
159              int (*cmp)(const void *p1, const void *p2),
160              int writeflag, int keysize, Res res)
161 {
162     ISAM new;
163     char *nm, *r, *pp[IS_MAX_BLOCKTYPES+1], m[2];
164     int num, size, rs, tmp, i;
165     is_type_header th;
166
167     logf (LOG_DEBUG, "is_open(%s, %s)", name, writeflag ? "RW" : "RDONLY");
168     if (writeflag)
169     {
170         statistics.total_merge_operations = 0;
171         statistics.total_items = 0;
172         statistics.dub_items_removed = 0;
173         statistics.new_items = 0;
174         statistics.failed_deletes = 0;
175         statistics.skipped_inserts = 0;
176         statistics.delete_insert_noop = 0;
177         statistics.delete_replace = 0;
178         statistics.delete = 0;
179         statistics.remaps = 0;
180         statistics.new_tables = 0;
181         statistics.block_jumps = 0;
182         statistics.tab_deletes = 0;
183     }
184
185     new = xmalloc(sizeof(*new));
186     new->writeflag = writeflag;
187     for (i = 0; i < IS_MAX_BLOCKTYPES; i++)
188         new->types[i].index = 0;                        /* dummy */
189
190     /* determine number and size of blocktypes */
191     if (!(r = res_get_def(res,
192                           nm = strconcat(name, ".",
193                                          "blocktypes", 0), "64 512 4K 32K")) ||
194         !(num = splitargs(r, pp, IS_MAX_BLOCKTYPES)))
195     {
196         logf (LOG_FATAL, "Failed to locate resource %s", nm);
197         return 0;
198     }
199     new->num_types = num;
200     for (i = 0; i < num; i++)
201     {
202         if ((rs = sscanf(pp[i], "%d%1[bBkKmM]", &size, m)) < 1)
203         {
204             logf (LOG_FATAL, "Error in resource %s: %s", r, pp[i]);
205             return 0;
206         }
207         if (rs == 1)
208                 *m = 'b';
209         switch (*m)
210         {
211                 case 'b': case 'B':
212                     new->types[i].blocksize = size; break;
213                 case 'k': case 'K':
214                     new->types[i].blocksize = size * 1024; break;
215                 case 'm': case 'M':
216                     new->types[i].blocksize = size * 1048576; break;
217                 default:
218                     logf (LOG_FATAL, "Illegal size suffix: %c", *m);
219                     return 0;
220         }
221         new->types[i].dbuf = xmalloc(new->types[i].blocksize);
222         m[0] = 'A' + i;
223         m[1] = '\0';
224         if (!(new->types[i].bf = bf_open(bfs, strconcat(name, m, 0), 
225             new->types[i].blocksize, writeflag)))
226         {
227             logf (LOG_FATAL, "bf_open failed");
228             return 0;
229         }
230         if ((rs = is_rb_read(&new->types[i], &th)) > 0)
231         {
232             if (th.blocksize != new->types[i].blocksize)
233             {
234                 logf (LOG_FATAL, "File blocksize mismatch in %s", name);
235                 exit(1);
236             }
237             new->types[i].freelist = th.freelist;
238             new->types[i].top = th.top;
239         }
240         else if (writeflag) /* write dummy superblock to determine top */
241         {
242             if ((rs = is_rb_write(&new->types[i], &th)) <=0)  /* dummy */
243             {
244                 logf (LOG_FATAL, "Failed to write initial superblock.");
245                 exit(1);
246             }
247             new->types[i].freelist = -1;
248             new->types[i].top = rs;
249         }
250         /* ELSE: this is an empty file opened in read-only mode. */
251     }
252     if (keysize > 0)
253         new->keysize = keysize;
254     else
255     {
256         if (!(r = res_get_def(res, nm = strconcat(name, ".",
257                                                   "keysize", 0), "4")))
258         {
259             logf (LOG_FATAL, "Failed to locate resource %s", nm);
260             return 0;
261         }
262         if ((new->keysize = atoi(r)) <= 0)
263         {
264             logf (LOG_FATAL, "Must specify positive keysize.");
265             return 0;
266         }
267     }
268
269     /* determine repack percent */
270     if (!(r = res_get_def(res, nm = strconcat(name, ".", "repack",
271                                               0), IS_DEF_REPACK_PERCENT)))
272     {
273         logf (LOG_FATAL, "Failed to locate resource %s", nm);
274         return 0;
275     }
276     new->repack = atoi(r);
277
278     /* determine max keys/blocksize */
279     if (!(r = res_get_def(res,
280                           nm = strconcat(name, ".",
281                                          "maxkeys", 0), "50 640 10000")) ||
282         !(num = splitargs(r, pp, IS_MAX_BLOCKTYPES)))
283     {
284         logf (LOG_FATAL, "Failed to locate resource %s", nm);
285         return 0;
286     }
287     if (num < new->num_types -1)
288     {
289         logf (LOG_FATAL, "Not enough elements in %s", nm);
290         return 0;
291     }
292     for (i = 0; i < num; i++)
293     {
294         if ((rs = sscanf(pp[i], "%d", &tmp)) < 1)
295         {
296             logf (LOG_FATAL, "Error in resource %s: %s", r, pp[i]);
297             return 0;
298         }
299         new->types[i].max_keys = tmp;
300     }
301
302     /* determine max keys/block */
303     for (i = 0; i < new->num_types; i++)
304     {
305         if (!new->types[i].index)
306         {
307             new->types[i].max_keys_block = (new->types[i].blocksize - 2 *
308                 sizeof(int)) / new->keysize;
309             new->types[i].max_keys_block0 = (new->types[i].blocksize - 3 *
310                 sizeof(int)) / new->keysize;
311         }
312         else
313             new->types[i].max_keys_block = new->types[i].max_keys_block0 /
314                 new->keysize;
315         if (new->types[i].max_keys_block0 < 1)
316         {
317             logf (LOG_FATAL, "Blocksize too small in %s", name);
318             exit(1);
319         }
320     }
321
322     /* determine nice fill rates */
323     if (!(r = res_get_def(res,
324                           nm = strconcat(name, ".",
325                                          "nicefill", 0), "90 90 90 95")) ||
326         !(num = splitargs(r, pp, IS_MAX_BLOCKTYPES)))
327     {
328         logf (LOG_FATAL, "Failed to locate resource %s", nm);
329         return 0;
330     }
331     if (num < new->num_types)
332     {
333         logf (LOG_FATAL, "Not enough elements in %s", nm);
334         return 0;
335     }
336     for (i = 0; i < num; i++)
337     {
338         if ((rs = sscanf(pp[i], "%d", &tmp)) < 1)
339         {
340             logf (LOG_FATAL, "Error in resource %s: %s", r, pp[i]);
341             return 0;
342         }
343         new->types[i].nice_keys_block = (new->types[i].max_keys_block0 * tmp) /
344             100;
345         if (new->types[i].nice_keys_block < 1)
346                 new->types[i].nice_keys_block = 1;
347     }
348
349     new->cmp = cmp ? cmp : is_default_cmp;
350     return new;
351 }
352
353 /*
354  * Close isam file.
355  */
356 int is_close(ISAM is)
357 {
358     int i;
359     is_type_header th;
360
361     logf (LOG_DEBUG, "is_close()");
362     for (i = 0; i < is->num_types; i++)
363     {
364         if (is->types[i].bf)
365         {
366             if (is->writeflag)
367             {
368                 th.blocksize = is->types[i].blocksize;
369                 th.keysize = is->keysize;
370                 th.freelist = is->types[i].freelist;
371                 th.top = is->types[i].top;
372                 if (is_rb_write(&is->types[i], &th) < 0)
373                 {
374                     logf (LOG_FATAL, "Failed to write headerblock");
375                     exit(1);
376                 }
377             }
378             bf_close(is->types[i].bf);
379         }
380     }
381     for (i = 0; i < is->num_types; i++)
382         xfree (is->types[i].dbuf);
383
384     if (is->writeflag)
385     {
386         logf(LOG_LOG, "ISAM statistics:");
387         logf(LOG_LOG, "total_merge_operations      %d",
388             statistics.total_merge_operations);
389         logf(LOG_LOG, "total_items                 %d", statistics.total_items);
390         logf(LOG_LOG, "dub_items_removed           %d",
391             statistics.dub_items_removed);
392         logf(LOG_LOG, "new_items                   %d", statistics.new_items);
393         logf(LOG_LOG, "failed_deletes              %d",
394             statistics.failed_deletes);
395         logf(LOG_LOG, "skipped_inserts             %d",
396             statistics.skipped_inserts);
397         logf(LOG_LOG, "delete_insert_noop          %d",
398             statistics.delete_insert_noop);
399         logf(LOG_LOG, "delete_replace              %d",
400             statistics.delete_replace);
401         logf(LOG_LOG, "delete                      %d", statistics.delete);
402         logf(LOG_LOG, "remaps                      %d", statistics.remaps);
403         logf(LOG_LOG, "block_jumps                 %d", statistics.block_jumps);
404         logf(LOG_LOG, "tab_deletes                 %d", statistics.tab_deletes);
405     }
406     xfree(is);
407     return 0;
408 }
409
410 static ISAM_P is_address(int type, int pos)
411 {
412     ISAM_P r;
413
414     r = pos << 2;
415     r |= type;
416     return r;
417 }
418
419 ISAM_P is_merge(ISAM is, ISAM_P pos, int num, char *data)
420 {
421     is_mtable tab;
422     int res;
423     char keybuf[IS_MAX_RECORD];
424     int oldnum, oldtype, i;
425     char operation, *record;
426
427     statistics.total_merge_operations++;
428     statistics.total_items += num;
429     if (!pos)
430         statistics.new_tables++;
431
432     is_m_establish_tab(is, &tab, pos);
433     if (pos)
434         if (is_m_read_full(&tab, tab.data) < 0)
435         {
436             logf (LOG_FATAL, "read_full failed");
437             exit(1);
438         }
439     oldnum = tab.num_records;
440     oldtype = tab.pos_type;
441     while (num)
442     {
443         operation = *(data)++;
444         record = (char*) data;
445         data += is_keysize(is);
446         num--;
447         while (num && !memcmp(record - 1, data, is_keysize(tab.is) + 1))
448         {
449             data += 1 + is_keysize(is);
450             num--;
451             statistics.dub_items_removed++;
452         }
453         if ((res = is_m_seek_record(&tab, record)) > 0)  /* no match */
454         {
455             if (operation == KEYOP_INSERT)
456             {
457                 logf (LOG_DEBUG, "XXInserting new record.");
458                 is_m_write_record(&tab, record);
459                 statistics.new_items++;
460             }
461             else
462             {
463                 logf (LOG_DEBUG, "XXDeletion failed to find match.");
464                 statistics.failed_deletes++;
465             }
466         }
467         else /* match found */
468         {
469             if (operation == KEYOP_INSERT)
470             {
471                 logf (LOG_DEBUG, "XXSkipping insertion - match found.");
472                 statistics.skipped_inserts++;
473                 continue;
474             }
475             else if (operation == KEYOP_DELETE)
476             {
477                 /* try to avoid needlessly moving data */
478                 if (num && *(data) == KEYOP_INSERT)
479                 {
480                     /* next key is identical insert? - NOOP - skip it */
481                     if (!memcmp(record, data + 1, is_keysize(is)))
482                     {
483                         logf (LOG_DEBUG, "XXNoop delete. skipping.");
484                         data += 1 + is_keysize(is);
485                         num--;
486                         while (num && !memcmp(data, data + is_keysize(tab.is) +
487                             1, is_keysize(tab.is) + 1))
488                         {
489                             data += 1 + is_keysize(is);
490                             num--;
491                             statistics.dub_items_removed++;
492                         }
493                         statistics.delete_insert_noop++;
494                         continue;
495                     }
496                     /* else check if next key can fit in this position */
497                     if (is_m_peek_record(&tab, keybuf) &&
498                         (*is->cmp)(data + 1, keybuf) < 0)
499                     {
500                         logf (LOG_DEBUG, "XXReplacing record.");
501                         is_m_replace_record(&tab, data + 1);
502                         data += 1 + is_keysize(is);
503                         num--;
504                         while (num && !memcmp(data, data + is_keysize(tab.is) +
505                             1, is_keysize(tab.is) + 1))
506                         {
507                             data += 1 + is_keysize(is);
508                             num--;
509                             statistics.dub_items_removed++;
510                         }
511                         statistics.delete_replace++;
512                         continue;
513                     }
514                 }
515                 logf (LOG_DEBUG, "Deleting record.");
516                 is_m_delete_record(&tab);
517                 statistics.delete++;
518             }
519         }
520     }
521     i = tab.pos_type;
522     while (i < tab.is->num_types - 1 && tab.num_records >
523         tab.is->types[i].max_keys)
524         i++;
525     if (i != tab.pos_type)
526     {
527         /* read remaining blocks */
528         for (; tab.cur_mblock; tab.cur_mblock = tab.cur_mblock->next)
529             if (tab.cur_mblock->state < IS_MBSTATE_CLEAN)
530                 is_m_read_full(&tab, tab.cur_mblock);
531         is_p_unmap(&tab);
532         tab.pos_type = i;
533         if (pos)
534             statistics.block_jumps++;
535     }
536     if (!oldnum || tab.pos_type != oldtype || (abs(oldnum - tab.num_records) *
537         100) / oldnum > tab.is->repack)
538     {
539         is_p_remap(&tab);
540         statistics.remaps++;
541     }
542     else
543         is_p_align(&tab);
544     if (tab.data)
545     {
546         is_p_sync(&tab);
547         pos = is_address(tab.pos_type, tab.data->diskpos);
548     }
549     else
550     {
551         pos = 0;
552         statistics.tab_deletes++;
553     }
554     is_m_release_tab(&tab);
555     return pos;
556 }
557
558 /*
559  * Locate a table of keys in an isam file. The ISPT is an individual
560  * position marker for that table.
561  */
562 ISPT is_position(ISAM is, ISAM_P pos)
563 {
564     ispt_struct *p;
565
566     p = ispt_alloc();
567     is_m_establish_tab(is, &p->tab, pos);
568     return p;
569 }
570
571 /*
572  * Release ISPT.
573  */
574 void is_pt_free(ISPT ip)
575 {
576     is_m_release_tab(&ip->tab);
577     ispt_free(ip);
578 }
579
580 /*
581  * Read a key from a table.
582  */
583 int is_readkey(ISPT ip, void *buf)
584 {
585     return is_m_read_record(&ip->tab, buf, 0);
586 }    
587
588 int is_numkeys(ISPT ip)
589 {
590     return is_m_num_records(&ip->tab);
591 }
592
593 void is_rewind(ISPT ip)
594 {
595     is_m_rewind(&ip->tab);
596 }