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