Module 3 · Lesson 38 of 77

Lock granularity and the sleep/wakeup race

Weigh coarse against fine locks with real contention counts, keep interrupt handlers from blocking, and explain how sleep_prepare, sleep and wakeup avoid a lost wakeup.

  • Beginner to advanced
  • 9 min read
  • 40 min lab
What you will need

A Linux machine or WSL2 with the xv6-riscv tree built as in the previous lessons, QEMU (qemu-system-misc), the riscv64 GNU toolchain and a text editor; no physical board is required

Your place in the module
By the end you can 4 objectives
  • Compare one big lock with fine-grained locks in terms of concurrency, overhead and deadlock risk.
  • Instrument xv6's spinlocks with acquire and spin counters and identify the most contended lock under an allocation workload.
  • Explain why interrupt handlers may only take spinlocks briefly and must never sleep, and how they hand work to sleeping processes with wakeup.
  • Trace the lost-wakeup race and show how registering the channel with sleep_prepare before releasing the condition lock closes it.
Video coming soonLock granularity and the sleep/wakeup race
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Deadlock and sleep locks
  • Two harts taking locks A and B in opposite orders each hold one and spin on the other forever; GDB showed CPU 0 in acquire(lock_a) and CPU 2 in acquire(lock_b), each lock held by the other CPU.
  • Deadlock needs a cycle in who waits for whom; a single global order for taking locks makes a cycle impossible, which is why proc.c says wait_lock must be acquired before any p->lock.
  • acquire panics with acquire when the calling hart already holds the lock; xv6 deliberately has no re-entrant locks because they hide broken invariants.
01

How much should one lock cover?

4 min read

The last lesson treated locks in isolation; this lesson places them in a running system. It covers coarse versus fine granularity, the rule that interrupt handlers never block, and the lost-wakeup race that sleep/wakeup's channel plus lock ordering closes.

The choice of what a lock covers is called its . The extreme coarse design is one lock for the whole kernel: take it on every entry, release it on every exit. Deadlock is impossible because there is only one lock, and any code written for one CPU stays correct. The price is that only one CPU at a time can run kernel code, so a machine with many cores runs system calls one after another. Linux started with exactly this, the Big Kernel Lock, when it first supported several CPUs, and spent many releases replacing it with finer locks; the last uses were removed in version 2.6.39 in 2011.

xv6 sits in the middle. Each subsystem has its own lock: kmem.lock for the free list, tickslock for the clock, bcache.lock for the block cache list, itable.lock for the inode table, pid_lock for the next pid, wait_lock for parent links, and one p->lock in every struct proc. Two system calls on different harts can run in parallel as long as they do not need the same lock. But finer locks cost something too: more acquire calls on each path, more locks held at once, and more orders to get right, which is exactly where the AB/BA deadlock of the last lesson comes from.

Measuring instead of guessing

Which lock is worth splitting? The one CPUs actually wait for. The lab adds two counters to every spinlock and a way to print them:

c
// kernel/spinlock.h, added to struct spinlock (lab addition)
  uint nacquire; // times acquired
  uint nspin;    // failed swaps while waiting

// kernel/spinlock.c, acquire() spin loop (lab addition)
  while (__atomic_exchange_n(&lk->locked, 1, __ATOMIC_ACQUIRE) != 0)
    __atomic_fetch_add(&lk->nspin, 1, __ATOMIC_RELAXED); // lab addition
  lk->nacquire++; // lab addition: we hold the lock, so this is safe

nspin counts failed swaps, so it grows only while another hart holds the lock: it measures contention. It is updated with an atomic add because the waiters do not hold the lock. nacquire is updated after the loop, while the lock is held, so a plain increment is safe. initlock also records each lock in a table of up to 256 entries (skipping pipe locks, which are freed with their pipes), and a lockstat(int reset) system call either zeroes the counters or prints totals per lock name.

The workload, user/allocstress.c, zeroes the counters and forks three children that each run 500 rounds of sbrk(32 * PGSIZE) followed by sbrk(-32 * PGSIZE): 16,000 page allocations and 16,000 frees per child. Then it prints. A real run:

