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