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