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