Module 5 · Lesson 22 of 129

Read-mostly synchronization

Choose a kernel synchronization mechanism for shared reads, coherent snapshots, replaceable objects, and per-CPU counters.

  • Beginner to advanced
  • 9 min read
  • 12 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, a text editor, and familiarity with kernel spinlocks and mutexes

Your place in the module
By the end you can 4 objectives
  • Choose between rwlock_t and rw_semaphore based on whether access may sleep.
  • Trace a seqlock reader through a concurrent update and identify when it must retry.
  • Explain when an RCU reader may use an object and when an updater may reclaim it.
  • Distinguish current-CPU operations, CPU pinning, and explicit CPU selection.
Video coming soonRead-mostly synchronization
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Sleeping locks and completions
  • Mutex acquisition can sleep, and only the task that acquired a mutex may unlock it.
  • A semaphore counts available permits. A successful down consumes a permit, and up returns one.
  • A completion records a signal even if the signal arrives before the waiter.
01

Reader-writer locks allow readers to overlap

3 min read

Mutexes and completions serialized both readers and writers. This lesson answers how the kernel lets many readers proceed at once with reader-writer locks, RCU and per-CPU data, and where each one is safe.

Linux timekeeping has a concrete version of the read-heavy problem. Code reading time needs a consistent set of values even while the kernel updates them. A reader that takes one value before an update and another afterward can compute a result from a combination that never existed. The kernel's sequence-lock documentation uses timekeeping as an example of why such a read needs a consistency check. A reader-writer lock can solve the same kind of consistency problem by keeping writers out while readers copy the values. Sequence counters and sequential locks

Suppose a configuration has a lower limit and an upper limit. Every published configuration must have a lower limit at or below the upper limit. Two readers can each copy both values while holding the same lock in read mode. A writer must wait until both readers release it before changing either value. While the writer holds the lock, another reader cannot acquire read access. Each reader gets a pair from a single configuration, even if another update occurs after it releases the lock and starts using its local copy.

Reader-writer lock typesrwlock_trw_semaphoreRead acquireread_lock()down_read()Write acquirewrite_lock()down_write()Reader overlapAllowedAllowedContendedacquisitionSpins onnon-RTMay sleep
Both lock types allow readers to overlap. The execution context determines which API is suitable.

Linux provides two common reader-writer lock types with this access rule:

  • With rwlock_t, call read_lock() before accessing the data and read_unlock() afterward. Writers pair write_lock() with write_unlock(). On a non-PREEMPT_RT kernel, this is a spinning lock. Keep the protected work short and use operations that can run without sleeping. When the same lock can be acquired by a local hard interrupt on a non-RT kernel, use the appropriate IRQ-safe locking discipline so the interrupt cannot interrupt a holder and wait for it. The plain lock calls alone leave local hard interrupts enabled if they were enabled on entry.
  • With struct rw_semaphore, call down_read() and up_read() for shared access, or down_write() and up_write() for exclusive access. The acquisition calls can sleep while waiting. Use them in sleepable context. A task can also sleep while it holds the semaphore, so the time it spends blocked can affect callers waiting for exclusive access.
Check the kernel configuration

PREEMPT_RT changes the implementation and context rules of rwlock_t. The spinning behavior described here applies to non-PREEMPT_RT kernels. Use the kernel's lock type documentation when checking code that must also run on PREEMPT_RT. Lock types and their rules

Pick the mode based on what the critical section does. Changing a field covered by the lock requires write mode even when the surrounding operation is called a read. A caller that discovers it needs to update can release read mode, acquire write mode and check the condition again. Another writer may change the state during the interval between those acquisitions.

Shared access lets readers do useful work concurrently, but acquiring and releasing the lock still involves shared lock state. If the protected work is only a short copy, coordinating access to the lock can account for much of its cost on a multicore system. A writer also depends on readers releasing their holds. Read frequency alone therefore tells you little about whether the change will improve performance. The length of the protected region, how often readers actually overlap, and how long an update can wait all matter.

02

Validate snapshots or publish replacements

5 min read

A lets a reader copy data without acquiring shared ownership of a lock. Consider the two limits again. A reader copies them into locals and checks whether an update overlapped the copy. If it did, the reader discards both values and repeats the whole read. The locals become usable only after validation succeeds.

For seqlock_t, writers enclose changes in write_seqlock() and write_sequnlock(). The sequence is odd while a write is in progress and even when it finishes. A reader calls read_seqbegin() to get a starting sequence from a stable point. It then copies both fields and passes the starting sequence to read_seqretry(). A true result means repeat from read_seqbegin(). This also catches a write that starts and finishes during the copy. Looking only for an even sequence at the end would miss that update.

Keep the retryable work safe to repeat. Copying scalar fields to local variables is suitable. Acting on the values, such as applying the limits to a request, belongs after validation. The validation check cannot reverse an action already taken. It also cannot make an earlier pointer dereference safe if a writer can free the object during the copy. Such a pointer needs its own lifetime protection.

Readers can lose time to retries when updates arrive frequently. Writer context matters too. A reader must be unable to interrupt an in-progress writer and then prevent that writer from resuming while it waits for an even sequence. Keep writes short and use the seqlock variant appropriate to the contexts that can read it. For example, if a hard interrupt can run the reader, the writer must exclude local hard interrupts during the write.

Going deeperRCU in a driver

suits a driver whose readers frequently look up a configuration that changes occasionally. Each configuration can be immutable once published. A writer prepares a fully initialized replacement, publishes it, then arranges for the previous object to be freed later. Readers can use either version if their lookup overlaps publication. They can safely finish with the version they obtained.

