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