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