]> git.sesse.net Git - bcachefs-tools-debian/blobdiff - libbcachefs/recovery.c
Update bcachefs sources to 021e62a098 bcachefs: Fix error in filesystem initialization
[bcachefs-tools-debian] / libbcachefs / recovery.c
index 23f3ed54faddd4c9d04ec828771680ed486c1ded..0b3521c9cc19ef3ba285805a05de94bcc8bfd717 100644 (file)
 
 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
 
+/* for -o reconstruct_alloc: */
+static void drop_alloc_keys(struct journal_keys *keys)
+{
+       size_t src, dst;
+
+       for (src = 0, dst = 0; src < keys->nr; src++)
+               if (keys->d[src].btree_id != BTREE_ID_ALLOC)
+                       keys->d[dst++] = keys->d[src];
+
+       keys->nr = dst;
+}
+
 /* iterate over keys read from the journal: */
 
-struct journal_iter bch2_journal_iter_init(struct journal_keys *keys,
-                                          enum btree_id id)
+static struct journal_key *journal_key_search(struct journal_keys *journal_keys,
+                                             enum btree_id id, unsigned level,
+                                             struct bpos pos)
+{
+       size_t l = 0, r = journal_keys->nr, m;
+
+       while (l < r) {
+               m = l + ((r - l) >> 1);
+               if ((cmp_int(id,        journal_keys->d[m].btree_id) ?:
+                    cmp_int(level,     journal_keys->d[m].level) ?:
+                    bkey_cmp(pos,      journal_keys->d[m].k->k.p)) > 0)
+                       l = m + 1;
+               else
+                       r = m;
+       }
+
+       BUG_ON(l < journal_keys->nr &&
+              (cmp_int(id,     journal_keys->d[l].btree_id) ?:
+               cmp_int(level,  journal_keys->d[l].level) ?:
+               bkey_cmp(pos,   journal_keys->d[l].k->k.p)) > 0);
+
+       BUG_ON(l &&
+              (cmp_int(id,     journal_keys->d[l - 1].btree_id) ?:
+               cmp_int(level,  journal_keys->d[l - 1].level) ?:
+               bkey_cmp(pos,   journal_keys->d[l - 1].k->k.p)) <= 0);
+
+       return l < journal_keys->nr ? journal_keys->d + l : NULL;
+}
+
+static struct bkey_i *bch2_journal_iter_peek(struct journal_iter *iter)
+{
+       if (iter->k &&
+           iter->k < iter->keys->d + iter->keys->nr &&
+           iter->k->btree_id   == iter->btree_id &&
+           iter->k->level      == iter->level)
+               return iter->k->k;
+
+       iter->k = NULL;
+       return NULL;
+}
+
+static void bch2_journal_iter_advance(struct journal_iter *iter)
+{
+       if (iter->k)
+               iter->k++;
+}
+
+static void bch2_journal_iter_init(struct journal_iter *iter,
+                                  struct journal_keys *journal_keys,
+                                  enum btree_id id, unsigned level,
+                                  struct bpos pos)
+{
+       iter->btree_id  = id;
+       iter->level     = level;
+       iter->keys      = journal_keys;
+       iter->k         = journal_key_search(journal_keys, id, level, pos);
+}
+
+static struct bkey_s_c bch2_journal_iter_peek_btree(struct btree_and_journal_iter *iter)
+{
+       return iter->btree
+               ? bch2_btree_iter_peek(iter->btree)
+               : bch2_btree_node_iter_peek_unpack(&iter->node_iter,
+                                                  iter->b, &iter->unpacked);
+}
+
+static void bch2_journal_iter_advance_btree(struct btree_and_journal_iter *iter)
+{
+       if (iter->btree)
+               bch2_btree_iter_next(iter->btree);
+       else
+               bch2_btree_node_iter_advance(&iter->node_iter, iter->b);
+}
+
+void bch2_btree_and_journal_iter_advance(struct btree_and_journal_iter *iter)
 {
-       return (struct journal_iter) {
-               .keys           = keys,
-               .k              = keys->d,
-               .btree_id       = id,
-       };
+       switch (iter->last) {
+       case none:
+               break;
+       case btree:
+               bch2_journal_iter_advance_btree(iter);
+               break;
+       case journal:
+               bch2_journal_iter_advance(&iter->journal);
+               break;
+       }
+
+       iter->last = none;
 }
 
-struct bkey_s_c bch2_journal_iter_peek(struct journal_iter *iter)
+struct bkey_s_c bch2_btree_and_journal_iter_peek(struct btree_and_journal_iter *iter)
 {
+       struct bkey_s_c ret;
+
        while (1) {
-               if (iter->k == iter->keys->d + iter->keys->nr)
+               struct bkey_s_c btree_k         =
+                       bch2_journal_iter_peek_btree(iter);
+               struct bkey_s_c journal_k       =
+                       bkey_i_to_s_c(bch2_journal_iter_peek(&iter->journal));
+
+               if (btree_k.k && journal_k.k) {
+                       int cmp = bkey_cmp(btree_k.k->p, journal_k.k->p);
+
+                       if (!cmp)
+                               bch2_journal_iter_advance_btree(iter);
+
+                       iter->last = cmp < 0 ? btree : journal;
+               } else if (btree_k.k) {
+                       iter->last = btree;
+               } else if (journal_k.k) {
+                       iter->last = journal;
+               } else {
+                       iter->last = none;
                        return bkey_s_c_null;
+               }
 
-               if (iter->k->btree_id == iter->btree_id)
-                       return bkey_i_to_s_c(iter->k->k);
+               ret = iter->last == journal ? journal_k : btree_k;
 
-               iter->k++;
+               if (iter->b &&
+                   bkey_cmp(ret.k->p, iter->b->data->max_key) > 0) {
+                       iter->journal.k = NULL;
+                       iter->last = none;
+                       return bkey_s_c_null;
+               }
+
+               if (!bkey_deleted(ret.k))
+                       break;
+
+               bch2_btree_and_journal_iter_advance(iter);
        }
 
-       return bkey_s_c_null;
+       return ret;
+}
+
+struct bkey_s_c bch2_btree_and_journal_iter_next(struct btree_and_journal_iter *iter)
+{
+       bch2_btree_and_journal_iter_advance(iter);
+
+       return bch2_btree_and_journal_iter_peek(iter);
 }
 
