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