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