The locks of the previous four chapters, spinlock, qrwlock and osq_lock, share one hard constraint: when a CPU fails to get the lock, it can only spin in place and must never sleep. That limits them to very short critical sections. Yet the kernel is full of critical sections that are anything but short: they read and write files, wait for DMA, allocate large chunks of memory, or even take other locks. These operations easily take several milliseconds, and making other CPUs spin idly for that long is pure waste. The mutex (mutual exclusion lock) in this chapter exists for exactly this case. It is the kernel’s most widely used sleeping lock: when it fails to get the lock, it does not burn cycles; it suspends the current task, gives the CPU away to do other work, and is woken up when the lock is released.
But a mutex does not “go to sleep at the first sign of trouble”. Sleeping is expensive (context switches, cache invalidation), so it first borrows the osq_lock from Chapter 4 for a round of optimistic spinning: if the owner is running on another CPU and will probably release the lock soon, spin a little while and wait for it; win the bet and a sleep is saved. The main thread of this chapter is how mutex makes a single owner field serve several purposes, how it trades off spinning against sleeping, and how it uses the handoff mechanism to keep waiters from being starved by an endless stream of “lock stealers”. The source lives mainly in kernel/locking/mutex.c, kernel/locking/mutex.h and include/linux/mutex.h.
Note: the main line assumes x86-64 and a non-
PREEMPT_RTconfiguration. UnderPREEMPT_RT,mutexis implemented on top ofrtmutexinstead, which is outside the scope of this chapter.