]> git.sesse.net Git - bcachefs-tools-debian/blobdiff - libbcachefs/btree_gc.c
Update bcachefs sources to e1f6739c4a bcachefs: Fix another iterator counting bug
[bcachefs-tools-debian] / libbcachefs / btree_gc.c
index 23013fbb6fb2b17270e332357096fe9f92215566..146f2428fe04ced98b545b545518d7c14903dc42 100644 (file)
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0
 /*
  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
  * Copyright (C) 2014 Datera Inc.
@@ -18,9 +19,9 @@
 #include "error.h"
 #include "extents.h"
 #include "journal.h"
-#include "journal_io.h"
 #include "keylist.h"
 #include "move.h"
+#include "recovery.h"
 #include "replicas.h"
 #include "super-io.h"
 
@@ -46,65 +47,42 @@ static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
        __gc_pos_set(c, new_pos);
 }
 
-/* range_checks - for validating min/max pos of each btree node: */
-
-struct range_checks {
-       struct range_level {
-               struct bpos     min;
-               struct bpos     max;
-       }                       l[BTREE_MAX_DEPTH];
-       unsigned                depth;
-};
-
-static void btree_node_range_checks_init(struct range_checks *r, unsigned depth)
-{
-       unsigned i;
-
-       for (i = 0; i < BTREE_MAX_DEPTH; i++)
-               r->l[i].min = r->l[i].max = POS_MIN;
-       r->depth = depth;
-}
-
-static void btree_node_range_checks(struct bch_fs *c, struct btree *b,
-                                   struct range_checks *r)
+static int bch2_gc_check_topology(struct bch_fs *c,
+                                 struct bkey_s_c k,
+                                 struct bpos *expected_start,
+                                 struct bpos expected_end,
+                                 bool is_last)
 {
-       struct range_level *l = &r->l[b->level];
-
-       struct bpos expected_min = bkey_cmp(l->min, l->max)
-               ? btree_type_successor(b->btree_id, l->max)
-               : l->max;
-
-       bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, expected_min), c,
-               "btree node has incorrect min key: %llu:%llu != %llu:%llu",
-               b->data->min_key.inode,
-               b->data->min_key.offset,
-               expected_min.inode,
-               expected_min.offset);
-
-       l->max = b->data->max_key;
+       int ret = 0;
 
-       if (b->level > r->depth) {
-               l = &r->l[b->level - 1];
+       if (k.k->type == KEY_TYPE_btree_ptr_v2) {
+               struct bkey_s_c_btree_ptr_v2 bp = bkey_s_c_to_btree_ptr_v2(k);
 
-               bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, l->min), c,
-                       "btree node min doesn't match min of child nodes: %llu:%llu != %llu:%llu",
-                       b->data->min_key.inode,
-                       b->data->min_key.offset,
-                       l->min.inode,
-                       l->min.offset);
+               if (fsck_err_on(bkey_cmp(*expected_start, bp.v->min_key), c,
+                               "btree node with incorrect min_key: got %llu:%llu, should be %llu:%llu",
+                               bp.v->min_key.inode,
+                               bp.v->min_key.offset,
+                               expected_start->inode,
+                               expected_start->offset)) {
+                       BUG();
+               }
+       }
 
-               bch2_fs_inconsistent_on(bkey_cmp(b->data->max_key, l->max), c,
-                       "btree node max doesn't match max of child nodes: %llu:%llu != %llu:%llu",
-                       b->data->max_key.inode,
-                       b->data->max_key.offset,
-                       l->max.inode,
-                       l->max.offset);
-
-               if (bkey_cmp(b->data->max_key, POS_MAX))
-                       l->min = l->max =
-                               btree_type_successor(b->btree_id,
-                                                    b->data->max_key);
+       *expected_start = bkey_cmp(k.k->p, POS_MAX)
+               ? bkey_successor(k.k->p)
+               : k.k->p;
+
+       if (fsck_err_on(is_last &&
+                       bkey_cmp(k.k->p, expected_end), c,
+                       "btree node with incorrect max_key: got %llu:%llu, should be %llu:%llu",
+                       k.k->p.inode,
+                       k.k->p.offset,
+                       expected_end.inode,
+                       expected_end.offset)) {
+               BUG();
        }
+fsck_err:
+       return ret;
 }
 
 /* marking of btree keys/nodes: */
