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