-struct bkey_s_c bch2_journal_iter_next(struct journal_iter *iter)
+void bch2_btree_and_journal_iter_init(struct btree_and_journal_iter *iter,
+                                     struct btree_trans *trans,
+                                     struct journal_keys *journal_keys,
+                                     enum btree_id id, struct bpos pos)
 {
-       if (iter->k == iter->keys->d + iter->keys->nr)
-               return bkey_s_c_null;
+       memset(iter, 0, sizeof(*iter));
 
-       iter->k++;
-       return bch2_journal_iter_peek(iter);
+       iter->btree = bch2_trans_get_iter(trans, id, pos, 0);
+       bch2_journal_iter_init(&iter->journal, journal_keys, id, 0, pos);
+}
+
+void bch2_btree_and_journal_iter_init_node_iter(struct btree_and_journal_iter *iter,
+                                               struct journal_keys *journal_keys,
+                                               struct btree *b)
+{
+       memset(iter, 0, sizeof(*iter));
+
+       iter->b = b;
+       bch2_btree_node_iter_init_from_start(&iter->node_iter, iter->b);
+       bch2_journal_iter_init(&iter->journal, journal_keys,
+                              b->c.btree_id, b->c.level, b->data->min_key);
+}
+
+/* Walk btree, overlaying keys from the journal: */
+
+static int bch2_btree_and_journal_walk_recurse(struct bch_fs *c, struct btree *b,
+                               struct journal_keys *journal_keys,
+                               enum btree_id btree_id,
+                               btree_walk_node_fn node_fn,
+                               btree_walk_key_fn key_fn)
+{
+       struct btree_and_journal_iter iter;
+       struct bkey_s_c k;
+       int ret = 0;
+
+       bch2_btree_and_journal_iter_init_node_iter(&iter, journal_keys, b);
+
+       while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
+               ret = key_fn(c, btree_id, b->c.level, k);
+               if (ret)
+                       break;
+
+               if (b->c.level) {
+                       struct btree *child;
+                       BKEY_PADDED(k) tmp;
+
+                       bkey_reassemble(&tmp.k, k);
+                       k = bkey_i_to_s_c(&tmp.k);
+
+                       bch2_btree_and_journal_iter_advance(&iter);
+
+                       if (b->c.level > 0) {
+                               child = bch2_btree_node_get_noiter(c, &tmp.k,
+                                                       b->c.btree_id, b->c.level - 1);
+                               ret = PTR_ERR_OR_ZERO(child);
+                               if (ret)
+                                       break;
+
+                               ret   = (node_fn ? node_fn(c, b) : 0) ?:
+                                       bch2_btree_and_journal_walk_recurse(c, child,
+                                               journal_keys, btree_id, node_fn, key_fn);
+                               six_unlock_read(&child->c.lock);
+
+                               if (ret)
+                                       break;
+                       }
+               } else {
+                       bch2_btree_and_journal_iter_advance(&iter);
+               }
+       }
+
+       return ret;
+}
+
+int bch2_btree_and_journal_walk(struct bch_fs *c, struct journal_keys *journal_keys,
+                               enum btree_id btree_id,
+                               btree_walk_node_fn node_fn,
+                               btree_walk_key_fn key_fn)
+{
+       struct btree *b = c->btree_roots[btree_id].b;
+       int ret = 0;
+
+       if (btree_node_fake(b))
+               return 0;
+
+       six_lock_read(&b->c.lock, NULL, NULL);
+       ret   = (node_fn ? node_fn(c, b) : 0) ?:
+               bch2_btree_and_journal_walk_recurse(c, b, journal_keys, btree_id,
+                                                   node_fn, key_fn) ?:
+               key_fn(c, btree_id, b->c.level + 1, bkey_i_to_s_c(&b->key));
+       six_unlock_read(&b->c.lock);
+
+       return ret;
 }
 
 /* sort and dedup all keys in the journal: */
 
-static void journal_entries_free(struct list_head *list)
+void bch2_journal_entries_free(struct list_head *list)
 {
 
        while (!list_empty(list)) {
@@ -75,43 +289,23 @@ static void journal_entries_free(struct list_head *list)
        }
 }
 
+/*
+ * When keys compare equal, oldest compares first:
+ */
 static int journal_sort_key_cmp(const void *_l, const void *_r)
 {
        const struct journal_key *l = _l;
        const struct journal_key *r = _r;
 
-       return cmp_int(l->btree_id, r->btree_id) ?:
-               bkey_cmp(l->pos, r->pos) ?:
+       return  cmp_int(l->btree_id,    r->btree_id) ?:
+               cmp_int(l->level,       r->level) ?:
+               bkey_cmp(l->k->k.p, r->k->k.p) ?:
                cmp_int(l->journal_seq, r->journal_seq) ?:
                cmp_int(l->journal_offset, r->journal_offset);
 }
 
-static int journal_sort_seq_cmp(const void *_l, const void *_r)
+void bch2_journal_keys_free(struct journal_keys *keys)
 {
-       const struct journal_key *l = _l;
-       const struct journal_key *r = _r;
-
-       return cmp_int(l->journal_seq, r->journal_seq) ?:
-               cmp_int(l->btree_id, r->btree_id) ?:
-               bkey_cmp(l->pos, r->pos);
-}
-
-static void journal_keys_sift(struct journal_keys *keys, struct journal_key *i)
-{
-       while (i + 1 < keys->d + keys->nr &&
-              journal_sort_key_cmp(i, i + 1) > 0) {
-               swap(i[0], i[1]);
-               i++;
-       }
-}
-
-static void journal_keys_free(struct journal_keys *keys)
-{
-       struct journal_key *i;
-
-       for_each_journal_key(*keys, i)
-               if (i->allocated)
-                       kfree(i->k);
        kvfree(keys->d);
        keys->d = NULL;
        keys->nr = 0;
@@ -122,108 +316,61 @@ static struct journal_keys journal_keys_sort(struct list_head *journal_entries)
        struct journal_replay *p;
        struct jset_entry *entry;
        struct bkey_i *k, *_n;
-       struct journal_keys keys = { NULL }, keys_deduped = { NULL };
-       struct journal_key *i;
+       struct journal_keys keys = { NULL };
+       struct journal_key *src, *dst;
        size_t nr_keys = 0;
 
-       list_for_each_entry(p, journal_entries, list)
+       if (list_empty(journal_entries))
+               return keys;
+
+       keys.journal_seq_base =
+               le64_to_cpu(list_last_entry(journal_entries,
+                               struct journal_replay, list)->j.last_seq);
+
+       list_for_each_entry(p, journal_entries, list) {
+               if (le64_to_cpu(p->j.seq) < keys.journal_seq_base)
+                       continue;
+
                for_each_jset_key(k, _n, entry, &p->j)
                        nr_keys++;
+       }
 
-       keys.journal_seq_base = keys_deduped.journal_seq_base =
-               le64_to_cpu(list_first_entry(journal_entries,
-                                            struct journal_replay,
-                                            list)->j.seq);
 
        keys.d = kvmalloc(sizeof(keys.d[0]) * nr_keys, GFP_KERNEL);
        if (!keys.d)
                goto err;
 
-       keys_deduped.d = kvmalloc(sizeof(keys.d[0]) * nr_keys * 2, GFP_KERNEL);
-       if (!keys_deduped.d)
-               goto err;
+       list_for_each_entry(p, journal_entries, list) {
+               if (le64_to_cpu(p->j.seq) < keys.journal_seq_base)
+                       continue;
 
-       list_for_each_entry(p, journal_entries, list)
                for_each_jset_key(k, _n, entry, &p->j)
                        keys.d[keys.nr++] = (struct journal_key) {
                                .btree_id       = entry->btree_id,
-                               .pos            = bkey_start_pos(&k->k),
+                               .level          = entry->level,
                                .k              = k,
                                .journal_seq    = le64_to_cpu(p->j.seq) -
                                        keys.journal_seq_base,
                                .journal_offset = k->_data - p->j._data,
                        };
+       }
 
-       sort(keys.d, nr_keys, sizeof(keys.d[0]), journal_sort_key_cmp, NULL);
-
-       i = keys.d;
-       while (i < keys.d + keys.nr) {
-               if (i + 1 < keys.d + keys.nr &&
-                   i[0].btree_id == i[1].btree_id &&
-                   !bkey_cmp(i[0].pos, i[1].pos)) {
-                       if (bkey_cmp(i[0].k->k.p, i[1].k->k.p) <= 0) {
-                               i++;
-                       } else {
-                               bch2_cut_front(i[1].k->k.p, i[0].k);
-                               i[0].pos = i[1].k->k.p;
-                               journal_keys_sift(&keys, i);
-                       }
-                       continue;
-               }
+       sort(keys.d, keys.nr, sizeof(keys.d[0]), journal_sort_key_cmp, NULL);
 
-               if (i + 1 < keys.d + keys.nr &&
-                   i[0].btree_id == i[1].btree_id &&
-                   bkey_cmp(i[0].k->k.p, bkey_start_pos(&i[1].k->k)) > 0) {
-                       if ((cmp_int(i[0].journal_seq, i[1].journal_seq) ?:
-                            cmp_int(i[0].journal_offset, i[1].journal_offset)) < 0) {
-                               if (bkey_cmp(i[0].k->k.p, i[1].k->k.p) <= 0) {
-                                       bch2_cut_back(bkey_start_pos(&i[1].k->k), &i[0].k->k);
-                               } else {
-                                       struct bkey_i *split =
-                                               kmalloc(bkey_bytes(i[0].k), GFP_KERNEL);
-
-                                       if (!split)
-                                               goto err;
-
-                                       bkey_copy(split, i[0].k);
-                                       bch2_cut_back(bkey_start_pos(&i[1].k->k), &split->k);
-                                       keys_deduped.d[keys_deduped.nr++] = (struct journal_key) {
-                                               .btree_id       = i[0].btree_id,
-                                               .allocated      = true,
-                                               .pos            = bkey_start_pos(&split->k),
-                                               .k              = split,
-                                               .journal_seq    = i[0].journal_seq,
-                                               .journal_offset = i[0].journal_offset,
-                                       };
-
-                                       bch2_cut_front(i[1].k->k.p, i[0].k);
-                                       i[0].pos = i[1].k->k.p;
-                                       journal_keys_sift(&keys, i);
-                                       continue;
-                               }
-                       } else {
-                               if (bkey_cmp(i[0].k->k.p, i[1].k->k.p) >= 0) {
-                                       i[1] = i[0];
-                                       i++;
-                                       continue;
-                               } else {
-                                       bch2_cut_front(i[0].k->k.p, i[1].k);
-                                       i[1].pos = i[0].k->k.p;
-                                       journal_keys_sift(&keys, i + 1);
-                                       continue;
-                               }
-                       }
-               }
+       src = dst = keys.d;
+       while (src < keys.d + keys.nr) {
+               while (src + 1 < keys.d + keys.nr &&
+                      src[0].btree_id  == src[1].btree_id &&
+                      src[0].level     == src[1].level &&
+                      !bkey_cmp(src[0].k->k.p, src[1].k->k.p))
+                       src++;
 
-               keys_deduped.d[keys_deduped.nr++] = *i++;
+               *dst++ = *src++;
        }
 
-       kvfree(keys.d);
-       return keys_deduped;
+       keys.nr = dst - keys.d;
 err:
-       journal_keys_free(&keys_deduped);
-       kvfree(keys.d);
-       return (struct journal_keys) { NULL };
+       return keys;
 }
 
 /* journal replay: */
@@ -254,7 +401,7 @@ static int bch2_extent_replay_key(struct bch_fs *c, enum btree_id btree_id,
         * Some extents aren't equivalent - w.r.t. what the triggers do
         * - if they're split:
         */
-       bool remark_if_split = bch2_extent_is_compressed(bkey_i_to_s_c(k)) ||
+       bool remark_if_split = bch2_bkey_sectors_compressed(bkey_i_to_s_c(k)) ||
                k->k.type == KEY_TYPE_reflink_p;
        bool remark = false;
        int ret;
@@ -274,11 +421,6 @@ retry:
 
                atomic_end = bpos_min(k->k.p, iter->l[0].b->key.k.p);
 
-               split_iter = bch2_trans_copy_iter(&trans, iter);
-               ret = PTR_ERR_OR_ZERO(split_iter);
-               if (ret)
-                       goto err;
-
                split = bch2_trans_kmalloc(&trans, bkey_bytes(&k->k));
                ret = PTR_ERR_OR_ZERO(split);
                if (ret)
@@ -289,7 +431,7 @@ retry:
                    bkey_cmp(atomic_end, k->k.p) < 0) {
                        ret = bch2_disk_reservation_add(c, &disk_res,
                                        k->k.size *
-                                       bch2_bkey_nr_dirty_ptrs(bkey_i_to_s_c(k)),
+                                       bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(k)),
                                        BCH_DISK_RESERVATION_NOFAIL);
                        BUG_ON(ret);
 
@@ -297,35 +439,51 @@ retry:
                }
 
                bkey_copy(split, k);
-               bch2_cut_front(split_iter->pos, split);
-               bch2_cut_back(atomic_end, &split->k);
+               bch2_cut_front(iter->pos, split);
+               bch2_cut_back(atomic_end, split);
+
+               split_iter = bch2_trans_copy_iter(&trans, iter);
+               ret = PTR_ERR_OR_ZERO(split_iter);
+               if (ret)
+                       goto err;
+
+               /*
+                * It's important that we don't go through the
+                * extent_handle_overwrites() and extent_update_to_keys() path
+                * here: journal replay is supposed to treat extents like
+                * regular keys
+                */
+               __bch2_btree_iter_set_pos(split_iter, split->k.p, false);
+               bch2_trans_update(&trans, split_iter, split,
+                                 BTREE_TRIGGER_NORUN);
+               bch2_trans_iter_put(&trans, split_iter);
 
-               bch2_trans_update(&trans, split_iter, split);
                bch2_btree_iter_set_pos(iter, split->k.p);
+
+               if (remark) {
+                       ret = bch2_trans_mark_key(&trans, bkey_i_to_s_c(split),
+                                                 0, split->k.size,
+                                                 BTREE_TRIGGER_INSERT);
+                       if (ret)
+                               goto err;
+               }
        } while (bkey_cmp(iter->pos, k->k.p) < 0);
 
        if (remark) {
                ret = bch2_trans_mark_key(&trans, bkey_i_to_s_c(k),
                                          0, -((s64) k->k.size),
-                                         BCH_BUCKET_MARK_OVERWRITE) ?:
-                     bch2_trans_commit(&trans, &disk_res, NULL,
-                                       BTREE_INSERT_ATOMIC|
-                                       BTREE_INSERT_NOFAIL|
-                                       BTREE_INSERT_LAZY_RW|
-                                       BTREE_INSERT_NOMARK_OVERWRITES|
-                                       BTREE_INSERT_NO_CLEAR_REPLICAS);
-       } else {
-               ret = bch2_trans_commit(&trans, &disk_res, NULL,
-                                       BTREE_INSERT_ATOMIC|
-                                       BTREE_INSERT_NOFAIL|
-                                       BTREE_INSERT_LAZY_RW|
-                                       BTREE_INSERT_JOURNAL_REPLAY|
-                                       BTREE_INSERT_NOMARK);
+                                         BTREE_TRIGGER_OVERWRITE);
+               if (ret)
+                       goto err;
        }
 
