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