]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
9dc162f2e1759d0c9569c43213f259d4befae287
[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 -EINTR;
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 fix_overlapping_extent(struct btree_trans *trans,
417                                        struct bkey_s_c k, struct bpos cut_at)
418 {
419         struct btree_iter *iter;
420         struct bkey_i *u;
421         int ret;
422
423         u = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
424         ret = PTR_ERR_OR_ZERO(u);
425         if (ret)
426                 return ret;
427
428         bkey_reassemble(u, k);
429         bch2_cut_front(cut_at, u);
430
431
432         /*
433          * We don't want to go through the extent_handle_overwrites path:
434          *
435          * XXX: this is going to screw up disk accounting, extent triggers
436          * assume things about extent overwrites - we should be running the
437          * triggers manually here
438          */
439         iter = bch2_trans_get_iter(trans, BTREE_ID_extents, u->k.p,
440                                    BTREE_ITER_INTENT|BTREE_ITER_NOT_EXTENTS);
441
442         BUG_ON(iter->flags & BTREE_ITER_IS_EXTENTS);
443         bch2_trans_update(trans, iter, u, BTREE_TRIGGER_NORUN);
444         bch2_trans_iter_put(trans, iter);
445
446         return bch2_trans_commit(trans, NULL, NULL,
447                                  BTREE_INSERT_NOFAIL|
448                                  BTREE_INSERT_LAZY_RW);
449 }
450
451 /*
452  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
453  * that i_size an i_sectors are consistent
454  */
455 noinline_for_stack
456 static int check_extents(struct bch_fs *c)
457 {
458         struct inode_walker w = inode_walker_init();
459         struct btree_trans trans;
460         struct btree_iter *iter;
461         struct bkey_s_c k;
462         struct bkey_buf prev;
463         u64 i_sectors = 0;
464         int ret = 0;
465
466         bch2_bkey_buf_init(&prev);
467         prev.k->k = KEY(0, 0, 0);
468         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
469
470         bch_verbose(c, "checking extents");
471
472         iter = bch2_trans_get_iter(&trans, BTREE_ID_extents,
473                                    POS(BCACHEFS_ROOT_INO, 0),
474                                    BTREE_ITER_INTENT);
475 retry:
476         while ((k = bch2_btree_iter_peek(iter)).k &&
477                !(ret = bkey_err(k))) {
478                 if (w.have_inode &&
479                     w.cur_inum != k.k->p.inode &&
480                     !(w.inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY) &&
481                     fsck_err_on(w.inode.bi_sectors != i_sectors, c,
482                                 "inode %llu has incorrect i_sectors: got %llu, should be %llu",
483                                 w.inode.bi_inum,
484                                 w.inode.bi_sectors, i_sectors)) {
485                         struct btree_iter *inode_iter =
486                                 bch2_trans_get_iter(&trans, BTREE_ID_inodes,
487                                                     POS(0, w.cur_inum),
488                                                     BTREE_ITER_INTENT);
489
490                         w.inode.bi_sectors = i_sectors;
491
492                         ret = __bch2_trans_do(&trans, NULL, NULL,
493                                               BTREE_INSERT_NOFAIL|
494                                               BTREE_INSERT_LAZY_RW,
495                                               bch2_inode_write(&trans, inode_iter, &w.inode));
496                         bch2_trans_iter_put(&trans, inode_iter);
497                         if (ret)
498                                 break;
499                 }
500
501                 if (bkey_cmp(prev.k->k.p, bkey_start_pos(k.k)) > 0) {
502                         char buf1[200];
503                         char buf2[200];
504
505                         bch2_bkey_val_to_text(&PBUF(buf1), c, bkey_i_to_s_c(prev.k));
506                         bch2_bkey_val_to_text(&PBUF(buf2), c, k);
507
508                         if (fsck_err(c, "overlapping extents:\n%s\n%s", buf1, buf2))
509                                 return fix_overlapping_extent(&trans, k, prev.k->k.p) ?: -EINTR;
510                 }
511
512                 ret = walk_inode(&trans, &w, k.k->p.inode);
513                 if (ret)
514                         break;
515
516                 if (w.first_this_inode)
517                         i_sectors = 0;
518
519                 if (fsck_err_on(!w.have_inode, c,
520                                 "extent type %u for missing inode %llu",
521                                 k.k->type, k.k->p.inode) ||
522                     fsck_err_on(w.have_inode &&
523                                 !S_ISREG(w.inode.bi_mode) && !S_ISLNK(w.inode.bi_mode), c,
524                                 "extent type %u for non regular file, inode %llu mode %o",
525                                 k.k->type, k.k->p.inode, w.inode.bi_mode)) {
526                         bch2_fs_lazy_rw(c);
527                         return bch2_btree_delete_range_trans(&trans, BTREE_ID_extents,
528                                                        POS(k.k->p.inode, 0),
529                                                        POS(k.k->p.inode, U64_MAX),
530                                                        NULL) ?: -EINTR;
531                 }
532
533                 if (fsck_err_on(w.have_inode &&
534                                 !(w.inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
535                                 k.k->type != KEY_TYPE_reservation &&
536                                 k.k->p.offset > round_up(w.inode.bi_size, block_bytes(c)) >> 9, c,
537                                 "extent type %u offset %llu past end of inode %llu, i_size %llu",
538                                 k.k->type, k.k->p.offset, k.k->p.inode, w.inode.bi_size)) {
539                         bch2_fs_lazy_rw(c);
540                         return bch2_btree_delete_range_trans(&trans, BTREE_ID_extents,
541                                         POS(k.k->p.inode, round_up(w.inode.bi_size, block_bytes(c))),
542                                         POS(k.k->p.inode, U64_MAX),
543                                         NULL) ?: -EINTR;
544                 }
545
546                 if (bkey_extent_is_allocation(k.k))
547                         i_sectors += k.k->size;
548                 bch2_bkey_buf_reassemble(&prev, c, k);
549
550                 bch2_btree_iter_advance(iter);
551         }
552 fsck_err:
553         if (ret == -EINTR)
554                 goto retry;
555         bch2_trans_iter_put(&trans, iter);
556         bch2_bkey_buf_exit(&prev, c);
557         return bch2_trans_exit(&trans) ?: ret;
558 }
559
560 /*
561  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
562  * validate d_type
563  */
564 noinline_for_stack
565 static int check_dirents(struct bch_fs *c)
566 {
567         struct inode_walker w = inode_walker_init();
568         struct hash_check h;
569         struct btree_trans trans;
570         struct btree_iter *iter;
571         struct bkey_s_c k;
572         unsigned name_len;
573         char buf[200];
574         int ret = 0;
575
576         bch_verbose(c, "checking dirents");
577
578         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
579
580         hash_check_init(&h);
581
582         iter = bch2_trans_get_iter(&trans, BTREE_ID_dirents,
583                                    POS(BCACHEFS_ROOT_INO, 0), 0);
584 retry:
585         while ((k = bch2_btree_iter_peek(iter)).k &&
586                !(ret = bkey_err(k))) {
587                 struct bkey_s_c_dirent d;
588                 struct bch_inode_unpacked target;
589                 bool have_target;
590                 u64 d_inum;
591
592                 ret = walk_inode(&trans, &w, k.k->p.inode);
593                 if (ret)
594                         break;
595
596                 if (fsck_err_on(!w.have_inode, c,
597                                 "dirent in nonexisting directory:\n%s",
598                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
599                                                        k), buf)) ||
600                     fsck_err_on(!S_ISDIR(w.inode.bi_mode), c,
601                                 "dirent in non directory inode type %u:\n%s",
602                                 mode_to_type(w.inode.bi_mode),
603                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
604                                                        k), buf))) {
605                         ret = bch2_btree_delete_at(&trans, iter, 0);
606                         if (ret)
607                                 goto err;
608                         continue;
609                 }
610
611                 if (w.first_this_inode && w.have_inode)
612                         hash_check_set_inode(&trans, &h, &w.inode);
613
614                 ret = check_dirent_hash(&trans, &h, iter, &k);
615                 if (ret > 0) {
616                         ret = 0;
617                         continue;
618                 }
619                 if (ret)
620                         goto fsck_err;
621
622                 if (ret)
623                         goto fsck_err;
624
625                 if (k.k->type != KEY_TYPE_dirent)
626                         continue;
627
628                 d = bkey_s_c_to_dirent(k);
629                 d_inum = le64_to_cpu(d.v->d_inum);
630
631                 name_len = bch2_dirent_name_bytes(d);
632
633                 if (fsck_err_on(!name_len, c, "empty dirent") ||
634                     fsck_err_on(name_len == 1 &&
635                                 !memcmp(d.v->d_name, ".", 1), c,
636                                 ". dirent") ||
637                     fsck_err_on(name_len == 2 &&
638                                 !memcmp(d.v->d_name, "..", 2), c,
639                                 ".. dirent") ||
640                     fsck_err_on(name_len == 2 &&
641                                 !memcmp(d.v->d_name, "..", 2), c,
642                                 ".. dirent") ||
643                     fsck_err_on(memchr(d.v->d_name, '/', name_len), c,
644                                 "dirent name has invalid chars")) {
645                         ret = remove_dirent(&trans, d);
646                         if (ret)
647                                 goto err;
648                         continue;
649                 }
650
651                 if (fsck_err_on(d_inum == d.k->p.inode, c,
652                                 "dirent points to own directory:\n%s",
653                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
654                                                        k), buf))) {
655                         ret = remove_dirent(&trans, d);
656                         if (ret)
657                                 goto err;
658                         continue;
659                 }
660
661                 ret = __bch2_inode_find_by_inum_trans(&trans, d_inum, &target, 0);
662                 if (ret && ret != -ENOENT)
663                         break;
664
665                 have_target = !ret;
666                 ret = 0;
667
668                 if (fsck_err_on(!have_target, c,
669                                 "dirent points to missing inode:\n%s",
670                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
671                                                        k), buf))) {
672                         ret = remove_dirent(&trans, d);
673                         if (ret)
674                                 goto err;
675                         continue;
676                 }
677
678                 if (fsck_err_on(have_target &&
679                                 d.v->d_type !=
680                                 mode_to_type(target.bi_mode), c,
681                                 "incorrect d_type: should be %u:\n%s",
682                                 mode_to_type(target.bi_mode),
683                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
684                                                        k), buf))) {
685                         struct bkey_i_dirent *n;
686
687                         n = kmalloc(bkey_bytes(d.k), GFP_KERNEL);
688                         if (!n) {
689                                 ret = -ENOMEM;
690                                 goto err;
691                         }
692
693                         bkey_reassemble(&n->k_i, d.s_c);
694                         n->v.d_type = mode_to_type(target.bi_mode);
695
696                         ret = __bch2_trans_do(&trans, NULL, NULL,
697                                               BTREE_INSERT_NOFAIL|
698                                               BTREE_INSERT_LAZY_RW,
699                                 (bch2_trans_update(&trans, iter, &n->k_i, 0), 0));
700                         kfree(n);
701                         if (ret)
702                                 goto err;
703
704                 }
705
706                 bch2_btree_iter_advance(iter);
707         }
708
709         hash_stop_chain(&trans, &h);
710 err:
711 fsck_err:
712         if (ret == -EINTR)
713                 goto retry;
714
715         bch2_trans_iter_put(&trans, h.chain);
716         bch2_trans_iter_put(&trans, iter);
717         return bch2_trans_exit(&trans) ?: ret;
718 }
719
720 /*
721  * Walk xattrs: verify that they all have a corresponding inode
722  */
723 noinline_for_stack
724 static int check_xattrs(struct bch_fs *c)
725 {
726         struct inode_walker w = inode_walker_init();
727         struct hash_check h;
728         struct btree_trans trans;
729         struct btree_iter *iter;
730         struct bkey_s_c k;
731         int ret = 0;
732
733         bch_verbose(c, "checking xattrs");
734
735         hash_check_init(&h);
736
737         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
738
739         iter = bch2_trans_get_iter(&trans, BTREE_ID_xattrs,
740                                    POS(BCACHEFS_ROOT_INO, 0), 0);
741 retry:
742         while ((k = bch2_btree_iter_peek(iter)).k &&
743                !(ret = bkey_err(k))) {
744                 ret = walk_inode(&trans, &w, k.k->p.inode);
745                 if (ret)
746                         break;
747
748                 if (fsck_err_on(!w.have_inode, c,
749                                 "xattr for missing inode %llu",
750                                 k.k->p.inode)) {
751                         ret = bch2_btree_delete_at(&trans, iter, 0);
752                         if (ret)
753                                 break;
754                         continue;
755                 }
756
757                 if (w.first_this_inode && w.have_inode)
758                         hash_check_set_inode(&trans, &h, &w.inode);
759
760                 ret = hash_check_key(&trans, bch2_xattr_hash_desc,
761                                      &h, iter, k);
762                 if (ret)
763                         break;
764
765                 bch2_btree_iter_advance(iter);
766         }
767 fsck_err:
768         if (ret == -EINTR)
769                 goto retry;
770
771         bch2_trans_iter_put(&trans, h.chain);
772         bch2_trans_iter_put(&trans, iter);
773         return bch2_trans_exit(&trans) ?: ret;
774 }
775
776 /* Get root directory, create if it doesn't exist: */
777 static int check_root(struct bch_fs *c, struct bch_inode_unpacked *root_inode)
778 {
779         struct bkey_inode_buf packed;
780         int ret;
781
782         bch_verbose(c, "checking root directory");
783
784         ret = bch2_trans_do(c, NULL, NULL, 0,
785                 __bch2_inode_find_by_inum_trans(&trans, BCACHEFS_ROOT_INO,
786                                                 root_inode, 0));
787         if (ret && ret != -ENOENT)
788                 return ret;
789
790         if (fsck_err_on(ret, c, "root directory missing"))
791                 goto create_root;
792
793         if (fsck_err_on(!S_ISDIR(root_inode->bi_mode), c,
794                         "root inode not a directory"))
795                 goto create_root;
796
797         return 0;
798 fsck_err:
799         return ret;
800 create_root:
801         bch2_inode_init(c, root_inode, 0, 0, S_IFDIR|0755,
802                         0, NULL);
803         root_inode->bi_inum = BCACHEFS_ROOT_INO;
804
805         bch2_inode_pack(c, &packed, root_inode);
806
807         return bch2_btree_insert(c, BTREE_ID_inodes, &packed.inode.k_i,
808                                  NULL, NULL,
809                                  BTREE_INSERT_NOFAIL|
810                                  BTREE_INSERT_LAZY_RW);
811 }
812
813 /* Get lost+found, create if it doesn't exist: */
814 static int check_lostfound(struct bch_fs *c,
815                            struct bch_inode_unpacked *root_inode,
816                            struct bch_inode_unpacked *lostfound_inode)
817 {
818         struct qstr lostfound = QSTR("lost+found");
819         struct bch_hash_info root_hash_info =
820                 bch2_hash_info_init(c, root_inode);
821         u64 inum;
822         int ret;
823
824         bch_verbose(c, "checking lost+found");
825
826         inum = bch2_dirent_lookup(c, BCACHEFS_ROOT_INO, &root_hash_info,
827                                  &lostfound);
828         if (!inum) {
829                 bch_notice(c, "creating lost+found");
830                 goto create_lostfound;
831         }
832
833         ret = bch2_trans_do(c, NULL, NULL, 0,
834                 __bch2_inode_find_by_inum_trans(&trans, inum, lostfound_inode, 0));
835         if (ret && ret != -ENOENT)
836                 return ret;
837
838         if (fsck_err_on(ret, c, "lost+found missing"))
839                 goto create_lostfound;
840
841         if (fsck_err_on(!S_ISDIR(lostfound_inode->bi_mode), c,
842                         "lost+found inode not a directory"))
843                 goto create_lostfound;
844
845         return 0;
846 fsck_err:
847         return ret;
848 create_lostfound:
849         bch2_inode_init_early(c, lostfound_inode);
850
851         ret = bch2_trans_do(c, NULL, NULL,
852                             BTREE_INSERT_NOFAIL|
853                             BTREE_INSERT_LAZY_RW,
854                 bch2_create_trans(&trans,
855                                   BCACHEFS_ROOT_INO, root_inode,
856                                   lostfound_inode, &lostfound,
857                                   0, 0, S_IFDIR|0700, 0, NULL, NULL));
858         if (ret)
859                 bch_err(c, "error creating lost+found: %i", ret);
860
861         return ret;
862 }
863
864 typedef GENRADIX(unsigned long) inode_bitmap;
865
866 static inline bool inode_bitmap_test(inode_bitmap *b, size_t nr)
867 {
868         unsigned long *w = genradix_ptr(b, nr / BITS_PER_LONG);
869         return w ? test_bit(nr & (BITS_PER_LONG - 1), w) : false;
870 }
871
872 static inline int inode_bitmap_set(inode_bitmap *b, size_t nr)
873 {
874         unsigned long *w = genradix_ptr_alloc(b, nr / BITS_PER_LONG, GFP_KERNEL);
875
876         if (!w)
877                 return -ENOMEM;
878
879         *w |= 1UL << (nr & (BITS_PER_LONG - 1));
880         return 0;
881 }
882
883 struct pathbuf {
884         size_t          nr;
885         size_t          size;
886
887         struct pathbuf_entry {
888                 u64     inum;
889                 u64     offset;
890         }               *entries;
891 };
892
893 static int path_down(struct pathbuf *p, u64 inum)
894 {
895         if (p->nr == p->size) {
896                 size_t new_size = max_t(size_t, 256UL, p->size * 2);
897                 void *n = krealloc(p->entries,
898                                    new_size * sizeof(p->entries[0]),
899                                    GFP_KERNEL);
900                 if (!n)
901                         return -ENOMEM;
902
903                 p->entries = n;
904                 p->size = new_size;
905         };
906
907         p->entries[p->nr++] = (struct pathbuf_entry) {
908                 .inum = inum,
909                 .offset = 0,
910         };
911         return 0;
912 }
913
914 noinline_for_stack
915 static int check_directory_structure(struct bch_fs *c,
916                                      struct bch_inode_unpacked *lostfound_inode)
917 {
918         inode_bitmap dirs_done;
919         struct pathbuf path = { 0, 0, NULL };
920         struct pathbuf_entry *e;
921         struct btree_trans trans;
922         struct btree_iter *iter;
923         struct bkey_s_c k;
924         struct bkey_s_c_dirent dirent;
925         bool had_unreachable;
926         u64 d_inum;
927         int ret = 0;
928
929         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
930
931         bch_verbose(c, "checking directory structure");
932
933         /* DFS: */
934 restart_dfs:
935         genradix_init(&dirs_done);
936         had_unreachable = false;
937
938         ret = inode_bitmap_set(&dirs_done, BCACHEFS_ROOT_INO);
939         if (ret) {
940                 bch_err(c, "memory allocation failure in inode_bitmap_set()");
941                 goto err;
942         }
943
944         ret = path_down(&path, BCACHEFS_ROOT_INO);
945         if (ret)
946                 goto err;
947
948         while (path.nr) {
949 next:
950                 e = &path.entries[path.nr - 1];
951
952                 if (e->offset == U64_MAX)
953                         goto up;
954
955                 for_each_btree_key(&trans, iter, BTREE_ID_dirents,
956                                    POS(e->inum, e->offset + 1), 0, k, ret) {
957                         if (k.k->p.inode != e->inum)
958                                 break;
959
960                         e->offset = k.k->p.offset;
961
962                         if (k.k->type != KEY_TYPE_dirent)
963                                 continue;
964
965                         dirent = bkey_s_c_to_dirent(k);
966
967                         if (dirent.v->d_type != DT_DIR)
968                                 continue;
969
970                         d_inum = le64_to_cpu(dirent.v->d_inum);
971
972                         if (fsck_err_on(inode_bitmap_test(&dirs_done, d_inum), c,
973                                         "directory %llu has multiple hardlinks",
974                                         d_inum)) {
975                                 ret = remove_dirent(&trans, dirent);
976                                 if (ret)
977                                         goto err;
978                                 continue;
979                         }
980
981                         ret = inode_bitmap_set(&dirs_done, d_inum);
982                         if (ret) {
983                                 bch_err(c, "memory allocation failure in inode_bitmap_set()");
984                                 goto err;
985                         }
986
987                         ret = path_down(&path, d_inum);
988                         if (ret) {
989                                 goto err;
990                         }
991
992                         ret = bch2_trans_iter_free(&trans, iter);
993                         if (ret) {
994                                 bch_err(c, "btree error %i in fsck", ret);
995                                 goto err;
996                         }
997                         goto next;
998                 }
999                 ret = bch2_trans_iter_free(&trans, iter) ?: ret;
1000                 if (ret) {
1001                         bch_err(c, "btree error %i in fsck", ret);
1002                         goto err;
1003                 }
1004 up:
1005                 path.nr--;
1006         }
1007
1008         iter = bch2_trans_get_iter(&trans, BTREE_ID_inodes, POS_MIN, 0);
1009 retry:
1010         for_each_btree_key_continue(iter, 0, k, ret) {
1011                 if (k.k->type != KEY_TYPE_inode)
1012                         continue;
1013
1014                 if (!S_ISDIR(le16_to_cpu(bkey_s_c_to_inode(k).v->bi_mode)))
1015                         continue;
1016
1017                 ret = bch2_empty_dir_trans(&trans, k.k->p.inode);
1018                 if (ret == -EINTR)
1019                         goto retry;
1020                 if (!ret)
1021                         continue;
1022
1023                 if (fsck_err_on(!inode_bitmap_test(&dirs_done, k.k->p.offset), c,
1024                                 "unreachable directory found (inum %llu)",
1025                                 k.k->p.offset)) {
1026                         bch2_trans_unlock(&trans);
1027
1028                         ret = reattach_inode(c, lostfound_inode, k.k->p.offset);
1029                         if (ret) {
1030                                 goto err;
1031                         }
1032
1033                         had_unreachable = true;
1034                 }
1035         }
1036         bch2_trans_iter_free(&trans, iter);
1037         if (ret)
1038                 goto err;
1039
1040         if (had_unreachable) {
1041                 bch_info(c, "reattached unreachable directories, restarting pass to check for loops");
1042                 genradix_free(&dirs_done);
1043                 kfree(path.entries);
1044                 memset(&dirs_done, 0, sizeof(dirs_done));
1045                 memset(&path, 0, sizeof(path));
1046                 goto restart_dfs;
1047         }
1048 err:
1049 fsck_err:
1050         ret = bch2_trans_exit(&trans) ?: ret;
1051         genradix_free(&dirs_done);
1052         kfree(path.entries);
1053         return ret;
1054 }
1055
1056 struct nlink {
1057         u32     count;
1058         u32     dir_count;
1059 };
1060
1061 typedef GENRADIX(struct nlink) nlink_table;
1062
1063 static void inc_link(struct bch_fs *c, nlink_table *links,
1064                      u64 range_start, u64 *range_end,
1065                      u64 inum, bool dir)
1066 {
1067         struct nlink *link;
1068
1069         if (inum < range_start || inum >= *range_end)
1070                 return;
1071
1072         if (inum - range_start >= SIZE_MAX / sizeof(struct nlink)) {
1073                 *range_end = inum;
1074                 return;
1075         }
1076
1077         link = genradix_ptr_alloc(links, inum - range_start, GFP_KERNEL);
1078         if (!link) {
1079                 bch_verbose(c, "allocation failed during fsck - will need another pass");
1080                 *range_end = inum;
1081                 return;
1082         }
1083
1084         if (dir)
1085                 link->dir_count++;
1086         else
1087                 link->count++;
1088 }
1089
1090 noinline_for_stack
1091 static int bch2_gc_walk_dirents(struct bch_fs *c, nlink_table *links,
1092                                u64 range_start, u64 *range_end)
1093 {
1094         struct btree_trans trans;
1095         struct btree_iter *iter;
1096         struct bkey_s_c k;
1097         struct bkey_s_c_dirent d;
1098         u64 d_inum;
1099         int ret;
1100
1101         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1102
1103         inc_link(c, links, range_start, range_end, BCACHEFS_ROOT_INO, false);
1104
1105         for_each_btree_key(&trans, iter, BTREE_ID_dirents, POS_MIN, 0, k, ret) {
1106                 switch (k.k->type) {
1107                 case KEY_TYPE_dirent:
1108                         d = bkey_s_c_to_dirent(k);
1109                         d_inum = le64_to_cpu(d.v->d_inum);
1110
1111                         if (d.v->d_type == DT_DIR)
1112                                 inc_link(c, links, range_start, range_end,
1113                                          d.k->p.inode, true);
1114
1115                         inc_link(c, links, range_start, range_end,
1116                                  d_inum, false);
1117
1118                         break;
1119                 }
1120
1121                 bch2_trans_cond_resched(&trans);
1122         }
1123         bch2_trans_iter_put(&trans, iter);
1124
1125         ret = bch2_trans_exit(&trans) ?: ret;
1126         if (ret)
1127                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
1128
1129         return ret;
1130 }
1131
1132 static int check_inode_nlink(struct bch_fs *c,
1133                              struct bch_inode_unpacked *lostfound_inode,
1134                              struct bch_inode_unpacked *u,
1135                              struct nlink *link,
1136                              bool *do_update)
1137 {
1138         u32 i_nlink = bch2_inode_nlink_get(u);
1139         u32 real_i_nlink =
1140                 link->count * nlink_bias(u->bi_mode) +
1141                 link->dir_count;
1142         int ret = 0;
1143
1144         /*
1145          * These should have been caught/fixed by earlier passes, we don't
1146          * repair them here:
1147          */
1148         if (S_ISDIR(u->bi_mode) && link->count > 1) {
1149                 need_fsck_err(c, "directory %llu with multiple hardlinks: %u",
1150                               u->bi_inum, link->count);
1151                 return 0;
1152         }
1153
1154         if (S_ISDIR(u->bi_mode) && !link->count) {
1155                 need_fsck_err(c, "unreachable directory found (inum %llu)",
1156                               u->bi_inum);
1157                 return 0;
1158         }
1159
1160         if (!S_ISDIR(u->bi_mode) && link->dir_count) {
1161                 need_fsck_err(c, "non directory with subdirectories (inum %llu)",
1162                               u->bi_inum);
1163                 return 0;
1164         }
1165
1166         if (!link->count &&
1167             !(u->bi_flags & BCH_INODE_UNLINKED) &&
1168             (c->sb.features & (1 << BCH_FEATURE_atomic_nlink))) {
1169                 if (fsck_err(c, "unreachable inode %llu not marked as unlinked (type %u)",
1170                              u->bi_inum, mode_to_type(u->bi_mode)) ==
1171                     FSCK_ERR_IGNORE)
1172                         return 0;
1173
1174                 ret = reattach_inode(c, lostfound_inode, u->bi_inum);
1175                 if (ret)
1176                         return ret;
1177
1178                 link->count = 1;
1179                 real_i_nlink = nlink_bias(u->bi_mode) + link->dir_count;
1180                 goto set_i_nlink;
1181         }
1182
1183         if (i_nlink < link->count) {
1184                 if (fsck_err(c, "inode %llu i_link too small (%u < %u, type %i)",
1185                              u->bi_inum, i_nlink, link->count,
1186                              mode_to_type(u->bi_mode)) == FSCK_ERR_IGNORE)
1187                         return 0;
1188                 goto set_i_nlink;
1189         }
1190
1191         if (i_nlink != real_i_nlink &&
1192             c->sb.clean) {
1193                 if (fsck_err(c, "filesystem marked clean, "
1194                              "but inode %llu has wrong i_nlink "
1195                              "(type %u i_nlink %u, should be %u)",
1196                              u->bi_inum, mode_to_type(u->bi_mode),
1197                              i_nlink, real_i_nlink) == FSCK_ERR_IGNORE)
1198                         return 0;
1199                 goto set_i_nlink;
1200         }
1201
1202         if (i_nlink != real_i_nlink &&
1203             (c->sb.features & (1 << BCH_FEATURE_atomic_nlink))) {
1204                 if (fsck_err(c, "inode %llu has wrong i_nlink "
1205                              "(type %u i_nlink %u, should be %u)",
1206                              u->bi_inum, mode_to_type(u->bi_mode),
1207                              i_nlink, real_i_nlink) == FSCK_ERR_IGNORE)
1208                         return 0;
1209                 goto set_i_nlink;
1210         }
1211
1212         if (real_i_nlink && i_nlink != real_i_nlink)
1213                 bch_verbose(c, "setting inode %llu nlink from %u to %u",
1214                             u->bi_inum, i_nlink, real_i_nlink);
1215 set_i_nlink:
1216         if (i_nlink != real_i_nlink) {
1217                 bch2_inode_nlink_set(u, real_i_nlink);
1218                 *do_update = true;
1219         }
1220 fsck_err:
1221         return ret;
1222 }
1223
1224 static int check_inode(struct btree_trans *trans,
1225                        struct bch_inode_unpacked *lostfound_inode,
1226                        struct btree_iter *iter,
1227                        struct bkey_s_c_inode inode,
1228                        struct nlink *link)
1229 {
1230         struct bch_fs *c = trans->c;
1231         struct bch_inode_unpacked u;
1232         bool do_update = false;
1233         int ret = 0;
1234
1235         ret = bch2_inode_unpack(inode, &u);
1236
1237         bch2_trans_unlock(trans);
1238
1239         if (bch2_fs_inconsistent_on(ret, c,
1240                          "error unpacking inode %llu in fsck",
1241                          inode.k->p.inode))
1242                 return ret;
1243
1244         if (link) {
1245                 ret = check_inode_nlink(c, lostfound_inode, &u, link,
1246                                         &do_update);
1247                 if (ret)
1248                         return ret;
1249         }
1250
1251         if (u.bi_flags & BCH_INODE_UNLINKED &&
1252             (!c->sb.clean ||
1253              fsck_err(c, "filesystem marked clean, but inode %llu unlinked",
1254                       u.bi_inum))) {
1255                 bch_verbose(c, "deleting inode %llu", u.bi_inum);
1256
1257                 bch2_fs_lazy_rw(c);
1258
1259                 ret = bch2_inode_rm(c, u.bi_inum, false);
1260                 if (ret)
1261                         bch_err(c, "error in fsck: error %i while deleting inode", ret);
1262                 return ret;
1263         }
1264
1265         if (u.bi_flags & BCH_INODE_I_SIZE_DIRTY &&
1266             (!c->sb.clean ||
1267              fsck_err(c, "filesystem marked clean, but inode %llu has i_size dirty",
1268                       u.bi_inum))) {
1269                 bch_verbose(c, "truncating inode %llu", u.bi_inum);
1270
1271                 bch2_fs_lazy_rw(c);
1272
1273                 /*
1274                  * XXX: need to truncate partial blocks too here - or ideally
1275                  * just switch units to bytes and that issue goes away
1276                  */
1277                 ret = bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
1278                                 POS(u.bi_inum, round_up(u.bi_size, block_bytes(c))),
1279                                 POS(u.bi_inum, U64_MAX),
1280                                 NULL);
1281                 if (ret) {
1282                         bch_err(c, "error in fsck: error %i truncating inode", ret);
1283                         return ret;
1284                 }
1285
1286                 /*
1287                  * We truncated without our normal sector accounting hook, just
1288                  * make sure we recalculate it:
1289                  */
1290                 u.bi_flags |= BCH_INODE_I_SECTORS_DIRTY;
1291
1292                 u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
1293                 do_update = true;
1294         }
1295
1296         if (u.bi_flags & BCH_INODE_I_SECTORS_DIRTY &&
1297             (!c->sb.clean ||
1298              fsck_err(c, "filesystem marked clean, but inode %llu has i_sectors dirty",
1299                       u.bi_inum))) {
1300                 s64 sectors;
1301
1302                 bch_verbose(c, "recounting sectors for inode %llu",
1303                             u.bi_inum);
1304
1305                 sectors = bch2_count_inode_sectors(trans, u.bi_inum);
1306                 if (sectors < 0) {
1307                         bch_err(c, "error in fsck: error %i recounting inode sectors",
1308                                 (int) sectors);
1309                         return sectors;
1310                 }
1311
1312                 u.bi_sectors = sectors;
1313                 u.bi_flags &= ~BCH_INODE_I_SECTORS_DIRTY;
1314                 do_update = true;
1315         }
1316
1317         if (do_update) {
1318                 struct bkey_inode_buf p;
1319
1320                 bch2_inode_pack(c, &p, &u);
1321
1322                 ret = __bch2_trans_do(trans, NULL, NULL,
1323                                       BTREE_INSERT_NOFAIL|
1324                                       BTREE_INSERT_LAZY_RW,
1325                         (bch2_trans_update(trans, iter, &p.inode.k_i, 0), 0));
1326                 if (ret)
1327                         bch_err(c, "error in fsck: error %i "
1328                                 "updating inode", ret);
1329         }
1330 fsck_err:
1331         return ret;
1332 }
1333
1334 noinline_for_stack
1335 static int bch2_gc_walk_inodes(struct bch_fs *c,
1336                                struct bch_inode_unpacked *lostfound_inode,
1337                                nlink_table *links,
1338                                u64 range_start, u64 range_end)
1339 {
1340         struct btree_trans trans;
1341         struct btree_iter *iter;
1342         struct bkey_s_c k;
1343         struct nlink *link, zero_links = { 0, 0 };
1344         struct genradix_iter nlinks_iter;
1345         int ret = 0, ret2 = 0;
1346         u64 nlinks_pos;
1347
1348         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1349
1350         iter = bch2_trans_get_iter(&trans, BTREE_ID_inodes,
1351                                    POS(0, range_start), 0);
1352         nlinks_iter = genradix_iter_init(links, 0);
1353
1354         while ((k = bch2_btree_iter_peek(iter)).k &&
1355                !(ret2 = bkey_err(k)) &&
1356                iter->pos.offset < range_end) {
1357 peek_nlinks:    link = genradix_iter_peek(&nlinks_iter, links);
1358
1359                 if (!link && (!k.k || iter->pos.offset >= range_end))
1360                         break;
1361
1362                 nlinks_pos = range_start + nlinks_iter.pos;
1363
1364                 if (link && nlinks_pos < iter->pos.offset) {
1365                         /* Should have been caught by dirents pass: */
1366                         need_fsck_err_on(link->count, c,
1367                                 "missing inode %llu (nlink %u)",
1368                                 nlinks_pos, link->count);
1369                         genradix_iter_advance(&nlinks_iter, links);
1370                         goto peek_nlinks;
1371                 }
1372
1373                 if (!link || nlinks_pos > iter->pos.offset)
1374                         link = &zero_links;
1375
1376                 if (k.k && k.k->type == KEY_TYPE_inode) {
1377                         ret = check_inode(&trans, lostfound_inode, iter,
1378                                           bkey_s_c_to_inode(k), link);
1379                         BUG_ON(ret == -EINTR);
1380                         if (ret)
1381                                 break;
1382                 } else {
1383                         /* Should have been caught by dirents pass: */
1384                         need_fsck_err_on(link->count, c,
1385                                 "missing inode %llu (nlink %u)",
1386                                 nlinks_pos, link->count);
1387                 }
1388
1389                 if (nlinks_pos == iter->pos.offset)
1390                         genradix_iter_advance(&nlinks_iter, links);
1391
1392                 bch2_btree_iter_advance(iter);
1393                 bch2_trans_cond_resched(&trans);
1394         }
1395 fsck_err:
1396         bch2_trans_iter_put(&trans, iter);
1397         bch2_trans_exit(&trans);
1398
1399         if (ret2)
1400                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret2);
1401
1402         return ret ?: ret2;
1403 }
1404
1405 noinline_for_stack
1406 static int check_inode_nlinks(struct bch_fs *c,
1407                               struct bch_inode_unpacked *lostfound_inode)
1408 {
1409         nlink_table links;
1410         u64 this_iter_range_start, next_iter_range_start = 0;
1411         int ret = 0;
1412
1413         bch_verbose(c, "checking inode nlinks");
1414
1415         genradix_init(&links);
1416
1417         do {
1418                 this_iter_range_start = next_iter_range_start;
1419                 next_iter_range_start = U64_MAX;
1420
1421                 ret = bch2_gc_walk_dirents(c, &links,
1422                                           this_iter_range_start,
1423                                           &next_iter_range_start);
1424                 if (ret)
1425                         break;
1426
1427                 ret = bch2_gc_walk_inodes(c, lostfound_inode, &links,
1428                                          this_iter_range_start,
1429                                          next_iter_range_start);
1430                 if (ret)
1431                         break;
1432
1433                 genradix_free(&links);
1434         } while (next_iter_range_start != U64_MAX);
1435
1436         genradix_free(&links);
1437
1438         return ret;
1439 }
1440
1441 /*
1442  * Checks for inconsistencies that shouldn't happen, unless we have a bug.
1443  * Doesn't fix them yet, mainly because they haven't yet been observed:
1444  */
1445 int bch2_fsck_full(struct bch_fs *c)
1446 {
1447         struct bch_inode_unpacked root_inode, lostfound_inode;
1448
1449         return  check_extents(c) ?:
1450                 check_dirents(c) ?:
1451                 check_xattrs(c) ?:
1452                 check_root(c, &root_inode) ?:
1453                 check_lostfound(c, &root_inode, &lostfound_inode) ?:
1454                 check_directory_structure(c, &lostfound_inode) ?:
1455                 check_inode_nlinks(c, &lostfound_inode);
1456 }
1457
1458 int bch2_fsck_inode_nlink(struct bch_fs *c)
1459 {
1460         struct bch_inode_unpacked root_inode, lostfound_inode;
1461
1462         return  check_root(c, &root_inode) ?:
1463                 check_lostfound(c, &root_inode, &lostfound_inode) ?:
1464                 check_inode_nlinks(c, &lostfound_inode);
1465 }
1466
1467 int bch2_fsck_walk_inodes_only(struct bch_fs *c)
1468 {
1469         struct btree_trans trans;
1470         struct btree_iter *iter;
1471         struct bkey_s_c k;
1472         struct bkey_s_c_inode inode;
1473         int ret;
1474
1475         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1476
1477         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN, 0, k, ret) {
1478                 if (k.k->type != KEY_TYPE_inode)
1479                         continue;
1480
1481                 inode = bkey_s_c_to_inode(k);
1482
1483                 if (inode.v->bi_flags &
1484                     (BCH_INODE_I_SIZE_DIRTY|
1485                      BCH_INODE_I_SECTORS_DIRTY|
1486                      BCH_INODE_UNLINKED)) {
1487                         ret = check_inode(&trans, NULL, iter, inode, NULL);
1488                         if (ret)
1489                                 break;
1490                 }
1491         }
1492         bch2_trans_iter_put(&trans, iter);
1493
1494         BUG_ON(ret == -EINTR);
1495
1496         return bch2_trans_exit(&trans) ?: ret;
1497 }