]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
Update bcachefs sources to 63924135a1 bcachefs: Have fsck check for stripe pointers...
[bcachefs-tools-debian] / libbcachefs / fsck.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "bkey_buf.h"
5 #include "btree_update.h"
6 #include "dirent.h"
7 #include "error.h"
8 #include "fs-common.h"
9 #include "fsck.h"
10 #include "inode.h"
11 #include "keylist.h"
12 #include "super.h"
13 #include "xattr.h"
14
15 #include <linux/dcache.h> /* struct qstr */
16 #include <linux/generic-radix-tree.h>
17
18 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
19
20 static s64 bch2_count_inode_sectors(struct btree_trans *trans, u64 inum)
21 {
22         struct btree_iter *iter;
23         struct bkey_s_c k;
24         u64 sectors = 0;
25         int ret;
26
27         for_each_btree_key(trans, iter, BTREE_ID_extents,
28                            POS(inum, 0), 0, k, ret) {
29                 if (k.k->p.inode != inum)
30                         break;
31
32                 if (bkey_extent_is_allocation(k.k))
33                         sectors += k.k->size;
34         }
35
36         bch2_trans_iter_free(trans, iter);
37
38         return ret ?: sectors;
39 }
40
41 static int __remove_dirent(struct btree_trans *trans,
42                            struct bkey_s_c_dirent dirent)
43 {
44         struct bch_fs *c = trans->c;
45         struct qstr name;
46         struct bch_inode_unpacked dir_inode;
47         struct bch_hash_info dir_hash_info;
48         u64 dir_inum = dirent.k->p.inode;
49         int ret;
50         char *buf;
51
52         name.len = bch2_dirent_name_bytes(dirent);
53         buf = bch2_trans_kmalloc(trans, name.len + 1);
54         if (IS_ERR(buf))
55                 return PTR_ERR(buf);
56
57         memcpy(buf, dirent.v->d_name, name.len);
58         buf[name.len] = '\0';
59         name.name = buf;
60
61         ret = __bch2_inode_find_by_inum_trans(trans, dir_inum, &dir_inode, 0);
62         if (ret && ret != -EINTR)
63                 bch_err(c, "remove_dirent: err %i looking up directory inode", ret);
64         if (ret)
65                 return ret;
66
67         dir_hash_info = bch2_hash_info_init(c, &dir_inode);
68
69         ret = bch2_hash_delete(trans, bch2_dirent_hash_desc,
70                                &dir_hash_info, dir_inum, &name);
71         if (ret && ret != -EINTR)
72                 bch_err(c, "remove_dirent: err %i deleting dirent", ret);
73         if (ret)
74                 return ret;
75
76         return 0;
77 }
78
79 static int remove_dirent(struct btree_trans *trans,
80                          struct bkey_s_c_dirent dirent)
81 {
82         return __bch2_trans_do(trans, NULL, NULL,
83                                BTREE_INSERT_NOFAIL|
84                                BTREE_INSERT_LAZY_RW,
85                                __remove_dirent(trans, dirent));
86 }
87
88 static int reattach_inode(struct bch_fs *c,
89                           struct bch_inode_unpacked *lostfound_inode,
90                           u64 inum)
91 {
92         struct bch_inode_unpacked dir_u, inode_u;
93         char name_buf[20];
94         struct qstr name;
95         int ret;
96
97         snprintf(name_buf, sizeof(name_buf), "%llu", inum);
98         name = (struct qstr) QSTR(name_buf);
99
100         ret = bch2_trans_do(c, NULL, NULL,
101                             BTREE_INSERT_LAZY_RW,
102                 bch2_link_trans(&trans, lostfound_inode->bi_inum,
103                                 inum, &dir_u, &inode_u, &name));
104         if (ret)
105                 bch_err(c, "error %i reattaching inode %llu", ret, inum);
106
107         return ret;
108 }
109
110 struct inode_walker {
111         bool                    first_this_inode;
112         bool                    have_inode;
113         u64                     cur_inum;
114         struct bch_inode_unpacked inode;
115 };
116
117 static struct inode_walker inode_walker_init(void)
118 {
119         return (struct inode_walker) {
120                 .cur_inum       = -1,
121                 .have_inode     = false,
122         };
123 }
124
125 static int walk_inode(struct btree_trans *trans,
126                       struct inode_walker *w, u64 inum)
127 {
128         if (inum != w->cur_inum) {
129                 int ret = __bch2_inode_find_by_inum_trans(trans, inum,
130                                                           &w->inode, 0);
131
132                 if (ret && ret != -ENOENT)
133                         return ret;
134
135                 w->have_inode   = !ret;
136                 w->cur_inum     = inum;
137                 w->first_this_inode = true;
138         } else {
139                 w->first_this_inode = false;
140         }
141
142         return 0;
143 }
144
145 struct hash_check {
146         struct bch_hash_info    info;
147
148         /* start of current chain of hash collisions: */
149         struct btree_iter       *chain;
150
151         /* next offset in current chain of hash collisions: */
152         u64                     chain_end;
153 };
154
155 static void hash_check_init(struct hash_check *h)
156 {
157         h->chain = NULL;
158         h->chain_end = 0;
159 }
160
161 static void hash_stop_chain(struct btree_trans *trans,
162                             struct hash_check *h)
163 {
164         if (h->chain)
165                 bch2_trans_iter_free(trans, h->chain);
166         h->chain = NULL;
167 }
168
169 static void hash_check_set_inode(struct btree_trans *trans,
170                                  struct hash_check *h,
171                                  const struct bch_inode_unpacked *bi)
172 {
173         h->info = bch2_hash_info_init(trans->c, bi);
174         hash_stop_chain(trans, h);
175 }
176
177 static int hash_redo_key(const struct bch_hash_desc desc,
178                          struct btree_trans *trans, struct hash_check *h,
179                          struct btree_iter *k_iter, struct bkey_s_c k,
180                          u64 hashed)
181 {
182         struct bkey_i delete;
183         struct bkey_i *tmp;
184
185         tmp = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
186         if (IS_ERR(tmp))
187                 return PTR_ERR(tmp);
188
189         bkey_reassemble(tmp, k);
190
191         bkey_init(&delete.k);
192         delete.k.p = k_iter->pos;
193         bch2_trans_update(trans, k_iter, &delete, 0);
194
195         return bch2_hash_set(trans, desc, &h->info, k_iter->pos.inode,
196                              tmp, 0);
197 }
198
199 static int fsck_hash_delete_at(struct btree_trans *trans,
200                                const struct bch_hash_desc desc,
201                                struct bch_hash_info *info,
202                                struct btree_iter *iter)
203 {
204         int ret;
205 retry:
206         ret   = bch2_hash_delete_at(trans, desc, info, iter) ?:
207                 bch2_trans_commit(trans, NULL, NULL,
208                                   BTREE_INSERT_NOFAIL|
209                                   BTREE_INSERT_LAZY_RW);
210         if (ret == -EINTR) {
211                 ret = bch2_btree_iter_traverse(iter);
212                 if (!ret)
213                         goto retry;
214         }
215
216         return ret;
217 }
218
219 static int hash_check_duplicates(struct btree_trans *trans,
220                         const struct bch_hash_desc desc, struct hash_check *h,
221                         struct btree_iter *k_iter, struct bkey_s_c k)
222 {
223         struct bch_fs *c = trans->c;
224         struct btree_iter *iter;
225         struct bkey_s_c k2;
226         char buf[200];
227         int ret = 0;
228
229         if (!bkey_cmp(h->chain->pos, k_iter->pos))
230                 return 0;
231
232         iter = bch2_trans_copy_iter(trans, h->chain);
233
234         for_each_btree_key_continue(iter, 0, k2, ret) {
235                 if (bkey_cmp(k2.k->p, k.k->p) >= 0)
236                         break;
237
238                 if (fsck_err_on(k2.k->type == desc.key_type &&
239                                 !desc.cmp_bkey(k, k2), c,
240                                 "duplicate hash table keys:\n%s",
241                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
242                                                        k), buf))) {
243                         ret = fsck_hash_delete_at(trans, desc, &h->info, k_iter);
244                         if (ret)
245                                 return ret;
246                         ret = 1;
247                         break;
248                 }
249         }
250 fsck_err:
251         bch2_trans_iter_free(trans, iter);
252         return ret;
253 }
254
255 static void hash_set_chain_start(struct btree_trans *trans,
256                         const struct bch_hash_desc desc,
257                         struct hash_check *h,
258                         struct btree_iter *k_iter, struct bkey_s_c k)
259 {
260         bool hole = (k.k->type != KEY_TYPE_hash_whiteout &&
261                      k.k->type != desc.key_type);
262
263         if (hole || k.k->p.offset > h->chain_end + 1)
264                 hash_stop_chain(trans, h);
265
266         if (!hole) {
267                 if (!h->chain)
268                         h->chain = bch2_trans_copy_iter(trans, k_iter);
269
270                 h->chain_end = k.k->p.offset;
271         }
272 }
273
274 static bool key_has_correct_hash(struct btree_trans *trans,
275                         const struct bch_hash_desc desc,
276                         struct hash_check *h,
277                         struct btree_iter *k_iter, struct bkey_s_c k)
278 {
279         u64 hash;
280
281         hash_set_chain_start(trans, desc, h, k_iter, k);
282
283         if (k.k->type != desc.key_type)
284                 return true;
285
286         hash = desc.hash_bkey(&h->info, k);
287
288         return hash >= h->chain->pos.offset &&
289                 hash <= k.k->p.offset;
290 }
291
292 static int hash_check_key(struct btree_trans *trans,
293                         const struct bch_hash_desc desc, struct hash_check *h,
294                         struct btree_iter *k_iter, struct bkey_s_c k)
295 {
296         struct bch_fs *c = trans->c;
297         char buf[200];
298         u64 hashed;
299         int ret = 0;
300
301         hash_set_chain_start(trans, desc, h, k_iter, k);
302
303         if (k.k->type != desc.key_type)
304                 return 0;
305
306         hashed = desc.hash_bkey(&h->info, k);
307
308         if (fsck_err_on(hashed < h->chain->pos.offset ||
309                         hashed > k.k->p.offset, c,
310                         "hash table key at wrong offset: btree %u, %llu, "
311                         "hashed to %llu chain starts at %llu\n%s",
312                         desc.btree_id, k.k->p.offset,
313                         hashed, h->chain->pos.offset,
314                         (bch2_bkey_val_to_text(&PBUF(buf), c, k), buf))) {
315                 ret = __bch2_trans_do(trans, NULL, NULL,
316                                       BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
317                         hash_redo_key(desc, trans, h, k_iter, k, hashed));
318                 if (ret) {
319                         bch_err(c, "hash_redo_key err %i", ret);
320                         return ret;
321                 }
322                 return 1;
323         }
324
325         ret = hash_check_duplicates(trans, desc, h, k_iter, k);
326 fsck_err:
327         return ret;
328 }
329
330 static int check_dirent_hash(struct btree_trans *trans, struct hash_check *h,
331                              struct btree_iter *iter, struct bkey_s_c *k)
332 {
333         struct bch_fs *c = trans->c;
334         struct bkey_i_dirent *d = NULL;
335         int ret = -EINVAL;
336         char buf[200];
337         unsigned len;
338         u64 hash;
339
340         if (key_has_correct_hash(trans, bch2_dirent_hash_desc, h, iter, *k))
341                 return 0;
342
343         len = bch2_dirent_name_bytes(bkey_s_c_to_dirent(*k));
344         BUG_ON(!len);
345
346         memcpy(buf, bkey_s_c_to_dirent(*k).v->d_name, len);
347         buf[len] = '\0';
348
349         d = kmalloc(bkey_bytes(k->k), GFP_KERNEL);
350         if (!d) {
351                 bch_err(c, "memory allocation failure");
352                 return -ENOMEM;
353         }
354
355         bkey_reassemble(&d->k_i, *k);
356
357         do {
358                 --len;
359                 if (!len)
360                         goto err_redo;
361
362                 d->k.u64s = BKEY_U64s + dirent_val_u64s(len);
363
364                 BUG_ON(bkey_val_bytes(&d->k) <
365                        offsetof(struct bch_dirent, d_name) + len);
366
367                 memset(d->v.d_name + len, 0,
368                        bkey_val_bytes(&d->k) -
369                        offsetof(struct bch_dirent, d_name) - len);
370
371                 hash = bch2_dirent_hash_desc.hash_bkey(&h->info,
372                                                 bkey_i_to_s_c(&d->k_i));
373         } while (hash < h->chain->pos.offset ||
374                  hash > k->k->p.offset);
375
376         if (fsck_err(c, "dirent with junk at end, was %s (%zu) now %s (%u)",
377                      buf, strlen(buf), d->v.d_name, len)) {
378                 ret = __bch2_trans_do(trans, NULL, NULL,
379                                       BTREE_INSERT_NOFAIL|
380                                       BTREE_INSERT_LAZY_RW,
381                         (bch2_trans_update(trans, iter, &d->k_i, 0), 0));
382                 if (ret)
383                         goto err;
384
385                 *k = bch2_btree_iter_peek(iter);
386
387                 BUG_ON(k->k->type != KEY_TYPE_dirent);
388         }
389 err:
390 fsck_err:
391         kfree(d);
392         return ret;
393 err_redo:
394         hash = bch2_dirent_hash_desc.hash_bkey(&h->info, *k);
395
396         if (fsck_err(c, "cannot fix dirent by removing trailing garbage %s (%zu)\n"
397                      "hash table key at wrong offset: btree %u, offset %llu, "
398                      "hashed to %llu chain starts at %llu\n%s",
399                      buf, strlen(buf), BTREE_ID_dirents,
400                      k->k->p.offset, hash, h->chain->pos.offset,
401                      (bch2_bkey_val_to_text(&PBUF(buf), c,
402                                             *k), buf))) {
403                 ret = __bch2_trans_do(trans, NULL, NULL,
404                                       BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
405                         hash_redo_key(bch2_dirent_hash_desc, trans,
406                                       h, iter, *k, hash));
407                 if (ret)
408                         bch_err(c, "hash_redo_key err %i", ret);
409                 else
410                         ret = 1;
411         }
412
413         goto err;
414 }
415
416 static int bch2_inode_truncate(struct bch_fs *c, u64 inode_nr, u64 new_size)
417 {
418         return bch2_btree_delete_range(c, BTREE_ID_extents,
419                         POS(inode_nr, round_up(new_size, block_bytes(c)) >> 9),
420                         POS(inode_nr + 1, 0), NULL);
421 }
422
423 static int bch2_fix_overlapping_extent(struct btree_trans *trans,
424                                        struct btree_iter *iter,
425                                        struct bkey_s_c k, struct bpos cut_at)
426 {
427         struct btree_iter *u_iter;
428         struct bkey_i *u;
429         int ret;
430
431         u = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
432         ret = PTR_ERR_OR_ZERO(u);
433         if (ret)
434                 return ret;
435
436         bkey_reassemble(u, k);
437         bch2_cut_front(cut_at, u);
438
439         u_iter = bch2_trans_copy_iter(trans, iter);
440
441         /*
442          * We don't want to go through the
443          * extent_handle_overwrites path:
444          */
445         u_iter->flags &= ~BTREE_ITER_IS_EXTENTS;
446         bch2_btree_iter_set_pos(u_iter, u->k.p);
447
448         /*
449          * XXX: this is going to leave disk space
450          * accounting slightly wrong
451          */
452         ret = bch2_trans_update(trans, u_iter, u, 0);
453         bch2_trans_iter_put(trans, u_iter);
454         return ret;
455 }
456
457 /*
458  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
459  * that i_size an i_sectors are consistent
460  */
461 noinline_for_stack
462 static int check_extents(struct bch_fs *c)
463 {
464         struct inode_walker w = inode_walker_init();
465         struct btree_trans trans;
466         struct btree_iter *iter;
467         struct bkey_s_c k;
468         struct bkey_buf prev;
469         u64 i_sectors;
470         int ret = 0;
471
472         bch2_bkey_buf_init(&prev);
473         prev.k->k = KEY(0, 0, 0);
474         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
475
476         bch_verbose(c, "checking extents");
477
478         iter = bch2_trans_get_iter(&trans, BTREE_ID_extents,
479                                    POS(BCACHEFS_ROOT_INO, 0),
480                                    BTREE_ITER_INTENT);
481 retry:
482         for_each_btree_key_continue(iter, 0, k, ret) {
483                 /*
484                  * due to retry errors we might see the same extent twice:
485                  */
486                 if (bkey_cmp(prev.k->k.p, k.k->p) &&
487                     bkey_cmp(prev.k->k.p, bkey_start_pos(k.k)) > 0) {
488                         char buf1[200];
489                         char buf2[200];
490
491                         bch2_bkey_val_to_text(&PBUF(buf1), c, bkey_i_to_s_c(prev.k));
492                         bch2_bkey_val_to_text(&PBUF(buf2), c, k);
493
494                         if (fsck_err(c, "overlapping extents:\n%s\n%s", buf1, buf2)) {
495                                 ret = __bch2_trans_do(&trans, NULL, NULL,
496                                                       BTREE_INSERT_NOFAIL|
497                                                       BTREE_INSERT_LAZY_RW,
498                                                 bch2_fix_overlapping_extent(&trans,
499                                                                 iter, k, prev.k->k.p));
500                                 if (ret)
501                                         goto err;
502                         }
503                 }
504                 bch2_bkey_buf_reassemble(&prev, c, k);
505
506                 ret = walk_inode(&trans, &w, k.k->p.inode);
507                 if (ret)
508                         break;
509
510                 if (fsck_err_on(!w.have_inode, c,
511                         "extent type %u for missing inode %llu",
512                         k.k->type, k.k->p.inode) ||
513                     fsck_err_on(w.have_inode &&
514                         !S_ISREG(w.inode.bi_mode) && !S_ISLNK(w.inode.bi_mode), c,
515                         "extent type %u for non regular file, inode %llu mode %o",
516                         k.k->type, k.k->p.inode, w.inode.bi_mode)) {
517                         bch2_trans_unlock(&trans);
518
519                         ret = bch2_inode_truncate(c, k.k->p.inode, 0);
520                         if (ret)
521                                 goto err;
522                         continue;
523                 }
524
525                 if (fsck_err_on(w.first_this_inode &&
526                         w.have_inode &&
527                         !(w.inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY) &&
528                         w.inode.bi_sectors !=
529                         (i_sectors = bch2_count_inode_sectors(&trans, w.cur_inum)),
530                         c, "inode %llu has incorrect i_sectors: got %llu, should be %llu",
531                         w.inode.bi_inum,
532                         w.inode.bi_sectors, i_sectors)) {
533                         struct bkey_inode_buf p;
534
535                         w.inode.bi_sectors = i_sectors;
536
537                         bch2_trans_unlock(&trans);
538
539                         bch2_inode_pack(c, &p, &w.inode);
540
541                         ret = bch2_btree_insert(c, BTREE_ID_inodes,
542                                                 &p.inode.k_i, NULL, NULL,
543                                                 BTREE_INSERT_NOFAIL|
544                                                 BTREE_INSERT_LAZY_RW);
545                         if (ret) {
546                                 bch_err(c, "error in fsck: error %i updating inode", ret);
547                                 goto err;
548                         }
549
550                         /* revalidate iterator: */
551                         k = bch2_btree_iter_peek(iter);
552                 }
553
554                 if (fsck_err_on(w.have_inode &&
555                         !(w.inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
556                         k.k->type != KEY_TYPE_reservation &&
557                         k.k->p.offset > round_up(w.inode.bi_size, block_bytes(c)) >> 9, c,
558                         "extent type %u offset %llu past end of inode %llu, i_size %llu",
559                         k.k->type, k.k->p.offset, k.k->p.inode, w.inode.bi_size)) {
560                         bch2_trans_unlock(&trans);
561
562                         ret = bch2_inode_truncate(c, k.k->p.inode,
563                                                   w.inode.bi_size);
564                         if (ret)
565                                 goto err;
566                         continue;
567                 }
568         }
569 err:
570 fsck_err:
571         if (ret == -EINTR)
572                 goto retry;
573         bch2_bkey_buf_exit(&prev, c);
574         return bch2_trans_exit(&trans) ?: ret;
575 }
576
577 /*
578  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
579  * validate d_type
580  */
581 noinline_for_stack
582 static int check_dirents(struct bch_fs *c)
583 {
584         struct inode_walker w = inode_walker_init();
585         struct hash_check h;
586         struct btree_trans trans;
587         struct btree_iter *iter;
588         struct bkey_s_c k;
589         unsigned name_len;
590         char buf[200];
591         int ret = 0;
592
593         bch_verbose(c, "checking dirents");
594
595         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
596
597         hash_check_init(&h);
598
599         iter = bch2_trans_get_iter(&trans, BTREE_ID_dirents,
600                                    POS(BCACHEFS_ROOT_INO, 0), 0);
601 retry:
602         for_each_btree_key_continue(iter, 0, k, ret) {
603                 struct bkey_s_c_dirent d;
604                 struct bch_inode_unpacked target;
605                 bool have_target;
606                 u64 d_inum;
607
608                 ret = walk_inode(&trans, &w, k.k->p.inode);
609                 if (ret)
610                         break;
611
612                 if (fsck_err_on(!w.have_inode, c,
613                                 "dirent in nonexisting directory:\n%s",
614                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
615                                                        k), buf)) ||
616                     fsck_err_on(!S_ISDIR(w.inode.bi_mode), c,
617                                 "dirent in non directory inode type %u:\n%s",
618                                 mode_to_type(w.inode.bi_mode),
619                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
620                                                        k), buf))) {
621                         ret = bch2_btree_delete_at(&trans, iter, 0);
622                         if (ret)
623                                 goto err;
624                         continue;
625                 }
626
627                 if (w.first_this_inode && w.have_inode)
628                         hash_check_set_inode(&trans, &h, &w.inode);
629
630                 ret = check_dirent_hash(&trans, &h, iter, &k);
631                 if (ret > 0) {
632                         ret = 0;
633                         continue;
634                 }
635                 if (ret)
636                         goto fsck_err;
637
638                 if (ret)
639                         goto fsck_err;
640
641                 if (k.k->type != KEY_TYPE_dirent)
642                         continue;
643
644                 d = bkey_s_c_to_dirent(k);
645                 d_inum = le64_to_cpu(d.v->d_inum);
646
647                 name_len = bch2_dirent_name_bytes(d);
648
649                 if (fsck_err_on(!name_len, c, "empty dirent") ||
650                     fsck_err_on(name_len == 1 &&
651                                 !memcmp(d.v->d_name, ".", 1), c,
652                                 ". dirent") ||
653                     fsck_err_on(name_len == 2 &&
654                                 !memcmp(d.v->d_name, "..", 2), c,
655                                 ".. dirent") ||
656                     fsck_err_on(name_len == 2 &&
657                                 !memcmp(d.v->d_name, "..", 2), c,
658                                 ".. dirent") ||
659                     fsck_err_on(memchr(d.v->d_name, '/', name_len), c,
660                                 "dirent name has invalid chars")) {
661                         ret = remove_dirent(&trans, d);
662                         if (ret)
663                                 goto err;
664                         continue;
665                 }
666
667                 if (fsck_err_on(d_inum == d.k->p.inode, c,
668                                 "dirent points to own directory:\n%s",
669                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
670                                                        k), buf))) {
671                         ret = remove_dirent(&trans, d);
672                         if (ret)
673                                 goto err;
674                         continue;
675                 }
676
677                 ret = __bch2_inode_find_by_inum_trans(&trans, d_inum, &target, 0);
678                 if (ret && ret != -ENOENT)
679                         break;
680
681                 have_target = !ret;
682                 ret = 0;
683
684                 if (fsck_err_on(!have_target, c,
685                                 "dirent points to missing inode:\n%s",
686                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
687                                                        k), buf))) {
688                         ret = remove_dirent(&trans, d);
689                         if (ret)
690                                 goto err;
691                         continue;
692                 }
693
694                 if (fsck_err_on(have_target &&
695                                 d.v->d_type !=
696                                 mode_to_type(target.bi_mode), c,
697                                 "incorrect d_type: should be %u:\n%s",
698                                 mode_to_type(target.bi_mode),
699                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
700                                                        k), buf))) {
701                         struct bkey_i_dirent *n;
702
703                         n = kmalloc(bkey_bytes(d.k), GFP_KERNEL);
704                         if (!n) {
705                                 ret = -ENOMEM;
706                                 goto err;
707                         }
708
709                         bkey_reassemble(&n->k_i, d.s_c);
710                         n->v.d_type = mode_to_type(target.bi_mode);
711
712                         ret = __bch2_trans_do(&trans, NULL, NULL,
713                                               BTREE_INSERT_NOFAIL|
714                                               BTREE_INSERT_LAZY_RW,
715                                 (bch2_trans_update(&trans, iter, &n->k_i, 0), 0));
716                         kfree(n);
717                         if (ret)
718                                 goto err;
719
720                 }
721         }
722
723         hash_stop_chain(&trans, &h);
724 err:
725 fsck_err:
726         if (ret == -EINTR)
727                 goto retry;
728
729         return bch2_trans_exit(&trans) ?: ret;
730 }
731
732 /*
733  * Walk xattrs: verify that they all have a corresponding inode
734  */
735 noinline_for_stack
736 static int check_xattrs(struct bch_fs *c)
737 {
738         struct inode_walker w = inode_walker_init();
739         struct hash_check h;
740         struct btree_trans trans;
741         struct btree_iter *iter;
742         struct bkey_s_c k;
743         int ret = 0;
744
745         bch_verbose(c, "checking xattrs");
746
747         hash_check_init(&h);
748
749         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
750
751         iter = bch2_trans_get_iter(&trans, BTREE_ID_xattrs,
752                                    POS(BCACHEFS_ROOT_INO, 0), 0);
753 retry:
754         for_each_btree_key_continue(iter, 0, k, ret) {
755                 ret = walk_inode(&trans, &w, k.k->p.inode);
756                 if (ret)
757                         break;
758
759                 if (fsck_err_on(!w.have_inode, c,
760                                 "xattr for missing inode %llu",
761                                 k.k->p.inode)) {
762                         ret = bch2_btree_delete_at(&trans, iter, 0);
763                         if (ret)
764                                 goto err;
765                         continue;
766                 }
767
768                 if (w.first_this_inode && w.have_inode)
769                         hash_check_set_inode(&trans, &h, &w.inode);
770
771                 ret = hash_check_key(&trans, bch2_xattr_hash_desc,
772                                      &h, iter, k);
773                 if (ret)
774                         goto fsck_err;
775         }
776 err:
777 fsck_err:
778         if (ret == -EINTR)
779                 goto retry;
780         return bch2_trans_exit(&trans) ?: ret;
781 }
782
783 /* Get root directory, create if it doesn't exist: */
784 static int check_root(struct bch_fs *c, struct bch_inode_unpacked *root_inode)
785 {
786         struct bkey_inode_buf packed;
787         int ret;
788
789         bch_verbose(c, "checking root directory");
790
791         ret = bch2_trans_do(c, NULL, NULL, 0,
792                 __bch2_inode_find_by_inum_trans(&trans, BCACHEFS_ROOT_INO,
793                                                 root_inode, 0));
794         if (ret && ret != -ENOENT)
795                 return ret;
796
797         if (fsck_err_on(ret, c, "root directory missing"))
798                 goto create_root;
799
800         if (fsck_err_on(!S_ISDIR(root_inode->bi_mode), c,
801                         "root inode not a directory"))
802                 goto create_root;
803
804         return 0;
805 fsck_err:
806         return ret;
807 create_root:
808         bch2_inode_init(c, root_inode, 0, 0, S_IFDIR|0755,
809                         0, NULL);
810         root_inode->bi_inum = BCACHEFS_ROOT_INO;
811
812         bch2_inode_pack(c, &packed, root_inode);
813
814         return bch2_btree_insert(c, BTREE_ID_inodes, &packed.inode.k_i,
815                                  NULL, NULL,
816                                  BTREE_INSERT_NOFAIL|
817                                  BTREE_INSERT_LAZY_RW);
818 }
819
820 /* Get lost+found, create if it doesn't exist: */
821 static int check_lostfound(struct bch_fs *c,
822                            struct bch_inode_unpacked *root_inode,
823                            struct bch_inode_unpacked *lostfound_inode)
824 {
825         struct qstr lostfound = QSTR("lost+found");
826         struct bch_hash_info root_hash_info =
827                 bch2_hash_info_init(c, root_inode);
828         u64 inum;
829         int ret;
830
831         bch_verbose(c, "checking lost+found");
832
833         inum = bch2_dirent_lookup(c, BCACHEFS_ROOT_INO, &root_hash_info,
834                                  &lostfound);
835         if (!inum) {
836                 bch_notice(c, "creating lost+found");
837                 goto create_lostfound;
838         }
839
840         ret = bch2_trans_do(c, NULL, NULL, 0,
841                 __bch2_inode_find_by_inum_trans(&trans, inum, lostfound_inode, 0));
842         if (ret && ret != -ENOENT)
843                 return ret;
844
845         if (fsck_err_on(ret, c, "lost+found missing"))
846                 goto create_lostfound;
847
848         if (fsck_err_on(!S_ISDIR(lostfound_inode->bi_mode), c,
849                         "lost+found inode not a directory"))
850                 goto create_lostfound;
851
852         return 0;
853 fsck_err:
854         return ret;
855 create_lostfound:
856         bch2_inode_init_early(c, lostfound_inode);
857
858         ret = bch2_trans_do(c, NULL, NULL,
859                             BTREE_INSERT_NOFAIL|
860                             BTREE_INSERT_LAZY_RW,
861                 bch2_create_trans(&trans,
862                                   BCACHEFS_ROOT_INO, root_inode,
863                                   lostfound_inode, &lostfound,
864                                   0, 0, S_IFDIR|0700, 0, NULL, NULL));
865         if (ret)
866                 bch_err(c, "error creating lost+found: %i", ret);
867
868         return ret;
869 }
870
871 typedef GENRADIX(unsigned long) inode_bitmap;
872
873 static inline bool inode_bitmap_test(inode_bitmap *b, size_t nr)
874 {
875         unsigned long *w = genradix_ptr(b, nr / BITS_PER_LONG);
876         return w ? test_bit(nr & (BITS_PER_LONG - 1), w) : false;
877 }
878
879 static inline int inode_bitmap_set(inode_bitmap *b, size_t nr)
880 {
881         unsigned long *w = genradix_ptr_alloc(b, nr / BITS_PER_LONG, GFP_KERNEL);
882
883         if (!w)
884                 return -ENOMEM;
885
886         *w |= 1UL << (nr & (BITS_PER_LONG - 1));
887         return 0;
888 }
889
890 struct pathbuf {
891         size_t          nr;
892         size_t          size;
893
894         struct pathbuf_entry {
895                 u64     inum;
896                 u64     offset;
897         }               *entries;
898 };
899
900 static int path_down(struct pathbuf *p, u64 inum)
901 {
902         if (p->nr == p->size) {
903                 size_t new_size = max_t(size_t, 256UL, p->size * 2);
904                 void *n = krealloc(p->entries,
905                                    new_size * sizeof(p->entries[0]),
906                                    GFP_KERNEL);
907                 if (!n)
908                         return -ENOMEM;
909
910                 p->entries = n;
911                 p->size = new_size;
912         };
913
914         p->entries[p->nr++] = (struct pathbuf_entry) {
915                 .inum = inum,
916                 .offset = 0,
917         };
918         return 0;
919 }
920
921 noinline_for_stack
922 static int check_directory_structure(struct bch_fs *c,
923                                      struct bch_inode_unpacked *lostfound_inode)
924 {
925         inode_bitmap dirs_done;
926         struct pathbuf path = { 0, 0, NULL };
927         struct pathbuf_entry *e;
928         struct btree_trans trans;
929         struct btree_iter *iter;
930         struct bkey_s_c k;
931         struct bkey_s_c_dirent dirent;
932         bool had_unreachable;
933         u64 d_inum;
934         int ret = 0;
935
936         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
937
938         bch_verbose(c, "checking directory structure");
939
940         /* DFS: */
941 restart_dfs:
942         genradix_init(&dirs_done);
943         had_unreachable = false;
944
945         ret = inode_bitmap_set(&dirs_done, BCACHEFS_ROOT_INO);
946         if (ret) {
947                 bch_err(c, "memory allocation failure in inode_bitmap_set()");
948                 goto err;
949         }
950
951         ret = path_down(&path, BCACHEFS_ROOT_INO);
952         if (ret)
953                 goto err;
954
955         while (path.nr) {
956 next:
957                 e = &path.entries[path.nr - 1];
958
959                 if (e->offset == U64_MAX)
960                         goto up;
961
962                 for_each_btree_key(&trans, iter, BTREE_ID_dirents,
963                                    POS(e->inum, e->offset + 1), 0, k, ret) {
964                         if (k.k->p.inode != e->inum)
965                                 break;
966
967                         e->offset = k.k->p.offset;
968
969                         if (k.k->type != KEY_TYPE_dirent)
970                                 continue;
971
972                         dirent = bkey_s_c_to_dirent(k);
973
974                         if (dirent.v->d_type != DT_DIR)
975                                 continue;
976
977                         d_inum = le64_to_cpu(dirent.v->d_inum);
978
979                         if (fsck_err_on(inode_bitmap_test(&dirs_done, d_inum), c,
980                                         "directory %llu has multiple hardlinks",
981                                         d_inum)) {
982                                 ret = remove_dirent(&trans, dirent);
983                                 if (ret)
984                                         goto err;
985                                 continue;
986                         }
987
988                         ret = inode_bitmap_set(&dirs_done, d_inum);
989                         if (ret) {
990                                 bch_err(c, "memory allocation failure in inode_bitmap_set()");
991                                 goto err;
992                         }
993
994                         ret = path_down(&path, d_inum);
995                         if (ret) {
996                                 goto err;
997                         }
998
999                         ret = bch2_trans_iter_free(&trans, iter);
1000                         if (ret) {
1001                                 bch_err(c, "btree error %i in fsck", ret);
1002                                 goto err;
1003                         }
1004                         goto next;
1005                 }
1006                 ret = bch2_trans_iter_free(&trans, iter) ?: ret;
1007                 if (ret) {
1008                         bch_err(c, "btree error %i in fsck", ret);
1009                         goto err;
1010                 }
1011 up:
1012                 path.nr--;
1013         }
1014
1015         iter = bch2_trans_get_iter(&trans, BTREE_ID_inodes, POS_MIN, 0);
1016 retry:
1017         for_each_btree_key_continue(iter, 0, k, ret) {
1018                 if (k.k->type != KEY_TYPE_inode)
1019                         continue;
1020
1021                 if (!S_ISDIR(le16_to_cpu(bkey_s_c_to_inode(k).v->bi_mode)))
1022                         continue;
1023
1024                 ret = bch2_empty_dir_trans(&trans, k.k->p.inode);
1025                 if (ret == -EINTR)
1026                         goto retry;
1027                 if (!ret)
1028                         continue;
1029
1030                 if (fsck_err_on(!inode_bitmap_test(&dirs_done, k.k->p.offset), c,
1031                                 "unreachable directory found (inum %llu)",
1032                                 k.k->p.offset)) {
1033                         bch2_trans_unlock(&trans);
1034
1035                         ret = reattach_inode(c, lostfound_inode, k.k->p.offset);
1036                         if (ret) {
1037                                 goto err;
1038                         }
1039
1040                         had_unreachable = true;
1041                 }
1042         }
1043         bch2_trans_iter_free(&trans, iter);
1044         if (ret)
1045                 goto err;
1046
1047         if (had_unreachable) {
1048                 bch_info(c, "reattached unreachable directories, restarting pass to check for loops");
1049                 genradix_free(&dirs_done);
1050                 kfree(path.entries);
1051                 memset(&dirs_done, 0, sizeof(dirs_done));
1052                 memset(&path, 0, sizeof(path));
1053                 goto restart_dfs;
1054         }
1055 err:
1056 fsck_err:
1057         ret = bch2_trans_exit(&trans) ?: ret;
1058         genradix_free(&dirs_done);
1059         kfree(path.entries);
1060         return ret;
1061 }
1062
1063 struct nlink {
1064         u32     count;
1065         u32     dir_count;
1066 };
1067
1068 typedef GENRADIX(struct nlink) nlink_table;
1069
1070 static void inc_link(struct bch_fs *c, nlink_table *links,
1071                      u64 range_start, u64 *range_end,
1072                      u64 inum, bool dir)
1073 {
1074         struct nlink *link;
1075
1076         if (inum < range_start || inum >= *range_end)
1077                 return;
1078
1079         if (inum - range_start >= SIZE_MAX / sizeof(struct nlink)) {
1080                 *range_end = inum;
1081                 return;
1082         }
1083
1084         link = genradix_ptr_alloc(links, inum - range_start, GFP_KERNEL);
1085         if (!link) {
1086                 bch_verbose(c, "allocation failed during fsck - will need another pass");
1087                 *range_end = inum;
1088                 return;
1089         }
1090
1091         if (dir)
1092                 link->dir_count++;
1093         else
1094                 link->count++;
1095 }
1096
1097 noinline_for_stack
1098 static int bch2_gc_walk_dirents(struct bch_fs *c, nlink_table *links,
1099                                u64 range_start, u64 *range_end)
1100 {
1101         struct btree_trans trans;
1102         struct btree_iter *iter;
1103         struct bkey_s_c k;
1104         struct bkey_s_c_dirent d;
1105         u64 d_inum;
1106         int ret;
1107
1108         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1109
1110         inc_link(c, links, range_start, range_end, BCACHEFS_ROOT_INO, false);
1111
1112         for_each_btree_key(&trans, iter, BTREE_ID_dirents, POS_MIN, 0, k, ret) {
1113                 switch (k.k->type) {
1114                 case KEY_TYPE_dirent:
1115                         d = bkey_s_c_to_dirent(k);
1116                         d_inum = le64_to_cpu(d.v->d_inum);
1117
1118                         if (d.v->d_type == DT_DIR)
1119                                 inc_link(c, links, range_start, range_end,
1120                                          d.k->p.inode, true);
1121
1122                         inc_link(c, links, range_start, range_end,
1123                                  d_inum, false);
1124
1125                         break;
1126                 }
1127
1128                 bch2_trans_cond_resched(&trans);
1129         }
1130         ret = bch2_trans_exit(&trans) ?: ret;
1131         if (ret)
1132                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
1133
1134         return ret;
1135 }
1136
1137 static int check_inode_nlink(struct bch_fs *c,
1138                              struct bch_inode_unpacked *lostfound_inode,
1139                              struct bch_inode_unpacked *u,
1140                              struct nlink *link,
1141                              bool *do_update)
1142 {
1143         u32 i_nlink = bch2_inode_nlink_get(u);
1144         u32 real_i_nlink =
1145                 link->count * nlink_bias(u->bi_mode) +
1146                 link->dir_count;
1147         int ret = 0;
1148
1149         /*
1150          * These should have been caught/fixed by earlier passes, we don't
1151          * repair them here:
1152          */
1153         if (S_ISDIR(u->bi_mode) && link->count > 1) {
1154                 need_fsck_err(c, "directory %llu with multiple hardlinks: %u",
1155                               u->bi_inum, link->count);
1156                 return 0;
1157         }
1158
1159         if (S_ISDIR(u->bi_mode) && !link->count) {
1160                 need_fsck_err(c, "unreachable directory found (inum %llu)",
1161                               u->bi_inum);
1162                 return 0;
1163         }
1164
1165         if (!S_ISDIR(u->bi_mode) && link->dir_count) {
1166                 need_fsck_err(c, "non directory with subdirectories (inum %llu)",
1167                               u->bi_inum);
1168                 return 0;
1169         }
1170
1171         if (!link->count &&
1172             !(u->bi_flags & BCH_INODE_UNLINKED) &&
1173             (c->sb.features & (1 << BCH_FEATURE_atomic_nlink))) {
1174                 if (fsck_err(c, "unreachable inode %llu not marked as unlinked (type %u)",
1175                              u->bi_inum, mode_to_type(u->bi_mode)) ==
1176                     FSCK_ERR_IGNORE)
1177                         return 0;
1178
1179                 ret = reattach_inode(c, lostfound_inode, u->bi_inum);
1180                 if (ret)
1181                         return ret;
1182
1183                 link->count = 1;
1184                 real_i_nlink = nlink_bias(u->bi_mode) + link->dir_count;
1185                 goto set_i_nlink;
1186         }
1187
1188         if (i_nlink < link->count) {
1189                 if (fsck_err(c, "inode %llu i_link too small (%u < %u, type %i)",
1190                              u->bi_inum, i_nlink, link->count,
1191                              mode_to_type(u->bi_mode)) == FSCK_ERR_IGNORE)
1192                         return 0;
1193                 goto set_i_nlink;
1194         }
1195
1196         if (i_nlink != real_i_nlink &&
1197             c->sb.clean) {
1198                 if (fsck_err(c, "filesystem marked clean, "
1199                              "but inode %llu has wrong i_nlink "
1200                              "(type %u i_nlink %u, should be %u)",
1201                              u->bi_inum, mode_to_type(u->bi_mode),
1202                              i_nlink, real_i_nlink) == FSCK_ERR_IGNORE)
1203                         return 0;
1204                 goto set_i_nlink;
1205         }
1206
1207         if (i_nlink != real_i_nlink &&
1208             (c->sb.features & (1 << BCH_FEATURE_atomic_nlink))) {
1209                 if (fsck_err(c, "inode %llu has wrong i_nlink "
1210                              "(type %u i_nlink %u, should be %u)",
1211                              u->bi_inum, mode_to_type(u->bi_mode),
1212                              i_nlink, real_i_nlink) == FSCK_ERR_IGNORE)
1213                         return 0;
1214                 goto set_i_nlink;
1215         }
1216
1217         if (real_i_nlink && i_nlink != real_i_nlink)
1218                 bch_verbose(c, "setting inode %llu nlink from %u to %u",
1219                             u->bi_inum, i_nlink, real_i_nlink);
1220 set_i_nlink:
1221         if (i_nlink != real_i_nlink) {
1222                 bch2_inode_nlink_set(u, real_i_nlink);
1223                 *do_update = true;
1224         }
1225 fsck_err:
1226         return ret;
1227 }
1228
1229 static int check_inode(struct btree_trans *trans,
1230                        struct bch_inode_unpacked *lostfound_inode,
1231                        struct btree_iter *iter,
1232                        struct bkey_s_c_inode inode,
1233                        struct nlink *link)
1234 {
1235         struct bch_fs *c = trans->c;
1236         struct bch_inode_unpacked u;
1237         bool do_update = false;
1238         int ret = 0;
1239
1240         ret = bch2_inode_unpack(inode, &u);
1241
1242         bch2_trans_unlock(trans);
1243
1244         if (bch2_fs_inconsistent_on(ret, c,
1245                          "error unpacking inode %llu in fsck",
1246                          inode.k->p.inode))
1247                 return ret;
1248
1249         if (link) {
1250                 ret = check_inode_nlink(c, lostfound_inode, &u, link,
1251                                         &do_update);
1252                 if (ret)
1253                         return ret;
1254         }
1255
1256         if (u.bi_flags & BCH_INODE_UNLINKED &&
1257             (!c->sb.clean ||
1258              fsck_err(c, "filesystem marked clean, but inode %llu unlinked",
1259                       u.bi_inum))) {
1260                 bch_verbose(c, "deleting inode %llu", u.bi_inum);
1261
1262                 bch2_fs_lazy_rw(c);
1263
1264                 ret = bch2_inode_rm(c, u.bi_inum, false);
1265                 if (ret)
1266                         bch_err(c, "error in fsck: error %i while deleting inode", ret);
1267                 return ret;
1268         }
1269
1270         if (u.bi_flags & BCH_INODE_I_SIZE_DIRTY &&
1271             (!c->sb.clean ||
1272              fsck_err(c, "filesystem marked clean, but inode %llu has i_size dirty",
1273                       u.bi_inum))) {
1274                 bch_verbose(c, "truncating inode %llu", u.bi_inum);
1275
1276                 bch2_fs_lazy_rw(c);
1277
1278                 /*
1279                  * XXX: need to truncate partial blocks too here - or ideally
1280                  * just switch units to bytes and that issue goes away
1281                  */
1282
1283                 ret = bch2_inode_truncate(c, u.bi_inum, u.bi_size);
1284                 if (ret) {
1285                         bch_err(c, "error in fsck: error %i truncating inode", ret);
1286                         return ret;
1287                 }
1288
1289                 /*
1290                  * We truncated without our normal sector accounting hook, just
1291                  * make sure we recalculate it:
1292                  */
1293                 u.bi_flags |= BCH_INODE_I_SECTORS_DIRTY;
1294
1295                 u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
1296                 do_update = true;
1297         }
1298
1299         if (u.bi_flags & BCH_INODE_I_SECTORS_DIRTY &&
1300             (!c->sb.clean ||
1301              fsck_err(c, "filesystem marked clean, but inode %llu has i_sectors dirty",
1302                       u.bi_inum))) {
1303                 s64 sectors;
1304
1305                 bch_verbose(c, "recounting sectors for inode %llu",
1306                             u.bi_inum);
1307
1308                 sectors = bch2_count_inode_sectors(trans, u.bi_inum);
1309                 if (sectors < 0) {
1310                         bch_err(c, "error in fsck: error %i recounting inode sectors",
1311                                 (int) sectors);
1312                         return sectors;
1313                 }
1314
1315                 u.bi_sectors = sectors;
1316                 u.bi_flags &= ~BCH_INODE_I_SECTORS_DIRTY;
1317                 do_update = true;
1318         }
1319
1320         if (do_update) {
1321                 struct bkey_inode_buf p;
1322
1323                 bch2_inode_pack(c, &p, &u);
1324
1325                 ret = __bch2_trans_do(trans, NULL, NULL,
1326                                       BTREE_INSERT_NOFAIL|
1327                                       BTREE_INSERT_LAZY_RW,
1328                         (bch2_trans_update(trans, iter, &p.inode.k_i, 0), 0));
1329                 if (ret)
1330                         bch_err(c, "error in fsck: error %i "
1331                                 "updating inode", ret);
1332         }
1333 fsck_err:
1334         return ret;
1335 }
1336
1337 noinline_for_stack
1338 static int bch2_gc_walk_inodes(struct bch_fs *c,
1339                                struct bch_inode_unpacked *lostfound_inode,
1340                                nlink_table *links,
1341                                u64 range_start, u64 range_end)
1342 {
1343         struct btree_trans trans;
1344         struct btree_iter *iter;
1345         struct bkey_s_c k;
1346         struct nlink *link, zero_links = { 0, 0 };
1347         struct genradix_iter nlinks_iter;
1348         int ret = 0, ret2 = 0;
1349         u64 nlinks_pos;
1350
1351         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1352
1353         iter = bch2_trans_get_iter(&trans, BTREE_ID_inodes,
1354                                    POS(0, range_start), 0);
1355         nlinks_iter = genradix_iter_init(links, 0);
1356
1357         while ((k = bch2_btree_iter_peek(iter)).k &&
1358                !(ret2 = bkey_err(k)) &&
1359                iter->pos.offset < range_end) {
1360 peek_nlinks:    link = genradix_iter_peek(&nlinks_iter, links);
1361
1362                 if (!link && (!k.k || iter->pos.offset >= range_end))
1363                         break;
1364
1365                 nlinks_pos = range_start + nlinks_iter.pos;
1366
1367                 if (link && nlinks_pos < iter->pos.offset) {
1368                         /* Should have been caught by dirents pass: */
1369                         need_fsck_err_on(link->count, c,
1370                                 "missing inode %llu (nlink %u)",
1371                                 nlinks_pos, link->count);
1372                         genradix_iter_advance(&nlinks_iter, links);
1373                         goto peek_nlinks;
1374                 }
1375
1376                 if (!link || nlinks_pos > iter->pos.offset)
1377                         link = &zero_links;
1378
1379                 if (k.k && k.k->type == KEY_TYPE_inode) {
1380                         ret = check_inode(&trans, lostfound_inode, iter,
1381                                           bkey_s_c_to_inode(k), link);
1382                         BUG_ON(ret == -EINTR);
1383                         if (ret)
1384                                 break;
1385                 } else {
1386                         /* Should have been caught by dirents pass: */
1387                         need_fsck_err_on(link->count, c,
1388                                 "missing inode %llu (nlink %u)",
1389                                 nlinks_pos, link->count);
1390                 }
1391
1392                 if (nlinks_pos == iter->pos.offset)
1393                         genradix_iter_advance(&nlinks_iter, links);
1394
1395                 bch2_btree_iter_next(iter);
1396                 bch2_trans_cond_resched(&trans);
1397         }
1398 fsck_err:
1399         bch2_trans_exit(&trans);
1400
1401         if (ret2)
1402                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret2);
1403
1404         return ret ?: ret2;
1405 }
1406
1407 noinline_for_stack
1408 static int check_inode_nlinks(struct bch_fs *c,
1409                               struct bch_inode_unpacked *lostfound_inode)
1410 {
1411         nlink_table links;
1412         u64 this_iter_range_start, next_iter_range_start = 0;
1413         int ret = 0;
1414
1415         bch_verbose(c, "checking inode nlinks");
1416
1417         genradix_init(&links);
1418
1419         do {
1420                 this_iter_range_start = next_iter_range_start;
1421                 next_iter_range_start = U64_MAX;
1422
1423                 ret = bch2_gc_walk_dirents(c, &links,
1424                                           this_iter_range_start,
1425                                           &next_iter_range_start);
1426                 if (ret)
1427                         break;
1428
1429                 ret = bch2_gc_walk_inodes(c, lostfound_inode, &links,
1430                                          this_iter_range_start,
1431                                          next_iter_range_start);
1432                 if (ret)
1433                         break;
1434
1435                 genradix_free(&links);
1436         } while (next_iter_range_start != U64_MAX);
1437
1438         genradix_free(&links);
1439
1440         return ret;
1441 }
1442
1443 /*
1444  * Checks for inconsistencies that shouldn't happen, unless we have a bug.
1445  * Doesn't fix them yet, mainly because they haven't yet been observed:
1446  */
1447 int bch2_fsck_full(struct bch_fs *c)
1448 {
1449         struct bch_inode_unpacked root_inode, lostfound_inode;
1450
1451         return  check_extents(c) ?:
1452                 check_dirents(c) ?:
1453                 check_xattrs(c) ?:
1454                 check_root(c, &root_inode) ?:
1455                 check_lostfound(c, &root_inode, &lostfound_inode) ?:
1456                 check_directory_structure(c, &lostfound_inode) ?:
1457                 check_inode_nlinks(c, &lostfound_inode);
1458 }
1459
1460 int bch2_fsck_inode_nlink(struct bch_fs *c)
1461 {
1462         struct bch_inode_unpacked root_inode, lostfound_inode;
1463
1464         return  check_root(c, &root_inode) ?:
1465                 check_lostfound(c, &root_inode, &lostfound_inode) ?:
1466                 check_inode_nlinks(c, &lostfound_inode);
1467 }
1468
1469 int bch2_fsck_walk_inodes_only(struct bch_fs *c)
1470 {
1471         struct btree_trans trans;
1472         struct btree_iter *iter;
1473         struct bkey_s_c k;
1474         struct bkey_s_c_inode inode;
1475         int ret;
1476
1477         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1478
1479         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN, 0, k, ret) {
1480                 if (k.k->type != KEY_TYPE_inode)
1481                         continue;
1482
1483                 inode = bkey_s_c_to_inode(k);
1484
1485                 if (inode.v->bi_flags &
1486                     (BCH_INODE_I_SIZE_DIRTY|
1487                      BCH_INODE_I_SECTORS_DIRTY|
1488                      BCH_INODE_UNLINKED)) {
1489                         ret = check_inode(&trans, NULL, iter, inode, NULL);
1490                         BUG_ON(ret == -EINTR);
1491                         if (ret)
1492                                 break;
1493                 }
1494         }
1495         BUG_ON(ret == -EINTR);
1496
1497         return bch2_trans_exit(&trans) ?: ret;
1498 }