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