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