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