How the Linux Context Switch Works: switch_to, Kernel Stacks, and Lazy FPU Restoration
A thread that calls sched_yield() or blocks on a futex does not leave its registers sitting in the CPU. The core must start executing another task. That handover is a context switch. The policy that chose the next task is the scheduler; the mechanism that actually moves the CPU from one task to the other is what this article covers.
Related reading: How Linux CFS Works, How System Calls Work, and How Virtual Memory Works.
The contract
A context switch saves enough state of the outgoing task so that it can later resume exactly where it stopped, then loads the state of the incoming task. On Linux the switch always happens inside the kernel, in schedule(). User-mode registers are already saved on the kernel stack by the entry path (syscall, interrupt, or exception). What remains is the kernel's own call chain and a few architecture-specific pieces.
Two things must change:
- The kernel stack pointer, so the CPU is now walking the incoming task's call chain.
- The address space, if the two tasks have different mm_structs, so subsequent user accesses translate against the right page tables.
Everything else (FPU, segment bases, debug registers) is either restored lazily or handled in a small C helper after the stack has already switched.
Where the switch happens
__schedule() selects the next task with pick_next_task(). If it differs from the current one, it calls context_switch(). That function does three main things:
- prepare_task_switch() for tracing and accounting.
- Switch the memory context with switch_mm_irqs_off() if the mm differs. This loads a new CR3 (or an ASID/PCID-tagged root). Kernel threads have no mm of their own; they borrow the previous active_mm under the lazy TLB rule.
- Call switch_to(prev, next, prev). After this call returns, the CPU is running on next's kernel stack.
The third argument is written back with the identity of the task that was running immediately before next last blocked. That lets finish_task_switch() clean up the correct previous task even if next has migrated between CPUs.
The assembly heart: __switch_to_asm
On x86-64, switch_to expands to a call to __switch_to_asm. The routine is short because the C calling convention already lets the call clobber most registers. Only the callee-saved ones (rbx, rbp, r12–r15) need an explicit save:
__switch_to_asm:
pushq %rbp
pushq %rbx
pushq %r12
pushq %r13
pushq %r14
pushq %r15
movq %rsp, TASK_threadsp(%rdi) /* save prev's stack pointer */
movq TASK_threadsp(%rsi), %rsp /* load next's stack pointer */
popq %r15
popq %r14
popq %r13
popq %r12
popq %rbx
popq %rbp
jmp __switch_to /* C helper for the rest */
The single instruction that changes which task is running is the load of %rsp. After that point the CPU is executing on next's kernel stack. The pops restore the registers that next pushed when it was switched out earlier. The jump into __switch_to continues on next's stack; when that function returns it returns into the schedule() call that next itself made last time it blocked.
Each task therefore appears frozen inside its own previous call to schedule(), with its kernel stack holding the continuation. There is no separate scheduler thread.
What __switch_to finishes
The C function __switch_to runs after the stack has switched, so current already points at next. It updates:
- FS and GS bases (thread-local storage).
- The TSS.sp0 so the next interrupt or exception uses next's kernel stack.
- Debug registers if they differ.
- FPU ownership. On modern kernels the actual XSAVE state is not restored here. Instead the kernel sets TIF_NEED_FPU_LOAD. The first use of the FPU (or the return to user mode) will restore it. This is the lazy path: a task that never touches floating-point or vector state pays almost nothing.
Protection-key state (PKRU) is an exception; it must be correct immediately because kernel accesses to user memory also honor it.
Why the switch is not free
Direct cost is small: a few dozen cycles for the register pushes, the stack swap, and the CR3 load when address spaces differ. Indirect cost is larger. The incoming task usually finds cold L1/L2 caches and a TLB that no longer matches its working set. On a machine with KPTI the CR3 switch also invalidates most user TLB entries. A tight loop that forces a context switch on every iteration therefore measures cache and TLB misses more than the switch itself.
Threads of the same process share an mm, so the CR3 load is skipped. That is one reason a context switch between threads is cheaper than a switch between processes.
Misconceptions
- The scheduler runs as its own thread. No. schedule() always runs in the context of the current task. The switch merely changes which task's stack the CPU is walking.
- All registers are saved and restored on every switch. Only callee-saved integer registers are pushed by the assembly. User registers were already saved by the entry path. FPU state is restored lazily.
- A context switch always changes the address space. Only when the mm differs. Kernel threads and same-process threads do not.
Takeaways
A Linux context switch is a change of kernel stack pointer plus, when needed, a change of page-table root. The assembly routine saves a handful of callee-saved registers, swaps %rsp, and continues on the new stack. FPU state is marked for lazy restore so that pure integer code does not pay for XSAVE. The scheduler decides who runs; the switch mechanism only moves the CPU. Both pieces are required, and they are not the same piece.
See also How Linux CFS Works for the selection policy and How RCU Works for why a context switch is a quiescent state.