]> git.sesse.net Git - bcachefs-tools-debian/blobdiff - libbcachefs/btree_iter.c
Update bcachefs sources to 9a555a741e80 bcachefs: omit alignment attribute on big...
[bcachefs-tools-debian] / libbcachefs / btree_iter.c
index 66778bd9206621cbe2efc4fef980144ff98c0eff..20b32c71b20af93626fe42da5b202751c237a979 100644 (file)
@@ -5,6 +5,7 @@
 #include "bkey_buf.h"
 #include "btree_cache.h"
 #include "btree_iter.h"
+#include "btree_journal_iter.h"
 #include "btree_key_cache.h"
 #include "btree_locking.h"
 #include "btree_update.h"
 #include "error.h"
 #include "extents.h"
 #include "journal.h"
-#include "recovery.h"
+#include "journal_io.h"
 #include "replicas.h"
-#include "subvolume.h"
+#include "snapshot.h"
+#include "trace.h"
 
+#include <linux/random.h>
 #include <linux/prefetch.h>
-#include <trace/events/bcachefs.h>
-
-static void btree_trans_verify_sorted(struct btree_trans *);
-static void btree_path_check_sort(struct btree_trans *, struct btree_path *, int);
 
 static inline void btree_path_list_remove(struct btree_trans *, struct btree_path *);
-static inline void btree_path_list_add(struct btree_trans *, struct btree_path *,
-                                      struct btree_path *);
+static inline void btree_path_list_add(struct btree_trans *,
+                       btree_path_idx_t, btree_path_idx_t);
 
 static inline unsigned long btree_iter_ip_allocated(struct btree_iter *iter)
 {
-#ifdef CONFIG_BCACHEFS_DEBUG
+#ifdef TRACK_PATH_ALLOCATED
        return iter->ip_allocated;
 #else
        return 0;
 #endif
 }
 
-static struct btree_path *btree_path_alloc(struct btree_trans *, struct btree_path *);
-
-/*
- * Unlocks before scheduling
- * Note: does not revalidate iterator
- */
-static inline int bch2_trans_cond_resched(struct btree_trans *trans)
-{
-       if (need_resched() || race_fault()) {
-               bch2_trans_unlock(trans);
-               schedule();
-               return bch2_trans_relock(trans) ? 0 : -EINTR;
-       } else {
-               return 0;
-       }
-}
+static btree_path_idx_t btree_path_alloc(struct btree_trans *, btree_path_idx_t);
+static void bch2_trans_srcu_lock(struct btree_trans *);
 
 static inline int __btree_path_cmp(const struct btree_path *l,
                                   enum btree_id        r_btree_id,
@@ -99,18 +84,12 @@ static inline struct bpos bkey_predecessor(struct btree_iter *iter, struct bpos
        return p;
 }
 
-static inline bool is_btree_node(struct btree_path *path, unsigned l)
-{
-       return l < BTREE_MAX_DEPTH &&
-               (unsigned long) path->l[l].b >= 128;
-}
-
 static inline struct bpos btree_iter_search_key(struct btree_iter *iter)
 {
        struct bpos pos = iter->pos;
 
        if ((iter->flags & BTREE_ITER_IS_EXTENTS) &&
-           bkey_cmp(pos, POS_MAX))
+           !bkey_eq(pos, POS_MAX))
                pos = bkey_successor(iter, pos);
        return pos;
 }
