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