Root Cause Analysis
1. Data Structure Layout and Invariant
In include/linux/lockref.h, struct lockref is defined as a union when USE_CMPXCHG_LOCKREF is enabled (true on 64-bit SMP systems where SPINLOCK_SIZE <= 4):
struct lockref {
union {
#if USE_CMPXCHG_LOCKREF
aligned_u64 lock_count;
#endif
struct {
spinlock_t lock;
int count;
};
};
};
On little-endian 64-bit architectures (such as x86_64), the 8-byte lock_count occupies the exact same memory as the 4-byte lock (bytes 0–3) and the 4-byte count (bytes 4–7).
The design invariant of lockref allows lockless optimistic operations (via CMPXCHG_LOOP in lib/lockref.c) to read the full 64-bit lock_count using READ_ONCE, verify whether the spinlock is unlocked (arch_spin_value_unlocked()), compute updated count values, and commit them atomically with try_cmpxchg64_relaxed().
2. Conflicting Memory Accesses
The reported KCSAN bug report highlights a data race on struct lockref between two paths accessing the same dentry:
-
Marked 8-byte read (lockref_get_not_dead in lib/lockref.c:147):
-
Unmarked 4-byte read-modify-write (dget_dlock in include/linux/dcache.h:344):
3. Why KCSAN Flags It vs. Real-World Correctness
- According to LKMM / KCSAN rules: Because
dentry->d_lockref.count++ is an unmarked plain write to memory that overlaps with the 8-byte READ_ONCE(lockref->lock_count), it constitutes an unmarked data race under the C memory model.
- According to the
lockref algorithmic design:
dget_dlock(parent) runs strictly inside a critical section bounded by spin_lock(&parent->d_lock) and spin_unlock(&parent->d_lock).
- If
lockref_get_not_dead() reads lock_count while d_lock is held by __d_alloc_parallel(), arch_spin_value_unlocked(old.lock.rlock.raw_lock) is false. CMPXCHG_LOOP immediately terminates without using old.count and falls back to spin_lock(&lockref->lock). It then blocks until parent->d_lock is unlocked and safely performs the increment under the lock.
- If
lockref_get_not_dead() reads lock_count right before the spinlock is locked or right as it is being unlocked, the 64-bit try_cmpxchg64_relaxed() detects the discrepancy against old.lock_count, fails, reloads the current lock_count, and either retries or falls back to spin_lock.
In practice, the race is benign algorithmically, but KCSAN flags it because the write in dget_dlock() (and similarly in lib/lockref.c lock-held fallback paths) is unmarked.