@@ -114,17 +92,20 @@ static int bch2_gc_mark_key(struct bch_fs *c, struct bkey_s_c k,
 {
        struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
        const struct bch_extent_ptr *ptr;
-       struct gc_pos pos = { 0 };
        unsigned flags =
-               BCH_BUCKET_MARK_GC|
-               (initial ? BCH_BUCKET_MARK_NOATOMIC : 0);
+               BTREE_TRIGGER_GC|
+               (initial ? BTREE_TRIGGER_NOATOMIC : 0);
        int ret = 0;
 
        if (initial) {
                BUG_ON(journal_seq_verify(c) &&
                       k.k->version.lo > journal_cur_seq(&c->journal));
 
-               if (k.k->version.lo > atomic64_read(&c->key_version))
+               /* XXX change to fsck check */
+               if (fsck_err_on(k.k->version.lo > atomic64_read(&c->key_version), c,
+                               "key version number higher than recorded: %llu > %llu",
+                               k.k->version.lo,
+                               atomic64_read(&c->key_version)))
                        atomic64_set(&c->key_version, k.k->version.lo);
 
                if (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
@@ -138,24 +119,28 @@ static int bch2_gc_mark_key(struct bch_fs *c, struct bkey_s_c k,
 
                bkey_for_each_ptr(ptrs, ptr) {
                        struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
-                       size_t b = PTR_BUCKET_NR(ca, ptr);
-                       struct bucket *g = PTR_BUCKET(ca, ptr);
+                       struct bucket *g = PTR_BUCKET(ca, ptr, true);
+                       struct bucket *g2 = PTR_BUCKET(ca, ptr, false);
 
                        if (mustfix_fsck_err_on(!g->gen_valid, c,
-                                       "found ptr with missing gen in alloc btree,\n"
-                                       "type %u gen %u",
-                                       k.k->type, ptr->gen)) {
-                               g->_mark.gen = ptr->gen;
-                               g->gen_valid = 1;
-                               bucket_set_dirty(ca, b);
+                                       "bucket %u:%zu data type %s ptr gen %u missing in alloc btree",
+                                       ptr->dev, PTR_BUCKET_NR(ca, ptr),
+                                       bch2_data_types[ptr_data_type(k.k, ptr)],
+                                       ptr->gen)) {
+                               g2->_mark.gen   = g->_mark.gen          = ptr->gen;
+                               g2->gen_valid   = g->gen_valid          = true;
                        }
 
                        if (mustfix_fsck_err_on(gen_cmp(ptr->gen, g->mark.gen) > 0, c,
-                                       "%u ptr gen in the future: %u > %u",
-                                       k.k->type, ptr->gen, g->mark.gen)) {
-                               g->_mark.gen = ptr->gen;
-                               g->gen_valid = 1;
-                               bucket_set_dirty(ca, b);
+                                       "bucket %u:%zu data type %s ptr gen in the future: %u > %u",
+                                       ptr->dev, PTR_BUCKET_NR(ca, ptr),
+                                       bch2_data_types[ptr_data_type(k.k, ptr)],
+                                       ptr->gen, g->mark.gen)) {
+                               g2->_mark.gen   = g->_mark.gen          = ptr->gen;
+                               g2->gen_valid   = g->gen_valid          = true;
+                               g2->_mark.data_type             = 0;
+                               g2->_mark.dirty_sectors         = 0;
+                               g2->_mark.cached_sectors        = 0;
                                set_bit(BCH_FS_FIXED_GENS, &c->flags);
                        }
                }
@@ -163,22 +148,23 @@ static int bch2_gc_mark_key(struct bch_fs *c, struct bkey_s_c k,
 
        bkey_for_each_ptr(ptrs, ptr) {
                struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
-               size_t b = PTR_BUCKET_NR(ca, ptr);
+               struct bucket *g = PTR_BUCKET(ca, ptr, true);
 
-               if (gen_after(ca->oldest_gens[b], ptr->gen))
-                       ca->oldest_gens[b] = ptr->gen;
+               if (gen_after(g->oldest_gen, ptr->gen))
+                       g->oldest_gen = ptr->gen;
 
                *max_stale = max(*max_stale, ptr_stale(ca, ptr));
        }
 
-       bch2_mark_key(c, k, true, k.k->size, pos, NULL, 0, flags);
+       bch2_mark_key(c, k, 0, k.k->size, NULL, 0, flags);
 fsck_err:
        return ret;
 }
 
-static int btree_gc_mark_node(struct bch_fs *c, struct btree *b,
-                             u8 *max_stale, bool initial)
+static int btree_gc_mark_node(struct bch_fs *c, struct btree *b, u8 *max_stale,
+                             bool initial)
 {
+       struct bpos next_node_start = b->data->min_key;
        struct btree_node_iter iter;
        struct bkey unpacked;
        struct bkey_s_c k;
@@ -189,84 +175,193 @@ static int btree_gc_mark_node(struct bch_fs *c, struct btree *b,
        if (!btree_node_type_needs_gc(btree_node_type(b)))
                return 0;
 
-       for_each_btree_node_key_unpack(b, k, &iter,
-                                      &unpacked) {
+       bch2_btree_node_iter_init_from_start(&iter, b);
+
+       while ((k = bch2_btree_node_iter_peek_unpack(&iter, b, &unpacked)).k) {
                bch2_bkey_debugcheck(c, b, k);
 
                ret = bch2_gc_mark_key(c, k, max_stale, initial);
                if (ret)
                        break;
+
+               bch2_btree_node_iter_advance(&iter, b);
+
+               if (b->level) {
+                       ret = bch2_gc_check_topology(c, k,
+                                       &next_node_start,
+                                       b->data->max_key,
+                                       bch2_btree_node_iter_end(&iter));
+                       if (ret)
+                               break;
+               }
        }
 
        return ret;
 }
 
 static int bch2_gc_btree(struct bch_fs *c, enum btree_id btree_id,
-                        bool initial)
+                        bool initial, bool metadata_only)
 {
-       struct btree_iter iter;
+       struct btree_trans trans;
+       struct btree_iter *iter;
        struct btree *b;
-       struct range_checks r;
-       unsigned depth = btree_node_type_needs_gc(btree_id) ? 0 : 1;
-       u8 max_stale;
+       unsigned depth = metadata_only                  ? 1
+               : expensive_debug_checks(c)             ? 0
+               : !btree_node_type_needs_gc(btree_id)   ? 1
+               : 0;
+       u8 max_stale = 0;
        int ret = 0;
 
-       gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
-
-       /*
-        * if expensive_debug_checks is on, run range_checks on all leaf nodes:
-        *
-        * and on startup, we have to read every btree node (XXX: only if it was
-        * an unclean shutdown)
-        */
-       if (initial || expensive_debug_checks(c))
-               depth = 0;
+       bch2_trans_init(&trans, c, 0, 0);
 
-       btree_node_range_checks_init(&r, depth);
+       gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
 
-       __for_each_btree_node(&iter, c, btree_id, POS_MIN,
+       __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
                              0, depth, BTREE_ITER_PREFETCH, b) {
-               btree_node_range_checks(c, b, &r);
-
                bch2_verify_btree_nr_keys(b);
 
+               gc_pos_set(c, gc_pos_btree_node(b));
+
                ret = btree_gc_mark_node(c, b, &max_stale, initial);
                if (ret)
                        break;
 
-               gc_pos_set(c, gc_pos_btree_node(b));
-
                if (!initial) {
                        if (max_stale > 64)
-                               bch2_btree_node_rewrite(c, &iter,
+                               bch2_btree_node_rewrite(c, iter,
                                                b->data->keys.seq,
                                                BTREE_INSERT_USE_RESERVE|
                                                BTREE_INSERT_NOWAIT|
                                                BTREE_INSERT_GC_LOCK_HELD);
                        else if (!btree_gc_rewrite_disabled(c) &&
                                 (btree_gc_always_rewrite(c) || max_stale > 16))
-                               bch2_btree_node_rewrite(c, &iter,
+                               bch2_btree_node_rewrite(c, iter,
                                                b->data->keys.seq,
                                                BTREE_INSERT_NOWAIT|
                                                BTREE_INSERT_GC_LOCK_HELD);
                }
 
-               bch2_btree_iter_cond_resched(&iter);
+               bch2_trans_cond_resched(&trans);
        }
-       ret = bch2_btree_iter_unlock(&iter) ?: ret;
+       ret = bch2_trans_exit(&trans) ?: ret;
        if (ret)
                return ret;
 
        mutex_lock(&c->btree_root_lock);
-
        b = c->btree_roots[btree_id].b;
        if (!btree_node_fake(b))
-               bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
-                                &max_stale, initial);
+               ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
+                                      &max_stale, initial);
        gc_pos_set(c, gc_pos_btree_root(b->btree_id));
-
        mutex_unlock(&c->btree_root_lock);
-       return 0;
+
+       return ret;
+}
+
+static int bch2_gc_btree_init_recurse(struct bch_fs *c, struct btree *b,
+                                     struct journal_keys *journal_keys,
+                                     unsigned target_depth)
+{
+       struct btree_and_journal_iter iter;
+       struct bkey_s_c k;
+       struct bpos next_node_start = b->data->min_key;
+       u8 max_stale = 0;
+       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) {
+               bch2_bkey_debugcheck(c, b, k);
+
+               BUG_ON(bkey_cmp(k.k->p, b->data->min_key) < 0);
+               BUG_ON(bkey_cmp(k.k->p, b->data->max_key) > 0);
+
+               ret = bch2_gc_mark_key(c, k, &max_stale, true);
+               if (ret)
+                       break;
+
+               if (b->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);
+
+                       ret = bch2_gc_check_topology(c, k,
+                                       &next_node_start,
+                                       b->data->max_key,
+                                       !bch2_btree_and_journal_iter_peek(&iter).k);
+                       if (ret)
+                               break;
+
+                       if (b->level > target_depth) {
+                               child = bch2_btree_node_get_noiter(c, &tmp.k,
+                                                       b->btree_id, b->level - 1);
+                               ret = PTR_ERR_OR_ZERO(child);
+                               if (ret)
+                                       break;
+
+                               ret = bch2_gc_btree_init_recurse(c, child,
+                                               journal_keys, target_depth);
+                               six_unlock_read(&child->lock);
+
+                               if (ret)
+                                       break;
+                       }
+               } else {
+                       bch2_btree_and_journal_iter_advance(&iter);
+               }
+       }
+
+       return ret;
+}
+
+static int bch2_gc_btree_init(struct bch_fs *c,
+                             struct journal_keys *journal_keys,
+                             enum btree_id btree_id,
+                             bool metadata_only)
+{
+       struct btree *b;
+       unsigned target_depth = metadata_only           ? 1
+               : expensive_debug_checks(c)             ? 0
+               : !btree_node_type_needs_gc(btree_id)   ? 1
+               : 0;
+       u8 max_stale = 0;
+       int ret = 0;
+
+       b = c->btree_roots[btree_id].b;
+
+       if (btree_node_fake(b))
+               return 0;
+
+       six_lock_read(&b->lock);
+       if (fsck_err_on(bkey_cmp(b->data->min_key, POS_MIN), c,
+                       "btree root with incorrect min_key: %llu:%llu",
+                       b->data->min_key.inode,
+                       b->data->min_key.offset)) {
+               BUG();
+       }
+
+       if (fsck_err_on(bkey_cmp(b->data->max_key, POS_MAX), c,
+                       "btree root with incorrect min_key: %llu:%llu",
+                       b->data->max_key.inode,
+                       b->data->max_key.offset)) {
+               BUG();
+       }
+
+       if (b->level >= target_depth)
+               ret = bch2_gc_btree_init_recurse(c, b,
+                                       journal_keys, target_depth);
+
+       if (!ret)
+               ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
+                                      &max_stale, true);
+fsck_err:
+       six_unlock_read(&b->lock);
+
+       return ret;
 }
 
 static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
@@ -275,11 +370,10 @@ static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
                (int) btree_id_to_gc_phase(r);
 }
 
