]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
c558895ef2918bafe0f7b48094477a6305765688
[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_update(struct bch_fs *c, struct snapshots_seen *s,
493                                  enum btree_id btree_id, struct bpos pos)
494 {
495         struct snapshots_seen_entry *i, n = {
496                 .id     = pos.snapshot,
497                 .equiv  = bch2_snapshot_equiv(c, pos.snapshot),
498         };
499         int ret;
500
501         if (bkey_cmp(s->pos, pos))
502                 s->ids.nr = 0;
503
504         pos.snapshot = n.equiv;
505         s->pos = pos;
506
507         darray_for_each(s->ids, i)
508                 if (i->equiv == n.equiv) {
509                         if (i->id != n.id) {
510                                 bch_err(c, "snapshot deletion did not run correctly:\n"
511                                         "  duplicate keys in btree %s at %llu:%llu snapshots %u, %u (equiv %u)\n",
512                                         bch2_btree_ids[btree_id],
513                                         pos.inode, pos.offset,
514                                         i->id, n.id, n.equiv);
515                                 return -EINVAL;
516                         }
517
518                         return 0;
519                 }
520
521         ret = darray_push(&s->ids, n);
522         if (ret)
523                 bch_err(c, "error reallocating snapshots_seen table (size %zu)",
524                         s->ids.size);
525         return ret;
526 }
527
528 /**
529  * key_visible_in_snapshot - returns true if @id is a descendent of @ancestor,
530  * and @ancestor hasn't been overwritten in @seen
531  *
532  * That is, returns whether key in @ancestor snapshot is visible in @id snapshot
533  */
534 static bool key_visible_in_snapshot(struct bch_fs *c, struct snapshots_seen *seen,
535                                     u32 id, u32 ancestor)
536 {
537         ssize_t i;
538         u32 top = seen->ids.nr ? seen->ids.data[seen->ids.nr - 1].equiv : 0;
539
540         BUG_ON(id > ancestor);
541         BUG_ON(!bch2_snapshot_is_equiv(c, id));
542         BUG_ON(!bch2_snapshot_is_equiv(c, ancestor));
543
544         /* @ancestor should be the snapshot most recently added to @seen */
545         BUG_ON(ancestor != seen->pos.snapshot);
546         BUG_ON(ancestor != top);
547
548         if (id == ancestor)
549                 return true;
550
551         if (!bch2_snapshot_is_ancestor(c, id, ancestor))
552                 return false;
553
554         for (i = seen->ids.nr - 2;
555              i >= 0 && seen->ids.data[i].equiv >= id;
556              --i)
557                 if (bch2_snapshot_is_ancestor(c, id, seen->ids.data[i].equiv) &&
558                     bch2_snapshot_is_ancestor(c, seen->ids.data[i].equiv, ancestor))
559                         return false;
560
561         return true;
562 }
563
564 /**
565  * ref_visible - given a key with snapshot id @src that points to a key with
566  * snapshot id @dst, test whether there is some snapshot in which @dst is
567  * visible.
568  *
569  * This assumes we're visiting @src keys in natural key order.
570  *
571  * @s   - list of snapshot IDs already seen at @src
572  * @src - snapshot ID of src key
573  * @dst - snapshot ID of dst key
574  */
575 static int ref_visible(struct bch_fs *c, struct snapshots_seen *s,
576                        u32 src, u32 dst)
577 {
578         return dst <= src
579                 ? key_visible_in_snapshot(c, s, dst, src)
580                 : bch2_snapshot_is_ancestor(c, src, dst);
581 }
582
583 #define for_each_visible_inode(_c, _s, _w, _snapshot, _i)                               \
584         for (_i = (_w)->inodes.data; _i < (_w)->inodes.data + (_w)->inodes.nr &&        \
585              (_i)->snapshot <= (_snapshot); _i++)                                       \
586                 if (key_visible_in_snapshot(_c, _s, _i->snapshot, _snapshot))
587
588 struct inode_walker_entry {
589         struct bch_inode_unpacked inode;
590         u32                     snapshot;
591         u64                     count;
592 };
593
594 struct inode_walker {
595         bool                            first_this_inode;
596         u64                             cur_inum;
597
598         DARRAY(struct inode_walker_entry) inodes;
599 };
600
601 static void inode_walker_exit(struct inode_walker *w)
602 {
603         darray_exit(&w->inodes);
604 }
605
606 static struct inode_walker inode_walker_init(void)
607 {
608         return (struct inode_walker) { 0, };
609 }
610
611 static int add_inode(struct bch_fs *c, struct inode_walker *w,
612                      struct bkey_s_c inode)
613 {
614         struct bch_inode_unpacked u;
615
616         BUG_ON(bch2_inode_unpack(inode, &u));
617
618         return darray_push(&w->inodes, ((struct inode_walker_entry) {
619                 .inode          = u,
620                 .snapshot       = bch2_snapshot_equiv(c, inode.k->p.snapshot),
621         }));
622 }
623
624 static int __walk_inode(struct btree_trans *trans,
625                         struct inode_walker *w, struct bpos pos)
626 {
627         struct bch_fs *c = trans->c;
628         struct btree_iter iter;
629         struct bkey_s_c k;
630         unsigned i;
631         int ret;
632
633         pos.snapshot = bch2_snapshot_equiv(c, pos.snapshot);
634
635         if (pos.inode == w->cur_inum) {
636                 w->first_this_inode = false;
637                 goto lookup_snapshot;
638         }
639
640         w->inodes.nr = 0;
641
642         for_each_btree_key(trans, iter, BTREE_ID_inodes, POS(0, pos.inode),
643                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
644                 if (k.k->p.offset != pos.inode)
645                         break;
646
647                 if (bkey_is_inode(k.k))
648                         add_inode(c, w, k);
649         }
650         bch2_trans_iter_exit(trans, &iter);
651
652         if (ret)
653                 return ret;
654
655         w->cur_inum             = pos.inode;
656         w->first_this_inode     = true;
657 lookup_snapshot:
658         for (i = 0; i < w->inodes.nr; i++)
659                 if (bch2_snapshot_is_ancestor(c, pos.snapshot, w->inodes.data[i].snapshot))
660                         goto found;
661         return INT_MAX;
662 found:
663         BUG_ON(pos.snapshot > w->inodes.data[i].snapshot);
664
665         if (pos.snapshot != w->inodes.data[i].snapshot) {
666                 struct inode_walker_entry e = w->inodes.data[i];
667
668                 e.snapshot = pos.snapshot;
669                 e.count = 0;
670
671                 bch_info(c, "have key for inode %llu:%u but have inode in ancestor snapshot %u",
672                          pos.inode, pos.snapshot, w->inodes.data[i].snapshot);
673
674                 while (i && w->inodes.data[i - 1].snapshot > pos.snapshot)
675                         --i;
676
677                 ret = darray_insert_item(&w->inodes, i, e);
678                 if (ret)
679                         return ret;
680         }
681
682         return i;
683 }
684
685 static int __get_visible_inodes(struct btree_trans *trans,
686                                 struct inode_walker *w,
687                                 struct snapshots_seen *s,
688                                 u64 inum)
689 {
690         struct bch_fs *c = trans->c;
691         struct btree_iter iter;
692         struct bkey_s_c k;
693         int ret;
694
695         w->inodes.nr = 0;
696
697         for_each_btree_key(trans, iter, BTREE_ID_inodes, POS(0, inum),
698                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
699                 u32 equiv = bch2_snapshot_equiv(c, k.k->p.snapshot);
700
701                 if (k.k->p.offset != inum)
702                         break;
703
704                 if (!ref_visible(c, s, s->pos.snapshot, equiv))
705                         continue;
706
707                 if (bkey_is_inode(k.k))
708                         add_inode(c, w, k);
709
710                 if (equiv >= s->pos.snapshot)
711                         break;
712         }
713         bch2_trans_iter_exit(trans, &iter);
714
715         return ret;
716 }
717
718 static int check_key_has_snapshot(struct btree_trans *trans,
719                                   struct btree_iter *iter,
720                                   struct bkey_s_c k)
721 {
722         struct bch_fs *c = trans->c;
723         struct printbuf buf = PRINTBUF;
724         int ret = 0;
725
726         if (mustfix_fsck_err_on(!bch2_snapshot_equiv(c, k.k->p.snapshot), c,
727                         "key in missing snapshot: %s",
728                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
729                 ret = bch2_btree_delete_at(trans, iter,
730                                             BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE) ?: 1;
731 fsck_err:
732         printbuf_exit(&buf);
733         return ret;
734 }
735
736 static int hash_redo_key(struct btree_trans *trans,
737                          const struct bch_hash_desc desc,
738                          struct bch_hash_info *hash_info,
739                          struct btree_iter *k_iter, struct bkey_s_c k)
740 {
741         bch_err(trans->c, "hash_redo_key() not implemented yet");
742         return -EINVAL;
743 #if 0
744         struct bkey_i *delete;
745         struct bkey_i *tmp;
746
747         delete = bch2_trans_kmalloc(trans, sizeof(*delete));
748         if (IS_ERR(delete))
749                 return PTR_ERR(delete);
750
751         tmp = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
752         if (IS_ERR(tmp))
753                 return PTR_ERR(tmp);
754
755         bkey_reassemble(tmp, k);
756
757         bkey_init(&delete->k);
758         delete->k.p = k_iter->pos;
759         return  bch2_btree_iter_traverse(k_iter) ?:
760                 bch2_trans_update(trans, k_iter, delete, 0) ?:
761                 bch2_hash_set(trans, desc, hash_info, k_iter->pos.inode, tmp, 0);
762 #endif
763 }
764
765 static int hash_check_key(struct btree_trans *trans,
766                           const struct bch_hash_desc desc,
767                           struct bch_hash_info *hash_info,
768                           struct btree_iter *k_iter, struct bkey_s_c hash_k)
769 {
770         struct bch_fs *c = trans->c;
771         struct btree_iter iter = { NULL };
772         struct printbuf buf = PRINTBUF;
773         struct bkey_s_c k;
774         u64 hash;
775         int ret = 0;
776
777         if (hash_k.k->type != desc.key_type)
778                 return 0;
779
780         hash = desc.hash_bkey(hash_info, hash_k);
781
782         if (likely(hash == hash_k.k->p.offset))
783                 return 0;
784
785         if (hash_k.k->p.offset < hash)
786                 goto bad_hash;
787
788         for_each_btree_key_norestart(trans, iter, desc.btree_id,
789                                      POS(hash_k.k->p.inode, hash),
790                                      BTREE_ITER_SLOTS, k, ret) {
791                 if (!bkey_cmp(k.k->p, hash_k.k->p))
792                         break;
793
794                 if (fsck_err_on(k.k->type == desc.key_type &&
795                                 !desc.cmp_bkey(k, hash_k), c,
796                                 "duplicate hash table keys:\n%s",
797                                 (printbuf_reset(&buf),
798                                  bch2_bkey_val_to_text(&buf, c, hash_k),
799                                  buf.buf))) {
800                         ret = bch2_hash_delete_at(trans, desc, hash_info, k_iter, 0) ?: 1;
801                         break;
802                 }
803
804                 if (bkey_deleted(k.k)) {
805                         bch2_trans_iter_exit(trans, &iter);
806                         goto bad_hash;
807                 }
808         }
809 out:
810         bch2_trans_iter_exit(trans, &iter);
811         printbuf_exit(&buf);
812         return ret;
813 bad_hash:
814         if (fsck_err(c, "hash table key at wrong offset: btree %s inode %llu offset %llu, "
815                      "hashed to %llu\n%s",
816                      bch2_btree_ids[desc.btree_id], hash_k.k->p.inode, hash_k.k->p.offset, hash,
817                      (printbuf_reset(&buf),
818                       bch2_bkey_val_to_text(&buf, c, hash_k), buf.buf)) == FSCK_ERR_IGNORE)
819                 return 0;
820
821         ret = hash_redo_key(trans, desc, hash_info, k_iter, hash_k);
822         if (ret) {
823                 bch_err(c, "hash_redo_key err %i", ret);
824                 return ret;
825         }
826         ret = -EINTR;
827 fsck_err:
828         goto out;
829 }
830
831 static int check_inode(struct btree_trans *trans,
832                        struct btree_iter *iter,
833                        struct bch_inode_unpacked *prev,
834                        struct snapshots_seen *s,
835                        bool full)
836 {
837         struct bch_fs *c = trans->c;
838         struct bkey_s_c k;
839         struct bch_inode_unpacked u;
840         bool do_update = false;
841         int ret;
842
843         k = bch2_btree_iter_peek(iter);
844         if (!k.k)
845                 return 0;
846
847         ret = bkey_err(k);
848         if (ret)
849                 return ret;
850
851         ret = check_key_has_snapshot(trans, iter, k);
852         if (ret < 0)
853                 goto err;
854         if (ret)
855                 return 0;
856
857         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
858         if (ret)
859                 goto err;
860
861         /*
862          * if snapshot id isn't a leaf node, skip it - deletion in
863          * particular is not atomic, so on the internal snapshot nodes
864          * we can see inodes marked for deletion after a clean shutdown
865          */
866         if (bch2_snapshot_internal_node(c, k.k->p.snapshot))
867                 return 0;
868
869         if (!bkey_is_inode(k.k))
870                 return 0;
871
872         BUG_ON(bch2_inode_unpack(k, &u));
873
874         if (!full &&
875             !(u.bi_flags & (BCH_INODE_I_SIZE_DIRTY|
876                             BCH_INODE_I_SECTORS_DIRTY|
877                             BCH_INODE_UNLINKED)))
878                 return 0;
879
880         if (prev->bi_inum != u.bi_inum)
881                 *prev = u;
882
883         if (fsck_err_on(prev->bi_hash_seed      != u.bi_hash_seed ||
884                         inode_d_type(prev)      != inode_d_type(&u), c,
885                         "inodes in different snapshots don't match")) {
886                 bch_err(c, "repair not implemented yet");
887                 return -EINVAL;
888         }
889
890         if (u.bi_flags & BCH_INODE_UNLINKED &&
891             (!c->sb.clean ||
892              fsck_err(c, "filesystem marked clean, but inode %llu unlinked",
893                       u.bi_inum))) {
894                 bch2_trans_unlock(trans);
895                 bch2_fs_lazy_rw(c);
896
897                 ret = fsck_inode_rm(trans, u.bi_inum, iter->pos.snapshot);
898                 if (ret)
899                         bch_err(c, "error in fsck: error %i while deleting inode", ret);
900                 return ret;
901         }
902
903         if (u.bi_flags & BCH_INODE_I_SIZE_DIRTY &&
904             (!c->sb.clean ||
905              fsck_err(c, "filesystem marked clean, but inode %llu has i_size dirty",
906                       u.bi_inum))) {
907                 bch_verbose(c, "truncating inode %llu", u.bi_inum);
908
909                 bch2_trans_unlock(trans);
910                 bch2_fs_lazy_rw(c);
911
912                 /*
913                  * XXX: need to truncate partial blocks too here - or ideally
914                  * just switch units to bytes and that issue goes away
915                  */
916                 ret = bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
917                                 SPOS(u.bi_inum, round_up(u.bi_size, block_bytes(c)) >> 9,
918                                      iter->pos.snapshot),
919                                 POS(u.bi_inum, U64_MAX),
920                                 0, NULL);
921                 if (ret) {
922                         bch_err(c, "error in fsck: error %i truncating inode", ret);
923                         return ret;
924                 }
925
926                 /*
927                  * We truncated without our normal sector accounting hook, just
928                  * make sure we recalculate it:
929                  */
930                 u.bi_flags |= BCH_INODE_I_SECTORS_DIRTY;
931
932                 u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
933                 do_update = true;
934         }
935
936         if (u.bi_flags & BCH_INODE_I_SECTORS_DIRTY &&
937             (!c->sb.clean ||
938              fsck_err(c, "filesystem marked clean, but inode %llu has i_sectors dirty",
939                       u.bi_inum))) {
940                 s64 sectors;
941
942                 bch_verbose(c, "recounting sectors for inode %llu",
943                             u.bi_inum);
944
945                 sectors = bch2_count_inode_sectors(trans, u.bi_inum, iter->pos.snapshot);
946                 if (sectors < 0) {
947                         bch_err(c, "error in fsck: error %i recounting inode sectors",
948                                 (int) sectors);
949                         return sectors;
950                 }
951
952                 u.bi_sectors = sectors;
953                 u.bi_flags &= ~BCH_INODE_I_SECTORS_DIRTY;
954                 do_update = true;
955         }
956
957         if (u.bi_flags & BCH_INODE_BACKPTR_UNTRUSTED) {
958                 u.bi_dir = 0;
959                 u.bi_dir_offset = 0;
960                 u.bi_flags &= ~BCH_INODE_BACKPTR_UNTRUSTED;
961                 do_update = true;
962         }
963
964         if (do_update) {
965                 ret = write_inode(trans, &u, iter->pos.snapshot);
966                 if (ret)
967                         bch_err(c, "error in fsck: error %i "
968                                 "updating inode", ret);
969         }
970 err:
971 fsck_err:
972         if (ret)
973                 bch_err(c, "error %i from check_inode()", ret);
974         return ret;
975 }
976
977 noinline_for_stack
978 static int check_inodes(struct bch_fs *c, bool full)
979 {
980         struct btree_trans trans;
981         struct btree_iter iter;
982         struct bch_inode_unpacked prev = { 0 };
983         struct snapshots_seen s;
984         int ret;
985
986         snapshots_seen_init(&s);
987         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
988
989         bch2_trans_iter_init(&trans, &iter, BTREE_ID_inodes, POS_MIN,
990                              BTREE_ITER_INTENT|
991                              BTREE_ITER_PREFETCH|
992                              BTREE_ITER_ALL_SNAPSHOTS);
993
994         do {
995                 ret = commit_do(&trans, NULL, NULL,
996                                       BTREE_INSERT_LAZY_RW|
997                                       BTREE_INSERT_NOFAIL,
998                         check_inode(&trans, &iter, &prev, &s, full));
999                 if (ret)
1000                         break;
1001         } while (bch2_btree_iter_advance(&iter));
1002         bch2_trans_iter_exit(&trans, &iter);
1003
1004         bch2_trans_exit(&trans);
1005         snapshots_seen_exit(&s);
1006         if (ret)
1007                 bch_err(c, "error %i from check_inodes()", ret);
1008         return ret;
1009 }
1010
1011 /*
1012  * Checking for overlapping extents needs to be reimplemented
1013  */
1014 #if 0
1015 static int fix_overlapping_extent(struct btree_trans *trans,
1016                                        struct bkey_s_c k, struct bpos cut_at)
1017 {
1018         struct btree_iter iter;
1019         struct bkey_i *u;
1020         int ret;
1021
1022         u = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1023         ret = PTR_ERR_OR_ZERO(u);
1024         if (ret)
1025                 return ret;
1026
1027         bkey_reassemble(u, k);
1028         bch2_cut_front(cut_at, u);
1029
1030
1031         /*
1032          * We don't want to go through the extent_handle_overwrites path:
1033          *
1034          * XXX: this is going to screw up disk accounting, extent triggers
1035          * assume things about extent overwrites - we should be running the
1036          * triggers manually here
1037          */
1038         bch2_trans_iter_init(trans, &iter, BTREE_ID_extents, u->k.p,
1039                              BTREE_ITER_INTENT|BTREE_ITER_NOT_EXTENTS);
1040
1041         BUG_ON(iter.flags & BTREE_ITER_IS_EXTENTS);
1042         ret   = bch2_btree_iter_traverse(&iter) ?:
1043                 bch2_trans_update(trans, &iter, u, BTREE_TRIGGER_NORUN) ?:
1044                 bch2_trans_commit(trans, NULL, NULL,
1045                                   BTREE_INSERT_NOFAIL|
1046                                   BTREE_INSERT_LAZY_RW);
1047         bch2_trans_iter_exit(trans, &iter);
1048         return ret;
1049 }
1050 #endif
1051
1052 static struct bkey_s_c_dirent dirent_get_by_pos(struct btree_trans *trans,
1053                                                 struct btree_iter *iter,
1054                                                 struct bpos pos)
1055 {
1056         struct bkey_s_c k;
1057         int ret;
1058
1059         bch2_trans_iter_init(trans, iter, BTREE_ID_dirents, pos, 0);
1060         k = bch2_btree_iter_peek_slot(iter);
1061         ret = bkey_err(k);
1062         if (!ret && k.k->type != KEY_TYPE_dirent)
1063                 ret = -ENOENT;
1064         if (ret) {
1065                 bch2_trans_iter_exit(trans, iter);
1066                 return (struct bkey_s_c_dirent) { .k = ERR_PTR(ret) };
1067         }
1068
1069         return bkey_s_c_to_dirent(k);
1070 }
1071
1072 static bool inode_points_to_dirent(struct bch_inode_unpacked *inode,
1073                                    struct bkey_s_c_dirent d)
1074 {
1075         return  inode->bi_dir           == d.k->p.inode &&
1076                 inode->bi_dir_offset    == d.k->p.offset;
1077 }
1078
1079 static bool dirent_points_to_inode(struct bkey_s_c_dirent d,
1080                                    struct bch_inode_unpacked *inode)
1081 {
1082         return d.v->d_type == DT_SUBVOL
1083                 ? le32_to_cpu(d.v->d_child_subvol)      == inode->bi_subvol
1084                 : le64_to_cpu(d.v->d_inum)              == inode->bi_inum;
1085 }
1086
1087 static int inode_backpointer_exists(struct btree_trans *trans,
1088                                     struct bch_inode_unpacked *inode,
1089                                     u32 snapshot)
1090 {
1091         struct btree_iter iter;
1092         struct bkey_s_c_dirent d;
1093         int ret;
1094
1095         d = dirent_get_by_pos(trans, &iter,
1096                         SPOS(inode->bi_dir, inode->bi_dir_offset, snapshot));
1097         ret = bkey_err(d.s_c);
1098         if (ret)
1099                 return ret == -ENOENT ? 0 : ret;
1100
1101         ret = dirent_points_to_inode(d, inode);
1102         bch2_trans_iter_exit(trans, &iter);
1103         return ret;
1104 }
1105
1106 static int check_i_sectors(struct btree_trans *trans, struct inode_walker *w)
1107 {
1108         struct bch_fs *c = trans->c;
1109         struct inode_walker_entry *i;
1110         int ret = 0, ret2 = 0;
1111         s64 count2;
1112
1113         darray_for_each(w->inodes, i) {
1114                 if (i->inode.bi_sectors == i->count)
1115                         continue;
1116
1117                 count2 = lockrestart_do(trans,
1118                         bch2_count_inode_sectors(trans, w->cur_inum, i->snapshot));
1119
1120                 if (i->count != count2) {
1121                         bch_err(c, "fsck counted i_sectors wrong: got %llu should be %llu",
1122                                 i->count, count2);
1123                         i->count = count2;
1124                         if (i->inode.bi_sectors == i->count)
1125                                 continue;
1126                 }
1127
1128                 if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY), c,
1129                             "inode %llu:%u has incorrect i_sectors: got %llu, should be %llu",
1130                             w->cur_inum, i->snapshot,
1131                             i->inode.bi_sectors, i->count) == FSCK_ERR_IGNORE)
1132                         continue;
1133
1134                 i->inode.bi_sectors = i->count;
1135                 ret = write_inode(trans, &i->inode, i->snapshot);
1136                 if (ret)
1137                         break;
1138                 ret2 = -EINTR;
1139         }
1140 fsck_err:
1141         if (ret)
1142                 bch_err(c, "error %i from check_i_sectors()", ret);
1143         return ret ?: ret2;
1144 }
1145
1146 static int check_extent(struct btree_trans *trans, struct btree_iter *iter,
1147                         struct inode_walker *inode,
1148                         struct snapshots_seen *s)
1149 {
1150         struct bch_fs *c = trans->c;
1151         struct bkey_s_c k;
1152         struct inode_walker_entry *i;
1153         struct printbuf buf = PRINTBUF;
1154         struct bpos equiv;
1155         int ret = 0;
1156 peek:
1157         k = bch2_btree_iter_peek(iter);
1158         if (!k.k)
1159                 goto out;
1160
1161         ret = bkey_err(k);
1162         if (ret)
1163                 goto err;
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                 goto peek;
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         if (!bch2_snapshot_internal_node(c, equiv.snapshot)) {
1242                 for_each_visible_inode(c, s, inode, equiv.snapshot, i) {
1243                         if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
1244                                         k.k->type != KEY_TYPE_reservation &&
1245                                         k.k->p.offset > round_up(i->inode.bi_size, block_bytes(c)) >> 9, c,
1246                                         "extent type %u offset %llu past end of inode %llu, i_size %llu",
1247                                         k.k->type, k.k->p.offset, k.k->p.inode, i->inode.bi_size)) {
1248                                 bch2_fs_lazy_rw(c);
1249                                 ret = bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
1250                                                 SPOS(k.k->p.inode, round_up(i->inode.bi_size, block_bytes(c)) >> 9,
1251                                                      equiv.snapshot),
1252                                                 POS(k.k->p.inode, U64_MAX),
1253                                                 0, NULL) ?: -EINTR;
1254                                 goto out;
1255                         }
1256                 }
1257         }
1258
1259         if (bkey_extent_is_allocation(k.k))
1260                 for_each_visible_inode(c, s, inode, equiv.snapshot, i)
1261                         i->count += k.k->size;
1262 #if 0
1263         bch2_bkey_buf_reassemble(&prev, c, k);
1264 #endif
1265
1266 out:
1267 err:
1268 fsck_err:
1269         printbuf_exit(&buf);
1270
1271         if (ret && ret != -EINTR)
1272                 bch_err(c, "error %i from check_extent()", ret);
1273         return ret;
1274 }
1275
1276 /*
1277  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
1278  * that i_size an i_sectors are consistent
1279  */
1280 noinline_for_stack
1281 static int check_extents(struct bch_fs *c)
1282 {
1283         struct inode_walker w = inode_walker_init();
1284         struct snapshots_seen s;
1285         struct btree_trans trans;
1286         struct btree_iter iter;
1287         int ret = 0;
1288
1289 #if 0
1290         struct bkey_buf prev;
1291         bch2_bkey_buf_init(&prev);
1292         prev.k->k = KEY(0, 0, 0);
1293 #endif
1294         snapshots_seen_init(&s);
1295         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1296
1297         bch_verbose(c, "checking extents");
1298
1299         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
1300                              POS(BCACHEFS_ROOT_INO, 0),
1301                              BTREE_ITER_INTENT|
1302                              BTREE_ITER_PREFETCH|
1303                              BTREE_ITER_ALL_SNAPSHOTS);
1304
1305         do {
1306                 ret = commit_do(&trans, NULL, NULL,
1307                                       BTREE_INSERT_LAZY_RW|
1308                                       BTREE_INSERT_NOFAIL,
1309                         check_extent(&trans, &iter, &w, &s));
1310                 if (ret)
1311                         break;
1312         } while (bch2_btree_iter_advance(&iter));
1313         bch2_trans_iter_exit(&trans, &iter);
1314 #if 0
1315         bch2_bkey_buf_exit(&prev, c);
1316 #endif
1317         inode_walker_exit(&w);
1318         bch2_trans_exit(&trans);
1319         snapshots_seen_exit(&s);
1320
1321         if (ret)
1322                 bch_err(c, "error %i from check_extents()", ret);
1323         return ret;
1324 }
1325
1326 static int check_subdir_count(struct btree_trans *trans, struct inode_walker *w)
1327 {
1328         struct bch_fs *c = trans->c;
1329         struct inode_walker_entry *i;
1330         int ret = 0, ret2 = 0;
1331         s64 count2;
1332
1333         darray_for_each(w->inodes, i) {
1334                 if (i->inode.bi_nlink == i->count)
1335                         continue;
1336
1337                 count2 = bch2_count_subdirs(trans, w->cur_inum, i->snapshot);
1338                 if (count2 < 0)
1339                         return count2;
1340
1341                 if (i->count != count2) {
1342                         bch_err(c, "fsck counted subdirectories wrong: got %llu should be %llu",
1343                                 i->count, count2);
1344                         i->count = count2;
1345                         if (i->inode.bi_nlink == i->count)
1346                                 continue;
1347                 }
1348
1349                 if (fsck_err_on(i->inode.bi_nlink != i->count, c,
1350                                 "directory %llu:%u with wrong i_nlink: got %u, should be %llu",
1351                                 w->cur_inum, i->snapshot, i->inode.bi_nlink, i->count)) {
1352                         i->inode.bi_nlink = i->count;
1353                         ret = write_inode(trans, &i->inode, i->snapshot);
1354                         if (ret)
1355                                 break;
1356                         ret2 = -EINTR;
1357                 }
1358         }
1359 fsck_err:
1360         if (ret)
1361                 bch_err(c, "error %i from check_subdir_count()", ret);
1362         return ret ?: ret2;
1363 }
1364
1365 static int check_dirent_target(struct btree_trans *trans,
1366                                struct btree_iter *iter,
1367                                struct bkey_s_c_dirent d,
1368                                struct bch_inode_unpacked *target,
1369                                u32 target_snapshot)
1370 {
1371         struct bch_fs *c = trans->c;
1372         struct bkey_i_dirent *n;
1373         bool backpointer_exists = true;
1374         struct printbuf buf = PRINTBUF;
1375         int ret = 0;
1376
1377         if (!target->bi_dir &&
1378             !target->bi_dir_offset) {
1379                 target->bi_dir          = d.k->p.inode;
1380                 target->bi_dir_offset   = d.k->p.offset;
1381
1382                 ret = __write_inode(trans, target, target_snapshot);
1383                 if (ret)
1384                         goto err;
1385         }
1386
1387         if (!inode_points_to_dirent(target, d)) {
1388                 ret = inode_backpointer_exists(trans, target, d.k->p.snapshot);
1389                 if (ret < 0)
1390                         goto err;
1391
1392                 backpointer_exists = ret;
1393                 ret = 0;
1394
1395                 if (fsck_err_on(S_ISDIR(target->bi_mode) &&
1396                                 backpointer_exists, c,
1397                                 "directory %llu with multiple links",
1398                                 target->bi_inum)) {
1399                         ret = __remove_dirent(trans, d.k->p);
1400                         goto out;
1401                 }
1402
1403                 if (fsck_err_on(backpointer_exists &&
1404                                 !target->bi_nlink, c,
1405                                 "inode %llu type %s has multiple links but i_nlink 0",
1406                                 target->bi_inum, bch2_d_types[d.v->d_type])) {
1407                         target->bi_nlink++;
1408                         target->bi_flags &= ~BCH_INODE_UNLINKED;
1409
1410                         ret = __write_inode(trans, target, target_snapshot);
1411                         if (ret)
1412                                 goto err;
1413                 }
1414
1415                 if (fsck_err_on(!backpointer_exists, c,
1416                                 "inode %llu:%u has wrong backpointer:\n"
1417                                 "got       %llu:%llu\n"
1418                                 "should be %llu:%llu",
1419                                 target->bi_inum, target_snapshot,
1420                                 target->bi_dir,
1421                                 target->bi_dir_offset,
1422                                 d.k->p.inode,
1423                                 d.k->p.offset)) {
1424                         target->bi_dir          = d.k->p.inode;
1425                         target->bi_dir_offset   = d.k->p.offset;
1426
1427                         ret = __write_inode(trans, target, target_snapshot);
1428                         if (ret)
1429                                 goto err;
1430                 }
1431         }
1432
1433         if (fsck_err_on(d.v->d_type != inode_d_type(target), c,
1434                         "incorrect d_type: got %s, should be %s:\n%s",
1435                         bch2_d_type_str(d.v->d_type),
1436                         bch2_d_type_str(inode_d_type(target)),
1437                         (printbuf_reset(&buf),
1438                          bch2_bkey_val_to_text(&buf, c, d.s_c), buf.buf))) {
1439                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1440                 ret = PTR_ERR_OR_ZERO(n);
1441                 if (ret)
1442                         goto err;
1443
1444                 bkey_reassemble(&n->k_i, d.s_c);
1445                 n->v.d_type = inode_d_type(target);
1446
1447                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1448                 if (ret)
1449                         goto err;
1450
1451                 d = dirent_i_to_s_c(n);
1452         }
1453
1454         if (d.v->d_type == DT_SUBVOL &&
1455             target->bi_parent_subvol != le32_to_cpu(d.v->d_parent_subvol) &&
1456             (c->sb.version < bcachefs_metadata_version_subvol_dirent ||
1457              fsck_err(c, "dirent has wrong d_parent_subvol field: got %u, should be %u",
1458                       le32_to_cpu(d.v->d_parent_subvol),
1459                       target->bi_parent_subvol))) {
1460                 n = bch2_trans_kmalloc(trans, bkey_bytes(d.k));
1461                 ret = PTR_ERR_OR_ZERO(n);
1462                 if (ret)
1463                         goto err;
1464
1465                 bkey_reassemble(&n->k_i, d.s_c);
1466                 n->v.d_parent_subvol = cpu_to_le32(target->bi_parent_subvol);
1467
1468                 ret = bch2_trans_update(trans, iter, &n->k_i, 0);
1469                 if (ret)
1470                         goto err;
1471
1472                 d = dirent_i_to_s_c(n);
1473         }
1474 out:
1475 err:
1476 fsck_err:
1477         printbuf_exit(&buf);
1478
1479         if (ret && ret != -EINTR)
1480                 bch_err(c, "error %i from check_target()", ret);
1481         return ret;
1482 }
1483
1484 static int check_dirent(struct btree_trans *trans, struct btree_iter *iter,
1485                         struct bch_hash_info *hash_info,
1486                         struct inode_walker *dir,
1487                         struct inode_walker *target,
1488                         struct snapshots_seen *s)
1489 {
1490         struct bch_fs *c = trans->c;
1491         struct bkey_s_c k;
1492         struct bkey_s_c_dirent d;
1493         struct inode_walker_entry *i;
1494         struct printbuf buf = PRINTBUF;
1495         struct bpos equiv;
1496         int ret = 0;
1497 peek:
1498         k = bch2_btree_iter_peek(iter);
1499         if (!k.k)
1500                 goto out;
1501
1502         ret = bkey_err(k);
1503         if (ret)
1504                 goto err;
1505
1506         ret = check_key_has_snapshot(trans, iter, k);
1507         if (ret) {
1508                 ret = ret < 0 ? ret : 0;
1509                 goto out;
1510         }
1511
1512         equiv = k.k->p;
1513         equiv.snapshot = bch2_snapshot_equiv(c, k.k->p.snapshot);
1514
1515         ret = snapshots_seen_update(c, s, iter->btree_id, k.k->p);
1516         if (ret)
1517                 goto err;
1518
1519         if (k.k->type == KEY_TYPE_whiteout)
1520                 goto out;
1521
1522         if (dir->cur_inum != k.k->p.inode) {
1523                 ret = check_subdir_count(trans, dir);
1524                 if (ret)
1525                         goto err;
1526         }
1527
1528         if (!iter->path->should_be_locked) {
1529                 /* hack: see check_extent() */
1530                 goto peek;
1531         }
1532
1533         ret = __walk_inode(trans, dir, equiv);
1534         if (ret < 0)
1535                 goto err;
1536
1537         if (fsck_err_on(ret == INT_MAX, c,
1538                         "dirent in nonexisting directory:\n%s",
1539                         (printbuf_reset(&buf),
1540                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1541                 ret = bch2_btree_delete_at(trans, iter,
1542                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1543                 goto out;
1544         }
1545
1546         if (ret == INT_MAX) {
1547                 ret = 0;
1548                 goto out;
1549         }
1550
1551         i = dir->inodes.data + ret;
1552         ret = 0;
1553
1554         if (fsck_err_on(!S_ISDIR(i->inode.bi_mode), c,
1555                         "dirent in non directory inode type %s:\n%s",
1556                         bch2_d_type_str(inode_d_type(&i->inode)),
1557                         (printbuf_reset(&buf),
1558                          bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1559                 ret = bch2_btree_delete_at(trans, iter, 0);
1560                 goto out;
1561         }
1562
1563         if (dir->first_this_inode)
1564                 *hash_info = bch2_hash_info_init(c, &dir->inodes.data[0].inode);
1565
1566         ret = hash_check_key(trans, bch2_dirent_hash_desc,
1567                              hash_info, iter, k);
1568         if (ret < 0)
1569                 goto err;
1570         if (ret) {
1571                 /* dirent has been deleted */
1572                 ret = 0;
1573                 goto out;
1574         }
1575
1576         if (k.k->type != KEY_TYPE_dirent)
1577                 goto out;
1578
1579         d = bkey_s_c_to_dirent(k);
1580
1581         if (d.v->d_type == DT_SUBVOL) {
1582                 struct bch_inode_unpacked subvol_root;
1583                 u32 target_subvol = le32_to_cpu(d.v->d_child_subvol);
1584                 u32 target_snapshot;
1585                 u64 target_inum;
1586
1587                 ret = __subvol_lookup(trans, target_subvol,
1588                                       &target_snapshot, &target_inum);
1589                 if (ret && ret != -ENOENT)
1590                         goto err;
1591
1592                 if (fsck_err_on(ret, c,
1593                                 "dirent points to missing subvolume %llu",
1594                                 le64_to_cpu(d.v->d_child_subvol))) {
1595                         ret = __remove_dirent(trans, d.k->p);
1596                         goto err;
1597                 }
1598
1599                 ret = __lookup_inode(trans, target_inum,
1600                                    &subvol_root, &target_snapshot);
1601                 if (ret && ret != -ENOENT)
1602                         goto err;
1603
1604                 if (fsck_err_on(ret, c,
1605                                 "subvolume %u points to missing subvolume root %llu",
1606                                 target_subvol,
1607                                 target_inum)) {
1608                         bch_err(c, "repair not implemented yet");
1609                         ret = -EINVAL;
1610                         goto err;
1611                 }
1612
1613                 if (fsck_err_on(subvol_root.bi_subvol != target_subvol, c,
1614                                 "subvol root %llu has wrong bi_subvol field: got %u, should be %u",
1615                                 target_inum,
1616                                 subvol_root.bi_subvol, target_subvol)) {
1617                         subvol_root.bi_subvol = target_subvol;
1618                         ret = __write_inode(trans, &subvol_root, target_snapshot);
1619                         if (ret)
1620                                 goto err;
1621                 }
1622
1623                 ret = check_dirent_target(trans, iter, d, &subvol_root,
1624                                           target_snapshot);
1625                 if (ret)
1626                         goto err;
1627         } else {
1628                 ret = __get_visible_inodes(trans, target, s, le64_to_cpu(d.v->d_inum));
1629                 if (ret)
1630                         goto err;
1631
1632                 if (fsck_err_on(!target->inodes.nr, c,
1633                                 "dirent points to missing inode: (equiv %u)\n%s",
1634                                 equiv.snapshot,
1635                                 (printbuf_reset(&buf),
1636                                  bch2_bkey_val_to_text(&buf, c, k),
1637                                  buf.buf))) {
1638                         ret = __remove_dirent(trans, d.k->p);
1639                         if (ret)
1640                                 goto err;
1641                 }
1642
1643                 darray_for_each(target->inodes, i) {
1644                         ret = check_dirent_target(trans, iter, d,
1645                                                   &i->inode, i->snapshot);
1646                         if (ret)
1647                                 goto err;
1648                 }
1649         }
1650
1651         if (d.v->d_type == DT_DIR)
1652                 for_each_visible_inode(c, s, dir, equiv.snapshot, i)
1653                         i->count++;
1654
1655 out:
1656 err:
1657 fsck_err:
1658         printbuf_exit(&buf);
1659
1660         if (ret && ret != -EINTR)
1661                 bch_err(c, "error %i from check_dirent()", ret);
1662         return ret;
1663 }
1664
1665 /*
1666  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
1667  * validate d_type
1668  */
1669 noinline_for_stack
1670 static int check_dirents(struct bch_fs *c)
1671 {
1672         struct inode_walker dir = inode_walker_init();
1673         struct inode_walker target = inode_walker_init();
1674         struct snapshots_seen s;
1675         struct bch_hash_info hash_info;
1676         struct btree_trans trans;
1677         struct btree_iter iter;
1678         int ret = 0;
1679
1680         bch_verbose(c, "checking dirents");
1681
1682         snapshots_seen_init(&s);
1683         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1684
1685         bch2_trans_iter_init(&trans, &iter, BTREE_ID_dirents,
1686                              POS(BCACHEFS_ROOT_INO, 0),
1687                              BTREE_ITER_INTENT|
1688                              BTREE_ITER_PREFETCH|
1689                              BTREE_ITER_ALL_SNAPSHOTS);
1690
1691         do {
1692                 ret = commit_do(&trans, NULL, NULL,
1693                                       BTREE_INSERT_LAZY_RW|
1694                                       BTREE_INSERT_NOFAIL,
1695                         check_dirent(&trans, &iter, &hash_info,
1696                                      &dir, &target, &s));
1697                 if (ret)
1698                         break;
1699         } while (bch2_btree_iter_advance(&iter));
1700         bch2_trans_iter_exit(&trans, &iter);
1701
1702         bch2_trans_exit(&trans);
1703         snapshots_seen_exit(&s);
1704         inode_walker_exit(&dir);
1705         inode_walker_exit(&target);
1706
1707         if (ret)
1708                 bch_err(c, "error %i from check_dirents()", ret);
1709         return ret;
1710 }
1711
1712 static int check_xattr(struct btree_trans *trans, struct btree_iter *iter,
1713                        struct bch_hash_info *hash_info,
1714                        struct inode_walker *inode)
1715 {
1716         struct bch_fs *c = trans->c;
1717         struct bkey_s_c k;
1718         int ret;
1719
1720         k = bch2_btree_iter_peek(iter);
1721         if (!k.k)
1722                 return 0;
1723
1724         ret = bkey_err(k);
1725         if (ret)
1726                 return ret;
1727
1728         ret = check_key_has_snapshot(trans, iter, k);
1729         if (ret)
1730                 return ret;
1731
1732         ret = __walk_inode(trans, inode, k.k->p);
1733         if (ret < 0)
1734                 return ret;
1735
1736         if (fsck_err_on(ret == INT_MAX, c,
1737                         "xattr for missing inode %llu",
1738                         k.k->p.inode))
1739                 return bch2_btree_delete_at(trans, iter, 0);
1740
1741         if (ret == INT_MAX)
1742                 return 0;
1743
1744         ret = 0;
1745
1746         if (inode->first_this_inode)
1747                 *hash_info = bch2_hash_info_init(c, &inode->inodes.data[0].inode);
1748
1749         ret = hash_check_key(trans, bch2_xattr_hash_desc, hash_info, iter, k);
1750 fsck_err:
1751         if (ret && ret != -EINTR)
1752                 bch_err(c, "error %i from check_xattr()", ret);
1753         return ret;
1754 }
1755
1756 /*
1757  * Walk xattrs: verify that they all have a corresponding inode
1758  */
1759 noinline_for_stack
1760 static int check_xattrs(struct bch_fs *c)
1761 {
1762         struct inode_walker inode = inode_walker_init();
1763         struct bch_hash_info hash_info;
1764         struct btree_trans trans;
1765         struct btree_iter iter;
1766         int ret = 0;
1767
1768         bch_verbose(c, "checking xattrs");
1769
1770         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1771
1772         bch2_trans_iter_init(&trans, &iter, BTREE_ID_xattrs,
1773                              POS(BCACHEFS_ROOT_INO, 0),
1774                              BTREE_ITER_INTENT|
1775                              BTREE_ITER_PREFETCH|
1776                              BTREE_ITER_ALL_SNAPSHOTS);
1777
1778         do {
1779                 ret = commit_do(&trans, NULL, NULL,
1780                                       BTREE_INSERT_LAZY_RW|
1781                                       BTREE_INSERT_NOFAIL,
1782                                       check_xattr(&trans, &iter, &hash_info,
1783                                                   &inode));
1784                 if (ret)
1785                         break;
1786         } while (bch2_btree_iter_advance(&iter));
1787         bch2_trans_iter_exit(&trans, &iter);
1788
1789         bch2_trans_exit(&trans);
1790
1791         if (ret)
1792                 bch_err(c, "error %i from check_xattrs()", ret);
1793         return ret;
1794 }
1795
1796 static int check_root_trans(struct btree_trans *trans)
1797 {
1798         struct bch_fs *c = trans->c;
1799         struct bch_inode_unpacked root_inode;
1800         u32 snapshot;
1801         u64 inum;
1802         int ret;
1803
1804         ret = __subvol_lookup(trans, BCACHEFS_ROOT_SUBVOL, &snapshot, &inum);
1805         if (ret && ret != -ENOENT)
1806                 return ret;
1807
1808         if (mustfix_fsck_err_on(ret, c, "root subvol missing")) {
1809                 struct bkey_i_subvolume root_subvol;
1810
1811                 snapshot        = U32_MAX;
1812                 inum            = BCACHEFS_ROOT_INO;
1813
1814                 bkey_subvolume_init(&root_subvol.k_i);
1815                 root_subvol.k.p.offset = BCACHEFS_ROOT_SUBVOL;
1816                 root_subvol.v.flags     = 0;
1817                 root_subvol.v.snapshot  = cpu_to_le32(snapshot);
1818                 root_subvol.v.inode     = cpu_to_le64(inum);
1819                 ret = commit_do(trans, NULL, NULL,
1820                                       BTREE_INSERT_NOFAIL|
1821                                       BTREE_INSERT_LAZY_RW,
1822                         __bch2_btree_insert(trans, BTREE_ID_subvolumes, &root_subvol.k_i));
1823                 if (ret) {
1824                         bch_err(c, "error writing root subvol: %i", ret);
1825                         goto err;
1826                 }
1827
1828         }
1829
1830         ret = __lookup_inode(trans, BCACHEFS_ROOT_INO, &root_inode, &snapshot);
1831         if (ret && ret != -ENOENT)
1832                 return ret;
1833
1834         if (mustfix_fsck_err_on(ret, c, "root directory missing") ||
1835             mustfix_fsck_err_on(!S_ISDIR(root_inode.bi_mode), c,
1836                                 "root inode not a directory")) {
1837                 bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755,
1838                                 0, NULL);
1839                 root_inode.bi_inum = inum;
1840
1841                 ret = __write_inode(trans, &root_inode, snapshot);
1842                 if (ret)
1843                         bch_err(c, "error writing root inode: %i", ret);
1844         }
1845 err:
1846 fsck_err:
1847         return ret;
1848 }
1849
1850 /* Get root directory, create if it doesn't exist: */
1851 noinline_for_stack
1852 static int check_root(struct bch_fs *c)
1853 {
1854         bch_verbose(c, "checking root directory");
1855
1856         return bch2_trans_do(c, NULL, NULL,
1857                              BTREE_INSERT_NOFAIL|
1858                              BTREE_INSERT_LAZY_RW,
1859                 check_root_trans(&trans));
1860 }
1861
1862 struct pathbuf_entry {
1863         u64     inum;
1864         u32     snapshot;
1865 };
1866
1867 typedef DARRAY(struct pathbuf_entry) pathbuf;
1868
1869 static bool path_is_dup(pathbuf *p, u64 inum, u32 snapshot)
1870 {
1871         struct pathbuf_entry *i;
1872
1873         darray_for_each(*p, i)
1874                 if (i->inum     == inum &&
1875                     i->snapshot == snapshot)
1876                         return true;
1877
1878         return false;
1879 }
1880
1881 static int path_down(struct bch_fs *c, pathbuf *p,
1882                      u64 inum, u32 snapshot)
1883 {
1884         int ret = darray_push(p, ((struct pathbuf_entry) {
1885                 .inum           = inum,
1886                 .snapshot       = snapshot,
1887         }));
1888
1889         if (ret)
1890                 bch_err(c, "fsck: error allocating memory for pathbuf, size %zu",
1891                         p->size);
1892         return ret;
1893 }
1894
1895 /*
1896  * Check that a given inode is reachable from the root:
1897  *
1898  * XXX: we should also be verifying that inodes are in the right subvolumes
1899  */
1900 static int check_path(struct btree_trans *trans,
1901                       pathbuf *p,
1902                       struct bch_inode_unpacked *inode,
1903                       u32 snapshot)
1904 {
1905         struct bch_fs *c = trans->c;
1906         int ret = 0;
1907
1908         snapshot = bch2_snapshot_equiv(c, snapshot);
1909         p->nr = 0;
1910
1911         while (!(inode->bi_inum == BCACHEFS_ROOT_INO &&
1912                  inode->bi_subvol == BCACHEFS_ROOT_SUBVOL)) {
1913                 struct btree_iter dirent_iter;
1914                 struct bkey_s_c_dirent d;
1915                 u32 parent_snapshot = snapshot;
1916
1917                 if (inode->bi_subvol) {
1918                         u64 inum;
1919
1920                         ret = subvol_lookup(trans, inode->bi_parent_subvol,
1921                                             &parent_snapshot, &inum);
1922                         if (ret)
1923                                 break;
1924                 }
1925
1926                 ret = lockrestart_do(trans,
1927                         PTR_ERR_OR_ZERO((d = dirent_get_by_pos(trans, &dirent_iter,
1928                                           SPOS(inode->bi_dir, inode->bi_dir_offset,
1929                                                parent_snapshot))).k));
1930                 if (ret && ret != -ENOENT)
1931                         break;
1932
1933                 if (!ret && !dirent_points_to_inode(d, inode)) {
1934                         bch2_trans_iter_exit(trans, &dirent_iter);
1935                         ret = -ENOENT;
1936                 }
1937
1938                 if (ret == -ENOENT) {
1939                         if (fsck_err(c,  "unreachable inode %llu:%u, type %s nlink %u backptr %llu:%llu",
1940                                      inode->bi_inum, snapshot,
1941                                      bch2_d_type_str(inode_d_type(inode)),
1942                                      inode->bi_nlink,
1943                                      inode->bi_dir,
1944                                      inode->bi_dir_offset))
1945                                 ret = reattach_inode(trans, inode, snapshot);
1946                         break;
1947                 }
1948
1949                 bch2_trans_iter_exit(trans, &dirent_iter);
1950
1951                 if (!S_ISDIR(inode->bi_mode))
1952                         break;
1953
1954                 ret = path_down(c, p, inode->bi_inum, snapshot);
1955                 if (ret) {
1956                         bch_err(c, "memory allocation failure");
1957                         return ret;
1958                 }
1959
1960                 snapshot = parent_snapshot;
1961
1962                 ret = lookup_inode(trans, inode->bi_dir, inode, &snapshot);
1963                 if (ret) {
1964                         /* Should have been caught in dirents pass */
1965                         bch_err(c, "error looking up parent directory: %i", ret);
1966                         break;
1967                 }
1968
1969                 if (path_is_dup(p, inode->bi_inum, snapshot)) {
1970                         struct pathbuf_entry *i;
1971
1972                         /* XXX print path */
1973                         bch_err(c, "directory structure loop");
1974
1975                         darray_for_each(*p, i)
1976                                 pr_err("%llu:%u", i->inum, i->snapshot);
1977                         pr_err("%llu:%u", inode->bi_inum, snapshot);
1978
1979                         if (!fsck_err(c, "directory structure loop"))
1980                                 return 0;
1981
1982                         ret = commit_do(trans, NULL, NULL,
1983                                               BTREE_INSERT_NOFAIL|
1984                                               BTREE_INSERT_LAZY_RW,
1985                                         remove_backpointer(trans, inode));
1986                         if (ret) {
1987                                 bch_err(c, "error removing dirent: %i", ret);
1988                                 break;
1989                         }
1990
1991                         ret = reattach_inode(trans, inode, snapshot);
1992                 }
1993         }
1994 fsck_err:
1995         if (ret)
1996                 bch_err(c, "%s: err %i", __func__, ret);
1997         return ret;
1998 }
1999
2000 /*
2001  * Check for unreachable inodes, as well as loops in the directory structure:
2002  * After check_dirents(), if an inode backpointer doesn't exist that means it's
2003  * unreachable:
2004  */
2005 noinline_for_stack
2006 static int check_directory_structure(struct bch_fs *c)
2007 {
2008         struct btree_trans trans;
2009         struct btree_iter iter;
2010         struct bkey_s_c k;
2011         struct bch_inode_unpacked u;
2012         pathbuf path = { 0, };
2013         int ret;
2014
2015         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2016
2017         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN,
2018                            BTREE_ITER_INTENT|
2019                            BTREE_ITER_PREFETCH|
2020                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2021                 if (!bkey_is_inode(k.k))
2022                         continue;
2023
2024                 ret = bch2_inode_unpack(k, &u);
2025                 if (ret) {
2026                         /* Should have been caught earlier in fsck: */
2027                         bch_err(c, "error unpacking inode %llu: %i", k.k->p.offset, ret);
2028                         break;
2029                 }
2030
2031                 if (u.bi_flags & BCH_INODE_UNLINKED)
2032                         continue;
2033
2034                 ret = check_path(&trans, &path, &u, iter.pos.snapshot);
2035                 if (ret)
2036                         break;
2037         }
2038         bch2_trans_iter_exit(&trans, &iter);
2039
2040         BUG_ON(ret == -EINTR);
2041
2042         darray_exit(&path);
2043
2044         bch2_trans_exit(&trans);
2045         return ret;
2046 }
2047
2048 struct nlink_table {
2049         size_t          nr;
2050         size_t          size;
2051
2052         struct nlink {
2053                 u64     inum;
2054                 u32     snapshot;
2055                 u32     count;
2056         }               *d;
2057 };
2058
2059 static int add_nlink(struct bch_fs *c, struct nlink_table *t,
2060                      u64 inum, u32 snapshot)
2061 {
2062         if (t->nr == t->size) {
2063                 size_t new_size = max_t(size_t, 128UL, t->size * 2);
2064                 void *d = kvmalloc(new_size * sizeof(t->d[0]), GFP_KERNEL);
2065                 if (!d) {
2066                         bch_err(c, "fsck: error allocating memory for nlink_table, size %zu",
2067                                 new_size);
2068                         return -ENOMEM;
2069                 }
2070
2071                 if (t->d)
2072                         memcpy(d, t->d, t->size * sizeof(t->d[0]));
2073                 kvfree(t->d);
2074
2075                 t->d = d;
2076                 t->size = new_size;
2077         }
2078
2079
2080         t->d[t->nr++] = (struct nlink) {
2081                 .inum           = inum,
2082                 .snapshot       = snapshot,
2083         };
2084
2085         return 0;
2086 }
2087
2088 static int nlink_cmp(const void *_l, const void *_r)
2089 {
2090         const struct nlink *l = _l;
2091         const struct nlink *r = _r;
2092
2093         return cmp_int(l->inum, r->inum) ?: cmp_int(l->snapshot, r->snapshot);
2094 }
2095
2096 static void inc_link(struct bch_fs *c, struct snapshots_seen *s,
2097                      struct nlink_table *links,
2098                      u64 range_start, u64 range_end, u64 inum, u32 snapshot)
2099 {
2100         struct nlink *link, key = {
2101                 .inum = inum, .snapshot = U32_MAX,
2102         };
2103
2104         if (inum < range_start || inum >= range_end)
2105                 return;
2106
2107         link = __inline_bsearch(&key, links->d, links->nr,
2108                                 sizeof(links->d[0]), nlink_cmp);
2109         if (!link)
2110                 return;
2111
2112         while (link > links->d && link[0].inum == link[-1].inum)
2113                 --link;
2114
2115         for (; link < links->d + links->nr && link->inum == inum; link++)
2116                 if (ref_visible(c, s, snapshot, link->snapshot)) {
2117                         link->count++;
2118                         if (link->snapshot >= snapshot)
2119                                 break;
2120                 }
2121 }
2122
2123 noinline_for_stack
2124 static int check_nlinks_find_hardlinks(struct bch_fs *c,
2125                                        struct nlink_table *t,
2126                                        u64 start, u64 *end)
2127 {
2128         struct btree_trans trans;
2129         struct btree_iter iter;
2130         struct bkey_s_c k;
2131         struct bch_inode_unpacked u;
2132         int ret = 0;
2133
2134         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2135
2136         for_each_btree_key(&trans, iter, BTREE_ID_inodes,
2137                            POS(0, start),
2138                            BTREE_ITER_INTENT|
2139                            BTREE_ITER_PREFETCH|
2140                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2141                 if (!bkey_is_inode(k.k))
2142                         continue;
2143
2144                 /* Should never fail, checked by bch2_inode_invalid: */
2145                 BUG_ON(bch2_inode_unpack(k, &u));
2146
2147                 /*
2148                  * Backpointer and directory structure checks are sufficient for
2149                  * directories, since they can't have hardlinks:
2150                  */
2151                 if (S_ISDIR(le16_to_cpu(u.bi_mode)))
2152                         continue;
2153
2154                 if (!u.bi_nlink)
2155                         continue;
2156
2157                 ret = add_nlink(c, t, k.k->p.offset, k.k->p.snapshot);
2158                 if (ret) {
2159                         *end = k.k->p.offset;
2160                         ret = 0;
2161                         break;
2162                 }
2163
2164         }
2165         bch2_trans_iter_exit(&trans, &iter);
2166         bch2_trans_exit(&trans);
2167
2168         if (ret)
2169                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2170
2171         return ret;
2172 }
2173
2174 noinline_for_stack
2175 static int check_nlinks_walk_dirents(struct bch_fs *c, struct nlink_table *links,
2176                                      u64 range_start, u64 range_end)
2177 {
2178         struct btree_trans trans;
2179         struct snapshots_seen s;
2180         struct btree_iter iter;
2181         struct bkey_s_c k;
2182         struct bkey_s_c_dirent d;
2183         int ret;
2184
2185         snapshots_seen_init(&s);
2186
2187         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2188
2189         for_each_btree_key(&trans, iter, BTREE_ID_dirents, POS_MIN,
2190                            BTREE_ITER_INTENT|
2191                            BTREE_ITER_PREFETCH|
2192                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2193                 ret = snapshots_seen_update(c, &s, iter.btree_id, k.k->p);
2194                 if (ret)
2195                         break;
2196
2197                 switch (k.k->type) {
2198                 case KEY_TYPE_dirent:
2199                         d = bkey_s_c_to_dirent(k);
2200
2201                         if (d.v->d_type != DT_DIR &&
2202                             d.v->d_type != DT_SUBVOL)
2203                                 inc_link(c, &s, links, range_start, range_end,
2204                                          le64_to_cpu(d.v->d_inum),
2205                                          d.k->p.snapshot);
2206                         break;
2207                 }
2208         }
2209         bch2_trans_iter_exit(&trans, &iter);
2210
2211         if (ret)
2212                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
2213
2214         bch2_trans_exit(&trans);
2215         snapshots_seen_exit(&s);
2216         return ret;
2217 }
2218
2219 noinline_for_stack
2220 static int check_nlinks_update_hardlinks(struct bch_fs *c,
2221                                struct nlink_table *links,
2222                                u64 range_start, u64 range_end)
2223 {
2224         struct btree_trans trans;
2225         struct btree_iter iter;
2226         struct bkey_s_c k;
2227         struct bch_inode_unpacked u;
2228         struct nlink *link = links->d;
2229         int ret = 0;
2230
2231         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2232
2233         for_each_btree_key(&trans, iter, BTREE_ID_inodes,
2234                            POS(0, range_start),
2235                            BTREE_ITER_INTENT|
2236                            BTREE_ITER_PREFETCH|
2237                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2238                 if (k.k->p.offset >= range_end)
2239                         break;
2240
2241                 if (!bkey_is_inode(k.k))
2242                         continue;
2243
2244                 BUG_ON(bch2_inode_unpack(k, &u));
2245
2246                 if (S_ISDIR(le16_to_cpu(u.bi_mode)))
2247                         continue;
2248
2249                 if (!u.bi_nlink)
2250                         continue;
2251
2252                 while ((cmp_int(link->inum, k.k->p.offset) ?:
2253                         cmp_int(link->snapshot, k.k->p.snapshot)) < 0) {
2254                         link++;
2255                         BUG_ON(link >= links->d + links->nr);
2256                 }
2257
2258                 if (fsck_err_on(bch2_inode_nlink_get(&u) != link->count, c,
2259                                 "inode %llu type %s has wrong i_nlink (%u, should be %u)",
2260                                 u.bi_inum, bch2_d_types[mode_to_type(u.bi_mode)],
2261                                 bch2_inode_nlink_get(&u), link->count)) {
2262                         bch2_inode_nlink_set(&u, link->count);
2263
2264                         ret = write_inode(&trans, &u, k.k->p.snapshot);
2265                         if (ret)
2266                                 bch_err(c, "error in fsck: error %i updating inode", ret);
2267                 }
2268         }
2269 fsck_err:
2270         bch2_trans_iter_exit(&trans, &iter);
2271         bch2_trans_exit(&trans);
2272
2273         if (ret)
2274                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2275
2276         return ret;
2277 }
2278
2279 noinline_for_stack
2280 static int check_nlinks(struct bch_fs *c)
2281 {
2282         struct nlink_table links = { 0 };
2283         u64 this_iter_range_start, next_iter_range_start = 0;
2284         int ret = 0;
2285
2286         bch_verbose(c, "checking inode nlinks");
2287
2288         do {
2289                 this_iter_range_start = next_iter_range_start;
2290                 next_iter_range_start = U64_MAX;
2291
2292                 ret = check_nlinks_find_hardlinks(c, &links,
2293                                                   this_iter_range_start,
2294                                                   &next_iter_range_start);
2295
2296                 ret = check_nlinks_walk_dirents(c, &links,
2297                                           this_iter_range_start,
2298                                           next_iter_range_start);
2299                 if (ret)
2300                         break;
2301
2302                 ret = check_nlinks_update_hardlinks(c, &links,
2303                                          this_iter_range_start,
2304                                          next_iter_range_start);
2305                 if (ret)
2306                         break;
2307
2308                 links.nr = 0;
2309         } while (next_iter_range_start != U64_MAX);
2310
2311         kvfree(links.d);
2312
2313         return ret;
2314 }
2315
2316 static int fix_reflink_p_key(struct btree_trans *trans, struct btree_iter *iter)
2317 {
2318         struct bkey_s_c k;
2319         struct bkey_s_c_reflink_p p;
2320         struct bkey_i_reflink_p *u;
2321         int ret;
2322
2323         k = bch2_btree_iter_peek(iter);
2324         if (!k.k)
2325                 return 0;
2326
2327         ret = bkey_err(k);
2328         if (ret)
2329                 return ret;
2330
2331         if (k.k->type != KEY_TYPE_reflink_p)
2332                 return 0;
2333
2334         p = bkey_s_c_to_reflink_p(k);
2335
2336         if (!p.v->front_pad && !p.v->back_pad)
2337                 return 0;
2338
2339         u = bch2_trans_kmalloc(trans, sizeof(*u));
2340         ret = PTR_ERR_OR_ZERO(u);
2341         if (ret)
2342                 return ret;
2343
2344         bkey_reassemble(&u->k_i, k);
2345         u->v.front_pad  = 0;
2346         u->v.back_pad   = 0;
2347
2348         return bch2_trans_update(trans, iter, &u->k_i, BTREE_TRIGGER_NORUN);
2349 }
2350
2351 noinline_for_stack
2352 static int fix_reflink_p(struct bch_fs *c)
2353 {
2354         struct btree_trans trans;
2355         struct btree_iter iter;
2356         struct bkey_s_c k;
2357         int ret;
2358
2359         if (c->sb.version >= bcachefs_metadata_version_reflink_p_fix)
2360                 return 0;
2361
2362         bch_verbose(c, "fixing reflink_p keys");
2363
2364         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2365
2366         for_each_btree_key(&trans, iter, BTREE_ID_extents, POS_MIN,
2367                            BTREE_ITER_INTENT|
2368                            BTREE_ITER_PREFETCH|
2369                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2370                 if (k.k->type == KEY_TYPE_reflink_p) {
2371                         ret = commit_do(&trans, NULL, NULL,
2372                                               BTREE_INSERT_NOFAIL|
2373                                               BTREE_INSERT_LAZY_RW,
2374                                               fix_reflink_p_key(&trans, &iter));
2375                         if (ret)
2376                                 break;
2377                 }
2378         }
2379         bch2_trans_iter_exit(&trans, &iter);
2380
2381         bch2_trans_exit(&trans);
2382         return ret;
2383 }
2384
2385 /*
2386  * Checks for inconsistencies that shouldn't happen, unless we have a bug.
2387  * Doesn't fix them yet, mainly because they haven't yet been observed:
2388  */
2389 int bch2_fsck_full(struct bch_fs *c)
2390 {
2391         return  bch2_fs_check_snapshots(c) ?:
2392                 bch2_fs_check_subvols(c) ?:
2393                 bch2_delete_dead_snapshots(c) ?:
2394                 check_inodes(c, true) ?:
2395                 check_extents(c) ?:
2396                 check_dirents(c) ?:
2397                 check_xattrs(c) ?:
2398                 check_root(c) ?:
2399                 check_directory_structure(c) ?:
2400                 check_nlinks(c) ?:
2401                 fix_reflink_p(c);
2402 }
2403
2404 int bch2_fsck_walk_inodes_only(struct bch_fs *c)
2405 {
2406         return  bch2_fs_check_snapshots(c) ?:
2407                 bch2_fs_check_subvols(c) ?:
2408                 bch2_delete_dead_snapshots(c) ?:
2409                 check_inodes(c, false);
2410 }