Root Cause Analysis
1. Functions, Structs, and Files Involved
- File:
kernel/printk/printk_ringbuffer.c
- Functions:
- Structs & Fields:
struct prb_desc: state_var (atomic_long_t) and text_blk_lpos (struct prb_data_blk_lpos)
struct prb_data_blk_lpos: begin and next (unsigned long)
2. Detailed Technical Mechanism
The Linux printk_ringbuffer implementation uses a lockless memory model where descriptors (struct prb_desc) are indexed in a circular descriptor ring (prb_desc_ring). Descriptors are tracked and validated using an atomic state variable (desc->state_var), which encodes both the descriptor ID (including wrap generation counts) and its state (desc_reserved, desc_committed, desc_finalized, or desc_reusable).
-
Optimistic Read in desc_read():
When a caller such as desc_push_tail() needs to inspect a descriptor (here the descriptor at tail_id), it invokes desc_read():
-
Concurrent Recycling and Allocation in data_alloc():
Concurrently on another CPU, a task executing prb_reserve() is allocating space for a new printk record and recycles the oldest descriptor slot:
-
Data-Race Manifestation:
If desc_read() completes its initial atomic_long_read() (desc_read:A) just before the writer executes desc_reserve:F, desc_read() enters the memcpy() (desc_read:C) at the exact time data_alloc() writes to blk_lpos->begin and blk_lpos->next.
Because memcpy() reads desc->text_blk_lpos without READ_ONCE() or data_race() annotations and data_alloc() performs plain stores without WRITE_ONCE() or data_race() annotations, KCSAN detects and reports a concurrent plain read/write data race on the 16-byte text_blk_lpos structure.
3. Correctness Guarantees Under the Ringbuffer Design
Although flagged by KCSAN as an unannotated data race, this scenario was anticipated by the ringbuffer design:
- The full memory barrier in
atomic_long_try_cmpxchg() (desc_reserve:F) pairs with smp_rmb() (desc_read:D).
- If
desc_read() reads during or after the writer changes desc->text_blk_lpos, the subsequent atomic_long_read() at desc_read:E is guaranteed to observe the new state_var (which contains either a different wrap ID or the desc_reserved state).
- When
desc_read() detects this state change, it returns desc_miss (or desc_reserved). Callers such as desc_push_tail() immediately branch away without accessing or utilizing desc_out->text_blk_lpos, safely discarding any torn or intermediate values copied during the race.