-static int bch2_gc_btrees(struct bch_fs *c, struct list_head *journal,
-                         bool initial)
+static int bch2_gc_btrees(struct bch_fs *c, struct journal_keys *journal_keys,
+                         bool initial, bool metadata_only)
 {
        enum btree_id ids[BTREE_ID_NR];
-       u8 max_stale;
        unsigned i;
 
        for (i = 0; i < BTREE_ID_NR; i++)
@@ -288,29 +382,12 @@ static int bch2_gc_btrees(struct bch_fs *c, struct list_head *journal,
 
        for (i = 0; i < BTREE_ID_NR; i++) {
                enum btree_id id = ids[i];
-               enum btree_node_type type = __btree_node_type(0, id);
-
-               int ret = bch2_gc_btree(c, id, initial);
+               int ret = initial
+                       ? bch2_gc_btree_init(c, journal_keys,
+                                            id, metadata_only)
+                       : bch2_gc_btree(c, id, initial, metadata_only);
                if (ret)
                        return ret;
-
-               if (journal && btree_node_type_needs_gc(type)) {
-                       struct bkey_i *k, *n;
-                       struct jset_entry *j;
-                       struct journal_replay *r;
-                       int ret;
-
-                       list_for_each_entry(r, journal, list)
-                               for_each_jset_key(k, n, j, &r->j) {
-                                       if (type == __btree_node_type(j->level, j->btree_id)) {
-                                               ret = bch2_gc_mark_key(c,
-                                                       bkey_i_to_s_c(k),
-                                                       &max_stale, initial);
-                                               if (ret)
-                                                       return ret;
-                                       }
-                               }
-               }
        }
 
        return 0;
@@ -348,9 +425,7 @@ void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
         */
        if (c) {
                lockdep_assert_held(&c->sb_lock);
-               percpu_down_read_preempt_disable(&c->mark_lock);
-       } else {
-               preempt_disable();
+               percpu_down_read(&c->mark_lock);
        }
 
        for (i = 0; i < layout->nr_superblocks; i++) {
@@ -372,11 +447,8 @@ void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
                                          gc_phase(GC_PHASE_SB), flags);
        }
 
-       if (c) {
-               percpu_up_read_preempt_enable(&c->mark_lock);
-       } else {
-               preempt_enable();
-       }
+       if (c)
+               percpu_up_read(&c->mark_lock);
 }
 
 static void bch2_mark_superblocks(struct bch_fs *c)
