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