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