@@ -388,14 +460,13 @@ static void bch2_mark_superblocks(struct bch_fs *c)
        gc_pos_set(c, gc_phase(GC_PHASE_SB));
 
        for_each_online_member(ca, c, i)
-               bch2_mark_dev_superblock(c, ca, BCH_BUCKET_MARK_GC);
+               bch2_mark_dev_superblock(c, ca, BTREE_TRIGGER_GC);
        mutex_unlock(&c->sb_lock);
 }
 
 /* Also see bch2_pending_btree_node_free_insert_done() */
 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
 {
-       struct gc_pos pos = { 0 };
        struct btree_update *as;
        struct pending_btree_node_free *d;
 
@@ -405,9 +476,8 @@ static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
        for_each_pending_btree_node_free(c, as, d)
                if (d->index_update_done)
                        bch2_mark_key(c, bkey_i_to_s_c(&d->key),
-                                     true, 0,
-                                     pos, NULL, 0,
-                                     BCH_BUCKET_MARK_GC);
+                                     0, 0, NULL, 0,
+                                     BTREE_TRIGGER_GC);
 
        mutex_unlock(&c->btree_interior_update_lock);
 }
@@ -419,7 +489,7 @@ static void bch2_mark_allocator_buckets(struct bch_fs *c)
        size_t i, j, iter;
        unsigned ci;
 
-       percpu_down_read_preempt_disable(&c->mark_lock);
+       percpu_down_read(&c->mark_lock);
 
        spin_lock(&c->freelist_lock);
        gc_pos_set(c, gc_pos_alloc(c, NULL));
@@ -428,7 +498,7 @@ static void bch2_mark_allocator_buckets(struct bch_fs *c)
                fifo_for_each_entry(i, &ca->free_inc, iter)
                        bch2_mark_alloc_bucket(c, ca, i, true,
                                               gc_pos_alloc(c, NULL),
-                                              BCH_BUCKET_MARK_GC);
+                                              BTREE_TRIGGER_GC);
 
 
 
@@ -436,7 +506,7 @@ static void bch2_mark_allocator_buckets(struct bch_fs *c)
                        fifo_for_each_entry(i, &ca->free[j], iter)
                                bch2_mark_alloc_bucket(c, ca, i, true,
                                                       gc_pos_alloc(c, NULL),
-                                                      BCH_BUCKET_MARK_GC);
+                                                      BTREE_TRIGGER_GC);
        }
 
        spin_unlock(&c->freelist_lock);
@@ -450,12 +520,12 @@ static void bch2_mark_allocator_buckets(struct bch_fs *c)
                        ca = bch_dev_bkey_exists(c, ob->ptr.dev);
                        bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), true,
                                               gc_pos_alloc(c, ob),
-                                              BCH_BUCKET_MARK_GC);
+                                              BTREE_TRIGGER_GC);
                }
                spin_unlock(&ob->lock);
        }
 
-       percpu_up_read_preempt_enable(&c->mark_lock);
+       percpu_up_read(&c->mark_lock);
 }
 
 static void bch2_gc_free(struct bch_fs *c)
@@ -475,119 +545,43 @@ static void bch2_gc_free(struct bch_fs *c)
                ca->usage[1] = NULL;
        }
 
-       percpu_down_write(&c->mark_lock);
-
-       free_percpu(c->usage[1]);
-       c->usage[1] = NULL;
-
-       percpu_up_write(&c->mark_lock);
+       free_percpu(c->usage_gc);
+       c->usage_gc = NULL;
 }
 
