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