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