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