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