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