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