-/*
- * Accumulate percpu counters onto one cpu's copy - only valid when access
- * against any percpu counter is guarded against
- */
-static u64 *acc_percpu_u64s(u64 __percpu *p, unsigned nr)
-{
-       u64 *ret;
-       int cpu;
-
-       preempt_disable();
-       ret = this_cpu_ptr(p);
-       preempt_enable();
-
-       for_each_possible_cpu(cpu) {
-               u64 *i = per_cpu_ptr(p, cpu);
-
-               if (i != ret) {
-                       acc_u64s(ret, i, nr);
-                       memset(i, 0, nr * sizeof(u64));
-               }
-       }
-
-       return ret;
-}
-
-static void bch2_gc_done_nocheck(struct bch_fs *c)
-{
-       struct bch_dev *ca;
-       unsigned i;
-
-       {
-               struct genradix_iter dst_iter = genradix_iter_init(&c->stripes[0], 0);
-               struct genradix_iter src_iter = genradix_iter_init(&c->stripes[1], 0);
-               struct stripe *dst, *src;
-
-               c->ec_stripes_heap.used = 0;
-
-               while ((dst = genradix_iter_peek(&dst_iter, &c->stripes[0])) &&
-                      (src = genradix_iter_peek(&src_iter, &c->stripes[1]))) {
-                       *dst = *src;
-
-                       if (dst->alive)
-                               bch2_stripes_heap_insert(c, dst, dst_iter.pos);
-
-                       genradix_iter_advance(&dst_iter, &c->stripes[0]);
-                       genradix_iter_advance(&src_iter, &c->stripes[1]);
-               }
-       }
-
-       for_each_member_device(ca, c, i) {
-               struct bucket_array *src = __bucket_array(ca, 1);
-
-               memcpy(__bucket_array(ca, 0), src,
-                      sizeof(struct bucket_array) +
-                      sizeof(struct bucket) * src->nbuckets);
-       };
-
-       for_each_member_device(ca, c, i) {
-               unsigned nr = sizeof(struct bch_dev_usage) / sizeof(u64);
-               struct bch_dev_usage *dst = (void *)
-                       acc_percpu_u64s((void *) ca->usage[0], nr);
-               struct bch_dev_usage *src = (void *)
-                       acc_percpu_u64s((void *) ca->usage[1], nr);
-
-               *dst = *src;
-       }
-
-       {
-               unsigned nr = sizeof(struct bch_fs_usage) / sizeof(u64) +
-                       c->replicas.nr;
-               struct bch_fs_usage *dst = (void *)
-                       acc_percpu_u64s((void *) c->usage[0], nr);
-               struct bch_fs_usage *src = (void *)
-                       acc_percpu_u64s((void *) c->usage[1], nr);
-
-               memcpy(&dst->s.gc_start[0],
-                      &src->s.gc_start[0],
-                      nr * sizeof(u64) - offsetof(typeof(*dst), s.gc_start));
-       }
-}
-
-static void bch2_gc_done(struct bch_fs *c, bool initial)
+static int bch2_gc_done(struct bch_fs *c,
+                       bool initial, bool metadata_only)
 {
        struct bch_dev *ca;
+       bool verify = !metadata_only &&
+               (!initial ||
+                (c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)));
        unsigned i;
