]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
Update bcachefs sources to 1336a995cbc3 bcachefs: Silence transaction restart error...
[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 found", 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_msg(trans->c, ret, "fetching inode %llu", inode_nr);
131         bch2_trans_iter_exit(trans, &iter);
132         return ret;
133 }
134
135 static int __lookup_inode(struct btree_trans *trans, u64 inode_nr,
136                           struct bch_inode_unpacked *inode,
137                           u32 *snapshot)
138 {
139         struct btree_iter iter;
140         struct bkey_s_c k;
141         int ret;
142
143         k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
144                                SPOS(0, inode_nr, *snapshot), 0);
145         ret = bkey_err(k);
146         if (ret)
147                 goto err;
148
149         ret = bkey_is_inode(k.k)
150                 ? bch2_inode_unpack(k, inode)
151                 : -BCH_ERR_ENOENT_inode;
152         if (!ret)
153                 *snapshot = iter.pos.snapshot;
154 err:
155         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
156                 bch_err_msg(trans->c, ret, "fetching inode %llu:%u", inode_nr, *snapshot);
157         bch2_trans_iter_exit(trans, &iter);
158         return ret;
159 }
160
161 static int lookup_inode(struct btree_trans *trans, u64 inode_nr,
162                         struct bch_inode_unpacked *inode,
163                         u32 *snapshot)
164 {
165         return lockrestart_do(trans, __lookup_inode(trans, inode_nr, inode, snapshot));
166 }
167
168 static int __lookup_dirent(struct btree_trans *trans,
169                            struct bch_hash_info hash_info,
170                            subvol_inum dir, struct qstr *name,
171                            u64 *target, unsigned *type)
172 {
173         struct btree_iter iter;
174         struct bkey_s_c_dirent d;
175         int ret;
176
177         ret = bch2_hash_lookup(trans, &iter, bch2_dirent_hash_desc,
178                                &hash_info, dir, name, 0);
179         if (ret)
180                 return ret;
181
182         d = bkey_s_c_to_dirent(bch2_btree_iter_peek_slot(&iter));
183         *target = le64_to_cpu(d.v->d_inum);
184         *type = d.v->d_type;
185         bch2_trans_iter_exit(trans, &iter);
186         return 0;
187 }
188
189 static int __write_inode(struct btree_trans *trans,
190                          struct bch_inode_unpacked *inode,
191                          u32 snapshot)
192 {
193         struct bkey_inode_buf *inode_p =
194                 bch2_trans_kmalloc(trans, sizeof(*inode_p));
195
196         if (IS_ERR(inode_p))
197                 return PTR_ERR(inode_p);
198
199         bch2_inode_pack(inode_p, inode);
200         inode_p->inode.k.p.snapshot = snapshot;
201
202         return bch2_btree_insert_nonextent(trans, BTREE_ID_inodes,
203                                 &inode_p->inode.k_i,
204                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
205 }
206
207 static int fsck_write_inode(struct btree_trans *trans,
208                             struct bch_inode_unpacked *inode,
209                             u32 snapshot)
210 {
211         int ret = commit_do(trans, NULL, NULL,
212                                   BTREE_INSERT_NOFAIL|
213                                   BTREE_INSERT_LAZY_RW,
214                                   __write_inode(trans, inode, snapshot));
215         if (ret)
216                 bch_err_fn(trans->c, ret);
217         return ret;
218 }
219
220 static int __remove_dirent(struct btree_trans *trans, struct bpos pos)
221 {
222         struct bch_fs *c = trans->c;
223         struct btree_iter iter;
224         struct bch_inode_unpacked dir_inode;
225         struct bch_hash_info dir_hash_info;
226         int ret;
227
228         ret = lookup_first_inode(trans, pos.inode, &dir_inode);
229         if (ret)
230                 goto err;
231
232         dir_hash_info = bch2_hash_info_init(c, &dir_inode);
233
234         bch2_trans_iter_init(trans, &iter, BTREE_ID_dirents, pos, BTREE_ITER_INTENT);
235
236         ret = bch2_hash_delete_at(trans, bch2_dirent_hash_desc,
237                                   &dir_hash_info, &iter,
238                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
239         bch2_trans_iter_exit(trans, &iter);
240 err:
241         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
242                 bch_err_fn(c, ret);
243         return ret;
244 }
245
246 /* Get lost+found, create if it doesn't exist: */
247 static int lookup_lostfound(struct btree_trans *trans, u32 subvol,
248                             struct bch_inode_unpacked *lostfound)
249 {
250         struct bch_fs *c = trans->c;
251         struct bch_inode_unpacked root;
252         struct bch_hash_info root_hash_info;
253         struct qstr lostfound_str = QSTR("lost+found");
254         subvol_inum root_inum = { .subvol = subvol };
255         u64 inum = 0;
256         unsigned d_type = 0;
257         u32 snapshot;
258         int ret;
259
260         ret = __subvol_lookup(trans, subvol, &snapshot, &root_inum.inum);
261         if (ret)
262                 return ret;
263
264         ret = __lookup_inode(trans, root_inum.inum, &root, &snapshot);
265         if (ret)
266                 return ret;
267
268         root_hash_info = bch2_hash_info_init(c, &root);
269
270         ret = __lookup_dirent(trans, root_hash_info, root_inum,
271                             &lostfound_str, &inum, &d_type);
272         if (bch2_err_matches(ret, ENOENT)) {
273                 bch_notice(c, "creating lost+found");
274                 goto create_lostfound;
275         }
276
277         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
278                 bch_err_fn(c, ret);
279         if (ret)
280                 return ret;
281
282         if (d_type != DT_DIR) {
283                 bch_err(c, "error looking up lost+found: not a directory");
284                 return -BCH_ERR_ENOENT_not_directory;
285         }
286
287         /*
288          * The bch2_check_dirents pass has already run, dangling dirents
289          * shouldn't exist here:
290          */
291         return __lookup_inode(trans, inum, lostfound, &snapshot);
292
293 create_lostfound:
294         bch2_inode_init_early(c, lostfound);
295
296         ret = bch2_create_trans(trans, root_inum, &root,
297                                 lostfound, &lostfound_str,
298                                 0, 0, S_IFDIR|0700, 0, NULL, NULL,
299                                 (subvol_inum) { }, 0);
300         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
301                 bch_err_msg(c, ret, "creating lost+found");
302         return ret;
303 }
304
305 static int __reattach_inode(struct btree_trans *trans,
306                           struct bch_inode_unpacked *inode,
307                           u32 inode_snapshot)
308 {
309         struct bch_hash_info dir_hash;
310         struct bch_inode_unpacked lostfound;
311         char name_buf[20];
312         struct qstr name;
313         u64 dir_offset = 0;
314         u32 subvol;
315         int ret;
316
317         ret = __snapshot_lookup_subvol(trans, inode_snapshot, &subvol);
318         if (ret)
319                 return ret;
320
321         ret = lookup_lostfound(trans, subvol, &lostfound);
322         if (ret)
323                 return ret;
324
325         if (S_ISDIR(inode->bi_mode)) {
326                 lostfound.bi_nlink++;
327
328                 ret = __write_inode(trans, &lostfound, U32_MAX);
329                 if (ret)
330                         return ret;
331         }
332
333         dir_hash = bch2_hash_info_init(trans->c, &lostfound);
334
335         snprintf(name_buf, sizeof(name_buf), "%llu", inode->bi_inum);
336         name = (struct qstr) QSTR(name_buf);
337
338         ret = bch2_dirent_create(trans,
339                                  (subvol_inum) {
340                                         .subvol = subvol,
341                                         .inum = lostfound.bi_inum,
342                                  },
343                                  &dir_hash,
344                                  inode_d_type(inode),
345                                  &name, inode->bi_inum, &dir_offset,
346                                  BCH_HASH_SET_MUST_CREATE);
347         if (ret)
348                 return ret;
349
350         inode->bi_dir           = lostfound.bi_inum;
351         inode->bi_dir_offset    = dir_offset;
352
353         return __write_inode(trans, inode, inode_snapshot);
354 }
355
356 static int reattach_inode(struct btree_trans *trans,
357                           struct bch_inode_unpacked *inode,
358                           u32 inode_snapshot)
359 {
360         int ret = commit_do(trans, NULL, NULL,
361                                   BTREE_INSERT_LAZY_RW|
362                                   BTREE_INSERT_NOFAIL,
363                         __reattach_inode(trans, inode, inode_snapshot));
364         if (ret) {
365                 bch_err_msg(trans->c, ret, "reattaching inode %llu", inode->bi_inum);
366                 return ret;
367         }
368
369         return ret;
370 }
371
372 static int remove_backpointer(struct btree_trans *trans,
373                               struct bch_inode_unpacked *inode)
374 {
375         struct btree_iter iter;
376         struct bkey_s_c_dirent d;
377         int ret;
378
379         d = bch2_bkey_get_iter_typed(trans, &iter, BTREE_ID_dirents,
380                                      POS(inode->bi_dir, inode->bi_dir_offset), 0,
381                                      dirent);
382         ret =   bkey_err(d) ?:
383                 __remove_dirent(trans, d.k->p);
384         bch2_trans_iter_exit(trans, &iter);
385         return ret;
386 }
387
388 struct snapshots_seen_entry {
389         u32                             id;
390         u32                             equiv;
391 };
392
393 struct snapshots_seen {
394         struct bpos                     pos;
395         DARRAY(struct snapshots_seen_entry) ids;
396 };
397
398 static inline void snapshots_seen_exit(struct snapshots_seen *s)
399 {
400         darray_exit(&s->ids);
401 }
402
403 static inline void snapshots_seen_init(struct snapshots_seen *s)
404 {
405         memset(s, 0, sizeof(*s));
406 }
407
408 static int snapshots_seen_add_inorder(struct bch_fs *c, struct snapshots_seen *s, u32 id)
409 {
410         struct snapshots_seen_entry *i, n = {
411                 .id     = id,
412                 .equiv  = bch2_snapshot_equiv(c, id),
413         };
414         int ret = 0;
415
416         darray_for_each(s->ids, i) {
417                 if (i->id == id)
418                         return 0;
419                 if (i->id > id)
420                         break;
421         }
422
423         ret = darray_insert_item(&s->ids, i - s->ids.data, n);
424         if (ret)
425                 bch_err(c, "error reallocating snapshots_seen table (size %zu)",
426                         s->ids.size);
427         return ret;
428 }
429
430 static int snapshots_seen_update(struct bch_fs *c, struct snapshots_seen *s,
431                                  enum btree_id btree_id, struct bpos pos)
432 {
433         struct snapshots_seen_entry *i, n = {
434                 .id     = pos.snapshot,
435                 .equiv  = bch2_snapshot_equiv(c, pos.snapshot),
436         };
437         int ret = 0;
438
439         if (!bkey_eq(s->pos, pos))
440                 s->ids.nr = 0;
441
442         s->pos = pos;
443         s->pos.snapshot = n.equiv;
444
445         darray_for_each(s->ids, i) {
446                 if (i->id == n.id)
447                         return 0;
448
449                 /*
450                  * We currently don't rigorously track for snapshot cleanup
451                  * needing to be run, so it shouldn't be a fsck error yet:
452                  */
453                 if (i->equiv == n.equiv) {
454                         bch_err(c, "snapshot deletion did not finish:\n"
455                                 "  duplicate keys in btree %s at %llu:%llu snapshots %u, %u (equiv %u)\n",
456                                 bch2_btree_ids[btree_id],
457                                 pos.inode, pos.offset,
458                                 i->id, n.id, n.equiv);
459                         return bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_delete_dead_snapshots);
460                 }
461         }
462
463         ret = darray_push(&s->ids, n);
464         if (ret)
465                 bch_err(c, "error reallocating snapshots_seen table (size %zu)",
466                         s->ids.size);
467         return ret;
468 }
469
470 /**
471  * key_visible_in_snapshot - returns true if @id is a descendent of @ancestor,
472  * and @ancestor hasn't been overwritten in @seen
473  *
474  * @c:          filesystem handle
475  * @seen:       list of snapshot ids already seen at current position
476  * @id:         descendent snapshot id
477  * @ancestor:   ancestor snapshot id
478  *
479  * Returns:     whether key in @ancestor snapshot is visible in @id snapshot
480  */
481 static bool key_visible_in_snapshot(struct bch_fs *c, struct snapshots_seen *seen,
482                                     u32 id, u32 ancestor)
483 {
484         ssize_t i;
485
486         EBUG_ON(id > ancestor);
487         EBUG_ON(!bch2_snapshot_is_equiv(c, id));
488         EBUG_ON(!bch2_snapshot_is_equiv(c, ancestor));
489
490         /* @ancestor should be the snapshot most recently added to @seen */
491         EBUG_ON(ancestor != seen->pos.snapshot);
492         EBUG_ON(ancestor != seen->ids.data[seen->ids.nr - 1].equiv);
493
494         if (id == ancestor)
495                 return true;
496
497         if (!bch2_snapshot_is_ancestor(c, id, ancestor))
498                 return false;
499
500         /*
501          * We know that @id is a descendant of @ancestor, we're checking if
502          * we've seen a key that overwrote @ancestor - i.e. also a descendent of
503          * @ascestor and with @id as a descendent.
504          *
505          * But we already know that we're scanning IDs between @id and @ancestor
506          * numerically, since snapshot ID lists are kept sorted, so if we find
507          * an id that's an ancestor of @id we're done:
508          */
509
510         for (i = seen->ids.nr - 2;
511              i >= 0 && seen->ids.data[i].equiv >= id;
512              --i)
513                 if (bch2_snapshot_is_ancestor(c, id, seen->ids.data[i].equiv))
514                         return false;
515
516         return true;
517 }
518
519 /**
520  * ref_visible - given a key with snapshot id @src that points to a key with
521  * snapshot id @dst, test whether there is some snapshot in which @dst is
522  * visible.
523  *
524  * @c:          filesystem handle
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  * Returns:     true if there is some snapshot in which @dst is visible
529  *
530  * Assumes we're visiting @src keys in natural key order
531  */
532 static bool ref_visible(struct bch_fs *c, struct snapshots_seen *s,
533                         u32 src, u32 dst)
534 {
535         return dst <= src
536                 ? key_visible_in_snapshot(c, s, dst, src)
537                 : bch2_snapshot_is_ancestor(c, src, dst);
538 }
539
540 static int ref_visible2(struct bch_fs *c,
541                         u32 src, struct snapshots_seen *src_seen,
542                         u32 dst, struct snapshots_seen *dst_seen)
543 {
544         src = bch2_snapshot_equiv(c, src);
545         dst = bch2_snapshot_equiv(c, dst);
546
547         if (dst > src) {
548                 swap(dst, src);
549                 swap(dst_seen, src_seen);
550         }
551         return key_visible_in_snapshot(c, src_seen, dst, src);
552 }
553
554 #define for_each_visible_inode(_c, _s, _w, _snapshot, _i)                               \
555         for (_i = (_w)->inodes.data; _i < (_w)->inodes.data + (_w)->inodes.nr &&        \
556              (_i)->snapshot <= (_snapshot); _i++)                                       \
557                 if (key_visible_in_snapshot(_c, _s, _i->snapshot, _snapshot))
558
559 struct inode_walker_entry {
560         struct bch_inode_unpacked inode;
561         u32                     snapshot;
562         bool                    seen_this_pos;
563         u64                     count;
564 };
565
566 struct inode_walker {
567         bool                            first_this_inode;
568         bool                            recalculate_sums;
569         struct bpos                     last_pos;
570
571         DARRAY(struct inode_walker_entry) inodes;
572 };
573
574 static void inode_walker_exit(struct inode_walker *w)
575 {
576         darray_exit(&w->inodes);
577 }
578
579 static struct inode_walker inode_walker_init(void)
580 {
581         return (struct inode_walker) { 0, };
582 }
583
584 static int add_inode(struct bch_fs *c, struct inode_walker *w,
585                      struct bkey_s_c inode)
586 {
587         struct bch_inode_unpacked u;
588
589         BUG_ON(bch2_inode_unpack(inode, &u));
590
591         return darray_push(&w->inodes, ((struct inode_walker_entry) {
592                 .inode          = u,
593                 .snapshot       = bch2_snapshot_equiv(c, inode.k->p.snapshot),
594         }));
595 }
596
597 static int get_inodes_all_snapshots(struct btree_trans *trans,
598                                     struct inode_walker *w, u64 inum)
599 {
600         struct bch_fs *c = trans->c;
601         struct btree_iter iter;
602         struct bkey_s_c k;
603         u32 restart_count = trans->restart_count;
604         int ret;
605
606         w->recalculate_sums = false;
607         w->inodes.nr = 0;
608
609         for_each_btree_key(trans, iter, BTREE_ID_inodes, POS(0, inum),
610                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
611                 if (k.k->p.offset != inum)
612                         break;
613
614                 if (bkey_is_inode(k.k))
615                         add_inode(c, w, k);
616         }
617         bch2_trans_iter_exit(trans, &iter);
618
619         if (ret)
620                 return ret;
621
622         w->first_this_inode = true;
623
624         return trans_was_restarted(trans, restart_count);
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_fn(c, 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         if (!bkey_is_inode(k.k))
857                 return 0;
858
859         BUG_ON(bch2_inode_unpack(k, &u));
860
861         if (!full &&
862             !(u.bi_flags & (BCH_INODE_I_SIZE_DIRTY|
863                             BCH_INODE_I_SECTORS_DIRTY|
864                             BCH_INODE_UNLINKED)))
865                 return 0;
866
867         if (prev->bi_inum != u.bi_inum)
868                 *prev = u;
869
870         if (fsck_err_on(prev->bi_hash_seed      != u.bi_hash_seed ||
871                         inode_d_type(prev)      != inode_d_type(&u), c,
872                         "inodes in different snapshots don't match")) {
873                 bch_err(c, "repair not implemented yet");
874                 return -EINVAL;
875         }
876
877         if ((u.bi_flags & (BCH_INODE_I_SIZE_DIRTY|BCH_INODE_UNLINKED)) &&
878             bch2_key_has_snapshot_overwrites(trans, BTREE_ID_inodes, k.k->p)) {
879                 struct bpos new_min_pos;
880
881                 ret = bch2_propagate_key_to_snapshot_leaves(trans, iter->btree_id, k, &new_min_pos);
882                 if (ret)
883                         goto err;
884
885                 u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY|BCH_INODE_UNLINKED;
886
887                 ret = __write_inode(trans, &u, iter->pos.snapshot);
888                 if (ret) {
889                         if (!bch2_err_matches(ret, BCH_ERR_transaction_restart))
890                                 bch_err_msg(c, ret, "in fsck updating inode");
891                         return ret;
892                 }
893
894                 if (!bpos_eq(new_min_pos, POS_MIN))
895                         bch2_btree_iter_set_pos(iter, bpos_predecessor(new_min_pos));
896                 return 0;
897         }
898
899         if (u.bi_flags & BCH_INODE_UNLINKED &&
900             (!c->sb.clean ||
901              fsck_err(c, "filesystem marked clean, but inode %llu unlinked",
902                       u.bi_inum))) {
903                 bch2_trans_unlock(trans);
904                 bch2_fs_lazy_rw(c);
905
906                 ret = bch2_inode_rm_snapshot(trans, u.bi_inum, iter->pos.snapshot);
907                 if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
908                         bch_err_msg(c, ret, "in fsck deleting inode");
909                 return ret;
910         }
911
912         if (u.bi_flags & BCH_INODE_I_SIZE_DIRTY &&
913             (!c->sb.clean ||
914              fsck_err(c, "filesystem marked clean, but inode %llu has i_size dirty",
915                       u.bi_inum))) {
916                 bch_verbose(c, "truncating inode %llu", u.bi_inum);
917
918                 bch2_trans_unlock(trans);
919                 bch2_fs_lazy_rw(c);
920
921                 /*
922                  * XXX: need to truncate partial blocks too here - or ideally
923                  * just switch units to bytes and that issue goes away
924                  */
925                 ret = bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
926                                 SPOS(u.bi_inum, round_up(u.bi_size, block_bytes(c)) >> 9,
927                                      iter->pos.snapshot),
928                                 POS(u.bi_inum, U64_MAX),
929                                 0, NULL);
930                 if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
931                         bch_err_msg(c, ret, "in fsck truncating inode");
932                 if (ret)
933                         return ret;
934
935                 /*
936                  * We truncated without our normal sector accounting hook, just
937                  * make sure we recalculate it:
938                  */
939                 u.bi_flags |= BCH_INODE_I_SECTORS_DIRTY;
940
941                 u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
942                 do_update = true;
943         }
944
945         if (u.bi_flags & BCH_INODE_I_SECTORS_DIRTY &&
946             (!c->sb.clean ||
947              fsck_err(c, "filesystem marked clean, but inode %llu has i_sectors dirty",
948                       u.bi_inum))) {
949                 s64 sectors;
950
951                 bch_verbose(c, "recounting sectors for inode %llu",
952                             u.bi_inum);
953
954                 sectors = bch2_count_inode_sectors(trans, u.bi_inum, iter->pos.snapshot);
955                 if (sectors < 0) {
956                         bch_err_msg(c, sectors, "fsck recounting inode sectors");
957                         return sectors;
958                 }
959
960                 u.bi_sectors = sectors;
961                 u.bi_flags &= ~BCH_INODE_I_SECTORS_DIRTY;
962                 do_update = true;
963         }
964
965         if (u.bi_flags & BCH_INODE_BACKPTR_UNTRUSTED) {
966                 u.bi_dir = 0;
967                 u.bi_dir_offset = 0;
968                 u.bi_flags &= ~BCH_INODE_BACKPTR_UNTRUSTED;
969                 do_update = true;
970         }
971
972         if (do_update) {
973                 ret = __write_inode(trans, &u, iter->pos.snapshot);
974                 if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
975                         bch_err_msg(c, ret, "in fsck updating inode");
976                 if (ret)
977                         return ret;
978         }
979 err:
980 fsck_err:
981         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
982                 bch_err_fn(c, ret);
983         return ret;
984 }
985
986 noinline_for_stack
987 int bch2_check_inodes(struct bch_fs *c)
988 {
989         bool full = c->opts.fsck;
990         struct btree_trans *trans = bch2_trans_get(c);
991         struct btree_iter iter;
992         struct bch_inode_unpacked prev = { 0 };
993         struct snapshots_seen s;
994         struct bkey_s_c k;
995         int ret;
996
997         snapshots_seen_init(&s);
998
999         ret = for_each_btree_key_commit(trans, iter, BTREE_ID_inodes,
1000                         POS_MIN,
1001                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
1002                         NULL, NULL, BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
1003                 check_inode(trans, &iter, k, &prev, &s, full));
1004
1005         snapshots_seen_exit(&s);
1006         bch2_trans_put(trans);
1007         if (ret)
1008                 bch_err_fn(c, ret);
1009         return ret;
1010 }
1011
1012 static struct bkey_s_c_dirent dirent_get_by_pos(struct btree_trans *trans,
1013                                                 struct btree_iter *iter,
1014                                                 struct bpos pos)
1015 {
1016         return bch2_bkey_get_iter_typed(trans, iter, BTREE_ID_dirents, pos, 0, dirent);
1017 }
1018
1019 static bool inode_points_to_dirent(struct bch_inode_unpacked *inode,
1020                                    struct bkey_s_c_dirent d)
1021 {
1022         return  inode->bi_dir           == d.k->p.inode &&
1023                 inode->bi_dir_offset    == d.k->p.offset;
1024 }
1025
1026 static bool dirent_points_to_inode(struct bkey_s_c_dirent d,
1027                                    struct bch_inode_unpacked *inode)
1028 {
1029         return d.v->d_type == DT_SUBVOL
1030                 ? le32_to_cpu(d.v->d_child_subvol)      == inode->bi_subvol
1031                 : le64_to_cpu(d.v->d_inum)              == inode->bi_inum;
1032 }
1033
1034 static int inode_backpointer_exists(struct btree_trans *trans,
1035                                     struct bch_inode_unpacked *inode,
1036                                     u32 snapshot)
1037 {
1038         struct btree_iter iter;
1039         struct bkey_s_c_dirent d;
1040         int ret;
1041
1042         d = dirent_get_by_pos(trans, &iter,
1043                         SPOS(inode->bi_dir, inode->bi_dir_offset, snapshot));
1044         ret = bkey_err(d);
1045         if (ret)
1046                 return bch2_err_matches(ret, ENOENT) ? 0 : ret;
1047
1048         ret = dirent_points_to_inode(d, inode);
1049         bch2_trans_iter_exit(trans, &iter);
1050         return ret;
1051 }
1052
1053 static int check_i_sectors(struct btree_trans *trans, struct inode_walker *w)
1054 {
1055         struct bch_fs *c = trans->c;
1056         struct inode_walker_entry *i;
1057         u32 restart_count = trans->restart_count;
1058         int ret = 0;
1059         s64 count2;
1060
1061         darray_for_each(w->inodes, i) {
1062                 if (i->inode.bi_sectors == i->count)
1063                         continue;
1064
1065                 count2 = bch2_count_inode_sectors(trans, w->last_pos.inode, i->snapshot);
1066
1067                 if (w->recalculate_sums)
1068                         i->count = count2;
1069
1070                 if (i->count != count2) {
1071                         bch_err(c, "fsck counted i_sectors wrong for inode %llu:%u: got %llu should be %llu",
1072                                 w->last_pos.inode, i->snapshot, i->count, count2);
1073                         return -BCH_ERR_internal_fsck_err;
1074                 }
1075
1076                 if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY), c,
1077                             "inode %llu:%u has incorrect i_sectors: got %llu, should be %llu",
1078                             w->last_pos.inode, i->snapshot,
1079                             i->inode.bi_sectors, i->count)) {
1080                         i->inode.bi_sectors = i->count;
1081                         ret = fsck_write_inode(trans, &i->inode, i->snapshot);
1082                         if (ret)
1083                                 break;
1084                 }
1085         }
1086 fsck_err:
1087         if (ret)
1088                 bch_err_fn(c, ret);
1089         return ret ?: trans_was_restarted(trans, restart_count);
1090 }
1091
1092 struct extent_end {
1093         u32                     snapshot;
1094         u64                     offset;
1095         struct snapshots_seen   seen;
1096 };
1097
1098 struct extent_ends {
1099         struct bpos                     last_pos;
1100         DARRAY(struct extent_end)       e;
1101 };
1102
1103 static void extent_ends_reset(struct extent_ends *extent_ends)
1104 {
1105         struct extent_end *i;
1106
1107         darray_for_each(extent_ends->e, i)
1108                 snapshots_seen_exit(&i->seen);
1109
1110         extent_ends->e.nr = 0;
1111 }
1112
1113 static void extent_ends_exit(struct extent_ends *extent_ends)
1114 {
1115         extent_ends_reset(extent_ends);
1116         darray_exit(&extent_ends->e);
1117 }
1118
1119 static void extent_ends_init(struct extent_ends *extent_ends)
1120 {
1121         memset(extent_ends, 0, sizeof(*extent_ends));
1122 }
1123
1124 static int extent_ends_at(struct bch_fs *c,
1125                           struct extent_ends *extent_ends,
1126                           struct snapshots_seen *seen,
1127                           struct bkey_s_c k)
1128 {
1129         struct extent_end *i, n = (struct extent_end) {
1130                 .offset         = k.k->p.offset,
1131                 .snapshot       = k.k->p.snapshot,
1132                 .seen           = *seen,
1133         };
1134
1135         n.seen.ids.data = kmemdup(seen->ids.data,
1136                               sizeof(seen->ids.data[0]) * seen->ids.size,
1137                               GFP_KERNEL);
1138         if (!n.seen.ids.data)
1139                 return -BCH_ERR_ENOMEM_fsck_extent_ends_at;
1140
1141         darray_for_each(extent_ends->e, i) {
1142                 if (i->snapshot == k.k->p.snapshot) {
1143                         snapshots_seen_exit(&i->seen);
1144                         *i = n;
1145                         return 0;
1146                 }
1147
1148                 if (i->snapshot >= k.k->p.snapshot)
1149                         break;
1150         }
1151
1152         return darray_insert_item(&extent_ends->e, i - extent_ends->e.data, n);
1153 }
1154
1155 static int overlapping_extents_found(struct btree_trans *trans,
1156                                      enum btree_id btree,
1157                                      struct bpos pos1, struct snapshots_seen *pos1_seen,
1158                                      struct bkey pos2,
1159                                      bool *fixed,
1160                                      struct extent_end *extent_end)
1161 {
1162         struct bch_fs *c = trans->c;
1163         struct printbuf buf = PRINTBUF;
1164         struct btree_iter iter1, iter2 = { NULL };
1165         struct bkey_s_c k1, k2;
1166         int ret;
1167
1168         BUG_ON(bkey_le(pos1, bkey_start_pos(&pos2)));
1169
1170         bch2_trans_iter_init(trans, &iter1, btree, pos1,
1171                              BTREE_ITER_ALL_SNAPSHOTS|
1172                              BTREE_ITER_NOT_EXTENTS);
1173         k1 = bch2_btree_iter_peek_upto(&iter1, POS(pos1.inode, U64_MAX));
1174         ret = bkey_err(k1);
1175         if (ret)
1176                 goto err;
1177
1178         prt_str(&buf, "\n  ");
1179         bch2_bkey_val_to_text(&buf, c, k1);
1180
1181         if (!bpos_eq(pos1, k1.k->p)) {
1182                 prt_str(&buf, "\n  wanted\n  ");
1183                 bch2_bpos_to_text(&buf, pos1);
1184                 prt_str(&buf, "\n  ");
1185                 bch2_bkey_to_text(&buf, &pos2);
1186
1187                 bch_err(c, "%s: error finding first overlapping extent when repairing, got%s",
1188                         __func__, buf.buf);
1189                 ret = -BCH_ERR_internal_fsck_err;
1190                 goto err;
1191         }
1192
1193         bch2_trans_copy_iter(&iter2, &iter1);
1194
1195         while (1) {
1196                 bch2_btree_iter_advance(&iter2);
1197
1198                 k2 = bch2_btree_iter_peek_upto(&iter2, POS(pos1.inode, U64_MAX));
1199                 ret = bkey_err(k2);
1200                 if (ret)
1201                         goto err;
1202
1203                 if (bpos_ge(k2.k->p, pos2.p))
1204                         break;
1205         }
1206
1207         prt_str(&buf, "\n  ");
1208         bch2_bkey_val_to_text(&buf, c, k2);
1209
1210         if (bpos_gt(k2.k->p, pos2.p) ||
1211             pos2.size != k2.k->size) {
1212                 bch_err(c, "%s: error finding seconding overlapping extent when repairing%s",
1213                         __func__, buf.buf);
1214                 ret = -BCH_ERR_internal_fsck_err;
1215                 goto err;
1216         }
1217
1218         prt_printf(&buf, "\n  overwriting %s extent",
1219                    pos1.snapshot >= pos2.p.snapshot ? "first" : "second");
1220
1221         if (fsck_err(c, "overlapping extents%s", buf.buf)) {
1222                 struct btree_iter *old_iter = &iter1;
1223                 struct disk_reservation res = { 0 };
1224
1225                 if (pos1.snapshot < pos2.p.snapshot) {
1226                         old_iter = &iter2;
1227                         swap(k1, k2);
1228                 }
1229
1230                 trans->extra_journal_res += bch2_bkey_sectors_compressed(k2);
1231
1232                 ret =   bch2_trans_update_extent_overwrite(trans, old_iter,
1233                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE,
1234                                 k1, k2) ?:
1235                         bch2_trans_commit(trans, &res, NULL,
1236                                 BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL);
1237                 bch2_disk_reservation_put(c, &res);
1238
1239                 if (ret)
1240                         goto err;
1241
1242                 *fixed = true;
1243
1244                 if (pos1.snapshot == pos2.p.snapshot) {
1245                         /*
1246                          * We overwrote the first extent, and did the overwrite
1247                          * in the same snapshot:
1248                          */
1249                         extent_end->offset = bkey_start_offset(&pos2);
1250                 } else if (pos1.snapshot > pos2.p.snapshot) {
1251                         /*
1252                          * We overwrote the first extent in pos2's snapshot:
1253                          */
1254                         ret = snapshots_seen_add_inorder(c, pos1_seen, pos2.p.snapshot);
1255                 } else {
1256                         /*
1257                          * We overwrote the second extent - restart
1258                          * check_extent() from the top:
1259                          */
1260                         ret = -BCH_ERR_transaction_restart_nested;
1261                 }
1262         }
1263 fsck_err:
1264 err:
1265         bch2_trans_iter_exit(trans, &iter2);
1266         bch2_trans_iter_exit(trans, &iter1);
1267         printbuf_exit(&buf);
1268         return ret;
1269 }
1270
1271 static int check_overlapping_extents(struct btree_trans *trans,
1272                               struct snapshots_seen *seen,
1273                               struct extent_ends *extent_ends,
1274                               struct bkey_s_c k,
1275                               u32 equiv,
1276                               struct btree_iter *iter,
1277                               bool *fixed)
1278 {
1279         struct bch_fs *c = trans->c;
1280         struct extent_end *i;
1281         int ret = 0;
1282
1283         /* transaction restart, running again */
1284         if (bpos_eq(extent_ends->last_pos, k.k->p))
1285                 return 0;
1286
1287         if (extent_ends->last_pos.inode != k.k->p.inode)
1288                 extent_ends_reset(extent_ends);
1289
1290         darray_for_each(extent_ends->e, i) {
1291                 if (i->offset <= bkey_start_offset(k.k))
1292                         continue;
1293
1294                 if (!ref_visible2(c,
1295                                   k.k->p.snapshot, seen,
1296                                   i->snapshot, &i->seen))
1297                         continue;
1298
1299                 ret = overlapping_extents_found(trans, iter->btree_id,
1300                                                 SPOS(iter->pos.inode,
1301                                                      i->offset,
1302                                                      i->snapshot),
1303                                                 &i->seen,
1304                                                 *k.k, fixed, i);
1305                 if (ret)
1306                         goto err;
1307         }
1308
1309         ret = extent_ends_at(c, extent_ends, seen, k);
1310         if (ret)
1311                 goto err;
1312
1313         extent_ends->last_pos = k.k->p;
1314 err:
1315         return ret;
1316 }
1317
1318 static int check_extent(struct btree_trans *trans, struct btree_iter *iter,
1319                         struct bkey_s_c k,
1320                         struct inode_walker *inode,
1321                         struct snapshots_seen *s,
1322                         struct extent_ends *extent_ends)
1323 {
1324         struct bch_fs *c = trans->c;
1325         struct inode_walker_entry *i;
1326         struct printbuf buf = PRINTBUF;
1327         struct bpos equiv = k.k->p;
1328         int ret = 0;
1329
1330         equiv.snapshot = bch2_snapshot_equiv(c, k.k->p.snapshot);
1331
1332         ret = check_key_has_snapshot(trans, iter, k);
1333         if (ret) {
1334                 ret = ret < 0 ? ret : 0;
1335                 goto out;
1336         }
1337
1338         if (inode->last_pos.inode != k.k->p.inode) {
1339                 ret = check_i_sectors(trans, inode);
1340                 if (ret)
1341                         goto err;
1342         }
1343
1344         i = walk_inode(trans, inode, equiv, k.k->type == KEY_TYPE_whiteout);
1345         ret = PTR_ERR_OR_ZERO(i);
1346         if (ret)
1347                 goto err;
1348
1349         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
1350         if (ret)
1351                 goto err;
1352
1353         if (k.k->type != KEY_TYPE_whiteout) {
1354                 if (fsck_err_on(!i, c,
1355                                 "extent in missing inode:\n  %s",
1356                                 (printbuf_reset(&buf),
1357                                  bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
1358                         goto delete;
1359
1360                 if (fsck_err_on(i &&
1361                                 !S_ISREG(i->inode.bi_mode) &&
1362                                 !S_ISLNK(i->inode.bi_mode), c,
1363                                 "extent in non regular inode mode %o:\n  %s",
1364                                 i->inode.bi_mode,
1365                                 (printbuf_reset(&buf),
1366                                  bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
1367                         goto delete;
1368
1369                 ret = check_overlapping_extents(trans, s, extent_ends, k,
1370                                                 equiv.snapshot, iter,
1371                                                 &inode->recalculate_sums);
1372                 if (ret)
1373                         goto err;
1374         }
1375
1376         /*
1377          * Check inodes in reverse order, from oldest snapshots to newest,
1378          * starting from the inode that matches this extent's snapshot. If we
1379          * didn't have one, iterate over all inodes:
1380          */
1381         if (!i)
1382                 i = inode->inodes.data + inode->inodes.nr - 1;
1383
1384         for (;
1385              inode->inodes.data && i >= inode->inodes.data;
1386              --i) {
1387                 if (i->snapshot > equiv.snapshot ||
1388                     !key_visible_in_snapshot(c, s, i->snapshot, equiv.snapshot))
1389                         continue;
1390
1391                 if (k.k->type != KEY_TYPE_whiteout) {
1392                         if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
1393                                         k.k->p.offset > round_up(i->inode.bi_size, block_bytes(c)) >> 9 &&
1394                                         !bkey_extent_is_reservation(k), c,
1395                                         "extent type past end of inode %llu:%u, i_size %llu\n  %s",
1396                                         i->inode.bi_inum, i->snapshot, i->inode.bi_size,
1397                                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1398                                 struct btree_iter iter2;
1399
1400                                 bch2_trans_copy_iter(&iter2, iter);
1401                                 bch2_btree_iter_set_snapshot(&iter2, i->snapshot);
1402                                 ret =   bch2_btree_iter_traverse(&iter2) ?:
1403                                         bch2_btree_delete_at(trans, &iter2,
1404                                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1405                                 bch2_trans_iter_exit(trans, &iter2);
1406                                 if (ret)
1407                                         goto err;
1408
1409                                 iter->k.type = KEY_TYPE_whiteout;
1410                         }
1411
1412                         if (bkey_extent_is_allocation(k.k))
1413                                 i->count += k.k->size;
1414                 }
1415
1416                 i->seen_this_pos = true;
1417         }
1418 out:
1419 err:
1420 fsck_err:
1421         printbuf_exit(&buf);
1422
1423         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1424                 bch_err_fn(c, ret);
1425         return ret;
1426 delete:
1427         ret = bch2_btree_delete_at(trans, iter, BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1428         goto out;
1429 }
1430
1431 /*
1432  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
1433  * that i_size an i_sectors are consistent
1434  */
1435 int bch2_check_extents(struct bch_fs *c)
1436 {
1437         struct inode_walker w = inode_walker_init();
1438         struct snapshots_seen s;
1439         struct btree_trans *trans = bch2_trans_get(c);
1440         struct btree_iter iter;
1441         struct bkey_s_c k;
1442         struct extent_ends extent_ends;
1443         struct disk_reservation res = { 0 };
1444         int ret = 0;
1445
1446         snapshots_seen_init(&s);
1447         extent_ends_init(&extent_ends);
1448
1449         ret = for_each_btree_key_commit(trans, iter, BTREE_ID_extents,
1450                         POS(BCACHEFS_ROOT_INO, 0),
1451                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
1452                         &res, NULL,
1453                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL, ({
1454                 bch2_disk_reservation_put(c, &res);
1455                 check_extent(trans, &iter, k, &w, &s, &extent_ends);
1456         })) ?:
1457         check_i_sectors(trans, &w);
1458
1459         bch2_disk_reservation_put(c, &res);
1460         extent_ends_exit(&extent_ends);
1461         inode_walker_exit(&w);
1462         snapshots_seen_exit(&s);
1463         bch2_trans_put(trans);
1464
1465         if (ret)
1466                 bch_err_fn(c, ret);
1467         return ret;
1468 }
1469
1470 static int check_subdir_count(struct btree_trans *trans, struct inode_walker *w)
1471 {
1472         struct bch_fs *c = trans->c;
1473         struct inode_walker_entry *i;
1474         u32 restart_count = trans->restart_count;
1475         int ret = 0;
1476         s64 count2;
1477
1478         darray_for_each(w->inodes, i) {
1479                 if (i->inode.bi_nlink == i->count)
1480                         continue;
1481
1482                 count2 = bch2_count_subdirs(trans, w->last_pos.inode, i->snapshot);
1483                 if (count2 < 0)
1484                         return count2;
1485
1486                 if (i->count != count2) {
1487                         bch_err(c, "fsck counted subdirectories wrong: got %llu should be %llu",
1488                                 i->count, count2);
1489                         i->count = count2;
1490                         if (i->inode.bi_nlink == i->count)
1491                                 continue;
1492                 }
1493
1494                 if (fsck_err_on(i->inode.bi_nlink != i->count, c,
1495                                 "directory %llu:%u with wrong i_nlink: got %u, should be %llu",
1496                                 w->last_pos.inode, i->snapshot, i->inode.bi_nlink, i->count)) {
1497                         i->inode.bi_nlink = i->count;
1498                         ret = fsck_write_inode(trans, &i->inode, i->snapshot);
1499                         if (ret)
1500                                 break;
1501                 }
1502         }
1503 fsck_err:
1504         if (ret)
1505                 bch_err_fn(c, ret);
1506         return ret ?: trans_was_restarted(trans, restart_count);
1507 }
1508
1509 static int check_dirent_target(struct btree_trans *trans,
1510                                struct btree_iter *iter,
1511                                struct bkey_s_c_dirent d,
1512                                struct bch_inode_unpacked *target,
1513                                u32 target_snapshot)
1514 {
1515         struct bch_fs *c = trans->c;
1516         struct bkey_i_dirent *n;
1517         bool backpointer_exists = true;
1518         struct printbuf buf = PRINTBUF;
1519         int ret = 0;
1520
1521         if (!target->bi_dir &&
1522             !target->bi_dir_offset) {
1523                 target->bi_dir          = d.k->p.inode;
1524                 target->bi_dir_offset   = d.k->p.offset;
1525
1526                 ret = __write_inode(trans, target, target_snapshot);
1527                 if (ret)
1528                         goto err;
1529         }
1530
1531         if (!inode_points_to_dirent(target, d)) {
1532                 ret = inode_backpointer_exists(trans, target, d.k->p.snapshot);
1533                 if (ret < 0)
1534                         goto err;
1535
1536                 backpointer_exists = ret;
1537                 ret = 0;
1538
1539                 if (fsck_err_on(S_ISDIR(target->bi_mode) &&
1540                                 backpointer_exists, c,
1541                                 "directory %llu with multiple links",
1542                                 target->bi_inum)) {
1543                         ret = __remove_dirent(trans, d.k->p);
1544                         goto out;
1545                 }
1546
1547                 if (fsck_err_on(backpointer_exists &&
1548                                 !target->bi_nlink, c,
1549                                 "inode %llu type %s has multiple links but i_nlink 0",
1550                                 target->bi_inum, bch2_d_types[d.v->d_type])) {
1551                         target->bi_nlink++;
1552                         target->bi_flags &= ~BCH_INODE_UNLINKED;
1553
1554                         ret = __write_inode(trans, target, target_snapshot);
1555                         if (ret)
1556                                 goto err;
1557                 }
1558
1559                 if (fsck_err_on(!backpointer_exists, c,
1560                                 "inode %llu:%u has wrong backpointer:\n"
1561                                 "got       %llu:%llu\n"
1562                                 "should be %llu:%llu",
1563                                 target->bi_inum, target_snapshot,
1564                                 target->bi_dir,
1565                                 target->bi_dir_offset,
1566                                 d.k->p.inode,
1567                                 d.k->p.offset)) {
1568                         target->bi_dir          = d.k->p.inode;
1569                         target->bi_dir_offset   = d.k->p.offset;
1570
1571                         ret = __write_inode(trans, target, target_snapshot);
1572                         if (ret)
1573                                 goto err;
1574                 }
1575         }
1576
1577         if (fsck_err_on(d.v->d_type != inode_d_type(target), c,
1578                         "incorrect d_type: got %s, should be %s:\n%s",
1579                         bch2_d_type_str(d.v->d_type),
1580                         bch2_d_type_str(inode_d_type(target)),
1581                         (printbuf_reset(&buf),
1582                          bch2_bkey_val_to_text(&buf, c, d.s_c), buf.buf))) {
1583                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1584                 ret = PTR_ERR_OR_ZERO(n);
1585                 if (ret)
1586                         goto err;
1587
1588                 bkey_reassemble(&n->k_i, d.s_c);
1589                 n->v.d_type = inode_d_type(target);
1590
1591                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1592                 if (ret)
1593                         goto err;
1594
1595                 d = dirent_i_to_s_c(n);
1596         }
1597
1598         if (d.v->d_type == DT_SUBVOL &&
1599             target->bi_parent_subvol != le32_to_cpu(d.v->d_parent_subvol) &&
1600             (c->sb.version < bcachefs_metadata_version_subvol_dirent ||
1601              fsck_err(c, "dirent has wrong d_parent_subvol field: got %u, should be %u",
1602                       le32_to_cpu(d.v->d_parent_subvol),
1603                       target->bi_parent_subvol))) {
1604                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1605                 ret = PTR_ERR_OR_ZERO(n);
1606                 if (ret)
1607                         goto err;
1608
1609                 bkey_reassemble(&n->k_i, d.s_c);
1610                 n->v.d_parent_subvol = cpu_to_le32(target->bi_parent_subvol);
1611
1612                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1613                 if (ret)
1614                         goto err;
1615
1616                 d = dirent_i_to_s_c(n);
1617         }
1618 out:
1619 err:
1620 fsck_err:
1621         printbuf_exit(&buf);
1622
1623         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1624                 bch_err_fn(c, ret);
1625         return ret;
1626 }
1627
1628 static int check_dirent(struct btree_trans *trans, struct btree_iter *iter,
1629                         struct bkey_s_c k,
1630                         struct bch_hash_info *hash_info,
1631                         struct inode_walker *dir,
1632                         struct inode_walker *target,
1633                         struct snapshots_seen *s)
1634 {
1635         struct bch_fs *c = trans->c;
1636         struct bkey_s_c_dirent d;
1637         struct inode_walker_entry *i;
1638         struct printbuf buf = PRINTBUF;
1639         struct bpos equiv;
1640         int ret = 0;
1641
1642         ret = check_key_has_snapshot(trans, iter, k);
1643         if (ret) {
1644                 ret = ret < 0 ? ret : 0;
1645                 goto out;
1646         }
1647
1648         equiv = k.k->p;
1649         equiv.snapshot = bch2_snapshot_equiv(c, k.k->p.snapshot);
1650
1651         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
1652         if (ret)
1653                 goto err;
1654
1655         if (k.k->type == KEY_TYPE_whiteout)
1656                 goto out;
1657
1658         if (dir->last_pos.inode != k.k->p.inode) {
1659                 ret = check_subdir_count(trans, dir);
1660                 if (ret)
1661                         goto err;
1662         }
1663
1664         BUG_ON(!iter->path->should_be_locked);
1665
1666         i = walk_inode(trans, dir, equiv, k.k->type == KEY_TYPE_whiteout);
1667         ret = PTR_ERR_OR_ZERO(i);
1668         if (ret < 0)
1669                 goto err;
1670
1671         if (dir->first_this_inode && dir->inodes.nr)
1672                 *hash_info = bch2_hash_info_init(c, &dir->inodes.data[0].inode);
1673         dir->first_this_inode = false;
1674
1675         if (fsck_err_on(!i, c,
1676                         "dirent in nonexisting directory:\n%s",
1677                         (printbuf_reset(&buf),
1678                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1679                 ret = bch2_btree_delete_at(trans, iter,
1680                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1681                 goto out;
1682         }
1683
1684         if (!i)
1685                 goto out;
1686
1687         if (fsck_err_on(!S_ISDIR(i->inode.bi_mode), c,
1688                         "dirent in non directory inode type %s:\n%s",
1689                         bch2_d_type_str(inode_d_type(&i->inode)),
1690                         (printbuf_reset(&buf),
1691                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1692                 ret = bch2_btree_delete_at(trans, iter, 0);
1693                 goto out;
1694         }
1695
1696         ret = hash_check_key(trans, bch2_dirent_hash_desc, hash_info, iter, k);
1697         if (ret < 0)
1698                 goto err;
1699         if (ret) {
1700                 /* dirent has been deleted */
1701                 ret = 0;
1702                 goto out;
1703         }
1704
1705         if (k.k->type != KEY_TYPE_dirent)
1706                 goto out;
1707
1708         d = bkey_s_c_to_dirent(k);
1709
1710         if (d.v->d_type == DT_SUBVOL) {
1711                 struct bch_inode_unpacked subvol_root;
1712                 u32 target_subvol = le32_to_cpu(d.v->d_child_subvol);
1713                 u32 target_snapshot;
1714                 u64 target_inum;
1715
1716                 ret = __subvol_lookup(trans, target_subvol,
1717                                       &target_snapshot, &target_inum);
1718                 if (ret && !bch2_err_matches(ret, ENOENT))
1719                         goto err;
1720
1721                 if (fsck_err_on(ret, c,
1722                                 "dirent points to missing subvolume %u",
1723                                 le32_to_cpu(d.v->d_child_subvol))) {
1724                         ret = __remove_dirent(trans, d.k->p);
1725                         goto err;
1726                 }
1727
1728                 ret = __lookup_inode(trans, target_inum,
1729                                    &subvol_root, &target_snapshot);
1730                 if (ret && !bch2_err_matches(ret, ENOENT))
1731                         goto err;
1732
1733                 if (fsck_err_on(ret, c,
1734                                 "subvolume %u points to missing subvolume root %llu",
1735                                 target_subvol,
1736                                 target_inum)) {
1737                         bch_err(c, "repair not implemented yet");
1738                         ret = -EINVAL;
1739                         goto err;
1740                 }
1741
1742                 if (fsck_err_on(subvol_root.bi_subvol != target_subvol, c,
1743                                 "subvol root %llu has wrong bi_subvol field: got %u, should be %u",
1744                                 target_inum,
1745                                 subvol_root.bi_subvol, target_subvol)) {
1746                         subvol_root.bi_subvol = target_subvol;
1747                         ret = __write_inode(trans, &subvol_root, target_snapshot);
1748                         if (ret)
1749                                 goto err;
1750                 }
1751
1752                 ret = check_dirent_target(trans, iter, d, &subvol_root,
1753                                           target_snapshot);
1754                 if (ret)
1755                         goto err;
1756         } else {
1757                 ret = __get_visible_inodes(trans, target, s, le64_to_cpu(d.v->d_inum));
1758                 if (ret)
1759                         goto err;
1760
1761                 if (fsck_err_on(!target->inodes.nr, c,
1762                                 "dirent points to missing inode: (equiv %u)\n%s",
1763                                 equiv.snapshot,
1764                                 (printbuf_reset(&buf),
1765                                  bch2_bkey_val_to_text(&buf, c, k),
1766                                  buf.buf))) {
1767                         ret = __remove_dirent(trans, d.k->p);
1768                         if (ret)
1769                                 goto err;
1770                 }
1771
1772                 darray_for_each(target->inodes, i) {
1773                         ret = check_dirent_target(trans, iter, d,
1774                                                   &i->inode, i->snapshot);
1775                         if (ret)
1776                                 goto err;
1777                 }
1778         }
1779
1780         if (d.v->d_type == DT_DIR)
1781                 for_each_visible_inode(c, s, dir, equiv.snapshot, i)
1782                         i->count++;
1783
1784 out:
1785 err:
1786 fsck_err:
1787         printbuf_exit(&buf);
1788
1789         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1790                 bch_err_fn(c, ret);
1791         return ret;
1792 }
1793
1794 /*
1795  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
1796  * validate d_type
1797  */
1798 int bch2_check_dirents(struct bch_fs *c)
1799 {
1800         struct inode_walker dir = inode_walker_init();
1801         struct inode_walker target = inode_walker_init();
1802         struct snapshots_seen s;
1803         struct bch_hash_info hash_info;
1804         struct btree_trans *trans = bch2_trans_get(c);
1805         struct btree_iter iter;
1806         struct bkey_s_c k;
1807         int ret = 0;
1808
1809         snapshots_seen_init(&s);
1810
1811         ret = for_each_btree_key_commit(trans, iter, BTREE_ID_dirents,
1812                         POS(BCACHEFS_ROOT_INO, 0),
1813                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1814                         k,
1815                         NULL, NULL,
1816                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
1817                 check_dirent(trans, &iter, k, &hash_info, &dir, &target, &s));
1818
1819         bch2_trans_put(trans);
1820         snapshots_seen_exit(&s);
1821         inode_walker_exit(&dir);
1822         inode_walker_exit(&target);
1823
1824         if (ret)
1825                 bch_err_fn(c, ret);
1826         return ret;
1827 }
1828
1829 static int check_xattr(struct btree_trans *trans, struct btree_iter *iter,
1830                        struct bkey_s_c k,
1831                        struct bch_hash_info *hash_info,
1832                        struct inode_walker *inode)
1833 {
1834         struct bch_fs *c = trans->c;
1835         struct inode_walker_entry *i;
1836         int ret;
1837
1838         ret = check_key_has_snapshot(trans, iter, k);
1839         if (ret)
1840                 return ret;
1841
1842         i = walk_inode(trans, inode, k.k->p, k.k->type == KEY_TYPE_whiteout);
1843         ret = PTR_ERR_OR_ZERO(i);
1844         if (ret)
1845                 return ret;
1846
1847         if (inode->first_this_inode && inode->inodes.nr)
1848                 *hash_info = bch2_hash_info_init(c, &inode->inodes.data[0].inode);
1849         inode->first_this_inode = false;
1850
1851         if (fsck_err_on(!i, c,
1852                         "xattr for missing inode %llu",
1853                         k.k->p.inode))
1854                 return bch2_btree_delete_at(trans, iter, 0);
1855
1856         if (!i)
1857                 return 0;
1858
1859         ret = hash_check_key(trans, bch2_xattr_hash_desc, hash_info, iter, k);
1860 fsck_err:
1861         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1862                 bch_err_fn(c, ret);
1863         return ret;
1864 }
1865
1866 /*
1867  * Walk xattrs: verify that they all have a corresponding inode
1868  */
1869 int bch2_check_xattrs(struct bch_fs *c)
1870 {
1871         struct inode_walker inode = inode_walker_init();
1872         struct bch_hash_info hash_info;
1873         struct btree_iter iter;
1874         struct bkey_s_c k;
1875         int ret = 0;
1876
1877         ret = bch2_trans_run(c,
1878                 for_each_btree_key_commit(trans, iter, BTREE_ID_xattrs,
1879                         POS(BCACHEFS_ROOT_INO, 0),
1880                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1881                         k,
1882                         NULL, NULL,
1883                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
1884                 check_xattr(trans, &iter, k, &hash_info, &inode)));
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(trans, BTREE_ID_subvolumes,
1917                                             &root_subvol.k_i, 0));
1918                 if (ret) {
1919                         bch_err_msg(c, ret, "writing root subvol");
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_msg(c, ret, "writing root inode");
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 = bch2_trans_get(c);
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         for_each_btree_key(trans, iter, BTREE_ID_inodes, POS_MIN,
2113                            BTREE_ITER_INTENT|
2114                            BTREE_ITER_PREFETCH|
2115                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2116                 if (!bkey_is_inode(k.k))
2117                         continue;
2118
2119                 ret = bch2_inode_unpack(k, &u);
2120                 if (ret) {
2121                         /* Should have been caught earlier in fsck: */
2122                         bch_err(c, "error unpacking inode %llu: %i", k.k->p.offset, ret);
2123                         break;
2124                 }
2125
2126                 if (u.bi_flags & BCH_INODE_UNLINKED)
2127                         continue;
2128
2129                 ret = check_path(trans, &path, &u, iter.pos.snapshot);
2130                 if (ret)
2131                         break;
2132         }
2133         bch2_trans_iter_exit(trans, &iter);
2134         bch2_trans_put(trans);
2135         darray_exit(&path);
2136
2137         if (ret)
2138                 bch_err_fn(c, ret);
2139         return ret;
2140 }
2141
2142 struct nlink_table {
2143         size_t          nr;
2144         size_t          size;
2145
2146         struct nlink {
2147                 u64     inum;
2148                 u32     snapshot;
2149                 u32     count;
2150         }               *d;
2151 };
2152
2153 static int add_nlink(struct bch_fs *c, struct nlink_table *t,
2154                      u64 inum, u32 snapshot)
2155 {
2156         if (t->nr == t->size) {
2157                 size_t new_size = max_t(size_t, 128UL, t->size * 2);
2158                 void *d = kvmalloc_array(new_size, sizeof(t->d[0]), GFP_KERNEL);
2159
2160                 if (!d) {
2161                         bch_err(c, "fsck: error allocating memory for nlink_table, size %zu",
2162                                 new_size);
2163                         return -BCH_ERR_ENOMEM_fsck_add_nlink;
2164                 }
2165
2166                 if (t->d)
2167                         memcpy(d, t->d, t->size * sizeof(t->d[0]));
2168                 kvfree(t->d);
2169
2170                 t->d = d;
2171                 t->size = new_size;
2172         }
2173
2174
2175         t->d[t->nr++] = (struct nlink) {
2176                 .inum           = inum,
2177                 .snapshot       = snapshot,
2178         };
2179
2180         return 0;
2181 }
2182
2183 static int nlink_cmp(const void *_l, const void *_r)
2184 {
2185         const struct nlink *l = _l;
2186         const struct nlink *r = _r;
2187
2188         return cmp_int(l->inum, r->inum) ?: cmp_int(l->snapshot, r->snapshot);
2189 }
2190
2191 static void inc_link(struct bch_fs *c, struct snapshots_seen *s,
2192                      struct nlink_table *links,
2193                      u64 range_start, u64 range_end, u64 inum, u32 snapshot)
2194 {
2195         struct nlink *link, key = {
2196                 .inum = inum, .snapshot = U32_MAX,
2197         };
2198
2199         if (inum < range_start || inum >= range_end)
2200                 return;
2201
2202         link = __inline_bsearch(&key, links->d, links->nr,
2203                                 sizeof(links->d[0]), nlink_cmp);
2204         if (!link)
2205                 return;
2206
2207         while (link > links->d && link[0].inum == link[-1].inum)
2208                 --link;
2209
2210         for (; link < links->d + links->nr && link->inum == inum; link++)
2211                 if (ref_visible(c, s, snapshot, link->snapshot)) {
2212                         link->count++;
2213                         if (link->snapshot >= snapshot)
2214                                 break;
2215                 }
2216 }
2217
2218 noinline_for_stack
2219 static int check_nlinks_find_hardlinks(struct bch_fs *c,
2220                                        struct nlink_table *t,
2221                                        u64 start, u64 *end)
2222 {
2223         struct btree_trans *trans = bch2_trans_get(c);
2224         struct btree_iter iter;
2225         struct bkey_s_c k;
2226         struct bch_inode_unpacked u;
2227         int ret = 0;
2228
2229         for_each_btree_key(trans, iter, BTREE_ID_inodes,
2230                            POS(0, start),
2231                            BTREE_ITER_INTENT|
2232                            BTREE_ITER_PREFETCH|
2233                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2234                 if (!bkey_is_inode(k.k))
2235                         continue;
2236
2237                 /* Should never fail, checked by bch2_inode_invalid: */
2238                 BUG_ON(bch2_inode_unpack(k, &u));
2239
2240                 /*
2241                  * Backpointer and directory structure checks are sufficient for
2242                  * directories, since they can't have hardlinks:
2243                  */
2244                 if (S_ISDIR(u.bi_mode))
2245                         continue;
2246
2247                 if (!u.bi_nlink)
2248                         continue;
2249
2250                 ret = add_nlink(c, t, k.k->p.offset, k.k->p.snapshot);
2251                 if (ret) {
2252                         *end = k.k->p.offset;
2253                         ret = 0;
2254                         break;
2255                 }
2256
2257         }
2258         bch2_trans_iter_exit(trans, &iter);
2259         bch2_trans_put(trans);
2260
2261         if (ret)
2262                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2263
2264         return ret;
2265 }
2266
2267 noinline_for_stack
2268 static int check_nlinks_walk_dirents(struct bch_fs *c, struct nlink_table *links,
2269                                      u64 range_start, u64 range_end)
2270 {
2271         struct btree_trans *trans = bch2_trans_get(c);
2272         struct snapshots_seen s;
2273         struct btree_iter iter;
2274         struct bkey_s_c k;
2275         struct bkey_s_c_dirent d;
2276         int ret;
2277
2278         snapshots_seen_init(&s);
2279
2280         for_each_btree_key(trans, iter, BTREE_ID_dirents, POS_MIN,
2281                            BTREE_ITER_INTENT|
2282                            BTREE_ITER_PREFETCH|
2283                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2284                 ret = snapshots_seen_update(c, &s, iter.btree_id, k.k->p);
2285                 if (ret)
2286                         break;
2287
2288                 switch (k.k->type) {
2289                 case KEY_TYPE_dirent:
2290                         d = bkey_s_c_to_dirent(k);
2291
2292                         if (d.v->d_type != DT_DIR &&
2293                             d.v->d_type != DT_SUBVOL)
2294                                 inc_link(c, &s, links, range_start, range_end,
2295                                          le64_to_cpu(d.v->d_inum),
2296                                          bch2_snapshot_equiv(c, d.k->p.snapshot));
2297                         break;
2298                 }
2299         }
2300         bch2_trans_iter_exit(trans, &iter);
2301
2302         if (ret)
2303                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
2304
2305         bch2_trans_put(trans);
2306         snapshots_seen_exit(&s);
2307         return ret;
2308 }
2309
2310 static int check_nlinks_update_inode(struct btree_trans *trans, struct btree_iter *iter,
2311                                      struct bkey_s_c k,
2312                                      struct nlink_table *links,
2313                                      size_t *idx, u64 range_end)
2314 {
2315         struct bch_fs *c = trans->c;
2316         struct bch_inode_unpacked u;
2317         struct nlink *link = &links->d[*idx];
2318         int ret = 0;
2319
2320         if (k.k->p.offset >= range_end)
2321                 return 1;
2322
2323         if (!bkey_is_inode(k.k))
2324                 return 0;
2325
2326         BUG_ON(bch2_inode_unpack(k, &u));
2327
2328         if (S_ISDIR(u.bi_mode))
2329                 return 0;
2330
2331         if (!u.bi_nlink)
2332                 return 0;
2333
2334         while ((cmp_int(link->inum, k.k->p.offset) ?:
2335                 cmp_int(link->snapshot, k.k->p.snapshot)) < 0) {
2336                 BUG_ON(*idx == links->nr);
2337                 link = &links->d[++*idx];
2338         }
2339
2340         if (fsck_err_on(bch2_inode_nlink_get(&u) != link->count, c,
2341                         "inode %llu type %s has wrong i_nlink (%u, should be %u)",
2342                         u.bi_inum, bch2_d_types[mode_to_type(u.bi_mode)],
2343                         bch2_inode_nlink_get(&u), link->count)) {
2344                 bch2_inode_nlink_set(&u, link->count);
2345                 ret = __write_inode(trans, &u, k.k->p.snapshot);
2346         }
2347 fsck_err:
2348         return ret;
2349 }
2350
2351 noinline_for_stack
2352 static int check_nlinks_update_hardlinks(struct bch_fs *c,
2353                                struct nlink_table *links,
2354                                u64 range_start, u64 range_end)
2355 {
2356         struct btree_iter iter;
2357         struct bkey_s_c k;
2358         size_t idx = 0;
2359         int ret = 0;
2360
2361         ret = bch2_trans_run(c,
2362                 for_each_btree_key_commit(trans, iter, BTREE_ID_inodes,
2363                                 POS(0, range_start),
2364                                 BTREE_ITER_INTENT|BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
2365                                 NULL, NULL, BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
2366                         check_nlinks_update_inode(trans, &iter, k, links, &idx, range_end)));
2367         if (ret < 0) {
2368                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2369                 return ret;
2370         }
2371
2372         return 0;
2373 }
2374
2375 int bch2_check_nlinks(struct bch_fs *c)
2376 {
2377         struct nlink_table links = { 0 };
2378         u64 this_iter_range_start, next_iter_range_start = 0;
2379         int ret = 0;
2380
2381         do {
2382                 this_iter_range_start = next_iter_range_start;
2383                 next_iter_range_start = U64_MAX;
2384
2385                 ret = check_nlinks_find_hardlinks(c, &links,
2386                                                   this_iter_range_start,
2387                                                   &next_iter_range_start);
2388
2389                 ret = check_nlinks_walk_dirents(c, &links,
2390                                           this_iter_range_start,
2391                                           next_iter_range_start);
2392                 if (ret)
2393                         break;
2394
2395                 ret = check_nlinks_update_hardlinks(c, &links,
2396                                          this_iter_range_start,
2397                                          next_iter_range_start);
2398                 if (ret)
2399                         break;
2400
2401                 links.nr = 0;
2402         } while (next_iter_range_start != U64_MAX);
2403
2404         kvfree(links.d);
2405
2406         if (ret)
2407                 bch_err_fn(c, ret);
2408         return ret;
2409 }
2410
2411 static int fix_reflink_p_key(struct btree_trans *trans, struct btree_iter *iter,
2412                              struct bkey_s_c k)
2413 {
2414         struct bkey_s_c_reflink_p p;
2415         struct bkey_i_reflink_p *u;
2416         int ret;
2417
2418         if (k.k->type != KEY_TYPE_reflink_p)
2419                 return 0;
2420
2421         p = bkey_s_c_to_reflink_p(k);
2422
2423         if (!p.v->front_pad && !p.v->back_pad)
2424                 return 0;
2425
2426         u = bch2_trans_kmalloc(trans, sizeof(*u));
2427         ret = PTR_ERR_OR_ZERO(u);
2428         if (ret)
2429                 return ret;
2430
2431         bkey_reassemble(&u->k_i, k);
2432         u->v.front_pad  = 0;
2433         u->v.back_pad   = 0;
2434
2435         return bch2_trans_update(trans, iter, &u->k_i, BTREE_TRIGGER_NORUN);
2436 }
2437
2438 int bch2_fix_reflink_p(struct bch_fs *c)
2439 {
2440         struct btree_iter iter;
2441         struct bkey_s_c k;
2442         int ret;
2443
2444         if (c->sb.version >= bcachefs_metadata_version_reflink_p_fix)
2445                 return 0;
2446
2447         ret = bch2_trans_run(c,
2448                 for_each_btree_key_commit(trans, iter,
2449                                 BTREE_ID_extents, POS_MIN,
2450                                 BTREE_ITER_INTENT|BTREE_ITER_PREFETCH|
2451                                 BTREE_ITER_ALL_SNAPSHOTS, k,
2452                                 NULL, NULL, BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
2453                         fix_reflink_p_key(trans, &iter, k)));
2454         if (ret)
2455                 bch_err_fn(c, ret);
2456         return ret;
2457 }