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