+       int ret = 0;
 
 #define copy_field(_f, _msg, ...)                                      \
        if (dst->_f != src->_f) {                                       \
-               bch_err(c, _msg ": got %llu, should be %llu, fixing"    \
-                       , ##__VA_ARGS__, dst->_f, src->_f);             \
+               if (verify)                                             \
+                       fsck_err(c, _msg ": got %llu, should be %llu"   \
+                               , ##__VA_ARGS__, dst->_f, src->_f);     \
                dst->_f = src->_f;                                      \
        }
 #define copy_stripe_field(_f, _msg, ...)                               \
        if (dst->_f != src->_f) {                                       \
-               bch_err_ratelimited(c, "stripe %zu has wrong "_msg      \
-                       ": got %u, should be %u, fixing",               \
-                       dst_iter.pos, ##__VA_ARGS__,                    \
-                       dst->_f, src->_f);                              \
+               if (verify)                                             \
+                       fsck_err(c, "stripe %zu has wrong "_msg         \
+                               ": got %u, should be %u",               \
+                               dst_iter.pos, ##__VA_ARGS__,            \
+                               dst->_f, src->_f);                      \
                dst->_f = src->_f;                                      \
+               dst->dirty = true;                                      \
        }
 #define copy_bucket_field(_f)                                          \
        if (dst->b[b].mark._f != src->b[b].mark._f) {                   \
-               bch_err_ratelimited(c, "dev %u bucket %zu has wrong " #_f\
-                       ": got %u, should be %u, fixing",               \
-                       i, b, dst->b[b].mark._f, src->b[b].mark._f);    \
+               if (verify)                                             \
+                       fsck_err(c, "dev %u bucket %zu has wrong " #_f  \
+                               ": got %u, should be %u", i, b,         \
+                               dst->b[b].mark._f, src->b[b].mark._f);  \
                dst->b[b]._mark._f = src->b[b].mark._f;                 \
        }
 #define copy_dev_field(_f, _msg, ...)                                  \
@@ -595,14 +589,7 @@ static void bch2_gc_done(struct bch_fs *c, bool initial)
 #define copy_fs_field(_f, _msg, ...)                                   \
        copy_field(_f, "fs has wrong " _msg, ##__VA_ARGS__)
 
-       percpu_down_write(&c->mark_lock);
-
-       if (initial) {
-               bch2_gc_done_nocheck(c);
-               goto out;
-       }
-
-       {
+       if (!metadata_only) {
                struct genradix_iter dst_iter = genradix_iter_init(&c->stripes[0], 0);
                struct genradix_iter src_iter = genradix_iter_init(&c->stripes[1], 0);
                struct stripe *dst, *src;
@@ -612,16 +599,18 @@ static void bch2_gc_done(struct bch_fs *c, bool initial)
 
                while ((dst = genradix_iter_peek(&dst_iter, &c->stripes[0])) &&
                       (src = genradix_iter_peek(&src_iter, &c->stripes[1]))) {
+                       BUG_ON(src_iter.pos != dst_iter.pos);
+
                        copy_stripe_field(alive,        "alive");
                        copy_stripe_field(sectors,      "sectors");
                        copy_stripe_field(algorithm,    "algorithm");
                        copy_stripe_field(nr_blocks,    "nr_blocks");
                        copy_stripe_field(nr_redundant, "nr_redundant");
-                       copy_stripe_field(blocks_nonempty.counter,
+                       copy_stripe_field(blocks_nonempty,
                                          "blocks_nonempty");
 
                        for (i = 0; i < ARRAY_SIZE(dst->block_sectors); i++)
-                               copy_stripe_field(block_sectors[i].counter,
+                               copy_stripe_field(block_sectors[i],
                                                  "block_sectors[%u]", i);
 
                        if (dst->alive)
@@ -637,12 +626,6 @@ static void bch2_gc_done(struct bch_fs *c, bool initial)
                struct bucket_array *src = __bucket_array(ca, 1);
                size_t b;
 
-               if (initial) {
-                       memcpy(dst, src,
-                              sizeof(struct bucket_array) +
-                              sizeof(struct bucket) * dst->nbuckets);
-               }
-
                for (b = 0; b < src->nbuckets; b++) {
                        copy_bucket_field(gen);
                        copy_bucket_field(data_type);
@@ -650,87 +633,76 @@ static void bch2_gc_done(struct bch_fs *c, bool initial)
                        copy_bucket_field(stripe);
                        copy_bucket_field(dirty_sectors);
                        copy_bucket_field(cached_sectors);
+
+                       dst->b[b].oldest_gen = src->b[b].oldest_gen;
                }
        };
 
-       for_each_member_device(ca, c, i) {
-               unsigned nr = sizeof(struct bch_dev_usage) / sizeof(u64);
-               struct bch_dev_usage *dst = (void *)
-                       acc_percpu_u64s((void *) ca->usage[0], nr);
-               struct bch_dev_usage *src = (void *)
-                       acc_percpu_u64s((void *) ca->usage[1], nr);
-               unsigned b;
-
-               for (b = 0; b < BCH_DATA_NR; b++)
-                       copy_dev_field(buckets[b],
-                                      "buckets[%s]", bch2_data_types[b]);
-               copy_dev_field(buckets_alloc, "buckets_alloc");
-               copy_dev_field(buckets_ec, "buckets_ec");
-
-               for (b = 0; b < BCH_DATA_NR; b++)
-                       copy_dev_field(sectors[b],
-                                      "sectors[%s]", bch2_data_types[b]);
-               copy_dev_field(sectors_fragmented,
-                              "sectors_fragmented");
-       }
+       bch2_fs_usage_acc_to_base(c, 0);
+       bch2_fs_usage_acc_to_base(c, 1);
+
+       bch2_dev_usage_from_buckets(c);
 
        {
-               unsigned nr = sizeof(struct bch_fs_usage) / sizeof(u64) +
-                       c->replicas.nr;
-               struct bch_fs_usage *dst = (void *)
-                       acc_percpu_u64s((void *) c->usage[0], nr);
+               unsigned nr = fs_usage_u64s(c);
+               struct bch_fs_usage *dst = c->usage_base;
                struct bch_fs_usage *src = (void *)
-                       acc_percpu_u64s((void *) c->usage[1], nr);
+                       bch2_acc_percpu_u64s((void *) c->usage_gc, nr);
+
+               copy_fs_field(hidden,           "hidden");
+               copy_fs_field(btree,            "btree");
 
-               copy_fs_field(s.hidden,         "hidden");
-               copy_fs_field(s.data,           "data");
-               copy_fs_field(s.cached,         "cached");
-               copy_fs_field(s.reserved,       "reserved");
-               copy_fs_field(s.nr_inodes,      "nr_inodes");
+               if (!metadata_only) {
+                       copy_fs_field(data,     "data");
+                       copy_fs_field(cached,   "cached");
+                       copy_fs_field(reserved, "reserved");
+                       copy_fs_field(nr_inodes,"nr_inodes");
 
-               for (i = 0; i < BCH_REPLICAS_MAX; i++)
-                       copy_fs_field(persistent_reserved[i],
-                                     "persistent_reserved[%i]", i);
+                       for (i = 0; i < BCH_REPLICAS_MAX; i++)
+                               copy_fs_field(persistent_reserved[i],
+                                             "persistent_reserved[%i]", i);
+               }
 
                for (i = 0; i < c->replicas.nr; i++) {
-                       /*
-                        * XXX: print out replicas entry
-                        */
-                       copy_fs_field(data[i], "data[%i]", i);
+                       struct bch_replicas_entry *e =
+                               cpu_replicas_entry(&c->replicas, i);
+                       char buf[80];
+
+                       if (metadata_only &&
+                           (e->data_type == BCH_DATA_USER ||
+                            e->data_type == BCH_DATA_CACHED))
+                               continue;
+
+                       bch2_replicas_entry_to_text(&PBUF(buf), e);
+
+                       copy_fs_field(replicas[i], "%s", buf);
                }
        }
-out:
-       percpu_up_write(&c->mark_lock);
 
 #undef copy_fs_field
 #undef copy_dev_field
 #undef copy_bucket_field
 #undef copy_stripe_field
 #undef copy_field
+fsck_err:
+       return ret;
 }
 
-static int bch2_gc_start(struct bch_fs *c)
+static int bch2_gc_start(struct bch_fs *c,
+                        bool metadata_only)
 {
        struct bch_dev *ca;
        unsigned i;
+       int ret;
 
-       /*
-        * indicate to stripe code that we need to allocate for the gc stripes
-        * radix tree, too
-        */
-       gc_pos_set(c, gc_phase(GC_PHASE_START));
-
-       percpu_down_write(&c->mark_lock);
-       BUG_ON(c->usage[1]);
-
-       c->usage[1] = __alloc_percpu_gfp(sizeof(struct bch_fs_usage) +
-                                        sizeof(u64) * c->replicas.nr,
-                                        sizeof(u64),
-                                        GFP_KERNEL);
-       percpu_up_write(&c->mark_lock);
+       BUG_ON(c->usage_gc);
 
-       if (!c->usage[1])
+       c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
+                                        sizeof(u64), GFP_KERNEL);
+       if (!c->usage_gc) {
+               bch_err(c, "error allocating c->usage_gc");
                return -ENOMEM;
+       }
 
        for_each_member_device(ca, c, i) {
                BUG_ON(ca->buckets[1]);
@@ -741,18 +713,32 @@ static int bch2_gc_start(struct bch_fs *c)
                                GFP_KERNEL|__GFP_ZERO);
                if (!ca->buckets[1]) {
                        percpu_ref_put(&ca->ref);
+                       bch_err(c, "error allocating ca->buckets[gc]");
                        return -ENOMEM;
                }
 
                ca->usage[1] = alloc_percpu(struct bch_dev_usage);
                if (!ca->usage[1]) {
+                       bch_err(c, "error allocating ca->usage[gc]");
                        percpu_ref_put(&ca->ref);
                        return -ENOMEM;
                }
        }
 
+       ret = bch2_ec_mem_alloc(c, true);
+       if (ret) {
+               bch_err(c, "error allocating ec gc mem");
+               return ret;
+       }
+
        percpu_down_write(&c->mark_lock);
 
+       /*
+        * indicate to stripe code that we need to allocate for the gc stripes
+        * radix tree, too
+        */
+       gc_pos_set(c, gc_phase(GC_PHASE_START));
+
        for_each_member_device(ca, c, i) {
                struct bucket_array *dst = __bucket_array(ca, 1);
                struct bucket_array *src = __bucket_array(ca, 0);
@@ -761,13 +747,25 @@ static int bch2_gc_start(struct bch_fs *c)
                dst->first_bucket       = src->first_bucket;
                dst->nbuckets           = src->nbuckets;
 
-               for (b = 0; b < src->nbuckets; b++)
-                       dst->b[b]._mark.gen = src->b[b].mark.gen;
+               for (b = 0; b < src->nbuckets; b++) {
+                       struct bucket *d = &dst->b[b];
+                       struct bucket *s = &src->b[b];
+
+                       d->_mark.gen = dst->b[b].oldest_gen = s->mark.gen;
+                       d->gen_valid = s->gen_valid;
+
+                       if (metadata_only &&
+                           (s->mark.data_type == BCH_DATA_USER ||
+                            s->mark.data_type == BCH_DATA_CACHED)) {
+                               d->_mark = s->mark;
+                               d->_mark.owned_by_allocator = 0;
+                       }
+               }
        };
 
        percpu_up_write(&c->mark_lock);
 
-       return bch2_ec_mem_alloc(c, true);
+       return 0;
 }
 
 /**
@@ -788,7 +786,8 @@ static int bch2_gc_start(struct bch_fs *c)
  *    move around - if references move backwards in the ordering GC
  *    uses, GC could skip past them
  */
-int bch2_gc(struct bch_fs *c, struct list_head *journal, bool initial)
+int bch2_gc(struct bch_fs *c, struct journal_keys *journal_keys,
+           bool initial, bool metadata_only)
 {
        struct bch_dev *ca;
        u64 start_time = local_clock();
@@ -799,13 +798,13 @@ int bch2_gc(struct bch_fs *c, struct list_head *journal, bool initial)
 
        down_write(&c->gc_lock);
 again:
-       ret = bch2_gc_start(c);
+       ret = bch2_gc_start(c, metadata_only);
        if (ret)
                goto out;
 
        bch2_mark_superblocks(c);
 
-       ret = bch2_gc_btrees(c, journal, initial);
+       ret = bch2_gc_btrees(c, journal_keys, initial, metadata_only);
        if (ret)
                goto out;
 
@@ -814,13 +813,23 @@ again:
 
        c->gc_count++;
 out:
-       if (!ret && test_bit(BCH_FS_FIXED_GENS, &c->flags)) {
+       if (!ret &&
+           (test_bit(BCH_FS_FIXED_GENS, &c->flags) ||
+            (!iter && test_restart_gc(c)))) {
                /*
                 * XXX: make sure gens we fixed got saved
                 */
                if (iter++ <= 2) {
                        bch_info(c, "Fixed gens, restarting mark and sweep:");
                        clear_bit(BCH_FS_FIXED_GENS, &c->flags);
+                       __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
+
+                       percpu_down_write(&c->mark_lock);
+                       bch2_gc_free(c);
+                       percpu_up_write(&c->mark_lock);
+                       /* flush fsck errors, reset counters */
+                       bch2_flush_fsck_errs(c);
+
                        goto again;
                }
 
@@ -828,17 +837,24 @@ out:
                ret = -EINVAL;
        }
 
-       if (!ret)
-               bch2_gc_done(c, initial);
+       if (!ret) {
+               bch2_journal_block(&c->journal);
+
+               percpu_down_write(&c->mark_lock);
+               ret = bch2_gc_done(c, initial, metadata_only);
+
+               bch2_journal_unblock(&c->journal);
+       } else {
+               percpu_down_write(&c->mark_lock);
+       }
 
        /* Indicates that gc is no longer in progress: */
        __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
 
        bch2_gc_free(c);
-       up_write(&c->gc_lock);
+       percpu_up_write(&c->mark_lock);
 
-       if (!ret && initial)
-               set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
+       up_write(&c->gc_lock);
 
        trace_gc_end(c);
        bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
@@ -923,7 +939,7 @@ static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
                return;
        }
 
-       as = bch2_btree_update_start(c, iter->btree_id,
+       as = bch2_btree_update_start(iter->trans, iter->btree_id,
                        btree_update_reserve_required(c, parent) + nr_old_nodes,
                        BTREE_INSERT_NOFAIL|
                        BTREE_INSERT_USE_RESERVE,
@@ -965,7 +981,7 @@ static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
                     k < vstruct_last(s2) &&
                     vstruct_blocks_plus(n1->data, c->block_bits,
                                         u64s + k->u64s) <= blocks;
-                    k = bkey_next(k)) {
+                    k = bkey_next_skip_noops(k, vstruct_last(s2))) {
                        last = k;
                        u64s += k->u64s;
                }
@@ -994,9 +1010,7 @@ static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
                        n1->key.k.p = n1->data->max_key =
                                bkey_unpack_pos(n1, last);
 
-                       n2->data->min_key =
-                               btree_type_successor(iter->btree_id,
-                                                    n1->data->max_key);
+                       n2->data->min_key = bkey_successor(n1->data->max_key);
 
                        memcpy_u64s(vstruct_last(s1),
                                    s2->start, u64s);
@@ -1083,18 +1097,20 @@ next:
                        old_nodes[i] = new_nodes[i];
                } else {
                        old_nodes[i] = NULL;
-                       if (new_nodes[i])
-                               six_unlock_intent(&new_nodes[i]->lock);
                }
        }
 
+       for (i = 0; i < nr_new_nodes; i++)
+               six_unlock_intent(&new_nodes[i]->lock);
+
        bch2_btree_update_done(as);
        bch2_keylist_free(&keylist, NULL);
 }
 
 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
 {
-       struct btree_iter iter;
+       struct btree_trans trans;
+       struct btree_iter *iter;
        struct btree *b;
        bool kthread = (current->flags & PF_KTHREAD) != 0;
        unsigned i;
@@ -1103,6 +1119,8 @@ static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
        struct btree *merge[GC_MERGE_NODES];
        u32 lock_seq[GC_MERGE_NODES];
 
+       bch2_trans_init(&trans, c, 0, 0);
+
        /*
         * XXX: We don't have a good way of positively matching on sibling nodes
         * that have the same parent - this code works by handling the cases
@@ -1112,7 +1130,7 @@ static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
         */
        memset(merge, 0, sizeof(merge));
 
-       __for_each_btree_node(&iter, c, btree_id, POS_MIN,
+       __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
                              BTREE_MAX_DEPTH, 0,
                              BTREE_ITER_PREFETCH, b) {
                memmove(merge + 1, merge,
@@ -1134,7 +1152,7 @@ static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
                }
                memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
 
-               bch2_coalesce_nodes(c, &iter, merge);
+               bch2_coalesce_nodes(c, iter, merge);
 
                for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
                        lock_seq[i] = merge[i]->lock.state.seq;
@@ -1144,23 +1162,23 @@ static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
                lock_seq[0] = merge[0]->lock.state.seq;
 
                if (kthread && kthread_should_stop()) {
-                       bch2_btree_iter_unlock(&iter);
+                       bch2_trans_exit(&trans);
                        return -ESHUTDOWN;
                }
 
-               bch2_btree_iter_cond_resched(&iter);
+               bch2_trans_cond_resched(&trans);
 
                /*
                 * If the parent node wasn't relocked, it might have been split
                 * and the nodes in our sliding window might not have the same
                 * parent anymore - blow away the sliding window:
                 */
-               if (btree_iter_node(&iter, iter.level + 1) &&
-                   !btree_node_intent_locked(&iter, iter.level + 1))
+               if (btree_iter_node(iter, iter->level + 1) &&
+                   !btree_node_intent_locked(iter, iter->level + 1))
                        memset(merge + 1, 0,
                               (GC_MERGE_NODES - 1) * sizeof(merge[0]));
        }
-       return bch2_btree_iter_unlock(&iter);
+       return bch2_trans_exit(&trans);
 }
 
 /**
@@ -1229,7 +1247,7 @@ static int bch2_gc_thread(void *arg)
                last = atomic_long_read(&clock->now);
                last_kick = atomic_read(&c->kick_gc);
 
-               ret = bch2_gc(c, NULL, false);
+               ret = bch2_gc(c, NULL, false, false);
                if (ret)
                        bch_err(c, "btree gc failed: %i", ret);
 
@@ -1267,19 +1285,3 @@ int bch2_gc_thread_start(struct bch_fs *c)
        wake_up_process(p);
        return 0;
 }
-
-/* Initial GC computes bucket marks during startup */
-
-int bch2_initial_gc(struct bch_fs *c, struct list_head *journal)
-{
-       int ret = bch2_gc(c, journal, true);
-
-       /*
-        * Skip past versions that might have possibly been used (as nonces),
-        * but hadn't had their pointers written:
-        */
-       if (c->sb.encryption_type)
-               atomic64_add(1 << 16, &c->key_version);
-
-       return ret;
-}