b9424e30c2790947f58923b7b099fbb956029982
[osl.git] / osl.c
1 /*
2  * Copyright (C) 2007-2008 Andre Noll <maan@systemlinux.org>
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 "error.h"
14 #include "fd.h"
15 #include "osl_core.h"
16
17 /* Taken from Drepper: How to write shared libraries, Appendix B. */
18 #include <stddef.h>
19 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
20 #define MSGSTRFIELD1(line) str##line
21 static const union msgstr_t {
22         struct {
23 #define _S(n, s) char MSGSTRFIELD(__LINE__)[sizeof(s)];
24 #include "errtab.h"
25 #undef _S
26         };
27         char str[0];
28 } msgstr = { {
29 #define _S(n, s) s,
30 #include "errtab.h"
31 #undef _S
32 } };
33 static const unsigned int errmsgidx[] = {
34 #define _S(n, s) [n] = offsetof(union msgstr_t, MSGSTRFIELD(__LINE__)),
35 #include "errtab.h"
36 #undef _S
37 };
38
39 __export const char *osl_strerror(int num)
40 {
41         if (IS_SYSTEM_ERROR(num))
42                 return strerror((num) & ((1 << SYSTEM_ERROR_BIT) - 1));
43         return msgstr.str + errmsgidx[num];
44 }
45
46 int loglevel = 0;
47
48 static void __attribute ((constructor)) init_loglevel(void)
49 {
50         char *p = getenv("OSL_LOGLEVEL");
51
52         /* don't log anything if unset */
53         loglevel = p? atoi(p) : EMERG + 1;
54 }
55
56 /**
57  * The log function.
58  *
59  * \param ll Loglevel.
60  * \param fmt Usual format string.
61  *
62  * All XXX_LOG() macros use this function.
63  */
64 __printf_2_3 void __log(int ll, const char* fmt,...)
65 {
66         va_list argp;
67         FILE *outfd;
68         struct tm *tm;
69         time_t t1;
70         char str[255] = "";
71
72         if (ll < loglevel)
73                 return;
74         outfd = stderr;
75         time(&t1);
76         tm = localtime(&t1);
77         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
78         fprintf(outfd, "%s ", str);
79         va_start(argp, fmt);
80         vfprintf(outfd, fmt, argp);
81         va_end(argp);
82 }
83
84 /**
85  * A wrapper for lseek(2).
86  *
87  * \param fd The file descriptor whose offset is to be to repositioned.
88  * \param offset A value-result parameter.
89  * \param whence Usual repositioning directive.
90  *
91  * Reposition the offset of the file descriptor \a fd to the argument \a offset
92  * according to the directive \a whence. Upon successful return, \a offset
93  * contains the resulting offset location as measured in bytes from the
94  * beginning of the file.
95  *
96  * \return Positive on success. Otherwise, the function returns \p -E_OSL_LSEEK.
97  *
98  * \sa lseek(2).
99  */
100 static int __lseek(int fd, off_t *offset, int whence)
101 {
102         *offset = lseek(fd, *offset, whence);
103         int ret = -E_OSL_LSEEK;
104         if (*offset == -1)
105                 return ret;
106         return 1;
107 }
108
109 static int append_file(const char *filename, char *header, size_t header_size,
110         char *data, size_t data_size, uint32_t *new_pos)
111 {
112         int ret, fd;
113
114 //      DEBUG_LOG("appending %zu  + %zu bytes\n", header_size, data_size);
115         ret = osl_open(filename, O_WRONLY | O_CREAT | O_APPEND, 0644);
116         if (ret < 0)
117                 return ret;
118         fd = ret;
119         if (header && header_size) {
120                 ret = write_all(fd, header, &header_size);
121                 if (ret < 0)
122                         goto out;
123         }
124         ret = write_all(fd, data, &data_size);
125         if (ret < 0)
126                 goto out;
127         if (new_pos) {
128                 off_t offset = 0;
129                 ret = __lseek(fd, &offset, SEEK_END);
130                 if (ret < 0)
131                         goto out;
132 //              DEBUG_LOG("new file size: " FMT_OFF_T "\n", offset);
133                 *new_pos = offset;
134         }
135         ret = 1;
136 out:
137         close(fd);
138         return ret;
139 }
140
141 static int verify_name(const char *name)
142 {
143         if (!name)
144                 return -E_OSL_BAD_NAME;
145         if (!*name)
146                 return -E_OSL_BAD_NAME;
147         if (strchr(name, '/'))
148                 return -E_OSL_BAD_NAME;
149         if (!strcmp(name, ".."))
150                 return -E_OSL_BAD_NAME;
151         if (!strcmp(name, "."))
152                 return -E_OSL_BAD_NAME;
153         return 1;
154 }
155
156 int osl_hash_compare(const struct osl_object *obj1, const struct osl_object *obj2)
157 {
158         return hash_compare((HASH_TYPE *)obj1->data, (HASH_TYPE *)obj2->data);
159 }
160
161 static char *disk_storage_dirname(const struct osl_table *t, unsigned col_num,
162                 const char *ds_name)
163 {
164         char *dirname, *column_name = column_filename(t, col_num);
165
166         if (!column_name)
167                 return NULL;
168         if (!(t->desc->flags & OSL_LARGE_TABLE))
169                 return column_name;
170         dirname = make_message("%s/%.2s", column_name, ds_name);
171         free(column_name);
172         return dirname;
173 }
174
175 static char *disk_storage_name_of_object(const struct osl_table *t,
176         const struct osl_object *obj)
177 {
178         HASH_TYPE hash[HASH_SIZE];
179         hash_object(obj, hash);
180         return disk_storage_name_of_hash(t, hash);
181 }
182
183 static int disk_storage_name_of_row(const struct osl_table *t,
184                 const struct osl_row *row, char **name)
185 {
186         struct osl_object obj;
187         int ret = osl_get_object(t, row, t->disk_storage_name_column, &obj);
188
189         if (ret < 0)
190                 return ret;
191         *name = disk_storage_name_of_object(t, &obj);
192         if (*name)
193                 return 1;
194         return -ERRNO_TO_ERROR(ENOMEM);
195 }
196
197 static void column_name_hash(const char *col_name, HASH_TYPE *hash)
198 {
199         hash_function(col_name, strlen(col_name), hash);
200 }
201
202 static int init_column_descriptions(struct osl_table *t)
203 {
204         int i, j, ret;
205         const struct osl_column_description *cd;
206
207         ret = -E_OSL_BAD_TABLE_DESC;
208         ret = verify_name(t->desc->name);
209         if (ret < 0)
210                 goto err;
211         ret = -E_OSL_BAD_DB_DIR;
212         if (!t->desc->dir && (t->num_disk_storage_columns || t->num_mapped_columns))
213                 goto err;
214         /* the size of the index header without column descriptions */
215         t->index_header_size = IDX_COLUMN_DESCRIPTIONS;
216         FOR_EACH_COLUMN(i, t->desc, cd) {
217                 struct osl_column *col = t->columns + i;
218                 if (cd->storage_flags & OSL_RBTREE) {
219                         if (!cd->compare_function)
220                                 return -E_OSL_NO_COMPARE_FUNC;
221                 }
222                 if (cd->storage_type == OSL_NO_STORAGE)
223                         continue;
224                 ret = -E_OSL_NO_COLUMN_NAME;
225                 if (!cd->name || !cd->name[0])
226                         goto err;
227                 ret = verify_name(cd->name);
228                 if (ret < 0)
229                         goto err;
230                 t->index_header_size += index_column_description_size(cd->name);
231                 column_name_hash(cd->name, col->name_hash);
232                 ret = -E_OSL_DUPLICATE_COL_NAME;
233                 for (j = i + 1; j < t->desc->num_columns; j++) {
234                         const char *name2 = get_column_description(t->desc,
235                                 j)->name;
236                         if (cd->name && name2 && !strcmp(cd->name, name2))
237                                 goto err;
238                 }
239         }
240         return 1;
241 err:
242         return ret;
243 }
244
245 /**
246  * Initialize a struct table from given table description.
247  *
248  * \param desc The description of the osl table.
249  * \param table_ptr Result is returned here.
250  *
251  * This function performs several sanity checks on \p desc and returns if any
252  * of these tests fail. On success, a struct \p osl_table is allocated and
253  * initialized with data derived from \p desc.
254  *
255  * \return Standard.
256  *
257  * \sa struct osl_table.
258  */
259 int init_table_structure(const struct osl_table_description *desc,
260                 struct osl_table **table_ptr)
261 {
262         const struct osl_column_description *cd;
263         struct osl_table *t = calloc(1, sizeof(*t));
264         int i, ret = -ERRNO_TO_ERROR(ENOMEM), have_disk_storage_name_column = 0;
265
266         if (!t)
267                 return ret;
268         ret = -E_OSL_BAD_TABLE_DESC;
269         if (!desc)
270                 goto err;
271         DEBUG_LOG("creating table structure for '%s' from table "
272                 "description\n", desc->name);
273         ret = -E_OSL_NO_COLUMN_DESC;
274         if (!desc->column_descriptions)
275                 goto err;
276         ret = -E_OSL_NO_COLUMNS;
277         if (!desc->num_columns)
278                 goto err;
279         ret = -ERRNO_TO_ERROR(ENOMEM);
280         t->columns = calloc(desc->num_columns, sizeof(struct osl_column));
281         if (!t->columns)
282                 goto err;
283         t->desc = desc;
284         FOR_EACH_COLUMN(i, t->desc, cd) {
285                 enum osl_storage_type st = cd->storage_type;
286                 enum osl_storage_flags sf = cd->storage_flags;
287                 struct osl_column *col = &t->columns[i];
288
289                 ret = -E_OSL_BAD_STORAGE_TYPE;
290                 if (st != OSL_MAPPED_STORAGE && st != OSL_DISK_STORAGE
291                                 && st != OSL_NO_STORAGE)
292                         goto err;
293                 ret = -E_OSL_BAD_STORAGE_FLAGS;
294                 if (st == OSL_DISK_STORAGE && sf & OSL_RBTREE)
295                         goto err;
296                 ret = -E_OSL_BAD_STORAGE_SIZE;
297                 if (sf & OSL_FIXED_SIZE && !cd->data_size)
298                         goto err;
299                 switch (st) {
300                 case OSL_DISK_STORAGE:
301                         t->num_disk_storage_columns++;
302                         break;
303                 case OSL_MAPPED_STORAGE:
304                         t->num_mapped_columns++;
305                         col->index_offset = t->row_index_size;
306                         t->row_index_size += 8;
307                         break;
308                 case OSL_NO_STORAGE:
309                         col->volatile_num = t->num_volatile_columns;
310                         t->num_volatile_columns++;
311                         break;
312                 }
313                 if (sf & OSL_RBTREE) {
314                         col->rbtree_num = t->num_rbtrees;
315                         t->num_rbtrees++;
316                         if ((sf & OSL_UNIQUE) && (st == OSL_MAPPED_STORAGE)) {
317                                 if (!have_disk_storage_name_column)
318                                         t->disk_storage_name_column = i;
319                                 have_disk_storage_name_column = 1;
320                         }
321                 }
322         }
323         ret = -E_OSL_NO_UNIQUE_RBTREE_COLUMN;
324         if (t->num_disk_storage_columns && !have_disk_storage_name_column)
325                 goto err;
326         ret = -E_OSL_NO_RBTREE_COL;
327         if (!t->num_rbtrees)
328                 goto err;
329         /* success */
330         DEBUG_LOG("OK. Index entry size: %u\n", t->row_index_size);
331         ret = init_column_descriptions(t);
332         if (ret < 0)
333                 goto err;
334         *table_ptr = t;
335         return 1;
336 err:
337         free(t->columns);
338         free(t);
339         return ret;
340 }
341
342 /**
343  * Read the table description from index header.
344  *
345  * \param map The memory mapping of the index file.
346  * \param desc The values found in the index header are returned here.
347  *
348  * Read the index header, check for the paraslash magic string and the table version number.
349  * Read all information stored in the index header into \a desc.
350  *
351  * \return Standard.
352  *
353  * \sa struct osl_table_description, osl_create_table.
354  */
355 int read_table_desc(struct osl_object *map, struct osl_table_description *desc)
356 {
357         char *buf = map->data;
358         uint8_t version;
359         uint16_t header_size;
360         int ret, i;
361         unsigned offset;
362         struct osl_column_description *cd;
363
364         if (map->size < MIN_INDEX_HEADER_SIZE(1))
365                 return -E_OSL_SHORT_TABLE;
366         if (strncmp(buf + IDX_PARA_MAGIC, PARA_MAGIC, strlen(PARA_MAGIC)))
367                 return -E_OSL_NO_MAGIC;
368         version = read_u8(buf + IDX_VERSION);
369         if (version < MIN_TABLE_VERSION || version > MAX_TABLE_VERSION)
370                 return -E_OSL_VERSION_MISMATCH;
371         desc->flags = read_u8(buf + IDX_TABLE_FLAGS);
372         desc->num_columns = read_u16(buf + IDX_NUM_COLUMNS);
373         INFO_LOG("%u columns\n", desc->num_columns);
374         if (!desc->num_columns)
375                 return -E_OSL_NO_COLUMNS;
376         header_size = read_u16(buf + IDX_HEADER_SIZE);
377         if (map->size < header_size)
378                 return -E_OSL_BAD_SIZE;
379         desc->column_descriptions = calloc(desc->num_columns,
380                 sizeof(struct osl_column_description));
381         if (!desc->column_descriptions)
382                 return -ERRNO_TO_ERROR(ENOMEM);
383         offset = IDX_COLUMN_DESCRIPTIONS;
384         FOR_EACH_COLUMN(i, desc, cd) {
385                 char *null_byte;
386
387                 ret = -E_OSL_SHORT_TABLE;
388                 if (map->size < offset + MIN_IDX_COLUMN_DESCRIPTION_SIZE) {
389                         ERROR_LOG("map size = %zu < %u = offset + min desc size\n",
390                                 map->size, offset + MIN_IDX_COLUMN_DESCRIPTION_SIZE);
391                         goto err;
392                 }
393                 cd->storage_type = read_u16(buf + offset + IDX_CD_STORAGE_TYPE);
394                 cd->storage_flags = read_u16(buf + offset +
395                         IDX_CD_STORAGE_FLAGS);
396                 cd->data_size = read_u32(buf + offset + IDX_CD_DATA_SIZE);
397                 null_byte = memchr(buf + offset + IDX_CD_NAME, '\0',
398                         map->size - offset - IDX_CD_NAME);
399                 ret = -E_OSL_INDEX_CORRUPTION;
400                 if (!null_byte)
401                         goto err;
402                 ret = -ERRNO_TO_ERROR(ENOMEM);
403                 cd->name = strdup(buf + offset + IDX_CD_NAME);
404                 if (!cd->name)
405                         goto err;
406                 offset += index_column_description_size(cd->name);
407         }
408         if (offset != header_size) {
409                 ret = -E_OSL_INDEX_CORRUPTION;
410                 ERROR_LOG("real header size = %u != %u = stored header size\n",
411                         offset, header_size);
412                 goto err;
413         }
414         return 1;
415 err:
416         FOR_EACH_COLUMN(i, desc, cd)
417                 free(cd->name);
418         return ret;
419 }
420
421 /*
422  * check whether the table description given by \p t->desc matches the on-disk
423  * table structure stored in the index of \a t.
424  */
425 static int compare_table_descriptions(struct osl_table *t)
426 {
427         int i, ret;
428         struct osl_table_description desc;
429         const struct osl_column_description *cd1, *cd2;
430
431         /* read the on-disk structure into desc */
432         ret = read_table_desc(&t->index_map, &desc);
433         if (ret < 0)
434                 return ret;
435         ret = -E_OSL_BAD_TABLE_FLAGS;
436         if (desc.flags != t->desc->flags)
437                 goto out;
438         ret = -E_OSL_BAD_COLUMN_NUM;
439         if (desc.num_columns > t->desc->num_columns)
440                 goto out;
441         if (desc.num_columns < t->desc->num_columns) {
442                 struct osl_column_description *cd;
443                 unsigned diff = t->desc->num_columns - desc.num_columns;
444                 INFO_LOG("extending table by %u volatile columns\n", diff);
445                 ret = -ERRNO_TO_ERROR(ENOMEM);
446                 desc.column_descriptions = realloc(desc.column_descriptions,
447                         t->desc->num_columns * sizeof(struct osl_column_description));
448                 if (!desc.column_descriptions)
449                         goto out;
450                 for (i = desc.num_columns; i < t->desc->num_columns; i++) {
451                         cd = get_column_description(&desc, i);
452                         cd->storage_type = OSL_NO_STORAGE;
453                         cd->name = NULL;
454                 }
455                 desc.num_columns += diff;
456         }
457         FOR_EACH_COLUMN(i, t->desc, cd1) {
458                 cd2 = get_column_description(&desc, i);
459                 ret = -E_OSL_BAD_STORAGE_TYPE;
460                 if (cd1->storage_type != cd2->storage_type)
461                         goto out;
462                 if (cd1->storage_type == OSL_NO_STORAGE)
463                         continue;
464                 ret = -E_OSL_BAD_STORAGE_FLAGS;
465                 if (cd1->storage_flags != cd2->storage_flags) {
466                         ERROR_LOG("sf1 = %u != %u = sf2\n",
467                                 cd1->storage_flags, cd2->storage_flags);
468                         goto out;
469                 }
470                 ret = -E_OSL_BAD_DATA_SIZE;
471                 if (cd1->storage_flags & OSL_FIXED_SIZE)
472                         if (cd1->data_size != cd2->data_size)
473                                 goto out;
474                 ret = -E_OSL_BAD_COLUMN_NAME;
475                 if (strcmp(cd1->name, cd2->name))
476                         goto out;
477         }
478         INFO_LOG("table description of '%s' matches on-disk data, good\n",
479                 t->desc->name);
480         ret = 1;
481 out:
482         FOR_EACH_COLUMN(i, &desc, cd1)
483                 free(cd1->name);
484         free(desc.column_descriptions);
485         return ret;
486 }
487
488 static int create_table_index(struct osl_table *t)
489 {
490         char *buf, *filename;
491         int i, ret;
492         size_t size = t->index_header_size;
493         const struct osl_column_description *cd;
494         unsigned offset;
495
496         INFO_LOG("creating %zu byte index for table %s\n", size,
497                 t->desc->name);
498         buf = calloc(1, size);
499         if (!buf)
500                 return -ERRNO_TO_ERROR(ENOMEM);
501         sprintf(buf + IDX_PARA_MAGIC, "%s", PARA_MAGIC);
502         write_u8(buf + IDX_TABLE_FLAGS, t->desc->flags);
503         write_u8(buf + IDX_DIRTY_FLAG, 0);
504         write_u8(buf + IDX_VERSION, CURRENT_TABLE_VERSION);
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 = -ERRNO_TO_ERROR(ENOMEM);
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 && !is_errno(-ret, EEXIST))
549                                 goto out;
550                         table_dir = make_message("%s/%s", desc->dir,
551                                 desc->name);
552                         ret = -ERRNO_TO_ERROR(ENOMEM);
553                         if (!table_dir)
554                                 goto out;
555                         ret = osl_mkdir(table_dir, 0777);
556                         if (ret < 0)
557                                 goto out;
558                 }
559                 ret = -ERRNO_TO_ERROR(ENOMEM);
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 -ERRNO_TO_ERROR(ENOMEM);
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 -ERRNO_TO_ERROR(ENOMEM);
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 *header;
766         char *cell_index;
767         int ret;
768
769         if (t->num_rows <= row_num)
770                 return -E_OSL_BAD_ROW_NUM;
771         ret = get_cell_index(t, row_num, col_num, &cell_index);
772         if (ret < 0)
773                 return ret;
774         offset = read_u32(cell_index);
775         obj->size = read_u32(cell_index + 4) - 1;
776         header = col->data_map.data + offset;
777         obj->data = header + 1;
778         if (read_u8(header) == 0xff) {
779                 ERROR_LOG("col %u, size %zu, offset %u\n", col_num,
780                         obj->size, offset);
781                 return -E_OSL_INVALID_OBJECT;
782         }
783         return 1;
784 }
785
786 static int search_rbtree(const struct osl_object *obj,
787                 const struct osl_table *t, unsigned col_num,
788                 struct rb_node **result, struct rb_node ***rb_link)
789 {
790         struct osl_column *col = &t->columns[col_num];
791         struct rb_node **new = &col->rbtree.rb_node, *parent = NULL;
792         const struct osl_column_description *cd =
793                 get_column_description(t->desc, col_num);
794         enum osl_storage_type st = cd->storage_type;
795         while (*new) {
796                 struct osl_row *this_row = get_row_pointer(*new,
797                         col->rbtree_num);
798                 int ret;
799                 struct osl_object this_obj;
800                 parent = *new;
801                 if (st == OSL_MAPPED_STORAGE) {
802                         ret = get_mapped_object(t, col_num, this_row->num,
803                                 &this_obj);
804                         if (ret < 0)
805                                 return ret;
806                 } else
807                         this_obj = this_row->volatile_objects[col->volatile_num];
808                 ret = cd->compare_function(obj, &this_obj);
809                 if (!ret) {
810                         if (result)
811                                 *result = get_rb_node_pointer(this_row,
812                                         col->rbtree_num);
813                         return 1;
814                 }
815                 if (ret < 0)
816                         new = &((*new)->rb_left);
817                 else
818                         new = &((*new)->rb_right);
819         }
820         if (result)
821                 *result = parent;
822         if (rb_link)
823                 *rb_link = new;
824         return -E_OSL_RB_KEY_NOT_FOUND;
825 }
826
827 static int insert_rbtree(struct osl_table *t, unsigned col_num,
828         const struct osl_row *row, const struct osl_object *obj)
829 {
830         struct rb_node *parent, **rb_link;
831         unsigned rbtree_num;
832         struct rb_node *n;
833         int ret = search_rbtree(obj, t, col_num, &parent, &rb_link);
834
835         if (ret > 0)
836                 return -E_OSL_RB_KEY_EXISTS;
837         rbtree_num = t->columns[col_num].rbtree_num;
838         n = get_rb_node_pointer(row, rbtree_num);
839         rb_link_node(n, parent, rb_link);
840         rb_insert_color(n, &t->columns[col_num].rbtree);
841         return 1;
842 }
843
844 static void remove_rb_node(struct osl_table *t, unsigned col_num,
845                 const struct osl_row *row)
846 {
847         struct osl_column *col = &t->columns[col_num];
848         const struct osl_column_description *cd =
849                 get_column_description(t->desc, col_num);
850         enum osl_storage_flags sf = cd->storage_flags;
851         struct rb_node *victim, *splice_out_node, *tmp;
852         if (!(sf & OSL_RBTREE))
853                 return;
854         /*
855          * Which node is removed/spliced out actually depends on how many
856          * children the victim node has: If it has no children, it gets
857          * deleted. If it has one child, it gets spliced out. If it has two
858          * children, its successor (which has at most a right child) gets
859          * spliced out.
860          */
861         victim = get_rb_node_pointer(row, col->rbtree_num);
862         if (victim->rb_left && victim->rb_right)
863                 splice_out_node = rb_next(victim);
864         else
865                 splice_out_node = victim;
866         /* Go up to the root and decrement the size of each node in the path. */
867         for (tmp = splice_out_node; tmp; tmp = rb_parent(tmp))
868                 tmp->size--;
869         rb_erase(victim, &col->rbtree);
870 }
871
872 static int add_row_to_rbtrees(struct osl_table *t, uint32_t row_num,
873                 struct osl_object *volatile_objs, struct osl_row **row_ptr)
874 {
875         unsigned i;
876         int ret;
877         struct osl_row *row = allocate_row(t->num_rbtrees);
878         const struct osl_column_description *cd;
879
880         if (!row)
881                 return -ERRNO_TO_ERROR(ENOMEM);
882         row->num = row_num;
883         row->volatile_objects = volatile_objs;
884         FOR_EACH_RBTREE_COLUMN(i, t, cd) {
885                 if (cd->storage_type == OSL_MAPPED_STORAGE) {
886                         struct osl_object obj;
887                         ret = get_mapped_object(t, i, row_num, &obj);
888                         if (ret < 0)
889                                 goto err;
890                         ret = insert_rbtree(t, i, row, &obj);
891                 } else { /* volatile */
892                         const struct osl_object *obj
893                                 = volatile_objs + t->columns[i].volatile_num;
894                         ret = insert_rbtree(t, i, row, obj);
895                 }
896                 if (ret < 0)
897                         goto err;
898         }
899         if (row_ptr)
900                 *row_ptr = row;
901         return 1;
902 err: /* rollback changes, i.e. remove added entries from rbtrees */
903         while (i)
904                 remove_rb_node(t, i--, row);
905         free(row);
906         return ret;
907 }
908
909 static void free_volatile_objects(const struct osl_table *t,
910                 enum osl_close_flags flags)
911 {
912         int i, j;
913         struct rb_node *n;
914         struct osl_column *rb_col;
915         const struct osl_column_description *cd;
916
917         if (!t->num_volatile_columns)
918                 return;
919         /* find the first rbtree column (any will do) */
920         FOR_EACH_RBTREE_COLUMN(i, t, cd)
921                 break;
922         rb_col = t->columns + i;
923         /* walk that rbtree and free all volatile objects */
924         for (n = rb_first(&rb_col->rbtree); n; n = rb_next(n)) {
925                 struct osl_row *r = get_row_pointer(n, rb_col->rbtree_num);
926                 if (flags & OSL_FREE_VOLATILE)
927                         FOR_EACH_VOLATILE_COLUMN(j, t, cd) {
928                                 if (cd->storage_flags & OSL_DONT_FREE)
929                                         continue;
930                                 free(r->volatile_objects[
931                                         t->columns[j].volatile_num].data);
932                         }
933 //                      for (j = 0; j < t->num_volatile_columns; j++)
934 //                              free(r->volatile_objects[j].data);
935                 free(r->volatile_objects);
936         }
937 }
938
939 /**
940  * Erase all rbtree nodes and free resources.
941  *
942  * \param t Pointer to an open osl table.
943  *
944  * This function is called by osl_close_table().
945  */
946 void clear_rbtrees(struct osl_table *t)
947 {
948         const struct osl_column_description *cd;
949         unsigned i, rbtrees_cleared = 0;
950
951         FOR_EACH_RBTREE_COLUMN(i, t, cd) {
952                 struct osl_column *col = &t->columns[i];
953                 struct rb_node *n;
954                 rbtrees_cleared++;
955                 for (n = rb_first(&col->rbtree); n;) {
956                         struct osl_row *r;
957                         rb_erase(n, &col->rbtree);
958                         if (rbtrees_cleared == t->num_rbtrees) {
959                                 r = get_row_pointer(n, col->rbtree_num);
960                                 n = rb_next(n);
961                                 free(r);
962                         } else
963                                 n = rb_next(n);
964                 }
965         }
966
967 }
968
969 __export int osl_close_table(struct osl_table *t, enum osl_close_flags flags)
970 {
971         int ret;
972
973         if (!t)
974                 return -E_OSL_BAD_TABLE;
975         NOTICE_LOG("closing table %s\n", t->desc->name);
976         free_volatile_objects(t, flags);
977         clear_rbtrees(t);
978         ret = unmap_table(t, flags);
979         if (ret < 0)
980                 ERROR_LOG("unmap_table failed: %d\n", ret);
981         free(t->columns);
982         free(t);
983         return ret;
984 }
985
986 /**
987  * Find out whether the given row number corresponds to an invalid row.
988  *
989  * \param t Pointer to the osl table.
990  * \param row_num The number of the row in question.
991  *
992  * By definition, a row is considered invalid if all its index entries
993  * are invalid.
994  *
995  * \return Positive if \a row_num corresponds to an invalid row,
996  * zero if it corresponds to a valid row, negative on errors.
997  */
998 int row_is_invalid(struct osl_table *t, uint32_t row_num)
999 {
1000         char *row_index;
1001         int i, ret = get_row_index(t, row_num, &row_index);
1002
1003         if (ret < 0)
1004                 return ret;
1005         for (i = 0; i < t->row_index_size; i++) {
1006                 if ((unsigned char)row_index[i] != 0xff)
1007                         return 0;
1008         }
1009         INFO_LOG("row %d is invalid\n", row_num);
1010         return 1;
1011 }
1012
1013 /**
1014  * Invalidate a row of an osl table.
1015  *
1016  * \param t Pointer to an open osl table.
1017  * \param row_num Number of the row to mark as invalid.
1018  *
1019  * This function marks each mapped object in the index entry of \a row as
1020  * invalid.
1021  *
1022  * \return Standard.
1023  */
1024 int mark_row_invalid(struct osl_table *t, uint32_t row_num)
1025 {
1026         char *row_index;
1027         int ret = get_row_index(t, row_num, &row_index);
1028
1029         if (ret < 0)
1030                 return ret;
1031         INFO_LOG("marking row %d as invalid\n", row_num);
1032         memset(row_index, 0xff, t->row_index_size);
1033         return 1;
1034 }
1035
1036 /**
1037  * Initialize all rbtrees and compute number of invalid rows.
1038  *
1039  * \param t The table containing the rbtrees to be initialized.
1040  *
1041  * \return Standard.
1042  */
1043 int init_rbtrees(struct osl_table *t)
1044 {
1045         int i, ret;
1046         const struct osl_column_description *cd;
1047
1048         /* create rbtrees */
1049         FOR_EACH_RBTREE_COLUMN(i, t, cd)
1050                 t->columns[i].rbtree = RB_ROOT;
1051         /* add valid rows to rbtrees */
1052         t->num_invalid_rows = 0;
1053         for (i = 0; i < t->num_rows; i++) {
1054                 ret = row_is_invalid(t, i);
1055                 if (ret < 0)
1056                         return ret;
1057                 if (ret) {
1058                         t->num_invalid_rows++;
1059                         continue;
1060                 }
1061                 ret = add_row_to_rbtrees(t, i, NULL, NULL);
1062                 if (ret < 0)
1063                         return ret;
1064         }
1065         return 1;
1066 }
1067
1068 __export int osl_open_table(const struct osl_table_description *table_desc,
1069                 struct osl_table **result)
1070 {
1071         int i, ret;
1072         struct osl_table *t;
1073         const struct osl_column_description *cd;
1074
1075         NOTICE_LOG("opening table %s\n", table_desc->name);
1076         ret = init_table_structure(table_desc, &t);
1077         if (ret < 0)
1078                 return ret;
1079         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
1080                 struct stat statbuf;
1081                 char *dirname = column_filename(t, i);
1082
1083                 ret = -ERRNO_TO_ERROR(ENOMEM);
1084                 if (!dirname)
1085                         goto err;
1086                 /* check if directory exists */
1087                 ret = stat(dirname, &statbuf);
1088                 free(dirname);
1089                 if (ret < 0) {
1090                         ret = -ERRNO_TO_ERROR(errno);
1091                         goto err;
1092                 }
1093                 ret = -ERRNO_TO_ERROR(ENOTDIR);
1094                 if (!S_ISDIR(statbuf.st_mode))
1095                         goto err;
1096         }
1097         ret = map_table(t, MAP_TBL_FL_VERIFY_INDEX);
1098         if (ret < 0)
1099                 goto err;
1100         t->num_rows = ret;
1101         DEBUG_LOG("num rows: %d\n", t->num_rows);
1102         ret = init_rbtrees(t);
1103         if (ret < 0) {
1104                 osl_close_table(t, OSL_MARK_CLEAN); /* ignore further errors */
1105                 return ret;
1106         }
1107         *result = t;
1108         return 1;
1109 err:
1110         free(t->columns);
1111         free(t);
1112         return ret;
1113 }
1114
1115 static int create_disk_storage_object_dir(const struct osl_table *t,
1116                 unsigned col_num, const char *ds_name)
1117 {
1118         char *dirname;
1119         int ret;
1120
1121         if (!(t->desc->flags & OSL_LARGE_TABLE))
1122                 return 1;
1123         dirname = disk_storage_dirname(t, col_num, ds_name);
1124         if (!dirname)
1125                 return -ERRNO_TO_ERROR(ENOMEM);
1126         ret = osl_mkdir(dirname, 0777);
1127         free(dirname);
1128         if (ret < 0 && !is_errno(-ret, EEXIST))
1129                 return ret;
1130         return 1;
1131 }
1132
1133 static int write_disk_storage_file(const struct osl_table *t, unsigned col_num,
1134         const struct osl_object *obj, const char *ds_name)
1135 {
1136         int ret;
1137         char *filename;
1138
1139         ret = create_disk_storage_object_dir(t, col_num, ds_name);
1140         if (ret < 0)
1141                 return ret;
1142         filename = disk_storage_path(t, col_num, ds_name);
1143         if (!filename)
1144                 return -ERRNO_TO_ERROR(ENOMEM);
1145         ret = write_file(filename, obj->data, obj->size);
1146         free(filename);
1147         return ret;
1148 }
1149
1150 static int append_map_file(const struct osl_table *t, unsigned col_num,
1151         const struct osl_object *obj, uint32_t *new_size)
1152 {
1153         char *filename = column_filename(t, col_num);
1154         int ret;
1155         char header = 0; /* zero means valid object */
1156
1157         if (!filename)
1158                 return -ERRNO_TO_ERROR(ENOMEM);
1159         ret = append_file(filename, &header, 1, obj->data, obj->size,
1160                 new_size);
1161         free(filename);
1162         return ret;
1163 }
1164
1165 static int append_row_index(const struct osl_table *t, char *row_index)
1166 {
1167         char *filename;
1168         int ret;
1169
1170         if (!t->num_mapped_columns)
1171                 return 1;
1172         filename = index_filename(t->desc);
1173         if (!filename)
1174                 return -ERRNO_TO_ERROR(ENOMEM);
1175         ret = append_file(filename, NULL, 0, row_index,
1176                 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 -ERRNO_TO_ERROR(ENOMEM);
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, err;
1199
1200         if (!filename)
1201                 return -ERRNO_TO_ERROR(ENOMEM);
1202         ret = unlink(filename);
1203         err = errno;
1204         free(filename);
1205         if (ret < 0)
1206                 return -ERRNO_TO_ERROR(err);
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 -ERRNO_TO_ERROR(ENOMEM);
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 -ERRNO_TO_ERROR(ENOMEM);
1232         rb_links = malloc(t->num_rbtrees * sizeof(struct rn_node**));
1233         if (!rb_links) {
1234                 free(rb_parents);
1235                 return -ERRNO_TO_ERROR(ENOMEM);
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 -ERRNO_TO_ERROR(ENOMEM);
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 = -ERRNO_TO_ERROR(ENOMEM);
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 = -ERRNO_TO_ERROR(ENOMEM);
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 static int mark_mapped_object_invalid(const struct osl_table *t,
1383                 uint32_t row_num, unsigned col_num)
1384 {
1385         struct osl_object obj;
1386         char *p;
1387         int ret = get_mapped_object(t, col_num, row_num, &obj);
1388
1389         if (ret < 0)
1390                 return ret;
1391         p = obj.data;
1392         p--;
1393         *p = 0xff;
1394         return 1;
1395 }
1396
1397 __export int osl_del_row(struct osl_table *t, struct osl_row *row)
1398 {
1399         struct osl_row *r = row;
1400         int i, ret;
1401         const struct osl_column_description *cd;
1402
1403         if (!t)
1404                 return -E_OSL_BAD_TABLE;
1405         INFO_LOG("deleting row %p\n", row);
1406
1407         if (t->num_disk_storage_columns) {
1408                 char *ds_name;
1409                 ret = disk_storage_name_of_row(t, r, &ds_name);
1410                 if (ret < 0)
1411                         goto out;
1412                 FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd)
1413                         delete_disk_storage_file(t, i, ds_name);
1414                 free(ds_name);
1415         }
1416         FOR_EACH_COLUMN(i, t->desc, cd) {
1417                 struct osl_column *col = t->columns + i;
1418                 enum osl_storage_type st = cd->storage_type;
1419                 remove_rb_node(t, i, r);
1420                 if (st == OSL_MAPPED_STORAGE) {
1421                         mark_mapped_object_invalid(t, r->num, i);
1422                         continue;
1423                 }
1424                 if (st == OSL_NO_STORAGE && !(cd->storage_flags & OSL_DONT_FREE))
1425                         free(r->volatile_objects[col->volatile_num].data);
1426         }
1427         if (t->num_mapped_columns) {
1428                 ret = mark_row_invalid(t, r->num);
1429                 if (ret < 0)
1430                         goto out;
1431                 t->num_invalid_rows++;
1432         } else
1433                 t->num_rows--;
1434         ret = 1;
1435 out:
1436         free(r->volatile_objects);
1437         free(r);
1438         return ret;
1439 }
1440
1441 /* test if column has an rbtree */
1442 static int check_rbtree_col(const struct osl_table *t, unsigned col_num,
1443                 struct osl_column **col)
1444 {
1445         if (!t)
1446                 return -E_OSL_BAD_TABLE;
1447         if (!(get_column_description(t->desc, col_num)->storage_flags & OSL_RBTREE))
1448                 return -E_OSL_BAD_STORAGE_FLAGS;
1449         *col = t->columns + col_num;
1450         return 1;
1451 }
1452
1453 __export int osl_get_row(const struct osl_table *t, unsigned col_num,
1454                 const struct osl_object *obj, struct osl_row **result)
1455 {
1456         int ret;
1457         struct rb_node *node;
1458         struct osl_row *row;
1459         struct osl_column *col;
1460
1461         *result = NULL;
1462         ret = check_rbtree_col(t, col_num, &col);
1463         if (ret < 0)
1464                 return ret;
1465         ret = search_rbtree(obj, t, col_num, &node, NULL);
1466         if (ret < 0)
1467                 return ret;
1468         row = get_row_pointer(node, t->columns[col_num].rbtree_num);
1469         *result = row;
1470         return 1;
1471 }
1472
1473 static int rbtree_loop(struct osl_column *col, void *private_data,
1474                 osl_rbtree_loop_func *func)
1475 {
1476         struct rb_node *n, *tmp;
1477
1478         /* this for-loop is safe against removal of an entry */
1479         for (n = rb_first(&col->rbtree), tmp = n? rb_next(n) : NULL;
1480                         n;
1481                         n = tmp, tmp = tmp? rb_next(tmp) : NULL) {
1482                 struct osl_row *r = get_row_pointer(n, col->rbtree_num);
1483                 if (func(r, private_data) < 0)
1484                         return -E_OSL_LOOP;
1485         }
1486         return 1;
1487 }
1488
1489 static int rbtree_loop_reverse(struct osl_column *col, void *private_data,
1490                 osl_rbtree_loop_func *func)
1491 {
1492         struct rb_node *n, *tmp;
1493
1494         /* safe against removal of an entry */
1495         for (n = rb_last(&col->rbtree), tmp = n? rb_prev(n) : NULL;
1496                         n;
1497                         n = tmp, tmp = tmp? rb_prev(tmp) : NULL) {
1498                 struct osl_row *r = get_row_pointer(n, col->rbtree_num);
1499                 if (func(r, private_data) < 0)
1500                         return -E_OSL_LOOP;
1501         }
1502         return 1;
1503 }
1504
1505 __export int osl_rbtree_loop(const struct osl_table *t, unsigned col_num,
1506         void *private_data, osl_rbtree_loop_func *func)
1507 {
1508         struct osl_column *col;
1509
1510         int ret = check_rbtree_col(t, col_num, &col);
1511         if (ret < 0)
1512                 return ret;
1513         return rbtree_loop(col, private_data, func);
1514 }
1515
1516 __export int osl_rbtree_loop_reverse(const struct osl_table *t, unsigned col_num,
1517         void *private_data, osl_rbtree_loop_func *func)
1518 {
1519         struct osl_column *col;
1520
1521         int ret = check_rbtree_col(t, col_num, &col);
1522         if (ret < 0)
1523                 return ret;
1524         return rbtree_loop_reverse(col, private_data, func);
1525 }
1526
1527 /* TODO: Rollback changes on errors */
1528 static int rename_disk_storage_objects(struct osl_table *t,
1529                 struct osl_object *old_obj, struct osl_object *new_obj)
1530 {
1531         int i, ret;
1532         const struct osl_column_description *cd;
1533         char *old_ds_name, *new_ds_name;
1534
1535         if (!t->num_disk_storage_columns)
1536                 return 1; /* nothing to do */
1537         if (old_obj->size == new_obj->size && !memcmp(new_obj->data,
1538                         old_obj->data, new_obj->size))
1539                 return 1; /* object did not change */
1540         old_ds_name = disk_storage_name_of_object(t, old_obj);
1541         new_ds_name = disk_storage_name_of_object(t, new_obj);
1542         ret = -ERRNO_TO_ERROR(ENOMEM);
1543         if (!old_ds_name || ! new_ds_name)
1544                 goto out;
1545
1546         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
1547                 char *old_filename, *new_filename;
1548                 ret = create_disk_storage_object_dir(t, i, new_ds_name);
1549                 if (ret < 0)
1550                         goto out;
1551                 old_filename = disk_storage_path(t, i, old_ds_name);
1552                 new_filename = disk_storage_path(t, i, new_ds_name);
1553                 if (!old_filename || !new_filename)
1554                         ret = -ERRNO_TO_ERROR(ENOMEM);
1555                 else
1556                         ret = osl_rename(old_filename, new_filename);
1557                 free(old_filename);
1558                 free(new_filename);
1559                 if (ret < 0)
1560                         goto out;
1561         }
1562         ret = 1;
1563 out:
1564         free(old_ds_name);
1565         free(new_ds_name);
1566         return ret;
1567
1568 }
1569
1570 __export int osl_update_object(struct osl_table *t, const struct osl_row *r,
1571                 unsigned col_num, struct osl_object *obj)
1572 {
1573         struct osl_column *col;
1574         const struct osl_column_description *cd;
1575         int ret;
1576
1577         if (!t)
1578                 return -E_OSL_BAD_TABLE;
1579         col = &t->columns[col_num];
1580         cd = get_column_description(t->desc, col_num);
1581         DEBUG_LOG("updating column %u of %s\n", col_num, t->desc->name);
1582         if (cd->storage_flags & OSL_RBTREE) {
1583                 if (search_rbtree(obj, t, col_num, NULL, NULL) > 0)
1584                         return -E_OSL_RB_KEY_EXISTS;
1585         }
1586         if (cd->storage_flags & OSL_FIXED_SIZE) {
1587                 if (obj->size != cd->data_size)
1588                         return -E_OSL_BAD_DATA_SIZE;
1589         }
1590         remove_rb_node(t, col_num, r);
1591         if (cd->storage_type == OSL_NO_STORAGE) { /* TODO: If fixed size, reuse object? */
1592                 free(r->volatile_objects[col->volatile_num].data);
1593                 r->volatile_objects[col->volatile_num] = *obj;
1594         } else if (cd->storage_type == OSL_DISK_STORAGE) {
1595                 char *ds_name;
1596                 ret = disk_storage_name_of_row(t, r, &ds_name);
1597                 if (ret < 0)
1598                         return ret;
1599                 ret = delete_disk_storage_file(t, col_num, ds_name);
1600                 if (ret < 0 && !is_errno(-ret, ENOENT)) {
1601                         free(ds_name);
1602                         return ret;
1603                 }
1604                 ret = write_disk_storage_file(t, col_num, obj, ds_name);
1605                 free(ds_name);
1606                 if (ret < 0)
1607                         return ret;
1608         } else { /* mapped storage */
1609                 struct osl_object old_obj;
1610                 ret = get_mapped_object(t, col_num, r->num, &old_obj);
1611                 if (ret < 0)
1612                         return ret;
1613                 /*
1614                  * If the updated column is the disk storage name column, the
1615                  * disk storage name changes, so we have to rename all disk
1616                  * storage objects accordingly.
1617                  */
1618                 if (col_num == t->disk_storage_name_column) {
1619                         ret = rename_disk_storage_objects(t, &old_obj, obj);
1620                         if (ret < 0)
1621                                 return ret;
1622                 }
1623                 if (cd->storage_flags & OSL_FIXED_SIZE)
1624                         memcpy(old_obj.data, obj->data, cd->data_size);
1625                 else { /* TODO: if the size doesn't change, use old space */
1626                         uint32_t new_data_map_size;
1627                         char *row_index;
1628                         ret = get_row_index(t, r->num, &row_index);
1629                         if (ret < 0)
1630                                 return ret;
1631                         ret = mark_mapped_object_invalid(t, r->num, col_num);
1632                         if (ret < 0)
1633                                 return ret;
1634                         unmap_column(t, col_num);
1635                         ret = append_map_file(t, col_num, obj,
1636                                 &new_data_map_size);
1637                         if (ret < 0)
1638                                 return ret;
1639                         ret = map_column(t, col_num);
1640                         if (ret < 0)
1641                                 return ret;
1642                         update_cell_index(row_index, col, new_data_map_size,
1643                                 obj->size);
1644                 }
1645         }
1646         if (cd->storage_flags & OSL_RBTREE) {
1647                 ret = insert_rbtree(t, col_num, r, obj);
1648                 if (ret < 0)
1649                         return ret;
1650         }
1651         return 1;
1652 }
1653
1654 __export int osl_open_disk_object(const struct osl_table *t, const struct osl_row *r,
1655                 unsigned col_num, struct osl_object *obj)
1656 {
1657         const struct osl_column_description *cd;
1658         char *ds_name, *filename;
1659         int ret;
1660
1661         if (!t)
1662                 return -E_OSL_BAD_TABLE;
1663         cd = get_column_description(t->desc, col_num);
1664         if (cd->storage_type != OSL_DISK_STORAGE)
1665                 return -E_OSL_BAD_STORAGE_TYPE;
1666
1667         ret = disk_storage_name_of_row(t, r, &ds_name);
1668         if (ret < 0)
1669                 return ret;
1670         filename = disk_storage_path(t, col_num, ds_name);
1671         free(ds_name);
1672         if (!filename)
1673                 return -ERRNO_TO_ERROR(ENOMEM);
1674         DEBUG_LOG("filename: %s\n", filename);
1675         ret = mmap_full_file(filename, O_RDONLY, &obj->data, &obj->size, NULL);
1676         free(filename);
1677         return ret;
1678 }
1679
1680 __export int osl_close_disk_object(struct osl_object *obj)
1681 {
1682         return osl_munmap(obj->data, obj->size);
1683 }
1684
1685 __export int osl_get_num_rows(const struct osl_table *t, unsigned *num_rows)
1686 {
1687         if (!t)
1688                 return -E_OSL_BAD_TABLE;
1689         assert(t->num_rows >= t->num_invalid_rows);
1690         *num_rows = t->num_rows - t->num_invalid_rows;
1691         return 1;
1692 }
1693
1694 __export int osl_get_rank(const struct osl_table *t, struct osl_row *r,
1695                 unsigned col_num, unsigned *rank)
1696 {
1697         struct osl_object obj;
1698         struct osl_column *col;
1699         struct rb_node *node;
1700         int ret = check_rbtree_col(t, col_num, &col);
1701
1702         if (ret < 0)
1703                 return ret;
1704         ret = osl_get_object(t, r, col_num, &obj);
1705         if (ret < 0)
1706                 return ret;
1707         ret = search_rbtree(&obj, t, col_num, &node, NULL);
1708         if (ret < 0)
1709                 return ret;
1710         ret = rb_rank(node, rank);
1711         if (ret < 0)
1712                 return -E_OSL_BAD_ROW;
1713         return 1;
1714 }
1715
1716 __export int osl_get_nth_row(const struct osl_table *t, unsigned col_num,
1717                 unsigned n, struct osl_row **result)
1718 {
1719         struct osl_column *col;
1720         struct rb_node *node;
1721         unsigned num_rows;
1722         int ret;
1723
1724         if (n == 0)
1725                 return -E_OSL_RB_KEY_NOT_FOUND;
1726         ret = osl_get_num_rows(t, &num_rows);
1727         if (ret < 0)
1728                 return ret;
1729         if (n > num_rows)
1730                 return -E_OSL_RB_KEY_NOT_FOUND;
1731         ret = check_rbtree_col(t, col_num, &col);
1732         if (ret < 0)
1733                 return ret;
1734         node = rb_nth(col->rbtree.rb_node, n);
1735         if (!node)
1736                 return -E_OSL_RB_KEY_NOT_FOUND;
1737         *result = get_row_pointer(node, col->rbtree_num);
1738         return 1;
1739 }
1740
1741 __export int osl_rbtree_first_row(const struct osl_table *t, unsigned col_num,
1742                 struct osl_row **result)
1743 {
1744         return osl_get_nth_row(t, col_num, 1, result);
1745 }
1746
1747 __export int osl_rbtree_last_row(const struct osl_table *t, unsigned col_num,
1748                 struct osl_row **result)
1749 {
1750         unsigned num_rows;
1751         int ret = osl_get_num_rows(t, &num_rows);
1752
1753         if (ret < 0)
1754                 return ret;
1755         return osl_get_nth_row(t, col_num, num_rows, result);
1756 }