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