]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
960280b706e382c75d630fd62724e11ebb209e46
[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 "buckets.h"
7 #include "darray.h"
8 #include "dirent.h"
9 #include "error.h"
10 #include "fs-common.h"
11 #include "fsck.h"
12 #include "inode.h"
13 #include "keylist.h"
14 #include "recovery.h"
15 #include "snapshot.h"
16 #include "super.h"
17 #include "xattr.h"
18
19 #include <linux/bsearch.h>
20 #include <linux/dcache.h> /* struct qstr */
21
22 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
23
24 /*
25  * XXX: this is handling transaction restarts without returning
26  * -BCH_ERR_transaction_restart_nested, this is not how we do things anymore:
27  */
28 static s64 bch2_count_inode_sectors(struct btree_trans *trans, u64 inum,
29                                     u32 snapshot)
30 {
31         struct btree_iter iter;
32         struct bkey_s_c k;
33         u64 sectors = 0;
34         int ret;
35
36         for_each_btree_key_upto(trans, iter, BTREE_ID_extents,
37                                 SPOS(inum, 0, snapshot),
38                                 POS(inum, U64_MAX),
39                                 0, k, ret)
40                 if (bkey_extent_is_allocation(k.k))
41                         sectors += k.k->size;
42
43         bch2_trans_iter_exit(trans, &iter);
44
45         return ret ?: sectors;
46 }
47
48 static s64 bch2_count_subdirs(struct btree_trans *trans, u64 inum,
49                                     u32 snapshot)
50 {
51         struct btree_iter iter;
52         struct bkey_s_c k;
53         struct bkey_s_c_dirent d;
54         u64 subdirs = 0;
55         int ret;
56
57         for_each_btree_key_upto(trans, iter, BTREE_ID_dirents,
58                                 SPOS(inum, 0, snapshot),
59                                 POS(inum, U64_MAX),
60                                 0, k, ret) {
61                 if (k.k->type != KEY_TYPE_dirent)
62                         continue;
63
64                 d = bkey_s_c_to_dirent(k);
65                 if (d.v->d_type == DT_DIR)
66                         subdirs++;
67         }
68         bch2_trans_iter_exit(trans, &iter);
69
70         return ret ?: subdirs;
71 }
72
73 static int __snapshot_lookup_subvol(struct btree_trans *trans, u32 snapshot,
74                                     u32 *subvol)
75 {
76         struct bch_snapshot s;
77         int ret = bch2_bkey_get_val_typed(trans, BTREE_ID_snapshots,
78                                           POS(0, snapshot), 0,
79                                           snapshot, &s);
80         if (!ret)
81                 *subvol = le32_to_cpu(s.subvol);
82         else if (bch2_err_matches(ret, ENOENT))
83                 bch_err(trans->c, "snapshot %u not fonud", snapshot);
84         return ret;
85
86 }
87
88 static int __subvol_lookup(struct btree_trans *trans, u32 subvol,
89                            u32 *snapshot, u64 *inum)
90 {
91         struct bch_subvolume s;
92         int ret;
93
94         ret = bch2_subvolume_get(trans, subvol, false, 0, &s);
95
96         *snapshot = le32_to_cpu(s.snapshot);
97         *inum = le64_to_cpu(s.inode);
98         return ret;
99 }
100
101 static int subvol_lookup(struct btree_trans *trans, u32 subvol,
102                          u32 *snapshot, u64 *inum)
103 {
104         return lockrestart_do(trans, __subvol_lookup(trans, subvol, snapshot, inum));
105 }
106
107 static int lookup_first_inode(struct btree_trans *trans, u64 inode_nr,
108                               struct bch_inode_unpacked *inode)
109 {
110         struct btree_iter iter;
111         struct bkey_s_c k;
112         int ret;
113
114         bch2_trans_iter_init(trans, &iter, BTREE_ID_inodes,
115                              POS(0, inode_nr),
116                              BTREE_ITER_ALL_SNAPSHOTS);
117         k = bch2_btree_iter_peek(&iter);
118         ret = bkey_err(k);
119         if (ret)
120                 goto err;
121
122         if (!k.k || !bkey_eq(k.k->p, POS(0, inode_nr))) {
123                 ret = -BCH_ERR_ENOENT_inode;
124                 goto err;
125         }
126
127         ret = bch2_inode_unpack(k, inode);
128 err:
129         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
130                 bch_err(trans->c, "error fetching inode %llu: %s",
131                         inode_nr, bch2_err_str(ret));
132         bch2_trans_iter_exit(trans, &iter);
133         return ret;
134 }
135
136 static int __lookup_inode(struct btree_trans *trans, u64 inode_nr,
137                           struct bch_inode_unpacked *inode,
138                           u32 *snapshot)
139 {
140         struct btree_iter iter;
141         struct bkey_s_c k;
142         int ret;
143
144         k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
145                                SPOS(0, inode_nr, *snapshot), 0);
146         ret = bkey_err(k);
147         if (ret)
148                 goto err;
149
150         ret = bkey_is_inode(k.k)
151                 ? bch2_inode_unpack(k, inode)
152                 : -BCH_ERR_ENOENT_inode;
153         if (!ret)
154                 *snapshot = iter.pos.snapshot;
155 err:
156         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
157                 bch_err(trans->c, "error fetching inode %llu:%u: %s",
158                         inode_nr, *snapshot, bch2_err_str(ret));
159         bch2_trans_iter_exit(trans, &iter);
160         return ret;
161 }
162
163 static int lookup_inode(struct btree_trans *trans, u64 inode_nr,
164                         struct bch_inode_unpacked *inode,
165                         u32 *snapshot)
166 {
167         return lockrestart_do(trans, __lookup_inode(trans, inode_nr, inode, snapshot));
168 }
169
170 static int __lookup_dirent(struct btree_trans *trans,
171                            struct bch_hash_info hash_info,
172                            subvol_inum dir, struct qstr *name,
173                            u64 *target, unsigned *type)
174 {
175         struct btree_iter iter;
176         struct bkey_s_c_dirent d;
177         int ret;
178
179         ret = bch2_hash_lookup(trans, &iter, bch2_dirent_hash_desc,
180                                &hash_info, dir, name, 0);
181         if (ret)
182                 return ret;
183
184         d = bkey_s_c_to_dirent(bch2_btree_iter_peek_slot(&iter));
185         *target = le64_to_cpu(d.v->d_inum);
186         *type = d.v->d_type;
187         bch2_trans_iter_exit(trans, &iter);
188         return 0;
189 }
190
191 static int __write_inode(struct btree_trans *trans,
192                          struct bch_inode_unpacked *inode,
193                          u32 snapshot)
194 {
195         struct bkey_inode_buf *inode_p =
196                 bch2_trans_kmalloc(trans, sizeof(*inode_p));
197
198         if (IS_ERR(inode_p))
199                 return PTR_ERR(inode_p);
200
201         bch2_inode_pack(inode_p, inode);
202         inode_p->inode.k.p.snapshot = snapshot;
203
204         return bch2_btree_insert_nonextent(trans, BTREE_ID_inodes,
205                                 &inode_p->inode.k_i,
206                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
207 }
208
209 static int write_inode(struct btree_trans *trans,
210                        struct bch_inode_unpacked *inode,
211                        u32 snapshot)
212 {
213         int ret = commit_do(trans, NULL, NULL,
214                                   BTREE_INSERT_NOFAIL|
215                                   BTREE_INSERT_LAZY_RW,
216                                   __write_inode(trans, inode, snapshot));
217         if (ret)
218                 bch_err(trans->c, "error in fsck: error updating inode: %s",
219                         bch2_err_str(ret));
220         return ret;
221 }
222
223 static int __remove_dirent(struct btree_trans *trans, struct bpos pos)
224 {
225         struct bch_fs *c = trans->c;
226         struct btree_iter iter;
227         struct bch_inode_unpacked dir_inode;
228         struct bch_hash_info dir_hash_info;
229         int ret;
230
231         ret = lookup_first_inode(trans, pos.inode, &dir_inode);
232         if (ret)
233                 goto err;
234
235         dir_hash_info = bch2_hash_info_init(c, &dir_inode);
236
237         bch2_trans_iter_init(trans, &iter, BTREE_ID_dirents, pos, BTREE_ITER_INTENT);
238
239         ret = bch2_hash_delete_at(trans, bch2_dirent_hash_desc,
240                                   &dir_hash_info, &iter,
241                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
242         bch2_trans_iter_exit(trans, &iter);
243 err:
244         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
245                 bch_err_fn(c, ret);
246         return ret;
247 }
248
249 /* Get lost+found, create if it doesn't exist: */
250 static int lookup_lostfound(struct btree_trans *trans, u32 subvol,
251                             struct bch_inode_unpacked *lostfound)
252 {
253         struct bch_fs *c = trans->c;
254         struct bch_inode_unpacked root;
255         struct bch_hash_info root_hash_info;
256         struct qstr lostfound_str = QSTR("lost+found");
257         subvol_inum root_inum = { .subvol = subvol };
258         u64 inum = 0;
259         unsigned d_type = 0;
260         u32 snapshot;
261         int ret;
262
263         ret = __subvol_lookup(trans, subvol, &snapshot, &root_inum.inum);
264         if (ret)
265                 return ret;
266
267         ret = __lookup_inode(trans, root_inum.inum, &root, &snapshot);
268         if (ret)
269                 return ret;
270
271         root_hash_info = bch2_hash_info_init(c, &root);
272
273         ret = __lookup_dirent(trans, root_hash_info, root_inum,
274                             &lostfound_str, &inum, &d_type);
275         if (bch2_err_matches(ret, ENOENT)) {
276                 bch_notice(c, "creating lost+found");
277                 goto create_lostfound;
278         }
279
280         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
281                 bch_err(c, "error looking up lost+found: %s", bch2_err_str(ret));
282         if (ret)
283                 return ret;
284
285         if (d_type != DT_DIR) {
286                 bch_err(c, "error looking up lost+found: not a directory");
287                 return ret;
288         }
289
290         /*
291          * The bch2_check_dirents pass has already run, dangling dirents
292          * shouldn't exist here:
293          */
294         return __lookup_inode(trans, inum, lostfound, &snapshot);
295
296 create_lostfound:
297         bch2_inode_init_early(c, lostfound);
298
299         ret = bch2_create_trans(trans, root_inum, &root,
300                                 lostfound, &lostfound_str,
301                                 0, 0, S_IFDIR|0700, 0, NULL, NULL,
302                                 (subvol_inum) { }, 0);
303         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
304                 bch_err(c, "error creating lost+found: %s", bch2_err_str(ret));
305         return ret;
306 }
307
308 static int __reattach_inode(struct btree_trans *trans,
309                           struct bch_inode_unpacked *inode,
310                           u32 inode_snapshot)
311 {
312         struct bch_hash_info dir_hash;
313         struct bch_inode_unpacked lostfound;
314         char name_buf[20];
315         struct qstr name;
316         u64 dir_offset = 0;
317         u32 subvol;
318         int ret;
319
320         ret = __snapshot_lookup_subvol(trans, inode_snapshot, &subvol);
321         if (ret)
322                 return ret;
323
324         ret = lookup_lostfound(trans, subvol, &lostfound);
325         if (ret)
326                 return ret;
327
328         if (S_ISDIR(inode->bi_mode)) {
329                 lostfound.bi_nlink++;
330
331                 ret = __write_inode(trans, &lostfound, U32_MAX);
332                 if (ret)
333                         return ret;
334         }
335
336         dir_hash = bch2_hash_info_init(trans->c, &lostfound);
337
338         snprintf(name_buf, sizeof(name_buf), "%llu", inode->bi_inum);
339         name = (struct qstr) QSTR(name_buf);
340
341         ret = bch2_dirent_create(trans,
342                                  (subvol_inum) {
343                                         .subvol = subvol,
344                                         .inum = lostfound.bi_inum,
345                                  },
346                                  &dir_hash,
347                                  inode_d_type(inode),
348                                  &name, inode->bi_inum, &dir_offset,
349                                  BCH_HASH_SET_MUST_CREATE);
350         if (ret)
351                 return ret;
352
353         inode->bi_dir           = lostfound.bi_inum;
354         inode->bi_dir_offset    = dir_offset;
355
356         return __write_inode(trans, inode, inode_snapshot);
357 }
358
359 static int reattach_inode(struct btree_trans *trans,
360                           struct bch_inode_unpacked *inode,
361                           u32 inode_snapshot)
362 {
363         int ret = commit_do(trans, NULL, NULL,
364                                   BTREE_INSERT_LAZY_RW|
365                                   BTREE_INSERT_NOFAIL,
366                         __reattach_inode(trans, inode, inode_snapshot));
367         if (ret) {
368                 bch_err(trans->c, "error reattaching inode %llu: %s",
369                         inode->bi_inum, bch2_err_str(ret));
370                 return ret;
371         }
372
373         return ret;
374 }
375
376 static int remove_backpointer(struct btree_trans *trans,
377                               struct bch_inode_unpacked *inode)
378 {
379         struct btree_iter iter;
380         struct bkey_s_c_dirent d;
381         int ret;
382
383         d = bch2_bkey_get_iter_typed(trans, &iter, BTREE_ID_dirents,
384                                      POS(inode->bi_dir, inode->bi_dir_offset), 0,
385                                      dirent);
386         ret =   bkey_err(d) ?:
387                 __remove_dirent(trans, d.k->p);
388         bch2_trans_iter_exit(trans, &iter);
389         return ret;
390 }
391
392 struct snapshots_seen_entry {
393         u32                             id;
394         u32                             equiv;
395 };
396
397 struct snapshots_seen {
398         struct bpos                     pos;
399         DARRAY(struct snapshots_seen_entry) ids;
400 };
401
402 static inline void snapshots_seen_exit(struct snapshots_seen *s)
403 {
404         darray_exit(&s->ids);
405 }
406
407 static inline void snapshots_seen_init(struct snapshots_seen *s)
408 {
409         memset(s, 0, sizeof(*s));
410 }
411
412 static int snapshots_seen_add_inorder(struct bch_fs *c, struct snapshots_seen *s, u32 id)
413 {
414         struct snapshots_seen_entry *i, n = {
415                 .id     = id,
416                 .equiv  = bch2_snapshot_equiv(c, id),
417         };
418         int ret = 0;
419
420         darray_for_each(s->ids, i) {
421                 if (i->id == id)
422                         return 0;
423                 if (i->id > id)
424                         break;
425         }
426
427         ret = darray_insert_item(&s->ids, i - s->ids.data, n);
428         if (ret)
429                 bch_err(c, "error reallocating snapshots_seen table (size %zu)",
430                         s->ids.size);
431         return ret;
432 }
433
434 static int snapshots_seen_update(struct bch_fs *c, struct snapshots_seen *s,
435                                  enum btree_id btree_id, struct bpos pos)
436 {
437         struct snapshots_seen_entry *i, n = {
438                 .id     = pos.snapshot,
439                 .equiv  = bch2_snapshot_equiv(c, pos.snapshot),
440         };
441         int ret = 0;
442
443         if (!bkey_eq(s->pos, pos))
444                 s->ids.nr = 0;
445
446         s->pos = pos;
447         s->pos.snapshot = n.equiv;
448
449         darray_for_each(s->ids, i) {
450                 if (i->id == n.id)
451                         return 0;
452
453                 /*
454                  * We currently don't rigorously track for snapshot cleanup
455                  * needing to be run, so it shouldn't be a fsck error yet:
456                  */
457                 if (i->equiv == n.equiv) {
458                         bch_err(c, "snapshot deletion did not finish:\n"
459                                 "  duplicate keys in btree %s at %llu:%llu snapshots %u, %u (equiv %u)\n",
460                                 bch2_btree_ids[btree_id],
461                                 pos.inode, pos.offset,
462                                 i->id, n.id, n.equiv);
463                         return bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_delete_dead_snapshots);
464                 }
465         }
466
467         ret = darray_push(&s->ids, n);
468         if (ret)
469                 bch_err(c, "error reallocating snapshots_seen table (size %zu)",
470                         s->ids.size);
471         return ret;
472 }
473
474 /**
475  * key_visible_in_snapshot - returns true if @id is a descendent of @ancestor,
476  * and @ancestor hasn't been overwritten in @seen
477  *
478  * That is, returns whether key in @ancestor snapshot is visible in @id snapshot
479  */
480 static bool key_visible_in_snapshot(struct bch_fs *c, struct snapshots_seen *seen,
481                                     u32 id, u32 ancestor)
482 {
483         ssize_t i;
484
485         EBUG_ON(id > ancestor);
486         EBUG_ON(!bch2_snapshot_is_equiv(c, id));
487         EBUG_ON(!bch2_snapshot_is_equiv(c, ancestor));
488
489         /* @ancestor should be the snapshot most recently added to @seen */
490         EBUG_ON(ancestor != seen->pos.snapshot);
491         EBUG_ON(ancestor != seen->ids.data[seen->ids.nr - 1].equiv);
492
493         if (id == ancestor)
494                 return true;
495
496         if (!bch2_snapshot_is_ancestor(c, id, ancestor))
497                 return false;
498
499         /*
500          * We know that @id is a descendant of @ancestor, we're checking if
501          * we've seen a key that overwrote @ancestor - i.e. also a descendent of
502          * @ascestor and with @id as a descendent.
503          *
504          * But we already know that we're scanning IDs between @id and @ancestor
505          * numerically, since snapshot ID lists are kept sorted, so if we find
506          * an id that's an ancestor of @id we're done:
507          */
508
509         for (i = seen->ids.nr - 2;
510              i >= 0 && seen->ids.data[i].equiv >= id;
511              --i)
512                 if (bch2_snapshot_is_ancestor(c, id, seen->ids.data[i].equiv))
513                         return false;
514
515         return true;
516 }
517
518 /**
519  * ref_visible - given a key with snapshot id @src that points to a key with
520  * snapshot id @dst, test whether there is some snapshot in which @dst is
521  * visible.
522  *
523  * This assumes we're visiting @src keys in natural key order.
524  *
525  * @s   - list of snapshot IDs already seen at @src
526  * @src - snapshot ID of src key
527  * @dst - snapshot ID of dst key
528  */
529 static int ref_visible(struct bch_fs *c, struct snapshots_seen *s,
530                        u32 src, u32 dst)
531 {
532         return dst <= src
533                 ? key_visible_in_snapshot(c, s, dst, src)
534                 : bch2_snapshot_is_ancestor(c, src, dst);
535 }
536
537 static int ref_visible2(struct bch_fs *c,
538                         u32 src, struct snapshots_seen *src_seen,
539                         u32 dst, struct snapshots_seen *dst_seen)
540 {
541         src = bch2_snapshot_equiv(c, src);
542         dst = bch2_snapshot_equiv(c, dst);
543
544         if (dst > src) {
545                 swap(dst, src);
546                 swap(dst_seen, src_seen);
547         }
548         return key_visible_in_snapshot(c, src_seen, dst, src);
549 }
550
551 #define for_each_visible_inode(_c, _s, _w, _snapshot, _i)                               \
552         for (_i = (_w)->inodes.data; _i < (_w)->inodes.data + (_w)->inodes.nr &&        \
553              (_i)->snapshot <= (_snapshot); _i++)                                       \
554                 if (key_visible_in_snapshot(_c, _s, _i->snapshot, _snapshot))
555
556 struct inode_walker_entry {
557         struct bch_inode_unpacked inode;
558         u32                     snapshot;
559         bool                    seen_this_pos;
560         u64                     count;
561 };
562
563 struct inode_walker {
564         bool                            first_this_inode;
565         bool                            recalculate_sums;
566         struct bpos                     last_pos;
567
568         DARRAY(struct inode_walker_entry) inodes;
569 };
570
571 static void inode_walker_exit(struct inode_walker *w)
572 {
573         darray_exit(&w->inodes);
574 }
575
576 static struct inode_walker inode_walker_init(void)
577 {
578         return (struct inode_walker) { 0, };
579 }
580
581 static int add_inode(struct bch_fs *c, struct inode_walker *w,
582                      struct bkey_s_c inode)
583 {
584         struct bch_inode_unpacked u;
585
586         BUG_ON(bch2_inode_unpack(inode, &u));
587
588         return darray_push(&w->inodes, ((struct inode_walker_entry) {
589                 .inode          = u,
590                 .snapshot       = bch2_snapshot_equiv(c, inode.k->p.snapshot),
591         }));
592 }
593
594 static int get_inodes_all_snapshots(struct btree_trans *trans,
595                                     struct inode_walker *w, u64 inum)
596 {
597         struct bch_fs *c = trans->c;
598         struct btree_iter iter;
599         struct bkey_s_c k;
600         u32 restart_count = trans->restart_count;
601         int ret;
602
603         w->recalculate_sums = false;
604         w->inodes.nr = 0;
605
606         for_each_btree_key(trans, iter, BTREE_ID_inodes, POS(0, inum),
607                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
608                 if (k.k->p.offset != inum)
609                         break;
610
611                 if (bkey_is_inode(k.k))
612                         add_inode(c, w, k);
613         }
614         bch2_trans_iter_exit(trans, &iter);
615
616         if (ret)
617                 return ret;
618
619         w->first_this_inode = true;
620
621         if (trans_was_restarted(trans, restart_count))
622                 return -BCH_ERR_transaction_restart_nested;
623
624         return 0;
625 }
626
627 static struct inode_walker_entry *
628 lookup_inode_for_snapshot(struct bch_fs *c, struct inode_walker *w,
629                           u32 snapshot, bool is_whiteout)
630 {
631         struct inode_walker_entry *i;
632
633         snapshot = bch2_snapshot_equiv(c, snapshot);
634
635         darray_for_each(w->inodes, i)
636                 if (bch2_snapshot_is_ancestor(c, snapshot, i->snapshot))
637                         goto found;
638
639         return NULL;
640 found:
641         BUG_ON(snapshot > i->snapshot);
642
643         if (snapshot != i->snapshot && !is_whiteout) {
644                 struct inode_walker_entry new = *i;
645                 size_t pos;
646                 int ret;
647
648                 new.snapshot = snapshot;
649                 new.count = 0;
650
651                 bch_info(c, "have key for inode %llu:%u but have inode in ancestor snapshot %u",
652                          w->last_pos.inode, snapshot, i->snapshot);
653
654                 while (i > w->inodes.data && i[-1].snapshot > snapshot)
655                         --i;
656
657                 pos = i - w->inodes.data;
658                 ret = darray_insert_item(&w->inodes, pos, new);
659                 if (ret)
660                         return ERR_PTR(ret);
661
662                 i = w->inodes.data + pos;
663         }
664
665         return i;
666 }
667
668 static struct inode_walker_entry *walk_inode(struct btree_trans *trans,
669                                              struct inode_walker *w, struct bpos pos,
670                                              bool is_whiteout)
671 {
672         if (w->last_pos.inode != pos.inode) {
673                 int ret = get_inodes_all_snapshots(trans, w, pos.inode);
674                 if (ret)
675                         return ERR_PTR(ret);
676         } else if (bkey_cmp(w->last_pos, pos)) {
677                 struct inode_walker_entry *i;
678
679                 darray_for_each(w->inodes, i)
680                         i->seen_this_pos = false;
681
682         }
683
684         w->last_pos = pos;
685
686         return lookup_inode_for_snapshot(trans->c, w, pos.snapshot, is_whiteout);
687 }
688
689 static int __get_visible_inodes(struct btree_trans *trans,
690                                 struct inode_walker *w,
691                                 struct snapshots_seen *s,
692                                 u64 inum)
693 {
694         struct bch_fs *c = trans->c;
695         struct btree_iter iter;
696         struct bkey_s_c k;
697         int ret;
698
699         w->inodes.nr = 0;
700
701         for_each_btree_key_norestart(trans, iter, BTREE_ID_inodes, POS(0, inum),
702                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
703                 u32 equiv = bch2_snapshot_equiv(c, k.k->p.snapshot);
704
705                 if (k.k->p.offset != inum)
706                         break;
707
708                 if (!ref_visible(c, s, s->pos.snapshot, equiv))
709                         continue;
710
711                 if (bkey_is_inode(k.k))
712                         add_inode(c, w, k);
713
714                 if (equiv >= s->pos.snapshot)
715                         break;
716         }
717         bch2_trans_iter_exit(trans, &iter);
718
719         return ret;
720 }
721
722 static int check_key_has_snapshot(struct btree_trans *trans,
723                                   struct btree_iter *iter,
724                                   struct bkey_s_c k)
725 {
726         struct bch_fs *c = trans->c;
727         struct printbuf buf = PRINTBUF;
728         int ret = 0;
729
730         if (mustfix_fsck_err_on(!bch2_snapshot_equiv(c, k.k->p.snapshot), c,
731                         "key in missing snapshot: %s",
732                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
733                 ret = bch2_btree_delete_at(trans, iter,
734                                             BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE) ?: 1;
735 fsck_err:
736         printbuf_exit(&buf);
737         return ret;
738 }
739
740 static int hash_redo_key(struct btree_trans *trans,
741                          const struct bch_hash_desc desc,
742                          struct bch_hash_info *hash_info,
743                          struct btree_iter *k_iter, struct bkey_s_c k)
744 {
745         struct bkey_i *delete;
746         struct bkey_i *tmp;
747
748         delete = bch2_trans_kmalloc(trans, sizeof(*delete));
749         if (IS_ERR(delete))
750                 return PTR_ERR(delete);
751
752         tmp = bch2_bkey_make_mut_noupdate(trans, k);
753         if (IS_ERR(tmp))
754                 return PTR_ERR(tmp);
755
756         bkey_init(&delete->k);
757         delete->k.p = k_iter->pos;
758         return  bch2_btree_iter_traverse(k_iter) ?:
759                 bch2_trans_update(trans, k_iter, delete, 0) ?:
760                 bch2_hash_set_snapshot(trans, desc, hash_info,
761                                        (subvol_inum) { 0, k.k->p.inode },
762                                        k.k->p.snapshot, tmp,
763                                        BCH_HASH_SET_MUST_CREATE,
764                                        BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE) ?:
765                 bch2_trans_commit(trans, NULL, NULL,
766                                   BTREE_INSERT_NOFAIL|
767                                   BTREE_INSERT_LAZY_RW);
768 }
769
770 static int hash_check_key(struct btree_trans *trans,
771                           const struct bch_hash_desc desc,
772                           struct bch_hash_info *hash_info,
773                           struct btree_iter *k_iter, struct bkey_s_c hash_k)
774 {
775         struct bch_fs *c = trans->c;
776         struct btree_iter iter = { NULL };
777         struct printbuf buf = PRINTBUF;
778         struct bkey_s_c k;
779         u64 hash;
780         int ret = 0;
781
782         if (hash_k.k->type != desc.key_type)
783                 return 0;
784
785         hash = desc.hash_bkey(hash_info, hash_k);
786
787         if (likely(hash == hash_k.k->p.offset))
788                 return 0;
789
790         if (hash_k.k->p.offset < hash)
791                 goto bad_hash;
792
793         for_each_btree_key_norestart(trans, iter, desc.btree_id,
794                                      SPOS(hash_k.k->p.inode, hash, hash_k.k->p.snapshot),
795                                      BTREE_ITER_SLOTS, k, ret) {
796                 if (bkey_eq(k.k->p, hash_k.k->p))
797                         break;
798
799                 if (fsck_err_on(k.k->type == desc.key_type &&
800                                 !desc.cmp_bkey(k, hash_k), c,
801                                 "duplicate hash table keys:\n%s",
802                                 (printbuf_reset(&buf),
803                                  bch2_bkey_val_to_text(&buf, c, hash_k),
804                                  buf.buf))) {
805                         ret = bch2_hash_delete_at(trans, desc, hash_info, k_iter, 0) ?: 1;
806                         break;
807                 }
808
809                 if (bkey_deleted(k.k)) {
810                         bch2_trans_iter_exit(trans, &iter);
811                         goto bad_hash;
812                 }
813         }
814 out:
815         bch2_trans_iter_exit(trans, &iter);
816         printbuf_exit(&buf);
817         return ret;
818 bad_hash:
819         if (fsck_err(c, "hash table key at wrong offset: btree %s inode %llu offset %llu, hashed to %llu\n%s",
820                      bch2_btree_ids[desc.btree_id], hash_k.k->p.inode, hash_k.k->p.offset, hash,
821                      (printbuf_reset(&buf),
822                       bch2_bkey_val_to_text(&buf, c, hash_k), buf.buf))) {
823                 ret = hash_redo_key(trans, desc, hash_info, k_iter, hash_k);
824                 if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
825                         bch_err(c, "hash_redo_key err %s", bch2_err_str(ret));
826                 if (ret)
827                         return ret;
828                 ret = -BCH_ERR_transaction_restart_nested;
829         }
830 fsck_err:
831         goto out;
832 }
833
834 static int check_inode(struct btree_trans *trans,
835                        struct btree_iter *iter,
836                        struct bkey_s_c k,
837                        struct bch_inode_unpacked *prev,
838                        struct snapshots_seen *s,
839                        bool full)
840 {
841         struct bch_fs *c = trans->c;
842         struct bch_inode_unpacked u;
843         bool do_update = false;
844         int ret;
845
846         ret = check_key_has_snapshot(trans, iter, k);
847         if (ret < 0)
848                 goto err;
849         if (ret)
850                 return 0;
851
852         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
853         if (ret)
854                 goto err;
855
856         /*
857          * if snapshot id isn't a leaf node, skip it - deletion in
858          * particular is not atomic, so on the internal snapshot nodes
859          * we can see inodes marked for deletion after a clean shutdown
860          */
861         if (bch2_snapshot_is_internal_node(c, k.k->p.snapshot))
862                 return 0;
863
864         if (!bkey_is_inode(k.k))
865                 return 0;
866
867         BUG_ON(bch2_inode_unpack(k, &u));
868
869         if (!full &&
870             !(u.bi_flags & (BCH_INODE_I_SIZE_DIRTY|
871                             BCH_INODE_I_SECTORS_DIRTY|
872                             BCH_INODE_UNLINKED)))
873                 return 0;
874
875         if (prev->bi_inum != u.bi_inum)
876                 *prev = u;
877
878         if (fsck_err_on(prev->bi_hash_seed      != u.bi_hash_seed ||
879                         inode_d_type(prev)      != inode_d_type(&u), c,
880                         "inodes in different snapshots don't match")) {
881                 bch_err(c, "repair not implemented yet");
882                 return -EINVAL;
883         }
884
885         if (u.bi_flags & BCH_INODE_UNLINKED &&
886             (!c->sb.clean ||
887              fsck_err(c, "filesystem marked clean, but inode %llu unlinked",
888                       u.bi_inum))) {
889                 bch2_trans_unlock(trans);
890                 bch2_fs_lazy_rw(c);
891
892                 ret = bch2_inode_rm_snapshot(trans, u.bi_inum, iter->pos.snapshot);
893                 if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
894                         bch_err(c, "error in fsck: error while deleting inode: %s",
895                                 bch2_err_str(ret));
896                 return ret;
897         }
898
899         if (u.bi_flags & BCH_INODE_I_SIZE_DIRTY &&
900             (!c->sb.clean ||
901              fsck_err(c, "filesystem marked clean, but inode %llu has i_size dirty",
902                       u.bi_inum))) {
903                 bch_verbose(c, "truncating inode %llu", u.bi_inum);
904
905                 bch2_trans_unlock(trans);
906                 bch2_fs_lazy_rw(c);
907
908                 /*
909                  * XXX: need to truncate partial blocks too here - or ideally
910                  * just switch units to bytes and that issue goes away
911                  */
912                 ret = bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
913                                 SPOS(u.bi_inum, round_up(u.bi_size, block_bytes(c)) >> 9,
914                                      iter->pos.snapshot),
915                                 POS(u.bi_inum, U64_MAX),
916                                 0, NULL);
917                 if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
918                         bch_err(c, "error in fsck: error truncating inode: %s",
919                                 bch2_err_str(ret));
920                 if (ret)
921                         return ret;
922
923                 /*
924                  * We truncated without our normal sector accounting hook, just
925                  * make sure we recalculate it:
926                  */
927                 u.bi_flags |= BCH_INODE_I_SECTORS_DIRTY;
928
929                 u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
930                 do_update = true;
931         }
932
933         if (u.bi_flags & BCH_INODE_I_SECTORS_DIRTY &&
934             (!c->sb.clean ||
935              fsck_err(c, "filesystem marked clean, but inode %llu has i_sectors dirty",
936                       u.bi_inum))) {
937                 s64 sectors;
938
939                 bch_verbose(c, "recounting sectors for inode %llu",
940                             u.bi_inum);
941
942                 sectors = bch2_count_inode_sectors(trans, u.bi_inum, iter->pos.snapshot);
943                 if (sectors < 0) {
944                         bch_err(c, "error in fsck: error recounting inode sectors: %s",
945                                 bch2_err_str(sectors));
946                         return sectors;
947                 }
948
949                 u.bi_sectors = sectors;
950                 u.bi_flags &= ~BCH_INODE_I_SECTORS_DIRTY;
951                 do_update = true;
952         }
953
954         if (u.bi_flags & BCH_INODE_BACKPTR_UNTRUSTED) {
955                 u.bi_dir = 0;
956                 u.bi_dir_offset = 0;
957                 u.bi_flags &= ~BCH_INODE_BACKPTR_UNTRUSTED;
958                 do_update = true;
959         }
960
961         if (do_update) {
962                 ret = __write_inode(trans, &u, iter->pos.snapshot);
963                 if (ret)
964                         bch_err(c, "error in fsck: error updating inode: %s",
965                                 bch2_err_str(ret));
966         }
967 err:
968 fsck_err:
969         if (ret)
970                 bch_err_fn(c, ret);
971         return ret;
972 }
973
974 noinline_for_stack
975 int bch2_check_inodes(struct bch_fs *c)
976 {
977         bool full = c->opts.fsck;
978         struct btree_trans trans;
979         struct btree_iter iter;
980         struct bch_inode_unpacked prev = { 0 };
981         struct snapshots_seen s;
982         struct bkey_s_c k;
983         int ret;
984
985         snapshots_seen_init(&s);
986         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
987
988         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_inodes,
989                         POS_MIN,
990                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
991                         NULL, NULL, BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
992                 check_inode(&trans, &iter, k, &prev, &s, full));
993
994         bch2_trans_exit(&trans);
995         snapshots_seen_exit(&s);
996         if (ret)
997                 bch_err_fn(c, ret);
998         return ret;
999 }
1000
1001 static struct bkey_s_c_dirent dirent_get_by_pos(struct btree_trans *trans,
1002                                                 struct btree_iter *iter,
1003                                                 struct bpos pos)
1004 {
1005         return bch2_bkey_get_iter_typed(trans, iter, BTREE_ID_dirents, pos, 0, dirent);
1006 }
1007
1008 static bool inode_points_to_dirent(struct bch_inode_unpacked *inode,
1009                                    struct bkey_s_c_dirent d)
1010 {
1011         return  inode->bi_dir           == d.k->p.inode &&
1012                 inode->bi_dir_offset    == d.k->p.offset;
1013 }
1014
1015 static bool dirent_points_to_inode(struct bkey_s_c_dirent d,
1016                                    struct bch_inode_unpacked *inode)
1017 {
1018         return d.v->d_type == DT_SUBVOL
1019                 ? le32_to_cpu(d.v->d_child_subvol)      == inode->bi_subvol
1020                 : le64_to_cpu(d.v->d_inum)              == inode->bi_inum;
1021 }
1022
1023 static int inode_backpointer_exists(struct btree_trans *trans,
1024                                     struct bch_inode_unpacked *inode,
1025                                     u32 snapshot)
1026 {
1027         struct btree_iter iter;
1028         struct bkey_s_c_dirent d;
1029         int ret;
1030
1031         d = dirent_get_by_pos(trans, &iter,
1032                         SPOS(inode->bi_dir, inode->bi_dir_offset, snapshot));
1033         ret = bkey_err(d);
1034         if (ret)
1035                 return bch2_err_matches(ret, ENOENT) ? 0 : ret;
1036
1037         ret = dirent_points_to_inode(d, inode);
1038         bch2_trans_iter_exit(trans, &iter);
1039         return ret;
1040 }
1041
1042 static int check_i_sectors(struct btree_trans *trans, struct inode_walker *w)
1043 {
1044         struct bch_fs *c = trans->c;
1045         struct inode_walker_entry *i;
1046         u32 restart_count = trans->restart_count;
1047         int ret = 0;
1048         s64 count2;
1049
1050         darray_for_each(w->inodes, i) {
1051                 if (i->inode.bi_sectors == i->count)
1052                         continue;
1053
1054                 count2 = bch2_count_inode_sectors(trans, w->last_pos.inode, i->snapshot);
1055
1056                 if (w->recalculate_sums)
1057                         i->count = count2;
1058
1059                 if (i->count != count2) {
1060                         bch_err(c, "fsck counted i_sectors wrong for inode %llu:%u: got %llu should be %llu",
1061                                 w->last_pos.inode, i->snapshot, i->count, count2);
1062                         return -BCH_ERR_internal_fsck_err;
1063                 }
1064
1065                 if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY), c,
1066                             "inode %llu:%u has incorrect i_sectors: got %llu, should be %llu",
1067                             w->last_pos.inode, i->snapshot,
1068                             i->inode.bi_sectors, i->count)) {
1069                         i->inode.bi_sectors = i->count;
1070                         ret = write_inode(trans, &i->inode, i->snapshot);
1071                         if (ret)
1072                                 break;
1073                 }
1074         }
1075 fsck_err:
1076         if (ret)
1077                 bch_err_fn(c, ret);
1078         if (!ret && trans_was_restarted(trans, restart_count))
1079                 ret = -BCH_ERR_transaction_restart_nested;
1080         return ret;
1081 }
1082
1083 struct extent_end {
1084         u32                     snapshot;
1085         u64                     offset;
1086         struct snapshots_seen   seen;
1087 };
1088
1089 struct extent_ends {
1090         struct bpos                     last_pos;
1091         DARRAY(struct extent_end)       e;
1092 };
1093
1094 static void extent_ends_reset(struct extent_ends *extent_ends)
1095 {
1096         struct extent_end *i;
1097
1098         darray_for_each(extent_ends->e, i)
1099                 snapshots_seen_exit(&i->seen);
1100
1101         extent_ends->e.nr = 0;
1102 }
1103
1104 static void extent_ends_exit(struct extent_ends *extent_ends)
1105 {
1106         extent_ends_reset(extent_ends);
1107         darray_exit(&extent_ends->e);
1108 }
1109
1110 static void extent_ends_init(struct extent_ends *extent_ends)
1111 {
1112         memset(extent_ends, 0, sizeof(*extent_ends));
1113 }
1114
1115 static int extent_ends_at(struct bch_fs *c,
1116                           struct extent_ends *extent_ends,
1117                           struct snapshots_seen *seen,
1118                           struct bkey_s_c k)
1119 {
1120         struct extent_end *i, n = (struct extent_end) {
1121                 .offset         = k.k->p.offset,
1122                 .snapshot       = k.k->p.snapshot,
1123                 .seen           = *seen,
1124         };
1125
1126         n.seen.ids.data = kmemdup(seen->ids.data,
1127                               sizeof(seen->ids.data[0]) * seen->ids.size,
1128                               GFP_KERNEL);
1129         if (!n.seen.ids.data)
1130                 return -BCH_ERR_ENOMEM_fsck_extent_ends_at;
1131
1132         darray_for_each(extent_ends->e, i) {
1133                 if (i->snapshot == k.k->p.snapshot) {
1134                         snapshots_seen_exit(&i->seen);
1135                         *i = n;
1136                         return 0;
1137                 }
1138
1139                 if (i->snapshot >= k.k->p.snapshot)
1140                         break;
1141         }
1142
1143         return darray_insert_item(&extent_ends->e, i - extent_ends->e.data, n);
1144 }
1145
1146 static int overlapping_extents_found(struct btree_trans *trans,
1147                                      enum btree_id btree,
1148                                      struct bpos pos1, struct snapshots_seen *pos1_seen,
1149                                      struct bkey pos2,
1150                                      bool *fixed,
1151                                      struct extent_end *extent_end)
1152 {
1153         struct bch_fs *c = trans->c;
1154         struct printbuf buf = PRINTBUF;
1155         struct btree_iter iter1, iter2 = { NULL };
1156         struct bkey_s_c k1, k2;
1157         int ret;
1158
1159         BUG_ON(bkey_le(pos1, bkey_start_pos(&pos2)));
1160
1161         bch2_trans_iter_init(trans, &iter1, btree, pos1,
1162                              BTREE_ITER_ALL_SNAPSHOTS|
1163                              BTREE_ITER_NOT_EXTENTS);
1164         k1 = bch2_btree_iter_peek_upto(&iter1, POS(pos1.inode, U64_MAX));
1165         ret = bkey_err(k1);
1166         if (ret)
1167                 goto err;
1168
1169         prt_str(&buf, "\n  ");
1170         bch2_bkey_val_to_text(&buf, c, k1);
1171
1172         if (!bpos_eq(pos1, k1.k->p)) {
1173                 prt_str(&buf, "\n  wanted\n  ");
1174                 bch2_bpos_to_text(&buf, pos1);
1175                 prt_str(&buf, "\n  ");
1176                 bch2_bkey_to_text(&buf, &pos2);
1177
1178                 bch_err(c, "%s: error finding first overlapping extent when repairing, got%s",
1179                         __func__, buf.buf);
1180                 ret = -BCH_ERR_internal_fsck_err;
1181                 goto err;
1182         }
1183
1184         bch2_trans_copy_iter(&iter2, &iter1);
1185
1186         while (1) {
1187                 bch2_btree_iter_advance(&iter2);
1188
1189                 k2 = bch2_btree_iter_peek_upto(&iter2, POS(pos1.inode, U64_MAX));
1190                 ret = bkey_err(k2);
1191                 if (ret)
1192                         goto err;
1193
1194                 if (bpos_ge(k2.k->p, pos2.p))
1195                         break;
1196         }
1197
1198         prt_str(&buf, "\n  ");
1199         bch2_bkey_val_to_text(&buf, c, k2);
1200
1201         if (bpos_gt(k2.k->p, pos2.p) ||
1202             pos2.size != k2.k->size) {
1203                 bch_err(c, "%s: error finding seconding overlapping extent when repairing%s",
1204                         __func__, buf.buf);
1205                 ret = -BCH_ERR_internal_fsck_err;
1206                 goto err;
1207         }
1208
1209         prt_printf(&buf, "\n  overwriting %s extent",
1210                    pos1.snapshot >= pos2.p.snapshot ? "first" : "second");
1211
1212         if (fsck_err(c, "overlapping extents%s", buf.buf)) {
1213                 struct btree_iter *old_iter = &iter1;
1214                 struct disk_reservation res = { 0 };
1215
1216                 if (pos1.snapshot < pos2.p.snapshot) {
1217                         old_iter = &iter2;
1218                         swap(k1, k2);
1219                 }
1220
1221                 trans->extra_journal_res += bch2_bkey_sectors_compressed(k2);
1222
1223                 ret =   bch2_trans_update_extent_overwrite(trans, old_iter,
1224                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE,
1225                                 k1, k2) ?:
1226                         bch2_trans_commit(trans, &res, NULL,
1227                                 BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL);
1228                 bch2_disk_reservation_put(c, &res);
1229
1230                 if (ret)
1231                         goto err;
1232
1233                 *fixed = true;
1234
1235                 if (pos1.snapshot == pos2.p.snapshot) {
1236                         /*
1237                          * We overwrote the first extent, and did the overwrite
1238                          * in the same snapshot:
1239                          */
1240                         extent_end->offset = bkey_start_offset(&pos2);
1241                 } else if (pos1.snapshot > pos2.p.snapshot) {
1242                         /*
1243                          * We overwrote the first extent in pos2's snapshot:
1244                          */
1245                         ret = snapshots_seen_add_inorder(c, pos1_seen, pos2.p.snapshot);
1246                 } else {
1247                         /*
1248                          * We overwrote the second extent - restart
1249                          * check_extent() from the top:
1250                          */
1251                         ret = -BCH_ERR_transaction_restart_nested;
1252                 }
1253         }
1254 fsck_err:
1255 err:
1256         bch2_trans_iter_exit(trans, &iter2);
1257         bch2_trans_iter_exit(trans, &iter1);
1258         printbuf_exit(&buf);
1259         return ret;
1260 }
1261
1262 static int check_overlapping_extents(struct btree_trans *trans,
1263                               struct snapshots_seen *seen,
1264                               struct extent_ends *extent_ends,
1265                               struct bkey_s_c k,
1266                               u32 equiv,
1267                               struct btree_iter *iter,
1268                               bool *fixed)
1269 {
1270         struct bch_fs *c = trans->c;
1271         struct extent_end *i;
1272         int ret = 0;
1273
1274         /* transaction restart, running again */
1275         if (bpos_eq(extent_ends->last_pos, k.k->p))
1276                 return 0;
1277
1278         if (extent_ends->last_pos.inode != k.k->p.inode)
1279                 extent_ends_reset(extent_ends);
1280
1281         darray_for_each(extent_ends->e, i) {
1282                 if (i->offset <= bkey_start_offset(k.k))
1283                         continue;
1284
1285                 if (!ref_visible2(c,
1286                                   k.k->p.snapshot, seen,
1287                                   i->snapshot, &i->seen))
1288                         continue;
1289
1290                 ret = overlapping_extents_found(trans, iter->btree_id,
1291                                                 SPOS(iter->pos.inode,
1292                                                      i->offset,
1293                                                      i->snapshot),
1294                                                 &i->seen,
1295                                                 *k.k, fixed, i);
1296                 if (ret)
1297                         goto err;
1298         }
1299
1300         ret = extent_ends_at(c, extent_ends, seen, k);
1301         if (ret)
1302                 goto err;
1303
1304         extent_ends->last_pos = k.k->p;
1305 err:
1306         return ret;
1307 }
1308
1309 static int check_extent(struct btree_trans *trans, struct btree_iter *iter,
1310                         struct bkey_s_c k,
1311                         struct inode_walker *inode,
1312                         struct snapshots_seen *s,
1313                         struct extent_ends *extent_ends)
1314 {
1315         struct bch_fs *c = trans->c;
1316         struct inode_walker_entry *i;
1317         struct printbuf buf = PRINTBUF;
1318         struct bpos equiv = k.k->p;
1319         int ret = 0;
1320
1321         equiv.snapshot = bch2_snapshot_equiv(c, k.k->p.snapshot);
1322
1323         ret = check_key_has_snapshot(trans, iter, k);
1324         if (ret) {
1325                 ret = ret < 0 ? ret : 0;
1326                 goto out;
1327         }
1328
1329         if (inode->last_pos.inode != k.k->p.inode) {
1330                 ret = check_i_sectors(trans, inode);
1331                 if (ret)
1332                         goto err;
1333         }
1334
1335         i = walk_inode(trans, inode, equiv, k.k->type == KEY_TYPE_whiteout);
1336         ret = PTR_ERR_OR_ZERO(i);
1337         if (ret)
1338                 goto err;
1339
1340         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
1341         if (ret)
1342                 goto err;
1343
1344         if (k.k->type != KEY_TYPE_whiteout) {
1345                 if (fsck_err_on(!i, c,
1346                                 "extent in missing inode:\n  %s",
1347                                 (printbuf_reset(&buf),
1348                                  bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
1349                         goto delete;
1350
1351                 if (fsck_err_on(i &&
1352                                 !S_ISREG(i->inode.bi_mode) &&
1353                                 !S_ISLNK(i->inode.bi_mode), c,
1354                                 "extent in non regular inode mode %o:\n  %s",
1355                                 i->inode.bi_mode,
1356                                 (printbuf_reset(&buf),
1357                                  bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
1358                         goto delete;
1359
1360                 ret = check_overlapping_extents(trans, s, extent_ends, k,
1361                                                 equiv.snapshot, iter,
1362                                                 &inode->recalculate_sums);
1363                 if (ret)
1364                         goto err;
1365         }
1366
1367         /*
1368          * Check inodes in reverse order, from oldest snapshots to newest,
1369          * starting from the inode that matches this extent's snapshot. If we
1370          * didn't have one, iterate over all inodes:
1371          */
1372         if (!i)
1373                 i = inode->inodes.data + inode->inodes.nr - 1;
1374
1375         for (;
1376              inode->inodes.data && i >= inode->inodes.data;
1377              --i) {
1378                 if (i->snapshot > equiv.snapshot ||
1379                     !key_visible_in_snapshot(c, s, i->snapshot, equiv.snapshot))
1380                         continue;
1381
1382                 if (k.k->type != KEY_TYPE_whiteout) {
1383                         if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
1384                                         k.k->p.offset > round_up(i->inode.bi_size, block_bytes(c)) >> 9 &&
1385                                         !bkey_extent_is_reservation(k), c,
1386                                         "extent type past end of inode %llu:%u, i_size %llu\n  %s",
1387                                         i->inode.bi_inum, i->snapshot, i->inode.bi_size,
1388                                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1389                                 struct btree_iter iter2;
1390
1391                                 bch2_trans_copy_iter(&iter2, iter);
1392                                 bch2_btree_iter_set_snapshot(&iter2, i->snapshot);
1393                                 ret =   bch2_btree_iter_traverse(&iter2) ?:
1394                                         bch2_btree_delete_at(trans, &iter2,
1395                                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1396                                 bch2_trans_iter_exit(trans, &iter2);
1397                                 if (ret)
1398                                         goto err;
1399
1400                                 iter->k.type = KEY_TYPE_whiteout;
1401                         }
1402
1403                         if (bkey_extent_is_allocation(k.k))
1404                                 i->count += k.k->size;
1405                 }
1406
1407                 i->seen_this_pos = true;
1408         }
1409 out:
1410 err:
1411 fsck_err:
1412         printbuf_exit(&buf);
1413
1414         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1415                 bch_err_fn(c, ret);
1416         return ret;
1417 delete:
1418         ret = bch2_btree_delete_at(trans, iter, BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1419         goto out;
1420 }
1421
1422 /*
1423  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
1424  * that i_size an i_sectors are consistent
1425  */
1426 int bch2_check_extents(struct bch_fs *c)
1427 {
1428         struct inode_walker w = inode_walker_init();
1429         struct snapshots_seen s;
1430         struct btree_trans trans;
1431         struct btree_iter iter;
1432         struct bkey_s_c k;
1433         struct extent_ends extent_ends;
1434         struct disk_reservation res = { 0 };
1435         int ret = 0;
1436
1437         snapshots_seen_init(&s);
1438         extent_ends_init(&extent_ends);
1439         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 4096);
1440
1441         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_extents,
1442                         POS(BCACHEFS_ROOT_INO, 0),
1443                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
1444                         &res, NULL,
1445                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL, ({
1446                 bch2_disk_reservation_put(c, &res);
1447                 check_extent(&trans, &iter, k, &w, &s, &extent_ends);
1448         })) ?:
1449         check_i_sectors(&trans, &w);
1450
1451         bch2_disk_reservation_put(c, &res);
1452         extent_ends_exit(&extent_ends);
1453         inode_walker_exit(&w);
1454         bch2_trans_exit(&trans);
1455         snapshots_seen_exit(&s);
1456
1457         if (ret)
1458                 bch_err_fn(c, ret);
1459         return ret;
1460 }
1461
1462 static int check_subdir_count(struct btree_trans *trans, struct inode_walker *w)
1463 {
1464         struct bch_fs *c = trans->c;
1465         struct inode_walker_entry *i;
1466         u32 restart_count = trans->restart_count;
1467         int ret = 0;
1468         s64 count2;
1469
1470         darray_for_each(w->inodes, i) {
1471                 if (i->inode.bi_nlink == i->count)
1472                         continue;
1473
1474                 count2 = bch2_count_subdirs(trans, w->last_pos.inode, i->snapshot);
1475                 if (count2 < 0)
1476                         return count2;
1477
1478                 if (i->count != count2) {
1479                         bch_err(c, "fsck counted subdirectories wrong: got %llu should be %llu",
1480                                 i->count, count2);
1481                         i->count = count2;
1482                         if (i->inode.bi_nlink == i->count)
1483                                 continue;
1484                 }
1485
1486                 if (fsck_err_on(i->inode.bi_nlink != i->count, c,
1487                                 "directory %llu:%u with wrong i_nlink: got %u, should be %llu",
1488                                 w->last_pos.inode, i->snapshot, i->inode.bi_nlink, i->count)) {
1489                         i->inode.bi_nlink = i->count;
1490                         ret = write_inode(trans, &i->inode, i->snapshot);
1491                         if (ret)
1492                                 break;
1493                 }
1494         }
1495 fsck_err:
1496         if (ret)
1497                 bch_err_fn(c, ret);
1498         if (!ret && trans_was_restarted(trans, restart_count))
1499                 ret = -BCH_ERR_transaction_restart_nested;
1500         return ret;
1501 }
1502
1503 static int check_dirent_target(struct btree_trans *trans,
1504                                struct btree_iter *iter,
1505                                struct bkey_s_c_dirent d,
1506                                struct bch_inode_unpacked *target,
1507                                u32 target_snapshot)
1508 {
1509         struct bch_fs *c = trans->c;
1510         struct bkey_i_dirent *n;
1511         bool backpointer_exists = true;
1512         struct printbuf buf = PRINTBUF;
1513         int ret = 0;
1514
1515         if (!target->bi_dir &&
1516             !target->bi_dir_offset) {
1517                 target->bi_dir          = d.k->p.inode;
1518                 target->bi_dir_offset   = d.k->p.offset;
1519
1520                 ret = __write_inode(trans, target, target_snapshot);
1521                 if (ret)
1522                         goto err;
1523         }
1524
1525         if (!inode_points_to_dirent(target, d)) {
1526                 ret = inode_backpointer_exists(trans, target, d.k->p.snapshot);
1527                 if (ret < 0)
1528                         goto err;
1529
1530                 backpointer_exists = ret;
1531                 ret = 0;
1532
1533                 if (fsck_err_on(S_ISDIR(target->bi_mode) &&
1534                                 backpointer_exists, c,
1535                                 "directory %llu with multiple links",
1536                                 target->bi_inum)) {
1537                         ret = __remove_dirent(trans, d.k->p);
1538                         goto out;
1539                 }
1540
1541                 if (fsck_err_on(backpointer_exists &&
1542                                 !target->bi_nlink, c,
1543                                 "inode %llu type %s has multiple links but i_nlink 0",
1544                                 target->bi_inum, bch2_d_types[d.v->d_type])) {
1545                         target->bi_nlink++;
1546                         target->bi_flags &= ~BCH_INODE_UNLINKED;
1547
1548                         ret = __write_inode(trans, target, target_snapshot);
1549                         if (ret)
1550                                 goto err;
1551                 }
1552
1553                 if (fsck_err_on(!backpointer_exists, c,
1554                                 "inode %llu:%u has wrong backpointer:\n"
1555                                 "got       %llu:%llu\n"
1556                                 "should be %llu:%llu",
1557                                 target->bi_inum, target_snapshot,
1558                                 target->bi_dir,
1559                                 target->bi_dir_offset,
1560                                 d.k->p.inode,
1561                                 d.k->p.offset)) {
1562                         target->bi_dir          = d.k->p.inode;
1563                         target->bi_dir_offset   = d.k->p.offset;
1564
1565                         ret = __write_inode(trans, target, target_snapshot);
1566                         if (ret)
1567                                 goto err;
1568                 }
1569         }
1570
1571         if (fsck_err_on(d.v->d_type != inode_d_type(target), c,
1572                         "incorrect d_type: got %s, should be %s:\n%s",
1573                         bch2_d_type_str(d.v->d_type),
1574                         bch2_d_type_str(inode_d_type(target)),
1575                         (printbuf_reset(&buf),
1576                          bch2_bkey_val_to_text(&buf, c, d.s_c), buf.buf))) {
1577                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1578                 ret = PTR_ERR_OR_ZERO(n);
1579                 if (ret)
1580                         goto err;
1581
1582                 bkey_reassemble(&n->k_i, d.s_c);
1583                 n->v.d_type = inode_d_type(target);
1584
1585                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1586                 if (ret)
1587                         goto err;
1588
1589                 d = dirent_i_to_s_c(n);
1590         }
1591
1592         if (d.v->d_type == DT_SUBVOL &&
1593             target->bi_parent_subvol != le32_to_cpu(d.v->d_parent_subvol) &&
1594             (c->sb.version < bcachefs_metadata_version_subvol_dirent ||
1595              fsck_err(c, "dirent has wrong d_parent_subvol field: got %u, should be %u",
1596                       le32_to_cpu(d.v->d_parent_subvol),
1597                       target->bi_parent_subvol))) {
1598                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1599                 ret = PTR_ERR_OR_ZERO(n);
1600                 if (ret)
1601                         goto err;
1602
1603                 bkey_reassemble(&n->k_i, d.s_c);
1604                 n->v.d_parent_subvol = cpu_to_le32(target->bi_parent_subvol);
1605
1606                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1607                 if (ret)
1608                         goto err;
1609
1610                 d = dirent_i_to_s_c(n);
1611         }
1612 out:
1613 err:
1614 fsck_err:
1615         printbuf_exit(&buf);
1616
1617         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1618                 bch_err_fn(c, ret);
1619         return ret;
1620 }
1621
1622 static int check_dirent(struct btree_trans *trans, struct btree_iter *iter,
1623                         struct bkey_s_c k,
1624                         struct bch_hash_info *hash_info,
1625                         struct inode_walker *dir,
1626                         struct inode_walker *target,
1627                         struct snapshots_seen *s)
1628 {
1629         struct bch_fs *c = trans->c;
1630         struct bkey_s_c_dirent d;
1631         struct inode_walker_entry *i;
1632         struct printbuf buf = PRINTBUF;
1633         struct bpos equiv;
1634         int ret = 0;
1635
1636         ret = check_key_has_snapshot(trans, iter, k);
1637         if (ret) {
1638                 ret = ret < 0 ? ret : 0;
1639                 goto out;
1640         }
1641
1642         equiv = k.k->p;
1643         equiv.snapshot = bch2_snapshot_equiv(c, k.k->p.snapshot);
1644
1645         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
1646         if (ret)
1647                 goto err;
1648
1649         if (k.k->type == KEY_TYPE_whiteout)
1650                 goto out;
1651
1652         if (dir->last_pos.inode != k.k->p.inode) {
1653                 ret = check_subdir_count(trans, dir);
1654                 if (ret)
1655                         goto err;
1656         }
1657
1658         BUG_ON(!iter->path->should_be_locked);
1659
1660         i = walk_inode(trans, dir, equiv, k.k->type == KEY_TYPE_whiteout);
1661         ret = PTR_ERR_OR_ZERO(i);
1662         if (ret < 0)
1663                 goto err;
1664
1665         if (dir->first_this_inode && dir->inodes.nr)
1666                 *hash_info = bch2_hash_info_init(c, &dir->inodes.data[0].inode);
1667         dir->first_this_inode = false;
1668
1669         if (fsck_err_on(!i, c,
1670                         "dirent in nonexisting directory:\n%s",
1671                         (printbuf_reset(&buf),
1672                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1673                 ret = bch2_btree_delete_at(trans, iter,
1674                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1675                 goto out;
1676         }
1677
1678         if (!i)
1679                 goto out;
1680
1681         if (fsck_err_on(!S_ISDIR(i->inode.bi_mode), c,
1682                         "dirent in non directory inode type %s:\n%s",
1683                         bch2_d_type_str(inode_d_type(&i->inode)),
1684                         (printbuf_reset(&buf),
1685                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1686                 ret = bch2_btree_delete_at(trans, iter, 0);
1687                 goto out;
1688         }
1689
1690         ret = hash_check_key(trans, bch2_dirent_hash_desc, hash_info, iter, k);
1691         if (ret < 0)
1692                 goto err;
1693         if (ret) {
1694                 /* dirent has been deleted */
1695                 ret = 0;
1696                 goto out;
1697         }
1698
1699         if (k.k->type != KEY_TYPE_dirent)
1700                 goto out;
1701
1702         d = bkey_s_c_to_dirent(k);
1703
1704         if (d.v->d_type == DT_SUBVOL) {
1705                 struct bch_inode_unpacked subvol_root;
1706                 u32 target_subvol = le32_to_cpu(d.v->d_child_subvol);
1707                 u32 target_snapshot;
1708                 u64 target_inum;
1709
1710                 ret = __subvol_lookup(trans, target_subvol,
1711                                       &target_snapshot, &target_inum);
1712                 if (ret && !bch2_err_matches(ret, ENOENT))
1713                         goto err;
1714
1715                 if (fsck_err_on(ret, c,
1716                                 "dirent points to missing subvolume %u",
1717                                 le32_to_cpu(d.v->d_child_subvol))) {
1718                         ret = __remove_dirent(trans, d.k->p);
1719                         goto err;
1720                 }
1721
1722                 ret = __lookup_inode(trans, target_inum,
1723                                    &subvol_root, &target_snapshot);
1724                 if (ret && !bch2_err_matches(ret, ENOENT))
1725                         goto err;
1726
1727                 if (fsck_err_on(ret, c,
1728                                 "subvolume %u points to missing subvolume root %llu",
1729                                 target_subvol,
1730                                 target_inum)) {
1731                         bch_err(c, "repair not implemented yet");
1732                         ret = -EINVAL;
1733                         goto err;
1734                 }
1735
1736                 if (fsck_err_on(subvol_root.bi_subvol != target_subvol, c,
1737                                 "subvol root %llu has wrong bi_subvol field: got %u, should be %u",
1738                                 target_inum,
1739                                 subvol_root.bi_subvol, target_subvol)) {
1740                         subvol_root.bi_subvol = target_subvol;
1741                         ret = __write_inode(trans, &subvol_root, target_snapshot);
1742                         if (ret)
1743                                 goto err;
1744                 }
1745
1746                 ret = check_dirent_target(trans, iter, d, &subvol_root,
1747                                           target_snapshot);
1748                 if (ret)
1749                         goto err;
1750         } else {
1751                 ret = __get_visible_inodes(trans, target, s, le64_to_cpu(d.v->d_inum));
1752                 if (ret)
1753                         goto err;
1754
1755                 if (fsck_err_on(!target->inodes.nr, c,
1756                                 "dirent points to missing inode: (equiv %u)\n%s",
1757                                 equiv.snapshot,
1758                                 (printbuf_reset(&buf),
1759                                  bch2_bkey_val_to_text(&buf, c, k),
1760                                  buf.buf))) {
1761                         ret = __remove_dirent(trans, d.k->p);
1762                         if (ret)
1763                                 goto err;
1764                 }
1765
1766                 darray_for_each(target->inodes, i) {
1767                         ret = check_dirent_target(trans, iter, d,
1768                                                   &i->inode, i->snapshot);
1769                         if (ret)
1770                                 goto err;
1771                 }
1772         }
1773
1774         if (d.v->d_type == DT_DIR)
1775                 for_each_visible_inode(c, s, dir, equiv.snapshot, i)
1776                         i->count++;
1777
1778 out:
1779 err:
1780 fsck_err:
1781         printbuf_exit(&buf);
1782
1783         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1784                 bch_err_fn(c, ret);
1785         return ret;
1786 }
1787
1788 /*
1789  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
1790  * validate d_type
1791  */
1792 int bch2_check_dirents(struct bch_fs *c)
1793 {
1794         struct inode_walker dir = inode_walker_init();
1795         struct inode_walker target = inode_walker_init();
1796         struct snapshots_seen s;
1797         struct bch_hash_info hash_info;
1798         struct btree_trans trans;
1799         struct btree_iter iter;
1800         struct bkey_s_c k;
1801         int ret = 0;
1802
1803         snapshots_seen_init(&s);
1804         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1805
1806         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_dirents,
1807                         POS(BCACHEFS_ROOT_INO, 0),
1808                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1809                         k,
1810                         NULL, NULL,
1811                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
1812                 check_dirent(&trans, &iter, k, &hash_info, &dir, &target, &s));
1813
1814         bch2_trans_exit(&trans);
1815         snapshots_seen_exit(&s);
1816         inode_walker_exit(&dir);
1817         inode_walker_exit(&target);
1818
1819         if (ret)
1820                 bch_err_fn(c, ret);
1821         return ret;
1822 }
1823
1824 static int check_xattr(struct btree_trans *trans, struct btree_iter *iter,
1825                        struct bkey_s_c k,
1826                        struct bch_hash_info *hash_info,
1827                        struct inode_walker *inode)
1828 {
1829         struct bch_fs *c = trans->c;
1830         struct inode_walker_entry *i;
1831         int ret;
1832
1833         ret = check_key_has_snapshot(trans, iter, k);
1834         if (ret)
1835                 return ret;
1836
1837         i = walk_inode(trans, inode, k.k->p, k.k->type == KEY_TYPE_whiteout);
1838         ret = PTR_ERR_OR_ZERO(i);
1839         if (ret)
1840                 return ret;
1841
1842         if (inode->first_this_inode && inode->inodes.nr)
1843                 *hash_info = bch2_hash_info_init(c, &inode->inodes.data[0].inode);
1844         inode->first_this_inode = false;
1845
1846         if (fsck_err_on(!i, c,
1847                         "xattr for missing inode %llu",
1848                         k.k->p.inode))
1849                 return bch2_btree_delete_at(trans, iter, 0);
1850
1851         if (!i)
1852                 return 0;
1853
1854         ret = hash_check_key(trans, bch2_xattr_hash_desc, hash_info, iter, k);
1855 fsck_err:
1856         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1857                 bch_err_fn(c, ret);
1858         return ret;
1859 }
1860
1861 /*
1862  * Walk xattrs: verify that they all have a corresponding inode
1863  */
1864 int bch2_check_xattrs(struct bch_fs *c)
1865 {
1866         struct inode_walker inode = inode_walker_init();
1867         struct bch_hash_info hash_info;
1868         struct btree_trans trans;
1869         struct btree_iter iter;
1870         struct bkey_s_c k;
1871         int ret = 0;
1872
1873         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1874
1875         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_xattrs,
1876                         POS(BCACHEFS_ROOT_INO, 0),
1877                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1878                         k,
1879                         NULL, NULL,
1880                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
1881                 check_xattr(&trans, &iter, k, &hash_info, &inode));
1882
1883         bch2_trans_exit(&trans);
1884
1885         if (ret)
1886                 bch_err_fn(c, ret);
1887         return ret;
1888 }
1889
1890 static int check_root_trans(struct btree_trans *trans)
1891 {
1892         struct bch_fs *c = trans->c;
1893         struct bch_inode_unpacked root_inode;
1894         u32 snapshot;
1895         u64 inum;
1896         int ret;
1897
1898         ret = __subvol_lookup(trans, BCACHEFS_ROOT_SUBVOL, &snapshot, &inum);
1899         if (ret && !bch2_err_matches(ret, ENOENT))
1900                 return ret;
1901
1902         if (mustfix_fsck_err_on(ret, c, "root subvol missing")) {
1903                 struct bkey_i_subvolume root_subvol;
1904
1905                 snapshot        = U32_MAX;
1906                 inum            = BCACHEFS_ROOT_INO;
1907
1908                 bkey_subvolume_init(&root_subvol.k_i);
1909                 root_subvol.k.p.offset = BCACHEFS_ROOT_SUBVOL;
1910                 root_subvol.v.flags     = 0;
1911                 root_subvol.v.snapshot  = cpu_to_le32(snapshot);
1912                 root_subvol.v.inode     = cpu_to_le64(inum);
1913                 ret = commit_do(trans, NULL, NULL,
1914                                       BTREE_INSERT_NOFAIL|
1915                                       BTREE_INSERT_LAZY_RW,
1916                         __bch2_btree_insert(trans, BTREE_ID_subvolumes,
1917                                             &root_subvol.k_i, 0));
1918                 if (ret) {
1919                         bch_err(c, "error writing root subvol: %s", bch2_err_str(ret));
1920                         goto err;
1921                 }
1922
1923         }
1924
1925         ret = __lookup_inode(trans, BCACHEFS_ROOT_INO, &root_inode, &snapshot);
1926         if (ret && !bch2_err_matches(ret, ENOENT))
1927                 return ret;
1928
1929         if (mustfix_fsck_err_on(ret, c, "root directory missing") ||
1930             mustfix_fsck_err_on(!S_ISDIR(root_inode.bi_mode), c,
1931                                 "root inode not a directory")) {
1932                 bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755,
1933                                 0, NULL);
1934                 root_inode.bi_inum = inum;
1935
1936                 ret = __write_inode(trans, &root_inode, snapshot);
1937                 if (ret)
1938                         bch_err(c, "error writing root inode: %s", bch2_err_str(ret));
1939         }
1940 err:
1941 fsck_err:
1942         return ret;
1943 }
1944
1945 /* Get root directory, create if it doesn't exist: */
1946 int bch2_check_root(struct bch_fs *c)
1947 {
1948         int ret;
1949
1950         ret = bch2_trans_do(c, NULL, NULL,
1951                              BTREE_INSERT_NOFAIL|
1952                              BTREE_INSERT_LAZY_RW,
1953                 check_root_trans(&trans));
1954
1955         if (ret)
1956                 bch_err_fn(c, ret);
1957         return ret;
1958 }
1959
1960 struct pathbuf_entry {
1961         u64     inum;
1962         u32     snapshot;
1963 };
1964
1965 typedef DARRAY(struct pathbuf_entry) pathbuf;
1966
1967 static bool path_is_dup(pathbuf *p, u64 inum, u32 snapshot)
1968 {
1969         struct pathbuf_entry *i;
1970
1971         darray_for_each(*p, i)
1972                 if (i->inum     == inum &&
1973                     i->snapshot == snapshot)
1974                         return true;
1975
1976         return false;
1977 }
1978
1979 static int path_down(struct bch_fs *c, pathbuf *p,
1980                      u64 inum, u32 snapshot)
1981 {
1982         int ret = darray_push(p, ((struct pathbuf_entry) {
1983                 .inum           = inum,
1984                 .snapshot       = snapshot,
1985         }));
1986
1987         if (ret)
1988                 bch_err(c, "fsck: error allocating memory for pathbuf, size %zu",
1989                         p->size);
1990         return ret;
1991 }
1992
1993 /*
1994  * Check that a given inode is reachable from the root:
1995  *
1996  * XXX: we should also be verifying that inodes are in the right subvolumes
1997  */
1998 static int check_path(struct btree_trans *trans,
1999                       pathbuf *p,
2000                       struct bch_inode_unpacked *inode,
2001                       u32 snapshot)
2002 {
2003         struct bch_fs *c = trans->c;
2004         int ret = 0;
2005
2006         snapshot = bch2_snapshot_equiv(c, snapshot);
2007         p->nr = 0;
2008
2009         while (!(inode->bi_inum == BCACHEFS_ROOT_INO &&
2010                  inode->bi_subvol == BCACHEFS_ROOT_SUBVOL)) {
2011                 struct btree_iter dirent_iter;
2012                 struct bkey_s_c_dirent d;
2013                 u32 parent_snapshot = snapshot;
2014
2015                 if (inode->bi_subvol) {
2016                         u64 inum;
2017
2018                         ret = subvol_lookup(trans, inode->bi_parent_subvol,
2019                                             &parent_snapshot, &inum);
2020                         if (ret)
2021                                 break;
2022                 }
2023
2024                 ret = lockrestart_do(trans,
2025                         PTR_ERR_OR_ZERO((d = dirent_get_by_pos(trans, &dirent_iter,
2026                                           SPOS(inode->bi_dir, inode->bi_dir_offset,
2027                                                parent_snapshot))).k));
2028                 if (ret && !bch2_err_matches(ret, ENOENT))
2029                         break;
2030
2031                 if (!ret && !dirent_points_to_inode(d, inode)) {
2032                         bch2_trans_iter_exit(trans, &dirent_iter);
2033                         ret = -BCH_ERR_ENOENT_dirent_doesnt_match_inode;
2034                 }
2035
2036                 if (bch2_err_matches(ret, ENOENT)) {
2037                         if (fsck_err(c,  "unreachable inode %llu:%u, type %s nlink %u backptr %llu:%llu",
2038                                      inode->bi_inum, snapshot,
2039                                      bch2_d_type_str(inode_d_type(inode)),
2040                                      inode->bi_nlink,
2041                                      inode->bi_dir,
2042                                      inode->bi_dir_offset))
2043                                 ret = reattach_inode(trans, inode, snapshot);
2044                         break;
2045                 }
2046
2047                 bch2_trans_iter_exit(trans, &dirent_iter);
2048
2049                 if (!S_ISDIR(inode->bi_mode))
2050                         break;
2051
2052                 ret = path_down(c, p, inode->bi_inum, snapshot);
2053                 if (ret) {
2054                         bch_err(c, "memory allocation failure");
2055                         return ret;
2056                 }
2057
2058                 snapshot = parent_snapshot;
2059
2060                 ret = lookup_inode(trans, inode->bi_dir, inode, &snapshot);
2061                 if (ret) {
2062                         /* Should have been caught in dirents pass */
2063                         bch_err(c, "error looking up parent directory: %i", ret);
2064                         break;
2065                 }
2066
2067                 if (path_is_dup(p, inode->bi_inum, snapshot)) {
2068                         struct pathbuf_entry *i;
2069
2070                         /* XXX print path */
2071                         bch_err(c, "directory structure loop");
2072
2073                         darray_for_each(*p, i)
2074                                 pr_err("%llu:%u", i->inum, i->snapshot);
2075                         pr_err("%llu:%u", inode->bi_inum, snapshot);
2076
2077                         if (!fsck_err(c, "directory structure loop"))
2078                                 return 0;
2079
2080                         ret = commit_do(trans, NULL, NULL,
2081                                               BTREE_INSERT_NOFAIL|
2082                                               BTREE_INSERT_LAZY_RW,
2083                                         remove_backpointer(trans, inode));
2084                         if (ret) {
2085                                 bch_err(c, "error removing dirent: %i", ret);
2086                                 break;
2087                         }
2088
2089                         ret = reattach_inode(trans, inode, snapshot);
2090                 }
2091         }
2092 fsck_err:
2093         if (ret)
2094                 bch_err_fn(c, ret);
2095         return ret;
2096 }
2097
2098 /*
2099  * Check for unreachable inodes, as well as loops in the directory structure:
2100  * After bch2_check_dirents(), if an inode backpointer doesn't exist that means it's
2101  * unreachable:
2102  */
2103 int bch2_check_directory_structure(struct bch_fs *c)
2104 {
2105         struct btree_trans trans;
2106         struct btree_iter iter;
2107         struct bkey_s_c k;
2108         struct bch_inode_unpacked u;
2109         pathbuf path = { 0, };
2110         int ret;
2111
2112         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2113
2114         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN,
2115                            BTREE_ITER_INTENT|
2116                            BTREE_ITER_PREFETCH|
2117                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2118                 if (!bkey_is_inode(k.k))
2119                         continue;
2120
2121                 ret = bch2_inode_unpack(k, &u);
2122                 if (ret) {
2123                         /* Should have been caught earlier in fsck: */
2124                         bch_err(c, "error unpacking inode %llu: %i", k.k->p.offset, ret);
2125                         break;
2126                 }
2127
2128                 if (u.bi_flags & BCH_INODE_UNLINKED)
2129                         continue;
2130
2131                 ret = check_path(&trans, &path, &u, iter.pos.snapshot);
2132                 if (ret)
2133                         break;
2134         }
2135         bch2_trans_iter_exit(&trans, &iter);
2136         bch2_trans_exit(&trans);
2137         darray_exit(&path);
2138
2139         if (ret)
2140                 bch_err_fn(c, ret);
2141         return ret;
2142 }
2143
2144 /* check_nlink pass: */
2145
2146 struct nlink_table {
2147         size_t          nr;
2148         size_t          size;
2149
2150         struct nlink {
2151                 u64     inum;
2152                 u32     snapshot;
2153                 u32     count;
2154         }               *d;
2155 };
2156
2157 static int add_nlink(struct bch_fs *c, struct nlink_table *t,
2158                      u64 inum, u32 snapshot)
2159 {
2160         if (t->nr == t->size) {
2161                 size_t new_size = max_t(size_t, 128UL, t->size * 2);
2162                 void *d = kvmalloc_array(new_size, sizeof(t->d[0]), GFP_KERNEL);
2163
2164                 if (!d) {
2165                         bch_err(c, "fsck: error allocating memory for nlink_table, size %zu",
2166                                 new_size);
2167                         return -BCH_ERR_ENOMEM_fsck_add_nlink;
2168                 }
2169
2170                 if (t->d)
2171                         memcpy(d, t->d, t->size * sizeof(t->d[0]));
2172                 kvfree(t->d);
2173
2174                 t->d = d;
2175                 t->size = new_size;
2176         }
2177
2178
2179         t->d[t->nr++] = (struct nlink) {
2180                 .inum           = inum,
2181                 .snapshot       = snapshot,
2182         };
2183
2184         return 0;
2185 }
2186
2187 static int nlink_cmp(const void *_l, const void *_r)
2188 {
2189         const struct nlink *l = _l;
2190         const struct nlink *r = _r;
2191
2192         return cmp_int(l->inum, r->inum) ?: cmp_int(l->snapshot, r->snapshot);
2193 }
2194
2195 static void inc_link(struct bch_fs *c, struct snapshots_seen *s,
2196                      struct nlink_table *links,
2197                      u64 range_start, u64 range_end, u64 inum, u32 snapshot)
2198 {
2199         struct nlink *link, key = {
2200                 .inum = inum, .snapshot = U32_MAX,
2201         };
2202
2203         if (inum < range_start || inum >= range_end)
2204                 return;
2205
2206         link = __inline_bsearch(&key, links->d, links->nr,
2207                                 sizeof(links->d[0]), nlink_cmp);
2208         if (!link)
2209                 return;
2210
2211         while (link > links->d && link[0].inum == link[-1].inum)
2212                 --link;
2213
2214         for (; link < links->d + links->nr && link->inum == inum; link++)
2215                 if (ref_visible(c, s, snapshot, link->snapshot)) {
2216                         link->count++;
2217                         if (link->snapshot >= snapshot)
2218                                 break;
2219                 }
2220 }
2221
2222 noinline_for_stack
2223 static int check_nlinks_find_hardlinks(struct bch_fs *c,
2224                                        struct nlink_table *t,
2225                                        u64 start, u64 *end)
2226 {
2227         struct btree_trans trans;
2228         struct btree_iter iter;
2229         struct bkey_s_c k;
2230         struct bch_inode_unpacked u;
2231         int ret = 0;
2232
2233         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2234
2235         for_each_btree_key(&trans, iter, BTREE_ID_inodes,
2236                            POS(0, start),
2237                            BTREE_ITER_INTENT|
2238                            BTREE_ITER_PREFETCH|
2239                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2240                 if (!bkey_is_inode(k.k))
2241                         continue;
2242
2243                 /* Should never fail, checked by bch2_inode_invalid: */
2244                 BUG_ON(bch2_inode_unpack(k, &u));
2245
2246                 /*
2247                  * Backpointer and directory structure checks are sufficient for
2248                  * directories, since they can't have hardlinks:
2249                  */
2250                 if (S_ISDIR(u.bi_mode))
2251                         continue;
2252
2253                 if (!u.bi_nlink)
2254                         continue;
2255
2256                 ret = add_nlink(c, t, k.k->p.offset, k.k->p.snapshot);
2257                 if (ret) {
2258                         *end = k.k->p.offset;
2259                         ret = 0;
2260                         break;
2261                 }
2262
2263         }
2264         bch2_trans_iter_exit(&trans, &iter);
2265         bch2_trans_exit(&trans);
2266
2267         if (ret)
2268                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2269
2270         return ret;
2271 }
2272
2273 noinline_for_stack
2274 static int check_nlinks_walk_dirents(struct bch_fs *c, struct nlink_table *links,
2275                                      u64 range_start, u64 range_end)
2276 {
2277         struct btree_trans trans;
2278         struct snapshots_seen s;
2279         struct btree_iter iter;
2280         struct bkey_s_c k;
2281         struct bkey_s_c_dirent d;
2282         int ret;
2283
2284         snapshots_seen_init(&s);
2285
2286         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2287
2288         for_each_btree_key(&trans, iter, BTREE_ID_dirents, POS_MIN,
2289                            BTREE_ITER_INTENT|
2290                            BTREE_ITER_PREFETCH|
2291                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2292                 ret = snapshots_seen_update(c, &s, iter.btree_id, k.k->p);
2293                 if (ret)
2294                         break;
2295
2296                 switch (k.k->type) {
2297                 case KEY_TYPE_dirent:
2298                         d = bkey_s_c_to_dirent(k);
2299
2300                         if (d.v->d_type != DT_DIR &&
2301                             d.v->d_type != DT_SUBVOL)
2302                                 inc_link(c, &s, links, range_start, range_end,
2303                                          le64_to_cpu(d.v->d_inum),
2304                                          bch2_snapshot_equiv(c, d.k->p.snapshot));
2305                         break;
2306                 }
2307         }
2308         bch2_trans_iter_exit(&trans, &iter);
2309
2310         if (ret)
2311                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
2312
2313         bch2_trans_exit(&trans);
2314         snapshots_seen_exit(&s);
2315         return ret;
2316 }
2317
2318 static int check_nlinks_update_inode(struct btree_trans *trans, struct btree_iter *iter,
2319                                      struct bkey_s_c k,
2320                                      struct nlink_table *links,
2321                                      size_t *idx, u64 range_end)
2322 {
2323         struct bch_fs *c = trans->c;
2324         struct bch_inode_unpacked u;
2325         struct nlink *link = &links->d[*idx];
2326         int ret = 0;
2327
2328         if (k.k->p.offset >= range_end)
2329                 return 1;
2330
2331         if (!bkey_is_inode(k.k))
2332                 return 0;
2333
2334         BUG_ON(bch2_inode_unpack(k, &u));
2335
2336         if (S_ISDIR(u.bi_mode))
2337                 return 0;
2338
2339         if (!u.bi_nlink)
2340                 return 0;
2341
2342         while ((cmp_int(link->inum, k.k->p.offset) ?:
2343                 cmp_int(link->snapshot, k.k->p.snapshot)) < 0) {
2344                 BUG_ON(*idx == links->nr);
2345                 link = &links->d[++*idx];
2346         }
2347
2348         if (fsck_err_on(bch2_inode_nlink_get(&u) != link->count, c,
2349                         "inode %llu type %s has wrong i_nlink (%u, should be %u)",
2350                         u.bi_inum, bch2_d_types[mode_to_type(u.bi_mode)],
2351                         bch2_inode_nlink_get(&u), link->count)) {
2352                 bch2_inode_nlink_set(&u, link->count);
2353                 ret = __write_inode(trans, &u, k.k->p.snapshot);
2354         }
2355 fsck_err:
2356         return ret;
2357 }
2358
2359 noinline_for_stack
2360 static int check_nlinks_update_hardlinks(struct bch_fs *c,
2361                                struct nlink_table *links,
2362                                u64 range_start, u64 range_end)
2363 {
2364         struct btree_trans trans;
2365         struct btree_iter iter;
2366         struct bkey_s_c k;
2367         size_t idx = 0;
2368         int ret = 0;
2369
2370         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2371
2372         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_inodes,
2373                         POS(0, range_start),
2374                         BTREE_ITER_INTENT|BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
2375                         NULL, NULL, BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
2376                 check_nlinks_update_inode(&trans, &iter, k, links, &idx, range_end));
2377
2378         bch2_trans_exit(&trans);
2379
2380         if (ret < 0) {
2381                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2382                 return ret;
2383         }
2384
2385         return 0;
2386 }
2387
2388 int bch2_check_nlinks(struct bch_fs *c)
2389 {
2390         struct nlink_table links = { 0 };
2391         u64 this_iter_range_start, next_iter_range_start = 0;
2392         int ret = 0;
2393
2394         do {
2395                 this_iter_range_start = next_iter_range_start;
2396                 next_iter_range_start = U64_MAX;
2397
2398                 ret = check_nlinks_find_hardlinks(c, &links,
2399                                                   this_iter_range_start,
2400                                                   &next_iter_range_start);
2401
2402                 ret = check_nlinks_walk_dirents(c, &links,
2403                                           this_iter_range_start,
2404                                           next_iter_range_start);
2405                 if (ret)
2406                         break;
2407
2408                 ret = check_nlinks_update_hardlinks(c, &links,
2409                                          this_iter_range_start,
2410                                          next_iter_range_start);
2411                 if (ret)
2412                         break;
2413
2414                 links.nr = 0;
2415         } while (next_iter_range_start != U64_MAX);
2416
2417         kvfree(links.d);
2418
2419         if (ret)
2420                 bch_err_fn(c, ret);
2421         return ret;
2422 }
2423
2424 static int fix_reflink_p_key(struct btree_trans *trans, struct btree_iter *iter,
2425                              struct bkey_s_c k)
2426 {
2427         struct bkey_s_c_reflink_p p;
2428         struct bkey_i_reflink_p *u;
2429         int ret;
2430
2431         if (k.k->type != KEY_TYPE_reflink_p)
2432                 return 0;
2433
2434         p = bkey_s_c_to_reflink_p(k);
2435
2436         if (!p.v->front_pad && !p.v->back_pad)
2437                 return 0;
2438
2439         u = bch2_trans_kmalloc(trans, sizeof(*u));
2440         ret = PTR_ERR_OR_ZERO(u);
2441         if (ret)
2442                 return ret;
2443
2444         bkey_reassemble(&u->k_i, k);
2445         u->v.front_pad  = 0;
2446         u->v.back_pad   = 0;
2447
2448         return bch2_trans_update(trans, iter, &u->k_i, BTREE_TRIGGER_NORUN);
2449 }
2450
2451 int bch2_fix_reflink_p(struct bch_fs *c)
2452 {
2453         struct btree_iter iter;
2454         struct bkey_s_c k;
2455         int ret;
2456
2457         if (c->sb.version >= bcachefs_metadata_version_reflink_p_fix)
2458                 return 0;
2459
2460         ret = bch2_trans_run(c,
2461                 for_each_btree_key_commit(&trans, iter,
2462                                 BTREE_ID_extents, POS_MIN,
2463                                 BTREE_ITER_INTENT|BTREE_ITER_PREFETCH|
2464                                 BTREE_ITER_ALL_SNAPSHOTS, k,
2465                                 NULL, NULL, BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
2466                         fix_reflink_p_key(&trans, &iter, k)));
2467
2468         if (ret)
2469                 bch_err_fn(c, ret);
2470         return ret;
2471 }