The spinlock from Chapter 2 treats every contender the same: whether you only want to take a quick look or need to make a change, you queue up for exclusive access. Yet one kind of workload is extremely common in practice: read-mostly data, read countless times and updated only occasionally. If reads do not conflict with one another, forcing them through a spinlock turns a multi-lane road into a single lane and wastes the parallelism of a multicore machine. The subject of this chapter, qrwlock (queued read/write lock), exists for exactly this case: it lets many readers enter the critical section at the same time and share the data, and demands exclusive access only when a writer shows up. Like spinlock, it never sleeps and can be used in interrupt context; the only difference is that it refines “mutual exclusion” into “shared for readers, exclusive for writers”. The thread running through this chapter is how the kernel encodes both the reader count and the writer state in a single 32-bit atomic word, and how it uses a single “waiting flag” to solve the problem every reader-writer lock is born with: writer starvation.
Note: this chapter follows x86-64. In modern kernels,
rwlock_tis implemented byqrwlockat the architecture level on all such platforms. The source lives inkernel/locking/qrwlock.c,include/asm-generic/qrwlock.handinclude/asm-generic/qrwlock_types.h.