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