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