1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2019 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2020 Hyunchul Lee <hyc.lee@gmail.com>
16 #include "exfat_ondisk.h"
20 #include "exfat_dir.h"
23 struct fsck_user_input {
24 struct exfat_user_input ei;
25 enum fsck_ui_options options;
28 #define EXFAT_MAX_UPCASE_CHARS 0x10000
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
46 struct exfat_fsck exfat_fsck;
47 struct exfat_stat exfat_stat;
48 struct path_resolve_ctx path_resolve_ctx;
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' },
64 static void usage(char *name)
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");
78 exit(FSCK_EXIT_SYNTAX_ERROR);
81 #define fsck_err(parent, inode, fmt, ...) \
83 exfat_resolve_path_parent(&path_resolve_ctx, \
85 exfat_err("ERROR: %s: " fmt, \
86 path_resolve_ctx.local_path, \
90 #define repair_file_ask(iter, inode, code, fmt, ...) \
93 exfat_resolve_path_parent(&path_resolve_ctx, \
94 (iter)->parent, inode); \
96 exfat_resolve_path(&path_resolve_ctx, \
98 exfat_repair_ask(&exfat_fsck, code, \
99 "ERROR: %s: " fmt " at %#" PRIx64, \
100 path_resolve_ctx.local_path, \
102 exfat_de_iter_device_offset(iter)); \
105 static int check_clus_chain(struct exfat_de_iter *de_iter, int stream_idx,
106 struct exfat_inode *node)
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;
113 clus = node->first_clus;
114 prev = EXFAT_EOF_CLUSTER;
116 max_count = DIV_ROUND_UP(node->size, exfat->clus_size);
118 if (node->size == 0 && node->first_clus == EXFAT_FREE_CLUSTER)
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,
126 "size %#" PRIx64 ", but the first cluster %#x",
127 node->size, node->first_clus))
133 while (clus != EXFAT_EOF_CLUSTER) {
134 if (count >= max_count) {
135 if (node->is_contiguous)
137 if (repair_file_ask(de_iter, node,
138 ER_FILE_SMALLER_SIZE,
139 "more clusters are allocated. truncate to %"
141 count * exfat->clus_size))
148 * This cluster is already allocated. it may be shared with
149 * the other file, or there is a loop in cluster chain.
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 %"
156 count * exfat->clus_size))
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",
170 /* This cluster is allocated or not */
171 if (exfat_get_inode_next_clus(exfat, node, clus, &next))
173 if (next == EXFAT_BAD_CLUSTER) {
174 if (repair_file_ask(de_iter, node,
175 ER_FILE_INVALID_CLUS,
176 "BAD cluster. truncate to %"
178 count * exfat->clus_size))
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 %"
189 (count + 1) * exfat->clus_size)) {
192 exfat_bitmap_set(exfat->alloc_bitmap,
202 exfat_bitmap_set(exfat->alloc_bitmap, clus);
207 if (count < max_count) {
208 if (repair_file_ask(de_iter, node, ER_FILE_LARGER_SIZE,
209 "less clusters are allocated. truncates to %"
211 count * exfat->clus_size))
219 node->size = count * exfat->clus_size;
220 if (!exfat_heap_clus(exfat, prev))
221 node->first_clus = EXFAT_FREE_CLUSTER;
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);
233 /* remaining clusters will be freed while FAT is compared with
236 if (!node->is_contiguous && exfat_heap_clus(exfat, prev)) {
237 if (exfat_set_fat(exfat, prev, EXFAT_EOF_CLUSTER))
243 static int root_check_clus_chain(struct exfat *exfat,
244 struct exfat_inode *node,
247 clus_t clus, next, prev = EXFAT_EOF_CLUSTER;
249 if (!exfat_heap_clus(exfat, node->first_clus))
252 clus = node->first_clus;
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"))
264 exfat_bitmap_set(exfat->alloc_bitmap, clus);
266 if (exfat_get_inode_next_clus(exfat, node, clus, &next)) {
267 exfat_err("ERROR: failed to read the fat entry of root");
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) {
287 } while (clus != EXFAT_EOF_CLUSTER);
291 if (!exfat_heap_clus(exfat, prev)) {
292 exfat_err("ERROR: the start cluster of root is wrong\n");
295 node->size = *clus_count * exfat->clus_size;
296 return exfat_set_fat(exfat, prev, EXFAT_EOF_CLUSTER);
299 static int boot_region_checksum(int dev_fd,
300 int bs_offset, unsigned int sect_size)
307 sect = malloc(sect_size);
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");
320 boot_calc_checksum(sect, sect_size, i == 0, &checksum);
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");
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);
344 static int exfat_mark_volume_dirty(struct exfat *exfat, bool dirty)
348 flags = le16_to_cpu(exfat->bs->bsx.vol_flags);
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");
361 if (fsync(exfat->blk_dev->dev_fd) != 0) {
362 exfat_err("failed to set VolumeDirty\n");
368 static int read_boot_region(struct exfat_blk_dev *bd, struct pbr **pbr,
369 int bs_offset, unsigned int sect_size,
374 unsigned long long clu_max_count;
377 bs = malloc(sizeof(struct pbr));
379 exfat_err("failed to allocate memory\n");
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");
390 if (memcmp(bs->bpb.oem_name, "EXFAT ", 8) != 0) {
392 exfat_err("failed to find exfat file system\n");
396 ret = boot_region_checksum(bd->dev_fd, bs_offset, sect_size);
401 if (EXFAT_SECTOR_SIZE(bs) < 512 || EXFAT_SECTOR_SIZE(bs) > 4 * KB) {
403 exfat_err("too small or big sector size: %d\n",
404 EXFAT_SECTOR_SIZE(bs));
408 if (EXFAT_CLUSTER_SIZE(bs) > 32 * MB) {
410 exfat_err("too big cluster size: %d\n",
411 EXFAT_CLUSTER_SIZE(bs));
415 if (bs->bsx.fs_version[1] != 1 || bs->bsx.fs_version[0] != 0) {
417 exfat_err("unsupported exfat version: %d.%d\n",
418 bs->bsx.fs_version[1], bs->bsx.fs_version[0]);
422 if (bs->bsx.num_fats != 1) {
424 exfat_err("unsupported FAT count: %d\n",
429 if (le64_to_cpu(bs->bsx.vol_length) * EXFAT_SECTOR_SIZE(bs) >
432 exfat_err("too large sector count: %" PRIu64 ", expected: %llu\n",
433 le64_to_cpu(bs->bsx.vol_length),
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) {
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));
455 static int restore_boot_region(struct exfat_blk_dev *bd, unsigned int sect_size)
461 sector = malloc(sect_size);
465 for (i = 0; i < 12; i++) {
466 if (exfat_read(bd->dev_fd, sector, sect_size,
467 BACKUP_BOOT_SEC_IDX * sect_size +
469 (ssize_t)sect_size) {
474 ((struct pbr *)sector)->bsx.perc_in_use = 0xff;
476 if (exfat_write(bd->dev_fd, sector, sect_size,
477 BOOT_SEC_IDX * sect_size +
479 (ssize_t)sect_size) {
485 if (fsync(bd->dev_fd)) {
496 static int exfat_boot_region_check(struct exfat_blk_dev *blkdev,
498 bool ignore_bad_fs_name)
500 struct pbr *boot_sect;
501 unsigned int sect_size;
504 /* First, find out the exfat sector size */
505 boot_sect = malloc(sizeof(*boot_sect));
506 if (boot_sect == NULL)
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");
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");
523 sect_size = 1 << boot_sect->bsx.sect_size_bits;
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"
533 const unsigned int sector_sizes[] = {512, 4096, 1024, 2048};
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,
544 for (i = 0; i < sizeof(sector_sizes)/sizeof(sector_sizes[0]); i++) {
545 if (sector_sizes[i] == sect_size)
548 ret = read_boot_region(blkdev, bs,
550 sector_sizes[i], false);
552 sect_size = sector_sizes[i];
556 exfat_err("backup boot region is also corrupted\n");
561 ret = restore_boot_region(blkdev, sect_size);
563 exfat_err("failed to restore boot region from backup\n");
570 static int file_calc_checksum(struct exfat_de_iter *iter, uint16_t *checksum)
572 struct exfat_dentry *file_de, *de;
576 ret = exfat_de_iter_get(iter, 0, &file_de);
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);
585 exfat_calc_dentry_checksum(de, checksum, false);
591 * return 0 if there are no errors, or 1 if errors are fixed, or
594 static int check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)
596 struct exfat *exfat = iter->exfat;
597 struct exfat_dentry *dentry;
602 ret = check_clus_chain(iter, 1, node);
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",
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;
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);
632 ret = file_calc_checksum(iter, &checksum);
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);
642 return valid ? ret : -EINVAL;
645 static int handle_duplicated_filename(struct exfat_de_iter *iter,
646 struct exfat_inode *inode)
649 struct exfat_lookup_filter filter;
650 char filename[PATH_MAX + 1] = {0};
652 ret = exfat_lookup_file_by_utf16name(iter->exfat, iter->parent,
653 inode->name, &filter);
657 free(filter.out.dentry_set);
659 /* Hash is same, but filename is not same */
660 if (exfat_de_iter_device_offset(iter) == filter.out.dev_offset)
663 ret = exfat_utf16_dec(inode->name, NAME_BUFFER_SIZE, filename,
666 exfat_err("failed to decode filename\n");
670 return exfat_repair_rename_ask(&exfat_fsck, iter, filename,
671 ER_DE_DUPLICATED_NAME, "filename is duplicated");
674 static int check_name_dentry_set(struct exfat_de_iter *iter,
675 struct exfat_inode *inode)
677 struct exfat_dentry *stream_de;
682 exfat_de_iter_get(iter, 1, &stream_de);
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;
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);
708 if (BITMAP_GET(iter->name_hash_bitmap, hash)) {
709 ret = handle_duplicated_filename(iter, inode);
711 BITMAP_SET(iter->name_hash_bitmap, hash);
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, };
719 static int handle_dot_dotdot_filename(struct exfat_de_iter *iter,
720 struct exfat_dentry *dentry,
725 if (!memcmp(dentry->name_unicode, MSDOS_DOT, strm_name_len * 2))
727 else if (!memcmp(dentry->name_unicode, MSDOS_DOTDOT,
733 return exfat_repair_rename_ask(&exfat_fsck, iter, filename,
734 ER_DE_DOT_NAME, "filename is not allowed");
737 static int read_file_dentry_set(struct exfat_de_iter *iter,
738 struct exfat_inode **new_node, int *skip_dentries)
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;
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");
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))
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))
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"))
781 node = exfat_alloc_inode(le16_to_cpu(file_de->file_attr));
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")) {
793 *skip_dentries = i + 1;
798 *skip_dentries = i + 1;
804 (i - 2) * ENTRY_NAME_MAX, dentry->name_unicode,
805 sizeof(dentry->name_unicode));
808 ret = check_name_dentry_set(iter, node);
810 *skip_dentries = file_de->file_num_ext + 1;
813 exfat_de_iter_get(iter, 1, &stream_de);
814 if (DIV_ROUND_UP(stream_de->stream_name_len, ENTRY_NAME_MAX) !=
816 i = DIV_ROUND_UP(stream_de->stream_name_len, ENTRY_NAME_MAX) + 2;
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);
823 *skip_dentries = file_de->file_num_ext + 1;
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};
834 * Vendor GUID should not be zero, But Windows fsck
835 * also does not check and fix it.
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;
844 /* verify cluster chain */
845 vendor_node = exfat_alloc_inode(0);
847 *skip_dentries = i + i;
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);
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;
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;
867 exfat_free_inode(vendor_node);
871 struct exfat_dentry *src_de;
873 exfat_de_iter_get_dirty(iter, j, &src_de);
874 memcpy(src_de, dentry, sizeof(struct exfat_dentry));
880 } else if (repair_file_ask(iter, NULL, ER_DE_UNKNOWN,
881 "unknown entry type %#x", dentry->type)) {
885 *skip_dentries = i + 1;
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);
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),
902 exfat_de_iter_get_dirty(iter, 1, &stream_de);
903 stream_de->stream_valid_size =
904 stream_de->stream_size;
906 *skip_dentries = file_de->file_num_ext + 1;
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;
918 *skip_dentries = file_de->file_num_ext + 1;
923 *skip_dentries = (file_de->file_num_ext + 1);
928 exfat_de_iter_get_dirty(iter, 0, &dentry);
929 dentry->type &= EXFAT_DELETE;
931 for (i = 1; i < *skip_dentries; i++) {
932 exfat_de_iter_get(iter, i, &dentry);
933 if (dentry->type == EXFAT_FILE)
936 exfat_de_iter_get_dirty(iter, i, &dentry);
937 dentry->type &= EXFAT_DELETE;
942 exfat_free_inode(node);
943 return need_delete ? 1 : -EINVAL;
946 static int read_file(struct exfat_de_iter *de_iter,
947 struct exfat_inode **new_node, int *dentry_count)
949 struct exfat_inode *node;
954 ret = read_file_dentry_set(de_iter, &node, dentry_count);
958 ret = check_inode(de_iter, node);
960 exfat_free_inode(node);
964 if (node->attr & ATTR_SUBDIR)
965 exfat_stat.dir_count++;
967 exfat_stat.file_count++;
972 static int read_bitmap(struct exfat *exfat)
974 struct exfat_lookup_filter filter = {
975 .in.type = EXFAT_BITMAP,
976 .in.dentry_count = 0,
980 struct exfat_dentry *dentry;
983 retval = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
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));
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));
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));
1004 exfat->disk_bitmap_clus = le32_to_cpu(dentry->bitmap_start_clu);
1005 exfat->disk_bitmap_size = DIV_ROUND_UP(exfat->clus_count, 8);
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,
1011 free(filter.out.dentry_set);
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)
1021 static int decompress_upcase_table(const __le16 *in_table, size_t in_len,
1022 __u16 *out_table, size_t out_len)
1027 if (in_len > out_len)
1030 for (k = 0; k < out_len; k++)
1033 for (i = 0, k = 0; i < in_len && k < out_len; i++) {
1034 ch = le16_to_cpu(in_table[i]);
1036 if (ch == 0xFFFF && i + 1 < in_len) {
1037 uint16_t len = le16_to_cpu(in_table[++i]);
1041 out_table[k++] = ch;
1047 static int read_upcase_table(struct exfat *exfat)
1049 struct exfat_lookup_filter filter = {
1050 .in.type = EXFAT_UPCASE,
1051 .in.dentry_count = 0,
1055 struct exfat_dentry *dentry = NULL;
1056 __le16 *upcase = NULL;
1061 retval = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
1065 dentry = filter.out.dentry_set;
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));
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));
1083 upcase = malloc(size);
1085 exfat_err("failed to allocate upcase table\n");
1090 if (exfat_read(exfat->blk_dev->dev_fd, upcase, size,
1092 le32_to_cpu(dentry->upcase_start_clu))) != size) {
1093 exfat_err("failed to read upcase table\n");
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));
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),
1112 exfat->upcase_table = calloc(EXFAT_UPCASE_TABLE_CHARS, sizeof(uint16_t));
1113 if (!exfat->upcase_table) {
1118 decompress_upcase_table(upcase, size / 2,
1119 exfat->upcase_table, EXFAT_UPCASE_TABLE_CHARS);
1128 static int read_children(struct exfat_fsck *fsck, struct exfat_inode *dir)
1130 struct exfat *exfat = fsck->exfat;
1131 struct exfat_inode *node = NULL;
1132 struct exfat_dentry *dentry;
1133 struct exfat_de_iter *de_iter;
1137 de_iter = &fsck->de_iter;
1138 ret = exfat_de_iter_init(de_iter, exfat, dir, fsck->buffer_desc);
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));
1149 ret = exfat_de_iter_get(de_iter, 0, &dentry);
1153 fsck_err(dir->parent, dir,
1154 "failed to get a dentry. %d\n", ret);
1160 switch (dentry->type) {
1162 ret = read_file(de_iter, &node, &dentry_count);
1164 exfat_stat.error_count++;
1167 exfat_stat.error_count++;
1168 exfat_stat.fixed_count++;
1172 if ((node->attr & ATTR_SUBDIR) && node->size) {
1174 list_add_tail(&node->sibling,
1176 list_add_tail(&node->list,
1179 exfat_free_inode(node);
1189 if (dir == exfat->root)
1193 if (IS_EXFAT_DELETED(dentry->type))
1195 if (repair_file_ask(de_iter, NULL, ER_DE_UNKNOWN,
1196 "unknown entry type %#x", dentry->type)) {
1197 struct exfat_dentry *dentry;
1199 exfat_de_iter_get_dirty(de_iter, 0, &dentry);
1200 dentry->type &= EXFAT_DELETE;
1205 exfat_de_iter_advance(de_iter, dentry_count);
1208 exfat_de_iter_flush(de_iter);
1211 exfat_free_children(dir, false);
1212 INIT_LIST_HEAD(&dir->children);
1213 exfat_de_iter_flush(de_iter);
1217 /* write bitmap segments for clusters which are marked
1218 * as free, but allocated to files.
1220 static int write_bitmap(struct exfat_fsck *fsck)
1222 struct exfat *exfat = fsck->exfat;
1223 bitmap_t *disk_b, *alloc_b, *ohead_b;
1225 unsigned int i, bitmap_bytes, byte_offset, write_bytes;
1227 dev_offset = exfat_c2o(exfat, exfat->disk_bitmap_clus);
1228 bitmap_bytes = EXFAT_BITMAP_SIZE(le32_to_cpu(exfat->bs->bsx.clu_count));
1230 disk_b = (bitmap_t *)exfat->disk_bitmap;
1231 alloc_b = (bitmap_t *)exfat->alloc_bitmap;
1232 ohead_b = (bitmap_t *)exfat->ohead_bitmap;
1234 for (i = 0; i < bitmap_bytes / sizeof(bitmap_t); i++)
1235 ohead_b[i] = alloc_b[i] | disk_b[i];
1238 while (i < bitmap_bytes / sizeof(bitmap_t)) {
1239 if (ohead_b[i] == disk_b[i]) {
1244 byte_offset = ((i * sizeof(bitmap_t)) / 512) * 512;
1245 write_bytes = MIN(512, bitmap_bytes - byte_offset);
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)
1252 i = (byte_offset + write_bytes) / sizeof(bitmap_t);
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.
1265 static int exfat_filesystem_check(struct exfat_fsck *fsck)
1267 struct exfat *exfat = fsck->exfat;
1268 struct exfat_inode *dir;
1269 int ret = 0, dir_errors;
1272 exfat_err("root is NULL\n");
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");
1282 list_add(&exfat->root->list, &exfat->dir_list);
1284 while (!list_empty(&exfat->dir_list)) {
1285 dir = list_entry(exfat->dir_list.next,
1286 struct exfat_inode, list);
1288 if (!(dir->attr & ATTR_SUBDIR)) {
1289 fsck_err(dir->parent, dir,
1290 "failed to travel directories. "
1291 "the node is not directory\n");
1296 dir_errors = read_children(fsck, dir);
1298 exfat_resolve_path(&path_resolve_ctx, dir);
1299 exfat_debug("failed to check dentries: %s\n",
1300 path_resolve_ctx.local_path);
1304 list_del(&dir->list);
1305 exfat_free_file_children(dir);
1306 exfat_free_ancestors(dir);
1309 exfat_free_dir_list(exfat);
1310 free(fsck->name_hash_bitmap);
1314 static int exfat_root_dir_check(struct exfat *exfat)
1316 struct exfat_inode *root;
1317 clus_t clus_count = 0;
1320 root = exfat_alloc_inode(ATTR_SUBDIR);
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);
1332 root->size = clus_count * exfat->clus_size;
1334 exfat_stat.dir_count++;
1335 exfat_debug("root directory: start cluster[0x%x] size[0x%" PRIx64 "]\n",
1336 root->first_clus, root->size);
1338 err = exfat_read_volume_label(exfat);
1339 if (err && err != EOF)
1340 exfat_err("failed to read volume label\n");
1342 err = read_bitmap(exfat);
1344 exfat_err("failed to read bitmap\n");
1348 err = read_upcase_table(exfat);
1350 exfat_err("failed to read upcase table\n");
1354 root->dev_offset = 0;
1355 err = exfat_build_file_dentry_set(exfat, " ", ATTR_SUBDIR,
1356 &root->dentry_set, &root->dentry_count);
1358 exfat_free_inode(root);
1364 static int read_lostfound(struct exfat *exfat, struct exfat_inode **lostfound)
1366 struct exfat_lookup_filter filter;
1367 struct exfat_inode *inode;
1370 err = exfat_lookup_file(exfat, exfat->root, "LOST+FOUND", &filter);
1374 inode = exfat_alloc_inode(ATTR_SUBDIR);
1376 free(filter.out.dentry_set);
1380 inode->dentry_set = filter.out.dentry_set;
1381 inode->dentry_count = filter.out.dentry_count;
1382 inode->dev_offset = filter.out.dev_offset;
1385 le32_to_cpu(filter.out.dentry_set[1].dentry.stream.start_clu);
1387 le64_to_cpu(filter.out.dentry_set[1].dentry.stream.size);
1393 /* Create temporary files under LOST+FOUND and assign orphan
1394 * chains of clusters to these files.
1396 static int rescue_orphan_clusters(struct exfat_fsck *fsck)
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;
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,
1413 clu_count = le32_to_cpu(exfat->bs->bsx.clu_count);
1415 /* find clusters which are not marked as free, but not allocated to
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];
1424 /* no orphan clusters */
1425 if (exfat_bitmap_find_one(exfat, exfat->ohead_bitmap,
1426 EXFAT_FIRST_CLUSTER, &s_clu))
1429 err = exfat_create_file(exfat_fsck.exfat,
1430 exfat_fsck.exfat->root,
1434 exfat_err("failed to create LOST+FOUND directory\n");
1438 if (fsync(exfat_fsck.exfat->blk_dev->dev_fd) != 0) {
1439 exfat_err("failed to sync()\n");
1443 err = read_lostfound(exfat, &lostfound);
1445 exfat_err("failed to find LOST+FOUND\n");
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");
1456 loc.parent = lostfound;
1457 loc.file_offset = lf.out.file_offset;
1458 loc.dev_offset = lf.out.dev_offset;
1460 /* build a template dentry set */
1461 err = exfat_build_file_dentry_set(exfat, name, 0, &dset, &dcount);
1463 exfat_err("failed to create a temporary file in LOST+FOUNDn");
1466 dset[1].dentry.stream.flags |= EXFAT_SF_CONTIGUOUS;
1468 /* create temporary files and allocate contiguous orphan clusters
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;
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);
1483 err = exfat_add_dentry_set(exfat, &loc, dset, dcount, true);
1491 exfat_free_inode(lostfound);
1495 static char *bytes_to_human_readable(size_t bytes)
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;
1502 while (i && (bytes >> i * 10) == 0)
1506 quoti = (unsigned int)(bytes / (1ULL << shift));
1509 remain = (unsigned int)
1510 ((bytes & ((1ULL << shift) - 1)) >> (shift - 10));
1511 remain = (remain * 100) / 1024;
1514 snprintf(buf, sizeof(buf), "%u.%02u %s", quoti, remain, units[i]);
1518 static void exfat_show_info(struct exfat_fsck *fsck, const char *dev_name)
1520 struct exfat *exfat = fsck->exfat;
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));
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);
1541 int main(int argc, char * const argv[])
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;
1549 memset(&ui, 0, sizeof(ui));
1550 memset(&bd, 0, sizeof(bd));
1552 print_level = EXFAT_ERROR;
1554 if (!setlocale(LC_CTYPE, ""))
1555 exfat_err("failed to init locale/codeset\n");
1558 while ((c = getopt_long(argc, argv, "arynpbsVvh", opts, NULL)) != EOF) {
1561 if (ui.options & FSCK_OPTS_REPAIR_ALL)
1563 ui.options |= FSCK_OPTS_REPAIR_NO;
1566 if (ui.options & FSCK_OPTS_REPAIR_ALL)
1568 ui.options |= FSCK_OPTS_REPAIR_ASK;
1571 if (ui.options & FSCK_OPTS_REPAIR_ALL)
1573 ui.options |= FSCK_OPTS_REPAIR_YES;
1577 if (ui.options & FSCK_OPTS_REPAIR_ALL)
1579 ui.options |= FSCK_OPTS_REPAIR_AUTO;
1582 ui.options |= FSCK_OPTS_IGNORE_BAD_FS_NAME;
1585 ui.options |= FSCK_OPTS_RESCUE_CLUS;
1588 version_only = true;
1591 if (print_level < EXFAT_DEBUG)
1602 if (optind != argc - 1)
1606 exit(FSCK_EXIT_SYNTAX_ERROR);
1607 if (ui.options & FSCK_OPTS_REPAIR_WRITE)
1608 ui.ei.writeable = true;
1610 if (ui.options & (FSCK_OPTS_IGNORE_BAD_FS_NAME |
1611 FSCK_OPTS_RESCUE_CLUS))
1613 ui.options |= FSCK_OPTS_REPAIR_NO;
1614 ui.ei.writeable = false;
1617 exfat_fsck.options = ui.options;
1619 snprintf(ui.ei.dev_name, sizeof(ui.ei.dev_name), "%s", argv[optind]);
1620 ret = exfat_get_blk_dev_info(&ui.ei, &bd);
1622 exfat_err("failed to open %s. %d\n", ui.ei.dev_name, ret);
1623 return FSCK_EXIT_OPERATION_ERROR;
1626 ret = exfat_boot_region_check(&bd, &bs,
1627 ui.options & FSCK_OPTS_IGNORE_BAD_FS_NAME ?
1632 exfat_fsck.exfat = exfat_alloc_exfat(&bd, bs);
1633 if (!exfat_fsck.exfat) {
1638 exfat_fsck.buffer_desc = exfat_alloc_buffer(exfat_fsck.exfat);
1639 if (!exfat_fsck.buffer_desc) {
1644 if ((exfat_fsck.options & FSCK_OPTS_REPAIR_WRITE) &&
1645 exfat_mark_volume_dirty(exfat_fsck.exfat, true)) {
1650 exfat_debug("verifying root directory...\n");
1651 ret = exfat_root_dir_check(exfat_fsck.exfat);
1653 exfat_err("failed to verify root directory.\n");
1657 exfat_debug("verifying directory entries...\n");
1658 ret = exfat_filesystem_check(&exfat_fsck);
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;
1668 if (exfat_fsck.options & FSCK_OPTS_REPAIR_WRITE) {
1669 ret = write_bitmap(&exfat_fsck);
1671 exfat_err("failed to write bitmap\n");
1676 if (ui.ei.writeable && fsync(bd.dev_fd)) {
1677 exfat_err("failed to sync\n");
1681 if (exfat_fsck.options & FSCK_OPTS_REPAIR_WRITE)
1682 exfat_mark_volume_dirty(exfat_fsck.exfat, false);
1685 exfat_show_info(&exfat_fsck, ui.ei.dev_name);
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;
1695 exit_code = FSCK_EXIT_NO_ERRORS;
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);