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