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