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