In the previous seven chapters, whether a lock spins or sleeps, is exclusive or reader-writer, single or multiple, readers and writers always coordinate through some form of mutual exclusion: while a reader holds the lock the writer must wait, and vice versa. But there is a large class of data that is rarely written yet read in enormous volume, and whose readers only want to copy out a consistent snapshot. The system clock is the classic example: gettimeofday may be called a million times per second, while xtime is updated only a few hundred times per second. If every reader had to contend for a reader-writer lock, the readers alone, repeatedly fighting over the same cache line to update the lock count, would be enough to wreck multicore scalability, even though reads never actually conflict with each other.

The seqcount/seqlock of this chapter takes the opposite approach to the first seven chapters: a writer is never blocked by readers, and readers never modify any shared state at all. The entire mechanism boils down to a sequence number: the writer increments it each time it enters and leaves the critical section, and the reader looks at it once before reading and once after. If the two values are equal and even, the read was not interrupted by a writer and the snapshot is valid; otherwise the reader starts over. All a reader pays is two loads and a compare: no atomic writes, no cache line contention, almost zero read-side overhead. The price is that readers may spin through retries, so it only fits one particular scenario: “very few writes, very many reads, and the data read consists of values that can be re-read as a whole.”

seqcount also pushes the formula from Chapter 1, “lock = atomic operations + barriers + waiting strategy”, to an extreme: it contains almost no atomic operations (the sequence increment is made safe by serializing writers), and everything hinges on memory barriers. The write-side smp_wmb pairs precisely with the read-side smp_rmb, guaranteeing that a reader either sees the complete old state from before the writer started, or notices that the sequence changed and retries; it never reads half-written, “torn” data. The source for this chapter lives in include/linux/seqlock.h and include/linux/seqlock_types.h.

Note: The main line is x86-64 with a non-PREEMPT_RT configuration. Under PREEMPT_RT, the write side of a seqcount_LOCKNAME_t with an associated lock no longer disables preemption; instead, a reader that detects a writer in progress “acquires and then releases” the associated lock to avoid livelock. The mechanism is mentioned in Section 8.6 and not developed further.