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