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