Root Cause Analysis
Involved Functions, Structs, Fields, and Files
- Source Files:
fs/pipe.c, include/linux/pipe_fs_i.h
- Data Structure & Field:
struct pipe_inode_info::writers (unsigned int, located at byte offset 0x60, 4 bytes).
- Functions Involved:
Technical Mechanism and Race Condition
In anon_pipe_read(), when a reader process finds the pipe empty and has not read any bytes yet, it drops pipe->mutex before sleeping on pipe->rd_wait:
// fs/pipe.c:411
mutex_unlock(&pipe->mutex);
if (wait_event_interruptible_exclusive(pipe->rd_wait, pipe_readable(pipe)) < 0)
return -ERESTARTSYS;
Inside wait_event_interruptible_exclusive(), the wait condition pipe_readable(pipe) is checked while not holding pipe->mutex:
// fs/pipe.c:262
/* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
static inline bool pipe_readable(const struct pipe_inode_info *pipe)
{
union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
unsigned int writers = READ_ONCE(pipe->writers);
return !pipe_empty(idx.head, idx.tail) || !writers;
}
Because pipe->mutex is not held, pipe_readable() reads pipe->writers using READ_ONCE(pipe->writers) to avoid compiler re-reading and hoisting.
Concurrently, a writer process closes its file descriptor during group exit (do_group_exit() -> exit_files() -> ... -> fput() -> pipe_release()):
// fs/pipe.c:765
static int pipe_release(struct inode *inode, struct file *file)
{
struct pipe_inode_info *pipe = file->private_data;
mutex_lock(&pipe->mutex);
if (file->f_mode & FMODE_READ)
pipe->readers--;
if (file->f_mode & FMODE_WRITE)
pipe->writers--; // Line 773: plain, unmarked write
...
Although the write in pipe_release() is performed inside the pipe->mutex critical section, the reader in pipe_readable() accesses pipe->writers concurrently outside pipe->mutex.
Under the Linux Kernel Memory Model (LKMM), any memory location accessed concurrently where at least one thread writes must have all concurrent accesses annotated (e.g., using READ_ONCE() / WRITE_ONCE()) or synchronized by locks. Because pipe->writers-- is a plain, unmarked decrement operation rather than WRITE_ONCE(pipe->writers, pipe->writers - 1):
- Task 6895 executes a marked read (
READ_ONCE(pipe->writers)) without holding pipe->mutex.
- Task 6924 executes a plain write (
pipe->writers--) under pipe->mutex.
- KCSAN detects the concurrent unmarked write against the marked read and flags a data race.