Expert · Module 10 · Lesson 4 of 12
Manual Assembly Context Switching: Callee-Saved Registers and Stack Pivots
Implement sub-5-nanosecond x86-64 user-space context switches in pure assembly, manipulate stack pivots, and seed initial stack frames for new fibers.
By the end you can
- Author an x86-64 assembly context switch routine adhering to the System V AMD64 ABI
- Preserve and restore callee-saved registers (%rbx, %rbp, %r12-%r15) without kernel traps
- Execute an atomic stack pivot between outgoing and incoming fiber stack pointers
- Seed synthetic activation records on fresh stacks so that ret jumps cleanly into entry functions
Builds on Historical & Standard Primitives: setjmp/longjmp, sigaltstack, and ucontext_t.
01 · A question first
A kernel thread switch takes 1,500 nanoseconds and POSIX swapcontext takes 600 nanoseconds. How can a hand-rolled 14-instruction x86-64 assembly routine switch entire execution contexts in under 3 nanoseconds?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Start with the problem
- How the idea works
- Complete Working Implementation: Two-Way Fiber Ping-Pong
- Why it is correct
- Pitfalls and variations
- Where it is used
03 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem