
Recall first from Lock granularity and the sleep/wakeup race
- One big lock is simple and deadlock-free but lets only one CPU run protected code at a time; Linux's Big Kernel Lock was removed entirely in version 2.6.39 (2011) after years of splitting it into finer locks.
- With lab counters in acquire, three processes allocating and freeing pages took kmem.lock 96,060 times and spun 126,039 times, while every other lock had at most 23 spins: kmem is the hot lock.
- Interrupt handlers run on whatever process they interrupted and cannot sleep; uartintr and virtio_disk_intr only take a spinlock briefly and call wakeup.
One lock, three CPUs: measuring contention
3 min readM3-S06A ended by pointing at a hot lock; this lesson fixes it. It measures contention, then replaces the single kmem lock with a per-CPU free-list where allocation is lock-free in the common case and stealing borrows from a neighbour under that CPU's lock.
Open kernel/kalloc.c in the xv6-riscv tree. The whole allocator is 82 lines, and its state is one anonymous struct:
// kernel/kalloc.c (stock xv6)
struct run {
struct run *next;
};
struct {
struct spinlock lock;
struct run *freelist;
} kmem;
Every free page holds a struct run in its first bytes, and kmem.freelist points to the first one. kfree pushes a page on the front of the list and kalloc pops one off, and both do it between acquire(&kmem.lock) and release(&kmem.lock). The critical section is three or four instructions long. That sounds harmless, but QEMU runs xv6 with -smp 3, so three harts can call kalloc in the same microsecond, and only one of them can hold the lock. The other two sit in the while loop of acquire, retrying the atomic swap. A CPU that spins does no useful work, and adding more CPUs adds more spinners, not more allocations: the allocator does not scale at all.
Lock contention is the situation where a CPU tries to acquire a lock that another CPU already holds, so it has to wait. It is measured by how often, and for how long, acquirers find the lock taken. is measurable, and you should measure before you change anything. Two numbers are enough. The first is how many times acquire failed its atomic swap and had to retry: add a counter to struct spinlock and bump it inside the spin loop. The second is how long the workload took, which a user program reads with the uptime() system call: it returns ticks, the counter that clockintr() in kernel/trap.c increments on CPU 0 at every timer interrupt, which the source comments as "about a tenth of a second".
The workload must hit the allocator from all CPUs at once. Growing and shrinking a process's memory does exactly that: sbrk(n) with a positive n calls growproc, which calls kalloc once per page, and a negative n frees the pages with kfree. This is our own test program, added to UPROGS in the Makefile:
// user/kmemtest.c (our test program)
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#define NCHILD 3
#define ROUNDS 5000
#define NPAGES 32
int
main(void)
{
lockstat(0); // reset the counters
int t0 = uptime();
for (int i = 0; i < NCHILD; i++) {
if (fork() == 0) {
for (int r = 0; r < ROUNDS; r++) {
char *a = sbrk(NPAGES * 4096);
if (a == SBRK_ERROR) {
printf("sbrk failed\n");
exit(1);
}
sbrk(-NPAGES * 4096);
}
exit(0);
}
}
for (int i = 0; i < NCHILD; i++)
wait(0);
int t1 = uptime();
printf("kmemtest: %d ticks\n", t1 - t0);
lockstat(1); // print the counters
exit(0);
}
lockstat is a small system call we added for this module (the counters and the call are shown in full in M3-S06B3): it prints, for every lock whose name starts with kmem or bcache, how many times it was acquired, how many swap attempts failed, and how much time (the RISC-V time counter, 10 million units per second on QEMU's virt board) acquirers spent spinning. Here is the stock kernel, run under make qemu on a three-hart QEMU:
$ kmemtest
kmemtest: 29 ticks
lock: kmem: #acquire 960060 #spin 418469 spintime 320613
total: #acquire 960060 #spin 418469 spintime 320613 elapsed 29008409
Three children times 5000 rounds times 32 pages, allocated and freed, is 960,000 lock acquisitions; the other 60 come from fork, exec and exit. Of those acquisitions, the failed swaps add up to 418469. That is the contention, and it is all on one lock.
A free list for every CPU
3 min readThe fix is not a faster lock. The amoswap in acquire is already a single instruction; what costs time is that three CPUs want the same lock at the same moment. The fix is to stop sharing. Turn the single struct into an array with one element per possible CPU. NCPU is 8 in kernel/param.h, which covers QEMU's three harts with room to spare:
// kernel/kalloc.c (lab change)
struct kmem {
struct spinlock lock;
struct run *freelist;
} kmem[NCPU];
void
kinit()
{
for (int i = 0; i < NCPU; i++)
initlock(&kmem[i].lock, "kmem");
freerange(end, (void *)PHYSTOP);
}
Every lock is still named kmem, so a statistics tool that matches names by prefix still finds them all. kinit runs only on CPU 0, early in main(), and freerange frees every page through kfree, so at boot all of physical memory lands on CPU 0's list. That is fine: the other CPUs fill their own lists by stealing, which the next section adds.
Now kfree. The page goes onto the list of the CPU that frees it:
// kfree, after the junk fill (lab change)
r = (struct run *)pa;
push_off(); // cpuid() is only stable with interrupts off
int id = cpuid();
acquire(&kmem[id].lock);
r->next = kmem[id].freelist;
kmem[id].freelist = r;
release(&kmem[id].lock);
pop_off();
The push_off() is not decoration. cpuid() returns the tp register, the hart number, and it is only true while the code stays on that hart. If interrupts were on, a timer interrupt could arrive between cpuid() and acquire, the scheduler could run another process here, and this process could resume later on a different hart, still holding the old id. Nothing would crash, because kmem[id].lock still protects kmem[id], but the point of the design, each CPU on its own list, would be lost. push_off() disables interrupts and counts the nesting, and acquire calls push_off() again internally, so the pair nests correctly with the lock's own push and pop.
The fast path of kalloc mirrors it: take your own lock, pop the first page, release. When three processes on three harts call kalloc, they touch three different locks and three different lists. None of them ever finds its lock held by another CPU, so the spin loop in acquire exits on the first swap. This is what "lock-free in the common case" means here: a lock is still acquired, but it is private in practice, so acquiring it costs one uncontended atomic swap and never a wait.
Stealing, and deleting the global lock
5 min readA per-CPU list can run dry even when memory is plentiful. Right after boot, CPU 1 and CPU 2 have empty lists and CPU 0 has every page. A process that frees many pages on CPU 2 and then migrates to CPU 1 leaves its memory on the wrong list. So kalloc needs a slow path: if its own list is empty, it walks the other CPUs and takes a page from the first list that has one.
// kalloc (lab change)
void *
kalloc(void)
{
struct run *r;
push_off();
int id = cpuid();
acquire(&kmem[id].lock);
r = kmem[id].freelist;
if (r)
kmem[id].freelist = r->next;
release(&kmem[id].lock);
// own list empty: steal one page from another CPU, under its lock
for (int i = 0; r == 0 && i < NCPU; i++) {
if (i == id)
continue;
acquire(&kmem[i].lock);
r = kmem[i].freelist;
if (r)
kmem[i].freelist = r->next;
release(&kmem[i].lock);
}
pop_off();
if (r)
memset((char *)r, 5, PGSIZE); // fill with junk
return (void *)r;
}
Three details make this correct. First, the CPU releases its own lock before it starts stealing, so at any moment it holds at most one kmem lock. Two CPUs stealing from each other at the same time therefore cannot deadlock: neither waits for a lock while holding another, so there is no cycle to form. Second, the victim's list is only ever touched under the victim's lock, the same lock the victim uses for its own kalloc and kfree, so the victim's list stays consistent. Third, kalloc returns 0 only after every list was found empty, which is the same out-of-memory contract the stock allocator has.
There is no global lock left anywhere: the old kmem.lock is gone, and so is the old kmem variable, because kmem is now an array. Any code you wrote earlier that walks kmem.freelist, such as a sysinfo free-memory counter, will no longer compile, and it should walk all NCPU lists, each under its own lock. The memset junk fill, which writes 4096 bytes and is by far the slowest step, stays outside every lock in both kalloc and kfree, exactly as in the stock code.
Here is kmemtest again on the changed kernel, same QEMU, same three harts:
$ kmemtest
kmemtest: 39 ticks
lock: kmem: #acquire 320179 #spin 15 spintime 64
lock: kmem: #acquire 318975 #spin 0 spintime 0
lock: kmem: #acquire 321045 #spin 0 spintime 0
total: #acquire 960199 #spin 15 spintime 64 elapsed 38625635
There are three kmem lines because only three of the eight locks were ever acquired: QEMU has three harts, so kmem[3] to kmem[7] stay empty and unused. The total number of acquisitions is about the same as before, because the work is the same, but it is split into three nearly equal shares, and the failed swaps fell from 418469 to 15. Your own counts will differ from run to run (a second run of ours printed 0 spins in total), but a drop from hundreds of thousands to almost nothing is what you should see.
Look at the tick count too: it did not fall. Our two runs before the change took 29 and 35 ticks, our two runs after it 39 and 29. Under QEMU, most of each round is spent in the two 4096-byte memset fills and in page-table work, all of which run outside the lock, so the time saved by not spinning is small next to the total. The spin time line makes this visible: before the change acquirers spent 320613 time units spinning (0.032 seconds over all three harts), out of a run of 29 ticks. M3-S06B3 returns to this question of when removing contention actually shortens a run.
Going deeperSplit the state, do not polish the lock
The general lesson reaches far beyond xv6. Contention comes from many CPUs writing the same memory: the lock word and the list head live in one cache line, and every acquire by a different CPU has to pull that line over from the CPU that last wrote it. A cleverer lock (a ticket lock, a queued lock) can make the waiting fairer or quieter, but every CPU still has to take its turn on the same line, so the throughput limit stays the same. Splitting the data removes the shared line altogether, which is why per-CPU structures appear wherever a kernel must scale: Linux keeps per-CPU lists of free pages in front of its page allocator for the same reason. The price is the slow path: a split structure needs a rule for when one share runs out (here, stealing) and a way to see the whole (here, walking all lists). Whenever you find a hot lock, ask first whether the data it protects can be divided so that most operations never touch another CPU's share.
The next lesson finds the second hot lock: every disk block read goes through bcache.lock in kernel/bio.c, and the same idea of splitting, this time by a hash of the block number, applies there.
Key takeaways
- Stock xv6 protects every free page with one spinlock, kmem.lock, so kalloc and kfree on all harts queue on it
- With kmem[NCPU] each CPU allocates and frees on its own list, and the kmemtest spin count fell from 418469 to 15 in our run
- cpuid() is only meaningful between push_off() and pop_off(), because a timer interrupt can move the process to another CPU
- A CPU whose list is empty steals a page from another CPU while holding only that CPU's lock, so no lock order and no deadlock is possible
Reflect
- Explain to a colleague, in two sentences: measure kmem lock contention with a spin counter and the uptime tick counter
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Sourcexv6-riscv kernel/kalloc.c
- Sourcexv6-riscv kernel/spinlock.c
- Bookxv6: a simple, Unix-like teaching operating system (RISC-V, rev5)
Official documentation first. Links checked when the lesson was published.