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