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