bash
$ allocstress
lock kmem: acquire 96060, spins 126039
lock nextpid: acquire 3, spins 0
lock wait_lock: acquire 12, spins 0
lock proc: acquire 8377, spins 23
lock time: acquire 6, spins 0
lock itable: acquire 6, spins 0
lock ftable: acquire 18, spins 0
lock log: acquire 9, spins 0

The free-list lock was taken 96,060 times, roughly once per kalloc and once per kfree, and the three harts spun on it 126,039 times, more failed attempts than successful ones. The 64 proc locks together saw 23 spins. Every allocation in the system funnels through one lock, and when several harts allocate at once they mostly wait for each other. That makes kmem.lock the obvious candidate for a finer design, which is the per-CPU allocator of the next session.

Lock granularity choicesOne big lockPer-subsystemlocksPer-CPU dataCPUs in kernelone at a timeone per lockall, mostlyDeadlock risknoneneeds lockorderlow, rarestealingOverheadone acquireseveralacquireslocal lockonlyExampleLinux BKLxv6 kmem.lockper-CPU freelists
Coarse, per-subsystem and per-CPU locking compared
02

Interrupt handlers never block

2 min read

A device interrupt arrives at an arbitrary moment and runs on the hart it hit, on top of whatever that hart was doing: a user process, a process in the middle of a system call, or the scheduler with no process at all. That shapes three rules.

Step by stepRules for code that runs in an interrupt handler
  1. Never sleep: the handler has no process of its own. Calling sleep would put to sleep whichever process was interrupted, or crash if there is none.

  2. Only spinlocks, held briefly: a handler may take a spinlock to touch shared state, but must not take a sleep lock, because waiting for one means sleeping.

  3. Hand off the work: do the minimum, record what happened, and call wakeup so a process does the rest in its own context.

xv6's handlers follow them closely. uartintr in kernel/uart.c acknowledges the interrupt, takes tx_lock just long enough to set tx_busy = 0 and call wakeup(&tx_chan), and passes received characters to consoleintr, which wakes readers sleeping on &cons.r. virtio_disk_intr takes disk.vdisk_lock, marks finished requests and calls wakeup(b) for each buffer; the process that started the read is sleeping in virtio_disk_rw and finishes the work itself. clockintr takes tickslock, increments ticks and calls wakeup(&ticks) for processes in pause.

The second half of the rule lives on the other side. Every spinlock that a handler can take must be held by ordinary code only with interrupts off on that hart, or the handler could spin on top of its own holder; acquire's push_off guarantees that for every spinlock. A short critical section therefore also keeps interrupt latency short: while any spinlock is held, that hart's device interrupts wait.

03

The lost wakeup and how xv6 closes it

5 min read

Sleeping processes wait for a condition: data in a pipe, a tick count, a free sleep lock. The condition is protected by a lock, and the code that makes it true calls wakeup on a . The naive way to wait has a hole:

Step by stepHow a wakeup is lost with a naive sleep
  1. Reader checks: holding pi->lock, the reader sees the pipe empty.

  2. Reader releases: it releases pi->lock so the writer can add data.

  3. Writer runs: on another hart, the writer takes the lock, adds a byte and calls wakeup(&pi->nread). Nobody is asleep yet, so nothing happens.

  4. Reader sleeps: the reader now goes to sleep on &pi->nread and waits for a wakeup that already happened, possibly forever.

The pinned xv6 closes the hole by splitting sleeping into two calls. piperead in kernel/pipe.c waits like this:

c
// kernel/pipe.c, piperead()
  acquire(&pi->lock);
  while (n > 0 && pi->nread == pi->nwrite && pi->writeopen) { //DOC: pipe-empty
    if (killed(pr)) {
      release(&pi->lock);
      return -1;
    }
    sleep_prepare(&pi->nread); //DOC: piperead-sleep
    release(&pi->lock);
    sleep();
    acquire(&pi->lock);
  }

And the three functions in kernel/proc.c are short:

