]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fsck.c
Update bcachefs sources to 3c41353bc1 bcachefs: Fix bch2_verify_keylist_sorted
[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 "super.h"
13 #include "xattr.h"
14
15 #include <linux/dcache.h> /* struct qstr */
16 #include <linux/generic-radix-tree.h>
17
18 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
19
20 static s64 bch2_count_inode_sectors(struct btree_trans *trans, u64 inum)
21 {
22         struct btree_iter *iter;
23         struct bkey_s_c k;
24         u64 sectors = 0;
25         int ret;
26
27         for_each_btree_key(trans, iter, BTREE_ID_extents,
28                            POS(inum, 0), 0, k, ret) {
29                 if (k.k->p.inode != inum)
30                         break;
31
32                 if (bkey_extent_is_allocation(k.k))
33                         sectors += k.k->size;
34         }
35
36         bch2_trans_iter_free(trans, iter);
37
38         return ret ?: sectors;
39 }
40
41 static int __lookup_inode(struct btree_trans *trans, u64 inode_nr,
42                           struct bch_inode_unpacked *inode,
43                           u32 *snapshot)
44 {
45         struct btree_iter *iter;
46         struct bkey_s_c k;
47         int ret;
48
49         iter = bch2_trans_get_iter(trans, BTREE_ID_inodes,
50                         POS(0, inode_nr), 0);
51         k = bch2_btree_iter_peek_slot(iter);
52         ret = bkey_err(k);
53         if (ret)
54                 goto err;
55
56         if (snapshot)
57                 *snapshot = iter->pos.snapshot;
58         ret = k.k->type == KEY_TYPE_inode
59                 ? bch2_inode_unpack(bkey_s_c_to_inode(k), inode)
60                 : -ENOENT;
61 err:
62         bch2_trans_iter_free(trans, iter);
63         return ret;
64 }
65
66 static int lookup_inode(struct btree_trans *trans, u64 inode_nr,
67                         struct bch_inode_unpacked *inode,
68                         u32 *snapshot)
69 {
70         return lockrestart_do(trans, __lookup_inode(trans, inode_nr, inode, snapshot));
71 }
72
73 static int __write_inode(struct btree_trans *trans,
74                          struct bch_inode_unpacked *inode,
75                          u32 snapshot)
76 {
77         struct btree_iter *inode_iter =
78                 bch2_trans_get_iter(trans, BTREE_ID_inodes,
79                                     SPOS(0, inode->bi_inum, snapshot),
80                                     BTREE_ITER_INTENT);
81         int ret = bch2_inode_write(trans, inode_iter, inode);
82         bch2_trans_iter_put(trans, inode_iter);
83         return ret;
84 }
85
86 static int write_inode(struct btree_trans *trans,
87                        struct bch_inode_unpacked *inode,
88                        u32 snapshot)
89 {
90         int ret = __bch2_trans_do(trans, NULL, NULL,
91                                   BTREE_INSERT_NOFAIL|
92                                   BTREE_INSERT_LAZY_RW,
93                                   __write_inode(trans, inode, snapshot));
94         if (ret)
95                 bch_err(trans->c, "error in fsck: error %i updating inode", ret);
96         return ret;
97 }
98
99 static int __remove_dirent(struct btree_trans *trans, struct bpos pos)
100 {
101         struct bch_fs *c = trans->c;
102         struct btree_iter *iter;
103         struct bch_inode_unpacked dir_inode;
104         struct bch_hash_info dir_hash_info;
105         int ret;
106
107         ret = lookup_inode(trans, pos.inode, &dir_inode, NULL);
108         if (ret)
109                 return ret;
110
111         dir_hash_info = bch2_hash_info_init(c, &dir_inode);
112
113         iter = bch2_trans_get_iter(trans, BTREE_ID_dirents, pos, BTREE_ITER_INTENT);
114
115         ret = bch2_hash_delete_at(trans, bch2_dirent_hash_desc,
116                                   &dir_hash_info, iter);
117         bch2_trans_iter_put(trans, iter);
118         return ret;
119 }
120
121 static int remove_dirent(struct btree_trans *trans, struct bpos pos)
122 {
123         int ret = __bch2_trans_do(trans, NULL, NULL,
124                                   BTREE_INSERT_NOFAIL|
125                                   BTREE_INSERT_LAZY_RW,
126                                   __remove_dirent(trans, pos));
127         if (ret)
128                 bch_err(trans->c, "remove_dirent: err %i deleting dirent", ret);
129         return ret;
130 }
131
132 /* Get lost+found, create if it doesn't exist: */
133 static int lookup_lostfound(struct btree_trans *trans,
134                             struct bch_inode_unpacked *lostfound)
135 {
136         struct bch_fs *c = trans->c;
137         struct bch_inode_unpacked root;
138         struct bch_hash_info root_hash_info;
139         struct qstr lostfound_str = QSTR("lost+found");
140         u64 inum;
141         u32 snapshot;
142         int ret;
143
144         ret = lookup_inode(trans, BCACHEFS_ROOT_INO, &root, &snapshot);
145         if (ret && ret != -ENOENT)
146                 return ret;
147
148         root_hash_info = bch2_hash_info_init(c, &root);
149         inum = bch2_dirent_lookup(c, BCACHEFS_ROOT_INO, &root_hash_info,
150                                   &lostfound_str);
151         if (!inum) {
152                 bch_notice(c, "creating lost+found");
153                 goto create_lostfound;
154         }
155
156         ret = lookup_inode(trans, inum, lostfound, &snapshot);
157         if (ret && ret != -ENOENT) {
158                 /*
159                  * The check_dirents pass has already run, dangling dirents
160                  * shouldn't exist here:
161                  */
162                 bch_err(c, "error looking up lost+found: %i", ret);
163                 return ret;
164         }
165
166         if (ret == -ENOENT) {
167 create_lostfound:
168                 bch2_inode_init_early(c, lostfound);
169
170                 ret = __bch2_trans_do(trans, NULL, NULL,
171                                       BTREE_INSERT_NOFAIL|
172                                       BTREE_INSERT_LAZY_RW,
173                         bch2_create_trans(trans,
174                                           BCACHEFS_ROOT_INO, &root,
175                                           lostfound,
176                                           &lostfound_str,
177                                           0, 0, S_IFDIR|0700, 0, NULL, NULL));
178                 if (ret)
179                         bch_err(c, "error creating lost+found: %i", ret);
180         }
181
182         return 0;
183 }
184
185 static int reattach_inode(struct btree_trans *trans,
186                           struct bch_inode_unpacked *inode)
187 {
188         struct bch_hash_info dir_hash;
189         struct bch_inode_unpacked lostfound;
190         char name_buf[20];
191         struct qstr name;
192         u64 dir_offset = 0;
193         int ret;
194
195         ret = lookup_lostfound(trans, &lostfound);
196         if (ret)
197                 return ret;
198
199         if (S_ISDIR(inode->bi_mode)) {
200                 lostfound.bi_nlink++;
201
202                 ret = write_inode(trans, &lostfound, U32_MAX);
203                 if (ret)
204                         return ret;
205         }
206
207         dir_hash = bch2_hash_info_init(trans->c, &lostfound);
208
209         snprintf(name_buf, sizeof(name_buf), "%llu", inode->bi_inum);
210         name = (struct qstr) QSTR(name_buf);
211
212         ret = __bch2_trans_do(trans, NULL, NULL, BTREE_INSERT_LAZY_RW,
213                 bch2_dirent_create(trans, lostfound.bi_inum, &dir_hash,
214                                    mode_to_type(inode->bi_mode),
215                                    &name, inode->bi_inum, &dir_offset,
216                                    BCH_HASH_SET_MUST_CREATE));
217         if (ret) {
218                 bch_err(trans->c, "error %i reattaching inode %llu",
219                         ret, inode->bi_inum);
220                 return ret;
221         }
222
223         inode->bi_dir           = lostfound.bi_inum;
224         inode->bi_dir_offset    = dir_offset;
225
226         return write_inode(trans, inode, U32_MAX);
227 }
228
229 static int remove_backpointer(struct btree_trans *trans,
230                               struct bch_inode_unpacked *inode)
231 {
232         struct btree_iter *iter;
233         struct bkey_s_c k;
234         int ret;
235
236         iter = bch2_trans_get_iter(trans, BTREE_ID_dirents,
237                                    POS(inode->bi_dir, inode->bi_dir_offset), 0);
238         k = bch2_btree_iter_peek_slot(iter);
239         ret = bkey_err(k);
240         if (ret)
241                 goto out;
242         if (k.k->type != KEY_TYPE_dirent) {
243                 ret = -ENOENT;
244                 goto out;
245         }
246
247         ret = remove_dirent(trans, k.k->p);
248 out:
249         bch2_trans_iter_put(trans, iter);
250         return ret;
251 }
252
253 struct inode_walker {
254         bool                    first_this_inode;
255         bool                    have_inode;
256         u64                     cur_inum;
257         u32                     snapshot;
258         struct bch_inode_unpacked inode;
259 };
260
261 static struct inode_walker inode_walker_init(void)
262 {
263         return (struct inode_walker) {
264                 .cur_inum       = -1,
265                 .have_inode     = false,
266         };
267 }
268
269 static int walk_inode(struct btree_trans *trans,
270                       struct inode_walker *w, u64 inum)
271 {
272         if (inum != w->cur_inum) {
273                 int ret = lookup_inode(trans, inum, &w->inode, &w->snapshot);
274
275                 if (ret && ret != -ENOENT)
276                         return ret;
277
278                 w->have_inode   = !ret;
279                 w->cur_inum     = inum;
280                 w->first_this_inode = true;
281         } else {
282                 w->first_this_inode = false;
283         }
284
285         return 0;
286 }
287
288 static int hash_redo_key(struct btree_trans *trans,
289                          const struct bch_hash_desc desc,
290                          struct bch_hash_info *hash_info,
291                          struct btree_iter *k_iter, struct bkey_s_c k)
292 {
293         struct bkey_i delete;
294         struct bkey_i *tmp;
295
296         tmp = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
297         if (IS_ERR(tmp))
298                 return PTR_ERR(tmp);
299
300         bkey_reassemble(tmp, k);
301
302         bkey_init(&delete.k);
303         delete.k.p = k_iter->pos;
304         bch2_trans_update(trans, k_iter, &delete, 0);
305
306         return bch2_hash_set(trans, desc, hash_info, k_iter->pos.inode,
307                              tmp, 0);
308 }
309
310 static int fsck_hash_delete_at(struct btree_trans *trans,
311                                const struct bch_hash_desc desc,
312                                struct bch_hash_info *info,
313                                struct btree_iter *iter)
314 {
315         int ret;
316 retry:
317         ret   = bch2_hash_delete_at(trans, desc, info, iter) ?:
318                 bch2_trans_commit(trans, NULL, NULL,
319                                   BTREE_INSERT_NOFAIL|
320                                   BTREE_INSERT_LAZY_RW);
321         if (ret == -EINTR) {
322                 ret = bch2_btree_iter_traverse(iter);
323                 if (!ret)
324                         goto retry;
325         }
326
327         return ret;
328 }
329
330 static int hash_check_key(struct btree_trans *trans,
331                           const struct bch_hash_desc desc,
332                           struct bch_hash_info *hash_info,
333                           struct btree_iter *k_iter, struct bkey_s_c hash_k)
334 {
335         struct bch_fs *c = trans->c;
336         struct btree_iter *iter = NULL;
337         char buf[200];
338         struct bkey_s_c k;
339         u64 hash;
340         int ret = 0;
341
342         if (hash_k.k->type != desc.key_type)
343                 return 0;
344
345         hash = desc.hash_bkey(hash_info, hash_k);
346
347         if (likely(hash == hash_k.k->p.offset))
348                 return 0;
349
350         if (hash_k.k->p.offset < hash)
351                 goto bad_hash;
352
353         for_each_btree_key(trans, iter, desc.btree_id, POS(hash_k.k->p.inode, hash),
354                            BTREE_ITER_SLOTS, k, ret) {
355                 if (!bkey_cmp(k.k->p, hash_k.k->p))
356                         break;
357
358                 if (fsck_err_on(k.k->type == desc.key_type &&
359                                 !desc.cmp_bkey(k, hash_k), c,
360                                 "duplicate hash table keys:\n%s",
361                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
362                                                        hash_k), buf))) {
363                         ret = fsck_hash_delete_at(trans, desc, hash_info, k_iter);
364                         if (ret)
365                                 return ret;
366                         ret = 1;
367                         break;
368                 }
369
370                 if (bkey_deleted(k.k)) {
371                         bch2_trans_iter_free(trans, iter);
372                         goto bad_hash;
373                 }
374
375         }
376         bch2_trans_iter_free(trans, iter);
377         return ret;
378 bad_hash:
379         if (fsck_err(c, "hash table key at wrong offset: btree %u inode %llu offset %llu, "
380                      "hashed to %llu should be at %llu\n%s",
381                      desc.btree_id, hash_k.k->p.inode, hash_k.k->p.offset,
382                      hash, iter->pos.offset,
383                      (bch2_bkey_val_to_text(&PBUF(buf), c, hash_k), buf)) == FSCK_ERR_IGNORE)
384                 return 0;
385
386         ret = __bch2_trans_do(trans, NULL, NULL,
387                               BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
388                 hash_redo_key(trans, desc, hash_info, k_iter, hash_k));
389         if (ret) {
390                 bch_err(c, "hash_redo_key err %i", ret);
391                 return ret;
392         }
393         return -EINTR;
394 fsck_err:
395         return ret;
396 }
397
398 static int check_inode(struct btree_trans *trans,
399                        struct btree_iter *iter,
400                        struct bkey_s_c_inode inode)
401 {
402         struct bch_fs *c = trans->c;
403         struct bch_inode_unpacked u;
404         bool do_update = false;
405         int ret = 0;
406
407         ret = bch2_inode_unpack(inode, &u);
408
409         if (bch2_fs_inconsistent_on(ret, c,
410                          "error unpacking inode %llu in fsck",
411                          inode.k->p.inode))
412                 return ret;
413
414         if (u.bi_flags & BCH_INODE_UNLINKED &&
415             (!c->sb.clean ||
416              fsck_err(c, "filesystem marked clean, but inode %llu unlinked",
417                       u.bi_inum))) {
418                 bch_verbose(c, "deleting inode %llu", u.bi_inum);
419
420                 bch2_trans_unlock(trans);
421                 bch2_fs_lazy_rw(c);
422
423                 ret = bch2_inode_rm(c, u.bi_inum, false);
424                 if (ret)
425                         bch_err(c, "error in fsck: error %i while deleting inode", ret);
426                 return ret;
427         }
428
429         if (u.bi_flags & BCH_INODE_I_SIZE_DIRTY &&
430             (!c->sb.clean ||
431              fsck_err(c, "filesystem marked clean, but inode %llu has i_size dirty",
432                       u.bi_inum))) {
433                 bch_verbose(c, "truncating inode %llu", u.bi_inum);
434
435                 bch2_trans_unlock(trans);
436                 bch2_fs_lazy_rw(c);
437
438                 /*
439                  * XXX: need to truncate partial blocks too here - or ideally
440                  * just switch units to bytes and that issue goes away
441                  */
442                 ret = bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
443                                 POS(u.bi_inum, round_up(u.bi_size, block_bytes(c))),
444                                 POS(u.bi_inum, U64_MAX),
445                                 NULL);
446                 if (ret) {
447                         bch_err(c, "error in fsck: error %i truncating inode", ret);
448                         return ret;
449                 }
450
451                 /*
452                  * We truncated without our normal sector accounting hook, just
453                  * make sure we recalculate it:
454                  */
455                 u.bi_flags |= BCH_INODE_I_SECTORS_DIRTY;
456
457                 u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
458                 do_update = true;
459         }
460
461         if (u.bi_flags & BCH_INODE_I_SECTORS_DIRTY &&
462             (!c->sb.clean ||
463              fsck_err(c, "filesystem marked clean, but inode %llu has i_sectors dirty",
464                       u.bi_inum))) {
465                 s64 sectors;
466
467                 bch_verbose(c, "recounting sectors for inode %llu",
468                             u.bi_inum);
469
470                 sectors = bch2_count_inode_sectors(trans, u.bi_inum);
471                 if (sectors < 0) {
472                         bch_err(c, "error in fsck: error %i recounting inode sectors",
473                                 (int) sectors);
474                         return sectors;
475                 }
476
477                 u.bi_sectors = sectors;
478                 u.bi_flags &= ~BCH_INODE_I_SECTORS_DIRTY;
479                 do_update = true;
480         }
481
482         if (u.bi_flags & BCH_INODE_BACKPTR_UNTRUSTED) {
483                 u.bi_dir = 0;
484                 u.bi_dir_offset = 0;
485                 u.bi_flags &= ~BCH_INODE_BACKPTR_UNTRUSTED;
486                 do_update = true;
487         }
488
489         if (do_update) {
490                 ret = __bch2_trans_do(trans, NULL, NULL,
491                                       BTREE_INSERT_NOFAIL|
492                                       BTREE_INSERT_LAZY_RW,
493                                 bch2_inode_write(trans, iter, &u));
494                 if (ret)
495                         bch_err(c, "error in fsck: error %i "
496                                 "updating inode", ret);
497         }
498 fsck_err:
499         return ret;
500 }
501
502 noinline_for_stack
503 static int check_inodes(struct bch_fs *c, bool full)
504 {
505         struct btree_trans trans;
506         struct btree_iter *iter;
507         struct bkey_s_c k;
508         struct bkey_s_c_inode inode;
509         int ret;
510
511         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
512
513         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN, 0, k, ret) {
514                 if (k.k->type != KEY_TYPE_inode)
515                         continue;
516
517                 inode = bkey_s_c_to_inode(k);
518
519                 if (full ||
520                     (inode.v->bi_flags & (BCH_INODE_I_SIZE_DIRTY|
521                                           BCH_INODE_I_SECTORS_DIRTY|
522                                           BCH_INODE_UNLINKED))) {
523                         ret = check_inode(&trans, iter, inode);
524                         if (ret)
525                                 break;
526                 }
527         }
528         bch2_trans_iter_put(&trans, iter);
529
530         BUG_ON(ret == -EINTR);
531
532         return bch2_trans_exit(&trans) ?: ret;
533 }
534
535 static int fix_overlapping_extent(struct btree_trans *trans,
536                                        struct bkey_s_c k, struct bpos cut_at)
537 {
538         struct btree_iter *iter;
539         struct bkey_i *u;
540         int ret;
541
542         u = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
543         ret = PTR_ERR_OR_ZERO(u);
544         if (ret)
545                 return ret;
546
547         bkey_reassemble(u, k);
548         bch2_cut_front(cut_at, u);
549
550
551         /*
552          * We don't want to go through the extent_handle_overwrites path:
553          *
554          * XXX: this is going to screw up disk accounting, extent triggers
555          * assume things about extent overwrites - we should be running the
556          * triggers manually here
557          */
558         iter = bch2_trans_get_iter(trans, BTREE_ID_extents, u->k.p,
559                                    BTREE_ITER_INTENT|BTREE_ITER_NOT_EXTENTS);
560
561         BUG_ON(iter->flags & BTREE_ITER_IS_EXTENTS);
562         bch2_trans_update(trans, iter, u, BTREE_TRIGGER_NORUN);
563         bch2_trans_iter_put(trans, iter);
564
565         return bch2_trans_commit(trans, NULL, NULL,
566                                  BTREE_INSERT_NOFAIL|
567                                  BTREE_INSERT_LAZY_RW);
568 }
569
570 static int inode_backpointer_exists(struct btree_trans *trans,
571                                     struct bch_inode_unpacked *inode)
572 {
573         struct btree_iter *iter;
574         struct bkey_s_c k;
575         int ret;
576
577         iter = bch2_trans_get_iter(trans, BTREE_ID_dirents,
578                                    POS(inode->bi_dir, inode->bi_dir_offset), 0);
579         k = bch2_btree_iter_peek_slot(iter);
580         ret = bkey_err(k);
581         if (ret)
582                 goto out;
583         if (k.k->type != KEY_TYPE_dirent)
584                 goto out;
585
586         ret = le64_to_cpu(bkey_s_c_to_dirent(k).v->d_inum) == inode->bi_inum;
587 out:
588         bch2_trans_iter_free(trans, iter);
589         return ret;
590 }
591
592 static bool inode_backpointer_matches(struct bkey_s_c_dirent d,
593                                       struct bch_inode_unpacked *inode)
594 {
595         return d.k->p.inode == inode->bi_dir &&
596                 d.k->p.offset == inode->bi_dir_offset;
597 }
598
599 /*
600  * Walk extents: verify that extents have a corresponding S_ISREG inode, and
601  * that i_size an i_sectors are consistent
602  */
603 noinline_for_stack
604 static int check_extents(struct bch_fs *c)
605 {
606         struct inode_walker w = inode_walker_init();
607         struct btree_trans trans;
608         struct btree_iter *iter;
609         struct bkey_s_c k;
610         struct bkey_buf prev;
611         u64 i_sectors = 0;
612         int ret = 0;
613
614         bch2_bkey_buf_init(&prev);
615         prev.k->k = KEY(0, 0, 0);
616         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
617
618         bch_verbose(c, "checking extents");
619
620         iter = bch2_trans_get_iter(&trans, BTREE_ID_extents,
621                                    POS(BCACHEFS_ROOT_INO, 0),
622                                    BTREE_ITER_INTENT);
623 retry:
624         while ((k = bch2_btree_iter_peek(iter)).k &&
625                !(ret = bkey_err(k))) {
626                 if (w.have_inode &&
627                     w.cur_inum != k.k->p.inode &&
628                     !(w.inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY) &&
629                     fsck_err_on(w.inode.bi_sectors != i_sectors, c,
630                                 "inode %llu has incorrect i_sectors: got %llu, should be %llu",
631                                 w.inode.bi_inum,
632                                 w.inode.bi_sectors, i_sectors)) {
633                         w.inode.bi_sectors = i_sectors;
634
635                         ret = write_inode(&trans, &w.inode, w.snapshot);
636                         if (ret)
637                                 break;
638                 }
639
640                 if (bkey_cmp(prev.k->k.p, bkey_start_pos(k.k)) > 0) {
641                         char buf1[200];
642                         char buf2[200];
643
644                         bch2_bkey_val_to_text(&PBUF(buf1), c, bkey_i_to_s_c(prev.k));
645                         bch2_bkey_val_to_text(&PBUF(buf2), c, k);
646
647                         if (fsck_err(c, "overlapping extents:\n%s\n%s", buf1, buf2))
648                                 return fix_overlapping_extent(&trans, k, prev.k->k.p) ?: -EINTR;
649                 }
650
651                 ret = walk_inode(&trans, &w, k.k->p.inode);
652                 if (ret)
653                         break;
654
655                 if (w.first_this_inode)
656                         i_sectors = 0;
657
658                 if (fsck_err_on(!w.have_inode, c,
659                                 "extent type %u for missing inode %llu",
660                                 k.k->type, k.k->p.inode) ||
661                     fsck_err_on(w.have_inode &&
662                                 !S_ISREG(w.inode.bi_mode) && !S_ISLNK(w.inode.bi_mode), c,
663                                 "extent type %u for non regular file, inode %llu mode %o",
664                                 k.k->type, k.k->p.inode, w.inode.bi_mode)) {
665                         bch2_fs_lazy_rw(c);
666                         return bch2_btree_delete_range_trans(&trans, BTREE_ID_extents,
667                                                        POS(k.k->p.inode, 0),
668                                                        POS(k.k->p.inode, U64_MAX),
669                                                        NULL) ?: -EINTR;
670                 }
671
672                 if (fsck_err_on(w.have_inode &&
673                                 !(w.inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
674                                 k.k->type != KEY_TYPE_reservation &&
675                                 k.k->p.offset > round_up(w.inode.bi_size, block_bytes(c)) >> 9, c,
676                                 "extent type %u offset %llu past end of inode %llu, i_size %llu",
677                                 k.k->type, k.k->p.offset, k.k->p.inode, w.inode.bi_size)) {
678                         bch2_fs_lazy_rw(c);
679                         return bch2_btree_delete_range_trans(&trans, BTREE_ID_extents,
680                                         POS(k.k->p.inode, round_up(w.inode.bi_size, block_bytes(c))),
681                                         POS(k.k->p.inode, U64_MAX),
682                                         NULL) ?: -EINTR;
683                 }
684
685                 if (bkey_extent_is_allocation(k.k))
686                         i_sectors += k.k->size;
687                 bch2_bkey_buf_reassemble(&prev, c, k);
688
689                 bch2_btree_iter_advance(iter);
690         }
691 fsck_err:
692         if (ret == -EINTR)
693                 goto retry;
694         bch2_trans_iter_put(&trans, iter);
695         bch2_bkey_buf_exit(&prev, c);
696         return bch2_trans_exit(&trans) ?: ret;
697 }
698
699 /*
700  * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
701  * validate d_type
702  */
703 noinline_for_stack
704 static int check_dirents(struct bch_fs *c)
705 {
706         struct inode_walker w = inode_walker_init();
707         struct bch_hash_info hash_info;
708         struct btree_trans trans;
709         struct btree_iter *iter;
710         struct bkey_s_c k;
711         char buf[200];
712         unsigned nr_subdirs = 0;
713         int ret = 0;
714
715         bch_verbose(c, "checking dirents");
716
717         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
718
719         iter = bch2_trans_get_iter(&trans, BTREE_ID_dirents,
720                                    POS(BCACHEFS_ROOT_INO, 0), 0);
721 retry:
722         while ((k = bch2_btree_iter_peek(iter)).k &&
723                !(ret = bkey_err(k))) {
724                 struct bkey_s_c_dirent d;
725                 struct bch_inode_unpacked target;
726                 u32 target_snapshot;
727                 bool have_target;
728                 bool backpointer_exists = true;
729                 u64 d_inum;
730
731                 if (w.have_inode &&
732                     w.cur_inum != k.k->p.inode &&
733                     fsck_err_on(w.inode.bi_nlink != nr_subdirs, c,
734                                 "directory %llu with wrong i_nlink: got %u, should be %u",
735                                 w.inode.bi_inum, w.inode.bi_nlink, nr_subdirs)) {
736                         w.inode.bi_nlink = nr_subdirs;
737                         ret = write_inode(&trans, &w.inode, w.snapshot);
738                         if (ret)
739                                 break;
740                 }
741
742                 ret = walk_inode(&trans, &w, k.k->p.inode);
743                 if (ret)
744                         break;
745
746                 if (w.first_this_inode)
747                         nr_subdirs = 0;
748
749                 if (fsck_err_on(!w.have_inode, c,
750                                 "dirent in nonexisting directory:\n%s",
751                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
752                                                        k), buf)) ||
753                     fsck_err_on(!S_ISDIR(w.inode.bi_mode), c,
754                                 "dirent in non directory inode type %u:\n%s",
755                                 mode_to_type(w.inode.bi_mode),
756                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
757                                                        k), buf))) {
758                         ret = lockrestart_do(&trans,
759                                         bch2_btree_delete_at(&trans, iter, 0));
760                         if (ret)
761                                 goto err;
762                         goto next;
763                 }
764
765                 if (!w.have_inode)
766                         goto next;
767
768                 if (w.first_this_inode)
769                         hash_info = bch2_hash_info_init(c, &w.inode);
770
771                 ret = hash_check_key(&trans, bch2_dirent_hash_desc,
772                                      &hash_info, iter, k);
773                 if (ret > 0) {
774                         ret = 0;
775                         goto next;
776                 }
777                 if (ret)
778                         goto fsck_err;
779
780                 if (k.k->type != KEY_TYPE_dirent)
781                         goto next;
782
783                 d = bkey_s_c_to_dirent(k);
784                 d_inum = le64_to_cpu(d.v->d_inum);
785
786                 ret = lookup_inode(&trans, d_inum, &target, &target_snapshot);
787                 if (ret && ret != -ENOENT)
788                         break;
789
790                 have_target = !ret;
791                 ret = 0;
792
793                 if (fsck_err_on(!have_target, c,
794                                 "dirent points to missing inode:\n%s",
795                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
796                                                        k), buf))) {
797                         ret = remove_dirent(&trans, d.k->p);
798                         if (ret)
799                                 goto err;
800                         goto next;
801                 }
802
803                 if (!have_target)
804                         goto next;
805
806                 if (!target.bi_dir &&
807                     !target.bi_dir_offset) {
808                         target.bi_dir           = k.k->p.inode;
809                         target.bi_dir_offset    = k.k->p.offset;
810
811                         ret = write_inode(&trans, &target, target_snapshot);
812                         if (ret)
813                                 goto err;
814                 }
815
816                 if (!inode_backpointer_matches(d, &target)) {
817                         ret = inode_backpointer_exists(&trans, &target);
818                         if (ret < 0)
819                                 goto err;
820
821                         backpointer_exists = ret;
822                         ret = 0;
823
824                         if (fsck_err_on(S_ISDIR(target.bi_mode) &&
825                                         backpointer_exists, c,
826                                         "directory %llu with multiple links",
827                                         target.bi_inum)) {
828                                 ret = remove_dirent(&trans, d.k->p);
829                                 if (ret)
830                                         goto err;
831                                 continue;
832                         }
833
834                         if (fsck_err_on(backpointer_exists &&
835                                         !target.bi_nlink, c,
836                                         "inode %llu has multiple links but i_nlink 0",
837                                         d_inum)) {
838                                 target.bi_nlink++;
839                                 target.bi_flags &= ~BCH_INODE_UNLINKED;
840
841                                 ret = write_inode(&trans, &target, target_snapshot);
842                                 if (ret)
843                                         goto err;
844                         }
845
846                         if (fsck_err_on(!backpointer_exists, c,
847                                         "inode %llu has wrong backpointer:\n"
848                                         "got       %llu:%llu\n"
849                                         "should be %llu:%llu",
850                                         d_inum,
851                                         target.bi_dir,
852                                         target.bi_dir_offset,
853                                         k.k->p.inode,
854                                         k.k->p.offset)) {
855                                 target.bi_dir           = k.k->p.inode;
856                                 target.bi_dir_offset    = k.k->p.offset;
857
858                                 ret = write_inode(&trans, &target, target_snapshot);
859                                 if (ret)
860                                         goto err;
861                         }
862                 }
863
864                 if (fsck_err_on(d.v->d_type != mode_to_type(target.bi_mode), c,
865                                 "incorrect d_type: should be %u:\n%s",
866                                 mode_to_type(target.bi_mode),
867                                 (bch2_bkey_val_to_text(&PBUF(buf), c,
868                                                        k), buf))) {
869                         struct bkey_i_dirent *n;
870
871                         n = kmalloc(bkey_bytes(d.k), GFP_KERNEL);
872                         if (!n) {
873                                 ret = -ENOMEM;
874                                 goto err;
875                         }
876
877                         bkey_reassemble(&n->k_i, d.s_c);
878                         n->v.d_type = mode_to_type(target.bi_mode);
879
880                         ret = __bch2_trans_do(&trans, NULL, NULL,
881                                               BTREE_INSERT_NOFAIL|
882                                               BTREE_INSERT_LAZY_RW,
883                                 (bch2_trans_update(&trans, iter, &n->k_i, 0), 0));
884                         kfree(n);
885                         if (ret)
886                                 goto err;
887
888                 }
889
890                 nr_subdirs += d.v->d_type == DT_DIR;
891 next:
892                 bch2_btree_iter_advance(iter);
893         }
894 err:
895 fsck_err:
896         if (ret == -EINTR)
897                 goto retry;
898
899         bch2_trans_iter_put(&trans, iter);
900         return bch2_trans_exit(&trans) ?: ret;
901 }
902
903 /*
904  * Walk xattrs: verify that they all have a corresponding inode
905  */
906 noinline_for_stack
907 static int check_xattrs(struct bch_fs *c)
908 {
909         struct inode_walker w = inode_walker_init();
910         struct bch_hash_info hash_info;
911         struct btree_trans trans;
912         struct btree_iter *iter;
913         struct bkey_s_c k;
914         int ret = 0;
915
916         bch_verbose(c, "checking xattrs");
917
918         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
919
920         iter = bch2_trans_get_iter(&trans, BTREE_ID_xattrs,
921                                    POS(BCACHEFS_ROOT_INO, 0), 0);
922 retry:
923         while ((k = bch2_btree_iter_peek(iter)).k &&
924                !(ret = bkey_err(k))) {
925                 ret = walk_inode(&trans, &w, k.k->p.inode);
926                 if (ret)
927                         break;
928
929                 if (fsck_err_on(!w.have_inode, c,
930                                 "xattr for missing inode %llu",
931                                 k.k->p.inode)) {
932                         ret = bch2_btree_delete_at(&trans, iter, 0);
933                         if (ret)
934                                 break;
935                         continue;
936                 }
937
938                 if (w.first_this_inode && w.have_inode)
939                         hash_info = bch2_hash_info_init(c, &w.inode);
940
941                 ret = hash_check_key(&trans, bch2_xattr_hash_desc,
942                                      &hash_info, iter, k);
943                 if (ret)
944                         break;
945
946                 bch2_btree_iter_advance(iter);
947         }
948 fsck_err:
949         if (ret == -EINTR)
950                 goto retry;
951
952         bch2_trans_iter_put(&trans, iter);
953         return bch2_trans_exit(&trans) ?: ret;
954 }
955
956 /* Get root directory, create if it doesn't exist: */
957 static int check_root(struct bch_fs *c, struct bch_inode_unpacked *root_inode)
958 {
959         struct bkey_inode_buf packed;
960         u32 snapshot;
961         int ret;
962
963         bch_verbose(c, "checking root directory");
964
965         ret = bch2_trans_do(c, NULL, NULL, 0,
966                 lookup_inode(&trans, BCACHEFS_ROOT_INO, root_inode, &snapshot));
967         if (ret && ret != -ENOENT)
968                 return ret;
969
970         if (fsck_err_on(ret, c, "root directory missing"))
971                 goto create_root;
972
973         if (fsck_err_on(!S_ISDIR(root_inode->bi_mode), c,
974                         "root inode not a directory"))
975                 goto create_root;
976
977         return 0;
978 fsck_err:
979         return ret;
980 create_root:
981         bch2_inode_init(c, root_inode, 0, 0, S_IFDIR|0755,
982                         0, NULL);
983         root_inode->bi_inum = BCACHEFS_ROOT_INO;
984
985         bch2_inode_pack(c, &packed, root_inode);
986
987         return bch2_btree_insert(c, BTREE_ID_inodes, &packed.inode.k_i,
988                                  NULL, NULL,
989                                  BTREE_INSERT_NOFAIL|
990                                  BTREE_INSERT_LAZY_RW);
991 }
992
993 struct pathbuf {
994         size_t          nr;
995         size_t          size;
996
997         struct pathbuf_entry {
998                 u64     inum;
999         }               *entries;
1000 };
1001
1002 static int path_down(struct pathbuf *p, u64 inum)
1003 {
1004         if (p->nr == p->size) {
1005                 size_t new_size = max_t(size_t, 256UL, p->size * 2);
1006                 void *n = krealloc(p->entries,
1007                                    new_size * sizeof(p->entries[0]),
1008                                    GFP_KERNEL);
1009                 if (!n) {
1010                         return -ENOMEM;
1011                 }
1012
1013                 p->entries = n;
1014                 p->size = new_size;
1015         };
1016
1017         p->entries[p->nr++] = (struct pathbuf_entry) {
1018                 .inum = inum,
1019         };
1020         return 0;
1021 }
1022
1023 static int check_path(struct btree_trans *trans,
1024                       struct pathbuf *p,
1025                       struct bch_inode_unpacked *inode)
1026 {
1027         struct bch_fs *c = trans->c;
1028         u32 snapshot;
1029         size_t i;
1030         int ret = 0;
1031
1032         p->nr = 0;
1033
1034         while (inode->bi_inum != BCACHEFS_ROOT_INO) {
1035                 ret = lockrestart_do(trans,
1036                         inode_backpointer_exists(trans, inode));
1037                 if (ret < 0)
1038                         break;
1039
1040                 if (!ret) {
1041                         if (fsck_err(c,  "unreachable inode %llu, type %u nlink %u backptr %llu:%llu",
1042                                      inode->bi_inum,
1043                                      mode_to_type(inode->bi_mode),
1044                                      inode->bi_nlink,
1045                                      inode->bi_dir,
1046                                      inode->bi_dir_offset))
1047                                 ret = reattach_inode(trans, inode);
1048                         break;
1049                 }
1050                 ret = 0;
1051
1052                 if (!S_ISDIR(inode->bi_mode))
1053                         break;
1054
1055                 ret = path_down(p, inode->bi_inum);
1056                 if (ret) {
1057                         bch_err(c, "memory allocation failure");
1058                         return ret;
1059                 }
1060
1061                 for (i = 0; i < p->nr; i++) {
1062                         if (inode->bi_dir != p->entries[i].inum)
1063                                 continue;
1064
1065                         /* XXX print path */
1066                         if (!fsck_err(c, "directory structure loop"))
1067                                 return 0;
1068
1069                         ret = lockrestart_do(trans,
1070                                          remove_backpointer(trans, inode));
1071                         if (ret) {
1072                                 bch_err(c, "error removing dirent: %i", ret);
1073                                 break;
1074                         }
1075
1076                         ret = reattach_inode(trans, inode);
1077                         break;
1078                 }
1079
1080                 ret = lookup_inode(trans, inode->bi_dir, inode, &snapshot);
1081                 if (ret) {
1082                         /* Should have been caught in dirents pass */
1083                         bch_err(c, "error looking up parent directory: %i", ret);
1084                         break;
1085                 }
1086         }
1087 fsck_err:
1088         if (ret)
1089                 bch_err(c, "%s: err %i", __func__, ret);
1090         return ret;
1091 }
1092
1093 /*
1094  * Check for unreachable inodes, as well as loops in the directory structure:
1095  * After check_dirents(), if an inode backpointer doesn't exist that means it's
1096  * unreachable:
1097  */
1098 static int check_directory_structure(struct bch_fs *c)
1099 {
1100         struct btree_trans trans;
1101         struct btree_iter *iter;
1102         struct bkey_s_c k;
1103         struct bch_inode_unpacked u;
1104         struct pathbuf path = { 0, 0, NULL };
1105         int ret;
1106
1107         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1108
1109         for_each_btree_key(&trans, iter, BTREE_ID_inodes, POS_MIN, 0, k, ret) {
1110                 if (k.k->type != KEY_TYPE_inode)
1111                         continue;
1112
1113                 ret = bch2_inode_unpack(bkey_s_c_to_inode(k), &u);
1114                 if (ret) {
1115                         /* Should have been caught earlier in fsck: */
1116                         bch_err(c, "error unpacking inode %llu: %i", k.k->p.offset, ret);
1117                         break;
1118                 }
1119
1120                 ret = check_path(&trans, &path, &u);
1121                 if (ret)
1122                         break;
1123         }
1124         bch2_trans_iter_put(&trans, iter);
1125
1126         BUG_ON(ret == -EINTR);
1127
1128         kfree(path.entries);
1129
1130         return bch2_trans_exit(&trans) ?: ret;
1131 }
1132
1133 struct nlink {
1134         u32     count;
1135 };
1136
1137 typedef GENRADIX(struct nlink) nlink_table;
1138
1139 static void inc_link(struct bch_fs *c, nlink_table *links,
1140                      u64 range_start, u64 *range_end, u64 inum)
1141 {
1142         struct nlink *link;
1143
1144         if (inum < range_start || inum >= *range_end)
1145                 return;
1146
1147         if (inum - range_start >= SIZE_MAX / sizeof(struct nlink)) {
1148                 *range_end = inum;
1149                 return;
1150         }
1151
1152         link = genradix_ptr_alloc(links, inum - range_start, GFP_KERNEL);
1153         if (!link) {
1154                 bch_verbose(c, "allocation failed during fsck - will need another pass");
1155                 *range_end = inum;
1156                 return;
1157         }
1158
1159         link->count++;
1160 }
1161
1162 noinline_for_stack
1163 static int bch2_gc_walk_dirents(struct bch_fs *c, nlink_table *links,
1164                                u64 range_start, u64 *range_end)
1165 {
1166         struct btree_trans trans;
1167         struct btree_iter *iter;
1168         struct bkey_s_c k;
1169         struct bkey_s_c_dirent d;
1170         int ret;
1171
1172         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1173
1174         for_each_btree_key(&trans, iter, BTREE_ID_dirents, POS_MIN, 0, k, ret) {
1175                 switch (k.k->type) {
1176                 case KEY_TYPE_dirent:
1177                         d = bkey_s_c_to_dirent(k);
1178
1179                         if (d.v->d_type != DT_DIR)
1180                                 inc_link(c, links, range_start, range_end,
1181                                          le64_to_cpu(d.v->d_inum));
1182                         break;
1183                 }
1184
1185                 bch2_trans_cond_resched(&trans);
1186         }
1187         bch2_trans_iter_put(&trans, iter);
1188
1189         ret = bch2_trans_exit(&trans) ?: ret;
1190         if (ret)
1191                 bch_err(c, "error in fsck: btree error %i while walking dirents", ret);
1192
1193         return ret;
1194 }
1195
1196 static int check_inode_nlink(struct btree_trans *trans,
1197                              struct btree_iter *iter,
1198                              struct bkey_s_c_inode inode,
1199                              unsigned nlink)
1200 {
1201         struct bch_fs *c = trans->c;
1202         struct bch_inode_unpacked u;
1203         int ret = 0;
1204
1205         /*
1206          * Backpointer and directory structure checks are sufficient for
1207          * directories, since they can't have hardlinks:
1208          */
1209         if (S_ISDIR(le16_to_cpu(inode.v->bi_mode)))
1210                 return 0;
1211
1212         if (!nlink) {
1213                 bch_err(c, "no links found to inode %llu", inode.k->p.offset);
1214                 return -EINVAL;
1215         }
1216
1217         ret = bch2_inode_unpack(inode, &u);
1218
1219         /* Should never happen, checked by bch2_inode_invalid: */
1220         if (bch2_fs_inconsistent_on(ret, c,
1221                          "error unpacking inode %llu in fsck",
1222                          inode.k->p.inode))
1223                 return ret;
1224
1225         if (fsck_err_on(bch2_inode_nlink_get(&u) != nlink, c,
1226                         "inode %llu has wrong i_nlink (type %u i_nlink %u, should be %u)",
1227                         u.bi_inum, mode_to_type(u.bi_mode),
1228                         bch2_inode_nlink_get(&u), nlink)) {
1229                 bch2_inode_nlink_set(&u, nlink);
1230
1231                 ret = __bch2_trans_do(trans, NULL, NULL,
1232                                       BTREE_INSERT_NOFAIL|
1233                                       BTREE_INSERT_LAZY_RW,
1234                                 bch2_inode_write(trans, iter, &u));
1235                 if (ret)
1236                         bch_err(c, "error in fsck: error %i updating inode", ret);
1237         }
1238 fsck_err:
1239         return ret;
1240 }
1241
1242 noinline_for_stack
1243 static int bch2_gc_walk_inodes(struct bch_fs *c,
1244                                nlink_table *links,
1245                                u64 range_start, u64 range_end)
1246 {
1247         struct btree_trans trans;
1248         struct btree_iter *iter;
1249         struct bkey_s_c k;
1250         struct nlink *link;
1251         int ret = 0;
1252
1253         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
1254
1255         for_each_btree_key(&trans, iter, BTREE_ID_inodes,
1256                            POS(0, range_start), 0, k, ret) {
1257                 if (!k.k || k.k->p.offset >= range_end)
1258                         break;
1259
1260                 if (k.k->type != KEY_TYPE_inode)
1261                         continue;
1262
1263                 link = genradix_ptr(links, k.k->p.offset - range_start);
1264                 ret = check_inode_nlink(&trans, iter,
1265                                         bkey_s_c_to_inode(k), link ? link->count : 0);
1266                 if (ret)
1267                         break;
1268
1269         }
1270         bch2_trans_iter_put(&trans, iter);
1271         bch2_trans_exit(&trans);
1272
1273         if (ret)
1274                 bch_err(c, "error in fsck: btree error %i while walking inodes", ret);
1275
1276         return ret;
1277 }
1278
1279 noinline_for_stack
1280 static int check_nlinks(struct bch_fs *c)
1281 {
1282         nlink_table links;
1283         u64 this_iter_range_start, next_iter_range_start = 0;
1284         int ret = 0;
1285
1286         bch_verbose(c, "checking inode nlinks");
1287
1288         genradix_init(&links);
1289
1290         do {
1291                 this_iter_range_start = next_iter_range_start;
1292                 next_iter_range_start = U64_MAX;
1293
1294                 ret = bch2_gc_walk_dirents(c, &links,
1295                                           this_iter_range_start,
1296                                           &next_iter_range_start);
1297                 if (ret)
1298                         break;
1299
1300                 ret = bch2_gc_walk_inodes(c, &links,
1301                                          this_iter_range_start,
1302                                          next_iter_range_start);
1303                 if (ret)
1304                         break;
1305
1306                 genradix_free(&links);
1307         } while (next_iter_range_start != U64_MAX);
1308
1309         genradix_free(&links);
1310
1311         return ret;
1312 }
1313
1314 /*
1315  * Checks for inconsistencies that shouldn't happen, unless we have a bug.
1316  * Doesn't fix them yet, mainly because they haven't yet been observed:
1317  */
1318 int bch2_fsck_full(struct bch_fs *c)
1319 {
1320         struct bch_inode_unpacked root_inode;
1321
1322         return  check_inodes(c, true) ?:
1323                 check_extents(c) ?:
1324                 check_dirents(c) ?:
1325                 check_xattrs(c) ?:
1326                 check_root(c, &root_inode) ?:
1327                 check_directory_structure(c) ?:
1328                 check_nlinks(c);
1329 }
1330
1331 int bch2_fsck_walk_inodes_only(struct bch_fs *c)
1332 {
1333         return check_inodes(c, false);
1334 }