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