]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
Update bcachefs sources to 33a60d9b05 bcachefs: Assorted fixes for clang
[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 {
1128         struct bch_fs *c = trans->c;
1129         struct printbuf buf = PRINTBUF;
1130         struct btree_iter iter;
1131         struct bkey_s_c k;
1132         u32 snapshot = min(pos1.snapshot, pos2.p.snapshot);
1133         int ret;
1134
1135         BUG_ON(bkey_le(pos1, bkey_start_pos(&pos2)));
1136
1137         bch2_trans_iter_init(trans, &iter, btree, SPOS(pos1.inode, pos1.offset - 1, snapshot), 0);
1138         k = bch2_btree_iter_peek_upto(&iter, POS(pos1.inode, U64_MAX));
1139         ret = bkey_err(k);
1140         if (ret)
1141                 goto err;
1142
1143         prt_str(&buf, "\n  ");
1144         bch2_bkey_val_to_text(&buf, c, k);
1145
1146         if (!bpos_eq(pos1, k.k->p)) {
1147                 bch_err(c, "%s: error finding first overlapping extent when repairing%s",
1148                         __func__, buf.buf);
1149                 ret = -BCH_ERR_internal_fsck_err;
1150                 goto err;
1151         }
1152
1153         while (1) {
1154                 bch2_btree_iter_advance(&iter);
1155
1156                 k = bch2_btree_iter_peek_upto(&iter, POS(pos1.inode, U64_MAX));
1157                 ret = bkey_err(k);
1158                 if (ret)
1159                         goto err;
1160
1161                 if (bkey_ge(k.k->p, pos2.p))
1162                         break;
1163
1164         }
1165
1166         prt_str(&buf, "\n  ");
1167         bch2_bkey_val_to_text(&buf, c, k);
1168
1169         if (bkey_gt(k.k->p, pos2.p) ||
1170             pos2.size != k.k->size) {
1171                 bch_err(c, "%s: error finding seconding overlapping extent when repairing%s",
1172                         __func__, buf.buf);
1173                 ret = -BCH_ERR_internal_fsck_err;
1174                 goto err;
1175         }
1176
1177         if (fsck_err(c, "overlapping extents%s", buf.buf)) {
1178                 struct bpos update_pos = pos1.snapshot < pos2.p.snapshot ? pos1 : pos2.p;
1179                 struct btree_iter update_iter;
1180
1181                 struct bkey_i *update = bch2_bkey_get_mut(trans, &update_iter,
1182                                                 btree, update_pos,
1183                                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1184                 bch2_trans_iter_exit(trans, &update_iter);
1185                 if ((ret = PTR_ERR_OR_ZERO(update)))
1186                         goto err;
1187
1188                 *fixed = true;
1189         }
1190 fsck_err:
1191 err:
1192         bch2_trans_iter_exit(trans, &iter);
1193         printbuf_exit(&buf);
1194         return ret;
1195 }
1196
1197 static int check_overlapping_extents(struct btree_trans *trans,
1198                               struct snapshots_seen *seen,
1199                               struct extent_ends *extent_ends,
1200                               struct bkey_s_c k,
1201                               u32 equiv,
1202                               struct btree_iter *iter)
1203 {
1204         struct bch_fs *c = trans->c;
1205         struct extent_end *i;
1206         bool fixed = false;
1207         int ret = 0;
1208
1209         /* transaction restart, running again */
1210         if (bpos_eq(extent_ends->last_pos, k.k->p))
1211                 return 0;
1212
1213         if (extent_ends->last_pos.inode != k.k->p.inode)
1214                 extent_ends_reset(extent_ends);
1215
1216         darray_for_each(extent_ends->e, i) {
1217                 if (i->offset <= bkey_start_offset(k.k))
1218                         continue;
1219
1220                 if (!ref_visible2(c,
1221                                   k.k->p.snapshot, seen,
1222                                   i->snapshot, &i->seen))
1223                         continue;
1224
1225                 ret = overlapping_extents_found(trans, iter->btree_id,
1226                                                 SPOS(iter->pos.inode,
1227                                                      i->offset,
1228                                                      i->snapshot),
1229                                                 *k.k, &fixed);
1230                 if (ret)
1231                         goto err;
1232         }
1233
1234         ret = extent_ends_at(c, extent_ends, seen, k);
1235         if (ret)
1236                 goto err;
1237
1238         extent_ends->last_pos = k.k->p;
1239 err:
1240         return ret ?: fixed;
1241 }
1242
1243 static int check_extent(struct btree_trans *trans, struct btree_iter *iter,
1244                         struct bkey_s_c k,
1245                         struct inode_walker *inode,
1246                         struct snapshots_seen *s,
1247                         struct extent_ends *extent_ends)
1248 {
1249         struct bch_fs *c = trans->c;
1250         struct inode_walker_entry *i;
1251         struct printbuf buf = PRINTBUF;
1252         struct bpos equiv = k.k->p;
1253         int ret = 0;
1254
1255         equiv.snapshot = bch2_snapshot_equiv(c, k.k->p.snapshot);
1256
1257         ret = check_key_has_snapshot(trans, iter, k);
1258         if (ret) {
1259                 ret = ret < 0 ? ret : 0;
1260                 goto out;
1261         }
1262
1263         if (inode->last_pos.inode != k.k->p.inode) {
1264                 ret = check_i_sectors(trans, inode);
1265                 if (ret)
1266                         goto err;
1267         }
1268
1269         i = walk_inode(trans, inode, equiv, k.k->type == KEY_TYPE_whiteout);
1270         ret = PTR_ERR_OR_ZERO(i);
1271         if (ret)
1272                 goto err;
1273
1274         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
1275         if (ret)
1276                 goto err;
1277
1278         if (k.k->type != KEY_TYPE_whiteout) {
1279                 if (fsck_err_on(!i, c,
1280                                 "extent in missing inode:\n  %s",
1281                                 (printbuf_reset(&buf),
1282                                  bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
1283                         goto delete;
1284
1285                 if (fsck_err_on(i &&
1286                                 !S_ISREG(i->inode.bi_mode) &&
1287                                 !S_ISLNK(i->inode.bi_mode), c,
1288                                 "extent in non regular inode mode %o:\n  %s",
1289                                 i->inode.bi_mode,
1290                                 (printbuf_reset(&buf),
1291                                  bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
1292                         goto delete;
1293
1294                 ret = check_overlapping_extents(trans, s, extent_ends, k,
1295                                                 equiv.snapshot, iter);
1296                 if (ret < 0)
1297                         goto err;
1298
1299                 if (ret)
1300                         inode->recalculate_sums = true;
1301                 ret = 0;
1302         }
1303
1304         /*
1305          * Check inodes in reverse order, from oldest snapshots to newest,
1306          * starting from the inode that matches this extent's snapshot. If we
1307          * didn't have one, iterate over all inodes:
1308          */
1309         if (!i)
1310                 i = inode->inodes.data + inode->inodes.nr - 1;
1311
1312         for (;
1313              inode->inodes.data && i >= inode->inodes.data;
1314              --i) {
1315                 if (i->snapshot > equiv.snapshot ||
1316                     !key_visible_in_snapshot(c, s, i->snapshot, equiv.snapshot))
1317                         continue;
1318
1319                 if (k.k->type != KEY_TYPE_whiteout) {
1320                         if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
1321                                         k.k->p.offset > round_up(i->inode.bi_size, block_bytes(c)) >> 9 &&
1322                                         !bkey_extent_is_reservation(k), c,
1323                                         "extent type past end of inode %llu:%u, i_size %llu\n  %s",
1324                                         i->inode.bi_inum, i->snapshot, i->inode.bi_size,
1325                                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1326                                 struct btree_iter iter2;
1327
1328                                 bch2_trans_copy_iter(&iter2, iter);
1329                                 bch2_btree_iter_set_snapshot(&iter2, i->snapshot);
1330                                 ret =   bch2_btree_iter_traverse(&iter2) ?:
1331                                         bch2_btree_delete_at(trans, &iter2,
1332                                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1333                                 bch2_trans_iter_exit(trans, &iter2);
1334                                 if (ret)
1335                                         goto err;
1336
1337                                 iter->k.type = KEY_TYPE_whiteout;
1338                         }
1339
1340                         if (bkey_extent_is_allocation(k.k))
1341                                 i->count += k.k->size;
1342                 }
1343
1344                 i->seen_this_pos = true;
1345         }
1346 out:
1347 err:
1348 fsck_err:
1349         printbuf_exit(&buf);
1350
1351         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1352                 bch_err_fn(c, ret);
1353         return ret;
1354 delete:
1355         ret = bch2_btree_delete_at(trans, iter, BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1356         goto out;
1357 }
1358
1359 /*
1360  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
1361  * that i_size an i_sectors are consistent
1362  */
1363 int bch2_check_extents(struct bch_fs *c)
1364 {
1365         struct inode_walker w = inode_walker_init();
1366         struct snapshots_seen s;
1367         struct btree_trans trans;
1368         struct btree_iter iter;
1369         struct bkey_s_c k;
1370         struct extent_ends extent_ends;
1371         struct disk_reservation res = { 0 };
1372         int ret = 0;
1373
1374         snapshots_seen_init(&s);
1375         extent_ends_init(&extent_ends);
1376         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1377
1378         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_extents,
1379                         POS(BCACHEFS_ROOT_INO, 0),
1380                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
1381                         &res, NULL,
1382                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL, ({
1383                 bch2_disk_reservation_put(c, &res);
1384                 check_extent(&trans, &iter, k, &w, &s, &extent_ends);
1385         })) ?:
1386         check_i_sectors(&trans, &w);
1387
1388         bch2_disk_reservation_put(c, &res);
1389         extent_ends_exit(&extent_ends);
1390         inode_walker_exit(&w);
1391         bch2_trans_exit(&trans);
1392         snapshots_seen_exit(&s);
1393
1394         if (ret)
1395                 bch_err_fn(c, ret);
1396         return ret;
1397 }
1398
1399 static int check_subdir_count(struct btree_trans *trans, struct inode_walker *w)
1400 {
1401         struct bch_fs *c = trans->c;
1402         struct inode_walker_entry *i;
1403         u32 restart_count = trans->restart_count;
1404         int ret = 0;
1405         s64 count2;
1406
1407         darray_for_each(w->inodes, i) {
1408                 if (i->inode.bi_nlink == i->count)
1409                         continue;
1410
1411                 count2 = bch2_count_subdirs(trans, w->last_pos.inode, i->snapshot);
1412                 if (count2 < 0)
1413                         return count2;
1414
1415                 if (i->count != count2) {
1416                         bch_err(c, "fsck counted subdirectories wrong: got %llu should be %llu",
1417                                 i->count, count2);
1418                         i->count = count2;
1419                         if (i->inode.bi_nlink == i->count)
1420                                 continue;
1421                 }
1422
1423                 if (fsck_err_on(i->inode.bi_nlink != i->count, c,
1424                                 "directory %llu:%u with wrong i_nlink: got %u, should be %llu",
1425                                 w->last_pos.inode, i->snapshot, i->inode.bi_nlink, i->count)) {
1426                         i->inode.bi_nlink = i->count;
1427                         ret = write_inode(trans, &i->inode, i->snapshot);
1428                         if (ret)
1429                                 break;
1430                 }
1431         }
1432 fsck_err:
1433         if (ret)
1434                 bch_err_fn(c, ret);
1435         if (!ret && trans_was_restarted(trans, restart_count))
1436                 ret = -BCH_ERR_transaction_restart_nested;
1437         return ret;
1438 }
1439
1440 static int check_dirent_target(struct btree_trans *trans,
1441                                struct btree_iter *iter,
1442                                struct bkey_s_c_dirent d,
1443                                struct bch_inode_unpacked *target,
1444                                u32 target_snapshot)
1445 {
1446         struct bch_fs *c = trans->c;
1447         struct bkey_i_dirent *n;
1448         bool backpointer_exists = true;
1449         struct printbuf buf = PRINTBUF;
1450         int ret = 0;
1451
1452         if (!target->bi_dir &&
1453             !target->bi_dir_offset) {
1454                 target->bi_dir          = d.k->p.inode;
1455                 target->bi_dir_offset   = d.k->p.offset;
1456
1457                 ret = __write_inode(trans, target, target_snapshot);
1458                 if (ret)
1459                         goto err;
1460         }
1461
1462         if (!inode_points_to_dirent(target, d)) {
1463                 ret = inode_backpointer_exists(trans, target, d.k->p.snapshot);
1464                 if (ret < 0)
1465                         goto err;
1466
1467                 backpointer_exists = ret;
1468                 ret = 0;
1469
1470                 if (fsck_err_on(S_ISDIR(target->bi_mode) &&
1471                                 backpointer_exists, c,
1472                                 "directory %llu with multiple links",
1473                                 target->bi_inum)) {
1474                         ret = __remove_dirent(trans, d.k->p);
1475                         goto out;
1476                 }
1477
1478                 if (fsck_err_on(backpointer_exists &&
1479                                 !target->bi_nlink, c,
1480                                 "inode %llu type %s has multiple links but i_nlink 0",
1481                                 target->bi_inum, bch2_d_types[d.v->d_type])) {
1482                         target->bi_nlink++;
1483                         target->bi_flags &= ~BCH_INODE_UNLINKED;
1484
1485                         ret = __write_inode(trans, target, target_snapshot);
1486                         if (ret)
1487                                 goto err;
1488                 }
1489
1490                 if (fsck_err_on(!backpointer_exists, c,
1491                                 "inode %llu:%u has wrong backpointer:\n"
1492                                 "got       %llu:%llu\n"
1493                                 "should be %llu:%llu",
1494                                 target->bi_inum, target_snapshot,
1495                                 target->bi_dir,
1496                                 target->bi_dir_offset,
1497                                 d.k->p.inode,
1498                                 d.k->p.offset)) {
1499                         target->bi_dir          = d.k->p.inode;
1500                         target->bi_dir_offset   = d.k->p.offset;
1501
1502                         ret = __write_inode(trans, target, target_snapshot);
1503                         if (ret)
1504                                 goto err;
1505                 }
1506         }
1507
1508         if (fsck_err_on(d.v->d_type != inode_d_type(target), c,
1509                         "incorrect d_type: got %s, should be %s:\n%s",
1510                         bch2_d_type_str(d.v->d_type),
1511                         bch2_d_type_str(inode_d_type(target)),
1512                         (printbuf_reset(&buf),
1513                          bch2_bkey_val_to_text(&buf, c, d.s_c), buf.buf))) {
1514                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1515                 ret = PTR_ERR_OR_ZERO(n);
1516                 if (ret)
1517                         goto err;
1518
1519                 bkey_reassemble(&n->k_i, d.s_c);
1520                 n->v.d_type = inode_d_type(target);
1521
1522                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1523                 if (ret)
1524                         goto err;
1525
1526                 d = dirent_i_to_s_c(n);
1527         }
1528
1529         if (d.v->d_type == DT_SUBVOL &&
1530             target->bi_parent_subvol != le32_to_cpu(d.v->d_parent_subvol) &&
1531             (c->sb.version < bcachefs_metadata_version_subvol_dirent ||
1532              fsck_err(c, "dirent has wrong d_parent_subvol field: got %u, should be %u",
1533                       le32_to_cpu(d.v->d_parent_subvol),
1534                       target->bi_parent_subvol))) {
1535                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1536                 ret = PTR_ERR_OR_ZERO(n);
1537                 if (ret)
1538                         goto err;
1539
1540                 bkey_reassemble(&n->k_i, d.s_c);
1541                 n->v.d_parent_subvol = cpu_to_le32(target->bi_parent_subvol);
1542
1543                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1544                 if (ret)
1545                         goto err;
1546
1547                 d = dirent_i_to_s_c(n);
1548         }
1549 out:
1550 err:
1551 fsck_err:
1552         printbuf_exit(&buf);
1553
1554         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1555                 bch_err_fn(c, ret);
1556         return ret;
1557 }
1558
1559 static int check_dirent(struct btree_trans *trans, struct btree_iter *iter,
1560                         struct bkey_s_c k,
1561                         struct bch_hash_info *hash_info,
1562                         struct inode_walker *dir,
1563                         struct inode_walker *target,
1564                         struct snapshots_seen *s)
1565 {
1566         struct bch_fs *c = trans->c;
1567         struct bkey_s_c_dirent d;
1568         struct inode_walker_entry *i;
1569         struct printbuf buf = PRINTBUF;
1570         struct bpos equiv;
1571         int ret = 0;
1572
1573         ret = check_key_has_snapshot(trans, iter, k);
1574         if (ret) {
1575                 ret = ret < 0 ? ret : 0;
1576                 goto out;
1577         }
1578
1579         equiv = k.k->p;
1580         equiv.snapshot = bch2_snapshot_equiv(c, k.k->p.snapshot);
1581
1582         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
1583         if (ret)
1584                 goto err;
1585
1586         if (k.k->type == KEY_TYPE_whiteout)
1587                 goto out;
1588
1589         if (dir->last_pos.inode != k.k->p.inode) {
1590                 ret = check_subdir_count(trans, dir);
1591                 if (ret)
1592                         goto err;
1593         }
1594
1595         BUG_ON(!iter->path->should_be_locked);
1596
1597         i = walk_inode(trans, dir, equiv, k.k->type == KEY_TYPE_whiteout);
1598         ret = PTR_ERR_OR_ZERO(i);
1599         if (ret < 0)
1600                 goto err;
1601
1602         if (dir->first_this_inode && dir->inodes.nr)
1603                 *hash_info = bch2_hash_info_init(c, &dir->inodes.data[0].inode);
1604         dir->first_this_inode = false;
1605
1606         if (fsck_err_on(!i, c,
1607                         "dirent in nonexisting directory:\n%s",
1608                         (printbuf_reset(&buf),
1609                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1610                 ret = bch2_btree_delete_at(trans, iter,
1611                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1612                 goto out;
1613         }
1614
1615         if (!i)
1616                 goto out;
1617
1618         if (fsck_err_on(!S_ISDIR(i->inode.bi_mode), c,
1619                         "dirent in non directory inode type %s:\n%s",
1620                         bch2_d_type_str(inode_d_type(&i->inode)),
1621                         (printbuf_reset(&buf),
1622                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1623                 ret = bch2_btree_delete_at(trans, iter, 0);
1624                 goto out;
1625         }
1626
1627         ret = hash_check_key(trans, bch2_dirent_hash_desc, hash_info, iter, k);
1628         if (ret < 0)
1629                 goto err;
1630         if (ret) {
1631                 /* dirent has been deleted */
1632                 ret = 0;
1633                 goto out;
1634         }
1635
1636         if (k.k->type != KEY_TYPE_dirent)
1637                 goto out;
1638
1639         d = bkey_s_c_to_dirent(k);
1640
1641         if (d.v->d_type == DT_SUBVOL) {
1642                 struct bch_inode_unpacked subvol_root;
1643                 u32 target_subvol = le32_to_cpu(d.v->d_child_subvol);
1644                 u32 target_snapshot;
1645                 u64 target_inum;
1646
1647                 ret = __subvol_lookup(trans, target_subvol,
1648                                       &target_snapshot, &target_inum);
1649                 if (ret && !bch2_err_matches(ret, ENOENT))
1650                         goto err;
1651
1652                 if (fsck_err_on(ret, c,
1653                                 "dirent points to missing subvolume %u",
1654                                 le32_to_cpu(d.v->d_child_subvol))) {
1655                         ret = __remove_dirent(trans, d.k->p);
1656                         goto err;
1657                 }
1658
1659                 ret = __lookup_inode(trans, target_inum,
1660                                    &subvol_root, &target_snapshot);
1661                 if (ret && !bch2_err_matches(ret, ENOENT))
1662                         goto err;
1663
1664                 if (fsck_err_on(ret, c,
1665                                 "subvolume %u points to missing subvolume root %llu",
1666                                 target_subvol,
1667                                 target_inum)) {
1668                         bch_err(c, "repair not implemented yet");
1669                         ret = -EINVAL;
1670                         goto err;
1671                 }
1672
1673                 if (fsck_err_on(subvol_root.bi_subvol != target_subvol, c,
1674                                 "subvol root %llu has wrong bi_subvol field: got %u, should be %u",
1675                                 target_inum,
1676                                 subvol_root.bi_subvol, target_subvol)) {
1677                         subvol_root.bi_subvol = target_subvol;
1678                         ret = __write_inode(trans, &subvol_root, target_snapshot);
1679                         if (ret)
1680                                 goto err;
1681                 }
1682
1683                 ret = check_dirent_target(trans, iter, d, &subvol_root,
1684                                           target_snapshot);
1685                 if (ret)
1686                         goto err;
1687         } else {
1688                 ret = __get_visible_inodes(trans, target, s, le64_to_cpu(d.v->d_inum));
1689                 if (ret)
1690                         goto err;
1691
1692                 if (fsck_err_on(!target->inodes.nr, c,
1693                                 "dirent points to missing inode: (equiv %u)\n%s",
1694                                 equiv.snapshot,
1695                                 (printbuf_reset(&buf),
1696                                  bch2_bkey_val_to_text(&buf, c, k),
1697                                  buf.buf))) {
1698                         ret = __remove_dirent(trans, d.k->p);
1699                         if (ret)
1700                                 goto err;
1701                 }
1702
1703                 darray_for_each(target->inodes, i) {
1704                         ret = check_dirent_target(trans, iter, d,
1705                                                   &i->inode, i->snapshot);
1706                         if (ret)
1707                                 goto err;
1708                 }
1709         }
1710
1711         if (d.v->d_type == DT_DIR)
1712                 for_each_visible_inode(c, s, dir, equiv.snapshot, i)
1713                         i->count++;
1714
1715 out:
1716 err:
1717 fsck_err:
1718         printbuf_exit(&buf);
1719
1720         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1721                 bch_err_fn(c, ret);
1722         return ret;
1723 }
1724
1725 /*
1726  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
1727  * validate d_type
1728  */
1729 int bch2_check_dirents(struct bch_fs *c)
1730 {
1731         struct inode_walker dir = inode_walker_init();
1732         struct inode_walker target = inode_walker_init();
1733         struct snapshots_seen s;
1734         struct bch_hash_info hash_info;
1735         struct btree_trans trans;
1736         struct btree_iter iter;
1737         struct bkey_s_c k;
1738         int ret = 0;
1739
1740         snapshots_seen_init(&s);
1741         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1742
1743         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_dirents,
1744                         POS(BCACHEFS_ROOT_INO, 0),
1745                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1746                         k,
1747                         NULL, NULL,
1748                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
1749                 check_dirent(&trans, &iter, k, &hash_info, &dir, &target, &s));
1750
1751         bch2_trans_exit(&trans);
1752         snapshots_seen_exit(&s);
1753         inode_walker_exit(&dir);
1754         inode_walker_exit(&target);
1755
1756         if (ret)
1757                 bch_err_fn(c, ret);
1758         return ret;
1759 }
1760
1761 static int check_xattr(struct btree_trans *trans, struct btree_iter *iter,
1762                        struct bkey_s_c k,
1763                        struct bch_hash_info *hash_info,
1764                        struct inode_walker *inode)
1765 {
1766         struct bch_fs *c = trans->c;
1767         struct inode_walker_entry *i;
1768         int ret;
1769
1770         ret = check_key_has_snapshot(trans, iter, k);
1771         if (ret)
1772                 return ret;
1773
1774         i = walk_inode(trans, inode, k.k->p, k.k->type == KEY_TYPE_whiteout);
1775         ret = PTR_ERR_OR_ZERO(i);
1776         if (ret)
1777                 return ret;
1778
1779         if (inode->first_this_inode && inode->inodes.nr)
1780                 *hash_info = bch2_hash_info_init(c, &inode->inodes.data[0].inode);
1781         inode->first_this_inode = false;
1782
1783         if (fsck_err_on(!i, c,
1784                         "xattr for missing inode %llu",
1785                         k.k->p.inode))
1786                 return bch2_btree_delete_at(trans, iter, 0);
1787
1788         if (!i)
1789                 return 0;
1790
1791         ret = hash_check_key(trans, bch2_xattr_hash_desc, hash_info, iter, k);
1792 fsck_err:
1793         if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
1794                 bch_err_fn(c, ret);
1795         return ret;
1796 }
1797
1798 /*
1799  * Walk xattrs: verify that they all have a corresponding inode
1800  */
1801 int bch2_check_xattrs(struct bch_fs *c)
1802 {
1803         struct inode_walker inode = inode_walker_init();
1804         struct bch_hash_info hash_info;
1805         struct btree_trans trans;
1806         struct btree_iter iter;
1807         struct bkey_s_c k;
1808         int ret = 0;
1809
1810         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1811
1812         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_xattrs,
1813                         POS(BCACHEFS_ROOT_INO, 0),
1814                         BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1815                         k,
1816                         NULL, NULL,
1817                         BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
1818                 check_xattr(&trans, &iter, k, &hash_info, &inode));
1819
1820         bch2_trans_exit(&trans);
1821
1822         if (ret)
1823                 bch_err_fn(c, ret);
1824         return ret;
1825 }
1826
1827 static int check_root_trans(struct btree_trans *trans)
1828 {
1829         struct bch_fs *c = trans->c;
1830         struct bch_inode_unpacked root_inode;
1831         u32 snapshot;
1832         u64 inum;
1833         int ret;
1834
1835         ret = __subvol_lookup(trans, BCACHEFS_ROOT_SUBVOL, &snapshot, &inum);
1836         if (ret && !bch2_err_matches(ret, ENOENT))
1837                 return ret;
1838
1839         if (mustfix_fsck_err_on(ret, c, "root subvol missing")) {
1840                 struct bkey_i_subvolume root_subvol;
1841
1842                 snapshot        = U32_MAX;
1843                 inum            = BCACHEFS_ROOT_INO;
1844
1845                 bkey_subvolume_init(&root_subvol.k_i);
1846                 root_subvol.k.p.offset = BCACHEFS_ROOT_SUBVOL;
1847                 root_subvol.v.flags     = 0;
1848                 root_subvol.v.snapshot  = cpu_to_le32(snapshot);
1849                 root_subvol.v.inode     = cpu_to_le64(inum);
1850                 ret = commit_do(trans, NULL, NULL,
1851                                       BTREE_INSERT_NOFAIL|
1852                                       BTREE_INSERT_LAZY_RW,
1853                         __bch2_btree_insert(trans, BTREE_ID_subvolumes,
1854                                             &root_subvol.k_i, 0));
1855                 if (ret) {
1856                         bch_err(c, "error writing root subvol: %s", bch2_err_str(ret));
1857                         goto err;
1858                 }
1859
1860         }
1861
1862         ret = __lookup_inode(trans, BCACHEFS_ROOT_INO, &root_inode, &snapshot);
1863         if (ret && !bch2_err_matches(ret, ENOENT))
1864                 return ret;
1865
1866         if (mustfix_fsck_err_on(ret, c, "root directory missing") ||
1867             mustfix_fsck_err_on(!S_ISDIR(root_inode.bi_mode), c,
1868                                 "root inode not a directory")) {
1869                 bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755,
1870                                 0, NULL);
1871                 root_inode.bi_inum = inum;
1872
1873                 ret = __write_inode(trans, &root_inode, snapshot);
1874                 if (ret)
1875                         bch_err(c, "error writing root inode: %s", bch2_err_str(ret));
1876         }
1877 err:
1878 fsck_err:
1879         return ret;
1880 }
1881
1882 /* Get root directory, create if it doesn't exist: */
1883 int bch2_check_root(struct bch_fs *c)
1884 {
1885         int ret;
1886
1887         ret = bch2_trans_do(c, NULL, NULL,
1888                              BTREE_INSERT_NOFAIL|
1889                              BTREE_INSERT_LAZY_RW,
1890                 check_root_trans(&trans));
1891
1892         if (ret)
1893                 bch_err_fn(c, ret);
1894         return ret;
1895 }
1896
1897 struct pathbuf_entry {
1898         u64     inum;
1899         u32     snapshot;
1900 };
1901
1902 typedef DARRAY(struct pathbuf_entry) pathbuf;
1903
1904 static bool path_is_dup(pathbuf *p, u64 inum, u32 snapshot)
1905 {
1906         struct pathbuf_entry *i;
1907
1908         darray_for_each(*p, i)
1909                 if (i->inum     == inum &&
1910                     i->snapshot == snapshot)
1911                         return true;
1912
1913         return false;
1914 }
1915
1916 static int path_down(struct bch_fs *c, pathbuf *p,
1917                      u64 inum, u32 snapshot)
1918 {
1919         int ret = darray_push(p, ((struct pathbuf_entry) {
1920                 .inum           = inum,
1921                 .snapshot       = snapshot,
1922         }));
1923
1924         if (ret)
1925                 bch_err(c, "fsck: error allocating memory for pathbuf, size %zu",
1926                         p->size);
1927         return ret;
1928 }
1929
1930 /*
1931  * Check that a given inode is reachable from the root:
1932  *
1933  * XXX: we should also be verifying that inodes are in the right subvolumes
1934  */
1935 static int check_path(struct btree_trans *trans,
1936                       pathbuf *p,
1937                       struct bch_inode_unpacked *inode,
1938                       u32 snapshot)
1939 {
1940         struct bch_fs *c = trans->c;
1941         int ret = 0;
1942
1943         snapshot = bch2_snapshot_equiv(c, snapshot);
1944         p->nr = 0;
1945
1946         while (!(inode->bi_inum == BCACHEFS_ROOT_INO &&
1947                  inode->bi_subvol == BCACHEFS_ROOT_SUBVOL)) {
1948                 struct btree_iter dirent_iter;
1949                 struct bkey_s_c_dirent d;
1950                 u32 parent_snapshot = snapshot;
1951
1952                 if (inode->bi_subvol) {
1953                         u64 inum;
1954
1955                         ret = subvol_lookup(trans, inode->bi_parent_subvol,
1956                                             &parent_snapshot, &inum);
1957                         if (ret)
1958                                 break;
1959                 }
1960
1961                 ret = lockrestart_do(trans,
1962                         PTR_ERR_OR_ZERO((d = dirent_get_by_pos(trans, &dirent_iter,
1963                                           SPOS(inode->bi_dir, inode->bi_dir_offset,
1964                                                parent_snapshot))).k));
1965                 if (ret && !bch2_err_matches(ret, ENOENT))
1966                         break;
1967
1968                 if (!ret && !dirent_points_to_inode(d, inode)) {
1969                         bch2_trans_iter_exit(trans, &dirent_iter);
1970                         ret = -BCH_ERR_ENOENT_dirent_doesnt_match_inode;
1971                 }
1972
1973                 if (bch2_err_matches(ret, ENOENT)) {
1974                         if (fsck_err(c,  "unreachable inode %llu:%u, type %s nlink %u backptr %llu:%llu",
1975                                      inode->bi_inum, snapshot,
1976                                      bch2_d_type_str(inode_d_type(inode)),
1977                                      inode->bi_nlink,
1978                                      inode->bi_dir,
1979                                      inode->bi_dir_offset))
1980                                 ret = reattach_inode(trans, inode, snapshot);
1981                         break;
1982                 }
1983
1984                 bch2_trans_iter_exit(trans, &dirent_iter);
1985
1986                 if (!S_ISDIR(inode->bi_mode))
1987                         break;
1988
1989                 ret = path_down(c, p, inode->bi_inum, snapshot);
1990                 if (ret) {
1991                         bch_err(c, "memory allocation failure");
1992                         return ret;
1993                 }
1994
1995                 snapshot = parent_snapshot;
1996
1997                 ret = lookup_inode(trans, inode->bi_dir, inode, &snapshot);
1998                 if (ret) {
1999                         /* Should have been caught in dirents pass */
2000                         bch_err(c, "error looking up parent directory: %i", ret);
2001                         break;
2002                 }
2003
2004                 if (path_is_dup(p, inode->bi_inum, snapshot)) {
2005                         struct pathbuf_entry *i;
2006
2007                         /* XXX print path */
2008                         bch_err(c, "directory structure loop");
2009
2010                         darray_for_each(*p, i)
2011                                 pr_err("%llu:%u", i->inum, i->snapshot);
2012                         pr_err("%llu:%u", inode->bi_inum, snapshot);
2013
2014                         if (!fsck_err(c, "directory structure loop"))
2015                                 return 0;
2016
2017                         ret = commit_do(trans, NULL, NULL,
2018                                               BTREE_INSERT_NOFAIL|
2019                                               BTREE_INSERT_LAZY_RW,
2020                                         remove_backpointer(trans, inode));
2021                         if (ret) {
2022                                 bch_err(c, "error removing dirent: %i", ret);
2023                                 break;
2024                         }
2025
2026                         ret = reattach_inode(trans, inode, snapshot);
2027                 }
2028         }
2029 fsck_err:
2030         if (ret)
2031                 bch_err_fn(c, ret);
2032         return ret;
2033 }
2034
2035 /*
2036  * Check for unreachable inodes, as well as loops in the directory structure:
2037  * After bch2_check_dirents(), if an inode backpointer doesn't exist that means it's
2038  * unreachable:
2039  */
2040 int bch2_check_directory_structure(struct bch_fs *c)
2041 {
2042         struct btree_trans trans;
2043         struct btree_iter iter;
2044         struct bkey_s_c k;
2045         struct bch_inode_unpacked u;
2046         pathbuf path = { 0, };
2047         int ret;
2048
2049         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2050
2051         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN,
2052                            BTREE_ITER_INTENT|
2053                            BTREE_ITER_PREFETCH|
2054                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2055                 if (!bkey_is_inode(k.k))
2056                         continue;
2057
2058                 ret = bch2_inode_unpack(k, &u);
2059                 if (ret) {
2060                         /* Should have been caught earlier in fsck: */
2061                         bch_err(c, "error unpacking inode %llu: %i", k.k->p.offset, ret);
2062                         break;
2063                 }
2064
2065                 if (u.bi_flags & BCH_INODE_UNLINKED)
2066                         continue;
2067
2068                 ret = check_path(&trans, &path, &u, iter.pos.snapshot);
2069                 if (ret)
2070                         break;
2071         }
2072         bch2_trans_iter_exit(&trans, &iter);
2073         bch2_trans_exit(&trans);
2074         darray_exit(&path);
2075
2076         if (ret)
2077                 bch_err_fn(c, ret);
2078         return ret;
2079 }
2080
2081 /* check_nlink pass: */
2082
2083 struct nlink_table {
2084         size_t          nr;
2085         size_t          size;
2086
2087         struct nlink {
2088                 u64     inum;
2089                 u32     snapshot;
2090                 u32     count;
2091         }               *d;
2092 };
2093
2094 static int add_nlink(struct bch_fs *c, struct nlink_table *t,
2095                      u64 inum, u32 snapshot)
2096 {
2097         if (t->nr == t->size) {
2098                 size_t new_size = max_t(size_t, 128UL, t->size * 2);
2099                 void *d = kvmalloc_array(new_size, sizeof(t->d[0]), GFP_KERNEL);
2100
2101                 if (!d) {
2102                         bch_err(c, "fsck: error allocating memory for nlink_table, size %zu",
2103                                 new_size);
2104                         return -BCH_ERR_ENOMEM_fsck_add_nlink;
2105                 }
2106
2107                 if (t->d)
2108                         memcpy(d, t->d, t->size * sizeof(t->d[0]));
2109                 kvfree(t->d);
2110
2111                 t->d = d;
2112                 t->size = new_size;
2113         }
2114
2115
2116         t->d[t->nr++] = (struct nlink) {
2117                 .inum           = inum,
2118                 .snapshot       = snapshot,
2119         };
2120
2121         return 0;
2122 }
2123
2124 static int nlink_cmp(const void *_l, const void *_r)
2125 {
2126         const struct nlink *l = _l;
2127         const struct nlink *r = _r;
2128
2129         return cmp_int(l->inum, r->inum) ?: cmp_int(l->snapshot, r->snapshot);
2130 }
2131
2132 static void inc_link(struct bch_fs *c, struct snapshots_seen *s,
2133                      struct nlink_table *links,
2134                      u64 range_start, u64 range_end, u64 inum, u32 snapshot)
2135 {
2136         struct nlink *link, key = {
2137                 .inum = inum, .snapshot = U32_MAX,
2138         };
2139
2140         if (inum < range_start || inum >= range_end)
2141                 return;
2142
2143         link = __inline_bsearch(&key, links->d, links->nr,
2144                                 sizeof(links->d[0]), nlink_cmp);
2145         if (!link)
2146                 return;
2147
2148         while (link > links->d && link[0].inum == link[-1].inum)
2149                 --link;
2150
2151         for (; link < links->d + links->nr && link->inum == inum; link++)
2152                 if (ref_visible(c, s, snapshot, link->snapshot)) {
2153                         link->count++;
2154                         if (link->snapshot >= snapshot)
2155                                 break;
2156                 }
2157 }
2158
2159 noinline_for_stack
2160 static int check_nlinks_find_hardlinks(struct bch_fs *c,
2161                                        struct nlink_table *t,
2162                                        u64 start, u64 *end)
2163 {
2164         struct btree_trans trans;
2165         struct btree_iter iter;
2166         struct bkey_s_c k;
2167         struct bch_inode_unpacked u;
2168         int ret = 0;
2169
2170         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2171
2172         for_each_btree_key(&trans, iter, BTREE_ID_inodes,
2173                            POS(0, start),
2174                            BTREE_ITER_INTENT|
2175                            BTREE_ITER_PREFETCH|
2176                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2177                 if (!bkey_is_inode(k.k))
2178                         continue;
2179
2180                 /* Should never fail, checked by bch2_inode_invalid: */
2181                 BUG_ON(bch2_inode_unpack(k, &u));
2182
2183                 /*
2184                  * Backpointer and directory structure checks are sufficient for
2185                  * directories, since they can't have hardlinks:
2186                  */
2187                 if (S_ISDIR(u.bi_mode))
2188                         continue;
2189
2190                 if (!u.bi_nlink)
2191                         continue;
2192
2193                 ret = add_nlink(c, t, k.k->p.offset, k.k->p.snapshot);
2194                 if (ret) {
2195                         *end = k.k->p.offset;
2196                         ret = 0;
2197                         break;
2198                 }
2199
2200         }
2201         bch2_trans_iter_exit(&trans, &iter);
2202         bch2_trans_exit(&trans);
2203
2204         if (ret)
2205                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2206
2207         return ret;
2208 }
2209
2210 noinline_for_stack
2211 static int check_nlinks_walk_dirents(struct bch_fs *c, struct nlink_table *links,
2212                                      u64 range_start, u64 range_end)
2213 {
2214         struct btree_trans trans;
2215         struct snapshots_seen s;
2216         struct btree_iter iter;
2217         struct bkey_s_c k;
2218         struct bkey_s_c_dirent d;
2219         int ret;
2220
2221         snapshots_seen_init(&s);
2222
2223         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2224
2225         for_each_btree_key(&trans, iter, BTREE_ID_dirents, POS_MIN,
2226                            BTREE_ITER_INTENT|
2227                            BTREE_ITER_PREFETCH|
2228                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2229                 ret = snapshots_seen_update(c, &s, iter.btree_id, k.k->p);
2230                 if (ret)
2231                         break;
2232
2233                 switch (k.k->type) {
2234                 case KEY_TYPE_dirent:
2235                         d = bkey_s_c_to_dirent(k);
2236
2237                         if (d.v->d_type != DT_DIR &&
2238                             d.v->d_type != DT_SUBVOL)
2239                                 inc_link(c, &s, links, range_start, range_end,
2240                                          le64_to_cpu(d.v->d_inum),
2241                                          bch2_snapshot_equiv(c, d.k->p.snapshot));
2242                         break;
2243                 }
2244         }
2245         bch2_trans_iter_exit(&trans, &iter);
2246
2247         if (ret)
2248                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
2249
2250         bch2_trans_exit(&trans);
2251         snapshots_seen_exit(&s);
2252         return ret;
2253 }
2254
2255 static int check_nlinks_update_inode(struct btree_trans *trans, struct btree_iter *iter,
2256                                      struct bkey_s_c k,
2257                                      struct nlink_table *links,
2258                                      size_t *idx, u64 range_end)
2259 {
2260         struct bch_fs *c = trans->c;
2261         struct bch_inode_unpacked u;
2262         struct nlink *link = &links->d[*idx];
2263         int ret = 0;
2264
2265         if (k.k->p.offset >= range_end)
2266                 return 1;
2267
2268         if (!bkey_is_inode(k.k))
2269                 return 0;
2270
2271         BUG_ON(bch2_inode_unpack(k, &u));
2272
2273         if (S_ISDIR(u.bi_mode))
2274                 return 0;
2275
2276         if (!u.bi_nlink)
2277                 return 0;
2278
2279         while ((cmp_int(link->inum, k.k->p.offset) ?:
2280                 cmp_int(link->snapshot, k.k->p.snapshot)) < 0) {
2281                 BUG_ON(*idx == links->nr);
2282                 link = &links->d[++*idx];
2283         }
2284
2285         if (fsck_err_on(bch2_inode_nlink_get(&u) != link->count, c,
2286                         "inode %llu type %s has wrong i_nlink (%u, should be %u)",
2287                         u.bi_inum, bch2_d_types[mode_to_type(u.bi_mode)],
2288                         bch2_inode_nlink_get(&u), link->count)) {
2289                 bch2_inode_nlink_set(&u, link->count);
2290                 ret = __write_inode(trans, &u, k.k->p.snapshot);
2291         }
2292 fsck_err:
2293         return ret;
2294 }
2295
2296 noinline_for_stack
2297 static int check_nlinks_update_hardlinks(struct bch_fs *c,
2298                                struct nlink_table *links,
2299                                u64 range_start, u64 range_end)
2300 {
2301         struct btree_trans trans;
2302         struct btree_iter iter;
2303         struct bkey_s_c k;
2304         size_t idx = 0;
2305         int ret = 0;
2306
2307         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2308
2309         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_inodes,
2310                         POS(0, range_start),
2311                         BTREE_ITER_INTENT|BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS, k,
2312                         NULL, NULL, BTREE_INSERT_LAZY_RW|BTREE_INSERT_NOFAIL,
2313                 check_nlinks_update_inode(&trans, &iter, k, links, &idx, range_end));
2314
2315         bch2_trans_exit(&trans);
2316
2317         if (ret < 0) {
2318                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2319                 return ret;
2320         }
2321
2322         return 0;
2323 }
2324
2325 int bch2_check_nlinks(struct bch_fs *c)
2326 {
2327         struct nlink_table links = { 0 };
2328         u64 this_iter_range_start, next_iter_range_start = 0;
2329         int ret = 0;
2330
2331         do {
2332                 this_iter_range_start = next_iter_range_start;
2333                 next_iter_range_start = U64_MAX;
2334
2335                 ret = check_nlinks_find_hardlinks(c, &links,
2336                                                   this_iter_range_start,
2337                                                   &next_iter_range_start);
2338
2339                 ret = check_nlinks_walk_dirents(c, &links,
2340                                           this_iter_range_start,
2341                                           next_iter_range_start);
2342                 if (ret)
2343                         break;
2344
2345                 ret = check_nlinks_update_hardlinks(c, &links,
2346                                          this_iter_range_start,
2347                                          next_iter_range_start);
2348                 if (ret)
2349                         break;
2350
2351                 links.nr = 0;
2352         } while (next_iter_range_start != U64_MAX);
2353
2354         kvfree(links.d);
2355
2356         if (ret)
2357                 bch_err_fn(c, ret);
2358         return ret;
2359 }
2360
2361 static int fix_reflink_p_key(struct btree_trans *trans, struct btree_iter *iter,
2362                              struct bkey_s_c k)
2363 {
2364         struct bkey_s_c_reflink_p p;
2365         struct bkey_i_reflink_p *u;
2366         int ret;
2367
2368         if (k.k->type != KEY_TYPE_reflink_p)
2369                 return 0;
2370
2371         p = bkey_s_c_to_reflink_p(k);
2372
2373         if (!p.v->front_pad && !p.v->back_pad)
2374                 return 0;
2375
2376         u = bch2_trans_kmalloc(trans, sizeof(*u));
2377         ret = PTR_ERR_OR_ZERO(u);
2378         if (ret)
2379                 return ret;
2380
2381         bkey_reassemble(&u->k_i, k);
2382         u->v.front_pad  = 0;
2383         u->v.back_pad   = 0;
2384
2385         return bch2_trans_update(trans, iter, &u->k_i, BTREE_TRIGGER_NORUN);
2386 }
2387
2388 int bch2_fix_reflink_p(struct bch_fs *c)
2389 {
2390         struct btree_iter iter;
2391         struct bkey_s_c k;
2392         int ret;
2393
2394         if (c->sb.version >= bcachefs_metadata_version_reflink_p_fix)
2395                 return 0;
2396
2397         ret = bch2_trans_run(c,
2398                 for_each_btree_key_commit(&trans, iter,
2399                                 BTREE_ID_extents, POS_MIN,
2400                                 BTREE_ITER_INTENT|BTREE_ITER_PREFETCH|
2401                                 BTREE_ITER_ALL_SNAPSHOTS, k,
2402                                 NULL, NULL, BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
2403                         fix_reflink_p_key(&trans, &iter, k)));
2404
2405         if (ret)
2406                 bch_err_fn(c, ret);
2407         return ret;
2408 }