@@ -118,13 +97,13 @@ static inline struct bpos btree_iter_search_key(struct btree_iter *iter)
 static inline bool btree_path_pos_before_node(struct btree_path *path,
                                              struct btree *b)
 {
-       return bpos_cmp(path->pos, b->data->min_key) < 0;
+       return bpos_lt(path->pos, b->data->min_key);
 }
 
 static inline bool btree_path_pos_after_node(struct btree_path *path,
                                             struct btree *b)
 {
-       return bpos_cmp(b->key.k.p, path->pos) < 0;
+       return bpos_gt(path->pos, b->key.k.p);
 }
 
 static inline bool btree_path_pos_in_node(struct btree_path *path,
@@ -135,432 +114,6 @@ static inline bool btree_path_pos_in_node(struct btree_path *path,
                !btree_path_pos_after_node(path, b);
 }
 
-/* Btree node locking: */
-
-void bch2_btree_node_unlock_write(struct btree_trans *trans,
-                       struct btree_path *path, struct btree *b)
-{
-       bch2_btree_node_unlock_write_inlined(trans, path, b);
-}
-
-void __bch2_btree_node_lock_write(struct btree_trans *trans, struct btree *b)
-{
-       struct btree_path *linked;
-       unsigned readers = 0;
-
-       trans_for_each_path(trans, linked)
-               if (linked->l[b->c.level].b == b &&
-                   btree_node_read_locked(linked, b->c.level))
-                       readers++;
-
-       /*
-        * Must drop our read locks before calling six_lock_write() -
-        * six_unlock() won't do wakeups until the reader count
-        * goes to 0, and it's safe because we have the node intent
-        * locked:
-        */
-       if (!b->c.lock.readers)
-               atomic64_sub(__SIX_VAL(read_lock, readers),
-                            &b->c.lock.state.counter);
-       else
-               this_cpu_sub(*b->c.lock.readers, readers);
-
-       six_lock_write(&b->c.lock, NULL, NULL);
-
-       if (!b->c.lock.readers)
-               atomic64_add(__SIX_VAL(read_lock, readers),
-                            &b->c.lock.state.counter);
-       else
-               this_cpu_add(*b->c.lock.readers, readers);
-}
-
-bool __bch2_btree_node_relock(struct btree_trans *trans,
-                             struct btree_path *path, unsigned level)
-{
-       struct btree *b = btree_path_node(path, level);
-       int want = __btree_lock_want(path, level);
-
-       if (!is_btree_node(path, level))
-               goto fail;
-
-       if (race_fault())
-               goto fail;
-
-       if (six_relock_type(&b->c.lock, want, path->l[level].lock_seq) ||
-           (btree_node_lock_seq_matches(path, b, level) &&
-            btree_node_lock_increment(trans, b, level, want))) {
-               mark_btree_node_locked(path, level, want);
-               return true;
-       }
-fail:
-       trace_btree_node_relock_fail(trans->fn, _RET_IP_,
-                                    path->btree_id,
-                                    &path->pos,
-                                    (unsigned long) b,
-                                    path->l[level].lock_seq,
-                                    is_btree_node(path, level) ? b->c.lock.state.seq : 0);
-       return false;
-}
-
-bool bch2_btree_node_upgrade(struct btree_trans *trans,
-                            struct btree_path *path, unsigned level)
-{
-       struct btree *b = path->l[level].b;
-
-       if (!is_btree_node(path, level))
-               return false;
-
-       switch (btree_lock_want(path, level)) {
-       case BTREE_NODE_UNLOCKED:
-               BUG_ON(btree_node_locked(path, level));
-               return true;
-       case BTREE_NODE_READ_LOCKED:
-               BUG_ON(btree_node_intent_locked(path, level));
-               return bch2_btree_node_relock(trans, path, level);
-       case BTREE_NODE_INTENT_LOCKED:
-               break;
-       }
-
-       if (btree_node_intent_locked(path, level))
-               return true;
-
-       if (race_fault())
-               return false;
-
-       if (btree_node_locked(path, level)
-           ? six_lock_tryupgrade(&b->c.lock)
-           : six_relock_type(&b->c.lock, SIX_LOCK_intent, path->l[level].lock_seq))
-               goto success;
-
-       if (btree_node_lock_seq_matches(path, b, level) &&
-           btree_node_lock_increment(trans, b, level, BTREE_NODE_INTENT_LOCKED)) {
-               btree_node_unlock(path, level);
-               goto success;
-       }
-
-       return false;
-success:
-       mark_btree_node_intent_locked(path, level);
-       return true;
-}
-
-static inline bool btree_path_get_locks(struct btree_trans *trans,
-                                       struct btree_path *path,
-                                       bool upgrade)
-{
-       unsigned l = path->level;
-       int fail_idx = -1;
-
-       do {
-               if (!btree_path_node(path, l))
-                       break;
-
-               if (!(upgrade
-                     ? bch2_btree_node_upgrade(trans, path, l)
-                     : bch2_btree_node_relock(trans, path, l)))
-                       fail_idx = l;
-
-               l++;
-       } while (l < path->locks_want);
-
-       /*
-        * When we fail to get a lock, we have to ensure that any child nodes
-        * can't be relocked so bch2_btree_path_traverse has to walk back up to
-        * the node that we failed to relock:
-        */
-       if (fail_idx >= 0) {
-               __bch2_btree_path_unlock(path);
-               btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
-
-               do {
-                       path->l[fail_idx].b = BTREE_ITER_NO_NODE_GET_LOCKS;
-                       --fail_idx;
-               } while (fail_idx >= 0);
-       }
-
-       if (path->uptodate == BTREE_ITER_NEED_RELOCK)
-               path->uptodate = BTREE_ITER_UPTODATE;
-
-       bch2_trans_verify_locks(trans);
-
-       return path->uptodate < BTREE_ITER_NEED_RELOCK;
-}
-
-static struct bpos btree_node_pos(struct btree_bkey_cached_common *_b,
-                                 bool cached)
-{
-       return !cached
-               ? container_of(_b, struct btree, c)->key.k.p
-               : container_of(_b, struct bkey_cached, c)->key.pos;
-}
-
-/* Slowpath: */
-bool __bch2_btree_node_lock(struct btree_trans *trans,
-                           struct btree_path *path,
-                           struct btree *b,
-                           struct bpos pos, unsigned level,
-                           enum six_lock_type type,
-                           six_lock_should_sleep_fn should_sleep_fn, void *p,
-                           unsigned long ip)
-{
-       struct btree_path *linked;
-       unsigned reason;
-
-       /* Check if it's safe to block: */
-       trans_for_each_path(trans, linked) {
-               if (!linked->nodes_locked)
-                       continue;
-
-               /*
-                * Can't block taking an intent lock if we have _any_ nodes read
-                * locked:
-                *
-                * - Our read lock blocks another thread with an intent lock on
-                *   the same node from getting a write lock, and thus from
-                *   dropping its intent lock
-                *
-                * - And the other thread may have multiple nodes intent locked:
-                *   both the node we want to intent lock, and the node we
-                *   already have read locked - deadlock:
-                */
-               if (type == SIX_LOCK_intent &&
-                   linked->nodes_locked != linked->nodes_intent_locked) {
-                       reason = 1;
-                       goto deadlock;
-               }
-
-               if (linked->btree_id != path->btree_id) {
-                       if (linked->btree_id < path->btree_id)
-                               continue;
-
-                       reason = 3;
-                       goto deadlock;
-               }
-
-               /*
-                * Within the same btree, non-cached paths come before cached
-                * paths:
-                */
-               if (linked->cached != path->cached) {
-                       if (!linked->cached)
-                               continue;
-
-                       reason = 4;
-                       goto deadlock;
-               }
-
-               /*
-                * Interior nodes must be locked before their descendants: if
-                * another path has possible descendants locked of the node
-                * we're about to lock, it must have the ancestors locked too:
-                */
-               if (level > __fls(linked->nodes_locked)) {
-                       reason = 5;
-                       goto deadlock;
-               }
-
-               /* Must lock btree nodes in key order: */
-               if (btree_node_locked(linked, level) &&
-                   bpos_cmp(pos, btree_node_pos((void *) linked->l[level].b,
-                                                linked->cached)) <= 0) {
-                       BUG_ON(trans->in_traverse_all);
-                       reason = 7;
-                       goto deadlock;
-               }
-       }
-
-       return btree_node_lock_type(trans, path, b, pos, level,
-                                   type, should_sleep_fn, p);
-deadlock:
-       trace_trans_restart_would_deadlock(trans->fn, ip,
-                       trans->in_traverse_all, reason,
-                       linked->btree_id,
-                       linked->cached,
-                       &linked->pos,
-                       path->btree_id,
-                       path->cached,
-                       &pos);
-       btree_trans_restart(trans);
-       return false;
-}
-
-/* Btree iterator locking: */
-
-#ifdef CONFIG_BCACHEFS_DEBUG
-
-static void bch2_btree_path_verify_locks(struct btree_path *path)
-{
-       unsigned l;
-
-       if (!path->nodes_locked) {
-               BUG_ON(path->uptodate == BTREE_ITER_UPTODATE &&
-                      btree_path_node(path, path->level));
-               return;
-       }
-
-       for (l = 0; btree_path_node(path, l); l++)
-               BUG_ON(btree_lock_want(path, l) !=
-                      btree_node_locked_type(path, l));
-}
-
-void bch2_trans_verify_locks(struct btree_trans *trans)
-{
-       struct btree_path *path;
-
-       trans_for_each_path(trans, path)
-               bch2_btree_path_verify_locks(path);
-}
-#else
-static inline void bch2_btree_path_verify_locks(struct btree_path *path) {}
-#endif
-
-/* Btree path locking: */
-
-/*
- * Only for btree_cache.c - only relocks intent locks
- */
-bool bch2_btree_path_relock_intent(struct btree_trans *trans,
-                                  struct btree_path *path)
-{
-       unsigned l;
-
-       for (l = path->level;
-            l < path->locks_want && btree_path_node(path, l);
-            l++) {
-               if (!bch2_btree_node_relock(trans, path, l)) {
-                       __bch2_btree_path_unlock(path);
-                       btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
-                       trace_trans_restart_relock_path_intent(trans->fn, _RET_IP_,
-                                                  path->btree_id, &path->pos);
-                       btree_trans_restart(trans);
-                       return false;
-               }
-       }
-
-       return true;
-}
-
-__flatten
-static bool bch2_btree_path_relock(struct btree_trans *trans,
-                       struct btree_path *path, unsigned long trace_ip)
-{
-       bool ret = btree_path_get_locks(trans, path, false);
-
-       if (!ret) {
-               trace_trans_restart_relock_path(trans->fn, trace_ip,
-                                               path->btree_id, &path->pos);
-               btree_trans_restart(trans);
-       }
-       return ret;
-}
-
-bool __bch2_btree_path_upgrade(struct btree_trans *trans,
-                              struct btree_path *path,
-                              unsigned new_locks_want)
-{
-       struct btree_path *linked;
-
-       EBUG_ON(path->locks_want >= new_locks_want);
-
-       path->locks_want = new_locks_want;
-
-       if (btree_path_get_locks(trans, path, true))
-               return true;
-
-       /*
-        * XXX: this is ugly - we'd prefer to not be mucking with other
-        * iterators in the btree_trans here.
-        *
-        * On failure to upgrade the iterator, setting iter->locks_want and
-        * calling get_locks() is sufficient to make bch2_btree_path_traverse()
-        * get the locks we want on transaction restart.
-        *
-        * But if this iterator was a clone, on transaction restart what we did
-        * to this iterator isn't going to be preserved.
-        *
-        * Possibly we could add an iterator field for the parent iterator when
-        * an iterator is a copy - for now, we'll just upgrade any other
-        * iterators with the same btree id.
-        *
-        * The code below used to be needed to ensure ancestor nodes get locked
-        * before interior nodes - now that's handled by
-        * bch2_btree_path_traverse_all().
-        */
-       trans_for_each_path(trans, linked)
-               if (linked != path &&
-                   linked->cached == path->cached &&
-                   linked->btree_id == path->btree_id &&
-                   linked->locks_want < new_locks_want) {
-                       linked->locks_want = new_locks_want;
-                       btree_path_get_locks(trans, linked, true);
-               }
-
-       return false;
-}
-
-void __bch2_btree_path_downgrade(struct btree_path *path,
-                                unsigned new_locks_want)
-{
-       unsigned l;
-
-       EBUG_ON(path->locks_want < new_locks_want);
-
-       path->locks_want = new_locks_want;
-
-       while (path->nodes_locked &&
-              (l = __fls(path->nodes_locked)) >= path->locks_want) {
-               if (l > path->level) {
-                       btree_node_unlock(path, l);
-               } else {
-                       if (btree_node_intent_locked(path, l)) {
-                               six_lock_downgrade(&path->l[l].b->c.lock);
-                               path->nodes_intent_locked ^= 1 << l;
-                       }
-                       break;
-               }
-       }
-
-       bch2_btree_path_verify_locks(path);
-}
-
-void bch2_trans_downgrade(struct btree_trans *trans)
-{
-       struct btree_path *path;
-
-       trans_for_each_path(trans, path)
-               bch2_btree_path_downgrade(path);
-}
-
-/* Btree transaction locking: */
-
-bool bch2_trans_relock(struct btree_trans *trans)
-{
-       struct btree_path *path;
-
-       if (unlikely(trans->restarted))
-               return false;
-
-       trans_for_each_path(trans, path)
-               if (path->should_be_locked &&
-                   !bch2_btree_path_relock(trans, path, _RET_IP_)) {
-                       trace_trans_restart_relock(trans->fn, _RET_IP_,
-                                       path->btree_id, &path->pos);
-                       BUG_ON(!trans->restarted);
-                       return false;
-               }
-       return true;
-}
-
-void bch2_trans_unlock(struct btree_trans *trans)
-{
-       struct btree_path *path;
-
-       trans_for_each_path(trans, path)
-               __bch2_btree_path_unlock(path);
-
-       BUG_ON(lock_class_is_held(&bch2_btree_node_lock_key));
-}
-
 /* Btree iterator: */
 
 #ifdef CONFIG_BCACHEFS_DEBUG
@@ -576,10 +129,10 @@ static void bch2_btree_path_verify_cached(struct btree_trans *trans,
 
        ck = (void *) path->l[0].b;
        BUG_ON(ck->key.btree_id != path->btree_id ||
-              bkey_cmp(ck->key.pos, path->pos));
+              !bkey_eq(ck->key.pos, path->pos));
 
        if (!locked)
-               btree_node_unlock(path, 0);
+               btree_node_unlock(trans, path, 0);
 }
 
 static void bch2_btree_path_verify_level(struct btree_trans *trans,
@@ -589,7 +142,9 @@ static void bch2_btree_path_verify_level(struct btree_trans *trans,
        struct btree_node_iter tmp;
        bool locked;
        struct bkey_packed *p, *k;
-       char buf1[100], buf2[100], buf3[100];
+       struct printbuf buf1 = PRINTBUF;
+       struct printbuf buf2 = PRINTBUF;
+       struct printbuf buf3 = PRINTBUF;
        const char *msg;
 
        if (!bch2_debug_check_iterators)
@@ -608,7 +163,7 @@ static void bch2_btree_path_verify_level(struct btree_trans *trans,
        if (!btree_path_node(path, level))
                return;
 
-       if (!bch2_btree_node_relock(trans, path, level))
+       if (!bch2_btree_node_relock_notrace(trans, path, level))
                return;
 
        BUG_ON(!btree_path_pos_in_node(path, l->b));
@@ -634,29 +189,32 @@ static void bch2_btree_path_verify_level(struct btree_trans *trans,
        }
 
        if (!locked)
-               btree_node_unlock(path, level);
+               btree_node_unlock(trans, path, level);
        return;
 err:
-       strcpy(buf2, "(none)");
-       strcpy(buf3, "(none)");
-
-       bch2_bpos_to_text(&PBUF(buf1), path->pos);
+       bch2_bpos_to_text(&buf1, path->pos);
 
        if (p) {
                struct bkey uk = bkey_unpack_key(l->b, p);
-               bch2_bkey_to_text(&PBUF(buf2), &uk);
+
+               bch2_bkey_to_text(&buf2, &uk);
+       } else {
+               prt_printf(&buf2, "(none)");
        }
 
        if (k) {
                struct bkey uk = bkey_unpack_key(l->b, k);
-               bch2_bkey_to_text(&PBUF(buf3), &uk);
+
+               bch2_bkey_to_text(&buf3, &uk);
+       } else {
+               prt_printf(&buf3, "(none)");
        }
 
        panic("path should be %s key at level %u:\n"
              "path pos %s\n"
              "prev key %s\n"
              "cur  key %s\n",
-             msg, level, buf1, buf2, buf3);
+             msg, level, buf1.buf, buf2.buf, buf3.buf);
 }
 
 static void bch2_btree_path_verify(struct btree_trans *trans,
@@ -670,7 +228,7 @@ static void bch2_btree_path_verify(struct btree_trans *trans,
        for (i = 0; i < (!path->cached ? BTREE_MAX_DEPTH : 1); i++) {
                if (!path->l[i].b) {
                        BUG_ON(!path->cached &&
-                              c->btree_roots[path->btree_id].b->c.level > i);
+                              bch2_btree_id_root(c, path->btree_id)->b->c.level > i);
                        break;
                }
 
@@ -683,8 +241,9 @@ static void bch2_btree_path_verify(struct btree_trans *trans,
 void bch2_trans_verify_paths(struct btree_trans *trans)
 {
        struct btree_path *path;
+       unsigned iter;
 
-       trans_for_each_path(trans, path)
+       trans_for_each_path(trans, path, iter)
                bch2_btree_path_verify(trans, path);
 }
 
@@ -694,18 +253,18 @@ static void bch2_btree_iter_verify(struct btree_iter *iter)
 
        BUG_ON(iter->btree_id >= BTREE_ID_NR);
 
-       BUG_ON(!!(iter->flags & BTREE_ITER_CACHED) != iter->path->cached);
+       BUG_ON(!!(iter->flags & BTREE_ITER_CACHED) != btree_iter_path(trans, iter)->cached);
 
        BUG_ON((iter->flags & BTREE_ITER_IS_EXTENTS) &&
               (iter->flags & BTREE_ITER_ALL_SNAPSHOTS));
 
        BUG_ON(!(iter->flags & __BTREE_ITER_ALL_SNAPSHOTS) &&
               (iter->flags & BTREE_ITER_ALL_SNAPSHOTS) &&
-              !btree_type_has_snapshots(iter->btree_id));
+              !btree_type_has_snapshot_field(iter->btree_id));
 
        if (iter->update_path)
-               bch2_btree_path_verify(trans, iter->update_path);
-       bch2_btree_path_verify(trans, iter->path);
+               bch2_btree_path_verify(trans, &trans->paths[iter->update_path]);
+       bch2_btree_path_verify(trans, btree_iter_path(trans, iter));
 }
 
 static void bch2_btree_iter_verify_entry_exit(struct btree_iter *iter)
@@ -716,8 +275,8 @@ static void bch2_btree_iter_verify_entry_exit(struct btree_iter *iter)
        BUG_ON(!(iter->flags & BTREE_ITER_ALL_SNAPSHOTS) &&
               iter->pos.snapshot != iter->snapshot);
 
-       BUG_ON(bkey_cmp(iter->pos, bkey_start_pos(&iter->k)) < 0 ||
-              bkey_cmp(iter->pos, iter->k.p) > 0);
+       BUG_ON(bkey_lt(iter->pos, bkey_start_pos(&iter->k)) ||
+              bkey_gt(iter->pos, iter->k.p));
 }
 
 static int bch2_btree_iter_verify_ret(struct btree_iter *iter, struct bkey_s_c k)
@@ -751,19 +310,19 @@ static int bch2_btree_iter_verify_ret(struct btree_iter *iter, struct bkey_s_c k
        if (ret)
                goto out;
 
-       if (!bkey_cmp(prev.k->p, k.k->p) &&
+       if (bkey_eq(prev.k->p, k.k->p) &&
            bch2_snapshot_is_ancestor(trans->c, iter->snapshot,
                                      prev.k->p.snapshot) > 0) {
-               char buf1[100], buf2[200];
+               struct printbuf buf1 = PRINTBUF, buf2 = PRINTBUF;
 
-               bch2_bkey_to_text(&PBUF(buf1), k.k);
-               bch2_bkey_to_text(&PBUF(buf2), prev.k);
+               bch2_bkey_to_text(&buf1, k.k);
+               bch2_bkey_to_text(&buf2, prev.k);
 
                panic("iter snap %u\n"
                      "k    %s\n"
                      "prev %s\n",
                      iter->snapshot,
-                     buf1, buf2);
+                     buf1.buf, buf2.buf);
        }
 out:
        bch2_trans_iter_exit(trans, &copy);
@@ -774,10 +333,12 @@ void bch2_assert_pos_locked(struct btree_trans *trans, enum btree_id id,
                            struct bpos pos, bool key_cache)
 {
        struct btree_path *path;
-       unsigned idx;
-       char buf[100];
+       struct trans_for_each_path_inorder_iter iter;
+       struct printbuf buf = PRINTBUF;
 
-       trans_for_each_path_inorder(trans, path, idx) {
+       btree_trans_sort_paths(trans);
+
+       trans_for_each_path_inorder(trans, path, iter) {
                int cmp = cmp_int(path->btree_id, id) ?:
                        cmp_int(path->cached, key_cache);
 
@@ -786,24 +347,25 @@ void bch2_assert_pos_locked(struct btree_trans *trans, enum btree_id id,
                if (cmp < 0)
                        continue;
 
-               if (!(path->nodes_locked & 1) ||
+               if (!btree_node_locked(path, 0) ||
                    !path->should_be_locked)
                        continue;
 
                if (!key_cache) {
-                       if (bkey_cmp(pos, path->l[0].b->data->min_key) >= 0 &&
-                           bkey_cmp(pos, path->l[0].b->key.k.p) <= 0)
+                       if (bkey_ge(pos, path->l[0].b->data->min_key) &&
+                           bkey_le(pos, path->l[0].b->key.k.p))
                                return;
                } else {
-                       if (!bkey_cmp(pos, path->pos))
+                       if (bkey_eq(pos, path->pos))
                                return;
                }
        }
 
        bch2_dump_trans_paths_updates(trans);
+       bch2_bpos_to_text(&buf, pos);
+
        panic("not locked: %s %s%s\n",
-             bch2_btree_ids[id],
-             (bch2_bpos_to_text(&PBUF(buf), pos), buf),
+             bch2_btree_id_str(id), buf.buf,
              key_cache ? " cached" : "");
 }
 
@@ -856,8 +418,9 @@ void bch2_btree_path_fix_key_modified(struct btree_trans *trans,
                                      struct bkey_packed *where)
 {
        struct btree_path *path;
+       unsigned i;
 
-       trans_for_each_path_with_node(trans, b, path) {
+       trans_for_each_path_with_node(trans, b, path, i) {
                __bch2_btree_path_fix_key_modified(path, b, where);
                bch2_btree_path_verify_level(trans, path, b->c.level);
        }
@@ -929,7 +492,6 @@ fixup_done:
        if (!bch2_btree_node_iter_end(node_iter) &&
            iter_current_key_modified &&
            b->c.level) {
-               struct bset_tree *t;
                struct bkey_packed *k, *k2, *p;
 
                k = bch2_btree_node_iter_peek_all(node_iter, b);
@@ -963,8 +525,9 @@ void bch2_btree_node_iter_fix(struct btree_trans *trans,
                              unsigned clobber_u64s,
                              unsigned new_u64s)
 {
-       struct bset_tree *t = bch2_bkey_to_bset(b, where);
+       struct bset_tree *t = bch2_bkey_to_bset_inlined(b, where);
        struct btree_path *linked;
+       unsigned i;
 
        if (node_iter != &path->l[b->c.level].iter) {
                __bch2_btree_node_iter_fix(path, b, node_iter, t,
@@ -974,7 +537,7 @@ void bch2_btree_node_iter_fix(struct btree_trans *trans,
                        bch2_btree_node_iter_verify(node_iter, b);
        }
 
-       trans_for_each_path_with_node(trans, b, linked) {
+       trans_for_each_path_with_node(trans, b, linked, i) {
                __bch2_btree_node_iter_fix(linked, b,
                                           &linked->l[b->c.level].iter, t,
                                           where, clobber_u64s, new_u64s);
@@ -1009,27 +572,31 @@ static inline struct bkey_s_c btree_path_level_peek_all(struct bch_fs *c,
                        bch2_btree_node_iter_peek_all(&l->iter, l->b));
 }
 
-static inline struct bkey_s_c btree_path_level_peek(struct bch_fs *c,
+static inline struct bkey_s_c btree_path_level_peek(struct btree_trans *trans,
                                                    struct btree_path *path,
                                                    struct btree_path_level *l,
                                                    struct bkey *u)
 {
-       struct bkey_s_c k = __btree_iter_unpack(c, l, u,
+       struct bkey_s_c k = __btree_iter_unpack(trans->c, l, u,
                        bch2_btree_node_iter_peek(&l->iter, l->b));
 
        path->pos = k.k ? k.k->p : l->b->key.k.p;
+       trans->paths_sorted = false;
+       bch2_btree_path_verify_level(trans, path, l - path->l);
        return k;
 }
 
-static inline struct bkey_s_c btree_path_level_prev(struct bch_fs *c,
+static inline struct bkey_s_c btree_path_level_prev(struct btree_trans *trans,
                                                    struct btree_path *path,
                                                    struct btree_path_level *l,
                                                    struct bkey *u)
 {
-       struct bkey_s_c k = __btree_iter_unpack(c, l, u,
+       struct bkey_s_c k = __btree_iter_unpack(trans->c, l, u,
                        bch2_btree_node_iter_prev(&l->iter, l->b));
 
        path->pos = k.k ? k.k->p : l->b->data->min_key;
+       trans->paths_sorted = false;
+       bch2_btree_path_verify_level(trans, path, l - path->l);
        return k;
 }
 
@@ -1052,61 +619,6 @@ static inline bool btree_path_advance_to_pos(struct btree_path *path,
        return true;
 }
 
-/*
- * Verify that iterator for parent node points to child node:
- */
-static void btree_path_verify_new_node(struct btree_trans *trans,
-                                      struct btree_path *path, struct btree *b)
-{
-       struct bch_fs *c = trans->c;
-       struct btree_path_level *l;
-       unsigned plevel;
-       bool parent_locked;
-       struct bkey_packed *k;
-
-       if (!IS_ENABLED(CONFIG_BCACHEFS_DEBUG))
-               return;
-
-       if (!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags))
-               return;
-
-       plevel = b->c.level + 1;
-       if (!btree_path_node(path, plevel))
-               return;
-
-       parent_locked = btree_node_locked(path, plevel);
-
-       if (!bch2_btree_node_relock(trans, path, plevel))
-               return;
-
-       l = &path->l[plevel];
-       k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
-       if (!k ||
-           bkey_deleted(k) ||
-           bkey_cmp_left_packed(l->b, k, &b->key.k.p)) {
-               char buf1[100];
-               char buf2[100];
-               char buf3[100];
-               char buf4[100];
-               struct bkey uk = bkey_unpack_key(b, k);
-
-               bch2_dump_btree_node(c, l->b);
-               bch2_bpos_to_text(&PBUF(buf1), path->pos);
-               bch2_bkey_to_text(&PBUF(buf2), &uk);
-               bch2_bpos_to_text(&PBUF(buf3), b->data->min_key);
-               bch2_bpos_to_text(&PBUF(buf3), b->data->max_key);
-               panic("parent iter doesn't point to new node:\n"
-                     "iter pos %s %s\n"
-                     "iter key %s\n"
-                     "new node %s-%s\n",
-                     bch2_btree_ids[path->btree_id], buf1,
-                     buf2, buf3, buf4);
-       }
-
-       if (!parent_locked)
-               btree_node_unlock(path, plevel);
-}
-
 static inline void __btree_path_level_init(struct btree_path *path,
                                           unsigned level)
 {
@@ -1122,47 +634,79 @@ static inline void __btree_path_level_init(struct btree_path *path,
                bch2_btree_node_iter_peek(&l->iter, l->b);
 }
 
-static inline void btree_path_level_init(struct btree_trans *trans,
-                                        struct btree_path *path,
-                                        struct btree *b)
+void bch2_btree_path_level_init(struct btree_trans *trans,
+                               struct btree_path *path,
+                               struct btree *b)
 {
        BUG_ON(path->cached);
 
-       btree_path_verify_new_node(trans, path, b);
-
        EBUG_ON(!btree_path_pos_in_node(path, b));
-       EBUG_ON(b->c.lock.state.seq & 1);
 
-       path->l[b->c.level].lock_seq = b->c.lock.state.seq;
+       path->l[b->c.level].lock_seq = six_lock_seq(&b->c.lock);
        path->l[b->c.level].b = b;
        __btree_path_level_init(path, b->c.level);
 }
 
 /* Btree path: fixups after btree node updates: */
 
+static void bch2_trans_revalidate_updates_in_node(struct btree_trans *trans, struct btree *b)
+{
+       struct bch_fs *c = trans->c;
+
+       trans_for_each_update(trans, i)
+               if (!i->cached &&
+                   i->level    == b->c.level &&
+                   i->btree_id == b->c.btree_id &&
+                   bpos_cmp(i->k->k.p, b->data->min_key) >= 0 &&
+                   bpos_cmp(i->k->k.p, b->data->max_key) <= 0) {
+                       i->old_v = bch2_btree_path_peek_slot(trans->paths + i->path, &i->old_k).v;
+
+                       if (unlikely(trans->journal_replay_not_finished)) {
+                               struct bkey_i *j_k =
+                                       bch2_journal_keys_peek_slot(c, i->btree_id, i->level,
+                                                                   i->k->k.p);
+
+                               if (j_k) {
+                                       i->old_k = j_k->k;
+                                       i->old_v = &j_k->v;
+                               }
+                       }
+               }
+}
+
 /*
  * A btree node is being replaced - update the iterator to point to the new
  * node:
  */
-void bch2_trans_node_add(struct btree_trans *trans, struct btree *b)
+void bch2_trans_node_add(struct btree_trans *trans,
+                        struct btree_path *path,
+                        struct btree *b)
 {
-       struct btree_path *path;
+       struct btree_path *prev;
+
+       BUG_ON(!btree_path_pos_in_node(path, b));
 
-       trans_for_each_path(trans, path)
-               if (!path->cached &&
-                   btree_path_pos_in_node(path, b)) {
+       while ((prev = prev_btree_path(trans, path)) &&
+              btree_path_pos_in_node(prev, b))
+               path = prev;
+
+       for (;
+            path && btree_path_pos_in_node(path, b);
+            path = next_btree_path(trans, path))
+               if (path->uptodate == BTREE_ITER_UPTODATE && !path->cached) {
                        enum btree_node_locked_type t =
                                btree_lock_want(path, b->c.level);
 
-                       if (path->nodes_locked &&
-                           t != BTREE_NODE_UNLOCKED) {
-                               btree_node_unlock(path, b->c.level);
-                               six_lock_increment(&b->c.lock, t);
-                               mark_btree_node_locked(path, b->c.level, t);
+                       if (t != BTREE_NODE_UNLOCKED) {
+                               btree_node_unlock(trans, path, b->c.level);
+                               six_lock_increment(&b->c.lock, (enum six_lock_type) t);
+                               mark_btree_node_locked(trans, path, b->c.level, t);
                        }
 
-                       btree_path_level_init(trans, path, b);
+                       bch2_btree_path_level_init(trans, path, b);
                }
+
+       bch2_trans_revalidate_updates_in_node(trans, b);
 }
 
 /*
@@ -1172,30 +716,26 @@ void bch2_trans_node_add(struct btree_trans *trans, struct btree *b)
 void bch2_trans_node_reinit_iter(struct btree_trans *trans, struct btree *b)
 {
        struct btree_path *path;
+       unsigned i;
 
-       trans_for_each_path_with_node(trans, b, path)
+       trans_for_each_path_with_node(trans, b, path, i)
                __btree_path_level_init(path, b->c.level);
+
+       bch2_trans_revalidate_updates_in_node(trans, b);
 }
 
 /* Btree path: traverse, set_pos: */
 
-static int lock_root_check_fn(struct six_lock *lock, void *p)
-{
-       struct btree *b = container_of(lock, struct btree, c.lock);
-       struct btree **rootp = p;
-
-       return b == *rootp ? 0 : -1;
-}
-
 static inline int btree_path_lock_root(struct btree_trans *trans,
                                       struct btree_path *path,
                                       unsigned depth_want,
                                       unsigned long trace_ip)
 {
        struct bch_fs *c = trans->c;
-       struct btree *b, **rootp = &c->btree_roots[path->btree_id].b;
+       struct btree *b, **rootp = &bch2_btree_id_root(c, path->btree_id)->b;
        enum six_lock_type lock_type;
        unsigned i;
+       int ret;
 
        EBUG_ON(path->nodes_locked);
 
@@ -1217,26 +757,28 @@ static inline int btree_path_lock_root(struct btree_trans *trans,
                }
 
                lock_type = __btree_lock_want(path, path->level);
-               if (unlikely(!btree_node_lock(trans, path, b, SPOS_MAX,
-                                             path->level, lock_type,
-                                             lock_root_check_fn, rootp,
-                                             trace_ip))) {
-                       if (trans->restarted)
-                               return -EINTR;
-                       continue;
+               ret = btree_node_lock(trans, path, &b->c,
+                                     path->level, lock_type, trace_ip);
+               if (unlikely(ret)) {
+                       if (bch2_err_matches(ret, BCH_ERR_lock_fail_root_changed))
+                               continue;
+                       if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
+                               return ret;
+                       BUG();
                }
 
                if (likely(b == READ_ONCE(*rootp) &&
                           b->c.level == path->level &&
                           !race_fault())) {
                        for (i = 0; i < path->level; i++)
-                               path->l[i].b = BTREE_ITER_NO_NODE_LOCK_ROOT;
+                               path->l[i].b = ERR_PTR(-BCH_ERR_no_btree_node_lock_root);
                        path->l[path->level].b = b;
                        for (i = path->level + 1; i < BTREE_MAX_DEPTH; i++)
                                path->l[i].b = NULL;
 
-                       mark_btree_node_locked(path, path->level, lock_type);
-                       btree_path_level_init(trans, path, b);
+                       mark_btree_node_locked(trans, path, path->level,
+                                              (enum btree_node_locked_type) lock_type);
+                       bch2_btree_path_level_init(trans, path, b);
                        return 0;
                }
 
@@ -1252,7 +794,7 @@ static int btree_path_prefetch(struct btree_trans *trans, struct btree_path *pat
        struct btree_node_iter node_iter = l->iter;
        struct bkey_packed *k;
        struct bkey_buf tmp;
-       unsigned nr = test_bit(BCH_FS_STARTED, &c->flags)
+       unsigned nr = test_bit(BCH_FS_started, &c->flags)
                ? (path->level > 1 ? 0 :  2)
                : (path->level > 1 ? 1 : 16);
        bool was_locked = btree_node_locked(path, path->level);
@@ -1260,7 +802,7 @@ static int btree_path_prefetch(struct btree_trans *trans, struct btree_path *pat
 
        bch2_bkey_buf_init(&tmp);
 
-       while (nr && !ret) {
+       while (nr-- && !ret) {
                if (!bch2_btree_node_relock(trans, path, path->level))
                        break;
 
@@ -1270,12 +812,12 @@ static int btree_path_prefetch(struct btree_trans *trans, struct btree_path *pat
                        break;
 
                bch2_bkey_buf_unpack(&tmp, c, l->b, k);
-               ret = bch2_btree_node_prefetch(c, trans, path, tmp.k, path->btree_id,
+               ret = bch2_btree_node_prefetch(trans, path, tmp.k, path->btree_id,
                                               path->level - 1);
        }
 
        if (!was_locked)
-               btree_node_unlock(path, path->level);
+               btree_node_unlock(trans, path, path->level);
 
        bch2_bkey_buf_exit(&tmp, c);
        return ret;
@@ -1287,7 +829,7 @@ static int btree_path_prefetch_j(struct btree_trans *trans, struct btree_path *p
        struct bch_fs *c = trans->c;
        struct bkey_s_c k;
        struct bkey_buf tmp;
-       unsigned nr = test_bit(BCH_FS_STARTED, &c->flags)
+       unsigned nr = test_bit(BCH_FS_started, &c->flags)
                ? (path->level > 1 ? 0 :  2)
                : (path->level > 1 ? 1 : 16);
        bool was_locked = btree_node_locked(path, path->level);
@@ -1295,7 +837,7 @@ static int btree_path_prefetch_j(struct btree_trans *trans, struct btree_path *p
 
        bch2_bkey_buf_init(&tmp);
 
-       while (nr && !ret) {
+       while (nr-- && !ret) {
                if (!bch2_btree_node_relock(trans, path, path->level))
                        break;
 
@@ -1305,12 +847,12 @@ static int btree_path_prefetch_j(struct btree_trans *trans, struct btree_path *p
                        break;
 
                bch2_bkey_buf_reassemble(&tmp, c, k);
-               ret = bch2_btree_node_prefetch(c, trans, path, tmp.k, path->btree_id,
+               ret = bch2_btree_node_prefetch(trans, path, tmp.k, path->btree_id,
                                               path->level - 1);
        }
 
        if (!was_locked)
-               btree_node_unlock(path, path->level);
+               btree_node_unlock(trans, path, path->level);
 
        bch2_bkey_buf_exit(&tmp, c);
        return ret;
@@ -1335,7 +877,7 @@ static noinline void btree_node_mem_ptr_set(struct btree_trans *trans,
        bp->mem_ptr = (unsigned long)b;
 
        if (!locked)
-               btree_node_unlock(path, plevel);
+               btree_node_unlock(trans, path, plevel);
 }
 
 static noinline int btree_node_iter_and_journal_peek(struct btree_trans *trans,
@@ -1349,13 +891,14 @@ static noinline int btree_node_iter_and_journal_peek(struct btree_trans *trans,
        struct bkey_s_c k;
        int ret = 0;
 
-       __bch2_btree_and_journal_iter_init_node_iter(&jiter, c, l->b, l->iter, path->pos);
+       __bch2_btree_and_journal_iter_init_node_iter(trans, &jiter, l->b, l->iter, path->pos);
 
        k = bch2_btree_and_journal_iter_peek(&jiter);
 
        bch2_bkey_buf_reassemble(out, c, k);
 
-       if (flags & BTREE_ITER_PREFETCH)
+       if ((flags & BTREE_ITER_PREFETCH) &&
+           c->opts.btree_node_prefetch)
                ret = btree_path_prefetch_j(trans, path, &jiter);
 
        bch2_btree_and_journal_iter_exit(&jiter);
@@ -1372,7 +915,6 @@ static __always_inline int btree_path_down(struct btree_trans *trans,
        struct btree *b;
        unsigned level = path->level - 1;
        enum six_lock_type lock_type = __btree_lock_want(path, level);
-       bool replay_done = test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags);
        struct bkey_buf tmp;
        int ret;
 
@@ -1380,7 +922,7 @@ static __always_inline int btree_path_down(struct btree_trans *trans,
 
        bch2_bkey_buf_init(&tmp);
 
-       if (unlikely(!replay_done)) {
+       if (unlikely(trans->journal_replay_not_finished)) {
                ret = btree_node_iter_and_journal_peek(trans, path, flags, &tmp);
                if (ret)
                        goto err;
@@ -1388,7 +930,8 @@ static __always_inline int btree_path_down(struct btree_trans *trans,
                bch2_bkey_buf_unpack(&tmp, c, l->b,
                                 bch2_btree_node_iter_peek(&l->iter, l->b));
 
-               if (flags & BTREE_ITER_PREFETCH) {
+               if ((flags & BTREE_ITER_PREFETCH) &&
+                   c->opts.btree_node_prefetch) {
                        ret = btree_path_prefetch(trans, path);
                        if (ret)
                                goto err;
@@ -1400,16 +943,18 @@ static __always_inline int btree_path_down(struct btree_trans *trans,
        if (unlikely(ret))
                goto err;
 
-       mark_btree_node_locked(path, level, lock_type);
-       btree_path_level_init(trans, path, b);
-
-       if (likely(replay_done && tmp.k->k.type == KEY_TYPE_btree_ptr_v2) &&
+       if (likely(!trans->journal_replay_not_finished &&
+                  tmp.k->k.type == KEY_TYPE_btree_ptr_v2) &&
            unlikely(b != btree_node_mem_ptr(tmp.k)))
                btree_node_mem_ptr_set(trans, path, level + 1, b);
 
        if (btree_node_read_locked(path, level + 1))
-               btree_node_unlock(path, level + 1);
+               btree_node_unlock(trans, path, level + 1);
+
+       mark_btree_node_locked(trans, path, level,
+                              (enum btree_node_locked_type) lock_type);
        path->level = level;
+       bch2_btree_path_level_init(trans, path, b);
 
        bch2_btree_path_verify_locks(path);
 err:
@@ -1417,38 +962,27 @@ err:
        return ret;
 }
 
-static int btree_path_traverse_one(struct btree_trans *, struct btree_path *,
-                                  unsigned, unsigned long);
 
 static int bch2_btree_path_traverse_all(struct btree_trans *trans)
 {
        struct bch_fs *c = trans->c;
        struct btree_path *path;
        unsigned long trace_ip = _RET_IP_;
-       int i, ret = 0;
+       unsigned i;
+       int ret = 0;
 
        if (trans->in_traverse_all)
-               return -EINTR;
+               return -BCH_ERR_transaction_restart_in_traverse_all;
 
        trans->in_traverse_all = true;
 retry_all:
-       trans->restarted = false;
+       trans->restarted = 0;
+       trans->last_restarted_ip = 0;
 
-       trans_for_each_path(trans, path)
+       trans_for_each_path(trans, path, i)
                path->should_be_locked = false;
 
-       btree_trans_verify_sorted(trans);
-
-       for (i = trans->nr_sorted - 2; i >= 0; --i) {
-               struct btree_path *path1 = trans->paths + trans->sorted[i];
-               struct btree_path *path2 = trans->paths + trans->sorted[i + 1];
-
-               if (path1->btree_id == path2->btree_id &&
-                   path1->locks_want < path2->locks_want)
-                       __bch2_btree_path_upgrade(trans, path1, path2->locks_want);
-               else if (!path1->locks_want && path2->locks_want)
-                       __bch2_btree_path_upgrade(trans, path1, 1);
-       }
+       btree_trans_sort_paths(trans);
 
        bch2_trans_unlock(trans);
        cond_resched();
@@ -1459,7 +993,7 @@ retry_all:
                closure_init_stack(&cl);
 
                do {
-                       ret = bch2_btree_cache_cannibalize_lock(c, &cl);
+                       ret = bch2_btree_cache_cannibalize_lock(trans, &cl);
                        closure_sync(&cl);
                } while (ret);
        }
@@ -1467,45 +1001,45 @@ retry_all:
        /* Now, redo traversals in correct order: */
        i = 0;
        while (i < trans->nr_sorted) {
-               path = trans->paths + trans->sorted[i];
+               btree_path_idx_t idx = trans->sorted[i];
 
                /*
                 * Traversing a path can cause another path to be added at about
                 * the same position:
                 */
-               if (path->uptodate) {
-                       ret = btree_path_traverse_one(trans, path, 0, _THIS_IP_);
-                       if (ret)
+               if (trans->paths[idx].uptodate) {
+                       __btree_path_get(&trans->paths[idx], false);
+                       ret = bch2_btree_path_traverse_one(trans, idx, 0, _THIS_IP_);
+                       __btree_path_put(&trans->paths[idx], false);
+
+                       if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
+                           bch2_err_matches(ret, ENOMEM))
                                goto retry_all;
+                       if (ret)
+                               goto err;
                } else {
                        i++;
                }
        }
 
        /*
-        * BTREE_ITER_NEED_RELOCK is ok here - if we called bch2_trans_unlock()
-        * and relock(), relock() won't relock since path->should_be_locked
-        * isn't set yet, which is all fine
+        * We used to assert that all paths had been traversed here
+        * (path->uptodate < BTREE_ITER_NEED_TRAVERSE); however, since
+        * path->should_be_locked is not set yet, we might have unlocked and
+        * then failed to relock a path - that's fine.
         */
-       trans_for_each_path(trans, path)
-               BUG_ON(path->uptodate >= BTREE_ITER_NEED_TRAVERSE);
-
-       bch2_btree_cache_cannibalize_unlock(c);
+err:
+       bch2_btree_cache_cannibalize_unlock(trans);
 
        trans->in_traverse_all = false;
 
-       trace_trans_traverse_all(trans->fn, trace_ip);
+       trace_and_count(c, trans_traverse_all, trans, trace_ip);
        return ret;
 }
 
-static inline bool btree_path_good_node(struct btree_trans *trans,
-                                       struct btree_path *path,
-                                       unsigned l, int check_pos)
+static inline bool btree_path_check_pos_in_node(struct btree_path *path,
+                                               unsigned l, int check_pos)
 {
-       if (!is_btree_node(path, l) ||
-           !bch2_btree_node_relock(trans, path, l))
-               return false;
-
        if (check_pos < 0 && btree_path_pos_before_node(path, path->l[l].b))
                return false;
        if (check_pos > 0 && btree_path_pos_after_node(path, path->l[l].b))
@@ -1513,33 +1047,64 @@ static inline bool btree_path_good_node(struct btree_trans *trans,
        return true;
 }
 
-static inline unsigned btree_path_up_until_good_node(struct btree_trans *trans,
-                                                    struct btree_path *path,
-                                                    int check_pos)
+static inline bool btree_path_good_node(struct btree_trans *trans,
+                                       struct btree_path *path,
+                                       unsigned l, int check_pos)
 {
-       unsigned i, l = path->level;
+       return is_btree_node(path, l) &&
+               bch2_btree_node_relock(trans, path, l) &&
+               btree_path_check_pos_in_node(path, l, check_pos);
+}
+
+static void btree_path_set_level_down(struct btree_trans *trans,
+                                     struct btree_path *path,
+                                     unsigned new_level)
+{
+       unsigned l;
+
+       path->level = new_level;
+
+       for (l = path->level + 1; l < BTREE_MAX_DEPTH; l++)
+               if (btree_lock_want(path, l) == BTREE_NODE_UNLOCKED)
+                       btree_node_unlock(trans, path, l);
 
+       btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
+       bch2_btree_path_verify(trans, path);
+}
+
+static noinline unsigned __btree_path_up_until_good_node(struct btree_trans *trans,
+                                                        struct btree_path *path,
+                                                        int check_pos)
+{
+       unsigned i, l = path->level;
+again:
        while (btree_path_node(path, l) &&
-              !btree_path_good_node(trans, path, l, check_pos)) {
-               btree_node_unlock(path, l);
-               path->l[l].b = BTREE_ITER_NO_NODE_UP;
-               l++;
-       }
+              !btree_path_good_node(trans, path, l, check_pos))
+               __btree_path_set_level_up(trans, path, l++);
 
        /* If we need intent locks, take them too: */
        for (i = l + 1;
             i < path->locks_want && btree_path_node(path, i);
             i++)
-               if (!bch2_btree_node_relock(trans, path, i))
-                       while (l <= i) {
-                               btree_node_unlock(path, l);
-                               path->l[l].b = BTREE_ITER_NO_NODE_UP;
-                               l++;
-                       }
+               if (!bch2_btree_node_relock(trans, path, i)) {
+                       while (l <= i)
+                               __btree_path_set_level_up(trans, path, l++);
+                       goto again;
+               }
 
        return l;
 }
 
+static inline unsigned btree_path_up_until_good_node(struct btree_trans *trans,
+                                                    struct btree_path *path,
+                                                    int check_pos)
+{
+       return likely(btree_node_locked(path, path->level) &&
+                     btree_path_check_pos_in_node(path, path->level, check_pos))
+               ? path->level
+               : __btree_path_up_until_good_node(trans, path, check_pos);
+}
+
 /*
  * This is the main state machine for walking down the btree - walks down to a
  * specified depth
@@ -1549,25 +1114,27 @@ static inline unsigned btree_path_up_until_good_node(struct btree_trans *trans,
  * On error, caller (peek_node()/peek_key()) must return NULL; the error is
  * stashed in the iterator and returned from bch2_trans_exit().
  */
-static int btree_path_traverse_one(struct btree_trans *trans,
-                                  struct btree_path *path,
-                                  unsigned flags,
-                                  unsigned long trace_ip)
+int bch2_btree_path_traverse_one(struct btree_trans *trans,
+                                btree_path_idx_t path_idx,
+                                unsigned flags,
+                                unsigned long trace_ip)
 {
+       struct btree_path *path = &trans->paths[path_idx];
        unsigned depth_want = path->level;
-       int ret = 0;
+       int ret = -((int) trans->restarted);
 
-       if (unlikely(trans->restarted)) {
-               ret = -EINTR;
+       if (unlikely(ret))
                goto out;
-       }
+
+       if (unlikely(!trans->srcu_held))
+               bch2_trans_srcu_lock(trans);
 
        /*
         * Ensure we obey path->should_be_locked: if it's set, we can't unlock
         * and re-traverse the path without a transaction restart:
         */
        if (path->should_be_locked) {
-               ret = bch2_btree_path_relock(trans, path, trace_ip) ? 0 : -EINTR;
+               ret = bch2_btree_path_relock(trans, path, trace_ip);
                goto out;
        }
 
@@ -1576,11 +1143,16 @@ static int btree_path_traverse_one(struct btree_trans *trans,
                goto out;
        }
 
+       path = &trans->paths[path_idx];
+
        if (unlikely(path->level >= BTREE_MAX_DEPTH))
-               goto out;
+               goto out_uptodate;
 
        path->level = btree_path_up_until_good_node(trans, path, 0);
 
+       EBUG_ON(btree_path_node(path, path->level) &&
+               !btree_node_locked(path, path->level));
+
        /*
         * Note: path->nodes[path->level] may be temporarily NULL here - that
         * would indicate to other code that we got to the end of the btree,
@@ -1601,111 +1173,88 @@ static int btree_path_traverse_one(struct btree_trans *trans,
                                goto out;
                        }
 
-                       __bch2_btree_path_unlock(path);
+                       __bch2_btree_path_unlock(trans, path);
                        path->level = depth_want;
-
-                       if (ret == -EIO)
-                               path->l[path->level].b =
-                                       BTREE_ITER_NO_NODE_ERROR;
-                       else
-                               path->l[path->level].b =
-                                       BTREE_ITER_NO_NODE_DOWN;
+                       path->l[path->level].b = ERR_PTR(ret);
                        goto out;
                }
        }
-
+out_uptodate:
        path->uptodate = BTREE_ITER_UPTODATE;
 out:
-       BUG_ON((ret == -EINTR) != !!trans->restarted);
+       if (bch2_err_matches(ret, BCH_ERR_transaction_restart) != !!trans->restarted)
+               panic("ret %s (%i) trans->restarted %s (%i)\n",
+                     bch2_err_str(ret), ret,
+                     bch2_err_str(trans->restarted), trans->restarted);
        bch2_btree_path_verify(trans, path);
        return ret;
 }
 
-int __must_check bch2_btree_path_traverse(struct btree_trans *trans,
-                                         struct btree_path *path, unsigned flags)
-{
-       if (path->uptodate < BTREE_ITER_NEED_RELOCK)
-               return 0;
-
-       return  bch2_trans_cond_resched(trans) ?:
-               btree_path_traverse_one(trans, path, flags, _RET_IP_);
-}
-
-static void btree_path_copy(struct btree_trans *trans, struct btree_path *dst,
+static inline void btree_path_copy(struct btree_trans *trans, struct btree_path *dst,
                            struct btree_path *src)
 {
-       unsigned i;
+       unsigned i, offset = offsetof(struct btree_path, pos);
 
-       memcpy(&dst->pos, &src->pos,
-              sizeof(struct btree_path) - offsetof(struct btree_path, pos));
+       memcpy((void *) dst + offset,
+              (void *) src + offset,
+              sizeof(struct btree_path) - offset);
 
-       for (i = 0; i < BTREE_MAX_DEPTH; i++)
-               if (btree_node_locked(dst, i))
-                       six_lock_increment(&dst->l[i].b->c.lock,
-                                          __btree_lock_want(dst, i));
+       for (i = 0; i < BTREE_MAX_DEPTH; i++) {
+               unsigned t = btree_node_locked_type(dst, i);
 
-       btree_path_check_sort(trans, dst, 0);
+               if (t != BTREE_NODE_UNLOCKED)
+                       six_lock_increment(&dst->l[i].b->c.lock, t);
+       }
 }
 
-static struct btree_path *btree_path_clone(struct btree_trans *trans, struct btree_path *src,
-                                          bool intent)
+static btree_path_idx_t btree_path_clone(struct btree_trans *trans, btree_path_idx_t src,
+                                        bool intent)
 {
-       struct btree_path *new = btree_path_alloc(trans, src);
-
-       btree_path_copy(trans, new, src);
-       __btree_path_get(new, intent);
+       btree_path_idx_t new = btree_path_alloc(trans, src);
+       btree_path_copy(trans, trans->paths + new, trans->paths + src);
+       __btree_path_get(trans->paths + new, intent);
        return new;
 }
 
-inline struct btree_path * __must_check
-bch2_btree_path_make_mut(struct btree_trans *trans,
-                        struct btree_path *path, bool intent,
-                        unsigned long ip)
+__flatten
+btree_path_idx_t __bch2_btree_path_make_mut(struct btree_trans *trans,
+                       btree_path_idx_t path, bool intent, unsigned long ip)
 {
-       if (path->ref > 1 || path->preserve) {
-               __btree_path_put(path, intent);
-               path = btree_path_clone(trans, path, intent);
-               path->preserve = false;
-#ifdef CONFIG_BCACHEFS_DEBUG
-               path->ip_allocated = ip;
-#endif
-               btree_trans_verify_sorted(trans);
-       }
-
+       __btree_path_put(trans->paths + path, intent);
+       path = btree_path_clone(trans, path, intent);
+       trans->paths[path].preserve = false;
        return path;
 }
 
-struct btree_path * __must_check
-bch2_btree_path_set_pos(struct btree_trans *trans,
-                  struct btree_path *path, struct bpos new_pos,
-                  bool intent, unsigned long ip)
+btree_path_idx_t __must_check
+__bch2_btree_path_set_pos(struct btree_trans *trans,
+                         btree_path_idx_t path_idx, struct bpos new_pos,
+                         bool intent, unsigned long ip)
 {
-       int cmp = bpos_cmp(new_pos, path->pos);
-       unsigned l = path->level;
-
-       EBUG_ON(trans->restarted);
-       EBUG_ON(!path->ref);
+       int cmp = bpos_cmp(new_pos, trans->paths[path_idx].pos);
 
-       if (!cmp)
-               return path;
+       bch2_trans_verify_not_in_restart(trans);
+       EBUG_ON(!trans->paths[path_idx].ref);
 
-       path = bch2_btree_path_make_mut(trans, path, intent, ip);
+       path_idx = bch2_btree_path_make_mut(trans, path_idx, intent, ip);
 
+       struct btree_path *path = trans->paths + path_idx;
        path->pos               = new_pos;
-       path->should_be_locked  = false;
-
-       btree_path_check_sort(trans, path, cmp);
+       trans->paths_sorted     = false;
 
        if (unlikely(path->cached)) {
-               btree_node_unlock(path, 0);
-               path->l[0].b = BTREE_ITER_NO_NODE_CACHED;
+               btree_node_unlock(trans, path, 0);
+               path->l[0].b = ERR_PTR(-BCH_ERR_no_btree_node_up);
                btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
                goto out;
        }
 
-       l = btree_path_up_until_good_node(trans, path, cmp);
+       unsigned level = btree_path_up_until_good_node(trans, path, cmp);
+
+       if (btree_path_node(path, level)) {
+               struct btree_path_level *l = &path->l[level];
 
-       if (btree_path_node(path, l)) {
+               BUG_ON(!btree_node_locked(path, level));
                /*
                 * We might have to skip over many keys, or just a few: try
                 * advancing the node iterator, and if we have to skip over too
@@ -1713,168 +1262,350 @@ bch2_btree_path_set_pos(struct btree_trans *trans,
                 * is expensive).
                 */
                if (cmp < 0 ||
-                   !btree_path_advance_to_pos(path, &path->l[l], 8))
-                       __btree_path_level_init(path, l);
+                   !btree_path_advance_to_pos(path, l, 8))
+                       bch2_btree_node_iter_init(&l->iter, l->b, &path->pos);
+
+               /*
+                * Iterators to interior nodes should always be pointed at the first non
+                * whiteout:
+                */
+               if (unlikely(level))
+                       bch2_btree_node_iter_peek(&l->iter, l->b);
        }
 
-       if (l != path->level) {
+       if (unlikely(level != path->level)) {
                btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
-               __bch2_btree_path_unlock(path);
+               __bch2_btree_path_unlock(trans, path);
        }
 out:
        bch2_btree_path_verify(trans, path);
-       return path;
+       return path_idx;
 }
 
 /* Btree path: main interface: */
 
 static struct btree_path *have_path_at_pos(struct btree_trans *trans, struct btree_path *path)
 {
-       struct btree_path *next;
+       struct btree_path *sib;
 
-       next = prev_btree_path(trans, path);
-       if (next && !btree_path_cmp(next, path))
-               return next;
+       sib = prev_btree_path(trans, path);
+       if (sib && !btree_path_cmp(sib, path))
+               return sib;
 
-       next = next_btree_path(trans, path);
-       if (next && !btree_path_cmp(next, path))
-               return next;
+       sib = next_btree_path(trans, path);
+       if (sib && !btree_path_cmp(sib, path))
+               return sib;
 
        return NULL;
 }
 
 static struct btree_path *have_node_at_pos(struct btree_trans *trans, struct btree_path *path)
 {
-       struct btree_path *next;
+       struct btree_path *sib;
 
-       next = prev_btree_path(trans, path);
-       if (next && next->level == path->level && path_l(next)->b == path_l(path)->b)
-               return next;
+       sib = prev_btree_path(trans, path);
+       if (sib && sib->level == path->level && path_l(sib)->b == path_l(path)->b)
+               return sib;
 
-       next = next_btree_path(trans, path);
-       if (next && next->level == path->level && path_l(next)->b == path_l(path)->b)
-               return next;
+       sib = next_btree_path(trans, path);
+       if (sib && sib->level == path->level && path_l(sib)->b == path_l(path)->b)
+               return sib;
 
        return NULL;
 }
 
-static inline void __bch2_path_free(struct btree_trans *trans, struct btree_path *path)
+static inline void __bch2_path_free(struct btree_trans *trans, btree_path_idx_t path)
 {
-       __bch2_btree_path_unlock(path);
-       btree_path_list_remove(trans, path);
-       trans->paths_allocated &= ~(1ULL << path->idx);
+       __bch2_btree_path_unlock(trans, trans->paths + path);
+       btree_path_list_remove(trans, trans->paths + path);
+       __clear_bit(path, trans->paths_allocated);
 }
 
-void bch2_path_put(struct btree_trans *trans, struct btree_path *path, bool intent)
+void bch2_path_put(struct btree_trans *trans, btree_path_idx_t path_idx, bool intent)
 {
-       struct btree_path *dup;
-
-       EBUG_ON(trans->paths + path->idx != path);
-       EBUG_ON(!path->ref);
+       struct btree_path *path = trans->paths + path_idx, *dup;
 
        if (!__btree_path_put(path, intent))
                return;
 
-       /*
-        * Perhaps instead we should check for duplicate paths in traverse_all:
-        */
-       if (path->preserve &&
-           (dup = have_path_at_pos(trans, path))) {
-               dup->preserve = true;
-               path->preserve = false;
-               goto free;
-       }
+       dup = path->preserve
+               ? have_path_at_pos(trans, path)
+               : have_node_at_pos(trans, path);
+
+       if (!dup && !(!path->preserve && !is_btree_node(path, path->level)))
+               return;
 
-       if (!path->preserve &&
-           (dup = have_node_at_pos(trans, path)))
-               goto free;
-       return;
-free:
        if (path->should_be_locked &&
-           !btree_node_locked(dup, path->level))
+           !trans->restarted &&
+           (!dup || !bch2_btree_path_relock_norestart(trans, dup)))
+               return;
+
+       if (dup) {
+               dup->preserve           |= path->preserve;
+               dup->should_be_locked   |= path->should_be_locked;
+       }
+
+       __bch2_path_free(trans, path_idx);
+}
+
+static void bch2_path_put_nokeep(struct btree_trans *trans, btree_path_idx_t path,
+                                bool intent)
+{
+       if (!__btree_path_put(trans->paths + path, intent))
                return;
 
-       dup->should_be_locked |= path->should_be_locked;
        __bch2_path_free(trans, path);
 }
 
+void __noreturn bch2_trans_restart_error(struct btree_trans *trans, u32 restart_count)
+{
+       panic("trans->restart_count %u, should be %u, last restarted by %pS\n",
+             trans->restart_count, restart_count,
+             (void *) trans->last_begin_ip);
+}
+
+void __noreturn bch2_trans_in_restart_error(struct btree_trans *trans)
+{
+       panic("in transaction restart: %s, last restarted by %pS\n",
+             bch2_err_str(trans->restarted),
+             (void *) trans->last_restarted_ip);
+}
+
 noinline __cold
-void bch2_dump_trans_paths_updates(struct btree_trans *trans)
+void bch2_trans_updates_to_text(struct printbuf *buf, struct btree_trans *trans)
 {
-       struct btree_path *path;
-       struct btree_insert_entry *i;
-       unsigned idx;
-       char buf1[300], buf2[300];
+       prt_printf(buf, "transaction updates for %s journal seq %llu",
+              trans->fn, trans->journal_res.seq);
+       prt_newline(buf);
+       printbuf_indent_add(buf, 2);
 
-       btree_trans_verify_sorted(trans);
+       trans_for_each_update(trans, i) {
+               struct bkey_s_c old = { &i->old_k, i->old_v };
 
-       trans_for_each_path_inorder(trans, path, idx)
-               printk(KERN_ERR "path: idx %u ref %u:%u%s%s btree %s pos %s locks %u %pS\n",
-                      path->idx, path->ref, path->intent_ref,
-                      path->should_be_locked ? " S" : "",
-                      path->preserve ? " P" : "",
-                      bch2_btree_ids[path->btree_id],
-                      (bch2_bpos_to_text(&PBUF(buf1), path->pos), buf1),
-                      path->nodes_locked,
-#ifdef CONFIG_BCACHEFS_DEBUG
-                      (void *) path->ip_allocated
-#else
-                      NULL
+               prt_printf(buf, "update: btree=%s cached=%u %pS",
+                      bch2_btree_id_str(i->btree_id),
+                      i->cached,
+                      (void *) i->ip_allocated);
+               prt_newline(buf);
+
+               prt_printf(buf, "  old ");
+               bch2_bkey_val_to_text(buf, trans->c, old);
+               prt_newline(buf);
+
+               prt_printf(buf, "  new ");
+               bch2_bkey_val_to_text(buf, trans->c, bkey_i_to_s_c(i->k));
+               prt_newline(buf);
+       }
+
+       for (struct jset_entry *e = trans->journal_entries;
+            e != btree_trans_journal_entries_top(trans);
+            e = vstruct_next(e))
+               bch2_journal_entry_to_text(buf, trans->c, e);
+
+       printbuf_indent_sub(buf, 2);
+}
+
+noinline __cold
+void bch2_dump_trans_updates(struct btree_trans *trans)
+{
+       struct printbuf buf = PRINTBUF;
+
+       bch2_trans_updates_to_text(&buf, trans);
+       bch2_print_string_as_lines(KERN_ERR, buf.buf);
+       printbuf_exit(&buf);
+}
+
+static void bch2_btree_path_to_text(struct printbuf *out, struct btree_trans *trans, btree_path_idx_t path_idx)
+{
+       struct btree_path *path = trans->paths + path_idx;
+
+       prt_printf(out, "path: idx %2u ref %u:%u %c %c btree=%s l=%u pos ",
+                  path_idx, path->ref, path->intent_ref,
+                  path->preserve ? 'P' : ' ',
+                  path->should_be_locked ? 'S' : ' ',
+                  bch2_btree_id_str(path->btree_id),
+                  path->level);
+       bch2_bpos_to_text(out, path->pos);
+
+       prt_printf(out, " locks %u", path->nodes_locked);
+#ifdef TRACK_PATH_ALLOCATED
+       prt_printf(out, " %pS", (void *) path->ip_allocated);
 #endif
-                      );
+       prt_newline(out);
+}
 
-       trans_for_each_update(trans, i) {
-               struct bkey u;
-               struct bkey_s_c old = bch2_btree_path_peek_slot(i->path, &u);
+static noinline __cold
+void __bch2_trans_paths_to_text(struct printbuf *out, struct btree_trans *trans,
+                               bool nosort)
+{
+       struct trans_for_each_path_inorder_iter iter;
+
+       if (!nosort)
+               btree_trans_sort_paths(trans);
+
+       trans_for_each_path_idx_inorder(trans, iter)
+               bch2_btree_path_to_text(out, trans, iter.path_idx);
+}
+
+noinline __cold
+void bch2_trans_paths_to_text(struct printbuf *out, struct btree_trans *trans)
+{
+       __bch2_trans_paths_to_text(out, trans, false);
+}
+
+static noinline __cold
+void __bch2_dump_trans_paths_updates(struct btree_trans *trans, bool nosort)
+{
+       struct printbuf buf = PRINTBUF;
+
+       __bch2_trans_paths_to_text(&buf, trans, nosort);
+       bch2_trans_updates_to_text(&buf, trans);
+
+       bch2_print_string_as_lines(KERN_ERR, buf.buf);
+       printbuf_exit(&buf);
+}
+
+noinline __cold
+void bch2_dump_trans_paths_updates(struct btree_trans *trans)
+{
+       __bch2_dump_trans_paths_updates(trans, false);
+}
+
+noinline __cold
+static void bch2_trans_update_max_paths(struct btree_trans *trans)
+{
+       struct btree_transaction_stats *s = btree_trans_stats(trans);
+       struct printbuf buf = PRINTBUF;
+       size_t nr = bitmap_weight(trans->paths_allocated, trans->nr_paths);
 
-               printk(KERN_ERR "update: btree %s %pS\n  old %s\n  new %s",
-                      bch2_btree_ids[i->btree_id],
-                      (void *) i->ip_allocated,
-                      (bch2_bkey_val_to_text(&PBUF(buf1), trans->c, old), buf1),
-                      (bch2_bkey_val_to_text(&PBUF(buf2), trans->c, bkey_i_to_s_c(i->k)), buf2));
+       bch2_trans_paths_to_text(&buf, trans);
+
+       if (!buf.allocation_failure) {
+               mutex_lock(&s->lock);
+               if (nr > s->nr_max_paths) {
+                       s->nr_max_paths = nr;
+                       swap(s->max_paths_text, buf.buf);
+               }
+               mutex_unlock(&s->lock);
        }
+
+       printbuf_exit(&buf);
+
+       trans->nr_paths_max = nr;
 }
 
-static struct btree_path *btree_path_alloc(struct btree_trans *trans,
-                                          struct btree_path *pos)
+noinline __cold
+int __bch2_btree_trans_too_many_iters(struct btree_trans *trans)
 {
-       struct btree_path *path;
-       unsigned idx;
+       if (trace_trans_restart_too_many_iters_enabled()) {
+               struct printbuf buf = PRINTBUF;
+
+               bch2_trans_paths_to_text(&buf, trans);
+               trace_trans_restart_too_many_iters(trans, _THIS_IP_, buf.buf);
+               printbuf_exit(&buf);
+       }
+
+       count_event(trans->c, trans_restart_too_many_iters);
+
+       return btree_trans_restart(trans, BCH_ERR_transaction_restart_too_many_iters);
+}
+
+static noinline void btree_path_overflow(struct btree_trans *trans)
+{
+       bch2_dump_trans_paths_updates(trans);
+       bch_err(trans->c, "trans path overflow");
+}
+
+static noinline void btree_paths_realloc(struct btree_trans *trans)
+{
+       unsigned nr = trans->nr_paths * 2;
+
+       void *p = kvzalloc(BITS_TO_LONGS(nr) * sizeof(unsigned long) +
+                         sizeof(struct btree_trans_paths) +
+                         nr * sizeof(struct btree_path) +
+                         nr * sizeof(btree_path_idx_t) + 8 +
+                         nr * sizeof(struct btree_insert_entry), GFP_KERNEL|__GFP_NOFAIL);
+
+       unsigned long *paths_allocated = p;
+       memcpy(paths_allocated, trans->paths_allocated, BITS_TO_LONGS(trans->nr_paths) * sizeof(unsigned long));
+       p += BITS_TO_LONGS(nr) * sizeof(unsigned long);
+
+       p += sizeof(struct btree_trans_paths);
+       struct btree_path *paths = p;
+       *trans_paths_nr(paths) = nr;
+       memcpy(paths, trans->paths, trans->nr_paths * sizeof(struct btree_path));
+       p += nr * sizeof(struct btree_path);
+
+       btree_path_idx_t *sorted = p;
+       memcpy(sorted, trans->sorted, trans->nr_sorted * sizeof(btree_path_idx_t));
+       p += nr * sizeof(btree_path_idx_t) + 8;
+
+       struct btree_insert_entry *updates = p;
+       memcpy(updates, trans->updates, trans->nr_paths * sizeof(struct btree_insert_entry));
+
+       unsigned long *old = trans->paths_allocated;
+
+       rcu_assign_pointer(trans->paths_allocated,      paths_allocated);
+       rcu_assign_pointer(trans->paths,                paths);
+       rcu_assign_pointer(trans->sorted,               sorted);
+       rcu_assign_pointer(trans->updates,              updates);
+
+       trans->nr_paths         = nr;
+
+       if (old != trans->_paths_allocated)
+               kfree_rcu_mightsleep(old);
+}
+
+static inline btree_path_idx_t btree_path_alloc(struct btree_trans *trans,
+                                               btree_path_idx_t pos)
+{
+       btree_path_idx_t idx = find_first_zero_bit(trans->paths_allocated, trans->nr_paths);
 
-       if (unlikely(trans->paths_allocated ==
-                    ~((~0ULL << 1) << (BTREE_ITER_MAX - 1)))) {
-               bch2_dump_trans_paths_updates(trans);
-               panic("trans path oveflow\n");
+       if (unlikely(idx == trans->nr_paths)) {
+               if (trans->nr_paths == BTREE_ITER_MAX) {
+                       btree_path_overflow(trans);
+                       return 0;
+               }
+
+               btree_paths_realloc(trans);
        }
 
-       idx = __ffs64(~trans->paths_allocated);
-       trans->paths_allocated |= 1ULL << idx;
+       /*
+        * Do this before marking the new path as allocated, since it won't be
+        * initialized yet:
+        */
+       if (unlikely(idx > trans->nr_paths_max))
+               bch2_trans_update_max_paths(trans);
 
-       path = &trans->paths[idx];
+       __set_bit(idx, trans->paths_allocated);
 
-       path->idx               = idx;
+       struct btree_path *path = &trans->paths[idx];
        path->ref               = 0;
        path->intent_ref        = 0;
        path->nodes_locked      = 0;
-       path->nodes_intent_locked = 0;
 
-       btree_path_list_add(trans, pos, path);
-       return path;
+       btree_path_list_add(trans, pos, idx);
+       trans->paths_sorted = false;
+       return idx;
 }
 
-struct btree_path *bch2_path_get(struct btree_trans *trans,
-                                enum btree_id btree_id, struct bpos pos,
-                                unsigned locks_want, unsigned level,
-                                unsigned flags, unsigned long ip)
+btree_path_idx_t bch2_path_get(struct btree_trans *trans,
+                            enum btree_id btree_id, struct bpos pos,
+                            unsigned locks_want, unsigned level,
+                            unsigned flags, unsigned long ip)
 {
-       struct btree_path *path, *path_pos = NULL;
+       struct btree_path *path;
        bool cached = flags & BTREE_ITER_CACHED;
        bool intent = flags & BTREE_ITER_INTENT;
-       int i;
+       struct trans_for_each_path_inorder_iter iter;
+       btree_path_idx_t path_pos = 0, path_idx;
 
-       BUG_ON(trans->restarted);
+       bch2_trans_verify_not_in_restart(trans);
+       bch2_trans_verify_locks(trans);
+
+       btree_trans_sort_paths(trans);
 
-       trans_for_each_path_inorder(trans, path, i) {
+       trans_for_each_path_inorder(trans, path, iter) {
                if (__btree_path_cmp(path,
                                     btree_id,
                                     cached,
@@ -1882,18 +1613,19 @@ struct btree_path *bch2_path_get(struct btree_trans *trans,
                                     level) > 0)
                        break;
 
-               path_pos = path;
+               path_pos = iter.path_idx;
        }
 
        if (path_pos &&
-           path_pos->cached    == cached &&
-           path_pos->btree_id  == btree_id &&
-           path_pos->level     == level) {
-               __btree_path_get(path_pos, intent);
-               path = bch2_btree_path_set_pos(trans, path_pos, pos, intent, ip);
+           trans->paths[path_pos].cached       == cached &&
+           trans->paths[path_pos].btree_id     == btree_id &&
+           trans->paths[path_pos].level        == level) {
+               __btree_path_get(trans->paths + path_pos, intent);
+               path_idx = bch2_btree_path_set_pos(trans, path_pos, pos, intent, ip);
+               path = trans->paths + path_idx;
        } else {
-               path = btree_path_alloc(trans, path_pos);
-               path_pos = NULL;
+               path_idx = btree_path_alloc(trans, path_pos);
+               path = trans->paths + path_idx;
 
                __btree_path_get(path, intent);
                path->pos                       = pos;
@@ -1904,13 +1636,12 @@ struct btree_path *bch2_path_get(struct btree_trans *trans,
                path->level                     = level;
                path->locks_want                = locks_want;
                path->nodes_locked              = 0;
-               path->nodes_intent_locked       = 0;
-               for (i = 0; i < ARRAY_SIZE(path->l); i++)
-                       path->l[i].b            = BTREE_ITER_NO_NODE_INIT;
-#ifdef CONFIG_BCACHEFS_DEBUG
+               for (unsigned i = 0; i < ARRAY_SIZE(path->l); i++)
+                       path->l[i].b            = ERR_PTR(-BCH_ERR_no_btree_node_init);
+#ifdef TRACK_PATH_ALLOCATED
                path->ip_allocated              = ip;
 #endif
-               btree_trans_verify_sorted(trans);
+               trans->paths_sorted             = false;
        }
 
        if (!(flags & BTREE_ITER_NOPRESERVE))
@@ -1928,45 +1659,43 @@ struct btree_path *bch2_path_get(struct btree_trans *trans,
         */
 
        locks_want = min(locks_want, BTREE_MAX_DEPTH);
-       if (locks_want > path->locks_want) {
-               path->locks_want = locks_want;
-               btree_path_get_locks(trans, path, true);
-       }
+       if (locks_want > path->locks_want)
+               bch2_btree_path_upgrade_noupgrade_sibs(trans, path, locks_want, NULL);
 
-       return path;
+       return path_idx;
 }
 
-inline struct bkey_s_c bch2_btree_path_peek_slot(struct btree_path *path, struct bkey *u)
+struct bkey_s_c bch2_btree_path_peek_slot(struct btree_path *path, struct bkey *u)
 {
 
+       struct btree_path_level *l = path_l(path);
+       struct bkey_packed *_k;
        struct bkey_s_c k;
 
-       if (!path->cached) {
-               struct btree_path_level *l = path_l(path);
-               struct bkey_packed *_k;
+       if (unlikely(!l->b))
+               return bkey_s_c_null;
 
-               EBUG_ON(path->uptodate != BTREE_ITER_UPTODATE);
+       EBUG_ON(path->uptodate != BTREE_ITER_UPTODATE);
+       EBUG_ON(!btree_node_locked(path, path->level));
 
+       if (!path->cached) {
                _k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
                k = _k ? bkey_disassemble(l->b, _k, u) : bkey_s_c_null;
 
-               EBUG_ON(k.k && bkey_deleted(k.k) && bpos_cmp(k.k->p, path->pos) == 0);
+               EBUG_ON(k.k && bkey_deleted(k.k) && bpos_eq(k.k->p, path->pos));
 
-               if (!k.k || bpos_cmp(path->pos, k.k->p))
+               if (!k.k || !bpos_eq(path->pos, k.k->p))
                        goto hole;
        } else {
                struct bkey_cached *ck = (void *) path->l[0].b;
 
                EBUG_ON(ck &&
                        (path->btree_id != ck->key.btree_id ||
-                        bkey_cmp(path->pos, ck->key.pos)));
-
-               /* BTREE_ITER_CACHED_NOFILL|BTREE_ITER_CACHED_NOCREATE? */
-               if (unlikely(!ck || !ck->valid))
+                        !bkey_eq(path->pos, ck->key.pos)));
+               if (!ck || !ck->valid)
                        return bkey_s_c_null;
 
-               EBUG_ON(path->uptodate != BTREE_ITER_UPTODATE);
-
+               *u = ck->k->k;
                k = bkey_i_to_s_c(ck->k);
        }
 
@@ -1988,9 +1717,10 @@ __bch2_btree_iter_traverse(struct btree_iter *iter)
 int __must_check
 bch2_btree_iter_traverse(struct btree_iter *iter)
 {
+       struct btree_trans *trans = iter->trans;
        int ret;
 
-       iter->path = bch2_btree_path_set_pos(iter->trans, iter->path,
+       iter->path = bch2_btree_path_set_pos(trans, iter->path,
                                        btree_iter_search_key(iter),
                                        iter->flags & BTREE_ITER_INTENT,
                                        btree_iter_ip_allocated(iter));
@@ -1999,7 +1729,7 @@ bch2_btree_iter_traverse(struct btree_iter *iter)
        if (ret)
                return ret;
 
-       iter->path->should_be_locked = true;
+       btree_path_set_should_be_locked(trans->paths + iter->path);
        return 0;
 }
 
@@ -2011,18 +1741,19 @@ struct btree *bch2_btree_iter_peek_node(struct btree_iter *iter)
        struct btree *b = NULL;
        int ret;
 
-       EBUG_ON(iter->path->cached);
+       EBUG_ON(trans->paths[iter->path].cached);
        bch2_btree_iter_verify(iter);
 
        ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
        if (ret)
                goto err;
 
-       b = btree_path_node(iter->path, iter->path->level);
+       struct btree_path *path = btree_iter_path(trans, iter);
+       b = btree_path_node(path, path->level);
        if (!b)
                goto out;
 
-       BUG_ON(bpos_cmp(b->key.k.p, iter->pos) < 0);
+       BUG_ON(bpos_lt(b->key.k.p, iter->pos));
 
        bkey_init(&iter->k);
        iter->k.p = iter->pos = b->key.k.p;
@@ -2030,8 +1761,7 @@ struct btree *bch2_btree_iter_peek_node(struct btree_iter *iter)
        iter->path = bch2_btree_path_set_pos(trans, iter->path, b->key.k.p,
                                        iter->flags & BTREE_ITER_INTENT,
                                        btree_iter_ip_allocated(iter));
-       iter->path->should_be_locked = true;
-       BUG_ON(iter->path->uptodate);
+       btree_path_set_should_be_locked(btree_iter_path(trans, iter));
 out:
        bch2_btree_iter_verify_entry_exit(iter);
        bch2_btree_iter_verify(iter);
@@ -2042,70 +1772,71 @@ err:
        goto out;
 }
 
+struct btree *bch2_btree_iter_peek_node_and_restart(struct btree_iter *iter)
+{
+       struct btree *b;
+
+       while (b = bch2_btree_iter_peek_node(iter),
+              bch2_err_matches(PTR_ERR_OR_ZERO(b), BCH_ERR_transaction_restart))
+               bch2_trans_begin(iter->trans);
+
+       return b;
+}
+
 struct btree *bch2_btree_iter_next_node(struct btree_iter *iter)
 {
        struct btree_trans *trans = iter->trans;
-       struct btree_path *path = iter->path;
        struct btree *b = NULL;
-       unsigned l;
        int ret;
 
-       BUG_ON(trans->restarted);
-       EBUG_ON(iter->path->cached);
+       EBUG_ON(trans->paths[iter->path].cached);
+       bch2_trans_verify_not_in_restart(trans);
        bch2_btree_iter_verify(iter);
 
+       struct btree_path *path = btree_iter_path(trans, iter);
+
        /* already at end? */
        if (!btree_path_node(path, path->level))
                return NULL;
 
        /* got to end? */
        if (!btree_path_node(path, path->level + 1)) {
-               btree_node_unlock(path, path->level);
-               path->l[path->level].b = BTREE_ITER_NO_NODE_UP;
-               path->level++;
+               btree_path_set_level_up(trans, path);
                return NULL;
        }
 
        if (!bch2_btree_node_relock(trans, path, path->level + 1)) {
-               __bch2_btree_path_unlock(path);
-               path->l[path->level].b = BTREE_ITER_NO_NODE_GET_LOCKS;
-               path->l[path->level + 1].b = BTREE_ITER_NO_NODE_GET_LOCKS;
-               trace_trans_restart_relock_next_node(trans->fn, _THIS_IP_,
-                                          path->btree_id, &path->pos);
-               btree_trans_restart(trans);
-               ret = -EINTR;
+               __bch2_btree_path_unlock(trans, path);
+               path->l[path->level].b          = ERR_PTR(-BCH_ERR_no_btree_node_relock);
+               path->l[path->level + 1].b      = ERR_PTR(-BCH_ERR_no_btree_node_relock);
+               btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
+               trace_and_count(trans->c, trans_restart_relock_next_node, trans, _THIS_IP_, path);
+               ret = btree_trans_restart(trans, BCH_ERR_transaction_restart_relock);
                goto err;
        }
 
        b = btree_path_node(path, path->level + 1);
 
-       if (!bpos_cmp(iter->pos, b->key.k.p)) {
-               btree_node_unlock(path, path->level);
-               path->l[path->level].b = BTREE_ITER_NO_NODE_UP;
-               path->level++;
+       if (bpos_eq(iter->pos, b->key.k.p)) {
+               __btree_path_set_level_up(trans, path, path->level++);
        } else {
                /*
                 * Haven't gotten to the end of the parent node: go back down to
                 * the next child node
                 */
-               path = iter->path =
-                       bch2_btree_path_set_pos(trans, path, bpos_successor(iter->pos),
-                                          iter->flags & BTREE_ITER_INTENT,
-                                          btree_iter_ip_allocated(iter));
-
-               path->level = iter->min_depth;
-
-               for (l = path->level + 1; l < BTREE_MAX_DEPTH; l++)
-                       if (btree_lock_want(path, l) == BTREE_NODE_UNLOCKED)
-                               btree_node_unlock(path, l);
+               iter->path = bch2_btree_path_set_pos(trans, iter->path,
+                                       bpos_successor(iter->pos),
+                                       iter->flags & BTREE_ITER_INTENT,
+                                       btree_iter_ip_allocated(iter));
 
-               btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
-               bch2_btree_iter_verify(iter);
+               path = btree_iter_path(trans, iter);
+               btree_path_set_level_down(trans, path, iter->min_depth);
 
-               ret = bch2_btree_path_traverse(trans, path, iter->flags);
+               ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
                if (ret)
                        goto err;
 
+               path = btree_iter_path(trans, iter);
                b = path->l[path->level].b;
        }
 
@@ -2115,8 +1846,8 @@ struct btree *bch2_btree_iter_next_node(struct btree_iter *iter)
        iter->path = bch2_btree_path_set_pos(trans, iter->path, b->key.k.p,
                                        iter->flags & BTREE_ITER_INTENT,
                                        btree_iter_ip_allocated(iter));
-       iter->path->should_be_locked = true;
-       BUG_ON(iter->path->uptodate);
+       btree_path_set_should_be_locked(btree_iter_path(trans, iter));
+       EBUG_ON(btree_iter_path(trans, iter)->uptodate);
 out:
        bch2_btree_iter_verify_entry_exit(iter);
        bch2_btree_iter_verify(iter);
@@ -2132,9 +1863,9 @@ err:
 inline bool bch2_btree_iter_advance(struct btree_iter *iter)
 {
        struct bpos pos = iter->k.p;
-       bool ret = (iter->flags & BTREE_ITER_ALL_SNAPSHOTS
-                   ? bpos_cmp(pos, SPOS_MAX)
-                   : bkey_cmp(pos, SPOS_MAX)) != 0;
+       bool ret = !(iter->flags & BTREE_ITER_ALL_SNAPSHOTS
+                    ? bpos_eq(pos, SPOS_MAX)
+                    : bkey_eq(pos, SPOS_MAX));
 
        if (ret && !(iter->flags & BTREE_ITER_IS_EXTENTS))
                pos = bkey_successor(iter, pos);
@@ -2145,9 +1876,9 @@ inline bool bch2_btree_iter_advance(struct btree_iter *iter)
 inline bool bch2_btree_iter_rewind(struct btree_iter *iter)
 {
        struct bpos pos = bkey_start_pos(&iter->k);
-       bool ret = (iter->flags & BTREE_ITER_ALL_SNAPSHOTS
-                   ? bpos_cmp(pos, POS_MIN)
-                   : bkey_cmp(pos, POS_MIN)) != 0;
+       bool ret = !(iter->flags & BTREE_ITER_ALL_SNAPSHOTS
+                    ? bpos_eq(pos, POS_MIN)
+                    : bkey_eq(pos, POS_MIN));
 
        if (ret && !(iter->flags & BTREE_ITER_IS_EXTENTS))
                pos = bkey_predecessor(iter, pos);
@@ -2155,39 +1886,78 @@ inline bool bch2_btree_iter_rewind(struct btree_iter *iter)
        return ret;
 }
 
-static inline struct bkey_i *btree_trans_peek_updates(struct btree_trans *trans,
-                                                     enum btree_id btree_id,
-                                                     struct bpos pos)
+static noinline
+void bch2_btree_trans_peek_prev_updates(struct btree_trans *trans, struct btree_iter *iter,
+                                       struct bkey_s_c *k)
 {
-       struct btree_insert_entry *i;
+       struct bpos end = path_l(btree_iter_path(trans, iter))->b->data->min_key;
 
        trans_for_each_update(trans, i)
-               if ((cmp_int(btree_id,  i->btree_id) ?:
-                    bpos_cmp(pos,      i->k->k.p)) <= 0) {
-                       if (btree_id == i->btree_id)
-                               return i->k;
-                       break;
+               if (!i->key_cache_already_flushed &&
+                   i->btree_id == iter->btree_id &&
+                   bpos_le(i->k->k.p, iter->pos) &&
+                   bpos_ge(i->k->k.p, k->k ? k->k->p : end)) {
+                       iter->k = i->k->k;
+                       *k = bkey_i_to_s_c(i->k);
                }
+}
 
-       return NULL;
+static noinline
+void bch2_btree_trans_peek_updates(struct btree_trans *trans, struct btree_iter *iter,
+                                  struct bkey_s_c *k)
+{
+       struct btree_path *path = btree_iter_path(trans, iter);
+       struct bpos end = path_l(path)->b->key.k.p;
+
+       trans_for_each_update(trans, i)
+               if (!i->key_cache_already_flushed &&
+                   i->btree_id == iter->btree_id &&
+                   bpos_ge(i->k->k.p, path->pos) &&
+                   bpos_le(i->k->k.p, k->k ? k->k->p : end)) {
+                       iter->k = i->k->k;
+                       *k = bkey_i_to_s_c(i->k);
+               }
 }
 
 static noinline
-struct bkey_i *__btree_trans_peek_journal(struct btree_trans *trans,
-                                         struct btree_path *path)
+void bch2_btree_trans_peek_slot_updates(struct btree_trans *trans, struct btree_iter *iter,
+                                       struct bkey_s_c *k)
+{
+       trans_for_each_update(trans, i)
+               if (!i->key_cache_already_flushed &&
+                   i->btree_id == iter->btree_id &&
+                   bpos_eq(i->k->k.p, iter->pos)) {
+                       iter->k = i->k->k;
+                       *k = bkey_i_to_s_c(i->k);
+               }
+}
+
+static struct bkey_i *bch2_btree_journal_peek(struct btree_trans *trans,
+                                             struct btree_iter *iter,
+                                             struct bpos end_pos)
 {
-       struct journal_keys *keys = &trans->c->journal_keys;
-       size_t idx = bch2_journal_key_search(keys, path->btree_id,
-                                            path->level, path->pos);
+       struct btree_path *path = btree_iter_path(trans, iter);
 
-       while (idx < keys->nr && keys->d[idx].overwritten)
-               idx++;
+       return bch2_journal_keys_peek_upto(trans->c, iter->btree_id,
+                                          path->level,
+                                          path->pos,
+                                          end_pos,
+                                          &iter->journal_idx);
+}
 
-       return (idx < keys->nr &&
-               keys->d[idx].btree_id   == path->btree_id &&
-               keys->d[idx].level      == path->level)
-               ? keys->d[idx].k
-               : NULL;
+static noinline
+struct bkey_s_c btree_trans_peek_slot_journal(struct btree_trans *trans,
+                                             struct btree_iter *iter)
+{
+       struct btree_path *path = btree_iter_path(trans, iter);
+       struct bkey_i *k = bch2_btree_journal_peek(trans, iter, path->pos);
+
+       if (k) {
+               iter->k = k->k;
+               return bkey_i_to_s_c(k);
+       } else {
+               return bkey_s_c_null;
+       }
 }
 
 static noinline
@@ -2195,12 +1965,12 @@ struct bkey_s_c btree_trans_peek_journal(struct btree_trans *trans,
                                         struct btree_iter *iter,
                                         struct bkey_s_c k)
 {
+       struct btree_path *path = btree_iter_path(trans, iter);
        struct bkey_i *next_journal =
-               __btree_trans_peek_journal(trans, iter->path);
+               bch2_btree_journal_peek(trans, iter,
+                               k.k ? k.k->p : path_l(path)->b->key.k.p);
 
-       if (next_journal &&
-           bpos_cmp(next_journal->k.p,
-                    k.k ? k.k->p : iter->path->l[0].b->key.k.p) <= 0) {
+       if (next_journal) {
                iter->k = next_journal->k;
                k = bkey_i_to_s_c(next_journal);
        }
@@ -2218,41 +1988,55 @@ struct bkey_s_c btree_trans_peek_key_cache(struct btree_iter *iter, struct bpos
        struct btree_trans *trans = iter->trans;
        struct bch_fs *c = trans->c;
        struct bkey u;
+       struct bkey_s_c k;
        int ret;
 
+       if ((iter->flags & BTREE_ITER_KEY_CACHE_FILL) &&
+           bpos_eq(iter->pos, pos))
+               return bkey_s_c_null;
+
        if (!bch2_btree_key_cache_find(c, iter->btree_id, pos))
                return bkey_s_c_null;
 
        if (!iter->key_cache_path)
                iter->key_cache_path = bch2_path_get(trans, iter->btree_id, pos,
                                                     iter->flags & BTREE_ITER_INTENT, 0,
-                                                    iter->flags|BTREE_ITER_CACHED,
+                                                    iter->flags|BTREE_ITER_CACHED|
+                                                    BTREE_ITER_CACHED_NOFILL,
                                                     _THIS_IP_);
 
        iter->key_cache_path = bch2_btree_path_set_pos(trans, iter->key_cache_path, pos,
                                        iter->flags & BTREE_ITER_INTENT,
                                        btree_iter_ip_allocated(iter));
 
-       ret = bch2_btree_path_traverse(trans, iter->key_cache_path, iter->flags|BTREE_ITER_CACHED);
+       ret =   bch2_btree_path_traverse(trans, iter->key_cache_path,
+                                        iter->flags|BTREE_ITER_CACHED) ?:
+               bch2_btree_path_relock(trans, btree_iter_path(trans, iter), _THIS_IP_);
        if (unlikely(ret))
                return bkey_s_c_err(ret);
 
-       iter->key_cache_path->should_be_locked = true;
+       btree_path_set_should_be_locked(trans->paths + iter->key_cache_path);
 
-       return bch2_btree_path_peek_slot(iter->key_cache_path, &u);
+       k = bch2_btree_path_peek_slot(trans->paths + iter->key_cache_path, &u);
+       if (k.k && !bkey_err(k)) {
+               iter->k = u;
+               k.k = &iter->k;
+       }
+       return k;
 }
 
 static struct bkey_s_c __bch2_btree_iter_peek(struct btree_iter *iter, struct bpos search_key)
 {
        struct btree_trans *trans = iter->trans;
-       struct bkey_i *next_update;
        struct bkey_s_c k, k2;
        int ret;
 
-       EBUG_ON(iter->path->cached || iter->path->level);
+       EBUG_ON(btree_iter_path(trans, iter)->cached);
        bch2_btree_iter_verify(iter);
 
        while (1) {
+               struct btree_path_level *l;
+
                iter->path = bch2_btree_path_set_pos(trans, iter->path, search_key,
                                        iter->flags & BTREE_ITER_INTENT,
                                        btree_iter_ip_allocated(iter));
@@ -2265,36 +2049,37 @@ static struct bkey_s_c __bch2_btree_iter_peek(struct btree_iter *iter, struct bp
                        goto out;
                }
 
-               iter->path->should_be_locked = true;
+               struct btree_path *path = btree_iter_path(trans, iter);
+               l = path_l(path);
+
+               if (unlikely(!l->b)) {
+                       /* No btree nodes at requested level: */
+                       bch2_btree_iter_set_pos(iter, SPOS_MAX);
+                       k = bkey_s_c_null;
+                       goto out;
+               }
+
+               btree_path_set_should_be_locked(path);
 
-               k = btree_path_level_peek_all(trans->c, &iter->path->l[0], &iter->k);
+               k = btree_path_level_peek_all(trans->c, l, &iter->k);
 
                if (unlikely(iter->flags & BTREE_ITER_WITH_KEY_CACHE) &&
                    k.k &&
                    (k2 = btree_trans_peek_key_cache(iter, k.k->p)).k) {
-                       ret = bkey_err(k2);
+                       k = k2;
+                       ret = bkey_err(k);
                        if (ret) {
-                               k = k2;
                                bch2_btree_iter_set_pos(iter, iter->pos);
                                goto out;
                        }
-
-                       k = k2;
-                       iter->k = *k.k;
                }
 
                if (unlikely(iter->flags & BTREE_ITER_WITH_JOURNAL))
                        k = btree_trans_peek_journal(trans, iter, k);
 
-               next_update = iter->flags & BTREE_ITER_WITH_UPDATES
-                       ? btree_trans_peek_updates(trans, iter->btree_id, search_key)
-                       : NULL;
-               if (next_update &&
-                   bpos_cmp(next_update->k.p,
-                            k.k ? k.k->p : iter->path->l[0].b->key.k.p) <= 0) {
-                       iter->k = next_update->k;
-                       k = bkey_i_to_s_c(next_update);
-               }
+               if (unlikely((iter->flags & BTREE_ITER_WITH_UPDATES) &&
+                            trans->nr_updates))
+                       bch2_btree_trans_peek_updates(trans, iter, &k);
 
                if (k.k && bkey_deleted(k.k)) {
                        /*
@@ -2304,7 +2089,7 @@ static struct bkey_s_c __bch2_btree_iter_peek(struct btree_iter *iter, struct bp
                         * whiteout, with a real key at the same position, since
                         * in the btree deleted keys sort before non deleted.
                         */
-                       search_key = bpos_cmp(search_key, k.k->p)
+                       search_key = !bpos_eq(search_key, k.k->p)
                                ? k.k->p
                                : bpos_successor(k.k->p);
                        continue;
@@ -2312,9 +2097,9 @@ static struct bkey_s_c __bch2_btree_iter_peek(struct btree_iter *iter, struct bp
 
                if (likely(k.k)) {
                        break;
-               } else if (likely(bpos_cmp(iter->path->l[0].b->key.k.p, SPOS_MAX))) {
+               } else if (likely(!bpos_eq(l->b->key.k.p, SPOS_MAX))) {
                        /* Advance to next leaf node: */
-                       search_key = bpos_successor(iter->path->l[0].b->key.k.p);
+                       search_key = bpos_successor(l->b->key.k.p);
                } else {
                        /* End of btree: */
                        bch2_btree_iter_set_pos(iter, SPOS_MAX);
@@ -2329,34 +2114,56 @@ out:
 }
 
 /**
- * bch2_btree_iter_peek: returns first key greater than or equal to iterator's
- * current position
+ * bch2_btree_iter_peek_upto() - returns first key greater than or equal to
+ * iterator's current position
+ * @iter:      iterator to peek from
+ * @end:       search limit: returns keys less than or equal to @end
+ *
+ * Returns:    key if found, or an error extractable with bkey_err().
  */
-struct bkey_s_c bch2_btree_iter_peek(struct btree_iter *iter)
+struct bkey_s_c bch2_btree_iter_peek_upto(struct btree_iter *iter, struct bpos end)
 {
        struct btree_trans *trans = iter->trans;
        struct bpos search_key = btree_iter_search_key(iter);
        struct bkey_s_c k;
+       struct bpos iter_pos;
        int ret;
 
+       EBUG_ON((iter->flags & BTREE_ITER_FILTER_SNAPSHOTS) && bkey_eq(end, POS_MAX));
+
        if (iter->update_path) {
-               bch2_path_put(trans, iter->update_path,
-                             iter->flags & BTREE_ITER_INTENT);
-               iter->update_path = NULL;
+               bch2_path_put_nokeep(trans, iter->update_path,
+                                    iter->flags & BTREE_ITER_INTENT);
+               iter->update_path = 0;
        }
 
        bch2_btree_iter_verify_entry_exit(iter);
 
        while (1) {
                k = __bch2_btree_iter_peek(iter, search_key);
-               if (!k.k || bkey_err(k))
-                       goto out;
+               if (unlikely(!k.k))
+                       goto end;
+               if (unlikely(bkey_err(k)))
+                       goto out_no_locked;
+
+               /*
+                * We need to check against @end before FILTER_SNAPSHOTS because
+                * if we get to a different inode that requested we might be
+                * seeing keys for a different snapshot tree that will all be
+                * filtered out.
+                *
+                * But we can't do the full check here, because bkey_start_pos()
+                * isn't monotonically increasing before FILTER_SNAPSHOTS, and
+                * that's what we check against in extents mode:
+                */
+               if (k.k->p.inode > end.inode)
+                       goto end;
 
                if (iter->update_path &&
-                   bkey_cmp(iter->update_path->pos, k.k->p)) {
-                       bch2_path_put(trans, iter->update_path,
-                                     iter->flags & BTREE_ITER_INTENT);
-                       iter->update_path = NULL;
+                   !bkey_eq(trans->paths[iter->update_path].pos, k.k->p)) {
+                       bch2_path_put_nokeep(trans, iter->update_path,
+                                            iter->flags & BTREE_ITER_INTENT);
+                       iter->update_path = 0;
                }
 
                if ((iter->flags & BTREE_ITER_FILTER_SNAPSHOTS) &&
@@ -2376,16 +2183,18 @@ struct bkey_s_c bch2_btree_iter_peek(struct btree_iter *iter)
                         * advance, same as on exit for iter->path, but only up
                         * to snapshot
                         */
-                       __btree_path_get(iter->path, iter->flags & BTREE_ITER_INTENT);
+                       __btree_path_get(trans->paths + iter->path, iter->flags & BTREE_ITER_INTENT);
                        iter->update_path = iter->path;
 
                        iter->update_path = bch2_btree_path_set_pos(trans,
                                                iter->update_path, pos,
                                                iter->flags & BTREE_ITER_INTENT,
-                                               btree_iter_ip_allocated(iter));
-
-                       BUG_ON(!(iter->update_path->nodes_locked & 1));
-                       iter->update_path->should_be_locked = true;
+                                               _THIS_IP_);
+                       ret = bch2_btree_path_traverse(trans, iter->update_path, iter->flags);
+                       if (unlikely(ret)) {
+                               k = bkey_s_c_err(ret);
+                               goto out_no_locked;
+                       }
                }
 
                /*
@@ -2406,28 +2215,39 @@ struct bkey_s_c bch2_btree_iter_peek(struct btree_iter *iter)
                        continue;
                }
 
+               /*
+                * iter->pos should be mononotically increasing, and always be
+                * equal to the key we just returned - except extents can
+                * straddle iter->pos:
+                */
+               if (!(iter->flags & BTREE_ITER_IS_EXTENTS))
+                       iter_pos = k.k->p;
+               else
+                       iter_pos = bkey_max(iter->pos, bkey_start_pos(k.k));
+
+               if (unlikely(!(iter->flags & BTREE_ITER_IS_EXTENTS)
+                            ? bkey_gt(iter_pos, end)
+                            : bkey_ge(iter_pos, end)))
+                       goto end;
+
                break;
        }
 
-       /*
-        * iter->pos should be mononotically increasing, and always be equal to
-        * the key we just returned - except extents can straddle iter->pos:
-        */
-       if (!(iter->flags & BTREE_ITER_IS_EXTENTS))
-               iter->pos = k.k->p;
-       else if (bkey_cmp(bkey_start_pos(k.k), iter->pos) > 0)
-               iter->pos = bkey_start_pos(k.k);
+       iter->pos = iter_pos;
 
        iter->path = bch2_btree_path_set_pos(trans, iter->path, k.k->p,
                                iter->flags & BTREE_ITER_INTENT,
                                btree_iter_ip_allocated(iter));
-       BUG_ON(!iter->path->nodes_locked);
-out:
+
+       btree_path_set_should_be_locked(btree_iter_path(trans, iter));
+out_no_locked:
        if (iter->update_path) {
-               BUG_ON(!(iter->update_path->nodes_locked & 1));
-               iter->update_path->should_be_locked = true;
+               ret = bch2_btree_path_relock(trans, trans->paths + iter->update_path, _THIS_IP_);
+               if (unlikely(ret))
+                       k = bkey_s_c_err(ret);
+               else
+                       btree_path_set_should_be_locked(trans->paths + iter->update_path);
        }
-       iter->path->should_be_locked = true;
 
        if (!(iter->flags & BTREE_ITER_ALL_SNAPSHOTS))
                iter->pos.snapshot = iter->snapshot;
@@ -2441,11 +2261,18 @@ out:
        bch2_btree_iter_verify_entry_exit(iter);
 
        return k;
+end:
+       bch2_btree_iter_set_pos(iter, end);
+       k = bkey_s_c_null;
+       goto out_no_locked;
 }
 
 /**
- * bch2_btree_iter_next: returns first key greater than iterator's current
+ * bch2_btree_iter_next() - returns first key greater than iterator's current
  * position
+ * @iter:      iterator to peek from
+ *
+ * Returns:    key if found, or an error extractable with bkey_err().
  */
 struct bkey_s_c bch2_btree_iter_next(struct btree_iter *iter)
 {
@@ -2456,24 +2283,27 @@ struct bkey_s_c bch2_btree_iter_next(struct btree_iter *iter)
 }
 
 /**
- * bch2_btree_iter_peek_prev: returns first key less than or equal to
+ * bch2_btree_iter_peek_prev() - returns first key less than or equal to
  * iterator's current position
+ * @iter:      iterator to peek from
+ *
+ * Returns:    key if found, or an error extractable with bkey_err().
  */
 struct bkey_s_c bch2_btree_iter_peek_prev(struct btree_iter *iter)
 {
        struct btree_trans *trans = iter->trans;
        struct bpos search_key = iter->pos;
-       struct btree_path *saved_path = NULL;
        struct bkey_s_c k;
        struct bkey saved_k;
        const struct bch_val *saved_v;
+       btree_path_idx_t saved_path = 0;
        int ret;
 
-       EBUG_ON(iter->path->cached || iter->path->level);
-       EBUG_ON(iter->flags & BTREE_ITER_WITH_UPDATES);
+       EBUG_ON(btree_iter_path(trans, iter)->cached ||
+               btree_iter_path(trans, iter)->level);
 
        if (iter->flags & BTREE_ITER_WITH_JOURNAL)
-               return bkey_s_c_err(-EIO);
+               return bkey_s_c_err(-BCH_ERR_btree_iter_with_journal_not_supported);
 
        bch2_btree_iter_verify(iter);
        bch2_btree_iter_verify_entry_exit(iter);
@@ -2491,19 +2321,21 @@ struct bkey_s_c bch2_btree_iter_peek_prev(struct btree_iter *iter)
                        /* ensure that iter->k is consistent with iter->pos: */
                        bch2_btree_iter_set_pos(iter, iter->pos);
                        k = bkey_s_c_err(ret);
-                       goto out;
+                       goto out_no_locked;
                }
 
-               k = btree_path_level_peek(trans->c, iter->path,
-                                         &iter->path->l[0], &iter->k);
+               struct btree_path *path = btree_iter_path(trans, iter);
+
+               k = btree_path_level_peek(trans, path, &path->l[0], &iter->k);
                if (!k.k ||
                    ((iter->flags & BTREE_ITER_IS_EXTENTS)
-                    ? bpos_cmp(bkey_start_pos(k.k), search_key) >= 0
-                    : bpos_cmp(k.k->p, search_key) > 0))
-                       k = btree_path_level_prev(trans->c, iter->path,
-                                                 &iter->path->l[0], &iter->k);
+                    ? bpos_ge(bkey_start_pos(k.k), search_key)
+                    : bpos_gt(k.k->p, search_key)))
+                       k = btree_path_level_prev(trans, path, &path->l[0], &iter->k);
 
-               btree_path_check_sort(trans, iter->path, 0);
+               if (unlikely((iter->flags & BTREE_ITER_WITH_UPDATES) &&
+                            trans->nr_updates))
+                       bch2_btree_trans_peek_prev_updates(trans, iter, &k);
 
                if (likely(k.k)) {
                        if (iter->flags & BTREE_ITER_FILTER_SNAPSHOTS) {
@@ -2515,24 +2347,25 @@ struct bkey_s_c bch2_btree_iter_peek_prev(struct btree_iter *iter)
                                 * longer at the same _key_ (not pos), return
                                 * that candidate
                                 */
-                               if (saved_path && bkey_cmp(k.k->p, saved_k.p)) {
-                                       bch2_path_put(trans, iter->path,
+                               if (saved_path && !bkey_eq(k.k->p, saved_k.p)) {
+                                       bch2_path_put_nokeep(trans, iter->path,
                                                      iter->flags & BTREE_ITER_INTENT);
                                        iter->path = saved_path;
-                                       saved_path = NULL;
+                                       saved_path = 0;
                                        iter->k = saved_k;
                                        k.v     = saved_v;
                                        goto got_key;
                                }
 
-                               if (bch2_snapshot_is_ancestor(iter->trans->c,
+                               if (bch2_snapshot_is_ancestor(trans->c,
                                                              iter->snapshot,
                                                              k.k->p.snapshot)) {
                                        if (saved_path)
-                                               bch2_path_put(trans, saved_path,
+                                               bch2_path_put_nokeep(trans, saved_path,
                                                      iter->flags & BTREE_ITER_INTENT);
                                        saved_path = btree_path_clone(trans, iter->path,
                                                                iter->flags & BTREE_ITER_INTENT);
+                                       path = btree_iter_path(trans, iter);
                                        saved_k = *k.k;
                                        saved_v = k.v;
                                }
@@ -2549,30 +2382,30 @@ got_key:
                                continue;
                        }
 
+                       btree_path_set_should_be_locked(path);
                        break;
-               } else if (likely(bpos_cmp(iter->path->l[0].b->data->min_key, POS_MIN))) {
+               } else if (likely(!bpos_eq(path->l[0].b->data->min_key, POS_MIN))) {
                        /* Advance to previous leaf node: */
-                       search_key = bpos_predecessor(iter->path->l[0].b->data->min_key);
+                       search_key = bpos_predecessor(path->l[0].b->data->min_key);
                } else {
                        /* Start of btree: */
                        bch2_btree_iter_set_pos(iter, POS_MIN);
                        k = bkey_s_c_null;
-                       goto out;
+                       goto out_no_locked;
                }
        }
 
-       EBUG_ON(bkey_cmp(bkey_start_pos(k.k), iter->pos) > 0);
+       EBUG_ON(bkey_gt(bkey_start_pos(k.k), iter->pos));
 
        /* Extents can straddle iter->pos: */
-       if (bkey_cmp(k.k->p, iter->pos) < 0)
+       if (bkey_lt(k.k->p, iter->pos))
                iter->pos = k.k->p;
 
        if (iter->flags & BTREE_ITER_FILTER_SNAPSHOTS)
                iter->pos.snapshot = iter->snapshot;
-out:
+out_no_locked:
        if (saved_path)
-               bch2_path_put(trans, saved_path, iter->flags & BTREE_ITER_INTENT);
-       iter->path->should_be_locked = true;
+               bch2_path_put_nokeep(trans, saved_path, iter->flags & BTREE_ITER_INTENT);
 
        bch2_btree_iter_verify_entry_exit(iter);
        bch2_btree_iter_verify(iter);
@@ -2581,8 +2414,11 @@ out:
 }
 
 /**
- * bch2_btree_iter_prev: returns first key less than iterator's current
+ * bch2_btree_iter_prev() - returns first key less than iterator's current
  * position
+ * @iter:      iterator to peek from
+ *
+ * Returns:    key if found, or an error extractable with bkey_err().
  */
 struct bkey_s_c bch2_btree_iter_prev(struct btree_iter *iter)
 {
@@ -2599,9 +2435,9 @@ struct bkey_s_c bch2_btree_iter_peek_slot(struct btree_iter *iter)
        struct bkey_s_c k;
        int ret;
 
-       EBUG_ON(iter->path->level);
        bch2_btree_iter_verify(iter);
        bch2_btree_iter_verify_entry_exit(iter);
+       EBUG_ON(btree_iter_path(trans, iter)->level && (iter->flags & BTREE_ITER_WITH_KEY_CACHE));
 
        /* extents can't span inode numbers: */
        if ((iter->flags & BTREE_ITER_IS_EXTENTS) &&
@@ -2618,48 +2454,54 @@ struct bkey_s_c bch2_btree_iter_peek_slot(struct btree_iter *iter)
                                        btree_iter_ip_allocated(iter));
 
        ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
-       if (unlikely(ret))
-               return bkey_s_c_err(ret);
+       if (unlikely(ret)) {
+               k = bkey_s_c_err(ret);
+               goto out_no_locked;
+       }
 
        if ((iter->flags & BTREE_ITER_CACHED) ||
            !(iter->flags & (BTREE_ITER_IS_EXTENTS|BTREE_ITER_FILTER_SNAPSHOTS))) {
-               struct bkey_i *next_update;
-
-               if ((iter->flags & BTREE_ITER_WITH_UPDATES) &&
-                   (next_update = btree_trans_peek_updates(trans,
-                                               iter->btree_id, search_key)) &&
-                   !bpos_cmp(next_update->k.p, iter->pos)) {
-                       iter->k = next_update->k;
-                       k = bkey_i_to_s_c(next_update);
-                       goto out;
+               k = bkey_s_c_null;
+
+               if (unlikely((iter->flags & BTREE_ITER_WITH_UPDATES) &&
+                            trans->nr_updates)) {
+                       bch2_btree_trans_peek_slot_updates(trans, iter, &k);
+                       if (k.k)
+                               goto out;
                }
 
                if (unlikely(iter->flags & BTREE_ITER_WITH_JOURNAL) &&
-                   (next_update = __btree_trans_peek_journal(trans, iter->path)) &&
-                   !bpos_cmp(next_update->k.p, iter->pos)) {
-                       iter->k = next_update->k;
-                       k = bkey_i_to_s_c(next_update);
+                   (k = btree_trans_peek_slot_journal(trans, iter)).k)
                        goto out;
-               }
 
                if (unlikely(iter->flags & BTREE_ITER_WITH_KEY_CACHE) &&
                    (k = btree_trans_peek_key_cache(iter, iter->pos)).k) {
                        if (!bkey_err(k))
                                iter->k = *k.k;
-                       goto out;
+                       /* We're not returning a key from iter->path: */
+                       goto out_no_locked;
                }
 
-               k = bch2_btree_path_peek_slot(iter->path, &iter->k);
+               k = bch2_btree_path_peek_slot(trans->paths + iter->path, &iter->k);
+               if (unlikely(!k.k))
+                       goto out_no_locked;
        } else {
                struct bpos next;
+               struct bpos end = iter->pos;
+
+               if (iter->flags & BTREE_ITER_IS_EXTENTS)
+                       end.offset = U64_MAX;
+
+               EBUG_ON(btree_iter_path(trans, iter)->level);
 
                if (iter->flags & BTREE_ITER_INTENT) {
                        struct btree_iter iter2;
 
                        bch2_trans_copy_iter(&iter2, iter);
-                       k = bch2_btree_iter_peek(&iter2);
+                       k = bch2_btree_iter_peek_upto(&iter2, end);
 
                        if (k.k && !bkey_err(k)) {
+                               swap(iter->key_cache_path, iter2.key_cache_path);
                                iter->k = iter2.k;
                                k.k = &iter->k;
                        }
@@ -2667,16 +2509,19 @@ struct bkey_s_c bch2_btree_iter_peek_slot(struct btree_iter *iter)
                } else {
                        struct bpos pos = iter->pos;
 
-                       k = bch2_btree_iter_peek(iter);
-                       iter->pos = pos;
+                       k = bch2_btree_iter_peek_upto(iter, end);
+                       if (unlikely(bkey_err(k)))
+                               bch2_btree_iter_set_pos(iter, pos);
+                       else
+                               iter->pos = pos;
                }
 
                if (unlikely(bkey_err(k)))
-                       return k;
+                       goto out_no_locked;
 
                next = k.k ? bkey_start_pos(k.k) : POS_MAX;
 
-               if (bkey_cmp(iter->pos, next) < 0) {
+               if (bkey_lt(iter->pos, next)) {
                        bkey_init(&iter->k);
                        iter->k.p = iter->pos;
 
@@ -2694,8 +2539,8 @@ struct bkey_s_c bch2_btree_iter_peek_slot(struct btree_iter *iter)
                }
        }
 out:
-       iter->path->should_be_locked = true;
-
+       btree_path_set_should_be_locked(btree_iter_path(trans, iter));
+out_no_locked:
        bch2_btree_iter_verify_entry_exit(iter);
        bch2_btree_iter_verify(iter);
        ret = bch2_btree_iter_verify_ret(iter, k);
@@ -2721,76 +2566,99 @@ struct bkey_s_c bch2_btree_iter_prev_slot(struct btree_iter *iter)
        return bch2_btree_iter_peek_slot(iter);
 }
 
-/* new transactional stuff: */
-
-static inline void btree_path_verify_sorted_ref(struct btree_trans *trans,
-                                               struct btree_path *path)
+struct bkey_s_c bch2_btree_iter_peek_and_restart_outlined(struct btree_iter *iter)
 {
-       EBUG_ON(path->sorted_idx >= trans->nr_sorted);
-       EBUG_ON(trans->sorted[path->sorted_idx] != path->idx);
-       EBUG_ON(!(trans->paths_allocated & (1ULL << path->idx)));
+       struct bkey_s_c k;
+
+       while (btree_trans_too_many_iters(iter->trans) ||
+              (k = bch2_btree_iter_peek_type(iter, iter->flags),
+               bch2_err_matches(bkey_err(k), BCH_ERR_transaction_restart)))
+               bch2_trans_begin(iter->trans);
+
+       return k;
 }
 
-static inline void btree_trans_verify_sorted_refs(struct btree_trans *trans)
-{
+/* new transactional stuff: */
+
 #ifdef CONFIG_BCACHEFS_DEBUG
+static void btree_trans_verify_sorted_refs(struct btree_trans *trans)
+{
+       struct btree_path *path;
        unsigned i;
 
-       for (i = 0; i < trans->nr_sorted; i++)
-               btree_path_verify_sorted_ref(trans, trans->paths + trans->sorted[i]);
-#endif
+       BUG_ON(trans->nr_sorted != bitmap_weight(trans->paths_allocated, trans->nr_paths) - 1);
+
+       trans_for_each_path(trans, path, i) {
+               BUG_ON(path->sorted_idx >= trans->nr_sorted);
+               BUG_ON(trans->sorted[path->sorted_idx] != i);
+       }
+
+       for (i = 0; i < trans->nr_sorted; i++) {
+               unsigned idx = trans->sorted[i];
+
+               BUG_ON(!test_bit(idx, trans->paths_allocated));
+               BUG_ON(trans->paths[idx].sorted_idx != i);
+       }
 }
 
 static void btree_trans_verify_sorted(struct btree_trans *trans)
 {
-#ifdef CONFIG_BCACHEFS_DEBUG
        struct btree_path *path, *prev = NULL;
-       unsigned i;
+       struct trans_for_each_path_inorder_iter iter;
+
+       if (!bch2_debug_check_iterators)
+               return;
 
-       trans_for_each_path_inorder(trans, path, i) {
-               BUG_ON(prev && btree_path_cmp(prev, path) > 0);
+       trans_for_each_path_inorder(trans, path, iter) {
+               if (prev && btree_path_cmp(prev, path) > 0) {
+                       __bch2_dump_trans_paths_updates(trans, true);
+                       panic("trans paths out of order!\n");
+               }
                prev = path;
        }
-#endif
 }
+#else
+static inline void btree_trans_verify_sorted_refs(struct btree_trans *trans) {}
+static inline void btree_trans_verify_sorted(struct btree_trans *trans) {}
+#endif
 
-static inline void btree_path_swap(struct btree_trans *trans,
-                                  struct btree_path *l, struct btree_path *r)
+void __bch2_btree_trans_sort_paths(struct btree_trans *trans)
 {
-       swap(l->sorted_idx, r->sorted_idx);
-       swap(trans->sorted[l->sorted_idx],
-            trans->sorted[r->sorted_idx]);
+       int i, l = 0, r = trans->nr_sorted, inc = 1;
+       bool swapped;
 
-       btree_path_verify_sorted_ref(trans, l);
-       btree_path_verify_sorted_ref(trans, r);
-}
-
-static void btree_path_check_sort(struct btree_trans *trans, struct btree_path *path,
-                                 int cmp)
-{
-       struct btree_path *n;
+       btree_trans_verify_sorted_refs(trans);
 
-       if (cmp <= 0) {
-               n = prev_btree_path(trans, path);
-               if (n && btree_path_cmp(n, path) > 0) {
-                       do {
-                               btree_path_swap(trans, n, path);
-                               n = prev_btree_path(trans, path);
-                       } while (n && btree_path_cmp(n, path) > 0);
+       if (trans->paths_sorted)
+               goto out;
 
-                       goto out;
+       /*
+        * Cocktail shaker sort: this is efficient because iterators will be
+        * mostly sorted.
+        */
+       do {
+               swapped = false;
+
+               for (i = inc > 0 ? l : r - 2;
+                    i + 1 < r && i >= l;
+                    i += inc) {
+                       if (btree_path_cmp(trans->paths + trans->sorted[i],
+                                          trans->paths + trans->sorted[i + 1]) > 0) {
+                               swap(trans->sorted[i], trans->sorted[i + 1]);
+                               trans->paths[trans->sorted[i]].sorted_idx = i;
+                               trans->paths[trans->sorted[i + 1]].sorted_idx = i + 1;
+                               swapped = true;
+                       }
                }
-       }
 
-       if (cmp >= 0) {
-               n = next_btree_path(trans, path);
-               if (n && btree_path_cmp(path, n) > 0) {
-                       do {
-                               btree_path_swap(trans, path, n);
-                               n = next_btree_path(trans, path);
-                       } while (n && btree_path_cmp(path, n) > 0);
-               }
-       }
+               if (inc > 0)
+                       --r;
+               else
+                       l++;
+               inc = -inc;
+       } while (swapped);
+
+       trans->paths_sorted = true;
 out:
        btree_trans_verify_sorted(trans);
 }
@@ -2798,33 +2666,40 @@ out:
 static inline void btree_path_list_remove(struct btree_trans *trans,
                                          struct btree_path *path)
 {
-       unsigned i;
-
        EBUG_ON(path->sorted_idx >= trans->nr_sorted);
-
+#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
+       trans->nr_sorted--;
+       memmove_u64s_down_small(trans->sorted + path->sorted_idx,
+                               trans->sorted + path->sorted_idx + 1,
+                               DIV_ROUND_UP(trans->nr_sorted - path->sorted_idx,
+                                            sizeof(u64) / sizeof(btree_path_idx_t)));
+#else
        array_remove_item(trans->sorted, trans->nr_sorted, path->sorted_idx);
-
-       for (i = path->sorted_idx; i < trans->nr_sorted; i++)
+#endif
+       for (unsigned i = path->sorted_idx; i < trans->nr_sorted; i++)
                trans->paths[trans->sorted[i]].sorted_idx = i;
-
-       path->sorted_idx = U8_MAX;
-
-       btree_trans_verify_sorted_refs(trans);
 }
 
 static inline void btree_path_list_add(struct btree_trans *trans,
-                                      struct btree_path *pos,
-                                      struct btree_path *path)
+                                      btree_path_idx_t pos,
+                                      btree_path_idx_t path_idx)
 {
-       unsigned i;
-
-       btree_trans_verify_sorted_refs(trans);
+       struct btree_path *path = trans->paths + path_idx;
 
-       path->sorted_idx = pos ? pos->sorted_idx + 1 : 0;
+       path->sorted_idx = pos ? trans->paths[pos].sorted_idx + 1 : trans->nr_sorted;
 
-       array_insert_item(trans->sorted, trans->nr_sorted, path->sorted_idx, path->idx);
+#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
+       memmove_u64s_up_small(trans->sorted + path->sorted_idx + 1,
+                             trans->sorted + path->sorted_idx,
+                             DIV_ROUND_UP(trans->nr_sorted - path->sorted_idx,
+                                          sizeof(u64) / sizeof(btree_path_idx_t)));
+       trans->nr_sorted++;
+       trans->sorted[path->sorted_idx] = path_idx;
+#else
+       array_insert_item(trans->sorted, trans->nr_sorted, path->sorted_idx, path_idx);
+#endif
 
-       for (i = path->sorted_idx; i < trans->nr_sorted; i++)
+       for (unsigned i = path->sorted_idx; i < trans->nr_sorted; i++)
                trans->paths[trans->sorted[i]].sorted_idx = i;
 
        btree_trans_verify_sorted_refs(trans);
@@ -2832,78 +2707,29 @@ static inline void btree_path_list_add(struct btree_trans *trans,
 
 void bch2_trans_iter_exit(struct btree_trans *trans, struct btree_iter *iter)
 {
+       if (iter->update_path)
+               bch2_path_put_nokeep(trans, iter->update_path,
+                             iter->flags & BTREE_ITER_INTENT);
        if (iter->path)
                bch2_path_put(trans, iter->path,
                              iter->flags & BTREE_ITER_INTENT);
-       if (iter->update_path)
-               bch2_path_put(trans, iter->update_path,
-                             iter->flags & BTREE_ITER_INTENT);
        if (iter->key_cache_path)
                bch2_path_put(trans, iter->key_cache_path,
                              iter->flags & BTREE_ITER_INTENT);
-       iter->path = NULL;
-       iter->update_path = NULL;
-       iter->key_cache_path = NULL;
-}
-
-static void __bch2_trans_iter_init(struct btree_trans *trans,
-                                  struct btree_iter *iter,
-                                  unsigned btree_id, struct bpos pos,
-                                  unsigned locks_want,
-                                  unsigned depth,
-                                  unsigned flags,
-                                  unsigned long ip)
-{
-       EBUG_ON(trans->restarted);
-
-       if (!(flags & (BTREE_ITER_ALL_SNAPSHOTS|BTREE_ITER_NOT_EXTENTS)) &&
-           btree_node_type_is_extents(btree_id))
-               flags |= BTREE_ITER_IS_EXTENTS;
-
-       if (!(flags & __BTREE_ITER_ALL_SNAPSHOTS) &&
-           !btree_type_has_snapshots(btree_id))
-               flags &= ~BTREE_ITER_ALL_SNAPSHOTS;
-
-       if (!(flags & BTREE_ITER_ALL_SNAPSHOTS) &&
-           btree_type_has_snapshots(btree_id))
-               flags |= BTREE_ITER_FILTER_SNAPSHOTS;
-
-       if (!test_bit(JOURNAL_REPLAY_DONE, &trans->c->journal.flags))
-               flags |= BTREE_ITER_WITH_JOURNAL;
-
-       if (!btree_id_cached(trans->c, btree_id)) {
-               flags &= ~BTREE_ITER_CACHED;
-               flags &= ~BTREE_ITER_WITH_KEY_CACHE;
-       } else if (!(flags & BTREE_ITER_CACHED))
-               flags |= BTREE_ITER_WITH_KEY_CACHE;
-
-       iter->trans     = trans;
-       iter->path      = NULL;
-       iter->update_path = NULL;
-       iter->key_cache_path = NULL;
-       iter->btree_id  = btree_id;
-       iter->min_depth = depth;
-       iter->flags     = flags;
-       iter->snapshot  = pos.snapshot;
-       iter->pos       = pos;
-       iter->k.type    = KEY_TYPE_deleted;
-       iter->k.p       = pos;
-       iter->k.size    = 0;
-#ifdef CONFIG_BCACHEFS_DEBUG
-       iter->ip_allocated = ip;
-#endif
-
-       iter->path = bch2_path_get(trans, btree_id, iter->pos,
-                                  locks_want, depth, flags, ip);
+       iter->path              = 0;
+       iter->update_path       = 0;
+       iter->key_cache_path    = 0;
+       iter->trans             = NULL;
 }
 
-void bch2_trans_iter_init(struct btree_trans *trans,
+void bch2_trans_iter_init_outlined(struct btree_trans *trans,
                          struct btree_iter *iter,
-                         unsigned btree_id, struct bpos pos,
+                         enum btree_id btree_id, struct bpos pos,
                          unsigned flags)
 {
-       __bch2_trans_iter_init(trans, iter, btree_id, pos,
-                              0, 0, flags, _RET_IP_);
+       bch2_trans_iter_init_common(trans, iter, btree_id, pos, 0, 0,
+                              bch2_btree_iter_flags(trans, btree_id, flags),
+                              _RET_IP_);
 }
 
 void bch2_trans_node_iter_init(struct btree_trans *trans,
@@ -2914,56 +2740,80 @@ void bch2_trans_node_iter_init(struct btree_trans *trans,
                               unsigned depth,
                               unsigned flags)
 {
-       __bch2_trans_iter_init(trans, iter, btree_id, pos, locks_want, depth,
-                              BTREE_ITER_NOT_EXTENTS|
-                              __BTREE_ITER_ALL_SNAPSHOTS|
-                              BTREE_ITER_ALL_SNAPSHOTS|
-                              flags, _RET_IP_);
-       BUG_ON(iter->path->locks_want    < min(locks_want, BTREE_MAX_DEPTH));
-       BUG_ON(iter->path->level        != depth);
-       BUG_ON(iter->min_depth          != depth);
+       flags |= BTREE_ITER_NOT_EXTENTS;
+       flags |= __BTREE_ITER_ALL_SNAPSHOTS;
+       flags |= BTREE_ITER_ALL_SNAPSHOTS;
+
+       bch2_trans_iter_init_common(trans, iter, btree_id, pos, locks_want, depth,
+                              __bch2_btree_iter_flags(trans, btree_id, flags),
+                              _RET_IP_);
+
+       iter->min_depth = depth;
+
+       struct btree_path *path = btree_iter_path(trans, iter);
+       BUG_ON(path->locks_want  < min(locks_want, BTREE_MAX_DEPTH));
+       BUG_ON(path->level      != depth);
+       BUG_ON(iter->min_depth  != depth);
 }
 
 void bch2_trans_copy_iter(struct btree_iter *dst, struct btree_iter *src)
 {
+       struct btree_trans *trans = src->trans;
+
        *dst = *src;
+#ifdef TRACK_PATH_ALLOCATED
+       dst->ip_allocated = _RET_IP_;
+#endif
        if (src->path)
-               __btree_path_get(src->path, src->flags & BTREE_ITER_INTENT);
+               __btree_path_get(trans->paths + src->path, src->flags & BTREE_ITER_INTENT);
        if (src->update_path)
-               __btree_path_get(src->update_path, src->flags & BTREE_ITER_INTENT);
-       dst->key_cache_path = NULL;
+               __btree_path_get(trans->paths + src->update_path, src->flags & BTREE_ITER_INTENT);
+       dst->key_cache_path = 0;
 }
 
-void *bch2_trans_kmalloc(struct btree_trans *trans, size_t size)
+void *__bch2_trans_kmalloc(struct btree_trans *trans, size_t size)
 {
-       size_t new_top = trans->mem_top + size;
+       struct bch_fs *c = trans->c;
+       unsigned new_top = trans->mem_top + size;
+       unsigned old_bytes = trans->mem_bytes;
+       unsigned new_bytes = roundup_pow_of_two(new_top);
+       int ret;
+       void *new_mem;
        void *p;
 
-       if (new_top > trans->mem_bytes) {
-               size_t old_bytes = trans->mem_bytes;
-               size_t new_bytes = roundup_pow_of_two(new_top);
-               void *new_mem;
+       WARN_ON_ONCE(new_bytes > BTREE_TRANS_MEM_MAX);
 
-               WARN_ON_ONCE(new_bytes > BTREE_TRANS_MEM_MAX);
+       struct btree_transaction_stats *s = btree_trans_stats(trans);
+       s->max_mem = max(s->max_mem, new_bytes);
 
-               new_mem = krealloc(trans->mem, new_bytes, GFP_NOFS);
+       new_mem = krealloc(trans->mem, new_bytes, GFP_NOWAIT|__GFP_NOWARN);
+       if (unlikely(!new_mem)) {
+               bch2_trans_unlock(trans);
+
+               new_mem = krealloc(trans->mem, new_bytes, GFP_KERNEL);
                if (!new_mem && new_bytes <= BTREE_TRANS_MEM_MAX) {
-                       new_mem = mempool_alloc(&trans->c->btree_trans_mem_pool, GFP_KERNEL);
+                       new_mem = mempool_alloc(&c->btree_trans_mem_pool, GFP_KERNEL);
                        new_bytes = BTREE_TRANS_MEM_MAX;
                        kfree(trans->mem);
                }
 
                if (!new_mem)
-                       return ERR_PTR(-ENOMEM);
+                       return ERR_PTR(-BCH_ERR_ENOMEM_trans_kmalloc);
 
                trans->mem = new_mem;
                trans->mem_bytes = new_bytes;
 
-               if (old_bytes) {
-                       trace_trans_restart_mem_realloced(trans->fn, _RET_IP_, new_bytes);
-                       btree_trans_restart(trans);
-                       return ERR_PTR(-EINTR);
-               }
+               ret = bch2_trans_relock(trans);
+               if (ret)
+                       return ERR_PTR(ret);
+       }
+
+       trans->mem = new_mem;
+       trans->mem_bytes = new_bytes;
+
+       if (old_bytes) {
+               trace_and_count(c, trans_restart_mem_realloced, trans, _RET_IP_, new_bytes);
+               return ERR_PTR(btree_trans_restart(trans, BCH_ERR_transaction_restart_mem_realloced));
        }
 
        p = trans->mem + trans->mem_top;
@@ -2972,106 +2822,210 @@ void *bch2_trans_kmalloc(struct btree_trans *trans, size_t size)
        return p;
 }
 
+static inline void check_srcu_held_too_long(struct btree_trans *trans)
+{
+       WARN(trans->srcu_held && time_after(jiffies, trans->srcu_lock_time + HZ * 10),
+            "btree trans held srcu lock (delaying memory reclaim) for %lu seconds",
+            (jiffies - trans->srcu_lock_time) / HZ);
+}
+
+void bch2_trans_srcu_unlock(struct btree_trans *trans)
+{
+       if (trans->srcu_held) {
+               struct bch_fs *c = trans->c;
+               struct btree_path *path;
+               unsigned i;
+
+               trans_for_each_path(trans, path, i)
+                       if (path->cached && !btree_node_locked(path, 0))
+                               path->l[0].b = ERR_PTR(-BCH_ERR_no_btree_node_srcu_reset);
+
+               check_srcu_held_too_long(trans);
+               srcu_read_unlock(&c->btree_trans_barrier, trans->srcu_idx);
+               trans->srcu_held = false;
+       }
+}
+
+static void bch2_trans_srcu_lock(struct btree_trans *trans)
+{
+       if (!trans->srcu_held) {
+               trans->srcu_idx = srcu_read_lock(&trans->c->btree_trans_barrier);
+               trans->srcu_lock_time   = jiffies;
+               trans->srcu_held = true;
+       }
+}
+
 /**
  * bch2_trans_begin() - reset a transaction after a interrupted attempt
  * @trans: transaction to reset
  *
- * While iterating over nodes or updating nodes a attempt to lock a btree
- * node may return EINTR when the trylock fails. When this occurs
- * bch2_trans_begin() should be called and the transaction retried.
+ * Returns:    current restart counter, to be used with trans_was_restarted()
+ *
+ * While iterating over nodes or updating nodes a attempt to lock a btree node
+ * may return BCH_ERR_transaction_restart when the trylock fails. When this
+ * occurs bch2_trans_begin() should be called and the transaction retried.
  */
-void bch2_trans_begin(struct btree_trans *trans)
+u32 bch2_trans_begin(struct btree_trans *trans)
 {
-       struct btree_insert_entry *i;
        struct btree_path *path;
+       unsigned i;
+       u64 now;
 
-       trans_for_each_update(trans, i)
-               __btree_path_put(i->path, true);
+       bch2_trans_reset_updates(trans);
 
-       memset(&trans->journal_res, 0, sizeof(trans->journal_res));
-       trans->extra_journal_res        = 0;
-       trans->nr_updates               = 0;
+       trans->restart_count++;
        trans->mem_top                  = 0;
+       trans->journal_entries          = NULL;
 
-       trans->hooks                    = NULL;
-       trans->extra_journal_entries    = NULL;
-       trans->extra_journal_entry_u64s = 0;
+       trans_for_each_path(trans, path, i) {
+               path->should_be_locked = false;
 
-       if (trans->fs_usage_deltas) {
-               trans->fs_usage_deltas->used = 0;
-               memset(&trans->fs_usage_deltas->memset_start, 0,
-                      (void *) &trans->fs_usage_deltas->memset_end -
-                      (void *) &trans->fs_usage_deltas->memset_start);
-       }
+               /*
+                * If the transaction wasn't restarted, we're presuming to be
+                * doing something new: dont keep iterators excpt the ones that
+                * are in use - except for the subvolumes btree:
+                */
+               if (!trans->restarted && path->btree_id != BTREE_ID_subvolumes)
+                       path->preserve = false;
 
-       trans_for_each_path(trans, path) {
                /*
                 * XXX: we probably shouldn't be doing this if the transaction
                 * was restarted, but currently we still overflow transaction
                 * iterators if we do that
                 */
                if (!path->ref && !path->preserve)
-                       __bch2_path_free(trans, path);
+                       __bch2_path_free(trans, i);
                else
-                       path->preserve = path->should_be_locked = false;
+                       path->preserve = false;
        }
 
-       bch2_trans_cond_resched(trans);
+       now = local_clock();
 
-       if (trans->restarted)
+       if (!IS_ENABLED(CONFIG_BCACHEFS_NO_LATENCY_ACCT) &&
+           time_after64(now, trans->last_begin_time + 10))
+               __time_stats_update(&btree_trans_stats(trans)->duration,
+                                        trans->last_begin_time, now);
+
+       if (!trans->restarted &&
+           (need_resched() ||
+            time_after64(now, trans->last_begin_time + BTREE_TRANS_MAX_LOCK_HOLD_TIME_NS))) {
+               drop_locks_do(trans, (cond_resched(), 0));
+               now = local_clock();
+       }
+       trans->last_begin_time = now;
+
+       if (unlikely(trans->srcu_held &&
+                    time_after(jiffies, trans->srcu_lock_time + msecs_to_jiffies(10))))
+               bch2_trans_srcu_unlock(trans);
+
+       trans->last_begin_ip = _RET_IP_;
+       if (trans->restarted) {
                bch2_btree_path_traverse_all(trans);
+               trans->notrace_relock_fail = false;
+       }
 
-       trans->restarted = false;
+       return trans->restart_count;
 }
 
-static void bch2_trans_alloc_paths(struct btree_trans *trans, struct bch_fs *c)
-{
-       size_t paths_bytes      = sizeof(struct btree_path) * BTREE_ITER_MAX;
-       size_t updates_bytes    = sizeof(struct btree_insert_entry) * BTREE_ITER_MAX;
-       void *p = NULL;
+const char *bch2_btree_transaction_fns[BCH_TRANSACTIONS_NR] = { "(unknown)" };
 
-       BUG_ON(trans->used_mempool);
-
-#ifdef __KERNEL__
-       p = this_cpu_xchg(c->btree_paths_bufs->path , NULL);
-#endif
-       if (!p)
-               p = mempool_alloc(&trans->c->btree_paths_pool, GFP_NOFS);
+unsigned bch2_trans_get_fn_idx(const char *fn)
+{
+       for (unsigned i = 0; i < ARRAY_SIZE(bch2_btree_transaction_fns); i++)
+               if (!bch2_btree_transaction_fns[i] ||
+                   bch2_btree_transaction_fns[i] == fn) {
+                       bch2_btree_transaction_fns[i] = fn;
+                       return i;
+               }
 
-       trans->paths            = p; p += paths_bytes;
-       trans->updates          = p; p += updates_bytes;
+       pr_warn_once("BCH_TRANSACTIONS_NR not big enough!");
+       return 0;
 }
 
-void __bch2_trans_init(struct btree_trans *trans, struct bch_fs *c,
-                      unsigned expected_nr_iters,
-                      size_t expected_mem_bytes,
-                      const char *fn)
+struct btree_trans *__bch2_trans_get(struct bch_fs *c, unsigned fn_idx)
        __acquires(&c->btree_trans_barrier)
 {
-       BUG_ON(lock_class_is_held(&bch2_btree_node_lock_key));
+       struct btree_trans *trans;
 
+       if (IS_ENABLED(__KERNEL__)) {
+               trans = this_cpu_xchg(c->btree_trans_bufs->trans, NULL);
+               if (trans) {
+                       memset(trans, 0, offsetof(struct btree_trans, list));
+                       goto got_trans;
+               }
+       }
+
+       trans = mempool_alloc(&c->btree_trans_pool, GFP_NOFS);
        memset(trans, 0, sizeof(*trans));
-       trans->c                = c;
-       trans->fn               = fn;
+       closure_init_stack(&trans->ref);
 
-       bch2_trans_alloc_paths(trans, c);
+       seqmutex_lock(&c->btree_trans_lock);
+       if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG)) {
+               struct btree_trans *pos;
+               pid_t pid = current->pid;
 
-       if (expected_mem_bytes) {
-               trans->mem_bytes = roundup_pow_of_two(expected_mem_bytes);
-               trans->mem = kmalloc(trans->mem_bytes, GFP_KERNEL|__GFP_NOFAIL);
+               trans->locking_wait.task = current;
 
-               if (!unlikely(trans->mem)) {
-                       trans->mem = mempool_alloc(&c->btree_trans_mem_pool, GFP_KERNEL);
-                       trans->mem_bytes = BTREE_TRANS_MEM_MAX;
+               list_for_each_entry(pos, &c->btree_trans_list, list) {
+                       struct task_struct *pos_task = READ_ONCE(pos->locking_wait.task);
+                       /*
+                        * We'd much prefer to be stricter here and completely
+                        * disallow multiple btree_trans in the same thread -
+                        * but the data move path calls bch2_write when we
+                        * already have a btree_trans initialized.
+                        */
+                       BUG_ON(pos_task &&
+                              pid == pos_task->pid &&
+                              bch2_trans_locked(pos));
+
+                       if (pos_task && pid < pos_task->pid) {
+                               list_add_tail(&trans->list, &pos->list);
+                               goto list_add_done;
+                       }
                }
        }
+       list_add_tail(&trans->list, &c->btree_trans_list);
+list_add_done:
+       seqmutex_unlock(&c->btree_trans_lock);
+got_trans:
+       trans->c                = c;
+       trans->last_begin_time  = local_clock();
+       trans->fn_idx           = fn_idx;
+       trans->locking_wait.task = current;
+       trans->journal_replay_not_finished =
+               unlikely(!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags)) &&
+               atomic_inc_not_zero(&c->journal_keys.ref);
+       trans->nr_paths         = ARRAY_SIZE(trans->_paths);
+       trans->paths_allocated  = trans->_paths_allocated;
+       trans->sorted           = trans->_sorted;
+       trans->paths            = trans->_paths;
+       trans->updates          = trans->_updates;
+
+       *trans_paths_nr(trans->paths) = BTREE_ITER_INITIAL;
+
+       trans->paths_allocated[0] = 1;
 
-       trans->srcu_idx = srcu_read_lock(&c->btree_trans_barrier);
+       if (fn_idx < BCH_TRANSACTIONS_NR) {
+               trans->fn = bch2_btree_transaction_fns[fn_idx];
 
-       trans->pid = current->pid;
-       mutex_lock(&c->btree_trans_lock);
-       list_add(&trans->list, &c->btree_trans_list);
-       mutex_unlock(&c->btree_trans_lock);
+               struct btree_transaction_stats *s = &c->btree_transaction_stats[fn_idx];
+
+               if (s->max_mem) {
+                       unsigned expected_mem_bytes = roundup_pow_of_two(s->max_mem);
+
+                       trans->mem = kmalloc(expected_mem_bytes, GFP_KERNEL);
+                       if (likely(trans->mem))
+                               trans->mem_bytes = expected_mem_bytes;
+               }
+
+               trans->nr_paths_max = s->nr_max_paths;
+               trans->journal_entries_size = s->journal_entries_size;
+       }
+
+       trans->srcu_idx         = srcu_read_lock(&c->btree_trans_barrier);
+       trans->srcu_lock_time   = jiffies;
+       trans->srcu_held        = true;
+       return trans;
 }
 
 static void check_btree_paths_leaked(struct btree_trans *trans)
@@ -3079,44 +3033,42 @@ static void check_btree_paths_leaked(struct btree_trans *trans)
 #ifdef CONFIG_BCACHEFS_DEBUG
        struct bch_fs *c = trans->c;
        struct btree_path *path;
+       unsigned i;
 
-       trans_for_each_path(trans, path)
+       trans_for_each_path(trans, path, i)
                if (path->ref)
                        goto leaked;
        return;
 leaked:
        bch_err(c, "btree paths leaked from %s!", trans->fn);
-       trans_for_each_path(trans, path)
+       trans_for_each_path(trans, path, i)
                if (path->ref)
                        printk(KERN_ERR "  btree %s %pS\n",
-                              bch2_btree_ids[path->btree_id],
+                              bch2_btree_id_str(path->btree_id),
                               (void *) path->ip_allocated);
        /* Be noisy about this: */
        bch2_fatal_error(c);
 #endif
 }
 
-void bch2_trans_exit(struct btree_trans *trans)
+void bch2_trans_put(struct btree_trans *trans)
        __releases(&c->btree_trans_barrier)
 {
-       struct btree_insert_entry *i;
        struct bch_fs *c = trans->c;
 
        bch2_trans_unlock(trans);
 
        trans_for_each_update(trans, i)
-               __btree_path_put(i->path, true);
-       trans->nr_updates               = 0;
+               __btree_path_put(trans->paths + i->path, true);
+       trans->nr_updates       = 0;
+       trans->locking_wait.task = NULL;
 
        check_btree_paths_leaked(trans);
 
-       mutex_lock(&c->btree_trans_lock);
-       list_del(&trans->list);
-       mutex_unlock(&c->btree_trans_lock);
-
-       srcu_read_unlock(&c->btree_trans_barrier, trans->srcu_idx);
-
-       bch2_journal_preres_put(&c->journal, &trans->journal_preres);
+       if (trans->srcu_held) {
+               check_srcu_held_too_long(trans);
+               srcu_read_unlock(&c->btree_trans_barrier, trans->srcu_idx);
+       }
 
        if (trans->fs_usage_deltas) {
                if (trans->fs_usage_deltas->size + sizeof(trans->fs_usage_deltas) ==
@@ -3127,123 +3079,190 @@ void bch2_trans_exit(struct btree_trans *trans)
                        kfree(trans->fs_usage_deltas);
        }
 
+       if (unlikely(trans->journal_replay_not_finished))
+               bch2_journal_keys_put(c);
+
+       unsigned long *paths_allocated = trans->paths_allocated;
+       trans->paths_allocated  = NULL;
+       trans->paths            = NULL;
+
+       if (paths_allocated != trans->_paths_allocated)
+               kvfree_rcu_mightsleep(paths_allocated);
+
        if (trans->mem_bytes == BTREE_TRANS_MEM_MAX)
                mempool_free(trans->mem, &c->btree_trans_mem_pool);
        else
                kfree(trans->mem);
 
-#ifdef __KERNEL__
-       /*
-        * Userspace doesn't have a real percpu implementation:
-        */
-       trans->paths = this_cpu_xchg(c->btree_paths_bufs->path, trans->paths);
-#endif
+       /* Userspace doesn't have a real percpu implementation: */
+       if (IS_ENABLED(__KERNEL__))
+               trans = this_cpu_xchg(c->btree_trans_bufs->trans, trans);
+
+       if (trans) {
+               closure_sync(&trans->ref);
 
-       if (trans->paths)
-               mempool_free(trans->paths, &c->btree_paths_pool);
+               seqmutex_lock(&c->btree_trans_lock);
+               list_del(&trans->list);
+               seqmutex_unlock(&c->btree_trans_lock);
 
-       trans->mem      = (void *) 0x1;
-       trans->paths    = (void *) 0x1;
+               mempool_free(trans, &c->btree_trans_pool);
+       }
 }
 
 static void __maybe_unused
-bch2_btree_path_node_to_text(struct printbuf *out,
-                            struct btree_bkey_cached_common *_b,
-                            bool cached)
+bch2_btree_bkey_cached_common_to_text(struct printbuf *out,
+                                     struct btree_bkey_cached_common *b)
 {
-       pr_buf(out, "    l=%u %s:",
-              _b->level, bch2_btree_ids[_b->btree_id]);
-       bch2_bpos_to_text(out, btree_node_pos(_b, cached));
-}
+       struct six_lock_count c = six_lock_counts(&b->lock);
+       struct task_struct *owner;
+       pid_t pid;
 
-static bool trans_has_locks(struct btree_trans *trans)
-{
-       struct btree_path *path;
+       rcu_read_lock();
+       owner = READ_ONCE(b->lock.owner);
+       pid = owner ? owner->pid : 0;
+       rcu_read_unlock();
+
+       prt_tab(out);
+       prt_printf(out, "%px %c l=%u %s:", b, b->cached ? 'c' : 'b',
+                  b->level, bch2_btree_id_str(b->btree_id));
+       bch2_bpos_to_text(out, btree_node_pos(b));
 
-       trans_for_each_path(trans, path)
-               if (path->nodes_locked)
-                       return true;
-       return false;
+       prt_tab(out);
+       prt_printf(out, " locks %u:%u:%u held by pid %u",
+                  c.n[0], c.n[1], c.n[2], pid);
 }
 
-void bch2_btree_trans_to_text(struct printbuf *out, struct bch_fs *c)
+void bch2_btree_trans_to_text(struct printbuf *out, struct btree_trans *trans)
 {
-       struct btree_trans *trans;
-       struct btree_path *path;
-       struct btree *b;
+       struct btree_bkey_cached_common *b;
        static char lock_types[] = { 'r', 'i', 'w' };
-       unsigned l;
+       struct task_struct *task = READ_ONCE(trans->locking_wait.task);
+       unsigned l, idx;
 
-       mutex_lock(&c->btree_trans_lock);
-       list_for_each_entry(trans, &c->btree_trans_list, list) {
-               if (!trans_has_locks(trans))
-                       continue;
+       /* before rcu_read_lock(): */
+       bch2_printbuf_make_room(out, 4096);
 
-               pr_buf(out, "%i %s\n", trans->pid, trans->fn);
+       if (!out->nr_tabstops) {
+               printbuf_tabstop_push(out, 16);
+               printbuf_tabstop_push(out, 32);
+       }
 
-               trans_for_each_path(trans, path) {
-                       if (!path->nodes_locked)
-                               continue;
+       prt_printf(out, "%i %s\n", task ? task->pid : 0, trans->fn);
 
-                       pr_buf(out, "  path %u %c l=%u %s:",
-                              path->idx,
-                              path->cached ? 'c' : 'b',
-                              path->level,
-                              bch2_btree_ids[path->btree_id]);
-                       bch2_bpos_to_text(out, path->pos);
-                       pr_buf(out, "\n");
-
-                       for (l = 0; l < BTREE_MAX_DEPTH; l++) {
-                               if (btree_node_locked(path, l)) {
-                                       pr_buf(out, "    %s l=%u ",
-                                              btree_node_intent_locked(path, l) ? "i" : "r", l);
-                                       bch2_btree_path_node_to_text(out,
-                                                       (void *) path->l[l].b,
-                                                       path->cached);
-                                       pr_buf(out, "\n");
-                               }
+       /* trans->paths is rcu protected vs. freeing */
+       rcu_read_lock();
+       out->atomic++;
+
+       struct btree_path *paths = rcu_dereference(trans->paths);
+       if (!paths)
+               goto out;
+
+       unsigned long *paths_allocated = trans_paths_allocated(paths);
+
+       trans_for_each_path_idx_from(paths_allocated, *trans_paths_nr(paths), idx, 1) {
+               struct btree_path *path = paths + idx;
+               if (!path->nodes_locked)
+                       continue;
+
+               prt_printf(out, "  path %u %c l=%u %s:",
+                      idx,
+                      path->cached ? 'c' : 'b',
+                      path->level,
+                      bch2_btree_id_str(path->btree_id));
+               bch2_bpos_to_text(out, path->pos);
+               prt_newline(out);
+
+               for (l = 0; l < BTREE_MAX_DEPTH; l++) {
+                       if (btree_node_locked(path, l) &&
+                           !IS_ERR_OR_NULL(b = (void *) READ_ONCE(path->l[l].b))) {
+                               prt_printf(out, "    %c l=%u ",
+                                          lock_types[btree_node_locked_type(path, l)], l);
+                               bch2_btree_bkey_cached_common_to_text(out, b);
+                               prt_newline(out);
                        }
                }
+       }
 
-               b = READ_ONCE(trans->locking);
-               if (b) {
-                       path = &trans->paths[trans->locking_path_idx];
-                       pr_buf(out, "  locking path %u %c l=%u %c %s:",
-                              trans->locking_path_idx,
-                              path->cached ? 'c' : 'b',
-                              trans->locking_level,
-                              lock_types[trans->locking_lock_type],
-                              bch2_btree_ids[trans->locking_btree_id]);
-                       bch2_bpos_to_text(out, trans->locking_pos);
-
-                       pr_buf(out, " node ");
-                       bch2_btree_path_node_to_text(out,
-                                       (void *) b, path->cached);
-                       pr_buf(out, "\n");
-               }
+       b = READ_ONCE(trans->locking);
+       if (b) {
+               prt_printf(out, "  blocked for %lluus on",
+                          div_u64(local_clock() - trans->locking_wait.start_time,
+                                  1000));
+               prt_newline(out);
+               prt_printf(out, "    %c", lock_types[trans->locking_wait.lock_want]);
+               bch2_btree_bkey_cached_common_to_text(out, b);
+               prt_newline(out);
        }
-       mutex_unlock(&c->btree_trans_lock);
+out:
+       --out->atomic;
+       rcu_read_unlock();
 }
 
 void bch2_fs_btree_iter_exit(struct bch_fs *c)
 {
+       struct btree_transaction_stats *s;
+       struct btree_trans *trans;
+       int cpu;
+
+       if (c->btree_trans_bufs)
+               for_each_possible_cpu(cpu) {
+                       struct btree_trans *trans =
+                               per_cpu_ptr(c->btree_trans_bufs, cpu)->trans;
+
+                       if (trans) {
+                               closure_sync(&trans->ref);
+
+                               seqmutex_lock(&c->btree_trans_lock);
+                               list_del(&trans->list);
+                               seqmutex_unlock(&c->btree_trans_lock);
+                       }
+                       kfree(trans);
+               }
+       free_percpu(c->btree_trans_bufs);
+
+       trans = list_first_entry_or_null(&c->btree_trans_list, struct btree_trans, list);
+       if (trans)
+               panic("%s leaked btree_trans\n", trans->fn);
+
+       for (s = c->btree_transaction_stats;
+            s < c->btree_transaction_stats + ARRAY_SIZE(c->btree_transaction_stats);
+            s++) {
+               kfree(s->max_paths_text);
+               time_stats_exit(&s->lock_hold_times);
+       }
+
        if (c->btree_trans_barrier_initialized)
                cleanup_srcu_struct(&c->btree_trans_barrier);
        mempool_exit(&c->btree_trans_mem_pool);
-       mempool_exit(&c->btree_paths_pool);
+       mempool_exit(&c->btree_trans_pool);
+}
+
+void bch2_fs_btree_iter_init_early(struct bch_fs *c)
+{
+       struct btree_transaction_stats *s;
+
+       for (s = c->btree_transaction_stats;
+            s < c->btree_transaction_stats + ARRAY_SIZE(c->btree_transaction_stats);
+            s++) {
+               time_stats_init(&s->duration);
+               time_stats_init(&s->lock_hold_times);
+               mutex_init(&s->lock);
+       }
+
+       INIT_LIST_HEAD(&c->btree_trans_list);
+       seqmutex_init(&c->btree_trans_lock);
 }
 
 int bch2_fs_btree_iter_init(struct bch_fs *c)
 {
-       unsigned nr = BTREE_ITER_MAX;
        int ret;
 
-       INIT_LIST_HEAD(&c->btree_trans_list);
-       mutex_init(&c->btree_trans_lock);
+       c->btree_trans_bufs = alloc_percpu(struct btree_trans_buf);
+       if (!c->btree_trans_bufs)
+               return -ENOMEM;
 
-       ret   = mempool_init_kmalloc_pool(&c->btree_paths_pool, 1,
-                       sizeof(struct btree_path) * nr +
-                       sizeof(struct btree_insert_entry) * nr) ?:
+       ret   = mempool_init_kmalloc_pool(&c->btree_trans_pool, 1,
+                                         sizeof(struct btree_trans)) ?:
                mempool_init_kmalloc_pool(&c->btree_trans_mem_pool, 1,
                                          BTREE_TRANS_MEM_MAX) ?:
                init_srcu_struct(&c->btree_trans_barrier);