]> git.sven.stormbind.net Git - sven/exfatprogs.git/blob - fsck/fsck.c
2485d2e433d7b1cd3f794f9a5ce64d17570a89ab
[sven/exfatprogs.git] / fsck / fsck.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2019 Namjae Jeon <linkinjeon@kernel.org>
4  *   Copyright (C) 2020 Hyunchul Lee <hyc.lee@gmail.com>
5  */
6
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <getopt.h>
11 #include <inttypes.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <locale.h>
15
16 #include "exfat_ondisk.h"
17 #include "libexfat.h"
18 #include "fsck.h"
19 #include "repair.h"
20
21 struct fsck_user_input {
22         struct exfat_user_input         ei;
23         enum fsck_ui_options            options;
24 };
25
26 #define EXFAT_MAX_UPCASE_CHARS  0x10000
27
28 #ifdef WORDS_BIGENDIAN
29 typedef __u8    bitmap_t;
30 #else
31 typedef __u32   bitmap_t;
32 #endif
33
34 #define BITS_PER        (sizeof(bitmap_t) * 8)
35 #define BIT_MASK(__c)   (1 << ((__c) % BITS_PER))
36 #define BIT_ENTRY(__c)  ((__c) / BITS_PER)
37
38 #define EXFAT_BITMAP_SIZE(__c_count)    \
39         (DIV_ROUND_UP(__c_count, BITS_PER) * sizeof(bitmap_t))
40 #define EXFAT_BITMAP_GET(__bmap, __c)   \
41                         (((bitmap_t *)(__bmap))[BIT_ENTRY(__c)] & BIT_MASK(__c))
42 #define EXFAT_BITMAP_SET(__bmap, __c)   \
43                         (((bitmap_t *)(__bmap))[BIT_ENTRY(__c)] |= \
44                          BIT_MASK(__c))
45
46 #define FSCK_EXIT_NO_ERRORS             0x00
47 #define FSCK_EXIT_CORRECTED             0x01
48 #define FSCK_EXIT_NEED_REBOOT           0x02
49 #define FSCK_EXIT_ERRORS_LEFT           0x04
50 #define FSCK_EXIT_OPERATION_ERROR       0x08
51 #define FSCK_EXIT_SYNTAX_ERROR          0x10
52 #define FSCK_EXIT_USER_CANCEL           0x20
53 #define FSCK_EXIT_LIBRARY_ERROR         0x80
54
55 struct exfat_stat {
56         long            dir_count;
57         long            file_count;
58         long            error_count;
59         long            fixed_count;
60 };
61
62 struct path_resolve_ctx {
63         struct exfat_inode      *ancestors[255];
64         __le16                  utf16_path[PATH_MAX + 2];
65         char                    local_path[PATH_MAX * MB_LEN_MAX + 1];
66 };
67
68 struct exfat_stat exfat_stat;
69 struct path_resolve_ctx path_resolve_ctx;
70
71 static struct option opts[] = {
72         {"repair",      no_argument,    NULL,   'r' },
73         {"repair-yes",  no_argument,    NULL,   'y' },
74         {"repair-no",   no_argument,    NULL,   'n' },
75         {"repair-auto", no_argument,    NULL,   'p' },
76         {"version",     no_argument,    NULL,   'V' },
77         {"verbose",     no_argument,    NULL,   'v' },
78         {"help",        no_argument,    NULL,   'h' },
79         {"?",           no_argument,    NULL,   '?' },
80         {NULL,          0,              NULL,    0  }
81 };
82
83 static void usage(char *name)
84 {
85         fprintf(stderr, "Usage: %s\n", name);
86         fprintf(stderr, "\t-r | --repair        Repair interactively\n");
87         fprintf(stderr, "\t-y | --repair-yes    Repair without ask\n");
88         fprintf(stderr, "\t-n | --repair-no     No repair\n");
89         fprintf(stderr, "\t-p | --repair-auto   Repair automatically\n");
90         fprintf(stderr, "\t-V | --version       Show version\n");
91         fprintf(stderr, "\t-v | --verbose       Print debug\n");
92         fprintf(stderr, "\t-h | --help          Show help\n");
93
94         exit(FSCK_EXIT_SYNTAX_ERROR);
95 }
96
97 #define fsck_err(parent, inode, fmt, ...)               \
98 ({                                                      \
99                 resolve_path_parent(&path_resolve_ctx,  \
100                         parent, inode);                 \
101                 exfat_err("ERROR: %s: " fmt,            \
102                         path_resolve_ctx.local_path,    \
103                         ##__VA_ARGS__);                 \
104 })
105
106 static struct exfat_inode *alloc_exfat_inode(__u16 attr)
107 {
108         struct exfat_inode *node;
109         int size;
110
111         size = offsetof(struct exfat_inode, name) + NAME_BUFFER_SIZE;
112         node = (struct exfat_inode *)calloc(1, size);
113         if (!node) {
114                 exfat_err("failed to allocate exfat_node\n");
115                 return NULL;
116         }
117
118         node->parent = NULL;
119         INIT_LIST_HEAD(&node->children);
120         INIT_LIST_HEAD(&node->sibling);
121         INIT_LIST_HEAD(&node->list);
122
123         node->last_pclus = EXFAT_EOF_CLUSTER;
124         node->attr = attr;
125         if (attr & ATTR_SUBDIR)
126                 exfat_stat.dir_count++;
127         else
128                 exfat_stat.file_count++;
129         return node;
130 }
131
132 static void free_exfat_inode(struct exfat_inode *node)
133 {
134         free(node);
135 }
136
137 static void inode_free_children(struct exfat_inode *dir, bool file_only)
138 {
139         struct exfat_inode *node, *i;
140
141         list_for_each_entry_safe(node, i, &dir->children, sibling) {
142                 if (file_only) {
143                         if (!(node->attr & ATTR_SUBDIR)) {
144                                 list_del(&node->sibling);
145                                 free_exfat_inode(node);
146                         }
147                 } else {
148                         list_del(&node->sibling);
149                         list_del(&node->list);
150                         free_exfat_inode(node);
151                 }
152         }
153 }
154
155 static void inode_free_file_children(struct exfat_inode *dir)
156 {
157         inode_free_children(dir, true);
158 }
159
160 /* delete @child and all ancestors that does not have
161  * children
162  */
163 static void inode_free_ancestors(struct exfat_inode *child)
164 {
165         struct exfat_inode *parent;
166
167         if (!list_empty(&child->children))
168                 return;
169
170         do {
171                 if (!(child->attr & ATTR_SUBDIR)) {
172                         exfat_err("not directory.\n");
173                         return;
174                 }
175
176                 parent = child->parent;
177                 list_del(&child->sibling);
178                 free_exfat_inode(child);
179
180                 child = parent;
181         } while (child && list_empty(&child->children));
182
183         return;
184 }
185
186 static void free_exfat(struct exfat *exfat)
187 {
188         int i;
189
190         if (exfat) {
191                 if (exfat->bs)
192                         free(exfat->bs);
193                 if (exfat->alloc_bitmap)
194                         free(exfat->alloc_bitmap);
195                 if (exfat->disk_bitmap)
196                         free(exfat->disk_bitmap);
197                 for (i = 0; i < 2; i++) {
198                         if (exfat->buffer_desc[i].buffer)
199                                 free(exfat->buffer_desc[i].buffer);
200                         if (exfat->buffer_desc[i].dirty)
201                                 free(exfat->buffer_desc[i].dirty);
202                 }
203                 free(exfat);
204         }
205 }
206
207 static int init_exfat(struct exfat *exfat, struct pbr *bs)
208 {
209         int i;
210
211         INIT_LIST_HEAD(&exfat->dir_list);
212         exfat->bs = bs;
213         exfat->clus_count = le32_to_cpu(bs->bsx.clu_count);
214         exfat->clus_size = EXFAT_CLUSTER_SIZE(bs);
215         exfat->sect_size = EXFAT_SECTOR_SIZE(bs);
216
217         /* TODO: bitmap could be very large. */
218         exfat->alloc_bitmap = (char *)calloc(1,
219                         EXFAT_BITMAP_SIZE(exfat->clus_count));
220         if (!exfat->alloc_bitmap) {
221                 exfat_err("failed to allocate bitmap\n");
222                 goto err;
223         }
224
225         exfat->disk_bitmap = (char *)malloc(
226                                 EXFAT_BITMAP_SIZE(exfat->clus_count));
227         if (!exfat->disk_bitmap) {
228                 exfat_err("failed to allocate bitmap\n");
229                 goto err;
230         }
231
232         /* allocate cluster buffers */
233         for (i = 0; i < 2; i++) {
234                 exfat->buffer_desc[i].buffer =
235                         (char *)malloc(exfat->clus_size);
236                 if (!exfat->buffer_desc[i].buffer)
237                         goto err;
238                 exfat->buffer_desc[i].dirty =
239                         (char *)calloc(
240                         (exfat->clus_size / exfat->sect_size), 1);
241                 if (!exfat->buffer_desc[i].dirty)
242                         goto err;
243         }
244         return 0;
245 err:
246         free_exfat(exfat);
247         return -ENOMEM;
248 }
249
250 static void exfat_free_dir_list(struct exfat *exfat)
251 {
252         struct exfat_inode *dir, *i;
253
254         list_for_each_entry_safe(dir, i, &exfat->dir_list, list) {
255                 inode_free_file_children(dir);
256                 list_del(&dir->list);
257                 free_exfat_inode(dir);
258         }
259 }
260
261 /*
262  * get references of ancestors that include @child until the count of
263  * ancesters is not larger than @count and the count of characters of
264  * their names is not larger than @max_char_len.
265  * return true if root is reached.
266  */
267 bool get_ancestors(struct exfat_inode *child,
268                 struct exfat_inode **ancestors, int count,
269                 int max_char_len,
270                 int *ancestor_count)
271 {
272         struct exfat_inode *dir;
273         int name_len, char_len;
274         int root_depth, depth, i;
275
276         root_depth = 0;
277         char_len = 0;
278         max_char_len += 1;
279
280         dir = child;
281         while (dir) {
282                 name_len = exfat_utf16_len(dir->name, NAME_BUFFER_SIZE);
283                 if (char_len + name_len > max_char_len)
284                         break;
285
286                 /* include '/' */
287                 char_len += name_len + 1;
288                 root_depth++;
289
290                 dir = dir->parent;
291         }
292
293         depth = MIN(root_depth, count);
294
295         for (dir = child, i = depth - 1; i >= 0; dir = dir->parent, i--)
296                 ancestors[i] = dir;
297
298         *ancestor_count = depth;
299         return dir == NULL;
300 }
301
302 static int resolve_path(struct path_resolve_ctx *ctx, struct exfat_inode *child)
303 {
304         int depth, i;
305         int name_len;
306         __le16 *utf16_path;
307         static const __le16 utf16_slash = cpu_to_le16(0x002F);
308         static const __le16 utf16_null = cpu_to_le16(0x0000);
309         size_t in_size;
310
311         ctx->local_path[0] = '\0';
312
313         get_ancestors(child,
314                         ctx->ancestors,
315                         sizeof(ctx->ancestors) / sizeof(ctx->ancestors[0]),
316                         PATH_MAX,
317                         &depth);
318
319         utf16_path = ctx->utf16_path;
320         for (i = 0; i < depth; i++) {
321                 name_len = exfat_utf16_len(ctx->ancestors[i]->name,
322                                 NAME_BUFFER_SIZE);
323                 memcpy((char *)utf16_path, (char *)ctx->ancestors[i]->name,
324                                 name_len * 2);
325                 utf16_path += name_len;
326                 memcpy((char *)utf16_path, &utf16_slash, sizeof(utf16_slash));
327                 utf16_path++;
328         }
329
330         if (depth > 0)
331                 utf16_path--;
332         memcpy((char *)utf16_path, &utf16_null, sizeof(utf16_null));
333         utf16_path++;
334
335         in_size = (utf16_path - ctx->utf16_path) * sizeof(__le16);
336         return exfat_utf16_dec(ctx->utf16_path, in_size,
337                                 ctx->local_path, sizeof(ctx->local_path));
338 }
339
340 static int resolve_path_parent(struct path_resolve_ctx *ctx,
341                         struct exfat_inode *parent, struct exfat_inode *child)
342 {
343         int ret;
344         struct exfat_inode *old;
345
346         old = child->parent;
347         child->parent = parent;
348
349         ret = resolve_path(ctx, child);
350         child->parent = old;
351         return ret;
352 }
353
354 #define repair_file_ask(iter, inode, code, fmt, ...)    \
355 ({                                                      \
356                 resolve_path_parent(&path_resolve_ctx,  \
357                                 (iter)->parent, inode); \
358                 exfat_repair_ask((iter)->exfat, code,   \
359                         "ERROR: %s: " fmt,              \
360                         path_resolve_ctx.local_path,    \
361                         ##__VA_ARGS__);                 \
362 })
363
364 static inline bool heap_clus(struct exfat *exfat, clus_t clus)
365 {
366         return clus >= EXFAT_FIRST_CLUSTER &&
367                 (clus - EXFAT_FIRST_CLUSTER) < exfat->clus_count;
368 }
369
370 int get_next_clus(struct exfat *exfat, struct exfat_inode *node,
371                                 clus_t clus, clus_t *next)
372 {
373         off_t offset;
374
375         *next = EXFAT_EOF_CLUSTER;
376
377         if (!heap_clus(exfat, clus))
378                 return -EINVAL;
379
380         if (node->is_contiguous) {
381                 *next = clus + 1;
382                 return 0;
383         }
384
385         offset = (off_t)le32_to_cpu(exfat->bs->bsx.fat_offset) <<
386                                 exfat->bs->bsx.sect_size_bits;
387         offset += sizeof(clus_t) * clus;
388
389         if (exfat_read(exfat->blk_dev->dev_fd, next, sizeof(*next), offset)
390                         != sizeof(*next))
391                 return -EIO;
392         *next = le32_to_cpu(*next);
393         return 0;
394 }
395
396 static int set_fat(struct exfat *exfat, clus_t clus, clus_t next_clus)
397 {
398         off_t offset;
399
400         offset = le32_to_cpu(exfat->bs->bsx.fat_offset) <<
401                 exfat->bs->bsx.sect_size_bits;
402         offset += sizeof(clus_t) * clus;
403
404         if (exfat_write(exfat->blk_dev->dev_fd, &next_clus, sizeof(next_clus),
405                         offset) != sizeof(next_clus))
406                 return -EIO;
407         return 0;
408 }
409
410 static int check_clus_chain(struct exfat *exfat, struct exfat_inode *node)
411 {
412         struct exfat_dentry *stream_de;
413         clus_t clus, prev, next;
414         uint64_t count, max_count;
415
416         clus = node->first_clus;
417         prev = EXFAT_EOF_CLUSTER;
418         count = 0;
419         max_count = DIV_ROUND_UP(node->size, exfat->clus_size);
420
421         if (node->size == 0 && node->first_clus == EXFAT_FREE_CLUSTER)
422                 return 0;
423
424         /* the first cluster is wrong */
425         if ((node->size == 0 && node->first_clus != EXFAT_FREE_CLUSTER) ||
426                 (node->size > 0 && !heap_clus(exfat, node->first_clus))) {
427                 if (repair_file_ask(&exfat->de_iter, node,
428                         ER_FILE_FIRST_CLUS, "first cluster is wrong"))
429                         goto truncate_file;
430                 else
431                         return -EINVAL;
432         }
433
434         while (clus != EXFAT_EOF_CLUSTER) {
435                 if (count >= max_count) {
436                         if (node->is_contiguous)
437                                 break;
438                         if (repair_file_ask(&exfat->de_iter, node,
439                                         ER_FILE_SMALLER_SIZE,
440                                         "more clusters are allocated. "
441                                         "truncate to %" PRIu64 " bytes",
442                                         count * exfat->clus_size))
443                                 goto truncate_file;
444                         else
445                                 return -EINVAL;
446                 }
447
448                 /*
449                  * This cluster is already allocated. it may be shared with
450                  * the other file, or there is a loop in cluster chain.
451                  */
452                 if (EXFAT_BITMAP_GET(exfat->alloc_bitmap,
453                                 clus - EXFAT_FIRST_CLUSTER)) {
454                         if (repair_file_ask(&exfat->de_iter, node,
455                                         ER_FILE_DUPLICATED_CLUS,
456                                         "cluster is already allocated for "
457                                         "the other file. truncated to %"
458                                         PRIu64 " bytes",
459                                         count * exfat->clus_size))
460                                 goto truncate_file;
461                         else
462                                 return -EINVAL;
463                 }
464
465                 if (!EXFAT_BITMAP_GET(exfat->disk_bitmap,
466                                 clus - EXFAT_FIRST_CLUSTER)) {
467                         if (repair_file_ask(&exfat->de_iter, node,
468                                         ER_FILE_INVALID_CLUS,
469                                         "cluster is marked as free. truncate to %" PRIu64 " bytes",
470                                         count * exfat->clus_size))
471                                 goto truncate_file;
472
473                         else
474                                 return -EINVAL;
475                 }
476
477                 /* This cluster is allocated or not */
478                 if (get_next_clus(exfat, node, clus, &next))
479                         goto truncate_file;
480                 if (!node->is_contiguous) {
481                         if (!heap_clus(exfat, next) &&
482                                         next != EXFAT_EOF_CLUSTER) {
483                                 if (repair_file_ask(&exfat->de_iter, node,
484                                                 ER_FILE_INVALID_CLUS,
485                                                 "broken cluster chain. "
486                                                 "truncate to %"
487                                                 PRIu64 " bytes",
488                                                 count * exfat->clus_size))
489                                         goto truncate_file;
490
491                                 else
492                                         return -EINVAL;
493                         }
494                 }
495
496                 count++;
497                 EXFAT_BITMAP_SET(exfat->alloc_bitmap,
498                                 clus - EXFAT_FIRST_CLUSTER);
499                 prev = clus;
500                 clus = next;
501         }
502
503         if (count < max_count) {
504                 if (repair_file_ask(&exfat->de_iter, node,
505                         ER_FILE_LARGER_SIZE, "less clusters are allocated. "
506                         "truncates to %" PRIu64 " bytes",
507                         count * exfat->clus_size))
508                         goto truncate_file;
509                 else
510                         return -EINVAL;
511         }
512
513         return 0;
514 truncate_file:
515         node->size = count * exfat->clus_size;
516         if (!heap_clus(exfat, prev))
517                 node->first_clus = EXFAT_FREE_CLUSTER;
518
519         exfat_de_iter_get_dirty(&exfat->de_iter, 1, &stream_de);
520         if (count * exfat->clus_size <
521                         le64_to_cpu(stream_de->stream_valid_size))
522                 stream_de->stream_valid_size = cpu_to_le64(
523                                 count * exfat->clus_size);
524         if (!heap_clus(exfat, prev))
525                 stream_de->stream_start_clu = EXFAT_FREE_CLUSTER;
526         stream_de->stream_size = cpu_to_le64(
527                         count * exfat->clus_size);
528
529         /* remaining clusters will be freed while FAT is compared with
530          * alloc_bitmap.
531          */
532         if (!node->is_contiguous && heap_clus(exfat, prev))
533                 return set_fat(exfat, prev, EXFAT_EOF_CLUSTER);
534         return 1;
535 }
536
537 static bool root_get_clus_count(struct exfat *exfat, struct exfat_inode *node,
538                                                         clus_t *clus_count)
539 {
540         clus_t clus;
541
542         clus = node->first_clus;
543         *clus_count = 0;
544
545         do {
546                 if (!heap_clus(exfat, clus)) {
547                         exfat_err("/: bad cluster. 0x%x\n", clus);
548                         return false;
549                 }
550
551                 if (EXFAT_BITMAP_GET(exfat->alloc_bitmap,
552                                 clus - EXFAT_FIRST_CLUSTER)) {
553                         exfat_err("/: cluster is already allocated, or "
554                                 "there is a loop in cluster chain\n");
555                         return false;
556                 }
557
558                 EXFAT_BITMAP_SET(exfat->alloc_bitmap,
559                                 clus - EXFAT_FIRST_CLUSTER);
560
561                 if (get_next_clus(exfat, node, clus, &clus) != 0) {
562                         exfat_err("/: broken cluster chain\n");
563                         return false;
564                 }
565
566                 (*clus_count)++;
567         } while (clus != EXFAT_EOF_CLUSTER);
568         return true;
569 }
570
571 static off_t exfat_s2o(struct exfat *exfat, off_t sect)
572 {
573         return sect << exfat->bs->bsx.sect_size_bits;
574 }
575
576 off_t exfat_c2o(struct exfat *exfat, unsigned int clus)
577 {
578         if (clus < EXFAT_FIRST_CLUSTER)
579                 return ~0L;
580
581         return exfat_s2o(exfat, le32_to_cpu(exfat->bs->bsx.clu_offset) +
582                                 ((off_t)(clus - EXFAT_FIRST_CLUSTER) <<
583                                  exfat->bs->bsx.sect_per_clus_bits));
584 }
585
586 static int boot_region_checksum(struct exfat_blk_dev *bd, int bs_offset)
587 {
588         void *sect;
589         unsigned int i;
590         uint32_t checksum;
591         int ret = 0;
592         unsigned int size;
593
594         size = bd->sector_size;
595         sect = malloc(size);
596         if (!sect)
597                 return -ENOMEM;
598
599         checksum = 0;
600         for (i = 0; i < 11; i++) {
601                 if (exfat_read(bd->dev_fd, sect, size,
602                                 bs_offset * size + i * size) !=
603                                 (ssize_t)size) {
604                         exfat_err("failed to read boot region\n");
605                         ret = -EIO;
606                         goto out;
607                 }
608                 boot_calc_checksum(sect, size, i == 0, &checksum);
609         }
610
611         if (exfat_read(bd->dev_fd, sect, size,
612                         bs_offset * size + 11 * size) !=
613                         (ssize_t)size) {
614                 exfat_err("failed to read a boot checksum sector\n");
615                 ret = -EIO;
616                 goto out;
617         }
618
619         for (i = 0; i < size/sizeof(checksum); i++) {
620                 if (le32_to_cpu(((__le32 *)sect)[i]) != checksum) {
621                         exfat_err("checksum of boot region is not correct. %#x, but expected %#x\n",
622                                 le32_to_cpu(((__le32 *)sect)[i]), checksum);
623                         ret = -EINVAL;
624                         goto out;
625                 }
626         }
627 out:
628         free(sect);
629         return ret;
630 }
631
632 static int exfat_mark_volume_dirty(struct exfat *exfat, bool dirty)
633 {
634         uint16_t flags;
635
636         if (!(exfat->options & FSCK_OPTS_REPAIR_WRITE))
637                 return 0;
638
639         flags = le16_to_cpu(exfat->bs->bsx.vol_flags);
640         if (dirty)
641                 flags |= 0x02;
642         else
643                 flags &= ~0x02;
644
645         exfat->bs->bsx.vol_flags = cpu_to_le16(flags);
646         if (exfat_write(exfat->blk_dev->dev_fd, exfat->bs,
647                         sizeof(struct pbr), 0) != (ssize_t)sizeof(struct pbr)) {
648                 exfat_err("failed to set VolumeDirty\n");
649                 return -EIO;
650         }
651
652         if (fsync(exfat->blk_dev->dev_fd) != 0) {
653                 exfat_err("failed to set VolumeDirty\n");
654                 return -EIO;
655         }
656         return 0;
657 }
658
659 static int read_boot_region(struct exfat_blk_dev *bd, struct pbr **pbr,
660                 int bs_offset)
661 {
662         struct pbr *bs;
663         int ret = -EINVAL;
664
665         *pbr = NULL;
666         bs = (struct pbr *)malloc(sizeof(struct pbr));
667         if (!bs) {
668                 exfat_err("failed to allocate memory\n");
669                 return -ENOMEM;
670         }
671
672         if (exfat_read(bd->dev_fd, bs, sizeof(*bs),
673                         bs_offset * bd->sector_size) != (ssize_t)sizeof(*bs)) {
674                 exfat_err("failed to read a boot sector\n");
675                 ret = -EIO;
676                 goto err;
677         }
678
679         if (memcmp(bs->bpb.oem_name, "EXFAT   ", 8) != 0) {
680                 exfat_err("failed to find exfat file system.\n");
681                 goto err;
682         }
683
684         ret = boot_region_checksum(bd, bs_offset);
685         if (ret < 0)
686                 goto err;
687
688         ret = -EINVAL;
689         if (EXFAT_SECTOR_SIZE(bs) < 512 || EXFAT_SECTOR_SIZE(bs) > 4 * KB) {
690                 exfat_err("too small or big sector size: %d\n",
691                                 EXFAT_SECTOR_SIZE(bs));
692                 goto err;
693         }
694
695         if (EXFAT_CLUSTER_SIZE(bs) > 32 * MB) {
696                 exfat_err("too big cluster size: %d\n", EXFAT_CLUSTER_SIZE(bs));
697                 goto err;
698         }
699
700         if (bs->bsx.fs_version[1] != 1 || bs->bsx.fs_version[0] != 0) {
701                 exfat_err("unsupported exfat version: %d.%d\n",
702                                 bs->bsx.fs_version[1], bs->bsx.fs_version[0]);
703                 goto err;
704         }
705
706         if (bs->bsx.num_fats != 1) {
707                 exfat_err("unsupported FAT count: %d\n", bs->bsx.num_fats);
708                 goto err;
709         }
710
711         if (le64_to_cpu(bs->bsx.vol_length) * EXFAT_SECTOR_SIZE(bs) >
712                         bd->size) {
713                 exfat_err("too large sector count: %" PRIu64 ", expected: %llu\n",
714                                 le64_to_cpu(bs->bsx.vol_length),
715                                 bd->num_sectors);
716                 goto err;
717         }
718
719         if (le32_to_cpu(bs->bsx.clu_count) * EXFAT_CLUSTER_SIZE(bs) >
720                         bd->size) {
721                 exfat_err("too large cluster count: %u, expected: %u\n",
722                                 le32_to_cpu(bs->bsx.clu_count),
723                                 bd->num_clusters);
724                 goto err;
725         }
726
727         *pbr = bs;
728         return 0;
729 err:
730         free(bs);
731         return ret;
732 }
733
734 static int restore_boot_region(struct exfat_blk_dev *bd)
735 {
736         int i;
737         char *sector;
738
739         sector = malloc(bd->sector_size);
740         if (!sector)
741                 return -ENOMEM;
742
743         for (i = 0; i < 12; i++) {
744                 if (exfat_read(bd->dev_fd, sector, bd->sector_size,
745                                 BACKUP_BOOT_SEC_IDX * bd->sector_size +
746                                 i * bd->sector_size) !=
747                                 (ssize_t)bd->sector_size)
748                         return -EIO;
749                 if (i == 0)
750                         ((struct pbr *)sector)->bsx.perc_in_use = 0xff;
751
752                 if (exfat_write(bd->dev_fd, sector, bd->sector_size,
753                                 BOOT_SEC_IDX * bd->sector_size +
754                                 i * bd->sector_size) !=
755                                 (ssize_t)bd->sector_size)
756                         return -EIO;
757         }
758         if (fsync(bd->dev_fd))
759                 return -EIO;
760         free(sector);
761         return 0;
762 }
763
764 static int exfat_boot_region_check(struct exfat *exfat, struct pbr **bs)
765 {
766         int ret;
767
768         ret = read_boot_region(exfat->blk_dev, bs, BOOT_SEC_IDX);
769         if (ret == -EINVAL && exfat_repair_ask(exfat, ER_BS_BOOT_REGION,
770                                 "boot region is corrupted. try to restore the region from backup"
771                                 )) {
772                 ret = read_boot_region(exfat->blk_dev, bs, BACKUP_BOOT_SEC_IDX);
773                 if (ret < 0) {
774                         exfat_err("backup boot region is also corrupted\n");
775                         return ret;
776                 }
777                 ret = restore_boot_region(exfat->blk_dev);
778                 if (ret < 0) {
779                         exfat_err("failed to restore boot region from backup\n");
780                         free(*bs);
781                         *bs = NULL;
782                         return ret;
783                 }
784         }
785         return ret;
786 }
787
788 static void dentry_calc_checksum(struct exfat_dentry *dentry,
789                                 __le16 *checksum, bool primary)
790 {
791         unsigned int i;
792         uint8_t *bytes;
793
794         bytes = (uint8_t *)dentry;
795
796         *checksum = ((*checksum << 15) | (*checksum >> 1)) + bytes[0];
797         *checksum = ((*checksum << 15) | (*checksum >> 1)) + bytes[1];
798
799         i = primary ? 4 : 2;
800         for (; i < sizeof(*dentry); i++) {
801                 *checksum = ((*checksum << 15) | (*checksum >> 1)) + bytes[i];
802         }
803 }
804
805 static __le16 file_calc_checksum(struct exfat_de_iter *iter)
806 {
807         __le16 checksum;
808         struct exfat_dentry *file_de, *de;
809         int i;
810
811         checksum = 0;
812         exfat_de_iter_get(iter, 0, &file_de);
813
814         dentry_calc_checksum(file_de, &checksum, true);
815         for (i = 1; i <= file_de->file_num_ext; i++) {
816                 exfat_de_iter_get(iter, i, &de);
817                 dentry_calc_checksum(de, &checksum, false);
818         }
819
820         return checksum;
821 }
822
823 /*
824  * return 0 if there are no errors, or 1 if errors are fixed, or
825  * an error code
826  */
827 static int check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)
828 {
829         struct exfat *exfat = iter->exfat;
830         struct exfat_dentry *dentry;
831         int ret = 0;
832         uint16_t checksum;
833         bool valid = true;
834
835         ret = check_clus_chain(exfat, node);
836         if (ret < 0)
837                 return ret;
838
839         if (node->size > le32_to_cpu(exfat->bs->bsx.clu_count) *
840                                 (uint64_t)exfat->clus_size) {
841                 fsck_err(iter->parent, node,
842                         "size %" PRIu64 " is greater than cluster heap\n",
843                         node->size);
844                 valid = false;
845         }
846
847         if (node->size == 0 && node->is_contiguous) {
848                 if (repair_file_ask(iter, node, ER_FILE_ZERO_NOFAT,
849                                 "empty, but has no Fat chain\n")) {
850                         exfat_de_iter_get_dirty(iter, 1, &dentry);
851                         dentry->stream_flags &= ~EXFAT_SF_CONTIGUOUS;
852                         ret = 1;
853                 } else
854                         valid = false;
855         }
856
857         if ((node->attr & ATTR_SUBDIR) &&
858                         node->size % exfat->clus_size != 0) {
859                 fsck_err(iter->parent, node,
860                         "directory size %" PRIu64 " is not divisible by %d\n",
861                         node->size, exfat->clus_size);
862                 valid = false;
863         }
864
865         checksum = file_calc_checksum(iter);
866         exfat_de_iter_get(iter, 0, &dentry);
867         if (checksum != le16_to_cpu(dentry->file_checksum)) {
868                 if (repair_file_ask(iter, node, ER_DE_CHECKSUM,
869                                 "the checksum of a file is wrong")) {
870                         exfat_de_iter_get_dirty(iter, 0, &dentry);
871                         dentry->file_checksum = cpu_to_le16(checksum);
872                         ret = 1;
873                 } else
874                         valid = false;
875         }
876
877         return valid ? ret : -EINVAL;
878 }
879
880 static int read_file_dentries(struct exfat_de_iter *iter,
881                         struct exfat_inode **new_node, int *skip_dentries)
882 {
883         struct exfat_dentry *file_de, *stream_de, *name_de;
884         struct exfat_inode *node;
885         int i, ret;
886
887         /* TODO: mtime, atime, ... */
888
889         ret = exfat_de_iter_get(iter, 0, &file_de);
890         if (ret || file_de->type != EXFAT_FILE) {
891                 exfat_err("failed to get file dentry. %d\n", ret);
892                 return -EINVAL;
893         }
894         ret = exfat_de_iter_get(iter, 1, &stream_de);
895         if (ret || stream_de->type != EXFAT_STREAM) {
896                 exfat_err("failed to get stream dentry. %d\n", ret);
897                 return -EINVAL;
898         }
899
900         *new_node = NULL;
901         node = alloc_exfat_inode(le16_to_cpu(file_de->file_attr));
902         if (!node)
903                 return -ENOMEM;
904
905         if (file_de->file_num_ext < 2) {
906                 exfat_err("too few secondary count. %d\n",
907                                 file_de->file_num_ext);
908                 free_exfat_inode(node);
909                 return -EINVAL;
910         }
911
912         for (i = 2; i <= file_de->file_num_ext; i++) {
913                 ret = exfat_de_iter_get(iter, i, &name_de);
914                 if (ret || name_de->type != EXFAT_NAME) {
915                         exfat_err("failed to get name dentry. %d\n", ret);
916                         ret = -EINVAL;
917                         goto err;
918                 }
919
920                 memcpy(node->name +
921                         (i-2) * ENTRY_NAME_MAX, name_de->name_unicode,
922                         sizeof(name_de->name_unicode));
923         }
924
925         node->first_clus = le32_to_cpu(stream_de->stream_start_clu);
926         node->is_contiguous =
927                 ((stream_de->stream_flags & EXFAT_SF_CONTIGUOUS) != 0);
928         node->size = le64_to_cpu(stream_de->stream_size);
929
930         if (node->size < le64_to_cpu(stream_de->stream_valid_size)) {
931                 if (repair_file_ask(iter, node, ER_FILE_VALID_SIZE,
932                         "valid size %" PRIu64 " greater than size %" PRIu64,
933                         le64_to_cpu(stream_de->stream_valid_size),
934                         node->size)) {
935                         exfat_de_iter_get_dirty(iter, 1, &stream_de);
936                         stream_de->stream_valid_size =
937                                         stream_de->stream_size;
938                 } else {
939                         ret = -EINVAL;
940                         goto err;
941                 }
942         }
943
944         *skip_dentries = (file_de->file_num_ext + 1);
945         *new_node = node;
946         return 0;
947 err:
948         *skip_dentries = 0;
949         *new_node = NULL;
950         free_exfat_inode(node);
951         return ret;
952 }
953
954 static int read_file(struct exfat_de_iter *de_iter,
955                 struct exfat_inode **new_node, int *dentry_count)
956 {
957         struct exfat_inode *node;
958         int ret;
959
960         *new_node = NULL;
961
962         ret = read_file_dentries(de_iter, &node, dentry_count);
963         if (ret)
964                 return ret;
965
966         ret = check_inode(de_iter, node);
967         if (ret < 0) {
968                 free_exfat_inode(node);
969                 return -EINVAL;
970         }
971
972         *new_node = node;
973         return ret;
974 }
975
976 static bool read_volume_label(struct exfat_de_iter *iter)
977 {
978         struct exfat *exfat;
979         struct exfat_dentry *dentry;
980         __le16 disk_label[VOLUME_LABEL_MAX_LEN];
981
982         exfat = iter->exfat;
983         if (exfat_de_iter_get(iter, 0, &dentry))
984                 return false;
985
986         if (dentry->vol_char_cnt == 0)
987                 return true;
988
989         if (dentry->vol_char_cnt > VOLUME_LABEL_MAX_LEN) {
990                 exfat_err("too long label. %d\n", dentry->vol_char_cnt);
991                 return false;
992         }
993
994         memcpy(disk_label, dentry->vol_label, sizeof(disk_label));
995         if (exfat_utf16_dec(disk_label, dentry->vol_char_cnt*2,
996                 exfat->volume_label, sizeof(exfat->volume_label)) < 0) {
997                 exfat_err("failed to decode volume label\n");
998                 return false;
999         }
1000
1001         exfat_info("volume label [%s]\n", exfat->volume_label);
1002         return true;
1003 }
1004
1005 static void exfat_bitmap_set_range(struct exfat *exfat,
1006                         clus_t start_clus, clus_t count)
1007 {
1008         clus_t clus;
1009
1010         if (!heap_clus(exfat, start_clus) ||
1011                 !heap_clus(exfat, start_clus + count))
1012                 return;
1013
1014         clus = start_clus;
1015         while (clus < start_clus + count) {
1016                 EXFAT_BITMAP_SET(exfat->alloc_bitmap,
1017                                 clus - EXFAT_FIRST_CLUSTER);
1018                 clus++;
1019         }
1020 }
1021
1022 static bool read_bitmap(struct exfat_de_iter *iter)
1023 {
1024         struct exfat_dentry *dentry;
1025         struct exfat *exfat;
1026
1027         exfat = iter->exfat;
1028         if (exfat_de_iter_get(iter, 0, &dentry))
1029                 return false;
1030
1031         exfat_debug("start cluster %#x, size %#" PRIx64 "\n",
1032                         le32_to_cpu(dentry->bitmap_start_clu),
1033                         le64_to_cpu(dentry->bitmap_size));
1034
1035         if (le64_to_cpu(dentry->bitmap_size) <
1036                         DIV_ROUND_UP(exfat->clus_count, 8)) {
1037                 exfat_err("invalid size of allocation bitmap. 0x%" PRIx64 "\n",
1038                                 le64_to_cpu(dentry->bitmap_size));
1039                 return false;
1040         }
1041         if (!heap_clus(exfat, le32_to_cpu(dentry->bitmap_start_clu))) {
1042                 exfat_err("invalid start cluster of allocate bitmap. 0x%x\n",
1043                                 le32_to_cpu(dentry->bitmap_start_clu));
1044                 return false;
1045         }
1046
1047         exfat->disk_bitmap_clus = le32_to_cpu(dentry->bitmap_start_clu);
1048         exfat->disk_bitmap_size = DIV_ROUND_UP(exfat->clus_count, 8);
1049
1050         exfat_bitmap_set_range(exfat, le64_to_cpu(dentry->bitmap_start_clu),
1051                         DIV_ROUND_UP(exfat->disk_bitmap_size,
1052                         exfat->clus_size));
1053
1054         if (exfat_read(exfat->blk_dev->dev_fd, exfat->disk_bitmap,
1055                         exfat->disk_bitmap_size,
1056                         exfat_c2o(exfat, exfat->disk_bitmap_clus)) !=
1057                         (ssize_t)exfat->disk_bitmap_size)
1058                 return false;
1059
1060         return true;
1061 }
1062
1063 static bool read_upcase_table(struct exfat_de_iter *iter)
1064 {
1065         struct exfat_dentry *dentry;
1066         struct exfat *exfat;
1067         ssize_t size;
1068         __le16 *upcase;
1069         __le32 checksum;
1070
1071         exfat = iter->exfat;
1072
1073         if (exfat_de_iter_get(iter, 0, &dentry))
1074                 return false;
1075
1076         if (!heap_clus(exfat, le32_to_cpu(dentry->upcase_start_clu))) {
1077                 exfat_err("invalid start cluster of upcase table. 0x%x\n",
1078                         le32_to_cpu(dentry->upcase_start_clu));
1079                 return false;
1080         }
1081
1082         size = (ssize_t)le64_to_cpu(dentry->upcase_size);
1083         if (size > (ssize_t)(EXFAT_MAX_UPCASE_CHARS * sizeof(__le16)) ||
1084                         size == 0 || size % sizeof(__le16)) {
1085                 exfat_err("invalid size of upcase table. 0x%" PRIx64 "\n",
1086                         le64_to_cpu(dentry->upcase_size));
1087                 return false;
1088         }
1089
1090         upcase = (__le16 *)malloc(size);
1091         if (!upcase) {
1092                 exfat_err("failed to allocate upcase table\n");
1093                 return false;
1094         }
1095
1096         if (exfat_read(exfat->blk_dev->dev_fd, upcase, size,
1097                         exfat_c2o(exfat,
1098                         le32_to_cpu(dentry->upcase_start_clu))) != size) {
1099                 exfat_err("failed to read upcase table\n");
1100                 free(upcase);
1101                 return false;
1102         }
1103
1104         checksum = 0;
1105         boot_calc_checksum((unsigned char *)upcase, size, false, &checksum);
1106         if (le32_to_cpu(dentry->upcase_checksum) != checksum) {
1107                 exfat_err("corrupted upcase table %#x (expected: %#x)\n",
1108                         checksum, le32_to_cpu(dentry->upcase_checksum));
1109                 free(upcase);
1110                 return false;
1111         }
1112
1113         exfat_bitmap_set_range(exfat, le32_to_cpu(dentry->upcase_start_clu),
1114                         DIV_ROUND_UP(le64_to_cpu(dentry->upcase_size),
1115                         exfat->clus_size));
1116
1117         free(upcase);
1118         return true;
1119 }
1120
1121 static int read_children(struct exfat *exfat, struct exfat_inode *dir)
1122 {
1123         int ret;
1124         struct exfat_inode *node = NULL;
1125         struct exfat_dentry *dentry;
1126         int dentry_count;
1127         struct exfat_de_iter *de_iter;
1128
1129         de_iter = &exfat->de_iter;
1130         ret = exfat_de_iter_init(de_iter, exfat, dir);
1131         if (ret == EOF)
1132                 return 0;
1133         else if (ret)
1134                 return ret;
1135
1136         while (1) {
1137                 ret = exfat_de_iter_get(de_iter, 0, &dentry);
1138                 if (ret == EOF) {
1139                         break;
1140                 } else if (ret) {
1141                         fsck_err(dir->parent, dir,
1142                                 "failed to get a dentry. %d\n", ret);
1143                         goto err;
1144                 }
1145
1146                 dentry_count = 1;
1147
1148                 switch (dentry->type) {
1149                 case EXFAT_FILE:
1150                         ret = read_file(de_iter, &node, &dentry_count);
1151                         if (ret < 0) {
1152                                 exfat_stat.error_count++;
1153                                 goto err;
1154                         } else if (ret) {
1155                                 exfat_stat.error_count++;
1156                                 exfat_stat.fixed_count++;
1157                         }
1158
1159                         if ((node->attr & ATTR_SUBDIR) && node->size) {
1160                                 node->parent = dir;
1161                                 list_add_tail(&node->sibling, &dir->children);
1162                                 list_add_tail(&node->list, &exfat->dir_list);
1163                         } else
1164                                 free_exfat_inode(node);
1165                         break;
1166                 case EXFAT_VOLUME:
1167                         if (!read_volume_label(de_iter)) {
1168                                 exfat_err("failed to verify volume label\n");
1169                                 ret = -EINVAL;
1170                                 goto err;
1171                         }
1172                         break;
1173                 case EXFAT_BITMAP:
1174                         if (!read_bitmap(de_iter)) {
1175                                 exfat_err(
1176                                         "failed to verify allocation bitmap\n");
1177                                 ret = -EINVAL;
1178                                 goto err;
1179                         }
1180                         break;
1181                 case EXFAT_UPCASE:
1182                         if (!read_upcase_table(de_iter)) {
1183                                 exfat_err(
1184                                         "failed to verify upcase table\n");
1185                                 ret = -EINVAL;
1186                                 goto err;
1187                         }
1188                         break;
1189                 case EXFAT_LAST:
1190                         goto out;
1191                 default:
1192                         if (IS_EXFAT_DELETED(dentry->type))
1193                                 break;
1194                         exfat_err("unknown entry type. 0x%x\n", dentry->type);
1195                         ret = -EINVAL;
1196                         goto err;
1197                 }
1198
1199                 exfat_de_iter_advance(de_iter, dentry_count);
1200         }
1201 out:
1202         exfat_de_iter_flush(de_iter);
1203         return 0;
1204 err:
1205         inode_free_children(dir, false);
1206         INIT_LIST_HEAD(&dir->children);
1207         exfat_de_iter_flush(de_iter);
1208         return ret;
1209 }
1210
1211 static int write_dirty_fat(struct exfat *exfat)
1212 {
1213         struct buffer_desc *bd;
1214         off_t offset;
1215         ssize_t len;
1216         size_t read_size, write_size;
1217         clus_t clus, last_clus, clus_count, i;
1218         unsigned int idx;
1219
1220         clus = 0;
1221         last_clus = le32_to_cpu(exfat->bs->bsx.clu_count) + 2;
1222         bd = exfat->buffer_desc;
1223         idx = 0;
1224         offset = le32_to_cpu(exfat->bs->bsx.fat_offset) *
1225                 exfat->sect_size;
1226         read_size = exfat->clus_size;
1227         write_size = exfat->sect_size;
1228
1229         while (clus < last_clus) {
1230                 clus_count = MIN(read_size / sizeof(clus_t), last_clus - clus);
1231                 len = exfat_read(exfat->blk_dev->dev_fd, bd[idx].buffer,
1232                                 clus_count * sizeof(clus_t), offset);
1233                 if (len != (ssize_t)(sizeof(clus_t) * clus_count)) {
1234                         exfat_err("failed to read fat entries, %zd\n", len);
1235                         return -EIO;
1236                 }
1237
1238                 /* TODO: read ahead */
1239
1240                 for (i = clus ? clus : EXFAT_FIRST_CLUSTER;
1241                                 i < clus + clus_count; i++) {
1242                         if (!EXFAT_BITMAP_GET(exfat->alloc_bitmap,
1243                                         i - EXFAT_FIRST_CLUSTER) &&
1244                                         ((clus_t *)bd[idx].buffer)[i - clus] !=
1245                                         EXFAT_FREE_CLUSTER) {
1246                                 ((clus_t *)bd[idx].buffer)[i - clus] =
1247                                         EXFAT_FREE_CLUSTER;
1248                                 bd[idx].dirty[(i - clus) /
1249                                         (write_size / sizeof(clus_t))] = true;
1250                         }
1251                 }
1252
1253                 for (i = 0; i < read_size; i += write_size) {
1254                         if (bd[idx].dirty[i / write_size]) {
1255                                 if (exfat_write(exfat->blk_dev->dev_fd,
1256                                                 &bd[idx].buffer[i], write_size,
1257                                                 offset + i) !=
1258                                                 (ssize_t)write_size) {
1259                                         exfat_err("failed to write "
1260                                                 "fat entries\n");
1261                                         return -EIO;
1262
1263                                 }
1264                                 bd[idx].dirty[i / write_size] = false;
1265                         }
1266                 }
1267
1268                 idx ^= 0x01;
1269                 clus = clus + clus_count;
1270                 offset += len;
1271         }
1272         return 0;
1273 }
1274
1275 static int write_dirty_bitmap(struct exfat *exfat)
1276 {
1277         struct buffer_desc *bd;
1278         off_t offset, last_offset, bitmap_offset;
1279         ssize_t len;
1280         ssize_t read_size, write_size, i, size;
1281         int idx;
1282
1283         offset = exfat_c2o(exfat, exfat->disk_bitmap_clus);
1284         last_offset = offset + exfat->disk_bitmap_size;
1285         bitmap_offset = 0;
1286         read_size = exfat->clus_size;
1287         write_size = exfat->sect_size;
1288
1289         bd = exfat->buffer_desc;
1290         idx = 0;
1291
1292         while (offset < last_offset) {
1293                 len = MIN(read_size, last_offset - offset);
1294                 if (exfat_read(exfat->blk_dev->dev_fd, bd[idx].buffer,
1295                                 len, offset) != (ssize_t)len)
1296                         return -EIO;
1297
1298                 /* TODO: read-ahead */
1299
1300                 for (i = 0; i < len; i += write_size) {
1301                         size = MIN(write_size, len - i);
1302                         if (memcmp(&bd[idx].buffer[i],
1303                                         exfat->alloc_bitmap + bitmap_offset + i,
1304                                         size)) {
1305                                 if (exfat_write(exfat->blk_dev->dev_fd,
1306                                         exfat->alloc_bitmap + bitmap_offset + i,
1307                                         size, offset + i) != size)
1308                                         return -EIO;
1309                         }
1310                 }
1311
1312                 idx ^= 0x01;
1313                 offset += len;
1314                 bitmap_offset += len;
1315         }
1316         return 0;
1317 }
1318
1319 static int reclaim_free_clusters(struct exfat *exfat)
1320 {
1321         if (write_dirty_fat(exfat)) {
1322                 exfat_err("failed to write fat entries\n");
1323                 return -EIO;
1324         }
1325         if (write_dirty_bitmap(exfat)) {
1326                 exfat_err("failed to write bitmap\n");
1327                 return -EIO;
1328         }
1329         return 0;
1330 }
1331
1332 /*
1333  * for each directory in @dir_list.
1334  * 1. read all dentries and allocate exfat_nodes for files and directories.
1335  *    and append directory exfat_nodes to the head of @dir_list
1336  * 2. free all of file exfat_nodes.
1337  * 3. if the directory does not have children, free its exfat_node.
1338  */
1339 static int exfat_filesystem_check(struct exfat *exfat)
1340 {
1341         struct exfat_inode *dir;
1342         int ret = 0, dir_errors;
1343
1344         if (!exfat->root) {
1345                 exfat_err("root is NULL\n");
1346                 return -ENOENT;
1347         }
1348
1349         list_add(&exfat->root->list, &exfat->dir_list);
1350
1351         while (!list_empty(&exfat->dir_list)) {
1352                 dir = list_entry(exfat->dir_list.next, struct exfat_inode, list);
1353
1354                 if (!(dir->attr & ATTR_SUBDIR)) {
1355                         fsck_err(dir->parent, dir,
1356                                 "failed to travel directories. "
1357                                 "the node is not directory\n");
1358                         ret = -EINVAL;
1359                         goto out;
1360                 }
1361
1362                 dir_errors = read_children(exfat, dir);
1363                 if (dir_errors) {
1364                         resolve_path(&path_resolve_ctx, dir);
1365                         exfat_debug("failed to check dentries: %s\n",
1366                                         path_resolve_ctx.local_path);
1367                         ret = dir_errors;
1368                 }
1369
1370                 list_del(&dir->list);
1371                 inode_free_file_children(dir);
1372                 inode_free_ancestors(dir);
1373         }
1374 out:
1375         exfat_free_dir_list(exfat);
1376         exfat->root = NULL;
1377         if (exfat->dirty_fat && reclaim_free_clusters(exfat))
1378                 return -EIO;
1379         return ret;
1380 }
1381
1382 static int exfat_root_dir_check(struct exfat *exfat)
1383 {
1384         struct exfat_inode *root;
1385         clus_t clus_count;
1386
1387         root = alloc_exfat_inode(ATTR_SUBDIR);
1388         if (!root) {
1389                 exfat_err("failed to allocate memory\n");
1390                 return -ENOMEM;
1391         }
1392
1393         root->first_clus = le32_to_cpu(exfat->bs->bsx.root_cluster);
1394         if (!root_get_clus_count(exfat, root, &clus_count)) {
1395                 exfat_err("failed to follow the cluster chain of root\n");
1396                 free_exfat_inode(root);
1397                 return -EINVAL;
1398         }
1399         root->size = clus_count * exfat->clus_size;
1400
1401         exfat->root = root;
1402         exfat_debug("root directory: start cluster[0x%x] size[0x%" PRIx64 "]\n",
1403                 root->first_clus, root->size);
1404         return 0;
1405 }
1406
1407 static char *bytes_to_human_readable(size_t bytes)
1408 {
1409         static const char * const units[] = {"B", "KB", "MB", "GB", "TB", "PB"};
1410         static char buf[15*4];
1411         unsigned int i, shift, quoti, remain;
1412
1413         shift = 0;
1414         for (i = 0; i < sizeof(units)/sizeof(units[0]); i++) {
1415                 if (bytes / (1ULL << (shift + 10)) == 0)
1416                         break;
1417                 shift += 10;
1418         }
1419
1420         quoti = (unsigned int)(bytes / (1ULL << shift));
1421         remain = 0;
1422         if (shift > 0) {
1423                 remain = (unsigned int)
1424                         ((bytes & ((1ULL << shift) - 1)) >> (shift - 10));
1425                 remain = (remain * 100) / 1024;
1426         }
1427
1428         snprintf(buf, sizeof(buf), "%u.%02u %s", quoti, remain, units[i]);
1429         return buf;
1430 }
1431
1432 static void exfat_show_info(struct exfat *exfat, const char *dev_name,
1433                         int errors)
1434 {
1435         exfat_info("sector size:  %s\n",
1436                 bytes_to_human_readable(1 << exfat->bs->bsx.sect_size_bits));
1437         exfat_info("cluster size: %s\n",
1438                 bytes_to_human_readable(exfat->clus_size));
1439         exfat_info("volume size:  %s\n",
1440                 bytes_to_human_readable(exfat->blk_dev->size));
1441
1442         printf("%s: %s. directories %ld, files %ld\n", dev_name,
1443                         errors ? "checking stopped" : "clean",
1444                         exfat_stat.dir_count, exfat_stat.file_count);
1445         if (errors || exfat->dirty)
1446                 printf("%s: files corrupted %ld, files fixed %ld\n", dev_name,
1447                         exfat_stat.error_count, exfat_stat.fixed_count);
1448 }
1449
1450 int main(int argc, char * const argv[])
1451 {
1452         struct fsck_user_input ui;
1453         struct exfat_blk_dev bd;
1454         struct exfat *exfat = NULL;
1455         struct pbr *bs = NULL;
1456         int c, ret, exit_code;
1457         bool version_only = false;
1458
1459         memset(&ui, 0, sizeof(ui));
1460         memset(&bd, 0, sizeof(bd));
1461
1462         print_level = EXFAT_ERROR;
1463
1464         if (!setlocale(LC_CTYPE, ""))
1465                 exfat_err("failed to init locale/codeset\n");
1466
1467         opterr = 0;
1468         while ((c = getopt_long(argc, argv, "rynpVvh", opts, NULL)) != EOF) {
1469                 switch (c) {
1470                 case 'n':
1471                         if (ui.options & FSCK_OPTS_REPAIR_ALL)
1472                                 usage(argv[0]);
1473                         ui.options |= FSCK_OPTS_REPAIR_NO;
1474                         break;
1475                 case 'r':
1476                         if (ui.options & FSCK_OPTS_REPAIR_ALL)
1477                                 usage(argv[0]);
1478                         ui.options |= FSCK_OPTS_REPAIR_ASK;
1479                         break;
1480                 case 'y':
1481                         if (ui.options & FSCK_OPTS_REPAIR_ALL)
1482                                 usage(argv[0]);
1483                         ui.options |= FSCK_OPTS_REPAIR_YES;
1484                         break;
1485                 case 'p':
1486                         if (ui.options & FSCK_OPTS_REPAIR_ALL)
1487                                 usage(argv[0]);
1488                         ui.options |= FSCK_OPTS_REPAIR_AUTO;
1489                         break;
1490                 case 'V':
1491                         version_only = true;
1492                         break;
1493                 case 'v':
1494                         if (print_level < EXFAT_DEBUG)
1495                                 print_level++;
1496                         break;
1497                 case '?':
1498                 case 'h':
1499                 default:
1500                         usage(argv[0]);
1501                 }
1502         }
1503
1504         show_version();
1505         if (optind != argc - 1)
1506                 usage(argv[0]);
1507
1508         if (version_only)
1509                 exit(FSCK_EXIT_SYNTAX_ERROR);
1510         if (ui.options & FSCK_OPTS_REPAIR_WRITE)
1511                 ui.ei.writeable = true;
1512         else {
1513                 ui.options |= FSCK_OPTS_REPAIR_NO;
1514                 ui.ei.writeable = false;
1515         }
1516
1517         snprintf(ui.ei.dev_name, sizeof(ui.ei.dev_name), "%s", argv[optind]);
1518         ret = exfat_get_blk_dev_info(&ui.ei, &bd);
1519         if (ret < 0) {
1520                 exfat_err("failed to open %s. %d\n", ui.ei.dev_name, ret);
1521                 return FSCK_EXIT_OPERATION_ERROR;
1522         }
1523
1524         exfat = (struct exfat *)calloc(1, sizeof(*exfat));
1525         if (!exfat) {
1526                 exfat_err("failed to allocate exfat\n");
1527                 ret = -ENOMEM;
1528                 goto err;
1529         }
1530         exfat->blk_dev = &bd;
1531         exfat->options = ui.options;
1532
1533         ret = exfat_boot_region_check(exfat, &bs);
1534         if (ret)
1535                 goto err;
1536
1537         ret = init_exfat(exfat, bs);
1538         if (ret)
1539                 goto err;
1540
1541         if (exfat_mark_volume_dirty(exfat, true)) {
1542                 ret = -EIO;
1543                 goto err;
1544         }
1545
1546         exfat_debug("verifying root directory...\n");
1547         ret = exfat_root_dir_check(exfat);
1548         if (ret) {
1549                 exfat_err("failed to verify root directory.\n");
1550                 goto out;
1551         }
1552
1553         exfat_debug("verifying directory entries...\n");
1554         ret = exfat_filesystem_check(exfat);
1555         if (ret)
1556                 goto out;
1557
1558         if (ui.ei.writeable && fsync(bd.dev_fd)) {
1559                 exfat_err("failed to sync\n");
1560                 ret = -EIO;
1561                 goto out;
1562         }
1563         exfat_mark_volume_dirty(exfat, false);
1564
1565 out:
1566         exfat_show_info(exfat, ui.ei.dev_name, ret);
1567 err:
1568         if (ret == -EINVAL)
1569                 exit_code = FSCK_EXIT_ERRORS_LEFT;
1570         else if (ret)
1571                 exit_code = FSCK_EXIT_OPERATION_ERROR;
1572         else if (exfat->dirty)
1573                 exit_code = FSCK_EXIT_CORRECTED;
1574         else
1575                 exit_code = FSCK_EXIT_NO_ERRORS;
1576
1577         free_exfat(exfat);
1578         close(bd.dev_fd);
1579         return exit_code;
1580 }