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