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