Root Cause Analysis
The reported KCSAN bug is a data race between an unmarked plain write and an unmarked plain read on the cpu field of struct optimistic_spin_node in kernel/locking/osq_lock.c.
Involved Components & State
Mechanism Leading to the Race
-
Queueing and Waiting:
- When CPU 1 contends on an optimistic spin queue (in this case, via
rwsem_down_write_slowpath() -> rwsem_optimistic_spin() -> osq_lock()), it exchanges lock->tail with its encoded CPU index (encode_cpu(1) = 2).
- CPU 1 observes
old tail pointing to CPU 0 (encode_cpu(0) = 1). CPU 1 sets node->prev = decode_cpu(old) (pointing to CPU 0's static per-CPU osq_node) and links itself to CPU 0's node via osq_link_next(prev, node).
- CPU 1 then enters the wait loop in
smp_cond_load_relaxed():
if (smp_cond_load_relaxed(&node->locked, VAL || need_resched() ||
vcpu_is_preempted(node_cpu(node->prev))))
return true;
- In each iteration where
node->locked is 0 and need_resched() is false, CPU 1 executes vcpu_is_preempted(node_cpu(node->prev)). The inline helper node_cpu(node->prev) performs an unmarked read:
static inline int node_cpu(struct optimistic_spin_node *node)
{
return node->cpu - 1;
}
Here, node->prev->cpu is loaded without atomic markings (e.g., READ_ONCE()).
-
Unlock / Unqueue and Re-entry:
-
Data Race:
- CPU 0 executes the plain write
node->cpu = curr; (kernel/locking/osq_lock.c:145) concurrently with CPU 1 executing the plain read node->cpu - 1 in node_cpu() (kernel/locking/osq_lock.c:34) on CPU 0's osq_node.
- Because neither access uses
READ_ONCE()/WRITE_ONCE() or synchronization barriers, KCSAN detects a data race under the Linux Kernel Memory Model (LKMM). Note that because CPU 0 always writes encode_cpu(0) (1) into its own osq_node.cpu, the stored value never varies across calls.