Skip to content

Read thread-locals safely when fibers migrate OS threads - #66

Merged
vadimskipin merged 2 commits into
mainfrom
vskipin/fix-tls-caching-across-fiber-migration
Jun 10, 2026
Merged

vadimskipin merged 2 commits into
mainfrom
vskipin/fix-tls-caching-across-fiber-migration

Conversation

@vadimskipin

Copy link
Copy Markdown
Collaborator

A fiber can suspend on one scheduler thread and resume on another, but the compiler caches the thread pointer in a callee-saved register that jump_fcontext preserves across the switch. After a migration, thread-local reads then address the previous thread's storage and return a stale value or null. This crashed getCurrentFiber (null deref of Fiber::isProxyFiber at 0x9) and made getCurrentProcessor pick the wrong io_uring ring. It worsens with inlining/unity/LTO; GCC and Clang have no /GT equivalent (PR 26461).

Make the accessors independent of the thread pointer being cached:

  • getCurrentProcessor reads it via volatile asm (movq %fs:0 / mrs tpidr_el0) so it cannot be hoisted across a suspension.
  • getCurrentFiber/getCurrentFiberId are noinline, so their reads run in a fresh activation on the current thread.

Add docs/tls.md on using thread-local storage from fiber code.

A fiber can suspend on one scheduler thread and resume on another, but the
compiler caches the thread pointer in a callee-saved register that
`jump_fcontext` preserves across the switch. After a migration, thread-local
reads then address the previous thread's storage and return a stale value or
null. This crashed `getCurrentFiber` (null deref of `Fiber::isProxyFiber` at
`0x9`) and made `getCurrentProcessor` pick the wrong io_uring ring. It worsens
with inlining/unity/LTO; GCC and Clang have no `/GT` equivalent (PR 26461).

Make the accessors independent of the thread pointer being cached:
- `getCurrentProcessor` reads it via volatile asm (`movq %fs:0` / `mrs
  tpidr_el0`) so it cannot be hoisted across a suspension.
- `getCurrentFiber`/`getCurrentFiberId` are `noinline`, so their reads run in a
  fresh activation on the current thread.

Add `docs/tls.md` on using thread-local storage from fiber code.
@vadimskipin
vadimskipin merged commit 35d0256 into main Jun 10, 2026
14 checks passed
@vadimskipin
vadimskipin deleted the vskipin/fix-tls-caching-across-fiber-migration branch June 10, 2026 16:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant