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