]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/recovery.c
cb2186a7d64e03f785421c137100c940b35c48e7
[bcachefs-tools-debian] / libbcachefs / recovery.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "backpointers.h"
5 #include "bkey_buf.h"
6 #include "alloc_background.h"
7 #include "btree_gc.h"
8 #include "btree_journal_iter.h"
9 #include "btree_update.h"
10 #include "btree_update_interior.h"
11 #include "btree_io.h"
12 #include "buckets.h"
13 #include "dirent.h"
14 #include "ec.h"
15 #include "errcode.h"
16 #include "error.h"
17 #include "fs-common.h"
18 #include "fsck.h"
19 #include "journal_io.h"
20 #include "journal_reclaim.h"
21 #include "journal_seq_blacklist.h"
22 #include "lru.h"
23 #include "move.h"
24 #include "quota.h"
25 #include "recovery.h"
26 #include "replicas.h"
27 #include "sb-clean.h"
28 #include "subvolume.h"
29 #include "super-io.h"
30
31 #include <linux/sort.h>
32 #include <linux/stat.h>
33
34 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
35
36 /* for -o reconstruct_alloc: */
37 static void drop_alloc_keys(struct journal_keys *keys)
38 {
39         size_t src, dst;
40
41         for (src = 0, dst = 0; src < keys->nr; src++)
42                 if (keys->d[src].btree_id != BTREE_ID_alloc)
43                         keys->d[dst++] = keys->d[src];
44
45         keys->nr = dst;
46 }
47
48 /*
49  * Btree node pointers have a field to stack a pointer to the in memory btree
50  * node; we need to zero out this field when reading in btree nodes, or when
51  * reading in keys from the journal:
52  */
53 static void zero_out_btree_mem_ptr(struct journal_keys *keys)
54 {
55         struct journal_key *i;
56
57         for (i = keys->d; i < keys->d + keys->nr; i++)
58                 if (i->k->k.type == KEY_TYPE_btree_ptr_v2)
59                         bkey_i_to_btree_ptr_v2(i->k)->v.mem_ptr = 0;
60 }
61
62 /* journal replay: */
63
64 static void replay_now_at(struct journal *j, u64 seq)
65 {
66         BUG_ON(seq < j->replay_journal_seq);
67
68         seq = min(seq, j->replay_journal_seq_end);
69
70         while (j->replay_journal_seq < seq)
71                 bch2_journal_pin_put(j, j->replay_journal_seq++);
72 }
73
74 static int bch2_journal_replay_key(struct btree_trans *trans,
75                                    struct journal_key *k)
76 {
77         struct btree_iter iter;
78         unsigned iter_flags =
79                 BTREE_ITER_INTENT|
80                 BTREE_ITER_NOT_EXTENTS;
81         unsigned update_flags = BTREE_TRIGGER_NORUN;
82         int ret;
83
84         /*
85          * BTREE_UPDATE_KEY_CACHE_RECLAIM disables key cache lookup/update to
86          * keep the key cache coherent with the underlying btree. Nothing
87          * besides the allocator is doing updates yet so we don't need key cache
88          * coherency for non-alloc btrees, and key cache fills for snapshots
89          * btrees use BTREE_ITER_FILTER_SNAPSHOTS, which isn't available until
90          * the snapshots recovery pass runs.
91          */
92         if (!k->level && k->btree_id == BTREE_ID_alloc)
93                 iter_flags |= BTREE_ITER_CACHED;
94         else
95                 update_flags |= BTREE_UPDATE_KEY_CACHE_RECLAIM;
96
97         bch2_trans_node_iter_init(trans, &iter, k->btree_id, k->k->k.p,
98                                   BTREE_MAX_DEPTH, k->level,
99                                   iter_flags);
100         ret = bch2_btree_iter_traverse(&iter);
101         if (ret)
102                 goto out;
103
104         /* Must be checked with btree locked: */
105         if (k->overwritten)
106                 goto out;
107
108         ret = bch2_trans_update(trans, &iter, k->k, update_flags);
109 out:
110         bch2_trans_iter_exit(trans, &iter);
111         return ret;
112 }
113
114 static int journal_sort_seq_cmp(const void *_l, const void *_r)
115 {
116         const struct journal_key *l = *((const struct journal_key **)_l);
117         const struct journal_key *r = *((const struct journal_key **)_r);
118
119         return cmp_int(l->journal_seq, r->journal_seq);
120 }
121
122 static int bch2_journal_replay(struct bch_fs *c)
123 {
124         struct journal_keys *keys = &c->journal_keys;
125         struct journal_key **keys_sorted, *k;
126         struct journal *j = &c->journal;
127         u64 start_seq   = c->journal_replay_seq_start;
128         u64 end_seq     = c->journal_replay_seq_start;
129         size_t i;
130         int ret;
131
132         move_gap(keys->d, keys->nr, keys->size, keys->gap, keys->nr);
133         keys->gap = keys->nr;
134
135         keys_sorted = kvmalloc_array(sizeof(*keys_sorted), keys->nr, GFP_KERNEL);
136         if (!keys_sorted)
137                 return -BCH_ERR_ENOMEM_journal_replay;
138
139         for (i = 0; i < keys->nr; i++)
140                 keys_sorted[i] = &keys->d[i];
141
142         sort(keys_sorted, keys->nr,
143              sizeof(keys_sorted[0]),
144              journal_sort_seq_cmp, NULL);
145
146         if (keys->nr) {
147                 ret = bch2_journal_log_msg(c, "Starting journal replay (%zu keys in entries %llu-%llu)",
148                                            keys->nr, start_seq, end_seq);
149                 if (ret)
150                         goto err;
151         }
152
153         for (i = 0; i < keys->nr; i++) {
154                 k = keys_sorted[i];
155
156                 cond_resched();
157
158                 replay_now_at(j, k->journal_seq);
159
160                 ret = bch2_trans_do(c, NULL, NULL,
161                                     BTREE_INSERT_LAZY_RW|
162                                     BTREE_INSERT_NOFAIL|
163                                     (!k->allocated
164                                      ? BTREE_INSERT_JOURNAL_REPLAY|BCH_WATERMARK_reclaim
165                                      : 0),
166                              bch2_journal_replay_key(&trans, k));
167                 if (ret) {
168                         bch_err(c, "journal replay: error while replaying key at btree %s level %u: %s",
169                                 bch2_btree_ids[k->btree_id], k->level, bch2_err_str(ret));
170                         goto err;
171                 }
172         }
173
174         replay_now_at(j, j->replay_journal_seq_end);
175         j->replay_journal_seq = 0;
176
177         bch2_journal_set_replay_done(j);
178         bch2_journal_flush_all_pins(j);
179         ret = bch2_journal_error(j);
180
181         if (keys->nr && !ret)
182                 bch2_journal_log_msg(c, "journal replay finished");
183 err:
184         kvfree(keys_sorted);
185
186         if (ret)
187                 bch_err_fn(c, ret);
188         return ret;
189 }
190
191 /* journal replay early: */
192
193 static int journal_replay_entry_early(struct bch_fs *c,
194                                       struct jset_entry *entry)
195 {
196         int ret = 0;
197
198         switch (entry->type) {
199         case BCH_JSET_ENTRY_btree_root: {
200                 struct btree_root *r;
201
202                 while (entry->btree_id >= c->btree_roots_extra.nr + BTREE_ID_NR) {
203                         ret = darray_push(&c->btree_roots_extra, (struct btree_root) { NULL });
204                         if (ret)
205                                 return ret;
206                 }
207
208                 r = bch2_btree_id_root(c, entry->btree_id);
209
210                 if (entry->u64s) {
211                         r->level = entry->level;
212                         bkey_copy(&r->key, &entry->start[0]);
213                         r->error = 0;
214                 } else {
215                         r->error = -EIO;
216                 }
217                 r->alive = true;
218                 break;
219         }
220         case BCH_JSET_ENTRY_usage: {
221                 struct jset_entry_usage *u =
222                         container_of(entry, struct jset_entry_usage, entry);
223
224                 switch (entry->btree_id) {
225                 case BCH_FS_USAGE_reserved:
226                         if (entry->level < BCH_REPLICAS_MAX)
227                                 c->usage_base->persistent_reserved[entry->level] =
228                                         le64_to_cpu(u->v);
229                         break;
230                 case BCH_FS_USAGE_inodes:
231                         c->usage_base->nr_inodes = le64_to_cpu(u->v);
232                         break;
233                 case BCH_FS_USAGE_key_version:
234                         atomic64_set(&c->key_version,
235                                      le64_to_cpu(u->v));
236                         break;
237                 }
238
239                 break;
240         }
241         case BCH_JSET_ENTRY_data_usage: {
242                 struct jset_entry_data_usage *u =
243                         container_of(entry, struct jset_entry_data_usage, entry);
244
245                 ret = bch2_replicas_set_usage(c, &u->r,
246                                               le64_to_cpu(u->v));
247                 break;
248         }
249         case BCH_JSET_ENTRY_dev_usage: {
250                 struct jset_entry_dev_usage *u =
251                         container_of(entry, struct jset_entry_dev_usage, entry);
252                 struct bch_dev *ca = bch_dev_bkey_exists(c, le32_to_cpu(u->dev));
253                 unsigned i, nr_types = jset_entry_dev_usage_nr_types(u);
254
255                 ca->usage_base->buckets_ec              = le64_to_cpu(u->buckets_ec);
256
257                 for (i = 0; i < min_t(unsigned, nr_types, BCH_DATA_NR); i++) {
258                         ca->usage_base->d[i].buckets    = le64_to_cpu(u->d[i].buckets);
259                         ca->usage_base->d[i].sectors    = le64_to_cpu(u->d[i].sectors);
260                         ca->usage_base->d[i].fragmented = le64_to_cpu(u->d[i].fragmented);
261                 }
262
263                 break;
264         }
265         case BCH_JSET_ENTRY_blacklist: {
266                 struct jset_entry_blacklist *bl_entry =
267                         container_of(entry, struct jset_entry_blacklist, entry);
268
269                 ret = bch2_journal_seq_blacklist_add(c,
270                                 le64_to_cpu(bl_entry->seq),
271                                 le64_to_cpu(bl_entry->seq) + 1);
272                 break;
273         }
274         case BCH_JSET_ENTRY_blacklist_v2: {
275                 struct jset_entry_blacklist_v2 *bl_entry =
276                         container_of(entry, struct jset_entry_blacklist_v2, entry);
277
278                 ret = bch2_journal_seq_blacklist_add(c,
279                                 le64_to_cpu(bl_entry->start),
280                                 le64_to_cpu(bl_entry->end) + 1);
281                 break;
282         }
283         case BCH_JSET_ENTRY_clock: {
284                 struct jset_entry_clock *clock =
285                         container_of(entry, struct jset_entry_clock, entry);
286
287                 atomic64_set(&c->io_clock[clock->rw].now, le64_to_cpu(clock->time));
288         }
289         }
290
291         return ret;
292 }
293
294 static int journal_replay_early(struct bch_fs *c,
295                                 struct bch_sb_field_clean *clean)
296 {
297         struct jset_entry *entry;
298         int ret;
299
300         if (clean) {
301                 for (entry = clean->start;
302                      entry != vstruct_end(&clean->field);
303                      entry = vstruct_next(entry)) {
304                         ret = journal_replay_entry_early(c, entry);
305                         if (ret)
306                                 return ret;
307                 }
308         } else {
309                 struct genradix_iter iter;
310                 struct journal_replay *i, **_i;
311
312                 genradix_for_each(&c->journal_entries, iter, _i) {
313                         i = *_i;
314
315                         if (!i || i->ignore)
316                                 continue;
317
318                         vstruct_for_each(&i->j, entry) {
319                                 ret = journal_replay_entry_early(c, entry);
320                                 if (ret)
321                                         return ret;
322                         }
323                 }
324         }
325
326         bch2_fs_usage_initialize(c);
327
328         return 0;
329 }
330
331 /* sb clean section: */
332
333 static bool btree_id_is_alloc(enum btree_id id)
334 {
335         switch (id) {
336         case BTREE_ID_alloc:
337         case BTREE_ID_backpointers:
338         case BTREE_ID_need_discard:
339         case BTREE_ID_freespace:
340         case BTREE_ID_bucket_gens:
341                 return true;
342         default:
343                 return false;
344         }
345 }
346
347 static int read_btree_roots(struct bch_fs *c)
348 {
349         unsigned i;
350         int ret = 0;
351
352         for (i = 0; i < btree_id_nr_alive(c); i++) {
353                 struct btree_root *r = bch2_btree_id_root(c, i);
354
355                 if (!r->alive)
356                         continue;
357
358                 if (btree_id_is_alloc(i) &&
359                     c->opts.reconstruct_alloc) {
360                         c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
361                         continue;
362                 }
363
364                 if (r->error) {
365                         __fsck_err(c, btree_id_is_alloc(i)
366                                    ? FSCK_CAN_IGNORE : 0,
367                                    "invalid btree root %s",
368                                    bch2_btree_ids[i]);
369                         if (i == BTREE_ID_alloc)
370                                 c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
371                 }
372
373                 ret = bch2_btree_root_read(c, i, &r->key, r->level);
374                 if (ret) {
375                         __fsck_err(c,
376                                    btree_id_is_alloc(i)
377                                    ? FSCK_CAN_IGNORE : 0,
378                                    "error reading btree root %s",
379                                    bch2_btree_ids[i]);
380                         if (btree_id_is_alloc(i))
381                                 c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
382                 }
383         }
384
385         for (i = 0; i < BTREE_ID_NR; i++) {
386                 struct btree_root *r = bch2_btree_id_root(c, i);
387
388                 if (!r->b) {
389                         r->alive = false;
390                         r->level = 0;
391                         bch2_btree_root_alloc(c, i);
392                 }
393         }
394 fsck_err:
395         return ret;
396 }
397
398 static int bch2_initialize_subvolumes(struct bch_fs *c)
399 {
400         struct bkey_i_snapshot_tree     root_tree;
401         struct bkey_i_snapshot          root_snapshot;
402         struct bkey_i_subvolume         root_volume;
403         int ret;
404
405         bkey_snapshot_tree_init(&root_tree.k_i);
406         root_tree.k.p.offset            = 1;
407         root_tree.v.master_subvol       = cpu_to_le32(1);
408         root_tree.v.root_snapshot       = cpu_to_le32(U32_MAX);
409
410         bkey_snapshot_init(&root_snapshot.k_i);
411         root_snapshot.k.p.offset = U32_MAX;
412         root_snapshot.v.flags   = 0;
413         root_snapshot.v.parent  = 0;
414         root_snapshot.v.subvol  = cpu_to_le32(BCACHEFS_ROOT_SUBVOL);
415         root_snapshot.v.tree    = cpu_to_le32(1);
416         SET_BCH_SNAPSHOT_SUBVOL(&root_snapshot.v, true);
417
418         bkey_subvolume_init(&root_volume.k_i);
419         root_volume.k.p.offset = BCACHEFS_ROOT_SUBVOL;
420         root_volume.v.flags     = 0;
421         root_volume.v.snapshot  = cpu_to_le32(U32_MAX);
422         root_volume.v.inode     = cpu_to_le64(BCACHEFS_ROOT_INO);
423
424         ret =   bch2_btree_insert(c, BTREE_ID_snapshot_trees,
425                                   &root_tree.k_i,
426                                   NULL, NULL, 0) ?:
427                 bch2_btree_insert(c, BTREE_ID_snapshots,
428                                   &root_snapshot.k_i,
429                                   NULL, NULL, 0) ?:
430                 bch2_btree_insert(c, BTREE_ID_subvolumes,
431                                   &root_volume.k_i,
432                                   NULL, NULL, 0);
433         if (ret)
434                 bch_err_fn(c, ret);
435         return ret;
436 }
437
438 static int __bch2_fs_upgrade_for_subvolumes(struct btree_trans *trans)
439 {
440         struct btree_iter iter;
441         struct bkey_s_c k;
442         struct bch_inode_unpacked inode;
443         int ret;
444
445         k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
446                                SPOS(0, BCACHEFS_ROOT_INO, U32_MAX), 0);
447         ret = bkey_err(k);
448         if (ret)
449                 return ret;
450
451         if (!bkey_is_inode(k.k)) {
452                 bch_err(trans->c, "root inode not found");
453                 ret = -BCH_ERR_ENOENT_inode;
454                 goto err;
455         }
456
457         ret = bch2_inode_unpack(k, &inode);
458         BUG_ON(ret);
459
460         inode.bi_subvol = BCACHEFS_ROOT_SUBVOL;
461
462         ret = bch2_inode_write(trans, &iter, &inode);
463 err:
464         bch2_trans_iter_exit(trans, &iter);
465         return ret;
466 }
467
468 /* set bi_subvol on root inode */
469 noinline_for_stack
470 static int bch2_fs_upgrade_for_subvolumes(struct bch_fs *c)
471 {
472         int ret = bch2_trans_do(c, NULL, NULL, BTREE_INSERT_LAZY_RW,
473                                 __bch2_fs_upgrade_for_subvolumes(&trans));
474         if (ret)
475                 bch_err_fn(c, ret);
476         return ret;
477 }
478
479 const char * const bch2_recovery_passes[] = {
480 #define x(_fn, _when)   #_fn,
481         BCH_RECOVERY_PASSES()
482 #undef x
483         NULL
484 };
485
486 static int bch2_check_allocations(struct bch_fs *c)
487 {
488         return bch2_gc(c, true, c->opts.norecovery);
489 }
490
491 static int bch2_set_may_go_rw(struct bch_fs *c)
492 {
493         set_bit(BCH_FS_MAY_GO_RW, &c->flags);
494         return 0;
495 }
496
497 struct recovery_pass_fn {
498         int             (*fn)(struct bch_fs *);
499         unsigned        when;
500 };
501
502 static struct recovery_pass_fn recovery_pass_fns[] = {
503 #define x(_fn, _when)   { .fn = bch2_##_fn, .when = _when },
504         BCH_RECOVERY_PASSES()
505 #undef x
506 };
507
508 static void check_version_upgrade(struct bch_fs *c)
509 {
510         unsigned latest_compatible = bch2_version_compatible(c->sb.version);
511         unsigned latest_version = bcachefs_metadata_version_current;
512         unsigned old_version = c->sb.version_upgrade_complete ?: c->sb.version;
513         unsigned new_version = 0;
514         u64 recovery_passes;
515
516         if (old_version < bcachefs_metadata_required_upgrade_below) {
517                 if (c->opts.version_upgrade == BCH_VERSION_UPGRADE_incompatible ||
518                     latest_compatible < bcachefs_metadata_required_upgrade_below)
519                         new_version = latest_version;
520                 else
521                         new_version = latest_compatible;
522         } else {
523                 switch (c->opts.version_upgrade) {
524                 case BCH_VERSION_UPGRADE_compatible:
525                         new_version = latest_compatible;
526                         break;
527                 case BCH_VERSION_UPGRADE_incompatible:
528                         new_version = latest_version;
529                         break;
530                 case BCH_VERSION_UPGRADE_none:
531                         new_version = old_version;
532                         break;
533                 }
534         }
535
536         if (new_version > old_version) {
537                 struct printbuf buf = PRINTBUF;
538
539                 if (old_version < bcachefs_metadata_required_upgrade_below)
540                         prt_str(&buf, "Version upgrade required:\n");
541
542                 if (old_version != c->sb.version) {
543                         prt_str(&buf, "Version upgrade from ");
544                         bch2_version_to_text(&buf, c->sb.version_upgrade_complete);
545                         prt_str(&buf, " to ");
546                         bch2_version_to_text(&buf, c->sb.version);
547                         prt_str(&buf, " incomplete\n");
548                 }
549
550                 prt_printf(&buf, "Doing %s version upgrade from ",
551                            BCH_VERSION_MAJOR(old_version) != BCH_VERSION_MAJOR(new_version)
552                            ? "incompatible" : "compatible");
553                 bch2_version_to_text(&buf, old_version);
554                 prt_str(&buf, " to ");
555                 bch2_version_to_text(&buf, new_version);
556                 prt_newline(&buf);
557
558                 recovery_passes = bch2_upgrade_recovery_passes(c, old_version, new_version);
559                 if (recovery_passes) {
560                         if ((recovery_passes & RECOVERY_PASS_ALL_FSCK) == RECOVERY_PASS_ALL_FSCK)
561                                 prt_str(&buf, "fsck required");
562                         else {
563                                 prt_str(&buf, "running recovery passses: ");
564                                 prt_bitflags(&buf, bch2_recovery_passes, recovery_passes);
565                         }
566
567                         c->recovery_passes_explicit |= recovery_passes;
568                         c->opts.fix_errors = FSCK_FIX_yes;
569                 }
570
571                 bch_info(c, "%s", buf.buf);
572
573                 mutex_lock(&c->sb_lock);
574                 bch2_sb_upgrade(c, new_version);
575                 mutex_unlock(&c->sb_lock);
576
577                 printbuf_exit(&buf);
578         }
579 }
580
581 u64 bch2_fsck_recovery_passes(void)
582 {
583         u64 ret = 0;
584
585         for (unsigned i = 0; i < ARRAY_SIZE(recovery_pass_fns); i++)
586                 if (recovery_pass_fns[i].when & PASS_FSCK)
587                         ret |= BIT_ULL(i);
588         return ret;
589 }
590
591 static bool should_run_recovery_pass(struct bch_fs *c, enum bch_recovery_pass pass)
592 {
593         struct recovery_pass_fn *p = recovery_pass_fns + c->curr_recovery_pass;
594
595         if (c->opts.norecovery && pass > BCH_RECOVERY_PASS_snapshots_read)
596                 return false;
597         if (c->recovery_passes_explicit & BIT_ULL(pass))
598                 return true;
599         if ((p->when & PASS_FSCK) && c->opts.fsck)
600                 return true;
601         if ((p->when & PASS_UNCLEAN) && !c->sb.clean)
602                 return true;
603         if (p->when & PASS_ALWAYS)
604                 return true;
605         return false;
606 }
607
608 static int bch2_run_recovery_pass(struct bch_fs *c, enum bch_recovery_pass pass)
609 {
610         int ret;
611
612         c->curr_recovery_pass = pass;
613
614         if (should_run_recovery_pass(c, pass)) {
615                 struct recovery_pass_fn *p = recovery_pass_fns + pass;
616
617                 if (!(p->when & PASS_SILENT))
618                         printk(KERN_INFO bch2_log_msg(c, "%s..."),
619                                bch2_recovery_passes[pass]);
620                 ret = p->fn(c);
621                 if (ret)
622                         return ret;
623                 if (!(p->when & PASS_SILENT))
624                         printk(KERN_CONT " done\n");
625
626                 c->recovery_passes_complete |= BIT_ULL(pass);
627         }
628
629         return 0;
630 }
631
632 static int bch2_run_recovery_passes(struct bch_fs *c)
633 {
634         int ret = 0;
635
636         while (c->curr_recovery_pass < ARRAY_SIZE(recovery_pass_fns)) {
637                 ret = bch2_run_recovery_pass(c, c->curr_recovery_pass);
638                 if (bch2_err_matches(ret, BCH_ERR_restart_recovery))
639                         continue;
640                 if (ret)
641                         break;
642                 c->curr_recovery_pass++;
643         }
644
645         return ret;
646 }
647
648 int bch2_fs_recovery(struct bch_fs *c)
649 {
650         struct bch_sb_field_clean *clean = NULL;
651         struct jset *last_journal_entry = NULL;
652         u64 last_seq, blacklist_seq, journal_seq;
653         bool write_sb = false;
654         int ret = 0;
655
656         if (c->sb.clean) {
657                 clean = bch2_read_superblock_clean(c);
658                 ret = PTR_ERR_OR_ZERO(clean);
659                 if (ret)
660                         goto err;
661
662                 bch_info(c, "recovering from clean shutdown, journal seq %llu",
663                          le64_to_cpu(clean->journal_seq));
664         } else {
665                 bch_info(c, "recovering from unclean shutdown");
666         }
667
668         if (!(c->sb.features & (1ULL << BCH_FEATURE_new_extent_overwrite))) {
669                 bch_err(c, "feature new_extent_overwrite not set, filesystem no longer supported");
670                 ret = -EINVAL;
671                 goto err;
672         }
673
674         if (!c->sb.clean &&
675             !(c->sb.features & (1ULL << BCH_FEATURE_extents_above_btree_updates))) {
676                 bch_err(c, "filesystem needs recovery from older version; run fsck from older bcachefs-tools to fix");
677                 ret = -EINVAL;
678                 goto err;
679         }
680
681         if (c->opts.fsck || !(c->opts.nochanges && c->opts.norecovery))
682                 check_version_upgrade(c);
683
684         if (c->opts.fsck && c->opts.norecovery) {
685                 bch_err(c, "cannot select both norecovery and fsck");
686                 ret = -EINVAL;
687                 goto err;
688         }
689
690         ret = bch2_blacklist_table_initialize(c);
691         if (ret) {
692                 bch_err(c, "error initializing blacklist table");
693                 goto err;
694         }
695
696         if (!c->sb.clean || c->opts.fsck || c->opts.keep_journal) {
697                 struct genradix_iter iter;
698                 struct journal_replay **i;
699
700                 bch_verbose(c, "starting journal read");
701                 ret = bch2_journal_read(c, &last_seq, &blacklist_seq, &journal_seq);
702                 if (ret)
703                         goto err;
704
705                 /*
706                  * note: cmd_list_journal needs the blacklist table fully up to date so
707                  * it can asterisk ignored journal entries:
708                  */
709                 if (c->opts.read_journal_only)
710                         goto out;
711
712                 genradix_for_each_reverse(&c->journal_entries, iter, i)
713                         if (*i && !(*i)->ignore) {
714                                 last_journal_entry = &(*i)->j;
715                                 break;
716                         }
717
718                 if (mustfix_fsck_err_on(c->sb.clean &&
719                                         last_journal_entry &&
720                                         !journal_entry_empty(last_journal_entry), c,
721                                 "filesystem marked clean but journal not empty")) {
722                         c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
723                         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
724                         c->sb.clean = false;
725                 }
726
727                 if (!last_journal_entry) {
728                         fsck_err_on(!c->sb.clean, c, "no journal entries found");
729                         if (clean)
730                                 goto use_clean;
731
732                         genradix_for_each_reverse(&c->journal_entries, iter, i)
733                                 if (*i) {
734                                         last_journal_entry = &(*i)->j;
735                                         (*i)->ignore = false;
736                                         break;
737                                 }
738                 }
739
740                 ret = bch2_journal_keys_sort(c);
741                 if (ret)
742                         goto err;
743
744                 if (c->sb.clean && last_journal_entry) {
745                         ret = bch2_verify_superblock_clean(c, &clean,
746                                                       last_journal_entry);
747                         if (ret)
748                                 goto err;
749                 }
750         } else {
751 use_clean:
752                 if (!clean) {
753                         bch_err(c, "no superblock clean section found");
754                         ret = -BCH_ERR_fsck_repair_impossible;
755                         goto err;
756
757                 }
758                 blacklist_seq = journal_seq = le64_to_cpu(clean->journal_seq) + 1;
759         }
760
761         c->journal_replay_seq_start     = last_seq;
762         c->journal_replay_seq_end       = blacklist_seq - 1;;
763
764         if (c->opts.reconstruct_alloc) {
765                 c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
766                 drop_alloc_keys(&c->journal_keys);
767         }
768
769         zero_out_btree_mem_ptr(&c->journal_keys);
770
771         ret = journal_replay_early(c, clean);
772         if (ret)
773                 goto err;
774
775         /*
776          * After an unclean shutdown, skip then next few journal sequence
777          * numbers as they may have been referenced by btree writes that
778          * happened before their corresponding journal writes - those btree
779          * writes need to be ignored, by skipping and blacklisting the next few
780          * journal sequence numbers:
781          */
782         if (!c->sb.clean)
783                 journal_seq += 8;
784
785         if (blacklist_seq != journal_seq) {
786                 ret =   bch2_journal_log_msg(c, "blacklisting entries %llu-%llu",
787                                              blacklist_seq, journal_seq) ?:
788                         bch2_journal_seq_blacklist_add(c,
789                                         blacklist_seq, journal_seq);
790                 if (ret) {
791                         bch_err(c, "error creating new journal seq blacklist entry");
792                         goto err;
793                 }
794         }
795
796         ret =   bch2_journal_log_msg(c, "starting journal at entry %llu, replaying %llu-%llu",
797                                      journal_seq, last_seq, blacklist_seq - 1) ?:
798                 bch2_fs_journal_start(&c->journal, journal_seq);
799         if (ret)
800                 goto err;
801
802         if (c->opts.reconstruct_alloc)
803                 bch2_journal_log_msg(c, "dropping alloc info");
804
805         /*
806          * Skip past versions that might have possibly been used (as nonces),
807          * but hadn't had their pointers written:
808          */
809         if (c->sb.encryption_type && !c->sb.clean)
810                 atomic64_add(1 << 16, &c->key_version);
811
812         ret = read_btree_roots(c);
813         if (ret)
814                 goto err;
815
816         if (c->opts.fsck &&
817             (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) ||
818              BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb)))
819                 c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_topology);
820
821         ret = bch2_run_recovery_passes(c);
822         if (ret)
823                 goto err;
824
825         /* If we fixed errors, verify that fs is actually clean now: */
826         if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) &&
827             test_bit(BCH_FS_ERRORS_FIXED, &c->flags) &&
828             !test_bit(BCH_FS_ERRORS_NOT_FIXED, &c->flags) &&
829             !test_bit(BCH_FS_ERROR, &c->flags)) {
830                 bch_info(c, "Fixed errors, running fsck a second time to verify fs is clean");
831                 clear_bit(BCH_FS_ERRORS_FIXED, &c->flags);
832
833                 c->curr_recovery_pass = BCH_RECOVERY_PASS_check_alloc_info;
834
835                 ret = bch2_run_recovery_passes(c);
836                 if (ret)
837                         goto err;
838
839                 if (test_bit(BCH_FS_ERRORS_FIXED, &c->flags) ||
840                     test_bit(BCH_FS_ERRORS_NOT_FIXED, &c->flags)) {
841                         bch_err(c, "Second fsck run was not clean");
842                         set_bit(BCH_FS_ERRORS_NOT_FIXED, &c->flags);
843                 }
844
845                 set_bit(BCH_FS_ERRORS_FIXED, &c->flags);
846         }
847
848         if (enabled_qtypes(c)) {
849                 bch_verbose(c, "reading quotas");
850                 ret = bch2_fs_quota_read(c);
851                 if (ret)
852                         goto err;
853                 bch_verbose(c, "quotas done");
854         }
855
856         mutex_lock(&c->sb_lock);
857         if (BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb) != c->sb.version) {
858                 SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, c->sb.version);
859                 write_sb = true;
860         }
861
862         if (!test_bit(BCH_FS_ERROR, &c->flags)) {
863                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_info);
864                 write_sb = true;
865         }
866
867         if (c->opts.fsck &&
868             !test_bit(BCH_FS_ERROR, &c->flags) &&
869             !test_bit(BCH_FS_ERRORS_NOT_FIXED, &c->flags)) {
870                 SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 0);
871                 SET_BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb, 0);
872                 write_sb = true;
873         }
874
875         if (write_sb)
876                 bch2_write_super(c);
877         mutex_unlock(&c->sb_lock);
878
879         if (!(c->sb.compat & (1ULL << BCH_COMPAT_extents_above_btree_updates_done)) ||
880             c->sb.version_min < bcachefs_metadata_version_btree_ptr_sectors_written) {
881                 struct bch_move_stats stats;
882
883                 bch2_move_stats_init(&stats, "recovery");
884
885                 bch_info(c, "scanning for old btree nodes");
886                 ret =   bch2_fs_read_write(c) ?:
887                         bch2_scan_old_btree_nodes(c, &stats);
888                 if (ret)
889                         goto err;
890                 bch_info(c, "scanning for old btree nodes done");
891         }
892
893         if (c->journal_seq_blacklist_table &&
894             c->journal_seq_blacklist_table->nr > 128)
895                 queue_work(system_long_wq, &c->journal_seq_blacklist_gc_work);
896
897         ret = 0;
898 out:
899         set_bit(BCH_FS_FSCK_DONE, &c->flags);
900         bch2_flush_fsck_errs(c);
901
902         if (!c->opts.keep_journal &&
903             test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags)) {
904                 bch2_journal_keys_free(&c->journal_keys);
905                 bch2_journal_entries_free(c);
906         }
907         kfree(clean);
908
909         if (!ret && test_bit(BCH_FS_HAVE_DELETED_SNAPSHOTS, &c->flags)) {
910                 bch2_fs_read_write_early(c);
911                 bch2_delete_dead_snapshots_async(c);
912         }
913
914         if (ret)
915                 bch_err_fn(c, ret);
916         return ret;
917 err:
918 fsck_err:
919         bch2_fs_emergency_read_only(c);
920         goto out;
921 }
922
923 int bch2_fs_initialize(struct bch_fs *c)
924 {
925         struct bch_inode_unpacked root_inode, lostfound_inode;
926         struct bkey_inode_buf packed_inode;
927         struct qstr lostfound = QSTR("lost+found");
928         struct bch_dev *ca;
929         unsigned i;
930         int ret;
931
932         bch_notice(c, "initializing new filesystem");
933
934         mutex_lock(&c->sb_lock);
935         c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
936         c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
937
938         bch2_sb_maybe_downgrade(c);
939
940         if (c->opts.version_upgrade != BCH_VERSION_UPGRADE_none) {
941                 bch2_sb_upgrade(c, bcachefs_metadata_version_current);
942                 SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, bcachefs_metadata_version_current);
943                 bch2_write_super(c);
944         }
945         mutex_unlock(&c->sb_lock);
946
947         c->curr_recovery_pass = ARRAY_SIZE(recovery_pass_fns);
948         set_bit(BCH_FS_MAY_GO_RW, &c->flags);
949         set_bit(BCH_FS_FSCK_DONE, &c->flags);
950
951         for (i = 0; i < BTREE_ID_NR; i++)
952                 bch2_btree_root_alloc(c, i);
953
954         for_each_online_member(ca, c, i)
955                 bch2_dev_usage_init(ca);
956
957         for_each_online_member(ca, c, i) {
958                 ret = bch2_dev_journal_alloc(ca);
959                 if (ret) {
960                         percpu_ref_put(&ca->io_ref);
961                         goto err;
962                 }
963         }
964
965         /*
966          * journal_res_get() will crash if called before this has
967          * set up the journal.pin FIFO and journal.cur pointer:
968          */
969         bch2_fs_journal_start(&c->journal, 1);
970         bch2_journal_set_replay_done(&c->journal);
971
972         ret = bch2_fs_read_write_early(c);
973         if (ret)
974                 goto err;
975
976         /*
977          * Write out the superblock and journal buckets, now that we can do
978          * btree updates
979          */
980         bch_verbose(c, "marking superblocks");
981         for_each_member_device(ca, c, i) {
982                 ret = bch2_trans_mark_dev_sb(c, ca);
983                 if (ret) {
984                         percpu_ref_put(&ca->ref);
985                         goto err;
986                 }
987
988                 ca->new_fs_bucket_idx = 0;
989         }
990
991         ret = bch2_fs_freespace_init(c);
992         if (ret)
993                 goto err;
994
995         ret = bch2_initialize_subvolumes(c);
996         if (ret)
997                 goto err;
998
999         bch_verbose(c, "reading snapshots table");
1000         ret = bch2_snapshots_read(c);
1001         if (ret)
1002                 goto err;
1003         bch_verbose(c, "reading snapshots done");
1004
1005         bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755, 0, NULL);
1006         root_inode.bi_inum      = BCACHEFS_ROOT_INO;
1007         root_inode.bi_subvol    = BCACHEFS_ROOT_SUBVOL;
1008         bch2_inode_pack(&packed_inode, &root_inode);
1009         packed_inode.inode.k.p.snapshot = U32_MAX;
1010
1011         ret = bch2_btree_insert(c, BTREE_ID_inodes,
1012                                 &packed_inode.inode.k_i,
1013                                 NULL, NULL, 0);
1014         if (ret) {
1015                 bch_err_msg(c, ret, "creating root directory");
1016                 goto err;
1017         }
1018
1019         bch2_inode_init_early(c, &lostfound_inode);
1020
1021         ret = bch2_trans_do(c, NULL, NULL, 0,
1022                 bch2_create_trans(&trans,
1023                                   BCACHEFS_ROOT_SUBVOL_INUM,
1024                                   &root_inode, &lostfound_inode,
1025                                   &lostfound,
1026                                   0, 0, S_IFDIR|0700, 0,
1027                                   NULL, NULL, (subvol_inum) { 0 }, 0));
1028         if (ret) {
1029                 bch_err_msg(c, ret, "creating lost+found");
1030                 goto err;
1031         }
1032
1033         if (enabled_qtypes(c)) {
1034                 ret = bch2_fs_quota_read(c);
1035                 if (ret)
1036                         goto err;
1037         }
1038
1039         ret = bch2_journal_flush(&c->journal);
1040         if (ret) {
1041                 bch_err_msg(c, ret, "writing first journal entry");
1042                 goto err;
1043         }
1044
1045         mutex_lock(&c->sb_lock);
1046         SET_BCH_SB_INITIALIZED(c->disk_sb.sb, true);
1047         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
1048
1049         bch2_write_super(c);
1050         mutex_unlock(&c->sb_lock);
1051
1052         return 0;
1053 err:
1054         bch_err_fn(ca, ret);
1055         return ret;
1056 }