• 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 "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  * ancesters 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(struct exfat_blk_dev * bd,int bs_offset)587 static int boot_region_checksum(struct exfat_blk_dev *bd, int bs_offset)
588 {
589 	void *sect;
590 	unsigned int i;
591 	uint32_t checksum;
592 	int ret = 0;
593 	unsigned int size;
594 
595 	size = bd->sector_size;
596 	sect = malloc(size);
597 	if (!sect)
598 		return -ENOMEM;
599 
600 	checksum = 0;
601 	for (i = 0; i < 11; i++) {
602 		if (exfat_read(bd->dev_fd, sect, size,
603 				bs_offset * size + i * size) !=
604 				(ssize_t)size) {
605 			exfat_err("failed to read boot region\n");
606 			ret = -EIO;
607 			goto out;
608 		}
609 		boot_calc_checksum(sect, size, i == 0, &checksum);
610 	}
611 
612 	if (exfat_read(bd->dev_fd, sect, size,
613 			bs_offset * size + 11 * size) !=
614 			(ssize_t)size) {
615 		exfat_err("failed to read a boot checksum sector\n");
616 		ret = -EIO;
617 		goto out;
618 	}
619 
620 	for (i = 0; i < size/sizeof(checksum); i++) {
621 		if (le32_to_cpu(((__le32 *)sect)[i]) != checksum) {
622 			exfat_err("checksum of boot region is not correct. %#x, but expected %#x\n",
623 				le32_to_cpu(((__le32 *)sect)[i]), checksum);
624 			ret = -EINVAL;
625 			goto out;
626 		}
627 	}
628 out:
629 	free(sect);
630 	return ret;
631 }
632 
exfat_mark_volume_dirty(struct exfat * exfat,bool dirty)633 static int exfat_mark_volume_dirty(struct exfat *exfat, bool dirty)
634 {
635 	uint16_t flags;
636 
637 	if (!(exfat->options & FSCK_OPTS_REPAIR_WRITE))
638 		return 0;
639 
640 	flags = le16_to_cpu(exfat->bs->bsx.vol_flags);
641 	if (dirty)
642 		flags |= 0x02;
643 	else
644 		flags &= ~0x02;
645 
646 	exfat->bs->bsx.vol_flags = cpu_to_le16(flags);
647 	if (exfat_write(exfat->blk_dev->dev_fd, exfat->bs,
648 			sizeof(struct pbr), 0) != (ssize_t)sizeof(struct pbr)) {
649 		exfat_err("failed to set VolumeDirty\n");
650 		return -EIO;
651 	}
652 
653 	if (fsync(exfat->blk_dev->dev_fd) != 0) {
654 		exfat_err("failed to set VolumeDirty\n");
655 		return -EIO;
656 	}
657 	return 0;
658 }
659 
read_boot_region(struct exfat_blk_dev * bd,struct pbr ** pbr,int bs_offset)660 static int read_boot_region(struct exfat_blk_dev *bd, struct pbr **pbr,
661 		int bs_offset)
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 * bd->sector_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 		exfat_err("failed to find exfat file system.\n");
682 		goto err;
683 	}
684 
685 	ret = boot_region_checksum(bd, bs_offset);
686 	if (ret < 0)
687 		goto err;
688 
689 	ret = -EINVAL;
690 	if (EXFAT_SECTOR_SIZE(bs) < 512 || EXFAT_SECTOR_SIZE(bs) > 4 * KB) {
691 		exfat_err("too small or big sector size: %d\n",
692 				EXFAT_SECTOR_SIZE(bs));
693 		goto err;
694 	}
695 
696 	if (EXFAT_CLUSTER_SIZE(bs) > 32 * MB) {
697 		exfat_err("too big cluster size: %d\n", EXFAT_CLUSTER_SIZE(bs));
698 		goto err;
699 	}
700 
701 	if (bs->bsx.fs_version[1] != 1 || bs->bsx.fs_version[0] != 0) {
702 		exfat_err("unsupported exfat version: %d.%d\n",
703 				bs->bsx.fs_version[1], bs->bsx.fs_version[0]);
704 		goto err;
705 	}
706 
707 	if (bs->bsx.num_fats != 1) {
708 		exfat_err("unsupported FAT count: %d\n", bs->bsx.num_fats);
709 		goto err;
710 	}
711 
712 	if (le64_to_cpu(bs->bsx.vol_length) * EXFAT_SECTOR_SIZE(bs) >
713 			bd->size) {
714 		exfat_err("too large sector count: %" PRIu64 ", expected: %llu\n",
715 				le64_to_cpu(bs->bsx.vol_length),
716 				bd->num_sectors);
717 		goto err;
718 	}
719 
720 	if (le32_to_cpu(bs->bsx.clu_count) * EXFAT_CLUSTER_SIZE(bs) >
721 			bd->size) {
722 		exfat_err("too large cluster count: %u, expected: %u\n",
723 				le32_to_cpu(bs->bsx.clu_count),
724 				bd->num_clusters);
725 		goto err;
726 	}
727 
728 	*pbr = bs;
729 	return 0;
730 err:
731 	free(bs);
732 	return ret;
733 }
734 
restore_boot_region(struct exfat_blk_dev * bd)735 static int restore_boot_region(struct exfat_blk_dev *bd)
736 {
737 	int i;
738 	char *sector;
739 	int ret;
740 
741 	sector = malloc(bd->sector_size);
742 	if (!sector)
743 		return -ENOMEM;
744 
745 	for (i = 0; i < 12; i++) {
746 		if (exfat_read(bd->dev_fd, sector, bd->sector_size,
747 				BACKUP_BOOT_SEC_IDX * bd->sector_size +
748 				i * bd->sector_size) !=
749 				(ssize_t)bd->sector_size) {
750 			ret = -EIO;
751 			goto free_sector;
752 		}
753 		if (i == 0)
754 			((struct pbr *)sector)->bsx.perc_in_use = 0xff;
755 
756 		if (exfat_write(bd->dev_fd, sector, bd->sector_size,
757 				BOOT_SEC_IDX * bd->sector_size +
758 				i * bd->sector_size) !=
759 				(ssize_t)bd->sector_size) {
760 			ret = -EIO;
761 			goto free_sector;
762 		}
763 	}
764 
765 	if (fsync(bd->dev_fd)) {
766 		ret = -EIO;
767 		goto free_sector;
768 	}
769 	ret = 0;
770 
771 free_sector:
772 	free(sector);
773 	return ret;
774 }
775 
exfat_boot_region_check(struct exfat * exfat,struct pbr ** bs)776 static int exfat_boot_region_check(struct exfat *exfat, struct pbr **bs)
777 {
778 	int ret;
779 
780 	ret = read_boot_region(exfat->blk_dev, bs, BOOT_SEC_IDX);
781 	if (ret == -EINVAL && exfat_repair_ask(exfat, ER_BS_BOOT_REGION,
782 				"boot region is corrupted. try to restore the region from backup"
783 				)) {
784 		ret = read_boot_region(exfat->blk_dev, bs, BACKUP_BOOT_SEC_IDX);
785 		if (ret < 0) {
786 			exfat_err("backup boot region is also corrupted\n");
787 			return ret;
788 		}
789 		ret = restore_boot_region(exfat->blk_dev);
790 		if (ret < 0) {
791 			exfat_err("failed to restore boot region from backup\n");
792 			free(*bs);
793 			*bs = NULL;
794 			return ret;
795 		}
796 	}
797 	return ret;
798 }
799 
dentry_calc_checksum(struct exfat_dentry * dentry,__le16 * checksum,bool primary)800 static void dentry_calc_checksum(struct exfat_dentry *dentry,
801 				__le16 *checksum, bool primary)
802 {
803 	unsigned int i;
804 	uint8_t *bytes;
805 
806 	bytes = (uint8_t *)dentry;
807 
808 	*checksum = ((*checksum << 15) | (*checksum >> 1)) + bytes[0];
809 	*checksum = ((*checksum << 15) | (*checksum >> 1)) + bytes[1];
810 
811 	i = primary ? 4 : 2;
812 	for (; i < sizeof(*dentry); i++) {
813 		*checksum = ((*checksum << 15) | (*checksum >> 1)) + bytes[i];
814 	}
815 }
816 
file_calc_checksum(struct exfat_de_iter * iter)817 static __le16 file_calc_checksum(struct exfat_de_iter *iter)
818 {
819 	__le16 checksum;
820 	struct exfat_dentry *file_de, *de;
821 	int i;
822 
823 	checksum = 0;
824 	exfat_de_iter_get(iter, 0, &file_de);
825 
826 	dentry_calc_checksum(file_de, &checksum, true);
827 	for (i = 1; i <= file_de->file_num_ext; i++) {
828 		exfat_de_iter_get(iter, i, &de);
829 		dentry_calc_checksum(de, &checksum, false);
830 	}
831 
832 	return checksum;
833 }
834 
835 /*
836  * return 0 if there are no errors, or 1 if errors are fixed, or
837  * an error code
838  */
check_inode(struct exfat_de_iter * iter,struct exfat_inode * node)839 static int check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)
840 {
841 	struct exfat *exfat = iter->exfat;
842 	struct exfat_dentry *dentry;
843 	int ret = 0;
844 	uint16_t checksum;
845 	bool valid = true;
846 
847 	ret = check_clus_chain(exfat, node);
848 	if (ret < 0)
849 		return ret;
850 
851 	if (node->size > le32_to_cpu(exfat->bs->bsx.clu_count) *
852 				(uint64_t)exfat->clus_size) {
853 		fsck_err(iter->parent, node,
854 			"size %" PRIu64 " is greater than cluster heap\n",
855 			node->size);
856 		valid = false;
857 	}
858 
859 	if (node->size == 0 && node->is_contiguous) {
860 		if (repair_file_ask(iter, node, ER_FILE_ZERO_NOFAT,
861 				"empty, but has no Fat chain\n")) {
862 			exfat_de_iter_get_dirty(iter, 1, &dentry);
863 			dentry->stream_flags &= ~EXFAT_SF_CONTIGUOUS;
864 			ret = 1;
865 		} else
866 			valid = false;
867 	}
868 
869 	if ((node->attr & ATTR_SUBDIR) &&
870 			node->size % exfat->clus_size != 0) {
871 		fsck_err(iter->parent, node,
872 			"directory size %" PRIu64 " is not divisible by %d\n",
873 			node->size, exfat->clus_size);
874 		valid = false;
875 	}
876 
877 	checksum = file_calc_checksum(iter);
878 	exfat_de_iter_get(iter, 0, &dentry);
879 	if (checksum != le16_to_cpu(dentry->file_checksum)) {
880 		if (repair_file_ask(iter, node, ER_DE_CHECKSUM,
881 				"the checksum of a file is wrong")) {
882 			exfat_de_iter_get_dirty(iter, 0, &dentry);
883 			dentry->file_checksum = cpu_to_le16(checksum);
884 			ret = 1;
885 		} else
886 			valid = false;
887 	}
888 
889 	return valid ? ret : -EINVAL;
890 }
891 
read_file_dentries(struct exfat_de_iter * iter,struct exfat_inode ** new_node,int * skip_dentries)892 static int read_file_dentries(struct exfat_de_iter *iter,
893 			struct exfat_inode **new_node, int *skip_dentries)
894 {
895 	struct exfat_dentry *file_de, *stream_de, *name_de;
896 	struct exfat_inode *node;
897 	int i, ret;
898 
899 	/* TODO: mtime, atime, ... */
900 
901 	ret = exfat_de_iter_get(iter, 0, &file_de);
902 	if (ret || file_de->type != EXFAT_FILE) {
903 		exfat_err("failed to get file dentry. %d\n", ret);
904 		return -EINVAL;
905 	}
906 	ret = exfat_de_iter_get(iter, 1, &stream_de);
907 	if (ret || stream_de->type != EXFAT_STREAM) {
908 		exfat_err("failed to get stream dentry. %d\n", ret);
909 		return -EINVAL;
910 	}
911 
912 	*new_node = NULL;
913 	node = alloc_exfat_inode(le16_to_cpu(file_de->file_attr));
914 	if (!node)
915 		return -ENOMEM;
916 
917 	if (file_de->file_num_ext < 2) {
918 		exfat_err("too few secondary count. %d\n",
919 				file_de->file_num_ext);
920 		free_exfat_inode(node);
921 		return -EINVAL;
922 	}
923 
924 	for (i = 2; i <= file_de->file_num_ext; i++) {
925 		ret = exfat_de_iter_get(iter, i, &name_de);
926 		if (ret || name_de->type != EXFAT_NAME) {
927 			exfat_err("failed to get name dentry. %d\n", ret);
928 			ret = -EINVAL;
929 			goto err;
930 		}
931 
932 		memcpy(node->name +
933 			(i-2) * ENTRY_NAME_MAX, name_de->name_unicode,
934 			sizeof(name_de->name_unicode));
935 	}
936 
937 	node->first_clus = le32_to_cpu(stream_de->stream_start_clu);
938 	node->is_contiguous =
939 		((stream_de->stream_flags & EXFAT_SF_CONTIGUOUS) != 0);
940 	node->size = le64_to_cpu(stream_de->stream_size);
941 
942 	if (node->size < le64_to_cpu(stream_de->stream_valid_size)) {
943 		if (repair_file_ask(iter, node, ER_FILE_VALID_SIZE,
944 			"valid size %" PRIu64 " greater than size %" PRIu64,
945 			le64_to_cpu(stream_de->stream_valid_size),
946 			node->size)) {
947 			exfat_de_iter_get_dirty(iter, 1, &stream_de);
948 			stream_de->stream_valid_size =
949 					stream_de->stream_size;
950 		} else {
951 			ret = -EINVAL;
952 			goto err;
953 		}
954 	}
955 
956 	*skip_dentries = (file_de->file_num_ext + 1);
957 	*new_node = node;
958 	return 0;
959 err:
960 	*skip_dentries = 0;
961 	*new_node = NULL;
962 	free_exfat_inode(node);
963 	return ret;
964 }
965 
read_file(struct exfat_de_iter * de_iter,struct exfat_inode ** new_node,int * dentry_count)966 static int read_file(struct exfat_de_iter *de_iter,
967 		struct exfat_inode **new_node, int *dentry_count)
968 {
969 	struct exfat_inode *node;
970 	int ret;
971 
972 	*new_node = NULL;
973 
974 	ret = read_file_dentries(de_iter, &node, dentry_count);
975 	if (ret)
976 		return ret;
977 
978 	ret = check_inode(de_iter, node);
979 	if (ret < 0) {
980 		free_exfat_inode(node);
981 		return -EINVAL;
982 	}
983 
984 	*new_node = node;
985 	return ret;
986 }
987 
read_volume_label(struct exfat_de_iter * iter)988 static bool read_volume_label(struct exfat_de_iter *iter)
989 {
990 	struct exfat *exfat;
991 	struct exfat_dentry *dentry;
992 	__le16 disk_label[VOLUME_LABEL_MAX_LEN];
993 
994 	exfat = iter->exfat;
995 	if (exfat_de_iter_get(iter, 0, &dentry))
996 		return false;
997 
998 	if (dentry->vol_char_cnt == 0)
999 		return true;
1000 
1001 	if (dentry->vol_char_cnt > VOLUME_LABEL_MAX_LEN) {
1002 		exfat_err("too long label. %d\n", dentry->vol_char_cnt);
1003 		return false;
1004 	}
1005 
1006 	memcpy(disk_label, dentry->vol_label, sizeof(disk_label));
1007 	if (exfat_utf16_dec(disk_label, dentry->vol_char_cnt*2,
1008 		exfat->volume_label, sizeof(exfat->volume_label)) < 0) {
1009 		exfat_err("failed to decode volume label\n");
1010 		return false;
1011 	}
1012 
1013 	exfat_info("volume label [%s]\n", exfat->volume_label);
1014 	return true;
1015 }
1016 
exfat_bitmap_set_range(struct exfat * exfat,clus_t start_clus,clus_t count)1017 static void exfat_bitmap_set_range(struct exfat *exfat,
1018 			clus_t start_clus, clus_t count)
1019 {
1020 	clus_t clus;
1021 
1022 	if (!heap_clus(exfat, start_clus) ||
1023 		!heap_clus(exfat, start_clus + count))
1024 		return;
1025 
1026 	clus = start_clus;
1027 	while (clus < start_clus + count) {
1028 		EXFAT_BITMAP_SET(exfat->alloc_bitmap,
1029 				clus - EXFAT_FIRST_CLUSTER);
1030 		clus++;
1031 	}
1032 }
1033 
read_bitmap(struct exfat_de_iter * iter)1034 static bool read_bitmap(struct exfat_de_iter *iter)
1035 {
1036 	struct exfat_dentry *dentry;
1037 	struct exfat *exfat;
1038 
1039 	exfat = iter->exfat;
1040 	if (exfat_de_iter_get(iter, 0, &dentry))
1041 		return false;
1042 
1043 	exfat_debug("start cluster %#x, size %#" PRIx64 "\n",
1044 			le32_to_cpu(dentry->bitmap_start_clu),
1045 			le64_to_cpu(dentry->bitmap_size));
1046 
1047 	if (le64_to_cpu(dentry->bitmap_size) <
1048 			DIV_ROUND_UP(exfat->clus_count, 8)) {
1049 		exfat_err("invalid size of allocation bitmap. 0x%" PRIx64 "\n",
1050 				le64_to_cpu(dentry->bitmap_size));
1051 		return false;
1052 	}
1053 	if (!heap_clus(exfat, le32_to_cpu(dentry->bitmap_start_clu))) {
1054 		exfat_err("invalid start cluster of allocate bitmap. 0x%x\n",
1055 				le32_to_cpu(dentry->bitmap_start_clu));
1056 		return false;
1057 	}
1058 
1059 	exfat->disk_bitmap_clus = le32_to_cpu(dentry->bitmap_start_clu);
1060 	exfat->disk_bitmap_size = DIV_ROUND_UP(exfat->clus_count, 8);
1061 
1062 	exfat_bitmap_set_range(exfat, le64_to_cpu(dentry->bitmap_start_clu),
1063 			DIV_ROUND_UP(exfat->disk_bitmap_size,
1064 			exfat->clus_size));
1065 
1066 	if (exfat_read(exfat->blk_dev->dev_fd, exfat->disk_bitmap,
1067 			exfat->disk_bitmap_size,
1068 			exfat_c2o(exfat, exfat->disk_bitmap_clus)) !=
1069 			(ssize_t)exfat->disk_bitmap_size)
1070 		return false;
1071 
1072 	return true;
1073 }
1074 
read_upcase_table(struct exfat_de_iter * iter)1075 static bool read_upcase_table(struct exfat_de_iter *iter)
1076 {
1077 	struct exfat_dentry *dentry;
1078 	struct exfat *exfat;
1079 	ssize_t size;
1080 	__le16 *upcase;
1081 	__le32 checksum;
1082 
1083 	exfat = iter->exfat;
1084 
1085 	if (exfat_de_iter_get(iter, 0, &dentry))
1086 		return false;
1087 
1088 	if (!heap_clus(exfat, le32_to_cpu(dentry->upcase_start_clu))) {
1089 		exfat_err("invalid start cluster of upcase table. 0x%x\n",
1090 			le32_to_cpu(dentry->upcase_start_clu));
1091 		return false;
1092 	}
1093 
1094 	size = (ssize_t)le64_to_cpu(dentry->upcase_size);
1095 	if (size > (ssize_t)(EXFAT_MAX_UPCASE_CHARS * sizeof(__le16)) ||
1096 			size == 0 || size % sizeof(__le16)) {
1097 		exfat_err("invalid size of upcase table. 0x%" PRIx64 "\n",
1098 			le64_to_cpu(dentry->upcase_size));
1099 		return false;
1100 	}
1101 
1102 	upcase = (__le16 *)malloc(size);
1103 	if (!upcase) {
1104 		exfat_err("failed to allocate upcase table\n");
1105 		return false;
1106 	}
1107 
1108 	if (exfat_read(exfat->blk_dev->dev_fd, upcase, size,
1109 			exfat_c2o(exfat,
1110 			le32_to_cpu(dentry->upcase_start_clu))) != size) {
1111 		exfat_err("failed to read upcase table\n");
1112 		free(upcase);
1113 		return false;
1114 	}
1115 
1116 	checksum = 0;
1117 	boot_calc_checksum((unsigned char *)upcase, size, false, &checksum);
1118 	if (le32_to_cpu(dentry->upcase_checksum) != checksum) {
1119 		exfat_err("corrupted upcase table %#x (expected: %#x)\n",
1120 			checksum, le32_to_cpu(dentry->upcase_checksum));
1121 		free(upcase);
1122 		return false;
1123 	}
1124 
1125 	exfat_bitmap_set_range(exfat, le32_to_cpu(dentry->upcase_start_clu),
1126 			DIV_ROUND_UP(le64_to_cpu(dentry->upcase_size),
1127 			exfat->clus_size));
1128 
1129 	free(upcase);
1130 	return true;
1131 }
1132 
read_children(struct exfat * exfat,struct exfat_inode * dir)1133 static int read_children(struct exfat *exfat, struct exfat_inode *dir)
1134 {
1135 	int ret;
1136 	struct exfat_inode *node = NULL;
1137 	struct exfat_dentry *dentry;
1138 	int dentry_count;
1139 	struct exfat_de_iter *de_iter;
1140 
1141 	de_iter = &exfat->de_iter;
1142 	ret = exfat_de_iter_init(de_iter, exfat, dir);
1143 	if (ret == EOF)
1144 		return 0;
1145 	else if (ret)
1146 		return ret;
1147 
1148 	while (1) {
1149 		ret = exfat_de_iter_get(de_iter, 0, &dentry);
1150 		if (ret == EOF) {
1151 			break;
1152 		} else if (ret) {
1153 			fsck_err(dir->parent, dir,
1154 				"failed to get a dentry. %d\n", ret);
1155 			goto err;
1156 		}
1157 
1158 		dentry_count = 1;
1159 
1160 		switch (dentry->type) {
1161 		case EXFAT_FILE:
1162 			ret = read_file(de_iter, &node, &dentry_count);
1163 			if (ret < 0) {
1164 				exfat_stat.error_count++;
1165 				goto err;
1166 			} else if (ret) {
1167 				exfat_stat.error_count++;
1168 				exfat_stat.fixed_count++;
1169 			}
1170 
1171 			if ((node->attr & ATTR_SUBDIR) && node->size) {
1172 				node->parent = dir;
1173 				list_add_tail(&node->sibling, &dir->children);
1174 				list_add_tail(&node->list, &exfat->dir_list);
1175 			} else
1176 				free_exfat_inode(node);
1177 			break;
1178 		case EXFAT_VOLUME:
1179 			if (!read_volume_label(de_iter)) {
1180 				exfat_err("failed to verify volume label\n");
1181 				ret = -EINVAL;
1182 				goto err;
1183 			}
1184 			break;
1185 		case EXFAT_BITMAP:
1186 			if (!read_bitmap(de_iter)) {
1187 				exfat_err(
1188 					"failed to verify allocation bitmap\n");
1189 				ret = -EINVAL;
1190 				goto err;
1191 			}
1192 			break;
1193 		case EXFAT_UPCASE:
1194 			if (!read_upcase_table(de_iter)) {
1195 				exfat_err(
1196 					"failed to verify upcase table\n");
1197 				ret = -EINVAL;
1198 				goto err;
1199 			}
1200 			break;
1201 		case EXFAT_LAST:
1202 			goto out;
1203 		default:
1204 			if (IS_EXFAT_DELETED(dentry->type))
1205 				break;
1206 			exfat_err("unknown entry type. 0x%x\n", dentry->type);
1207 			ret = -EINVAL;
1208 			goto err;
1209 		}
1210 
1211 		exfat_de_iter_advance(de_iter, dentry_count);
1212 	}
1213 out:
1214 	exfat_de_iter_flush(de_iter);
1215 	return 0;
1216 err:
1217 	inode_free_children(dir, false);
1218 	INIT_LIST_HEAD(&dir->children);
1219 	exfat_de_iter_flush(de_iter);
1220 	return ret;
1221 }
1222 
write_dirty_fat(struct exfat * exfat)1223 static int write_dirty_fat(struct exfat *exfat)
1224 {
1225 	struct buffer_desc *bd;
1226 	off_t offset;
1227 	ssize_t len;
1228 	size_t read_size, write_size;
1229 	clus_t clus, last_clus, clus_count, i;
1230 	unsigned int idx;
1231 
1232 	clus = 0;
1233 	last_clus = le32_to_cpu(exfat->bs->bsx.clu_count) + 2;
1234 	bd = exfat->buffer_desc;
1235 	idx = 0;
1236 	offset = le32_to_cpu(exfat->bs->bsx.fat_offset) *
1237 		exfat->sect_size;
1238 	read_size = exfat->clus_size;
1239 	write_size = exfat->sect_size;
1240 
1241 	while (clus < last_clus) {
1242 		clus_count = MIN(read_size / sizeof(clus_t), last_clus - clus);
1243 		len = exfat_read(exfat->blk_dev->dev_fd, bd[idx].buffer,
1244 				clus_count * sizeof(clus_t), offset);
1245 		if (len != (ssize_t)(sizeof(clus_t) * clus_count)) {
1246 			exfat_err("failed to read fat entries, %zd\n", len);
1247 			return -EIO;
1248 		}
1249 
1250 		/* TODO: read ahead */
1251 
1252 		for (i = clus ? clus : EXFAT_FIRST_CLUSTER;
1253 				i < clus + clus_count; i++) {
1254 			if (!EXFAT_BITMAP_GET(exfat->alloc_bitmap,
1255 					i - EXFAT_FIRST_CLUSTER) &&
1256 					((clus_t *)bd[idx].buffer)[i - clus] !=
1257 					EXFAT_FREE_CLUSTER) {
1258 				((clus_t *)bd[idx].buffer)[i - clus] =
1259 					EXFAT_FREE_CLUSTER;
1260 				bd[idx].dirty[(i - clus) /
1261 					(write_size / sizeof(clus_t))] = true;
1262 			}
1263 		}
1264 
1265 		for (i = 0; i < read_size; i += write_size) {
1266 			if (bd[idx].dirty[i / write_size]) {
1267 				if (exfat_write(exfat->blk_dev->dev_fd,
1268 						&bd[idx].buffer[i], write_size,
1269 						offset + i) !=
1270 						(ssize_t)write_size) {
1271 					exfat_err("failed to write "
1272 						"fat entries\n");
1273 					return -EIO;
1274 
1275 				}
1276 				bd[idx].dirty[i / write_size] = false;
1277 			}
1278 		}
1279 
1280 		idx ^= 0x01;
1281 		clus = clus + clus_count;
1282 		offset += len;
1283 	}
1284 	return 0;
1285 }
1286 
write_dirty_bitmap(struct exfat * exfat)1287 static int write_dirty_bitmap(struct exfat *exfat)
1288 {
1289 	struct buffer_desc *bd;
1290 	off_t offset, last_offset, bitmap_offset;
1291 	ssize_t len;
1292 	ssize_t read_size, write_size, i, size;
1293 	int idx;
1294 
1295 	offset = exfat_c2o(exfat, exfat->disk_bitmap_clus);
1296 	last_offset = offset + exfat->disk_bitmap_size;
1297 	bitmap_offset = 0;
1298 	read_size = exfat->clus_size;
1299 	write_size = exfat->sect_size;
1300 
1301 	bd = exfat->buffer_desc;
1302 	idx = 0;
1303 
1304 	while (offset < last_offset) {
1305 		len = MIN(read_size, last_offset - offset);
1306 		if (exfat_read(exfat->blk_dev->dev_fd, bd[idx].buffer,
1307 				len, offset) != (ssize_t)len)
1308 			return -EIO;
1309 
1310 		/* TODO: read-ahead */
1311 
1312 		for (i = 0; i < len; i += write_size) {
1313 			size = MIN(write_size, len - i);
1314 			if (memcmp(&bd[idx].buffer[i],
1315 					exfat->alloc_bitmap + bitmap_offset + i,
1316 					size)) {
1317 				if (exfat_write(exfat->blk_dev->dev_fd,
1318 					exfat->alloc_bitmap + bitmap_offset + i,
1319 					size, offset + i) != size)
1320 					return -EIO;
1321 			}
1322 		}
1323 
1324 		idx ^= 0x01;
1325 		offset += len;
1326 		bitmap_offset += len;
1327 	}
1328 	return 0;
1329 }
1330 
reclaim_free_clusters(struct exfat * exfat)1331 static int reclaim_free_clusters(struct exfat *exfat)
1332 {
1333 	if (write_dirty_fat(exfat)) {
1334 		exfat_err("failed to write fat entries\n");
1335 		return -EIO;
1336 	}
1337 	if (write_dirty_bitmap(exfat)) {
1338 		exfat_err("failed to write bitmap\n");
1339 		return -EIO;
1340 	}
1341 	return 0;
1342 }
1343 
1344 /*
1345  * for each directory in @dir_list.
1346  * 1. read all dentries and allocate exfat_nodes for files and directories.
1347  *    and append directory exfat_nodes to the head of @dir_list
1348  * 2. free all of file exfat_nodes.
1349  * 3. if the directory does not have children, free its exfat_node.
1350  */
exfat_filesystem_check(struct exfat * exfat)1351 static int exfat_filesystem_check(struct exfat *exfat)
1352 {
1353 	struct exfat_inode *dir;
1354 	int ret = 0, dir_errors;
1355 
1356 	if (!exfat->root) {
1357 		exfat_err("root is NULL\n");
1358 		return -ENOENT;
1359 	}
1360 
1361 	list_add(&exfat->root->list, &exfat->dir_list);
1362 
1363 	while (!list_empty(&exfat->dir_list)) {
1364 		dir = list_entry(exfat->dir_list.next, struct exfat_inode, list);
1365 
1366 		if (!(dir->attr & ATTR_SUBDIR)) {
1367 			fsck_err(dir->parent, dir,
1368 				"failed to travel directories. "
1369 				"the node is not directory\n");
1370 			ret = -EINVAL;
1371 			goto out;
1372 		}
1373 
1374 		dir_errors = read_children(exfat, dir);
1375 		if (dir_errors) {
1376 			resolve_path(&path_resolve_ctx, dir);
1377 			exfat_debug("failed to check dentries: %s\n",
1378 					path_resolve_ctx.local_path);
1379 			ret = dir_errors;
1380 		}
1381 
1382 		list_del(&dir->list);
1383 		inode_free_file_children(dir);
1384 		inode_free_ancestors(dir);
1385 	}
1386 out:
1387 	exfat_free_dir_list(exfat);
1388 	exfat->root = NULL;
1389 	if (exfat->dirty_fat && reclaim_free_clusters(exfat))
1390 		return -EIO;
1391 	return ret;
1392 }
1393 
exfat_root_dir_check(struct exfat * exfat)1394 static int exfat_root_dir_check(struct exfat *exfat)
1395 {
1396 	struct exfat_inode *root;
1397 	clus_t clus_count;
1398 
1399 	root = alloc_exfat_inode(ATTR_SUBDIR);
1400 	if (!root) {
1401 		exfat_err("failed to allocate memory\n");
1402 		return -ENOMEM;
1403 	}
1404 
1405 	root->first_clus = le32_to_cpu(exfat->bs->bsx.root_cluster);
1406 	if (!root_get_clus_count(exfat, root, &clus_count)) {
1407 		exfat_err("failed to follow the cluster chain of root\n");
1408 		free_exfat_inode(root);
1409 		return -EINVAL;
1410 	}
1411 	root->size = clus_count * exfat->clus_size;
1412 
1413 	exfat->root = root;
1414 	exfat_debug("root directory: start cluster[0x%x] size[0x%" PRIx64 "]\n",
1415 		root->first_clus, root->size);
1416 	return 0;
1417 }
1418 
bytes_to_human_readable(size_t bytes)1419 static char *bytes_to_human_readable(size_t bytes)
1420 {
1421 	static const char * const units[] = {"B", "KB", "MB", "GB", "TB", "PB"};
1422 	static char buf[15*4];
1423 	unsigned int i, shift, quoti, remain;
1424 
1425 	shift = 0;
1426 	for (i = 0; i < sizeof(units)/sizeof(units[0]); i++) {
1427 		if (bytes / (1ULL << (shift + 10)) == 0)
1428 			break;
1429 		shift += 10;
1430 	}
1431 
1432 	quoti = (unsigned int)(bytes / (1ULL << shift));
1433 	remain = 0;
1434 	if (shift > 0) {
1435 		remain = (unsigned int)
1436 			((bytes & ((1ULL << shift) - 1)) >> (shift - 10));
1437 		remain = (remain * 100) / 1024;
1438 	}
1439 
1440 	snprintf(buf, sizeof(buf), "%u.%02u %s", quoti, remain, units[i]);
1441 	return buf;
1442 }
1443 
exfat_show_info(struct exfat * exfat,const char * dev_name,int errors)1444 static void exfat_show_info(struct exfat *exfat, const char *dev_name,
1445 			int errors)
1446 {
1447 	exfat_info("sector size:  %s\n",
1448 		bytes_to_human_readable(1 << exfat->bs->bsx.sect_size_bits));
1449 	exfat_info("cluster size: %s\n",
1450 		bytes_to_human_readable(exfat->clus_size));
1451 	exfat_info("volume size:  %s\n",
1452 		bytes_to_human_readable(exfat->blk_dev->size));
1453 
1454 	printf("%s: %s. directories %ld, files %ld\n", dev_name,
1455 			errors ? "checking stopped" : "clean",
1456 			exfat_stat.dir_count, exfat_stat.file_count);
1457 	if (errors || exfat->dirty)
1458 		printf("%s: files corrupted %ld, files fixed %ld\n", dev_name,
1459 			exfat_stat.error_count, exfat_stat.fixed_count);
1460 }
1461 
main(int argc,char * const argv[])1462 int main(int argc, char * const argv[])
1463 {
1464 	struct fsck_user_input ui;
1465 	struct exfat_blk_dev bd;
1466 	struct exfat *exfat = NULL;
1467 	struct pbr *bs = NULL;
1468 	int c, ret, exit_code;
1469 	bool version_only = false;
1470 
1471 	memset(&ui, 0, sizeof(ui));
1472 	memset(&bd, 0, sizeof(bd));
1473 
1474 	print_level = EXFAT_ERROR;
1475 
1476 	if (!setlocale(LC_CTYPE, ""))
1477 		exfat_err("failed to init locale/codeset\n");
1478 
1479 	opterr = 0;
1480 	while ((c = getopt_long(argc, argv, "arynpVvh", opts, NULL)) != EOF) {
1481 		switch (c) {
1482 		case 'n':
1483 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1484 				usage(argv[0]);
1485 			ui.options |= FSCK_OPTS_REPAIR_NO;
1486 			break;
1487 		case 'r':
1488 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1489 				usage(argv[0]);
1490 			ui.options |= FSCK_OPTS_REPAIR_ASK;
1491 			break;
1492 		case 'y':
1493 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1494 				usage(argv[0]);
1495 			ui.options |= FSCK_OPTS_REPAIR_YES;
1496 			break;
1497 		case 'a':
1498 		case 'p':
1499 			if (ui.options & FSCK_OPTS_REPAIR_ALL)
1500 				usage(argv[0]);
1501 			ui.options |= FSCK_OPTS_REPAIR_AUTO;
1502 			break;
1503 		case 'V':
1504 			version_only = true;
1505 			break;
1506 		case 'v':
1507 			if (print_level < EXFAT_DEBUG)
1508 				print_level++;
1509 			break;
1510 		case '?':
1511 		case 'h':
1512 		default:
1513 			usage(argv[0]);
1514 		}
1515 	}
1516 
1517 	show_version();
1518 	if (optind != argc - 1)
1519 		usage(argv[0]);
1520 
1521 	if (version_only)
1522 		exit(FSCK_EXIT_SYNTAX_ERROR);
1523 	if (ui.options & FSCK_OPTS_REPAIR_WRITE)
1524 		ui.ei.writeable = true;
1525 	else {
1526 		ui.options |= FSCK_OPTS_REPAIR_NO;
1527 		ui.ei.writeable = false;
1528 	}
1529 
1530 	snprintf(ui.ei.dev_name, sizeof(ui.ei.dev_name), "%s", argv[optind]);
1531 	ret = exfat_get_blk_dev_info(&ui.ei, &bd);
1532 	if (ret < 0) {
1533 		exfat_err("failed to open %s. %d\n", ui.ei.dev_name, ret);
1534 		return FSCK_EXIT_OPERATION_ERROR;
1535 	}
1536 
1537 	exfat = (struct exfat *)calloc(1, sizeof(*exfat));
1538 	if (!exfat) {
1539 		exfat_err("failed to allocate exfat\n");
1540 		ret = -ENOMEM;
1541 		goto err;
1542 	}
1543 	exfat->blk_dev = &bd;
1544 	exfat->options = ui.options;
1545 
1546 	ret = exfat_boot_region_check(exfat, &bs);
1547 	if (ret)
1548 		goto err;
1549 
1550 	ret = init_exfat(exfat, bs);
1551 	if (ret)
1552 		goto err;
1553 
1554 	if (exfat_mark_volume_dirty(exfat, true)) {
1555 		ret = -EIO;
1556 		goto err;
1557 	}
1558 
1559 	exfat_debug("verifying root directory...\n");
1560 	ret = exfat_root_dir_check(exfat);
1561 	if (ret) {
1562 		exfat_err("failed to verify root directory.\n");
1563 		goto out;
1564 	}
1565 
1566 	exfat_debug("verifying directory entries...\n");
1567 	ret = exfat_filesystem_check(exfat);
1568 	if (ret)
1569 		goto out;
1570 
1571 	if (ui.ei.writeable && fsync(bd.dev_fd)) {
1572 		exfat_err("failed to sync\n");
1573 		ret = -EIO;
1574 		goto out;
1575 	}
1576 	exfat_mark_volume_dirty(exfat, false);
1577 
1578 out:
1579 	exfat_show_info(exfat, ui.ei.dev_name, ret);
1580 err:
1581 	if (ret == -EINVAL)
1582 		exit_code = FSCK_EXIT_ERRORS_LEFT;
1583 	else if (ret)
1584 		exit_code = FSCK_EXIT_OPERATION_ERROR;
1585 	else if (exfat->dirty)
1586 		exit_code = FSCK_EXIT_CORRECTED;
1587 	else
1588 		exit_code = FSCK_EXIT_NO_ERRORS;
1589 
1590 	free_exfat(exfat);
1591 	close(bd.dev_fd);
1592 	return exit_code;
1593 }
1594