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