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