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