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