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