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