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