SwadhyAI Notes

All Operating Systems notes

Start here

A context switch is changing the CPU from running one thread to another. It is more than saving registers, address-space switches can affect the TLB; FPU state may be lazily managed.

Context switch (definition)

The scheduler picks the next runnable entity, saves the old execution context (registers, kernel stack pointer, and optionally FPU), updates address-space registers if needed, then restores the new context and resumes execution.

By the end of this page you should be able to

  1. Explain why switching between two threads in the same process is often cheaper than two processes.
  2. Name two costs beyond saving general-purpose registers.
  3. Relate `switch_mm` (conceptually) to address-space change.

Operating systems · Processes

Context switching

Saving one execution context and restoring another

TL;DR

A context switch changes the CPU from running one thread to another: save registers and kernel stack pointer, switch address space if needed (`switch_mm`), load the next thread’s state, and resume at its saved PC, cost includes TLB/cache effects beyond the obvious register moves.

Summary

Context switches are the tax of multitasking. OS design minimizes them via batching, smarter wakeup patterns, and avoiding unnecessary cross-core migrations.

Deeper narrative

Context switches are not free: switching `mm` flushes TLB shootdowns on some paths; FPU state is lazy; spectre mitigations add fences. The scheduler switches when quantum expires, higher priority wakes, or blocking syscalls yield CPU.

Mechanism (step by step)

Treat each step as a sentence in the story you tell on a whiteboard.
1

Pick next

Scheduler selects runnable entity respecting affinity and cgroup limits.

2

Save old

Store GPRs, kernel SP, FPU if needed, perf counters optional.

3

Switch address space

If `mm` differs, load CR3 / ASID; shootdown remote TLB entries if required.

4

Restore new

Load GPRs, return to kernel or user mode continuation.

Key insights

Each card is a compression of the lesson, use them as spaced-repetition prompts.

Scheduler vs context switch

Picking “who next” is policy; switching is mechanism, both must be fast, but different code paths.

Address space switch cost

Reloading CR3 / TTBR0 flushes user TLB entries, why separating I/O threads across cores with hot caches matters.

Kernel preemption

Linux can preempt kernel threads unless holding spinlocks, design invariant to avoid deadlocks on SMP.

Metrics

`context-switches` field in `/proc/stat` helps correlate latency spikes with scheduling churn.

Did you know?

Trivia with teeth: the kind of fact that changes how you reason about a design.
Switching within the same address space (threads) avoids `switch_mm` but still invalidates some microarchitectural state.
Voluntary switches happen on blocking syscalls; involuntary on timer preemption.
Some kernels optimize lazy FPU save so SIMD state is not touched until user uses it.

Common pitfalls

Where smart people still trip, read slowly.

Ignoring TLB effects

Thread switches cheaper than process switches due to shared `mm`: benchmark fairly.

Measuring switch cost alone

Cache cold misses after switch dominate microbenchmarks, use realistic working sets.

Comparison

Thread switch vs process switch (typical)

Thread switch (same process)Process switch
Address spaceUsually unchangedOften `switch_mm`
TLB user entriesMay remain validOften flushed
Typical relative costLowerHigher

Another lens

Switch cost drivers

ChangeTypical extra cost
Same thread group, same mmRegisters + kernel stack
Different mmTLB/PCID/ASID management
Cross-CPU migrationCache cold + runqueue remote locks

Glossary

ASID

Address Space ID tags TLB entries to avoid full flush on some switches.

CR3

x86 page table root physical address register.

Runqueue lock

Protects scheduler structures; contention shows as sys time.

Interview follow-ups

  1. Why is switching between two kernel threads cheaper than two processes?
  2. What is lazy FPU context switching?
  3. When does `switch_mm` not run during a context switch?

Callouts

Perf

If profiling shows high `context-switches` with low CPU, look for lock contention or excessive `poll`/`select` wakeups.

Walkthrough & deep dive

Left: practical “how would I use this?” threads. Right: slower, code-leaning explanations, open one panel at a time so the page does not feel like a wall of sameness.

Walkthrough

Estimate

Discuss why a pipeline of tiny processes can be slower than threads passing buffers in one address space.

Deep dive

What `schedule()` does (conceptually)

Dequeue current from runqueue if not blocking, pick next entity via class-specific logic, context_switch to next, return when your task runs again.

Context switch rate

Terminal
grep ctxt /proc/stat

Self-check

Misses here are cheap; misses in an interview are not. Treat wrong answers as a patch list for tomorrow.

1Switching address spaces on x86 typically involves…

2Voluntary context switch often follows…

3TLB flushes hurt performance because…