Locks are the most heavily used mechanism in the kernel, and the easiest to misuse. spinlock, mutex and rwsem all provide mutual exclusion, yet they behave very differently: whether they may sleep, whether they work in interrupt context, who gets the lock under heavy contention, and how writers avoid starvation when reads dominate. Knowing the API is not enough. When a deadlock, a latency spike or a rare data corruption shows up, you have to go back to the implementation to find the cause.

This book uses the Linux 7.1 source as its baseline. It starts from atomic operations and memory barriers, then works through the kernel’s synchronization primitives in order: spinning locks, sleeping locks, and lock-free and special-purpose primitives. Every chapter follows the same structure: the problem the lock solves, its data structures and key code paths, and finally where to use it, common mistakes and how to debug it. The last two chapters cover lockdep and locktorture, showing how the kernel catches deadlocks during development and stress-tests its lock implementations.

Contents

  • 1. Atomics and Memory Barriers: The Foundation of Every Lock
  • 2. spinlock and qspinlock: From Test-and-Set to the MCS Queue
  • 3. rwlock and qrwlock: The Spinning Trade-offs of Readers and Writers
  • 4. osq_lock: The Optimistic Spin Queue
  • 5. mutex: Optimistic Spinning and Handoff
  • 6. rwsem: Count Encoding and Lock Stealing in the Reader-Writer Semaphore
  • 7. ww_mutex: Wound/Wait Deadlock Avoidance
  • 8. seqlock and seqcount: Lock-Free Reads Driven by a Sequence Number
  • 9. semaphore: The Plainest Counting Semaphore
  • 10. RCU and SRCU: Lock-Free Reads Driven by Grace Periods
  • 11. lockdep: How Deadlock Detection Works
  • 12. locktorture: Stress-Testing Lock Implementations

Who it is for

  • Kernel and driver developers who need to pick and use the right lock across process, softirq and interrupt context.
  • Engineers debugging deadlocks, contention-driven latency spikes or rare data corruption.
  • Readers who want a solid grasp of kernel concurrency before reading the scheduler or memory-management code.

Readers are expected to know C and basic operating-system concepts. Architecture details focus on x86-64 and arm64.