Root Cause Analysis
1. Components and Functions Involved
- Source file:
kernel/fork.c
- Function:
copy_process() (line 2198)
- Data structure:
struct task_struct (specifically the unsigned int flags field at offset 0x2c / 352 bits)
- Flag macro:
PF_NPROC_EXCEEDED (0x00001000 defined in include/linux/sched.h)
2. Technical Mechanism and Triggering Flow
The PF_NPROC_EXCEEDED flag is used in conjunction with credential modifications and process execution (sys_setuid, sys_setreuid, sys_setresuid via flag_nproc_exceeded() in kernel/sys.c, and checked in do_execveat_common() in fs/exec.c). When user limits are exceeded during set*uid(), PF_NPROC_EXCEEDED is flagged on current to defer the -EAGAIN failure until the subsequent execve() call, avoiding breaking applications that fail to check the return code of setuid().
During process creation via clone() or fork(), kernel_clone() calls copy_process(). At kernel/fork.c:2198:
retval = -EAGAIN;
if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
if (p->real_cred->user != INIT_USER &&
!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
goto bad_fork_cleanup_count;
}
current->flags &= ~PF_NPROC_EXCEEDED;
While modifying p->flags (lines 2170, 2210β2211) modifies the newly allocated child task_struct before it is visible or runnable anywhere, line 2198 operates on current->flagsβthe live calling parent task.
The line performs an unconditional, unmarked compound read-modify-write (&= ~PF_NPROC_EXCEEDED) on current->flags on every fork/clone invocation, even though PF_NPROC_EXCEEDED is almost always already clear.
3. Invariant Violation and KCSAN Detection
In the Linux kernel's task concurrency model (documented in include/linux/sched.h above clear_stopped_child_used_math()):
- Only the
current task writes to its own tsk->flags (flags requiring cross-thread atomic modifications are stored in task_struct::atomic_flags with PFA_* accessors).
- However, various kernel subsystems (e.g., preemption hooks in
__schedule(), PSI, workqueue management, tracing, or asynchronous thread checks like tsk_used_math()) read tsk->flags locklessly.
Because current->flags &= ~PF_NPROC_EXCEEDED is an plain C compound read-modify-write without explicit atomic markup (such as READ_ONCE() / WRITE_ONCE()) and without checking whether current->flags & PF_NPROC_EXCEEDED is actually set before writing, KCSAN's watchpoint on the read-modify-write detects concurrent lockless reads, triggering the data race report.