Improve documentation of osl_rbtree_loop().
[osl.git] / fsck.c
1 /*
2  * Copyright (C) 2007-2009 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file fsck.c The program used to check an osl table. */
8
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <dirent.h>
12 #include <lopsub.h>
13 #include <assert.h>
14 #include <pwd.h>
15
16 #include "log.h"
17 #include "osl.h"
18 #include "util.h"
19 #include "osl_core.h"
20 #include "oslfsck.lsg.h"
21
22 static struct lls_parse_result *lpr;
23 #define CMD_PTR (lls_cmd(0, oslfsck_suite))
24 #define OPT_RESULT(_name) \
25         (lls_opt_result(LSG_OSLFSCK_OSLFSCK_OPT_ ## _name, lpr))
26 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
27 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
28 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
29
30 #define FSCK_ERRORS \
31         FSCK_ERROR(RANGE_VIOLATION, "range violation detected, very bad"), \
32         FSCK_ERROR(NOT_A_REGULAR_FILE, "not a regular file"), \
33         FSCK_ERROR(SYNTAX, "fsck syntax error"), \
34         FSCK_ERROR(ACCESS, "permission denied"), \
35         FSCK_ERROR(CHDIR, "could not change directory"), \
36         FSCK_ERROR(OPENDIR, "could not open directory"),
37
38 #define FSCK_ERROR_BIT 29
39 #define FSCK_ERROR(num, txt) E_FSCK_ ## num
40 enum {
41         FSCK_DUMMY = (1 << FSCK_ERROR_BIT) - 1,
42         FSCK_ERRORS
43 };
44 #undef FSCK_ERROR
45 #define FSCK_ERROR(num, txt) txt
46 static const char *fsck_errors[] = {
47         FSCK_ERRORS
48 };
49
50 static const char *fsck_strerror(int num)
51 {
52         if (num & (1 << FSCK_ERROR_BIT))
53                 return fsck_errors[num & ((1 << FSCK_ERROR_BIT) - 1)];
54         return osl_strerror(num);
55 }
56
57 extern int loglevel;
58
59 /* taken from git */
60 static signed char hexval_table[256] = {
61          -1, -1, -1, -1, -1, -1, -1, -1,                /* 00-07 */
62          -1, -1, -1, -1, -1, -1, -1, -1,                /* 08-0f */
63          -1, -1, -1, -1, -1, -1, -1, -1,                /* 10-17 */
64          -1, -1, -1, -1, -1, -1, -1, -1,                /* 18-1f */
65          -1, -1, -1, -1, -1, -1, -1, -1,                /* 20-27 */
66          -1, -1, -1, -1, -1, -1, -1, -1,                /* 28-2f */
67           0,  1,  2,  3,  4,  5,  6,  7,                /* 30-37 */
68           8,  9, -1, -1, -1, -1, -1, -1,                /* 38-3f */
69          -1, 10, 11, 12, 13, 14, 15, -1,                /* 40-47 */
70          -1, -1, -1, -1, -1, -1, -1, -1,                /* 48-4f */
71          -1, -1, -1, -1, -1, -1, -1, -1,                /* 50-57 */
72          -1, -1, -1, -1, -1, -1, -1, -1,                /* 58-5f */
73          -1, 10, 11, 12, 13, 14, 15, -1,                /* 60-67 */
74          -1, -1, -1, -1, -1, -1, -1, -1,                /* 68-67 */
75          -1, -1, -1, -1, -1, -1, -1, -1,                /* 70-77 */
76          -1, -1, -1, -1, -1, -1, -1, -1,                /* 78-7f */
77          -1, -1, -1, -1, -1, -1, -1, -1,                /* 80-87 */
78          -1, -1, -1, -1, -1, -1, -1, -1,                /* 88-8f */
79          -1, -1, -1, -1, -1, -1, -1, -1,                /* 90-97 */
80          -1, -1, -1, -1, -1, -1, -1, -1,                /* 98-9f */
81          -1, -1, -1, -1, -1, -1, -1, -1,                /* a0-a7 */
82          -1, -1, -1, -1, -1, -1, -1, -1,                /* a8-af */
83          -1, -1, -1, -1, -1, -1, -1, -1,                /* b0-b7 */
84          -1, -1, -1, -1, -1, -1, -1, -1,                /* b8-bf */
85          -1, -1, -1, -1, -1, -1, -1, -1,                /* c0-c7 */
86          -1, -1, -1, -1, -1, -1, -1, -1,                /* c8-cf */
87          -1, -1, -1, -1, -1, -1, -1, -1,                /* d0-d7 */
88          -1, -1, -1, -1, -1, -1, -1, -1,                /* d8-df */
89          -1, -1, -1, -1, -1, -1, -1, -1,                /* e0-e7 */
90          -1, -1, -1, -1, -1, -1, -1, -1,                /* e8-ef */
91          -1, -1, -1, -1, -1, -1, -1, -1,                /* f0-f7 */
92          -1, -1, -1, -1, -1, -1, -1, -1,                /* f8-ff */
93 };
94
95 static int asc_to_hash(const char *asc_hash, int len, HASH_TYPE *hash)
96 {
97         int i = 0;
98         const unsigned char *asc = (const unsigned char *) asc_hash;
99
100         while (*asc && i++ < len) {
101                 unsigned int val = (hexval_table[asc[0]] << 4) | hexval_table[asc[1]];
102                 if (val & ~0xff)
103                         return -1;
104                 *hash++ = val;
105                 asc += 2;
106
107         }
108         return 1;
109 }
110
111 static int _write_all(int fd, const char *buf, size_t len)
112 {
113         return write_all(fd, buf, &len);
114 }
115
116 /*
117  * Wrapper for malloc().
118  *
119  * \param size The desired new size.
120  *
121  * A wrapper for malloc(3) which exits on errors.
122  *
123  * \return A pointer to the allocated memory, which is suitably aligned for any
124  * kind of variable.
125  *
126  * \sa malloc(3).
127  */
128 __must_check __malloc static void *fsck_malloc(size_t size)
129 {
130         assert(size);
131         void *p = malloc(size);
132
133         if (!p) {
134                 EMERG_LOG("malloc failed (size = %zu),  aborting\n",
135                         size);
136                 exit(EXIT_FAILURE);
137         }
138         return p;
139 }
140
141 /**
142  * Allocate memory and fill with zeros.
143  *
144  * \param size The desired new size.
145  *
146  * A wrapper for calloc(3) which exits on errors.
147  *
148  * \return A pointer to the allocated and zeroed-out memory, which is suitably
149  * aligned for any kind of variable.
150  *
151  * \sa calloc(3)
152  */
153 __must_check __malloc static void *fsck_calloc(size_t size)
154 {
155         void *ret = fsck_malloc(size);
156
157         memset(ret, 0, size);
158         return ret;
159 }
160
161 /**
162  * Save version of strdup().
163  *
164  * \param s The string to be duplicated.
165  *
166  * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
167  * there is no need to check the return value in the caller.
168  *
169  * \return A pointer to the duplicated string. If \p s was the NULL pointer,
170  * an pointer to an empty string is returned.
171  *
172  * \sa strdup(3)
173  */
174 __must_check __malloc static char *fsck_strdup(const char *s)
175 {
176         char *ret;
177
178         if ((ret = strdup(s? s: "")))
179                 return ret;
180         EMERG_LOG("strdup failed, aborting\n");
181         exit(EXIT_FAILURE);
182 }
183
184 /**
185  * Compare two osl objects pointing to unsigned integers of 32 bit size.
186  *
187  * \param obj1 Pointer to the first integer.
188  * \param obj2 Pointer to the second integer.
189  *
190  * \return The values required for an osl compare function.
191  *
192  * \sa osl_compare_func, osl_hash_compare().
193  */
194 static int uint32_compare(const struct osl_object *obj1, const struct osl_object *obj2)
195 {
196         uint32_t d1 = read_u32((const char *)obj1->data);
197         uint32_t d2 = read_u32((const char *)obj2->data);
198
199         if (d1 < d2)
200                 return 1;
201         if (d1 > d2)
202                 return -1;
203         return 0;
204 }
205
206 /**
207  * A wrapper for fchdir().
208  *
209  * \param fd An open file descriptor.
210  *
211  * \return Standard.
212  */
213 static inline int __fchdir(int fd)
214 {
215         if (fchdir(fd) >= 0)
216                 return 1;
217         return errno == EACCES? -E_FSCK_ACCESS : -E_FSCK_CHDIR;
218 }
219
220 /**
221  * Wrapper for chdir(2).
222  *
223  * \param path The specified directory.
224  *
225  * \return Standard.
226  */
227 _static_inline_ int __chdir(const char *path)
228 {
229         if (chdir(path) >= 0)
230                 return 1;
231         return errno == EACCES? -E_FSCK_ACCESS : -E_FSCK_CHDIR;
232 }
233
234 /**
235  * Save the cwd and open a given directory.
236  *
237  * \param dirname Path to the directory to open.
238  * \param dir Result pointer.
239  * \param cwd File descriptor of the current working directory.
240  *
241  * \return Standard.
242  *
243  * Opening the current directory (".") and calling fchdir() to return is
244  * usually faster and more reliable than saving cwd in some buffer and calling
245  * chdir() afterwards.
246  *
247  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
248  * stored in \a cwd. If the function returns success, and \a cwd is not \p
249  * NULL, the caller must close this file descriptor (probably after calling
250  * fchdir(*cwd)).
251  *
252  * On errors, the function undos everything, so the caller needs neither close
253  * any files, nor change back to the original working directory.
254  *
255  * \sa getcwd(3).
256  *
257  */
258 static int fsck_opendir(const char *dirname, DIR **dir, int *cwd)
259 {
260         int ret;
261
262         if (cwd) {
263                 ret = osl_open(".", O_RDONLY, 0);
264                 if (ret < 0)
265                         return ret;
266                 *cwd = ret;
267         }
268         ret = __chdir(dirname);
269         if (ret < 0)
270                 goto close_cwd;
271         *dir = opendir(".");
272         if (*dir)
273                 return 1;
274         ret = errno == EACCES? -E_FSCK_ACCESS : -E_FSCK_OPENDIR;
275         /* Ignore return value of fchdir() and close(). We're busted anyway. */
276         if (cwd) {
277                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
278         }
279 close_cwd:
280         if (cwd)
281                 close(*cwd);
282         return ret;
283 }
284
285
286
287 /**
288  * Traverse the given directory recursively.
289  *
290  * \param dirname The directory to traverse.
291  * \param func The function to call for each entry.
292  * \param private_data Pointer to an arbitrary data structure.
293  *
294  * For each regular file under \a dirname, the supplied function \a func is
295  * called.  The full path of the regular file and the \a private_data pointer
296  * are passed to \a func. Directories for which the calling process has no
297  * permissions to change to are silently ignored.
298  *
299  * \return Standard.
300  */
301 static int for_each_file_in_dir(const char *dirname,
302                 int (*func)(const char *, void *), void *private_data)
303 {
304         DIR *dir;
305         struct dirent *entry;
306         int cwd_fd, ret2, ret = fsck_opendir(dirname, &dir, &cwd_fd);
307
308         if (ret < 0)
309                 return ret == -E_FSCK_ACCESS? 1 : ret;
310         /* scan cwd recursively */
311         while ((entry = readdir(dir))) {
312                 mode_t m;
313                 char *tmp;
314                 struct stat s;
315
316                 if (!strcmp(entry->d_name, "."))
317                         continue;
318                 if (!strcmp(entry->d_name, ".."))
319                         continue;
320                 if (lstat(entry->d_name, &s) == -1)
321                         continue;
322                 m = s.st_mode;
323                 if (!S_ISREG(m) && !S_ISDIR(m))
324                         continue;
325                 tmp = make_message("%s/%s", dirname, entry->d_name);
326                 if (!S_ISDIR(m)) {
327                         ret = func(tmp, private_data);
328                         free(tmp);
329                         if (ret < 0)
330                                 goto out;
331                         continue;
332                 }
333                 /* directory */
334                 ret = for_each_file_in_dir(tmp, func, private_data);
335                 free(tmp);
336                 if (ret < 0)
337                         goto out;
338         }
339         ret = 1;
340 out:
341         closedir(dir);
342         ret2 = __fchdir(cwd_fd);
343         if (ret2 < 0 && ret >= 0)
344                 ret = ret2;
345         close(cwd_fd);
346         return ret;
347 }
348
349 /*
350  * check for object boundary violations
351  *
352  * test whether the range pointed to by the index entry for a given cell is
353  * contained in mapped data file. This should always be the case. Otherwise
354  * we are in real trouble.
355  */
356 static int check_range(struct osl_table *t, uint32_t row_num, uint32_t col_num)
357 {
358         char *index_entry;
359         struct osl_object obj;
360         struct osl_column *col;
361         int ret;
362         char *map_start, *obj_start;
363
364         ret = get_cell_index(t, row_num, col_num, &index_entry);
365         if (ret < 0)
366                 return ret;
367         ret = get_mapped_object(t, col_num, row_num, &obj);
368         if (ret < 0)
369                 return ret;
370         col = t->columns + col_num;
371         obj_start = obj.data;
372         map_start = col->data_map.data;
373 //      INFO_LOG("obj: %p..%p\n", obj_start, obj_start + obj.size);
374 //      INFO_LOG("map: %p..%p\n", map_start, map_start + col->data_map.size);
375         if (obj_start < map_start || obj_start + obj.size > map_start + col->data_map.size) {
376                 CRIT_LOG("range violation in row %u, col %u\n", row_num,
377                         col_num);
378                 return -E_FSCK_RANGE_VIOLATION;
379         }
380         DEBUG_LOG("col %u: ok\n", col_num);
381         return 1;
382 }
383
384 static int fsck_mark_row_invalid(struct osl_table *t, int i)
385 {
386         if (OPT_GIVEN(DRY_RUN))
387                 return 0;
388         return mark_row_invalid(t, i);
389 }
390
391 /*
392  * check all cells of the given table for boundary violations
393  */
394 static int check_index_ranges(struct osl_table *t)
395 {
396         int i, j, ret;
397
398         INFO_LOG("checking for range violations in index\n");
399         //DEBUG_LOG("%d rows. %d columns\n", t->num_rows, t->desc->num_columns);
400         t->num_invalid_rows = 0;
401         for (i = 0; i < t->num_rows; i++) {
402                 const struct osl_column_description *cd;
403
404                 if (row_is_invalid(t, i)) {
405                         t->num_invalid_rows++;
406                         continue;
407                 }
408                 FOR_EACH_MAPPED_COLUMN(j, t, cd) {
409                         ret = check_range(t, i, j);
410                         if (ret < 0) {
411                                 if (ret != -E_FSCK_RANGE_VIOLATION)
412                                         goto err;
413                                 ret = fsck_mark_row_invalid(t, i);
414                                 if (ret < 0)
415                                         goto err;
416                                 t->num_invalid_rows++;
417                                 break;
418                         }
419                 }
420
421         }
422         if (t->num_invalid_rows)
423                 NOTICE_LOG("ranges OK. %d invalid row(s) detected\n",
424                         t->num_invalid_rows);
425         else
426                 INFO_LOG("no invalid rows, no range violations, good\n");
427         return 1;
428 err:
429         return ret;
430 }
431
432 static int move_index_entry(struct osl_table *t, uint32_t dest, uint32_t src)
433 {
434         char *dest_ie, *src_ie;
435         int ret = get_row_index(t, dest, &dest_ie);
436
437         if (ret < 0)
438                 return ret;
439         ret = get_row_index(t, src, &src_ie);
440         if (ret < 0)
441                 return ret;
442         INFO_LOG("moving entry #%u to position %u\n", src, dest);
443         memcpy(dest_ie, src_ie, t->row_index_size);
444         return 1;
445 }
446
447 static int map_index(const struct osl_table_description *desc, struct osl_object *map)
448 {
449         char *filename = index_filename(desc);
450         int ret;
451
452         ret = mmap_full_file(filename, O_RDWR, &map->data, &map->size, NULL);
453         DEBUG_LOG("mapping index %s: ret: %d, size: %zu\n", filename, ret, map->size);
454         free(filename);
455         return ret;
456 }
457
458 static int prune_invalid_rows_from_index(struct osl_table *t)
459 {
460         uint32_t top = 0, bottom;
461         char *filename;
462         int ret;
463
464         if (!t->num_invalid_rows) {
465                 INFO_LOG("all rows are valid, good\n");
466                 return 1;
467         }
468         NOTICE_LOG("index contains %u invalid row(s) (%d bytes)\n",
469                 t->num_invalid_rows, t->row_index_size * t->num_invalid_rows);
470         if (OPT_GIVEN(DRY_RUN))
471                 return 0;
472         NOTICE_LOG("removing invalid rows from index\n");
473         bottom = t->num_rows - 1;
474         while (top < bottom) {
475                 if (!row_is_invalid(t, top)) {
476                         top++;
477                         continue;
478                 }
479                 while (bottom > top) {
480                         if (row_is_invalid(t, bottom)) {
481                                 bottom--;
482                                 continue;
483                         }
484                         /* move bottom index entry to top */
485                         move_index_entry(t, top, bottom);
486                         bottom--;
487                         top++;
488                         break;
489                 }
490         }
491         DEBUG_LOG("unmapping index\n");
492         osl_munmap(t->index_map.data, t->index_map.size);
493         filename = index_filename(t->desc);
494         ret = truncate_file(filename, t->row_index_size
495                 * t->num_invalid_rows);
496         free(filename);
497         if (ret < 0)
498                 return ret;
499         ret = map_index(t->desc, &t->index_map);
500         if (ret < 0)
501                 return ret;
502         t->num_rows = table_num_rows(t);
503         return 1;
504 }
505
506 static int check_for_invalid_objects(struct osl_table *t, uint32_t **lost_bytes)
507 {
508         int i, j, ret;
509         const struct osl_column_description *cd;
510         uint32_t *loss = fsck_malloc(sizeof(uint32_t) * t->desc->num_columns);
511
512         INFO_LOG("looking for mapped objects not contained in index\n");
513         /* first count used bytes */
514         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
515                 loss[i] = t->columns[i].data_map.size;
516                 DEBUG_LOG("column %i data map: %zu bytes\n", i,
517                         t->columns[i].data_map.size);
518                 for (j = 0; j < t->num_rows; j++) {
519                         struct osl_object obj;
520                         ret = get_mapped_object(t, i, j, &obj);
521                         if (ret < 0)
522                                 goto err;
523                         loss[i] -= obj.size;
524                 }
525         }
526         ret = 0;
527         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
528                 if (loss[i]) {
529                         NOTICE_LOG("column %u contains %u lost bytes\n",
530                                 i, loss[i]);
531                         ret = 1;
532                 }
533         }
534         if (!ret)
535                 INFO_LOG("all mapped objects are valid, good\n");
536         *lost_bytes = loss;
537         return ret;
538 err:
539         free(loss);
540         return ret;
541 }
542
543 /* prune_invalid_rows() must be run on the table before calling this */
544 static int prune_mapped_column(struct osl_table *t, uint32_t col_num, int fd)
545 {
546         int i, ret;
547         uint32_t written = 0;
548         struct osl_column *col = t->columns + col_num;
549
550         INFO_LOG("pruning col %u\n", col_num);
551         for (i = 0; i < t->num_rows; i++) {
552                 struct osl_object obj;
553                 char *index_entry;
554
555                 DEBUG_LOG("checking row %u/%u\n", i, t->num_rows);
556                 ret = get_mapped_object(t, col_num, i, &obj);
557                 if (ret < 0)
558                         return ret;
559                 ret = _write_all(fd, (char *)(obj.data), obj.size);
560                 if (ret < 0)
561                         return ret;
562                 written += obj.size;
563                 ret = get_row_index(t, i, &index_entry);
564                 if (ret < 0)
565                         return ret;
566                 update_cell_index(index_entry, col, written, obj.size);
567         }
568         return 1;
569 }
570
571 static int prune_objects(struct osl_table *t, uint32_t *lost_bytes)
572 {
573         int i, ret;
574         const struct osl_column_description *cd;
575         char **col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
576         char **new_col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
577         char *idx_filename = index_filename(t->desc);
578         char *old_idx_filename = make_message("%s.bak", idx_filename);
579         int fd;
580
581         NOTICE_LOG("removing unreferenced objects from data files\n");
582         /* first make a copy of the index */
583         DEBUG_LOG("opening %s\n", old_idx_filename);
584         ret = osl_open(old_idx_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
585         if (ret < 0)
586                 goto out_free;
587         fd = ret;
588         ret = _write_all(fd, t->index_map.data, t->index_map.size);
589         close(fd);
590         if (ret < 0)
591                 goto out_free;
592         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
593                 if (!lost_bytes[i])
594                         continue;
595                 col_filenames[i] = column_filename(t, i);
596                 new_col_filenames[i] = make_message("%s.fsck", col_filenames[i]);
597                 ret = osl_open(new_col_filenames[i], O_WRONLY | O_CREAT | O_EXCL, 0644);
598                 if (ret < 0)
599                         goto out_unlink_data;
600                 fd = ret;
601                 ret = prune_mapped_column(t, i, fd);
602                 close(fd);
603                 if (ret < 0)
604                         goto out_unlink_data;
605         }
606         ret = unmap_table(t, OSL_MARK_CLEAN);
607         if (ret < 0)
608                 goto out_unlink_data;
609         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
610                 if (!lost_bytes[i])
611                         continue;
612                 ret = osl_rename(new_col_filenames[i], col_filenames[i]);
613                 if (ret < 0) { /* we're kinda screwed here */
614                         CRIT_LOG("rename of col %i failed: %s\n", i,
615                                 osl_strerror(errno));
616                         goto out_free;
617                 }
618         }
619         unlink(old_idx_filename);
620         ret = map_table(t, 0);
621         goto out_free;
622 out_unlink_data:
623         FOR_EACH_MAPPED_COLUMN(i, t, cd)
624                 unlink(new_col_filenames[i]);
625 out_free:
626         free(old_idx_filename);
627         free(idx_filename);
628         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
629                 free(col_filenames[i]);
630                 free(new_col_filenames[i]);
631         }
632         free(col_filenames);
633         free(new_col_filenames);
634         return ret;
635 }
636
637 static struct osl_column_description hash_tree_table_cols[] = {
638         {
639                 .storage_type = OSL_NO_STORAGE,
640                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
641                 .name = "hash",
642                 .compare_function = uint32_compare,
643                 .data_size = HASH_SIZE
644         },
645 };
646
647 static const struct osl_table_description hash_tree_table_desc = {
648         .dir = "/", /* irrelevant */
649         .name = "hash_tree",
650         .num_columns = 1,
651         .flags = 0,
652         .column_descriptions = hash_tree_table_cols
653 };
654
655 /**
656  * The hash_tree table contains all hashes of the disk storage name column.
657  * of each row. It is used for checking if a disk storage file has a reference
658  * in the table.
659  */
660 static struct osl_table *hash_tree_table;
661 static HASH_TYPE *hashes;
662
663 static int check_disk_storage_column(struct osl_table *t, int row_num,
664                 int col_num, char *ds_name, unsigned *num_missing_objects)
665 {
666         int ret;
667         struct stat statbuf;
668         char *path = disk_storage_path(t, col_num, ds_name);
669         unsigned dsnc = t->disk_storage_name_column;
670         struct osl_object obj;
671
672         DEBUG_LOG("checking if %s is a regular file\n", path);
673         ret = stat(path, &statbuf);
674         if (ret < 0 && errno == ENOENT) {
675                 struct osl_row *row;
676                 (*num_missing_objects)++;
677                 ERROR_LOG("row %d: object %s is missing\n", row_num, path);
678                 ret = 0;
679                 if (OPT_GIVEN(DRY_RUN))
680                         goto out;
681                 NOTICE_LOG("trying to delete row %d\n", row_num);
682                 ret = osl_get_row(t, dsnc, &obj, &row);
683                 if (ret < 0) {
684                         CRIT_LOG("unable to get row %d\n", row_num);
685                         fsck_mark_row_invalid(t, row_num);
686                         CRIT_LOG("Please re-run fsck\n");
687                         goto out;
688                 }
689                 ret = osl_del_row(t, row);
690                 if (ret < 0)
691                         goto out;
692         }
693 out:
694         free(path);
695         if (ret < 0)
696                 return ret;
697         ret = -E_FSCK_NOT_A_REGULAR_FILE;
698         if (!(S_IFREG & statbuf.st_mode))
699                 return ret;
700         return 1;
701 }
702
703 static int check_disk_storage_presence(struct osl_table *t)
704 {
705         int ret, i, j;
706         struct osl_object obj, hash_obj = {.size = HASH_SIZE};
707         char *ds_name;
708         const struct osl_column_description *cd;
709         unsigned dsnc = t->disk_storage_name_column, missing_objects = 0;
710
711         if (!t->num_rows)
712                 return 1;
713         hashes = fsck_malloc(t->num_rows * HASH_SIZE);
714         INFO_LOG("looking for missing disk storage objects\n");
715         for (i = 0; i < t->num_rows; i++) {
716                 if (row_is_invalid(t, i))
717                         continue;
718                 ret = get_mapped_object(t, dsnc, i, &obj);
719                 if (ret < 0)
720                         return ret;
721                 hash_object(&obj, hashes + i * HASH_SIZE);
722                 hash_obj.data = hashes + i * HASH_SIZE;
723                 osl_add_row(hash_tree_table, &hash_obj);
724                 ds_name = disk_storage_name_of_hash(t, hashes + i * HASH_SIZE);
725                 FOR_EACH_DISK_STORAGE_COLUMN(j, t, cd) {
726                         ret = check_disk_storage_column(t, i, j, ds_name,
727                                 &missing_objects);
728                         if (ret < 0)
729                                 goto err;
730                 }
731                 free(ds_name);
732         }
733         if (!missing_objects)
734                 INFO_LOG("all referenced disk storage objects exist, good\n");
735         else
736                 NOTICE_LOG("%d missing object(s)\n", missing_objects);
737         return missing_objects;
738 err:
739         free(ds_name);
740         return ret;
741 }
742
743 static int dummy_compare(const struct osl_object *obj1, const struct osl_object *obj2)
744 {
745         if (obj1 < obj2)
746                 return -1;
747         if (obj1 > obj2)
748                 return 1;
749         return 0;
750 }
751
752 static unsigned files_pruned;
753
754 static int prune_disk_storage_file(const char *path, void *private_data)
755 {
756         HASH_TYPE hash[HASH_SIZE];
757         uint8_t flags = *(uint8_t *)private_data;
758         struct osl_object obj = {.data = hash, .size = HASH_SIZE};
759         struct osl_row *row;
760         int ret = -1;
761         size_t len = strlen(path);
762
763
764         DEBUG_LOG("path: %s\n", path);
765         if (flags & OSL_LARGE_TABLE) {
766                 if (len < HASH_SIZE * 2 + 2)
767                         goto invalid;
768 //              NOTICE_LOG("p: %s\n", path + len - 2 * HASH_SIZE - 1);
769                 ret = asc_to_hash(path + len - 2 * HASH_SIZE - 1, 1, hash);
770                 if (ret < 0)
771                         goto invalid;
772                 ret = asc_to_hash(path + len - 2 * HASH_SIZE + 2, HASH_SIZE - 1,
773                         hash + 1);
774                 if (ret < 0)
775                         goto invalid;
776 //              INFO_LOG("high: %x, low: %x, hash: %x\n", high, low, hash);
777         } else {
778                 if (len < 2 * HASH_SIZE + 1)
779                         goto invalid;
780                 ret = asc_to_hash(path + len - 2 * HASH_SIZE, 2 * HASH_SIZE, hash);
781                 if (ret < 0)
782                         goto invalid;
783 //              INFO_LOG("hash: %x\n", hash);
784         }
785 #if 0
786 {
787         char asc[2 * HASH_SIZE + 1];
788         hash_to_asc(hash, asc);
789         NOTICE_LOG("before: %s\nafter: %s\n", path, asc);
790 }
791 #endif
792         ret = osl_get_row(hash_tree_table, 0, &obj, &row);
793         if (ret >= 0)
794                 return 1;
795         NOTICE_LOG("unreferenced file in hash dir: %s\n", path);
796         goto remove;
797 invalid:
798         ERROR_LOG("could not read hash value of %s\n", path);
799 remove:
800         if (OPT_GIVEN(DRY_RUN))
801                 return 0;
802         NOTICE_LOG("removing %s\n", path);
803         unlink(path);
804         files_pruned++;
805         return 1;
806 }
807
808 static int prune_disk_storage_files(struct osl_table *t)
809 {
810         int i, ret = 1;
811         const struct osl_column_description *cd;
812
813         INFO_LOG("looking for unreferenced disk storage files\n");
814         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
815                 char *dirname = column_filename(t, i);
816                 uint8_t flags = t->desc->flags;
817                 ret = for_each_file_in_dir(dirname, prune_disk_storage_file,
818                         &flags);
819                 free(dirname);
820         }
821         if (files_pruned)
822                 NOTICE_LOG("%u disk storage files deleted\n",
823                         files_pruned);
824         else
825                 INFO_LOG("all files are are referenced, good\n");
826         return ret;
827 }
828
829 static int check_disk_storage_columns(struct osl_table *t)
830 {
831         int ret, i;
832         const struct osl_column_description *cd;
833
834         if (!t->num_disk_storage_columns) {
835                 INFO_LOG("no disk storage columns in table '%s', "
836                         "skipping checks\n", t->desc->name);
837                 return 1;
838         }
839         FOR_EACH_COLUMN(i, t->desc, cd)
840                 t->desc->column_descriptions[i].compare_function = dummy_compare;
841         ret = init_rbtrees(t);
842         if (ret < 0)
843                 return ret;
844         INFO_LOG("creating rbtree for disk storage hash values\n");
845         ret = osl_open_table(&hash_tree_table_desc, &hash_tree_table);
846         if (ret < 0)
847                 goto out;
848         ret = check_disk_storage_presence(t);
849         if (ret < 0)
850                 goto out_close_hash_tree;
851         ret = prune_disk_storage_files(t);
852 out_close_hash_tree:
853         osl_close_table(hash_tree_table, 0);
854         free(hashes);
855         hashes = NULL;
856 out:
857         clear_rbtrees(t); /* TODO why are we doing that here? Seems odd */
858         return ret;
859 }
860
861 static void set_dummy_contents(struct osl_table_description *desc)
862 {
863         int i;
864         struct osl_column_description *cd;
865
866         for (i = 0; i < desc->num_columns; i++) {
867                 cd = get_column_description(desc, i);
868                 cd->compare_function = dummy_compare;
869         }
870 }
871
872 static int fsck_init(struct osl_table_description *desc, struct osl_table **t)
873 {
874         struct osl_object map;
875         int ret = map_index(desc, &map);
876
877         if (ret < 0)
878                 goto out;
879         ret = read_table_desc(&map, desc);
880         if (ret < 0) {
881                 osl_munmap(map.data, map.size);
882                 goto out;
883         }
884         set_dummy_contents(desc);
885         ret = init_table_structure(desc, t);
886         if (ret < 0) {
887                 osl_munmap(map.data, map.size);
888                 goto out;
889         }
890         DEBUG_LOG("unmapping index\n");
891         osl_munmap(map.data, map.size);
892         if (OPT_GIVEN(FORCE))
893                 ret = map_table(*t, (MAP_TBL_FL_IGNORE_DIRTY));
894         else
895                 ret = map_table(*t, 0);
896         if (ret >= 0) {
897                 (*t)->num_rows = table_num_rows(*t);
898                 DEBUG_LOG("index header size: %d\n", (*t)->index_header_size);
899                 DEBUG_LOG("row index size: %d\n", (*t)->row_index_size);
900         }
901 out:
902         return ret;
903 }
904
905 static void fsck_cleanup(struct osl_table *t)
906 {
907         int i;
908
909         if (!t)
910                 return;
911         if (t->desc->column_descriptions) {
912                 struct osl_column_description *cd;
913                 for (i = 0; i < t->desc->num_columns; i++) {
914                         cd = get_column_description(t->desc, i);
915                         free((char*)cd->name);
916                 }
917                 free(t->desc->column_descriptions);
918         }
919         free(t->columns);
920         free(t);
921
922 }
923
924 #define ST_CASE(st) case st: return #st
925
926 static const char *get_asc_storage_type(enum osl_storage_type st)
927 {
928         switch (st) {
929                 ST_CASE(OSL_MAPPED_STORAGE);
930                 ST_CASE(OSL_DISK_STORAGE);
931                 ST_CASE(OSL_NO_STORAGE);
932         }
933         return NULL;
934 }
935
936 #define APPEND_ASC_SF(sf, flag, str) do { if (sf & flag) { \
937         if (str) str = make_message("%s%s", str, " | " # flag); \
938         else str = fsck_strdup(#flag); }} while (0)
939
940
941 static char *get_asc_storage_flags(enum osl_storage_type sf)
942 {
943         char *asc_sf = NULL;
944
945         APPEND_ASC_SF(sf, OSL_RBTREE, asc_sf);
946         APPEND_ASC_SF(sf, OSL_FIXED_SIZE, asc_sf);
947         APPEND_ASC_SF(sf, OSL_UNIQUE, asc_sf);
948         return asc_sf;
949 }
950
951 static int dump_table_desc(struct osl_table *t, int fd)
952 {
953         const struct osl_table_description *desc = t->desc;
954         int ret, i;
955         struct osl_column_description *cd;
956         char *msg = make_message("static struct osl_column_description cols[] = {\n");
957         ret = _write_all(fd, msg, strlen(msg));
958         if (ret < 0)
959                 return ret;
960         free(msg);
961         FOR_EACH_COLUMN(i, desc, cd) {
962                 const char *asc_st;
963                 msg = make_message("\t[%d] = {\n", i);
964                 ret = _write_all(fd, msg, strlen(msg));
965                 if (ret < 0)
966                         return ret;
967                 free(msg);
968                 asc_st = get_asc_storage_type(cd->storage_type);
969                 msg = make_message("\t\t.storage_type = %s,\n", asc_st);
970                 ret = _write_all(fd, msg, strlen(msg));
971                 if (ret < 0)
972                         return ret;
973                 free(msg);
974                 if (cd->storage_flags) {
975                         char *asc_sf = get_asc_storage_flags(cd->storage_flags);
976                         msg = make_message("\t\t,storage_flags = %s,\n", asc_sf);
977                         free(asc_sf);
978                         ret = _write_all(fd, msg, strlen(msg));
979                         if (ret < 0)
980                                 return ret;
981                         free(msg);
982                 }
983                 if (cd->storage_flags & OSL_FIXED_SIZE) {
984                         msg = make_message("\t\t.data_size = %u,\n", cd->data_size);
985                         ret = _write_all(fd, msg, strlen(msg));
986                         if (ret < 0)
987                                 return ret;
988                         free(msg);
989                 }
990                 msg = make_message("\t\t.name = \"%s\",\n", cd->name);
991                 ret = _write_all(fd, msg, strlen(msg));
992                 if (ret < 0)
993                         return ret;
994                 free(msg);
995                 if (cd->storage_flags & OSL_RBTREE) {
996                         msg = make_message("\t\t.compare_function = compare_func,\n");
997                         ret = _write_all(fd, msg, strlen(msg));
998                         if (ret < 0)
999                                 return ret;
1000                         free(msg);
1001                 }
1002                 msg = make_message("\t},\n");
1003                 ret = _write_all(fd, msg, strlen(msg));
1004                 if (ret < 0)
1005                         return ret;
1006                 free(msg);
1007         }
1008         msg = make_message("};\n");
1009         ret = _write_all(fd, msg, strlen(msg));
1010         if (ret < 0)
1011                 return ret;
1012         free(msg);
1013         return 1;
1014 }
1015
1016 static int dump_row(struct osl_table *t, unsigned row_num, const char *row_dir)
1017 {
1018         int ret, i;
1019         const struct osl_column_description *cd;
1020         unsigned dsnc;
1021         struct osl_object obj;
1022         char *ds_name;
1023         HASH_TYPE hash[HASH_SIZE];
1024         char *filename;
1025
1026         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
1027                 ret = get_mapped_object(t, i, row_num, &obj);
1028                 if (ret < 0)
1029                         return ret;
1030                 filename = make_message("%s/col_%03u", row_dir, i);
1031                 ret = write_file(filename, obj.data, obj.size);
1032                 free(filename);
1033                 if (ret < 0)
1034                         return ret;
1035         }
1036         if (!t->num_disk_storage_columns)
1037                 return 1;
1038         dsnc = t->disk_storage_name_column;
1039         ret = get_mapped_object(t, dsnc, row_num, &obj);
1040         if (ret < 0)
1041                 return ret;
1042         hash_object(&obj, hash);
1043         ds_name = disk_storage_name_of_hash(t, hash);
1044         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
1045                 filename = disk_storage_path(t, i, ds_name);
1046                 ret = mmap_full_file(filename, O_RDONLY, &obj.data, &obj.size, NULL);
1047                 free(filename);
1048                 if (ret < 0)
1049                         goto out;
1050                 filename = make_message("%s/col_%03u", row_dir, i);
1051                 ret = write_file(filename, obj.data, obj.size);
1052                 free(filename);
1053                 if (ret < 0)
1054                         goto out;
1055         }
1056         ret = 1;
1057 out:
1058         free(ds_name);
1059         return ret;
1060 }
1061
1062 static int dump_rows(char *dump_dir, struct osl_table *t)
1063 {
1064         unsigned i;
1065         char *current_dir = NULL;
1066         int ret = 0;
1067
1068         for (i = 0; i < t->num_rows; i++) {
1069                 char *row_dir;
1070                 if (row_is_invalid(t, i))
1071                         continue;
1072                 if (!(i % 1000)) {
1073                         free(current_dir);
1074                         current_dir = make_message("%s/rows_%u-%u", dump_dir, i, i + 999);
1075                         NOTICE_LOG("dumping rows %u - %u\n", i, i + 999);
1076                         ret = osl_mkdir(current_dir, 0777);
1077                         if (ret < 0 && ret != -E_OSL_DIR_EXISTS)
1078                                 goto out;
1079                 }
1080                 row_dir = make_message("%s/row_%03u", current_dir, i);
1081                 ret = osl_mkdir(row_dir, 0777);
1082                 if (ret < 0 && ret != -E_OSL_DIR_EXISTS) {
1083                         free(row_dir);
1084                         goto out;
1085                 }
1086                 ret = dump_row(t, i, row_dir);
1087                 free(row_dir);
1088                 if (ret < 0)
1089                         goto out;
1090         }
1091 out:
1092         free(current_dir);
1093         return ret;
1094 }
1095
1096 static int dump_table(const char *dump_dir, struct osl_table_description *desc)
1097 {
1098         struct osl_table *t = NULL;
1099         int fd, ret = fsck_init(desc, &t);
1100         char *desc_file;
1101         char *table_dump_dir = NULL;
1102
1103         if (ret < 0)
1104                 goto out;
1105         ret = osl_mkdir(dump_dir, 0777);
1106         if (ret < 0 && ret != -E_OSL_DIR_EXISTS)
1107                 goto out;
1108         table_dump_dir = make_message("%s/%s", dump_dir, desc->name);
1109         ret = osl_mkdir(table_dump_dir, 0777);
1110         if (ret < 0 && ret != -E_OSL_DIR_EXISTS)
1111                 goto out;
1112         desc_file = make_message("%s/table_description.c", table_dump_dir);
1113         ret = osl_open(desc_file, O_WRONLY | O_CREAT | O_EXCL, 0644);
1114         free(desc_file);
1115         if (ret < 0)
1116                 goto out;
1117         fd = ret;
1118         ret = dump_table_desc(t, fd);
1119         close(fd);
1120         if (ret < 0)
1121                 goto out;
1122         ret = dump_rows(table_dump_dir, t);
1123 out:
1124         free(table_dump_dir);
1125         fsck_cleanup(t);
1126         return ret;
1127 }
1128
1129 static int fsck(struct osl_table_description *desc)
1130 {
1131         int ret;
1132         struct osl_table *t = NULL;
1133         uint32_t *lost_bytes = NULL;
1134
1135         ret = fsck_init(desc, &t);
1136         if (ret < 0)
1137                 goto out;
1138         ret = check_index_ranges(t);
1139         if (ret < 0)
1140                 goto out_unmap;
1141         ret = check_disk_storage_columns(t);
1142         if (ret < 0)
1143                 goto out_unmap;
1144         ret = prune_invalid_rows_from_index(t);
1145         if (ret < 0)
1146                 goto out_unmap;
1147         ret = check_for_invalid_objects(t, &lost_bytes);
1148         if (ret < 0)
1149                 goto out_unmap;
1150         if (ret > 0 && !OPT_GIVEN(DRY_RUN)) {
1151                 /* at least one mapped data file needs pruning */
1152                 ret = prune_objects(t, lost_bytes);
1153                 if (ret < 0)
1154                         goto out_unmap;
1155         }
1156         free(lost_bytes);
1157 out_unmap:
1158         unmap_table(t, OSL_MARK_CLEAN);
1159 out:
1160         fsck_cleanup(t);
1161         return ret;
1162 }
1163
1164 static int check_table(const char *db_dir, const char *table_name)
1165 {
1166         struct osl_table_description desc = {
1167                 .column_descriptions = NULL,
1168                 .dir = db_dir,
1169                 .name = table_name
1170         };
1171         int ret;
1172
1173         INFO_LOG("checking table %s\n", table_name);
1174         if (!OPT_GIVEN(NO_FSCK)) {
1175                 ret = fsck(&desc);
1176                 if (ret < 0)
1177                         goto out;
1178         }
1179         ret = 1;
1180         if (!OPT_GIVEN(DUMP_DIR) || !*OPT_STRING_VAL(DUMP_DIR))
1181                 goto out;
1182         ret = dump_table(OPT_STRING_VAL(DUMP_DIR), &desc);
1183 out:
1184         if (ret < 0)
1185                 ERROR_LOG("failed to check table %s: %s\n", table_name,
1186                         fsck_strerror(-ret));
1187         else
1188                 NOTICE_LOG("successfully checked table %s\n", table_name);
1189         return ret;
1190 }
1191
1192 static int check_all_tables(const char *db_dir)
1193 {
1194         DIR *dir;
1195         struct dirent *entry;
1196         int cwd_fd, ret2, ret = fsck_opendir(db_dir, &dir, &cwd_fd);
1197
1198         if (ret < 0)
1199                 return ret;
1200         while ((entry = readdir(dir))) {
1201                 mode_t m;
1202                 struct stat s;
1203                 if (!strcmp(entry->d_name, "."))
1204                         continue;
1205                 if (!strcmp(entry->d_name, ".."))
1206                         continue;
1207                 if (lstat(entry->d_name, &s) == -1)
1208                         continue;
1209                 m = s.st_mode;
1210                 if (!S_ISDIR(m))
1211                         continue;
1212                 ret = check_table(db_dir, entry->d_name);
1213                 if (ret < 0)
1214                         break;
1215         }
1216         closedir(dir);
1217         ret2 = __fchdir(cwd_fd);
1218         if (ret2 < 0 && ret >= 0)
1219                 ret = ret2;
1220         close(cwd_fd);
1221         return ret;
1222 }
1223
1224 int main(int argc, char **argv)
1225 {
1226         int i, ret;
1227         char *errctx = NULL;
1228         const char *dd;
1229
1230         loglevel = 0;
1231         ret = lls_parse(argc, argv, CMD_PTR, &lpr, &errctx);
1232         if (ret < 0) {
1233                 if (errctx)
1234                         ERROR_LOG("%s\n", errctx);
1235                 EMERG_LOG("%s\n", lls_strerror(-ret));
1236                 exit(EXIT_FAILURE);
1237         }
1238         loglevel = OPT_UINT32_VAL(LOGLEVEL);
1239         if (OPT_GIVEN(DETAILED_HELP)) {
1240                 printf("%s\n", lls_long_help(CMD_PTR));
1241                 exit(EXIT_SUCCESS);
1242         }
1243         if (OPT_GIVEN(HELP)) {
1244                 printf("%s\n", lls_short_help(CMD_PTR));
1245                 exit(EXIT_SUCCESS);
1246         }
1247         if (OPT_GIVEN(VERSION)) {
1248                 printf(
1249                         "oslfsck " OSL_VERSION "\n"
1250                         "Copyright (C) 2008-2009 Andre Noll\n"
1251                         "This is free software with ABSOLUTELY NO WARRANTY."
1252                         " See COPYING for details.\n"
1253                         "Written by Andre Noll.\n"
1254                         "Report bugs to <maan@tuebingen.mpg.de>.\n"
1255                 );
1256                 exit(EXIT_SUCCESS);
1257         }
1258         dd = OPT_STRING_VAL(DATABASE_DIR);
1259         if (!dd) {
1260                 EMERG_LOG("--database-dir: mandatory option not given\n");
1261                 exit(EXIT_FAILURE);
1262         }
1263         INFO_LOG("database dir: %s\n", dd);
1264         if (lls_num_inputs(lpr) == 0) {
1265                 ret = check_all_tables(dd);
1266                 goto out;
1267         }
1268         for (i = 0; i < lls_num_inputs(lpr); i++) {
1269                 ret = check_table(dd, lls_input(i, lpr));
1270                 if (ret < 0)
1271                         break;
1272         }
1273 out:
1274         if (ret < 0) {
1275                 ERROR_LOG("%s\n", fsck_strerror(-ret));
1276                 if (loglevel > 1)
1277                         EMERG_LOG("re-run with \"--loglevel %d\" to increase verbosity\n",
1278                                 loglevel - 1);
1279         } else
1280                 NOTICE_LOG("success\n");
1281         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1282 }