c
// kernel/proc.c
void
sleep_prepare(void *chan)
{
  struct proc *p = myproc();

  acquire(&p->lock);
  if (chan == 0)
    panic("sleep_prepare: zero chan");
  p->chan = chan;
  release(&p->lock);
}

void
sleep(void)
{
  struct proc *p = myproc();

  acquire(&p->lock);
  if (p->chan != 0) {
    p->state = SLEEPING;
    sched();
  }
  release(&p->lock);
}

wakeup(chan) walks the process table; for each process it takes p->lock, and if p->chan == chan it sets p->chan = 0 and, if the process is already SLEEPING, makes it RUNNABLE.

Replay the race. The reader registers p->chan = &pi->nread while it still holds pi->lock, so the writer cannot have changed the pipe in between: the registration is in place before the condition can change. If the writer's wakeup now runs before the reader reaches sleep(), it finds p->chan set, clears it, and leaves the state alone; when the reader calls sleep(), it sees p->chan == 0 and returns at once, then rechecks the pipe and finds the byte. If instead the reader gets into sleep() first, it sets SLEEPING and calls sched while holding p->lock, and the scheduler releases that lock only after the switch, so the writer's wakeup, which needs p->lock, can only see the finished state SLEEPING and make it RUNNABLE. Either order delivers the wakeup.

The lock order is the other half: the condition lock (pi->lock) is taken first and p->lock inside it, both in sleep_prepare and in wakeup, which the writer calls while holding pi->lock. And the while loop matters: a woken process always rechecks the condition, because wakeup wakes every sleeper on the channel and another reader may already have taken the data.

sleep_prepare saves an early wakeupReaderpi->lockWriterpipe empty:sleep_preparereleaseacquire, add bytewakeup: p->chan = 0sleep(): chan 0,returnacquire, read byte1. Reader → pi->lockpipe empty: sleep_prepare2. Reader → pi->lockrelease3. Writer → pi->lockacquire, add byte4. Writer → Readerwakeup: p->chan = 05. Reader → Readersleep(): chan 0, return6. Reader → pi->lockacquire, read byte
A wakeup that arrives before sleep() is not lost
Going deeperPer-CPU data instead of a lock

The allocstress numbers suggest a different question: does the free list need to be shared at all? A page freed by hart 1 is just as good for hart 1's next allocation as any other page. If each hart keeps its own free list with its own lock, the common case touches only that hart's list, and the lock is almost never contended, because only that hart normally takes it. A hart whose list runs empty steals pages from another hart's list, taking that list's lock for the rare transfer. This is the per-CPU allocator of session M3-S06B. It trades a little memory imbalance for nearly no contention, and Linux uses the same idea for its per-CPU page lists and per-CPU counters. Going further, some data needs no lock at all because only one hart ever writes it: per-CPU statistics can be summed by a reader that accepts a slightly stale total.

Going deeperFinding races and hot locks

Races are found with two habits. The first is to state invariants as checks that run all the time. xv6 is full of them: acquire panics if the hart already holds the lock, release if it does not, pop_off if interrupts are on, sched if more than p->lock is held, and sleep_prepare if the channel is zero. Each turns a silent corruption into an immediate, located failure. The lab's negative-count panic("kfree: ref") in the cow lab is the same habit. The second habit is to measure. Counting nacquire and nspin per lock, as above, shows where CPUs wait, and the lock lab of the next session uses similar per-lock statistics for kmem and bcache to show the effect of splitting them. A lock with many acquires and almost no spins is not a problem; a lock whose spins exceed its acquires is where the parallelism is being lost.

The measurements point at one lock, kmem.lock, and the deep blocks at the cure. The next lesson, the per-CPU memory allocator, starts the lock lab: it splits the free list per hart and measures the contention again.

Key takeaways

  • 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.
  • In the pinned xv6, sleep_prepare(chan) records p->chan under p->lock while the condition lock is still held; a wakeup that arrives before sleep() clears p->chan, so sleep() returns at once instead of losing it.
Reflect
  1. Explain to a colleague, in two sentences: compare one big lock with fine-grained locks in terms of concurrency, overhead and deadlock risk.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Find your next step

↑ ↓ to move · Enter to open · Esc to close