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