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