| 0/0 |
2026/07/25 22:53 |
flow |
assessment-kcsan |
23m
Results: map[Benign:true Explanation:### Race Summary
`__mutex_lock_common` vs `__mutex_remove_waiter` on `lock->first_waiter`.
---
### Synchronization Context
* **Thread A (Task 10859):** Executing the slowpath of `__mutex_lock_common`.
After waking up from `schedule_preempt_disabled()`, it reads
`lock->first_waiter` locklessly (outside of `lock->wait_lock`) to check if it
has become the first waiter on the list:
```c
first = lock->first_waiter == &waiter;
```
* **Thread B (Task 10862):** Removing a waiter in `__mutex_remove_waiter` under
the protection of `lock->wait_lock`:
```c
lock->first_waiter = list_next_entry(waiter, list);
```
Because Thread A performs the read without holding `lock->wait_lock`, KCSAN
flags this concurrent access as a data race.
---
### Final Classification: **BENIGN**
#### **Reasoning:**
The logic is structurally tolerant to stale or concurrent reads of
`lock->first_waiter`:
1. **Stale `false` Read:**
If Thread A reads `first` as `false` when it has actually just become `true`
(due to the previous first waiter removing itself concurrently):
* `first` is passed to `__mutex_trylock_or_handoff(lock, first)`.
* Since `first` is `false`, the `MUTEX_FLAG_HANDOFF` flag is not set in this
iteration.
* Thread A will call `schedule_preempt_disabled()` and sleep again.
* In the next iteration, Thread A will read `first` again, see it as `true`,
and correctly set the handoff flag.
* Thus, a stale `false` read only delays the handoff flag setting by one
iteration, which is a safe, sub-optimal but correct slow-path behavior.
2. **Stale `true` Read:**
If Thread A reads `first` as `true` when it is actually `false` (which can
only happen in `ww_mutex` if a waiter with an earlier stamp is inserted
before us after we read `first` as `true` but before we acquire the lock):
* Thread A will set the `MUTEX_FLAG_HANDOFF` flag.
* The next unlock will hand off the lock to the first waiter on the list.
Since the first waiter on the list is the newly inserted waiter with the
earlier stamp, the lock is correctly handed off to that waiter.
* If Thread A also enters optimistic spinning because `first` was `true`, the
optimistic spinning loop (`ww_mutex_spin_on_owner`) will immediately detect
that we are no longer the first waiter (using the
`data_race(lock->first_waiter != waiter)` check) and terminate safely.
3. **No Torn Reads:**
Pointer reads are atomic on all supported architectures, so there is no risk
of a torn read.
4. **No Compiler Optimizations/Livelocks:**
Compiler optimizations such as load merging or hoisting out of the loop are
prevented by the compiler barriers (e.g., `raw_spin_lock`,
`schedule_preempt_disabled`, etc.) present in the loop.
---
### Recommended Annotations
To suppress the KCSAN warning and document the intentional lockless access, the
read should be wrapped in `data_race()`, consistent with how it is done in
`ww_mutex_spin_on_owner()` (line 372):
```diff
- first = lock->first_waiter == &waiter;
+ first = data_race(lock->first_waiter == &waiter);
```]
|
| 1/1 |
2026/07/25 22:53 |
action |
kernel-checkouter |
1m
Results: map[KernelSrc:/app/workdir/cache/src/ea1ec46165a34622b3d5769ce1a7084d96856f42]
|
| 2/1 |
2026/07/25 22:55 |
action |
kernel-builder |
11m
Results: map[KernelObj:/app/workdir/cache/build/25109052d6703f3f74ee67dd78dfe5a133f45305]
|
| 3/1 |
2026/07/25 23:07 |
action |
codesearch-prepare |
8m
Results: map[Index:codesearch-index]
|
| 4/1 |
2026/07/25 23:15 |
agent |
expert |
2m
Model:
Results:
Instruction: # KCSAN Data Race Severity Analysis Protocol
You are an expert Linux kernel concurrency engineer analyzing a Kernel
Concurrency Sanitizer (KCSAN) data race report to determine if it is
**BENIGN** or **HARMFUL**.
## 1. CLASSIFICATIONS
### **BENIGN (Truly Benign)**
The logic is sound and structurally tolerant to compiler optimizations or
stale/torn reads.
- **Diagnostics/Stats:** Reads used only for `/proc`, `/sys`, counters, or
`pr_info`.
- **Heuristic Hints:** A "hint" flag where an old value only causes a
slightly delayed update or a sub-optimal but safe fast-path.
- **Single-Writer Flag Updates:** A single writer updating flags where the
concurrent read is a simple bitwise check (e.g., `flags & MASK`). These are
historically tolerated, assuming neither "Fused Accesses" nor "Ordering
Violations" are relevant in this context.
- **Marked Reloads:** A load feeding into a `cmpxchg()` loop or checked
against a later `READ_ONCE()` reload.
- **Safe Overwrites:** Writing the same value already present.
### **HARMFUL (Logic Bug or Marking Required)**
The race causes incorrect behavior due to a synchronization failure or
because missing annotations allow the compiler to break the algorithm.
**Marking Required for Correctness:**
The algorithm is logically sound but requires annotations (`READ_ONCE()`,
`WRITE_ONCE()`, `smp_load_acquire()`, `smp_store_release()`, etc.) to be safe.
- **Fused Accesses:** The compiler might merge accesses or hoist a load out
of a loop, breaking polling/wait loops (livelocks).
- **Torn Accesses:** A large access (e.g., 64-bit on 32-bit arch) might be
split into multiple non-atomic accesses. Note that `READ_ONCE()` does **not**
guarantee atomicity for 64-bit variables on 32-bit architectures.
- **Ordering Violations:** The race breaks a "happens-before" relationship
(requires primitives with implied or explicit memory barriers).
**Logic Bugs:**
A fundamental synchronization failure. Marking accesses will **not** fix it;
the logic itself must change.
- **Pointers/Lifecycle:** The racing variable is a pointer being dereferenced
or a refcount governing object lifecycle (Use-After-Free risk).
- **Control Flow:** The variable guards a critical section, memory allocation,
or hardware command.
- **Bitfields:** Concurrent writes to different bits in the same word.
Compilers often use non-atomic read-modify-write sequences, meaning a
write to `bit_A` can "clobber" a concurrent write to `bit_B`. However,
do not blindly assume all bitfield accesses are harmful; you must prove
that a concurrent write actually clobbers another in a way that breaks
logic.
- **Complex Structures:** Races on shared lists, trees, or hashmaps.
- **Lossy Updates:** Concurrent plain RMW operations (e.g., `var++`) on
non-diagnostic variables where every increment must be preserved.
- **State Machines:** Races allowing a state machine to bypass transitions
or enter an invalid state.
- **Adjacent Unsynchronized Operations:** Consider races happening at the
same time. For example, if both threads execute `struct->has_elements = true;
list_add(node, &struct->list);`, the race on `has_elements` implies an
adjacent race on `list_head`, which is HARMFUL.
## 2. RESEARCH & ANALYSIS WORKFLOW
1. **Locate the Race:** Find the exact variables and functions in the stack
traces. Do not speculate about hypothetical compiler
behaviors or theoretical dangers (e.g., dismissing something as
"fundamentally unsafe") without tracing the actual data flow to a crash.
2. **Contextualize:** Identify held locks, RCU sections, or interrupt
contexts. Explain why the race is possible (e.g., "Thread A holds `lock`,
but Thread B is a lockless reader").
3. **Data Flow:** Follow the racing variable into its subsequent uses. If
the reader sees a stale or torn value, what branch is taken? Does it lead
to a pointer dereference or `BUG_ON()`? **You must prove harm via this
data flow.**
4. **Failure Sequencing (if HARMFUL):** Construct a two-column execution trace
demonstrating the failure.
*Example format:*
```text
CPU0 CPU1
function_a()
// lockless read
ptr = global_ptr
<PREEMPT>
function_b()
lock(&my_lock)
global_ptr = NULL
unlock(&my_lock)
kfree(ptr)
if (ptr)
*ptr = 1; // -> Use-After-Free!
```
## 3. OUTPUT FORMAT
- **Race Summary:** `[Function A]` vs `[Function B]` on `[Variable/Field]`.
- **Synchronization context:** List held locks and explain the lack of mutual
exclusion.
- **Final Classification:** **BENIGN** or **HARMFUL**.
**If BENIGN:**
- **Reasoning:** Briefly explain why the race is structurally tolerant to stale
or torn reads.
- **Recommended Annotations:** Suggest appropriate annotations (e.g.,
`READ_ONCE()`, `data_race()`).
**If HARMFUL:**
- **Failure Reasoning:** Explain and provide a two-column interleaving showing
exactly how the race leads to a failure such as corruption or kernel crash.
- **Recommended Fix (ONLY if fix is trivial):** Suggest a structural fix (e.g.,
"Hold `mapping->i_pages` lock", "Convert to `atomic_t`") or required memory
ordering annotations (e.g., "Wrap in `READ_ONCE()`", "Use
`smp_load_acquire()`").
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The data race report is:
==================================================================
BUG: KCSAN: data-race in __mutex_lock / __mutex_lock
write to 0xffff888124366070 of 8 bytes by task 10862 on cpu 1:
__mutex_remove_waiter kernel/locking/mutex.c:249 [inline]
__mutex_lock_common kernel/locking/mutex.c:786 [inline]
__mutex_lock+0x9d2/0xf40 kernel/locking/mutex.c:821
__mutex_lock_interruptible_slowpath+0xa/0x10 kernel/locking/mutex.c:1179
mutex_lock_interruptible+0x8c/0xa0 kernel/locking/mutex.c:1112
tty_write_lock drivers/tty/tty_io.c:942 [inline]
iterate_tty_write drivers/tty/tty_io.c:958 [inline]
file_tty_write+0x2b5/0x690 drivers/tty/tty_io.c:1081
tty_write+0x25/0x30 drivers/tty/tty_io.c:1102
new_sync_write fs/read_write.c:595 [inline]
vfs_write+0x57d/0x990 fs/read_write.c:687
ksys_write+0xdc/0x1a0 fs/read_write.c:739
__do_sys_write fs/read_write.c:750 [inline]
__se_sys_write fs/read_write.c:747 [inline]
__x64_sys_write+0x40/0x50 fs/read_write.c:747
x64_sys_call+0x27e1/0x3020 arch/x86/include/generated/asm/syscalls_64.h:2
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x136/0x3c0 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
read to 0xffff888124366070 of 8 bytes by task 10859 on cpu 0:
__mutex_lock_common kernel/locking/mutex.c:728 [inline]
__mutex_lock+0x52d/0xf40 kernel/locking/mutex.c:821
__mutex_lock_interruptible_slowpath+0xa/0x10 kernel/locking/mutex.c:1179
mutex_lock_interruptible+0x8c/0xa0 kernel/locking/mutex.c:1112
tty_write_lock drivers/tty/tty_io.c:942 [inline]
iterate_tty_write drivers/tty/tty_io.c:958 [inline]
file_tty_write+0x2b5/0x690 drivers/tty/tty_io.c:1081
tty_write+0x25/0x30 drivers/tty/tty_io.c:1102
new_sync_write fs/read_write.c:595 [inline]
vfs_write+0x57d/0x990 fs/read_write.c:687
ksys_write+0xdc/0x1a0 fs/read_write.c:739
__do_sys_write fs/read_write.c:750 [inline]
__se_sys_write fs/read_write.c:747 [inline]
__x64_sys_write+0x40/0x50 fs/read_write.c:747
x64_sys_call+0x27e1/0x3020 arch/x86/include/generated/asm/syscalls_64.h:2
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x136/0x3c0 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
value changed: 0xffffc90010913ca8 -> 0xffffc9001097fca8
Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 10859 Comm: syz.0.2761 Tainted: G W syzkaller #0 PREEMPT(lazy)
Tainted: [W]=WARN
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/16/2026
==================================================================
Reply: ### Race Summary
`__mutex_lock_common` vs `__mutex_remove_waiter` on `lock->first_waiter`.
---
### Synchronization Context
* **Thread A (Task 10859):** Executing the slowpath of `__mutex_lock_common`. After waking up from `schedule_preempt_disabled()`, it reads `lock->first_waiter` locklessly (outside of `lock->wait_lock`) to check if it has become the first waiter on the list:
```c
first = lock->first_waiter == &waiter;
```
* **Thread B (Task 10862):** Removing a waiter in `__mutex_remove_waiter` under the protection of `lock->wait_lock`:
```c
lock->first_waiter = list_next_entry(waiter, list);
```
Because Thread A performs the read without holding `lock->wait_lock`, KCSAN flags this concurrent access as a data race.
---
### Final Classification: **BENIGN**
#### **Reasoning:**
The logic is structurally tolerant to stale or concurrent reads of `lock->first_waiter`:
1. **Stale `false` Read:**
If Thread A reads `first` as `false` when it has actually just become `true` (due to the previous first waiter removing itself concurrently):
* `first` is passed to `__mutex_trylock_or_handoff(lock, first)`.
* Since `first` is `false`, the `MUTEX_FLAG_HANDOFF` flag is not set in this iteration.
* Thread A will call `schedule_preempt_disabled()` and sleep again.
* In the next iteration, Thread A will read `first` again, see it as `true`, and correctly set the handoff flag.
* Thus, a stale `false` read only delays the handoff flag setting by one iteration, which is a safe, sub-optimal but correct slow-path behavior.
2. **Stale `true` Read:**
If Thread A reads `first` as `true` when it is actually `false` (which can only happen in `ww_mutex` if a waiter with an earlier stamp is inserted before us after we read `first` as `true` but before we acquire the lock):
* Thread A will set the `MUTEX_FLAG_HANDOFF` flag.
* The next unlock will hand off the lock to the first waiter on the list. Since the first waiter on the list is the newly inserted waiter with the earlier stamp, the lock is correctly handed off to that waiter.
* If Thread A also enters optimistic spinning because `first` was `true`, the optimistic spinning loop (`ww_mutex_spin_on_owner`) will immediately detect that we are no longer the first waiter (using the `data_race(lock->first_waiter != waiter)` check) and terminate safely.
3. **No Torn Reads:**
Pointer reads are atomic on all supported architectures, so there is no risk of a torn read.
4. **No Compiler Optimizations/Livelocks:**
Compiler optimizations such as load merging or hoisting out of the loop are prevented by the compiler barriers (e.g., `raw_spin_lock`, `schedule_preempt_disabled`, etc.) present in the loop.
---
### Recommended Annotations
To suppress the KCSAN warning and document the intentional lockless access, the read should be wrapped in `data_race()`, consistent with how it is done in `ww_mutex_spin_on_owner()` (line 372):
```diff
- first = lock->first_waiter == &waiter;
+ first = data_race(lock->first_waiter == &waiter);
```
|
| 5/2 |
2026/07/25 23:15 |
llm |
expert |
0m
Model:
Tokens:
input: 6368
output: 105
thoughts: 325
Thoughts: **Analyzing the KCSAN Data Race Report**
Okay, so I need to dig into this KCSAN data race report. The user wants me to analyze it, so let's get to work. First things first, I need to pinpoint the source of the problem. I'll start by locating the code. The report gives me the key lines: the write to address `0xffff888124366070` by task 10862 on CPU 1, and the read from the same address by task 10859 on CPU 0. The report points to `kernel/locking/mutex.c` with the following lines referenced: 249, 786, 821 for the write and 728 for the read.
My immediate plan is to delve into `kernel/locking/mutex.c`. I'll want to inspect the relevant code sections around those line numbers β 249, 786, 821, and 728. I can use my usual arsenal of tools for this: `read-file` for a quick glance, or maybe `codesearch-definition-source` or even `codesearch-find-references` to get a better sense of the surrounding context and related functions. I'll begin by focusing on lines 249 and 728 to get a handle on the direct points of contention.
|
| 6/2 |
2026/07/25 23:15 |
tool |
read-file |
0m
Args: map[File:kernel/locking/mutex.c FirstLine:230 LineCount:40]
Results: map[Contents: 230: if (first) {
231: list_add_tail(&waiter->list, &first->list);
232: return;
233: }
234:
235: INIT_LIST_HEAD(&waiter->list);
236: lock->first_waiter = waiter;
237: __mutex_set_flag(lock, MUTEX_FLAG_WAITERS);
238: }
239:
240: static void
241: __mutex_remove_waiter(struct mutex *lock, struct mutex_waiter *waiter)
242: __must_hold(&lock->wait_lock)
243: {
244: if (list_empty(&waiter->list)) {
245: __mutex_clear_flag(lock, MUTEX_FLAGS);
246: lock->first_waiter = NULL;
247: } else {
248: if (lock->first_waiter == waiter)
249: lock->first_waiter = list_next_entry(waiter, list);
250: list_del(&waiter->list);
251: }
252:
253: debug_mutex_remove_waiter(lock, waiter, current);
254: hung_task_clear_blocker();
255: }
256:
257: /*
258: * Give up ownership to a specific task, when @task = NULL, this is equivalent
259: * to a regular unlock. Sets PICKUP on a handoff, clears HANDOFF, preserves
260: * WAITERS. Provides RELEASE semantics like a regular unlock, the
261: * __mutex_trylock() provides a matching ACQUIRE semantics for the handoff.
262: */
263: static void __mutex_handoff(struct mutex *lock, struct task_struct *task)
264: {
265: unsigned long owner = atomic_long_read(&lock->owner);
266:
267: for (;;) {
268: unsigned long new;
269:
]
|
| 7/2 |
2026/07/25 23:15 |
tool |
read-file |
0m
Args: map[File:kernel/locking/mutex.c FirstLine:710 LineCount:40]
Results: map[Contents: 710: * wait_lock. This ensures the lock cancellation is ordered
711: * against mutex_unlock() and wake-ups do not go missing.
712: */
713: if (signal_pending_state(state, current)) {
714: ret = -EINTR;
715: goto err;
716: }
717:
718: if (ww_ctx) {
719: ret = __ww_mutex_check_kill(lock, &waiter, ww_ctx);
720: if (ret)
721: goto err;
722: }
723:
724: raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q);
725:
726: schedule_preempt_disabled();
727:
728: first = lock->first_waiter == &waiter;
729:
730: raw_spin_lock_irqsave(&lock->wait_lock, flags);
731: raw_spin_lock(¤t->blocked_lock);
732: /*
733: * As we likely have been woken up by task
734: * that has cleared our blocked_on state, re-set
735: * it to the lock we are trying to acquire.
736: */
737: __set_task_blocked_on(current, lock);
738: set_current_state(state);
739: /*
740: * Here we order against unlock; we must either see it change
741: * state back to RUNNING and fall through the next schedule(),
742: * or we must see its unlock and acquire.
743: */
744: if (__mutex_trylock_or_handoff(lock, first))
745: break;
746:
747: if (first) {
748: bool opt_acquired;
749:
]
|
| 8/2 |
2026/07/25 23:15 |
tool |
read-file |
0m
Args: map[File:kernel/locking/mutex.c FirstLine:770 LineCount:60]
Results: map[Contents: 770: trace_contention_begin(lock, LCB_F_MUTEX);
771: }
772: }
773: __clear_task_blocked_on(current, lock);
774: __set_current_state(TASK_RUNNING);
775: raw_spin_unlock(¤t->blocked_lock);
776:
777: if (ww_ctx) {
778: /*
779: * Wound-Wait; we stole the lock (!first_waiter), check the
780: * waiters as anyone might want to wound us.
781: */
782: if (!ww_ctx->is_wait_die && lock->first_waiter != &waiter)
783: __ww_mutex_check_waiters(lock, ww_ctx, &wake_q);
784: }
785:
786: __mutex_remove_waiter(lock, &waiter);
787:
788: debug_mutex_free_waiter(&waiter);
789:
790: skip_wait:
791: /* got the lock - cleanup and rejoice! */
792: lock_acquired(&lock->dep_map, ip);
793: trace_contention_end(lock, 0);
794:
795: if (ww_ctx)
796: ww_mutex_lock_acquired(ww, ww_ctx);
797:
798: raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q);
799: preempt_enable();
800: return 0;
801:
802: err:
803: clear_task_blocked_on(current, lock);
804: __set_current_state(TASK_RUNNING);
805: __mutex_remove_waiter(lock, &waiter);
806: err_early_kill:
807: WARN_ON(get_task_blocked_on(current));
808: trace_contention_end(lock, ret);
809: raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q);
810: debug_mutex_free_waiter(&waiter);
811: mutex_release(&lock->dep_map, ip);
812: preempt_enable();
813: return ret;
814: }
815:
816: static int __sched
817: __mutex_lock(struct mutex *lock, unsigned int state, unsigned int subclass,
818: struct lockdep_map *nest_lock, unsigned long ip)
819: __cond_acquires(0, lock)
820: {
821: return __mutex_lock_common(lock, state, subclass, nest_lock, ip, NULL, false);
822: }
823:
824: static int __sched
825: __ww_mutex_lock(struct mutex *lock, unsigned int state, unsigned int subclass,
826: unsigned long ip, struct ww_acquire_ctx *ww_ctx)
827: __cond_acquires(0, lock)
828: {
829: return __mutex_lock_common(lock, state, subclass, NULL, ip, ww_ctx, true);
]
|
| 9/2 |
2026/07/25 23:15 |
llm |
expert |
0m
Model:
Tokens:
input: 9251
output: 43
thoughts: 453
Thoughts: **Analyzing a Race Condition**
Okay, let's break this down. I'm seeing a potential race condition and I need to figure out what's happening. The code snippet I'm looking at, specifically the section around line 249, has caught my attention:
```c
if (list_empty(&waiter->list)) {
__mutex_clear_flag(lock, MUTEX_FLAGS);
lock->first_waiter = NULL;
} else {
if (lock->first_waiter == waiter)
lock->first_waiter = list_next_entry(waiter, list);
list_del(&waiter->list);
}
```
Line 249 is crucial, it's where `lock->first_waiter` is *written* to. Now, I'm also seeing a read of `lock->first_waiter` at line 728:
`first = lock->first_waiter == &waiter;`
Hang on... this read is happening without a lock! That raises a red flag immediately. Let's look at the context around that read. Lines 724-730 confirm my suspicion:
```c
raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q);
schedule_preempt_disabled();
first = lock->first_waiter == &waiter;
raw_spin_lock_irqsave(&lock->wait_lock, flags);
```
Okay, the read `first = lock->first_waiter == &waiter;` *is* executed outside of the protection of `lock->wait_lock`. That's the crux of the problem. Why is this read done locklessly? There has to be a reason, and it's essential to understand the implications of this.
To get to the bottom of this, I need to understand the intent. Is there a comment? A design explanation? I'm going to turn to `git-log` or `git-blame` to trace this back. I need to find the commit that introduced this lockless read, or at least any associated comments. That should explain the rationale behind this approach and whether it was deliberate, a potential optimization, or perhaps a bug that's been missed. Time to dig in and see what the history reveals.
|
| 10/2 |
2026/07/25 23:15 |
tool |
git-log |
0m
Args: map[CodeRegexp:first = lock->first_waiter == &waiter; PathPrefix:kernel/locking/mutex.c]
Results: map[Output:25500ba7e77c locking/mutex: Remove the list_head from struct mutex
]
|
| 11/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 10309
output: 26
thoughts: 19
Thoughts: Okay, here's my interpretation of that request, formatted for a technically proficient user:
**Analyzing Commit 25500ba7e77c**
Alright, so the task at hand is to take a look at the commit with hash `25500ba7e77c`. I need to essentially deconstruct this specific point in the project's history. My focus is going to be on understanding the delta β what changes were introduced by this commit? I'll probably start by using `git show` or a similar command to get a good overview: the diff, the commit message (which should offer some context), the author, the date, and potentially the affected files.
Then, I'll dive a bit deeper, likely running `git diff 25500ba7e77c^ 25500ba7e77c` (or a similar construct, depending on the toolchain) to get a granular view. I'll want to quickly identify any potential performance implications, security vulnerabilities (depending on the project, naturally), or any changes to the architecture/design I should be aware of. I'll be specifically looking for edge cases, non-obvious bugs, and any deviation from established patterns or coding standards.
If the commit is large, I'll probably narrow my focus to the most relevant parts β using `git log -p -n 1 -- <file>` if it touches specific files I'm interested in or perhaps examining the code more thoroughly using my preferred IDE or a code analysis tool. Finally, I'll assess this commit in context with the rest of the project. I'll ask myself, *Does this change align with the overall project goals and roadmap? Does it introduce any regressions? Does it fit well within the current system?* The goal is to develop a deep understanding of what's going on.
|
| 12/2 |
2026/07/25 23:16 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 25500ba7e77ce9d3d9b5a1929d41a2ee2e23f6fe
Author: Matthew Wilcox (Oracle) <willy@infradead.org>
Date: Thu Mar 5 19:55:43 2026 +0000
locking/mutex: Remove the list_head from struct mutex
Instead of embedding a list_head in struct mutex, store a pointer to
the first waiter. The list of waiters remains a doubly linked list so
we can efficiently add to the tail of the list, remove from the front
(or middle) of the list.
Some of the list manipulation becomes more complicated, but it's a
reasonable tradeoff on the slow paths to shrink data structures which
embed a mutex like struct file.
Some of the debug checks have to be deleted because there's no equivalent
to checking them in the new scheme (eg an empty waiter->list now means
that it is the only waiter, not that the waiter is no longer on the list).
Signed-off-by: Matthew Wilcox (Oracle) <willy@infradead.org>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Link: https://patch.msgid.link/20260305195545.3707590-4-willy@infradead.org
diff --git a/include/linux/mutex.h b/include/linux/mutex.h
index 2f648ee204e7..c471b129f703 100644
--- a/include/linux/mutex.h
+++ b/include/linux/mutex.h
@@ -79,7 +79,7 @@ do { \
#define __MUTEX_INITIALIZER(lockname) \
{ .owner = ATOMIC_LONG_INIT(0) \
, .wait_lock = __RAW_SPIN_LOCK_UNLOCKED(lockname.wait_lock) \
- , .wait_list = LIST_HEAD_INIT(lockname.wait_list) \
+ , .first_waiter = NULL \
__DEBUG_MUTEX_INITIALIZER(lockname) \
__DEP_MAP_MUTEX_INITIALIZER(lockname) }
diff --git a/include/linux/mutex_types.h b/include/linux/mutex_types.h
index 80975935ec48..a8f119f81177 100644
--- a/include/linux/mutex_types.h
+++ b/include/linux/mutex_types.h
@@ -44,7 +44,7 @@ context_lock_struct(mutex) {
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
struct optimistic_spin_queue osq; /* Spinner MCS lock */
#endif
- struct list_head wait_list;
+ struct mutex_waiter *first_waiter;
#ifdef CONFIG_DEBUG_MUTEXES
void *magic;
#endif
diff --git a/kernel/locking/mutex-debug.c b/kernel/locking/mutex-debug.c
index 2c6b02d4699b..94930d506bcf 100644
--- a/kernel/locking/mutex-debug.c
+++ b/kernel/locking/mutex-debug.c
@@ -37,9 +37,8 @@ void debug_mutex_lock_common(struct mutex *lock, struct mutex_waiter *waiter)
void debug_mutex_wake_waiter(struct mutex *lock, struct mutex_waiter *waiter)
{
lockdep_assert_held(&lock->wait_lock);
- DEBUG_LOCKS_WARN_ON(list_empty(&lock->wait_list));
+ DEBUG_LOCKS_WARN_ON(!lock->first_waiter);
DEBUG_LOCKS_WARN_ON(waiter->magic != waiter);
- DEBUG_LOCKS_WARN_ON(list_empty(&waiter->list));
}
void debug_mutex_free_waiter(struct mutex_waiter *waiter)
@@ -62,7 +61,6 @@ void debug_mutex_remove_waiter(struct mutex *lock, struct mutex_waiter *waiter,
{
struct mutex *blocked_on = __get_task_blocked_on(task);
- DEBUG_LOCKS_WARN_ON(list_empty(&waiter->list));
DEBUG_LOCKS_WARN_ON(waiter->task != task);
DEBUG_LOCKS_WARN_ON(blocked_on && blocked_on != lock);
@@ -74,7 +72,6 @@ void debug_mutex_unlock(struct mutex *lock)
{
if (likely(debug_locks)) {
DEBUG_LOCKS_WARN_ON(lock->magic != lock);
- DEBUG_LOCKS_WARN_ON(!lock->wait_list.prev && !lock->wait_list.next);
}
}
diff --git a/kernel/locking/mutex.c b/kernel/locking/mutex.c
index c867f6c15530..95f1822122a1 100644
--- a/kernel/locking/mutex.c
+++ b/kernel/locking/mutex.c
@@ -47,7 +47,7 @@ static void __mutex_init_generic(struct mutex *lock)
{
atomic_long_set(&lock->owner, 0);
raw_spin_lock_init(&lock->wait_lock);
- INIT_LIST_HEAD(&lock->wait_list);
+ lock->first_waiter = NULL;
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
osq_lock_init(&lock->osq);
#endif
@@ -194,33 +194,42 @@ static inline void __mutex_clear_flag(struct mutex *lock, unsigned long flag)
atomic_long_andnot(flag, &lock->owner);
}
-static inline bool __mutex_waiter_is_first(struct mutex *lock, struct mutex_waiter *waiter)
-{
- return list_first_entry(&lock->wait_list, struct mutex_waiter, list) == waiter;
-}
-
/*
* Add @waiter to a given location in the lock wait_list and set the
* FLAG_WAITERS flag if it's the first waiter.
*/
static void
__mutex_add_waiter(struct mutex *lock, struct mutex_waiter *waiter,
- struct list_head *list)
+ struct mutex_waiter *first)
{
hung_task_set_blocker(lock, BLOCKER_TYPE_MUTEX);
debug_mutex_add_waiter(lock, waiter, current);
- list_add_tail(&waiter->list, list);
- if (__mutex_waiter_is_first(lock, waiter))
+ if (!first)
+ first = lock->first_waiter;
+
+ if (first) {
+ list_add_tail(&waiter->list, &first->list);
+ } else {
+ INIT_LIST_HEAD(&waiter->list);
+ lock->first_waiter = waiter;
__mutex_set_flag(lock, MUTEX_FLAG_WAITERS);
+ }
}
static void
__mutex_remove_waiter(struct mutex *lock, struct mutex_waiter *waiter)
{
- list_del(&waiter->list);
- if (likely(list_empty(&lock->wait_list)))
+ if (list_empty(&waiter->list)) {
__mutex_clear_flag(lock, MUTEX_FLAGS);
+ lock->first_waiter = NULL;
+ } else {
+ if (lock->first_waiter == waiter) {
+ lock->first_waiter = list_first_entry(&waiter->list,
+ struct mutex_waiter, list);
+ }
+ list_del(&waiter->list);
+ }
debug_mutex_remove_waiter(lock, waiter, current);
hung_task_clear_blocker();
@@ -340,7 +349,7 @@ bool ww_mutex_spin_on_owner(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
* Similarly, stop spinning if we are no longer the
* first waiter.
*/
- if (waiter && !__mutex_waiter_is_first(lock, waiter))
+ if (waiter && lock->first_waiter != waiter)
return false;
return true;
@@ -645,7 +654,7 @@ __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclas
if (!use_ww_ctx) {
/* add waiting tasks to the end of the waitqueue (FIFO): */
- __mutex_add_waiter(lock, &waiter, &lock->wait_list);
+ __mutex_add_waiter(lock, &waiter, NULL);
} else {
/*
* Add in stamp order, waking up waiters that must kill
@@ -691,7 +700,7 @@ __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclas
schedule_preempt_disabled();
- first = __mutex_waiter_is_first(lock, &waiter);
+ first = lock->first_waiter == &waiter;
/*
* As we likely have been woken up by task
@@ -734,8 +743,7 @@ __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclas
* Wound-Wait; we stole the lock (!first_waiter), check the
* waiters as anyone might want to wound us.
*/
- if (!ww_ctx->is_wait_die &&
- !__mutex_waiter_is_first(lock, &waiter))
+ if (!ww_ctx->is_wait_die && lock->first_waiter != &waiter)
__ww_mutex_check_waiters(lock, ww_ctx, &wake_q);
}
@@ -931,6 +939,7 @@ EXPORT_SYMBOL_GPL(ww_mutex_lock_interruptible);
static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip)
{
struct task_struct *next = NULL;
+ struct mutex_waiter *waiter;
DEFINE_WAKE_Q(wake_q);
unsigned long owner;
unsigned long flags;
@@ -962,12 +971,8 @@ static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigne
raw_spin_lock_irqsave(&lock->wait_lock, flags);
debug_mutex_unlock(lock);
- if (!list_empty(&lock->wait_list)) {
- /* get the first entry from the wait-list: */
- struct mutex_waiter *waiter =
- list_first_entry(&lock->wait_list,
- struct mutex_waiter, list);
-
+ waiter = lock->first_waiter;
+ if (waiter) {
next = waiter->task;
debug_mutex_wake_waiter(lock, waiter);
diff --git a/kernel/locking/ww_mutex.h b/kernel/locking/ww_mutex.h
index 31a785afee6c..a0847e91ae04 100644
--- a/kernel/locking/ww_mutex.h
+++ b/kernel/locking/ww_mutex.h
@@ -8,20 +8,14 @@
static inline struct mutex_waiter *
__ww_waiter_first(struct mutex *lock)
{
- struct mutex_waiter *w;
-
- w = list_first_entry(&lock->wait_list, struct mutex_waiter, list);
- if (list_entry_is_head(w, &lock->wait_list, list))
- return NULL;
-
- return w;
+ return lock->first_waiter;
}
static inline struct mutex_waiter *
__ww_waiter_next(struct mutex *lock, struct mutex_waiter *w)
{
w = list_next_entry(w, list);
- if (list_entry_is_head(w, &lock->wait_list, list))
+ if (lock->first_waiter == w)
return NULL;
return w;
@@ -31,7 +25,7 @@ static inline struct mutex_waiter *
__ww_waiter_prev(struct mutex *lock, struct mutex_waiter *w)
{
w = list_prev_entry(w, list);
- if (list_entry_is_head(w, &lock->wait_list, list))
+ if (lock->first_waiter == w)
return NULL;
return w;
@@ -40,22 +34,17 @@ __ww_waiter_prev(struct mutex *lock, struct mutex_waiter *w)
static inline struct mutex_waiter *
__ww_waiter_last(struct mutex *lock)
{
- struct mutex_waiter *w;
-
- w = list_last_entry(&lock->wait_list, struct mutex_waiter, list);
- if (list_entry_is_head(w, &lock->wait_list, list))
- return NULL;
+ struct mutex_waiter *w = lock->first_waiter;
+ if (w)
+ w = list_prev_entry(w, list);
return w;
}
static inline void
__ww_waiter_add(struct mutex *lock, struct mutex_waiter *waiter, struct mutex_waiter *pos)
{
- struct list_head *p = &lock->wait_list;
- if (pos)
- p = &pos->list;
- __mutex_add_waiter(lock, waiter, p);
+ __mutex_add_waiter(lock, waiter, pos);
}
static inline struct task_struct *
]
|
| 13/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 14383
output: 41
thoughts: 916
Thoughts: **Analyzing a Lockless Read Optimization**
Okay, so I'm looking at commit `25500ba7e77c`. It looks like they replaced a call to `__mutex_waiter_is_first(lock, &waiter)` with a direct comparison: `lock->first_waiter == &waiter`. I need to understand why this is a safe optimization, and if it is, I can determine why KCSAN did not catch the change earlier.
My initial thought is to compare the old code:
```c
static inline bool __mutex_waiter_is_first(struct mutex *lock, struct mutex_waiter *waiter)
{
return list_first_entry(&lock->wait_list, struct mutex_waiter, list) == waiter;
}
```
with what was in place before. The original `__mutex_waiter_is_first` used `list_first_entry` on `lock->wait_list`, where `wait_list` is a `struct list_head` embedded in `struct mutex`.
I need to understand the usage context: this call existed at line 694 (now 728) in the code. I recall the line was:
```c
schedule_preempt_disabled();
first = __mutex_waiter_is_first(lock, &waiter);
```
I have to consider: why was `__mutex_waiter_is_first` safe to call locklessly previously? I'll examine `list_first_entry`. The address of `&lock->wait_list` is a constant, and that's good. It reads `lock->wait_list.next`. If `lock->wait_list.next` changes concurrently, that could indicate a data race. However, maybe KCSAN didn't flag it, or perhaps it was a race that was somehow acceptable in this case. Or perhaps the race was harmless since the code just checked to see if the "next" pointer was equivalent to `&waiter->list`.
Now, the new code directly reads `lock->first_waiter`. This means reading a pointer to a `struct mutex_waiter`.
I have to check: where is `lock->first_waiter` modified? It's modified in `__mutex_remove_waiter` and `__mutex_add_waiter`, and those are protected by `lock->wait_lock`.
Crucially, here, the read of `lock->first_waiter` is *without* the `lock->wait_lock`. I need to verify that this is safe.
If this read is stale or torn, what are the implications? Let's check the type of `lock->first_waiter`. It's a `struct mutex_waiter *`. On a modern architecture, pointer reads/writes are atomic as long as the pointer is aligned. It *is* aligned.
The next question: can the compiler optimize this read? Since it's lockless, there's a possibility of optimization, but it's just a single read: `first = lock->first_waiter == &waiter;`.
Where is `first` used?
```c
first = lock->first_waiter == &waiter;
raw_spin_lock_irqsave(&lock->wait_lock, flags);
raw_spin_lock(¤t->blocked_lock);
/*
* As we likely have been woken up by task
* that has cleared our blocked_on state, re-set
* it to the lock we are trying to acquire.
*/
__set_task_blocked_on(current, lock);
set_current_state(state);
/*
* Here we order against unlock; we must either see it change
* state back to RUNNING and fall through the next schedule(),
* or we must see its unlock and acquire.
*/
if (__mutex_trylock_or_handoff(lock, first))
break;
```
Ah! `first` is passed to `__mutex_trylock_or_handoff(lock, first)`. That's the crucial point. I need to examine the definition of `__mutex_trylock_or_handoff` to see how it uses `first`.
|
| 14/2 |
2026/07/25 23:16 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/locking/mutex.c Name:__mutex_trylock_or_handoff]
Results: map[SourceCode: 121: /*
122: * Trylock or set HANDOFF
123: */
124: static inline bool __mutex_trylock_or_handoff(struct mutex *lock, bool handoff)
125: {
126: return !__mutex_trylock_common(lock, handoff);
127: }
SourceFile:kernel/locking/mutex.c]
|
| 15/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 16421
output: 38
thoughts: 13
Thoughts: Here's my thought process, as if I were considering this myself:
**Tracing Down `__mutex_trylock_common`**
Okay, so I need to find `__mutex_trylock_common`. This sounds like a core function, probably low-level, related to the implementation of mutexes. My immediate thought is, "Where would *I* expect to find this?" Given my familiarity with system programming, it's likely nestled within the kernel source or perhaps a highly optimized system library, depending on the specifics of the operating system. If I were dealing with glibc, I'd start looking within its threading implementation. If it's something lower level, I might start searching the kernel's synchronization primitives code. My instinct is that this function likely deals with the "try" aspect of a mutex lock, so perhaps it doesn't block β which is the core difference from a standard lock. The "common" suggests it's a shared implementation point, maybe dealing with architecture-specific nuances or platform-dependent atomic operations. I'll need to examine the calling conventions and potentially any arguments it takes to understand how it interfaces with the higher-level mutex API. It's likely a relatively short function, given the "try" nature, so I don't anticipate a complex implementation. I should also keep in mind that I might be looking at inline assembly, depending on the architecture. Let's start digging!
|
| 16/2 |
2026/07/25 23:16 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/locking/mutex.c Name:__mutex_trylock_common]
Results: map[SourceCode: 82: /*
83: * Returns: __mutex_owner(lock) on failure or NULL on success.
84: */
85: static inline struct task_struct *__mutex_trylock_common(struct mutex *lock, bool handoff)
86: {
87: unsigned long owner, curr = (unsigned long)current;
88:
89: owner = atomic_long_read(&lock->owner);
90: for (;;) { /* must loop, can race against a flag */
91: unsigned long flags = __owner_flags(owner);
92: unsigned long task = owner & ~MUTEX_FLAGS;
93:
94: if (task) {
95: if (flags & MUTEX_FLAG_PICKUP) {
96: if (task != curr)
97: break;
98: flags &= ~MUTEX_FLAG_PICKUP;
99: } else if (handoff) {
100: if (flags & MUTEX_FLAG_HANDOFF)
101: break;
102: flags |= MUTEX_FLAG_HANDOFF;
103: } else {
104: break;
105: }
106: } else {
107: MUTEX_WARN_ON(flags & (MUTEX_FLAG_HANDOFF | MUTEX_FLAG_PICKUP));
108: task = curr;
109: }
110:
111: if (atomic_long_try_cmpxchg_acquire(&lock->owner, &owner, task | flags)) {
112: if (task == curr)
113: return NULL;
114: break;
115: }
116: }
117:
118: return __owner_task(owner);
119: }
SourceFile:kernel/locking/mutex.c]
|
| 17/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 17311
output: 33
thoughts: 1949
Thoughts: **Analyzing the mutex handoff mechanism**
Okay, so `handoff` gets passed to `__mutex_trylock_common`, interesting. We're trying to figure out how `first` relates to the setting of `MUTEX_FLAG_HANDOFF`. Essentially, `first` is determining if we can set the handoff flag. My concern is whether `first` is re-validated under the lock or if there's a potential race here. Let's revisit `__mutex_lock_common`.
I see that `first` is determined *before* we acquire `lock->wait_lock`. So, if `first` is `true` (meaning `lock->first_waiter` points to us) and, between reading `first` and acquiring the lock, another thread modifies `lock->first_waiter`, is `first` accurate anymore? Can we be the first waiter, then somehow cease to be the first waiter without our knowledge? Well, we're the only ones who can remove ourselves from the wait list, for instance during an interrupt or timeout. No other thread can remove us, that's good.
Wait a second, can another thread be *added* before us? No, the wait list is FIFO for regular mutexes, so we're added to the tail. If we read that `first` is false, and it isn't, the previous first waiter is woken up, removes itself, and *then* we are the first waiter. But if it is false, we don't set the handoff flag, but the next loop we'll read again and if we are, in fact, the first waiter, that's fine. It's a safe optimization, just delaying the handoff flag.
But what if we read `first` as `true` when we are NOT the first waiter? That's impossible. We can only remove ourselves, and our unique stack-allocated `&waiter` means our pointer is the only valid value. Only we can set `lock->first_waiter` to point at our structure, so that's not possible.
Now, let's consider compiler optimizations and the potential for torn reads on 64-bit architectures, and could the compiler optimize away the re-read? A torn read is possible, even if unlikely, a garbage pointer might match `&waiter`, but more importantly, the Linux Kernel Memory Model says that shared variables accessed by at least one writer must be accessed using a memory model instruction, like `READ_ONCE`, to prevent load tearing, store tearing, and, critically, load merging, which could be an issue, given this is in a loop.
Wait, looking at the loop in `__mutex_lock_common`! If the compiler merged the load of `lock->first_waiter`, it might read it once and reuse it! If that happens, even if we *become* the first waiter later, `first` would remain false, and the handoff flag would never be set, which could cause problems under heavy contention.
Ah, but is that actually true? Let's check `lock->first_waiter` for `READ_ONCE` or barriers. Between reading `lock->first_waiter` and the next iteration, we've got a whole bunch of calls, specifically: `raw_spin_lock_irqsave`, `raw_spin_lock`, `__set_task_blocked_on`, and `set_current_state`, with `__mutex_trylock_or_handoff`. The barriers in the `raw_spin_lock` calls prevent the compiler from merging the load. That's a huge relief.
Wait, though, we still have a data race! KCSAN flagged a race because `lock->first_waiter` is written to in `__mutex_remove_waiter` (under `lock->wait_lock`) and read in `__mutex_lock_common` (locklessly). I need to check if this is benign or needs marking. I'll search the kernel's history for reports about KCSAN or similar issues with `lock->first_waiter`, using `git log`.
|
| 18/2 |
2026/07/25 23:16 |
tool |
git-log |
0m
Args: map[CodeRegexp:KCSAN PathPrefix:kernel/locking/mutex.c]
Results:
|
| 19/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 20195
output: 35
thoughts: 50
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Mutex KCSAN Investigation**
Alright, I'm digging into `kernel/locking/mutex.c` today. First things first: I'm noticing there haven't been any recent commits flagged with "KCSAN" in the commit message related to this file. That's interesting, but doesn't necessarily mean we're in the clear. KCSAN is a powerful tool, but it's not the only way data races can be introduced or detected.
So, let's pivot. Given the nature of mutexes and concurrent access, I need to check for subtle race conditions that might have slipped through. My next move is to search the code for any instances of "data_race". I'll also do a thorough scan for "READ_ONCE". `READ_ONCE` and `WRITE_ONCE` are crucial primitives in this space, and their misuse (or lack of use where needed) are often indicators of potential issues that can lead to subtle, hard-to-debug data races. This will give me a better understanding of how memory access is being managed in critical sections protected by the mutex implementation. Time to get to work!
|
| 20/2 |
2026/07/25 23:16 |
tool |
grepper |
0m
Args: map[Expression:READ_ONCE|data_race PathPrefix:kernel/locking/mutex.c]
Results: map[Output:kernel/locking/mutex.c=337=bool ww_mutex_spin_on_owner(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
--
kernel/locking/mutex.c-354- */
kernel/locking/mutex.c:355: if (ww_ctx->acquired > 0 && READ_ONCE(ww->ctx))
kernel/locking/mutex.c-356- return false;
--
kernel/locking/mutex.c-371- */
kernel/locking/mutex.c:372: if (waiter && data_race(lock->first_waiter != waiter))
kernel/locking/mutex.c-373- return false;
--
kernel/locking/mutex.c=609=__mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclass,
--
kernel/locking/mutex.c-628- if (ww_ctx) {
kernel/locking/mutex.c:629: if (unlikely(ww_ctx == READ_ONCE(ww->ctx)))
kernel/locking/mutex.c-630- return -EALREADY;
]
|
| 21/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 20837
output: 35
thoughts: 75
Thoughts: **Analyzing a Potential Data Race in Kernel Locking**
Aha! Line 372 is the key: `if (waiter && data_race(lock->first_waiter != waiter))`. My immediate concern is that `data_race` call. Why is it used in this context? I need to understand the rationale behind that specific check. My next step is to dive into the `kernel/locking/mutex.c` file and examine the code surrounding line 372. I need to understand what's happening at that exact point in the mutex's release path. I'm looking for the conditions that necessitate a data race check and the specific logic that warrants this approach. What kind of concurrency scenarios are they attempting to catch? I need to see the context of this check to fully grasp its function.
|
| 22/2 |
2026/07/25 23:16 |
tool |
read-file |
0m
Args: map[File:kernel/locking/mutex.c FirstLine:350 LineCount:30]
Results: map[Contents: 350: * performed the optimistic spinning cannot be done.
351: *
352: * Check this in every inner iteration because we may
353: * be racing against another thread's ww_mutex_lock.
354: */
355: if (ww_ctx->acquired > 0 && READ_ONCE(ww->ctx))
356: return false;
357:
358: /*
359: * If we aren't on the wait list yet, cancel the spin
360: * if there are waiters. We want to avoid stealing the
361: * lock from a waiter with an earlier stamp, since the
362: * other thread may already own a lock that we also
363: * need.
364: */
365: if (!waiter && (atomic_long_read(&lock->owner) & MUTEX_FLAG_WAITERS))
366: return false;
367:
368: /*
369: * Similarly, stop spinning if we are no longer the
370: * first waiter.
371: */
372: if (waiter && data_race(lock->first_waiter != waiter))
373: return false;
374:
375: return true;
376: }
377:
378: /*
379: * Look out! "owner" is an entirely speculative pointer access and not
]
|
| 23/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 21542
output: 35
thoughts: 86
Thoughts: **Debugging a Suspected Data Race**
Okay, so I'm digging into this code and I see something interesting: `data_race(lock->first_waiter != waiter)` is being used within `ww_mutex_spin_on_owner`. My initial reaction is, "Aha! That's a potential area for a data race." I need to understand the context and how this came to be.
My next step is to trace back the origin of that specific `data_race` call. I need to understand when and why it was introduced. I'm thinking I'll use `git log` with the `-G` flag. That should allow me to search the commit history for changes related to that specific line of code. If that doesn't work, I can also try `git blame` on line 372 β assuming that's the relevant line within `ww_mutex_spin_on_owner`. That should show me the last modification and the associated commit. That's where I'll find my answer and figure out why we're using this call.
|
| 24/2 |
2026/07/25 23:16 |
tool |
git-blame |
0m
Args: map[End:375 File:kernel/locking/mutex.c Start:370]
Results: map[Output:c516df978df14 370) * first waiter.
c516df978df14 371) */
5c4326231cde3 372) if (waiter && data_race(lock->first_waiter != waiter))
c516df978df14 373) return false;
c516df978df14 374)
c516df978df14 375) return true;
]
|
| 25/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 22051
output: 27
thoughts: 19
Thoughts: Okay, here's my interpretation of that request, formatted as requested:
**Examining Commit 5c4326231cde3**
Alright, let's take a look at commit `5c4326231cde3`. I'm going to start by pulling up the diff. I need to understand the scope of the changes. What files were touched? What lines were modified? Were there additions, deletions, or merely refactoring? I'll probably start with the most relevant files β based on my prior understanding of the codebase, I have a good idea where to focus my attention.
I'll be looking for any potential impact on core functionality, paying close attention to any edge cases that might have been introduced or addressed. I'm going to scan for any logic changes, algorithmic improvements (or regressions!), potential memory leaks, or concurrency issues. I'll need to see if the commit includes any unit tests, and if so, how comprehensive they are. Do they actually cover the new code paths, or is there a gap?
Next, I will look at the commit message; does it accurately describe the changes made and the motivation behind them? Is it clear, concise, and technically sound? Does it link to any related issues or pull requests? The commit message should align with my professional development standards and standards defined by my team.
Finally, I'll consider the broader context. How does this commit relate to the overall project roadmap and architecture? Does it introduce any breaking changes or require any downstream adjustments? I'll be thinking about possible future implications β are these changes sustainable in the long run? Based on this analysis, I'll form a well-grounded opinion on its quality and impact.
|
| 26/2 |
2026/07/25 23:16 |
tool |
git-show |
0m
Args: map[Commit:5c4326231cde3]
Results: map[Output:commit 5c4326231cde36fd5e90c41e403df9fac6238f4b
Author: Peter Zijlstra <peterz@infradead.org>
Date: Tue Jan 20 10:06:08 2026 +0100
locking/mutex: Add context analysis
Add compiler context analysis annotations.
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Link: https://patch.msgid.link/20260121111213.745353747@infradead.org
diff --git a/include/linux/mutex.h b/include/linux/mutex.h
index c471b129f703..734048c02f4f 100644
--- a/include/linux/mutex.h
+++ b/include/linux/mutex.h
@@ -183,7 +183,7 @@ static inline int __must_check __devm_mutex_init(struct device *dev, struct mute
*/
#ifdef CONFIG_DEBUG_LOCK_ALLOC
extern void mutex_lock_nested(struct mutex *lock, unsigned int subclass) __acquires(lock);
-extern void _mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest_lock);
+extern void _mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest_lock) __acquires(lock);
extern int __must_check mutex_lock_interruptible_nested(struct mutex *lock,
unsigned int subclass) __cond_acquires(0, lock);
extern int __must_check _mutex_lock_killable(struct mutex *lock,
diff --git a/include/linux/mutex_types.h b/include/linux/mutex_types.h
index a8f119f81177..24ed599fdda8 100644
--- a/include/linux/mutex_types.h
+++ b/include/linux/mutex_types.h
@@ -44,7 +44,7 @@ context_lock_struct(mutex) {
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
struct optimistic_spin_queue osq; /* Spinner MCS lock */
#endif
- struct mutex_waiter *first_waiter;
+ struct mutex_waiter *first_waiter __guarded_by(&wait_lock);
#ifdef CONFIG_DEBUG_MUTEXES
void *magic;
#endif
diff --git a/kernel/locking/Makefile b/kernel/locking/Makefile
index a114949eeed5..264447d606a6 100644
--- a/kernel/locking/Makefile
+++ b/kernel/locking/Makefile
@@ -3,6 +3,8 @@
# and is generally not a function of system call inputs.
KCOV_INSTRUMENT := n
+CONTEXT_ANALYSIS_mutex.o := y
+
obj-y += mutex.o semaphore.o rwsem.o percpu-rwsem.o
# Avoid recursion lockdep -> sanitizer -> ... -> lockdep & improve performance.
diff --git a/kernel/locking/mutex.c b/kernel/locking/mutex.c
index 95f1822122a1..427187ff02db 100644
--- a/kernel/locking/mutex.c
+++ b/kernel/locking/mutex.c
@@ -46,8 +46,9 @@
static void __mutex_init_generic(struct mutex *lock)
{
atomic_long_set(&lock->owner, 0);
- raw_spin_lock_init(&lock->wait_lock);
- lock->first_waiter = NULL;
+ scoped_guard (raw_spinlock_init, &lock->wait_lock) {
+ lock->first_waiter = NULL;
+ }
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
osq_lock_init(&lock->osq);
#endif
@@ -150,6 +151,7 @@ EXPORT_SYMBOL(mutex_init_generic);
* follow with a __mutex_trylock() before failing.
*/
static __always_inline bool __mutex_trylock_fast(struct mutex *lock)
+ __cond_acquires(true, lock)
{
unsigned long curr = (unsigned long)current;
unsigned long zero = 0UL;
@@ -163,6 +165,7 @@ static __always_inline bool __mutex_trylock_fast(struct mutex *lock)
}
static __always_inline bool __mutex_unlock_fast(struct mutex *lock)
+ __cond_releases(true, lock)
{
unsigned long curr = (unsigned long)current;
@@ -201,6 +204,7 @@ static inline void __mutex_clear_flag(struct mutex *lock, unsigned long flag)
static void
__mutex_add_waiter(struct mutex *lock, struct mutex_waiter *waiter,
struct mutex_waiter *first)
+ __must_hold(&lock->wait_lock)
{
hung_task_set_blocker(lock, BLOCKER_TYPE_MUTEX);
debug_mutex_add_waiter(lock, waiter, current);
@@ -219,6 +223,7 @@ __mutex_add_waiter(struct mutex *lock, struct mutex_waiter *waiter,
static void
__mutex_remove_waiter(struct mutex *lock, struct mutex_waiter *waiter)
+ __must_hold(&lock->wait_lock)
{
if (list_empty(&waiter->list)) {
__mutex_clear_flag(lock, MUTEX_FLAGS);
@@ -268,7 +273,8 @@ static void __mutex_handoff(struct mutex *lock, struct task_struct *task)
* We also put the fastpath first in the kernel image, to make sure the
* branch is predicted by the CPU as default-untaken.
*/
-static void __sched __mutex_lock_slowpath(struct mutex *lock);
+static void __sched __mutex_lock_slowpath(struct mutex *lock)
+ __acquires(lock);
/**
* mutex_lock - acquire the mutex
@@ -349,7 +355,7 @@ bool ww_mutex_spin_on_owner(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
* Similarly, stop spinning if we are no longer the
* first waiter.
*/
- if (waiter && lock->first_waiter != waiter)
+ if (waiter && data_race(lock->first_waiter != waiter))
return false;
return true;
@@ -534,7 +540,8 @@ mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
}
#endif
-static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip);
+static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip)
+ __releases(lock);
/**
* mutex_unlock - release the mutex
@@ -574,6 +581,7 @@ EXPORT_SYMBOL(mutex_unlock);
* of a unlocked mutex is not allowed.
*/
void __sched ww_mutex_unlock(struct ww_mutex *lock)
+ __no_context_analysis
{
__ww_mutex_unlock(lock);
mutex_unlock(&lock->base);
@@ -587,6 +595,7 @@ static __always_inline int __sched
__mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclass,
struct lockdep_map *nest_lock, unsigned long ip,
struct ww_acquire_ctx *ww_ctx, const bool use_ww_ctx)
+ __cond_acquires(0, lock)
{
DEFINE_WAKE_Q(wake_q);
struct mutex_waiter waiter;
@@ -780,6 +789,7 @@ __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclas
static int __sched
__mutex_lock(struct mutex *lock, unsigned int state, unsigned int subclass,
struct lockdep_map *nest_lock, unsigned long ip)
+ __cond_acquires(0, lock)
{
return __mutex_lock_common(lock, state, subclass, nest_lock, ip, NULL, false);
}
@@ -787,6 +797,7 @@ __mutex_lock(struct mutex *lock, unsigned int state, unsigned int subclass,
static int __sched
__ww_mutex_lock(struct mutex *lock, unsigned int state, unsigned int subclass,
unsigned long ip, struct ww_acquire_ctx *ww_ctx)
+ __cond_acquires(0, lock)
{
return __mutex_lock_common(lock, state, subclass, NULL, ip, ww_ctx, true);
}
@@ -834,6 +845,7 @@ void __sched
mutex_lock_nested(struct mutex *lock, unsigned int subclass)
{
__mutex_lock(lock, TASK_UNINTERRUPTIBLE, subclass, NULL, _RET_IP_);
+ __acquire(lock);
}
EXPORT_SYMBOL_GPL(mutex_lock_nested);
@@ -842,6 +854,7 @@ void __sched
_mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest)
{
__mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, nest, _RET_IP_);
+ __acquire(lock);
}
EXPORT_SYMBOL_GPL(_mutex_lock_nest_lock);
@@ -870,12 +883,14 @@ mutex_lock_io_nested(struct mutex *lock, unsigned int subclass)
token = io_schedule_prepare();
__mutex_lock_common(lock, TASK_UNINTERRUPTIBLE,
subclass, NULL, _RET_IP_, NULL, 0);
+ __acquire(lock);
io_schedule_finish(token);
}
EXPORT_SYMBOL_GPL(mutex_lock_io_nested);
static inline int
ww_mutex_deadlock_injection(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
+ __cond_releases(nonzero, lock)
{
#ifdef CONFIG_DEBUG_WW_MUTEX_SLOWPATH
unsigned tmp;
@@ -937,6 +952,7 @@ EXPORT_SYMBOL_GPL(ww_mutex_lock_interruptible);
* Release the lock, slowpath:
*/
static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip)
+ __releases(lock)
{
struct task_struct *next = NULL;
struct mutex_waiter *waiter;
@@ -945,6 +961,7 @@ static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigne
unsigned long flags;
mutex_release(&lock->dep_map, ip);
+ __release(lock);
/*
* Release the lock before (potentially) taking the spinlock such that
@@ -1066,24 +1083,29 @@ EXPORT_SYMBOL_GPL(mutex_lock_io);
static noinline void __sched
__mutex_lock_slowpath(struct mutex *lock)
+ __acquires(lock)
{
__mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, NULL, _RET_IP_);
+ __acquire(lock);
}
static noinline int __sched
__mutex_lock_killable_slowpath(struct mutex *lock)
+ __cond_acquires(0, lock)
{
return __mutex_lock(lock, TASK_KILLABLE, 0, NULL, _RET_IP_);
}
static noinline int __sched
__mutex_lock_interruptible_slowpath(struct mutex *lock)
+ __cond_acquires(0, lock)
{
return __mutex_lock(lock, TASK_INTERRUPTIBLE, 0, NULL, _RET_IP_);
}
static noinline int __sched
__ww_mutex_lock_slowpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
+ __cond_acquires(0, lock)
{
return __ww_mutex_lock(&lock->base, TASK_UNINTERRUPTIBLE, 0,
_RET_IP_, ctx);
@@ -1092,6 +1114,7 @@ __ww_mutex_lock_slowpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
static noinline int __sched
__ww_mutex_lock_interruptible_slowpath(struct ww_mutex *lock,
struct ww_acquire_ctx *ctx)
+ __cond_acquires(0, lock)
{
return __ww_mutex_lock(&lock->base, TASK_INTERRUPTIBLE, 0,
_RET_IP_, ctx);
diff --git a/kernel/locking/mutex.h b/kernel/locking/mutex.h
index 9ad4da8cea00..b94ef40c1f48 100644
--- a/kernel/locking/mutex.h
+++ b/kernel/locking/mutex.h
@@ -7,6 +7,7 @@
* Copyright (C) 2004, 2005, 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
*/
#ifndef CONFIG_PREEMPT_RT
+#include <linux/mutex.h>
/*
* This is the control structure for tasks blocked on mutex, which resides
* on the blocked task's kernel stack:
diff --git a/kernel/locking/ww_mutex.h b/kernel/locking/ww_mutex.h
index a0847e91ae04..c50ea5dd3c44 100644
--- a/kernel/locking/ww_mutex.h
+++ b/kernel/locking/ww_mutex.h
@@ -7,12 +7,14 @@
static inline struct mutex_waiter *
__ww_waiter_first(struct mutex *lock)
+ __must_hold(&lock->wait_lock)
{
return lock->first_waiter;
}
static inline struct mutex_waiter *
__ww_waiter_next(struct mutex *lock, struct mutex_waiter *w)
+ __must_hold(&lock->wait_lock)
{
w = list_next_entry(w, list);
if (lock->first_waiter == w)
@@ -23,6 +25,7 @@ __ww_waiter_next(struct mutex *lock, struct mutex_waiter *w)
static inline struct mutex_waiter *
__ww_waiter_prev(struct mutex *lock, struct mutex_waiter *w)
+ __must_hold(&lock->wait_lock)
{
w = list_prev_entry(w, list);
if (lock->first_waiter == w)
@@ -33,6 +36,7 @@ __ww_waiter_prev(struct mutex *lock, struct mutex_waiter *w)
static inline struct mutex_waiter *
__ww_waiter_last(struct mutex *lock)
+ __must_hold(&lock->wait_lock)
{
struct mutex_waiter *w = lock->first_waiter;
@@ -43,6 +47,7 @@ __ww_waiter_last(struct mutex *lock)
static inline void
__ww_waiter_add(struct mutex *lock, struct mutex_waiter *waiter, struct mutex_waiter *pos)
+ __must_hold(&lock->wait_lock)
{
__mutex_add_waiter(lock, waiter, pos);
}
@@ -60,16 +65,19 @@ __ww_mutex_has_waiters(struct mutex *lock)
}
static inline void lock_wait_lock(struct mutex *lock, unsigned long *flags)
+ __acquires(&lock->wait_lock)
{
raw_spin_lock_irqsave(&lock->wait_lock, *flags);
}
static inline void unlock_wait_lock(struct mutex *lock, unsigned long *flags)
+ __releases(&lock->wait_lock)
{
raw_spin_unlock_irqrestore(&lock->wait_lock, *flags);
}
static inline void lockdep_assert_wait_lock_held(struct mutex *lock)
+ __must_hold(&lock->wait_lock)
{
lockdep_assert_held(&lock->wait_lock);
}
@@ -296,6 +304,7 @@ static bool __ww_mutex_wound(struct MUTEX *lock,
struct ww_acquire_ctx *ww_ctx,
struct ww_acquire_ctx *hold_ctx,
struct wake_q_head *wake_q)
+ __must_hold(&lock->wait_lock)
{
struct task_struct *owner = __ww_mutex_owner(lock);
@@ -360,6 +369,7 @@ static bool __ww_mutex_wound(struct MUTEX *lock,
static void
__ww_mutex_check_waiters(struct MUTEX *lock, struct ww_acquire_ctx *ww_ctx,
struct wake_q_head *wake_q)
+ __must_hold(&lock->wait_lock)
{
struct MUTEX_WAITER *cur;
@@ -453,6 +463,7 @@ __ww_mutex_kill(struct MUTEX *lock, struct ww_acquire_ctx *ww_ctx)
static inline int
__ww_mutex_check_kill(struct MUTEX *lock, struct MUTEX_WAITER *waiter,
struct ww_acquire_ctx *ctx)
+ __must_hold(&lock->wait_lock)
{
struct ww_mutex *ww = container_of(lock, struct ww_mutex, base);
struct ww_acquire_ctx *hold_ctx = READ_ONCE(ww->ctx);
@@ -503,6 +514,7 @@ __ww_mutex_add_waiter(struct MUTEX_WAITER *waiter,
struct MUTEX *lock,
struct ww_acquire_ctx *ww_ctx,
struct wake_q_head *wake_q)
+ __must_hold(&lock->wait_lock)
{
struct MUTEX_WAITER *cur, *pos = NULL;
bool is_wait_die;
]
|
| 27/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 27197
output: 43
thoughts: 300
Thoughts: **Data Race Discovered in Mutex Waiter Handling**
Okay, here's what's running through my head. I'm looking at commit `5c4326231cde3` by Peter Zijlstra, where he added those handy context analysis annotations β specifically, `struct mutex_waiter *first_waiter __guarded_by(&wait_lock)`. He added the `data_race(lock->first_waiter != waiter)` annotation in `ww_mutex_spin_on_owner` to keep the compiler and KCSAN quiet. But, hold on a second... what about line 728 in `__mutex_lock_common`?
```c
schedule_preempt_disabled();
first = lock->first_waiter == &waiter;
raw_spin_lock_irqsave(&lock->wait_lock, flags);
```
Damn! That line, `first = lock->first_waiter == &waiter;`, is also accessed without holding `lock->wait_lock`! It's *exactly* the same data race as the one in `ww_mutex_spin_on_owner`, but it looks like it was either missed entirely or wasn't annotated with `data_race()` or, ideally, `READ_ONCE()`! That's a definite oversight.
Right, let's not jump to conclusions. I need to be methodical. I need to confirm I'm not missing anything. I need to check and make sure that this isn't just a pattern, that this race doesn't occur elsewhere in the code. I'm going to search for other instances where `lock->first_waiter` is read locklessly. Time to comb through `kernel/locking/mutex.c` and see what else pops up.
|
| 28/2 |
2026/07/25 23:16 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/locking/mutex.c IncludeSnippetLines:1 Name:mutex::first_waiter]
Results: map[References:[map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__mutex_add_waiter SourceFile:kernel/locking/mutex.c SourceLine:212 SourceSnippet: 211: {
212: struct mutex_waiter *first = lock->first_waiter;
213:
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:__mutex_add_waiter SourceFile:kernel/locking/mutex.c SourceLine:226 SourceSnippet: 225: if (pos == first)
226: lock->first_waiter = waiter;
227: return;
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:__mutex_add_waiter SourceFile:kernel/locking/mutex.c SourceLine:236 SourceSnippet: 235: INIT_LIST_HEAD(&waiter->list);
236: lock->first_waiter = waiter;
237: __mutex_set_flag(lock, MUTEX_FLAG_WAITERS);
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:__mutex_init_generic SourceFile:kernel/locking/mutex.c SourceLine:50 SourceSnippet: 49: scoped_guard (raw_spinlock_init, &lock->wait_lock) {
50: lock->first_waiter = NULL;
51: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__mutex_lock_common SourceFile:kernel/locking/mutex.c SourceLine:728 SourceSnippet: 727:
728: first = lock->first_waiter == &waiter;
729:
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__mutex_lock_common SourceFile:kernel/locking/mutex.c SourceLine:782 SourceSnippet: 781: */
782: if (!ww_ctx->is_wait_die && lock->first_waiter != &waiter)
783: __ww_mutex_check_waiters(lock, ww_ctx, &wake_q);
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:__mutex_remove_waiter SourceFile:kernel/locking/mutex.c SourceLine:246 SourceSnippet: 245: __mutex_clear_flag(lock, MUTEX_FLAGS);
246: lock->first_waiter = NULL;
247: } else {
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__mutex_remove_waiter SourceFile:kernel/locking/mutex.c SourceLine:248 SourceSnippet: 247: } else {
248: if (lock->first_waiter == waiter)
249: lock->first_waiter = list_next_entry(waiter, list);
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:__mutex_remove_waiter SourceFile:kernel/locking/mutex.c SourceLine:249 SourceSnippet: 248: if (lock->first_waiter == waiter)
249: lock->first_waiter = list_next_entry(waiter, list);
250: list_del(&waiter->list);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__mutex_unlock_slowpath SourceFile:kernel/locking/mutex.c SourceLine:1057 SourceSnippet:1056: */
1057: waiter = lock->first_waiter;
1058: if (!next && waiter) {
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__ww_waiter_first SourceFile:kernel/locking/ww_mutex.h SourceLine:26 SourceSnippet: 25: {
26: return lock->first_waiter;
27: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__ww_waiter_last SourceFile:kernel/locking/ww_mutex.h SourceLine:72 SourceSnippet: 71: {
72: struct mutex_waiter *w = lock->first_waiter;
73:
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__ww_waiter_next SourceFile:kernel/locking/ww_mutex.h SourceLine:43 SourceSnippet: 42: */
43: if (lock->first_waiter == w)
44: return NULL;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__ww_waiter_prev SourceFile:kernel/locking/ww_mutex.h SourceLine:62 SourceSnippet: 61: */
62: if (lock->first_waiter == w)
63: return NULL;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ww_mutex_spin_on_owner SourceFile:kernel/locking/mutex.c SourceLine:372 SourceSnippet: 371: */
372: if (waiter && data_race(lock->first_waiter != waiter))
373: return false;
]] TruncatedOutput:false]
|
| 29/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 29461
output: 35
thoughts: 97
Thoughts: **Analyzing a Potential Race Condition**
Okay, let's dive into this. First, I need to zero in on line 782: `if (!ww_ctx->is_wait_die && lock->first_waiter != &waiter)`. Hmm, a critical conditional, it seems. My initial thought is to quickly verify the locking context. Is this line *actually* executed while we hold `lock->wait_lock`? That's the key question here, it's essential for understanding the thread safety.
To properly assess this, I'm going to back up and look at the surrounding code. Let's trace back to the relevant function. Let's see... `__mutex_lock_common` is the likely candidate. I'll need to read the code around line 782, so I'll go to `kernel/locking/mutex.c`. Specifically, I'll examine lines 770 through 790. A proper analysis necessitates that I understand the code that influences the state of those variables in the `if` statement.
|
| 30/2 |
2026/07/25 23:16 |
tool |
read-file |
0m
Args: map[File:kernel/locking/mutex.c FirstLine:770 LineCount:20]
Results: map[Contents: 770: trace_contention_begin(lock, LCB_F_MUTEX);
771: }
772: }
773: __clear_task_blocked_on(current, lock);
774: __set_current_state(TASK_RUNNING);
775: raw_spin_unlock(¤t->blocked_lock);
776:
777: if (ww_ctx) {
778: /*
779: * Wound-Wait; we stole the lock (!first_waiter), check the
780: * waiters as anyone might want to wound us.
781: */
782: if (!ww_ctx->is_wait_die && lock->first_waiter != &waiter)
783: __ww_mutex_check_waiters(lock, ww_ctx, &wake_q);
784: }
785:
786: __mutex_remove_waiter(lock, &waiter);
787:
788: debug_mutex_free_waiter(&waiter);
789:
]
|
| 31/2 |
2026/07/25 23:16 |
llm |
expert |
0m
Model:
Tokens:
input: 30140
output: 35
thoughts: 86
Thoughts: **Analyzing a Potential Race Condition**
Okay, here's what I'm thinking... Line 782, we're deep inside `__mutex_lock_common`, past the main loop, that's where we're at, right? And the nagging question is, is `lock->wait_lock` held *at* that point? That's the crux of the matter. So, to figure this out, I'm going to track the life cycle of `lock->wait_lock`. I need to understand when it's acquired and when it's released, to figure out whether it *should* be held at line 782. I'll need to re-read the relevant section of `__mutex_lock_common`. Let's focus on lines 720 to 760, and trace `lock->wait_lock`'s behavior within that code block. That should give me the answer.
|
| 32/2 |
2026/07/25 23:17 |
tool |
read-file |
0m
Args: map[File:kernel/locking/mutex.c FirstLine:720 LineCount:40]
Results: map[Contents: 720: if (ret)
721: goto err;
722: }
723:
724: raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q);
725:
726: schedule_preempt_disabled();
727:
728: first = lock->first_waiter == &waiter;
729:
730: raw_spin_lock_irqsave(&lock->wait_lock, flags);
731: raw_spin_lock(¤t->blocked_lock);
732: /*
733: * As we likely have been woken up by task
734: * that has cleared our blocked_on state, re-set
735: * it to the lock we are trying to acquire.
736: */
737: __set_task_blocked_on(current, lock);
738: set_current_state(state);
739: /*
740: * Here we order against unlock; we must either see it change
741: * state back to RUNNING and fall through the next schedule(),
742: * or we must see its unlock and acquire.
743: */
744: if (__mutex_trylock_or_handoff(lock, first))
745: break;
746:
747: if (first) {
748: bool opt_acquired;
749:
750: /*
751: * mutex_optimistic_spin() can call schedule(), so
752: * we need to release these locks before calling it,
753: * and clear blocked on so we don't become unselectable
754: * to run.
755: */
756: __clear_task_blocked_on(current, lock);
757: raw_spin_unlock(¤t->blocked_lock);
758: raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
759:
]
|
| 33/2 |
2026/07/25 23:17 |
llm |
expert |
0m
Model:
Tokens:
input: 31048
output: 38
thoughts: 399
Thoughts: **Analyzing the Mutex Locking Mechanism**
Okay, here's what's running through my head as I dissect this code. I'm focusing on the intricacies of the locking mechanism, specifically within the `__mutex_lock_common` and potentially `__mutex_unlock_slowpath` functions.
At line 744, the code checks the return value of `__mutex_trylock_or_handoff`. If it's successful, we exit the loop. I'm noting that at this point, we definitely have a hold on both `lock->wait_lock` (acquired earlier) and `current->blocked_lock` (also acquired earlier).
Then, after the loop, we release `current->blocked_lock`, but critically, *we still hold* `lock->wait_lock`. This means that at line 782, `lock->wait_lock` is definitely held. This is the crucial point. This implies that the comparison `lock->first_waiter != &waiter` at line 782 is completely protected by `lock->wait_lock`! No race condition there.
So the only place where we're reading `lock->first_waiter` *without* any lock is at line 728:
`first = lock->first_waiter == &waiter;`
I need to confirm that that is indeed the *only* lockless read of `lock->first_waiter` in `__mutex_lock_common`.
Just to be absolutely sure, I'm going to quickly check `__mutex_unlock_slowpath` to see if there are any other possible lockless reads of `lock->first_waiter` in that function. I need to be absolutely certain I've got this right. I'll need to figure out the line number of `__mutex_unlock_slowpath` in `kernel/locking/mutex.c` so I can check. I'll search for it.
|
| 34/2 |
2026/07/25 23:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/locking/mutex.c Name:__mutex_unlock_slowpath]
Results: map[SourceCode: 978: /*
979: * Release the lock, slowpath:
980: */
981: static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip)
982: __releases(lock)
983: {
984: struct task_struct *donor, *next = NULL;
985: struct mutex_waiter *waiter;
986: unsigned long owner;
987: unsigned long flags;
988:
989: mutex_release(&lock->dep_map, ip);
990: __release(lock);
991:
992: /*
993: * Ensures the proxy donor stack is stable across unlock and handoff.
994: * Specifically, it avoids the case where current->blocked_donor is
995: * NULL when it is inspected while doing the unlock, but a preemption
996: * before taking the wake_lock would make it set and a hand-off is
997: * missed.
998: */
999: guard(preempt)();
1000: /*
1001: * Release the lock before (potentially) taking the spinlock such that
1002: * other contenders can get on with things ASAP.
1003: *
1004: * Except when HANDOFF, in that case we must not clear the owner field,
1005: * but instead set it to the top waiter.
1006: */
1007: owner = atomic_long_read(&lock->owner);
1008: for (;;) {
1009: MUTEX_WARN_ON(__owner_task(owner) != current);
1010: MUTEX_WARN_ON(owner & MUTEX_FLAG_PICKUP);
1011:
1012: if (sched_proxy_exec() && current->blocked_donor) {
1013: /* force handoff if we have a blocked_donor */
1014: owner = MUTEX_FLAG_HANDOFF;
1015: break;
1016: }
1017:
1018: if (owner & MUTEX_FLAG_HANDOFF)
1019: break;
1020:
1021: if (atomic_long_try_cmpxchg_release(&lock->owner, &owner, __owner_flags(owner))) {
1022: if (owner & MUTEX_FLAG_WAITERS)
1023: break;
1024:
1025: return;
1026: }
1027: }
1028:
1029: raw_spin_lock_irqsave(&lock->wait_lock, flags);
1030: raw_spin_lock(¤t->blocked_lock);
1031: debug_mutex_unlock(lock);
1032:
1033: if (sched_proxy_exec()) {
1034: /*
1035: * If we have a task boosting current, and that task was boosting
1036: * current through this lock, hand the lock to that task, as that
1037: * is the highest waiter, as selected by the scheduling function.
1038: */
1039: donor = current->blocked_donor;
1040: if (donor) {
1041: struct mutex *next_lock;
1042:
1043: raw_spin_lock_nested(&donor->blocked_lock, SINGLE_DEPTH_NESTING);
1044: next_lock = __get_task_blocked_on(donor);
1045: if (next_lock == lock) {
1046: next = get_task_struct(donor);
1047: __clear_task_blocked_on(next, lock);
1048: current->blocked_donor = NULL;
1049: }
1050: raw_spin_unlock(&donor->blocked_lock);
1051: }
1052: }
1053:
1054: /*
1055: * Failing that, pick first on the wait list.
1056: */
1057: waiter = lock->first_waiter;
1058: if (!next && waiter) {
1059: next = get_task_struct(waiter->task);
1060:
1061: raw_spin_lock_nested(&next->blocked_lock, SINGLE_DEPTH_NESTING);
1062: debug_mutex_wake_waiter(lock, waiter);
1063: __clear_task_blocked_on(next, lock);
1064: raw_spin_unlock(&next->blocked_lock);
1065:
1066: }
1067:
1068: if (trace_contended_release_enabled() && waiter)
1069: trace_call__contended_release(lock);
1070:
1071: if (owner & MUTEX_FLAG_HANDOFF)
1072: __mutex_handoff(lock, next);
1073:
1074: raw_spin_unlock(¤t->blocked_lock);
1075: raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
1076: if (next) {
1077: wake_up_process(next);
1078: put_task_struct(next);
1079: }
1080: }
SourceFile:kernel/locking/mutex.c]
|
| 35/2 |
2026/07/25 23:17 |
llm |
expert |
0m
Model:
Tokens:
input: 33426
output: 32
thoughts: 1975
Thoughts: **Analyzing the lockless read of `lock->first_waiter` in `__mutex_trylock_or_handoff`**
Okay, so I'm looking at this mutex code, specifically the `__mutex_unlock_slowpath` function. I see the lockless read of `lock->first_waiter` at line 728: `first = lock->first_waiter == &waiter;`. This is interesting because the write to `lock->first_waiter` is protected by `lock->wait_lock`.
I'm trying to figure out if this introduces a real data race and if itβs harmful. Is it benign or not? Let's classify it. According to my understanding, it could be a "hint" flag. If the read is stale (it reads `false` when it should be `true`), it just causes a slight delay, a suboptimal path. The loop runs again, schedules, and it will eventually read the correct value. The `MUTEX_FLAG_HANDOFF` flag might not get set initially, but it will be set in a subsequent loop. The slow path loop iteration is not an issue since it's just one loop iteration.
Now, what if we read `first` as `true` when it should be `false`? Can that even happen? We are comparing `lock->first_waiter` to our own `waiter` pointer. Only we can have `&waiter`, so, if it reads as true, we are the first waiter, right? Well, unless something removes us *after* the read. But *we* can't be removed, and since standard mutexes are FIFO, no other threads can be added before us. Ah, but `ww_mutex`es! A waiter with an earlier timestamp *could* be added, and that might invalidate our `first = true` assumption.
If `ww_mutex` does insert a waiter with an earlier timestamp, the list will be updated, and the subsequent unlock will still hand the lock to the correct waiter. `__mutex_unlock_slowpath` correctly chooses the first waiter from `lock->first_waiter`.
Also, thereβs this optimistic spin: if `first` is true, we do `mutex_optimistic_spin`. Inside there is `ww_mutex_spin_on_owner`. If we are no longer the first waiter, there is a `data_race` check which immediately returns `false` inside the optimistic spin. So we don't have an indefinite spin or incorrect behavior. Phew!
Now, let's think about compiler optimizations. Could the compiler mess this up? `first` is a local, and we only read the member once per iteration. Let me see... load tearing? Pointer reads are atomic on 32- and 64-bit architectures, so that's not possible. Load merging/hoisting? Nope, the function calls inside the loop act as barriers.
Okay, so the compiler shouldn't be able to break this.
Now the KCSAN warning: It will flag this as a data race because of the lockless read. To suppress this, and document that we know it is a data race (but harmless), we can wrap this in `data_race()` or `READ_ONCE()`. This documents that it is intentional.
Time to check for existing patches/discussions in the kernel and see if anyone has seen this before. It might be in the code already. Let's start with a search...
|
| 36/2 |
2026/07/25 23:17 |
tool |
grepper |
0m
Args: map[Expression:first_waiter == &waiter PathPrefix:kernel/locking/]
Results: map[Output:kernel/locking/mutex.c=609=__mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclass,
--
kernel/locking/mutex.c-727-
kernel/locking/mutex.c:728: first = lock->first_waiter == &waiter;
kernel/locking/mutex.c-729-
]
|
| 37/2 |
2026/07/25 23:17 |
llm |
expert |
0m
Model:
Tokens:
input: 36282
output: 28
thoughts: 95
Thoughts: **Investigating a Potential Data Race in the Kernel Mutex Implementation**
Okay, let's dive into this. My initial thought is to see if a fix for this data race has already been addressed in either the linux-next or mainline kernel. That seems like the logical first step, but before I go hunting through changelogs, I should probably narrow the focus. Let's start with a focused approach using `git log`. I want to zero in on any recent commits that touch `kernel/locking/mutex.c`, specifically those that might relate to `first_waiter` or, of course, the general term "data_race." I'll set the time window to the past year to keep the search manageable and relevant. I want to see if any recent work provides a quick win.
|
| 38/2 |
2026/07/25 23:17 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:kernel/locking/mutex.c]
Results: map[Output:4f070ccb4dc4 locking: Add contended_release tracepoint to sleepable locks
ec9d4f1c4241 sched/proxy: Remove PROXY_WAKING
1628b25248d0 sched: Add blocked_donor link to task for smarter mutex handoffs
bdaf235913e1 locking: mutex: Fix proxy-exec potentially deactivating tasks marked TASK_RUNNING
0adc92b910b3 locking/mutex: Fix ww_mutex wait_list operations
2d7622669836 sched/locking: Add special p->blocked_on==PROXY_WAKING value for proxy return-migration
fa4a1ff8ab23 locking: Add task::blocked_lock to serialize blocked_on state
5c4326231cde locking/mutex: Add context analysis
25500ba7e77c locking/mutex: Remove the list_head from struct mutex
8b65eb52d93e locking/mutex: Rename mutex_init_lockep()
51d7a054521d locking/mutex: Redo __mutex_init() to reduce generated code size
1dfe5ea6dbb3 locking/mutex: Remove redundant #ifdefs
a4f0b6fef4b0 locking/mutex: Add p->blocked_on wrappers for correctness checks
44e4e0297c3c locking/mutex: Rework task_struct::blocked_on
fb49f07ba1d9 locking/mutex: implement mutex_lock_killable_nest_lock
c5b6ababd21a locking/mutex: implement mutex_trylock_nested
e711faaafbe5 hung_task: replace blocker_mutex with encoded blocker
3cf67d61ff98 hung_task: show the blocker task if the task is hung on mutex
337369f8ce9e locking/mutex: Add MUTEX_WARN_ON() into fast path
abfdccd6af2b sched/wake_q: Add helper to call wake_up_q after unlock with preemption disabled
]
|
| 39/2 |
2026/07/25 23:17 |
llm |
expert |
0m
Model:
Tokens:
input: 37084
output: 25
thoughts: 216
Thoughts: **Analyzing Commit Chronology**
Okay, so I'm looking at commit `25500ba7e77c` which removes `list_head` from `struct mutex`, and it was authored on March 5th, 2026. My initial reaction is to note the date. Let's dig deeper and compare it to other commits. I also want to cross-reference with other relevant commits.
Now, let's look at `5c4326231cde`, which introduces context analysis. That was authored on January 20th, 2026. Hmm, it appears in the log before `25500ba7e77c`, that's an observation. This raises the question of their order in the overall repository's timeline.
Right, I need to remind myself that `git log` presents commits in reverse chronological order. The most recent commit is listed first. So, the order *is* correct.
And now I see that `4f070ccb4dc4` is the most recent. Let me check its date as well.
|
| 40/2 |
2026/07/25 23:17 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 4f070ccb4dc4692e3b6757819fb80655f58b4f12
Author: Dmitry Ilvokhin <d@ilvokhin.com>
Date: Thu Jun 4 07:15:07 2026 +0000
locking: Add contended_release tracepoint to sleepable locks
Add the contended_release trace event. This tracepoint fires on the
holder side when a contended lock is released, complementing the
existing contention_begin/contention_end tracepoints which fire on the
waiter side.
This enables correlating lock hold time under contention with waiter
events by lock address.
Add trace_contended_release()/trace_call__contended_release() calls to
the slowpath unlock paths of sleepable locks: mutex, rtmutex, semaphore,
rwsem, percpu-rwsem, and RT-specific rwbase locks.
Where possible, trace_contended_release() fires before the lock is
released and before the waiter is woken. For some lock types, the
tracepoint fires after the release but before the wake. Making the
placement consistent across all lock types is not worth the added
complexity.
For reader/writer locks, the tracepoint fires for every reader releasing
while a writer is waiting, not only for the last reader.
Signed-off-by: Dmitry Ilvokhin <d@ilvokhin.com>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Acked-by: Paul E. McKenney <paulmck@kernel.org>
Acked-by: Usama Arif <usama.arif@linux.dev>
Link: https://patch.msgid.link/02f4f6c5ce6761e7f6587cf0ff2289d962ecddd4.1780506267.git.d@ilvokhin.com
diff --git a/include/trace/events/lock.h b/include/trace/events/lock.h
index da978f2afb45..1ded869cd619 100644
--- a/include/trace/events/lock.h
+++ b/include/trace/events/lock.h
@@ -137,6 +137,23 @@ TRACE_EVENT(contention_end,
TP_printk("%p (ret=%d)", __entry->lock_addr, __entry->ret)
);
+TRACE_EVENT(contended_release,
+
+ TP_PROTO(void *lock),
+
+ TP_ARGS(lock),
+
+ TP_STRUCT__entry(
+ __field(void *, lock_addr)
+ ),
+
+ TP_fast_assign(
+ __entry->lock_addr = lock;
+ ),
+
+ TP_printk("%p", __entry->lock_addr)
+);
+
#endif /* _TRACE_LOCK_H */
/* This part must be outside protection */
diff --git a/kernel/locking/mutex.c b/kernel/locking/mutex.c
index 09534628dc01..43b7f7e281a0 100644
--- a/kernel/locking/mutex.c
+++ b/kernel/locking/mutex.c
@@ -1023,6 +1023,9 @@ static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigne
wake_q_add(&wake_q, next);
}
+ if (trace_contended_release_enabled() && waiter)
+ trace_call__contended_release(lock);
+
if (owner & MUTEX_FLAG_HANDOFF)
__mutex_handoff(lock, next);
@@ -1220,6 +1223,7 @@ EXPORT_SYMBOL(ww_mutex_lock_interruptible);
EXPORT_TRACEPOINT_SYMBOL_GPL(contention_begin);
EXPORT_TRACEPOINT_SYMBOL_GPL(contention_end);
+EXPORT_TRACEPOINT_SYMBOL_GPL(contended_release);
/**
* atomic_dec_and_mutex_lock - return holding mutex if we dec to 0
diff --git a/kernel/locking/percpu-rwsem.c b/kernel/locking/percpu-rwsem.c
index f3ee7a0d6047..f7e152c40d6d 100644
--- a/kernel/locking/percpu-rwsem.c
+++ b/kernel/locking/percpu-rwsem.c
@@ -263,6 +263,9 @@ void percpu_up_write(struct percpu_rw_semaphore *sem)
{
rwsem_release(&sem->dep_map, _RET_IP_);
+ if (trace_contended_release_enabled() && wq_has_sleeper(&sem->waiters))
+ trace_call__contended_release(sem);
+
/*
* Signal the writer is done, no fast path yet.
*
@@ -292,6 +295,14 @@ EXPORT_SYMBOL_GPL(percpu_up_write);
void __percpu_up_read(struct percpu_rw_semaphore *sem)
{
lockdep_assert_preemption_disabled();
+ /*
+ * After percpu_up_write() completes, rcu_sync_is_idle() can still
+ * return false during the grace period, forcing readers into this
+ * slowpath. Only trace when a writer is actually waiting for
+ * readers to drain.
+ */
+ if (trace_contended_release_enabled() && rcuwait_active(&sem->writer))
+ trace_call__contended_release(sem);
/*
* slowpath; reader will only ever wake a single blocked
* writer.
diff --git a/kernel/locking/rtmutex.c b/kernel/locking/rtmutex.c
index 9147d6a31b78..28beae7d21fe 100644
--- a/kernel/locking/rtmutex.c
+++ b/kernel/locking/rtmutex.c
@@ -1470,6 +1470,7 @@ static void __sched rt_mutex_slowunlock(struct rt_mutex_base *lock)
raw_spin_lock_irqsave(&lock->wait_lock, flags);
}
+ trace_contended_release(lock);
/*
* The wakeup next waiter path does not suffer from the above
* race. See the comments there.
diff --git a/kernel/locking/rwbase_rt.c b/kernel/locking/rwbase_rt.c
index 82e078c0665a..2835c9ef9b3f 100644
--- a/kernel/locking/rwbase_rt.c
+++ b/kernel/locking/rwbase_rt.c
@@ -174,6 +174,8 @@ static void __sched __rwbase_read_unlock(struct rwbase_rt *rwb,
static __always_inline void rwbase_read_unlock(struct rwbase_rt *rwb,
unsigned int state)
{
+ if (trace_contended_release_enabled() && rt_mutex_owner(&rwb->rtmutex))
+ trace_call__contended_release(rwb);
/*
* rwb->readers can only hit 0 when a writer is waiting for the
* active readers to leave the critical section.
@@ -205,6 +207,8 @@ static inline void rwbase_write_unlock(struct rwbase_rt *rwb)
unsigned long flags;
raw_spin_lock_irqsave(&rtm->wait_lock, flags);
+ if (trace_contended_release_enabled() && rt_mutex_has_waiters(rtm))
+ trace_call__contended_release(rwb);
__rwbase_write_unlock(rwb, WRITER_BIAS, flags);
}
@@ -214,6 +218,8 @@ static inline void rwbase_write_downgrade(struct rwbase_rt *rwb)
unsigned long flags;
raw_spin_lock_irqsave(&rtm->wait_lock, flags);
+ if (trace_contended_release_enabled() && rt_mutex_has_waiters(rtm))
+ trace_call__contended_release(rwb);
/* Release it and account current as reader */
__rwbase_write_unlock(rwb, WRITER_BIAS - 1, flags);
}
diff --git a/kernel/locking/rwsem.c b/kernel/locking/rwsem.c
index bf647097369c..b9c180ac1eee 100644
--- a/kernel/locking/rwsem.c
+++ b/kernel/locking/rwsem.c
@@ -1387,6 +1387,8 @@ static inline void __up_read(struct rw_semaphore *sem)
rwsem_clear_reader_owned(sem);
tmp = atomic_long_add_return_release(-RWSEM_READER_BIAS, &sem->count);
DEBUG_RWSEMS_WARN_ON(tmp < 0, sem);
+ if (trace_contended_release_enabled() && (tmp & RWSEM_FLAG_WAITERS))
+ trace_call__contended_release(sem);
if (unlikely((tmp & (RWSEM_LOCK_MASK|RWSEM_FLAG_WAITERS)) ==
RWSEM_FLAG_WAITERS)) {
clear_nonspinnable(sem);
@@ -1413,8 +1415,10 @@ static inline void __up_write(struct rw_semaphore *sem)
preempt_disable();
rwsem_clear_owner(sem);
tmp = atomic_long_fetch_add_release(-RWSEM_WRITER_LOCKED, &sem->count);
- if (unlikely(tmp & RWSEM_FLAG_WAITERS))
+ if (unlikely(tmp & RWSEM_FLAG_WAITERS)) {
+ trace_contended_release(sem);
rwsem_wake(sem);
+ }
preempt_enable();
}
@@ -1437,8 +1441,10 @@ static inline void __downgrade_write(struct rw_semaphore *sem)
tmp = atomic_long_fetch_add_release(
-RWSEM_WRITER_LOCKED+RWSEM_READER_BIAS, &sem->count);
rwsem_set_reader_owned(sem);
- if (tmp & RWSEM_FLAG_WAITERS)
+ if (tmp & RWSEM_FLAG_WAITERS) {
+ trace_contended_release(sem);
rwsem_downgrade_wake(sem);
+ }
preempt_enable();
}
diff --git a/kernel/locking/semaphore.c b/kernel/locking/semaphore.c
index 74d41433ba13..233730c25933 100644
--- a/kernel/locking/semaphore.c
+++ b/kernel/locking/semaphore.c
@@ -230,6 +230,10 @@ void __sched up(struct semaphore *sem)
sem->count++;
else
__up(sem, &wake_q);
+
+ if (trace_contended_release_enabled() && !wake_q_empty(&wake_q))
+ trace_call__contended_release(sem);
+
raw_spin_unlock_irqrestore(&sem->lock, flags);
if (!wake_q_empty(&wake_q))
wake_up_q(&wake_q);
]
|
| 41/2 |
2026/07/25 23:17 |
llm |
expert |
0m
Model:
Tokens:
input: 40582
output: 15
thoughts: 1618
Thoughts: **Analysis of Lockless Read in `mutex.c`**
Alright, let's dive into this potentially problematic line of code in `kernel/locking/mutex.c`, specifically line 728: `first = lock->first_waiter == &waiter;`. This looks like a lockless read of `lock->first_waiter`, which raises the specter of a data race given that it could collide with writes in `__mutex_remove_waiter` or `__mutex_add_waiter`.
First, let's confirm that there aren't any other lockless reads of `lock->first_waiter`. I'll run through the call sites. Okay, after checking the references, `__mutex_add_waiter`, `__mutex_remove_waiter`, `__mutex_unlock_slowpath`, `__ww_waiter_first`, `__ww_waiter_last`, `__ww_waiter_next`, and `__ww_waiter_prev` all read `lock->first_waiter`, but crucially, they are all called with `lock->wait_lock` held. Only `ww_mutex_spin_on_owner` at line 372 is lockless, but it uses the `data_race()` annotation already. So, yes, line 728 is the only unannotated lockless read.
Now, is this race benign? Let's break it down:
1. The read determines whether the current waiter is the first in line (`first`).
2. `first` is passed to `__mutex_trylock_or_handoff(lock, first)`.
3. If `first` is read as `false` when it should be `true` (due to a concurrent removal), we won't set the handoff flag. We'll sleep and try again. In the next iteration, we'll read `first` correctly, setting the handoff flag then. A stale `false` read just delays the handoff by one iteration, which is safe.
4. If `first` is read as `true` when it's `false` (in `ww_mutex`), we'll set the `MUTEX_FLAG_HANDOFF` flag. The next unlock will hand off the lock to the *actual* first waiter (with the earlier stamp). If we're optimistic spinning, we'll immediately detect we're *not* the first waiter and terminate the loop. This, too, is safe.
5. Pointer reads are atomic, so no torn reads.
6. Compiler barriers in the loop prevent optimizations that could create issues.
Therefore, the race *is* benign.
However, even though benign, it's still a data race and should be annotated for clarity and to suppress KCSAN warnings. Given that `lock->first_waiter` is a shared variable, wrapping it in `data_race()` or `READ_ONCE()` is the right move. And since Peter Zijlstra already used `data_race(lock->first_waiter != waiter)` in the codebase, let's use the same style to improve consistency. Therefore, on line 728, we can write: `first = data_race(lock->first_waiter == &waiter);` or `first = data_race(lock->first_waiter) == &waiter;`
Okay, and now I'll call `set-results` with `Benign: true`.
|
| 42/2 |
2026/07/25 23:17 |
tool |
set-results |
0m
Args:
Results:
|
| 43/2 |
2026/07/25 23:17 |
llm |
expert |
0m
Model:
Tokens:
input: 42988
output: 845
thoughts: 577
Thoughts: **My Analysis of the Data Race in `__mutex_lock_common` and `__mutex_remove_waiter`**
Okay, excellent. Let's craft a really solid, clear, and comprehensive explanation here. We've got all the pieces. I need to make this crystal clear.
First, the core of the issue: We're looking at a data race between `__mutex_lock_common` and `__mutex_remove_waiter`, specifically around the `lock->first_waiter` pointer.
Here's the breakdown:
1. **The Race:** Thread A (Task 10859) is in the slow path of `__mutex_lock_common`. It has woken up and is now reading `lock->first_waiter` locklessly (outside the protection of `lock->wait_lock`) at line 728: `first = lock->first_waiter == &waiter;` Meanwhile, Thread B (Task 10862) is in `__mutex_remove_waiter` and, under `lock->wait_lock`, modifies `lock->first_waiter` at line 249: `lock->first_waiter = list_next_entry(waiter, list);` The KCSAN tool is, quite rightly, flagging this as a data race because Thread A doesn't hold `lock->wait_lock` when it's reading `lock->first_waiter`.
2. **Synchronization Context:** We have two threads interacting with the same shared memory location, one reader locklessly and one writer, under a lock. This is exactly the kind of situation KCSAN is designed to detect.
3. **My Classification:** **BENIGN** (Truly Benign). This is a textbook example of a *benign* data race, where the race condition does not compromise correctness.
4. **Detailed Reasoning:**
* **Stale `false` Read:** A stale read where `first` is `false` is perfectly safe. It simply means that Thread A might delay by *one* loop iteration before recognizing it is the "first waiter". This is suboptimal, sure, but it's not incorrect. The handoff will eventually be set correctly. It's just a slight performance hit in a highly contended scenario.
* **Stale `true` Read:** A stale read where `first` is `true` is also safe, *especially* in `ww_mutex`. If a waiter with an earlier timestamp is inserted, the lock handoff will still proceed to the correct first waiter and the optimistic spin will abort. The `data_race(lock->first_waiter != waiter)` check immediately takes care of that, preventing any actual problem.
* **Torn Reads:** Torn reads are *impossible* in our scenario. Pointer reads are guaranteed to be atomic on all our supported architectures. We don't have to worry about the pointer being partially updated.
* **Compiler Optimization Barriers:** The compiler barriers within the slow-path loop itself (think `raw_spin_lock`, `schedule_preempt_disabled`, etc.) effectively block any aggressive compiler optimizations like load merging or hoisting that could cause the race to become more problematic. The compiler is being made to follow the intended memory semantics.
5. **Recommended Annotation:** To keep KCSAN happy (and make our intent very clear to future maintainers), we should wrap the offending line in a `data_race()` call. This will suppress the warning and document the intentional lockless access, which is consistent with how it's handled in `ww_mutex_spin_on_owner()` (line 372).
Here's the code change I'm suggesting:
```c
first = data_race(lock->first_waiter == &waiter);
```
That's it. A nice, well-reasoned, and practically actionable response.
|
| 44/1 |
2026/07/25 23:17 |
action |
format-explanation |
0m
Results: map[Explanation:### Race Summary
`__mutex_lock_common` vs `__mutex_remove_waiter` on `lock->first_waiter`.
---
### Synchronization Context
* **Thread A (Task 10859):** Executing the slowpath of `__mutex_lock_common`.
After waking up from `schedule_preempt_disabled()`, it reads
`lock->first_waiter` locklessly (outside of `lock->wait_lock`) to check if it
has become the first waiter on the list:
```c
first = lock->first_waiter == &waiter;
```
* **Thread B (Task 10862):** Removing a waiter in `__mutex_remove_waiter` under
the protection of `lock->wait_lock`:
```c
lock->first_waiter = list_next_entry(waiter, list);
```
Because Thread A performs the read without holding `lock->wait_lock`, KCSAN
flags this concurrent access as a data race.
---
### Final Classification: **BENIGN**
#### **Reasoning:**
The logic is structurally tolerant to stale or concurrent reads of
`lock->first_waiter`:
1. **Stale `false` Read:**
If Thread A reads `first` as `false` when it has actually just become `true`
(due to the previous first waiter removing itself concurrently):
* `first` is passed to `__mutex_trylock_or_handoff(lock, first)`.
* Since `first` is `false`, the `MUTEX_FLAG_HANDOFF` flag is not set in this
iteration.
* Thread A will call `schedule_preempt_disabled()` and sleep again.
* In the next iteration, Thread A will read `first` again, see it as `true`,
and correctly set the handoff flag.
* Thus, a stale `false` read only delays the handoff flag setting by one
iteration, which is a safe, sub-optimal but correct slow-path behavior.
2. **Stale `true` Read:**
If Thread A reads `first` as `true` when it is actually `false` (which can
only happen in `ww_mutex` if a waiter with an earlier stamp is inserted
before us after we read `first` as `true` but before we acquire the lock):
* Thread A will set the `MUTEX_FLAG_HANDOFF` flag.
* The next unlock will hand off the lock to the first waiter on the list.
Since the first waiter on the list is the newly inserted waiter with the
earlier stamp, the lock is correctly handed off to that waiter.
* If Thread A also enters optimistic spinning because `first` was `true`, the
optimistic spinning loop (`ww_mutex_spin_on_owner`) will immediately detect
that we are no longer the first waiter (using the
`data_race(lock->first_waiter != waiter)` check) and terminate safely.
3. **No Torn Reads:**
Pointer reads are atomic on all supported architectures, so there is no risk
of a torn read.
4. **No Compiler Optimizations/Livelocks:**
Compiler optimizations such as load merging or hoisting out of the loop are
prevented by the compiler barriers (e.g., `raw_spin_lock`,
`schedule_preempt_disabled`, etc.) present in the loop.
---
### Recommended Annotations
To suppress the KCSAN warning and document the intentional lockless access, the
read should be wrapped in `data_race()`, consistent with how it is done in
`ww_mutex_spin_on_owner()` (line 372):
```diff
- first = lock->first_waiter == &waiter;
+ first = data_race(lock->first_waiter == &waiter);
```]
|