-       if (ret)
-               goto err;
+       ret = bch2_trans_commit(&trans, &disk_res, NULL,
+                               BTREE_INSERT_NOFAIL|
+                               BTREE_INSERT_LAZY_RW|
+                               BTREE_INSERT_JOURNAL_REPLAY);
 err:
+       bch2_trans_iter_put(&trans, iter);
+
        if (ret == -EINTR)
                goto retry;
 
@@ -334,37 +492,150 @@ err:
        return bch2_trans_exit(&trans) ?: ret;
 }
 
+static int __bch2_journal_replay_key(struct btree_trans *trans,
+                                    enum btree_id id, unsigned level,
+                                    struct bkey_i *k)
+{
+       struct btree_iter *iter;
+       int ret;
+
+       iter = bch2_trans_get_node_iter(trans, id, k->k.p,
+                                       BTREE_MAX_DEPTH, level,
+                                       BTREE_ITER_INTENT);
+       if (IS_ERR(iter))
+               return PTR_ERR(iter);
+
+       /*
+        * iter->flags & BTREE_ITER_IS_EXTENTS triggers the update path to run
+        * extent_handle_overwrites() and extent_update_to_keys() - but we don't
+        * want that here, journal replay is supposed to treat extents like
+        * regular keys:
+        */
+       __bch2_btree_iter_set_pos(iter, k->k.p, false);
+
+       ret   = bch2_btree_iter_traverse(iter) ?:
+               bch2_trans_update(trans, iter, k, BTREE_TRIGGER_NORUN);
+       bch2_trans_iter_put(trans, iter);
+       return ret;
+}
+
+static int bch2_journal_replay_key(struct bch_fs *c, enum btree_id id,
+                                  unsigned level, struct bkey_i *k)
+{
+       return bch2_trans_do(c, NULL, NULL,
+                            BTREE_INSERT_NOFAIL|
+                            BTREE_INSERT_LAZY_RW|
+                            BTREE_INSERT_JOURNAL_REPLAY,
+                            __bch2_journal_replay_key(&trans, id, level, k));
+}
+
+static int __bch2_alloc_replay_key(struct btree_trans *trans, struct bkey_i *k)
+{
+       struct btree_iter *iter;
+       int ret;
+
+       iter = bch2_trans_get_iter(trans, BTREE_ID_ALLOC, k->k.p,
+                                  BTREE_ITER_CACHED|
+                                  BTREE_ITER_CACHED_NOFILL|
+                                  BTREE_ITER_INTENT);
+       ret =   PTR_ERR_OR_ZERO(iter) ?:
+               bch2_trans_update(trans, iter, k, BTREE_TRIGGER_NORUN);
+       bch2_trans_iter_put(trans, iter);
+       return ret;
+}
+
+static int bch2_alloc_replay_key(struct bch_fs *c, struct bkey_i *k)
+{
+       return bch2_trans_do(c, NULL, NULL,
+                            BTREE_INSERT_NOFAIL|
+                            BTREE_INSERT_USE_RESERVE|
+                            BTREE_INSERT_LAZY_RW|
+                            BTREE_INSERT_JOURNAL_REPLAY,
+                       __bch2_alloc_replay_key(&trans, k));
+}
+
+static int journal_sort_seq_cmp(const void *_l, const void *_r)
+{
+       const struct journal_key *l = _l;
+       const struct journal_key *r = _r;
+
+       return  cmp_int(r->level,       l->level) ?:
+               cmp_int(l->journal_seq, r->journal_seq) ?:
+               cmp_int(l->btree_id,    r->btree_id) ?:
+               bkey_cmp(l->k->k.p,     r->k->k.p);
+}
+
 static int bch2_journal_replay(struct bch_fs *c,
                               struct journal_keys keys)
 {
        struct journal *j = &c->journal;
        struct journal_key *i;
+       u64 seq;
        int ret;
 
        sort(keys.d, keys.nr, sizeof(keys.d[0]), journal_sort_seq_cmp, NULL);
 
+       if (keys.nr)
+               replay_now_at(j, keys.journal_seq_base);
+
+       seq = j->replay_journal_seq;
+
+       /*
+        * First replay updates to the alloc btree - these will only update the
+        * btree key cache:
+        */
        for_each_journal_key(keys, i) {
-               replay_now_at(j, keys.journal_seq_base + i->journal_seq);
+               cond_resched();
 
-               if (i->btree_id == BTREE_ID_ALLOC)
+               if (!i->level && i->btree_id == BTREE_ID_ALLOC) {
+                       j->replay_journal_seq = keys.journal_seq_base + i->journal_seq;
                        ret = bch2_alloc_replay_key(c, i->k);
-               else if (btree_node_type_is_extents(i->btree_id))
-                       ret = bch2_extent_replay_key(c, i->btree_id, i->k);
-               else
-                       ret = bch2_btree_insert(c, i->btree_id, i->k,
-                                               NULL, NULL,
-                                               BTREE_INSERT_NOFAIL|
-                                               BTREE_INSERT_LAZY_RW|
-                                               BTREE_INSERT_JOURNAL_REPLAY|
-                                               BTREE_INSERT_NOMARK);
+                       if (ret)
+                               goto err;
+               }
+       }
 
-               if (ret) {
-                       bch_err(c, "journal replay: error %d while replaying key",
-                               ret);
-                       return ret;
+       /*
+        * Next replay updates to interior btree nodes:
+        */
+       for_each_journal_key(keys, i) {
+               cond_resched();
+
+               if (i->level) {
+                       j->replay_journal_seq = keys.journal_seq_base + i->journal_seq;
+                       ret = bch2_journal_replay_key(c, i->btree_id, i->level, i->k);
+                       if (ret)
+                               goto err;
                }
+       }
 
+       /*
+        * Now that the btree is in a consistent state, we can start journal
+        * reclaim (which will be flushing entries from the btree key cache back
+        * to the btree:
+        */
+       set_bit(BCH_FS_BTREE_INTERIOR_REPLAY_DONE, &c->flags);
+       set_bit(JOURNAL_RECLAIM_STARTED, &j->flags);
+       journal_reclaim_kick(j);
+
+       j->replay_journal_seq = seq;
+
+       /*
+        * Now replay leaf node updates:
+        */
+       for_each_journal_key(keys, i) {
                cond_resched();
+
+               if (i->level || i->btree_id == BTREE_ID_ALLOC)
+                       continue;
+
+               replay_now_at(j, keys.journal_seq_base + i->journal_seq);
+
+               ret = i->k->k.size
+                       ? bch2_extent_replay_key(c, i->btree_id, i->k)
+                       : bch2_journal_replay_key(c, i->btree_id, i->level, i->k);
+               if (ret)
+                       goto err;
        }
 
        replay_now_at(j, j->replay_journal_seq_end);
@@ -373,6 +644,9 @@ static int bch2_journal_replay(struct bch_fs *c,
        bch2_journal_set_replay_done(j);
        bch2_journal_flush_all_pins(j);
        return bch2_journal_error(j);
+err:
+       bch_err(c, "journal replay: error %d while replaying key", ret);
+       return ret;
 }
 
 static bool journal_empty(struct list_head *journal)
@@ -394,6 +668,9 @@ verify_journal_entries_not_blacklisted_or_missing(struct bch_fs *c,
        int ret = 0;
 
        list_for_each_entry(i, journal, list) {
+               if (le64_to_cpu(i->j.seq) < start_seq)
+                       continue;
+
                fsck_err_on(seq != le64_to_cpu(i->j.seq), c,
                        "journal entries %llu-%llu missing! (replaying %llu-%llu)",
                        seq, le64_to_cpu(i->j.seq) - 1,
@@ -584,11 +861,14 @@ static int verify_superblock_clean(struct bch_fs *c,
        }
 
        mustfix_fsck_err_on(j->read_clock != clean->read_clock, c,
-                       "superblock read clock doesn't match journal after clean shutdown");
+                       "superblock read clock %u doesn't match journal %u after clean shutdown",
+                       clean->read_clock, j->read_clock);
        mustfix_fsck_err_on(j->write_clock != clean->write_clock, c,
-                       "superblock read clock doesn't match journal after clean shutdown");
+                       "superblock write clock %u doesn't match journal %u after clean shutdown",
+                       clean->write_clock, j->write_clock);
 
        for (i = 0; i < BTREE_ID_NR; i++) {
+               char buf1[200], buf2[200];
                struct bkey_i *k1, *k2;
                unsigned l1 = 0, l2 = 0;
 
@@ -604,7 +884,11 @@ static int verify_superblock_clean(struct bch_fs *c,
                                    k1->k.u64s != k2->k.u64s ||
                                    memcmp(k1, k2, bkey_bytes(k1)) ||
                                    l1 != l2, c,
-                       "superblock btree root doesn't match journal after clean shutdown");
+                       "superblock btree root %u doesn't match journal after clean shutdown\n"
+                       "sb:      l=%u %s\n"
+                       "journal: l=%u %s\n", i,
+                       l1, (bch2_bkey_val_to_text(&PBUF(buf1), c, bkey_i_to_s_c(k1)), buf1),
+                       l2, (bch2_bkey_val_to_text(&PBUF(buf2), c, bkey_i_to_s_c(k2)), buf2));
        }
 fsck_err:
        return ret;
@@ -662,7 +946,6 @@ static int read_btree_roots(struct bch_fs *c)
                        continue;
                }
 
-
                if (r->error) {
                        __fsck_err(c, i == BTREE_ID_ALLOC
                                   ? FSCK_CAN_IGNORE : 0,
@@ -695,9 +978,7 @@ int bch2_fs_recovery(struct bch_fs *c)
        const char *err = "cannot allocate memory";
        struct bch_sb_field_clean *clean = NULL;
        u64 journal_seq;
-       LIST_HEAD(journal_entries);
-       struct journal_keys journal_keys = { NULL };
-       bool wrote = false, write_sb = false;
+       bool write_sb = false, need_write_alloc = false;
        int ret;
 
        if (c->sb.clean)
@@ -710,38 +991,39 @@ int bch2_fs_recovery(struct bch_fs *c)
                bch_info(c, "recovering from clean shutdown, journal seq %llu",
                         le64_to_cpu(clean->journal_seq));
 
-       if (!c->replicas.entries) {
+       if (!c->replicas.entries ||
+           c->opts.rebuild_replicas) {
                bch_info(c, "building replicas info");
                set_bit(BCH_FS_REBUILD_REPLICAS, &c->flags);
        }
 
-       if (!c->sb.clean || c->opts.fsck) {
+       if (!c->sb.clean || c->opts.fsck || c->opts.keep_journal) {
                struct jset *j;
 
-               ret = bch2_journal_read(c, &journal_entries);
+               ret = bch2_journal_read(c, &c->journal_entries);
                if (ret)
                        goto err;
 
-               if (mustfix_fsck_err_on(c->sb.clean && !journal_empty(&journal_entries), c,
+               if (mustfix_fsck_err_on(c->sb.clean && !journal_empty(&c->journal_entries), c,
                                "filesystem marked clean but journal not empty")) {
                        c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
                        SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
                        c->sb.clean = false;
                }
 
-               if (!c->sb.clean && list_empty(&journal_entries)) {
+               if (!c->sb.clean && list_empty(&c->journal_entries)) {
                        bch_err(c, "no journal entries found");
                        ret = BCH_FSCK_REPAIR_IMPOSSIBLE;
                        goto err;
                }
 
-               journal_keys = journal_keys_sort(&journal_entries);
-               if (!journal_keys.d) {
+               c->journal_keys = journal_keys_sort(&c->journal_entries);
+               if (!c->journal_keys.d) {
                        ret = -ENOMEM;
                        goto err;
                }
 
-               j = &list_last_entry(&journal_entries,
+               j = &list_last_entry(&c->journal_entries,
                                     struct journal_replay, list)->j;
 
                ret = verify_superblock_clean(c, &clean, j);
@@ -753,7 +1035,19 @@ int bch2_fs_recovery(struct bch_fs *c)
                journal_seq = le64_to_cpu(clean->journal_seq) + 1;
        }
 
-       ret = journal_replay_early(c, clean, &journal_entries);
+       if (!c->sb.clean &&
+           !(c->sb.features & (1ULL << BCH_FEATURE_extents_above_btree_updates))) {
+               bch_err(c, "filesystem needs recovery from older version; run fsck from older bcachefs-tools to fix");
+               ret = -EINVAL;
+               goto err;
+       }
+
+       if (c->opts.reconstruct_alloc) {
+               c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
+               drop_alloc_keys(&c->journal_keys);
+       }
+
+       ret = journal_replay_early(c, clean, &c->journal_entries);
        if (ret)
                goto err;
 
@@ -767,19 +1061,24 @@ int bch2_fs_recovery(struct bch_fs *c)
                }
 
                journal_seq += 4;
+
+               /*
+                * The superblock needs to be written before we do any btree
+                * node writes: it will be in the read_write() path
+                */
        }
 
        ret = bch2_blacklist_table_initialize(c);
 
-       if (!list_empty(&journal_entries)) {
+       if (!list_empty(&c->journal_entries)) {
                ret = verify_journal_entries_not_blacklisted_or_missing(c,
-                                                       &journal_entries);
+                                                       &c->journal_entries);
                if (ret)
                        goto err;
        }
 
        ret = bch2_fs_journal_start(&c->journal, journal_seq,
-                                   &journal_entries);
+                                   &c->journal_entries);
        if (ret)
                goto err;
 
@@ -789,14 +1088,14 @@ int bch2_fs_recovery(struct bch_fs *c)
 
        bch_verbose(c, "starting alloc read");
        err = "error reading allocation information";
-       ret = bch2_alloc_read(c, &journal_keys);
+       ret = bch2_alloc_read(c, &c->journal_keys);
        if (ret)
                goto err;
        bch_verbose(c, "alloc read done");
 
        bch_verbose(c, "starting stripes_read");
        err = "error reading stripes";
-       ret = bch2_stripes_read(c, &journal_keys);
+       ret = bch2_stripes_read(c, &c->journal_keys);
        if (ret)
                goto err;
        bch_verbose(c, "stripes_read done");
@@ -812,9 +1111,11 @@ int bch2_fs_recovery(struct bch_fs *c)
                 */
                bch_info(c, "starting metadata mark and sweep");
                err = "error in mark and sweep";
-               ret = bch2_gc(c, NULL, true, true);
-               if (ret)
+               ret = bch2_gc(c, &c->journal_keys, true, true);
+               if (ret < 0)
                        goto err;
+               if (ret)
+                       need_write_alloc = true;
                bch_verbose(c, "mark and sweep done");
        }
 
@@ -823,9 +1124,11 @@ int bch2_fs_recovery(struct bch_fs *c)
            test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags)) {
                bch_info(c, "starting mark and sweep");
                err = "error in mark and sweep";
-               ret = bch2_gc(c, &journal_keys, true, false);
-               if (ret)
+               ret = bch2_gc(c, &c->journal_keys, true, false);
+               if (ret < 0)
                        goto err;
+               if (ret)
+                       need_write_alloc = true;
                bch_verbose(c, "mark and sweep done");
        }
 
@@ -844,12 +1147,12 @@ int bch2_fs_recovery(struct bch_fs *c)
 
        bch_verbose(c, "starting journal replay");
        err = "journal replay failed";
-       ret = bch2_journal_replay(c, journal_keys);
+       ret = bch2_journal_replay(c, c->journal_keys);
        if (ret)
                goto err;
        bch_verbose(c, "journal replay done");
 
-       if (!c->opts.nochanges) {
+       if (need_write_alloc && !c->opts.nochanges) {
                /*
                 * note that even when filesystem was clean there might be work
                 * to do here, if we ran gc (because of fsck) which recalculated
@@ -857,17 +1160,19 @@ int bch2_fs_recovery(struct bch_fs *c)
                 */
                bch_verbose(c, "writing allocation info");
                err = "error writing out alloc info";
-               ret = bch2_stripes_write(c, BTREE_INSERT_LAZY_RW, &wrote) ?:
-                       bch2_alloc_write(c, BTREE_INSERT_LAZY_RW, &wrote);
+               ret = bch2_stripes_write(c, BTREE_INSERT_LAZY_RW) ?:
+                       bch2_alloc_write(c, BTREE_INSERT_LAZY_RW);
                if (ret) {
                        bch_err(c, "error writing alloc info");
                        goto err;
                }
                bch_verbose(c, "alloc write done");
+
+               set_bit(BCH_FS_ALLOC_WRITTEN, &c->flags);
        }
 
        if (!c->sb.clean) {
-               if (!(c->sb.features & (1 << BCH_FEATURE_ATOMIC_NLINK))) {
+               if (!(c->sb.features & (1 << BCH_FEATURE_atomic_nlink))) {
                        bch_info(c, "checking inode link counts");
                        err = "error in recovery";
                        ret = bch2_fsck_inode_nlink(c);
@@ -908,6 +1213,7 @@ int bch2_fs_recovery(struct bch_fs *c)
                        c->disk_sb.sb->version_min =
                                le16_to_cpu(bcachefs_metadata_version_min);
                c->disk_sb.sb->version = le16_to_cpu(bcachefs_metadata_version_current);
+               c->disk_sb.sb->features[0] |= BCH_SB_FEATURES_ALL;
                write_sb = true;
        }
 
@@ -918,7 +1224,7 @@ int bch2_fs_recovery(struct bch_fs *c)
 
        if (c->opts.fsck &&
            !test_bit(BCH_FS_ERROR, &c->flags)) {
-               c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_ATOMIC_NLINK;
+               c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_atomic_nlink;
                SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 0);
                write_sb = true;
        }
@@ -937,8 +1243,10 @@ fsck_err:
        set_bit(BCH_FS_FSCK_DONE, &c->flags);
        bch2_flush_fsck_errs(c);
 
-       journal_keys_free(&journal_keys);
-       journal_entries_free(&journal_entries);
+       if (!c->opts.keep_journal) {
+               bch2_journal_keys_free(&c->journal_keys);
+               bch2_journal_entries_free(&c->journal_entries);
+       }
        kfree(clean);
        if (ret)
                bch_err(c, "Error in recovery: %s (%i)", err, ret);
@@ -965,12 +1273,24 @@ int bch2_fs_initialize(struct bch_fs *c)
                bch2_mark_dev_superblock(c, ca, 0);
        mutex_unlock(&c->sb_lock);
 
+       mutex_lock(&c->sb_lock);
+       c->disk_sb.sb->version = c->disk_sb.sb->version_min =
+               le16_to_cpu(bcachefs_metadata_version_current);
+       c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_atomic_nlink;
+       c->disk_sb.sb->features[0] |= BCH_SB_FEATURES_ALL;
+
+       bch2_write_super(c);
+       mutex_unlock(&c->sb_lock);
+
        set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
        set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
 
        for (i = 0; i < BTREE_ID_NR; i++)
                bch2_btree_root_alloc(c, i);
 
+       set_bit(BCH_FS_BTREE_INTERIOR_REPLAY_DONE, &c->flags);
+       set_bit(JOURNAL_RECLAIM_STARTED, &c->journal.flags);
+
        err = "unable to allocate journal buckets";
        for_each_online_member(ca, c, i) {
                ret = bch2_dev_journal_alloc(ca);
@@ -987,15 +1307,24 @@ int bch2_fs_initialize(struct bch_fs *c)
        bch2_fs_journal_start(&c->journal, 1, &journal);
        bch2_journal_set_replay_done(&c->journal);
 
-       err = "error going read write";
-       ret = __bch2_fs_read_write(c, true);
+       err = "error going read-write";
+       ret = bch2_fs_read_write_early(c);
+       if (ret)
+               goto err;
+
+       /*
+        * Write out the superblock and journal buckets, now that we can do
+        * btree updates
+        */
+       err = "error writing alloc info";
+       ret = bch2_alloc_write(c, 0);
        if (ret)
                goto err;
 
        bch2_inode_init(c, &root_inode, 0, 0,
                        S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO, 0, NULL);
        root_inode.bi_inum = BCACHEFS_ROOT_INO;
-       bch2_inode_pack(&packed_inode, &root_inode);
+       bch2_inode_pack(c, &packed_inode, &root_inode);
 
        err = "error creating root directory";
        ret = bch2_btree_insert(c, BTREE_ID_INODES,
@@ -1007,11 +1336,11 @@ int bch2_fs_initialize(struct bch_fs *c)
        bch2_inode_init_early(c, &lostfound_inode);
 
        err = "error creating lost+found";
-       ret = bch2_trans_do(c, NULL, BTREE_INSERT_ATOMIC,
+       ret = bch2_trans_do(c, NULL, NULL, 0,
                bch2_create_trans(&trans, BCACHEFS_ROOT_INO,
                                  &root_inode, &lostfound_inode,
                                  &lostfound,
-                                 0, 0, S_IFDIR|0755, 0,
+                                 0, 0, S_IFDIR|0700, 0,
                                  NULL, NULL));
        if (ret)
                goto err;
@@ -1028,10 +1357,6 @@ int bch2_fs_initialize(struct bch_fs *c)
                goto err;
 
        mutex_lock(&c->sb_lock);
-       c->disk_sb.sb->version = c->disk_sb.sb->version_min =
-               le16_to_cpu(bcachefs_metadata_version_current);
-       c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_ATOMIC_NLINK;
-
        SET_BCH_SB_INITIALIZED(c->disk_sb.sb, true);
        SET_BCH_SB_CLEAN(c->disk_sb.sb, false);