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