]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
Update bcachefs sources to 07c2895cb3 bcachefs: Add a valgrind memcheck hint
[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         int ret;
1054
1055         bch2_trans_iter_init(trans, &iter, BTREE_ID_dirents,
1056                         SPOS(inode->bi_dir, inode->bi_dir_offset, snapshot), 0);
1057         k = bch2_btree_iter_peek_slot(&iter);
1058         ret = bkey_err(k);
1059         if (ret)
1060                 goto out;
1061         if (k.k->type != KEY_TYPE_dirent)
1062                 goto out;
1063
1064         ret = le64_to_cpu(bkey_s_c_to_dirent(k).v->d_inum) == inode->bi_inum;
1065 out:
1066         bch2_trans_iter_exit(trans, &iter);
1067         return ret;
1068 }
1069
1070 static bool inode_backpointer_matches(struct bkey_s_c_dirent d,
1071                                       struct bch_inode_unpacked *inode)
1072 {
1073         return d.k->p.inode == inode->bi_dir &&
1074                 d.k->p.offset == inode->bi_dir_offset;
1075 }
1076
1077 static int check_i_sectors(struct btree_trans *trans, struct inode_walker *w)
1078 {
1079         struct bch_fs *c = trans->c;
1080         struct inode_walker_entry *i;
1081         int ret = 0, ret2 = 0;
1082         s64 count2;
1083
1084         for (i = w->d; i < w->d + w->nr; i++) {
1085                 if (i->inode.bi_sectors == i->count)
1086                         continue;
1087
1088                 count2 = lockrestart_do(trans,
1089                         bch2_count_inode_sectors(trans, w->cur_inum, i->snapshot));
1090
1091                 if (i->count != count2) {
1092                         bch_err(c, "fsck counted i_sectors wrong: got %llu should be %llu",
1093                                 i->count, count2);
1094                         i->count = count2;
1095                         if (i->inode.bi_sectors == i->count)
1096                                 continue;
1097                 }
1098
1099                 if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY), c,
1100                             "inode %llu:%u has incorrect i_sectors: got %llu, should be %llu",
1101                             w->cur_inum, i->snapshot,
1102                             i->inode.bi_sectors, i->count) == FSCK_ERR_IGNORE)
1103                         continue;
1104
1105                 i->inode.bi_sectors = i->count;
1106                 ret = write_inode(trans, &i->inode, i->snapshot);
1107                 if (ret)
1108                         break;
1109                 ret2 = -EINTR;
1110         }
1111 fsck_err:
1112         return ret ?: ret2;
1113 }
1114
1115 static int check_extent(struct btree_trans *trans, struct btree_iter *iter,
1116                         struct inode_walker *inode,
1117                         struct snapshots_seen *s)
1118 {
1119         struct bch_fs *c = trans->c;
1120         struct bkey_s_c k;
1121         struct inode_walker_entry *i;
1122         char buf[200];
1123         int ret = 0;
1124
1125         k = bch2_btree_iter_peek(iter);
1126         if (!k.k)
1127                 return 0;
1128
1129         ret = bkey_err(k);
1130         if (ret)
1131                 return ret;
1132
1133         ret = check_key_has_snapshot(trans, iter, k);
1134         if (ret)
1135                 return ret;
1136
1137         ret = snapshots_seen_update(c, s, k.k->p);
1138         if (ret)
1139                 return ret;
1140
1141         if (k.k->type == KEY_TYPE_whiteout)
1142                 return 0;
1143
1144         if (inode->cur_inum != k.k->p.inode) {
1145                 ret = check_i_sectors(trans, inode);
1146                 if (ret)
1147                         return ret;
1148         }
1149 #if 0
1150         if (bkey_cmp(prev.k->k.p, bkey_start_pos(k.k)) > 0) {
1151                 char buf1[200];
1152                 char buf2[200];
1153
1154                 bch2_bkey_val_to_text(&PBUF(buf1), c, bkey_i_to_s_c(prev.k));
1155                 bch2_bkey_val_to_text(&PBUF(buf2), c, k);
1156
1157                 if (fsck_err(c, "overlapping extents:\n%s\n%s", buf1, buf2))
1158                         return fix_overlapping_extent(trans, k, prev.k->k.p) ?: -EINTR;
1159         }
1160 #endif
1161         ret = __walk_inode(trans, inode, k.k->p);
1162         if (ret < 0)
1163                 return ret;
1164
1165         if (fsck_err_on(ret == INT_MAX, c,
1166                         "extent in missing inode:\n  %s",
1167                         (bch2_bkey_val_to_text(&PBUF(buf), c, k), buf)))
1168                 return __bch2_trans_do(trans, NULL, NULL, BTREE_INSERT_LAZY_RW,
1169                         bch2_btree_delete_at(trans, iter,
1170                                              BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE));
1171
1172         if (ret == INT_MAX)
1173                 return 0;
1174
1175         i = inode->d + ret;
1176         ret = 0;
1177
1178         if (fsck_err_on(!S_ISREG(i->inode.bi_mode) &&
1179                         !S_ISLNK(i->inode.bi_mode), c,
1180                         "extent in non regular inode mode %o:\n  %s",
1181                         i->inode.bi_mode,
1182                         (bch2_bkey_val_to_text(&PBUF(buf), c, k), buf)))
1183                 return __bch2_trans_do(trans, NULL, NULL, BTREE_INSERT_LAZY_RW,
1184                          bch2_btree_delete_at(trans, iter,
1185                                               BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE));
1186
1187         if (!bch2_snapshot_internal_node(c, k.k->p.snapshot)) {
1188                 for_each_visible_inode(c, s, inode, k.k->p.snapshot, i) {
1189                         if (fsck_err_on(!(i->inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
1190                                         k.k->type != KEY_TYPE_reservation &&
1191                                         k.k->p.offset > round_up(i->inode.bi_size, block_bytes(c)) >> 9, c,
1192                                         "extent type %u offset %llu past end of inode %llu, i_size %llu",
1193                                         k.k->type, k.k->p.offset, k.k->p.inode, i->inode.bi_size)) {
1194                                 bch2_fs_lazy_rw(c);
1195                                 return bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
1196                                                 SPOS(k.k->p.inode, round_up(i->inode.bi_size, block_bytes(c)) >> 9,
1197                                                      k.k->p.snapshot),
1198                                                 POS(k.k->p.inode, U64_MAX),
1199                                                 0, NULL) ?: -EINTR;
1200                         }
1201                 }
1202         }
1203
1204         if (bkey_extent_is_allocation(k.k))
1205                 for_each_visible_inode(c, s, inode, k.k->p.snapshot, i)
1206                         i->count += k.k->size;
1207 #if 0
1208         bch2_bkey_buf_reassemble(&prev, c, k);
1209 #endif
1210
1211 fsck_err:
1212         return ret;
1213 }
1214
1215 /*
1216  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
1217  * that i_size an i_sectors are consistent
1218  */
1219 noinline_for_stack
1220 static int check_extents(struct bch_fs *c)
1221 {
1222         struct inode_walker w = inode_walker_init();
1223         struct snapshots_seen s;
1224         struct btree_trans trans;
1225         struct btree_iter iter;
1226         int ret = 0;
1227
1228 #if 0
1229         struct bkey_buf prev;
1230         bch2_bkey_buf_init(&prev);
1231         prev.k->k = KEY(0, 0, 0);
1232 #endif
1233         snapshots_seen_init(&s);
1234         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1235
1236         bch_verbose(c, "checking extents");
1237
1238         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
1239                              POS(BCACHEFS_ROOT_INO, 0),
1240                              BTREE_ITER_INTENT|
1241                              BTREE_ITER_PREFETCH|
1242                              BTREE_ITER_ALL_SNAPSHOTS);
1243
1244         do {
1245                 ret = lockrestart_do(&trans,
1246                         check_extent(&trans, &iter, &w, &s));
1247                 if (ret)
1248                         break;
1249         } while (bch2_btree_iter_advance(&iter));
1250         bch2_trans_iter_exit(&trans, &iter);
1251 #if 0
1252         bch2_bkey_buf_exit(&prev, c);
1253 #endif
1254         inode_walker_exit(&w);
1255         bch2_trans_exit(&trans);
1256         snapshots_seen_exit(&s);
1257
1258         return ret;
1259 }
1260
1261 static int check_subdir_count(struct btree_trans *trans, struct inode_walker *w)
1262 {
1263         struct bch_fs *c = trans->c;
1264         struct inode_walker_entry *i;
1265         int ret = 0, ret2 = 0;
1266         s64 count2;
1267
1268         for (i = w->d; i < w->d + w->nr; i++) {
1269                 if (i->inode.bi_nlink == i->count)
1270                         continue;
1271
1272                 count2 = lockrestart_do(trans,
1273                                 bch2_count_subdirs(trans, w->cur_inum, i->snapshot));
1274
1275                 if (i->count != count2) {
1276                         bch_err(c, "fsck counted subdirectories wrong: got %llu should be %llu",
1277                                 i->count, count2);
1278                         i->count = count2;
1279                         if (i->inode.bi_nlink == i->count)
1280                                 continue;
1281                 }
1282
1283                 if (fsck_err_on(i->inode.bi_nlink != i->count, c,
1284                                 "directory %llu:%u with wrong i_nlink: got %u, should be %llu",
1285                                 w->cur_inum, i->snapshot, i->inode.bi_nlink, i->count)) {
1286                         i->inode.bi_nlink = i->count;
1287                         ret = write_inode(trans, &i->inode, i->snapshot);
1288                         if (ret)
1289                                 break;
1290                         ret2 = -EINTR;
1291                 }
1292         }
1293 fsck_err:
1294         return ret ?: ret2;
1295 }
1296
1297 static int check_dirent_target(struct btree_trans *trans,
1298                                struct btree_iter *iter,
1299                                struct bkey_s_c_dirent d,
1300                                struct bch_inode_unpacked *target,
1301                                u32 target_snapshot)
1302 {
1303         struct bch_fs *c = trans->c;
1304         bool backpointer_exists = true;
1305         char buf[200];
1306         int ret = 0;
1307
1308         if (!target->bi_dir &&
1309             !target->bi_dir_offset) {
1310                 target->bi_dir          = d.k->p.inode;
1311                 target->bi_dir_offset   = d.k->p.offset;
1312
1313                 ret = write_inode(trans, target, target_snapshot);
1314                 if (ret)
1315                         goto err;
1316         }
1317
1318         if (!inode_backpointer_matches(d, target)) {
1319                 ret = inode_backpointer_exists(trans, target, d.k->p.snapshot);
1320                 if (ret < 0)
1321                         goto err;
1322
1323                 backpointer_exists = ret;
1324                 ret = 0;
1325
1326                 if (fsck_err_on(S_ISDIR(target->bi_mode) &&
1327                                 backpointer_exists, c,
1328                                 "directory %llu with multiple links",
1329                                 target->bi_inum)) {
1330                         ret = remove_dirent(trans, d.k->p);
1331                         if (ret)
1332                                 goto err;
1333                         return 0;
1334                 }
1335
1336                 if (fsck_err_on(backpointer_exists &&
1337                                 !target->bi_nlink, c,
1338                                 "inode %llu has multiple links but i_nlink 0",
1339                                 target->bi_inum)) {
1340                         target->bi_nlink++;
1341                         target->bi_flags &= ~BCH_INODE_UNLINKED;
1342
1343                         ret = write_inode(trans, target, target_snapshot);
1344                         if (ret)
1345                                 goto err;
1346                 }
1347
1348                 if (fsck_err_on(!backpointer_exists, c,
1349                                 "inode %llu has wrong backpointer:\n"
1350                                 "got       %llu:%llu\n"
1351                                 "should be %llu:%llu",
1352                                 target->bi_inum,
1353                                 target->bi_dir,
1354                                 target->bi_dir_offset,
1355                                 d.k->p.inode,
1356                                 d.k->p.offset)) {
1357                         target->bi_dir          = d.k->p.inode;
1358                         target->bi_dir_offset   = d.k->p.offset;
1359
1360                         ret = write_inode(trans, target, target_snapshot);
1361                         if (ret)
1362                                 goto err;
1363                 }
1364         }
1365
1366         if (fsck_err_on(vfs_d_type(d.v->d_type) != mode_to_type(target->bi_mode), c,
1367                         "incorrect d_type: should be %u:\n%s",
1368                         mode_to_type(target->bi_mode),
1369                         (bch2_bkey_val_to_text(&PBUF(buf), c, d.s_c), buf))) {
1370                 struct bkey_i_dirent *n;
1371
1372                 n = kmalloc(bkey_bytes(d.k), GFP_KERNEL);
1373                 if (!n) {
1374                         ret = -ENOMEM;
1375                         goto err;
1376                 }
1377
1378                 bkey_reassemble(&n->k_i, d.s_c);
1379                 n->v.d_type = mode_to_type(target->bi_mode);
1380
1381                 ret = __bch2_trans_do(trans, NULL, NULL,
1382                                       BTREE_INSERT_NOFAIL|
1383                                       BTREE_INSERT_LAZY_RW,
1384                         bch2_trans_update(trans, iter, &n->k_i, 0));
1385                 kfree(n);
1386                 if (ret)
1387                         goto err;
1388         }
1389 err:
1390 fsck_err:
1391         return ret;
1392 }
1393
1394 static int check_dirent(struct btree_trans *trans, struct btree_iter *iter,
1395                         struct bch_hash_info *hash_info,
1396                         struct inode_walker *dir,
1397                         struct inode_walker *target,
1398                         struct snapshots_seen *s)
1399 {
1400         struct bch_fs *c = trans->c;
1401         struct bkey_s_c k;
1402         struct bkey_s_c_dirent d;
1403         struct inode_walker_entry *i;
1404         u32 target_snapshot;
1405         u32 target_subvol;
1406         u64 target_inum;
1407         char buf[200];
1408         int ret;
1409
1410         k = bch2_btree_iter_peek(iter);
1411         if (!k.k)
1412                 return 0;
1413
1414         ret = bkey_err(k);
1415         if (ret)
1416                 return ret;
1417
1418         ret = check_key_has_snapshot(trans, iter, k);
1419         if (ret)
1420                 return ret;
1421
1422         ret = snapshots_seen_update(c, s, k.k->p);
1423         if (ret)
1424                 return ret;
1425
1426         if (k.k->type == KEY_TYPE_whiteout)
1427                 return 0;
1428
1429         if (dir->cur_inum != k.k->p.inode) {
1430                 ret = check_subdir_count(trans, dir);
1431                 if (ret)
1432                         return ret;
1433         }
1434
1435         ret = __walk_inode(trans, dir, k.k->p);
1436         if (ret < 0)
1437                 return ret;
1438
1439         if (fsck_err_on(ret == INT_MAX, c,
1440                         "dirent in nonexisting directory:\n%s",
1441                         (bch2_bkey_val_to_text(&PBUF(buf), c, k), buf)))
1442                 return __bch2_trans_do(trans, NULL, NULL, BTREE_INSERT_LAZY_RW,
1443                                 bch2_btree_delete_at(trans, iter,
1444                                                      BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE));
1445
1446         if (ret == INT_MAX)
1447                 return 0;
1448
1449         i = dir->d + ret;
1450         ret = 0;
1451
1452         if (fsck_err_on(!S_ISDIR(i->inode.bi_mode), c,
1453                         "dirent in non directory inode type %u:\n%s",
1454                         mode_to_type(i->inode.bi_mode),
1455                         (bch2_bkey_val_to_text(&PBUF(buf), c, k), buf)))
1456                 return __bch2_trans_do(trans, NULL, NULL, 0,
1457                                 bch2_btree_delete_at(trans, iter, 0));
1458
1459         if (dir->first_this_inode)
1460                 *hash_info = bch2_hash_info_init(c, &dir->d[0].inode);
1461
1462         ret = hash_check_key(trans, bch2_dirent_hash_desc,
1463                              hash_info, iter, k);
1464         if (ret < 0)
1465                 return ret;
1466         if (ret) /* dirent has been deleted */
1467                 return 0;
1468
1469         if (k.k->type != KEY_TYPE_dirent)
1470                 return 0;
1471
1472         d = bkey_s_c_to_dirent(k);
1473
1474         ret = __bch2_dirent_read_target(trans, d,
1475                                         &target_subvol,
1476                                         &target_snapshot,
1477                                         &target_inum,
1478                                         true);
1479         if (ret && ret != -ENOENT)
1480                 return ret;
1481
1482         if (fsck_err_on(ret, c,
1483                         "dirent points to missing subvolume %llu",
1484                         le64_to_cpu(d.v->d_inum)))
1485                 return remove_dirent(trans, d.k->p);
1486
1487         if (target_subvol) {
1488                 struct bch_inode_unpacked subvol_root;
1489
1490                 ret = __lookup_inode(trans, target_inum,
1491                                    &subvol_root, &target_snapshot);
1492                 if (ret && ret != -ENOENT)
1493                         return ret;
1494
1495                 if (fsck_err_on(ret, c,
1496                                 "subvolume %u points to missing subvolume root %llu",
1497                                 target_subvol,
1498                                 target_inum)) {
1499                         bch_err(c, "repair not implemented yet");
1500                         return -EINVAL;
1501                 }
1502
1503                 if (fsck_err_on(subvol_root.bi_subvol != target_subvol, c,
1504                                 "subvol root %llu has wrong bi_subvol field: got %u, should be %u",
1505                                 target_inum,
1506                                 subvol_root.bi_subvol, target_subvol)) {
1507                         subvol_root.bi_subvol = target_subvol;
1508                         ret = write_inode(trans, &subvol_root, target_snapshot);
1509                         if (ret)
1510                                 return ret;
1511                 }
1512
1513                 ret = check_dirent_target(trans, iter, d, &subvol_root,
1514                                           target_snapshot);
1515                 if (ret)
1516                         return ret;
1517         } else {
1518                 ret = __get_visible_inodes(trans, target, s, target_inum);
1519                 if (ret)
1520                         return ret;
1521
1522                 if (fsck_err_on(!target->nr, c,
1523                                 "dirent points to missing inode:\n%s",
1524                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
1525                                                        k), buf))) {
1526                         ret = remove_dirent(trans, d.k->p);
1527                         if (ret)
1528                                 return ret;
1529                 }
1530
1531                 for (i = target->d; i < target->d + target->nr; i++) {
1532                         ret = check_dirent_target(trans, iter, d,
1533                                                   &i->inode, i->snapshot);
1534                         if (ret)
1535                                 return ret;
1536                 }
1537         }
1538
1539         if (d.v->d_type == DT_DIR)
1540                 for_each_visible_inode(c, s, dir, d.k->p.snapshot, i)
1541                         i->count++;
1542
1543 fsck_err:
1544         return ret;
1545 }
1546
1547 /*
1548  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
1549  * validate d_type
1550  */
1551 noinline_for_stack
1552 static int check_dirents(struct bch_fs *c)
1553 {
1554         struct inode_walker dir = inode_walker_init();
1555         struct inode_walker target = inode_walker_init();
1556         struct snapshots_seen s;
1557         struct bch_hash_info hash_info;
1558         struct btree_trans trans;
1559         struct btree_iter iter;
1560         int ret = 0;
1561
1562         bch_verbose(c, "checking dirents");
1563
1564         snapshots_seen_init(&s);
1565         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1566
1567         bch2_trans_iter_init(&trans, &iter, BTREE_ID_dirents,
1568                              POS(BCACHEFS_ROOT_INO, 0),
1569                              BTREE_ITER_INTENT|
1570                              BTREE_ITER_PREFETCH|
1571                              BTREE_ITER_ALL_SNAPSHOTS);
1572
1573         do {
1574                 ret = lockrestart_do(&trans,
1575                         check_dirent(&trans, &iter, &hash_info,
1576                                      &dir, &target, &s));
1577                 if (ret)
1578                         break;
1579         } while (bch2_btree_iter_advance(&iter));
1580         bch2_trans_iter_exit(&trans, &iter);
1581
1582         bch2_trans_exit(&trans);
1583         snapshots_seen_exit(&s);
1584         inode_walker_exit(&dir);
1585         inode_walker_exit(&target);
1586         return ret;
1587 }
1588
1589 /*
1590  * Walk xattrs: verify that they all have a corresponding inode
1591  */
1592 noinline_for_stack
1593 static int check_xattrs(struct bch_fs *c)
1594 {
1595         struct inode_walker w = inode_walker_init();
1596         struct bch_hash_info hash_info;
1597         struct btree_trans trans;
1598         struct btree_iter iter;
1599         struct bkey_s_c k;
1600         int ret = 0;
1601
1602         bch_verbose(c, "checking xattrs");
1603
1604         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1605
1606         bch2_trans_iter_init(&trans, &iter, BTREE_ID_xattrs,
1607                              POS(BCACHEFS_ROOT_INO, 0),
1608                              BTREE_ITER_INTENT|
1609                              BTREE_ITER_PREFETCH|
1610                              BTREE_ITER_ALL_SNAPSHOTS);
1611 retry:
1612         bch2_trans_begin(&trans);
1613
1614         while ((k = bch2_btree_iter_peek(&iter)).k &&
1615                !(ret = bkey_err(k))) {
1616                 ret = check_key_has_snapshot(&trans, &iter, k);
1617                 if (ret)
1618                         break;
1619
1620                 ret = walk_inode(&trans, &w, k.k->p);
1621                 if (ret < 0)
1622                         break;
1623
1624                 if (fsck_err_on(ret == INT_MAX, c,
1625                                 "xattr for missing inode %llu",
1626                                 k.k->p.inode)) {
1627                         ret = bch2_btree_delete_at(&trans, &iter, 0);
1628                         if (ret)
1629                                 break;
1630                         continue;
1631                 }
1632
1633                 if (ret == INT_MAX)
1634                         goto next;
1635                 ret = 0;
1636
1637                 if (w.first_this_inode)
1638                         hash_info = bch2_hash_info_init(c, &w.d[0].inode);
1639
1640                 ret = hash_check_key(&trans, bch2_xattr_hash_desc,
1641                                      &hash_info, &iter, k);
1642                 if (ret)
1643                         break;
1644 next:
1645                 bch2_btree_iter_advance(&iter);
1646         }
1647 fsck_err:
1648         if (ret == -EINTR)
1649                 goto retry;
1650
1651         bch2_trans_iter_exit(&trans, &iter);
1652         return bch2_trans_exit(&trans) ?: ret;
1653 }
1654
1655 /* Get root directory, create if it doesn't exist: */
1656 static int check_root(struct bch_fs *c)
1657 {
1658         struct btree_trans trans;
1659         struct bch_inode_unpacked root_inode;
1660         u32 snapshot;
1661         u64 inum;
1662         int ret;
1663
1664         bch2_trans_init(&trans, c, 0, 0);
1665
1666         bch_verbose(c, "checking root directory");
1667
1668         ret = subvol_lookup(&trans, BCACHEFS_ROOT_SUBVOL, &snapshot, &inum);
1669         if (ret && ret != -ENOENT)
1670                 return ret;
1671
1672         if (mustfix_fsck_err_on(ret, c, "root subvol missing")) {
1673                 struct bkey_i_subvolume root_subvol;
1674
1675                 snapshot        = U32_MAX;
1676                 inum            = BCACHEFS_ROOT_INO;
1677
1678                 bkey_subvolume_init(&root_subvol.k_i);
1679                 root_subvol.k.p.offset = BCACHEFS_ROOT_SUBVOL;
1680                 root_subvol.v.flags     = 0;
1681                 root_subvol.v.snapshot  = cpu_to_le32(snapshot);
1682                 root_subvol.v.inode     = cpu_to_le64(inum);
1683                 ret = __bch2_trans_do(&trans, NULL, NULL,
1684                                       BTREE_INSERT_NOFAIL|
1685                                       BTREE_INSERT_LAZY_RW,
1686                         __bch2_btree_insert(&trans, BTREE_ID_subvolumes, &root_subvol.k_i));
1687                 if (ret) {
1688                         bch_err(c, "error writing root subvol: %i", ret);
1689                         goto err;
1690                 }
1691
1692         }
1693
1694         ret = lookup_inode(&trans, BCACHEFS_ROOT_INO, &root_inode, &snapshot);
1695         if (ret && ret != -ENOENT)
1696                 return ret;
1697
1698         if (mustfix_fsck_err_on(ret, c, "root directory missing") ||
1699             mustfix_fsck_err_on(!S_ISDIR(root_inode.bi_mode), c,
1700                                 "root inode not a directory")) {
1701                 bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755,
1702                                 0, NULL);
1703                 root_inode.bi_inum = inum;
1704
1705                 ret = write_inode(&trans, &root_inode, snapshot);
1706                 if (ret)
1707                         bch_err(c, "error writing root inode: %i", ret);
1708         }
1709 err:
1710 fsck_err:
1711         bch2_trans_exit(&trans);
1712         return ret;
1713 }
1714
1715 struct pathbuf {
1716         size_t          nr;
1717         size_t          size;
1718
1719         struct pathbuf_entry {
1720                 u64     inum;
1721         }               *entries;
1722 };
1723
1724 static int path_down(struct pathbuf *p, u64 inum)
1725 {
1726         if (p->nr == p->size) {
1727                 size_t new_size = max_t(size_t, 256UL, p->size * 2);
1728                 void *n = krealloc(p->entries,
1729                                    new_size * sizeof(p->entries[0]),
1730                                    GFP_KERNEL);
1731                 if (!n) {
1732                         return -ENOMEM;
1733                 }
1734
1735                 p->entries = n;
1736                 p->size = new_size;
1737         };
1738
1739         p->entries[p->nr++] = (struct pathbuf_entry) {
1740                 .inum = inum,
1741         };
1742         return 0;
1743 }
1744
1745 static int check_path(struct btree_trans *trans,
1746                       struct pathbuf *p,
1747                       struct bch_inode_unpacked *inode,
1748                       u32 snapshot)
1749 {
1750         struct bch_fs *c = trans->c;
1751         size_t i;
1752         int ret = 0;
1753
1754         snapshot = snapshot_t(c, snapshot)->equiv;
1755         p->nr = 0;
1756
1757         while (inode->bi_inum != BCACHEFS_ROOT_INO) {
1758                 ret = lockrestart_do(trans,
1759                         inode_backpointer_exists(trans, inode, snapshot));
1760                 if (ret < 0)
1761                         break;
1762
1763                 if (!ret) {
1764                         if (fsck_err(c,  "unreachable inode %llu:%u, type %u nlink %u backptr %llu:%llu",
1765                                      inode->bi_inum, snapshot,
1766                                      mode_to_type(inode->bi_mode),
1767                                      inode->bi_nlink,
1768                                      inode->bi_dir,
1769                                      inode->bi_dir_offset))
1770                                 ret = reattach_inode(trans, inode, snapshot);
1771                         break;
1772                 }
1773                 ret = 0;
1774
1775                 if (!S_ISDIR(inode->bi_mode))
1776                         break;
1777
1778                 ret = path_down(p, inode->bi_inum);
1779                 if (ret) {
1780                         bch_err(c, "memory allocation failure");
1781                         return ret;
1782                 }
1783
1784                 for (i = 0; i < p->nr; i++) {
1785                         if (inode->bi_dir != p->entries[i].inum)
1786                                 continue;
1787
1788                         /* XXX print path */
1789                         if (!fsck_err(c, "directory structure loop"))
1790                                 return 0;
1791
1792                         ret = lockrestart_do(trans,
1793                                         remove_backpointer(trans, inode));
1794                         if (ret) {
1795                                 bch_err(c, "error removing dirent: %i", ret);
1796                                 break;
1797                         }
1798
1799                         ret = reattach_inode(trans, inode, snapshot);
1800                         break;
1801                 }
1802
1803                 ret = lookup_inode(trans, inode->bi_dir, inode, &snapshot);
1804                 if (ret) {
1805                         /* Should have been caught in dirents pass */
1806                         bch_err(c, "error looking up parent directory: %i", ret);
1807                         break;
1808                 }
1809         }
1810 fsck_err:
1811         if (ret)
1812                 bch_err(c, "%s: err %i", __func__, ret);
1813         return ret;
1814 }
1815
1816 /*
1817  * Check for unreachable inodes, as well as loops in the directory structure:
1818  * After check_dirents(), if an inode backpointer doesn't exist that means it's
1819  * unreachable:
1820  */
1821 static int check_directory_structure(struct bch_fs *c)
1822 {
1823         struct btree_trans trans;
1824         struct btree_iter iter;
1825         struct bkey_s_c k;
1826         struct bch_inode_unpacked u;
1827         struct pathbuf path = { 0, 0, NULL };
1828         int ret;
1829
1830         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1831
1832         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN,
1833                            BTREE_ITER_INTENT|
1834                            BTREE_ITER_PREFETCH|
1835                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
1836                 if (k.k->type != KEY_TYPE_inode)
1837                         continue;
1838
1839                 ret = bch2_inode_unpack(bkey_s_c_to_inode(k), &u);
1840                 if (ret) {
1841                         /* Should have been caught earlier in fsck: */
1842                         bch_err(c, "error unpacking inode %llu: %i", k.k->p.offset, ret);
1843                         break;
1844                 }
1845
1846                 if (u.bi_flags & BCH_INODE_UNLINKED)
1847                         continue;
1848
1849                 ret = check_path(&trans, &path, &u, iter.pos.snapshot);
1850                 if (ret)
1851                         break;
1852         }
1853         bch2_trans_iter_exit(&trans, &iter);
1854
1855         BUG_ON(ret == -EINTR);
1856
1857         kfree(path.entries);
1858
1859         return bch2_trans_exit(&trans) ?: ret;
1860 }
1861
1862 struct nlink_table {
1863         size_t          nr;
1864         size_t          size;
1865
1866         struct nlink {
1867                 u64     inum;
1868                 u32     snapshot;
1869                 u32     count;
1870         }               *d;
1871 };
1872
1873 static int add_nlink(struct nlink_table *t, u64 inum, u32 snapshot)
1874 {
1875         if (t->nr == t->size) {
1876                 size_t new_size = max_t(size_t, 128UL, t->size * 2);
1877                 void *d = kvmalloc(new_size * sizeof(t->d[0]), GFP_KERNEL);
1878                 if (!d) {
1879                         return -ENOMEM;
1880                 }
1881
1882                 if (t->d)
1883                         memcpy(d, t->d, t->size * sizeof(t->d[0]));
1884                 kvfree(t->d);
1885
1886                 t->d = d;
1887                 t->size = new_size;
1888         }
1889
1890
1891         t->d[t->nr++] = (struct nlink) {
1892                 .inum           = inum,
1893                 .snapshot       = snapshot,
1894         };
1895
1896         return 0;
1897 }
1898
1899 static int nlink_cmp(const void *_l, const void *_r)
1900 {
1901         const struct nlink *l = _l;
1902         const struct nlink *r = _r;
1903
1904         return cmp_int(l->inum, r->inum) ?: cmp_int(l->snapshot, r->snapshot);
1905 }
1906
1907 static void inc_link(struct bch_fs *c, struct snapshots_seen *s,
1908                      struct nlink_table *links,
1909                      u64 range_start, u64 range_end, u64 inum, u32 snapshot)
1910 {
1911         struct nlink *link, key = {
1912                 .inum = inum, .snapshot = U32_MAX,
1913         };
1914
1915         if (inum < range_start || inum >= range_end)
1916                 return;
1917
1918         link = __inline_bsearch(&key, links->d, links->nr,
1919                                 sizeof(links->d[0]), nlink_cmp);
1920         if (!link)
1921                 return;
1922
1923         while (link > links->d && link[0].inum == link[-1].inum)
1924                 --link;
1925
1926         for (; link < links->d + links->nr && link->inum == inum; link++)
1927                 if (ref_visible(c, s, snapshot, link->snapshot)) {
1928                         link->count++;
1929                         if (link->snapshot >= snapshot)
1930                                 break;
1931                 }
1932 }
1933
1934 noinline_for_stack
1935 static int check_nlinks_find_hardlinks(struct bch_fs *c,
1936                                        struct nlink_table *t,
1937                                        u64 start, u64 *end)
1938 {
1939         struct btree_trans trans;
1940         struct btree_iter iter;
1941         struct bkey_s_c k;
1942         struct bkey_s_c_inode inode;
1943         struct bch_inode_unpacked u;
1944         int ret = 0;
1945
1946         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1947
1948         for_each_btree_key(&trans, iter, BTREE_ID_inodes,
1949                            POS(0, start),
1950                            BTREE_ITER_INTENT|
1951                            BTREE_ITER_PREFETCH|
1952                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
1953                 if (k.k->type != KEY_TYPE_inode)
1954                         continue;
1955
1956                 inode = bkey_s_c_to_inode(k);
1957
1958                 /*
1959                  * Backpointer and directory structure checks are sufficient for
1960                  * directories, since they can't have hardlinks:
1961                  */
1962                 if (S_ISDIR(le16_to_cpu(inode.v->bi_mode)))
1963                         continue;
1964
1965                 /* Should never fail, checked by bch2_inode_invalid: */
1966                 BUG_ON(bch2_inode_unpack(inode, &u));
1967
1968                 if (!u.bi_nlink)
1969                         continue;
1970
1971                 ret = add_nlink(t, k.k->p.offset, k.k->p.snapshot);
1972                 if (ret) {
1973                         *end = k.k->p.offset;
1974                         ret = 0;
1975                         break;
1976                 }
1977
1978         }
1979         bch2_trans_iter_exit(&trans, &iter);
1980         bch2_trans_exit(&trans);
1981
1982         if (ret)
1983                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
1984
1985         return ret;
1986 }
1987
1988 noinline_for_stack
1989 static int check_nlinks_walk_dirents(struct bch_fs *c, struct nlink_table *links,
1990                                      u64 range_start, u64 range_end)
1991 {
1992         struct btree_trans trans;
1993         struct snapshots_seen s;
1994         struct btree_iter iter;
1995         struct bkey_s_c k;
1996         struct bkey_s_c_dirent d;
1997         int ret;
1998
1999         snapshots_seen_init(&s);
2000
2001         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2002
2003         for_each_btree_key(&trans, iter, BTREE_ID_dirents, POS_MIN,
2004                            BTREE_ITER_INTENT|
2005                            BTREE_ITER_PREFETCH|
2006                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2007                 ret = snapshots_seen_update(c, &s, k.k->p);
2008                 if (ret)
2009                         break;
2010
2011                 switch (k.k->type) {
2012                 case KEY_TYPE_dirent:
2013                         d = bkey_s_c_to_dirent(k);
2014
2015                         if (d.v->d_type != DT_DIR &&
2016                             d.v->d_type != DT_SUBVOL)
2017                                 inc_link(c, &s, links, range_start, range_end,
2018                                          le64_to_cpu(d.v->d_inum),
2019                                          d.k->p.snapshot);
2020                         break;
2021                 }
2022
2023                 bch2_trans_cond_resched(&trans);
2024         }
2025         bch2_trans_iter_exit(&trans, &iter);
2026
2027         if (ret)
2028                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
2029
2030         bch2_trans_exit(&trans);
2031         snapshots_seen_exit(&s);
2032         return ret;
2033 }
2034
2035 noinline_for_stack
2036 static int check_nlinks_update_hardlinks(struct bch_fs *c,
2037                                struct nlink_table *links,
2038                                u64 range_start, u64 range_end)
2039 {
2040         struct btree_trans trans;
2041         struct btree_iter iter;
2042         struct bkey_s_c k;
2043         struct bkey_s_c_inode inode;
2044         struct bch_inode_unpacked u;
2045         struct nlink *link = links->d;
2046         int ret = 0;
2047
2048         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
2049
2050         for_each_btree_key(&trans, iter, BTREE_ID_inodes,
2051                            POS(0, range_start),
2052                            BTREE_ITER_INTENT|
2053                            BTREE_ITER_PREFETCH|
2054                            BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
2055                 if (k.k->p.offset >= range_end)
2056                         break;
2057
2058                 if (k.k->type != KEY_TYPE_inode)
2059                         continue;
2060
2061                 inode = bkey_s_c_to_inode(k);
2062                 if (S_ISDIR(le16_to_cpu(inode.v->bi_mode)))
2063                         continue;
2064
2065                 BUG_ON(bch2_inode_unpack(inode, &u));
2066
2067                 if (!u.bi_nlink)
2068                         continue;
2069
2070                 while ((cmp_int(link->inum, k.k->p.offset) ?:
2071                         cmp_int(link->snapshot, k.k->p.snapshot)) < 0) {
2072                         link++;
2073                         BUG_ON(link >= links->d + links->nr);
2074                 }
2075
2076                 if (fsck_err_on(bch2_inode_nlink_get(&u) != link->count, c,
2077                                 "inode %llu has wrong i_nlink (type %u i_nlink %u, should be %u)",
2078                                 u.bi_inum, mode_to_type(u.bi_mode),
2079                                 bch2_inode_nlink_get(&u), link->count)) {
2080                         bch2_inode_nlink_set(&u, link->count);
2081
2082                         ret = write_inode(&trans, &u, k.k->p.snapshot);
2083                         if (ret)
2084                                 bch_err(c, "error in fsck: error %i updating inode", ret);
2085                 }
2086         }
2087 fsck_err:
2088         bch2_trans_iter_exit(&trans, &iter);
2089         bch2_trans_exit(&trans);
2090
2091         if (ret)
2092                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
2093
2094         return ret;
2095 }
2096
2097 noinline_for_stack
2098 static int check_nlinks(struct bch_fs *c)
2099 {
2100         struct nlink_table links = { 0 };
2101         u64 this_iter_range_start, next_iter_range_start = 0;
2102         int ret = 0;
2103
2104         bch_verbose(c, "checking inode nlinks");
2105
2106         do {
2107                 this_iter_range_start = next_iter_range_start;
2108                 next_iter_range_start = U64_MAX;
2109
2110                 ret = check_nlinks_find_hardlinks(c, &links,
2111                                                   this_iter_range_start,
2112                                                   &next_iter_range_start);
2113
2114                 ret = check_nlinks_walk_dirents(c, &links,
2115                                           this_iter_range_start,
2116                                           next_iter_range_start);
2117                 if (ret)
2118                         break;
2119
2120                 ret = check_nlinks_update_hardlinks(c, &links,
2121                                          this_iter_range_start,
2122                                          next_iter_range_start);
2123                 if (ret)
2124                         break;
2125
2126                 links.nr = 0;
2127         } while (next_iter_range_start != U64_MAX);
2128
2129         kvfree(links.d);
2130
2131         return ret;
2132 }
2133
2134 /*
2135  * Checks for inconsistencies that shouldn't happen, unless we have a bug.
2136  * Doesn't fix them yet, mainly because they haven't yet been observed:
2137  */
2138 int bch2_fsck_full(struct bch_fs *c)
2139 {
2140         return  bch2_fs_snapshots_check(c) ?:
2141                 check_inodes(c, true) ?:
2142                 check_subvols(c) ?:
2143                 check_extents(c) ?:
2144                 check_dirents(c) ?:
2145                 check_xattrs(c) ?:
2146                 check_root(c) ?:
2147                 check_directory_structure(c) ?:
2148                 check_nlinks(c);
2149 }
2150
2151 int bch2_fsck_walk_inodes_only(struct bch_fs *c)
2152 {
2153         return check_inodes(c, false);
2154 }