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