Day63 - Seqlock and RCU Motivation¶
Overview¶
This lab explores the motivation behind seqlock and RCU by implementing a minimal userspace seqlock.
The experiments demonstrate:
- Sequence counter design
- Reader snapshot validation
- Lockless reader synchronization
- Writer serialization
- Memory ordering considerations
- Why RCU is needed beyond seqlock
Lab1 - Version Counter Demonstration¶
Objective¶
Understand the basic sequence counter mechanism.
Shared Data¶
Writer Flow¶
Reader Flow¶
Observation¶
Readers never accepted inconsistent data when sequence validation was enabled.
Lab2 - Broken Reader Demonstration¶
Objective¶
Observe what happens when snapshot validation is removed.
Reader Logic¶
Snapshot validation was intentionally removed.
Observation¶
The reader frequently observed partially updated data.
Example:
This demonstrated that the sequence counter alone does not protect data consistency.
Reader-side validation is required.
Lab3 - Mini Seqlock Implementation¶
Objective¶
Implement a minimal seqlock abstraction.
Implemented APIs¶
int mini_seqlock_init(...);
unsigned int mini_seqlock_read_begin(...);
bool mini_seqlock_read_retry(...);
int mini_seqlock_write_begin(...);
int mini_seqlock_write_end(...);
Reader Algorithm¶
Writer Algorithm¶
Observation¶
Readers successfully obtained consistent snapshots without acquiring locks.
Lab4 - Multi-Writer Contention and Memory Ordering¶
Objective¶
Observe writer serialization and reader retry behavior under contention.
Test Configuration¶
Writer Statistics¶
Added:
Definitions:
writer_busy_count
Writer observed an active writer
(sequence was odd)
writer_cas_fail_count
CAS acquisition failed
due to concurrent writer competition
Example Result¶
Analysis¶
Sequence value:
2 writers
500 updates each
1 final stop update each
Total transactions:
(500 + 1) * 2 = 1002
Sequence increments twice per transaction
1002 * 2 = 2004
Writer contention was successfully observed.
Reader retries increased significantly when writer critical sections were extended using:
inside the write section.
Memory Ordering Discussion¶
Initial Version¶
The implementation used implicit sequential consistency.
Explicit Version¶
The implementation was later migrated to:
Key Insight¶
Writer begin acquires ownership.
Writer end publishes updated data.
Reader acquire operations observe published state.
Seqlock Limitations¶
Seqlock guarantees:
Seqlock does not guarantee:
Example:
Retry cannot recover from use-after-free situations.
This limitation motivates the introduction of RCU.
Conclusion¶
This lab demonstrated:
- Version counter synchronization
- Lockless readers
- Reader retry validation
- Writer serialization
- Multi-writer contention
- Memory ordering requirements
- RCU motivation
The mini seqlock implementation successfully reproduced the fundamental behavior of Linux kernel sequence locks.