Chapter 22Down the Rabbit Hole: How Linux Frees Memory Nobody Admits to Reading
One line in the kernel docs pulled me in: in a non-preemptible kernel, rcu_read_lock() generates no code. Not an atomic, not a relaxed load. Nothing.
A reader that does nothing can't tell anyone it's reading. So how does the kernel know when it's safe to free memory under it? Freeing memory another CPU is still dereferencing is a use-after-free. The answer is RCU's grace period.
The shop sign#
A shop swaps a price sign. Shoppers mid-glance at the old one are still looking. The manager hangs the new sign where new shoppers will see it, waits until everyone who was already looking has walked on, then bins the old sign.
In the kernel: a route list A -> B -> C, four cores reading. Core 2 is partway through reading B when an admin deletes it. One pointer store makes the list A -> C. Core 3 starts a lookup and never sees B. Core 2 still holds B, so B stays allocated until every core has passed a point where it provably isn't mid-lookup.
list: A ──▶ B ──▶ C core 2: reading B core 3: idle state: nothing happening yet
Core 2 is partway through a lookup that reached B.
That "wait for everyone who was already looking" is the grace period.
Why not just take a lock#
Both usual fixes make readers pay. A reader-writer lock makes every reader write the lock word, and that cache line bounces between CPUs all day. A reference count costs two atomics on a shared line per lookup. The common case, a read, pays for the rare case, an update.
RCU's constraint is the opposite: readers write nothing shared. Then the updater can't see readers at all, so it needs another way to know they're gone.
CPU0 lookup: write lock word ──┐ CPU1 lookup: write lock word ──┼──▶ [ lock word ] one line, CPU2 lookup: write lock word ──┤ bouncing CPU3 lookup: write lock word ──┘ between CPUs
CPU0 lookup: read data (own cache) CPU1 lookup: read data (own cache) CPU2 lookup: read data (own cache) CPU3 lookup: read data (own cache) nothing shared is written; the updater pays instead
The API from a driver author's side
/* reader */
rcu_read_lock();
p = rcu_dereference(gp);
if (p) use(p->a);
rcu_read_unlock(); /* p must not be used after this */
/* updater (holds its own lock) */
new = kmalloc(sizeof(*new), GFP_KERNEL);
new->a = 42;
old = rcu_dereference_protected(gp, lockdep_is_held(&my_lock));
rcu_assign_pointer(gp, new); /* store-release */
synchronize_rcu(); /* sleeps one grace period */
kfree(old);
/* or, without sleeping: kfree_rcu(old, rcu); */rcu_assign_pointer is a store-release, so a reader that sees the new pointer also sees the new node's fields. And the updater still holds its own lock: RCU coordinates readers with updaters, but two updaters still need ordinary mutual exclusion.
The rule, in one line#
For any read-side critical section R and any grace period G:
either R ends before G ends,
or R begins after G begins.They can't straddle. The updater unlinks, runs G, then frees. Any reader that could have seen the old node started before the unlink, so before G began, so it's done when G ends.
The surprise: a reader that starts a microsecond after the unlink is not waited for. It can run long past the grace period, because it can never reach the old node.
Counting nothing#
In classic RCU a read-side section can't block or be switched out. So if a CPU context-switches, goes idle, or returns to user mode, it cannot be inside an earlier read section. That moment is a quiescent state.
The kernel never tracks readers. It watches CPUs for events they go through anyway. Once every CPU has had one after the unlink, the grace period is over. The evidence comes from the scheduler, not the reader, which is why the read side can compile to nothing.
Relax the rule and it breaks: let readers sleep and a context switch proves nothing. That's why SRCU exists, with explicit per-reader accounting.
Making it scale: the combining tree#
One bitmask with a bit per CPU becomes the exact cache-line fight RCU avoids. Tree RCU uses a combining tree instead.
┌──────────────┐
│ root node │ mask 0 => grace period over
└──┬────────┬──┘
┌───────┘ └───────┐
┌──────┴──────┐ ┌──────┴──────┐
│ leaf node │ ... │ leaf node │ leaf mask 0 =>
└─┬───┬─────┬─┘ └─┬───┬─────┬─┘ clear bit in parent
CPU0 CPU1 .. CPU15 CPU16 .. CPU31Each per-CPU rcu_data points at a leaf rcu_node. Leaves cover 16 CPUs by default (CONFIG_RCU_FANOUT_LEAF). 64 leaves of 16 gives 1,024 CPUs in two levels.
A kernel thread drives it. In rcu_gp_fqs_loop() it sleeps for jiffies_till_first_fqs, checks whether the root mask is zero, and if not goes looking for CPUs that haven't reported, then sleeps jiffies_till_next_fqs and retries. Idle CPUs aren't asked; they're already in an extended quiescent state.
The main loop in tree.c, and gp_seq
I read kernel/rcu/tree.c for this. The loop is pleasingly small:
for (;;) {
for (;;) { /* wait for a GP request */
gp_state = RCU_GP_WAIT_GPS;
swait_event_idle_exclusive(gp_wq, gp_flags & RCU_GP_FLAG_INIT);
gp_state = RCU_GP_DONE_GPS;
if (rcu_gp_init()) break;
}
rcu_gp_fqs_loop(); /* wait, then force quiescent states */
gp_state = RCU_GP_CLEANUP;
rcu_gp_cleanup();
gp_state = RCU_GP_CLEANED;
}CPUs can disagree about which grace period is current. Each rcu_node and rcu_data carries a gp_seq counter with the phase in its low two bits, and a CPU in dyntick-idle can lag arbitrarily and catch up on wake. Comparing these needs wrap-safe arithmetic (subtract unsigned, check which half of the range you landed in), not a plain less-than.
Two ways to wait#
synchronize_rcu()sleeps through a grace period. Simple, but the updater blocks for roughly milliseconds. The expedited variant, per the kernel docs, spends tens of microseconds of extra CPU to cut the wait from milliseconds to tens of microseconds.call_rcu()queues a callback and returns.kfree_rcu()is shorthand for "free this after a grace period".
The backlog grows, the batch grows, but no single batch freezes the CPU.
A toy that shows the cost#
The dive included a small Python simulator that models only the rule that matters: after an unlink, the wait ends when every CPU has passed a quiescent state. A CPU in a read section reports when it ends; any other CPU reports at its next scheduler event, up to one 1 ms tick away.
The simulator's output
cpus read_us GP mean us GP p99 us old readers at unlink
1 10 477 987 0.05
1 500 495 1947 0.71
16 10 940 999 0.76
16 500 1537 3544 11.37
256 10 996 1000 12.16
256 500 2892 4745 182.83These are model parameters, not kernel measurements, but the shapes matter. The grace period is roughly as long as the slowest CPU, so more CPUs push the mean toward the worst case. And the last column is why RCU exists: freeing at the moment of unlink would hit that many live readers per update. At 16 CPUs with 500 µs reads, that's 11 use-after-frees every time.
Where it breaks#
The grace period is only as fast as the slowest CPU. That's the design, and the failure mode.
| Failure | What happens |
|---|---|
| Stalls | One CPU never passes a quiescent state, so no grace period finishes anywhere. Culprits per the kernel docs: looping inside a read section, looping with interrupts or preemption off, a non-preemptible loop with no cond_resched(), even a slow console. After CONFIG_RCU_CPU_STALL_TIMEOUT you get "rcu_sched detected stall". |
| Callback floods | Every call_rcu() holds memory until its grace period ends. Once a CPU's queue grows by more than qhimark (10,000), call_rcu_core() kicks the grace period and raises the batch limit to 10,000. That drains, but can't make a grace period end if a CPU won't report. |
| Module unload | synchronize_rcu() doesn't wait for queued callbacks. Stop posting, then call rcu_barrier() before unload, or a callback runs code that's gone. |
| "Just a moment" | After rcu_read_unlock() the pointer is not safe for a bit longer. The grace period can end the instant you leave. |
Preemptible RCU (real-time kernels) lets a read section be preempted, so a preempted reader now holds up the grace period. PREEMPT_RT uses priority boosting to get those readers running again.
The open question: fast reads or bounded memory#
RCU and epoch-style reclamation make reads nearly free, but one stalled reader blocks every free on the machine. Hazard pointers go the other way: each reader announces its pointer, so a stalled reader pins only what it announced. The cost is a store and a barrier per protected read.
| Scheme | Read cost | Stalled reader |
|---|---|---|
| Reader-writer lock | Writes the lock word | Blocks writers |
| Reference count | Two atomics | Pins one object |
| RCU / epoch | About none | Blocks all reclamation |
| Hazard pointers | Store + barrier per pointer | Pins only what it announced |
A 2026 proposal from Desnoyers and McKenney, covered on LWN, adds hazard pointers to the kernel beside RCU for cases where one stuck reader must not block all frees. Hybrids like HP-BRCU and EpochPOP claim bounded memory with cheap reads, but I only saw the authors' claims and couldn't verify them.
Other pressures on the edges
- Lazy RCU (
CONFIG_RCU_LAZY) batches callbacks for roughly 10 seconds on offloaded CPUs so idle cores can sleep. The patch reported 5 to 10% idle power savings, andcall_rcu_hurry()exists because some callers can't wait that long. - A vCPU preempted by the hypervisor looks like a running one, which breaks assumptions cheap-reader tricks rely on.
- A PLDI 2025 paper mechanically verifies RCU on relaxed memory. I only saw the metadata.
What stays with me is how much of the cleverness is not doing work. The reader does nothing, the scheduler does what it was going to anyway, and a tree of bitmasks adds it up. The cost lands on the updater, as latency and memory, and on the one CPU that forgets to stop.
If I go deeper next, it'll be hazard pointers: how announcing a pointer bounds memory, and what it costs each read.
Sources#
- Linux kernel docs, What is RCU?
- Linux kernel docs, RCU data structures (the
rcu_nodetree,rcu_data, segmented callback lists) - Linux kernel docs, RCU CPU stall warnings
- Linux source:
kernel/rcu/tree.c,tree.h,srcutree.c(mainline, read October 2026) - LWN, hazard pointers proposal
- LWN, RCU changes for lazy preemption
- LWN, vCPU preemption and asymmetric barriers
- "Verifying General-Purpose RCU for Reclamation in Relaxed Memory Separation Logic", PLDI 2025, DOI 10.1145/3729246 (metadata only)