• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
usage(char * name)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 
check_clus_chain(struct exfat_de_iter * de_iter,struct exfat_inode * node)105 static int check_clus_chain(struct exfat_de_iter *de_iter,
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, 1, &stream_de);
224 	if (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 
root_check_clus_chain(struct exfat * exfat,struct exfat_inode * node,clus_t * clus_count)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 
boot_region_checksum(int dev_fd,int bs_offset,unsigned int sect_size)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 
exfat_mark_volume_dirty(struct exfat * exfat,bool dirty)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 
read_boot_region(struct exfat_blk_dev * bd,struct pbr ** pbr,int bs_offset,unsigned int sect_size,bool verbose)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 
375 	*pbr = NULL;
376 	bs = (struct pbr *)malloc(sizeof(struct pbr));
377 	if (!bs) {
378 		exfat_err("failed to allocate memory\n");
379 		return -ENOMEM;
380 	}
381 
382 	if (exfat_read(bd->dev_fd, bs, sizeof(*bs),
383 			bs_offset * sect_size) != (ssize_t)sizeof(*bs)) {
384 		exfat_err("failed to read a boot sector\n");
385 		ret = -EIO;
386 		goto err;
387 	}
388 
389 	if (memcmp(bs->bpb.oem_name, "EXFAT   ", 8) != 0) {
390 		if (verbose)
391 			exfat_err("failed to find exfat file system\n");
392 		goto err;
393 	}
394 
395 	ret = boot_region_checksum(bd->dev_fd, bs_offset, sect_size);
396 	if (ret < 0)
397 		goto err;
398 
399 	ret = -EINVAL;
400 	if (EXFAT_SECTOR_SIZE(bs) < 512 || EXFAT_SECTOR_SIZE(bs) > 4 * KB) {
401 		if (verbose)
402 			exfat_err("too small or big sector size: %d\n",
403 				  EXFAT_SECTOR_SIZE(bs));
404 		goto err;
405 	}
406 
407 	if (EXFAT_CLUSTER_SIZE(bs) > 32 * MB) {
408 		if (verbose)
409 			exfat_err("too big cluster size: %d\n",
410 				  EXFAT_CLUSTER_SIZE(bs));
411 		goto err;
412 	}
413 
414 	if (bs->bsx.fs_version[1] != 1 || bs->bsx.fs_version[0] != 0) {
415 		if (verbose)
416 			exfat_err("unsupported exfat version: %d.%d\n",
417 				  bs->bsx.fs_version[1], bs->bsx.fs_version[0]);
418 		goto err;
419 	}
420 
421 	if (bs->bsx.num_fats != 1) {
422 		if (verbose)
423 			exfat_err("unsupported FAT count: %d\n",
424 				  bs->bsx.num_fats);
425 		goto err;
426 	}
427 
428 	if (le64_to_cpu(bs->bsx.vol_length) * EXFAT_SECTOR_SIZE(bs) >
429 			bd->size) {
430 		if (verbose)
431 			exfat_err("too large sector count: %" PRIu64 ", expected: %llu\n",
432 				  le64_to_cpu(bs->bsx.vol_length),
433 				  bd->num_sectors);
434 		goto err;
435 	}
436 
437 	if (le32_to_cpu(bs->bsx.clu_count) * EXFAT_CLUSTER_SIZE(bs) >
438 			bd->size) {
439 		if (verbose)
440 			exfat_err("too large cluster count: %u, expected: %u\n",
441 				  le32_to_cpu(bs->bsx.clu_count),
442 				  bd->num_clusters);
443 		goto err;
444 	}
445 
446 	*pbr = bs;
447 	return 0;
448 err:
449 	free(bs);
450 	return ret;
451 }
452 
restore_boot_region(struct exfat_blk_dev * bd,unsigned int sect_size)453 static int restore_boot_region(struct exfat_blk_dev *bd, unsigned int sect_size)
454 {
455 	int i;
456 	char *sector;
457 	int ret;
458 
459 	sector = malloc(sect_size);
460 	if (!sector)
461 		return -ENOMEM;
462 
463 	for (i = 0; i < 12; i++) {
464 		if (exfat_read(bd->dev_fd, sector, sect_size,
465 				BACKUP_BOOT_SEC_IDX * sect_size +
466 				i * sect_size) !=
467 				(ssize_t)sect_size) {
468 			ret = -EIO;
469 			goto free_sector;
470 		}
471 		if (i == 0)
472 			((struct pbr *)sector)->bsx.perc_in_use = 0xff;
473 
474 		if (exfat_write(bd->dev_fd, sector, sect_size,
475 				BOOT_SEC_IDX * sect_size +
476 				i * sect_size) !=
477 				(ssize_t)sect_size) {
478 			ret = -EIO;
479 			goto free_sector;
480 		}
481 	}
482 
483 	if (fsync(bd->dev_fd)) {
484 		ret = -EIO;
485 		goto free_sector;
486 	}
487 	ret = 0;
488 
489 free_sector:
490 	free(sector);
491 	return ret;
492 }
493 
exfat_boot_region_check(struct exfat_blk_dev * blkdev,struct pbr ** bs,bool ignore_bad_fs_name)494 static int exfat_boot_region_check(struct exfat_blk_dev *blkdev,
495 				   struct pbr **bs,
496 				   bool ignore_bad_fs_name)
497 {
498 	struct pbr *boot_sect;
499 	unsigned int sect_size;
500 	int ret;
501 
502 	/* First, find out the exfat sector size */
503 	boot_sect = malloc(sizeof(*boot_sect));
504 	if (boot_sect == NULL)
505 		return -ENOMEM;
506 
507 	if (exfat_read(blkdev->dev_fd, boot_sect,
508 		       sizeof(*boot_sect), 0) != (ssize_t)sizeof(*boot_sect)) {
509 		exfat_err("failed to read Main boot sector\n");
510 		free(boot_sect);
511 		return -EIO;
512 	}
513 
514 	if (memcmp(boot_sect->bpb.oem_name, "EXFAT   ", 8) != 0 &&
515 	    !ignore_bad_fs_name) {
516 		exfat_err("Bad fs_name in boot sector, which does not describe a valid exfat filesystem\n");
517 		free(boot_sect);
518 		return -ENOTSUP;
519 	}
520 
521 	sect_size = 1 << boot_sect->bsx.sect_size_bits;
522 	free(boot_sect);
523 
524 	/* check boot regions */
525 	ret = read_boot_region(blkdev, bs,
526 			       BOOT_SEC_IDX, sect_size, true);
527 	if (ret == -EINVAL &&
528 	    exfat_repair_ask(&exfat_fsck, ER_BS_BOOT_REGION,
529 			     "boot region is corrupted. try to restore the region from backup"
530 				)) {
531 		const unsigned int sector_sizes[] = {512, 4096, 1024, 2048};
532 		unsigned int i;
533 
534 		if (sect_size >= 512 && sect_size <= EXFAT_MAX_SECTOR_SIZE) {
535 			ret = read_boot_region(blkdev, bs,
536 					       BACKUP_BOOT_SEC_IDX, sect_size,
537 					       false);
538 			if (!ret)
539 				goto restore;
540 		}
541 
542 		for (i = 0; i < sizeof(sector_sizes)/sizeof(sector_sizes[0]); i++) {
543 			if (sector_sizes[i] == sect_size)
544 				continue;
545 
546 			ret = read_boot_region(blkdev, bs,
547 					       BACKUP_BOOT_SEC_IDX,
548 					       sector_sizes[i], false);
549 			if (!ret) {
550 				sect_size = sector_sizes[i];
551 				goto restore;
552 			}
553 		}
554 		exfat_err("backup boot region is also corrupted\n");
555 	}
556 
557 	return ret;
558 restore:
559 	ret = restore_boot_region(blkdev, sect_size);
560 	if (ret) {
561 		exfat_err("failed to restore boot region from backup\n");
562 		free(*bs);
563 		*bs = NULL;
564 	}
565 	return ret;
566 }
567 
file_calc_checksum(struct exfat_de_iter * iter)568 static uint16_t file_calc_checksum(struct exfat_de_iter *iter)
569 {
570 	uint16_t checksum;
571 	struct exfat_dentry *file_de, *de;
572 	int i;
573 
574 	checksum = 0;
575 	exfat_de_iter_get(iter, 0, &file_de);
576 
577 	exfat_calc_dentry_checksum(file_de, &checksum, true);
578 	for (i = 1; i <= file_de->file_num_ext; i++) {
579 		exfat_de_iter_get(iter, i, &de);
580 		exfat_calc_dentry_checksum(de, &checksum, false);
581 	}
582 	return checksum;
583 }
584 
585 /*
586  * return 0 if there are no errors, or 1 if errors are fixed, or
587  * an error code
588  */
check_inode(struct exfat_de_iter * iter,struct exfat_inode * node)589 static int check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)
590 {
591 	struct exfat *exfat = iter->exfat;
592 	struct exfat_dentry *dentry;
593 	int ret = 0;
594 	uint16_t checksum;
595 	bool valid = true;
596 
597 	ret = check_clus_chain(iter, node);
598 	if (ret < 0)
599 		return ret;
600 
601 	if (node->size > le32_to_cpu(exfat->bs->bsx.clu_count) *
602 				(uint64_t)exfat->clus_size) {
603 		fsck_err(iter->parent, node,
604 			"size %" PRIu64 " is greater than cluster heap\n",
605 			node->size);
606 		valid = false;
607 	}
608 
609 	if (node->size == 0 && node->is_contiguous) {
610 		if (repair_file_ask(iter, node, ER_FILE_ZERO_NOFAT,
611 				"empty, but has no Fat chain")) {
612 			exfat_de_iter_get_dirty(iter, 1, &dentry);
613 			dentry->stream_flags &= ~EXFAT_SF_CONTIGUOUS;
614 			ret = 1;
615 		} else
616 			valid = false;
617 	}
618 
619 	if ((node->attr & ATTR_SUBDIR) &&
620 			node->size % exfat->clus_size != 0) {
621 		fsck_err(iter->parent, node,
622 			"directory size %" PRIu64 " is not divisible by %d\n",
623 			node->size, exfat->clus_size);
624 		valid = false;
625 	}
626 
627 	checksum = file_calc_checksum(iter);
628 	exfat_de_iter_get(iter, 0, &dentry);
629 	if (checksum != le16_to_cpu(dentry->file_checksum)) {
630 		exfat_de_iter_get_dirty(iter, 0, &dentry);
631 		dentry->file_checksum = cpu_to_le16(checksum);
632 		ret = 1;
633 	}
634 
635 	return valid ? ret : -EINVAL;
636 }
637 
check_name_dentry_set(struct exfat_de_iter * iter,struct exfat_inode * inode)638 static int check_name_dentry_set(struct exfat_de_iter *iter,
639 				 struct exfat_inode *inode)
640 {
641 	struct exfat_dentry *stream_de;
642 	size_t name_len;
643 	__u16 hash;
644 
645 	exfat_de_iter_get(iter, 1, &stream_de);
646 
647 	name_len = exfat_utf16_len(inode->name, NAME_BUFFER_SIZE);
648 	if (stream_de->stream_name_len != name_len) {
649 		if (repair_file_ask(iter, NULL, ER_DE_NAME_LEN,
650 				    "the name length of a file is wrong")) {
651 			exfat_de_iter_get_dirty(iter, 1, &stream_de);
652 			stream_de->stream_name_len = (__u8)name_len;
653 		} else {
654 			return -EINVAL;
655 		}
656 	}
657 
658 	hash = exfat_calc_name_hash(iter->exfat, inode->name, (int)name_len);
659 	if (cpu_to_le16(hash) != stream_de->stream_name_hash) {
660 		if (repair_file_ask(iter, NULL, ER_DE_NAME_HASH,
661 				    "the name hash of a file is wrong")) {
662 			exfat_de_iter_get_dirty(iter, 1, &stream_de);
663 			stream_de->stream_name_hash = cpu_to_le16(hash);
664 		} else {
665 			return -EINVAL;
666 		}
667 	}
668 	return 0;
669 }
670 
check_bad_char(char w)671 static int check_bad_char(char w)
672 {
673 	return (w < 0x0020) || (w == '*') || (w == '?') || (w == '<') ||
674 		(w == '>') || (w == '|') || (w == '"') || (w == ':') ||
675 		(w == '/') || (w == '\\');
676 }
677 
get_rename_from_user(struct exfat_de_iter * iter)678 static char *get_rename_from_user(struct exfat_de_iter *iter)
679 {
680 	char *rename = malloc(ENTRY_NAME_MAX + 2);
681 
682 	if (!rename)
683 		return NULL;
684 
685 retry:
686 	/* +2 means LF(Line Feed) and NULL terminator */
687 	memset(rename, 0x1, ENTRY_NAME_MAX + 2);
688 	printf("New name: ");
689 	if (fgets(rename, ENTRY_NAME_MAX + 2, stdin)) {
690 		int i, len, err;
691 		struct exfat_lookup_filter filter;
692 
693 		len = strlen(rename);
694 		/* Remove LF in filename */
695 		rename[len - 1] = '\0';
696 		for (i = 0; i < len - 1; i++) {
697 			if (check_bad_char(rename[i])) {
698 				printf("filename contain invalid character(%c)\n", rename[i]);
699 				goto retry;
700 			}
701 		}
702 
703 		exfat_de_iter_flush(iter);
704 		err = exfat_lookup_file(iter->exfat, iter->parent, rename, &filter);
705 		if (!err) {
706 			printf("file(%s) already exists, retry to insert name\n", rename);
707 			goto retry;
708 		}
709 	}
710 
711 	return rename;
712 }
713 
generate_rename(struct exfat_de_iter * iter)714 static char *generate_rename(struct exfat_de_iter *iter)
715 {
716 	char *rename;
717 
718 	if (iter->dot_name_num > DOT_NAME_NUM_MAX)
719 		return NULL;
720 
721 	rename = malloc(ENTRY_NAME_MAX + 1);
722 	if (!rename)
723 		return NULL;
724 
725 	while (1) {
726 		struct exfat_lookup_filter filter;
727 		int err;
728 
729 		snprintf(rename, ENTRY_NAME_MAX + 1, "FILE%07d.CHK",
730 			 iter->dot_name_num++);
731 		err = exfat_lookup_file(iter->exfat, iter->parent, rename,
732 					&filter);
733 		if (!err)
734 			continue;
735 		break;
736 	}
737 
738 	return rename;
739 }
740 
741 const __le16 MSDOS_DOT[ENTRY_NAME_MAX] = {cpu_to_le16(46), 0, };
742 const __le16 MSDOS_DOTDOT[ENTRY_NAME_MAX] = {cpu_to_le16(46), cpu_to_le16(46), 0, };
743 
handle_dot_dotdot_filename(struct exfat_de_iter * iter,struct exfat_dentry * dentry,int strm_name_len)744 static int handle_dot_dotdot_filename(struct exfat_de_iter *iter,
745 				      struct exfat_dentry *dentry,
746 				      int strm_name_len)
747 {
748 	char *filename;
749 	char error_msg[150];
750 	int num;
751 
752 	if (!memcmp(dentry->name_unicode, MSDOS_DOT, strm_name_len * 2))
753 		filename = ".";
754 	else if (!memcmp(dentry->name_unicode, MSDOS_DOTDOT,
755 			 strm_name_len * 2))
756 		filename = "..";
757 	else
758 		return 0;
759 
760 	sprintf(error_msg, "ERROR: '%s' filename is not allowed.\n"
761 			" [1] Insert the name you want to rename.\n"
762 			" [2] Automatically renames filename.\n"
763 			" [3] Bypass this check(No repair)\n", filename);
764 ask_again:
765 	num = exfat_repair_ask(&exfat_fsck, ER_DE_DOT_NAME,
766 			       error_msg);
767 	if (num) {
768 		__le16 utf16_name[ENTRY_NAME_MAX];
769 		char *rename = NULL;
770 		__u16 hash;
771 		struct exfat_dentry *stream_de;
772 		int ret;
773 
774 		switch (num) {
775 		case 1:
776 			rename = get_rename_from_user(iter);
777 			break;
778 		case 2:
779 			rename = generate_rename(iter);
780 			break;
781 		case 3:
782 			break;
783 		default:
784 			exfat_info("select 1 or 2 number instead of %d\n", num);
785 			goto ask_again;
786 		}
787 
788 		if (!rename)
789 			return -EINVAL;
790 
791 		exfat_info("%s filename is renamed to %s\n", filename, rename);
792 
793 		exfat_de_iter_get_dirty(iter, 2, &dentry);
794 
795 		memset(utf16_name, 0, sizeof(utf16_name));
796 		ret = exfat_utf16_enc(rename, utf16_name, sizeof(utf16_name));
797 		free(rename);
798 		if (ret < 0)
799 			return ret;
800 
801 		ret >>= 1;
802 		memcpy(dentry->name_unicode, utf16_name, ENTRY_NAME_MAX * 2);
803 		hash = exfat_calc_name_hash(iter->exfat, utf16_name, ret);
804 		exfat_de_iter_get_dirty(iter, 1, &stream_de);
805 		stream_de->stream_name_len = (__u8)ret;
806 		stream_de->stream_name_hash = cpu_to_le16(hash);
807 	}
808 
809 	return 0;
810 }
811 
read_file_dentry_set(struct exfat_de_iter * iter,struct exfat_inode ** new_node,int * skip_dentries)812 static int read_file_dentry_set(struct exfat_de_iter *iter,
813 				struct exfat_inode **new_node, int *skip_dentries)
814 {
815 	struct exfat_dentry *file_de, *stream_de, *dentry;
816 	struct exfat_inode *node = NULL;
817 	int i, ret;
818 	bool need_delete = false;
819 	uint16_t checksum;
820 
821 	ret = exfat_de_iter_get(iter, 0, &file_de);
822 	if (ret || file_de->type != EXFAT_FILE) {
823 		exfat_err("failed to get file dentry\n");
824 		return -EINVAL;
825 	}
826 
827 	checksum = file_calc_checksum(iter);
828 	if (checksum != le16_to_cpu(file_de->file_checksum)) {
829 		if (repair_file_ask(iter, NULL, ER_DE_CHECKSUM,
830 				    "the checksum of a file is wrong"))
831 			need_delete = true;
832 		*skip_dentries = 1;
833 		goto skip_dset;
834 	}
835 
836 	if (file_de->file_num_ext < 2) {
837 		if (repair_file_ask(iter, NULL, ER_DE_SECONDARY_COUNT,
838 				    "a file has too few secondary count. %d",
839 				    file_de->file_num_ext))
840 			need_delete = true;
841 		*skip_dentries = 1;
842 		goto skip_dset;
843 	}
844 
845 	ret = exfat_de_iter_get(iter, 1, &stream_de);
846 	if (ret || stream_de->type != EXFAT_STREAM) {
847 		if (repair_file_ask(iter, NULL, ER_DE_STREAM,
848 				    "failed to get stream dentry"))
849 			need_delete = true;
850 		*skip_dentries = 2;
851 		goto skip_dset;
852 	}
853 
854 	*new_node = NULL;
855 	node = exfat_alloc_inode(le16_to_cpu(file_de->file_attr));
856 	if (!node)
857 		return -ENOMEM;
858 
859 	for (i = 2; i <= file_de->file_num_ext; i++) {
860 		ret = exfat_de_iter_get(iter, i, &dentry);
861 		if (ret || dentry->type != EXFAT_NAME) {
862 			if (i > 2 && repair_file_ask(iter, NULL, ER_DE_NAME,
863 						     "failed to get name dentry")) {
864 				exfat_de_iter_get_dirty(iter, 0, &file_de);
865 				file_de->file_num_ext = i - 1;
866 				break;
867 			}
868 			*skip_dentries = i + 1;
869 			goto skip_dset;
870 		}
871 
872 		memcpy(node->name +
873 		       (i - 2) * ENTRY_NAME_MAX, dentry->name_unicode,
874 		       sizeof(dentry->name_unicode));
875 	}
876 
877 	ret = check_name_dentry_set(iter, node);
878 	if (ret) {
879 		*skip_dentries = file_de->file_num_ext + 1;
880 		goto skip_dset;
881 	}
882 
883 	if (file_de->file_num_ext == 2 && stream_de->stream_name_len <= 2) {
884 		ret = handle_dot_dotdot_filename(iter, dentry,
885 				stream_de->stream_name_len);
886 		if (ret < 0) {
887 			*skip_dentries = file_de->file_num_ext + 1;
888 			goto skip_dset;
889 		}
890 	}
891 
892 	node->first_clus = le32_to_cpu(stream_de->stream_start_clu);
893 	node->is_contiguous =
894 		((stream_de->stream_flags & EXFAT_SF_CONTIGUOUS) != 0);
895 	node->size = le64_to_cpu(stream_de->stream_size);
896 
897 	if (node->size < le64_to_cpu(stream_de->stream_valid_size)) {
898 		*skip_dentries = file_de->file_num_ext + 1;
899 		if (repair_file_ask(iter, node, ER_FILE_VALID_SIZE,
900 				    "valid size %" PRIu64 " greater than size %" PRIu64,
901 				    le64_to_cpu(stream_de->stream_valid_size),
902 				    node->size)) {
903 			exfat_de_iter_get_dirty(iter, 1, &stream_de);
904 			stream_de->stream_valid_size =
905 					stream_de->stream_size;
906 		} else {
907 			*skip_dentries = file_de->file_num_ext + 1;
908 			goto skip_dset;
909 		}
910 	}
911 
912 	*skip_dentries = (file_de->file_num_ext + 1);
913 	*new_node = node;
914 	return 0;
915 skip_dset:
916 	if (need_delete) {
917 		exfat_de_iter_get_dirty(iter, 0, &dentry);
918 		dentry->type &= EXFAT_DELETE;
919 	}
920 	for (i = 1; i < *skip_dentries; i++) {
921 		exfat_de_iter_get(iter, i, &dentry);
922 		if (dentry->type == EXFAT_FILE)
923 			break;
924 		if (need_delete) {
925 			exfat_de_iter_get_dirty(iter, i, &dentry);
926 			dentry->type &= EXFAT_DELETE;
927 		}
928 	}
929 	*skip_dentries = i;
930 	*new_node = NULL;
931 	exfat_free_inode(node);
932 	return need_delete ? 1 : -EINVAL;
933 }
934 
read_file(struct exfat_de_iter * de_iter,struct exfat_inode ** new_node,int * dentry_count)935 static int read_file(struct exfat_de_iter *de_iter,
936 		struct exfat_inode **new_node, int *dentry_count)
937 {
938 	struct exfat_inode *node;
939 	int ret;
940 
941 	*new_node = NULL;
942 
943 	ret = read_file_dentry_set(de_iter, &node, dentry_count);
944 	if (ret)
945 		return ret;
946 
947 	ret = check_inode(de_iter, node);
948 	if (ret < 0) {
949 		exfat_free_inode(node);
950 		return -EINVAL;
951 	}
952 
953 	if (node->attr & ATTR_SUBDIR)
954 		exfat_stat.dir_count++;
955 	else
956 		exfat_stat.file_count++;
957 	*new_node = node;
958 	return ret;
959 }
960 
read_bitmap(struct exfat * exfat)961 static int read_bitmap(struct exfat *exfat)
962 {
963 	struct exfat_lookup_filter filter = {
964 		.in.type	= EXFAT_BITMAP,
965 		.in.filter	= NULL,
966 		.in.param	= NULL,
967 	};
968 	struct exfat_dentry *dentry;
969 	int retval;
970 
971 	retval = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
972 	if (retval)
973 		return retval;
974 
975 	dentry = filter.out.dentry_set;
976 	exfat_debug("start cluster %#x, size %#" PRIx64 "\n",
977 			le32_to_cpu(dentry->bitmap_start_clu),
978 			le64_to_cpu(dentry->bitmap_size));
979 
980 	if (le64_to_cpu(dentry->bitmap_size) <
981 			DIV_ROUND_UP(exfat->clus_count, 8)) {
982 		exfat_err("invalid size of allocation bitmap. 0x%" PRIx64 "\n",
983 				le64_to_cpu(dentry->bitmap_size));
984 		return -EINVAL;
985 	}
986 	if (!exfat_heap_clus(exfat, le32_to_cpu(dentry->bitmap_start_clu))) {
987 		exfat_err("invalid start cluster of allocate bitmap. 0x%x\n",
988 				le32_to_cpu(dentry->bitmap_start_clu));
989 		return -EINVAL;
990 	}
991 
992 	exfat->disk_bitmap_clus = le32_to_cpu(dentry->bitmap_start_clu);
993 	exfat->disk_bitmap_size = DIV_ROUND_UP(exfat->clus_count, 8);
994 
995 	exfat_bitmap_set_range(exfat, exfat->alloc_bitmap,
996 			       le64_to_cpu(dentry->bitmap_start_clu),
997 			       DIV_ROUND_UP(exfat->disk_bitmap_size,
998 					    exfat->clus_size));
999 	free(filter.out.dentry_set);
1000 
1001 	if (exfat_read(exfat->blk_dev->dev_fd, exfat->disk_bitmap,
1002 			exfat->disk_bitmap_size,
1003 			exfat_c2o(exfat, exfat->disk_bitmap_clus)) !=
1004 			(ssize_t)exfat->disk_bitmap_size)
1005 		return -EIO;
1006 	return 0;
1007 }
1008 
decompress_upcase_table(const __le16 * in_table,size_t in_len,__u16 * out_table,size_t out_len)1009 static int decompress_upcase_table(const __le16 *in_table, size_t in_len,
1010 				   __u16 *out_table, size_t out_len)
1011 {
1012 	size_t i, k;
1013 	uint16_t ch;
1014 
1015 	if (in_len > out_len)
1016 		return -E2BIG;
1017 
1018 	for (k = 0; k < out_len; k++)
1019 		out_table[k] = k;
1020 
1021 	for (i = 0, k = 0; i < in_len && k < out_len; i++) {
1022 		ch = le16_to_cpu(in_table[i]);
1023 
1024 		if (ch == 0xFFFF && i + 1 < in_len) {
1025 			uint16_t len = le16_to_cpu(in_table[++i]);
1026 
1027 			k += len;
1028 		} else {
1029 			out_table[k++] = ch;
1030 		}
1031 	}
1032 	return 0;
1033 }
1034 
read_upcase_table(struct exfat * exfat)1035 static int read_upcase_table(struct exfat *exfat)
1036 {
1037 	struct exfat_lookup_filter filter = {
1038 		.in.type	= EXFAT_UPCASE,
1039 		.in.filter	= NULL,
1040 		.in.param	= NULL,
1041 	};
1042 	struct exfat_dentry *dentry = NULL;
1043 	__le16 *upcase = NULL;
1044 	int retval;
1045 	ssize_t size;
1046 	__le32 checksum;
1047 
1048 	retval = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
1049 	if (retval)
1050 		return retval;
1051 
1052 	dentry = filter.out.dentry_set;
1053 
1054 	if (!exfat_heap_clus(exfat, le32_to_cpu(dentry->upcase_start_clu))) {
1055 		exfat_err("invalid start cluster of upcase table. 0x%x\n",
1056 			le32_to_cpu(dentry->upcase_start_clu));
1057 		retval = -EINVAL;
1058 		goto out;
1059 	}
1060 
1061 	size = (ssize_t)le64_to_cpu(dentry->upcase_size);
1062 	if (size > (ssize_t)(EXFAT_MAX_UPCASE_CHARS * sizeof(__le16)) ||
1063 			size == 0 || size % sizeof(__le16)) {
1064 		exfat_err("invalid size of upcase table. 0x%" PRIx64 "\n",
1065 			le64_to_cpu(dentry->upcase_size));
1066 		retval = -EINVAL;
1067 		goto out;
1068 	}
1069 
1070 	upcase = (__le16 *)malloc(size);
1071 	if (!upcase) {
1072 		exfat_err("failed to allocate upcase table\n");
1073 		retval = -ENOMEM;
1074 		goto out;
1075 	}
1076 
1077 	if (exfat_read(exfat->blk_dev->dev_fd, upcase, size,
1078 			exfat_c2o(exfat,
1079 			le32_to_cpu(dentry->upcase_start_clu))) != size) {
1080 		exfat_err("failed to read upcase table\n");
1081 		retval = -EIO;
1082 		goto out;
1083 	}
1084 
1085 	checksum = 0;
1086 	boot_calc_checksum((unsigned char *)upcase, size, false, &checksum);
1087 	if (le32_to_cpu(dentry->upcase_checksum) != checksum) {
1088 		exfat_err("corrupted upcase table %#x (expected: %#x)\n",
1089 			checksum, le32_to_cpu(dentry->upcase_checksum));
1090 		retval = -EINVAL;
1091 		goto out;
1092 	}
1093 
1094 	exfat_bitmap_set_range(exfat, exfat->alloc_bitmap,
1095 			       le32_to_cpu(dentry->upcase_start_clu),
1096 			       DIV_ROUND_UP(le64_to_cpu(dentry->upcase_size),
1097 					    exfat->clus_size));
1098 
1099 	exfat->upcase_table = calloc(1,
1100 				     sizeof(uint16_t) * EXFAT_UPCASE_TABLE_CHARS);
1101 	if (!exfat->upcase_table) {
1102 		retval = -EIO;
1103 		goto out;
1104 	}
1105 
1106 	decompress_upcase_table(upcase, size / 2,
1107 				exfat->upcase_table, EXFAT_UPCASE_TABLE_CHARS);
1108 out:
1109 	if (dentry)
1110 		free(dentry);
1111 	if (upcase)
1112 		free(upcase);
1113 	return retval;
1114 }
1115 
read_children(struct exfat_fsck * fsck,struct exfat_inode * dir)1116 static int read_children(struct exfat_fsck *fsck, struct exfat_inode *dir)
1117 {
1118 	struct exfat *exfat = fsck->exfat;
1119 	struct exfat_inode *node = NULL;
1120 	struct exfat_dentry *dentry;
1121 	struct exfat_de_iter *de_iter;
1122 	int dentry_count;
1123 	int ret;
1124 
1125 	de_iter = &fsck->de_iter;
1126 	ret = exfat_de_iter_init(de_iter, exfat, dir, fsck->buffer_desc);
1127 	if (ret == EOF)
1128 		return 0;
1129 	else if (ret)
1130 		return ret;
1131 
1132 	while (1) {
1133 		ret = exfat_de_iter_get(de_iter, 0, &dentry);
1134 		if (ret == EOF) {
1135 			break;
1136 		} else if (ret) {
1137 			fsck_err(dir->parent, dir,
1138 				"failed to get a dentry. %d\n", ret);
1139 			goto err;
1140 		}
1141 
1142 		dentry_count = 1;
1143 
1144 		switch (dentry->type) {
1145 		case EXFAT_FILE:
1146 			ret = read_file(de_iter, &node, &dentry_count);
1147 			if (ret < 0) {
1148 				exfat_stat.error_count++;
1149 				break;
1150 			} else if (ret) {
1151 				exfat_stat.error_count++;
1152 				exfat_stat.fixed_count++;
1153 			}
1154 
1155 			if (node) {
1156 				if ((node->attr & ATTR_SUBDIR) && node->size) {
1157 					node->parent = dir;
1158 					list_add_tail(&node->sibling,
1159 						      &dir->children);
1160 					list_add_tail(&node->list,
1161 						      &exfat->dir_list);
1162 				} else {
1163 					exfat_free_inode(node);
1164 				}
1165 			}
1166 			break;
1167 		case EXFAT_LAST:
1168 			goto out;
1169 		case EXFAT_VOLUME:
1170 		case EXFAT_BITMAP:
1171 		case EXFAT_UPCASE:
1172 			if (dir == exfat->root)
1173 				break;
1174 			/* fallthrough */
1175 		default:
1176 			if (IS_EXFAT_DELETED(dentry->type))
1177 				break;
1178 			if (repair_file_ask(de_iter, NULL, ER_DE_UNKNOWN,
1179 					    "unknown entry type %#x at %07" PRIx64,
1180 					    dentry->type,
1181 					    exfat_de_iter_file_offset(de_iter))) {
1182 				struct exfat_dentry *dentry;
1183 
1184 				exfat_de_iter_get_dirty(de_iter, 0, &dentry);
1185 				dentry->type &= EXFAT_DELETE;
1186 			}
1187 			break;
1188 		}
1189 
1190 		exfat_de_iter_advance(de_iter, dentry_count);
1191 	}
1192 out:
1193 	exfat_de_iter_flush(de_iter);
1194 	return 0;
1195 err:
1196 	exfat_free_children(dir, false);
1197 	INIT_LIST_HEAD(&dir->children);
1198 	exfat_de_iter_flush(de_iter);
1199 	return ret;
1200 }
1201 
1202 /* write bitmap segments for clusters which are marked
1203  * as free, but allocated to files.
1204  */
write_bitmap(struct exfat_fsck * fsck)1205 static int write_bitmap(struct exfat_fsck *fsck)
1206 {
1207 	struct exfat *exfat = fsck->exfat;
1208 	bitmap_t *disk_b, *alloc_b, *ohead_b;
1209 	off_t dev_offset;
1210 	unsigned int i, bitmap_bytes, byte_offset, write_bytes;
1211 
1212 	dev_offset = exfat_c2o(exfat, exfat->disk_bitmap_clus);
1213 	bitmap_bytes = EXFAT_BITMAP_SIZE(le32_to_cpu(exfat->bs->bsx.clu_count));
1214 
1215 	disk_b = (bitmap_t *)exfat->disk_bitmap;
1216 	alloc_b = (bitmap_t *)exfat->alloc_bitmap;
1217 	ohead_b = (bitmap_t *)exfat->ohead_bitmap;
1218 
1219 	for (i = 0; i < bitmap_bytes / sizeof(bitmap_t); i++)
1220 		ohead_b[i] = alloc_b[i] | disk_b[i];
1221 
1222 	i = 0;
1223 	while (i < bitmap_bytes / sizeof(bitmap_t)) {
1224 		if (ohead_b[i] == disk_b[i]) {
1225 			i++;
1226 			continue;
1227 		}
1228 
1229 		byte_offset = ((i * sizeof(bitmap_t)) / 512) * 512;
1230 		write_bytes = MIN(512, bitmap_bytes - byte_offset);
1231 
1232 		if (exfat_write(exfat->blk_dev->dev_fd,
1233 				(char *)ohead_b + byte_offset, write_bytes,
1234 				dev_offset + byte_offset) != (ssize_t)write_bytes)
1235 			return -EIO;
1236 
1237 		i = (byte_offset + write_bytes) / sizeof(bitmap_t);
1238 	}
1239 	return 0;
1240 
1241 }
1242 
1243 /*
1244  * for each directory in @dir_list.
1245  * 1. read all dentries and allocate exfat_nodes for files and directories.
1246  *    and append directory exfat_nodes to the head of @dir_list
1247  * 2. free all of file exfat_nodes.
1248  * 3. if the directory does not have children, free its exfat_node.
1249  */
exfat_filesystem_check(struct exfat_fsck * fsck)1250 static int exfat_filesystem_check(struct exfat_fsck *fsck)
1251 {
1252 	struct exfat *exfat = fsck->exfat;
1253 	struct exfat_inode *dir;
1254 	int ret = 0, dir_errors;
1255 
1256 	if (!exfat->root) {
1257 		exfat_err("root is NULL\n");
1258 		return -ENOENT;
1259 	}
1260 
1261 	list_add(&exfat->root->list, &exfat->dir_list);
1262 
1263 	while (!list_empty(&exfat->dir_list)) {
1264 		dir = list_entry(exfat->dir_list.next,
1265 				 struct exfat_inode, list);
1266 
1267 		if (!(dir->attr & ATTR_SUBDIR)) {
1268 			fsck_err(dir->parent, dir,
1269 				"failed to travel directories. "
1270 				"the node is not directory\n");
1271 			ret = -EINVAL;
1272 			goto out;
1273 		}
1274 
1275 		dir_errors = read_children(fsck, dir);
1276 		if (dir_errors) {
1277 			exfat_resolve_path(&path_resolve_ctx, dir);
1278 			exfat_debug("failed to check dentries: %s\n",
1279 					path_resolve_ctx.local_path);
1280 			ret = dir_errors;
1281 		}
1282 
1283 		list_del(&dir->list);
1284 		exfat_free_file_children(dir);
1285 		exfat_free_ancestors(dir);
1286 	}
1287 out:
1288 	exfat_free_dir_list(exfat);
1289 	return ret;
1290 }
1291 
exfat_root_dir_check(struct exfat * exfat)1292 static int exfat_root_dir_check(struct exfat *exfat)
1293 {
1294 	struct exfat_inode *root;
1295 	clus_t clus_count = 0;
1296 	int err;
1297 
1298 	root = exfat_alloc_inode(ATTR_SUBDIR);
1299 	if (!root)
1300 		return -ENOMEM;
1301 
1302 	exfat->root = root;
1303 	root->first_clus = le32_to_cpu(exfat->bs->bsx.root_cluster);
1304 	if (root_check_clus_chain(exfat, root, &clus_count)) {
1305 		exfat_err("failed to follow the cluster chain of root\n");
1306 		exfat_free_inode(root);
1307 		exfat->root = NULL;
1308 		return -EINVAL;
1309 	}
1310 	root->size = clus_count * exfat->clus_size;
1311 
1312 	exfat_stat.dir_count++;
1313 	exfat_debug("root directory: start cluster[0x%x] size[0x%" PRIx64 "]\n",
1314 		root->first_clus, root->size);
1315 
1316 	err = exfat_read_volume_label(exfat);
1317 	if (err && err != EOF)
1318 		exfat_err("failed to read volume label\n");
1319 	err = 0;
1320 
1321 	err = read_bitmap(exfat);
1322 	if (err) {
1323 		exfat_err("failed to read bitmap\n");
1324 		return -EINVAL;
1325 	}
1326 
1327 	err = read_upcase_table(exfat);
1328 	if (err) {
1329 		exfat_err("failed to read upcase table\n");
1330 		return -EINVAL;
1331 	}
1332 
1333 	root->dev_offset = 0;
1334 	err = exfat_build_file_dentry_set(exfat, " ", ATTR_SUBDIR,
1335 					  &root->dentry_set, &root->dentry_count);
1336 	if (err) {
1337 		exfat_free_inode(root);
1338 		return -ENOMEM;
1339 	}
1340 	return 0;
1341 }
1342 
read_lostfound(struct exfat * exfat,struct exfat_inode ** lostfound)1343 static int read_lostfound(struct exfat *exfat, struct exfat_inode **lostfound)
1344 {
1345 	struct exfat_lookup_filter filter;
1346 	struct exfat_inode *inode;
1347 	int err;
1348 
1349 	err = exfat_lookup_file(exfat, exfat->root, "LOST+FOUND", &filter);
1350 	if (err)
1351 		return err;
1352 
1353 	inode = exfat_alloc_inode(ATTR_SUBDIR);
1354 	if (!inode) {
1355 		free(filter.out.dentry_set);
1356 		return -ENOMEM;
1357 	}
1358 
1359 	inode->dentry_set = filter.out.dentry_set;
1360 	inode->dentry_count = filter.out.dentry_count;
1361 	inode->dev_offset = filter.out.dev_offset;
1362 
1363 	inode->first_clus =
1364 		le32_to_cpu(filter.out.dentry_set[1].dentry.stream.start_clu);
1365 	inode->size =
1366 		le64_to_cpu(filter.out.dentry_set[1].dentry.stream.size);
1367 
1368 	*lostfound = inode;
1369 	return 0;
1370 }
1371 
1372 /* Create temporary files under LOST+FOUND and assign orphan
1373  * chains of clusters to these files.
1374  */
rescue_orphan_clusters(struct exfat_fsck * fsck)1375 static int rescue_orphan_clusters(struct exfat_fsck *fsck)
1376 {
1377 	struct exfat *exfat = fsck->exfat;
1378 	struct exfat_inode *lostfound;
1379 	bitmap_t *disk_b, *alloc_b, *ohead_b;
1380 	struct exfat_dentry *dset;
1381 	clus_t clu_count, clu, s_clu, e_clu;
1382 	int err, dcount;
1383 	unsigned int i;
1384 	char name[] = "FILE0000000.CHK";
1385 	struct exfat_dentry_loc loc;
1386 	struct exfat_lookup_filter lf = {
1387 		.in.type = EXFAT_INVAL,
1388 		.in.filter = NULL,
1389 	};
1390 
1391 	err = read_lostfound(exfat, &lostfound);
1392 	if (err) {
1393 		exfat_err("failed to find LOST+FOUND\n");
1394 		return err;
1395 	}
1396 
1397 	/* get the last empty region of LOST+FOUND */
1398 	err = exfat_lookup_dentry_set(exfat, lostfound, &lf);
1399 	if (err && err != EOF) {
1400 		exfat_err("failed to find the last empty slot in LOST+FOUND\n");
1401 		goto out;
1402 	}
1403 
1404 	loc.parent = lostfound;
1405 	loc.file_offset = lf.out.file_offset;
1406 	loc.dev_offset = lf.out.dev_offset;
1407 
1408 	/* build a template dentry set */
1409 	err = exfat_build_file_dentry_set(exfat, name, 0, &dset, &dcount);
1410 	if (err) {
1411 		exfat_err("failed to create a temporary file in LOST+FOUNDn");
1412 		goto out;
1413 	}
1414 	dset[1].dentry.stream.flags |= EXFAT_SF_CONTIGUOUS;
1415 
1416 	clu_count = le32_to_cpu(exfat->bs->bsx.clu_count);
1417 
1418 	/* find clusters which are not marked as free, but not allocated to
1419 	 * any files.
1420 	 */
1421 	disk_b = (bitmap_t *)exfat->disk_bitmap;
1422 	alloc_b = (bitmap_t *)exfat->alloc_bitmap;
1423 	ohead_b = (bitmap_t *)exfat->ohead_bitmap;
1424 	for (i = 0; i < EXFAT_BITMAP_SIZE(clu_count) / sizeof(bitmap_t); i++)
1425 		ohead_b[i] = disk_b[i] & ~alloc_b[i];
1426 
1427 	/* create temporary files and allocate contiguous orphan clusters
1428 	 * to each file.
1429 	 */
1430 	for (clu = EXFAT_FIRST_CLUSTER; clu < clu_count + EXFAT_FIRST_CLUSTER &&
1431 	     exfat_bitmap_find_one(exfat, exfat->ohead_bitmap, clu, &s_clu) == 0;) {
1432 		if (exfat_bitmap_find_zero(exfat, exfat->ohead_bitmap, s_clu, &e_clu))
1433 			e_clu = clu_count + EXFAT_FIRST_CLUSTER;
1434 		clu = e_clu;
1435 
1436 		snprintf(name, sizeof(name), "FILE%07d.CHK",
1437 			 (unsigned int)(loc.file_offset >> 5));
1438 		err = exfat_update_file_dentry_set(exfat, dset, dcount,
1439 						   name, s_clu, e_clu - s_clu);
1440 		if (err)
1441 			continue;
1442 		err = exfat_add_dentry_set(exfat, &loc, dset, dcount, true);
1443 		if (err)
1444 			continue;
1445 	}
1446 
1447 	free(dset);
1448 	err = 0;
1449 out:
1450 	exfat_free_inode(lostfound);
1451 	return err;
1452 }
1453 
bytes_to_human_readable(size_t bytes)1454 static char *bytes_to_human_readable(size_t bytes)
1455 {
1456 	static const char * const units[] = {"B", "KB", "MB", "GB", "TB", "PB"};
1457 	static char buf[15*4];
1458 	unsigned int i, shift, quoti, remain;
1459 	i = sizeof(units) / sizeof(units[0]) - 1;
1460 
1461 	while (i && (bytes >> i * 10) == 0)
1462 		i--;
1463 
1464 	shift = i * 10;
1465 	quoti = (unsigned int)(bytes / (1ULL << shift));
1466 	remain = 0;
1467 	if (shift > 0) {
1468 		remain = (unsigned int)
1469 			((bytes & ((1ULL << shift) - 1)) >> (shift - 10));
1470 		remain = (remain * 100) / 1024;
1471 	}
1472 
1473 	snprintf(buf, sizeof(buf), "%u.%02u %s", quoti, remain, units[i]);
1474 	return buf;
1475 }
1476 
exfat_show_info(struct exfat_fsck * fsck,const char * dev_name)1477 static void exfat_show_info(struct exfat_fsck *fsck, const char *dev_name)
1478 {
1479 	struct exfat *exfat = fsck->exfat;
1480 	bool clean;
1481 
1482 	exfat_info("sector size:  %s\n",
1483 		bytes_to_human_readable(1 << exfat->bs->bsx.sect_size_bits));
1484 	exfat_info("cluster size: %s\n",
1485 		bytes_to_human_readable(exfat->clus_size));
1486 	exfat_info("volume size:  %s\n",
1487 		bytes_to_human_readable(exfat->blk_dev->size));
1488 
1489 	clean = exfat_stat.error_count == 0 ||
1490 		exfat_stat.error_count == exfat_stat.fixed_count;
1491 	printf("%s: %s. directories %ld, files %ld\n", dev_name,
1492 			clean ? "clean" : "corrupted",
1493 			exfat_stat.dir_count, exfat_stat.file_count);
1494 	if (exfat_stat.error_count)
1495 		printf("%s: files corrupted %ld, files fixed %ld\n", dev_name,
1496 			exfat_stat.error_count - exfat_stat.fixed_count,
1497 			exfat_stat.fixed_count);
1498 }
1499 
main(int argc,char * const argv[])1500 int main(int argc, char * const argv[])
1501 {
1502 	struct fsck_user_input ui;
1503 	struct exfat_blk_dev bd;
1504 	struct pbr *bs = NULL;
1505 	int c, ret, exit_code;
1506 	bool version_only = false;
1507 
1508 	memset(&ui, 0, sizeof(ui));
1509 	memset(&bd, 0, sizeof(bd));
1510 
1511 	print_level = EXFAT_ERROR;
1512 
1513 	if (!setlocale(LC_CTYPE, ""))
1514 		exfat_err("failed to init locale/codeset\n");
1515 
1516 	opterr = 0;
1517 	while ((c = getopt_long(argc, argv, "arynpbsVvh", opts, NULL)) != EOF) {
1518 		switch (c) {
1519 		case 'n':
1520 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1521 				usage(argv[0]);
1522 			ui.options |= FSCK_OPTS_REPAIR_NO;
1523 			break;
1524 		case 'r':
1525 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1526 				usage(argv[0]);
1527 			ui.options |= FSCK_OPTS_REPAIR_ASK;
1528 			break;
1529 		case 'y':
1530 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1531 				usage(argv[0]);
1532 			ui.options |= FSCK_OPTS_REPAIR_YES;
1533 			break;
1534 		case 'a':
1535 		case 'p':
1536 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1537 				usage(argv[0]);
1538 			ui.options |= FSCK_OPTS_REPAIR_AUTO;
1539 			break;
1540 		case 'b':
1541 			ui.options |= FSCK_OPTS_IGNORE_BAD_FS_NAME;
1542 			break;
1543 		case 's':
1544 			ui.options |= FSCK_OPTS_RESCUE_CLUS;
1545 			break;
1546 		case 'V':
1547 			version_only = true;
1548 			break;
1549 		case 'v':
1550 			if (print_level < EXFAT_DEBUG)
1551 				print_level++;
1552 			break;
1553 		case '?':
1554 		case 'h':
1555 		default:
1556 			usage(argv[0]);
1557 		}
1558 	}
1559 
1560 	show_version();
1561 	if (optind != argc - 1)
1562 		usage(argv[0]);
1563 
1564 	if (version_only)
1565 		exit(FSCK_EXIT_SYNTAX_ERROR);
1566 	if (ui.options & FSCK_OPTS_REPAIR_WRITE)
1567 		ui.ei.writeable = true;
1568 	else {
1569 		if (ui.options & (FSCK_OPTS_IGNORE_BAD_FS_NAME |
1570 				  FSCK_OPTS_RESCUE_CLUS))
1571 			usage(argv[0]);
1572 		ui.options |= FSCK_OPTS_REPAIR_NO;
1573 		ui.ei.writeable = false;
1574 	}
1575 
1576 	exfat_fsck.options = ui.options;
1577 
1578 	snprintf(ui.ei.dev_name, sizeof(ui.ei.dev_name), "%s", argv[optind]);
1579 	ret = exfat_get_blk_dev_info(&ui.ei, &bd);
1580 	if (ret < 0) {
1581 		exfat_err("failed to open %s. %d\n", ui.ei.dev_name, ret);
1582 		return FSCK_EXIT_OPERATION_ERROR;
1583 	}
1584 
1585 	ret = exfat_boot_region_check(&bd, &bs,
1586 				      ui.options & FSCK_OPTS_IGNORE_BAD_FS_NAME ?
1587 				      true : false);
1588 	if (ret)
1589 		goto err;
1590 
1591 	exfat_fsck.exfat = exfat_alloc_exfat(&bd, bs);
1592 	if (!exfat_fsck.exfat) {
1593 		ret = -ENOMEM;
1594 		goto err;
1595 	}
1596 
1597 	exfat_fsck.buffer_desc = exfat_alloc_buffer(2,
1598 						    exfat_fsck.exfat->clus_size,
1599 						    exfat_fsck.exfat->sect_size);
1600 	if (!exfat_fsck.buffer_desc) {
1601 		ret = -ENOMEM;
1602 		goto err;
1603 	}
1604 
1605 	if ((exfat_fsck.options & FSCK_OPTS_REPAIR_WRITE) &&
1606 	    exfat_mark_volume_dirty(exfat_fsck.exfat, true)) {
1607 		ret = -EIO;
1608 		goto err;
1609 	}
1610 
1611 	exfat_debug("verifying root directory...\n");
1612 	ret = exfat_root_dir_check(exfat_fsck.exfat);
1613 	if (ret) {
1614 		exfat_err("failed to verify root directory.\n");
1615 		goto out;
1616 	}
1617 
1618 	if (exfat_fsck.options & FSCK_OPTS_RESCUE_CLUS) {
1619 		ret = exfat_create_file(exfat_fsck.exfat,
1620 					exfat_fsck.exfat->root,
1621 					"LOST+FOUND",
1622 					ATTR_SUBDIR);
1623 		if (ret) {
1624 			exfat_err("failed to create lost+found directory\n");
1625 			goto out;
1626 		}
1627 
1628 		if (fsync(exfat_fsck.exfat->blk_dev->dev_fd) != 0) {
1629 			ret = -EIO;
1630 			exfat_err("failed to sync()\n");
1631 			goto out;
1632 		}
1633 	}
1634 
1635 	exfat_debug("verifying directory entries...\n");
1636 	ret = exfat_filesystem_check(&exfat_fsck);
1637 	if (ret)
1638 		goto out;
1639 
1640 	if (exfat_fsck.options & FSCK_OPTS_RESCUE_CLUS) {
1641 		rescue_orphan_clusters(&exfat_fsck);
1642 		exfat_fsck.dirty = true;
1643 		exfat_fsck.dirty_fat = true;
1644 	}
1645 
1646 	if (exfat_fsck.options & FSCK_OPTS_REPAIR_WRITE) {
1647 		ret = write_bitmap(&exfat_fsck);
1648 		if (ret) {
1649 			exfat_err("failed to write bitmap\n");
1650 			goto out;
1651 		}
1652 	}
1653 
1654 	if (ui.ei.writeable && fsync(bd.dev_fd)) {
1655 		exfat_err("failed to sync\n");
1656 		ret = -EIO;
1657 		goto out;
1658 	}
1659 	if (exfat_fsck.options & FSCK_OPTS_REPAIR_WRITE)
1660 		exfat_mark_volume_dirty(exfat_fsck.exfat, false);
1661 
1662 out:
1663 	exfat_show_info(&exfat_fsck, ui.ei.dev_name);
1664 err:
1665 	if (ret && ret != -EINVAL)
1666 		exit_code = FSCK_EXIT_OPERATION_ERROR;
1667 	else if (ret == -EINVAL ||
1668 		 exfat_stat.error_count != exfat_stat.fixed_count)
1669 		exit_code = FSCK_EXIT_ERRORS_LEFT;
1670 	else if (exfat_fsck.dirty)
1671 		exit_code = FSCK_EXIT_CORRECTED;
1672 	else
1673 		exit_code = FSCK_EXIT_NO_ERRORS;
1674 
1675 	if (exfat_fsck.buffer_desc)
1676 		exfat_free_buffer(exfat_fsck.buffer_desc, 2);
1677 	if (exfat_fsck.exfat)
1678 		exfat_free_exfat(exfat_fsck.exfat);
1679 	close(bd.dev_fd);
1680 	return exit_code;
1681 }
1682