Module 3 · Lesson 37 of 77

Deadlock and sleep locks

Create an AB/BA deadlock in xv6 and inspect it in GDB, explain why xv6 forbids re-entrant locks, and use sleep locks for waits that are too long to spin.

  • Beginner to advanced
  • 7 min read
  • 35 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, gdb-multiarch and a text editor; no physical board is required

Your place in the module
By the end you can 4 objectives
  • Create an AB/BA deadlock between two harts and identify it in GDB from the threads' backtraces and the lock fields.
  • State a lock-ordering rule that prevents deadlock and find the order xv6 documents for wait_lock and p->lock.
  • Explain why xv6 panics on re-acquiring a held spinlock instead of supporting re-entrant locks.
  • Explain how a sleep lock lets a process hold a lock across a sleep and why spinlocks cannot.
Video coming soonDeadlock and sleep locks
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from How the spinlock works
  • acquire spins on __atomic_exchange_n(&lk->locked, 1, __ATOMIC_ACQUIRE), which compiles to amoswap.w.aq: the old value is read and 1 written as one atomic operation.
  • release uses __atomic_store_n(&lk->locked, 0, __ATOMIC_RELEASE), which compiles to fence rw,w followed by sw zero, so every access in the critical section completes before the lock is seen free.
  • push_off clears SIE with one csrrci instruction and counts nesting in mycpu()->noff; pop_off re-enables interrupts only when noff returns to 0 and they were on before the first push_off.
01

Two locks, two orders

4 min read

Spinlocks are strict and short, as the last lesson showed; now they can go wrong. This lesson covers deadlock from AB/BA lock ordering, xv6's no-reentrancy rule, and the sleep lock used for long operations like disk I/O.

A single lock cannot deadlock by itself: whoever holds it will eventually release it. Two locks can. The lab extends the counter system call from the race lesson with two more spinlocks, lock_a and lock_b, and two operations that take both, in opposite orders, with a long pause in between:

c
// kernel/sysproc.c (lab addition, excerpt)
struct spinlock lock_a, lock_b;   // initlock'ed as "A" and "B" by op 0

static void
spin_a_while(void)
{
  for (volatile int i = 0; i < 200000000; i++)
    ;
}

  } else if (op == 7 || op == 8) {     // A then B, or B then A
    struct spinlock *first = (op == 7) ? &lock_a : &lock_b;
    struct spinlock *second = (op == 7) ? &lock_b : &lock_a;
    acquire(first);
    spin_a_while();
    acquire(second);
    release(second);
    release(first);
  }

The user side, race abba, resets, forks a child that calls counter(7, 0) (A then B) and has the parent call counter(8, 0) (B then A). The pause makes the window wide: the parent takes B, and while it spins, the child starts on another hart and takes A. Then each reaches its second acquire and waits for a lock the other holds. The console printed $ race abba and then nothing ever again.

Looking at it with GDB

QEMU's GDB stub can stop all harts and show what each is doing. The lab run started QEMU with -gdb tcp::25000 (the same option make qemu-gdb adds, without starting paused), waited for the hang, and attached gdb-multiarch with target remote :25000. info threads lists one GDB thread per hart:

bash
  Id   Target Id                    Frame
