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