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