* 1    Thread 1.1 (CPU#0 [running]) acquire (lk=lk@entry=0x80018210 <lock_a>) at kernel/spinlock.c:37
  2    Thread 1.2 (CPU#1 [halted ]) s_sstatus (x=2) at kernel/riscv.h:67
  3    Thread 1.3 (CPU#2 [running]) acquire (lk=lk@entry=0x80018228 <lock_b>) at kernel/spinlock.c:37

Line 37 of kernel/spinlock.c is the while (__atomic_exchange_n(...)) loop. CPU 0 is spinning for lock_a, CPU 2 for lock_b, and CPU 1 is idle in the scheduler, halted until an interrupt. thread apply all bt showed both spinning harts called from sys_counter at the same line, through syscall and usertrap. Printing the locks shows who holds them:

bash
$1 = {locked = 1, name = 0x800073b8 "A", cpu = 0x800124f8 <cpus+256>}
$2 = {locked = 1, name = 0x800073c0 "B", cpu = 0x800123f8 <cpus>}

struct cpu is 128 bytes, so cpus+256 is cpus[2]: A is held by CPU 2, which is waiting for B, and B is held by cpus[0], CPU 0, which is waiting for A. That closed loop is the . Both spinning harts have interrupts off, from push_off, so not even the timer can take them away.

AB/BA deadlock between two hartsCPU 2 (A thenB)Lock ALock BCPU 0 (B thenA)acquire(B):takenacquire(A):takenacquire(B): spinsacquire(A): spins1. CPU 0 (B then A) → Lock Bacquire(B): taken2. CPU 2 (A then B) → Lock Aacquire(A): taken3. CPU 2 (A then B) → Lock Bacquire(B): spins4. CPU 0 (B then A) → Lock Aacquire(A): spins
The wait-for cycle GDB revealed between CPU 0 and CPU 2

The cure is an order

The classic analysis, by Coffman, Elphick and Shoshani in their 1971 survey "System Deadlocks", names four conditions that must all hold for a deadlock. Each maps directly onto what GDB showed. Mutual exclusion: a spinlock has at most one holder. Hold and wait: each hart kept its first lock while spinning for the second. No preemption: nothing can take a spinlock away from its holder, and with interrupts off not even the timer can stop the hart. Circular wait: CPU 0 waited for CPU 2, which waited for CPU 0. Removing any one of the four prevents the deadlock, but the first three are what make a spinlock useful, so in practice kernels attack the fourth.

A cycle needs one CPU to take A before B while another takes B before A. If every piece of code that ever holds two locks takes them in one agreed order, no cycle can form: whoever holds the "later" lock never waits for an "earlier" one. That is a , and it is the main deadlock defence in xv6 and in Linux.

xv6 writes its orders down in comments. Above the declaration of wait_lock in kernel/proc.c the comment says it "must be acquired before any p->lock", and kwait does exactly that: it acquires wait_lock, then each child's p->lock. kexit follows the same order. A new function that took a p->lock and then wait_lock would compile, pass most tests, and deadlock one day against kwait on another hart. The ps lab lesson listed that reversed order as one of the classic mistakes for exactly this reason.

02

No re-entrant locks

2 min read

Some lock libraries offer re-entrant (recursive) locks: the holder may acquire the same lock again, and it is released only after an equal number of releases. xv6 does not. Without special handling, a second acquire by the holder would spin forever, waiting for itself; with interrupts off, that hart would be lost. So acquire checks holding(lk) before spinning. The lab's race twice calls an operation that does acquire(&count_lock); acquire(&count_lock);, and the real result was:

bash
$ race twice
panic: acquire

Why not just allow it? Because a lock protects an invariant, and code between acquire and release is allowed to break the invariant temporarily. If function F holds the lock, has half-updated the data, and then calls G, which acquires the same lock, G expects the invariant to hold and reads half-updated data. With a re-entrant lock this runs silently and corrupts state; with xv6's rule it panics at the first test. The fix is a code structure question: split G into a locked wrapper and an unlocked worker that requires the caller to hold the lock, which is the pattern xv6 uses with holding() assertions, for example sched checking holding(&p->lock).

03

Sleep locks for long waits

3 min read

Spinlocks have two limits. Waiting burns a CPU, which is fine for the few instructions of a critical section but wasteful for the milliseconds a disk read takes. And the holder may not sleep. A process sleeps by calling sched, and sched in kernel/proc.c refuses to switch away if this hart holds any spinlock other than p->lock:

c
// kernel/proc.c, start of sched()
  if (!holding(&p->lock))
    panic("sched p->lock");
  if (mycpu()->noff != 1)
    panic("sched locks");

noff counts the push_off calls of the held spinlocks, so it is 1 only when p->lock is the sole lock held. The lab's race sleeplocked takes count_lock and then sleeps, and the real result was panic: sched locks. The rule protects against a nasty deadlock: a process holding a spinlock goes to sleep with interrupts off, and the next process scheduled on that hart spins on the same lock with interrupts off, so the sleeper can never be woken to release it.

xv6's answer is the in kernel/sleeplock.h and kernel/sleeplock.c:

c
// kernel/sleeplock.c
void
acquiresleep(struct sleeplock *lk)
{
  acquire(&lk->lk);
  while (lk->locked) {
    sleep_prepare(lk);
    release(&lk->lk);
    sleep();
    acquire(&lk->lk);
  }
  lk->locked = 1;
  lk->pid = myproc()->pid;
  release(&lk->lk);
}

void
releasesleep(struct sleeplock *lk)
{
  acquire(&lk->lk);
  lk->locked = 0;
  lk->pid = 0;
  wakeup(lk);
  release(&lk->lk);
}

The inner spinlock lk->lk is held only for a few instructions at a time, to test and set the locked flag. If the flag is set, the process registers itself as waiting on the channel lk with sleep_prepare, releases the spinlock, and sleeps; releasesleep clears the flag and calls wakeup(lk), and each woken waiter loops back to test the flag again. When acquiresleep returns, the caller holds the sleep lock but no spinlock, so it may sleep, take interrupts and be rescheduled. The pid field records the holder, and holdingsleep compares it with the caller's pid, the sleep-lock version of holding. The exact split between sleep_prepare and sleep is the subject of the next lesson.

Sleep locks guard the slow objects of the file system. Every buffer in the block cache has one: kernel/bio.c initialises them with initsleeplock(&b->lock, "buffer"), bget returns a buffer with acquiresleep(&b->lock) held, and brelse releases it. The disk driver then sleeps inside virtio_disk_rw until the interrupt reports the read is done, while the process still holds the buffer's sleep lock, so no other process can use a half-read buffer. Inodes work the same way: ilock in kernel/fs.c calls acquiresleep(&ip->lock).

Spinlock versus sleep lock in xv6SpinlockSleep lockWaitersspin onamoswapsleep on thelockHolder may sleepno: panicsched locksyesInterrupts whileheldoffonIn interrupthandlersyesnoUsed forkmem,tickslock,p->lockbuffers,inodes
Spinlocks and sleep locks compared

Sleep locks are not a replacement for spinlocks. They cannot be used in interrupt handlers, which have no process to put to sleep, and taking one costs a spinlock acquisition plus possibly two context switches, far more than a short critical section. xv6 uses spinlocks for almost everything and sleep locks only where the holder must wait for a device.

Locks now have a rule for ordering, a rule against re-entry, and a sleeping variant for long waits. The next lesson, lock granularity and the sleep/wakeup race, places them in the running kernel: how much each lock should cover, why interrupt handlers must never block, and how sleep_prepare and wakeup avoid losing a wakeup that arrives between checking a condition and going to sleep.

Key takeaways

  • 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.
  • A sleep lock is a flag protected by a spinlock; acquiresleep sleeps while the flag is set, so the holder can sleep too, which is why buffers and inodes use sleep locks during disk I/O.
Reflect
  1. Explain to a colleague, in two sentences: create an AB/BA deadlock between two harts and identify it in GDB from the threads' backtraces and the lock fields.
  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