On the reader side, call rcu_read_lock(), load the shared pointer with rcu_dereference(), and check for NULL if the pointer can be absent. Read the fields you need before calling rcu_read_unlock(). If you need the limits afterward, copy the scalar values while protected. Keeping the address beyond rcu_read_unlock() requires separate lifetime protection, such as a reference acquired while still protected. In the ordinary RCU read-side section used here, write the read path so it does not voluntarily block. Preemption by the scheduler is a different event from the reader calling an operation that sleeps.

On the writer side, serialize competing replacements, for example with a mutex when all writers run in sleepable context. Publish the initialized object with rcu_assign_pointer(). This pairs with rcu_dereference() so a reader that obtains the new pointer can safely see the initialization. RCU read-side protection permits concurrent writers and readers, and writer serialization must still come from the update design. The immutable-object pattern gives readers a consistent version because writers replace the object as a unit.

RCU configuration replacementReaderUpdaterRCUObtain old pointerPublish new pointerQueue free callbackFinish using oldGrace period endsCallback frees old1. Reader → ReaderObtain old pointer2. Updater → UpdaterPublish new pointer3. Updater → RCUQueue free callback4. Reader → ReaderFinish using old5. RCU → RCUGrace period ends6. RCU → RCUCallback frees old
A reader can finish with the old configuration after a writer publishes its replacement.

After removing the old object from the shared pointer, the updater can pass its embedded struct rcu_head to call_rcu() along with a callback that frees the enclosing object. call_rcu() queues the callback and returns. A determines when reclamation becomes safe. The callback runs after a suitable grace period and may run later than its end. Readers that already obtained the old pointer can finish, and a continuous stream of new readers need not stop for the callback to become eligible.

The callback must be safe to execute without sleeping. An updater in sleepable context can instead call synchronize_rcu() after unpublishing the object, then reclaim it when the call returns. That wait protects against pre-existing readers. Callback completion is a separate concern. For example, before unloading a module that supplies callback functions to call_rcu(), stop new callback submissions and use rcu_barrier() to wait for callbacks already queued through that API to finish. Otherwise, a callback could still need to run code from the unloaded module.

If a reader must block while retaining access to an object, consider SRCU, or sleepable RCU. Its read-side calls operate on a struct srcu_struct. Save the index returned by srcu_read_lock() and pass it to srcu_read_unlock() with the same SRCU instance. The updater uses the matching synchronize_srcu() or call_srcu() on that instance. A sleeping reader can extend the wait for reclamation, so the time that the object stays reachable by that reader matters even if updates themselves are infrequent.

03

Give each CPU its own data

3 min read

Consider a counter that records how often a path runs. Updating a global counter on every event makes all CPUs modify the same memory location. If the total is needed only occasionally, give each CPU a counter and add the values when someone asks for the total. The frequent operation modifies the current CPU's copy. The infrequent operation does the work of reading all the copies. This design fits counts because each event contributes independently to the sum.

Per-CPU counter accessSlot ownerCPU ACPU BUpdateIncrementAIncrementBReportingSample ASample BThe reporting task adds the samples.
Each update changes one CPU's counter. A reporting task reads the slots separately.

DEFINE_PER_CPU(unsigned long, samples) defines a per-CPU variable named samples. this_cpu_inc(samples) increments the instance for the CPU executing that operation. A single this_cpu operation handles CPU selection for that access, so the caller does not need to pin itself just to perform the increment. For a count of events, it is usually fine for an event to be charged to whichever CPU ran the increment. Two successive operations can target different instances if the task migrates between them.

Sometimes several accesses must use the same instance. get_cpu() disables preemption and returns the current CPU number. Use per_cpu_ptr(&samples, cpu) to obtain the address for that CPU, perform the short sequence of accesses, then call put_cpu() to re-enable preemption at that nesting level. Keep the sequence free of sleeping operations. After put_cpu(), the address still names the selected CPU's slot, but the task may now run elsewhere. CPU pinning also leaves local interrupts possible. If an interrupt can update the same slot, an ordinary load followed by a store can overwrite the interrupt's update. Use synchronization that also covers those accesses.

A reporting task can call per_cpu_ptr() with an explicitly selected CPU number to read a remote slot. The macro computes the address. The design still has to make each read safe while the owner updates it. For a simple naturally aligned unsigned long counter, a READ_ONCE() of the slot can sample that slot while its owner increments it. Avoid writing remote slots that are being updated with this_cpu operations. Those operations rely on local access and need not provide atomicity against writes by another CPU.

If the reader samples one CPU just before its next increment and a different CPU just after an increment, the reported values come from different times. That can be fine for activity statistics. If a decision needs every value from a coherent global snapshot, it needs additional coordination. Combining per-CPU values also costs more as the number of slots to read grows. The performance trade-off is worthwhile when updates are frequent and independent and the aggregate is read much less often.

When reviewing a read-heavy path, specify what its reader must observe. Shared locking provides a stable interval for accessing the protected state. A seqlock provides a validated copy with possible retries. RCU supports a version whose lifetime is protected during lookup and use. Per-CPU data reduces shared writes when operations can be assigned independently to CPUs. The next lesson, “Lock ordering and deadlocks,” asks what happens when a single operation needs several locks, even if each lock is appropriate for the data it protects.

Key takeaways

  • Reader-writer locks allow concurrent readers and give writers exclusive access.
  • Seqlock readers validate a snapshot before using it and retry if a writer intervenes.
  • RCU allows readers to use an old version while an updater publishes a replacement and defers reclamation.
  • Per-CPU counters avoid shared updates, while concurrent aggregation can observe values from different times.
Reflect
  1. Explain to a colleague, in two sentences: choose between rwlock_t and rw_semaphore based on whether access may sleep.
  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