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