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