• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * fsck.c
3  *
4  * Copyright (c) 2013 Samsung Electronics Co., Ltd.
5  *             http://www.samsung.com/
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11 #include "fsck.h"
12 #include "xattr.h"
13 #include "quotaio.h"
14 #include <time.h>
15 
16 char *tree_mark;
17 uint32_t tree_mark_size = 256;
18 
f2fs_set_main_bitmap(struct f2fs_sb_info * sbi,u32 blk,int type)19 int f2fs_set_main_bitmap(struct f2fs_sb_info *sbi, u32 blk, int type)
20 {
21 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
22 	struct seg_entry *se;
23 	int fix = 0;
24 
25 	se = get_seg_entry(sbi, GET_SEGNO(sbi, blk));
26 	if (se->type >= NO_CHECK_TYPE)
27 		fix = 1;
28 	else if (IS_DATASEG(se->type) != IS_DATASEG(type))
29 		fix = 1;
30 
31 	/* just check data and node types */
32 	if (fix) {
33 		DBG(1, "Wrong segment type [0x%x] %x -> %x",
34 				GET_SEGNO(sbi, blk), se->type, type);
35 		se->type = type;
36 	}
37 	return f2fs_set_bit(BLKOFF_FROM_MAIN(sbi, blk), fsck->main_area_bitmap);
38 }
39 
f2fs_test_main_bitmap(struct f2fs_sb_info * sbi,u32 blk)40 static inline int f2fs_test_main_bitmap(struct f2fs_sb_info *sbi, u32 blk)
41 {
42 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
43 
44 	return f2fs_test_bit(BLKOFF_FROM_MAIN(sbi, blk),
45 						fsck->main_area_bitmap);
46 }
47 
f2fs_clear_main_bitmap(struct f2fs_sb_info * sbi,u32 blk)48 static inline int f2fs_clear_main_bitmap(struct f2fs_sb_info *sbi, u32 blk)
49 {
50 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
51 
52 	return f2fs_clear_bit(BLKOFF_FROM_MAIN(sbi, blk),
53 						fsck->main_area_bitmap);
54 }
55 
f2fs_test_sit_bitmap(struct f2fs_sb_info * sbi,u32 blk)56 static inline int f2fs_test_sit_bitmap(struct f2fs_sb_info *sbi, u32 blk)
57 {
58 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
59 
60 	return f2fs_test_bit(BLKOFF_FROM_MAIN(sbi, blk), fsck->sit_area_bitmap);
61 }
62 
f2fs_set_sit_bitmap(struct f2fs_sb_info * sbi,u32 blk)63 int f2fs_set_sit_bitmap(struct f2fs_sb_info *sbi, u32 blk)
64 {
65 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
66 
67 	return f2fs_set_bit(BLKOFF_FROM_MAIN(sbi, blk), fsck->sit_area_bitmap);
68 }
69 
add_into_hard_link_list(struct f2fs_sb_info * sbi,u32 nid,u32 link_cnt)70 static int add_into_hard_link_list(struct f2fs_sb_info *sbi,
71 						u32 nid, u32 link_cnt)
72 {
73 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
74 	struct hard_link_node *node = NULL, *tmp = NULL, *prev = NULL;
75 
76 	node = calloc(sizeof(struct hard_link_node), 1);
77 	ASSERT(node != NULL);
78 
79 	node->nid = nid;
80 	node->links = link_cnt;
81 	node->actual_links = 1;
82 	node->next = NULL;
83 
84 	if (fsck->hard_link_list_head == NULL) {
85 		fsck->hard_link_list_head = node;
86 		goto out;
87 	}
88 
89 	tmp = fsck->hard_link_list_head;
90 
91 	/* Find insertion position */
92 	while (tmp && (nid < tmp->nid)) {
93 		ASSERT(tmp->nid != nid);
94 		prev = tmp;
95 		tmp = tmp->next;
96 	}
97 
98 	if (tmp == fsck->hard_link_list_head) {
99 		node->next = tmp;
100 		fsck->hard_link_list_head = node;
101 	} else {
102 		prev->next = node;
103 		node->next = tmp;
104 	}
105 
106 out:
107 	DBG(2, "ino[0x%x] has hard links [0x%x]\n", nid, link_cnt);
108 	return 0;
109 }
110 
find_and_dec_hard_link_list(struct f2fs_sb_info * sbi,u32 nid)111 static int find_and_dec_hard_link_list(struct f2fs_sb_info *sbi, u32 nid)
112 {
113 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
114 	struct hard_link_node *node = NULL, *prev = NULL;
115 
116 	if (fsck->hard_link_list_head == NULL)
117 		return -EINVAL;
118 
119 	node = fsck->hard_link_list_head;
120 
121 	while (node && (nid < node->nid)) {
122 		prev = node;
123 		node = node->next;
124 	}
125 
126 	if (node == NULL || (nid != node->nid))
127 		return -EINVAL;
128 
129 	/* Decrease link count */
130 	node->links = node->links - 1;
131 	node->actual_links++;
132 
133 	/* if link count becomes one, remove the node */
134 	if (node->links == 1) {
135 		if (fsck->hard_link_list_head == node)
136 			fsck->hard_link_list_head = node->next;
137 		else
138 			prev->next = node->next;
139 		free(node);
140 	}
141 	return 0;
142 }
143 
is_valid_ssa_node_blk(struct f2fs_sb_info * sbi,u32 nid,u32 blk_addr)144 static int is_valid_ssa_node_blk(struct f2fs_sb_info *sbi, u32 nid,
145 							u32 blk_addr)
146 {
147 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
148 	struct f2fs_summary_block *sum_blk;
149 	struct f2fs_summary *sum_entry;
150 	struct seg_entry * se;
151 	u32 segno, offset;
152 	int need_fix = 0, ret = 0;
153 	int type;
154 
155 	if (get_sb(feature) & cpu_to_le32(F2FS_FEATURE_RO))
156 		return 0;
157 
158 	segno = GET_SEGNO(sbi, blk_addr);
159 	offset = OFFSET_IN_SEG(sbi, blk_addr);
160 
161 	sum_blk = get_sum_block(sbi, segno, &type);
162 
163 	if (type != SEG_TYPE_NODE && type != SEG_TYPE_CUR_NODE) {
164 		/* can't fix current summary, then drop the block */
165 		if (!c.fix_on || type < 0) {
166 			ASSERT_MSG("Summary footer is not for node segment");
167 			ret = -EINVAL;
168 			goto out;
169 		}
170 
171 		need_fix = 1;
172 		se = get_seg_entry(sbi, segno);
173 		if(IS_NODESEG(se->type)) {
174 			FIX_MSG("Summary footer indicates a node segment: 0x%x", segno);
175 			sum_blk->footer.entry_type = SUM_TYPE_NODE;
176 		} else {
177 			ret = -EINVAL;
178 			goto out;
179 		}
180 	}
181 
182 	sum_entry = &(sum_blk->entries[offset]);
183 
184 	if (le32_to_cpu(sum_entry->nid) != nid) {
185 		if (!c.fix_on || type < 0) {
186 			DBG(0, "nid                       [0x%x]\n", nid);
187 			DBG(0, "target blk_addr           [0x%x]\n", blk_addr);
188 			DBG(0, "summary blk_addr          [0x%x]\n",
189 						GET_SUM_BLKADDR(sbi,
190 						GET_SEGNO(sbi, blk_addr)));
191 			DBG(0, "seg no / offset           [0x%x / 0x%x]\n",
192 						GET_SEGNO(sbi, blk_addr),
193 						OFFSET_IN_SEG(sbi, blk_addr));
194 			DBG(0, "summary_entry.nid         [0x%x]\n",
195 						le32_to_cpu(sum_entry->nid));
196 			DBG(0, "--> node block's nid      [0x%x]\n", nid);
197 			ASSERT_MSG("Invalid node seg summary\n");
198 			ret = -EINVAL;
199 		} else {
200 			FIX_MSG("Set node summary 0x%x -> [0x%x] [0x%x]",
201 						segno, nid, blk_addr);
202 			sum_entry->nid = cpu_to_le32(nid);
203 			need_fix = 1;
204 		}
205 	}
206 	if (need_fix && f2fs_dev_is_writable()) {
207 		u64 ssa_blk;
208 		int ret2;
209 
210 		ssa_blk = GET_SUM_BLKADDR(sbi, segno);
211 		ret2 = dev_write_block(sum_blk, ssa_blk);
212 		ASSERT(ret2 >= 0);
213 	}
214 out:
215 	if (type == SEG_TYPE_NODE || type == SEG_TYPE_DATA ||
216 					type == SEG_TYPE_MAX)
217 		free(sum_blk);
218 	return ret;
219 }
220 
is_valid_summary(struct f2fs_sb_info * sbi,struct f2fs_summary * sum,u32 blk_addr)221 static int is_valid_summary(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
222 							u32 blk_addr)
223 {
224 	u16 ofs_in_node = le16_to_cpu(sum->ofs_in_node);
225 	u32 nid = le32_to_cpu(sum->nid);
226 	struct f2fs_node *node_blk = NULL;
227 	__le32 target_blk_addr;
228 	struct node_info ni;
229 	int ret = 0;
230 
231 	node_blk = (struct f2fs_node *)calloc(BLOCK_SZ, 1);
232 	ASSERT(node_blk != NULL);
233 
234 	if (!IS_VALID_NID(sbi, nid))
235 		goto out;
236 
237 	get_node_info(sbi, nid, &ni);
238 
239 	if (!IS_VALID_BLK_ADDR(sbi, ni.blk_addr))
240 		goto out;
241 
242 	/* read node_block */
243 	ret = dev_read_block(node_blk, ni.blk_addr);
244 	ASSERT(ret >= 0);
245 
246 	if (le32_to_cpu(node_blk->footer.nid) != nid)
247 		goto out;
248 
249 	/* check its block address */
250 	if (node_blk->footer.nid == node_blk->footer.ino) {
251 		int ofs = get_extra_isize(node_blk);
252 
253 		if (ofs + ofs_in_node >= DEF_ADDRS_PER_INODE)
254 			goto out;
255 		target_blk_addr = node_blk->i.i_addr[ofs + ofs_in_node];
256 	} else {
257 		if (ofs_in_node >= DEF_ADDRS_PER_BLOCK)
258 			goto out;
259 		target_blk_addr = node_blk->dn.addr[ofs_in_node];
260 	}
261 
262 	if (blk_addr == le32_to_cpu(target_blk_addr))
263 		ret = 1;
264 out:
265 	free(node_blk);
266 	return ret;
267 }
268 
is_valid_ssa_data_blk(struct f2fs_sb_info * sbi,u32 blk_addr,u32 parent_nid,u16 idx_in_node,u8 version)269 static int is_valid_ssa_data_blk(struct f2fs_sb_info *sbi, u32 blk_addr,
270 		u32 parent_nid, u16 idx_in_node, u8 version)
271 {
272 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
273 	struct f2fs_summary_block *sum_blk;
274 	struct f2fs_summary *sum_entry;
275 	struct seg_entry * se;
276 	u32 segno, offset;
277 	int need_fix = 0, ret = 0;
278 	int type;
279 
280 	if (get_sb(feature) & cpu_to_le32(F2FS_FEATURE_RO))
281 		return 0;
282 
283 	segno = GET_SEGNO(sbi, blk_addr);
284 	offset = OFFSET_IN_SEG(sbi, blk_addr);
285 
286 	sum_blk = get_sum_block(sbi, segno, &type);
287 
288 	if (type != SEG_TYPE_DATA && type != SEG_TYPE_CUR_DATA) {
289 		/* can't fix current summary, then drop the block */
290 		if (!c.fix_on || type < 0) {
291 			ASSERT_MSG("Summary footer is not for data segment");
292 			ret = -EINVAL;
293 			goto out;
294 		}
295 
296 		need_fix = 1;
297 		se = get_seg_entry(sbi, segno);
298 		if (IS_DATASEG(se->type)) {
299 			FIX_MSG("Summary footer indicates a data segment: 0x%x", segno);
300 			sum_blk->footer.entry_type = SUM_TYPE_DATA;
301 		} else {
302 			ret = -EINVAL;
303 			goto out;
304 		}
305 	}
306 
307 	sum_entry = &(sum_blk->entries[offset]);
308 
309 	if (le32_to_cpu(sum_entry->nid) != parent_nid ||
310 			sum_entry->version != version ||
311 			le16_to_cpu(sum_entry->ofs_in_node) != idx_in_node) {
312 		if (!c.fix_on || type < 0) {
313 			DBG(0, "summary_entry.nid         [0x%x]\n",
314 					le32_to_cpu(sum_entry->nid));
315 			DBG(0, "summary_entry.version     [0x%x]\n",
316 					sum_entry->version);
317 			DBG(0, "summary_entry.ofs_in_node [0x%x]\n",
318 					le16_to_cpu(sum_entry->ofs_in_node));
319 			DBG(0, "parent nid                [0x%x]\n",
320 					parent_nid);
321 			DBG(0, "version from nat          [0x%x]\n", version);
322 			DBG(0, "idx in parent node        [0x%x]\n",
323 					idx_in_node);
324 
325 			DBG(0, "Target data block addr    [0x%x]\n", blk_addr);
326 			ASSERT_MSG("Invalid data seg summary\n");
327 			ret = -EINVAL;
328 		} else if (is_valid_summary(sbi, sum_entry, blk_addr)) {
329 			/* delete wrong index */
330 			ret = -EINVAL;
331 		} else {
332 			FIX_MSG("Set data summary 0x%x -> [0x%x] [0x%x] [0x%x]",
333 					segno, parent_nid, version, idx_in_node);
334 			sum_entry->nid = cpu_to_le32(parent_nid);
335 			sum_entry->version = version;
336 			sum_entry->ofs_in_node = cpu_to_le16(idx_in_node);
337 			need_fix = 1;
338 		}
339 	}
340 	if (need_fix && f2fs_dev_is_writable()) {
341 		u64 ssa_blk;
342 		int ret2;
343 
344 		ssa_blk = GET_SUM_BLKADDR(sbi, segno);
345 		ret2 = dev_write_block(sum_blk, ssa_blk);
346 		ASSERT(ret2 >= 0);
347 	}
348 out:
349 	if (type == SEG_TYPE_NODE || type == SEG_TYPE_DATA ||
350 					type == SEG_TYPE_MAX)
351 		free(sum_blk);
352 	return ret;
353 }
354 
__check_inode_mode(u32 nid,enum FILE_TYPE ftype,u16 mode)355 static int __check_inode_mode(u32 nid, enum FILE_TYPE ftype, u16 mode)
356 {
357 	if (ftype >= F2FS_FT_MAX)
358 		return 0;
359 	/* f2fs_iget will return -EIO if mode is not valid file type */
360 	if (!S_ISLNK(mode) && !S_ISREG(mode) && !S_ISDIR(mode) &&
361 	    !S_ISCHR(mode) && !S_ISBLK(mode) && !S_ISFIFO(mode) &&
362 	    !S_ISSOCK(mode)) {
363 		ASSERT_MSG("inode [0x%x] unknown file type i_mode [0x%x]",
364 			   nid, mode);
365 		return -1;
366 	}
367 
368 	if (S_ISLNK(mode) && ftype != F2FS_FT_SYMLINK)
369 		goto err;
370 	if (S_ISREG(mode) && ftype != F2FS_FT_REG_FILE)
371 		goto err;
372 	if (S_ISDIR(mode) && ftype != F2FS_FT_DIR)
373 		goto err;
374 	if (S_ISCHR(mode) && ftype != F2FS_FT_CHRDEV)
375 		goto err;
376 	if (S_ISBLK(mode) && ftype != F2FS_FT_BLKDEV)
377 		goto err;
378 	if (S_ISFIFO(mode) && ftype != F2FS_FT_FIFO)
379 		goto err;
380 	if (S_ISSOCK(mode) && ftype != F2FS_FT_SOCK)
381 		goto err;
382 	return 0;
383 err:
384 	ASSERT_MSG("inode [0x%x] mismatch i_mode [0x%x vs. 0x%x]",
385 		   nid, ftype, mode);
386 	return -1;
387 }
388 
sanity_check_nid(struct f2fs_sb_info * sbi,u32 nid,struct f2fs_node * node_blk,enum FILE_TYPE ftype,enum NODE_TYPE ntype,struct node_info * ni)389 static int sanity_check_nid(struct f2fs_sb_info *sbi, u32 nid,
390 			struct f2fs_node *node_blk,
391 			enum FILE_TYPE ftype, enum NODE_TYPE ntype,
392 			struct node_info *ni)
393 {
394 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
395 	int ret;
396 
397 	if (!IS_VALID_NID(sbi, nid)) {
398 		ASSERT_MSG("nid is not valid. [0x%x]", nid);
399 		return -EINVAL;
400 	}
401 
402 	get_node_info(sbi, nid, ni);
403 	if (ni->ino == 0) {
404 		ASSERT_MSG("nid[0x%x] ino is 0", nid);
405 		return -EINVAL;
406 	}
407 
408 	if (ni->blk_addr == NEW_ADDR) {
409 		ASSERT_MSG("nid is NEW_ADDR. [0x%x]", nid);
410 		return -EINVAL;
411 	}
412 
413 	if (!IS_VALID_BLK_ADDR(sbi, ni->blk_addr)) {
414 		ASSERT_MSG("blkaddress is not valid. [0x%x]", ni->blk_addr);
415 		return -EINVAL;
416 	}
417 
418 	ret = dev_read_block(node_blk, ni->blk_addr);
419 	ASSERT(ret >= 0);
420 
421 	if (ntype == TYPE_INODE &&
422 			node_blk->footer.nid != node_blk->footer.ino) {
423 		ASSERT_MSG("nid[0x%x] footer.nid[0x%x] footer.ino[0x%x]",
424 				nid, le32_to_cpu(node_blk->footer.nid),
425 				le32_to_cpu(node_blk->footer.ino));
426 		return -EINVAL;
427 	}
428 	if (ni->ino != le32_to_cpu(node_blk->footer.ino)) {
429 		ASSERT_MSG("nid[0x%x] nat_entry->ino[0x%x] footer.ino[0x%x]",
430 				nid, ni->ino, le32_to_cpu(node_blk->footer.ino));
431 		return -EINVAL;
432 	}
433 	if (ntype != TYPE_INODE &&
434 			node_blk->footer.nid == node_blk->footer.ino) {
435 		ASSERT_MSG("nid[0x%x] footer.nid[0x%x] footer.ino[0x%x]",
436 				nid, le32_to_cpu(node_blk->footer.nid),
437 				le32_to_cpu(node_blk->footer.ino));
438 		return -EINVAL;
439 	}
440 
441 	if (le32_to_cpu(node_blk->footer.nid) != nid) {
442 		ASSERT_MSG("nid[0x%x] blk_addr[0x%x] footer.nid[0x%x]",
443 				nid, ni->blk_addr,
444 				le32_to_cpu(node_blk->footer.nid));
445 		return -EINVAL;
446 	}
447 
448 	if (ntype == TYPE_XATTR) {
449 		u32 flag = le32_to_cpu(node_blk->footer.flag);
450 
451 		if ((flag >> OFFSET_BIT_SHIFT) != XATTR_NODE_OFFSET) {
452 			ASSERT_MSG("xnid[0x%x] has wrong ofs:[0x%x]",
453 					nid, flag);
454 			return -EINVAL;
455 		}
456 	}
457 
458 	if ((ntype == TYPE_INODE && ftype == F2FS_FT_DIR) ||
459 			(ntype == TYPE_XATTR && ftype == F2FS_FT_XATTR)) {
460 		/* not included '.' & '..' */
461 		if (f2fs_test_main_bitmap(sbi, ni->blk_addr) != 0) {
462 			ASSERT_MSG("Duplicated node blk. nid[0x%x][0x%x]\n",
463 					nid, ni->blk_addr);
464 			return -EINVAL;
465 		}
466 	}
467 
468 	/* this if only from fix_hard_links */
469 	if (ftype == F2FS_FT_MAX)
470 		return 0;
471 
472 	if (ntype == TYPE_INODE &&
473 		__check_inode_mode(nid, ftype, le16_to_cpu(node_blk->i.i_mode)))
474 		return -EINVAL;
475 
476 	/* workaround to fix later */
477 	if (ftype != F2FS_FT_ORPHAN ||
478 			f2fs_test_bit(nid, fsck->nat_area_bitmap) != 0) {
479 		f2fs_clear_bit(nid, fsck->nat_area_bitmap);
480 		/* avoid reusing nid when reconnecting files */
481 		f2fs_set_bit(nid, NM_I(sbi)->nid_bitmap);
482 	} else
483 		ASSERT_MSG("orphan or xattr nid is duplicated [0x%x]\n",
484 				nid);
485 
486 	if (is_valid_ssa_node_blk(sbi, nid, ni->blk_addr)) {
487 		ASSERT_MSG("summary node block is not valid. [0x%x]", nid);
488 		return -EINVAL;
489 	}
490 
491 	if (f2fs_test_sit_bitmap(sbi, ni->blk_addr) == 0)
492 		ASSERT_MSG("SIT bitmap is 0x0. blk_addr[0x%x]",
493 				ni->blk_addr);
494 
495 	if (f2fs_test_main_bitmap(sbi, ni->blk_addr) == 0) {
496 
497 		fsck->chk.valid_blk_cnt++;
498 		fsck->chk.valid_node_cnt++;
499 
500 		/* Progress report */
501 		if (!c.show_file_map && sbi->total_valid_node_count > 1000) {
502 			unsigned int p10 = sbi->total_valid_node_count / 10;
503 
504 			if (sbi->fsck->chk.checked_node_cnt++ % p10)
505 				return 0;
506 
507 			printf("[FSCK] Check node %"PRIu64" / %u (%.2f%%)\n",
508 				sbi->fsck->chk.checked_node_cnt,
509 				sbi->total_valid_node_count,
510 				10 * (float)sbi->fsck->chk.checked_node_cnt /
511 				p10);
512 		}
513 	}
514 	return 0;
515 }
516 
fsck_sanity_check_nid(struct f2fs_sb_info * sbi,u32 nid,struct f2fs_node * node_blk,enum FILE_TYPE ftype,enum NODE_TYPE ntype,struct node_info * ni)517 int fsck_sanity_check_nid(struct f2fs_sb_info *sbi, u32 nid,
518 			struct f2fs_node *node_blk,
519 			enum FILE_TYPE ftype, enum NODE_TYPE ntype,
520 			struct node_info *ni)
521 {
522 	return sanity_check_nid(sbi, nid, node_blk, ftype, ntype, ni);
523 }
524 
fsck_chk_xattr_blk(struct f2fs_sb_info * sbi,u32 ino,u32 x_nid,u32 * blk_cnt)525 static int fsck_chk_xattr_blk(struct f2fs_sb_info *sbi, u32 ino,
526 					u32 x_nid, u32 *blk_cnt)
527 {
528 	struct f2fs_node *node_blk = NULL;
529 	struct node_info ni;
530 	int ret = 0;
531 
532 	if (x_nid == 0x0)
533 		return 0;
534 
535 	node_blk = (struct f2fs_node *)calloc(BLOCK_SZ, 1);
536 	ASSERT(node_blk != NULL);
537 
538 	/* Sanity check */
539 	if (sanity_check_nid(sbi, x_nid, node_blk,
540 				F2FS_FT_XATTR, TYPE_XATTR, &ni)) {
541 		ret = -EINVAL;
542 		goto out;
543 	}
544 
545 	*blk_cnt = *blk_cnt + 1;
546 	f2fs_set_main_bitmap(sbi, ni.blk_addr, CURSEG_COLD_NODE);
547 	DBG(2, "ino[0x%x] x_nid[0x%x]\n", ino, x_nid);
548 out:
549 	free(node_blk);
550 	return ret;
551 }
552 
fsck_chk_node_blk(struct f2fs_sb_info * sbi,struct f2fs_inode * inode,u32 nid,enum FILE_TYPE ftype,enum NODE_TYPE ntype,u32 * blk_cnt,struct f2fs_compr_blk_cnt * cbc,struct child_info * child)553 int fsck_chk_node_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode,
554 		u32 nid, enum FILE_TYPE ftype, enum NODE_TYPE ntype,
555 		u32 *blk_cnt, struct f2fs_compr_blk_cnt *cbc,
556 		struct child_info *child)
557 {
558 	struct node_info ni;
559 	struct f2fs_node *node_blk = NULL;
560 
561 	node_blk = (struct f2fs_node *)calloc(BLOCK_SZ, 1);
562 	ASSERT(node_blk != NULL);
563 
564 	if (sanity_check_nid(sbi, nid, node_blk, ftype, ntype, &ni))
565 		goto err;
566 
567 	if (ntype == TYPE_INODE) {
568 		struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
569 
570 		fsck_chk_inode_blk(sbi, nid, ftype, node_blk, blk_cnt, cbc,
571 				&ni, child);
572 		quota_add_inode_usage(fsck->qctx, nid, &node_blk->i);
573 	} else {
574 		switch (ntype) {
575 		case TYPE_DIRECT_NODE:
576 			f2fs_set_main_bitmap(sbi, ni.blk_addr,
577 							CURSEG_WARM_NODE);
578 			fsck_chk_dnode_blk(sbi, inode, nid, ftype, node_blk,
579 					blk_cnt, cbc, child, &ni);
580 			break;
581 		case TYPE_INDIRECT_NODE:
582 			f2fs_set_main_bitmap(sbi, ni.blk_addr,
583 							CURSEG_COLD_NODE);
584 			fsck_chk_idnode_blk(sbi, inode, ftype, node_blk,
585 					blk_cnt, cbc, child);
586 			break;
587 		case TYPE_DOUBLE_INDIRECT_NODE:
588 			f2fs_set_main_bitmap(sbi, ni.blk_addr,
589 							CURSEG_COLD_NODE);
590 			fsck_chk_didnode_blk(sbi, inode, ftype, node_blk,
591 					blk_cnt, cbc, child);
592 			break;
593 		default:
594 			ASSERT(0);
595 		}
596 	}
597 	free(node_blk);
598 	return 0;
599 err:
600 	free(node_blk);
601 	return -EINVAL;
602 }
603 
get_extent_info(struct extent_info * ext,struct f2fs_extent * i_ext)604 static inline void get_extent_info(struct extent_info *ext,
605 					struct f2fs_extent *i_ext)
606 {
607 	ext->fofs = le32_to_cpu(i_ext->fofs);
608 	ext->blk = le32_to_cpu(i_ext->blk_addr);
609 	ext->len = le32_to_cpu(i_ext->len);
610 }
611 
check_extent_info(struct child_info * child,block_t blkaddr,int last)612 static void check_extent_info(struct child_info *child,
613 						block_t blkaddr, int last)
614 {
615 	struct extent_info *ei = &child->ei;
616 	u32 pgofs = child->pgofs;
617 	int is_hole = 0;
618 
619 	if (!ei->len)
620 		return;
621 
622 	if (child->state & FSCK_UNMATCHED_EXTENT)
623 		return;
624 
625 	if ((child->state & FSCK_INLINE_INODE) && ei->len)
626 		goto unmatched;
627 
628 	if (last) {
629 		/* hole exist in the back of extent */
630 		if (child->last_blk != ei->blk + ei->len - 1)
631 			child->state |= FSCK_UNMATCHED_EXTENT;
632 		return;
633 	}
634 
635 	if (blkaddr == NULL_ADDR || blkaddr == NEW_ADDR)
636 		is_hole = 1;
637 
638 	if (pgofs >= ei->fofs && pgofs < ei->fofs + ei->len) {
639 		/* unmatched blkaddr */
640 		if (is_hole || (blkaddr != pgofs - ei->fofs + ei->blk))
641 			goto unmatched;
642 
643 		if (!child->last_blk) {
644 			/* hole exists in the front of extent */
645 			if (pgofs != ei->fofs)
646 				goto unmatched;
647 		} else if (child->last_blk + 1 != blkaddr) {
648 			/* hole exists in the middle of extent */
649 			goto unmatched;
650 		}
651 		child->last_blk = blkaddr;
652 		return;
653 	}
654 
655 	if (is_hole)
656 		return;
657 
658 	if (blkaddr < ei->blk || blkaddr >= ei->blk + ei->len)
659 		return;
660 	/* unmatched file offset */
661 unmatched:
662 	child->state |= FSCK_UNMATCHED_EXTENT;
663 }
664 
fsck_reada_node_block(struct f2fs_sb_info * sbi,u32 nid)665 void fsck_reada_node_block(struct f2fs_sb_info *sbi, u32 nid)
666 {
667 	struct node_info ni;
668 
669 	if (nid != 0 && IS_VALID_NID(sbi, nid)) {
670 		get_node_info(sbi, nid, &ni);
671 		if (IS_VALID_BLK_ADDR(sbi, ni.blk_addr))
672 			dev_reada_block(ni.blk_addr);
673 	}
674 }
675 
fsck_reada_all_direct_node_blocks(struct f2fs_sb_info * sbi,struct f2fs_node * node_blk)676 void fsck_reada_all_direct_node_blocks(struct f2fs_sb_info *sbi,
677 						struct f2fs_node *node_blk)
678 {
679 	int i;
680 
681 	for (i = 0; i < NIDS_PER_BLOCK; i++) {
682 		u32 nid = le32_to_cpu(node_blk->in.nid[i]);
683 
684 		fsck_reada_node_block(sbi, nid);
685 	}
686 }
687 
is_zeroed(const u8 * p,size_t size)688 static bool is_zeroed(const u8 *p, size_t size)
689 {
690 	size_t i;
691 
692 	for (i = 0; i < size; i++) {
693 		if (p[i])
694 			return false;
695 	}
696 	return true;
697 }
698 
chk_extended_attributes(struct f2fs_sb_info * sbi,u32 nid,struct f2fs_node * inode)699 int chk_extended_attributes(struct f2fs_sb_info *sbi, u32 nid,
700 		struct f2fs_node *inode)
701 {
702 	void *xattr;
703 	void *last_base_addr;
704 	struct f2fs_xattr_entry *ent;
705 	__u32 xattr_size = XATTR_SIZE(&inode->i);
706 	bool need_fix = false;
707 
708 	if (xattr_size == 0)
709 		return 0;
710 
711 	xattr = read_all_xattrs(sbi, inode, false);
712 	ASSERT(xattr);
713 
714 	last_base_addr = (void *)xattr + xattr_size;
715 
716 	list_for_each_xattr(ent, xattr) {
717 		if ((void *)(ent) + sizeof(__u32) > last_base_addr ||
718 			(void *)XATTR_NEXT_ENTRY(ent) > last_base_addr) {
719 			ASSERT_MSG("[0x%x] last xattr entry (offset: %lx) "
720 					"crosses the boundary",
721 					nid, (long int)((void *)ent - xattr));
722 			need_fix = true;
723 			break;
724 		}
725 	}
726 	if (!need_fix &&
727 	    !is_zeroed((u8 *)ent, (u8 *)last_base_addr - (u8 *)ent)) {
728 		ASSERT_MSG("[0x%x] nonzero bytes in xattr space after "
729 				"end of list", nid);
730 		need_fix = true;
731 	}
732 	if (need_fix && c.fix_on) {
733 		memset(ent, 0, (u8 *)last_base_addr - (u8 *)ent);
734 		write_all_xattrs(sbi, inode, xattr_size, xattr);
735 		FIX_MSG("[0x%x] nullify wrong xattr entries", nid);
736 		free(xattr);
737 		return 1;
738 	}
739 	free(xattr);
740 	return 0;
741 }
742 
743 /* start with valid nid and blkaddr */
fsck_chk_inode_blk(struct f2fs_sb_info * sbi,u32 nid,enum FILE_TYPE ftype,struct f2fs_node * node_blk,u32 * blk_cnt,struct f2fs_compr_blk_cnt * cbc,struct node_info * ni,struct child_info * child_d)744 void fsck_chk_inode_blk(struct f2fs_sb_info *sbi, u32 nid,
745 		enum FILE_TYPE ftype, struct f2fs_node *node_blk,
746 		u32 *blk_cnt, struct f2fs_compr_blk_cnt *cbc,
747 		struct node_info *ni, struct child_info *child_d)
748 {
749 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
750 	struct child_info child;
751 	enum NODE_TYPE ntype;
752 	u32 i_links = le32_to_cpu(node_blk->i.i_links);
753 	u64 i_size = le64_to_cpu(node_blk->i.i_size);
754 	u64 i_blocks = le64_to_cpu(node_blk->i.i_blocks);
755 	bool compr_supported = c.feature & cpu_to_le32(F2FS_FEATURE_COMPRESSION);
756 	u32 i_flags = le32_to_cpu(node_blk->i.i_flags);
757 	bool compressed = i_flags & F2FS_COMPR_FL;
758 	bool compr_rel = node_blk->i.i_inline & F2FS_COMPRESS_RELEASED;
759 	u64 i_compr_blocks = le64_to_cpu(node_blk->i.i_compr_blocks);
760 	nid_t i_xattr_nid = le32_to_cpu(node_blk->i.i_xattr_nid);
761 	int ofs;
762 	char *en;
763 	u32 namelen;
764 	unsigned int addrs, idx = 0;
765 	unsigned short i_gc_failures;
766 	int need_fix = 0;
767 	int ret;
768 	u32 cluster_size = 1 << node_blk->i.i_log_cluster_size;
769 
770 	if (!compressed)
771 		goto check_next;
772 
773 	if (!compr_supported || (node_blk->i.i_inline & F2FS_INLINE_DATA)) {
774 		/*
775 		 * The 'compression' flag in i_flags affects the traverse of
776 		 * the node tree.  Thus, it must be fixed unconditionally
777 		 * in the memory (node_blk).
778 		 */
779 		node_blk->i.i_flags &= ~cpu_to_le32(F2FS_COMPR_FL);
780 		compressed = false;
781 		if (c.fix_on) {
782 			need_fix = 1;
783 			FIX_MSG("[0x%x] i_flags=0x%x -> 0x%x",
784 					nid, i_flags, node_blk->i.i_flags);
785 		}
786 		i_flags &= ~F2FS_COMPR_FL;
787 	}
788 check_next:
789 	memset(&child, 0, sizeof(child));
790 	child.links = 2;
791 	child.p_ino = nid;
792 	child.pp_ino = le32_to_cpu(node_blk->i.i_pino);
793 	child.dir_level = node_blk->i.i_dir_level;
794 
795 	if (f2fs_test_main_bitmap(sbi, ni->blk_addr) == 0)
796 		fsck->chk.valid_inode_cnt++;
797 
798 	if (ftype == F2FS_FT_DIR) {
799 		f2fs_set_main_bitmap(sbi, ni->blk_addr, CURSEG_HOT_NODE);
800 		namelen = le32_to_cpu(node_blk->i.i_namelen);
801 		if (namelen > F2FS_NAME_LEN)
802 			namelen = F2FS_NAME_LEN;
803 		memcpy(child.p_name, node_blk->i.i_name, namelen);
804 	} else {
805 		if (f2fs_test_main_bitmap(sbi, ni->blk_addr) == 0) {
806 			f2fs_set_main_bitmap(sbi, ni->blk_addr,
807 							CURSEG_WARM_NODE);
808 			if (i_links > 1 && ftype != F2FS_FT_ORPHAN &&
809 					!is_qf_ino(F2FS_RAW_SUPER(sbi), nid)) {
810 				/* First time. Create new hard link node */
811 				add_into_hard_link_list(sbi, nid, i_links);
812 				fsck->chk.multi_hard_link_files++;
813 			}
814 		} else {
815 			DBG(3, "[0x%x] has hard links [0x%x]\n", nid, i_links);
816 			if (find_and_dec_hard_link_list(sbi, nid)) {
817 				ASSERT_MSG("[0x%x] needs more i_links=0x%x",
818 						nid, i_links);
819 				if (c.fix_on) {
820 					node_blk->i.i_links =
821 						cpu_to_le32(i_links + 1);
822 					need_fix = 1;
823 					FIX_MSG("File: 0x%x "
824 						"i_links= 0x%x -> 0x%x",
825 						nid, i_links, i_links + 1);
826 				}
827 				goto skip_blkcnt_fix;
828 			}
829 			/* No need to go deep into the node */
830 			return;
831 		}
832 	}
833 
834 	/* readahead xattr node block */
835 	fsck_reada_node_block(sbi, i_xattr_nid);
836 
837 	if (fsck_chk_xattr_blk(sbi, nid, i_xattr_nid, blk_cnt)) {
838 		if (c.fix_on) {
839 			node_blk->i.i_xattr_nid = 0;
840 			need_fix = 1;
841 			FIX_MSG("Remove xattr block: 0x%x, x_nid = 0x%x",
842 							nid, i_xattr_nid);
843 		}
844 	}
845 
846 	if (ftype == F2FS_FT_CHRDEV || ftype == F2FS_FT_BLKDEV ||
847 			ftype == F2FS_FT_FIFO || ftype == F2FS_FT_SOCK)
848 		goto check;
849 
850 	/* init extent info */
851 	get_extent_info(&child.ei, &node_blk->i.i_ext);
852 	child.last_blk = 0;
853 
854 	if (f2fs_has_extra_isize(&node_blk->i)) {
855 		if (c.feature & cpu_to_le32(F2FS_FEATURE_EXTRA_ATTR)) {
856 			unsigned int isize =
857 				le16_to_cpu(node_blk->i.i_extra_isize);
858 			if (isize > 4 * DEF_ADDRS_PER_INODE) {
859 				ASSERT_MSG("[0x%x] wrong i_extra_isize=0x%x",
860 						nid, isize);
861 				if (c.fix_on) {
862 					FIX_MSG("ino[0x%x] recover i_extra_isize "
863 						"from %u to %u",
864 						nid, isize,
865 						calc_extra_isize());
866 					node_blk->i.i_extra_isize =
867 						cpu_to_le16(calc_extra_isize());
868 					need_fix = 1;
869 				}
870 			}
871 		} else {
872 			ASSERT_MSG("[0x%x] wrong extra_attr flag", nid);
873 			if (c.fix_on) {
874 				FIX_MSG("ino[0x%x] remove F2FS_EXTRA_ATTR "
875 					"flag in i_inline:%u",
876 					nid, node_blk->i.i_inline);
877 				/* we don't support tuning F2FS_FEATURE_EXTRA_ATTR now */
878 				node_blk->i.i_inline &= ~F2FS_EXTRA_ATTR;
879 				need_fix = 1;
880 			}
881 		}
882 
883 		if ((c.feature &
884 			cpu_to_le32(F2FS_FEATURE_FLEXIBLE_INLINE_XATTR)) &&
885 			(node_blk->i.i_inline & F2FS_INLINE_XATTR)) {
886 			unsigned int inline_size =
887 				le16_to_cpu(node_blk->i.i_inline_xattr_size);
888 
889 			if (!inline_size ||
890 					inline_size > MAX_INLINE_XATTR_SIZE) {
891 				ASSERT_MSG("[0x%x] wrong inline_xattr_size:%u",
892 						nid, inline_size);
893 				if (c.fix_on) {
894 					FIX_MSG("ino[0x%x] recover inline xattr size "
895 						"from %u to %u",
896 						nid, inline_size,
897 						DEFAULT_INLINE_XATTR_ADDRS);
898 					node_blk->i.i_inline_xattr_size =
899 						cpu_to_le16(DEFAULT_INLINE_XATTR_ADDRS);
900 					need_fix = 1;
901 				}
902 			}
903 		}
904 	}
905 	ofs = get_extra_isize(node_blk);
906 
907 	if ((node_blk->i.i_flags & cpu_to_le32(F2FS_CASEFOLD_FL)) &&
908 	    (ftype != F2FS_FT_DIR ||
909 	     !(c.feature & cpu_to_le32(F2FS_FEATURE_CASEFOLD)))) {
910 		ASSERT_MSG("[0x%x] unexpected casefold flag", nid);
911 		if (c.fix_on) {
912 			FIX_MSG("ino[0x%x] clear casefold flag", nid);
913 			node_blk->i.i_flags &= ~cpu_to_le32(F2FS_CASEFOLD_FL);
914 			need_fix = 1;
915 		}
916 	}
917 
918 	if (chk_extended_attributes(sbi, nid, node_blk))
919 		need_fix = 1;
920 
921 	if ((node_blk->i.i_inline & F2FS_INLINE_DATA)) {
922 		unsigned int inline_size = MAX_INLINE_DATA(node_blk);
923 		if (cur_qtype != -1)
924 			qf_szchk_type[cur_qtype] = QF_SZCHK_INLINE;
925 		block_t blkaddr = le32_to_cpu(node_blk->i.i_addr[ofs]);
926 
927 		if (blkaddr != 0) {
928 			ASSERT_MSG("[0x%x] wrong inline reserve blkaddr:%u",
929 					nid, blkaddr);
930 			if (c.fix_on) {
931 				FIX_MSG("inline_data has wrong 0'th block = %x",
932 								blkaddr);
933 				node_blk->i.i_addr[ofs] = 0;
934 				node_blk->i.i_blocks = cpu_to_le64(*blk_cnt);
935 				need_fix = 1;
936 			}
937 		}
938 		if (i_size > inline_size) {
939 			ASSERT_MSG("[0x%x] wrong inline size:%lu",
940 					nid, (unsigned long)i_size);
941 			if (c.fix_on) {
942 				node_blk->i.i_size = cpu_to_le64(inline_size);
943 				FIX_MSG("inline_data has wrong i_size %lu",
944 							(unsigned long)i_size);
945 				need_fix = 1;
946 			}
947 		}
948 		if (!(node_blk->i.i_inline & F2FS_DATA_EXIST)) {
949 			char buf[MAX_INLINE_DATA(node_blk)];
950 			memset(buf, 0, MAX_INLINE_DATA(node_blk));
951 
952 			if (memcmp(buf, inline_data_addr(node_blk),
953 						MAX_INLINE_DATA(node_blk))) {
954 				ASSERT_MSG("[0x%x] junk inline data", nid);
955 				if (c.fix_on) {
956 					FIX_MSG("inline_data has DATA_EXIST");
957 					node_blk->i.i_inline |= F2FS_DATA_EXIST;
958 					need_fix = 1;
959 				}
960 			}
961 		}
962 		DBG(3, "ino[0x%x] has inline data!\n", nid);
963 		child.state |= FSCK_INLINE_INODE;
964 		goto check;
965 	}
966 
967 	if ((node_blk->i.i_inline & F2FS_INLINE_DENTRY)) {
968 		block_t blkaddr = le32_to_cpu(node_blk->i.i_addr[ofs]);
969 
970 		DBG(3, "ino[0x%x] has inline dentry!\n", nid);
971 		if (blkaddr != 0) {
972 			ASSERT_MSG("[0x%x] wrong inline reserve blkaddr:%u",
973 								nid, blkaddr);
974 			if (c.fix_on) {
975 				FIX_MSG("inline_dentry has wrong 0'th block = %x",
976 								blkaddr);
977 				node_blk->i.i_addr[ofs] = 0;
978 				node_blk->i.i_blocks = cpu_to_le64(*blk_cnt);
979 				need_fix = 1;
980 			}
981 		}
982 
983 		ret = fsck_chk_inline_dentries(sbi, node_blk, &child);
984 		if (ret < 0) {
985 			if (c.fix_on)
986 				need_fix = 1;
987 		}
988 		child.state |= FSCK_INLINE_INODE;
989 		goto check;
990 	}
991 
992 	/* check data blocks in inode */
993 	addrs = ADDRS_PER_INODE(&node_blk->i);
994 	if (cur_qtype != -1) {
995 		u64 addrs_per_blk = (u64)ADDRS_PER_BLOCK(&node_blk->i);
996 		qf_szchk_type[cur_qtype] = QF_SZCHK_REGFILE;
997 		qf_maxsize[cur_qtype] = (u64)(addrs + 2 * addrs_per_blk +
998 				2 * addrs_per_blk * NIDS_PER_BLOCK +
999 				addrs_per_blk * NIDS_PER_BLOCK *
1000 				NIDS_PER_BLOCK) * F2FS_BLKSIZE;
1001 	}
1002 	for (idx = 0; idx < addrs; idx++, child.pgofs++) {
1003 		block_t blkaddr = le32_to_cpu(node_blk->i.i_addr[ofs + idx]);
1004 
1005 		/* check extent info */
1006 		check_extent_info(&child, blkaddr, 0);
1007 
1008 		if (blkaddr == NULL_ADDR)
1009 			continue;
1010 		if (blkaddr == COMPRESS_ADDR) {
1011 			if (!compressed || (child.pgofs &
1012 					(cluster_size - 1)) != 0) {
1013 				if (c.fix_on) {
1014 					node_blk->i.i_addr[ofs + idx] =
1015 							NULL_ADDR;
1016 					need_fix = 1;
1017 					FIX_MSG("[0x%x] i_addr[%d] = 0", nid,
1018 							ofs + idx);
1019 				}
1020 				continue;
1021 			}
1022 			if (!compr_rel) {
1023 				fsck->chk.valid_blk_cnt++;
1024 				*blk_cnt = *blk_cnt + 1;
1025 				cbc->cheader_pgofs = child.pgofs;
1026 				cbc->cnt++;
1027 			}
1028 			continue;
1029 		}
1030 		if (!compr_rel && blkaddr == NEW_ADDR &&
1031 				child.pgofs - cbc->cheader_pgofs < cluster_size)
1032 			cbc->cnt++;
1033 		ret = fsck_chk_data_blk(sbi,
1034 				IS_CASEFOLDED(&node_blk->i),
1035 				blkaddr,
1036 				&child, (i_blocks == *blk_cnt),
1037 				ftype, nid, idx, ni->version,
1038 				file_is_encrypt(&node_blk->i));
1039 		if (!ret) {
1040 			*blk_cnt = *blk_cnt + 1;
1041 			if (cur_qtype != -1 && blkaddr != NEW_ADDR)
1042 				qf_last_blkofs[cur_qtype] = child.pgofs;
1043 		} else if (c.fix_on) {
1044 			node_blk->i.i_addr[ofs + idx] = 0;
1045 			need_fix = 1;
1046 			FIX_MSG("[0x%x] i_addr[%d] = 0", nid, ofs + idx);
1047 		}
1048 	}
1049 
1050 	/* readahead node blocks */
1051 	for (idx = 0; idx < 5; idx++) {
1052 		u32 nid = le32_to_cpu(node_blk->i.i_nid[idx]);
1053 		fsck_reada_node_block(sbi, nid);
1054 	}
1055 
1056 	/* check node blocks in inode */
1057 	for (idx = 0; idx < 5; idx++) {
1058 		nid_t i_nid = le32_to_cpu(node_blk->i.i_nid[idx]);
1059 
1060 		if (idx == 0 || idx == 1)
1061 			ntype = TYPE_DIRECT_NODE;
1062 		else if (idx == 2 || idx == 3)
1063 			ntype = TYPE_INDIRECT_NODE;
1064 		else if (idx == 4)
1065 			ntype = TYPE_DOUBLE_INDIRECT_NODE;
1066 		else
1067 			ASSERT(0);
1068 
1069 		if (i_nid == 0x0)
1070 			goto skip;
1071 
1072 		ret = fsck_chk_node_blk(sbi, &node_blk->i, i_nid,
1073 				ftype, ntype, blk_cnt, cbc, &child);
1074 		if (!ret) {
1075 			*blk_cnt = *blk_cnt + 1;
1076 		} else if (ret == -EINVAL) {
1077 			if (c.fix_on) {
1078 				node_blk->i.i_nid[idx] = 0;
1079 				need_fix = 1;
1080 				FIX_MSG("[0x%x] i_nid[%d] = 0", nid, idx);
1081 			}
1082 skip:
1083 			if (ntype == TYPE_DIRECT_NODE)
1084 				child.pgofs += ADDRS_PER_BLOCK(&node_blk->i);
1085 			else if (ntype == TYPE_INDIRECT_NODE)
1086 				child.pgofs += ADDRS_PER_BLOCK(&node_blk->i) *
1087 								NIDS_PER_BLOCK;
1088 			else
1089 				child.pgofs += ADDRS_PER_BLOCK(&node_blk->i) *
1090 						NIDS_PER_BLOCK * NIDS_PER_BLOCK;
1091 		}
1092 
1093 	}
1094 
1095 check:
1096 	/* check uncovered range in the back of extent */
1097 	check_extent_info(&child, 0, 1);
1098 
1099 	if (child.state & FSCK_UNMATCHED_EXTENT) {
1100 		ASSERT_MSG("ino: 0x%x has wrong ext: [pgofs:%u, blk:%u, len:%u]",
1101 				nid, child.ei.fofs, child.ei.blk, child.ei.len);
1102 		if (c.fix_on)
1103 			need_fix = 1;
1104 	}
1105 
1106 	if (i_blocks != *blk_cnt) {
1107 		ASSERT_MSG("ino: 0x%x has i_blocks: %08"PRIx64", "
1108 				"but has %u blocks",
1109 				nid, i_blocks, *blk_cnt);
1110 		if (c.fix_on) {
1111 			node_blk->i.i_blocks = cpu_to_le64(*blk_cnt);
1112 			need_fix = 1;
1113 			FIX_MSG("[0x%x] i_blocks=0x%08"PRIx64" -> 0x%x",
1114 					nid, i_blocks, *blk_cnt);
1115 		}
1116 	}
1117 
1118 	if (compressed && i_compr_blocks != cbc->cnt) {
1119 		if (c.fix_on) {
1120 			node_blk->i.i_compr_blocks = cpu_to_le64(cbc->cnt);
1121 			need_fix = 1;
1122 			FIX_MSG("[0x%x] i_compr_blocks=0x%08"PRIx64" -> 0x%x",
1123 					nid, i_compr_blocks, cbc->cnt);
1124 		}
1125 	}
1126 
1127 skip_blkcnt_fix:
1128 	en = malloc(F2FS_PRINT_NAMELEN);
1129 	ASSERT(en);
1130 
1131 	namelen = le32_to_cpu(node_blk->i.i_namelen);
1132 	if (namelen > F2FS_NAME_LEN) {
1133 		if (child_d && child_d->i_namelen <= F2FS_NAME_LEN) {
1134 			ASSERT_MSG("ino: 0x%x has i_namelen: 0x%x, "
1135 					"but has %d characters for name",
1136 					nid, namelen, child_d->i_namelen);
1137 			if (c.fix_on) {
1138 				FIX_MSG("[0x%x] i_namelen=0x%x -> 0x%x", nid, namelen,
1139 					child_d->i_namelen);
1140 				node_blk->i.i_namelen = cpu_to_le32(child_d->i_namelen);
1141 				need_fix = 1;
1142 			}
1143 			namelen = child_d->i_namelen;
1144 		} else
1145 			namelen = F2FS_NAME_LEN;
1146 	}
1147 	pretty_print_filename(node_blk->i.i_name, namelen, en,
1148 			      file_enc_name(&node_blk->i));
1149 	if (ftype == F2FS_FT_ORPHAN)
1150 		DBG(1, "Orphan Inode: 0x%x [%s] i_blocks: %u\n\n",
1151 				le32_to_cpu(node_blk->footer.ino),
1152 				en, (u32)i_blocks);
1153 
1154 	if (is_qf_ino(F2FS_RAW_SUPER(sbi), nid))
1155 		DBG(1, "Quota Inode: 0x%x [%s] i_blocks: %u\n\n",
1156 				le32_to_cpu(node_blk->footer.ino),
1157 				en, (u32)i_blocks);
1158 
1159 	if (ftype == F2FS_FT_DIR) {
1160 		DBG(1, "Directory Inode: 0x%x [%s] depth: %d has %d files\n\n",
1161 				le32_to_cpu(node_blk->footer.ino), en,
1162 				le32_to_cpu(node_blk->i.i_current_depth),
1163 				child.files);
1164 
1165 		if (i_links != child.links) {
1166 			ASSERT_MSG("ino: 0x%x i_links: %u, real links: %u",
1167 					nid, i_links, child.links);
1168 			if (c.fix_on) {
1169 				node_blk->i.i_links = cpu_to_le32(child.links);
1170 				need_fix = 1;
1171 				FIX_MSG("Dir: 0x%x i_links= 0x%x -> 0x%x",
1172 						nid, i_links, child.links);
1173 			}
1174 		}
1175 		if (child.dots < 2 &&
1176 				!(node_blk->i.i_inline & F2FS_INLINE_DOTS)) {
1177 			ASSERT_MSG("ino: 0x%x dots: %u",
1178 					nid, child.dots);
1179 			if (c.fix_on) {
1180 				node_blk->i.i_inline |= F2FS_INLINE_DOTS;
1181 				need_fix = 1;
1182 				FIX_MSG("Dir: 0x%x set inline_dots", nid);
1183 			}
1184 		}
1185 	}
1186 
1187 	i_gc_failures = le16_to_cpu(node_blk->i.i_gc_failures);
1188 
1189 	/*
1190 	 * old kernel initialized i_gc_failures as 0x01, in preen mode 2,
1191 	 * let's skip repairing.
1192 	 */
1193 	if (ftype == F2FS_FT_REG_FILE && i_gc_failures &&
1194 		(c.preen_mode != PREEN_MODE_2 || i_gc_failures != 0x01)) {
1195 
1196 		DBG(1, "Regular Inode: 0x%x [%s] depth: %d\n\n",
1197 				le32_to_cpu(node_blk->footer.ino), en,
1198 				i_gc_failures);
1199 
1200 		if (c.fix_on) {
1201 			node_blk->i.i_gc_failures = cpu_to_le16(0);
1202 			need_fix = 1;
1203 			FIX_MSG("Regular: 0x%x reset i_gc_failures from 0x%x to 0x00",
1204 					nid, i_gc_failures);
1205 		}
1206 	}
1207 
1208 	free(en);
1209 
1210 	if (ftype == F2FS_FT_SYMLINK && i_size == 0 &&
1211 			i_blocks == (i_xattr_nid ? 3 : 2)) {
1212 		node_blk->i.i_size = cpu_to_le64(F2FS_BLKSIZE);
1213 		need_fix = 1;
1214 		FIX_MSG("Symlink: recover 0x%x with i_size=%lu",
1215 					nid, (unsigned long)F2FS_BLKSIZE);
1216 	}
1217 
1218 	if (ftype == F2FS_FT_ORPHAN && i_links) {
1219 		ASSERT_MSG("ino: 0x%x is orphan inode, but has i_links: %u",
1220 				nid, i_links);
1221 		if (c.fix_on) {
1222 			node_blk->i.i_links = 0;
1223 			need_fix = 1;
1224 			FIX_MSG("ino: 0x%x orphan_inode, i_links= 0x%x -> 0",
1225 					nid, i_links);
1226 		}
1227 	}
1228 
1229 	/* drop extent information to avoid potential wrong access */
1230 	if (need_fix && f2fs_dev_is_writable())
1231 		node_blk->i.i_ext.len = 0;
1232 
1233 	if ((c.feature & cpu_to_le32(F2FS_FEATURE_INODE_CHKSUM)) &&
1234 				f2fs_has_extra_isize(&node_blk->i)) {
1235 		__u32 provided, calculated;
1236 
1237 		provided = le32_to_cpu(node_blk->i.i_inode_checksum);
1238 		calculated = f2fs_inode_chksum(node_blk);
1239 
1240 		if (provided != calculated) {
1241 			ASSERT_MSG("ino: 0x%x chksum:0x%x, but calculated one is: 0x%x",
1242 				nid, provided, calculated);
1243 			if (c.fix_on) {
1244 				node_blk->i.i_inode_checksum =
1245 							cpu_to_le32(calculated);
1246 				need_fix = 1;
1247 				FIX_MSG("ino: 0x%x recover, i_inode_checksum= 0x%x -> 0x%x",
1248 						nid, provided, calculated);
1249 			}
1250 		}
1251 	}
1252 
1253 	if (need_fix && f2fs_dev_is_writable()) {
1254 		ret = dev_write_block(node_blk, ni->blk_addr);
1255 		ASSERT(ret >= 0);
1256 	}
1257 }
1258 
fsck_chk_dnode_blk(struct f2fs_sb_info * sbi,struct f2fs_inode * inode,u32 nid,enum FILE_TYPE ftype,struct f2fs_node * node_blk,u32 * blk_cnt,struct f2fs_compr_blk_cnt * cbc,struct child_info * child,struct node_info * ni)1259 int fsck_chk_dnode_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode,
1260 		u32 nid, enum FILE_TYPE ftype, struct f2fs_node *node_blk,
1261 		u32 *blk_cnt, struct f2fs_compr_blk_cnt *cbc,
1262 		struct child_info *child, struct node_info *ni)
1263 {
1264 	int idx, ret;
1265 	int need_fix = 0;
1266 	child->p_ino = nid;
1267 	child->pp_ino = le32_to_cpu(inode->i_pino);
1268 	u32 i_flags = le32_to_cpu(inode->i_flags);
1269 	bool compressed = i_flags & F2FS_COMPR_FL;
1270 	bool compr_rel = inode->i_inline & F2FS_COMPRESS_RELEASED;
1271 	u32 cluster_size = 1 << inode->i_log_cluster_size;
1272 
1273 	for (idx = 0; idx < ADDRS_PER_BLOCK(inode); idx++, child->pgofs++) {
1274 		block_t blkaddr = le32_to_cpu(node_blk->dn.addr[idx]);
1275 
1276 		check_extent_info(child, blkaddr, 0);
1277 
1278 		if (blkaddr == NULL_ADDR)
1279 			continue;
1280 		if (blkaddr == COMPRESS_ADDR) {
1281 			if (!compressed || (child->pgofs &
1282 					(cluster_size - 1)) != 0) {
1283 				if (c.fix_on) {
1284 					node_blk->dn.addr[idx] = NULL_ADDR;
1285 					need_fix = 1;
1286 					FIX_MSG("[0x%x] dn.addr[%d] = 0", nid,
1287 							idx);
1288 				}
1289 				continue;
1290 			}
1291 			if (!compr_rel) {
1292 				F2FS_FSCK(sbi)->chk.valid_blk_cnt++;
1293 				*blk_cnt = *blk_cnt + 1;
1294 				cbc->cheader_pgofs = child->pgofs;
1295 				cbc->cnt++;
1296 			}
1297 			continue;
1298 		}
1299 		if (!compr_rel && blkaddr == NEW_ADDR && child->pgofs -
1300 				cbc->cheader_pgofs < cluster_size)
1301 			cbc->cnt++;
1302 		ret = fsck_chk_data_blk(sbi, IS_CASEFOLDED(inode),
1303 			blkaddr, child,
1304 			le64_to_cpu(inode->i_blocks) == *blk_cnt, ftype,
1305 			nid, idx, ni->version,
1306 			file_is_encrypt(inode));
1307 		if (!ret) {
1308 			*blk_cnt = *blk_cnt + 1;
1309 			if (cur_qtype != -1 && blkaddr != NEW_ADDR)
1310 				qf_last_blkofs[cur_qtype] = child->pgofs;
1311 		} else if (c.fix_on) {
1312 			node_blk->dn.addr[idx] = NULL_ADDR;
1313 			need_fix = 1;
1314 			FIX_MSG("[0x%x] dn.addr[%d] = 0", nid, idx);
1315 		}
1316 	}
1317 	if (need_fix && f2fs_dev_is_writable()) {
1318 		ret = dev_write_block(node_blk, ni->blk_addr);
1319 		ASSERT(ret >= 0);
1320 	}
1321 	return 0;
1322 }
1323 
fsck_chk_idnode_blk(struct f2fs_sb_info * sbi,struct f2fs_inode * inode,enum FILE_TYPE ftype,struct f2fs_node * node_blk,u32 * blk_cnt,struct f2fs_compr_blk_cnt * cbc,struct child_info * child)1324 int fsck_chk_idnode_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode,
1325 		enum FILE_TYPE ftype, struct f2fs_node *node_blk, u32 *blk_cnt,
1326 		struct f2fs_compr_blk_cnt *cbc, struct child_info *child)
1327 {
1328 	int need_fix = 0, ret;
1329 	int i = 0;
1330 
1331 	fsck_reada_all_direct_node_blocks(sbi, node_blk);
1332 
1333 	for (i = 0; i < NIDS_PER_BLOCK; i++) {
1334 		if (le32_to_cpu(node_blk->in.nid[i]) == 0x0)
1335 			goto skip;
1336 		ret = fsck_chk_node_blk(sbi, inode,
1337 				le32_to_cpu(node_blk->in.nid[i]),
1338 				ftype, TYPE_DIRECT_NODE, blk_cnt,
1339 				cbc, child);
1340 		if (!ret)
1341 			*blk_cnt = *blk_cnt + 1;
1342 		else if (ret == -EINVAL) {
1343 			if (!c.fix_on)
1344 				printf("should delete in.nid[i] = 0;\n");
1345 			else {
1346 				node_blk->in.nid[i] = 0;
1347 				need_fix = 1;
1348 				FIX_MSG("Set indirect node 0x%x -> 0", i);
1349 			}
1350 skip:
1351 			child->pgofs += ADDRS_PER_BLOCK(&node_blk->i);
1352 		}
1353 	}
1354 
1355 	if (need_fix && f2fs_dev_is_writable()) {
1356 		struct node_info ni;
1357 		nid_t nid = le32_to_cpu(node_blk->footer.nid);
1358 
1359 		get_node_info(sbi, nid, &ni);
1360 		ret = dev_write_block(node_blk, ni.blk_addr);
1361 		ASSERT(ret >= 0);
1362 	}
1363 
1364 	return 0;
1365 }
1366 
fsck_chk_didnode_blk(struct f2fs_sb_info * sbi,struct f2fs_inode * inode,enum FILE_TYPE ftype,struct f2fs_node * node_blk,u32 * blk_cnt,struct f2fs_compr_blk_cnt * cbc,struct child_info * child)1367 int fsck_chk_didnode_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode,
1368 		enum FILE_TYPE ftype, struct f2fs_node *node_blk, u32 *blk_cnt,
1369 		struct f2fs_compr_blk_cnt *cbc, struct child_info *child)
1370 {
1371 	int i = 0;
1372 	int need_fix = 0, ret = 0;
1373 
1374 	fsck_reada_all_direct_node_blocks(sbi, node_blk);
1375 
1376 	for (i = 0; i < NIDS_PER_BLOCK; i++) {
1377 		if (le32_to_cpu(node_blk->in.nid[i]) == 0x0)
1378 			goto skip;
1379 		ret = fsck_chk_node_blk(sbi, inode,
1380 				le32_to_cpu(node_blk->in.nid[i]),
1381 				ftype, TYPE_INDIRECT_NODE, blk_cnt, cbc, child);
1382 		if (!ret)
1383 			*blk_cnt = *blk_cnt + 1;
1384 		else if (ret == -EINVAL) {
1385 			if (!c.fix_on)
1386 				printf("should delete in.nid[i] = 0;\n");
1387 			else {
1388 				node_blk->in.nid[i] = 0;
1389 				need_fix = 1;
1390 				FIX_MSG("Set double indirect node 0x%x -> 0", i);
1391 			}
1392 skip:
1393 			child->pgofs += ADDRS_PER_BLOCK(&node_blk->i) *
1394 							NIDS_PER_BLOCK;
1395 		}
1396 	}
1397 
1398 	if (need_fix && f2fs_dev_is_writable()) {
1399 		struct node_info ni;
1400 		nid_t nid = le32_to_cpu(node_blk->footer.nid);
1401 
1402 		get_node_info(sbi, nid, &ni);
1403 		ret = dev_write_block(node_blk, ni.blk_addr);
1404 		ASSERT(ret >= 0);
1405 	}
1406 
1407 	return 0;
1408 }
1409 
1410 static const char *lookup_table =
1411         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
1412 
1413 /**
1414  * base64_encode() -
1415  *
1416  * Encodes the input string using characters from the set [A-Za-z0-9+,].
1417  * The encoded string is roughly 4/3 times the size of the input string.
1418  */
base64_encode(const u8 * src,int len,char * dst)1419 static int base64_encode(const u8 *src, int len, char *dst)
1420 {
1421 	int i, bits = 0, ac = 0;
1422 	char *cp = dst;
1423 
1424 	for (i = 0; i < len; i++) {
1425 		ac += src[i] << bits;
1426 		bits += 8;
1427 		do {
1428 			*cp++ = lookup_table[ac & 0x3f];
1429 			ac >>= 6;
1430 			bits -= 6;
1431 		} while (bits >= 6);
1432 	}
1433 	if (bits)
1434 		*cp++ = lookup_table[ac & 0x3f];
1435 	return cp - dst;
1436 }
1437 
pretty_print_filename(const u8 * raw_name,u32 len,char out[F2FS_PRINT_NAMELEN],int enc_name)1438 void pretty_print_filename(const u8 *raw_name, u32 len,
1439 			   char out[F2FS_PRINT_NAMELEN], int enc_name)
1440 {
1441 	len = min(len, (u32)F2FS_NAME_LEN);
1442 
1443 	if (enc_name)
1444 		len = base64_encode(raw_name, len, out);
1445 	else
1446 		memcpy(out, raw_name, len);
1447 	out[len] = 0;
1448 }
1449 
print_dentry(struct f2fs_sb_info * sbi,__u8 * name,u8 * bitmap,struct f2fs_dir_entry * dentry,int max,int idx,int last_blk,int enc_name)1450 static void print_dentry(struct f2fs_sb_info *sbi, __u8 *name,
1451 		u8 *bitmap, struct f2fs_dir_entry *dentry,
1452 		int max, int idx, int last_blk, int enc_name)
1453 {
1454 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
1455 	u32 depth = fsck->dentry_depth;
1456 	int last_de = 0;
1457 	int next_idx = 0;
1458 	u32 name_len;
1459 	unsigned int i;
1460 	int bit_offset;
1461 	char new[F2FS_PRINT_NAMELEN];
1462 
1463 	if (!c.show_dentry && !c.show_file_map)
1464 		return;
1465 
1466 	name_len = le16_to_cpu(dentry[idx].name_len);
1467 	next_idx = idx + (name_len + F2FS_SLOT_LEN - 1) / F2FS_SLOT_LEN;
1468 
1469 	bit_offset = find_next_bit_le(bitmap, max, next_idx);
1470 	if (bit_offset >= max && last_blk)
1471 		last_de = 1;
1472 
1473 	if (tree_mark_size <= depth) {
1474 		tree_mark_size *= 2;
1475 		ASSERT(tree_mark_size != 0);
1476 		tree_mark = realloc(tree_mark, tree_mark_size);
1477 		ASSERT(tree_mark != NULL);
1478 	}
1479 
1480 	if (last_de)
1481 		tree_mark[depth] = '`';
1482 	else
1483 		tree_mark[depth] = '|';
1484 
1485 	if (tree_mark[depth - 1] == '`')
1486 		tree_mark[depth - 1] = ' ';
1487 
1488 	pretty_print_filename(name, name_len, new, enc_name);
1489 
1490 	if (c.show_file_map) {
1491 		struct f2fs_dentry *d = fsck->dentry;
1492 
1493 		if (dentry[idx].file_type != F2FS_FT_REG_FILE)
1494 			return;
1495 
1496 		while (d) {
1497 			if (d->depth > 1)
1498 				printf("/%s", d->name);
1499 			d = d->next;
1500 		}
1501 		printf("/%s", new);
1502 		if (dump_node(sbi, le32_to_cpu(dentry[idx].ino), 0))
1503 			printf("\33[2K\r");
1504 	} else {
1505 		for (i = 1; i < depth; i++)
1506 			printf("%c   ", tree_mark[i]);
1507 
1508 		printf("%c-- %s <ino = 0x%x>, <encrypted (%d)>\n",
1509 			last_de ? '`' : '|',
1510 			new, le32_to_cpu(dentry[idx].ino),
1511 			enc_name);
1512 	}
1513 }
1514 
f2fs_check_hash_code(int encoding,int casefolded,struct f2fs_dir_entry * dentry,const unsigned char * name,u32 len,int enc_name)1515 static int f2fs_check_hash_code(int encoding, int casefolded,
1516 			struct f2fs_dir_entry *dentry,
1517 			const unsigned char *name, u32 len, int enc_name)
1518 {
1519 	/* Casefolded Encrypted names require a key to compute siphash */
1520 	if (enc_name && casefolded)
1521 		return 0;
1522 
1523 	f2fs_hash_t hash_code = f2fs_dentry_hash(encoding, casefolded, name, len);
1524 	/* fix hash_code made by old buggy code */
1525 	if (dentry->hash_code != hash_code) {
1526 		char new[F2FS_PRINT_NAMELEN];
1527 
1528 		pretty_print_filename(name, len, new, enc_name);
1529 		FIX_MSG("Mismatch hash_code for \"%s\" [%x:%x]",
1530 				new, le32_to_cpu(dentry->hash_code),
1531 				hash_code);
1532 		dentry->hash_code = cpu_to_le32(hash_code);
1533 		return 1;
1534 	}
1535 	return 0;
1536 }
1537 
1538 
__get_current_level(int dir_level,u32 pgofs)1539 static int __get_current_level(int dir_level, u32 pgofs)
1540 {
1541 	unsigned int bidx = 0;
1542 	int i;
1543 
1544 	for (i = 0; i < MAX_DIR_HASH_DEPTH; i++) {
1545 		bidx += dir_buckets(i, dir_level) * bucket_blocks(i);
1546 		if (bidx > pgofs)
1547 			break;
1548 	}
1549 	return i;
1550 }
1551 
f2fs_check_dirent_position(const struct f2fs_dir_entry * dentry,const char * printable_name,u32 pgofs,u8 dir_level,u32 pino)1552 static int f2fs_check_dirent_position(const struct f2fs_dir_entry *dentry,
1553 				      const char *printable_name,
1554 				      u32 pgofs, u8 dir_level, u32 pino)
1555 {
1556 	unsigned int nbucket, nblock;
1557 	unsigned int bidx, end_block;
1558 	int level;
1559 
1560 	level = __get_current_level(dir_level, pgofs);
1561 
1562 	nbucket = dir_buckets(level, dir_level);
1563 	nblock = bucket_blocks(level);
1564 
1565 	bidx = dir_block_index(level, dir_level,
1566 			       le32_to_cpu(dentry->hash_code) % nbucket);
1567 	end_block = bidx + nblock;
1568 
1569 	if (pgofs >= bidx && pgofs < end_block)
1570 		return 0;
1571 
1572 	ASSERT_MSG("Wrong position of dirent pino:%u, name:%s, level:%d, "
1573 		"dir_level:%d, pgofs:%u, correct range:[%u, %u]\n",
1574 		pino, printable_name, level, dir_level, pgofs, bidx,
1575 		end_block - 1);
1576 	return 1;
1577 }
1578 
__chk_dots_dentries(struct f2fs_sb_info * sbi,int casefolded,struct f2fs_dir_entry * dentry,struct child_info * child,u8 * name,int len,__u8 (* filename)[F2FS_SLOT_LEN],int enc_name)1579 static int __chk_dots_dentries(struct f2fs_sb_info *sbi,
1580 			       int casefolded,
1581 			       struct f2fs_dir_entry *dentry,
1582 			       struct child_info *child,
1583 			       u8 *name, int len,
1584 			       __u8 (*filename)[F2FS_SLOT_LEN],
1585 			       int enc_name)
1586 {
1587 	int fixed = 0;
1588 
1589 	if ((name[0] == '.' && len == 1)) {
1590 		if (le32_to_cpu(dentry->ino) != child->p_ino) {
1591 			ASSERT_MSG("Bad inode number[0x%x] for '.', parent_ino is [0x%x]\n",
1592 				le32_to_cpu(dentry->ino), child->p_ino);
1593 			dentry->ino = cpu_to_le32(child->p_ino);
1594 			fixed = 1;
1595 		}
1596 	}
1597 
1598 	if (name[0] == '.' && name[1] == '.' && len == 2) {
1599 		if (child->p_ino == F2FS_ROOT_INO(sbi)) {
1600 			if (le32_to_cpu(dentry->ino) != F2FS_ROOT_INO(sbi)) {
1601 				ASSERT_MSG("Bad inode number[0x%x] for '..'\n",
1602 					le32_to_cpu(dentry->ino));
1603 				dentry->ino = cpu_to_le32(F2FS_ROOT_INO(sbi));
1604 				fixed = 1;
1605 			}
1606 		} else if (le32_to_cpu(dentry->ino) != child->pp_ino) {
1607 			ASSERT_MSG("Bad inode number[0x%x] for '..', parent parent ino is [0x%x]\n",
1608 				le32_to_cpu(dentry->ino), child->pp_ino);
1609 			dentry->ino = cpu_to_le32(child->pp_ino);
1610 			fixed = 1;
1611 		}
1612 	}
1613 
1614 	if (f2fs_check_hash_code(get_encoding(sbi), casefolded, dentry, name, len, enc_name))
1615 		fixed = 1;
1616 
1617 	if (name[len] != '\0') {
1618 		ASSERT_MSG("'.' is not NULL terminated\n");
1619 		name[len] = '\0';
1620 		memcpy(*filename, name, len);
1621 		fixed = 1;
1622 	}
1623 	return fixed;
1624 }
1625 
nullify_dentry(struct f2fs_dir_entry * dentry,int offs,__u8 (* filename)[F2FS_SLOT_LEN],u8 ** bitmap)1626 static void nullify_dentry(struct f2fs_dir_entry *dentry, int offs,
1627 			   __u8 (*filename)[F2FS_SLOT_LEN], u8 **bitmap)
1628 {
1629 	memset(dentry, 0, sizeof(struct f2fs_dir_entry));
1630 	test_and_clear_bit_le(offs, *bitmap);
1631 	memset(*filename, 0, F2FS_SLOT_LEN);
1632 }
1633 
__chk_dentries(struct f2fs_sb_info * sbi,int casefolded,struct child_info * child,u8 * bitmap,struct f2fs_dir_entry * dentry,__u8 (* filenames)[F2FS_SLOT_LEN],int max,int last_blk,int enc_name)1634 static int __chk_dentries(struct f2fs_sb_info *sbi, int casefolded,
1635 			struct child_info *child,
1636 			u8 *bitmap, struct f2fs_dir_entry *dentry,
1637 			__u8 (*filenames)[F2FS_SLOT_LEN],
1638 			int max, int last_blk, int enc_name)
1639 {
1640 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
1641 	enum FILE_TYPE ftype;
1642 	int dentries = 0;
1643 	u32 blk_cnt;
1644 	struct f2fs_compr_blk_cnt cbc;
1645 	u8 *name;
1646 	char en[F2FS_PRINT_NAMELEN];
1647 	u16 name_len;
1648 	int ret = 0;
1649 	int fixed = 0;
1650 	int i, slots;
1651 
1652 	/* readahead inode blocks */
1653 	for (i = 0; i < max; i++) {
1654 		u32 ino;
1655 
1656 		if (test_bit_le(i, bitmap) == 0)
1657 			continue;
1658 
1659 		ino = le32_to_cpu(dentry[i].ino);
1660 
1661 		if (IS_VALID_NID(sbi, ino)) {
1662 			struct node_info ni;
1663 
1664 			get_node_info(sbi, ino, &ni);
1665 			if (IS_VALID_BLK_ADDR(sbi, ni.blk_addr)) {
1666 				dev_reada_block(ni.blk_addr);
1667 				name_len = le16_to_cpu(dentry[i].name_len);
1668 				if (name_len > 0)
1669 					i += (name_len + F2FS_SLOT_LEN - 1) / F2FS_SLOT_LEN - 1;
1670 			}
1671 		}
1672 	}
1673 
1674 	for (i = 0; i < max;) {
1675 		if (test_bit_le(i, bitmap) == 0) {
1676 			i++;
1677 			continue;
1678 		}
1679 		if (!IS_VALID_NID(sbi, le32_to_cpu(dentry[i].ino))) {
1680 			ASSERT_MSG("Bad dentry 0x%x with invalid NID/ino 0x%x",
1681 				    i, le32_to_cpu(dentry[i].ino));
1682 			if (c.fix_on) {
1683 				FIX_MSG("Clear bad dentry 0x%x with bad ino 0x%x",
1684 					i, le32_to_cpu(dentry[i].ino));
1685 				test_and_clear_bit_le(i, bitmap);
1686 				fixed = 1;
1687 			}
1688 			i++;
1689 			continue;
1690 		}
1691 
1692 		ftype = dentry[i].file_type;
1693 		if ((ftype <= F2FS_FT_UNKNOWN || ftype > F2FS_FT_LAST_FILE_TYPE)) {
1694 			ASSERT_MSG("Bad dentry 0x%x with unexpected ftype 0x%x",
1695 						le32_to_cpu(dentry[i].ino), ftype);
1696 			if (c.fix_on) {
1697 				FIX_MSG("Clear bad dentry 0x%x with bad ftype 0x%x",
1698 					i, ftype);
1699 				test_and_clear_bit_le(i, bitmap);
1700 				fixed = 1;
1701 			}
1702 			i++;
1703 			continue;
1704 		}
1705 
1706 		name_len = le16_to_cpu(dentry[i].name_len);
1707 
1708 		if (name_len == 0 || name_len > F2FS_NAME_LEN) {
1709 			ASSERT_MSG("Bad dentry 0x%x with invalid name_len", i);
1710 			if (c.fix_on) {
1711 				FIX_MSG("Clear bad dentry 0x%x", i);
1712 				test_and_clear_bit_le(i, bitmap);
1713 				fixed = 1;
1714 			}
1715 			i++;
1716 			continue;
1717 		}
1718 		name = calloc(name_len + 1, 1);
1719 		ASSERT(name);
1720 
1721 		memcpy(name, filenames[i], name_len);
1722 		slots = (name_len + F2FS_SLOT_LEN - 1) / F2FS_SLOT_LEN;
1723 
1724 		/* Becareful. 'dentry.file_type' is not imode. */
1725 		if (ftype == F2FS_FT_DIR) {
1726 			if ((name[0] == '.' && name_len == 1) ||
1727 				(name[0] == '.' && name[1] == '.' &&
1728 							name_len == 2)) {
1729 				ret = __chk_dots_dentries(sbi, casefolded, &dentry[i],
1730 					child, name, name_len, &filenames[i],
1731 					enc_name);
1732 				switch (ret) {
1733 				case 1:
1734 					fixed = 1;
1735 					fallthrough;
1736 				case 0:
1737 					child->dots++;
1738 					break;
1739 				}
1740 
1741 				if (child->dots > 2) {
1742 					ASSERT_MSG("More than one '.' or '..', should delete the extra one\n");
1743 					nullify_dentry(&dentry[i], i,
1744 						       &filenames[i], &bitmap);
1745 					child->dots--;
1746 					fixed = 1;
1747 				}
1748 
1749 				i++;
1750 				free(name);
1751 				continue;
1752 			}
1753 		}
1754 
1755 		if (f2fs_check_hash_code(get_encoding(sbi), casefolded, dentry + i, name, name_len, enc_name))
1756 			fixed = 1;
1757 
1758 		pretty_print_filename(name, name_len, en, enc_name);
1759 
1760 		if (max == NR_DENTRY_IN_BLOCK) {
1761 			ret = f2fs_check_dirent_position(dentry + i, en,
1762 					child->pgofs, child->dir_level,
1763 					child->p_ino);
1764 			if (ret) {
1765 				if (c.fix_on) {
1766 					FIX_MSG("Clear bad dentry 0x%x", i);
1767 					test_and_clear_bit_le(i, bitmap);
1768 					fixed = 1;
1769 				}
1770 				i++;
1771 				free(name);
1772 				continue;
1773 			}
1774 		}
1775 
1776 		DBG(1, "[%3u]-[0x%x] name[%s] len[0x%x] ino[0x%x] type[0x%x]\n",
1777 				fsck->dentry_depth, i, en, name_len,
1778 				le32_to_cpu(dentry[i].ino),
1779 				dentry[i].file_type);
1780 
1781 		print_dentry(sbi, name, bitmap,
1782 				dentry, max, i, last_blk, enc_name);
1783 
1784 		blk_cnt = 1;
1785 		cbc.cnt = 0;
1786 		cbc.cheader_pgofs = CHEADER_PGOFS_NONE;
1787 		child->i_namelen = name_len;
1788 		ret = fsck_chk_node_blk(sbi,
1789 				NULL, le32_to_cpu(dentry[i].ino),
1790 				ftype, TYPE_INODE, &blk_cnt, &cbc, child);
1791 
1792 		if (ret && c.fix_on) {
1793 			int j;
1794 
1795 			for (j = 0; j < slots; j++)
1796 				test_and_clear_bit_le(i + j, bitmap);
1797 			FIX_MSG("Unlink [0x%x] - %s len[0x%x], type[0x%x]",
1798 					le32_to_cpu(dentry[i].ino),
1799 					en, name_len,
1800 					dentry[i].file_type);
1801 			fixed = 1;
1802 		} else if (ret == 0) {
1803 			if (ftype == F2FS_FT_DIR)
1804 				child->links++;
1805 			dentries++;
1806 			child->files++;
1807 		}
1808 
1809 		i += slots;
1810 		free(name);
1811 	}
1812 	return fixed ? -1 : dentries;
1813 }
1814 
fsck_chk_inline_dentries(struct f2fs_sb_info * sbi,struct f2fs_node * node_blk,struct child_info * child)1815 int fsck_chk_inline_dentries(struct f2fs_sb_info *sbi,
1816 		struct f2fs_node *node_blk, struct child_info *child)
1817 {
1818 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
1819 	struct f2fs_dentry *cur_dentry = fsck->dentry_end;
1820 	struct f2fs_dentry *new_dentry;
1821 	struct f2fs_dentry_ptr d;
1822 	void *inline_dentry;
1823 	int dentries;
1824 
1825 	inline_dentry = inline_data_addr(node_blk);
1826 	ASSERT(inline_dentry != NULL);
1827 
1828 	make_dentry_ptr(&d, node_blk, inline_dentry, 2);
1829 
1830 	fsck->dentry_depth++;
1831 	new_dentry = calloc(sizeof(struct f2fs_dentry), 1);
1832 	ASSERT(new_dentry != NULL);
1833 
1834 	new_dentry->depth = fsck->dentry_depth;
1835 	memcpy(new_dentry->name, child->p_name, F2FS_NAME_LEN);
1836 	cur_dentry->next = new_dentry;
1837 	fsck->dentry_end = new_dentry;
1838 
1839 	dentries = __chk_dentries(sbi, IS_CASEFOLDED(&node_blk->i), child,
1840 			d.bitmap, d.dentry, d.filename, d.max, 1,
1841 			file_is_encrypt(&node_blk->i));// pass through
1842 	if (dentries < 0) {
1843 		DBG(1, "[%3d] Inline Dentry Block Fixed hash_codes\n\n",
1844 			fsck->dentry_depth);
1845 	} else {
1846 		DBG(1, "[%3d] Inline Dentry Block Done : "
1847 				"dentries:%d in %d slots (len:%d)\n\n",
1848 			fsck->dentry_depth, dentries,
1849 			d.max, F2FS_NAME_LEN);
1850 	}
1851 	fsck->dentry = cur_dentry;
1852 	fsck->dentry_end = cur_dentry;
1853 	cur_dentry->next = NULL;
1854 	free(new_dentry);
1855 	fsck->dentry_depth--;
1856 	return dentries;
1857 }
1858 
fsck_chk_dentry_blk(struct f2fs_sb_info * sbi,int casefolded,u32 blk_addr,struct child_info * child,int last_blk,int enc_name)1859 int fsck_chk_dentry_blk(struct f2fs_sb_info *sbi, int casefolded, u32 blk_addr,
1860 		struct child_info *child, int last_blk, int enc_name)
1861 {
1862 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
1863 	struct f2fs_dentry_block *de_blk;
1864 	struct f2fs_dentry *cur_dentry = fsck->dentry_end;
1865 	struct f2fs_dentry *new_dentry;
1866 	int dentries, ret;
1867 
1868 	de_blk = (struct f2fs_dentry_block *)calloc(BLOCK_SZ, 1);
1869 	ASSERT(de_blk != NULL);
1870 
1871 	ret = dev_read_block(de_blk, blk_addr);
1872 	ASSERT(ret >= 0);
1873 
1874 	fsck->dentry_depth++;
1875 	new_dentry = calloc(sizeof(struct f2fs_dentry), 1);
1876 	ASSERT(new_dentry != NULL);
1877 	new_dentry->depth = fsck->dentry_depth;
1878 	memcpy(new_dentry->name, child->p_name, F2FS_NAME_LEN);
1879 	cur_dentry->next = new_dentry;
1880 	fsck->dentry_end = new_dentry;
1881 
1882 	dentries = __chk_dentries(sbi, casefolded, child,
1883 			de_blk->dentry_bitmap,
1884 			de_blk->dentry, de_blk->filename,
1885 			NR_DENTRY_IN_BLOCK, last_blk, enc_name);
1886 
1887 	if (dentries < 0 && f2fs_dev_is_writable()) {
1888 		ret = dev_write_block(de_blk, blk_addr);
1889 		ASSERT(ret >= 0);
1890 		DBG(1, "[%3d] Dentry Block [0x%x] Fixed hash_codes\n\n",
1891 			fsck->dentry_depth, blk_addr);
1892 	} else {
1893 		DBG(1, "[%3d] Dentry Block [0x%x] Done : "
1894 				"dentries:%d in %d slots (len:%d)\n\n",
1895 			fsck->dentry_depth, blk_addr, dentries,
1896 			NR_DENTRY_IN_BLOCK, F2FS_NAME_LEN);
1897 	}
1898 	fsck->dentry = cur_dentry;
1899 	fsck->dentry_end = cur_dentry;
1900 	cur_dentry->next = NULL;
1901 	free(new_dentry);
1902 	fsck->dentry_depth--;
1903 	free(de_blk);
1904 	return 0;
1905 }
1906 
fsck_chk_data_blk(struct f2fs_sb_info * sbi,int casefolded,u32 blk_addr,struct child_info * child,int last_blk,enum FILE_TYPE ftype,u32 parent_nid,u16 idx_in_node,u8 ver,int enc_name)1907 int fsck_chk_data_blk(struct f2fs_sb_info *sbi, int casefolded,
1908 		u32 blk_addr, struct child_info *child, int last_blk,
1909 		enum FILE_TYPE ftype, u32 parent_nid, u16 idx_in_node, u8 ver,
1910 		int enc_name)
1911 {
1912 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
1913 
1914 	/* Is it reserved block? */
1915 	if (blk_addr == NEW_ADDR) {
1916 		fsck->chk.valid_blk_cnt++;
1917 		return 0;
1918 	}
1919 
1920 	if (!IS_VALID_BLK_ADDR(sbi, blk_addr)) {
1921 		ASSERT_MSG("blkaddress is not valid. [0x%x]", blk_addr);
1922 		return -EINVAL;
1923 	}
1924 
1925 	if (is_valid_ssa_data_blk(sbi, blk_addr, parent_nid,
1926 						idx_in_node, ver)) {
1927 		ASSERT_MSG("summary data block is not valid. [0x%x]",
1928 						parent_nid);
1929 		return -EINVAL;
1930 	}
1931 
1932 	if (f2fs_test_sit_bitmap(sbi, blk_addr) == 0)
1933 		ASSERT_MSG("SIT bitmap is 0x0. blk_addr[0x%x]", blk_addr);
1934 
1935 	if (f2fs_test_main_bitmap(sbi, blk_addr) != 0)
1936 		ASSERT_MSG("Duplicated data [0x%x]. pnid[0x%x] idx[0x%x]",
1937 				blk_addr, parent_nid, idx_in_node);
1938 
1939 	fsck->chk.valid_blk_cnt++;
1940 
1941 	if (ftype == F2FS_FT_DIR) {
1942 		f2fs_set_main_bitmap(sbi, blk_addr, CURSEG_HOT_DATA);
1943 		return fsck_chk_dentry_blk(sbi, casefolded, blk_addr, child,
1944 						last_blk, enc_name);
1945 	} else {
1946 		f2fs_set_main_bitmap(sbi, blk_addr, CURSEG_WARM_DATA);
1947 	}
1948 	return 0;
1949 }
1950 
fsck_chk_orphan_node(struct f2fs_sb_info * sbi)1951 int fsck_chk_orphan_node(struct f2fs_sb_info *sbi)
1952 {
1953 	u32 blk_cnt = 0;
1954 	struct f2fs_compr_blk_cnt cbc = {0, CHEADER_PGOFS_NONE};
1955 	block_t start_blk, orphan_blkaddr, i, j;
1956 	struct f2fs_orphan_block *orphan_blk, *new_blk;
1957 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
1958 	u32 entry_count;
1959 
1960 	if (!is_set_ckpt_flags(F2FS_CKPT(sbi), CP_ORPHAN_PRESENT_FLAG))
1961 		return 0;
1962 
1963 	start_blk = __start_cp_addr(sbi) + 1 + get_sb(cp_payload);
1964 	orphan_blkaddr = __start_sum_addr(sbi) - 1 - get_sb(cp_payload);
1965 
1966 	f2fs_ra_meta_pages(sbi, start_blk, orphan_blkaddr, META_CP);
1967 
1968 	orphan_blk = calloc(BLOCK_SZ, 1);
1969 	ASSERT(orphan_blk);
1970 
1971 	new_blk = calloc(BLOCK_SZ, 1);
1972 	ASSERT(new_blk);
1973 
1974 	for (i = 0; i < orphan_blkaddr; i++) {
1975 		int ret = dev_read_block(orphan_blk, start_blk + i);
1976 		u32 new_entry_count = 0;
1977 
1978 		ASSERT(ret >= 0);
1979 		entry_count = le32_to_cpu(orphan_blk->entry_count);
1980 
1981 		for (j = 0; j < entry_count; j++) {
1982 			nid_t ino = le32_to_cpu(orphan_blk->ino[j]);
1983 			DBG(1, "[%3d] ino [0x%x]\n", i, ino);
1984 			struct node_info ni;
1985 			blk_cnt = 1;
1986 			cbc.cnt = 0;
1987 			cbc.cheader_pgofs = CHEADER_PGOFS_NONE;
1988 
1989 			if (c.preen_mode == PREEN_MODE_1 && !c.fix_on) {
1990 				get_node_info(sbi, ino, &ni);
1991 				if (!IS_VALID_NID(sbi, ino) ||
1992 				    !IS_VALID_BLK_ADDR(sbi, ni.blk_addr)) {
1993 					free(orphan_blk);
1994 					free(new_blk);
1995 					return -EINVAL;
1996 				}
1997 
1998 				continue;
1999 			}
2000 
2001 			ret = fsck_chk_node_blk(sbi, NULL, ino,
2002 					F2FS_FT_ORPHAN, TYPE_INODE, &blk_cnt,
2003 					&cbc, NULL);
2004 			if (!ret)
2005 				new_blk->ino[new_entry_count++] =
2006 							orphan_blk->ino[j];
2007 			else if (ret && c.fix_on)
2008 				FIX_MSG("[0x%x] remove from orphan list", ino);
2009 			else if (ret)
2010 				ASSERT_MSG("[0x%x] wrong orphan inode", ino);
2011 		}
2012 		if (f2fs_dev_is_writable() && c.fix_on &&
2013 				entry_count != new_entry_count) {
2014 			new_blk->entry_count = cpu_to_le32(new_entry_count);
2015 			ret = dev_write_block(new_blk, start_blk + i);
2016 			ASSERT(ret >= 0);
2017 		}
2018 		memset(orphan_blk, 0, BLOCK_SZ);
2019 		memset(new_blk, 0, BLOCK_SZ);
2020 	}
2021 	free(orphan_blk);
2022 	free(new_blk);
2023 
2024 	return 0;
2025 }
2026 
fsck_chk_quota_node(struct f2fs_sb_info * sbi)2027 int fsck_chk_quota_node(struct f2fs_sb_info *sbi)
2028 {
2029 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
2030 	enum quota_type qtype;
2031 	int ret = 0;
2032 	u32 blk_cnt = 0;
2033 	struct f2fs_compr_blk_cnt cbc = {0, CHEADER_PGOFS_NONE};
2034 
2035 	for (qtype = 0; qtype < F2FS_MAX_QUOTAS; qtype++) {
2036 		cur_qtype = qtype;
2037 		if (sb->qf_ino[qtype] == 0)
2038 			continue;
2039 		nid_t ino = QUOTA_INO(sb, qtype);
2040 		struct node_info ni;
2041 
2042 		DBG(1, "qtype [%d] ino [0x%x]\n", qtype, ino);
2043 		blk_cnt = 1;
2044 		cbc.cnt = 0;
2045 		cbc.cheader_pgofs = CHEADER_PGOFS_NONE;
2046 
2047 		if (c.preen_mode == PREEN_MODE_1 && !c.fix_on) {
2048 			get_node_info(sbi, ino, &ni);
2049 			if (!IS_VALID_NID(sbi, ino) ||
2050 					!IS_VALID_BLK_ADDR(sbi, ni.blk_addr))
2051 				return -EINVAL;
2052 			continue;
2053 		}
2054 		ret = fsck_chk_node_blk(sbi, NULL, ino,
2055 				F2FS_FT_REG_FILE, TYPE_INODE, &blk_cnt,
2056 				&cbc, NULL);
2057 		if (ret) {
2058 			ASSERT_MSG("wrong quota inode, qtype [%d] ino [0x%x]",
2059 								qtype, ino);
2060 			qf_szchk_type[qtype] = QF_SZCHK_ERR;
2061 			if (c.fix_on)
2062 				f2fs_rebuild_qf_inode(sbi, qtype);
2063 		}
2064 	}
2065 	cur_qtype = -1;
2066 	return ret;
2067 }
2068 
fsck_chk_quota_files(struct f2fs_sb_info * sbi)2069 int fsck_chk_quota_files(struct f2fs_sb_info *sbi)
2070 {
2071 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2072 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
2073 	enum quota_type qtype;
2074 	f2fs_ino_t ino;
2075 	int ret = 0;
2076 	int needs_writeout;
2077 
2078 	/* Return if quota feature is disabled */
2079 	if (!fsck->qctx)
2080 		return 0;
2081 
2082 	for (qtype = 0; qtype < F2FS_MAX_QUOTAS; qtype++) {
2083 		ino = sb->qf_ino[qtype];
2084 		if (!ino)
2085 			continue;
2086 
2087 	        DBG(1, "Checking Quota file ([%3d] ino [0x%x])\n", qtype, ino);
2088 		needs_writeout = 0;
2089 		ret = quota_compare_and_update(sbi, qtype, &needs_writeout,
2090 						c.preserve_limits);
2091 		if (ret == 0 && needs_writeout == 0) {
2092 			DBG(1, "OK\n");
2093 			continue;
2094 		}
2095 
2096 		/* Something is wrong */
2097 		if (c.fix_on) {
2098 			DBG(0, "Fixing Quota file ([%3d] ino [0x%x])\n",
2099 							qtype, ino);
2100 			f2fs_filesize_update(sbi, ino, 0);
2101 			ret = quota_write_inode(sbi, qtype);
2102 			if (!ret) {
2103 				c.quota_fixed = true;
2104 				DBG(1, "OK\n");
2105 			} else {
2106 				ASSERT_MSG("Unable to write quota file");
2107 			}
2108 		} else {
2109 			ASSERT_MSG("Quota file is missing or invalid"
2110 					" quota file content found.");
2111 		}
2112 	}
2113 	return ret;
2114 }
2115 
fsck_chk_meta(struct f2fs_sb_info * sbi)2116 int fsck_chk_meta(struct f2fs_sb_info *sbi)
2117 {
2118 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2119 	struct f2fs_checkpoint *cp = F2FS_CKPT(sbi);
2120 	struct seg_entry *se;
2121 	unsigned int sit_valid_segs = 0, sit_node_blks = 0;
2122 	unsigned int i;
2123 
2124 	/* 1. check sit usage with CP: curseg is lost? */
2125 	for (i = 0; i < MAIN_SEGS(sbi); i++) {
2126 		se = get_seg_entry(sbi, i);
2127 		if (se->valid_blocks != 0)
2128 			sit_valid_segs++;
2129 		else if (IS_CUR_SEGNO(sbi, i)) {
2130 			/* curseg has not been written back to device */
2131 			MSG(1, "\tInfo: curseg %u is counted in valid segs\n", i);
2132 			sit_valid_segs++;
2133 		}
2134 		if (IS_NODESEG(se->type))
2135 			sit_node_blks += se->valid_blocks;
2136 	}
2137 	if (fsck->chk.sit_free_segs + sit_valid_segs !=
2138 				get_usable_seg_count(sbi)) {
2139 		ASSERT_MSG("SIT usage does not match: sit_free_segs %u, "
2140 				"sit_valid_segs %u, total_segs %u",
2141 			fsck->chk.sit_free_segs, sit_valid_segs,
2142 			get_usable_seg_count(sbi));
2143 		return -EINVAL;
2144 	}
2145 
2146 	/* 2. check node count */
2147 	if (fsck->chk.valid_nat_entry_cnt != sit_node_blks) {
2148 		ASSERT_MSG("node count does not match: valid_nat_entry_cnt %u,"
2149 			" sit_node_blks %u",
2150 			fsck->chk.valid_nat_entry_cnt, sit_node_blks);
2151 		return -EINVAL;
2152 	}
2153 
2154 	/* 3. check SIT with CP */
2155 	if (fsck->chk.sit_free_segs != le32_to_cpu(cp->free_segment_count)) {
2156 		ASSERT_MSG("free segs does not match: sit_free_segs %u, "
2157 				"free_segment_count %u",
2158 				fsck->chk.sit_free_segs,
2159 				le32_to_cpu(cp->free_segment_count));
2160 		return -EINVAL;
2161 	}
2162 
2163 	/* 4. check NAT with CP */
2164 	if (fsck->chk.valid_nat_entry_cnt !=
2165 					le32_to_cpu(cp->valid_node_count)) {
2166 		ASSERT_MSG("valid node does not match: valid_nat_entry_cnt %u,"
2167 				" valid_node_count %u",
2168 				fsck->chk.valid_nat_entry_cnt,
2169 				le32_to_cpu(cp->valid_node_count));
2170 		return -EINVAL;
2171 	}
2172 
2173 	/* 4. check orphan inode simply */
2174 	if (fsck_chk_orphan_node(sbi))
2175 		return -EINVAL;
2176 
2177 	/* 5. check nat entry -- must be done before quota check */
2178 	for (i = 0; i < fsck->nr_nat_entries; i++) {
2179 		u32 blk = le32_to_cpu(fsck->entries[i].block_addr);
2180 		nid_t ino = le32_to_cpu(fsck->entries[i].ino);
2181 
2182 		if (!blk)
2183 			/*
2184 			 * skip entry whose ino is 0, otherwise, we will
2185 			 * get a negative number by BLKOFF_FROM_MAIN(sbi, blk)
2186 			 */
2187 			continue;
2188 
2189 		if (!IS_VALID_BLK_ADDR(sbi, blk)) {
2190 			MSG(0, "\tError: nat entry[ino %u block_addr 0x%x]"
2191 				" is in valid\n",
2192 				ino, blk);
2193 			return -EINVAL;
2194 		}
2195 
2196 		if (!f2fs_test_sit_bitmap(sbi, blk)) {
2197 			MSG(0, "\tError: nat entry[ino %u block_addr 0x%x]"
2198 				" not find it in sit_area_bitmap\n",
2199 				ino, blk);
2200 			return -EINVAL;
2201 		}
2202 
2203 		if (!IS_VALID_NID(sbi, ino)) {
2204 			MSG(0, "\tError: nat_entry->ino %u exceeds the range"
2205 				" of nat entries %u\n",
2206 				ino, fsck->nr_nat_entries);
2207 			return -EINVAL;
2208 		}
2209 
2210 		if (!f2fs_test_bit(ino, fsck->nat_area_bitmap)) {
2211 			MSG(0, "\tError: nat_entry->ino %u is not set in"
2212 				" nat_area_bitmap\n", ino);
2213 			return -EINVAL;
2214 		}
2215 	}
2216 
2217 	/* 6. check quota inode simply */
2218 	if (fsck_chk_quota_node(sbi))
2219 		return -EINVAL;
2220 
2221 	if (fsck->nat_valid_inode_cnt != le32_to_cpu(cp->valid_inode_count)) {
2222 		ASSERT_MSG("valid inode does not match: nat_valid_inode_cnt %u,"
2223 				" valid_inode_count %u",
2224 				fsck->nat_valid_inode_cnt,
2225 				le32_to_cpu(cp->valid_inode_count));
2226 		return -EINVAL;
2227 	}
2228 
2229 	return 0;
2230 }
2231 
fsck_chk_checkpoint(struct f2fs_sb_info * sbi)2232 void fsck_chk_checkpoint(struct f2fs_sb_info *sbi)
2233 {
2234 	struct f2fs_checkpoint *cp = F2FS_CKPT(sbi);
2235 
2236 	if (get_cp(ckpt_flags) & CP_LARGE_NAT_BITMAP_FLAG) {
2237 		if (get_cp(checksum_offset) != CP_MIN_CHKSUM_OFFSET) {
2238 			ASSERT_MSG("Deprecated layout of large_nat_bitmap, "
2239 				"chksum_offset:%u", get_cp(checksum_offset));
2240 			c.fix_chksum = 1;
2241 		}
2242 	}
2243 }
2244 
fsck_init(struct f2fs_sb_info * sbi)2245 void fsck_init(struct f2fs_sb_info *sbi)
2246 {
2247 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2248 	struct f2fs_sm_info *sm_i = SM_I(sbi);
2249 
2250 	/*
2251 	 * We build three bitmap for main/sit/nat so that may check consistency
2252 	 * of filesystem.
2253 	 * 1. main_area_bitmap will be used to check whether all blocks of main
2254 	 *    area is used or not.
2255 	 * 2. nat_area_bitmap has bitmap information of used nid in NAT.
2256 	 * 3. sit_area_bitmap has bitmap information of used main block.
2257 	 * At Last sequence, we compare main_area_bitmap with sit_area_bitmap.
2258 	 */
2259 	fsck->nr_main_blks = sm_i->main_segments << sbi->log_blocks_per_seg;
2260 	fsck->main_area_bitmap_sz = (fsck->nr_main_blks + 7) / 8;
2261 	fsck->main_area_bitmap = calloc(fsck->main_area_bitmap_sz, 1);
2262 	ASSERT(fsck->main_area_bitmap != NULL);
2263 
2264 	build_nat_area_bitmap(sbi);
2265 
2266 	build_sit_area_bitmap(sbi);
2267 
2268 	ASSERT(tree_mark_size != 0);
2269 	tree_mark = calloc(tree_mark_size, 1);
2270 	ASSERT(tree_mark != NULL);
2271 	fsck->dentry = calloc(sizeof(struct f2fs_dentry), 1);
2272 	ASSERT(fsck->dentry != NULL);
2273 	memcpy(fsck->dentry->name, "/", 1);
2274 	fsck->dentry_end = fsck->dentry;
2275 
2276 	c.quota_fixed = false;
2277 }
2278 
fix_hard_links(struct f2fs_sb_info * sbi)2279 static void fix_hard_links(struct f2fs_sb_info *sbi)
2280 {
2281 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2282 	struct hard_link_node *tmp, *node;
2283 	struct f2fs_node *node_blk = NULL;
2284 	struct node_info ni;
2285 	int ret;
2286 
2287 	if (fsck->hard_link_list_head == NULL)
2288 		return;
2289 
2290 	node_blk = (struct f2fs_node *)calloc(BLOCK_SZ, 1);
2291 	ASSERT(node_blk != NULL);
2292 
2293 	node = fsck->hard_link_list_head;
2294 	while (node) {
2295 		/* Sanity check */
2296 		if (sanity_check_nid(sbi, node->nid, node_blk,
2297 					F2FS_FT_MAX, TYPE_INODE, &ni))
2298 			FIX_MSG("Failed to fix, rerun fsck.f2fs");
2299 
2300 		node_blk->i.i_links = cpu_to_le32(node->actual_links);
2301 
2302 		FIX_MSG("File: 0x%x i_links= 0x%x -> 0x%x",
2303 				node->nid, node->links, node->actual_links);
2304 
2305 		ret = dev_write_block(node_blk, ni.blk_addr);
2306 		ASSERT(ret >= 0);
2307 		tmp = node;
2308 		node = node->next;
2309 		free(tmp);
2310 	}
2311 	free(node_blk);
2312 }
2313 
fix_nat_entries(struct f2fs_sb_info * sbi)2314 static void fix_nat_entries(struct f2fs_sb_info *sbi)
2315 {
2316 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2317 	u32 i;
2318 
2319 	for (i = 0; i < fsck->nr_nat_entries; i++)
2320 		if (f2fs_test_bit(i, fsck->nat_area_bitmap) != 0)
2321 			nullify_nat_entry(sbi, i);
2322 }
2323 
flush_curseg_sit_entries(struct f2fs_sb_info * sbi)2324 static void flush_curseg_sit_entries(struct f2fs_sb_info *sbi)
2325 {
2326 	struct sit_info *sit_i = SIT_I(sbi);
2327 	struct f2fs_sit_block *sit_blk;
2328 	int i;
2329 
2330 	sit_blk = calloc(BLOCK_SZ, 1);
2331 	ASSERT(sit_blk);
2332 	/* update curseg sit entries, since we may change
2333 	 * a segment type in move_curseg_info
2334 	 */
2335 	for (i = 0; i < NO_CHECK_TYPE; i++) {
2336 		struct curseg_info *curseg = CURSEG_I(sbi, i);
2337 		struct f2fs_sit_entry *sit;
2338 		struct seg_entry *se;
2339 
2340 		se = get_seg_entry(sbi, curseg->segno);
2341 		get_current_sit_page(sbi, curseg->segno, sit_blk);
2342 		sit = &sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, curseg->segno)];
2343 		sit->vblocks = cpu_to_le16((se->type << SIT_VBLOCKS_SHIFT) |
2344 							se->valid_blocks);
2345 		rewrite_current_sit_page(sbi, curseg->segno, sit_blk);
2346 	}
2347 
2348 	free(sit_blk);
2349 }
2350 
fix_checksum(struct f2fs_sb_info * sbi)2351 static void fix_checksum(struct f2fs_sb_info *sbi)
2352 {
2353 	struct f2fs_checkpoint *cp = F2FS_CKPT(sbi);
2354 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2355 	struct sit_info *sit_i = SIT_I(sbi);
2356 	void *bitmap_offset;
2357 
2358 	if (!c.fix_chksum)
2359 		return;
2360 
2361 	bitmap_offset = cp->sit_nat_version_bitmap + sizeof(__le32);
2362 
2363 	memcpy(bitmap_offset, nm_i->nat_bitmap, nm_i->bitmap_size);
2364 	memcpy(bitmap_offset + nm_i->bitmap_size,
2365 			sit_i->sit_bitmap, sit_i->bitmap_size);
2366 }
2367 
fix_checkpoint(struct f2fs_sb_info * sbi)2368 static void fix_checkpoint(struct f2fs_sb_info *sbi)
2369 {
2370 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2371 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
2372 	struct f2fs_checkpoint *cp = F2FS_CKPT(sbi);
2373 	unsigned long long cp_blk_no;
2374 	u32 flags = c.alloc_failed ? CP_FSCK_FLAG: CP_UMOUNT_FLAG;
2375 	block_t orphan_blks = 0;
2376 	block_t cp_blocks;
2377 	u32 i;
2378 	int ret;
2379 	uint32_t crc = 0;
2380 
2381 	/* should call from fsck */
2382 	ASSERT(c.func == FSCK);
2383 
2384 	if (is_set_ckpt_flags(cp, CP_ORPHAN_PRESENT_FLAG)) {
2385 		orphan_blks = __start_sum_addr(sbi) - 1;
2386 		flags |= CP_ORPHAN_PRESENT_FLAG;
2387 	}
2388 	if (is_set_ckpt_flags(cp, CP_TRIMMED_FLAG))
2389 		flags |= CP_TRIMMED_FLAG;
2390 	if (is_set_ckpt_flags(cp, CP_DISABLED_FLAG))
2391 		flags |= CP_DISABLED_FLAG;
2392 	if (is_set_ckpt_flags(cp, CP_LARGE_NAT_BITMAP_FLAG)) {
2393 		flags |= CP_LARGE_NAT_BITMAP_FLAG;
2394 		set_cp(checksum_offset, CP_MIN_CHKSUM_OFFSET);
2395 	} else {
2396 		set_cp(checksum_offset, CP_CHKSUM_OFFSET);
2397 	}
2398 
2399 	if (flags & CP_UMOUNT_FLAG)
2400 		cp_blocks = 8;
2401 	else
2402 		cp_blocks = 5;
2403 
2404 	set_cp(cp_pack_total_block_count, cp_blocks +
2405 				orphan_blks + get_sb(cp_payload));
2406 
2407 	flags = update_nat_bits_flags(sb, cp, flags);
2408 	flags |= CP_NOCRC_RECOVERY_FLAG;
2409 	set_cp(ckpt_flags, flags);
2410 
2411 	set_cp(free_segment_count, get_free_segments(sbi));
2412 	set_cp(valid_block_count, fsck->chk.valid_blk_cnt);
2413 	set_cp(valid_node_count, fsck->chk.valid_node_cnt);
2414 	set_cp(valid_inode_count, fsck->chk.valid_inode_cnt);
2415 
2416 	crc = f2fs_checkpoint_chksum(cp);
2417 	*((__le32 *)((unsigned char *)cp + get_cp(checksum_offset))) =
2418 							cpu_to_le32(crc);
2419 
2420 	cp_blk_no = get_sb(cp_blkaddr);
2421 	if (sbi->cur_cp == 2)
2422 		cp_blk_no += 1 << get_sb(log_blocks_per_seg);
2423 
2424 	ret = dev_write_block(cp, cp_blk_no++);
2425 	ASSERT(ret >= 0);
2426 
2427 	for (i = 0; i < get_sb(cp_payload); i++) {
2428 		ret = dev_write_block(((unsigned char *)cp) +
2429 					(i + 1) * F2FS_BLKSIZE, cp_blk_no++);
2430 		ASSERT(ret >= 0);
2431 	}
2432 
2433 	cp_blk_no += orphan_blks;
2434 
2435 	for (i = 0; i < NO_CHECK_TYPE; i++) {
2436 		struct curseg_info *curseg = CURSEG_I(sbi, i);
2437 
2438 		if (!(flags & CP_UMOUNT_FLAG) && IS_NODESEG(i))
2439 			continue;
2440 
2441 		ret = dev_write_block(curseg->sum_blk, cp_blk_no++);
2442 		ASSERT(ret >= 0);
2443 	}
2444 
2445 	/* Write nat bits */
2446 	if (flags & CP_NAT_BITS_FLAG)
2447 		write_nat_bits(sbi, sb, cp, sbi->cur_cp);
2448 
2449 	ret = f2fs_fsync_device();
2450 	ASSERT(ret >= 0);
2451 
2452 	ret = dev_write_block(cp, cp_blk_no++);
2453 	ASSERT(ret >= 0);
2454 
2455 	ret = f2fs_fsync_device();
2456 	ASSERT(ret >= 0);
2457 }
2458 
fix_checkpoints(struct f2fs_sb_info * sbi)2459 static void fix_checkpoints(struct f2fs_sb_info *sbi)
2460 {
2461 	/* copy valid checkpoint to its mirror position */
2462 	duplicate_checkpoint(sbi);
2463 
2464 	/* repair checkpoint at CP #0 position */
2465 	sbi->cur_cp = 1;
2466 	fix_checkpoint(sbi);
2467 }
2468 
2469 #ifdef HAVE_LINUX_BLKZONED_H
2470 
2471 /*
2472  * Refer valid block map and return offset of the last valid block in the zone.
2473  * Obtain valid block map from SIT and fsync data.
2474  * If there is no valid block in the zone, return -1.
2475  */
last_vblk_off_in_zone(struct f2fs_sb_info * sbi,unsigned int zone_segno)2476 static int last_vblk_off_in_zone(struct f2fs_sb_info *sbi,
2477 				 unsigned int zone_segno)
2478 {
2479 	int s, b;
2480 	unsigned int segs_per_zone = sbi->segs_per_sec * sbi->secs_per_zone;
2481 	struct seg_entry *se;
2482 
2483 	for (s = segs_per_zone - 1; s >= 0; s--) {
2484 		se = get_seg_entry(sbi, zone_segno + s);
2485 
2486 		/*
2487 		 * Refer not cur_valid_map but ckpt_valid_map which reflects
2488 		 * fsync data.
2489 		 */
2490 		ASSERT(se->ckpt_valid_map);
2491 		for (b = sbi->blocks_per_seg - 1; b >= 0; b--)
2492 			if (f2fs_test_bit(b, (const char*)se->ckpt_valid_map))
2493 				return b + (s << sbi->log_blocks_per_seg);
2494 	}
2495 
2496 	return -1;
2497 }
2498 
check_curseg_write_pointer(struct f2fs_sb_info * sbi,int type)2499 static int check_curseg_write_pointer(struct f2fs_sb_info *sbi, int type)
2500 {
2501 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2502 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2503 	struct blk_zone blkz;
2504 	block_t cs_block, wp_block, zone_last_vblock;
2505 	uint64_t cs_sector, wp_sector;
2506 	int i, ret;
2507 	unsigned int zone_segno;
2508 	int log_sectors_per_block = sbi->log_blocksize - SECTOR_SHIFT;
2509 
2510 	/* get the device the curseg points to */
2511 	cs_block = START_BLOCK(sbi, curseg->segno) + curseg->next_blkoff;
2512 	for (i = 0; i < MAX_DEVICES; i++) {
2513 		if (!c.devices[i].path)
2514 			break;
2515 		if (c.devices[i].start_blkaddr <= cs_block &&
2516 		    cs_block <= c.devices[i].end_blkaddr)
2517 			break;
2518 	}
2519 
2520 	if (i >= MAX_DEVICES)
2521 		return -EINVAL;
2522 
2523 	if (c.devices[i].zoned_model != F2FS_ZONED_HM)
2524 		return 0;
2525 
2526 	/* get write pointer position of the zone the curseg points to */
2527 	cs_sector = (cs_block - c.devices[i].start_blkaddr)
2528 		<< log_sectors_per_block;
2529 	ret = f2fs_report_zone(i, cs_sector, &blkz);
2530 	if (ret)
2531 		return ret;
2532 
2533 	if (blk_zone_type(&blkz) != BLK_ZONE_TYPE_SEQWRITE_REQ)
2534 		return 0;
2535 
2536 	/* check consistency between the curseg and the write pointer */
2537 	wp_block = c.devices[i].start_blkaddr +
2538 		(blk_zone_wp_sector(&blkz) >> log_sectors_per_block);
2539 	wp_sector = blk_zone_wp_sector(&blkz);
2540 
2541 	if (cs_sector == wp_sector)
2542 		return 0;
2543 
2544 	if (cs_sector > wp_sector) {
2545 		MSG(0, "Inconsistent write pointer with curseg %d: "
2546 		    "curseg %d[0x%x,0x%x] > wp[0x%x,0x%x]\n",
2547 		    type, type, curseg->segno, curseg->next_blkoff,
2548 		    GET_SEGNO(sbi, wp_block), OFFSET_IN_SEG(sbi, wp_block));
2549 		fsck->chk.wp_inconsistent_zones++;
2550 		return -EINVAL;
2551 	}
2552 
2553 	MSG(0, "Write pointer goes advance from curseg %d: "
2554 	    "curseg %d[0x%x,0x%x] wp[0x%x,0x%x]\n",
2555 	    type, type, curseg->segno, curseg->next_blkoff,
2556 	    GET_SEGNO(sbi, wp_block), OFFSET_IN_SEG(sbi, wp_block));
2557 
2558 	zone_segno = GET_SEG_FROM_SEC(sbi,
2559 				      GET_SEC_FROM_SEG(sbi, curseg->segno));
2560 	zone_last_vblock = START_BLOCK(sbi, zone_segno) +
2561 		last_vblk_off_in_zone(sbi, zone_segno);
2562 
2563 	/*
2564 	 * If valid blocks exist between the curseg position and the write
2565 	 * pointer, they are fsync data. This is not an error to fix. Leave it
2566 	 * for kernel to recover later.
2567 	 * If valid blocks exist between the curseg's zone start and the curseg
2568 	 * position, or if there is no valid block in the curseg's zone, fix
2569 	 * the inconsistency between the curseg and the writ pointer.
2570 	 * Of Note is that if there is no valid block in the curseg's zone,
2571 	 * last_vblk_off_in_zone() returns -1 and zone_last_vblock is always
2572 	 * smaller than cs_block.
2573 	 */
2574 	if (cs_block <= zone_last_vblock && zone_last_vblock < wp_block) {
2575 		MSG(0, "Curseg has fsync data: curseg %d[0x%x,0x%x] "
2576 		    "last valid block in zone[0x%x,0x%x]\n",
2577 		    type, curseg->segno, curseg->next_blkoff,
2578 		    GET_SEGNO(sbi, zone_last_vblock),
2579 		    OFFSET_IN_SEG(sbi, zone_last_vblock));
2580 		return 0;
2581 	}
2582 
2583 	fsck->chk.wp_inconsistent_zones++;
2584 	return -EINVAL;
2585 }
2586 
2587 #else
2588 
check_curseg_write_pointer(struct f2fs_sb_info * UNUSED (sbi),int UNUSED (type))2589 static int check_curseg_write_pointer(struct f2fs_sb_info *UNUSED(sbi),
2590 					int UNUSED(type))
2591 {
2592 	return 0;
2593 }
2594 
2595 #endif
2596 
check_curseg_offset(struct f2fs_sb_info * sbi,int type)2597 int check_curseg_offset(struct f2fs_sb_info *sbi, int type)
2598 {
2599 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
2600 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2601 	struct seg_entry *se;
2602 	int j, nblocks;
2603 
2604 	if (get_sb(feature) & cpu_to_le32(F2FS_FEATURE_RO) &&
2605 			type != CURSEG_HOT_DATA && type != CURSEG_HOT_NODE)
2606 		return 0;
2607 
2608 	if ((curseg->next_blkoff >> 3) >= SIT_VBLOCK_MAP_SIZE) {
2609 		ASSERT_MSG("Next block offset:%u is invalid, type:%d",
2610 			curseg->next_blkoff, type);
2611 		return -EINVAL;
2612 	}
2613 	se = get_seg_entry(sbi, curseg->segno);
2614 	if (f2fs_test_bit(curseg->next_blkoff,
2615 				(const char *)se->cur_valid_map)) {
2616 		ASSERT_MSG("Next block offset is not free, type:%d", type);
2617 		return -EINVAL;
2618 	}
2619 	if (curseg->alloc_type == SSR)
2620 		return 0;
2621 
2622 	nblocks = sbi->blocks_per_seg;
2623 	for (j = curseg->next_blkoff + 1; j < nblocks; j++) {
2624 		if (f2fs_test_bit(j, (const char *)se->cur_valid_map)) {
2625 			ASSERT_MSG("For LFS curseg, space after .next_blkoff "
2626 				"should be unused, type:%d", type);
2627 			return -EINVAL;
2628 		}
2629 	}
2630 
2631 	if (c.zoned_model == F2FS_ZONED_HM)
2632 		return check_curseg_write_pointer(sbi, type);
2633 
2634 	return 0;
2635 }
2636 
check_curseg_offsets(struct f2fs_sb_info * sbi)2637 int check_curseg_offsets(struct f2fs_sb_info *sbi)
2638 {
2639 	int i, ret;
2640 
2641 	for (i = 0; i < NO_CHECK_TYPE; i++) {
2642 		ret = check_curseg_offset(sbi, i);
2643 		if (ret)
2644 			return ret;
2645 	}
2646 	return 0;
2647 }
2648 
fix_curseg_info(struct f2fs_sb_info * sbi)2649 static void fix_curseg_info(struct f2fs_sb_info *sbi)
2650 {
2651 	int i, need_update = 0;
2652 
2653 	for (i = 0; i < NO_CHECK_TYPE; i++) {
2654 		if (check_curseg_offset(sbi, i)) {
2655 			update_curseg_info(sbi, i);
2656 			need_update = 1;
2657 		}
2658 	}
2659 
2660 	if (need_update) {
2661 		write_curseg_info(sbi);
2662 		flush_curseg_sit_entries(sbi);
2663 	}
2664 }
2665 
check_sit_types(struct f2fs_sb_info * sbi)2666 int check_sit_types(struct f2fs_sb_info *sbi)
2667 {
2668 	unsigned int i;
2669 	int err = 0;
2670 
2671 	for (i = 0; i < MAIN_SEGS(sbi); i++) {
2672 		struct seg_entry *se;
2673 
2674 		se = get_seg_entry(sbi, i);
2675 		if (se->orig_type != se->type) {
2676 			if (se->orig_type == CURSEG_COLD_DATA &&
2677 					se->type <= CURSEG_COLD_DATA) {
2678 				se->type = se->orig_type;
2679 			} else {
2680 				FIX_MSG("Wrong segment type [0x%x] %x -> %x",
2681 						i, se->orig_type, se->type);
2682 				err = -EINVAL;
2683 			}
2684 		}
2685 	}
2686 	return err;
2687 }
2688 
fsck_get_lpf(struct f2fs_sb_info * sbi)2689 static struct f2fs_node *fsck_get_lpf(struct f2fs_sb_info *sbi)
2690 {
2691 	struct f2fs_node *node;
2692 	struct node_info ni;
2693 	nid_t lpf_ino;
2694 	int err;
2695 
2696 	/* read root inode first */
2697 	node = calloc(F2FS_BLKSIZE, 1);
2698 	ASSERT(node);
2699 	get_node_info(sbi, F2FS_ROOT_INO(sbi), &ni);
2700 	err = dev_read_block(node, ni.blk_addr);
2701 	ASSERT(err >= 0);
2702 
2703 	/* lookup lost+found in root directory */
2704 	lpf_ino = f2fs_lookup(sbi, node, (u8 *)LPF, strlen(LPF));
2705 	if (lpf_ino) { /* found */
2706 		get_node_info(sbi, lpf_ino, &ni);
2707 		err = dev_read_block(node, ni.blk_addr);
2708 		ASSERT(err >= 0);
2709 		DBG(1, "Found lost+found 0x%x at blkaddr [0x%x]\n",
2710 		    lpf_ino, ni.blk_addr);
2711 		if (!S_ISDIR(le16_to_cpu(node->i.i_mode))) {
2712 			ASSERT_MSG("lost+found is not directory [0%o]\n",
2713 				   le16_to_cpu(node->i.i_mode));
2714 			/* FIXME: give up? */
2715 			goto out;
2716 		}
2717 	} else { /* not found, create it */
2718 		struct dentry de;
2719 
2720 		memset(&de, 0, sizeof(de));
2721 		de.name = (u8 *) LPF;
2722 		de.len = strlen(LPF);
2723 		de.mode = 0x41c0;
2724 		de.pino = F2FS_ROOT_INO(sbi),
2725 		de.file_type = F2FS_FT_DIR,
2726 		de.uid = getuid();
2727 		de.gid = getgid();
2728 		de.mtime = time(NULL);
2729 
2730 		err = f2fs_mkdir(sbi, &de);
2731 		if (err) {
2732 			ASSERT_MSG("Failed create lost+found");
2733 			goto out;
2734 		}
2735 
2736 		get_node_info(sbi, de.ino, &ni);
2737 		err = dev_read_block(node, ni.blk_addr);
2738 		ASSERT(err >= 0);
2739 		DBG(1, "Create lost+found 0x%x at blkaddr [0x%x]\n",
2740 		    de.ino, ni.blk_addr);
2741 	}
2742 
2743 	c.lpf_ino = le32_to_cpu(node->footer.ino);
2744 	return node;
2745 out:
2746 	free(node);
2747 	return NULL;
2748 }
2749 
fsck_do_reconnect_file(struct f2fs_sb_info * sbi,struct f2fs_node * lpf,struct f2fs_node * fnode)2750 static int fsck_do_reconnect_file(struct f2fs_sb_info *sbi,
2751 				  struct f2fs_node *lpf,
2752 				  struct f2fs_node *fnode)
2753 {
2754 	char name[80];
2755 	size_t namelen;
2756 	nid_t ino = le32_to_cpu(fnode->footer.ino);
2757 	struct node_info ni;
2758 	int ftype, ret;
2759 
2760 	namelen = snprintf(name, 80, "%u", ino);
2761 	if (namelen >= 80)
2762 		/* ignore terminating '\0', should never happen */
2763 		namelen = 79;
2764 
2765 	if (f2fs_lookup(sbi, lpf, (u8 *)name, namelen)) {
2766 		ASSERT_MSG("Name %s already exist in lost+found", name);
2767 		return -EEXIST;
2768 	}
2769 
2770 	get_node_info(sbi, le32_to_cpu(lpf->footer.ino), &ni);
2771 	ftype = map_de_type(le16_to_cpu(fnode->i.i_mode));
2772 	ret = f2fs_add_link(sbi, lpf, (unsigned char *)name, namelen,
2773 			    ino, ftype, ni.blk_addr, 0);
2774 	if (ret) {
2775 		ASSERT_MSG("Failed to add inode [0x%x] to lost+found", ino);
2776 		return -EINVAL;
2777 	}
2778 
2779 	/* update fnode */
2780 	memcpy(fnode->i.i_name, name, namelen);
2781 	fnode->i.i_namelen = cpu_to_le32(namelen);
2782 	fnode->i.i_pino = c.lpf_ino;
2783 	get_node_info(sbi, le32_to_cpu(fnode->footer.ino), &ni);
2784 	ret = dev_write_block(fnode, ni.blk_addr);
2785 	ASSERT(ret >= 0);
2786 
2787 	DBG(1, "Reconnect inode [0x%x] to lost+found\n", ino);
2788 	return 0;
2789 }
2790 
fsck_failed_reconnect_file_dnode(struct f2fs_sb_info * sbi,nid_t nid)2791 static void fsck_failed_reconnect_file_dnode(struct f2fs_sb_info *sbi,
2792 					     nid_t nid)
2793 {
2794 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2795 	struct f2fs_node *node;
2796 	struct node_info ni;
2797 	u32 addr;
2798 	int i, err;
2799 
2800 	node = calloc(F2FS_BLKSIZE, 1);
2801 	ASSERT(node);
2802 
2803 	get_node_info(sbi, nid, &ni);
2804 	err = dev_read_block(node, ni.blk_addr);
2805 	ASSERT(err >= 0);
2806 
2807 	fsck->chk.valid_node_cnt--;
2808 	fsck->chk.valid_blk_cnt--;
2809 	f2fs_clear_main_bitmap(sbi, ni.blk_addr);
2810 
2811 	for (i = 0; i < ADDRS_PER_BLOCK(&node->i); i++) {
2812 		addr = le32_to_cpu(node->dn.addr[i]);
2813 		if (!addr)
2814 			continue;
2815 		fsck->chk.valid_blk_cnt--;
2816 		if (addr == NEW_ADDR)
2817 			continue;
2818 		f2fs_clear_main_bitmap(sbi, addr);
2819 	}
2820 
2821 	free(node);
2822 }
2823 
fsck_failed_reconnect_file_idnode(struct f2fs_sb_info * sbi,nid_t nid)2824 static void fsck_failed_reconnect_file_idnode(struct f2fs_sb_info *sbi,
2825 					      nid_t nid)
2826 {
2827 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2828 	struct f2fs_node *node;
2829 	struct node_info ni;
2830 	nid_t tmp;
2831 	int i, err;
2832 
2833 	node = calloc(F2FS_BLKSIZE, 1);
2834 	ASSERT(node);
2835 
2836 	get_node_info(sbi, nid, &ni);
2837 	err = dev_read_block(node, ni.blk_addr);
2838 	ASSERT(err >= 0);
2839 
2840 	fsck->chk.valid_node_cnt--;
2841 	fsck->chk.valid_blk_cnt--;
2842 	f2fs_clear_main_bitmap(sbi, ni.blk_addr);
2843 
2844 	for (i = 0; i < NIDS_PER_BLOCK; i++) {
2845 		tmp = le32_to_cpu(node->in.nid[i]);
2846 		if (!tmp)
2847 			continue;
2848 		fsck_failed_reconnect_file_dnode(sbi, tmp);
2849 	}
2850 
2851 	free(node);
2852 }
2853 
fsck_failed_reconnect_file_didnode(struct f2fs_sb_info * sbi,nid_t nid)2854 static void fsck_failed_reconnect_file_didnode(struct f2fs_sb_info *sbi,
2855 					       nid_t nid)
2856 {
2857 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2858 	struct f2fs_node *node;
2859 	struct node_info ni;
2860 	nid_t tmp;
2861 	int i, err;
2862 
2863 	node = calloc(F2FS_BLKSIZE, 1);
2864 	ASSERT(node);
2865 
2866 	get_node_info(sbi, nid, &ni);
2867 	err = dev_read_block(node, ni.blk_addr);
2868 	ASSERT(err >= 0);
2869 
2870 	fsck->chk.valid_node_cnt--;
2871 	fsck->chk.valid_blk_cnt--;
2872 	f2fs_clear_main_bitmap(sbi, ni.blk_addr);
2873 
2874 	for (i = 0; i < NIDS_PER_BLOCK; i++) {
2875 		tmp = le32_to_cpu(node->in.nid[i]);
2876 		if (!tmp)
2877 			continue;
2878 		fsck_failed_reconnect_file_idnode(sbi, tmp);
2879 	}
2880 
2881 	free(node);
2882 }
2883 
2884 /*
2885  * Counters and main_area_bitmap are already changed during checking
2886  * inode block, so clear them. There is no need to clear new blocks
2887  * allocted to lost+found.
2888  */
fsck_failed_reconnect_file(struct f2fs_sb_info * sbi,nid_t ino)2889 static void fsck_failed_reconnect_file(struct f2fs_sb_info *sbi, nid_t ino)
2890 {
2891 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2892 	struct f2fs_node *node;
2893 	struct node_info ni;
2894 	nid_t nid;
2895 	int ofs, i, err;
2896 
2897 	node = calloc(F2FS_BLKSIZE, 1);
2898 	ASSERT(node);
2899 
2900 	get_node_info(sbi, ino, &ni);
2901 	err = dev_read_block(node, ni.blk_addr);
2902 	ASSERT(err >= 0);
2903 
2904 	/* clear inode counters */
2905 	fsck->chk.valid_inode_cnt--;
2906 	fsck->chk.valid_node_cnt--;
2907 	fsck->chk.valid_blk_cnt--;
2908 	f2fs_clear_main_bitmap(sbi, ni.blk_addr);
2909 
2910 	/* clear xnid counters */
2911 	if (node->i.i_xattr_nid) {
2912 		nid = le32_to_cpu(node->i.i_xattr_nid);
2913 		fsck->chk.valid_node_cnt--;
2914 		fsck->chk.valid_blk_cnt--;
2915 		get_node_info(sbi, nid, &ni);
2916 		f2fs_clear_main_bitmap(sbi, ni.blk_addr);
2917 	}
2918 
2919 	/* clear data counters */
2920 	if(!(node->i.i_inline & F2FS_INLINE_DATA)) {
2921 		ofs = get_extra_isize(node);
2922 		for (i = 0; i < ADDRS_PER_INODE(&node->i); i++) {
2923 			block_t addr = le32_to_cpu(node->i.i_addr[ofs + i]);
2924 			if (!addr)
2925 				continue;
2926 			fsck->chk.valid_blk_cnt--;
2927 			if (addr == NEW_ADDR)
2928 				continue;
2929 			f2fs_clear_main_bitmap(sbi, addr);
2930 		}
2931 	}
2932 
2933 	for (i = 0; i < 5; i++) {
2934 		nid = le32_to_cpu(node->i.i_nid[i]);
2935 		if (!nid)
2936 			continue;
2937 
2938 		switch (i) {
2939 		case 0: /* direct node */
2940 		case 1:
2941 			fsck_failed_reconnect_file_dnode(sbi, nid);
2942 			break;
2943 		case 2: /* indirect node */
2944 		case 3:
2945 			fsck_failed_reconnect_file_idnode(sbi, nid);
2946 			break;
2947 		case 4: /* double indirect node */
2948 			fsck_failed_reconnect_file_didnode(sbi, nid);
2949 			break;
2950 		}
2951 	}
2952 
2953 	free(node);
2954 }
2955 
2956 /*
2957  * Scan unreachable nids and find only regular file inodes. If these files
2958  * are not corrupted, reconnect them to lost+found.
2959  *
2960  * Since all unreachable nodes are already checked, we can allocate new
2961  * blocks safely.
2962  *
2963  * This function returns the number of files been reconnected.
2964  */
fsck_reconnect_file(struct f2fs_sb_info * sbi)2965 static int fsck_reconnect_file(struct f2fs_sb_info *sbi)
2966 {
2967 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
2968 	struct f2fs_node *lpf_node, *node;
2969 	struct node_info ni;
2970 	char *reconnect_bitmap;
2971 	u32 blk_cnt;
2972 	struct f2fs_compr_blk_cnt cbc;
2973 	nid_t nid;
2974 	int err, cnt = 0, ftype;
2975 
2976 	node = calloc(F2FS_BLKSIZE, 1);
2977 	ASSERT(node);
2978 
2979 	reconnect_bitmap = calloc(fsck->nat_area_bitmap_sz, 1);
2980 	ASSERT(reconnect_bitmap);
2981 
2982 	for (nid = 0; nid < fsck->nr_nat_entries; nid++) {
2983 		if (f2fs_test_bit(nid, fsck->nat_area_bitmap)) {
2984 			if (is_qf_ino(F2FS_RAW_SUPER(sbi), nid)) {
2985 				DBG(1, "Not support quota inode [0x%x]\n",
2986 				    nid);
2987 				continue;
2988 			}
2989 
2990 			get_node_info(sbi, nid, &ni);
2991 			err = dev_read_block(node, ni.blk_addr);
2992 			ASSERT(err >= 0);
2993 
2994 			/* reconnection will restore these nodes if needed */
2995 			if (node->footer.ino != node->footer.nid) {
2996 				DBG(1, "Not support non-inode node [0x%x]\n",
2997 				    nid);
2998 				continue;
2999 			}
3000 
3001 			if (S_ISDIR(le16_to_cpu(node->i.i_mode))) {
3002 				DBG(1, "Not support directory inode [0x%x]\n",
3003 				    nid);
3004 				continue;
3005 			}
3006 
3007 			ftype = map_de_type(le16_to_cpu(node->i.i_mode));
3008 			if (sanity_check_nid(sbi, nid, node, ftype,
3009 					     TYPE_INODE, &ni)) {
3010 				ASSERT_MSG("Invalid nid [0x%x]\n", nid);
3011 				continue;
3012 			}
3013 
3014 			DBG(1, "Check inode 0x%x\n", nid);
3015 			blk_cnt = 1;
3016 			cbc.cnt = 0;
3017 			cbc.cheader_pgofs = CHEADER_PGOFS_NONE;
3018 			fsck_chk_inode_blk(sbi, nid, ftype, node,
3019 					   &blk_cnt, &cbc, &ni, NULL);
3020 
3021 			f2fs_set_bit(nid, reconnect_bitmap);
3022 		}
3023 	}
3024 
3025 	lpf_node = fsck_get_lpf(sbi);
3026 	if (!lpf_node)
3027 		goto out;
3028 
3029 	for (nid = 0; nid < fsck->nr_nat_entries; nid++) {
3030 		if (f2fs_test_bit(nid, reconnect_bitmap)) {
3031 			get_node_info(sbi, nid, &ni);
3032 			err = dev_read_block(node, ni.blk_addr);
3033 			ASSERT(err >= 0);
3034 
3035 			if (fsck_do_reconnect_file(sbi, lpf_node, node)) {
3036 				DBG(1, "Failed to reconnect inode [0x%x]\n",
3037 				    nid);
3038 				fsck_failed_reconnect_file(sbi, nid);
3039 				continue;
3040 			}
3041 
3042 			quota_add_inode_usage(fsck->qctx, nid, &node->i);
3043 
3044 			DBG(1, "Reconnected inode [0x%x] to lost+found\n", nid);
3045 			cnt++;
3046 		}
3047 	}
3048 
3049 out:
3050 	free(node);
3051 	free(lpf_node);
3052 	free(reconnect_bitmap);
3053 	return cnt;
3054 }
3055 
3056 #ifdef HAVE_LINUX_BLKZONED_H
3057 
3058 struct write_pointer_check_data {
3059 	struct f2fs_sb_info *sbi;
3060 	int dev_index;
3061 };
3062 
chk_and_fix_wp_with_sit(int UNUSED (i),void * blkzone,void * opaque)3063 static int chk_and_fix_wp_with_sit(int UNUSED(i), void *blkzone, void *opaque)
3064 {
3065 	struct blk_zone *blkz = (struct blk_zone *)blkzone;
3066 	struct write_pointer_check_data *wpd = opaque;
3067 	struct f2fs_sb_info *sbi = wpd->sbi;
3068 	struct device_info *dev = c.devices + wpd->dev_index;
3069 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
3070 	block_t zone_block, wp_block, wp_blkoff;
3071 	unsigned int zone_segno, wp_segno;
3072 	struct curseg_info *cs;
3073 	int cs_index, ret, last_valid_blkoff;
3074 	int log_sectors_per_block = sbi->log_blocksize - SECTOR_SHIFT;
3075 	unsigned int segs_per_zone = sbi->segs_per_sec * sbi->secs_per_zone;
3076 
3077 	if (blk_zone_conv(blkz))
3078 		return 0;
3079 
3080 	zone_block = dev->start_blkaddr
3081 		+ (blk_zone_sector(blkz) >> log_sectors_per_block);
3082 	zone_segno = GET_SEGNO(sbi, zone_block);
3083 	if (zone_segno >= MAIN_SEGS(sbi))
3084 		return 0;
3085 
3086 	wp_block = dev->start_blkaddr
3087 		+ (blk_zone_wp_sector(blkz) >> log_sectors_per_block);
3088 	wp_segno = GET_SEGNO(sbi, wp_block);
3089 	wp_blkoff = wp_block - START_BLOCK(sbi, wp_segno);
3090 
3091 	/* if a curseg points to the zone, skip the check */
3092 	for (cs_index = 0; cs_index < NO_CHECK_TYPE; cs_index++) {
3093 		cs = &SM_I(sbi)->curseg_array[cs_index];
3094 		if (zone_segno <= cs->segno &&
3095 		    cs->segno < zone_segno + segs_per_zone)
3096 			return 0;
3097 	}
3098 
3099 	last_valid_blkoff = last_vblk_off_in_zone(sbi, zone_segno);
3100 
3101 	/*
3102 	 * When there is no valid block in the zone, check write pointer is
3103 	 * at zone start. If not, reset the write pointer.
3104 	 */
3105 	if (last_valid_blkoff < 0 &&
3106 	    blk_zone_wp_sector(blkz) != blk_zone_sector(blkz)) {
3107 		if (!c.fix_on) {
3108 			MSG(0, "Inconsistent write pointer: wp[0x%x,0x%x]\n",
3109 			    wp_segno, wp_blkoff);
3110 			fsck->chk.wp_inconsistent_zones++;
3111 			return 0;
3112 		}
3113 
3114 		FIX_MSG("Reset write pointer of zone at segment 0x%x",
3115 			zone_segno);
3116 		ret = f2fs_reset_zone(wpd->dev_index, blkz);
3117 		if (ret) {
3118 			printf("[FSCK] Write pointer reset failed: %s\n",
3119 			       dev->path);
3120 			return ret;
3121 		}
3122 		fsck->chk.wp_fixed = 1;
3123 		return 0;
3124 	}
3125 
3126 	/*
3127 	 * If valid blocks exist in the zone beyond the write pointer, it
3128 	 * is a bug. No need to fix because the zone is not selected for the
3129 	 * write. Just report it.
3130 	 */
3131 	if (last_valid_blkoff + zone_block > wp_block) {
3132 		MSG(0, "Unexpected invalid write pointer: wp[0x%x,0x%x]\n",
3133 		    wp_segno, wp_blkoff);
3134 		return 0;
3135 	}
3136 
3137 	return 0;
3138 }
3139 
fix_wp_sit_alignment(struct f2fs_sb_info * sbi)3140 static void fix_wp_sit_alignment(struct f2fs_sb_info *sbi)
3141 {
3142 	unsigned int i;
3143 	struct write_pointer_check_data wpd = {	sbi, 0 };
3144 
3145 	if (c.zoned_model != F2FS_ZONED_HM)
3146 		return;
3147 
3148 	for (i = 0; i < MAX_DEVICES; i++) {
3149 		if (!c.devices[i].path)
3150 			break;
3151 		if (c.devices[i].zoned_model != F2FS_ZONED_HM)
3152 			break;
3153 
3154 		wpd.dev_index = i;
3155 		if (f2fs_report_zones(i, chk_and_fix_wp_with_sit, &wpd)) {
3156 			printf("[FSCK] Write pointer check failed: %s\n",
3157 			       c.devices[i].path);
3158 			return;
3159 		}
3160 	}
3161 }
3162 
3163 #else
3164 
fix_wp_sit_alignment(struct f2fs_sb_info * UNUSED (sbi))3165 static void fix_wp_sit_alignment(struct f2fs_sb_info *UNUSED(sbi))
3166 {
3167 	return;
3168 }
3169 
3170 #endif
3171 
3172 /*
3173  * Check and fix consistency with write pointers at the beginning of
3174  * fsck so that following writes by fsck do not fail.
3175  */
fsck_chk_and_fix_write_pointers(struct f2fs_sb_info * sbi)3176 void fsck_chk_and_fix_write_pointers(struct f2fs_sb_info *sbi)
3177 {
3178 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
3179 
3180 	if (c.zoned_model != F2FS_ZONED_HM)
3181 		return;
3182 
3183 	if (check_curseg_offsets(sbi) && c.fix_on) {
3184 		fix_curseg_info(sbi);
3185 		fsck->chk.wp_fixed = 1;
3186 	}
3187 
3188 	fix_wp_sit_alignment(sbi);
3189 }
3190 
fsck_chk_curseg_info(struct f2fs_sb_info * sbi)3191 int fsck_chk_curseg_info(struct f2fs_sb_info *sbi)
3192 {
3193 	struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
3194 	struct curseg_info *curseg;
3195 	struct seg_entry *se;
3196 	struct f2fs_summary_block *sum_blk;
3197 	int i, ret = 0;
3198 
3199 	for (i = 0; i < NO_CHECK_TYPE; i++) {
3200 		curseg = CURSEG_I(sbi, i);
3201 		se = get_seg_entry(sbi, curseg->segno);
3202 		sum_blk = curseg->sum_blk;
3203 
3204 		if ((get_sb(feature) & cpu_to_le32(F2FS_FEATURE_RO)) &&
3205 			(i != CURSEG_HOT_DATA && i != CURSEG_HOT_NODE))
3206 			continue;
3207 
3208 		if (se->type != i) {
3209 			ASSERT_MSG("Incorrect curseg [%d]: segno [0x%x] "
3210 				   "type(SIT) [%d]", i, curseg->segno,
3211 				   se->type);
3212 			if (c.fix_on || c.preen_mode)
3213 				se->type = i;
3214 			ret = -1;
3215 		}
3216 		if (i <= CURSEG_COLD_DATA && IS_SUM_DATA_SEG(sum_blk->footer)) {
3217 			continue;
3218 		} else if (i > CURSEG_COLD_DATA && IS_SUM_NODE_SEG(sum_blk->footer)) {
3219 			continue;
3220 		} else {
3221 			ASSERT_MSG("Incorrect curseg [%d]: segno [0x%x] "
3222 				   "type(SSA) [%d]", i, curseg->segno,
3223 				   sum_blk->footer.entry_type);
3224 			if (c.fix_on || c.preen_mode)
3225 				sum_blk->footer.entry_type =
3226 					i <= CURSEG_COLD_DATA ?
3227 					SUM_TYPE_DATA : SUM_TYPE_NODE;
3228 			ret = -1;
3229 		}
3230 	}
3231 
3232 	return ret;
3233 }
3234 
fsck_verify(struct f2fs_sb_info * sbi)3235 int fsck_verify(struct f2fs_sb_info *sbi)
3236 {
3237 	unsigned int i = 0;
3238 	int ret = 0;
3239 	int force = 0;
3240 	u32 nr_unref_nid = 0;
3241 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
3242 	struct hard_link_node *node = NULL;
3243 	bool verify_failed = false;
3244 	uint64_t max_blks, data_secs, node_secs, free_blks;
3245 
3246 	if (c.show_file_map)
3247 		return 0;
3248 
3249 	printf("\n");
3250 
3251 	if (c.zoned_model == F2FS_ZONED_HM) {
3252 		printf("[FSCK] Write pointers consistency                    ");
3253 		if (fsck->chk.wp_inconsistent_zones == 0x0) {
3254 			printf(" [Ok..]\n");
3255 		} else {
3256 			printf(" [Fail] [0x%x]\n",
3257 			       fsck->chk.wp_inconsistent_zones);
3258 			verify_failed = true;
3259 		}
3260 
3261 		if (fsck->chk.wp_fixed && c.fix_on)
3262 			force = 1;
3263 	}
3264 
3265 	if (c.feature & cpu_to_le32(F2FS_FEATURE_LOST_FOUND)) {
3266 		for (i = 0; i < fsck->nr_nat_entries; i++)
3267 			if (f2fs_test_bit(i, fsck->nat_area_bitmap) != 0)
3268 				break;
3269 		if (i < fsck->nr_nat_entries) {
3270 			i = fsck_reconnect_file(sbi);
3271 			printf("[FSCK] Reconnect %u files to lost+found\n", i);
3272 		}
3273 	}
3274 
3275 	for (i = 0; i < fsck->nr_nat_entries; i++) {
3276 		if (f2fs_test_bit(i, fsck->nat_area_bitmap) != 0) {
3277 			struct node_info ni;
3278 
3279 			get_node_info(sbi, i, &ni);
3280 			printf("NID[0x%x] is unreachable, blkaddr:0x%x\n",
3281 							i, ni.blk_addr);
3282 			nr_unref_nid++;
3283 		}
3284 	}
3285 
3286 	if (fsck->hard_link_list_head != NULL) {
3287 		node = fsck->hard_link_list_head;
3288 		while (node) {
3289 			printf("NID[0x%x] has [0x%x] more unreachable links\n",
3290 					node->nid, node->links);
3291 			node = node->next;
3292 		}
3293 		c.bug_on = 1;
3294 	}
3295 
3296 	data_secs = round_up(sbi->total_valid_node_count, BLKS_PER_SEC(sbi));
3297 	node_secs = round_up(sbi->total_valid_block_count -
3298 				sbi->total_valid_node_count, BLKS_PER_SEC(sbi));
3299 	free_blks = (sbi->total_sections - data_secs - node_secs) *
3300 							BLKS_PER_SEC(sbi);
3301 	max_blks = SM_I(sbi)->main_blkaddr + (data_secs + node_secs) *
3302 							BLKS_PER_SEC(sbi);
3303 	printf("[FSCK] Max image size: %"PRIu64" MB, Free space: %"PRIu64" MB\n",
3304 						max_blks >> 8, free_blks >> 8);
3305 	printf("[FSCK] Unreachable nat entries                       ");
3306 	if (nr_unref_nid == 0x0) {
3307 		printf(" [Ok..] [0x%x]\n", nr_unref_nid);
3308 	} else {
3309 		printf(" [Fail] [0x%x]\n", nr_unref_nid);
3310 		verify_failed = true;
3311 	}
3312 
3313 	printf("[FSCK] SIT valid block bitmap checking                ");
3314 	if (memcmp(fsck->sit_area_bitmap, fsck->main_area_bitmap,
3315 					fsck->sit_area_bitmap_sz) == 0x0) {
3316 		printf("[Ok..]\n");
3317 	} else {
3318 		printf("[Fail]\n");
3319 		verify_failed = true;
3320 	}
3321 
3322 	printf("[FSCK] Hard link checking for regular file           ");
3323 	if (fsck->hard_link_list_head == NULL) {
3324 		printf(" [Ok..] [0x%x]\n", fsck->chk.multi_hard_link_files);
3325 	} else {
3326 		printf(" [Fail] [0x%x]\n", fsck->chk.multi_hard_link_files);
3327 		verify_failed = true;
3328 	}
3329 
3330 	printf("[FSCK] valid_block_count matching with CP            ");
3331 	if (sbi->total_valid_block_count == fsck->chk.valid_blk_cnt) {
3332 		printf(" [Ok..] [0x%x]\n", (u32)fsck->chk.valid_blk_cnt);
3333 	} else {
3334 		printf(" [Fail] [0x%x]\n", (u32)fsck->chk.valid_blk_cnt);
3335 		verify_failed = true;
3336 	}
3337 
3338 	printf("[FSCK] valid_node_count matching with CP (de lookup) ");
3339 	if (sbi->total_valid_node_count == fsck->chk.valid_node_cnt) {
3340 		printf(" [Ok..] [0x%x]\n", fsck->chk.valid_node_cnt);
3341 	} else {
3342 		printf(" [Fail] [0x%x]\n", fsck->chk.valid_node_cnt);
3343 		verify_failed = true;
3344 	}
3345 
3346 	printf("[FSCK] valid_node_count matching with CP (nat lookup)");
3347 	if (sbi->total_valid_node_count == fsck->chk.valid_nat_entry_cnt) {
3348 		printf(" [Ok..] [0x%x]\n", fsck->chk.valid_nat_entry_cnt);
3349 	} else {
3350 		printf(" [Fail] [0x%x]\n", fsck->chk.valid_nat_entry_cnt);
3351 		verify_failed = true;
3352 	}
3353 
3354 	printf("[FSCK] valid_inode_count matched with CP             ");
3355 	if (sbi->total_valid_inode_count == fsck->chk.valid_inode_cnt) {
3356 		printf(" [Ok..] [0x%x]\n", fsck->chk.valid_inode_cnt);
3357 	} else {
3358 		printf(" [Fail] [0x%x]\n", fsck->chk.valid_inode_cnt);
3359 		verify_failed = true;
3360 	}
3361 
3362 	printf("[FSCK] free segment_count matched with CP            ");
3363 	if (le32_to_cpu(F2FS_CKPT(sbi)->free_segment_count) ==
3364 						fsck->chk.sit_free_segs) {
3365 		printf(" [Ok..] [0x%x]\n", fsck->chk.sit_free_segs);
3366 	} else {
3367 		printf(" [Fail] [0x%x]\n", fsck->chk.sit_free_segs);
3368 		verify_failed = true;
3369 	}
3370 
3371 	printf("[FSCK] next block offset is free                     ");
3372 	if (check_curseg_offsets(sbi) == 0) {
3373 		printf(" [Ok..]\n");
3374 	} else {
3375 		printf(" [Fail]\n");
3376 		verify_failed = true;
3377 	}
3378 
3379 	printf("[FSCK] fixing SIT types\n");
3380 	if (check_sit_types(sbi) != 0)
3381 		force = 1;
3382 
3383 	printf("[FSCK] other corrupted bugs                          ");
3384 	if (c.bug_on == 0) {
3385 		printf(" [Ok..]\n");
3386 	} else {
3387 		printf(" [Fail]\n");
3388 		ret = EXIT_ERR_CODE;
3389 	}
3390 
3391 	if (verify_failed) {
3392 		ret = EXIT_ERR_CODE;
3393 		c.bug_on = 1;
3394 	}
3395 
3396 #ifndef WITH_ANDROID
3397 	if (nr_unref_nid && !c.ro) {
3398 		char ans[255] = {0};
3399 		int res;
3400 
3401 		printf("\nDo you want to restore lost files into ./lost_found/? [Y/N] ");
3402 		res = scanf("%s", ans);
3403 		ASSERT(res >= 0);
3404 		if (!strcasecmp(ans, "y")) {
3405 			for (i = 0; i < fsck->nr_nat_entries; i++) {
3406 				if (f2fs_test_bit(i, fsck->nat_area_bitmap))
3407 					dump_node(sbi, i, 1);
3408 			}
3409 		}
3410 	}
3411 #endif
3412 
3413 	/* fix global metadata */
3414 	if (force || (c.fix_on && f2fs_dev_is_writable())) {
3415 		struct f2fs_checkpoint *cp = F2FS_CKPT(sbi);
3416 		struct f2fs_super_block *sb = F2FS_RAW_SUPER(sbi);
3417 
3418 		if (force || c.bug_on || c.bug_nat_bits || c.quota_fixed) {
3419 			/* flush nats to write_nit_bits below */
3420 			flush_journal_entries(sbi);
3421 			fix_hard_links(sbi);
3422 			fix_nat_entries(sbi);
3423 			rewrite_sit_area_bitmap(sbi);
3424 			fix_wp_sit_alignment(sbi);
3425 			fix_curseg_info(sbi);
3426 			fix_checksum(sbi);
3427 			fix_checkpoints(sbi);
3428 		} else if (is_set_ckpt_flags(cp, CP_FSCK_FLAG) ||
3429 			is_set_ckpt_flags(cp, CP_QUOTA_NEED_FSCK_FLAG)) {
3430 			write_checkpoints(sbi);
3431 		}
3432 
3433 		if (c.abnormal_stop)
3434 			memset(sb->s_stop_reason, 0, MAX_STOP_REASON);
3435 
3436 		if (c.fs_errors)
3437 			memset(sb->s_errors, 0, MAX_F2FS_ERRORS);
3438 
3439 		if (c.abnormal_stop || c.fs_errors)
3440 			update_superblock(sb, SB_MASK_ALL);
3441 
3442 		/* to return FSCK_ERROR_CORRECTED */
3443 		ret = 0;
3444 	}
3445 	return ret;
3446 }
3447 
fsck_free(struct f2fs_sb_info * sbi)3448 void fsck_free(struct f2fs_sb_info *sbi)
3449 {
3450 	struct f2fs_fsck *fsck = F2FS_FSCK(sbi);
3451 
3452 	if (fsck->qctx)
3453 		quota_release_context(&fsck->qctx);
3454 
3455 	if (fsck->main_area_bitmap)
3456 		free(fsck->main_area_bitmap);
3457 
3458 	if (fsck->nat_area_bitmap)
3459 		free(fsck->nat_area_bitmap);
3460 
3461 	if (fsck->sit_area_bitmap)
3462 		free(fsck->sit_area_bitmap);
3463 
3464 	if (fsck->entries)
3465 		free(fsck->entries);
3466 
3467 	if (tree_mark)
3468 		free(tree_mark);
3469 
3470 	while (fsck->dentry) {
3471 		struct f2fs_dentry *dentry = fsck->dentry;
3472 
3473 		fsck->dentry = fsck->dentry->next;
3474 		free(dentry);
3475 	}
3476 }
3477