Remove COMPAT_TABLE_VERSION.
[osl.git] / osl.c
1 /*
2  * Copyright (C) 2007-2009 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file osl.c Object storage layer functions. */
8 #include <dirent.h> /* readdir() */
9 #include <assert.h>
10
11 #include "log.h"
12 #include "osl.h"
13 #include "util.h"
14 #include "osl_core.h"
15
16 /*
17  * Taken from Drepper: How to write shared libraries, Appendix B.
18  *
19  * The main reason for this rather fancy implementation of strerror() is to
20  * avoid having an array of pointers. This is desirable because initialized
21  * pointer variables increase the startup time of the library due to the
22  * processing of relocations.
23  */
24 #include <stddef.h>
25 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
26 #define MSGSTRFIELD1(line) str##line
27 static const union msgstr_t {
28         struct {
29 #define OSL_ERROR(n, s) char MSGSTRFIELD(__LINE__)[sizeof(s)];
30 #include "errtab.h"
31 #undef OSL_ERROR
32         };
33         char str[0];
34 } msgstr = { {
35 #define OSL_ERROR(n, s) s,
36 #include "errtab.h"
37 #undef OSL_ERROR
38 } };
39 static const unsigned int errmsgidx[] = {
40 #define OSL_ERROR(n, s) [n] = offsetof(union msgstr_t, MSGSTRFIELD(__LINE__)),
41 #include "errtab.h"
42 #undef OSL_ERROR
43 };
44
45 __export const char *osl_strerror(int num)
46 {
47         return msgstr.str + errmsgidx[num];
48 }
49
50 int loglevel = 0;
51
52 static void __attribute ((constructor)) init_loglevel(void)
53 {
54         char *p = getenv("OSL_LOGLEVEL");
55
56         /* don't log anything if unset */
57         loglevel = p? atoi(p) : EMERG + 1;
58 }
59
60 /**
61  * The log function.
62  *
63  * \param ll Loglevel.
64  * \param fmt Usual format string.
65  *
66  * All XXX_LOG() macros use this function.
67  */
68 __printf_2_3 void __log(int ll, const char* fmt,...)
69 {
70         va_list argp;
71         struct tm *tm;
72         time_t t1;
73         char str[255] = "";
74
75         if (ll < loglevel)
76                 return;
77         time(&t1);
78         tm = localtime(&t1);
79         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
80         fprintf(stderr, "%s ", str);
81         va_start(argp, fmt);
82         vfprintf(stderr, fmt, argp);
83         va_end(argp);
84 }
85
86 /**
87  * A wrapper for lseek(2).
88  *
89  * \param fd The file descriptor whose offset is to be to repositioned.
90  * \param offset A value-result parameter.
91  * \param whence Usual repositioning directive.
92  *
93  * Reposition the offset of the file descriptor \a fd to the argument \a offset
94  * according to the directive \a whence. Upon successful return, \a offset
95  * contains the resulting offset location as measured in bytes from the
96  * beginning of the file.
97  *
98  * \return Positive on success. Otherwise, the function returns \p -E_OSL_LSEEK.
99  *
100  * \sa lseek(2).
101  */
102 static int __lseek(int fd, off_t *offset, int whence)
103 {
104         *offset = lseek(fd, *offset, whence);
105         int ret = -E_OSL_LSEEK;
106         if (*offset == -1)
107                 return ret;
108         return 1;
109 }
110
111 static int append_file(const char *filename, char *data, size_t data_size,
112                 uint32_t *new_pos)
113 {
114         int ret, fd;
115
116 //      DEBUG_LOG("appending %zu  + %zu bytes\n", header_size, data_size);
117         ret = osl_open(filename, O_WRONLY | O_CREAT | O_APPEND, 0644);
118         if (ret < 0)
119                 return ret;
120         fd = ret;
121         ret = write_all(fd, data, &data_size);
122         if (ret < 0)
123                 goto out;
124         if (new_pos) {
125                 off_t offset = 0;
126                 ret = __lseek(fd, &offset, SEEK_END);
127                 if (ret < 0)
128                         goto out;
129 //              DEBUG_LOG("new file size: " FMT_OFF_T "\n", offset);
130                 *new_pos = offset;
131         }
132         ret = 1;
133 out:
134         close(fd);
135         return ret;
136 }
137
138 static int verify_name(const char *name)
139 {
140         if (!name)
141                 return -E_OSL_BAD_NAME;
142         if (!*name)
143                 return -E_OSL_BAD_NAME;
144         if (strchr(name, '/'))
145                 return -E_OSL_BAD_NAME;
146         if (!strcmp(name, ".."))
147                 return -E_OSL_BAD_NAME;
148         if (!strcmp(name, "."))
149                 return -E_OSL_BAD_NAME;
150         return 1;
151 }
152
153 static char *disk_storage_dirname(const struct osl_table *t, unsigned col_num,
154                 const char *ds_name)
155 {
156         char *dirname, *column_name = column_filename(t, col_num);
157
158         if (!column_name)
159                 return NULL;
160         if (!(t->desc->flags & OSL_LARGE_TABLE))
161                 return column_name;
162         dirname = make_message("%s/%.2s", column_name, ds_name);
163         free(column_name);
164         return dirname;
165 }
166
167 static char *disk_storage_name_of_object(const struct osl_table *t,
168         const struct osl_object *obj)
169 {
170         HASH_TYPE hash[HASH_SIZE];
171         hash_object(obj, hash);
172         return disk_storage_name_of_hash(t, hash);
173 }
174
175 static int disk_storage_name_of_row(const struct osl_table *t,
176                 const struct osl_row *row, char **name)
177 {
178         struct osl_object obj;
179         int ret = osl_get_object(t, row, t->disk_storage_name_column, &obj);
180
181         if (ret < 0)
182                 return ret;
183         *name = disk_storage_name_of_object(t, &obj);
184         if (*name)
185                 return 1;
186         return -E_OSL_NOMEM;
187 }
188
189 static void column_name_hash(const char *col_name, HASH_TYPE *hash)
190 {
191         hash_function(col_name, strlen(col_name), hash);
192 }
193
194 static int init_column_descriptions(struct osl_table *t)
195 {
196         int i, j, ret;
197         const struct osl_column_description *cd;
198
199         ret = verify_name(t->desc->name);
200         if (ret < 0)
201                 goto err;
202         ret = -E_OSL_BAD_DB_DIR;
203         if (!t->desc->dir && (t->num_disk_storage_columns || t->num_mapped_columns))
204                 goto err;
205         /* the size of the index header without column descriptions */
206         t->index_header_size = IDX_COLUMN_DESCRIPTIONS;
207         FOR_EACH_COLUMN(i, t->desc, cd) {
208                 struct osl_column *col = t->columns + i;
209                 if (cd->storage_flags & OSL_RBTREE) {
210                         if (!cd->compare_function)
211                                 return -E_OSL_NO_COMPARE_FUNC;
212                 }
213                 if (cd->storage_type == OSL_NO_STORAGE)
214                         continue;
215                 ret = -E_OSL_NO_COLUMN_NAME;
216                 if (!cd->name || !cd->name[0])
217                         goto err;
218                 ret = verify_name(cd->name);
219                 if (ret < 0)
220                         goto err;
221                 t->index_header_size += index_column_description_size(cd->name);
222                 column_name_hash(cd->name, col->name_hash);
223                 ret = -E_OSL_DUPLICATE_COL_NAME;
224                 for (j = i + 1; j < t->desc->num_columns; j++) {
225                         const char *name2 = get_column_description(t->desc,
226                                 j)->name;
227                         if (cd->name && name2 && !strcmp(cd->name, name2))
228                                 goto err;
229                 }
230         }
231         return 1;
232 err:
233         return ret;
234 }
235
236 /**
237  * Initialize a struct table from given table description.
238  *
239  * \param desc The description of the osl table.
240  * \param table_ptr Result is returned here.
241  *
242  * This function performs several sanity checks on \p desc and returns if any
243  * of these tests fail. On success, a struct \p osl_table is allocated and
244  * initialized with data derived from \p desc.
245  *
246  * \return Standard.
247  *
248  * \sa struct osl_table.
249  */
250 int init_table_structure(const struct osl_table_description *desc,
251                 struct osl_table **table_ptr)
252 {
253         const struct osl_column_description *cd;
254         struct osl_table *t = calloc(1, sizeof(*t));
255         int i, ret = -E_OSL_NOMEM, have_disk_storage_name_column = 0;
256
257         if (!t)
258                 return ret;
259         ret = -E_OSL_BAD_TABLE_DESC;
260         if (!desc)
261                 goto err;
262         DEBUG_LOG("creating table structure for '%s' from table "
263                 "description\n", desc->name);
264         ret = -E_OSL_NO_COLUMN_DESC;
265         if (!desc->column_descriptions)
266                 goto err;
267         ret = -E_OSL_NO_COLUMNS;
268         if (!desc->num_columns)
269                 goto err;
270         ret = -E_OSL_NOMEM;
271         t->columns = calloc(desc->num_columns, sizeof(struct osl_column));
272         if (!t->columns)
273                 goto err;
274         t->desc = desc;
275         FOR_EACH_COLUMN(i, t->desc, cd) {
276                 enum osl_storage_type st = cd->storage_type;
277                 enum osl_storage_flags sf = cd->storage_flags;
278                 struct osl_column *col = &t->columns[i];
279
280                 ret = -E_OSL_BAD_STORAGE_TYPE;
281                 if (st != OSL_MAPPED_STORAGE && st != OSL_DISK_STORAGE
282                                 && st != OSL_NO_STORAGE)
283                         goto err;
284                 ret = -E_OSL_BAD_STORAGE_FLAGS;
285                 if (st == OSL_DISK_STORAGE && sf & OSL_RBTREE)
286                         goto err;
287                 if ((sf & OSL_RBTREE) && !(sf & OSL_UNIQUE))
288                         WARNING_LOG("invalid storage flags for column %s: "
289                                 "OSL_RBTREE && !OSL_UNIQUE\n", cd->name);
290                 ret = -E_OSL_BAD_STORAGE_SIZE;
291                 if (sf & OSL_FIXED_SIZE && !cd->data_size)
292                         goto err;
293                 switch (st) {
294                 case OSL_DISK_STORAGE:
295                         t->num_disk_storage_columns++;
296                         break;
297                 case OSL_MAPPED_STORAGE:
298                         t->num_mapped_columns++;
299                         col->index_offset = t->row_index_size;
300                         t->row_index_size += 8;
301                         break;
302                 case OSL_NO_STORAGE:
303                         col->volatile_num = t->num_volatile_columns;
304                         t->num_volatile_columns++;
305                         break;
306                 }
307                 if (sf & OSL_RBTREE) {
308                         col->rbtree_num = t->num_rbtrees;
309                         t->num_rbtrees++;
310                         if ((sf & OSL_UNIQUE) && (st == OSL_MAPPED_STORAGE)) {
311                                 if (!have_disk_storage_name_column)
312                                         t->disk_storage_name_column = i;
313                                 have_disk_storage_name_column = 1;
314                         }
315                 }
316         }
317         ret = -E_OSL_NO_UNIQUE_RBTREE_COLUMN;
318         if (t->num_disk_storage_columns && !have_disk_storage_name_column)
319                 goto err;
320         ret = -E_OSL_NO_RBTREE_COL;
321         if (!t->num_rbtrees)
322                 goto err;
323         /* success */
324         DEBUG_LOG("OK. Index entry size: %u\n", t->row_index_size);
325         ret = init_column_descriptions(t);
326         if (ret < 0)
327                 goto err;
328         *table_ptr = t;
329         return 1;
330 err:
331         free(t->columns);
332         free(t);
333         return ret;
334 }
335
336 /**
337  * Read the table description from index header.
338  *
339  * \param map The memory mapping of the index file.
340  * \param desc The values found in the index header are returned here.
341  *
342  * Read the index header, check for the osl magic string and the table version
343  * number.  Read all information stored in the index header into \a desc.
344  *
345  * \return Standard.
346  *
347  * \sa struct osl_table_description, osl_create_table.
348  */
349 int read_table_desc(struct osl_object *map, struct osl_table_description *desc)
350 {
351         char *buf = map->data;
352         uint8_t table_version;
353         uint16_t header_size;
354         int ret, i;
355         unsigned offset;
356         struct osl_column_description *cd;
357
358         if (map->size < MIN_INDEX_HEADER_SIZE(1))
359                 return -E_OSL_SHORT_TABLE;
360         if (strncmp(buf + IDX_OSL_MAGIC, OSL_MAGIC, strlen(OSL_MAGIC)))
361                 return -E_OSL_NO_MAGIC;
362         table_version = read_u8(buf + IDX_VERSION);
363         INFO_LOG("osl versions (table/min/current): %u/%u/%u\n",
364                 table_version, MIN_TABLE_VERSION, CURRENT_TABLE_VERSION);
365         if (table_version < MIN_TABLE_VERSION /* table too old */
366                 || table_version > CURRENT_TABLE_VERSION) /* libosl too old */
367                 return -E_OSL_VERSION_MISMATCH;
368         desc->flags = read_u8(buf + IDX_TABLE_FLAGS);
369         desc->num_columns = read_u16(buf + IDX_NUM_COLUMNS);
370         INFO_LOG("%u columns\n", desc->num_columns);
371         if (!desc->num_columns)
372                 return -E_OSL_NO_COLUMNS;
373         header_size = read_u16(buf + IDX_HEADER_SIZE);
374         if (map->size < header_size)
375                 return -E_OSL_BAD_SIZE;
376         desc->column_descriptions = calloc(desc->num_columns,
377                 sizeof(struct osl_column_description));
378         if (!desc->column_descriptions)
379                 return -E_OSL_NOMEM;
380         offset = IDX_COLUMN_DESCRIPTIONS;
381         FOR_EACH_COLUMN(i, desc, cd) {
382                 char *null_byte;
383
384                 ret = -E_OSL_SHORT_TABLE;
385                 if (map->size < offset + MIN_IDX_COLUMN_DESCRIPTION_SIZE) {
386                         ERROR_LOG("map size = %zu < %u = offset + min desc size\n",
387                                 map->size, offset + MIN_IDX_COLUMN_DESCRIPTION_SIZE);
388                         goto err;
389                 }
390                 cd->storage_type = read_u16(buf + offset + IDX_CD_STORAGE_TYPE);
391                 cd->storage_flags = read_u16(buf + offset +
392                         IDX_CD_STORAGE_FLAGS);
393                 cd->data_size = read_u32(buf + offset + IDX_CD_DATA_SIZE);
394                 null_byte = memchr(buf + offset + IDX_CD_NAME, '\0',
395                         map->size - offset - IDX_CD_NAME);
396                 ret = -E_OSL_INDEX_CORRUPTION;
397                 if (!null_byte)
398                         goto err;
399                 ret = -E_OSL_NOMEM;
400                 cd->name = strdup(buf + offset + IDX_CD_NAME);
401                 if (!cd->name)
402                         goto err;
403                 offset += index_column_description_size(cd->name);
404         }
405         if (offset != header_size) {
406                 ret = -E_OSL_INDEX_CORRUPTION;
407                 ERROR_LOG("real header size = %u != %u = stored header size\n",
408                         offset, header_size);
409                 goto err;
410         }
411         return 1;
412 err:
413         FOR_EACH_COLUMN(i, desc, cd)
414                 free(cd->name);
415         return ret;
416 }
417
418 /*
419  * check whether the table description given by \p t->desc matches the on-disk
420  * table structure stored in the index of \a t.
421  */
422 static int compare_table_descriptions(struct osl_table *t)
423 {
424         int i, ret;
425         struct osl_table_description desc;
426         const struct osl_column_description *cd1, *cd2;
427
428         /* read the on-disk structure into desc */
429         ret = read_table_desc(&t->index_map, &desc);
430         if (ret < 0)
431                 return ret;
432         ret = -E_OSL_BAD_TABLE_FLAGS;
433         if (desc.flags != t->desc->flags)
434                 goto out;
435         ret = -E_OSL_BAD_COLUMN_NUM;
436         if (desc.num_columns > t->desc->num_columns)
437                 goto out;
438         if (desc.num_columns < t->desc->num_columns) {
439                 struct osl_column_description *cd;
440                 unsigned diff = t->desc->num_columns - desc.num_columns;
441                 INFO_LOG("extending table by %u volatile columns\n", diff);
442                 ret = -E_OSL_NOMEM;
443                 desc.column_descriptions = realloc(desc.column_descriptions,
444                         t->desc->num_columns * sizeof(struct osl_column_description));
445                 if (!desc.column_descriptions)
446                         goto out;
447                 for (i = desc.num_columns; i < t->desc->num_columns; i++) {
448                         cd = get_column_description(&desc, i);
449                         cd->storage_type = OSL_NO_STORAGE;
450                         cd->name = NULL;
451                 }
452                 desc.num_columns += diff;
453         }
454         FOR_EACH_COLUMN(i, t->desc, cd1) {
455                 cd2 = get_column_description(&desc, i);
456                 ret = -E_OSL_BAD_STORAGE_TYPE;
457                 if (cd1->storage_type != cd2->storage_type)
458                         goto out;
459                 if (cd1->storage_type == OSL_NO_STORAGE)
460                         continue;
461                 ret = -E_OSL_BAD_STORAGE_FLAGS;
462                 if (cd1->storage_flags != cd2->storage_flags) {
463                         ERROR_LOG("sf1 = %u != %u = sf2\n",
464                                 cd1->storage_flags, cd2->storage_flags);
465                         goto out;
466                 }
467                 ret = -E_OSL_BAD_DATA_SIZE;
468                 if (cd1->storage_flags & OSL_FIXED_SIZE)
469                         if (cd1->data_size != cd2->data_size)
470                                 goto out;
471                 ret = -E_OSL_BAD_COLUMN_NAME;
472                 if (strcmp(cd1->name, cd2->name))
473                         goto out;
474         }
475         INFO_LOG("table description of '%s' matches on-disk data, good\n",
476                 t->desc->name);
477         ret = 1;
478 out:
479         FOR_EACH_COLUMN(i, &desc, cd1)
480                 free(cd1->name);
481         free(desc.column_descriptions);
482         return ret;
483 }
484
485 static int create_table_index(struct osl_table *t)
486 {
487         char *buf, *filename;
488         int i, ret;
489         size_t size = t->index_header_size;
490         const struct osl_column_description *cd;
491         unsigned offset;
492
493         INFO_LOG("creating %zu byte index for table %s\n", size,
494                 t->desc->name);
495         buf = calloc(1, size);
496         if (!buf)
497                 return -E_OSL_NOMEM;
498         sprintf(buf + IDX_OSL_MAGIC, "%s", OSL_MAGIC);
499         write_u8(buf + IDX_TABLE_FLAGS, t->desc->flags);
500         write_u8(buf + IDX_DIRTY_FLAG, 0);
501         write_u8(buf + IDX_VERSION, CURRENT_TABLE_VERSION);
502         write_u16(buf + IDX_NUM_COLUMNS, t->num_mapped_columns + t->num_disk_storage_columns);
503         write_u16(buf + IDX_HEADER_SIZE, t->index_header_size);
504         offset = IDX_COLUMN_DESCRIPTIONS;
505         FOR_EACH_COLUMN(i, t->desc, cd) {
506                 /* no need to store info about volatile storage */
507                 if (cd->storage_type == OSL_NO_STORAGE)
508                         continue;
509                 write_u16(buf + offset + IDX_CD_STORAGE_TYPE,
510                         cd->storage_type);
511                 write_u16(buf + offset + IDX_CD_STORAGE_FLAGS,
512                         cd->storage_flags);
513                 if (cd->storage_flags & OSL_FIXED_SIZE)
514                         write_u32(buf + offset + IDX_CD_DATA_SIZE,
515                                 cd->data_size);
516                 strcpy(buf + offset + IDX_CD_NAME, cd->name);
517                 offset += index_column_description_size(cd->name);
518         }
519         assert(offset == size);
520         filename = index_filename(t->desc);
521         if (filename)
522                 ret = write_file(filename, buf, size);
523         else
524                 ret = -E_OSL_NOMEM;
525         free(buf);
526         free(filename);
527         return ret;
528 }
529
530 __export int osl_create_table(const struct osl_table_description *desc)
531 {
532         const struct osl_column_description *cd;
533         char *table_dir = NULL, *filename;
534         struct osl_table *t;
535         int i, ret = init_table_structure(desc, &t);
536
537         if (ret < 0)
538                 return ret;
539         INFO_LOG("creating %s\n", desc->name);
540         FOR_EACH_COLUMN(i, t->desc, cd) {
541                 if (cd->storage_type == OSL_NO_STORAGE)
542                         continue;
543                 if (!table_dir) {
544                         ret = osl_mkdir(desc->dir, 0777);
545                         if (ret < 0 && ret != -E_OSL_DIR_EXISTS)
546                                 goto out;
547                         table_dir = make_message("%s/%s", desc->dir,
548                                 desc->name);
549                         ret = -E_OSL_NOMEM;
550                         if (!table_dir)
551                                 goto out;
552                         ret = osl_mkdir(table_dir, 0777);
553                         if (ret < 0)
554                                 goto out;
555                 }
556                 ret = -E_OSL_NOMEM;
557                 filename = column_filename(t, i);
558                 if (!filename)
559                         goto out;
560                 INFO_LOG("filename: %s\n", filename);
561                 if (cd->storage_type == OSL_MAPPED_STORAGE) {
562                         ret = osl_open(filename, O_RDWR | O_CREAT | O_EXCL,
563                                 0644);
564                         free(filename);
565                         if (ret < 0)
566                                 goto out;
567                         close(ret);
568                         continue;
569                 }
570                 /* DISK STORAGE */
571                 ret = osl_mkdir(filename, 0777);
572                 free(filename);
573                 if (ret < 0)
574                         goto out;
575         }
576         if (t->num_mapped_columns) {
577                 ret = create_table_index(t);
578                 if (ret < 0)
579                         goto out;
580         }
581         ret = 1;
582 out:
583         free(table_dir);
584         free(t->columns);
585         free(t);
586         return ret;
587 }
588
589 static int table_is_dirty(struct osl_table *t)
590 {
591         char *buf = (char *)t->index_map.data + IDX_DIRTY_FLAG;
592         uint8_t dirty = read_u8(buf) & 0x1;
593         return !!dirty;
594 }
595
596 static void mark_table_dirty(struct osl_table *t)
597 {
598         char *buf = (char *)t->index_map.data + IDX_DIRTY_FLAG;
599         write_u8(buf, read_u8(buf) | 1);
600 }
601
602 static void mark_table_clean(struct osl_table *t)
603 {
604         char *buf = (char *)t->index_map.data + IDX_DIRTY_FLAG;
605         write_u8(buf, read_u8(buf) & 0xfe);
606 }
607
608 static void unmap_column(struct osl_table *t, unsigned col_num)
609 {
610         struct osl_object map = t->columns[col_num].data_map;
611         int ret;
612         if (!map.data)
613                 return;
614         ret = osl_munmap(map.data, map.size);
615         assert(ret > 0);
616         map.data = NULL;
617 }
618
619 /**
620  * Unmap all mapped files of an osl table.
621  *
622  * \param t Pointer to a mapped table.
623  * \param flags Options for unmapping.
624  *
625  * \return Positive on success, negative on errors.
626  *
627  * \sa map_table(), enum osl_close_flags, osl_munmap().
628  */
629 int unmap_table(struct osl_table *t, enum osl_close_flags flags)
630 {
631         unsigned i;
632         const struct osl_column_description *cd;
633         int ret;
634
635         if (!t->num_mapped_columns) /* can this ever happen? */
636                 return 1;
637         INFO_LOG("unmapping table '%s'\n", t->desc->name);
638         if (!t->index_map.data)
639                 return -E_OSL_NOT_MAPPED;
640         if (flags & OSL_MARK_CLEAN)
641                 mark_table_clean(t);
642         ret = osl_munmap(t->index_map.data, t->index_map.size);
643         if (ret < 0)
644                 return ret;
645         t->index_map.data = NULL;
646         if (!t->num_rows)
647                 return 1;
648         FOR_EACH_MAPPED_COLUMN(i, t, cd)
649                 unmap_column(t, i);
650         return 1;
651 }
652
653 static int map_column(struct osl_table *t, unsigned col_num)
654 {
655         struct stat statbuf;
656         char *filename = column_filename(t, col_num);
657         int ret;
658
659         if (!filename)
660                 return -E_OSL_NOMEM;
661         ret = osl_stat(filename, &statbuf);
662         if (ret < 0) {
663                 free(filename);
664                 return ret;
665         }
666         if (!(S_IFREG & statbuf.st_mode)) {
667                 free(filename);
668                 return ret;
669         }
670         ret = mmap_full_file(filename, O_RDWR,
671                 &t->columns[col_num].data_map.data,
672                 &t->columns[col_num].data_map.size,
673                 NULL);
674         free(filename);
675         return ret;
676 }
677
678 /**
679  * Map the index file and all columns of type \p OSL_MAPPED_STORAGE into memory.
680  *
681  * \param t Pointer to an initialized table structure.
682  * \param flags Mapping options.
683  *
684  * \return Negative return value on errors; on success the number of rows
685  * (including invalid rows) is returned.
686  *
687  * \sa unmap_table(), enum map_table_flags, osl_open_table(), mmap(2).
688  */
689 int map_table(struct osl_table *t, enum map_table_flags flags)
690 {
691         char *filename;
692         const struct osl_column_description *cd;
693         int i = 0, ret, num_rows = 0;
694
695         if (!t->num_mapped_columns)
696                 return 0;
697         if (t->index_map.data)
698                 return -E_OSL_ALREADY_MAPPED;
699         filename = index_filename(t->desc);
700         if (!filename)
701                 return -E_OSL_NOMEM;
702         INFO_LOG("mapping table '%s' (index: %s)\n", t->desc->name, filename);
703         ret = mmap_full_file(filename, flags & MAP_TBL_FL_MAP_RDONLY?
704                 O_RDONLY : O_RDWR, &t->index_map.data, &t->index_map.size, NULL);
705         free(filename);
706         if (ret < 0)
707                 return ret;
708         if (flags & MAP_TBL_FL_VERIFY_INDEX) {
709                 ret = compare_table_descriptions(t);
710                 if (ret < 0)
711                         goto err;
712         }
713         ret = -E_OSL_BUSY;
714         if (!(flags & MAP_TBL_FL_IGNORE_DIRTY)) {
715                 if (table_is_dirty(t)) {
716                         ERROR_LOG("%s is dirty\n", t->desc->name);
717                         goto err;
718                 }
719         }
720         mark_table_dirty(t);
721         num_rows = table_num_rows(t);
722         if (!num_rows)
723                 return num_rows;
724         /* map data files */
725         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
726                 ret = map_column(t, i);
727                 if (ret < 0)
728                         goto err;
729         }
730         return num_rows;
731 err:    /* unmap what is already mapped */
732         for (i--; i >= 0; i--) {
733                 struct osl_object map = t->columns[i].data_map;
734                 osl_munmap(map.data, map.size);
735                 map.data = NULL;
736         }
737         osl_munmap(t->index_map.data, t->index_map.size);
738         t->index_map.data = NULL;
739         return ret;
740 }
741
742 /**
743  * Retrieve a mapped object by row and column number.
744  *
745  * \param t Pointer to an open osl table.
746  * \param col_num Number of the mapped column containing the object to retrieve.
747  * \param row_num Number of the row containing the object to retrieve.
748  * \param obj The result is returned here.
749  *
750  * It is considered an error if \a col_num does not refer to a column
751  * of storage type \p OSL_MAPPED_STORAGE.
752  *
753  * \return Standard.
754  *
755  * \sa osl_storage_type.
756  */
757 int get_mapped_object(const struct osl_table *t, unsigned col_num,
758         uint32_t row_num, struct osl_object *obj)
759 {
760         struct osl_column *col = &t->columns[col_num];
761         uint32_t offset;
762         char *cell_index;
763         int ret;
764
765         if (t->num_rows <= row_num)
766                 return -E_OSL_BAD_ROW_NUM;
767         ret = get_cell_index(t, row_num, col_num, &cell_index);
768         if (ret < 0)
769                 return ret;
770         offset = read_u32(cell_index);
771         obj->size = read_u32(cell_index + 4);
772         obj->data = col->data_map.data + offset;
773         return 1;
774 }
775
776 /*
777  * It's OK to call this with result = rb_node = NULL.  If result is not NULL,
778  * and rb key was not found, result points to the parent node.
779  */
780 static int search_rbtree(const struct osl_object *obj,
781                 const struct osl_table *t, unsigned col_num,
782                 struct rb_node **result, struct rb_node ***rb_link)
783 {
784         struct osl_column *col = &t->columns[col_num];
785         struct rb_node **new = &col->rbtree.rb_node, *parent = NULL;
786         const struct osl_column_description *cd =
787                 get_column_description(t->desc, col_num);
788         enum osl_storage_type st = cd->storage_type;
789         while (*new) {
790                 struct osl_row *this_row = get_row_pointer(*new,
791                         col->rbtree_num);
792                 int ret;
793                 struct osl_object this_obj;
794                 parent = *new;
795                 if (st == OSL_MAPPED_STORAGE) {
796                         ret = get_mapped_object(t, col_num, this_row->num,
797                                 &this_obj);
798                         if (ret < 0)
799                                 return ret;
800                 } else
801                         this_obj = this_row->volatile_objects[col->volatile_num];
802                 ret = cd->compare_function(obj, &this_obj);
803                 if (!ret) {
804                         if (result)
805                                 *result = get_rb_node_pointer(this_row,
806                                         col->rbtree_num);
807                         return 1;
808                 }
809                 if (ret < 0)
810                         new = &((*new)->rb_left);
811                 else
812                         new = &((*new)->rb_right);
813         }
814         if (result)
815                 *result = parent;
816         if (rb_link)
817                 *rb_link = new;
818         return -E_OSL_RB_KEY_NOT_FOUND;
819 }
820
821 static int insert_rbtree(struct osl_table *t, unsigned col_num,
822         const struct osl_row *row, const struct osl_object *obj)
823 {
824         struct rb_node *parent, **rb_link;
825         unsigned rbtree_num;
826         struct rb_node *n;
827         int ret = search_rbtree(obj, t, col_num, &parent, &rb_link);
828
829         if (ret > 0)
830                 return -E_OSL_RB_KEY_EXISTS;
831         rbtree_num = t->columns[col_num].rbtree_num;
832         n = get_rb_node_pointer(row, rbtree_num);
833         rb_link_node(n, parent, rb_link);
834         rb_insert_color(n, &t->columns[col_num].rbtree);
835         return 1;
836 }
837
838 static void remove_rb_node(struct osl_table *t, unsigned col_num,
839                 const struct osl_row *row)
840 {
841         struct osl_column *col = &t->columns[col_num];
842         const struct osl_column_description *cd =
843                 get_column_description(t->desc, col_num);
844         enum osl_storage_flags sf = cd->storage_flags;
845         struct rb_node *victim, *splice_out_node, *tmp;
846         if (!(sf & OSL_RBTREE))
847                 return;
848         /*
849          * Which node is removed/spliced out actually depends on how many
850          * children the victim node has: If it has no children, it gets
851          * deleted. If it has one child, it gets spliced out. If it has two
852          * children, its successor (which has at most a right child) gets
853          * spliced out.
854          */
855         victim = get_rb_node_pointer(row, col->rbtree_num);
856         if (victim->rb_left && victim->rb_right)
857                 splice_out_node = rb_next(victim);
858         else
859                 splice_out_node = victim;
860         /* Go up to the root and decrement the size of each node in the path. */
861         for (tmp = splice_out_node; tmp; tmp = rb_parent(tmp))
862                 tmp->size--;
863         rb_erase(victim, &col->rbtree);
864 }
865
866 static int add_row_to_rbtrees(struct osl_table *t, uint32_t row_num,
867                 struct osl_object *volatile_objs, struct osl_row **row_ptr)
868 {
869         unsigned i;
870         int ret;
871         struct osl_row *row = allocate_row(t->num_rbtrees);
872         const struct osl_column_description *cd;
873
874         if (!row)
875                 return -E_OSL_NOMEM;
876         row->num = row_num;
877         row->volatile_objects = volatile_objs;
878         FOR_EACH_RBTREE_COLUMN(i, t, cd) {
879                 if (cd->storage_type == OSL_MAPPED_STORAGE) {
880                         struct osl_object obj;
881                         ret = get_mapped_object(t, i, row_num, &obj);
882                         if (ret < 0)
883                                 goto err;
884                         ret = insert_rbtree(t, i, row, &obj);
885                 } else { /* volatile */
886                         const struct osl_object *obj
887                                 = volatile_objs + t->columns[i].volatile_num;
888                         ret = insert_rbtree(t, i, row, obj);
889                 }
890                 if (ret < 0)
891                         goto err;
892         }
893         if (row_ptr)
894                 *row_ptr = row;
895         return 1;
896 err: /* rollback changes, i.e. remove added entries from rbtrees */
897         while (i)
898                 remove_rb_node(t, i--, row);
899         free(row);
900         return ret;
901 }
902
903 static void free_volatile_objects(const struct osl_table *t,
904                 enum osl_close_flags flags)
905 {
906         int i, j;
907         struct rb_node *n;
908         struct osl_column *rb_col;
909         const struct osl_column_description *cd;
910
911         if (!t->num_volatile_columns)
912                 return;
913         /* find the first rbtree column (any will do) */
914         FOR_EACH_RBTREE_COLUMN(i, t, cd)
915                 break;
916         rb_col = t->columns + i;
917         /* walk that rbtree and free all volatile objects */
918         for (n = rb_first(&rb_col->rbtree); n; n = rb_next(n)) {
919                 struct osl_row *r = get_row_pointer(n, rb_col->rbtree_num);
920                 if (flags & OSL_FREE_VOLATILE)
921                         FOR_EACH_VOLATILE_COLUMN(j, t, cd) {
922                                 if (cd->storage_flags & OSL_DONT_FREE)
923                                         continue;
924                                 free(r->volatile_objects[
925                                         t->columns[j].volatile_num].data);
926                         }
927 //                      for (j = 0; j < t->num_volatile_columns; j++)
928 //                              free(r->volatile_objects[j].data);
929                 free(r->volatile_objects);
930         }
931 }
932
933 /**
934  * Erase all rbtree nodes and free resources.
935  *
936  * \param t Pointer to an open osl table.
937  *
938  * This function is called by osl_close_table().
939  */
940 void clear_rbtrees(struct osl_table *t)
941 {
942         const struct osl_column_description *cd;
943         unsigned i, rbtrees_cleared = 0;
944
945         FOR_EACH_RBTREE_COLUMN(i, t, cd) {
946                 struct osl_column *col = &t->columns[i];
947                 struct rb_node *n;
948                 rbtrees_cleared++;
949                 for (n = rb_first(&col->rbtree); n;) {
950                         struct osl_row *r;
951                         rb_erase(n, &col->rbtree);
952                         if (rbtrees_cleared == t->num_rbtrees) {
953                                 r = get_row_pointer(n, col->rbtree_num);
954                                 n = rb_next(n);
955                                 free(r);
956                         } else
957                                 n = rb_next(n);
958                 }
959         }
960
961 }
962
963 __export int osl_close_table(struct osl_table *t, enum osl_close_flags flags)
964 {
965         int ret;
966
967         if (!t)
968                 return -E_OSL_BAD_TABLE;
969         NOTICE_LOG("closing table %s\n", t->desc->name);
970         free_volatile_objects(t, flags);
971         clear_rbtrees(t);
972         ret = unmap_table(t, flags);
973         if (ret < 0)
974                 ERROR_LOG("unmap_table failed: %d\n", ret);
975         free(t->columns);
976         free(t);
977         return ret;
978 }
979
980 /**
981  * Find out whether the given row number corresponds to an invalid row.
982  *
983  * \param t Pointer to the osl table.
984  * \param row_num The number of the row in question.
985  *
986  * By definition, a row is considered invalid if all its index entries
987  * are invalid.
988  *
989  * \return Positive if \a row_num corresponds to an invalid row,
990  * zero if it corresponds to a valid row, negative on errors.
991  */
992 int row_is_invalid(struct osl_table *t, uint32_t row_num)
993 {
994         char *row_index;
995         int i, ret = get_row_index(t, row_num, &row_index);
996
997         if (ret < 0)
998                 return ret;
999         for (i = 0; i < t->row_index_size; i++) {
1000                 if ((unsigned char)row_index[i] != 0xff)
1001                         return 0;
1002         }
1003         INFO_LOG("row %d is invalid\n", row_num);
1004         return 1;
1005 }
1006
1007 /**
1008  * Invalidate a row of an osl table.
1009  *
1010  * \param t Pointer to an open osl table.
1011  * \param row_num Number of the row to mark as invalid.
1012  *
1013  * This function marks each mapped object in the index entry of \a row as
1014  * invalid.
1015  *
1016  * \return Standard.
1017  */
1018 int mark_row_invalid(struct osl_table *t, uint32_t row_num)
1019 {
1020         char *row_index;
1021         int ret = get_row_index(t, row_num, &row_index);
1022
1023         if (ret < 0)
1024                 return ret;
1025         INFO_LOG("marking row %d as invalid\n", row_num);
1026         memset(row_index, 0xff, t->row_index_size);
1027         return 1;
1028 }
1029
1030 /**
1031  * Initialize all rbtrees and compute number of invalid rows.
1032  *
1033  * \param t The table containing the rbtrees to be initialized.
1034  *
1035  * \return Standard.
1036  */
1037 int init_rbtrees(struct osl_table *t)
1038 {
1039         int i, ret;
1040         const struct osl_column_description *cd;
1041
1042         /* create rbtrees */
1043         FOR_EACH_RBTREE_COLUMN(i, t, cd)
1044                 t->columns[i].rbtree = RB_ROOT;
1045         /* add valid rows to rbtrees */
1046         t->num_invalid_rows = 0;
1047         for (i = 0; i < t->num_rows; i++) {
1048                 struct osl_object *volatile_objs;
1049                 ret = row_is_invalid(t, i);
1050                 if (ret < 0)
1051                         return ret;
1052                 if (ret) {
1053                         t->num_invalid_rows++;
1054                         continue;
1055                 }
1056                 if (t->num_volatile_columns > 0) {
1057                         volatile_objs = calloc(t->num_volatile_columns,
1058                                 sizeof(struct osl_object));
1059                         if (!volatile_objs)
1060                                 return -E_OSL_NOMEM;
1061                 } else
1062                         volatile_objs = NULL;
1063                 ret = add_row_to_rbtrees(t, i, volatile_objs, NULL);
1064                 if (ret < 0)
1065                         return ret;
1066         }
1067         return 1;
1068 }
1069
1070 __export int osl_open_table(const struct osl_table_description *table_desc,
1071                 struct osl_table **result)
1072 {
1073         int i, ret;
1074         struct osl_table *t;
1075         const struct osl_column_description *cd;
1076
1077         NOTICE_LOG("opening table %s\n", table_desc->name);
1078         ret = init_table_structure(table_desc, &t);
1079         if (ret < 0)
1080                 return ret;
1081         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
1082                 struct stat statbuf;
1083                 char *dirname = column_filename(t, i);
1084
1085                 ret = -E_OSL_NOMEM;
1086                 if (!dirname)
1087                         goto err;
1088                 /* check if directory exists */
1089                 ret = osl_stat(dirname, &statbuf);
1090                 free(dirname);
1091                 if (ret < 0)
1092                         goto err;
1093                 ret = -E_OSL_NOTDIR;
1094                 if (!S_ISDIR(statbuf.st_mode))
1095                         goto err;
1096         }
1097         ret = map_table(t, MAP_TBL_FL_VERIFY_INDEX);
1098         if (ret < 0)
1099                 goto err;
1100         t->num_rows = ret;
1101         DEBUG_LOG("num rows: %d\n", t->num_rows);
1102         ret = init_rbtrees(t);
1103         if (ret < 0) {
1104                 osl_close_table(t, OSL_MARK_CLEAN); /* ignore further errors */
1105                 return ret;
1106         }
1107         *result = t;
1108         return 1;
1109 err:
1110         free(t->columns);
1111         free(t);
1112         return ret;
1113 }
1114
1115 static int create_disk_storage_object_dir(const struct osl_table *t,
1116                 unsigned col_num, const char *ds_name)
1117 {
1118         char *dirname;
1119         int ret;
1120
1121         if (!(t->desc->flags & OSL_LARGE_TABLE))
1122                 return 1;
1123         dirname = disk_storage_dirname(t, col_num, ds_name);
1124         if (!dirname)
1125                 return -E_OSL_NOMEM;
1126         ret = osl_mkdir(dirname, 0777);
1127         free(dirname);
1128         if (ret < 0 && ret != -E_OSL_DIR_EXISTS)
1129                 return ret;
1130         return 1;
1131 }
1132
1133 static int write_disk_storage_file(const struct osl_table *t, unsigned col_num,
1134         const struct osl_object *obj, const char *ds_name)
1135 {
1136         int ret;
1137         char *filename;
1138
1139         ret = create_disk_storage_object_dir(t, col_num, ds_name);
1140         if (ret < 0)
1141                 return ret;
1142         filename = disk_storage_path(t, col_num, ds_name);
1143         if (!filename)
1144                 return -E_OSL_NOMEM;
1145         ret = write_file(filename, obj->data, obj->size);
1146         free(filename);
1147         return ret;
1148 }
1149
1150 static int append_map_file(const struct osl_table *t, unsigned col_num,
1151         const struct osl_object *obj, uint32_t *new_size)
1152 {
1153         char *filename = column_filename(t, col_num);
1154         int ret;
1155
1156         if (!filename)
1157                 return -E_OSL_NOMEM;
1158         ret = append_file(filename, obj->data, obj->size, new_size);
1159         free(filename);
1160         return ret;
1161 }
1162
1163 static int append_row_index(const struct osl_table *t, char *row_index)
1164 {
1165         char *filename;
1166         int ret;
1167
1168         if (!t->num_mapped_columns)
1169                 return 1;
1170         filename = index_filename(t->desc);
1171         if (!filename)
1172                 return -E_OSL_NOMEM;
1173         ret = append_file(filename, row_index, t->row_index_size, NULL);
1174         free(filename);
1175         return ret;
1176 }
1177
1178 static int truncate_mapped_file(const struct osl_table *t, unsigned col_num,
1179                 off_t size)
1180 {
1181         int ret;
1182         char *filename = column_filename(t, col_num);
1183
1184         if (!filename)
1185                 return -E_OSL_NOMEM;
1186         ret = truncate_file(filename, size);
1187         free(filename);
1188         return ret;
1189 }
1190
1191 static int delete_disk_storage_file(const struct osl_table *t, unsigned col_num,
1192                 const char *ds_name)
1193 {
1194         char *dirname, *filename = disk_storage_path(t, col_num, ds_name);
1195         int ret = 1;
1196
1197         if (!filename)
1198                 return -E_OSL_NOMEM;
1199         if (unlink(filename) < 0)
1200                 ret = errno == ENOENT? -E_OSL_NOENT : -E_OSL_UNLINK;
1201         free(filename);
1202         if (ret < 0)
1203                 return ret;
1204         if (!(t->desc->flags & OSL_LARGE_TABLE))
1205                 return 1;
1206         dirname = disk_storage_dirname(t, col_num, ds_name);
1207         if (!dirname)
1208                 return -E_OSL_NOMEM;
1209         rmdir(dirname);
1210         free(dirname);
1211         return 1;
1212 }
1213
1214 __export int osl_add_and_get_row(struct osl_table *t, struct osl_object *objects,
1215                 struct osl_row **row)
1216 {
1217         int i, ret;
1218         char *ds_name = NULL;
1219         struct rb_node **rb_parents = NULL, ***rb_links = NULL;
1220         char *new_row_index = NULL;
1221         struct osl_object *volatile_objs = NULL;
1222         const struct osl_column_description *cd;
1223
1224         if (!t)
1225                 return -E_OSL_BAD_TABLE;
1226         rb_parents = malloc(t->num_rbtrees * sizeof(struct rn_node*));
1227         if (!rb_parents)
1228                 return -E_OSL_NOMEM;
1229         rb_links = malloc(t->num_rbtrees * sizeof(struct rn_node**));
1230         if (!rb_links) {
1231                 free(rb_parents);
1232                 return -E_OSL_NOMEM;
1233         }
1234         if (t->num_mapped_columns) {
1235                 new_row_index = malloc(t->row_index_size);
1236                 if (!new_row_index) {
1237                         free(rb_links);
1238                         free(rb_parents);
1239                         return -E_OSL_NOMEM;
1240                 }
1241         }
1242         /* pass 1: sanity checks */
1243 //      DEBUG_LOG("sanity tests: %p:%p\n", objects[0].data,
1244 //              objects[1].data);
1245         FOR_EACH_COLUMN(i, t->desc, cd) {
1246                 enum osl_storage_type st = cd->storage_type;
1247                 enum osl_storage_flags sf = cd->storage_flags;
1248
1249 //              ret = -E_OSL_NULL_OBJECT;
1250 //              if (!objects[i])
1251 //                      goto out;
1252                 if (st == OSL_DISK_STORAGE)
1253                         continue;
1254                 if (sf & OSL_RBTREE) {
1255                         unsigned rbtree_num = t->columns[i].rbtree_num;
1256                         ret = -E_OSL_RB_KEY_EXISTS;
1257 //                      DEBUG_LOG("checking whether %p exists\n",
1258 //                              objects[i].data);
1259                         if (search_rbtree(objects + i, t, i,
1260                                         &rb_parents[rbtree_num],
1261                                         &rb_links[rbtree_num]) > 0)
1262                                 goto out;
1263                 }
1264                 if (sf & OSL_FIXED_SIZE) {
1265 //                      DEBUG_LOG("fixed size. need: %zu, have: %d\n",
1266 //                              objects[i].size, cd->data_size);
1267                         ret = -E_OSL_BAD_DATA_SIZE;
1268                         if (objects[i].size != cd->data_size)
1269                                 goto out;
1270                 }
1271         }
1272         if (t->num_disk_storage_columns) {
1273                 ds_name = disk_storage_name_of_object(t,
1274                         &objects[t->disk_storage_name_column]);
1275                 ret = -E_OSL_NOMEM;
1276                 if (!ds_name)
1277                         goto out;
1278         }
1279         ret = unmap_table(t, OSL_MARK_CLEAN);
1280         if (ret < 0)
1281                 goto out;
1282 //      DEBUG_LOG("sanity tests passed%s\n", "");
1283         /* pass 2: create data files, append map data */
1284         FOR_EACH_COLUMN(i, t->desc, cd) {
1285                 enum osl_storage_type st = cd->storage_type;
1286                 if (st == OSL_NO_STORAGE)
1287                         continue;
1288                 if (st == OSL_MAPPED_STORAGE) {
1289                         uint32_t new_size;
1290                         struct osl_column *col = &t->columns[i];
1291 //                      DEBUG_LOG("appending object of size %zu\n",
1292 //                              objects[i].size);
1293                         ret = append_map_file(t, i, objects + i, &new_size);
1294                         if (ret < 0)
1295                                 goto rollback;
1296                         update_cell_index(new_row_index, col, new_size,
1297                                 objects[i].size);
1298                         continue;
1299                 }
1300                 /* DISK_STORAGE */
1301                 ret = write_disk_storage_file(t, i, objects + i, ds_name);
1302                 if (ret < 0)
1303                         goto rollback;
1304         }
1305         ret = append_row_index(t, new_row_index);
1306         if (ret < 0)
1307                 goto rollback;
1308         ret = map_table(t, MAP_TBL_FL_VERIFY_INDEX);
1309         if (ret < 0) { /* truncate index and rollback changes */
1310                 char *filename = index_filename(t->desc);
1311                 if (filename)
1312                         truncate_file(filename, t->row_index_size);
1313                 free(filename);
1314                 goto rollback;
1315         }
1316         /* pass 3: add entry to rbtrees */
1317         if (t->num_volatile_columns) {
1318                 ret = -E_OSL_NOMEM;
1319                 volatile_objs = calloc(t->num_volatile_columns,
1320                         sizeof(struct osl_object));
1321                 if (!volatile_objs)
1322                         goto out;
1323                 FOR_EACH_VOLATILE_COLUMN(i, t, cd)
1324                         volatile_objs[t->columns[i].volatile_num] = objects[i];
1325         }
1326         t->num_rows++;
1327 //      DEBUG_LOG("adding new entry as row #%d\n", t->num_rows - 1);
1328         ret = add_row_to_rbtrees(t, t->num_rows - 1, volatile_objs, row);
1329         if (ret < 0)
1330                 goto out;
1331 //      DEBUG_LOG("added new entry as row #%d\n", t->num_rows - 1);
1332         ret = 1;
1333         goto out;
1334 rollback: /* rollback all changes made, ignore further errors */
1335         for (i--; i >= 0; i--) {
1336                 cd = get_column_description(t->desc, i);
1337                 enum osl_storage_type st = cd->storage_type;
1338                 if (st == OSL_NO_STORAGE)
1339                         continue;
1340
1341                 if (st == OSL_MAPPED_STORAGE)
1342                         truncate_mapped_file(t, i, objects[i].size);
1343                 else /* disk storage */
1344                         delete_disk_storage_file(t, i, ds_name);
1345         }
1346         /* ignore error and return previous error value */
1347         map_table(t, MAP_TBL_FL_VERIFY_INDEX);
1348 out:
1349         free(new_row_index);
1350         free(ds_name);
1351         free(rb_parents);
1352         free(rb_links);
1353         return ret;
1354 }
1355
1356 __export int osl_add_row(struct osl_table *t, struct osl_object *objects)
1357 {
1358         return osl_add_and_get_row(t, objects, NULL);
1359 }
1360
1361 __export int osl_get_object(const struct osl_table *t, const struct osl_row *r,
1362         unsigned col_num, struct osl_object *object)
1363 {
1364         const struct osl_column_description *cd;
1365
1366         if (!t)
1367                 return -E_OSL_BAD_TABLE;
1368         cd = get_column_description(t->desc, col_num);
1369         /* col must not be disk storage */
1370         if (cd->storage_type == OSL_DISK_STORAGE)
1371                 return -E_OSL_BAD_STORAGE_TYPE;
1372         if (cd->storage_type == OSL_MAPPED_STORAGE)
1373                 return get_mapped_object(t, col_num, r->num, object);
1374         /* volatile */
1375         *object = r->volatile_objects[t->columns[col_num].volatile_num];
1376         return 1;
1377 }
1378
1379 __export int osl_del_row(struct osl_table *t, struct osl_row *row)
1380 {
1381         struct osl_row *r = row;
1382         int i, ret;
1383         const struct osl_column_description *cd;
1384
1385         if (!t)
1386                 return -E_OSL_BAD_TABLE;
1387         INFO_LOG("deleting row %p\n", row);
1388
1389         if (t->num_disk_storage_columns) {
1390                 char *ds_name;
1391                 ret = disk_storage_name_of_row(t, r, &ds_name);
1392                 if (ret < 0)
1393                         goto out;
1394                 FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd)
1395                         delete_disk_storage_file(t, i, ds_name);
1396                 free(ds_name);
1397         }
1398         FOR_EACH_COLUMN(i, t->desc, cd) {
1399                 struct osl_column *col = t->columns + i;
1400                 enum osl_storage_type st = cd->storage_type;
1401                 remove_rb_node(t, i, r);
1402                 if (st == OSL_MAPPED_STORAGE)
1403                         continue;
1404                 if (st == OSL_NO_STORAGE && !(cd->storage_flags & OSL_DONT_FREE))
1405                         free(r->volatile_objects[col->volatile_num].data);
1406         }
1407         if (t->num_mapped_columns) {
1408                 ret = mark_row_invalid(t, r->num);
1409                 if (ret < 0)
1410                         goto out;
1411                 t->num_invalid_rows++;
1412         } else
1413                 t->num_rows--;
1414         ret = 1;
1415 out:
1416         free(r->volatile_objects);
1417         free(r);
1418         return ret;
1419 }
1420
1421 /* test if column has an rbtree */
1422 static int check_rbtree_col(const struct osl_table *t, unsigned col_num,
1423                 struct osl_column **col)
1424 {
1425         if (!t)
1426                 return -E_OSL_BAD_TABLE;
1427         if (!(get_column_description(t->desc, col_num)->storage_flags & OSL_RBTREE))
1428                 return -E_OSL_BAD_STORAGE_FLAGS;
1429         *col = t->columns + col_num;
1430         return 1;
1431 }
1432
1433 __export int osl_get_row(const struct osl_table *t, unsigned col_num,
1434                 const struct osl_object *obj, struct osl_row **result)
1435 {
1436         int ret;
1437         struct rb_node *node;
1438         struct osl_row *row;
1439         struct osl_column *col;
1440
1441         *result = NULL;
1442         ret = check_rbtree_col(t, col_num, &col);
1443         if (ret < 0)
1444                 return ret;
1445         ret = search_rbtree(obj, t, col_num, &node, NULL);
1446         if (ret < 0)
1447                 return ret;
1448         row = get_row_pointer(node, t->columns[col_num].rbtree_num);
1449         *result = row;
1450         return 1;
1451 }
1452
1453 static int rbtree_loop(struct osl_column *col, void *private_data,
1454                 osl_rbtree_loop_func *func)
1455 {
1456         struct rb_node *n, *tmp;
1457
1458         /* this for-loop is safe against removal of an entry */
1459         for (n = rb_first(&col->rbtree), tmp = n? rb_next(n) : NULL;
1460                         n;
1461                         n = tmp, tmp = tmp? rb_next(tmp) : NULL) {
1462                 struct osl_row *r = get_row_pointer(n, col->rbtree_num);
1463                 if (func(r, private_data) < 0)
1464                         return -E_OSL_LOOP;
1465         }
1466         return 1;
1467 }
1468
1469 static int rbtree_loop_reverse(struct osl_column *col, void *private_data,
1470                 osl_rbtree_loop_func *func)
1471 {
1472         struct rb_node *n, *tmp;
1473
1474         /* safe against removal of an entry */
1475         for (n = rb_last(&col->rbtree), tmp = n? rb_prev(n) : NULL;
1476                         n;
1477                         n = tmp, tmp = tmp? rb_prev(tmp) : NULL) {
1478                 struct osl_row *r = get_row_pointer(n, col->rbtree_num);
1479                 if (func(r, private_data) < 0)
1480                         return -E_OSL_LOOP;
1481         }
1482         return 1;
1483 }
1484
1485 __export int osl_rbtree_loop(const struct osl_table *t, unsigned col_num,
1486         void *private_data, osl_rbtree_loop_func *func)
1487 {
1488         struct osl_column *col;
1489
1490         int ret = check_rbtree_col(t, col_num, &col);
1491         if (ret < 0)
1492                 return ret;
1493         return rbtree_loop(col, private_data, func);
1494 }
1495
1496 __export int osl_rbtree_loop_reverse(const struct osl_table *t, unsigned col_num,
1497         void *private_data, osl_rbtree_loop_func *func)
1498 {
1499         struct osl_column *col;
1500
1501         int ret = check_rbtree_col(t, col_num, &col);
1502         if (ret < 0)
1503                 return ret;
1504         return rbtree_loop_reverse(col, private_data, func);
1505 }
1506
1507 /* TODO: Rollback changes on errors */
1508 static int rename_disk_storage_objects(struct osl_table *t,
1509                 struct osl_object *old_obj, struct osl_object *new_obj)
1510 {
1511         int i, ret;
1512         const struct osl_column_description *cd;
1513         char *old_ds_name, *new_ds_name;
1514
1515         if (!t->num_disk_storage_columns)
1516                 return 1; /* nothing to do */
1517         if (old_obj->size == new_obj->size && !memcmp(new_obj->data,
1518                         old_obj->data, new_obj->size))
1519                 return 1; /* object did not change */
1520         old_ds_name = disk_storage_name_of_object(t, old_obj);
1521         new_ds_name = disk_storage_name_of_object(t, new_obj);
1522         ret = -E_OSL_NOMEM;
1523         if (!old_ds_name || ! new_ds_name)
1524                 goto out;
1525
1526         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
1527                 char *old_filename, *new_filename;
1528                 ret = create_disk_storage_object_dir(t, i, new_ds_name);
1529                 if (ret < 0)
1530                         goto out;
1531                 old_filename = disk_storage_path(t, i, old_ds_name);
1532                 new_filename = disk_storage_path(t, i, new_ds_name);
1533                 if (!old_filename || !new_filename)
1534                         ret = -E_OSL_NOMEM;
1535                 else
1536                         ret = osl_rename(old_filename, new_filename);
1537                 free(old_filename);
1538                 free(new_filename);
1539                 if (ret < 0)
1540                         goto out;
1541         }
1542         ret = 1;
1543 out:
1544         free(old_ds_name);
1545         free(new_ds_name);
1546         return ret;
1547
1548 }
1549
1550 __export int osl_update_object(struct osl_table *t, const struct osl_row *r,
1551                 unsigned col_num, struct osl_object *obj)
1552 {
1553         struct osl_column *col;
1554         const struct osl_column_description *cd;
1555         int ret;
1556
1557         if (!t)
1558                 return -E_OSL_BAD_TABLE;
1559         col = &t->columns[col_num];
1560         cd = get_column_description(t->desc, col_num);
1561         DEBUG_LOG("updating column %u of %s\n", col_num, t->desc->name);
1562         if (cd->storage_flags & OSL_RBTREE) {
1563                 if (search_rbtree(obj, t, col_num, NULL, NULL) > 0)
1564                         return -E_OSL_RB_KEY_EXISTS;
1565         }
1566         if (cd->storage_flags & OSL_FIXED_SIZE) {
1567                 if (obj->size != cd->data_size)
1568                         return -E_OSL_BAD_DATA_SIZE;
1569         }
1570         remove_rb_node(t, col_num, r);
1571         if (cd->storage_type == OSL_NO_STORAGE) { /* TODO: If fixed size, reuse object? */
1572                 if (!(cd->storage_flags & OSL_DONT_FREE))
1573                         free(r->volatile_objects[col->volatile_num].data);
1574                 r->volatile_objects[col->volatile_num] = *obj;
1575         } else if (cd->storage_type == OSL_DISK_STORAGE) {
1576                 char *ds_name;
1577                 ret = disk_storage_name_of_row(t, r, &ds_name);
1578                 if (ret < 0)
1579                         return ret;
1580                 ret = delete_disk_storage_file(t, col_num, ds_name);
1581                 if (ret < 0 && ret != -E_OSL_NOENT) {
1582                         free(ds_name);
1583                         return ret;
1584                 }
1585                 ret = write_disk_storage_file(t, col_num, obj, ds_name);
1586                 free(ds_name);
1587                 if (ret < 0)
1588                         return ret;
1589         } else { /* mapped storage */
1590                 struct osl_object old_obj;
1591                 ret = get_mapped_object(t, col_num, r->num, &old_obj);
1592                 if (ret < 0)
1593                         return ret;
1594                 /*
1595                  * If the updated column is the disk storage name column, the
1596                  * disk storage name changes, so we have to rename all disk
1597                  * storage objects accordingly.
1598                  */
1599                 if (col_num == t->disk_storage_name_column) {
1600                         ret = rename_disk_storage_objects(t, &old_obj, obj);
1601                         if (ret < 0)
1602                                 return ret;
1603                 }
1604                 if (cd->storage_flags & OSL_FIXED_SIZE)
1605                         memcpy(old_obj.data, obj->data, cd->data_size);
1606                 else { /* TODO: if the size doesn't change, use old space */
1607                         uint32_t new_data_map_size;
1608                         char *row_index;
1609                         ret = get_row_index(t, r->num, &row_index);
1610                         if (ret < 0)
1611                                 return ret;
1612                         unmap_column(t, col_num);
1613                         ret = append_map_file(t, col_num, obj,
1614                                 &new_data_map_size);
1615                         if (ret < 0)
1616                                 return ret;
1617                         ret = map_column(t, col_num);
1618                         if (ret < 0)
1619                                 return ret;
1620                         update_cell_index(row_index, col, new_data_map_size,
1621                                 obj->size);
1622                 }
1623         }
1624         if (cd->storage_flags & OSL_RBTREE) {
1625                 ret = insert_rbtree(t, col_num, r, obj);
1626                 if (ret < 0)
1627                         return ret;
1628         }
1629         return 1;
1630 }
1631
1632 __export int osl_open_disk_object(const struct osl_table *t, const struct osl_row *r,
1633                 unsigned col_num, struct osl_object *obj)
1634 {
1635         const struct osl_column_description *cd;
1636         char *ds_name, *filename;
1637         int ret;
1638
1639         if (!t)
1640                 return -E_OSL_BAD_TABLE;
1641         cd = get_column_description(t->desc, col_num);
1642         if (cd->storage_type != OSL_DISK_STORAGE)
1643                 return -E_OSL_BAD_STORAGE_TYPE;
1644
1645         ret = disk_storage_name_of_row(t, r, &ds_name);
1646         if (ret < 0)
1647                 return ret;
1648         filename = disk_storage_path(t, col_num, ds_name);
1649         free(ds_name);
1650         if (!filename)
1651                 return -E_OSL_NOMEM;
1652         DEBUG_LOG("filename: %s\n", filename);
1653         ret = mmap_full_file(filename, O_RDONLY, &obj->data, &obj->size, NULL);
1654         free(filename);
1655         return ret;
1656 }
1657
1658 __export int osl_close_disk_object(struct osl_object *obj)
1659 {
1660         return osl_munmap(obj->data, obj->size);
1661 }
1662
1663 __export int osl_get_num_rows(const struct osl_table *t, unsigned *num_rows)
1664 {
1665         if (!t)
1666                 return -E_OSL_BAD_TABLE;
1667         assert(t->num_rows >= t->num_invalid_rows);
1668         *num_rows = t->num_rows - t->num_invalid_rows;
1669         return 1;
1670 }
1671
1672 __export int osl_get_rank(const struct osl_table *t, struct osl_row *r,
1673                 unsigned col_num, unsigned *rank)
1674 {
1675         struct osl_object obj;
1676         struct osl_column *col;
1677         struct rb_node *node;
1678         int ret = check_rbtree_col(t, col_num, &col);
1679
1680         if (ret < 0)
1681                 return ret;
1682         ret = osl_get_object(t, r, col_num, &obj);
1683         if (ret < 0)
1684                 return ret;
1685         ret = search_rbtree(&obj, t, col_num, &node, NULL);
1686         if (ret < 0)
1687                 return ret;
1688         ret = rb_rank(node, rank);
1689         if (ret < 0)
1690                 return -E_OSL_BAD_ROW;
1691         return 1;
1692 }
1693
1694 __export int osl_get_nth_row(const struct osl_table *t, unsigned col_num,
1695                 unsigned n, struct osl_row **result)
1696 {
1697         struct osl_column *col;
1698         struct rb_node *node;
1699         unsigned num_rows;
1700         int ret;
1701
1702         *result = NULL;
1703         if (n == 0)
1704                 return -E_OSL_RB_KEY_NOT_FOUND;
1705         ret = osl_get_num_rows(t, &num_rows);
1706         if (ret < 0)
1707                 return ret;
1708         if (n > num_rows)
1709                 return -E_OSL_RB_KEY_NOT_FOUND;
1710         ret = check_rbtree_col(t, col_num, &col);
1711         if (ret < 0)
1712                 return ret;
1713         node = rb_nth(col->rbtree.rb_node, n);
1714         if (!node)
1715                 return -E_OSL_RB_KEY_NOT_FOUND;
1716         *result = get_row_pointer(node, col->rbtree_num);
1717         return 1;
1718 }
1719
1720 __export int osl_rbtree_first_row(const struct osl_table *t, unsigned col_num,
1721                 struct osl_row **result)
1722 {
1723         return osl_get_nth_row(t, col_num, 1, result);
1724 }
1725
1726 __export int osl_rbtree_last_row(const struct osl_table *t, unsigned col_num,
1727                 struct osl_row **result)
1728 {
1729         unsigned num_rows;
1730         int ret = osl_get_num_rows(t, &num_rows);
1731
1732         if (ret < 0)
1733                 return ret;
1734         return osl_get_nth_row(t, col_num, num_rows, result);
1735 }