| 0/0 |
2026/09/23 15:43 |
flow |
assessment-kcsan |
5h09m
Results: map[Benign:false Explanation:### Race Summary
`__mmput` vs `copy_mm` / `dup_mm` on `oldmm` (specifically `oldmm->mmlist`).
- **Task 21217 (CPU 1)**: Executing `exit_mm()` -> `mmput()` -> `__mmput()`. At
line 1198 (`kernel/fork.c`), it modifies `mm->mmlist` under
`spin_lock(&mmlist_lock)`.
- **Task 3876 (CPU 0)**: Executing `kernel_clone()` -> `copy_process()` ->
`copy_mm()` -> `dup_mm()`. At line 1537 (`kernel/fork.c`), it performs
`memcpy(mm, oldmm, sizeof(*mm))` which reads the entire `oldmm` structure (1728
bytes, including `oldmm->mmlist`) without holding `mmlist_lock` or `mmap_lock`.
---
### Synchronization Context
In `__mmput()`, `list_del(&mm->mmlist)` is executed with `mmlist_lock` held.
However, in `dup_mm()`, `memcpy(mm, oldmm, sizeof(*mm))` reads the entire
`struct mm_struct` without locking (neither `mmlist_lock` nor `mmap_lock` is
held; `dup_mmap` takes `mmap_write_lock_killable(oldmm)` only after `memcpy()`
and `mm_init()`).
More fundamentally, for `__mmput()` to be running on CPU 1,
`atomic_dec_and_test(&mm->mm_users)` in `mmput()` evaluated to `true`,
indicating `mm->mm_users` reached 0. Concurrently, Task 3876 on CPU 0 is cloning
with `oldmm == current->mm` and dereferencing / copying `oldmm`. This indicates
an address space refcount/lifecycle violation.
---
### Final Classification
**HARMFUL**
---
### Failure Reasoning
1. **Teardown & Use-After-Free (UAF):**
When `mmput()` drops `mm_users` to 0, `__mmput()` proceeds to tear down the
entire address space:
- `exit_mmap(mm)` dismantles VMAs and tears down page tables
(`free_pgtables`, `tear_down_vmas`, `__mt_destroy(&mm->mm_mt)`).
- `futex_hash_free(mm)` and `mmdrop(mm)` release and potentially free the
underlying memory.
Concurrently, `dup_mm()` on CPU 0 executes `dup_mmap(mm, oldmm)`. It attempts
to walk `oldmm->mm_mt` via `__mt_dup()`, access `mpnt` VMAs, and copy page
tables (`copy_page_range()`). As `oldmm` is actively torn down and destroyed,
this results in Use-After-Free, page table corruption, kernel panic, or
crash.
2. **Torn/Corrupted Memory Copy:**
`memcpy(mm, oldmm, sizeof(*mm))` copies pointers and fields that are actively
being modified by `__mmput()` and its callees (`exit_aio`, `ksm_exit`,
`khugepaged_exit`, `exit_mmap`, `list_del`). The newly created `mm` ends up
with corrupted or stale pointers to resources already freed or unlinked on
the other CPU.
#### Failure Interleaving
```text
CPU 0 (Task 3876 - clone) CPU 1 (Task 21217 - do_exit)
------------------------- ----------------------------
do_exit()
exit_mm()
current->mm = NULL;
mmput(mm)
atomic_dec_and_test(&mm->mm_users)
== true
__mmput(mm)
exit_mmap(mm)
// Tears down VMAs and page
tables
kernel_clone()
copy_process()
copy_mm()
dup_mm(tsk, current->mm)
// memcpy reads oldmm while
// __mmput modifies it
memcpy(mm, oldmm, sizeof(*mm));
spin_lock(&mmlist_lock);
list_del(&mm->mmlist); // <---
WRITE
spin_unlock(&mmlist_lock);
futex_hash_free(mm);
mmdrop(mm); // frees mm /
structures
mm_init(mm, tsk);
dup_mmap(mm, oldmm);
mmap_write_lock_killable(oldmm);
__mt_dup(&oldmm->mm_mt, ...); // -> CRASH / UAF: maple tree & VMAs
already destroyed!
```
---
### Recommended Fix
The root issue is a lifecycle/refcount violation where `mm_users` is allowed to
drop to 0 while another task is still referencing `current->mm` in
`copy_process()`. Ensure proper `mm_users` accounting across asynchronous
tasks/kthreads borrowing or referencing `mm` (e.g. via `kthread_use_mm` /
`mmget_not_zero`) so that `__mmput()` cannot execute while `current->mm` is
concurrently accessed during `clone`.]
|
| 1/1 |
2026/09/23 15:43 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/c96e9842a2e42f5340b2f4b9b533b1911fdc63ee]
|
| 2/1 |
2026/09/23 15:43 |
action |
kernel-builder |
0m
Results: map[KernelObj:/app/workdir/cache/build/65e5a180555a10aefd0f39eefc3c4f90f0d14121]
|
| 3/1 |
2026/09/23 15:43 |
action |
codesearch-prepare |
0m
Results: map[Index:codesearch-index]
|
| 4/1 |
2026/09/23 15:44 |
agent |
expert |
5h08m
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 __mmput / copy_mm
write to 0xffff8881046681f8 of 8 bytes by task 21217 on cpu 1:
__list_del include/linux/list.h:241 [inline]
__list_del_entry include/linux/list.h:264 [inline]
list_del include/linux/list.h:275 [inline]
__mmput+0xe2/0x1c0 kernel/fork.c:1198
mmput+0x40/0x50 kernel/fork.c:1216
exit_mm+0x113/0x1a0 kernel/exit.c:618
do_exit+0x438/0x1510 kernel/exit.c:1000
do_group_exit+0xfe/0x140 kernel/exit.c:1155
get_signal+0xe07/0xf10 kernel/signal.c:3112
arch_do_signal_or_restart+0x96/0x480 arch/x86/kernel/signal.c:337
__exit_to_user_mode_loop kernel/entry/common.c:66 [inline]
exit_to_user_mode_loop+0x15d/0x8c0 kernel/entry/common.c:101
__exit_to_user_mode_prepare include/linux/irq-entry-common.h:207 [inline]
syscall_exit_to_user_mode_prepare include/linux/irq-entry-common.h:230 [inline]
syscall_exit_to_user_mode include/linux/entry-common.h:343 [inline]
do_syscall_64+0x212/0x360 arch/x86/entry/syscall_64.c:89
entry_SYSCALL_64_after_hwframe+0x77/0x7f
read to 0xffff888104668000 of 1728 bytes by task 3876 on cpu 0:
dup_mm kernel/fork.c:1537 [inline]
copy_mm+0xd6/0x340 kernel/fork.c:1595
copy_process+0x108a/0x2350 kernel/fork.c:2310
kernel_clone+0x1c0/0x5f0 kernel/fork.c:2769
__do_sys_clone kernel/fork.c:2911 [inline]
__se_sys_clone kernel/fork.c:2895 [inline]
__x64_sys_clone+0x143/0x180 kernel/fork.c:2895
x64_sys_call+0x2479/0x2550 arch/x86/include/generated/asm/syscalls_64.h:57
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x112/0x360 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 3876 Comm: syz-executor Not tainted syzkaller #0 PREEMPT(lazy)
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/24/2026
==================================================================
Reply: ### Race Summary
`__mmput` vs `copy_mm` / `dup_mm` on `oldmm` (specifically `oldmm->mmlist`).
- **Task 21217 (CPU 1)**: Executing `exit_mm()` -> `mmput()` -> `__mmput()`. At line 1198 (`kernel/fork.c`), it modifies `mm->mmlist` under `spin_lock(&mmlist_lock)`.
- **Task 3876 (CPU 0)**: Executing `kernel_clone()` -> `copy_process()` -> `copy_mm()` -> `dup_mm()`. At line 1537 (`kernel/fork.c`), it performs `memcpy(mm, oldmm, sizeof(*mm))` which reads the entire `oldmm` structure (1728 bytes, including `oldmm->mmlist`) without holding `mmlist_lock` or `mmap_lock`.
---
### Synchronization Context
In `__mmput()`, `list_del(&mm->mmlist)` is executed with `mmlist_lock` held. However, in `dup_mm()`, `memcpy(mm, oldmm, sizeof(*mm))` reads the entire `struct mm_struct` without locking (neither `mmlist_lock` nor `mmap_lock` is held; `dup_mmap` takes `mmap_write_lock_killable(oldmm)` only after `memcpy()` and `mm_init()`).
More fundamentally, for `__mmput()` to be running on CPU 1, `atomic_dec_and_test(&mm->mm_users)` in `mmput()` evaluated to `true`, indicating `mm->mm_users` reached 0. Concurrently, Task 3876 on CPU 0 is cloning with `oldmm == current->mm` and dereferencing / copying `oldmm`. This indicates an address space refcount/lifecycle violation.
---
### Final Classification
**HARMFUL**
---
### Failure Reasoning
1. **Teardown & Use-After-Free (UAF):**
When `mmput()` drops `mm_users` to 0, `__mmput()` proceeds to tear down the entire address space:
- `exit_mmap(mm)` dismantles VMAs and tears down page tables (`free_pgtables`, `tear_down_vmas`, `__mt_destroy(&mm->mm_mt)`).
- `futex_hash_free(mm)` and `mmdrop(mm)` release and potentially free the underlying memory.
Concurrently, `dup_mm()` on CPU 0 executes `dup_mmap(mm, oldmm)`. It attempts to walk `oldmm->mm_mt` via `__mt_dup()`, access `mpnt` VMAs, and copy page tables (`copy_page_range()`). As `oldmm` is actively torn down and destroyed, this results in Use-After-Free, page table corruption, kernel panic, or crash.
2. **Torn/Corrupted Memory Copy:**
`memcpy(mm, oldmm, sizeof(*mm))` copies pointers and fields that are actively being modified by `__mmput()` and its callees (`exit_aio`, `ksm_exit`, `khugepaged_exit`, `exit_mmap`, `list_del`). The newly created `mm` ends up with corrupted or stale pointers to resources already freed or unlinked on the other CPU.
#### Failure Interleaving
```text
CPU 0 (Task 3876 - clone) CPU 1 (Task 21217 - do_exit)
------------------------- ----------------------------
do_exit()
exit_mm()
current->mm = NULL;
mmput(mm)
atomic_dec_and_test(&mm->mm_users) == true
__mmput(mm)
exit_mmap(mm)
// Tears down VMAs and page tables
kernel_clone()
copy_process()
copy_mm()
dup_mm(tsk, current->mm)
// memcpy reads oldmm while
// __mmput modifies it
memcpy(mm, oldmm, sizeof(*mm));
spin_lock(&mmlist_lock);
list_del(&mm->mmlist); // <--- WRITE
spin_unlock(&mmlist_lock);
futex_hash_free(mm);
mmdrop(mm); // frees mm / structures
mm_init(mm, tsk);
dup_mmap(mm, oldmm);
mmap_write_lock_killable(oldmm);
__mt_dup(&oldmm->mm_mt, ...); // -> CRASH / UAF: maple tree & VMAs already destroyed!
```
---
### Recommended Fix
The root issue is a lifecycle/refcount violation where `mm_users` is allowed to drop to 0 while another task is still referencing `current->mm` in `copy_process()`. Ensure proper `mm_users` accounting across asynchronous tasks/kthreads borrowing or referencing `mm` (e.g. via `kthread_use_mm` / `mmget_not_zero`) so that `__mmput()` cannot execute while `current->mm` is concurrently accessed during `clone`.
|
| 5/2 |
2026/09/23 15:44 |
llm |
expert |
0m
Model:
Tokens:
input: 6298
output: 34
thoughts: 622
Thoughts: **Analyzing a KCSAN Data Race Report**
Okay, so I've got a KCSAN data race report to analyze. First, let's make sure this is safe; this is a standard concurrency debugging exercise and bug triage related to the Linux kernel, so no malicious requests or exploit generation is involved. We're good to proceed.
Now, let's get into the details. The report says there's a data race in `__mmput` and `copy_mm`. The report clearly details a write operation: a write to address `0xffff8881046681f8` of 8 bytes performed by task 21217 on CPU 1. The call stack shows this write happens within `__mmput`, which then calls `mmput`, and then `exit_mm`, and so on.
On the read side, there's a read from address `0xffff888104668000` of 1728 bytes by task 3876 on CPU 0. The call stack here traces through `dup_mm` which calls `copy_mm`, and that leads to `kernel_clone` further down.
A quick check of the addresses reveals that the write and read addresses are related, which is what we would expect in a data race. The write is only 504 bytes offset from the start of the read. The read is 1728 bytes. The size of the read is important: that looks a lot like the size of a `struct mm_struct`, or something large which could indicate a `memcpy` or similar large read operation in `dup_mm` and then `copy_mm`.
So, it seems like `__mmput` might be messing with the same memory that `copy_mm` (called via `dup_mm`) is reading. We will want to look at `kernel/fork.c` around line 1198 (where the write happens in `__mmput`) and line 1537 (where the read happens, in `dup_mm`, which calls `copy_mm`) and see what's going on.
|
| 6/2 |
2026/09/23 15:44 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1180 LineCount:40]
Results: map[Contents:1180: memset(mm, 0, sizeof(*mm));
1181: return mm_init(mm, current);
1182: }
1183: EXPORT_SYMBOL_IF_KUNIT(mm_alloc);
1184:
1185: static inline void __mmput(struct mm_struct *mm)
1186: {
1187: VM_BUG_ON(atomic_read(&mm->mm_users));
1188:
1189: uprobe_clear_state(mm);
1190: exit_aio(mm);
1191: ksm_exit(mm);
1192: khugepaged_exit(mm); /* must run before exit_mmap */
1193: exit_mmap(mm);
1194: mm_put_huge_zero_folio(mm);
1195: set_mm_exe_file(mm, NULL);
1196: if (!list_empty(&mm->mmlist)) {
1197: spin_lock(&mmlist_lock);
1198: list_del(&mm->mmlist);
1199: spin_unlock(&mmlist_lock);
1200: }
1201: if (mm->binfmt)
1202: module_put(mm->binfmt->module);
1203: lru_gen_del_mm(mm);
1204: futex_hash_free(mm);
1205: mmdrop(mm);
1206: }
1207:
1208: /*
1209: * Decrement the use count and release all resources for an mm.
1210: */
1211: void mmput(struct mm_struct *mm)
1212: {
1213: might_sleep();
1214:
1215: if (atomic_dec_and_test(&mm->mm_users))
1216: __mmput(mm);
1217: }
1218: EXPORT_SYMBOL_GPL(mmput);
1219:
]
|
| 7/2 |
2026/09/23 15:44 |
llm |
expert |
0m
Model:
Tokens:
input: 7998
output: 34
thoughts: 136
Thoughts: **Analyzing Memory Management in the Kernel**
Okay, let's dive in. I'm focusing on lines 1196-1200 here, that snippet dealing with `mm->mmlist`. Specifically, this `list_del(&mm->mmlist)` call. My immediate thought is, "This is modifying the `mm` structure itself." I need to understand the implications of this. I'm noting that the memory location 0xffff8881046681f8, specifically, is within the `mm` struct.
To fully grasp the context, I need to check how `mm` is duplicated. I suspect there's a connection, potentially related to copying or sharing memory regions. So, I need to check out the `dup_mm` function, which I believe is around line 1537. That's the next logical step. I'll need to see how the `mmlist` is handled there during the duplication process, if at all. This should provide some insight into what's happening.
|
| 8/2 |
2026/09/23 15:44 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1520 LineCount:45]
Results: map[Contents:1520: * @oldmm: the mm to duplicate.
1521: *
1522: * Allocates a new mm structure and duplicates the provided @oldmm structure
1523: * content into it.
1524: *
1525: * Return: the duplicated mm or NULL on failure.
1526: */
1527: static struct mm_struct *dup_mm(struct task_struct *tsk,
1528: struct mm_struct *oldmm)
1529: {
1530: struct mm_struct *mm;
1531: int err;
1532:
1533: mm = allocate_mm();
1534: if (!mm)
1535: goto fail_nomem;
1536:
1537: memcpy(mm, oldmm, sizeof(*mm));
1538:
1539: if (!mm_init(mm, tsk))
1540: goto fail_nomem;
1541:
1542: uprobe_start_dup_mmap();
1543: err = dup_mmap(mm, oldmm);
1544: if (err)
1545: goto free_pt;
1546: uprobe_end_dup_mmap();
1547:
1548: mm->hiwater_rss = get_mm_rss(mm);
1549: mm->hiwater_vm = mm->total_vm;
1550:
1551: if (mm->binfmt && !try_module_get(mm->binfmt->module))
1552: goto free_pt;
1553:
1554: return mm;
1555:
1556: free_pt:
1557: /* don't put binfmt in mmput, we haven't got module yet */
1558: mm->binfmt = NULL;
1559: mm_init_owner(mm, NULL);
1560: mmput(mm);
1561: if (err)
1562: uprobe_end_dup_mmap();
1563:
1564: fail_nomem:
]
|
| 9/2 |
2026/09/23 15:44 |
llm |
expert |
0m
Model:
Tokens:
input: 9008
output: 34
thoughts: 42
Thoughts: Okay, here's my interpretation of that code snippet, delivered as if it's my own thought process:
**Diving into that Memory Copy**
Alright, let's zoom in on line 1537. That `memcpy` call... `memcpy(mm, oldmm, sizeof(*mm));`... that's where things get interesting. I suspect that's a *direct* memory copy, so let's see why it's there. I need to understand what's being copied, and why. I'll need some more context.
Now, let's jump over to the `copy_mm` function, which I seem to recall is around line 1595. I'm guessing that's the *source* of this copy, so it must be called before that call to `memcpy`. I need to figure out how this function sets up the "oldmm" structure. I'm betting `copy_mm` performs some initialization of a memory descriptor and `memcpy` is used to efficiently duplicate the descriptor later. The key is in understanding *what* constitutes `mm` in this context. And I know I need to be careful with the implications of making a copy, particularly with how shared memory is treated. Let's see if this `copy_mm` is doing any clever tricks, or if it's a straightforward duplication.
|
| 10/2 |
2026/09/23 15:44 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1580 LineCount:40]
Results: map[Contents:1580: tsk->active_mm = NULL;
1581:
1582: /*
1583: * Are we cloning a kernel thread?
1584: *
1585: * We need to steal a active VM for that..
1586: */
1587: oldmm = current->mm;
1588: if (!oldmm)
1589: return 0;
1590:
1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
1597: return -ENOMEM;
1598: }
1599:
1600: tsk->mm = mm;
1601: tsk->active_mm = mm;
1602: return 0;
1603: }
1604:
1605: static int copy_exec_state(u64 clone_flags, struct task_struct *tsk)
1606: {
1607: struct task_exec_state *exec_state;
1608:
1609: /* CLONE_VM siblings refcount-share the parent's exec_state. */
1610: if (clone_flags & CLONE_VM) {
1611: exec_state = rcu_dereference_protected(current->exec_state, true);
1612: refcount_inc(&exec_state->count);
1613: rcu_assign_pointer(tsk->exec_state, exec_state);
1614: return 0;
1615: }
1616:
1617: /* Everyone else inherits a fresh copy. */
1618: return task_exec_state_copy(tsk);
1619: }
]
|
| 11/2 |
2026/09/23 15:44 |
llm |
expert |
0m
Model:
Tokens:
input: 9921
output: 32
thoughts: 234
Thoughts: **Analyzing a Memory Management Conundrum**
Okay, here's what I'm seeing: Task 3876 is deep in the weeds with a `fork()` or `clone()` operation, specifically calling `kernel_clone` which traces back to `copy_mm` through the standard process. It looks like it's a clone *without* `CLONE_VM`, which means a new address space. This leads me to `dup_mm(tsk, current->mm)`, where `current->mm` represents the `oldmm` we are forking.
Now, the plot thickens. Simultaneously, Task 21217 is kicking off `do_exit`, and that's going down the `exit_mm` rabbit hole, eventually culminating in `mmput` and `__mmput`. This is where my expertise jumps into action. I'm seeing a potential collision! How can Task 21217 be actively engaged in freeing an `mm` using `__mmput(mm)` while, at the exact same time, Task 3876 is attempting to *duplicate* the very same `mm` using `dup_mm`? This violates my expectations.
Wait... could they somehow share the same memory management structure? Could it be a shared memory situation? In other words, are these threads sharing the same memory space? Maybe a `CLONE_VM` thread situation, perhaps related to a threading library like pthreads?
Okay, let's explore this further. If two threads *do* share an `mm`, like in a `CLONE_VM` context...
Let's assume Thread A is exiting and going through `exit_mm()`. That is where I will focus my efforts to fully grok the situation.
|
| 12/2 |
2026/09/23 15:45 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:exit_mm]
Results: map[SourceCode: 580: /*
581: * Turn us into a lazy TLB process if we
582: * aren't already..
583: */
584: static void exit_mm(void)
585: {
586: struct mm_struct *mm = current->mm;
587:
588: mm_exit_exec_release(current, mm);
589: if (!mm)
590: return;
591:
592: exit_mm_sched_cache(mm);
593:
594: mmap_read_lock(mm);
595: mmgrab_lazy_tlb(mm);
596: BUG_ON(mm != current->active_mm);
597: /* more a memory barrier than a real lock */
598: task_lock(current);
599: /*
600: * When a thread stops operating on an address space, the loop
601: * in membarrier_private_expedited() may not observe that
602: * tsk->mm, and the loop in membarrier_global_expedited() may
603: * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
604: * rq->membarrier_state, so those would not issue an IPI.
605: * Membarrier requires a memory barrier after accessing
606: * user-space memory, before clearing tsk->mm or the
607: * rq->membarrier_state.
608: */
609: smp_mb__after_spinlock();
610: local_irq_disable();
611: current->mm = NULL;
612: membarrier_update_current_mm(NULL);
613: enter_lazy_tlb(mm, current);
614: local_irq_enable();
615: task_unlock(current);
616: mmap_read_unlock(mm);
617: mm_update_next_owner(mm);
618: mmput(mm);
619: if (test_thread_flag(TIF_MEMDIE))
620: exit_oom_victim();
621: }
SourceFile:kernel/exit.c]
|
| 13/2 |
2026/09/23 15:45 |
llm |
expert |
0m
Model:
Tokens:
input: 11211
output: 39
thoughts: 1036
Thoughts: **Debugging a Memory Management Issue**
Okay, here's what I'm thinking. I'm staring at this `exit_mm` code and something feels off. Specifically, this `mmput(mm)` call. It calls `__mmput(mm)` only when `atomic_dec_and_test(&mm->mm_users)` returns true, meaning the user count has dropped to zero. But wait a minute...how can `mm->mm_users` reach zero if task 3876 currently *has* `current->mm == mm`? This should have prevented the mm from being freed!
Could task 3876 be a thread within the same process, sharing the memory space? I'm checking, and it looks like task 21217 also did the same exit path, and is exiting, it calls `do_group_exit`. Okay, so it looks like 21217 exited. Does that mean 3876 shares the memory with it? It makes the situation possible. I need to know if 3876 is in the same thread group or shares the mm? Assuming it does, and 3876 *does* have `current->mm == mm`, it still doesn't explain how 21217 could decrement `mm->mm_users` to zero. I think I'm missing something fundamental about the MM usage.
Okay, let me think this through. When a thread is created with `CLONE_VM`, the `copy_mm` function *should* increment `mm_users` with `mmget(oldmm)`. So *every* thread sharing the mm should contribute to the user count. Then why did this go to zero? Did 3876 *already* exit its memory space, which seems like a problem since it's running `copy_process` now. This does not make sense! I need to know more about the relationship of the two tasks.
What if 3876 is *not* a `CLONE_VM` thread? What if it's doing something else entirely? Could `current->mm` in 3876 *still* be the same `mm`? Let's check the memory addresses directly to be certain. I'm checking the addresses now... Okay, I see `0xffff8881046681f8` and the mm struct starts at `0xffff888104668000`, 1728 bytes. That means the second is the start of the mm struct, and the first is inside the mm struct memory! Let's just confirm `0xffff8881046681f8` is in the mm struct.
Okay, 0x1f8 is 504. The struct is 1728 bytes or 0x6c0. 0x1f8 is less than 0x6c0. Yes! `0xffff8881046681f8` is inside! Now, let's confirm the layout of the `mm_struct` to figure out what that offset refers to, and confirm this is a valid mm struct. I'm going to look up the offset to be certain!
|
| 14/2 |
2026/09/23 15:45 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:kernel/fork.c FieldOffset:504 Name:mm_struct]
Results: map[Fields:[map[Name: OffsetBits:0 SizeBits:13824]]]
|
| 15/2 |
2026/09/23 15:45 |
llm |
expert |
0m
Model:
Tokens:
input: 13027
output: 32
thoughts: 12
Thoughts: Here's a summary of my mental process:
**Diving Deep into `mm_struct` Fields**
Alright, let's break this down. The objective is clear: I need to get a comprehensive understanding of the `mm_struct`. It's fundamental, a core data structure, and therefore I need to have a very detailed look at its components. This isn't just a casual glance; I'm going to meticulously examine *every* field within the `mm_struct`. I want a complete inventory, a solid grasp of what each attribute represents and, most importantly, how they all interrelate. This knowledge is crucial for understanding memory management. This includes understanding the impact of these components on performance, security, and stability of the system.
|
| 16/2 |
2026/09/23 15:45 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_struct]
Results: map[Fields:[map[Name: OffsetBits:0 SizeBits:13824] map[Name:flexible_array OffsetBits:13824 SizeBits:0]]]
|
| 17/2 |
2026/09/23 15:45 |
llm |
expert |
0m
Model:
Tokens:
input: 13284
output: 36
thoughts: 38
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing the Anonymous Struct within `mm_struct`**
Okay, so the output I'm seeing has an anonymous struct or, possibly, a union lurking within `mm_struct`. That's not entirely unexpected, but I need to understand what it *is* and why it's there. I'm going to quickly reference `include/linux/mm_types.h`. I'll want to review the complete definition of `struct mm_struct` to pinpoint this anonymous structure. I'm looking for the context of this inner data, and any potential implications for memory management or task context switching based on its design. Knowing the specifics of that nested struct, and how it relates to the larger mm_struct, is key to comprehending this output fully.
|
| 18/2 |
2026/09/23 15:45 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/mm_types.h Name:mm_struct]
Results: map[SourceCode:1175: struct mm_struct {
1176: struct {
1177: /*
1178: * Fields which are often written to are placed in a separate
1179: * cache line.
1180: */
1181: struct {
1182: /**
1183: * @mm_count: The number of references to &struct
1184: * mm_struct (@mm_users count as 1).
1185: *
1186: * Use mmgrab()/mmdrop() to modify. When this drops to
1187: * 0, the &struct mm_struct is freed.
1188: */
1189: atomic_t mm_count;
1190: } ____cacheline_aligned_in_smp;
1191:
1192: struct maple_tree mm_mt;
1193:
1194: unsigned long mmap_base; /* base of mmap area */
1195: unsigned long mmap_legacy_base; /* base of mmap area in bottom-up allocations */
1196: #ifdef CONFIG_HAVE_ARCH_COMPAT_MMAP_BASES
1197: /* Base addresses for compatible mmap() */
1198: unsigned long mmap_compat_base;
1199: unsigned long mmap_compat_legacy_base;
1200: #endif
1201: unsigned long task_size; /* size of task vm space */
1202: pgd_t * pgd;
1203:
1204: #ifdef CONFIG_MEMBARRIER
1205: /**
1206: * @membarrier_state: Flags controlling membarrier behavior.
1207: *
1208: * This field is close to @pgd to hopefully fit in the same
1209: * cache-line, which needs to be touched by switch_mm().
1210: */
1211: atomic_t membarrier_state;
1212: #endif
1213:
1214: /**
1215: * @mm_users: The number of users including userspace.
1216: *
1217: * Use mmget()/mmget_not_zero()/mmput() to modify. When this
1218: * drops to 0 (i.e. when the task exits and there are no other
1219: * temporary reference holders), we also release a reference on
1220: * @mm_count (which may then free the &struct mm_struct if
1221: * @mm_count also drops to 0).
1222: */
1223: atomic_t mm_users;
1224:
1225: /* MM CID related storage */
1226: struct mm_mm_cid mm_cid;
1227:
1228: /* sched_cache related statistics */
1229: struct sched_cache_stat sc_stat;
1230: #ifdef CONFIG_MMU
1231: atomic_long_t pgtables_bytes; /* size of all page tables */
1232: #endif
1233: int map_count; /* number of VMAs */
1234:
1235: spinlock_t page_table_lock; /* Protects page tables and some
1236: * counters
1237: */
1238: /*
1239: * Typically the current mmap_lock's offset is 56 bytes from
1240: * the last cacheline boundary, which is very optimal, as
1241: * its two hot fields 'count' and 'owner' sit in 2 different
1242: * cachelines, and when mmap_lock is highly contended, both
1243: * of the 2 fields will be accessed frequently, current layout
1244: * will help to reduce cache bouncing.
1245: *
1246: * So please be careful with adding new fields before
1247: * mmap_lock, which can easily push the 2 fields into one
1248: * cacheline.
1249: */
1250: struct rw_semaphore mmap_lock;
1251:
1252: struct list_head mmlist; /* List of maybe swapped mm's. These
1253: * are globally strung together off
1254: * init_mm.mmlist, and are protected
1255: * by mmlist_lock
1256: */
1257: #ifdef CONFIG_PER_VMA_LOCK
1258: struct rcuwait vma_writer_wait;
1259: /*
1260: * This field has lock-like semantics, meaning it is sometimes
1261: * accessed with ACQUIRE/RELEASE semantics.
1262: * Roughly speaking, incrementing the sequence number is
1263: * equivalent to releasing locks on VMAs; reading the sequence
1264: * number can be part of taking a read lock on a VMA.
1265: * Incremented every time mmap_lock is write-locked/unlocked.
1266: * Initialized to 0, therefore odd values indicate mmap_lock
1267: * is write-locked and even values that it's released.
1268: *
1269: * Can be modified under write mmap_lock using RELEASE
1270: * semantics.
1271: * Can be read with no other protection when holding write
1272: * mmap_lock.
1273: * Can be read with ACQUIRE semantics if not holding write
1274: * mmap_lock.
1275: */
1276: seqcount_t mm_lock_seq;
1277: #endif
1278: struct futex_mm_data futex;
1279:
1280: unsigned long hiwater_rss; /* High-watermark of RSS usage */
1281: unsigned long hiwater_vm; /* High-water virtual memory usage */
1282:
1283: unsigned long total_vm; /* Total pages mapped */
1284: unsigned long locked_vm; /* Pages that have PG_mlocked set */
1285: atomic64_t pinned_vm; /* Refcount permanently increased */
1286: unsigned long data_vm; /* VM_WRITE & ~VM_SHARED & ~VM_STACK */
1287: unsigned long exec_vm; /* VM_EXEC & ~VM_WRITE & ~VM_STACK */
1288: unsigned long stack_vm; /* VM_STACK */
1289: union {
1290: /* Temporary while VMA flags are being converted. */
1291: vm_flags_t def_flags;
1292: vma_flags_t def_vma_flags;
1293: };
1294:
1295: /**
1296: * @write_protect_seq: Locked when any thread is write
1297: * protecting pages mapped by this mm to enforce a later COW,
1298: * for instance during page table copying for fork().
1299: */
1300: seqcount_t write_protect_seq;
1301:
1302: spinlock_t arg_lock; /* protect the below fields */
1303:
1304: unsigned long start_code, end_code, start_data, end_data;
1305: unsigned long start_brk, brk, start_stack;
1306: unsigned long arg_start, arg_end, env_start, env_end;
1307:
1308: unsigned long saved_auxv[AT_VECTOR_SIZE]; /* for /proc/PID/auxv */
1309:
1310: #ifdef CONFIG_ARCH_HAS_ELF_CORE_EFLAGS
1311: /* the ABI-related flags from the ELF header. Used for core dump */
1312: unsigned long saved_e_flags;
1313: #endif
1314:
1315: struct percpu_counter rss_stat[NR_MM_COUNTERS];
1316:
1317: struct linux_binfmt *binfmt;
1318:
1319: /* Architecture-specific MM context */
1320: mm_context_t context;
1321:
1322: mm_flags_t flags; /* Must use mm_flags_* hlpers to access */
1323:
1324: #ifdef CONFIG_AIO
1325: spinlock_t ioctx_lock;
1326: struct kioctx_table __rcu *ioctx_table;
1327: #endif
1328: #ifdef CONFIG_MEMCG
1329: /*
1330: * "owner" points to a task that is regarded as the canonical
1331: * user/owner of this mm. All of the following must be true in
1332: * order for it to be changed:
1333: *
1334: * current == mm->owner
1335: * current->mm != mm
1336: * new_owner->mm == mm
1337: * new_owner->alloc_lock is held
1338: */
1339: struct task_struct __rcu *owner;
1340: #endif
1341:
1342: /* store ref to file /proc/<pid>/exe symlink points to */
1343: struct file __rcu *exe_file;
1344: #ifdef CONFIG_MMU_NOTIFIER
1345: struct mmu_notifier_subscriptions *notifier_subscriptions;
1346: #endif
1347: #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
1348: pgtable_t pmd_huge_pte; /* protected by page_table_lock */
1349: #endif
1350: #ifdef CONFIG_NUMA_BALANCING
1351: /*
1352: * numa_next_scan is the next time that PTEs will be remapped
1353: * PROT_NONE to trigger NUMA hinting faults; such faults gather
1354: * statistics and migrate pages to new nodes if necessary.
1355: */
1356: unsigned long numa_next_scan;
1357:
1358: /* Restart point for scanning and remapping PTEs. */
1359: unsigned long numa_scan_offset;
1360:
1361: /* numa_scan_seq prevents two threads remapping PTEs. */
1362: int numa_scan_seq;
1363: #endif
1364: /*
1365: * An operation with batched TLB flushing is going on. Anything
1366: * that can move process memory needs to flush the TLB when
1367: * moving a PROT_NONE mapped page.
1368: */
1369: atomic_t tlb_flush_pending;
1370: #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
1371: /* See flush_tlb_batched_pending() */
1372: atomic_t tlb_flush_batched;
1373: #endif
1374: struct uprobes_state uprobes_state;
1375: #ifdef CONFIG_PREEMPT_RT
1376: struct rcu_head delayed_drop;
1377: #endif
1378: #ifdef CONFIG_HUGETLB_PAGE
1379: atomic_long_t hugetlb_usage;
1380: #endif
1381: struct work_struct async_put_work;
1382:
1383: #ifdef CONFIG_IOMMU_MM_DATA
1384: struct iommu_mm_data *iommu_mm;
1385: #endif
1386: #ifdef CONFIG_KSM
1387: /*
1388: * Represent how many pages of this process are involved in KSM
1389: * merging (not including ksm_zero_pages).
1390: */
1391: unsigned long ksm_merging_pages;
1392: /*
1393: * Represent how many pages are checked for ksm merging
1394: * including merged and not merged.
1395: */
1396: unsigned long ksm_rmap_items;
1397: /*
1398: * Represent how many empty pages are merged with kernel zero
1399: * pages when enabling KSM use_zero_pages.
1400: */
1401: atomic_long_t ksm_zero_pages;
1402: #endif /* CONFIG_KSM */
1403: #ifdef CONFIG_LRU_GEN_WALKS_MMU
1404: struct {
1405: /* this mm_struct is on lru_gen_mm_list */
1406: struct list_head list;
1407: /*
1408: * Set when switching to this mm_struct, as a hint of
1409: * whether it has been used since the last time per-node
1410: * page table walkers cleared the corresponding bits.
1411: */
1412: unsigned long bitmap;
1413: #ifdef CONFIG_MEMCG
1414: /* points to the memcg of "owner" above */
1415: struct mem_cgroup *memcg;
1416: #endif
1417: } lru_gen;
1418: #endif /* CONFIG_LRU_GEN_WALKS_MMU */
1419: #ifdef CONFIG_MM_ID
1420: mm_id_t mm_id;
1421: #endif /* CONFIG_MM_ID */
1422: } __randomize_layout;
1423:
1424: /*
1425: * The mm_cpumask needs to be at the end of mm_struct, because it
1426: * is dynamically sized based on nr_cpu_ids.
1427: */
1428: char flexible_array[] __aligned(__alignof__(unsigned long));
1429: };
SourceFile:include/linux/mm_types.h]
|
| 19/2 |
2026/09/23 15:46 |
llm |
expert |
0m
Model:
Tokens:
input: 17457
output: 33
thoughts: 642
Thoughts: **Debugging a Suspect Memory Corruption**
Okay, let's break this down. Line 1252 points me to `struct list_head mmlist;`, that's a key structure I need to keep in mind. The report shows a write to 0xffff8881046681f8, and it looks like `__list_del` is involved, specifically the call stack leads us to `list_del(&mm->mmlist)` within `__mmput`. Yep, that address lines up with `mm->mmlist`. So, that write is, in fact, modifying a list head associated with an `mm_struct`.
Now, on the read side, task 3876 is reading from a related address, but this time during `dup_mm` which is called during process creation. The read is to 0xffff888104668000, which looks like it's part of the `mm` structure that's copied in `dup_mm` which calls `memcpy(mm, oldmm, sizeof(*mm))`. The problematic thing is that `current->mm` in 3876 is the same `mm` that task 21217 is calling `__mmput` on! Why is 21217 calling `__mmput`? Oh right, because `atomic_dec_and_test(&mm->mm_users)` was true.
Here's the problem. How can task 3876 be *using* `mm` during `dup_mm`, while `mm->mm_users == 0`? That seems like an impossible race condition and indicates a significant bug. Something's allowing `mm` to be accessed *after* it should have been released! This should not happen.
Time to search the git history. I need to look for commits touching `dup_mm`, `mmput`, `memcpy(mm, oldmm)` and similar patterns to see if there's an existing bug report or a known issue with how memory management is handled during process forking and exiting. Let's see if we can get some clues by blaming some code. I'm going to run `git log` or `git blame` or do a wider search for similar issues.
|
| 20/2 |
2026/09/23 15:46 |
tool |
git-log |
0m
Args: map[CodeRegexp:dup_mm.*memcpy PathPrefix:kernel/fork.c]
Results:
|
| 21/2 |
2026/09/23 15:46 |
llm |
expert |
0m
Model:
Tokens:
input: 18638
output: 35
thoughts: 20
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing the Git Log for `dup_mm` in `kernel/fork.c`**
Alright, time to dig into the `git log` history of the `dup_mm` function within `kernel/fork.c`. I need to understand the evolution of that memory management duplication routine. What's the context? What bugs were squashed? What performance improvements were implemented over time? I'm anticipating looking for changes related to copy-on-write behavior, potential race conditions, or optimization attempts around the memory map duplication process itself. I want to see how it's handled, how it was changed, and when those changes occurred in relation to releases or other significant kernel modifications. I'll be particularly interested in identifying any commits that touch on memory accounting or potential deadlocks related to the memory management structures involved. And obviously, I'll be looking for any signs of refactoring or architectural shifts within that area of the code. This function is a core piece of the forking mechanism, and I need to be up to speed on its recent history.
|
| 22/2 |
2026/09/23 15:46 |
tool |
git-log |
0m
Error:
Args: map[Count:10 PathPrefix:kernel/fork.c SymbolName:dup_mm]
Results:
|
| 23/2 |
2026/09/23 15:46 |
llm |
expert |
0m
Model:
Tokens:
input: 18953
output: 35
thoughts: 10
Thoughts: Okay, here's the summary, assuming I'm the expert and the "Thoughts" section is my internal monologue:
**Navigating and Utilizing SourcePath with SymbolName**
Right, let's get down to brass tacks. I need to leverage `SourcePath` in conjunction with `SymbolName`. Clearly, this isn't a random pairing; there's a specific use case I'm targeting here. The interaction of these two elements will yield some useful result. I'm probably dealing with either code analysis, perhaps refactoring tools, or even some deep-dive debugging where understanding the source's lineage relative to a particular symbol is critical. I will be looking to resolve symbol locations, manage references, or pinpoint dependencies. I'm going to start by formulating a precise question or query. This will then allow me to map out a clear path through the framework to produce the desired result. Now, let's explore this combination.
|
| 24/2 |
2026/09/23 15:46 |
tool |
git-log |
0m
Args: map[Count:10 SourcePath:kernel/fork.c SymbolName:dup_mm]
Results: map[Output:26a8f57760c1 mm: move dup_mmap() to mm
0357ef03c94e fs: don't block write during exec on pre-content watched files
3b832035387f Revert "fs: don't block i_writecount during exec"
2a010c412853 fs: don't block i_writecount during exec
fe69d560b5bd kernel/fork: always deny write access to current MM exe_file
d70f2a14b72a include/linux/sched/mm.h: uninline mmdrop_async(), etc
]
|
| 25/2 |
2026/09/23 15:46 |
llm |
expert |
0m
Model:
Tokens:
input: 19369
output: 34
thoughts: 1690
Thoughts: **Analyzing a Potential Race Condition in `dup_mm` and `__mmput`**
Okay, let's break this down. My initial question is how `dup_mm` could race with `__mmput`. I need to think carefully about thread groups and `fork` in this context. Let's say we have a multi-threaded process with Thread 1 (task 3876) and Thread 2 (task 21217). How were these threads created? If they were created with `CLONE_VM`, there's no `fork` involved. Wait, what if Thread 1 *does* call `fork`? Can a multi-threaded process even call `fork`? Yes, POSIX allows it.
So, when `fork` is called by one thread, the `clone_flags` will *not* have `CLONE_VM`. This means in the `copy_mm` function, the code branches to call `dup_mm`.
Specifically, if Thread 1 calls `fork`, it executes the `dup_mm(tsk, current->mm)` branch. But what about Thread 2? Now, if Thread 2 calls `exit`, that means we have `exit_mm()` function being called. In that function, it ultimately calls `mmput(mm)`.
Here's the problem: If Thread 2 exits and calls `mmput(mm)`, why would that drop `mm->mm_users` to 0 when Thread 1 is still running and has `current->mm == mm`? Thread 1 *should* be holding a reference in `mm->mm_users`. This means when Thread 2 exits, `mm_users` must not be 0. So why is `__mmput` being called?
Let's look at `__mmput`. This function is only called if `atomic_dec_and_test(&mm->mm_users)` returns true, meaning `mm_users` became 0. But that shouldn't happen if Thread 1 is running, right? This means the issue is *why* would `mm_users` become 0 if Thread 1 is running? I have to figure out how Task 3876 got its mm, and if there is a reference being held.
The stack trace for Task 3876 is interesting. It shows `dup_mm`, `copy_mm`, and `kernel_clone`. It's calling the `clone()` syscall! Can a task call `clone()` while `mm_users` is 0? The key here is the fact that Task 3876 and Task 21217 are running on different CPUs. That suggests something very specific. I need to understand what's happening to Task 21217.
The stack trace for Task 21217 indicates an exit path. Specifically, `get_signal` -> `do_group_exit` -> `do_exit` -> `exit_mm`! So this is a group exit, not a simple thread exit. I need to understand what `do_group_exit` and `zap_other_threads` do in this context. It looks like `do_group_exit` might be the clue.
|
| 26/2 |
2026/09/23 15:46 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:do_group_exit]
Results: map[SourceCode:1125: /*
1126: * Take down every thread in the group. This is called by fatal signals
1127: * as well as by sys_exit_group (below).
1128: */
1129: void __noreturn
1130: do_group_exit(int exit_code)
1131: {
1132: struct signal_struct *sig = current->signal;
1133:
1134: if (sig->flags & SIGNAL_GROUP_EXIT)
1135: exit_code = sig->group_exit_code;
1136: else if (sig->group_exec_task)
1137: exit_code = 0;
1138: else {
1139: struct sighand_struct *const sighand = current->sighand;
1140:
1141: spin_lock_irq(&sighand->siglock);
1142: if (sig->flags & SIGNAL_GROUP_EXIT)
1143: /* Another thread got here before we took the lock. */
1144: exit_code = sig->group_exit_code;
1145: else if (sig->group_exec_task)
1146: exit_code = 0;
1147: else {
1148: sig->group_exit_code = exit_code;
1149: sig->flags = SIGNAL_GROUP_EXIT;
1150: zap_other_threads(current);
1151: }
1152: spin_unlock_irq(&sighand->siglock);
1153: }
1154:
1155: do_exit(exit_code);
1156: /* NOTREACHED */
1157: }
SourceFile:kernel/exit.c]
|
| 27/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 22296
output: 34
thoughts: 214
Thoughts: **Analyzing Thread Group Exit and Memory Management**
Okay, let's break this down. I'm looking at `do_group_exit`, and immediately I see `zap_other_threads(current)`. Right, that's the function that's sending those fatal signals to all the other threads within the group. Now I have to think about what happens after that. Task 3876, did that thread exit? This is where it gets interesting... Did Task 3876 exit, and if so, did it call `exit_mm` already?
HOLD ON! Can a task even call `clone()` *after* it's called `exit_mm()`? No, that can't be right, `exit_mm()` is inside `do_exit()`! It's right there in the function call chain! So... could Task 3876 *possibly* have called `exit_mm`? No, because it's in `copy_process` now.
But wait a minute, if Task 3876 is in `copy_process`, how could `mm->mm_users` possibly reach zero? That's what I don't understand. I need to go back and really look at `copy_process`.
Right, `copy_process`. Okay, where's `copy_mm` called within `copy_process`? I need to understand that relationship... Let's look at `kernel/fork.c` around line 2310 and map all this out.
|
| 28/2 |
2026/09/23 15:47 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2290 LineCount:40]
Results: map[Contents:2290: /* copy all the process information */
2291: shm_init_task(p);
2292: retval = security_task_alloc(p, clone_flags);
2293: if (retval)
2294: goto bad_fork_cleanup_audit;
2295: retval = copy_semundo(clone_flags, p);
2296: if (retval)
2297: goto bad_fork_cleanup_security;
2298: retval = copy_files(clone_flags, p, args->no_files);
2299: if (retval)
2300: goto bad_fork_cleanup_semundo;
2301: retval = copy_fs(clone_flags, p, args->umh);
2302: if (retval)
2303: goto bad_fork_cleanup_files;
2304: retval = copy_sighand(clone_flags, p);
2305: if (retval)
2306: goto bad_fork_cleanup_fs;
2307: retval = copy_signal(clone_flags, p);
2308: if (retval)
2309: goto bad_fork_cleanup_sighand;
2310: retval = copy_mm(clone_flags, p);
2311: if (retval)
2312: goto bad_fork_cleanup_signal;
2313: retval = copy_namespaces(clone_flags, p);
2314: if (retval)
2315: goto bad_fork_cleanup_mm;
2316: retval = copy_io(clone_flags, p);
2317: if (retval)
2318: goto bad_fork_cleanup_namespaces;
2319: retval = copy_thread(p, args);
2320: if (retval)
2321: goto bad_fork_cleanup_io;
2322:
2323: stackleak_task_init(p);
2324:
2325: if (pid != &init_struct_pid) {
2326: pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2327: args->set_tid_size);
2328: if (IS_ERR(pid)) {
2329: retval = PTR_ERR(pid);
]
|
| 29/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 23519
output: 34
thoughts: 66
Thoughts: Here's a breakdown of my thought process:
**Diving into Process Cloning and Memory Management**
Okay, so I'm looking at `copy_mm(clone_flags, p)`... that's where the memory management really kicks in, right? But before I get too deep into that function, I need to understand the larger context. Let me zoom out a bit. Back in `copy_process`, what's going on *before* that `copy_mm` call? I know this process like the back of my hand, but a quick review is always a good idea. I'll need to remember the arguments passed, and what each means. Alright, to solidify things, let's head over to `kernel/fork.c`, I'll probably be looking around lines 2200 to 2290. That area usually has the core setup for process creation. I'm going to track what's happening to `clone_flags` and `p`.
|
| 30/2 |
2026/09/23 15:47 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2200 LineCount:60]
Results: map[Contents:2200: rcu_copy_process(p);
2201: p->vfork_done = NULL;
2202: spin_lock_init(&p->alloc_lock);
2203:
2204: init_sigpending(&p->pending);
2205:
2206: p->utime = p->stime = p->gtime = 0;
2207: #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2208: p->utimescaled = p->stimescaled = 0;
2209: #endif
2210: prev_cputime_init(&p->prev_cputime);
2211:
2212: #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2213: seqcount_init(&p->vtime.seqcount);
2214: p->vtime.starttime = 0;
2215: p->vtime.state = VTIME_INACTIVE;
2216: #endif
2217:
2218: #ifdef CONFIG_IO_URING
2219: p->io_uring = NULL;
2220: retval = io_uring_fork(p);
2221: if (unlikely(retval))
2222: goto bad_fork_cleanup_delayacct;
2223: retval = -EAGAIN;
2224: #endif
2225:
2226: p->default_timer_slack_ns = current->timer_slack_ns;
2227:
2228: #ifdef CONFIG_PSI
2229: p->psi_flags = 0;
2230: #endif
2231:
2232: task_io_accounting_init(&p->ioac);
2233: acct_clear_integrals(p);
2234:
2235: posix_cputimers_init(&p->posix_cputimers);
2236: tick_dep_init_task(p);
2237:
2238: p->io_context = NULL;
2239: audit_set_context(p, NULL);
2240: cgroup_fork(p);
2241: if (args->kthread) {
2242: if (!set_kthread_struct(p))
2243: goto bad_fork_cleanup_delayacct;
2244: }
2245: #ifdef CONFIG_NUMA
2246: p->mempolicy = mpol_dup(p->mempolicy);
2247: if (IS_ERR(p->mempolicy)) {
2248: retval = PTR_ERR(p->mempolicy);
2249: p->mempolicy = NULL;
2250: goto bad_fork_cleanup_delayacct;
2251: }
2252: #endif
2253: #ifdef CONFIG_CPUSETS
2254: p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2255: seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2256: #endif
2257: #ifdef CONFIG_TRACE_IRQFLAGS
2258: memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2259: p->irqtrace.hardirq_disable_ip = _THIS_IP_;
]
|
| 31/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 24774
output: 34
thoughts: 36
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing the `copy_process` Function**
Okay, hold on a second. I need to take a closer look at something related to process creation. Let's immediately zero in on the `copy_process` function. Specifically, let's start by examining the core process duplication logic, so I'm skipping to `kernel/fork.c`, and I'm going to focus my attention on lines 2100 through 2200. This is where I anticipate the key aspects of the fork operation are likely defined. I'll be looking for nuances to ensure I understand how the new process inherits or copies resources, especially in the context of recent modifications I'm aware of. I'll need to see how the kernel handles the memory mappings, file descriptor table, signal handlers, and other crucial process attributes during a fork. I'll be looking for anything out of the ordinary, or any optimization efforts. This is a critical area for concurrency.
|
| 32/2 |
2026/09/23 15:47 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2120 LineCount:60]
Results: map[Contents:2120: sigemptyset(&delayed.signal);
2121: INIT_HLIST_NODE(&delayed.node);
2122:
2123: spin_lock_irq(¤t->sighand->siglock);
2124: if (!(clone_flags & CLONE_THREAD))
2125: hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
2126: recalc_sigpending();
2127: spin_unlock_irq(¤t->sighand->siglock);
2128: retval = -ERESTARTNOINTR;
2129: if (task_sigpending(current))
2130: goto fork_out;
2131:
2132: retval = -ENOMEM;
2133: p = dup_task_struct(current, node);
2134: if (!p)
2135: goto fork_out;
2136: /*
2137: * Must run before the first fallible op, so error paths never
2138: * free the parent's ret_stack.
2139: */
2140: ftrace_graph_init_task(p);
2141: retval = copy_exec_state(clone_flags, p);
2142: if (retval)
2143: goto bad_fork_free;
2144: p->flags &= ~PF_KTHREAD;
2145: if (args->kthread)
2146: p->flags |= PF_KTHREAD;
2147: if (args->user_worker) {
2148: /*
2149: * Mark us a user worker, and block any signal that isn't
2150: * fatal or STOP
2151: */
2152: p->flags |= PF_USER_WORKER;
2153: siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2154: }
2155: if (args->io_thread)
2156: p->flags |= PF_IO_WORKER;
2157:
2158: if (args->name)
2159: strscpy_pad(p->comm, args->name, sizeof(p->comm));
2160:
2161: p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2162: /*
2163: * TID is cleared in mm_release() when the task exits
2164: */
2165: p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2166:
2167: rt_mutex_init_task(p);
2168: raw_spin_lock_init(&p->blocked_lock);
2169:
2170: lockdep_assert_irqs_enabled();
2171: #ifdef CONFIG_PROVE_LOCKING
2172: DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2173: #endif
2174: retval = copy_creds(p, clone_flags);
2175: if (retval < 0)
2176: goto bad_fork_free;
2177:
2178: retval = -EAGAIN;
2179: if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
]
|
| 33/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 26040
output: 30
thoughts: 151
Thoughts: Okay, let's see...
**Analyzing Potential Race Conditions in `copy_process`**
Right, I'm digging into `copy_process` and I've hit a potential snag. I'm focusing on line 2129, specifically this snippet:
```c
if (task_sigpending(current))
goto fork_out;
```
It checks for pending signals with `task_sigpending(current)`. My immediate thought is, *that check alone isn't sufficient.* Signals could absolutely arrive *after* that check but *before* the subsequent operations are completed. This feels like a classic race condition scenario. I need to understand the window of vulnerability.
So, the next question is, can a fatal signal actually arrive while `copy_process` is in the midst of its execution? That's the crux of it. If it can, then `task_sigpending` is potentially inadequate as a gatekeeper. What specifically happens if a fatal signal targets the entire thread group at this juncture? The implications could be quite serious.
Okay, let me pivot slightly. In the interest of covering my bases, does `copy_process` itself have a safeguard of some sort? Specifically, does it call `fatal_signal_pending(current)`? I really need to check if there is a deeper check that it's relying on.
Alright, time to go old-school. I'm going to search through `kernel/fork.c` for any and all instances of `fatal_signal_pending` or, for good measure, just `signal_pending`. That should give me a holistic view of how signals are handled within this critical fork path. I've got a feeling this is where the interesting tidbits will be.
|
| 34/2 |
2026/09/23 15:47 |
tool |
grepper |
0m
Args: map[Expression:fatal_signal_pending PathPrefix:kernel/fork.c]
Results: map[Output:kernel/fork.c=2012=__latent_entropy struct task_struct *copy_process(
--
kernel/fork.c-2486- * child missed SIGKILL. If current is not in the same namespace,
kernel/fork.c:2487: * we can't rely on fatal_signal_pending() below.
kernel/fork.c-2488- */
--
kernel/fork.c-2494- /* Let kill terminate clone/fork in the middle */
kernel/fork.c:2495: if (fatal_signal_pending(current)) {
kernel/fork.c-2496- retval = -EINTR;
]
|
| 35/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 26773
output: 42
thoughts: 2050
Thoughts: **Debugging a Potential `mm_users` Race Condition**
Okay, so I'm looking at this report, and my initial thought is, line 2495 is definitely *after* `copy_mm`! But that still doesn't quite explain this `mm_users` issue. The main question is: how did `mm_users` become 0 while Task 3876 is still running? Wait... did it *actually* become 0? Gotta re-read this carefully.
First step, who *is* task 21217, and what is it doing? The report shows it's writing and exiting. The stack trace looks like it's exiting: `exit_mm` -> `mmput` -> `__mmput` -> `list_del`. So it's releasing the MM.
Meanwhile, Task 3876 is reading and calling `copy_mm` -> `clone()`. Why did `mmput` call `__mmput`? That means `atomic_dec_and_test(&mm->mm_users)` was TRUE. Why was *that* true? If it went to 0, it means it *started* at 1. So, if Task 21217 decremented `mm->mm_users` to 0, then Task 3876 can't be holding a reference *in `mm->mm_users`*!
Wait...how is Task 3876 using `current->mm` without `mm_users`?! Can two tasks share an `mm` without *both* holding `mm_users`? This feels like a race condition!
Let's see: How are these two tasks *related*? Let's check `clone` flags... What flags are used to create a task?
If `CLONE_VM` is passed, `copy_mm` calls `mmget`. And that *should* increment `mm_users`! But if `CLONE_VM` is *not* passed, we get `dup_mm`.
In Task 3876, `current->mm` is `0xffff888104668000`. And, hey, Task 21217 is *also* exiting with the *same* `current->mm` address! Wait... Did they have the *same* `mm`? Yes! They're threads of the *same process* (or sharing mm via `CLONE_VM`)!
But, back to the problem! How did `mm->mm_users` reach 0 when Task 21217 calls `exit_mm()`? Did Task 3876 not increment `mm_users` when it was created? If it was created with `CLONE_VM`, then `mmget` *should* have been called. `mm->mm_users` would be at least 2 (one for 21217, one for 3876). Then `mmput` in 21217 *should* leave `mm_users` as 1, not 0! So `__mmput` would *not* be called!
So why was `__mmput(mm)` called? Why was `atomic_dec_and_test(&mm->mm_users)` true? Unless `mm_users` wasn't 2. But why wouldn't it be 2?! Hmm... could `CLONE_VFORK` be relevant? Or `kthread_use_mm`? Something else? I'm going to have to carefully check every place that modifies `mm_users`, or changes `current->mm`. Let's search the kernel code for `mm_users`...
|
| 36/2 |
2026/09/23 15:47 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:0 Name:mm_struct::mm_users]
Results: map[References:<nil> TruncatedOutput:false]
|
| 37/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 29702
output: 37
thoughts: 598
Thoughts: **Analyzing Memory Management and Task Relationships**
Okay, let's break this down. I need to understand how `mm_users` is being accessed, especially concerning Tasks 3876 and 21217. I'm seeing it's touched by `mmget`, `mmput`, `mmget_not_zero`, and `atomic_read(&mm->mm_users)`. The key here is the relationship between the `mm` (memory management) structures and the tasks. I'll focus on `mmget` and `mmput` and also keep `CLONE_VFORK` in mind.
Aha! Task 3876… could it be a child spawned using `vfork`? That's a good lead. Let's think through `vfork()`'s behavior. Does it use the `CLONE_VM` flag? It *should*... Yes! It uses `CLONE_VFORK | CLONE_VM | SIGCHLD`.
Okay, so `vfork` *does* pass `CLONE_VM`. Which means it should call `mmget(oldmm)` when `CLONE_VM` is passed to the syscall. Let's verify that quickly, looking at `kernel/fork.c`, lines 1591-1593: and there it is:
```c
if (clone_flags & CLONE_VM) {
mmget(oldmm);
mm = oldmm;
}
```
Confirmed! `mmget(oldmm)` *is* called. That's good.
So, if `CLONE_VM` is passed, they share the `mm`, right? If it wasn't passed, we'd use `dup_mm` which would create a copy. Now I need to think about why two tasks *would* share the `mm`... only through `CLONE_VM` or `kthread_use_mm`. Hmmm, what about `kthread_use_mm`?
Could a kernel thread call `sys_clone`? I need to check. Let's trace it out. Task 3876 is in `entry_SYSCALL_64_after_hwframe` -> `do_syscall_64` -> `x64_sys_call` -> `__x64_sys_clone`. That tells me *definitely* that Task 3876 is a userspace task. Similarly, Task 21217 also seems to be a userspace task, its trace is `entry_SYSCALL_64_after_hwframe` -> `do_syscall_64` -> `syscall_exit_to_user_mode` -> `get_signal` -> `do_group_exit` -> `exit_mm`.
Wait... Could Task 3876 have called `mmput` earlier? This is the crucial question. I need to know where `mmput` is called! Can a userspace task even call `mmput` while still running? I need to search the codebase for `mmput` references immediately.
|
| 38/2 |
2026/09/23 15:47 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:0 Name:mmput]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__do_sys_process_madvise SourceFile:mm/madvise.c SourceLine:2154] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:access_process_vm SourceFile:mm/memory.c SourceLine:7323] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:build_map_info SourceFile:kernel/events/uprobes.c SourceLine:1253] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:clear_refs_write SourceFile:fs/proc/task_mmu.c SourceLine:1926] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_process SourceFile:kernel/fork.c SourceLine:2607] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_remote_vm_str SourceFile:mm/memory.c SourceLine:7442] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_attach_task SourceFile:kernel/cgroup/cpuset.c SourceLine:3334] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_migrate_mm SourceFile:kernel/cgroup/cpuset.c SourceLine:2623] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_migrate_mm SourceFile:kernel/cgroup/cpuset.c SourceLine:2635] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_migrate_mm_workfn SourceFile:kernel/cgroup/cpuset.c SourceLine:2613] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_update_tasks_nodemask SourceFile:kernel/cgroup/cpuset.c SourceLine:2750] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_procmap_query SourceFile:fs/proc/task_mmu.c SourceLine:722] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_procmap_query SourceFile:fs/proc/task_mmu.c SourceLine:800] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_procmap_query SourceFile:fs/proc/task_mmu.c SourceLine:841] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_task_stat SourceFile:fs/proc/array.c SourceLine:667] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:dup_mm SourceFile:kernel/fork.c SourceLine:1560] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:environ_read SourceFile:fs/proc/base.c SourceLine:1043] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ep_user_copy_worker SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:478] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:exec_mm_put_old SourceFile:fs/exec.c SourceLine:919] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:exit_mm SourceFile:kernel/exit.c SourceLine:618] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ffs_user_copy_worker SourceFile:drivers/usb/gadget/function/f_fs.c SourceLine:883] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:free_bprm SourceFile:fs/exec.c SourceLine:1480] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:get_cmdline SourceFile:mm/util.c SourceLine:1059] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:get_task_cmdline SourceFile:fs/proc/base.c SourceLine:381] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:getrusage SourceFile:kernel/sys.c SourceLine:1925] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ib_umem_odp_alloc_child SourceFile:drivers/infiniband/core/umem_odp.c SourceLine:209] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ib_umem_odp_alloc_child SourceFile:drivers/infiniband/core/umem_odp.c SourceLine:214] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:iommu_sva_handle_mm SourceFile:drivers/iommu/iommu-sva.c SourceLine:270] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:kernel_migrate_pages SourceFile:mm/mempolicy.c SourceLine:1938] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:kernel_move_pages SourceFile:mm/migrate.c SourceLine:2629] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:m_start SourceFile:fs/proc/task_mmu.c SourceLine:332] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:m_stop SourceFile:fs/proc/task_mmu.c SourceLine:371] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:map_files_d_revalidate SourceFile:fs/proc/base.c SourceLine:2210] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:map_files_get_link SourceFile:fs/proc/base.c SourceLine:2262] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:mem_rw SourceFile:fs/proc/base.c SourceLine:931] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:mm_access SourceFile:kernel/fork.c SourceLine:1424] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:pagemap_read SourceFile:fs/proc/task_mmu.c SourceLine:2393] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:perf_event_addr_filters_apply SourceFile:kernel/events/core.c SourceLine:11993] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_coredump_filter_read SourceFile:fs/proc/base.c SourceLine:2943] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_coredump_filter_write SourceFile:fs/proc/base.c SourceLine:2985] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_map_files_lookup SourceFile:fs/proc/base.c SourceLine:2362] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_map_files_readdir SourceFile:fs/proc/base.c SourceLine:2460] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_mem_open SourceFile:fs/proc/base.c SourceLine:835] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_pid_statm SourceFile:fs/proc/array.c SourceLine:696] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_pid_status SourceFile:fs/proc/array.c SourceLine:454] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:process_vm_rw_core SourceFile:mm/process_vm_access.c SourceLine:229] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ptrace_access_vm SourceFile:kernel/ptrace.c SourceLine:81] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:register_for_each_vma SourceFile:kernel/events/uprobes.c SourceLine:1327] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:show_smaps_rollup SourceFile:fs/proc/task_mmu.c SourceLine:1601] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_get_next SourceFile:kernel/bpf/task_iter.c SourceLine:490] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_get_next SourceFile:kernel/bpf/task_iter.c SourceLine:522] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_get_next SourceFile:kernel/bpf/task_iter.c SourceLine:552] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_stop SourceFile:kernel/bpf/task_iter.c SourceLine:648] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:trace_user_stack_print SourceFile:kernel/trace/trace_output.c SourceLine:1506] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2768] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2772] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2785] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:uverbs_user_mmap_disassociate SourceFile:drivers/infiniband/core/uverbs_main.c SourceLine:831] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:xacct_add_tsk SourceFile:kernel/tsacct.c SourceLine:104] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:zap_pages SourceFile:kernel/bpf/arena.c SourceLine:839] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_mmput_1425 SourceFile:kernel/fork.c SourceLine:1218] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_mmput SourceFile:kernel/fork.c SourceLine:1218] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_mmput SourceFile:kernel/fork.c SourceLine:1218]] TruncatedOutput:false]
|
| 39/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 34349
output: 34
thoughts: 54
Thoughts: Okay, let's see. My first thought is: **Kernel Fork Implementation Investigation**.
Wait a minute, I need to check the references within `kernel/fork.c`. Ah, there it is! `copy_process` on line 2607 calls `mmput`. Now, let's dive into line 2607 within `kernel/fork.c` and have a closer look. I need to understand why this specific call is happening there.
|
| 40/2 |
2026/09/23 15:47 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2595 LineCount:35]
Results: map[Contents:2595: if (pid != &init_struct_pid)
2596: free_pid(pid);
2597: bad_fork_cleanup_thread:
2598: exit_thread(p);
2599: bad_fork_cleanup_io:
2600: if (p->io_context)
2601: exit_io_context(p);
2602: bad_fork_cleanup_namespaces:
2603: exit_nsproxy_namespaces(p);
2604: bad_fork_cleanup_mm:
2605: if (p->mm) {
2606: mm_clear_owner(p->mm, p);
2607: mmput(p->mm);
2608: }
2609: bad_fork_cleanup_signal:
2610: if (!(clone_flags & CLONE_THREAD))
2611: free_signal_struct(p->signal);
2612: bad_fork_cleanup_sighand:
2613: __cleanup_sighand(p->sighand);
2614: bad_fork_cleanup_fs:
2615: exit_fs(p); /* blocking */
2616: bad_fork_cleanup_files:
2617: exit_files(p); /* blocking */
2618: bad_fork_cleanup_semundo:
2619: exit_sem(p);
2620: bad_fork_cleanup_security:
2621: security_task_free(p);
2622: bad_fork_cleanup_audit:
2623: audit_free(p);
2624: bad_fork_cleanup_perf:
2625: perf_event_free_task(p);
2626: bad_fork_sched_cancel_fork:
2627: sched_cancel_fork(p);
2628: bad_fork_cleanup_policy:
2629: lockdep_free_task(p);
]
|
| 41/2 |
2026/09/23 15:47 |
llm |
expert |
0m
Model:
Tokens:
input: 35084
output: 18
thoughts: 1956
Thoughts: **The Concurrency Conundrum: A Deep Dive into `mm_struct` Management**
Okay, here's the situation as I see it. I'm staring at a concurrency issue, and it's centered around memory management, specifically with `mm_struct` and the interplay between forking processes and their memory spaces. My initial reaction is to investigate the `bad_fork_cleanup_mm` function, as that's where cleanup is handled, but quickly realized that the original problematic task (21217) wasn't even within that function. I then noticed that task 21217 performed `__mmput`, which is unusual and deserves a closer look.
It appears that task 21217 is exiting, and during this exit sequence, it decrements the `mm_users` counter within the `mm_struct`. The core of the problem stems from the fact that `atomic_dec_and_test(&mm->mm_users)` returned TRUE, indicating that 21217 was the *last* user. This triggers the cleanup in `__mmput`. However, there's another task (3876) accessing the SAME `mm_struct` concurrently.
The key is that task 3876 is performing a `dup_mm` operation which duplicates `oldmm` at the same virtual address as the soon to be freed/reallocated memory, resulting in a read-after-free scenario. This is because `dup_mm` copies the old memory map. I need to understand how two tasks can be referencing the same `mm_struct` concurrently and how `mm_users` is getting manipulated to allow for the race condition.
I need to understand what is happening in `copy_process` and see if there are any discrepancies. If the `CLONE_VM` flag is not set, the child process gets a *copy* of the parent's memory map. The `dup_mm` function does the memory copy.
I'm starting to think about this in the terms of the `CLONE_VM` flag. If `CLONE_VM` *is* set, the child (let's say 3876) shares the same memory space as its parent, in which case both would share the `oldmm`.
If this is true, then if 21217 had decremented `oldmm->mm_users` to zero, then 3876's access to the same virtual memory space would be the problem.
Given that `CLONE_VM` *was* used, then `mmget(oldmm)` must have been called, implying `oldmm->mm_users` was at least 2: one for each task. But the logic says the `atomic_dec_and_test` did not return TRUE. Task 21217 called `__mmput` anyway, so something else is at play and I need to figure out why.
The only other way Task 3876 could have `current->mm == oldmm` is that `oldmm` had an `mm_users` count of 1.
So how can task 3876's `current->mm` be the same as task 21217's `oldmm`, without using the clone vm functionality?
I need to trace all instances where `current->mm` is being assigned to. I need to look at assignments, and how they relate to the memory and the users.
|
| 42/2 |
2026/09/23 15:47 |
tool |
grepper |
0m
Args: map[Expression:current->mm =]
Results: map[Output:Documentation/mm/active_mm.rst=9=helpers, which abstract this config option.
--
Documentation/mm/active_mm.rst-77-
Documentation/mm/active_mm.rst:78: if (current->mm == &init_mm)
Documentation/mm/active_mm.rst-79-
--
Documentation/translations/zh_CN/mm/active_mm.rst=13=Active MM
--
Documentation/translations/zh_CN/mm/active_mm.rst-75-
Documentation/translations/zh_CN/mm/active_mm.rst:76: if (current->mm == &init_mm)
Documentation/translations/zh_CN/mm/active_mm.rst-77-
--
arch/arc/mm/tlb.c=177=noinline void local_flush_tlb_mm(struct mm_struct *mm)
--
arch/arc/mm/tlb.c-195- destroy_context(mm);
arch/arc/mm/tlb.c:196: if (current->mm == mm)
arch/arc/mm/tlb.c-197- get_new_mmu_context(mm);
--
arch/arc/mm/tlb.c=394=static void create_tlb(struct vm_area_struct *vma, unsigned long vaddr, pte_t *ptep)
--
arch/arc/mm/tlb.c-401- /*
arch/arc/mm/tlb.c:402: * create_tlb() assumes that current->mm == vma->mm, since
arch/arc/mm/tlb.c-403- * -it ASID for TLB entry is fetched from MMU ASID reg (valid for curr)
--
arch/arm/mach-rpc/ecard.c=245=static int ecard_init_mm(void)
--
arch/arm/mach-rpc/ecard.c-252-
arch/arm/mach-rpc/ecard.c:253: current->mm = mm;
arch/arm/mach-rpc/ecard.c-254- current->active_mm = mm;
--
arch/loongarch/include/asm/mmu_context.h=141=drop_mmu_context(struct mm_struct *mm, unsigned int cpu)
--
arch/loongarch/include/asm/mmu_context.h-152-
arch/loongarch/include/asm/mmu_context.h:153: if (!current->mm || (current->mm == mm)) {
arch/loongarch/include/asm/mmu_context.h-154- get_new_mmu_context(mm, cpu, &need_flush);
--
arch/m68k/mm/mcfmmu.c=36=void __init paging_init(void)
--
arch/m68k/mm/mcfmmu.c-71-
arch/m68k/mm/mcfmmu.c:72: current->mm = NULL;
arch/m68k/mm/mcfmmu.c-73-}
--
arch/m68k/mm/sun3mmu.c=36=void __init paging_init(void)
--
arch/m68k/mm/sun3mmu.c-78-
arch/m68k/mm/sun3mmu.c:79: current->mm = NULL;
arch/m68k/mm/sun3mmu.c-80-}
--
arch/m68k/sun3/mmu_emu.c=355=int mmu_emu_handle_fault (unsigned long vaddr, int read_flag, int kernel_fault)
--
arch/m68k/sun3/mmu_emu.c-361-
arch/m68k/sun3/mmu_emu.c:362: if(current->mm == NULL) {
arch/m68k/sun3/mmu_emu.c-363- crp = swapper_pg_dir;
--
arch/microblaze/mm/fault.c=86=void do_page_fault(struct pt_regs *regs, unsigned long address,
--
arch/microblaze/mm/fault.c-113- /* faulthandler_disabled() in user mode is really bad,
arch/microblaze/mm/fault.c:114: as is current->mm == NULL. */
arch/microblaze/mm/fault.c-115- pr_emerg("Page fault in user mode with faulthandler_disabled(), mm = %p\n",
--
arch/nios2/mm/tlb.c=257=void flush_tlb_mm(struct mm_struct *mm)
arch/nios2/mm/tlb.c-258-{
arch/nios2/mm/tlb.c:259: if (current->mm == mm) {
arch/nios2/mm/tlb.c-260- unsigned long mmu_pid = get_pid_from_context(&mm->context);
--
arch/powerpc/mm/book3s64/hash_utils.c=1615=void demote_segment_4k(struct mm_struct *mm, unsigned long addr)
--
arch/powerpc/mm/book3s64/hash_utils.c-1622-#endif
arch/powerpc/mm/book3s64/hash_utils.c:1623: if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {
arch/powerpc/mm/book3s64/hash_utils.c-1624-
--
arch/powerpc/mm/book3s64/hash_utils.c=1718=int hash_page_mm(struct mm_struct *mm, unsigned long ea,
--
arch/powerpc/mm/book3s64/hash_utils.c-1852-#endif
arch/powerpc/mm/book3s64/hash_utils.c:1853: if (current->mm == mm)
arch/powerpc/mm/book3s64/hash_utils.c-1854- check_paca_psize(ea, mm, psize, user_region);
--
arch/powerpc/mm/book3s64/hash_utils.c-1898-
arch/powerpc/mm/book3s64/hash_utils.c:1899: if (current->mm == mm)
arch/powerpc/mm/book3s64/hash_utils.c-1900- check_paca_psize(ea, mm, psize, user_region);
--
arch/powerpc/mm/book3s64/radix_tlb.c=661=static void exit_lazy_flush_tlb(struct mm_struct *mm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-672- */
arch/powerpc/mm/book3s64/radix_tlb.c:673: if (current->mm == mm)
arch/powerpc/mm/book3s64/radix_tlb.c-674- goto out;
--
arch/powerpc/mm/book3s64/radix_tlb.c=761=static enum tlb_flush_type flush_type_needed(struct mm_struct *mm, bool fullmm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-800- */
arch/powerpc/mm/book3s64/radix_tlb.c:801: if (atomic_read(&mm->mm_users) <= 1 && current->mm == mm) {
arch/powerpc/mm/book3s64/radix_tlb.c-802- exit_flush_lazy_tlbs(mm);
--
arch/powerpc/mm/book3s64/radix_tlb.c-818- exit_flush_lazy_tlbs(mm);
arch/powerpc/mm/book3s64/radix_tlb.c:819: if (current->mm == mm)
arch/powerpc/mm/book3s64/radix_tlb.c-820- return FLUSH_TYPE_LOCAL;
--
arch/sparc/include/asm/mman.h=14=static inline void ipi_set_tstate_mcde(void *arg)
--
arch/sparc/include/asm/mman.h-21- */
arch/sparc/include/asm/mman.h:22: if (current->mm == mm) {
arch/sparc/include/asm/mman.h-23- struct pt_regs *regs;
--
arch/um/kernel/skas/process.c=45=unsigned long current_stub_stack(void)
arch/um/kernel/skas/process.c-46-{
arch/um/kernel/skas/process.c:47: if (current->mm == NULL)
arch/um/kernel/skas/process.c-48- return 0;
--
arch/um/kernel/skas/process.c=53=struct mm_id *current_mm_id(void)
arch/um/kernel/skas/process.c-54-{
arch/um/kernel/skas/process.c:55: if (current->mm == NULL)
arch/um/kernel/skas/process.c-56- return NULL;
--
arch/um/kernel/skas/process.c=61=void current_mm_sync(void)
arch/um/kernel/skas/process.c-62-{
arch/um/kernel/skas/process.c:63: if (current->mm == NULL)
arch/um/kernel/skas/process.c-64- return;
--
arch/um/kernel/trap.c=308=unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user,
--
arch/um/kernel/trap.c-344- }
arch/um/kernel/trap.c:345: else if (current->mm == NULL) {
arch/um/kernel/trap.c-346- show_regs(container_of(regs, struct pt_regs, regs));
--
arch/x86/kvm/x86.c=10014=void kvm_arch_destroy_vm(struct kvm *kvm)
arch/x86/kvm/x86.c-10015-{
arch/x86/kvm/x86.c:10016: if (current->mm == kvm->mm) {
arch/x86/kvm/x86.c-10017- /*
--
arch/x86/mm/tlb.c=1640=STATIC_NOPV void native_flush_tlb_local(void)
--
arch/x86/mm/tlb.c-1650-
arch/x86/mm/tlb.c:1651: /* If current->mm == NULL then the read_cr3() "borrows" an mm */
arch/x86/mm/tlb.c-1652- native_write_cr3(__native_read_cr3());
--
drivers/vfio/vfio_iommu_type1.c=3138=static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
--
drivers/vfio/vfio_iommu_type1.c-3145- struct vfio_dma *dma;
drivers/vfio/vfio_iommu_type1.c:3146: bool kthread = current->mm == NULL;
drivers/vfio/vfio_iommu_type1.c-3147- size_t offset;
--
include/trace/events/kmem.h=427=TRACE_EVENT(rss_stat,
--
include/trace/events/kmem.h-448- */
include/trace/events/kmem.h:449: __entry->curr = current->mm == mm && !(current->flags & PF_KTHREAD);
include/trace/events/kmem.h-450- __entry->member = member;
--
kernel/exit.c=584=static void exit_mm(void)
--
kernel/exit.c-610- local_irq_disable();
kernel/exit.c:611: current->mm = NULL;
kernel/exit.c-612- membarrier_update_current_mm(NULL);
--
kernel/sched/membarrier.c-111- * d: smp_mb()
kernel/sched/membarrier.c:112: * e: current->mm = NULL
kernel/sched/membarrier.c-113- * b: read rq->curr->mm == NULL
--
kernel/sched/membarrier.c-125- * d: smp_mb()
kernel/sched/membarrier.c:126: * e: current->mm = NULL
kernel/sched/membarrier.c-127- * b: read rq->curr->mm == NULL
kernel/sched/membarrier.c-128- * kthread_use_mm()
kernel/sched/membarrier.c:129: * f: current->mm = mm
kernel/sched/membarrier.c-130- * g: smp_mb()
--
mm/madvise.c=1889=static inline unsigned long get_untagged_addr(struct mm_struct *mm,
--
mm/madvise.c-1891-{
mm/madvise.c:1892: return current->mm == mm ? untagged_addr(start) :
mm/madvise.c-1893- untagged_addr_remote(mm, start);
--
tools/testing/vma/tests/mmap.c=3=static bool test_mmap_region_basic(void)
--
tools/testing/vma/tests/mmap.c-11-
tools/testing/vma/tests/mmap.c:12: current->mm = &mm;
tools/testing/vma/tests/mmap.c-13-
]
|
| 43/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 41468
output: 29
thoughts: 91
Thoughts: Okay, let me think this through.
**Memory Management in Fork and Exec: A Quick Recap**
Alright, my internal radar went off. I need to refresh my understanding of how memory management is handled during `fork` and `exec`. Specifically, where does the assignment of `tsk->mm` happen when a new process is created by `fork`? Let's see... a quick look at `kernel/fork.c` reveals the answer: `copy_mm`. Aha! It's right there: `tsk->mm = mm;` and `tsk->active_mm = mm;`. That handles `fork`. But what about `exec`? Does the memory structure get created the same way for an `exec`? I remember that the `bprm->mm` is also involved in the process. Now I need to review how this is handled, so I’ll check `fs/exec.c`, and specifically `exec_mmap(bprm->mm)`, that should show me the critical part of the process.
|
| 44/2 |
2026/09/23 15:48 |
tool |
grepper |
0m
Error:
Args: map[Expression:current->mm = PathPrefix:fs/exec.c]
Results:
|
| 45/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 41820
output: 28
thoughts: 20
Thoughts: Okay, let's break this down.
**Understanding Kernel Memory Management in `fs/exec.c`**
Alright, I'm looking at `fs/exec.c` and specifically this line: `tsk->mm = mm`. This is core. This is where a process's memory space, its `mm_struct`, is being assigned. `tsk` is obviously the task structure, representing the process. And `mm`... that's the memory descriptor. So what this tells me is that the kernel is *linking* the current process, represented by the task structure (`tsk`), to a specific memory map (`mm`). This is happening during the `exec` system call, when a new program is loaded and executed. It's the critical step of giving the new program its own virtual address space, or re-using the existing one. It’s what makes a new program *run*. I need to see what `mm` is, where its defined, what happens with other memory managers. This is fundamental: without this assignment, the process has no defined address space, and it can't run. Let's see how that connection is made. I suspect this will set up the virtual memory layout for the new executable.
|
| 46/2 |
2026/09/23 15:48 |
tool |
grepper |
0m
Args: map[Expression:->mm = PathPrefix:fs/exec.c]
Results: map[Output:fs/exec.c=258=static int bprm_mm_init(struct linux_binprm *bprm)
--
fs/exec.c-262-
fs/exec.c:263: bprm->mm = mm = mm_alloc();
fs/exec.c-264- err = -ENOMEM;
--
fs/exec.c-287- if (mm) {
fs/exec.c:288: bprm->mm = NULL;
fs/exec.c-289- mmdrop(mm);
--
fs/exec.c=843=static int exec_mmap(struct linux_binprm *bprm)
--
fs/exec.c-883- tsk->active_mm = mm;
fs/exec.c:884: tsk->mm = mm;
fs/exec.c-885- mm_init_cid(mm, tsk);
--
fs/exec.c=1135=int begin_new_exec(struct linux_binprm * bprm)
--
fs/exec.c-1223-
fs/exec.c:1224: bprm->mm = NULL;
fs/exec.c-1225-
]
|
| 47/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 42449
output: 33
thoughts: 38
Thoughts: Here's my analysis of the provided snippet, framed as my own thought process:
**Diving into `exec_mmap` in `fs/exec.c`**
Okay, so I'm focusing in on `fs/exec.c` and specifically the `exec_mmap` function. My initial inclination is to thoroughly understand how the memory mapping is handled during an executable's loading process. Let's zoom in on lines 843 through 925. That section is usually key for seeing the interaction between the file system and virtual memory. I'm expecting to see calls related to `vm_area_struct` manipulation, page table setup, and potentially error handling or resource allocation. The specifics of how file contents are mapped into memory will be critical. I'll be looking for any hints about memory protections, copy-on-write behavior, and the use of the `mmap` system call family within the kernel's execution path. I will see exactly how the kernel handles the initial setup of memory mapping for executables. I'll need to figure out the security implications, if any, that are present here.
|
| 48/2 |
2026/09/23 15:48 |
tool |
read-file |
0m
Args: map[File:fs/exec.c FirstLine:843 LineCount:80]
Results: map[Contents: 843: static int exec_mmap(struct linux_binprm *bprm)
844: {
845: struct task_exec_state *exec_state __free(put_task_exec_state) = NULL;
846: struct mm_struct *mm = bprm->mm;
847: struct task_struct *tsk;
848: struct mm_struct *old_mm, *active_mm;
849: int ret;
850:
851: exec_state = alloc_task_exec_state(bprm->user_ns);
852: if (!exec_state)
853: return -ENOMEM;
854:
855: /* Notify parent that we're no longer interested in the old VM */
856: tsk = current;
857: old_mm = current->mm;
858: /* Clean up futexes and release the mm */
859: mm_exit_exec_release(tsk, old_mm);
860:
861: ret = down_write_killable(&tsk->signal->exec_update_lock);
862: if (ret)
863: return ret;
864:
865: if (old_mm) {
866: /*
867: * If there is a pending fatal signal perhaps a signal
868: * whose default action is to create a coredump get
869: * out and die instead of going through with the exec.
870: */
871: ret = mmap_read_lock_killable(old_mm);
872: if (ret) {
873: up_write(&tsk->signal->exec_update_lock);
874: return ret;
875: }
876: }
877:
878: task_lock(tsk);
879: membarrier_exec_mmap(mm);
880:
881: local_irq_disable();
882: active_mm = tsk->active_mm;
883: tsk->active_mm = mm;
884: tsk->mm = mm;
885: mm_init_cid(mm, tsk);
886: exec_state = task_exec_state_replace(tsk, exec_state);
887: /*
888: * This prevents preemption while active_mm is being loaded and
889: * it and mm are being updated, which could cause problems for
890: * lazy tlb mm refcounting when these are updated by context
891: * switches. Not all architectures can handle irqs off over
892: * activate_mm yet.
893: */
894: if (!IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM))
895: local_irq_enable();
896: activate_mm(active_mm, mm);
897: if (IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM))
898: local_irq_enable();
899: lru_gen_add_mm(mm);
900: task_unlock(tsk);
901: lru_gen_use_mm(mm);
902: if (old_mm) {
903: mmap_read_unlock(old_mm);
904: BUG_ON(active_mm != old_mm);
905: /* Defer teardown to setup_new_exec(), outside the exec locks. */
906: bprm->old_mm = old_mm;
907: } else {
908: mmdrop_lazy_tlb(active_mm);
909: }
910: futex_exec_done(tsk);
911: return 0;
912: }
913:
914: /* Release the address space replaced by exec, outside the exec locks. */
915: static void exec_mm_put_old(struct mm_struct *old_mm)
916: {
917: setmax_mm_hiwater_rss(¤t->signal->maxrss, old_mm);
918: mm_update_next_owner(old_mm);
919: mmput(old_mm);
920: }
921:
922: static int de_thread(struct task_struct *tsk)
]
|
| 49/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 44017
output: 33
thoughts: 36
Thoughts: Here's a summary of my immediate thought process, focusing on an analysis of `de_thread` based on the provided prompts:
**Analyzing the `de_thread` Function**
My attention is immediately drawn to `de_thread`. My initial reaction is, "Right, let's see what this particular thread is doing within the greater context of the system." My next thought is a direct question to myself: "Okay, what's the purpose of `de_thread`? What specific tasks or responsibilities does it handle?" Given my expertise, I already have a broad understanding of the architecture, but I need to quickly zero in on the function of this particular component. Finally, to gain a concrete understanding, I'll need to locate the definition of this in the codebase. Therefore, my immediate next step is to examine the code around line 922, as that may provide the entrypoint for understanding this `de_thread` function and its function. My focus is entirely on identifying its purpose and behavior.
|
| 50/2 |
2026/09/23 15:48 |
tool |
read-file |
0m
Args: map[File:fs/exec.c FirstLine:922 LineCount:90]
Results: map[Contents: 922: static int de_thread(struct task_struct *tsk)
923: {
924: struct signal_struct *sig = tsk->signal;
925: struct sighand_struct *oldsighand = tsk->sighand;
926: spinlock_t *lock = &oldsighand->siglock;
927:
928: if (thread_group_empty(tsk))
929: goto no_thread_group;
930:
931: /*
932: * Kill all other threads in the thread group.
933: */
934: spin_lock_irq(lock);
935: if ((sig->flags & SIGNAL_GROUP_EXIT) || sig->group_exec_task) {
936: /*
937: * Another group action in progress, just
938: * return so that the signal is processed.
939: */
940: spin_unlock_irq(lock);
941: return -EAGAIN;
942: }
943:
944: sig->group_exec_task = tsk;
945: sig->notify_count = zap_other_threads(tsk);
946: if (!thread_group_leader(tsk))
947: sig->notify_count--;
948:
949: while (sig->notify_count) {
950: __set_current_state(TASK_KILLABLE);
951: spin_unlock_irq(lock);
952: schedule();
953: if (__fatal_signal_pending(tsk))
954: goto killed;
955: spin_lock_irq(lock);
956: }
957: spin_unlock_irq(lock);
958:
959: /*
960: * At this point all other threads have exited, all we have to
961: * do is to wait for the thread group leader to become inactive,
962: * and to assume its PID:
963: */
964: if (!thread_group_leader(tsk)) {
965: struct task_struct *leader = tsk->group_leader;
966:
967: for (;;) {
968: cgroup_threadgroup_change_begin(tsk);
969: write_lock_irq(&tasklist_lock);
970: /*
971: * Do this under tasklist_lock to ensure that
972: * exit_notify() can't miss ->group_exec_task
973: */
974: sig->notify_count = -1;
975: if (likely(leader->exit_state))
976: break;
977: __set_current_state(TASK_KILLABLE);
978: write_unlock_irq(&tasklist_lock);
979: cgroup_threadgroup_change_end(tsk);
980: schedule();
981: if (__fatal_signal_pending(tsk))
982: goto killed;
983: }
984:
985: /*
986: * The only record we have of the real-time age of a
987: * process, regardless of execs it's done, is start_time.
988: * All the past CPU time is accumulated in signal_struct
989: * from sister threads now dead. But in this non-leader
990: * exec, nothing survives from the original leader thread,
991: * whose birth marks the true age of this process now.
992: * When we take on its identity by switching to its PID, we
993: * also take its birthdate (always earlier than our own).
994: */
995: tsk->start_time = leader->start_time;
996: tsk->start_boottime = leader->start_boottime;
997:
998: BUG_ON(!same_thread_group(leader, tsk));
999: /*
1000: * An exec() starts a new thread group with the
1001: * TGID of the previous thread group. Rehash the
1002: * two threads with a switched PID, and release
1003: * the former thread group leader:
1004: */
1005:
1006: /* Become a process group leader with the old leader's pid.
1007: * The old leader becomes a thread of the this thread group.
1008: */
1009: exchange_tids(tsk, leader);
1010: transfer_pid(leader, tsk, PIDTYPE_TGID);
1011: transfer_pid(leader, tsk, PIDTYPE_PGID);
]
|
| 51/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 45649
output: 32
thoughts: 24
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Tracing Memory Management in Execution Setup**
Okay, hold on a minute. I need to zoom in on this `setup_new_exec` function. It's crucial for understanding how the memory space transitions during process execution. My immediate question is: where exactly does `exec_mm_put_old` get invoked? I need to know where the old memory management data is released or updated. This is likely the lynchpin for tracking how the old process's memory maps are handled *before* the new executable is loaded. Identifying the call site(s) of `exec_mm_put_old` is the critical next step. It'll give me a clear picture of when the old process's memory is either freed or migrated as a consequence of this new exec call.
|
| 52/2 |
2026/09/23 15:48 |
tool |
grepper |
0m
Args: map[Expression:exec_mm_put_old PathPrefix:fs/exec.c]
Results: map[Output:fs/exec.c=843=static int exec_mmap(struct linux_binprm *bprm)
--
fs/exec.c-914-/* Release the address space replaced by exec, outside the exec locks. */
fs/exec.c:915:static void exec_mm_put_old(struct mm_struct *old_mm)
fs/exec.c-916-{
--
fs/exec.c=1380=void setup_new_exec(struct linux_binprm * bprm)
--
fs/exec.c-1398- if (bprm->old_mm) {
fs/exec.c:1399: exec_mm_put_old(bprm->old_mm);
fs/exec.c-1400- bprm->old_mm = NULL;
--
fs/exec.c=1476=static void free_bprm(struct linux_binprm *bprm)
--
fs/exec.c-1492- if (bprm->old_mm)
fs/exec.c:1493: exec_mm_put_old(bprm->old_mm);
fs/exec.c-1494- /* An unconsumed PT_INTERP substitute from a binfmt_misc loader entry. */
]
|
| 53/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 46218
output: 34
thoughts: 260
Thoughts: **My Analysis of the System Call Trace**
Okay, hold on a second! I was initially thinking `exec` was the culprit, but I just realized that in `exec`, all other threads are killed in `de_thread` before `exec_mmap`! That throws that initial hypothesis out the window. So, that's definitely not what's happening.
Alright, time to refocus. Let's revisit the core of the report. What's actually happening here?
Looking at Task 21217, the call stack goes something like this: `do_syscall_64` -> `syscall_exit_to_user_mode` -> `exit_to_user_mode_loop` -> `arch_do_signal_or_restart` -> `get_signal` -> `do_group_exit` -> `do_exit` -> `exit_mm` -> `mmput` -> `__mmput`. Seems like a process exiting or being signaled.
Then, for Task 3876, we have: `do_syscall_64` -> `x64_sys_call` -> `__x64_sys_clone` -> `kernel_clone` -> `copy_process` -> `copy_mm` -> `dup_mm`. Ah, `clone`! That looks like the creation of a new process or thread.
WAIT! Let's pause and really consider this `kernel_clone` call in relation to what's happening.
The question is, when did task 21217 get created? Could these two tasks, 21217 and 3876, be related? It's a key question.
Now I need to go back and really scrutinize `kernel_clone` more closely, specifically around line 2769. I think there might be something important buried in that code.
|
| 54/2 |
2026/09/23 15:48 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2750 LineCount:50]
Results: map[Contents:2750:
2751: /*
2752: * Determine whether and which event to report to ptracer. When
2753: * called from kernel_thread or CLONE_UNTRACED is explicitly
2754: * requested, no event is reported; otherwise, report if the event
2755: * for the type of forking is enabled.
2756: */
2757: if (!(clone_flags & CLONE_UNTRACED)) {
2758: if (clone_flags & CLONE_VFORK)
2759: trace = PTRACE_EVENT_VFORK;
2760: else if (args->exit_signal != SIGCHLD)
2761: trace = PTRACE_EVENT_CLONE;
2762: else
2763: trace = PTRACE_EVENT_FORK;
2764:
2765: if (likely(!ptrace_event_enabled(current, trace)))
2766: trace = 0;
2767: }
2768:
2769: p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2770: add_latent_entropy();
2771:
2772: if (IS_ERR(p))
2773: return PTR_ERR(p);
2774:
2775: /*
2776: * Do this prior waking up the new thread - the thread pointer
2777: * might get invalid after that point, if the thread exits quickly.
2778: */
2779: trace_sched_process_fork(current, p);
2780:
2781: pid = get_task_pid(p, PIDTYPE_PID);
2782: nr = pid_vnr(pid);
2783:
2784: if (clone_flags & CLONE_PARENT_SETTID)
2785: put_user(nr, args->parent_tid);
2786:
2787: if (clone_flags & CLONE_VFORK) {
2788: p->vfork_done = &vfork;
2789: init_completion(&vfork);
2790: get_task_struct(p);
2791: }
2792:
2793: if (IS_ENABLED(CONFIG_LRU_GEN_WALKS_MMU) && !(clone_flags & CLONE_VM)) {
2794: /* lock the task to synchronize with memcg migration */
2795: task_lock(p);
2796: lru_gen_add_mm(p->mm);
2797: task_unlock(p);
2798: }
2799:
]
|
| 55/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 47673
output: 33
thoughts: 481
Thoughts: **Memory Management Cloning Concerns**
Okay, hold on a second. I need to zoom in on this `copy_process` function, specifically this line: `p = copy_process(NULL, trace, NUMA_NO_NODE, args);`. Within that, the call to `copy_mm` is what's catching my eye. Let's trace it down: `retval = copy_mm(clone_flags, p);`
Inside `copy_mm`, we have:
```c
oldmm = current->mm;
if (!oldmm)
return 0;
if (clone_flags & CLONE_VM) {
mmget(oldmm);
mm = oldmm;
} else {
mm = dup_mm(tsk, current->mm);
if (!mm)
return -ENOMEM;
}
tsk->mm = mm;
tsk->active_mm = mm;
return 0;
```
Ah, right, the critical part is in the `else` block, where a copy is being made: `mm = dup_mm(tsk, current->mm);`. The `CLONE_VM` path is straightforward; the process is sharing the `mm_struct`, so we don't have to concern ourselves with locking here.
But wait a minute! What locks are in place to protect the `dup_mm(tsk, current->mm)` operation from concurrent modifications to `current->mm`? We need to verify the atomicity of the operation, given it is copying the memory structures. Let's look at `dup_mm` more closely:
```c
static struct mm_struct *dup_mm(struct task_struct *tsk,
struct mm_struct *oldmm)
{
struct mm_struct *mm;
int err;
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
if (!mm_init(mm, tsk))
goto fail_nomem;
uprobe_start_dup_mmap();
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
uprobe_end_dup_mmap();
...
```
Now, focus on line 1537: `memcpy(mm, oldmm, sizeof(*mm));`. Does `dup_mm` itself hold *any* lock on `oldmm` during that `memcpy` call? The answer is a glaring NO! That is a potential race condition!
This is where the race condition is possible: `oldmm` is getting copied via `memcpy`, and that copy is happening without any locking. Hmm. We need to check when the `oldmm` *is* locked. The next place to look would be `dup_mmap` function. Where is the `mmap_lock` held within that function? We need to trace this call further to see how it is protected. Let's find out!
|
| 56/2 |
2026/09/23 15:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mmap]
Results: map[SourceCode:1708: __latent_entropy int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
1709: {
1710: struct vm_area_struct *mpnt, *tmp;
1711: int retval;
1712: unsigned long charge = 0;
1713: LIST_HEAD(uf);
1714: VMA_ITERATOR(vmi, mm, 0);
1715:
1716: if (mmap_write_lock_killable(oldmm))
1717: return -EINTR;
1718: flush_cache_dup_mm(oldmm);
1719: uprobe_dup_mmap(oldmm, mm);
1720: /*
1721: * Not linked in yet - no deadlock potential:
1722: */
1723: mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
1724:
1725: /* No ordering required: file already has been exposed. */
1726: dup_mm_exe_file(mm, oldmm);
1727:
1728: mm->total_vm = oldmm->total_vm;
1729: mm->data_vm = oldmm->data_vm;
1730: mm->exec_vm = oldmm->exec_vm;
1731: mm->stack_vm = oldmm->stack_vm;
1732:
1733: /* Use __mt_dup() to efficiently build an identical maple tree. */
1734: retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
1735: if (unlikely(retval))
1736: goto out;
1737:
1738: mt_clear_in_rcu(vmi.mas.tree);
1739: for_each_vma(vmi, mpnt) {
1740: struct file *file;
1741:
1742: retval = vma_start_write_killable(mpnt);
1743: if (retval < 0)
1744: goto loop_out;
1745: if (vma_test(mpnt, VMA_DONTCOPY_BIT)) {
1746: retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
1747: mpnt->vm_end, GFP_KERNEL);
1748: if (retval)
1749: goto loop_out;
1750:
1751: vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
1752: continue;
1753: }
1754: charge = 0;
1755: if (vma_test(mpnt, VMA_ACCOUNT_BIT)) {
1756: unsigned long len = vma_pages(mpnt);
1757:
1758: if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
1759: goto fail_nomem;
1760: charge = len;
1761: }
1762:
1763: tmp = vm_area_dup(mpnt);
1764: if (!tmp)
1765: goto fail_nomem;
1766: retval = vma_dup_policy(mpnt, tmp);
1767: if (retval)
1768: goto fail_nomem_policy;
1769: tmp->vm_mm = mm;
1770: retval = dup_userfaultfd(tmp, &uf);
1771: if (retval)
1772: goto fail_nomem_anon_vma_fork;
1773:
1774: if (vma_test(tmp, VMA_WIPEONFORK_BIT)) {
1775: /*
1776: * VMA_WIPEONFORK_BIT gets a clean slate in the child.
1777: * Don't prepare anon_vma until fault since we don't
1778: * copy page for current vma.
1779: */
1780: tmp->anon_vma = NULL;
1781: } else if (anon_vma_fork(tmp, mpnt))
1782: goto fail_nomem_anon_vma_fork;
1783:
1784: vma_start_write(tmp);
1785: vma_clear_flags_mask(tmp, VMA_LOCKED_MASK);
1786: /*
1787: * Copy/update hugetlb private vma information.
1788: */
1789: if (is_vm_hugetlb_page(tmp))
1790: hugetlb_dup_vma_private(tmp);
1791:
1792: /*
1793: * Link the vma into the MT. After using __mt_dup(), memory
1794: * allocation is not necessary here, so it cannot fail.
1795: */
1796: vma_iter_bulk_store(&vmi, tmp);
1797:
1798: mm->map_count++;
1799:
1800: if (tmp->vm_ops && tmp->vm_ops->open)
1801: tmp->vm_ops->open(tmp);
1802:
1803: file = tmp->vm_file;
1804: if (file) {
1805: struct address_space *mapping = file->f_mapping;
1806:
1807: get_file(file);
1808: i_mmap_lock_write(mapping);
1809: if (vma_is_shared_maywrite(tmp))
1810: mapping_allow_writable(mapping);
1811: flush_dcache_mmap_lock(mapping);
1812: /* insert tmp into the share list, just after mpnt */
1813: mapping_rmap_tree_insert_after(tmp, mpnt, mapping);
1814: flush_dcache_mmap_unlock(mapping);
1815: i_mmap_unlock_write(mapping);
1816: }
1817:
1818: if (!vma_test(tmp, VMA_WIPEONFORK_BIT))
1819: retval = copy_page_range(tmp, mpnt);
1820:
1821: if (retval) {
1822: mpnt = vma_next(&vmi);
1823: goto loop_out;
1824: }
1825: }
1826: /* a new mm has just been created */
1827: retval = arch_dup_mmap(oldmm, mm);
1828: loop_out:
1829: vma_iter_free(&vmi);
1830: if (!retval) {
1831: mt_set_in_rcu(vmi.mas.tree);
1832: ksm_fork(mm, oldmm);
1833: khugepaged_fork(mm, oldmm);
1834: } else {
1835: unsigned long end;
1836:
1837: /*
1838: * The entire maple tree has already been duplicated, but
1839: * replacing the vmas failed at mpnt (which could be NULL if
1840: * all were allocated but the last vma was not fully set up).
1841: * Use the start address of the failure point to clean up the
1842: * partially initialized tree.
1843: */
1844: if (!mm->map_count) {
1845: /* zero vmas were written to the new tree. */
1846: end = 0;
1847: } else if (mpnt) {
1848: /* partial tree failure */
1849: end = mpnt->vm_start;
1850: } else {
1851: /* All vmas were written to the new tree */
1852: end = ULONG_MAX;
1853: }
1854:
1855: /* Hide mm from oom killer because the memory is being freed */
1856: mm_flags_set(MMF_OOM_SKIP, mm);
1857: if (end) {
1858: vma_iter_set(&vmi, 0);
1859: tmp = vma_next(&vmi);
1860: UNMAP_STATE(unmap, &vmi, /* first = */ tmp,
1861: /* vma_start = */ 0, /* vma_end = */ end,
1862: /* prev = */ NULL, /* next = */ NULL);
1863:
1864: /*
1865: * Don't iterate over vmas beyond the failure point for
1866: * both unmap_vma() and free_pgtables().
1867: */
1868: unmap.tree_end = end;
1869: flush_cache_mm(mm);
1870: unmap_region(&unmap);
1871: charge = tear_down_vmas(mm, &vmi, tmp, end);
1872: vm_unacct_memory(charge);
1873: }
1874: __mt_destroy(&mm->mm_mt);
1875: /*
1876: * The mm_struct is going to exit, but the locks will be dropped
1877: * first. Set the mm_struct as unstable is advisable as it is
1878: * not fully initialised.
1879: */
1880: mm_flags_set(MMF_UNSTABLE, mm);
1881: }
1882: out:
1883: mmap_write_unlock(mm);
1884: flush_tlb_mm(oldmm);
1885: mmap_write_unlock(oldmm);
1886: if (!retval)
1887: dup_userfaultfd_complete(&uf);
1888: else
1889: dup_userfaultfd_fail(&uf);
1890: return retval;
1891:
1892: fail_nomem_anon_vma_fork:
1893: mpol_put(vma_policy(tmp));
1894: fail_nomem_policy:
1895: vm_area_free(tmp);
1896: fail_nomem:
1897: retval = -ENOMEM;
1898: vm_unacct_memory(charge);
1899: goto loop_out;
1900: }
SourceFile:mm/mmap.c]
|
| 57/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 51857
output: 35
thoughts: 1109
Thoughts: **Analyzing `dup_mm` and Memory Management in Threaded Processes**
Okay, so I'm looking at `dup_mm` in the kernel code, specifically around lines 1537 in the provided context, and I'm seeing something that strikes me as potentially problematic. The `memcpy(mm, oldmm, sizeof(*mm))` operation copies the entire `mm_struct` *before* the call to `dup_mmap(mm, oldmm)`. Now, `dup_mmap` seems to be responsible for duplicating the memory mappings, and it explicitly acquires `mmap_lock` on the `oldmm` within its function body: `if (mmap_write_lock_killable(oldmm))`. But the `memcpy` is happening *without* any locking on `oldmm`'s behalf. That's a classic race condition scenario that needs to be scrutinized. There could be corruption occurring.
I need to circle back and look at the `exit_mm` function as well. What happens when a process exits its memory space? Let's refresh my memory. It acquires a `mmap_read_lock`, sets `current->mm` to `NULL`, and then releases the lock. The crucial part here is the `mmput(mm)` call after unlocking. Inside `mmput`, we see `atomic_dec_and_test(&mm->mm_users)`. This is a counter that indicates how many users still have references to that mm.
I'm starting to put the pieces together. The `atomic_dec_and_test` evaluates to true at some point. This is interesting: How can the reference count decrement to zero? Let's check how threads and `mm_users` relate, and, most importantly, when does the reference count *start* to decrement? Perhaps by comparing how tasks 3876 and 21217 may be related.
The potential issue is that a process with threads, could fork. Suppose process P has two threads: Thread A (Task 21217) and Thread B (Task 3876).
Now, if Thread A and Thread B are indeed threads of the same process, then I need to consider what the `mm_users` count actually reflects. When a thread is created using `CLONE_THREAD | CLONE_VM`, the code calls `mmget(oldmm)`. And that's the key.
Does `mmget(oldmm)` increment `mm->mm_users`? I'm going to quickly check the definition of `mmget` to verify if this is what happens when a new thread is created using `CLONE_VM`, which is the correct flag. I need to make sure to account for that. This is the likely point where the reference counting comes into play. If multiple threads are sharing a `mm_struct`, each new thread with the `CLONE_VM` flag would increment `mm_users`, and so only one thread needs to release the `mm` when it exits.
|
| 58/2 |
2026/09/23 15:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/sched/mm.h Name:mmget]
Results: map[SourceCode: 115: /**
116: * mmget() - Pin the address space associated with a &struct mm_struct.
117: * @mm: The address space to pin.
118: *
119: * Make sure that the address space of the given &struct mm_struct doesn't
120: * go away. This does not protect against parts of the address space being
121: * modified or freed, however.
122: *
123: * Never use this function to pin this address space for an
124: * unbounded/indefinite amount of time.
125: *
126: * Use mmput() to release the reference acquired by mmget().
127: *
128: * See also <Documentation/mm/active_mm.rst> for an in-depth explanation
129: * of &mm_struct.mm_count vs &mm_struct.mm_users.
130: */
131: static inline void mmget(struct mm_struct *mm)
132: {
133: atomic_inc(&mm->mm_users);
134: }
SourceFile:include/linux/sched/mm.h]
|
| 59/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 54000
output: 36
thoughts: 203
Thoughts: **Debugging a Memory Management Conundrum**
Okay, here's the situation. I'm looking at this memory management issue, and something just isn't adding up. If Thread B was created with `CLONE_VM`, then `atomic_inc(&mm->mm_users)` should have been called, right? Which means `mm->mm_users` should be at least 2. But then, how in the world did `atomic_dec_and_test(&mm->mm_users)` return true for Task 21217? That's the first red flag.
Now, my mind is racing. Could it be that Task 3876 wasn't created with `CLONE_VM`? If that's true, then how could Task 3876 have `current->mm == mm`? Unless...wait a minute. What if Task 3876 *didn't* originally have `current->mm == mm`? Perhaps it somehow gained access later. Could it have called `kthread_use_mm`? That's got to be the key! I need to find out what `kthread_use_mm` *actually* does. Let's dig into that function's implementation immediately. I'm certain that's where the answer lies!
|
| 60/2 |
2026/09/23 15:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/kthread.c Name:kthread_use_mm]
Results: map[SourceCode:1611: /**
1612: * kthread_use_mm - make the calling kthread operate on an address space
1613: * @mm: address space to operate on
1614: */
1615: void kthread_use_mm(struct mm_struct *mm)
1616: {
1617: struct mm_struct *active_mm;
1618: struct task_struct *tsk = current;
1619:
1620: WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1621: WARN_ON_ONCE(tsk->mm);
1622:
1623: /*
1624: * It is possible for mm to be the same as tsk->active_mm, but
1625: * we must still mmgrab(mm) and mmdrop_lazy_tlb(active_mm),
1626: * because these references are not equivalent.
1627: */
1628: mmgrab(mm);
1629:
1630: task_lock(tsk);
1631: /* Hold off tlb flush IPIs while switching mm's */
1632: local_irq_disable();
1633: active_mm = tsk->active_mm;
1634: tsk->active_mm = mm;
1635: tsk->mm = mm;
1636: membarrier_update_current_mm(mm);
1637: switch_mm_irqs_off(active_mm, mm, tsk);
1638: local_irq_enable();
1639: task_unlock(tsk);
1640: #ifdef finish_arch_post_lock_switch
1641: finish_arch_post_lock_switch();
1642: #endif
1643:
1644: /*
1645: * When a kthread starts operating on an address space, the loop
1646: * in membarrier_{private,global}_expedited() may not observe
1647: * that tsk->mm, and not issue an IPI. Membarrier requires a
1648: * memory barrier after storing to tsk->mm, before accessing
1649: * user-space memory. A full memory barrier for membarrier
1650: * {PRIVATE,GLOBAL}_EXPEDITED is implicitly provided by
1651: * mmdrop_lazy_tlb().
1652: */
1653: mmdrop_lazy_tlb(active_mm);
1654: }
SourceFile:kernel/kthread.c]
|
| 61/2 |
2026/09/23 15:48 |
llm |
expert |
0m
Model:
Tokens:
input: 55234
output: 26
thoughts: 2468
Thoughts: **Analyzing a Concurrency Issue in Memory Management**
Okay, so I'm looking at a potential data race involving `__mmput` and `copy_mm`, and it's a bit tricky. My initial thought was to check if a kernel thread, a kthread, was involved by looking at `kthread_use_mm`, but quickly realized the stack traces tell me that user-space syscalls were involved. Task 3876 is in userspace, doing a `sys_clone` call. I ruled out io_uring workers since they don't use the standard syscall entry points. This is a real userspace thread calling `clone`.
Now the core issue: I'm trying to understand why `atomic_dec_and_test(&mm->mm_users)` returned true in Task 21217. I considered if Task 21217 was the *last* thread and if Task 3876 had already called `exit_mm()`, but then saw Task 3876's stack - it's *in* `clone()`, so it can't have exited.
Then I considered if Task 3876 was created without `CLONE_VM`, which would duplicate the memory map, but even then, it doesn't explain how Task 21217 would have the same `mm`. Wait, could Task 21217 be the child thread created by Task 3876? Looking at Task 21217's stack, it exited and called `exit_mm`, which would explain the decrement. However, why did `mmput` drop `mm_users` to 0?
I started to think through the ways `mm_users` could be modified: the process itself, `CLONE_VM` threads, and various other kernel operations like `procfs` access (e.g. `/proc/$pid/mem`). Then it hit me: the key is that tasks like the `/proc/$pid/mem` access *increment and decrement* `mm_users` with `mmget` and `mmput`. They don't make it 0.
So, why are `__mmput` and `dup_mm` running concurrently? My current assumption is that Task 3876 and Task 21217 share an `mm` through `CLONE_VM`. But if that's the case, why would `atomic_dec_and_test(&mm->mm_users)` be true for the second thread? Could Task 3876 already have decremented `mm_users` through `exit_mm()`? No, because a thread can't call `clone()` *after* `exit_mm()`. It can only be called from `do_exit()` or `exec_mmap()`, and you never return to user space.
So, maybe Task 3876 isn't the "first" thread in this shared memory map situation. This leads me to question the fundamental assumption: is there *any other* way Task 3876 and 21217 could be sharing an `mm`? If not `CLONE_VM`, what else is possible?
The next step is to examine what syzkaller does, because that's what triggered this. Time to search the syzkaller tests or the Git log for this specific "BUG: KCSAN: data-race" and those functions. Keywords for searching are: "__mmput / copy_mm" or just "__mmput" and "dup_mm" and "copy_mm."
|
| 62/2 |
2026/09/23 15:48 |
tool |
git-log |
0m
Args: map[MessageRegexps:[__mmput copy_mm]]
Results:
|
| 63/2 |
2026/09/23 15:49 |
llm |
expert |
0m
Model:
Tokens:
input: 58515
output: 25
thoughts: 29
Thoughts: Here's my thought process, as if I were considering this myself:
**Investigating Memory Duplication and Data Races in the Kernel**
Okay, so I need to track down potential memory duplication or data race issues. My initial thought is to dive into the git log. The goal here is to get a handle on related patches that might have introduced or interacted with these types of problems. Since I'm familiar with the kernel's KCSAN and data-race tooling, I'm going to leverage that knowledge to narrow the search. Specifically, I'll start with "dup_mm" and "copy_mm" as likely search terms, looking for mentions of either in the commit messages. I'm choosing these because those functions are directly related to memory management and duplication, which is where I would start my focus. Then I'll combine them with "KCSAN" or "data-race" to filter for commits that are explicitly flagged or address those concerns. This combined approach should give me a more focused set of candidates to review, as opposed to a more general search for memory-related changes, right? I can then analyze those commits more closely to determine how they might relate to my specific concerns, whatever those might be. Let's see what the log turns up.
|
| 64/2 |
2026/09/23 15:49 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[copy_mm]]
Results: map[Output:faa6f77b0dfa x86/locking/atomic: Improve performance by using asm_inline() for atomic locking instructions
e914d8f00391 mm: fix unexpected zeroed page mapping with zram swap
a6895399380a kernel/fork.c: simplify copy_mm()
f3c64eda3e50 mm: avoid early COW write protect games during fork()
f39356261c26 powerpc/book3s/64: check for NULL pointer in pgd_alloc()
07dcd7fe8993 fork: Define usercopy region in mm_struct slab caches
52b1e66587b6 powerpc/mm: Move copy_mm_to_paca to paca.c
edfe63ec97ed x86/mtrr: Fix Xorg crashes in Qemu sessions
68ce670b6e8e kernel/fork.c: remove redundant NULL check in dup_mm()
da1816b1caec uprobes: Teach handler_chain() to filter out the probed task
]
|
| 65/2 |
2026/09/23 15:49 |
llm |
expert |
0m
Model:
Tokens:
input: 59113
output: 25
thoughts: 12
Thoughts: Here's my take on those thoughts:
**Analyzing `__mmput` Usage**
Alright, let's dive into this. The task at hand is to investigate commit messages with a focus on `__mmput`. This likely means we're looking to understand how this function is being used, where it's being used, and potentially the context around its implementation or changes. This could be anything from debugging memory management issues, to performance optimization, to refactoring efforts that involve resource release. Perhaps we're looking for patterns in how it's being handled across different subsystems. We could be researching its lifecycle, or hunting for specific bugs. Whatever the reason, starting with a targeted search for commit messages mentioning `__mmput` is the logical first step. It's a key function related to memory management in the kernel, so there's probably a wealth of data to be gleaned from commit logs.
|
| 66/2 |
2026/09/23 15:49 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[__mmput]]
Results: map[Output:bde023808364 futex: Fix race on the initial mm->futex.phash.ref allocation
4c92afb4c143 drm/xe/vf: Add drm_dev guards when detaching CCS read/write buffers
1ae415a6eefe drm/xe/vf: Add drm_dev guards when detaching CCS read/write buffers
38205ecbe6b6 exec: free the old mm outside the exec locks
ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
fda4d71651f7 powerpc/pgtable-frag: Fix bad page state in pte_frag_destroy
8821e857759b xdp: produce a warning when calculated tailroom is negative
4ddfab5436b6 KVM: arm64: Reschedule as needed when destroying the stage-2 page-tables
00c14a09a70e hfs/hfsplus: prevent getting negative values of offset/length
d9b05321e21e futex: Move futex_hash_free() back to __mmput()
e9abe311f356 KVM: arm64: Reschedule as needed when destroying the stage-2 page-tables
dde30854bddf mm/debug_vm_pgtable: clear page table entries at destroy_args()
e703b7e24750 futex: Move futex cleanup to __mmdrop()
ee40c9920ac2 mm: fix copy_vma() error handling for hugetlb mappings
7bcfeddb36b7 drm/xe: Fix an out-of-bounds shift when invalidating TLB
b88f48f86500 drm/xe: Fix an out-of-bounds shift when invalidating TLB
dc84bc2aba85 x86/mm/pat: Fix VM_PAT handling when fork() fails in copy_page_range()
7cd1f5f77925 LoongArch: Add architecture specific huge_pte_clear()
66edc3a5894c mm: page_alloc: move mlocked flag clearance into free_pages_prepare()
818f916e3a07 mm: swap: prevent possible data-race in __try_to_reclaim_swap
]
|
| 67/2 |
2026/09/23 15:49 |
llm |
expert |
0m
Model:
Tokens:
input: 59917
output: 25
thoughts: 31
Thoughts: Okay, let's dive into commit `38205ecbe6b6 exec: free the old mm outside the exec locks`. I need to understand why this change was made, and what it's trying to address. My initial thought is this is likely related to improving concurrency or preventing deadlocks within the execution process. We're talking about memory management (`mm`) here, and specifically, the freeing of the old memory map. The phrase "outside the exec locks" is the key. It suggests a potential bottleneck or critical section within the `execve()` system call. So, the goal is likely to decouple the memory freeing operation from the locking mechanism associated with the execution environment. This could have significant implications for performance and responsiveness if the memory freeing operation is time-consuming or if there's contention for those locks. I'll need to look at the surrounding code to understand the specific locks involved and the rationale behind moving this operation. This is likely an attempt to optimize the path taken during process creation. I also need to see if this change introduced any other concurrency hazards or made a memory management change.
|
| 68/2 |
2026/09/23 15:49 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 38205ecbe6b6dc47968ad4e9c978e2117720969e
Author: Christian Brauner <brauner@kernel.org>
Date: Fri May 22 16:03:30 2026 +0200
exec: free the old mm outside the exec locks
exec_mmap() installs the new mm and then tears the old one down while
still holding exec_update_lock for writing -- and with cred_guard_mutex
held all the way to setup_new_exec():
setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm);
mm_update_next_owner(old_mm);
mmput(old_mm);
Neither lock is needed for this. exec_update_lock only exists to make the
mm swap atomic with the later commit_creds(), so that permission-checking
readers (proc, ptrace, the futex robust list, perf, kcmp, mm_access())
never observe the new mm together with the old credentials. Those readers
all operate on task->mm, i.e. the new mm after the swap; none looks at the
detached old mm, its ->owner or signal->maxrss. cred_guard_mutex guards
credential calculation and is equally irrelevant here.
The cost is real: __mmput() runs exit_mmap() over the entire old address
space and can block in exit_aio() waiting for in-flight AIO, all while
holding exec_update_lock for writing and cred_guard_mutex. For execve() of
a large process this blocks ptrace_attach() and every exec_update_lock
reader for the duration of the teardown.
Stash the old mm in bprm->old_mm and release it from setup_new_exec()
after both locks are dropped. setup_new_exec() still runs before
setup_arg_pages() and the segment mappings, so the old address space is
freed before the new one is populated and peak memory is unchanged. The
ordering constraints are kept: old_mm's mmap_lock is still dropped in
exec_mmap() before mm_update_next_owner() (required since commit
31a78f23bac0 ("mm owner: fix race between swapoff and exit")), and
mm_update_next_owner() still precedes mmput(); both run in the execing
task's context, as mm_update_next_owner() requires.
If exec swaps the mm but fails before setup_new_exec() runs the old mm
would leak, so add a backstop in free_bprm(). The lazy-tlb case
(old_mm == NULL, e.g. kernel_execve()) has no address space to
free and is left in exec_mmap().
Link: https://patch.msgid.link/20260522-work-exit_mm-v1-1-bd32d5a560bb@kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
diff --git a/fs/exec.c b/fs/exec.c
index 9e7f25e2cd41..824b46c069ae 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -836,16 +836,18 @@ EXPORT_SYMBOL(read_code);
/*
* Maps the mm_struct mm into the current task struct.
* On success, this function returns with exec_update_lock
- * held for writing.
+ * held for writing. The replaced address space is stashed in
+ * bprm->old_mm for setup_new_exec() to release outside the lock.
*/
-static int exec_mmap(struct mm_struct *mm, struct user_namespace *user_ns)
+static int exec_mmap(struct linux_binprm *bprm)
{
struct task_exec_state *exec_state __free(put_task_exec_state) = NULL;
+ struct mm_struct *mm = bprm->mm;
struct task_struct *tsk;
struct mm_struct *old_mm, *active_mm;
int ret;
- exec_state = alloc_task_exec_state(user_ns);
+ exec_state = alloc_task_exec_state(bprm->user_ns);
if (!exec_state)
return -ENOMEM;
@@ -898,15 +900,22 @@ static int exec_mmap(struct mm_struct *mm, struct user_namespace *user_ns)
if (old_mm) {
mmap_read_unlock(old_mm);
BUG_ON(active_mm != old_mm);
- setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm);
- mm_update_next_owner(old_mm);
- mmput(old_mm);
+ /* Defer teardown to setup_new_exec(), outside the exec locks. */
+ bprm->old_mm = old_mm;
return 0;
}
mmdrop_lazy_tlb(active_mm);
return 0;
}
+/* Release the address space replaced by exec, outside the exec locks. */
+static void exec_mm_put_old(struct mm_struct *old_mm)
+{
+ setmax_mm_hiwater_rss(¤t->signal->maxrss, old_mm);
+ mm_update_next_owner(old_mm);
+ mmput(old_mm);
+}
+
static int de_thread(struct task_struct *tsk)
{
struct signal_struct *sig = tsk->signal;
@@ -1155,7 +1164,7 @@ int begin_new_exec(struct linux_binprm * bprm)
* Release all of the old mmap stuff
*/
acct_arg_size(bprm, 0);
- retval = exec_mmap(bprm->mm, bprm->user_ns);
+ retval = exec_mmap(bprm);
if (retval)
goto out;
@@ -1338,6 +1347,12 @@ void setup_new_exec(struct linux_binprm * bprm)
me->mm->task_size = TASK_SIZE;
up_write(&me->signal->exec_update_lock);
mutex_unlock(&me->signal->cred_guard_mutex);
+
+ /* The exec locks are dropped: release the old address space now. */
+ if (bprm->old_mm) {
+ exec_mm_put_old(bprm->old_mm);
+ bprm->old_mm = NULL;
+ }
}
EXPORT_SYMBOL(setup_new_exec);
@@ -1394,6 +1409,9 @@ static void free_bprm(struct linux_binprm *bprm)
mutex_unlock(¤t->signal->cred_guard_mutex);
abort_creds(bprm->cred);
}
+ /* exec swapped the mm but failed before setup_new_exec() freed it */
+ if (bprm->old_mm)
+ exec_mm_put_old(bprm->old_mm);
do_close_execat(bprm->file);
if (bprm->executable)
fput(bprm->executable);
diff --git a/include/linux/binfmts.h b/include/linux/binfmts.h
index a8379f4eee61..2c77e383e737 100644
--- a/include/linux/binfmts.h
+++ b/include/linux/binfmts.h
@@ -25,6 +25,7 @@ struct linux_binprm {
struct page *page[MAX_ARG_PAGES];
#endif
struct mm_struct *mm;
+ struct mm_struct *old_mm; /* replaced address space, freed by setup_new_exec() */
/* user_ns published to task->exec_state at execve, narrowed by would_dump(). */
struct user_namespace *user_ns;
unsigned long p; /* current top of mem */
]
|
| 69/2 |
2026/09/23 15:49 |
llm |
expert |
0m
Model:
Tokens:
input: 62302
output: 34
thoughts: 1169
Thoughts: **Analyzing Recent Commit and Process Behavior**
Okay, first thing I notice is that commit `38205ecbe6b6` is pretty fresh, dating back to May 2026. That piques my interest immediately. I need to figure out if it's connected to this race condition we're investigating. Let's dig into the details from the report and connect the dots.
The report shows a write operation of 8 bytes by task 21217 on CPU 1, and a read of 1728 bytes by task 3876 on CPU 0. The write traces to `__mmput` and `exit_mm`, and the read, to the `clone` system call. The write operation involves `__list_del`, which is interesting, given the memory corruption scenario.
Aha! Task 21217 is calling `exit_mm`. Crucially, it's NOT in `exec_mm_put_old`, as I suspected, but in `exit_mm` instead! This changes everything. Let's get the exact line numbers from task 21217: `kernel/fork.c` lines 1198 and 1216, `kernel/exit.c` lines 618, 1000 and 1155, and `kernel/signal.c` line 3112.
Now, let's carefully consider the sequence. We have a task exiting via `do_group_exit`, which then calls `get_signal`. Now, I need to understand the connection between these two tasks, 21217 and 3876. I need to know why 21217 is terminating through the group exit.
To clarify, let's check `kernel/signal.c` line 3112 to confirm my initial hypothesis on the control flow. Who is task 3876 and 21217, and what is each task's role in this race? It's time to dig into the process IDs and see what context they are running under. Let's see if this lines up with the memory model we have in mind for the race condition.
|
| 70/2 |
2026/09/23 15:49 |
tool |
read-file |
0m
Args: map[File:kernel/signal.c FirstLine:3100 LineCount:30]
Results: map[Contents:3100: /*
3101: * PF_USER_WORKER threads will catch and exit on fatal signals
3102: * themselves. They have cleanup that must be performed, so we
3103: * cannot call do_exit() on their behalf. Note that ksig won't
3104: * be properly initialized, PF_USER_WORKER's shouldn't use it.
3105: */
3106: if (current->flags & PF_USER_WORKER)
3107: goto out;
3108:
3109: /*
3110: * Death signals, no core dump.
3111: */
3112: do_group_exit(signr);
3113: /* NOTREACHED */
3114: }
3115: spin_unlock_irq(&sighand->siglock);
3116:
3117: ksig->sig = signr;
3118:
3119: if (signr && !(ksig->ka.sa.sa_flags & SA_EXPOSE_TAGBITS))
3120: hide_si_addr_tag_bits(ksig);
3121: out:
3122: return signr > 0;
3123: }
3124:
3125: /**
3126: * signal_delivered - called after signal delivery to update blocked signals
3127: * @ksig: kernel signal struct
3128: * @stepping: nonzero if debugger single-step or block-step in use
3129: *
]
|
| 71/2 |
2026/09/23 15:49 |
llm |
expert |
0m
Model:
Tokens:
input: 64430
output: 29
thoughts: 2317
Thoughts: **Analyzing a Memory Management Double-Free Vulnerability**
Okay, so I've got this death signal on task 21217. My mind immediately races – what's the cause? It's time to dig into the kernel's memory management to understand the root cause! The core issue is that `mmput` is dropping `mm_users` to zero in task 21217, but task 3876 is still using that same memory structure. This shouldn't be possible, and it suggests a critical error.
First, I consider the common scenarios: Are they related by threading? Could 21217 be a thread of 3876? If they were in the same thread group, and there were two threads and 3876 was still alive then `mm_users` should be at least two, since each thread would have a reference. But what if `mm_users` is one instead of two? Perhaps they're *not* in the same thread group? How could they share the same memory structure then? Ah, I remember - `clone(CLONE_VM)` without `CLONE_THREAD` allows different thread groups to share an `mm`. But even then, `mmget` is called, so `mm_users` should still be two.
Next, I think - is task 3876 using `copy_mm` to perform cloning of memory space, is it the parent, or the child, in this scenario? I confirm that task 3876 is the current task, and then examine `copy_mm`. I'm seeing that task 3876's `current->mm` is `0xffff888104668000`, which is the very same `mm` being used by 21217.
But wait, I need to keep clear about the fact that if a task is calling `exit_mm()` then it can set current->mm to null BEFORE calling `mmput(mm)`. Also, in the case of `exec`, the old `mm` is released in a similar manner.
I consider `vfork`. If A calls `vfork()`, a child B is created, sharing the `mm`. If B calls `clone()` (effectively `fork()`) it will `dup_mm`, which wouldn't share the same `mm` as the original parent, which would be waiting.
So I need to rule out `vfork`, since the parent should be waiting for the child.
So the key now is to identify how task 3876 gets the same `mm` as 21217, and which `mm_users` counter would get decremented in this process.
`copy_mm` calls `dup_mm` when `CLONE_VM` is *not* set. Now, I see that this is the relevant path: task 3876's `kernel_clone` calls `copy_process` calls `copy_mm`. That task 3876 calls `dup_mm(tsk, current->mm)`, where `tsk` is the new child. Crucially, 21217 is calling `exit_mm` and the same `mm_struct`, so the same memory structure is indeed shared!
So the critical issue is: why is `mm_users` dropping to zero? `__mmput` is only called when `atomic_dec_and_test(&mm->mm_users)` hits zero. Thus, when `mm->mm_users` was 1, 21217 decremented it to zero.
So the key question is, why was `mm->mm_users` equal to 1? Task 3876 has `current->mm == mm`. But how is it *possible* for a task to have a valid `current->mm` that *doesn't* contribute to the `mm_users` count? This is a memory management violation. I need to review every place where `mm_users` is decremented or where `current->mm` is set. I need to be *sure* to catch how this double free is occurring.
I'll also keep `io_uring` in mind - could it be contributing to an invalid `mm` reference in `current`.
|
| 72/2 |
2026/09/23 15:49 |
tool |
grepper |
0m
Error:
Args: map[Expression:kthread_use_mm PathPrefix:io_uring]
Results:
|
| 73/2 |
2026/09/23 15:49 |
llm |
expert |
0m
Model:
Tokens:
input: 67719
output: 25
thoughts: 27
Thoughts: Here's my thought process, as if I were considering those search terms within the context of `io_uring`:
**Digging into io_uring Memory Management**
Okay, so I'm thinking about memory management within `io_uring`. I want to zero in on how it interacts with the process's memory space, especially given the asynchronous nature of this interface. That leads me to suspect I'll be interested in how the kernel interacts with the process memory map.
My initial approach is to start with a targeted keyword search. I'm going to look for key functions or structures involved in this area. Specifically, the keywords that jump out at me are `mmput`, `current->mm`, and `mmget`. `mmput` and `mmget` are, of course, the obvious candidates for reference counting and managing the memory map, while `current->mm` is how the kernel usually accesses the memory map of the current process. Searching for these will almost certainly provide the critical interactions I need to understand. I'm going to start my search with these and see what comes up within the `io_uring/` directory. That's likely where the core of this interaction is defined. I'll make sure to note all the contexts each keyword is used in. Then, I can start mapping out how `io_uring` interacts with the process memory space.
|
| 74/2 |
2026/09/23 15:50 |
tool |
grepper |
0m
Error:
Args: map[Expression:mmget PathPrefix:io_uring]
Results:
|
| 75/2 |
2026/09/23 15:50 |
llm |
expert-compressor |
0m
Model:
Reply: ### 1. Approaches Tried and Results
* **Report Dissection:**
* Analyzed KCSAN data race report between task 21217 (`__mmput` / `list_del(&mm->mmlist)`) and task 3876 (`copy_mm` / `dup_mm` / `memcpy(mm, oldmm, sizeof(*mm))`).
* Identified addresses and offsets:
* Read: 1728 bytes starting at `0xffff888104668000` (base of `struct mm_struct`, size 1728 bytes / 0x6c0).
* Write: 8 bytes at `0xffff8881046681f8` (offset 0x1f8 = 504 bytes, which is `mm->mmlist`).
* Investigated `__mmput`:
* Line 1198 in `kernel/fork.c`: `list_del(&mm->mmlist)` under `mmlist_lock`.
* Preceded by `mmput` -> `if (atomic_dec_and_test(&mm->mm_users)) __mmput(mm);`.
* Investigated `dup_mm`:
* Line 1537 in `kernel/fork.c`: `memcpy(mm, oldmm, sizeof(*mm))` done *before* `dup_mmap` takes `mmap_write_lock_killable(oldmm)`. No locks on `oldmm` are held during `memcpy`.
* **Hypothesis 1: Thread group exit / CLONE_VM sibling teardown:**
* Examined `do_group_exit` (`kernel/exit.c:1130`) and `zap_other_threads`.
* Examined `exit_mm` (`kernel/exit.c:584`): clears `current->mm = NULL`, calls `mmput(mm)`.
* Checked how `mm_users` could hit zero if task 3876 still had `current->mm == oldmm`.
* If task 3876 and task 21217 were `CLONE_VM` siblings, `mm_users` should have been at least 2 (`mmget` called on `CLONE_VM` in `copy_mm`).
* If both are running, `mmput` from 21217 alone should only decrement `mm_users` to 1, unless task 3876 had already released its `mm` (not possible while running `copy_process` via `sys_clone`) or something else happened.
* **Hypothesis 2: `execve` / `de_thread` / `exec_mmap`:**
* Examined `fs/exec.c` (`exec_mmap`, `de_thread`, `exec_mm_put_old`).
* `de_thread` terminates all other threads before `exec_mmap` proceeds.
* Dead-end: `exec` waits for all other threads to die (`sig->notify_count == 0`), so a concurrent `clone()` by another thread in the same group cannot race with `exec_mm_put_old` from `setup_new_exec`.
* **Hypothesis 3: Signal termination / Process teardown / Failure paths:**
* Looked into `copy_process` error paths: `bad_fork_cleanup_mm` calls `mmput(p->mm)`.
* Looked at `fatal_signal_pending(current)` in `copy_process` (line 2495), which is well after `copy_mm` (line 2310).
* **Hypothesis 4: Locking during `dup_mm`:**
* Inspected `dup_mm` and `dup_mmap` (`mm/mmap.c:1708`).
* In `dup_mm`:
```c
memcpy(mm, oldmm, sizeof(*mm));
...
dup_mmap(mm, oldmm);
```
* `dup_mmap` acquires `mmap_write_lock_killable(oldmm)`. But `memcpy(mm, oldmm, sizeof(*mm))` occurs *prior* to `dup_mmap` acquiring `mmap_lock` on `oldmm`!
* Furthermore, `mmlist_lock` protects `mm->mmlist`, but `memcpy` in `dup_mm` does not hold `mmlist_lock` or `mmap_lock`.
---
### 2. Current Hypotheses & Active Lines of Investigation
1. **How `__mmput` was reached concurrently with `dup_mm` on the same `mm`:**
* Is it possible for another task/process to hold an `mm` reference and call `mmput`, dropping `mm_users` to 0 while `current->mm` still points to it?
* *Scenario A:* Could `oldmm` be manipulated via `kthread_use_mm` / `use_mm`? (Task 3876 is in `sys_clone`, so it's a userspace task, not kthread).
* *Scenario B:* Ptrace / `process_vm_access` / `/proc/$pid/mem`? Those take `mm_users` (`mm_access()` -> `get_task_mm()`) and put it with `mmput()`, but that increments and decrements, never drops it below 1 unless the task is already exiting.
* *Scenario C:* Multithreaded process where task A does `sys_clone()` without `CLONE_VM` (i.e. `fork()`). Meanwhile, another thread or process does something that results in `mmput`. Why would `mm_users` hit 0?
* What if task 3876 is an exiting task or what if task 3876 was forked from a process where `mm_users` was already 1?
* What if task 21217 is the *last* user of `oldmm`, but why would task 3876 have `current->mm == oldmm`?
* Check if task 3876 *is* the child or parent: task 3876 called `sys_clone` -> `kernel_clone` -> `copy_process` -> `copy_mm` -> `dup_mm(tsk, current->mm)`. So task 3876 is the parent calling `clone()`.
* If task 3876 is the parent calling `clone()`, why did task 21217 call `__mmput` on task 3876's `current->mm`?
* Could task 21217 be another thread sharing `mm`? If task 21217 and task 3876 shared `mm`, `mm_users` should be at least 2! How could `atomic_dec_and_test(&mm->mm_users)` trigger in `exit_mm`?
* Let's check `mm_users` accounting across all clone/fork flags (e.g. `CLONE_VM` without `CLONE_THREAD`, or `io_uring`, or vhost, or something doing an extra `mmput` or missing `mmget`).
* OR: Could `0xffff888104668000` be an `mm_struct` that was *freed and reallocated* (SLAB / kmem_cache reuse, Use-After-Free)?
* Check if `mm_struct` is allocated via `kmem_cache` (`mm_cachep`).
* If it's a slab reuse, KCSAN wouldn't normally report a data race unless both accesses touched the same live allocation, or KCSAN tracked the address across a free/alloc.
* OR: Could this be `mm` borrowed/used elsewhere, or `atomic_dec_and_test` occurring because of a bug or specific kernel mechanism (e.g., `exit_mm` running when another thread died without decrements)?
* Check `kernel/fork.c`: `dup_mm`:
```c
memcpy(mm, oldmm, sizeof(*mm));
if (!mm_init(mm, tsk))
goto fail_nomem;
```
In `mm_init()`:
```c
INIT_LIST_HEAD(&mm->mmlist);
```
Note that `memcpy` blindly copied `oldmm->mmlist` into `mm->mmlist`! Then `mm_init` re-initializes `mm->mmlist`. But reading `oldmm->mmlist` during `memcpy` races with anything modifying `oldmm->mmlist`.
2. **What modifies `oldmm->mmlist` concurrently?**
* `__mmput` does `list_del(&mm->mmlist)`.
* What else modifies `mmlist`? `ksm`, `swap`, etc.
* Does `dup_mm` hold any lock against concurrent modifications to `oldmm`?
* Why does `dup_mm` use `memcpy` before acquiring `mmap_lock`?
* Why was `__mmput` called on `oldmm`?
* Need to check: Could another thread have called `exit_mm()`? Why did `mm_users` become 0?
---
### 3. Critical Code Snippets & File Paths
* **`kernel/fork.c:1185` (`__mmput`):**
```c
static inline void __mmput(struct mm_struct *mm)
{
VM_BUG_ON(atomic_read(&mm->mm_users));
uprobe_clear_state(mm);
exit_aio(mm);
ksm_exit(mm);
khugepaged_exit(mm); /* must run before exit_mmap */
exit_mmap(mm);
mm_put_huge_zero_folio(mm);
set_mm_exe_file(mm, NULL);
if (!list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
list_del(&mm->mmlist);
spin_unlock(&mmlist_lock);
}
if (mm->binfmt)
module_put(mm->binfmt->module);
lru_gen_del_mm(mm);
futex_hash_free(mm);
mmdrop(mm);
}
```
* **`kernel/fork.c:1211` (`mmput`):**
```c
void mmput(struct mm_struct *mm)
{
might_sleep();
if (atomic_dec_and_test(&mm->mm_users))
__mmput(mm);
}
```
* **`kernel/fork.c:1527` (`dup_mm`):**
```c
static struct mm_struct *dup_mm(struct task_struct *tsk,
struct mm_struct *oldmm)
{
struct mm_struct *mm;
int err;
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
if (!mm_init(mm, tsk))
goto fail_nomem;
uprobe_start_dup_mmap();
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
uprobe_end_dup_mmap();
...
```
* **`kernel/exit.c:584` (`exit_mm`):**
```c
static void exit_mm(void)
{
struct mm_struct *mm = current->mm;
...
mmap_read_lock(mm);
mmgrab_lazy_tlb(mm);
BUG_ON(mm != current->active_mm);
task_lock(current);
smp_mb__after_spinlock();
local_irq_disable();
current->mm = NULL;
membarrier_update_current_mm(NULL);
enter_lazy_tlb(mm, current);
local_irq_enable();
task_unlock(current);
mmap_read_unlock(mm);
mm_update_next_owner(mm);
mmput(mm);
...
}
```
* **`include/linux/mm_types.h:1175` (`struct mm_struct`):**
* `mmlist` at offset 504 (0x1f8).
* `sizeof(struct mm_struct)` is 1728 (0x6c0) bytes.
---
### 4. Watch Out for Loops / Next Steps to Investigate
* **Avoid repetitive grepping** on basic clone/exit mechanisms.
* **Key unanswered questions to investigate next:**
1. How can `atomic_dec_and_test(&mm->mm_users)` succeed in task 21217 while task 3876 is in `copy_process` reading `current->mm`?
* Search kernel for any race or commit regarding `atomic_dec_and_test(&mm->mm_users)` or `mmput` vs `clone` / `copy_mm` / `dup_mm`.
* Check if `CLONE_VM` allows creating a thread without incrementing `mm_users`? (No, `copy_mm` does `mmget`).
* Check `io_uring` worker / `vhost` / `kthread_use_mm`?
* Check if `oldmm` could have had `mm_users` decremented prematurely.
* Check what `set-results` classification applies once the concurrency mechanism is confirmed (HARMFUL: teardown/use-after-free or torn list pointer copy vs BENIGN).
2. Examine git history for:
* `git log -S "memcpy(mm, oldmm"`
* `git log -S "list_del(&mm->mmlist)"`
* Known KCSAN reports on `dup_mm` vs `__mmput` or `list_del(&mm->mmlist)`.
Tokens:
input: 42549
output: 3261
thoughts: 0
|
| 76/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 18424
output: 40
thoughts: 0
|
| 77/2 |
2026/09/23 15:50 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:5 Name:create_io_thread]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:create_io_worker SourceFile:io_uring/io-wq.c SourceLine:925 SourceSnippet: 920: worker->wq = wq;
921: worker->acct = acct;
922: raw_spin_lock_init(&worker->lock);
923: init_completion(&worker->ref_done);
924:
925: tsk = create_io_thread(io_wq_worker, worker, NUMA_NO_NODE);
926: if (!IS_ERR(tsk)) {
927: io_init_new_worker(wq, acct, worker, tsk);
928: } else if (!io_should_retry_thread(worker, PTR_ERR(tsk))) {
929: kfree(worker);
930: goto fail;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:create_worker_cont SourceFile:io_uring/io-wq.c SourceLine:860 SourceSnippet: 855:
856: worker = container_of(cb, struct io_worker, create_work);
857: clear_bit_unlock(0, &worker->create_state);
858: wq = worker->wq;
859: acct = io_wq_get_acct(worker);
860: tsk = create_io_thread(io_wq_worker, worker, NUMA_NO_NODE);
861: if (!IS_ERR(tsk)) {
862: io_init_new_worker(wq, acct, worker, tsk);
863: io_worker_release(worker);
864: return;
865: } else if (!io_should_retry_thread(worker, PTR_ERR(tsk))) {
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:io_sq_offload_create SourceFile:io_uring/sqpoll.c SourceLine:513 SourceSnippet: 508: sqd->sq_cpu = -1;
509: }
510:
511: sqd->task_pid = current->pid;
512: sqd->task_tgid = current->tgid;
513: tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
514: if (IS_ERR(tsk)) {
515: ret = PTR_ERR(tsk);
516: goto err_sqpoll;
517: }
518:
]] TruncatedOutput:false]
|
| 78/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 19220
output: 34
thoughts: 0
|
| 79/2 |
2026/09/23 15:50 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:create_io_thread]
Results: map[SourceCode:2688: /*
2689: * This is like kernel_clone(), but shaved down and tailored to just
2690: * creating io_uring workers. It returns a created task, or an error pointer.
2691: * The returned task is inactive, and the caller must fire it up through
2692: * wake_up_new_task(p). All signals are blocked in the created task.
2693: */
2694: struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2695: {
2696: unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2697: CLONE_IO|CLONE_VM|CLONE_UNTRACED;
2698: struct kernel_clone_args args = {
2699: .flags = flags,
2700: .fn = fn,
2701: .fn_arg = arg,
2702: .io_thread = 1,
2703: .user_worker = 1,
2704: };
2705:
2706: return copy_process(NULL, 0, node, &args);
2707: }
SourceFile:kernel/fork.c]
|
| 80/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 19627
output: 32
thoughts: 0
|
| 81/2 |
2026/09/23 15:50 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_mm]
Results: map[SourceCode:1568: static int copy_mm(u64 clone_flags, struct task_struct *tsk)
1569: {
1570: struct mm_struct *mm, *oldmm;
1571:
1572: tsk->min_flt = tsk->maj_flt = 0;
1573: tsk->nvcsw = tsk->nivcsw = 0;
1574: #ifdef CONFIG_DETECT_HUNG_TASK
1575: tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1576: tsk->last_switch_time = 0;
1577: #endif
1578:
1579: tsk->mm = NULL;
1580: tsk->active_mm = NULL;
1581:
1582: /*
1583: * Are we cloning a kernel thread?
1584: *
1585: * We need to steal a active VM for that..
1586: */
1587: oldmm = current->mm;
1588: if (!oldmm)
1589: return 0;
1590:
1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
1597: return -ENOMEM;
1598: }
1599:
1600: tsk->mm = mm;
1601: tsk->active_mm = mm;
1602: return 0;
1603: }
SourceFile:kernel/fork.c]
|
| 82/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 20170
output: 33
thoughts: 1127
Thoughts: **Analyzing a Potential Memory Management Issue**
Okay, let's break this down. I see two seemingly unrelated stack traces here, and my intuition tells me there's more than meets the eye.
First, task 3876 is performing a `sys_clone` call, but notably *without* the `CLONE_VM` flag. This means a new memory space is supposed to be created. The call stack shows `dup_mm`, `copy_mm`, and eventually `copy_process`, indicating the memory management data structures are being duplicated, a process that should lead to independent memory spaces. The kernel reports that task 3876's `current->mm` is at `0xffff888104668000`. So far, so good, a standard `fork` behavior without shared memory.
The second stack trace, from task 21217, is where things get interesting. This task is calling `exit_mm`, which leads to the `mmput` family of functions and, ultimately, a `list_del` operation. This `list_del` is acting on the same memory address, `0xffff888104668000`, as task 3876's `current->mm`. And it's writing to the `mmlist` field, the linked list used by the memory management structure. Now, that's not right.
The central point of my concern is this: task 21217 is deallocating, via `exit_mm`, the *exact* same memory structure (`mm`) that task 3876 is currently using *as its own*. It's a classic race condition or double free scenario in the making. The problem arises because 3876 has created a copy of the parent memory, and, because it did NOT use `CLONE_VM` it should not share the underlying memory.
I need to confirm the ownership and lifetime of this memory region and how 21217 gets a reference to the same memory region being copied by 3876. I have to find the point in time when 21217 somehow ends up with a reference to a memory structure that should be exclusively owned by 3876 after the `clone` operation.
|
| 83/2 |
2026/09/23 15:50 |
tool |
read-file |
0m
Args: map[File:kernel/exit.c FirstLine:580 LineCount:45]
Results: map[Contents: 580: /*
581: * Turn us into a lazy TLB process if we
582: * aren't already..
583: */
584: static void exit_mm(void)
585: {
586: struct mm_struct *mm = current->mm;
587:
588: mm_exit_exec_release(current, mm);
589: if (!mm)
590: return;
591:
592: exit_mm_sched_cache(mm);
593:
594: mmap_read_lock(mm);
595: mmgrab_lazy_tlb(mm);
596: BUG_ON(mm != current->active_mm);
597: /* more a memory barrier than a real lock */
598: task_lock(current);
599: /*
600: * When a thread stops operating on an address space, the loop
601: * in membarrier_private_expedited() may not observe that
602: * tsk->mm, and the loop in membarrier_global_expedited() may
603: * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
604: * rq->membarrier_state, so those would not issue an IPI.
605: * Membarrier requires a memory barrier after accessing
606: * user-space memory, before clearing tsk->mm or the
607: * rq->membarrier_state.
608: */
609: smp_mb__after_spinlock();
610: local_irq_disable();
611: current->mm = NULL;
612: membarrier_update_current_mm(NULL);
613: enter_lazy_tlb(mm, current);
614: local_irq_enable();
615: task_unlock(current);
616: mmap_read_unlock(mm);
617: mm_update_next_owner(mm);
618: mmput(mm);
619: if (test_thread_flag(TIF_MEMDIE))
620: exit_oom_victim();
621: }
622:
623: static struct task_struct *find_alive_thread(struct task_struct *p)
624: {
]
|
| 84/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 22501
output: 34
thoughts: 788
Thoughts: **Analyzing `exit_mm` and Memory Management in the Kernel**
Okay, let's break this down. I'm looking at `exit_mm`, specifically the lines where `current->mm` is set to NULL and `mmput(mm)` is called. My initial thought is focused on how the reference count, `mm->mm_users`, is managed. The key lies in `atomic_dec_and_test(&mm->mm_users)`. If this returns true, it means the count decremented from 1 to 0, which triggers a deallocation via `__mmput`.
Then the thought strikes: if task 21217 had `current->mm == mm` and the atomic decrement brought `mm_users` to zero, that implies its count was *one* just before 21217 decremented. But wait, how could another task, say 3876, *also* have `current->mm == mm`? This raises a red flag immediately.
The obvious conclusion is that 21217 and 3876 are likely threads, sharing the same memory space (`mm`). This is reinforced by the `CLONE_VM` flag in `copy_mm`. When a thread is created with `CLONE_VM`, the `copy_mm` function calls `mmget(oldmm)`, effectively incrementing `mm->mm_users`. So, each thread with the shared `mm` *should* contribute to this count.
So let's walk through it. Say thread 1 starts. Its `mm_users` is 1. If thread 1 creates thread 2 with `CLONE_VM`, `mmget(oldmm)` is called, so `mm_users` becomes 2. Both threads have `tsk->mm == mm`. If thread 2 exits, its `exit_mm()` is called, and `mmput(mm)` is invoked. This decrements `mm_users` to 1. Since `atomic_dec_and_test` returns false, `__mmput` is *not* called. It's only when the *last* thread exits that `mm_users` hits zero, and the memory is deallocated.
So... why would `__mmput` be called in task 21217 if task 3876, another thread, is still alive and has `current->mm == mm`? That's the core question. It shouldn't happen, based on how I understand the reference counting. This leads to a crucial hypothesis: either task 3876 is *not* properly sharing the mm in the expected way, its reference isn't correctly accounted for, *or* there's a concurrency issue.
Could task 3876 have failed to increment `mm_users`? Or, conversely, could there be a premature decrement? Or are 3876 and 21217 related in a way I'm not seeing? This is where I need to look deeper into other functions interacting with `mm_users` and how `current->mm` can be accessed concurrently with `__mmput`. I'll start by checking `kernel/fork.c:1537` to see what I missed.
|
| 85/2 |
2026/09/23 15:50 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1520 LineCount:40]
Results: map[Contents:1520: * @oldmm: the mm to duplicate.
1521: *
1522: * Allocates a new mm structure and duplicates the provided @oldmm structure
1523: * content into it.
1524: *
1525: * Return: the duplicated mm or NULL on failure.
1526: */
1527: static struct mm_struct *dup_mm(struct task_struct *tsk,
1528: struct mm_struct *oldmm)
1529: {
1530: struct mm_struct *mm;
1531: int err;
1532:
1533: mm = allocate_mm();
1534: if (!mm)
1535: goto fail_nomem;
1536:
1537: memcpy(mm, oldmm, sizeof(*mm));
1538:
1539: if (!mm_init(mm, tsk))
1540: goto fail_nomem;
1541:
1542: uprobe_start_dup_mmap();
1543: err = dup_mmap(mm, oldmm);
1544: if (err)
1545: goto free_pt;
1546: uprobe_end_dup_mmap();
1547:
1548: mm->hiwater_rss = get_mm_rss(mm);
1549: mm->hiwater_vm = mm->total_vm;
1550:
1551: if (mm->binfmt && !try_module_get(mm->binfmt->module))
1552: goto free_pt;
1553:
1554: return mm;
1555:
1556: free_pt:
1557: /* don't put binfmt in mmput, we haven't got module yet */
1558: mm->binfmt = NULL;
1559: mm_init_owner(mm, NULL);
]
|
| 86/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 24580
output: 34
thoughts: 500
Thoughts: **Analyzing a Memory Corruption Vulnerability in `dup_mm`**
Okay, let's break this down. I'm looking at the `dup_mm` function, specifically how it duplicates the memory management structure during a `fork` operation. The code first allocates a new `mm_struct` called `mm`, and then it uses `memcpy` on line 1537 to copy data from the old memory management structure, `oldmm`, into the newly allocated `mm`.
Now, the red flag immediately pops up: `memcpy(mm, oldmm, sizeof(*mm));`. I see that `sizeof(*mm)` is 1728 bytes! It's a sizable chunk of memory. `memcpy` copies exactly that many bytes from `oldmm` to `mm`.
So, `memcpy` reads exactly 1728 bytes from `oldmm` at address `0xffff888104668000`.
Then I see some interesting output from the system which shows that `task 21217` is writing 8 bytes to address `0xffff8881046681f8` on CPU 1. This write happens within the context of `__mmput`, which is called from the `exit_mm` and `do_exit` functions. This means a process (or thread) is in the process of exiting and is releasing its memory, which leads to `mmput` being called.
Specifically, the write happens inside of `__list_del`. My suspicion is that this write is happening at an offset, in the very data that `memcpy` copied from `oldmm` into `mm`.
The code shows that on line 1198 of `kernel/fork.c`, `__mmput` is being called.
This looks like a potential use-after-free situation, or possibly a double-free, where a process might be deallocating memory that's still being used or referenced by the newly forked process. This is a very interesting avenue to pursue, as `memcpy` is writing to one memory location, while this other task is writing to another location that the first one is using.
|
| 87/2 |
2026/09/23 15:50 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1185 LineCount:35]
Results: map[Contents:1185: static inline void __mmput(struct mm_struct *mm)
1186: {
1187: VM_BUG_ON(atomic_read(&mm->mm_users));
1188:
1189: uprobe_clear_state(mm);
1190: exit_aio(mm);
1191: ksm_exit(mm);
1192: khugepaged_exit(mm); /* must run before exit_mmap */
1193: exit_mmap(mm);
1194: mm_put_huge_zero_folio(mm);
1195: set_mm_exe_file(mm, NULL);
1196: if (!list_empty(&mm->mmlist)) {
1197: spin_lock(&mmlist_lock);
1198: list_del(&mm->mmlist);
1199: spin_unlock(&mmlist_lock);
1200: }
1201: if (mm->binfmt)
1202: module_put(mm->binfmt->module);
1203: lru_gen_del_mm(mm);
1204: futex_hash_free(mm);
1205: mmdrop(mm);
1206: }
1207:
1208: /*
1209: * Decrement the use count and release all resources for an mm.
1210: */
1211: void mmput(struct mm_struct *mm)
1212: {
1213: might_sleep();
1214:
1215: if (atomic_dec_and_test(&mm->mm_users))
1216: __mmput(mm);
1217: }
1218: EXPORT_SYMBOL_GPL(mmput);
1219:
]
|
| 88/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 26091
output: 39
thoughts: 134
Thoughts: **Analyzing Memory Management Structure Deletion**
Okay, let's break this down. Line 1198. Right, that's where `list_del(&mm->mmlist);` is executed. My immediate thought is, "Yes, that's *precisely* the line we're focusing on!".
Now, `list_del` is the key here. We're removing the `mm` structure from the linked list. My understanding of the linked list data structure tells me that this function directly manipulates the `next` and `prev` pointers of the `mmlist` element. It's essentially unlinking this entry. This action is critical for freeing up the resource associated with this memory region.
I'm starting to think about where `mmlist` is located within the `mm_struct`. To confirm this, I need to know the offset of `mmlist`. My next step is clear: I'll quickly check the structure layout to pinpoint the offset. Using `codesearch-struct-layout` or a similar tool is the obvious choice to rapidly verify the exact offset within `struct mm_struct`. This is an essential step in understanding the precise impact of this `list_del` operation.
|
| 89/2 |
2026/09/23 15:50 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:kernel/fork.c FieldOffset:504 Name:mm_struct]
Results: map[Fields:[map[Name: OffsetBits:0 SizeBits:13824]]]
|
| 90/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 26556
output: 32
thoughts: 19
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm deep in my domain of expertise:
**Diving into the Data at Offset 0x1f8**
Alright, let's get down to brass tacks. The objective here is clearly to inspect the data within the immediate vicinity of offset 504 – or, as we often see it in hex, 0x1f8. This is where the real work begins. I'm immediately thinking, "What specific area of the data structure is likely residing at that offset?".
Given what I'm looking at, my brain is already running through my mental map of where certain critical fields or metadata commonly reside in this particular context. I need to quickly establish the context. "What kind of data are we dealing with here, and what am I looking for?" Depending on the data structure, this offset could be anything from a pointer to another structure, a control flag, a data length field, or even the beginning of the data itself. My expertise tells me what's most likely based on its place in the data structure.
The goal is to understand how this offset is used. I'm going to start mentally stepping through the bytes. "What do I know about the surrounding data?". I need to analyze any surrounding data at this offset in relation to adjacent, known fields to see if I can infer anything. The bytes themselves are just raw material; what is important is to understand the function of them. I'll need to interpret the significance based on the field I'm looking for. I need to understand what this information *means* in order to be an effective analyst.
|
| 91/2 |
2026/09/23 15:50 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_struct]
Results: map[Fields:[map[Name: OffsetBits:0 SizeBits:13824] map[Name:flexible_array OffsetBits:13824 SizeBits:0]]]
|
| 92/2 |
2026/09/23 15:50 |
llm |
expert |
0m
Model:
Tokens:
input: 27007
output: 36
thoughts: 23
Thoughts: Okay, let's dive into this. Here's how I'd approach that query, as my internal monologue:
**Investigating the `mm_struct` Definition**
Alright, I'm going to start by tracking down the definition of the `mm_struct`. It's a fundamental data structure in the Linux kernel's memory management system, so I need to understand it thoroughly. I know it's a critical component, so it's probably in a central, well-organized header file. Given its purpose, "mm" is a very likely hint, so *`include/linux/mm_types.h`* sounds like the best initial bet. That's where I'd expect to find the basic types and structures related to memory management.
|
| 93/2 |
2026/09/23 15:51 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/mm_types.h Name:mm_struct]
Results: map[SourceCode:1175: struct mm_struct {
1176: struct {
1177: /*
1178: * Fields which are often written to are placed in a separate
1179: * cache line.
1180: */
1181: struct {
1182: /**
1183: * @mm_count: The number of references to &struct
1184: * mm_struct (@mm_users count as 1).
1185: *
1186: * Use mmgrab()/mmdrop() to modify. When this drops to
1187: * 0, the &struct mm_struct is freed.
1188: */
1189: atomic_t mm_count;
1190: } ____cacheline_aligned_in_smp;
1191:
1192: struct maple_tree mm_mt;
1193:
1194: unsigned long mmap_base; /* base of mmap area */
1195: unsigned long mmap_legacy_base; /* base of mmap area in bottom-up allocations */
1196: #ifdef CONFIG_HAVE_ARCH_COMPAT_MMAP_BASES
1197: /* Base addresses for compatible mmap() */
1198: unsigned long mmap_compat_base;
1199: unsigned long mmap_compat_legacy_base;
1200: #endif
1201: unsigned long task_size; /* size of task vm space */
1202: pgd_t * pgd;
1203:
1204: #ifdef CONFIG_MEMBARRIER
1205: /**
1206: * @membarrier_state: Flags controlling membarrier behavior.
1207: *
1208: * This field is close to @pgd to hopefully fit in the same
1209: * cache-line, which needs to be touched by switch_mm().
1210: */
1211: atomic_t membarrier_state;
1212: #endif
1213:
1214: /**
1215: * @mm_users: The number of users including userspace.
1216: *
1217: * Use mmget()/mmget_not_zero()/mmput() to modify. When this
1218: * drops to 0 (i.e. when the task exits and there are no other
1219: * temporary reference holders), we also release a reference on
1220: * @mm_count (which may then free the &struct mm_struct if
1221: * @mm_count also drops to 0).
1222: */
1223: atomic_t mm_users;
1224:
1225: /* MM CID related storage */
1226: struct mm_mm_cid mm_cid;
1227:
1228: /* sched_cache related statistics */
1229: struct sched_cache_stat sc_stat;
1230: #ifdef CONFIG_MMU
1231: atomic_long_t pgtables_bytes; /* size of all page tables */
1232: #endif
1233: int map_count; /* number of VMAs */
1234:
1235: spinlock_t page_table_lock; /* Protects page tables and some
1236: * counters
1237: */
1238: /*
1239: * Typically the current mmap_lock's offset is 56 bytes from
1240: * the last cacheline boundary, which is very optimal, as
1241: * its two hot fields 'count' and 'owner' sit in 2 different
1242: * cachelines, and when mmap_lock is highly contended, both
1243: * of the 2 fields will be accessed frequently, current layout
1244: * will help to reduce cache bouncing.
1245: *
1246: * So please be careful with adding new fields before
1247: * mmap_lock, which can easily push the 2 fields into one
1248: * cacheline.
1249: */
1250: struct rw_semaphore mmap_lock;
1251:
1252: struct list_head mmlist; /* List of maybe swapped mm's. These
1253: * are globally strung together off
1254: * init_mm.mmlist, and are protected
1255: * by mmlist_lock
1256: */
1257: #ifdef CONFIG_PER_VMA_LOCK
1258: struct rcuwait vma_writer_wait;
1259: /*
1260: * This field has lock-like semantics, meaning it is sometimes
1261: * accessed with ACQUIRE/RELEASE semantics.
1262: * Roughly speaking, incrementing the sequence number is
1263: * equivalent to releasing locks on VMAs; reading the sequence
1264: * number can be part of taking a read lock on a VMA.
1265: * Incremented every time mmap_lock is write-locked/unlocked.
1266: * Initialized to 0, therefore odd values indicate mmap_lock
1267: * is write-locked and even values that it's released.
1268: *
1269: * Can be modified under write mmap_lock using RELEASE
1270: * semantics.
1271: * Can be read with no other protection when holding write
1272: * mmap_lock.
1273: * Can be read with ACQUIRE semantics if not holding write
1274: * mmap_lock.
1275: */
1276: seqcount_t mm_lock_seq;
1277: #endif
1278: struct futex_mm_data futex;
1279:
1280: unsigned long hiwater_rss; /* High-watermark of RSS usage */
1281: unsigned long hiwater_vm; /* High-water virtual memory usage */
1282:
1283: unsigned long total_vm; /* Total pages mapped */
1284: unsigned long locked_vm; /* Pages that have PG_mlocked set */
1285: atomic64_t pinned_vm; /* Refcount permanently increased */
1286: unsigned long data_vm; /* VM_WRITE & ~VM_SHARED & ~VM_STACK */
1287: unsigned long exec_vm; /* VM_EXEC & ~VM_WRITE & ~VM_STACK */
1288: unsigned long stack_vm; /* VM_STACK */
1289: union {
1290: /* Temporary while VMA flags are being converted. */
1291: vm_flags_t def_flags;
1292: vma_flags_t def_vma_flags;
1293: };
1294:
1295: /**
1296: * @write_protect_seq: Locked when any thread is write
1297: * protecting pages mapped by this mm to enforce a later COW,
1298: * for instance during page table copying for fork().
1299: */
1300: seqcount_t write_protect_seq;
1301:
1302: spinlock_t arg_lock; /* protect the below fields */
1303:
1304: unsigned long start_code, end_code, start_data, end_data;
1305: unsigned long start_brk, brk, start_stack;
1306: unsigned long arg_start, arg_end, env_start, env_end;
1307:
1308: unsigned long saved_auxv[AT_VECTOR_SIZE]; /* for /proc/PID/auxv */
1309:
1310: #ifdef CONFIG_ARCH_HAS_ELF_CORE_EFLAGS
1311: /* the ABI-related flags from the ELF header. Used for core dump */
1312: unsigned long saved_e_flags;
1313: #endif
1314:
1315: struct percpu_counter rss_stat[NR_MM_COUNTERS];
1316:
1317: struct linux_binfmt *binfmt;
1318:
1319: /* Architecture-specific MM context */
1320: mm_context_t context;
1321:
1322: mm_flags_t flags; /* Must use mm_flags_* hlpers to access */
1323:
1324: #ifdef CONFIG_AIO
1325: spinlock_t ioctx_lock;
1326: struct kioctx_table __rcu *ioctx_table;
1327: #endif
1328: #ifdef CONFIG_MEMCG
1329: /*
1330: * "owner" points to a task that is regarded as the canonical
1331: * user/owner of this mm. All of the following must be true in
1332: * order for it to be changed:
1333: *
1334: * current == mm->owner
1335: * current->mm != mm
1336: * new_owner->mm == mm
1337: * new_owner->alloc_lock is held
1338: */
1339: struct task_struct __rcu *owner;
1340: #endif
1341:
1342: /* store ref to file /proc/<pid>/exe symlink points to */
1343: struct file __rcu *exe_file;
1344: #ifdef CONFIG_MMU_NOTIFIER
1345: struct mmu_notifier_subscriptions *notifier_subscriptions;
1346: #endif
1347: #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
1348: pgtable_t pmd_huge_pte; /* protected by page_table_lock */
1349: #endif
1350: #ifdef CONFIG_NUMA_BALANCING
1351: /*
1352: * numa_next_scan is the next time that PTEs will be remapped
1353: * PROT_NONE to trigger NUMA hinting faults; such faults gather
1354: * statistics and migrate pages to new nodes if necessary.
1355: */
1356: unsigned long numa_next_scan;
1357:
1358: /* Restart point for scanning and remapping PTEs. */
1359: unsigned long numa_scan_offset;
1360:
1361: /* numa_scan_seq prevents two threads remapping PTEs. */
1362: int numa_scan_seq;
1363: #endif
1364: /*
1365: * An operation with batched TLB flushing is going on. Anything
1366: * that can move process memory needs to flush the TLB when
1367: * moving a PROT_NONE mapped page.
1368: */
1369: atomic_t tlb_flush_pending;
1370: #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
1371: /* See flush_tlb_batched_pending() */
1372: atomic_t tlb_flush_batched;
1373: #endif
1374: struct uprobes_state uprobes_state;
1375: #ifdef CONFIG_PREEMPT_RT
1376: struct rcu_head delayed_drop;
1377: #endif
1378: #ifdef CONFIG_HUGETLB_PAGE
1379: atomic_long_t hugetlb_usage;
1380: #endif
1381: struct work_struct async_put_work;
1382:
1383: #ifdef CONFIG_IOMMU_MM_DATA
1384: struct iommu_mm_data *iommu_mm;
1385: #endif
1386: #ifdef CONFIG_KSM
1387: /*
1388: * Represent how many pages of this process are involved in KSM
1389: * merging (not including ksm_zero_pages).
1390: */
1391: unsigned long ksm_merging_pages;
1392: /*
1393: * Represent how many pages are checked for ksm merging
1394: * including merged and not merged.
1395: */
1396: unsigned long ksm_rmap_items;
1397: /*
1398: * Represent how many empty pages are merged with kernel zero
1399: * pages when enabling KSM use_zero_pages.
1400: */
1401: atomic_long_t ksm_zero_pages;
1402: #endif /* CONFIG_KSM */
1403: #ifdef CONFIG_LRU_GEN_WALKS_MMU
1404: struct {
1405: /* this mm_struct is on lru_gen_mm_list */
1406: struct list_head list;
1407: /*
1408: * Set when switching to this mm_struct, as a hint of
1409: * whether it has been used since the last time per-node
1410: * page table walkers cleared the corresponding bits.
1411: */
1412: unsigned long bitmap;
1413: #ifdef CONFIG_MEMCG
1414: /* points to the memcg of "owner" above */
1415: struct mem_cgroup *memcg;
1416: #endif
1417: } lru_gen;
1418: #endif /* CONFIG_LRU_GEN_WALKS_MMU */
1419: #ifdef CONFIG_MM_ID
1420: mm_id_t mm_id;
1421: #endif /* CONFIG_MM_ID */
1422: } __randomize_layout;
1423:
1424: /*
1425: * The mm_cpumask needs to be at the end of mm_struct, because it
1426: * is dynamically sized based on nr_cpu_ids.
1427: */
1428: char flexible_array[] __aligned(__alignof__(unsigned long));
1429: };
SourceFile:include/linux/mm_types.h]
|
| 94/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 31149
output: 34
thoughts: 1007
Thoughts: **Analyzing a Kernel Concurrency Issue**
Okay, let's see. `mmlist` is located at offset 504. Now, I need to figure out how Task 21217 could possibly be executing `__mmput` on `oldmm` at the *same* time Task 3876 is running `dup_mm` on the *same* `oldmm`. That seems fundamentally wrong. I need to break this down.
Let's examine the call stacks:
For Task 21217, I see a write operation: It appears to be going through the exit path! It is clearly going through `__mmput`, which is called as part of process exit! Specifically: `do_exit`, and all the way back up to `get_signal`. Wait a minute! I see a signal!
`get_signal+0xe07/0xf10 kernel/signal.c:3112`
For Task 3876, the call stack reveals a read during `dup_mm`. Looks like this is a clone operation.
Now, that's interesting. Task 21217 is handling a signal and is *exiting* the process. It's using the signal to end the process. So, it appears `do_group_exit` is in the path. What's going on in `do_group_exit`? Let me see the source code in `kernel/exit.c:1155`. I need to figure out what happens in that function. It is likely that this is the mechanism where the mm is being released by the exiting task. The signal is the reason the mm is being released.
|
| 95/2 |
2026/09/23 15:51 |
tool |
read-file |
0m
Args: map[File:kernel/exit.c FirstLine:1120 LineCount:40]
Results: map[Contents:1120: SYSCALL_DEFINE1(exit, int, error_code)
1121: {
1122: do_exit((error_code & 0xff) << 8);
1123: }
1124:
1125: /*
1126: * Take down every thread in the group. This is called by fatal signals
1127: * as well as by sys_exit_group (below).
1128: */
1129: void __noreturn
1130: do_group_exit(int exit_code)
1131: {
1132: struct signal_struct *sig = current->signal;
1133:
1134: if (sig->flags & SIGNAL_GROUP_EXIT)
1135: exit_code = sig->group_exit_code;
1136: else if (sig->group_exec_task)
1137: exit_code = 0;
1138: else {
1139: struct sighand_struct *const sighand = current->sighand;
1140:
1141: spin_lock_irq(&sighand->siglock);
1142: if (sig->flags & SIGNAL_GROUP_EXIT)
1143: /* Another thread got here before we took the lock. */
1144: exit_code = sig->group_exit_code;
1145: else if (sig->group_exec_task)
1146: exit_code = 0;
1147: else {
1148: sig->group_exit_code = exit_code;
1149: sig->flags = SIGNAL_GROUP_EXIT;
1150: zap_other_threads(current);
1151: }
1152: spin_unlock_irq(&sighand->siglock);
1153: }
1154:
1155: do_exit(exit_code);
1156: /* NOTREACHED */
1157: }
1158:
1159: /*
]
|
| 96/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 33129
output: 34
thoughts: 1885
Thoughts: **Debugging a Concurrency Issue in `mm_struct` Handling**
Okay, here's what's running through my head. I'm looking at `do_group_exit`, which means a fatal signal in a thread group triggered it. I'm focusing on tasks 3876 and 21217 and wondering if they're in the same thread group. If they are, they *should* share the `mm` (memory management) structure. But then the puzzle arises: how could `atomic_dec_and_test(&mm->mm_users)` in `exit_mm` return true *before* task 3876 has even called `exit_mm`? It's still inside `dup_mm`!
This makes me question whether they are *really* in the same thread group, even though they share an `mm`. Then, wait, how would they share the same `0xffff888104668000` memory region if not? Aha! It hits me: `clone(CLONE_VM)` *without* `CLONE_THREAD`! A child process can share the `mm_struct` but have its own thread group. This is the key: `vfork` does this, as can userspace.
Okay, so with `CLONE_VM` but not `CLONE_THREAD`, the child task gets its own signal struct, but gets a shared `mm_struct`, and each process still incremented `mm_users` with `mmget()`, so if process 1 created process 2 with `CLONE_VM`, there are TWO tasks pointing to the `mm` struct, so `mm->mm_users` should be 2. If process 2 receives a fatal signal, `do_group_exit` only exits process 2. It calls `exit_mm()` -> `mmput(mm)`. This makes `atomic_dec_and_test(&mm->mm_users)`: 2 - 1 = 1 != 0, so `__mmput` should *not* be called yet. Something is wrong! Why would `__mmput` be called?
Let's think carefully: `atomic_dec_and_test(&mm->mm_users)` is 0 only when the *last* user calls `mmput(mm)`. So I need to examine how a task could *lose* its reference. Wait, is task 3876 *not* holding a valid reference, or is there an invalid decrementation? The system *should* prevent `current->mm == mm` without also holding a user reference. Let's hunt for places where `tsk->mm` is set without `mmget` or where `mmput` is called without clearing `tsk->mm`. I need to search the code.
Could task 3876 be an `io_uring` worker? Let's check. Nope, it looks like task 3876 is in userspace doing `sys_clone`, so it is a userspace task, and 21217 is not an `io_uring` worker either.
Okay, back to the `clone()` issue. Could that `0xffff888104668000` address be *reused* by slab reuse or even a use-after-free scenario?
Now, I see a crucial clue: task 3876 is *reading* from `0xffff888104668000` with `dup_mm` and `memcpy(mm, oldmm, sizeof(*mm))`. Wait! `oldmm` is the *source* of the `memcpy`, and that's the address it's *reading* from. And, task 21217 is *writing* to `0xffff8881046681f8` - and 0x1f8 bytes offset from `0xffff888104668000`. Both tasks are using *the same `mm_struct` object* concurrently! Task 21217 is *modifying* `mm->mmlist` while task 3876 is *copying* the `mm_struct` data.
WHY are they doing this concurrently? HOW can `__mmput` be running on `oldmm` while `dup_mm` is running? How can `mm_users` reach 0 while `dup_mm` is running on the same `mm_struct` object? I need to look closely at how `mm_users` is tracked and how `copy_mm` works. I need to focus on `copy_process`.
|
| 97/2 |
2026/09/23 15:51 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2300 LineCount:40]
Results: map[Contents:2300: goto bad_fork_cleanup_semundo;
2301: retval = copy_fs(clone_flags, p, args->umh);
2302: if (retval)
2303: goto bad_fork_cleanup_files;
2304: retval = copy_sighand(clone_flags, p);
2305: if (retval)
2306: goto bad_fork_cleanup_fs;
2307: retval = copy_signal(clone_flags, p);
2308: if (retval)
2309: goto bad_fork_cleanup_sighand;
2310: retval = copy_mm(clone_flags, p);
2311: if (retval)
2312: goto bad_fork_cleanup_signal;
2313: retval = copy_namespaces(clone_flags, p);
2314: if (retval)
2315: goto bad_fork_cleanup_mm;
2316: retval = copy_io(clone_flags, p);
2317: if (retval)
2318: goto bad_fork_cleanup_namespaces;
2319: retval = copy_thread(p, args);
2320: if (retval)
2321: goto bad_fork_cleanup_io;
2322:
2323: stackleak_task_init(p);
2324:
2325: if (pid != &init_struct_pid) {
2326: pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2327: args->set_tid_size);
2328: if (IS_ERR(pid)) {
2329: retval = PTR_ERR(pid);
2330: goto bad_fork_cleanup_thread;
2331: }
2332: }
2333:
2334: /*
2335: * This has to happen after we've potentially unshared the file
2336: * descriptor table (so that the pidfd doesn't leak into the child
2337: * if the fd table isn't shared).
2338: */
2339: if (clone_flags & CLONE_PIDFD) {
]
|
| 98/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 36691
output: 34
thoughts: 12
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Diving Deeper into `copy_process`**
Right, let's drill down into `copy_process`. We've identified it as the key function, now I need to understand its lower-level interactions. I'm not just interested in the high-level flow; I need to see *how* it's implemented. Specifically, I want to trace its dependencies, examine any potential areas for optimization, and of course, catch any red flags related to security or resource management. Time to dig into the guts of this thing.
|
| 99/2 |
2026/09/23 15:51 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2480 LineCount:40]
Results: map[Contents:2480: rv_task_fork(p);
2481:
2482: rseq_fork(p, clone_flags);
2483:
2484: /*
2485: * If zap_pid_ns_processes() was called after alloc_pid(), the new
2486: * child missed SIGKILL. If current is not in the same namespace,
2487: * we can't rely on fatal_signal_pending() below.
2488: */
2489: if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2490: retval = -ENOMEM;
2491: goto bad_fork_core_free;
2492: }
2493:
2494: /* Let kill terminate clone/fork in the middle */
2495: if (fatal_signal_pending(current)) {
2496: retval = -EINTR;
2497: goto bad_fork_core_free;
2498: }
2499:
2500: /* No more failure paths after this point. */
2501:
2502: /*
2503: * Copy seccomp details explicitly here, in case they were changed
2504: * before holding sighand lock.
2505: */
2506: copy_seccomp(p);
2507:
2508: if (clone_flags & CLONE_NNP)
2509: task_set_no_new_privs(p);
2510:
2511: init_task_pid_links(p);
2512: if (likely(p->pid)) {
2513: ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2514:
2515: init_task_pid(p, PIDTYPE_PID, pid);
2516: if (thread_group_leader(p)) {
2517: init_task_pid(p, PIDTYPE_TGID, pid);
2518: init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2519: init_task_pid(p, PIDTYPE_SID, task_session(current));
]
|
| 100/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 37510
output: 34
thoughts: 79
Thoughts: Here's my summary, as though I'm processing this code:
**Interrupting a Clone/Fork: A Closer Look**
Alright, let's zero in on line 2495. Ah, yes, this section here is guarding against signals interrupting a `clone` or `fork` system call midway through its execution. We want to ensure that if a fatal signal, like `SIGKILL`, comes in, we don't end up with a partially created process in a corrupted state. Makes sense.
Okay, let me just check... if `fatal_signal_pending(current)` returns true, meaning a signal is waiting to be delivered, we set the return value to `-EINTR`, signifying an interrupted system call. And, we jump to `bad_fork_core_free`. Right, that's where the critical cleanup routines are located. A quick check of `bad_fork_core_free` will verify the necessary resources are deallocated correctly in this interrupt scenario. This is crucial for avoiding resource leaks and system instability. Good, good. This looks solid.
|
| 101/2 |
2026/09/23 15:51 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2590 LineCount:40]
Results: map[Contents:2590: if (clone_flags & CLONE_PIDFD) {
2591: fput(pidfile);
2592: put_unused_fd(pidfd);
2593: }
2594: bad_fork_free_pid:
2595: if (pid != &init_struct_pid)
2596: free_pid(pid);
2597: bad_fork_cleanup_thread:
2598: exit_thread(p);
2599: bad_fork_cleanup_io:
2600: if (p->io_context)
2601: exit_io_context(p);
2602: bad_fork_cleanup_namespaces:
2603: exit_nsproxy_namespaces(p);
2604: bad_fork_cleanup_mm:
2605: if (p->mm) {
2606: mm_clear_owner(p->mm, p);
2607: mmput(p->mm);
2608: }
2609: bad_fork_cleanup_signal:
2610: if (!(clone_flags & CLONE_THREAD))
2611: free_signal_struct(p->signal);
2612: bad_fork_cleanup_sighand:
2613: __cleanup_sighand(p->sighand);
2614: bad_fork_cleanup_fs:
2615: exit_fs(p); /* blocking */
2616: bad_fork_cleanup_files:
2617: exit_files(p); /* blocking */
2618: bad_fork_cleanup_semundo:
2619: exit_sem(p);
2620: bad_fork_cleanup_security:
2621: security_task_free(p);
2622: bad_fork_cleanup_audit:
2623: audit_free(p);
2624: bad_fork_cleanup_perf:
2625: perf_event_free_task(p);
2626: bad_fork_sched_cancel_fork:
2627: sched_cancel_fork(p);
2628: bad_fork_cleanup_policy:
2629: lockdep_free_task(p);
]
|
| 102/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 38470
output: 33
thoughts: 2917
Thoughts: **Analyzing a Double Free in `mm_struct` with KCSAN**
Okay, here's what I've figured out so far. I'm looking at a situation where a `mm_struct` is being destroyed (by Task 21217 in `exit_mm`) while another task, Task 3876, appears to be actively using it (in `copy_process`). The KCSAN output points to a memory overlap, suggesting a race condition or a double-free scenario involving the `mm_struct` at `0xffff888104668000`.
Initially, my thought was a reallocated slab object, but the timing in `__mmput` rules that out. `__mmput` is freeing memory, so a re-use of that memory would require a delay between `__mmput` and the other task. Both happen at the same time: that's the key.
The stack traces are crucial: Task 3876 is in the middle of `copy_mm` (specifically, `dup_mm`), copying the `mm_struct` from `current->mm`. Task 21217 is in `exit_mm`, calling `mmput` on the *same* `mm_struct`. The `oldmm` passed to `dup_mm` is `current->mm`, which is the very `mm_struct` that 21217 is in the process of destroying!
The key question is: how can a task be in `dup_mm` with `oldmm` while `oldmm` is being destroyed in `__mmput`?
My initial thought, and the most common scenario, is a refcount issue. `exit_mm` calls `mmput`, which decrements `mm->mm_users` and if `mm_users` reaches 0, triggers `__mmput`. This looks like a race on the refcount. But how could `mm->mm_users` reach 0 when Task 3876 *should* be holding a reference? I have to consider:
* Can `exit_mm` call `mmput(mm)` and have `atomic_dec_and_test(&mm->mm_users)` trigger `__mmput`? Yes, if `mm->mm_users` drops to 0!
* How could `mm->mm_users` drop to 0 if Task 3876 has `current->mm == mm`?!
I started thinking about when a task holds a reference. Normally, a task with `tsk->mm != NULL` *should* hold a count in `mm->mm_users`. However, I need to know WHEN that reference is taken. With `CLONE_VM`, there would be at least two.
Then the key realization: both tasks must be using the same `mm_struct`. This points to either shared VM via `CLONE_VM` (not a thread group, I'm sure of it, or vfork), and there are then at least 2 users. If one task is exiting, `mm->mm_users` has to be at least 2. If it's 2, `exit_mm` -> `mmput` will not zero out `mm_users`, the normal case.
So the `mm_users` refcount imbalance is the cause, and I need to figure out why `__mmput` is being called when it shouldn't be. Either Task 3876 is *not* holding a reference, or something else is decrementing `mm->mm_users`.
Then I see the KCSAN report: it shows overlapping memory accesses, a read by CPU 0 and a write by CPU 1 to the *same* physical address. This solidifies that Task 21217 and Task 3876 are dealing with the *same* `mm_struct` instance and that the access is occurring simultaneously. This cannot be a re-use of the `mm_struct`, because the memory is being written at the same time that it's being read from!
Now the key is: how do I reconcile a task destroying its `mm_struct` *while* another task is copying from it? That means one task is not taking a ref!
Now I need to understand when `current->mm` can be destroyed *while* the current task is running or when `oldmm` is passed to `dup_mm`. I have to look into every possible kernel path related to `mm_struct` destruction and cloning, and especially the interaction between `copy_mm`, `exit_mm`, `__mmput`, and `dup_mm`. Specifically, I have to look at all cases in the Linux kernel where
|
| 103/2 |
2026/09/23 15:51 |
tool |
git-log |
0m
Args: map[Count:30 PathPrefix:kernel/fork.c Since:5 years]
Results: map[Output:b61b6f95d672 futex: Also allocate private hash on vfork()
08cacffeef8f ftrace: fork: Initialize function graph state before copy_exec_state()
221b62e97811 futex: Clean up the redundant exit/exec functions
1db1573bc59f kernel/fork: declare max_threads __read_mostly
9a560af15fd3 smp: Use task-local IPI cpumask in smp_call_function_many_cond()
38af0dd6a266 uprobes/x86: Remove struct uprobe_trampoline object
9b51a6155d14 bpf,fork: wipe ->bpf_storage before bailouts that access it
ed4b16725290 fs: add umh argument to struct kernel_clone_args
1d4ee94a51bd fs: add real_fs to track task's actual fs_struct
21bcea3ef202 fs: add switch_fs_struct()
fd38b75c4b43 kernel/fork: clear PF_BLOCK_TS in copy_process()
d7b3f52c861f futex: Make futex_mm_init() void
1628b25248d0 sched: Add blocked_donor link to task for smarter mutex handoffs
6ae51adb084a kasan: skip HW tagging for all kernel thread stacks
6b1c66c9cca9 exec_state: relocate dumpable information
09e7827e7857 kernel/fork: validate exit_signal in kernel_clone()
ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
df0d98475954 sched/cache: Introduce infrastructure for cache-aware load balancing
fa4a1ff8ab23 locking: Add task::blocked_lock to serialize blocked_on state
929cc1a53a6f fork: zero vmap stack using clear_pages() instead of memset()
8fba1920ac9f pid: document the PIDNS_ADDING checks in alloc_pid() and copy_process()
380369ea2e9d fork: replace simple_strtoul with kstrtoul in coredump_filter_setup
a98621a0f187 unshare: fix nsproxy leak in ksys_unshare() on set_cred_ucounts() failure
935a04923ad2 nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL
a96ef5848cb0 randomize_kstack: Unify random source across arches
37beb4256016 randomize_kstack: Maintain kstack_offset per task
d9c857aee2eb pid_namespace: avoid optimization of accesses to ->child_reaper
9d4e752a24f7 namespace: allow creating empty mount namespaces
c8134b5f13ae pidfd: add CLONE_PIDFD_AUTOKILL
24baca56fafc clone: add CLONE_NNP
]
|
| 104/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 43228
output: 18
thoughts: 2286
Thoughts: **Memory Management Reference Leakage in Multithreaded Processes: A Deep Dive**
Okay, so I'm digging into this memory management issue, specifically around process forking and thread creation. I started by tracing the execution path, looking at `bad_fork_cleanup_mm`, `copy_process`, and `copy_mm` to understand how memory descriptors (`mm_struct`) are handled during a fork. I can see the potential for imbalance if `copy_process` fails *after* `copy_mm`, where we could end up leaking an `mm` reference due to incomplete cleanup. This is because `mmget` in `copy_mm` increments `mm_users`, and a later failure might only `mmput` the newly created `mm`.
Then, I shifted focus to `vfork`, noting the shared `mm` and how the child's `mm_users` increment is crucial. The parent/child relationship and potential exit scenarios raised immediate concerns: if the child exits, the parent's continued use of the shared `mm` requires careful management of `mm_users`. I thought of a situation where a child thread calls `clone()` without `CLONE_VM`, or if the parent is killed, or the child calls `exit`. It seems like the child exiting decrements `mm_users` to 1 instead of 0, which would be important.
Then I get into the current situation. I'm focusing on two tasks, 21217 and 3876. I traced Task 21217, noting it's returning from a syscall (`do_syscall_64`) via `exit_mm` and then `mmput`. Task 3876, on the other hand, is deep within `clone` in the `copy_mm` function.
Now I am wondering...could these be threads in a multithreaded process? Let's say there's a process, P, with threads T1 (Task 3876) and T2 (Task 21217). When T1 creates T2 with `clone(..., CLONE_VM | CLONE_THREAD, ...)` the `mm_users` gets incremented to 2.
Here's the critical scenario: Let's imagine a fatal signal, or a `SIGKILL` sent to a thread group. My thinking is that the signal propagation is critical. T2 enters `get_signal` and calls `do_group_exit`, which then triggers `do_exit`. During the thread exit, `exit_mm` is called, and then `mmput`.
Okay, here's where it gets interesting. I need to understand what happens to the second thread, T1. If `zap_other_threads` sends a `SIGKILL`, the kernel doesn't immediately exit. Instead, it seems like `copy_process` continues. I'm thinking here, could the fatal signal affect the value of `mm_users`?
Then I realize T1 is potentially still running inside the kernel and it will not immediately exit! The `copy_process` routine will continue. I also notice a check for fatal signals, but it happens after `copy_mm` which means that the memory management is already in flight! Then T2 calls `do_exit` and `exit_mm`, and eventually `mmput(mm)`. I am assuming `mmput(mm)` should decrement `mm_users`.
But wait. What value should `mm_users` have when T2 calls `mmput`?
The state of the threads would be something like:
- `mm_users` should be 2, because T1 and T2 are alive.
- T2 decrements it and that should be 1.
- `atomic_dec_and_test(&mm->mm_users)` should be false!
So, the critical question is this: WHY WOULD `atomic_dec_and_test(&mm->mm_users)` RETURN TRUE AND THUS CALL `__mmput` AND FREE THE MEMORY?!
If the value is TRUE, then it must be 1. If it's 1, then the process can't have two threads that are alive! Is T1 not a thread? Or, maybe it's `mm_users` is not decremented properly! Or T1 has no mm?
This has to be some sort of reference count issue or missing accounting in this multithreaded environment. So, I need to methodically check every single place in the kernel code where `current->mm` is set, making sure I am not missing a place where a reference is lost or created inappropriately. I'm going to `grep` the kernel code to track down every `->mm =` assignment.
|
| 105/2 |
2026/09/23 15:51 |
tool |
grepper |
0m
Args: map[Expression:current->mm =]
Results: map[Output:Documentation/mm/active_mm.rst=9=helpers, which abstract this config option.
--
Documentation/mm/active_mm.rst-77-
Documentation/mm/active_mm.rst:78: if (current->mm == &init_mm)
Documentation/mm/active_mm.rst-79-
--
Documentation/translations/zh_CN/mm/active_mm.rst=13=Active MM
--
Documentation/translations/zh_CN/mm/active_mm.rst-75-
Documentation/translations/zh_CN/mm/active_mm.rst:76: if (current->mm == &init_mm)
Documentation/translations/zh_CN/mm/active_mm.rst-77-
--
arch/arc/mm/tlb.c=177=noinline void local_flush_tlb_mm(struct mm_struct *mm)
--
arch/arc/mm/tlb.c-195- destroy_context(mm);
arch/arc/mm/tlb.c:196: if (current->mm == mm)
arch/arc/mm/tlb.c-197- get_new_mmu_context(mm);
--
arch/arc/mm/tlb.c=394=static void create_tlb(struct vm_area_struct *vma, unsigned long vaddr, pte_t *ptep)
--
arch/arc/mm/tlb.c-401- /*
arch/arc/mm/tlb.c:402: * create_tlb() assumes that current->mm == vma->mm, since
arch/arc/mm/tlb.c-403- * -it ASID for TLB entry is fetched from MMU ASID reg (valid for curr)
--
arch/arm/mach-rpc/ecard.c=245=static int ecard_init_mm(void)
--
arch/arm/mach-rpc/ecard.c-252-
arch/arm/mach-rpc/ecard.c:253: current->mm = mm;
arch/arm/mach-rpc/ecard.c-254- current->active_mm = mm;
--
arch/loongarch/include/asm/mmu_context.h=141=drop_mmu_context(struct mm_struct *mm, unsigned int cpu)
--
arch/loongarch/include/asm/mmu_context.h-152-
arch/loongarch/include/asm/mmu_context.h:153: if (!current->mm || (current->mm == mm)) {
arch/loongarch/include/asm/mmu_context.h-154- get_new_mmu_context(mm, cpu, &need_flush);
--
arch/m68k/mm/mcfmmu.c=36=void __init paging_init(void)
--
arch/m68k/mm/mcfmmu.c-71-
arch/m68k/mm/mcfmmu.c:72: current->mm = NULL;
arch/m68k/mm/mcfmmu.c-73-}
--
arch/m68k/mm/sun3mmu.c=36=void __init paging_init(void)
--
arch/m68k/mm/sun3mmu.c-78-
arch/m68k/mm/sun3mmu.c:79: current->mm = NULL;
arch/m68k/mm/sun3mmu.c-80-}
--
arch/m68k/sun3/mmu_emu.c=355=int mmu_emu_handle_fault (unsigned long vaddr, int read_flag, int kernel_fault)
--
arch/m68k/sun3/mmu_emu.c-361-
arch/m68k/sun3/mmu_emu.c:362: if(current->mm == NULL) {
arch/m68k/sun3/mmu_emu.c-363- crp = swapper_pg_dir;
--
arch/microblaze/mm/fault.c=86=void do_page_fault(struct pt_regs *regs, unsigned long address,
--
arch/microblaze/mm/fault.c-113- /* faulthandler_disabled() in user mode is really bad,
arch/microblaze/mm/fault.c:114: as is current->mm == NULL. */
arch/microblaze/mm/fault.c-115- pr_emerg("Page fault in user mode with faulthandler_disabled(), mm = %p\n",
--
arch/nios2/mm/tlb.c=257=void flush_tlb_mm(struct mm_struct *mm)
arch/nios2/mm/tlb.c-258-{
arch/nios2/mm/tlb.c:259: if (current->mm == mm) {
arch/nios2/mm/tlb.c-260- unsigned long mmu_pid = get_pid_from_context(&mm->context);
--
arch/powerpc/mm/book3s64/hash_utils.c=1615=void demote_segment_4k(struct mm_struct *mm, unsigned long addr)
--
arch/powerpc/mm/book3s64/hash_utils.c-1622-#endif
arch/powerpc/mm/book3s64/hash_utils.c:1623: if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {
arch/powerpc/mm/book3s64/hash_utils.c-1624-
--
arch/powerpc/mm/book3s64/hash_utils.c=1718=int hash_page_mm(struct mm_struct *mm, unsigned long ea,
--
arch/powerpc/mm/book3s64/hash_utils.c-1852-#endif
arch/powerpc/mm/book3s64/hash_utils.c:1853: if (current->mm == mm)
arch/powerpc/mm/book3s64/hash_utils.c-1854- check_paca_psize(ea, mm, psize, user_region);
--
arch/powerpc/mm/book3s64/hash_utils.c-1898-
arch/powerpc/mm/book3s64/hash_utils.c:1899: if (current->mm == mm)
arch/powerpc/mm/book3s64/hash_utils.c-1900- check_paca_psize(ea, mm, psize, user_region);
--
arch/powerpc/mm/book3s64/radix_tlb.c=661=static void exit_lazy_flush_tlb(struct mm_struct *mm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-672- */
arch/powerpc/mm/book3s64/radix_tlb.c:673: if (current->mm == mm)
arch/powerpc/mm/book3s64/radix_tlb.c-674- goto out;
--
arch/powerpc/mm/book3s64/radix_tlb.c=761=static enum tlb_flush_type flush_type_needed(struct mm_struct *mm, bool fullmm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-800- */
arch/powerpc/mm/book3s64/radix_tlb.c:801: if (atomic_read(&mm->mm_users) <= 1 && current->mm == mm) {
arch/powerpc/mm/book3s64/radix_tlb.c-802- exit_flush_lazy_tlbs(mm);
--
arch/powerpc/mm/book3s64/radix_tlb.c-818- exit_flush_lazy_tlbs(mm);
arch/powerpc/mm/book3s64/radix_tlb.c:819: if (current->mm == mm)
arch/powerpc/mm/book3s64/radix_tlb.c-820- return FLUSH_TYPE_LOCAL;
--
arch/sparc/include/asm/mman.h=14=static inline void ipi_set_tstate_mcde(void *arg)
--
arch/sparc/include/asm/mman.h-21- */
arch/sparc/include/asm/mman.h:22: if (current->mm == mm) {
arch/sparc/include/asm/mman.h-23- struct pt_regs *regs;
--
arch/um/kernel/skas/process.c=45=unsigned long current_stub_stack(void)
arch/um/kernel/skas/process.c-46-{
arch/um/kernel/skas/process.c:47: if (current->mm == NULL)
arch/um/kernel/skas/process.c-48- return 0;
--
arch/um/kernel/skas/process.c=53=struct mm_id *current_mm_id(void)
arch/um/kernel/skas/process.c-54-{
arch/um/kernel/skas/process.c:55: if (current->mm == NULL)
arch/um/kernel/skas/process.c-56- return NULL;
--
arch/um/kernel/skas/process.c=61=void current_mm_sync(void)
arch/um/kernel/skas/process.c-62-{
arch/um/kernel/skas/process.c:63: if (current->mm == NULL)
arch/um/kernel/skas/process.c-64- return;
--
arch/um/kernel/trap.c=308=unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user,
--
arch/um/kernel/trap.c-344- }
arch/um/kernel/trap.c:345: else if (current->mm == NULL) {
arch/um/kernel/trap.c-346- show_regs(container_of(regs, struct pt_regs, regs));
--
arch/x86/kvm/x86.c=10014=void kvm_arch_destroy_vm(struct kvm *kvm)
arch/x86/kvm/x86.c-10015-{
arch/x86/kvm/x86.c:10016: if (current->mm == kvm->mm) {
arch/x86/kvm/x86.c-10017- /*
--
arch/x86/mm/tlb.c=1640=STATIC_NOPV void native_flush_tlb_local(void)
--
arch/x86/mm/tlb.c-1650-
arch/x86/mm/tlb.c:1651: /* If current->mm == NULL then the read_cr3() "borrows" an mm */
arch/x86/mm/tlb.c-1652- native_write_cr3(__native_read_cr3());
--
drivers/vfio/vfio_iommu_type1.c=3138=static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
--
drivers/vfio/vfio_iommu_type1.c-3145- struct vfio_dma *dma;
drivers/vfio/vfio_iommu_type1.c:3146: bool kthread = current->mm == NULL;
drivers/vfio/vfio_iommu_type1.c-3147- size_t offset;
--
include/trace/events/kmem.h=427=TRACE_EVENT(rss_stat,
--
include/trace/events/kmem.h-448- */
include/trace/events/kmem.h:449: __entry->curr = current->mm == mm && !(current->flags & PF_KTHREAD);
include/trace/events/kmem.h-450- __entry->member = member;
--
kernel/exit.c=584=static void exit_mm(void)
--
kernel/exit.c-610- local_irq_disable();
kernel/exit.c:611: current->mm = NULL;
kernel/exit.c-612- membarrier_update_current_mm(NULL);
--
kernel/sched/membarrier.c-111- * d: smp_mb()
kernel/sched/membarrier.c:112: * e: current->mm = NULL
kernel/sched/membarrier.c-113- * b: read rq->curr->mm == NULL
--
kernel/sched/membarrier.c-125- * d: smp_mb()
kernel/sched/membarrier.c:126: * e: current->mm = NULL
kernel/sched/membarrier.c-127- * b: read rq->curr->mm == NULL
kernel/sched/membarrier.c-128- * kthread_use_mm()
kernel/sched/membarrier.c:129: * f: current->mm = mm
kernel/sched/membarrier.c-130- * g: smp_mb()
--
mm/madvise.c=1889=static inline unsigned long get_untagged_addr(struct mm_struct *mm,
--
mm/madvise.c-1891-{
mm/madvise.c:1892: return current->mm == mm ? untagged_addr(start) :
mm/madvise.c-1893- untagged_addr_remote(mm, start);
--
tools/testing/vma/tests/mmap.c=3=static bool test_mmap_region_basic(void)
--
tools/testing/vma/tests/mmap.c-11-
tools/testing/vma/tests/mmap.c:12: current->mm = &mm;
tools/testing/vma/tests/mmap.c-13-
]
|
| 106/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 50211
output: 23
thoughts: 34
Thoughts: Okay, let's break this down.
**Investigating Memory Management Context Assignment**
Alright, so the core question buzzing in my head is, "How exactly does the `tsk->mm` field get populated?" I know it's fundamental to understanding process memory space, and I need a clear picture. My initial approach is straightforward, the bread and butter of this kind of investigation: let's hunt for instances where `p->mm =` or `tsk->mm =` is used in the codebase. That's where the assignment is happening, and that will give me the clearest insight into the process. Time to start digging through the source... I'll look for those assignments to trace the flow.
|
| 107/2 |
2026/09/23 15:51 |
tool |
grepper |
0m
Args: map[Expression:(p|tsk)->mm\s*=]
Results: map[Output:Documentation/mm/active_mm.rst=9=helpers, which abstract this config option.
--
Documentation/mm/active_mm.rst-55-
Documentation/mm/active_mm.rst:56: For a anonymous process, tsk->mm == NULL, and tsk->active_mm is the
Documentation/mm/active_mm.rst-57- "borrowed" mm while the anonymous process is running. When the
--
Documentation/translations/zh_CN/mm/active_mm.rst=13=Active MM
--
Documentation/translations/zh_CN/mm/active_mm.rst-59-
Documentation/translations/zh_CN/mm/active_mm.rst:60: 对于一个匿名进程,tsk->mm == NULL,而tsk->active_mm是匿名进程运行时
Documentation/translations/zh_CN/mm/active_mm.rst-61- “借用”的mm。当匿名进程被调度走时,借用的地址空间被返回并清除。
--
arch/x86/kernel/cpu/sgx/encl.c=816=static struct sgx_encl_mm *sgx_encl_find_mm(struct sgx_encl *encl,
--
arch/x86/kernel/cpu/sgx/encl.c-825- list_for_each_entry_rcu(tmp, &encl->mm_list, list) {
arch/x86/kernel/cpu/sgx/encl.c:826: if (tmp->mm == mm) {
arch/x86/kernel/cpu/sgx/encl.c-827- encl_mm = tmp;
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c=1397=void kfd_process_notifier_release_internal(struct kfd_process *p)
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c-1426- /* Indicate to other users that MM is no longer valid */
drivers/gpu/drm/amd/amdkfd/kfd_process.c:1427: p->mm = NULL;
drivers/gpu/drm/amd/amdkfd/kfd_process.c-1428- kfd_dbg_trap_disable(p);
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c=2037=struct kfd_process *kfd_lookup_process_by_id(const struct mm_struct *mm, u16 id)
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c-2044- hash_for_each_rcu(kfd_processes_table, temp, p, kfd_processes) {
drivers/gpu/drm/amd/amdkfd/kfd_process.c:2045: if (p->mm == mm && p->context_id == id) {
drivers/gpu/drm/amd/amdkfd/kfd_process.c-2046- kref_get(&p->ref);
--
drivers/usb/gadget/function/f_fs.c=1268=static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
--
drivers/usb/gadget/function/f_fs.c-1285- p->data = *from;
drivers/usb/gadget/function/f_fs.c:1286: p->mm = current->mm;
drivers/usb/gadget/function/f_fs.c-1287-
--
drivers/usb/gadget/function/f_fs.c=1309=static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
--
drivers/usb/gadget/function/f_fs.c-1335- }
drivers/usb/gadget/function/f_fs.c:1336: p->mm = current->mm;
drivers/usb/gadget/function/f_fs.c-1337-
--
fs/exec.c=843=static int exec_mmap(struct linux_binprm *bprm)
--
fs/exec.c-883- tsk->active_mm = mm;
fs/exec.c:884: tsk->mm = mm;
fs/exec.c-885- mm_init_cid(mm, tsk);
--
include/linux/mmu_notifier.h=64=struct mmu_notifier_ops {
--
include/linux/mmu_notifier.h-73- * through the secondary mmu by the time the last thread with
include/linux/mmu_notifier.h:74: * tsk->mm == mm exits.
include/linux/mmu_notifier.h-75- *
--
kernel/exit.c=460=static bool __try_to_set_owner(struct task_struct *tsk, struct mm_struct *mm)
--
kernel/exit.c-464- task_lock(tsk);
kernel/exit.c:465: if (likely(tsk->mm == mm)) {
kernel/exit.c-466- /* tsk can't pass exit_mm/exec_mmap and exit */
--
kernel/fork.c=1568=static int copy_mm(u64 clone_flags, struct task_struct *tsk)
--
kernel/fork.c-1578-
kernel/fork.c:1579: tsk->mm = NULL;
kernel/fork.c-1580- tsk->active_mm = NULL;
--
kernel/fork.c-1599-
kernel/fork.c:1600: tsk->mm = mm;
kernel/fork.c-1601- tsk->active_mm = mm;
--
kernel/kthread.c=1615=void kthread_use_mm(struct mm_struct *mm)
--
kernel/kthread.c-1634- tsk->active_mm = mm;
kernel/kthread.c:1635: tsk->mm = mm;
kernel/kthread.c-1636- membarrier_update_current_mm(mm);
--
kernel/kthread.c=1661=void kthread_unuse_mm(struct mm_struct *mm)
--
kernel/kthread.c-1677- local_irq_disable();
kernel/kthread.c:1678: tsk->mm = NULL;
kernel/kthread.c-1679- membarrier_update_current_mm(NULL);
--
kernel/sched/fair.c=3843=static void task_numa_group(struct task_struct *p, int cpupid, int flags,
--
kernel/sched/fair.c-3903- /* Always join threads in the same process. */
kernel/sched/fair.c:3904: if (tsk->mm == current->mm)
kernel/sched/fair.c-3905- join = true;
--
kernel/sched/membarrier.c=330=static int membarrier_private_expedited(int flags, int cpu_id)
--
kernel/sched/membarrier.c-411- p = rcu_dereference(cpu_rq(cpu)->curr);
kernel/sched/membarrier.c:412: if (p && p->mm == mm)
kernel/sched/membarrier.c-413- __cpumask_set_cpu(cpu, tmpmask);
--
kernel/sched/membarrier.c=445=static int sync_runqueues_membarrier_state(struct mm_struct *mm)
--
kernel/sched/membarrier.c-489- p = rcu_dereference(rq->curr);
kernel/sched/membarrier.c:490: if (p && p->mm == mm)
kernel/sched/membarrier.c-491- __cpumask_set_cpu(cpu, tmpmask);
--
mm/memory-failure.c=528=struct task_struct *task_early_kill(struct task_struct *tsk, int force_early)
--
mm/memory-failure.c-535- */
mm/memory-failure.c:536: if (force_early && tsk->mm == current->mm)
mm/memory-failure.c-537- return current;
]
|
| 108/2 |
2026/09/23 15:51 |
llm |
expert |
0m
Model:
Tokens:
input: 52536
output: 21
thoughts: 3393
Thoughts: **Analyzing a Memory Management Double-Free Vulnerability**
Okay, so I'm diving deep into this crash report, focusing on a double-free scenario related to memory management (`mm_struct`). The key is that some task (21217) is trying to release memory, but another task (3876) appears to still be using it. I've already examined the places where `tsk->mm = mm` is set in the kernel: `exec_mmap`, `copy_mm`, and `kthread_use_mm`. I'm initially thinking it might be related to `exec`, given what I know about how the memory space is swapped out with a new one. I went back and re-read commit `38205ecbe6b6` which I remembered. That commit seems to have something to do with releasing the old mm outside of the locks involved in an `exec` call. My initial hypothesis focuses on the `exec` path. The stack trace of task 21217 shows it's calling `exit_mm` which eventually calls `mmput`. This is where things start to get interesting. Task 21217 is exiting because of a signal.
Now, I'm thinking about how the memory is being freed. `mmput` decrements `mm_users` in the `mm_struct`, and if it hits zero, it frees the `mm_struct`. The crash is happening within `__mmput`, which is called after `atomic_dec_and_test` confirms that `mm_users` is zero after the decrement. This means the reference count had to be 1 to start.
I've checked the stack trace for task 3876. It seems to be forking, calling `copy_mm`. That gives a completely new `mm` (copy of a `mm`), so why would it cause an issue with `mm_users` being 1?
I need to understand what's happening. Task 3876 has `current->mm` point to the same `mm_struct` that Task 21217 is releasing. That should never happen! Task 3876 is running a `clone` syscall. It looks like Task 3876 is running with `mm`, but the reference count is somehow off. This doesn't seem possible. Task 3876 can't be a kthread, because it's in userspace. And an `io_uring` worker has the same issue of not having a `clone` syscall.
The `fork` code seems to handle reference counting correctly: if `CLONE_VM` is set, it increments `mm_users`; if not, it calls `dup_mm` which creates a new `mm_struct`, incrementing the new `mm_users`.
My current hypothesis is that task 3876 could potentially have already called `mmput` at some point? Could there be a code path that calls `mmput(current->mm)` without also clearing `current->mm`?
I'm going to search for instances of that! I need to be sure.
|
| 109/2 |
2026/09/23 15:51 |
tool |
grepper |
0m
Error:
Args: map[Expression:mmput\(current->mm\)]
Results:
|
| 110/2 |
2026/09/23 15:52 |
llm |
expert |
0m
Model:
Tokens:
input: 56651
output: 31
thoughts: 16
Thoughts: Okay, here's my summary, tailored for an expert audience, in the first person:
**Diving into the Memory Management Mystery**
Alright, so I'm trying to track down a specific memory management operation, and I'm thinking the best way to do this is to search the code base. I need to be precise here. I'm going to focus on a function that looks like it's managing the memory space associated with a task struct, let's say. Specifically, I'm going to look for implementations of either `mmput(tsk->mm)` or something structurally similar to that. This will likely give me a good entry point to understand how that memory space is being managed. This is my working hypothesis: find the deallocation, and the rest of the puzzle should fall into place.
|
| 111/2 |
2026/09/23 15:52 |
tool |
grepper |
0m
Args: map[Expression:mmput\([a-zA-Z0-9_]+->mm\)]
Results: map[Output:arch/powerpc/platforms/book3s/vas-api.c=66=int get_vas_user_win_ref(struct vas_user_win_ref *task_ref)
--
arch/powerpc/platforms/book3s/vas-api.c-88- mmgrab(task_ref->mm);
arch/powerpc/platforms/book3s/vas-api.c:89: mmput(task_ref->mm);
arch/powerpc/platforms/book3s/vas-api.c-90- /*
--
arch/s390/kvm/s390/pv.c=576=int kvm_s390_pv_deinit_cleanup_all(struct kvm *kvm, u16 *rc, u16 *rrc)
--
arch/s390/kvm/s390/pv.c-629- gmap_pv_destroy_range(kvm->arch.gmap, 0, asce_end(kvm->arch.gmap->asce), false);
arch/s390/kvm/s390/pv.c:630: mmput(kvm->mm);
arch/s390/kvm/s390/pv.c-631- }
--
drivers/accel/amdxdna/aie2_ctx.c=387=aie2_sched_job_run(struct drm_sched_job *sched_job)
--
drivers/accel/amdxdna/aie2_ctx.c-435- aie2_job_put(job);
drivers/accel/amdxdna/aie2_ctx.c:436: mmput(job->mm);
drivers/accel/amdxdna/aie2_ctx.c-437- fence = ERR_PTR(ret);
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c=963=struct kfd_process *kfd_create_process(struct task_struct *thread)
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c-1024- mutex_unlock(&kfd_processes_mutex);
drivers/gpu/drm/amd/amdkfd/kfd_process.c:1025: mmput(thread->mm);
drivers/gpu/drm/amd/amdkfd/kfd_process.c-1026-
--
drivers/gpu/drm/xe/xe_sync.c=76=static void user_fence_worker(struct work_struct *w)
--
drivers/gpu/drm/xe/xe_sync.c-85- kthread_unuse_mm(ufence->mm);
drivers/gpu/drm/xe/xe_sync.c:86: mmput(ufence->mm);
drivers/gpu/drm/xe/xe_sync.c-87- } else {
--
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c=262=static int arm_smmu_sva_set_dev_pasid(struct iommu_domain *domain,
--
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c-284-
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c:285: mmput(domain->mm);
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c-286- return ret;
--
drivers/usb/gadget/function/f_fs.c=871=static void ffs_user_copy_worker(struct work_struct *work)
--
drivers/usb/gadget/function/f_fs.c-882- kthread_unuse_mm(io_data->mm);
drivers/usb/gadget/function/f_fs.c:883: mmput(io_data->mm);
drivers/usb/gadget/function/f_fs.c-884- } else {
--
drivers/vfio/vfio_iommu_type1.c=1648=static int vfio_change_dma_owner(struct vfio_dma *dma)
--
drivers/vfio/vfio_iommu_type1.c-1665- mm_lock_acct(dma->task, dma->mm, dma->lock_cap, -npage);
drivers/vfio/vfio_iommu_type1.c:1666: mmput(dma->mm);
drivers/vfio/vfio_iommu_type1.c-1667- }
--
drivers/vhost/vhost.c=709=static void vhost_detach_mm(struct vhost_dev *dev)
--
drivers/vhost/vhost.c-714- if (dev->use_worker)
drivers/vhost/vhost.c:715: mmput(dev->mm);
drivers/vhost/vhost.c-716- else
--
fs/exec.c=1476=static void free_bprm(struct linux_binprm *bprm)
--
fs/exec.c-1479- acct_arg_size(bprm, 0);
fs/exec.c:1480: mmput(bprm->mm);
fs/exec.c-1481- }
--
kernel/bpf/task_iter.c=631=static void task_vma_seq_stop(struct seq_file *seq, void *v)
--
kernel/bpf/task_iter.c-647- mmap_read_unlock(info->mm);
kernel/bpf/task_iter.c:648: mmput(info->mm);
kernel/bpf/task_iter.c-649- info->mm = NULL;
--
kernel/cgroup/cpuset.c=2606=static void cpuset_migrate_mm_workfn(struct work_struct *work)
--
kernel/cgroup/cpuset.c-2612- do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
kernel/cgroup/cpuset.c:2613: mmput(mwork->mm);
kernel/cgroup/cpuset.c-2614- kfree(mwork);
--
kernel/events/uprobes.c=1205=build_map_info(struct address_space *mapping, loff_t offset, bool is_register)
--
kernel/events/uprobes.c-1252- while (curr) {
kernel/events/uprobes.c:1253: mmput(curr->mm);
kernel/events/uprobes.c-1254- curr = curr->next;
--
kernel/fork.c=2012=__latent_entropy struct task_struct *copy_process(
--
kernel/fork.c-2606- mm_clear_owner(p->mm, p);
kernel/fork.c:2607: mmput(p->mm);
kernel/fork.c-2608- }
--
mm/debug_vm_pgtable.c=987=static void __init destroy_args(struct pgtable_debug_args *args)
--
mm/debug_vm_pgtable.c-1041- if (args->mm)
mm/debug_vm_pgtable.c:1042: mmput(args->mm);
mm/debug_vm_pgtable.c-1043-}
--
mm/userfaultfd.c=4102=static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
--
mm/userfaultfd.c-4141- uffdio_copy.len, flags);
mm/userfaultfd.c:4142: mmput(ctx->mm);
mm/userfaultfd.c-4143- } else {
--
mm/userfaultfd.c=4162=static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
--
mm/userfaultfd.c-4195- uffdio_zeropage.range.len);
mm/userfaultfd.c:4196: mmput(ctx->mm);
mm/userfaultfd.c-4197- } else {
--
mm/userfaultfd.c=4216=static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
--
mm/userfaultfd.c-4251- uffdio_wp.range.len, mode_wp);
mm/userfaultfd.c:4252: mmput(ctx->mm);
mm/userfaultfd.c-4253- } else {
--
mm/userfaultfd.c=4268=static int userfaultfd_rwprotect(struct userfaultfd_ctx *ctx,
--
mm/userfaultfd.c-4300- uffdio_rwp.range.len, mode_rwp);
mm/userfaultfd.c:4301: mmput(ctx->mm);
mm/userfaultfd.c-4302- } else {
--
mm/userfaultfd.c=4420=static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
--
mm/userfaultfd.c-4457- uffdio_continue.range.len, flags);
mm/userfaultfd.c:4458: mmput(ctx->mm);
mm/userfaultfd.c-4459- } else {
--
mm/userfaultfd.c=4481=static inline int userfaultfd_poison(struct userfaultfd_ctx *ctx, unsigned long arg)
--
mm/userfaultfd.c-4514- uffdio_poison.range.len, 0);
mm/userfaultfd.c:4515: mmput(ctx->mm);
mm/userfaultfd.c-4516- } else {
]
|
| 112/2 |
2026/09/23 15:52 |
llm |
expert |
0m
Model:
Tokens:
input: 59450
output: 48
thoughts: 52
Thoughts: Here's my take on those thoughts:
**Investigating a Suspect Memory Management Operation in AMD's KFD Driver**
Okay, I'm digging into the AMD KFD driver, specifically `drivers/gpu/drm/amd/amdkfd/kfd_process.c`. Hmm, I'm looking at this function and I see `mmput(thread->mm);` and I get a bad feeling about that. I need to understand that. I need to understand what's happening to the process's memory space here. Right, let's back up and trace the creation of that process; I need to check `kfd_create_process`. I need to figure out the context of that `mmput`. Is this related to a memory leak, or is it expected? This could be something very serious if it's mishandled.
|
| 113/2 |
2026/09/23 15:52 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:drivers/gpu/drm/amd/amdkfd/kfd_process.c Name:kfd_create_process]
Results: map[SourceCode: SourceFile:]
|
| 114/2 |
2026/09/23 15:52 |
llm |
expert |
0m
Model:
Tokens:
input: 59754
output: 47
thoughts: 32
Thoughts: Okay, here's my interpretation of what's going on, thinking as if these are *my* thoughts:
**Analyzing `kfd_process.c` around Line 1020**
Alright, I'm heading into `drivers/gpu/drm/amd/amdkfd/kfd_process.c`. I need to focus on the code around line 1020. This usually means I'm looking for a specific function call, a data structure definition, or a critical logic branch related to process management within the KFD (Kernel Fusion Driver). Knowing the file name, `kfd_process.c`, tells me this section should be dealing with how the driver interacts with user-space processes. I'm probably looking at something related to creating, destroying, scheduling, or managing resources for processes that are going to use the AMD GPUs.
Given the line number, I'll need to figure out the context of the code to understand what is occurring. Is there a potential bug here? I'm going to look for any potential race conditions, memory leaks, or incorrect resource allocation within the code at or around line 1020.
|
| 115/2 |
2026/09/23 15:52 |
tool |
read-file |
0m
Args: map[File:drivers/gpu/drm/amd/amdkfd/kfd_process.c FirstLine:1010 LineCount:25]
Results: map[Contents:1010: goto out;
1011:
1012: ret = kfd_create_process_sysfs(process);
1013: if (ret)
1014: pr_warn("Failed to create sysfs entry for the kfd_process");
1015:
1016: ret = kfd_debugfs_add_process(process);
1017: if (ret)
1018: pr_warn("Failed to create debugfs entry for the kfd_process, ret = %d\n",
1019: ret);
1020:
1021: init_waitqueue_head(&process->wait_irq_drain);
1022: }
1023: out:
1024: mutex_unlock(&kfd_processes_mutex);
1025: mmput(thread->mm);
1026:
1027: return process;
1028: }
1029:
1030: /**
1031: * amdgpu_amdkfd_set_sigbus_delay - Set per-process KFD SIGBUS delay
1032: * @task: task in the target process
1033: * @ms: encoded delay value (0 = immediate, 0xFFFFFFFF = suppress,
1034: * otherwise delay in milliseconds)
]
|
| 116/2 |
2026/09/23 15:52 |
llm |
expert |
0m
Model:
Tokens:
input: 60451
output: 306
thoughts: 196
Thoughts: Okay, let's unpack this.
**Analyzing a Potential Race Condition in Kernel Memory Management**
Alright, so I'm looking at `kfd_create_process` and specifically the memory management aspects. I see that it grabbed a reference with `get_task_mm(thread)` and then releases it with `mmput(thread->mm)`. Standard procedure, right? But something's niggling at me.
Hold on, let's take a beat and zoom out. The concern isn't about the individual function calls themselves; that seems correct. My intuition is that there's a larger picture to consider, a potential race condition. The core question is: how could `__mmput` and `dup_mm` *possibly* be racing on the *same* `struct mm_struct`? That's the crux of this.
To make sure I'm not missing something obvious, I need to understand the mechanism here: why this race *could* occur. Let me formulate the question properly.
I'm thinking: "How can a task running `dup_mm(tsk, current->mm)` during `sys_clone` (without `CLONE_VM`) race with another task calling `__mmput(mm)` on the *same* `mm_struct` from `exit_mm()` -> `mmput(mm)`? Specifically, I'm trying to wrap my head around a scenario where `mm->mm_users` gets decremented to zero by one task while the *other* task, executing a clone operation, is still actively using `current->mm`." This is what I need to investigate in more detail. I'll need to double check the memory management structure and ensure I'm not overlooking some subtle detail.
|
| 117/2 |
2026/09/23 15:52 |
tool |
codeexpert |
3h53m
Args: map[Question:In the Linux kernel, KCSAN detected a data race between:
Task A (task 21217 on cpu 1):
__mmput (list_del(&mm->mmlist) at kernel/fork.c:1198)
mmput
exit_mm
do_exit
do_group_exit
get_signal
syscall_exit_to_user_mode
and Task B (task 3876 on cpu 0):
dup_mm (memcpy(mm, oldmm, sizeof(*mm)) at kernel/fork.c:1537)
copy_mm
copy_process
kernel_clone
sys_clone
Task B is executing sys_clone (without CLONE_VM, so it calls dup_mm(tsk, current->mm)), and Task A is exiting and calling mmput(mm) which triggers __mmput(mm) because atomic_dec_and_test(&mm->mm_users) succeeded. Both are operating on the exact same struct mm_struct.
How can Task A and Task B be concurrently in these states on the same mm_struct? Does Task B not hold an mm_users refcount, or how did mm->mm_users drop to 0? Is this data race benign or harmful, and why?]
Results: map[Answer:Based on the analysis of the Linux kernel source code and refcounting invariants:
1. How Task A and Task B reach these states concurrently on the same mm_struct:
- Task A and Task B share the same `struct mm_struct` (created via `clone` with `CLONE_VM`, such as sibling threads in a process or a parent/child sharing VM via `vfork`).
- Task B is executing `sys_clone` without `CLONE_VM` (e.g. a standard `fork()`), which invokes `copy_process() -> copy_mm() -> dup_mm(tsk, current->mm)`. In `dup_mm()`, it allocates a new `mm_struct` and copies `oldmm` (`current->mm`) via `memcpy(mm, oldmm, sizeof(*mm))` at line 1537.
- Concurrently, Task A is exiting due to a fatal signal or group exit (`syscall_exit_to_user_mode -> get_signal -> do_group_exit -> do_exit -> exit_mm`). In `exit_mm()`, Task A clears `current->mm` and calls `mmput(mm)`.
- In `mmput()`, `atomic_dec_and_test(&mm->mm_users)` evaluates to true, transitioning `mm_users` from 1 to 0 and triggering `__mmput(mm)`. Inside `__mmput()`, Task A begins destroying the address space and unlinks `mm->mmlist` via `list_del(&mm->mmlist)` at line 1198.
- Because `dup_mm()` does not hold `mmlist_lock` (or any lock protecting `oldmm` during the raw `memcpy`), KCSAN flags the concurrent write to `mm->mmlist` in Task A and read in Task B.
2. Does Task B hold an mm_users refcount, or how did mm->mm_users drop to 0:
- Under standard kernel invariants, every user task with an active `current->mm` holds a reference counted in `mm->mm_users`. If Task B held an active reference in `mm->mm_users`, the count would have been at least 2, and Task A's `atomic_dec_and_test(&mm->mm_users)` would have decremented the count to 1 and returned false without calling `__mmput()`.
- Because `atomic_dec_and_test(&mm->mm_users)` succeeded in Task A, `mm->mm_users` was exactly 1 before Task A's decrement, meaning Task B did NOT hold an active `mm_users` reference at the time of the race.
- How `mm_users` dropped to 0:
* In a normal multithreaded process, this indicates an unbalanced/premature `mmput` or refcount underflow bug, leaving Task B executing with a borrowed or dangling `current->mm` while only Task A held the single remaining `mm_users` refcount.
* In `vfork()` scenarios (where parent Task A and child Task B share `mm`), if the vfork child is running while parent teardown is triggered (e.g. fatal signal waking parent prematurely from `TASK_KILLABLE` sleep or completion misordering), a race can expose `mm` teardown.
* (Caveat/Unverified): Without the exact reproducer or syscall trace from syzbot/KCSAN, the exact trigger (e.g., specific ioctl/driver `mmput`, asynchronous `io_uring`/binder teardown, or vfork/signal race) causing Task B to run without an active `mm_users` count could not be verified in the tree.
3. Is the data race benign or harmful, and why:
- This data race is severely HARMFUL (critical bug / fatal race):
* Concurrent structure teardown and read: Task A in `__mmput()` is actively destructing `oldmm`. Task B's `memcpy()` reads torn and invalid pointers (e.g., `mmlist` pointers being unlinked).
* Imminent Use-After-Free: Right after `memcpy()`, `dup_mm()` calls `dup_mmap(mm, oldmm)` which iterates over `oldmm`'s VMAs and page tables. Meanwhile, `__mmput()` calls `exit_mmap(oldmm)`, which frees those exact page tables and VMAs. This will cause `dup_mmap()` to dereference already-freed memory, causing memory corruption, NULL pointer dereferences, or kernel panics.
* Invariant violation: `__mmput()` asserts `VM_BUG_ON(atomic_read(&mm->mm_users))`. Executing `dup_mm()` against an `mm_struct` in `__mmput()` completely violates the memory management lifecycle rules.]
|
| 118/3 |
2026/09/23 15:52 |
agent |
codeexpert |
3h53m
Model:
Results: map[Answer:Based on the analysis of the Linux kernel source code and refcounting invariants:
1. How Task A and Task B reach these states concurrently on the same mm_struct:
- Task A and Task B share the same `struct mm_struct` (created via `clone` with `CLONE_VM`, such as sibling threads in a process or a parent/child sharing VM via `vfork`).
- Task B is executing `sys_clone` without `CLONE_VM` (e.g. a standard `fork()`), which invokes `copy_process() -> copy_mm() -> dup_mm(tsk, current->mm)`. In `dup_mm()`, it allocates a new `mm_struct` and copies `oldmm` (`current->mm`) via `memcpy(mm, oldmm, sizeof(*mm))` at line 1537.
- Concurrently, Task A is exiting due to a fatal signal or group exit (`syscall_exit_to_user_mode -> get_signal -> do_group_exit -> do_exit -> exit_mm`). In `exit_mm()`, Task A clears `current->mm` and calls `mmput(mm)`.
- In `mmput()`, `atomic_dec_and_test(&mm->mm_users)` evaluates to true, transitioning `mm_users` from 1 to 0 and triggering `__mmput(mm)`. Inside `__mmput()`, Task A begins destroying the address space and unlinks `mm->mmlist` via `list_del(&mm->mmlist)` at line 1198.
- Because `dup_mm()` does not hold `mmlist_lock` (or any lock protecting `oldmm` during the raw `memcpy`), KCSAN flags the concurrent write to `mm->mmlist` in Task A and read in Task B.
2. Does Task B hold an mm_users refcount, or how did mm->mm_users drop to 0:
- Under standard kernel invariants, every user task with an active `current->mm` holds a reference counted in `mm->mm_users`. If Task B held an active reference in `mm->mm_users`, the count would have been at least 2, and Task A's `atomic_dec_and_test(&mm->mm_users)` would have decremented the count to 1 and returned false without calling `__mmput()`.
- Because `atomic_dec_and_test(&mm->mm_users)` succeeded in Task A, `mm->mm_users` was exactly 1 before Task A's decrement, meaning Task B did NOT hold an active `mm_users` reference at the time of the race.
- How `mm_users` dropped to 0:
* In a normal multithreaded process, this indicates an unbalanced/premature `mmput` or refcount underflow bug, leaving Task B executing with a borrowed or dangling `current->mm` while only Task A held the single remaining `mm_users` refcount.
* In `vfork()` scenarios (where parent Task A and child Task B share `mm`), if the vfork child is running while parent teardown is triggered (e.g. fatal signal waking parent prematurely from `TASK_KILLABLE` sleep or completion misordering), a race can expose `mm` teardown.
* (Caveat/Unverified): Without the exact reproducer or syscall trace from syzbot/KCSAN, the exact trigger (e.g., specific ioctl/driver `mmput`, asynchronous `io_uring`/binder teardown, or vfork/signal race) causing Task B to run without an active `mm_users` count could not be verified in the tree.
3. Is the data race benign or harmful, and why:
- This data race is severely HARMFUL (critical bug / fatal race):
* Concurrent structure teardown and read: Task A in `__mmput()` is actively destructing `oldmm`. Task B's `memcpy()` reads torn and invalid pointers (e.g., `mmlist` pointers being unlinked).
* Imminent Use-After-Free: Right after `memcpy()`, `dup_mm()` calls `dup_mmap(mm, oldmm)` which iterates over `oldmm`'s VMAs and page tables. Meanwhile, `__mmput()` calls `exit_mmap(oldmm)`, which frees those exact page tables and VMAs. This will cause `dup_mmap()` to dereference already-freed memory, causing memory corruption, NULL pointer dereferences, or kernel panics.
* Invariant violation: `__mmput()` asserts `VM_BUG_ON(atomic_read(&mm->mm_users))`. Executing `dup_mm()` against an `mm_struct` in `__mmput()` completely violates the memory management lifecycle rules.]
Instruction:
You are a capable Linux kernel developer tasked with researching complex questions
about kernel source code. You will be given a concrete question, and need to provide
a concrete answer.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
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: In the Linux kernel, KCSAN detected a data race between:
Task A (task 21217 on cpu 1):
__mmput (list_del(&mm->mmlist) at kernel/fork.c:1198)
mmput
exit_mm
do_exit
do_group_exit
get_signal
syscall_exit_to_user_mode
and Task B (task 3876 on cpu 0):
dup_mm (memcpy(mm, oldmm, sizeof(*mm)) at kernel/fork.c:1537)
copy_mm
copy_process
kernel_clone
sys_clone
Task B is executing sys_clone (without CLONE_VM, so it calls dup_mm(tsk, current->mm)), and Task A is exiting and calling mmput(mm) which triggers __mmput(mm) because atomic_dec_and_test(&mm->mm_users) succeeded. Both are operating on the exact same struct mm_struct.
How can Task A and Task B be concurrently in these states on the same mm_struct? Does Task B not hold an mm_users refcount, or how did mm->mm_users drop to 0? Is this data race benign or harmful, and why?
|
| 119/4 |
2026/09/23 15:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4438
output: 32
thoughts: 637
Thoughts: **Analyzing a KCSAN Data Race Report: A Deep Dive into Kernel Memory Management**
Okay, this is an interesting one. A user is asking about a KCSAN data race report in the Linux kernel, specifically concerning the interaction between `__mmput`, `dup_mm`, and the `mm_users` refcount. The core of the issue: how can two tasks, Task A (exiting) and Task B (cloning), concurrently access the same `mm_struct` in a way that triggers this race? This is a pretty deep dive into kernel architecture and concurrency, specifically around the `fork`/`exit` mechanisms and memory management within the kernel, so this needs to be investigated in detail to fully fulfill. It's a concurrency analysis issue, so the risk is low, but understanding the race itself is important.
First, I need to break down the user's report. They've identified that Task A is in the process of exiting (`do_exit -> exit_mm -> mmput -> __mmput`), and Task B is calling `sys_clone` (without `CLONE_VM`) and thus calling `dup_mm`. Both are acting on the *same* `mm_struct`, which is where the data race comes in. The question is how is this possible?
My initial thoughts are: What does `dup_mm` *actually* do? How does it interact with `copy_mm`? And how does `exit_mm` affect the `mm_struct`? The fact that both threads are operating on the same `mm` suggests a shared context. Is Task B cloning Task A? Or, is Task B another thread within the same thread group? I need to analyze the surrounding source code to understand how this is possible. If Task B *is* cloning Task A, that could explain it. If it's a thread, it makes a little more sense, but the core issue is how the `mm_users` count gets to zero in the first place, allowing `__mmput` to execute. The user specifically wonders, "Does Task B not hold an `mm_users` refcount?" Is the data race benign, or potentially harmful, and why? I need to figure this out.
So, let's start with `kernel/fork.c`, which is the likely source of truth. I need to understand what `copy_mm`, `dup_mm`, `exit_mm`, and `__mmput` are doing, and how these functions could lead to this simultaneous access. Tools like `codesearch-definition-source` or `grepper` will be invaluable here. Let's start digging into the source!
|
| 120/4 |
2026/09/23 15:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_mm]
Results: map[SourceCode:1568: static int copy_mm(u64 clone_flags, struct task_struct *tsk)
1569: {
1570: struct mm_struct *mm, *oldmm;
1571:
1572: tsk->min_flt = tsk->maj_flt = 0;
1573: tsk->nvcsw = tsk->nivcsw = 0;
1574: #ifdef CONFIG_DETECT_HUNG_TASK
1575: tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1576: tsk->last_switch_time = 0;
1577: #endif
1578:
1579: tsk->mm = NULL;
1580: tsk->active_mm = NULL;
1581:
1582: /*
1583: * Are we cloning a kernel thread?
1584: *
1585: * We need to steal a active VM for that..
1586: */
1587: oldmm = current->mm;
1588: if (!oldmm)
1589: return 0;
1590:
1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
1597: return -ENOMEM;
1598: }
1599:
1600: tsk->mm = mm;
1601: tsk->active_mm = mm;
1602: return 0;
1603: }
SourceFile:kernel/fork.c]
|
| 121/4 |
2026/09/23 15:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6180
output: 32
thoughts: 18
Thoughts: Okay, let's dive into this. Here's my thought process on this:
**Analyzing `dup_mm` in `kernel/fork.c`**
Alright, time to get to the heart of the matter. I'm focusing my attention on `dup_mm` within the `kernel/fork.c` file. This function is critical; it's the core of how a new process (child) duplicates its memory map from its parent. Given my expertise, I already have a mental model of how `fork` generally operates, but I need to understand the specifics of *this* duplication process. I'm expecting to see the low-level details of how virtual memory regions are copied, reference counts are managed, and how the page table entries (PTEs) are handled. Understanding `dup_mm` is crucial for grasping how memory isolation is maintained between parent and child and for the performance implications involved, especially around copy-on-write strategies, if used. I need to pinpoint the exact sequence of operations it performs, looking for potential areas of optimization or vulnerabilities that might be relevant in my own research.
|
| 122/4 |
2026/09/23 15:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mm]
Results: map[SourceCode:1517: /**
1518: * dup_mm() - duplicates an existing mm structure
1519: * @tsk: the task_struct with which the new mm will be associated.
1520: * @oldmm: the mm to duplicate.
1521: *
1522: * Allocates a new mm structure and duplicates the provided @oldmm structure
1523: * content into it.
1524: *
1525: * Return: the duplicated mm or NULL on failure.
1526: */
1527: static struct mm_struct *dup_mm(struct task_struct *tsk,
1528: struct mm_struct *oldmm)
1529: {
1530: struct mm_struct *mm;
1531: int err;
1532:
1533: mm = allocate_mm();
1534: if (!mm)
1535: goto fail_nomem;
1536:
1537: memcpy(mm, oldmm, sizeof(*mm));
1538:
1539: if (!mm_init(mm, tsk))
1540: goto fail_nomem;
1541:
1542: uprobe_start_dup_mmap();
1543: err = dup_mmap(mm, oldmm);
1544: if (err)
1545: goto free_pt;
1546: uprobe_end_dup_mmap();
1547:
1548: mm->hiwater_rss = get_mm_rss(mm);
1549: mm->hiwater_vm = mm->total_vm;
1550:
1551: if (mm->binfmt && !try_module_get(mm->binfmt->module))
1552: goto free_pt;
1553:
1554: return mm;
1555:
1556: free_pt:
1557: /* don't put binfmt in mmput, we haven't got module yet */
1558: mm->binfmt = NULL;
1559: mm_init_owner(mm, NULL);
1560: mmput(mm);
1561: if (err)
1562: uprobe_end_dup_mmap();
1563:
1564: fail_nomem:
1565: return NULL;
1566: }
SourceFile:kernel/fork.c]
|
| 123/4 |
2026/09/23 15:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7163
output: 32
thoughts: 113
Thoughts: **Analyzing Memory Management During Fork**
Okay, let's break this down. First, I'm looking at the `dup_mm` function. Specifically, that `memcpy` call, copying the memory map (`mm`) from the old memory map (`oldmm`). I see that it perfectly lines up with the prompt, the specific line number in `kernel/fork.c`. That's at line 1537, matching the prompt. Now I need to understand how this ties into the bigger picture.
I need to look at Task A, specifically `__mmput`. Let's see how `__mmput` deals with `mmlist` during a deallocation or cleanup, especially since the prompt references it at line 1198 in `kernel/fork.c`. I need to fully grasp the memory management implications here, particularly around how resources are released after a fork.
|
| 124/4 |
2026/09/23 15:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:__mmput]
Results: map[SourceCode:1185: static inline void __mmput(struct mm_struct *mm)
1186: {
1187: VM_BUG_ON(atomic_read(&mm->mm_users));
1188:
1189: uprobe_clear_state(mm);
1190: exit_aio(mm);
1191: ksm_exit(mm);
1192: khugepaged_exit(mm); /* must run before exit_mmap */
1193: exit_mmap(mm);
1194: mm_put_huge_zero_folio(mm);
1195: set_mm_exe_file(mm, NULL);
1196: if (!list_empty(&mm->mmlist)) {
1197: spin_lock(&mmlist_lock);
1198: list_del(&mm->mmlist);
1199: spin_unlock(&mmlist_lock);
1200: }
1201: if (mm->binfmt)
1202: module_put(mm->binfmt->module);
1203: lru_gen_del_mm(mm);
1204: futex_hash_free(mm);
1205: mmdrop(mm);
1206: }
SourceFile:kernel/fork.c]
|
| 125/4 |
2026/09/23 15:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7864
output: 32
thoughts: 15
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience and presented in the first person:
**Checking `exit_mm` and `mmput`**
Right, let's get down to brass tacks and assess the crucial functions `exit_mm` and `mmput`. Given the context, I immediately start running through my mental checklist: what's the typical behavior of these functions in relation to memory management? What dependencies are they likely to have? Are there potential race conditions I need to consider, especially concerning shared memory regions or page table entries?
My primary concern with `exit_mm` is always the cleanup. We're essentially tearing down a process's memory space. So, I need to verify that all associated resources are properly released, from page table entries and MMU structures to any private memory regions. Think about the implications of dangling pointers or double frees – a real recipe for disaster. I want to make sure the function cleans up correctly on failure as well as success, and if it calls other memory management functions, are they thread safe?
With `mmput`, my initial thought is how it interacts with reference counting. If the MM object is no longer in use, it will be freed, but if there's other processes still using that object, it is being held back from freeing until the reference count is zero. I'm especially interested in the synchronization primitives used to manage that count. Are there any contention points here, particularly during multi-threaded access? And, what about potential memory leaks if the reference count isn't decremented correctly? Are there scenarios where a process could exit prematurely, causing an incorrect count?
Essentially, I'm thinking about the robustness and the overall integrity of the memory management system. I need to know these functions are rock solid because they're fundamental to the stability of the entire system.
|
| 126/4 |
2026/09/23 15:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:exit_mm]
Results: map[SourceCode: 580: /*
581: * Turn us into a lazy TLB process if we
582: * aren't already..
583: */
584: static void exit_mm(void)
585: {
586: struct mm_struct *mm = current->mm;
587:
588: mm_exit_exec_release(current, mm);
589: if (!mm)
590: return;
591:
592: exit_mm_sched_cache(mm);
593:
594: mmap_read_lock(mm);
595: mmgrab_lazy_tlb(mm);
596: BUG_ON(mm != current->active_mm);
597: /* more a memory barrier than a real lock */
598: task_lock(current);
599: /*
600: * When a thread stops operating on an address space, the loop
601: * in membarrier_private_expedited() may not observe that
602: * tsk->mm, and the loop in membarrier_global_expedited() may
603: * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
604: * rq->membarrier_state, so those would not issue an IPI.
605: * Membarrier requires a memory barrier after accessing
606: * user-space memory, before clearing tsk->mm or the
607: * rq->membarrier_state.
608: */
609: smp_mb__after_spinlock();
610: local_irq_disable();
611: current->mm = NULL;
612: membarrier_update_current_mm(NULL);
613: enter_lazy_tlb(mm, current);
614: local_irq_enable();
615: task_unlock(current);
616: mmap_read_unlock(mm);
617: mm_update_next_owner(mm);
618: mmput(mm);
619: if (test_thread_flag(TIF_MEMDIE))
620: exit_oom_victim();
621: }
SourceFile:kernel/exit.c]
|
| 127/4 |
2026/09/23 15:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 8947
output: 31
thoughts: 43
Thoughts: Okay, let's see. My mental process is currently focused on something called `exit_mm`. Ah, yes, there it is! I'm pretty sure that's defined within the `kernel/exit.c` file. Let me confirm that quickly. Right, good.
Now, considering the lifecycle of this memory management structure at exit, I should examine `mmput`, which is likely where the final cleanup occurs. I will head to `kernel/fork.c` now, since I understand this is often related to process creation and termination. Let's see how memory is freed upon exit.
|
| 128/4 |
2026/09/23 15:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:mmput]
Results: map[SourceCode:1208: /*
1209: * Decrement the use count and release all resources for an mm.
1210: */
1211: void mmput(struct mm_struct *mm)
1212: {
1213: might_sleep();
1214:
1215: if (atomic_dec_and_test(&mm->mm_users))
1216: __mmput(mm);
1217: }
SourceFile:kernel/fork.c]
|
| 129/4 |
2026/09/23 15:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 9301
output: 33
thoughts: 54
Thoughts: Okay, here's my take on those thoughts, framed as my own, given my expertise:
**Diving Deep into the Memory Management Conundrum**
Alright, before I start writing any more code or speculating further, let's take a deep dive into the historical context here. My gut feeling tells me this "dup_mm" issue, or anything related to memory management copying like "memcpy(mm, oldmm)", "mmlist", or "mm_users" data races is likely to have cropped up before. I need to understand if this is a new problem, or an old one rearing its ugly head.
The most efficient way to do that is to look at the commit history. I'm going to leverage my familiarity with the codebase and search the git logs specifically. Keywords are the key here. I'll start with "dup_mm" as that seems to be the core function in question. Then I'll expand my search to include related areas. Things like `memcpy` operations involving memory management structures (`mm, oldmm`), any mention of `mmlist` or `mm_users`, and of course the dreaded "data race" keyword. I'm hoping to uncover past discussions, bug reports, and crucially, any existing fixes or workarounds related to similar concurrency problems. It's a waste of time to reinvent the wheel, and I need to see what previous experts have uncovered. The goal is to either find a precedent or, if this is truly new, understand the *why* behind similar past issues to better target the current problem.
|
| 130/4 |
2026/09/23 15:52 |
tool |
git-log |
0m
Args: map[CodeRegexp:dup_mm.*memcpy PathPrefix:kernel/fork.c]
Results:
|
| 131/4 |
2026/09/23 15:53 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 9726
output: 36
thoughts: 22
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience:
**Analyzing Fork.c for Memory Duplication Concerns**
Alright, my initial approach would be to dive into the codebase, specifically targeting `fork.c`. The goal here is pretty clear: I need to pinpoint any areas where we might be inadvertently duplicating memory during a `fork()` operation. The key search terms are obvious: I'd zero in on commit messages that mention `dup_mm` or `memcpy` within `fork.c`. These keywords are immediate red flags in a process that inherently involves memory management and, potentially, data duplication. Searching for these terms offers the most direct path to identifying areas where performance, memory usage, or subtle concurrency issues could be lurking. This narrows the scope of investigation and quickly leads me to the most likely points for analysis and verification.
|
| 132/4 |
2026/09/23 15:53 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[dup_mm] PathPrefix:kernel/fork.c]
Results: map[Output:6b1c66c9cca9 exec_state: relocate dumpable information
26a8f57760c1 mm: move dup_mmap() to mm
64c37e134b12 kernel: be more careful about dup_mmap() failures and uprobe registering
8ac662f5da19 fork: avoid inappropriate uprobe access to invalid mm
985da552a98e fork: only invoke khugepaged, ksm hooks if no error
f64e67e5d3a4 fork: do not invoke uffd on fork if error occurs
35e351780fa9 fork: defer linking file vma until vma is fully initialized
d24062914837 fork: use __mt_dup() to duplicate maple tree in dup_mmap()
c9dbe82cb99d kernel/fork: use maple tree for dup_mmap() during forking
d2081b2bf819 mm: khugepaged: make khugepaged_enter() void function
73eb7f9a4ff0 mm: use helper function put_write_access()
cf508b58457c mm: use helper function mapping_allow_writable()
93949bb21b52 mm: don't prepare anon_vma if vma has VM_WIPEONFORK
aad42dd44db0 uprobes: Initialize uprobes earlier
1ed0cc5a01a4 mm: respect arch_dup_mmap() return value
655c79bb40a0 mm: check for SIGKILL inside dup_mmap() loop
07dcd7fe8993 fork: Define usercopy region in mm_struct slab caches
c10e83f598d0 arch, mm: Allow arch_dup_mmap() to fail
355627f51897 mm, uprobes: fix multiple free of ->uprobes_state.xol_area
2b7e8665b4ff fork: fix incorrect fput of ->exe_file causing use-after-free
]
|
| 133/4 |
2026/09/23 15:53 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10485
output: 30
thoughts: 447
Thoughts: **Analyzing a KCSAN Data Race in the Linux Kernel**
Okay, let's break this down. My initial instinct is to jump straight into searching commit messages for keywords like `mmlist`, `memcpy`, or `dup_mm` to see if there's any existing discussion about these functions. But hold on, let's re-read the prompt carefully, really understand the problem.
The problem, as I see it, is a KCSAN-detected data race. We have two tasks: Task A, which is exiting and calling `__mmput` and ultimately `list_del(&mm->mmlist)`, and Task B, which is cloning without `CLONE_VM` and calling `dup_mm` with a `memcpy` operation on the same `mm_struct`. The core of the issue is that both tasks seem to be operating concurrently on the same `mm_struct`, which is highly unusual.
The key question is, *how* can this happen? Specifically, I need to understand: Does Task B fail to hold an `mm_users` refcount during its execution, or how does `mm->mm_users` get decremented to zero *before* Task B is completely done? We also need to assess whether this race is something to be concerned about or not.
Now, let's try to see if others have faced this exact issue. I should check the Linux Kernel Mailing List (LKML) archives or syzkaller reports. I need to search the git log or a code search tool like Grep, and specifically look for any prior discussions, commits, or reports related to KCSAN, data races, and these key functions (`mmlist`, `dup_mm`, etc.). That's the best next step to gain context.
|
| 134/4 |
2026/09/23 15:53 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[dup_mm data race]]
Results: map[Output:6e4bd50f3888 mm/page_counter: fix various data races at memsw
7e2345200262 percpu_counter: fix a data race at vm_committed_as
]
|
| 135/4 |
2026/09/23 15:53 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 11400
output: 31
thoughts: 65
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience:
**Analyzing Kernel Memory Management Related Commit Messages**
Right, let's dive into some kernel history. My gut tells me there could be some interesting interactions around memory management, specifically with `mm_users`. I'm going to start by querying the commit messages. I need to be precise, so I'm thinking about searching for a few key terms and function calls that are usually good indicators of interesting behaviors.
First, I’ll look for instances of `atomic_dec_and_test(&mm->mm_users)`. That function is a pretty big flag, it usually shows up when the refcounting of the `mm_struct` is the source of contention. Anything involving that call is worth a closer look, especially around concurrent operations.
I'll also widen the net and search simply for `mm_users` on its own; a lot of problems tend to center around how that particular field is used and modified, and simply seeing its presence could give some context.
Beyond `mm_users` specifically, I'm going to check for the common culprits in memory management edge cases: `exit_mm`, `dup_mm`, `SIGKILL`, `zap_other_threads`, and `complete_signal`, especially in combination. These often signal potential issues related to process termination, memory duplication, signal handling, and thread synchronization, which are all prime candidates for race conditions or memory corruption bugs if the `mm` structures aren't handled correctly. The presence of any of these, in the context of memory management, likely deserves a deeper dive.
I'm essentially trying to find commits where changes in these areas intersect – that's where the real problems are likely lurking. I expect there to be a few interesting hits here and there, and I need to keep a keen eye to isolate those potential issues.
|
| 136/4 |
2026/09/23 15:53 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[dup_mm mm_users]]
Results: map[Output:86c9e8126e9f arm64: mm: Fix false positives in set_pte_at access/dirty race detection
402b08622d9a s390: KVM preparation: provide hook to enable pgstes in user pagetable
ba8a9229ab9e [S390] tlb flush fix.
]
|
| 137/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 11992
output: 25
thoughts: 1324
Thoughts: **Analyzing a Potential Memory Management Issue**
Okay, let's break this down systematically. I'm looking at two tasks, Task A and Task B, seemingly interacting with the same `mm_struct`. The core of the problem appears to be a double-free or premature release of memory related to process memory management. I'm seeing Task B, running `sys_clone` (without `CLONE_VM`, important!), and Task A exiting, calling `mmput`, and then triggering `__mmput` which is where the problem is manifesting.
My initial thoughts are, Task B is calling `sys_clone()` and Task A is exiting and calling `mmput()`. Because `atomic_dec_and_test(&mm->mm_users)` succeeds, which is unexpected, because it means the refcount for the `mm` structure must have reached zero. So, something is wrong, and I need to figure out why.
First, I established the basic flow. Task B's call chain: `sys_clone -> copy_mm -> dup_mm`. Task A's is `syscall_exit_to_user_mode -> get_signal -> do_group_exit -> do_exit -> exit_mm -> mmput -> __mmput`. Task A received a fatal signal, which is why it called `do_group_exit`.
The fact that both operate on the *exact* same `mm_struct` immediately flags a potential issue with shared memory and reference counting. Since Task A called `do_group_exit`, it must have received a fatal signal.
I need to understand the reference counting. The initial `mm_users` is 1. If we create a *thread* with `CLONE_VM`, the `mm_users` gets incremented. So, if we have two threads sharing `mm`, the `mm_users` would be at least 2. If it is 2 and we decrement, it should NOT reach zero.
I'm thinking about how `mm_users` is managed. `mmget` increments, `mmput` decrements. If Task B is using `CLONE_VM` but somehow doesn't have an appropriate `mm_users` count, that would be the problem.
So, let me investigate the `CLONE_VM` path. If the clone call uses `CLONE_VM`, it should call `mmget(oldmm);`. If there are two threads that share `mm`, then each `current->mm == mm` contributes 1 to `mm_users`. Then `mm_users` should be at least 2.
But `atomic_dec_and_test(&mm->mm_users)` succeeded! That means `mm->mm_users` must have been 0 before Task A decremented it. But how? Task B is still running.
So, how can `mm->mm_users` reach 0? It's not the normal thread case, where `CLONE_VM` is used. This requires careful consideration, as I'm starting to think about different scenarios. I'm going through the possibilities in my head. Could Task B have called `exit_mm` already? No, because it is in `sys_clone`. Was it created without `CLONE_VM`? No, if it was, it would have its own `mm`.
I'm starting to think about this in different ways. What if Task B was *not* a thread of Task A, but a separate process that was created with `CLONE_VM`? Could this be the case? The answer is yes, two tasks can share `mm` through `clone(CLONE_VM)`. Then, in `copy_mm`, we have `mmget(oldmm);`. But why would `mm->mm_users` drop to zero? So, I need to check where `mm_users` can be decremented or modified. I'm going to search for all instances of `mm_users` in the kernel to find the root cause.
|
| 138/4 |
2026/09/23 15:54 |
tool |
grepper |
0m
Args: map[Expression:mm_users PathPrefix:kernel/]
Results: map[Output:kernel/bpf/task_iter.c=428=task_vma_seq_get_next(struct bpf_iter_seq_task_vma_info *info)
--
kernel/bpf/task_iter.c-436- /* If this function returns a non-NULL vma, it holds a reference to
kernel/bpf/task_iter.c:437: * the task_struct, holds a refcount on mm->mm_users, and holds
kernel/bpf/task_iter.c-438- * read lock on vma->mm->mmap_lock.
--
kernel/events/uprobes.c=1663=void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
--
kernel/events/uprobes.c-1667-
kernel/events/uprobes.c:1668: if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */
kernel/events/uprobes.c-1669- return;
--
kernel/exit.c=495=void mm_update_next_owner(struct mm_struct *mm)
--
kernel/exit.c-509- */
kernel/exit.c:510: if (atomic_read(&mm->mm_users) <= 1) {
kernel/exit.c-511- WRITE_ONCE(mm->owner, NULL);
--
kernel/exit.c-533- for_each_process(g) {
kernel/exit.c:534: if (atomic_read(&mm->mm_users) <= 1)
kernel/exit.c-535- break;
--
kernel/exit.c-542- /*
kernel/exit.c:543: * We found no owner yet mm_users > 1: this implies that we are
kernel/exit.c-544- * most likely racing with swapoff (try_to_unuse()) or /proc or
--
kernel/fork.c=676=static void cleanup_lazy_tlbs(struct mm_struct *mm)
--
kernel/fork.c-707- * lock, to filter out false-positives in the cpumask.
kernel/fork.c:708: * - After mm_users or mm_count reaches zero, switching away from the
kernel/fork.c-709- * mm could clear mm_cpumask to reduce some IPIs, perhaps together
--
kernel/fork.c=1091=static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
--
kernel/fork.c-1094- mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
kernel/fork.c:1095: atomic_set(&mm->mm_users, 1);
kernel/fork.c-1096- atomic_set(&mm->mm_count, 1);
--
kernel/fork.c=1185=static inline void __mmput(struct mm_struct *mm)
kernel/fork.c-1186-{
kernel/fork.c:1187: VM_BUG_ON(atomic_read(&mm->mm_users));
kernel/fork.c-1188-
--
kernel/fork.c=1211=void mmput(struct mm_struct *mm)
--
kernel/fork.c-1214-
kernel/fork.c:1215: if (atomic_dec_and_test(&mm->mm_users))
kernel/fork.c-1216- __mmput(mm);
--
kernel/fork.c=1229=void mmput_async(struct mm_struct *mm)
kernel/fork.c-1230-{
kernel/fork.c:1231: if (atomic_dec_and_test(&mm->mm_users)) {
kernel/fork.c-1232- INIT_WORK(&mm->async_put_work, mmput_async_fn);
--
kernel/fork.c=1478=static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
--
kernel/fork.c-1490- if (tsk->clear_child_tid) {
kernel/fork.c:1491: if (atomic_read(&mm->mm_users) > 1) {
kernel/fork.c-1492- /*
--
kernel/sched/fair.c=4386=void init_numa_balancing(u64 clone_flags, struct task_struct *p)
kernel/sched/fair.c-4387-{
kernel/sched/fair.c:4388: int mm_users = 0;
kernel/sched/fair.c-4389- struct mm_struct *mm = p->mm;
--
kernel/sched/fair.c-4391- if (mm) {
kernel/sched/fair.c:4392: mm_users = atomic_read(&mm->mm_users);
kernel/sched/fair.c:4393: if (mm_users == 1) {
kernel/sched/fair.c-4394- mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
--
kernel/sched/fair.c-4426- delay = min_t(unsigned int, task_scan_max(current),
kernel/sched/fair.c:4427: current->numa_scan_period * mm_users * NSEC_PER_MSEC);
kernel/sched/fair.c-4428- delay += 2 * TICK_NSEC;
--
kernel/sched/membarrier.c=330=static int membarrier_private_expedited(int flags, int cpu_id)
--
kernel/sched/membarrier.c-357- if (flags != MEMBARRIER_FLAG_SYNC_CORE &&
kernel/sched/membarrier.c:358: (atomic_read(&mm->mm_users) == 1 || num_online_cpus() == 1))
kernel/sched/membarrier.c-359- return 0;
--
kernel/sched/membarrier.c=445=static int sync_runqueues_membarrier_state(struct mm_struct *mm)
--
kernel/sched/membarrier.c-450-
kernel/sched/membarrier.c:451: if (atomic_read(&mm->mm_users) == 1 || num_online_cpus() == 1) {
kernel/sched/membarrier.c-452- this_cpu_write(runqueues.membarrier_state, membarrier_state);
]
|
| 139/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15915
output: 34
thoughts: 383
Thoughts: **Analyzing Task Exit: A Deep Dive into Memory Management and Signal Handling**
Okay, so I'm looking at Task A's call stack, specifically focusing on its exit sequence. The `__mmput` call within `exit_mm` is immediately grabbing my attention. I know this function is critical for cleaning up the memory management structures associated with a process when it exits. I need to understand this process in detail.
Peering at the `exit_mm` code itself, I'm noting the key steps: `mm_exit_exec_release`, which presumably deals with releasing resources tied to an executed program, then the conditional check for `mm`. The locking and unlocking is interesting, especially the `task_lock` with its memory barrier implications. I’m zeroing in on this sequence: the disabling and enabling of local interrupts and setting `current->mm = NULL`, which is where the task’s memory descriptor is being unlinked from the current task. Then, the call to `mmput(mm)` which *should* release this MM struct. Finally, the conditional `exit_oom_victim` call in case the process died due to an out-of-memory condition.
So, `exit_mm` is the core of this memory cleanup. I’ll need to trace back from that. I'm especially interested in the synchronization primitives around `current->mm = NULL`. What’s the locking strategy, and how is it protecting the memory descriptor? The `mmgrab_lazy_tlb` call also piques my interest; it's likely involved in managing the Translation Lookaside Buffer (TLB) entries associated with the process's memory map.
To fully understand this, I must look at `do_group_exit`. It is responsible for handling the termination of process groups and their associated signals. My attention now turns to the signal handling path in `kernel/signal.c`. That’s where I need to check to understand how a signal, possibly a termination signal, interacts with the memory cleanup. The flow there will be key to understanding the relationship between the signal delivery and the memory deallocation process. Simultaneously, I will check `kernel/exit.c` for any critical actions related to the exit function. This needs to be traced through to be sure I am catching all the conditions.
Okay, let's start digging into `kernel/signal.c` and `kernel/exit.c`…
|
| 140/4 |
2026/09/23 15:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:do_group_exit]
Results: map[SourceCode:1125: /*
1126: * Take down every thread in the group. This is called by fatal signals
1127: * as well as by sys_exit_group (below).
1128: */
1129: void __noreturn
1130: do_group_exit(int exit_code)
1131: {
1132: struct signal_struct *sig = current->signal;
1133:
1134: if (sig->flags & SIGNAL_GROUP_EXIT)
1135: exit_code = sig->group_exit_code;
1136: else if (sig->group_exec_task)
1137: exit_code = 0;
1138: else {
1139: struct sighand_struct *const sighand = current->sighand;
1140:
1141: spin_lock_irq(&sighand->siglock);
1142: if (sig->flags & SIGNAL_GROUP_EXIT)
1143: /* Another thread got here before we took the lock. */
1144: exit_code = sig->group_exit_code;
1145: else if (sig->group_exec_task)
1146: exit_code = 0;
1147: else {
1148: sig->group_exit_code = exit_code;
1149: sig->flags = SIGNAL_GROUP_EXIT;
1150: zap_other_threads(current);
1151: }
1152: spin_unlock_irq(&sighand->siglock);
1153: }
1154:
1155: do_exit(exit_code);
1156: /* NOTREACHED */
1157: }
SourceFile:kernel/exit.c]
|
| 141/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17347
output: 34
thoughts: 59
Thoughts: Here's my summary, as I see it:
**Analyzing Thread Termination**
Hold on a second! My attention's drawn to this call, `zap_other_threads(current)`. Immediately, the alarm bells are ringing – a direct thread kill like that usually needs very close inspection. What's the function `zap_other_threads` actually *doing*? Ah, it appears to be sending a `SIGKILL` signal to other threads within the current thread group. Okay, that confirms my initial concern. Time to dive deeper; either `zap_other_threads` or the potentially related `complete_signal` function require immediate scrutiny. Gotta understand the conditions under which these lethal signals are dispatched.
|
| 142/4 |
2026/09/23 15:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/signal.c Name:zap_other_threads]
Results: map[SourceCode:1368: /*
1369: * Nuke all other threads in the group.
1370: */
1371: int zap_other_threads(struct task_struct *p)
1372: {
1373: struct task_struct *t;
1374: int count = 0;
1375:
1376: p->signal->group_stop_count = 0;
1377: task_clear_jobctl_pending(p, JOBCTL_PENDING_MASK);
1378:
1379: for_other_threads(p, t) {
1380: task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
1381: count++;
1382:
1383: /* Don't bother with already dead threads */
1384: if (t->exit_state)
1385: continue;
1386: sigaddset(&t->pending.signal, SIGKILL);
1387: signal_wake_up(t, 1);
1388: }
1389:
1390: return count;
1391: }
SourceFile:kernel/signal.c]
|
| 143/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17938
output: 32
thoughts: 46
Thoughts: Okay, here's my assessment of the situation, tailored for my fellow experts:
**Potential Race Condition in Process Forking**
Hold on a second! I'm concerned about a potential race condition here. Specifically, I'm envisioning a scenario where Task B might enter the `copy_process` function *while* Task A is in the process of exiting. That would be a nightmare. We need to be absolutely certain this isn't possible.
Let's zoom in on this, focusing on what happens within `copy_process` itself. I'm going to quickly check the code in `kernel/fork.c`, as that's where `copy_process` is usually defined. I need to understand the sequencing of operations during the process duplication. The goal is to identify if there are any critical sections or locking mechanisms that protect against this overlapping execution. I need to meticulously trace the steps to confirm the concurrency assumptions. This requires a very careful re-evaluation of the synchronization primitives involved, looking for any potential gaps.
|
| 144/4 |
2026/09/23 15:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_process]
Results: map[SourceCode:2004: /*
2005: * This creates a new process as a copy of the old one,
2006: * but does not actually start it yet.
2007: *
2008: * It copies the registers, and all the appropriate
2009: * parts of the process environment (as per the clone
2010: * flags). The actual kick-off is left to the caller.
2011: */
2012: __latent_entropy struct task_struct *copy_process(
2013: struct pid *pid,
2014: int trace,
2015: int node,
2016: struct kernel_clone_args *args)
2017: {
2018: int pidfd = -1, retval;
2019: struct task_struct *p;
2020: struct multiprocess_signals delayed;
2021: struct file *pidfile = NULL;
2022: const u64 clone_flags = args->flags;
2023: struct nsproxy *nsp = current->nsproxy;
2024:
2025: /*
2026: * Don't allow sharing the root directory with processes in a different
2027: * namespace
2028: */
2029: if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
2030: return ERR_PTR(-EINVAL);
2031:
2032: if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2033: return ERR_PTR(-EINVAL);
2034:
2035: /*
2036: * Thread groups must share signals as well, and detached threads
2037: * can only be started up within the thread group.
2038: */
2039: if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
2040: return ERR_PTR(-EINVAL);
2041:
2042: /*
2043: * Shared signal handlers imply shared VM. By way of the above,
2044: * thread groups also imply shared VM. Blocking this case allows
2045: * for various simplifications in other code.
2046: */
2047: if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2048: return ERR_PTR(-EINVAL);
2049:
2050: /*
2051: * Siblings of global init remain as zombies on exit since they are
2052: * not reaped by their parent (swapper). To solve this and to avoid
2053: * multi-rooted process trees, prevent global and container-inits
2054: * from creating siblings.
2055: */
2056: if ((clone_flags & CLONE_PARENT) &&
2057: current->signal->flags & SIGNAL_UNKILLABLE)
2058: return ERR_PTR(-EINVAL);
2059:
2060: /*
2061: * If the new process will be in a different pid or user namespace
2062: * do not allow it to share a thread group with the forking task.
2063: */
2064: if (clone_flags & CLONE_THREAD) {
2065: if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2066: (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2067: return ERR_PTR(-EINVAL);
2068: }
2069:
2070: if (clone_flags & CLONE_PIDFD) {
2071: /*
2072: * - CLONE_DETACHED is blocked so that we can potentially
2073: * reuse it later for CLONE_PIDFD.
2074: */
2075: if (clone_flags & CLONE_DETACHED)
2076: return ERR_PTR(-EINVAL);
2077: }
2078:
2079: if (clone_flags & CLONE_AUTOREAP) {
2080: if (clone_flags & CLONE_THREAD)
2081: return ERR_PTR(-EINVAL);
2082: if (clone_flags & CLONE_PARENT)
2083: return ERR_PTR(-EINVAL);
2084: if (args->exit_signal)
2085: return ERR_PTR(-EINVAL);
2086: }
2087:
2088: if ((clone_flags & CLONE_PARENT) && current->signal->autoreap)
2089: return ERR_PTR(-EINVAL);
2090:
2091: if (clone_flags & CLONE_NNP) {
2092: if (clone_flags & CLONE_THREAD)
2093: return ERR_PTR(-EINVAL);
2094: }
2095:
2096: if (clone_flags & CLONE_PIDFD_AUTOKILL) {
2097: if (!(clone_flags & CLONE_PIDFD))
2098: return ERR_PTR(-EINVAL);
2099: if (!(clone_flags & CLONE_AUTOREAP))
2100: return ERR_PTR(-EINVAL);
2101: if (clone_flags & CLONE_THREAD)
2102: return ERR_PTR(-EINVAL);
2103: /*
2104: * Without CLONE_NNP the child could escalate privileges
2105: * after being spawned, so require CAP_SYS_ADMIN.
2106: * With CLONE_NNP the child can't gain new privileges,
2107: * so allow unprivileged usage.
2108: */
2109: if (!(clone_flags & CLONE_NNP) &&
2110: !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
2111: return ERR_PTR(-EPERM);
2112: }
2113:
2114: /*
2115: * Force any signals received before this point to be delivered
2116: * before the fork happens. Collect up signals sent to multiple
2117: * processes that happen during the fork and delay them so that
2118: * they appear to happen after the fork.
2119: */
2120: sigemptyset(&delayed.signal);
2121: INIT_HLIST_NODE(&delayed.node);
2122:
2123: spin_lock_irq(¤t->sighand->siglock);
2124: if (!(clone_flags & CLONE_THREAD))
2125: hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
2126: recalc_sigpending();
2127: spin_unlock_irq(¤t->sighand->siglock);
2128: retval = -ERESTARTNOINTR;
2129: if (task_sigpending(current))
2130: goto fork_out;
2131:
2132: retval = -ENOMEM;
2133: p = dup_task_struct(current, node);
2134: if (!p)
2135: goto fork_out;
2136: /*
2137: * Must run before the first fallible op, so error paths never
2138: * free the parent's ret_stack.
2139: */
2140: ftrace_graph_init_task(p);
2141: retval = copy_exec_state(clone_flags, p);
2142: if (retval)
2143: goto bad_fork_free;
2144: p->flags &= ~PF_KTHREAD;
2145: if (args->kthread)
2146: p->flags |= PF_KTHREAD;
2147: if (args->user_worker) {
2148: /*
2149: * Mark us a user worker, and block any signal that isn't
2150: * fatal or STOP
2151: */
2152: p->flags |= PF_USER_WORKER;
2153: siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2154: }
2155: if (args->io_thread)
2156: p->flags |= PF_IO_WORKER;
2157:
2158: if (args->name)
2159: strscpy_pad(p->comm, args->name, sizeof(p->comm));
2160:
2161: p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2162: /*
2163: * TID is cleared in mm_release() when the task exits
2164: */
2165: p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2166:
2167: rt_mutex_init_task(p);
2168: raw_spin_lock_init(&p->blocked_lock);
2169:
2170: lockdep_assert_irqs_enabled();
2171: #ifdef CONFIG_PROVE_LOCKING
2172: DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2173: #endif
2174: retval = copy_creds(p, clone_flags);
2175: if (retval < 0)
2176: goto bad_fork_free;
2177:
2178: retval = -EAGAIN;
2179: if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2180: if (p->real_cred->user != INIT_USER &&
2181: !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2182: goto bad_fork_cleanup_count;
2183: }
2184: current->flags &= ~PF_NPROC_EXCEEDED;
2185:
2186: /*
2187: * If multiple threads are within copy_process(), then this check
2188: * triggers too late. This doesn't hurt, the check is only there
2189: * to stop root fork bombs.
2190: */
2191: retval = -EAGAIN;
2192: if (data_race(nr_threads >= max_threads))
2193: goto bad_fork_cleanup_count;
2194:
2195: delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
2196: p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2197: p->flags |= PF_FORKNOEXEC;
2198: INIT_LIST_HEAD(&p->children);
2199: INIT_LIST_HEAD(&p->sibling);
2200: rcu_copy_process(p);
2201: p->vfork_done = NULL;
2202: spin_lock_init(&p->alloc_lock);
2203:
2204: init_sigpending(&p->pending);
2205:
2206: p->utime = p->stime = p->gtime = 0;
2207: #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2208: p->utimescaled = p->stimescaled = 0;
2209: #endif
2210: prev_cputime_init(&p->prev_cputime);
2211:
2212: #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2213: seqcount_init(&p->vtime.seqcount);
2214: p->vtime.starttime = 0;
2215: p->vtime.state = VTIME_INACTIVE;
2216: #endif
2217:
2218: #ifdef CONFIG_IO_URING
2219: p->io_uring = NULL;
2220: retval = io_uring_fork(p);
2221: if (unlikely(retval))
2222: goto bad_fork_cleanup_delayacct;
2223: retval = -EAGAIN;
2224: #endif
2225:
2226: p->default_timer_slack_ns = current->timer_slack_ns;
2227:
2228: #ifdef CONFIG_PSI
2229: p->psi_flags = 0;
2230: #endif
2231:
2232: task_io_accounting_init(&p->ioac);
2233: acct_clear_integrals(p);
2234:
2235: posix_cputimers_init(&p->posix_cputimers);
2236: tick_dep_init_task(p);
2237:
2238: p->io_context = NULL;
2239: audit_set_context(p, NULL);
2240: cgroup_fork(p);
2241: if (args->kthread) {
2242: if (!set_kthread_struct(p))
2243: goto bad_fork_cleanup_delayacct;
2244: }
2245: #ifdef CONFIG_NUMA
2246: p->mempolicy = mpol_dup(p->mempolicy);
2247: if (IS_ERR(p->mempolicy)) {
2248: retval = PTR_ERR(p->mempolicy);
2249: p->mempolicy = NULL;
2250: goto bad_fork_cleanup_delayacct;
2251: }
2252: #endif
2253: #ifdef CONFIG_CPUSETS
2254: p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2255: seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2256: #endif
2257: #ifdef CONFIG_TRACE_IRQFLAGS
2258: memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2259: p->irqtrace.hardirq_disable_ip = _THIS_IP_;
2260: p->irqtrace.softirq_enable_ip = _THIS_IP_;
2261: p->softirqs_enabled = 1;
2262: p->softirq_context = 0;
2263: #endif
2264:
2265: p->pagefault_disabled = 0;
2266:
2267: lockdep_init_task(p);
2268:
2269: p->blocked_on = NULL; /* not blocked yet */
2270: p->blocked_donor = NULL; /* nobody is boosting p yet */
2271:
2272: #ifdef CONFIG_BCACHE
2273: p->sequential_io = 0;
2274: p->sequential_io_avg = 0;
2275: #endif
2276:
2277: unwind_task_init(p);
2278:
2279: /* Perform scheduler related setup. Assign this task to a CPU. */
2280: retval = sched_fork(clone_flags, p);
2281: if (retval)
2282: goto bad_fork_cleanup_policy;
2283:
2284: retval = perf_event_init_task(p, clone_flags);
2285: if (retval)
2286: goto bad_fork_sched_cancel_fork;
2287: retval = audit_alloc(p);
2288: if (retval)
2289: goto bad_fork_cleanup_perf;
2290: /* copy all the process information */
2291: shm_init_task(p);
2292: retval = security_task_alloc(p, clone_flags);
2293: if (retval)
2294: goto bad_fork_cleanup_audit;
2295: retval = copy_semundo(clone_flags, p);
2296: if (retval)
2297: goto bad_fork_cleanup_security;
2298: retval = copy_files(clone_flags, p, args->no_files);
2299: if (retval)
2300: goto bad_fork_cleanup_semundo;
2301: retval = copy_fs(clone_flags, p, args->umh);
2302: if (retval)
2303: goto bad_fork_cleanup_files;
2304: retval = copy_sighand(clone_flags, p);
2305: if (retval)
2306: goto bad_fork_cleanup_fs;
2307: retval = copy_signal(clone_flags, p);
2308: if (retval)
2309: goto bad_fork_cleanup_sighand;
2310: retval = copy_mm(clone_flags, p);
2311: if (retval)
2312: goto bad_fork_cleanup_signal;
2313: retval = copy_namespaces(clone_flags, p);
2314: if (retval)
2315: goto bad_fork_cleanup_mm;
2316: retval = copy_io(clone_flags, p);
2317: if (retval)
2318: goto bad_fork_cleanup_namespaces;
2319: retval = copy_thread(p, args);
2320: if (retval)
2321: goto bad_fork_cleanup_io;
2322:
2323: stackleak_task_init(p);
2324:
2325: if (pid != &init_struct_pid) {
2326: pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2327: args->set_tid_size);
2328: if (IS_ERR(pid)) {
2329: retval = PTR_ERR(pid);
2330: goto bad_fork_cleanup_thread;
2331: }
2332: }
2333:
2334: /*
2335: * This has to happen after we've potentially unshared the file
2336: * descriptor table (so that the pidfd doesn't leak into the child
2337: * if the fd table isn't shared).
2338: */
2339: if (clone_flags & CLONE_PIDFD) {
2340: unsigned flags = PIDFD_STALE;
2341:
2342: if (clone_flags & CLONE_THREAD)
2343: flags |= PIDFD_THREAD;
2344: if (clone_flags & CLONE_PIDFD_AUTOKILL)
2345: flags |= PIDFD_AUTOKILL;
2346:
2347: /*
2348: * Note that no task has been attached to @pid yet indicate
2349: * that via CLONE_PIDFD.
2350: */
2351: retval = pidfd_prepare(pid, flags, &pidfile);
2352: if (retval < 0)
2353: goto bad_fork_free_pid;
2354: pidfd = retval;
2355:
2356: retval = put_user(pidfd, args->pidfd);
2357: if (retval)
2358: goto bad_fork_put_pidfd;
2359: }
2360:
2361: #ifdef CONFIG_BLOCK
2362: p->plug = NULL;
2363: p->flags &= ~PF_BLOCK_TS;
2364: #endif
2365: futex_init_task(p);
2366:
2367: /*
2368: * sigaltstack should be cleared when sharing the same VM
2369: */
2370: if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2371: sas_ss_reset(p);
2372:
2373: /*
2374: * Syscall tracing and stepping should be turned off in the
2375: * child regardless of CLONE_PTRACE.
2376: */
2377: user_disable_single_step(p);
2378: clear_task_syscall_work(p, SYSCALL_TRACE);
2379: #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2380: clear_task_syscall_work(p, SYSCALL_EMU);
2381: #endif
2382: clear_tsk_latency_tracing(p);
2383:
2384: /* ok, now we should be set up.. */
2385: p->pid = pid_nr(pid);
2386: if (clone_flags & CLONE_THREAD) {
2387: p->group_leader = current->group_leader;
2388: p->tgid = current->tgid;
2389: } else {
2390: p->group_leader = p;
2391: p->tgid = p->pid;
2392: }
2393:
2394: p->nr_dirtied = 0;
2395: p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2396: p->dirty_paused_when = 0;
2397:
2398: p->pdeath_signal = 0;
2399: p->task_works = NULL;
2400: clear_posix_cputimers_work(p);
2401:
2402: #ifdef CONFIG_KRETPROBES
2403: p->kretprobe_instances.first = NULL;
2404: #endif
2405: #ifdef CONFIG_RETHOOK
2406: p->rethooks.first = NULL;
2407: #endif
2408:
2409: /*
2410: * Ensure that the cgroup subsystem policies allow the new process to be
2411: * forked. It should be noted that the new process's css_set can be changed
2412: * between here and cgroup_post_fork() if an organisation operation is in
2413: * progress.
2414: */
2415: retval = cgroup_can_fork(p, args);
2416: if (retval)
2417: goto bad_fork_put_pidfd;
2418:
2419: /*
2420: * Now that the cgroups are pinned, re-clone the parent cgroup and put
2421: * the new task on the correct runqueue. All this *before* the task
2422: * becomes visible.
2423: *
2424: * This isn't part of ->can_fork() because while the re-cloning is
2425: * cgroup specific, it unconditionally needs to place the task on a
2426: * runqueue.
2427: */
2428: retval = sched_cgroup_fork(p, args);
2429: if (retval)
2430: goto bad_fork_cancel_cgroup;
2431:
2432: if (need_futex_hash_allocate_default(clone_flags)) {
2433: retval = futex_hash_allocate_default();
2434: if (retval)
2435: goto bad_fork_cancel_cgroup;
2436: /*
2437: * If we fail beyond this point we don't free the allocated
2438: * futex hash map. We assume that another thread will be created
2439: * and makes use of it. The hash map will be freed once the main
2440: * thread terminates.
2441: */
2442: }
2443: /*
2444: * From this point on we must avoid any synchronous user-space
2445: * communication until we take the tasklist-lock. In particular, we do
2446: * not want user-space to be able to predict the process start-time by
2447: * stalling fork(2) after we recorded the start_time but before it is
2448: * visible to the system.
2449: */
2450:
2451: p->start_time = ktime_get_ns();
2452: p->start_boottime = ktime_get_boottime_ns();
2453:
2454: /*
2455: * Make it visible to the rest of the system, but dont wake it up yet.
2456: * Need tasklist lock for parent etc handling!
2457: */
2458: write_lock_irq(&tasklist_lock);
2459:
2460: /* CLONE_PARENT re-uses the old parent */
2461: if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2462: p->real_parent = current->real_parent;
2463: p->parent_exec_id = current->parent_exec_id;
2464: if (clone_flags & CLONE_THREAD)
2465: p->exit_signal = -1;
2466: else
2467: p->exit_signal = current->group_leader->exit_signal;
2468: } else {
2469: p->real_parent = current;
2470: p->parent_exec_id = current->self_exec_id;
2471: p->exit_signal = args->exit_signal;
2472: }
2473:
2474: klp_copy_process(p);
2475:
2476: sched_core_fork(p);
2477:
2478: spin_lock(¤t->sighand->siglock);
2479:
2480: rv_task_fork(p);
2481:
2482: rseq_fork(p, clone_flags);
2483:
2484: /*
2485: * If zap_pid_ns_processes() was called after alloc_pid(), the new
2486: * child missed SIGKILL. If current is not in the same namespace,
2487: * we can't rely on fatal_signal_pending() below.
2488: */
2489: if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2490: retval = -ENOMEM;
2491: goto bad_fork_core_free;
2492: }
2493:
2494: /* Let kill terminate clone/fork in the middle */
2495: if (fatal_signal_pending(current)) {
2496: retval = -EINTR;
2497: goto bad_fork_core_free;
2498: }
2499:
2500: /* No more failure paths after this point. */
2501:
2502: /*
2503: * Copy seccomp details explicitly here, in case they were changed
2504: * before holding sighand lock.
2505: */
2506: copy_seccomp(p);
2507:
2508: if (clone_flags & CLONE_NNP)
2509: task_set_no_new_privs(p);
2510:
2511: init_task_pid_links(p);
2512: if (likely(p->pid)) {
2513: ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2514:
2515: init_task_pid(p, PIDTYPE_PID, pid);
2516: if (thread_group_leader(p)) {
2517: init_task_pid(p, PIDTYPE_TGID, pid);
2518: init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2519: init_task_pid(p, PIDTYPE_SID, task_session(current));
2520:
2521: if (is_child_reaper(pid)) {
2522: struct pid_namespace *ns = ns_of_pid(pid);
2523:
2524: ASSERT_EXCLUSIVE_WRITER(ns->child_reaper);
2525: WRITE_ONCE(ns->child_reaper, p);
2526: p->signal->flags |= SIGNAL_UNKILLABLE;
2527: }
2528: p->signal->shared_pending.signal = delayed.signal;
2529: p->signal->tty = tty_kref_get(current->signal->tty);
2530: /*
2531: * Inherit has_child_subreaper flag under the same
2532: * tasklist_lock with adding child to the process tree
2533: * for propagate_has_child_subreaper optimization.
2534: */
2535: p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2536: p->real_parent->signal->is_child_subreaper;
2537: if (clone_flags & CLONE_AUTOREAP)
2538: p->signal->autoreap = 1;
2539: list_add_tail(&p->sibling, &p->real_parent->children);
2540: list_add_tail_rcu(&p->tasks, &init_task.tasks);
2541: attach_pid(p, PIDTYPE_TGID);
2542: attach_pid(p, PIDTYPE_PGID);
2543: attach_pid(p, PIDTYPE_SID);
2544: __this_cpu_inc(process_counts);
2545: } else {
2546: current->signal->nr_threads++;
2547: current->signal->quick_threads++;
2548: atomic_inc(¤t->signal->live);
2549: refcount_inc(¤t->signal->sigcnt);
2550: task_join_group_stop(p);
2551: list_add_tail_rcu(&p->thread_node,
2552: &p->signal->thread_head);
2553: }
2554: attach_pid(p, PIDTYPE_PID);
2555: nr_threads++;
2556: }
2557: total_forks++;
2558: hlist_del_init(&delayed.node);
2559: spin_unlock(¤t->sighand->siglock);
2560: syscall_tracepoint_update(p);
2561: write_unlock_irq(&tasklist_lock);
2562:
2563: if (pidfile)
2564: fd_install(pidfd, pidfile);
2565:
2566: proc_fork_connector(p);
2567: /*
2568: * sched_ext needs @p to be associated with its cgroup in its post_fork
2569: * hook. cgroup_post_fork() should come before sched_post_fork().
2570: */
2571: cgroup_post_fork(p, args);
2572: sched_post_fork(p);
2573: perf_event_fork(p);
2574:
2575: trace_task_newtask(p, clone_flags);
2576: uprobe_copy_process(p, clone_flags);
2577: user_events_fork(p, clone_flags);
2578:
2579: copy_oom_score_adj(clone_flags, p);
2580:
2581: return p;
2582:
2583: bad_fork_core_free:
2584: sched_core_free(p);
2585: spin_unlock(¤t->sighand->siglock);
2586: write_unlock_irq(&tasklist_lock);
2587: bad_fork_cancel_cgroup:
2588: cgroup_cancel_fork(p, args);
2589: bad_fork_put_pidfd:
2590: if (clone_flags & CLONE_PIDFD) {
2591: fput(pidfile);
2592: put_unused_fd(pidfd);
2593: }
2594: bad_fork_free_pid:
2595: if (pid != &init_struct_pid)
2596: free_pid(pid);
2597: bad_fork_cleanup_thread:
2598: exit_thread(p);
2599: bad_fork_cleanup_io:
2600: if (p->io_context)
2601: exit_io_context(p);
2602: bad_fork_cleanup_namespaces:
2603: exit_nsproxy_namespaces(p);
2604: bad_fork_cleanup_mm:
2605: if (p->mm) {
2606: mm_clear_owner(p->mm, p);
2607: mmput(p->mm);
2608: }
2609: bad_fork_cleanup_signal:
2610: if (!(clone_flags & CLONE_THREAD))
2611: free_signal_struct(p->signal);
2612: bad_fork_cleanup_sighand:
2613: __cleanup_sighand(p->sighand);
2614: bad_fork_cleanup_fs:
2615: exit_fs(p); /* blocking */
2616: bad_fork_cleanup_files:
2617: exit_files(p); /* blocking */
2618: bad_fork_cleanup_semundo:
2619: exit_sem(p);
2620: bad_fork_cleanup_security:
2621: security_task_free(p);
2622: bad_fork_cleanup_audit:
2623: audit_free(p);
2624: bad_fork_cleanup_perf:
2625: perf_event_free_task(p);
2626: bad_fork_sched_cancel_fork:
2627: sched_cancel_fork(p);
2628: bad_fork_cleanup_policy:
2629: lockdep_free_task(p);
2630: #ifdef CONFIG_NUMA
2631: mpol_put(p->mempolicy);
2632: #endif
2633: bad_fork_cleanup_delayacct:
2634: io_uring_free(p);
2635: delayacct_tsk_free(p);
2636: bad_fork_cleanup_count:
2637: dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2638: exit_cred_namespaces(p);
2639: exit_creds(p);
2640: bad_fork_free:
2641: WRITE_ONCE(p->__state, TASK_DEAD);
2642: exit_task_stack_account(p);
2643: put_task_stack(p);
2644: delayed_free_task(p);
2645: fork_out:
2646: spin_lock_irq(¤t->sighand->siglock);
2647: hlist_del_init(&delayed.node);
2648: spin_unlock_irq(¤t->sighand->siglock);
2649: return ERR_PTR(retval);
2650: }
SourceFile:kernel/fork.c]
|
| 145/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 28279
output: 44
thoughts: 1082
Thoughts: **Tracing a Concurrency Issue in Kernel Memory Management**
Okay, let's break this down. KCSAN has flagged a data race, and my expert intuition is piqued. We've got two tasks, A and B, operating on the same `mm_struct`, and I need to figure out how this is possible. Task A, identified as task 21217 on CPU 1, is deep inside `mmput` and, specifically, calling `list_del(&mm->mmlist)` which suggests memory management cleanup, while Task B, identified as task 3876 on CPU 0, is executing `sys_clone` *without* `CLONE_VM`. This is immediately interesting.
Task B's `sys_clone` call is leading to a `dup_mm` call, where it appears to be reading `oldmm` (which is equal to `current->mm`) using `memcpy(mm, oldmm, sizeof(*mm))`. The critical point here is that Task A is *writing* to `mm->mmlist` via `list_del`, which is *inside* the `struct mm_struct` itself, while Task B is concurrently *reading* that same `struct mm_struct` during the `memcpy` operation.
KCSAN correctly detects a potential data race because the write in Task A's `list_del` and the read in Task B's `memcpy` are operating on the same memory location, specifically the `mmlist` field within the `mm_struct`.
Now, the core of the mystery: How can these tasks be operating on the same `mm_struct` in the first place? And more importantly, how can `atomic_dec_and_test(&mm->mm_users)` succeed in Task A (leading to the `list_del`) if Task B is still running?
The key lies in the fact that Task B is created by `sys_clone` *without* `CLONE_VM`. The question implies that Task A is exiting and calling `mmput(mm)`. Therefore, how does `mm->mm_users` get to zero to allow the cleanup if Task B, the child, is still running and potentially holding a reference to the `mm_struct`? The question implies that `Task B` *does not* hold an `mm_users` reference!
If Task B's `current->mm` is the same as the `oldmm` passed to `dup_mm`, then it has to be the same `mm_struct` that Task A is using. If Task B had been created with `CLONE_VM`, there would be a `mmget(oldmm)` call in `copy_mm`, which would increment `mm->mm_users`. With `CLONE_VM`, there would be no problem! However, because Task B *didn't* use `CLONE_VM`, Task B would not get an `mmget(oldmm)` call and thus would NOT increment `mm->mm_users`.
So, if Task B didn't get an `mm_users` refcount, then it is possible that while Task B is running, `mm->mm_users` can be decremented to zero and that Task A will be able to perform the memory cleanup operations in its `mmput` call.
The remaining questions now are if this data race is harmless or harmful. That depends on what the code does when it detects this condition. Also, does Task B ever drop its `mm_users` reference? I better search the entire kernel for calls to `mmput` to find out!
|
| 146/4 |
2026/09/23 15:54 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:1 Name:mmput SourceTreePrefix:]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__do_sys_process_madvise SourceFile:mm/madvise.c SourceLine:2154 SourceSnippet:2153: release_mm:
2154: mmput(mm);
2155: release_task:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:access_process_vm SourceFile:mm/memory.c SourceLine:7323 SourceSnippet:7322:
7323: mmput(mm);
7324:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:build_map_info SourceFile:kernel/events/uprobes.c SourceLine:1253 SourceSnippet:1252: while (curr) {
1253: mmput(curr->mm);
1254: curr = curr->next;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:clear_refs_write SourceFile:fs/proc/task_mmu.c SourceLine:1926 SourceSnippet:1925: out_mm:
1926: mmput(mm);
1927: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_process SourceFile:kernel/fork.c SourceLine:2607 SourceSnippet:2606: mm_clear_owner(p->mm, p);
2607: mmput(p->mm);
2608: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_remote_vm_str SourceFile:mm/memory.c SourceLine:7442 SourceSnippet:7441:
7442: mmput(mm);
7443:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_attach_task SourceFile:kernel/cgroup/cpuset.c SourceLine:3334 SourceSnippet:3333: } else {
3334: mmput(mm);
3335: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_migrate_mm SourceFile:kernel/cgroup/cpuset.c SourceLine:2623 SourceSnippet:2622: if (nodes_equal(*from, *to)) {
2623: mmput(mm);
2624: return;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_migrate_mm SourceFile:kernel/cgroup/cpuset.c SourceLine:2635 SourceSnippet:2634: } else {
2635: mmput(mm);
2636: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_migrate_mm_workfn SourceFile:kernel/cgroup/cpuset.c SourceLine:2613 SourceSnippet:2612: do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
2613: mmput(mwork->mm);
2614: kfree(mwork);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:cpuset_update_tasks_nodemask SourceFile:kernel/cgroup/cpuset.c SourceLine:2750 SourceSnippet:2749: else
2750: mmput(mm);
2751: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_procmap_query SourceFile:fs/proc/task_mmu.c SourceLine:722 SourceSnippet: 721: if (err) {
722: mmput(mm);
723: return err;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_procmap_query SourceFile:fs/proc/task_mmu.c SourceLine:800 SourceSnippet: 799: query_vma_teardown(&lock_ctx);
800: mmput(mm);
801:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_procmap_query SourceFile:fs/proc/task_mmu.c SourceLine:841 SourceSnippet: 840: query_vma_teardown(&lock_ctx);
841: mmput(mm);
842: out_file:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_task_stat SourceFile:fs/proc/array.c SourceLine:667 SourceSnippet: 666: if (mm)
667: mmput(mm);
668: return 0;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:dup_mm SourceFile:kernel/fork.c SourceLine:1560 SourceSnippet:1559: mm_init_owner(mm, NULL);
1560: mmput(mm);
1561: if (err)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:environ_read SourceFile:fs/proc/base.c SourceLine:1043 SourceSnippet:1042: *ppos = src;
1043: mmput(mm);
1044:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ep_user_copy_worker SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:478 SourceSnippet: 477: kthread_unuse_mm(mm);
478: mmput(mm);
479: if (!ret)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:exec_mm_put_old SourceFile:fs/exec.c SourceLine:919 SourceSnippet: 918: mm_update_next_owner(old_mm);
919: mmput(old_mm);
920: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:exit_mm SourceFile:kernel/exit.c SourceLine:618 SourceSnippet: 617: mm_update_next_owner(mm);
618: mmput(mm);
619: if (test_thread_flag(TIF_MEMDIE))
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ffs_user_copy_worker SourceFile:drivers/usb/gadget/function/f_fs.c SourceLine:883 SourceSnippet: 882: kthread_unuse_mm(io_data->mm);
883: mmput(io_data->mm);
884: } else {
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:free_bprm SourceFile:fs/exec.c SourceLine:1480 SourceSnippet:1479: acct_arg_size(bprm, 0);
1480: mmput(bprm->mm);
1481: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:get_cmdline SourceFile:mm/util.c SourceLine:1059 SourceSnippet:1058: out_mm:
1059: mmput(mm);
1060: out:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:get_task_cmdline SourceFile:fs/proc/base.c SourceLine:381 SourceSnippet: 380: ret = get_mm_cmdline(mm, buf, count, pos);
381: mmput(mm);
382: return ret;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:getrusage SourceFile:kernel/sys.c SourceLine:1925 SourceSnippet:1924: setmax_mm_hiwater_rss(&maxrss, mm);
1925: mmput(mm);
1926: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ib_umem_odp_alloc_child SourceFile:drivers/infiniband/core/umem_odp.c SourceLine:209 SourceSnippet: 208: goto out_tgid;
209: mmput(umem->owning_mm);
210: return odp_data;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ib_umem_odp_alloc_child SourceFile:drivers/infiniband/core/umem_odp.c SourceLine:214 SourceSnippet: 213: put_pid(odp_data->tgid);
214: mmput(umem->owning_mm);
215: out_free:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:iommu_sva_handle_mm SourceFile:drivers/iommu/iommu-sva.c SourceLine:270 SourceSnippet: 269: mmap_read_unlock(mm);
270: mmput(mm);
271:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:kernel_migrate_pages SourceFile:mm/mempolicy.c SourceLine:1938 SourceSnippet:1937:
1938: mmput(mm);
1939: out:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:kernel_move_pages SourceFile:mm/migrate.c SourceLine:2629 SourceSnippet:2628:
2629: mmput(mm);
2630: return err;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:m_start SourceFile:fs/proc/task_mmu.c SourceLine:332 SourceSnippet: 331: if (!lock_vma_range(m, lock_ctx)) {
332: mmput(mm);
333: put_task_struct(priv->task);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:m_stop SourceFile:fs/proc/task_mmu.c SourceLine:371 SourceSnippet: 370: unlock_vma_range(&priv->lock_ctx);
371: mmput(mm);
372: put_task_struct(priv->task);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:map_files_d_revalidate SourceFile:fs/proc/base.c SourceLine:2210 SourceSnippet:2209:
2210: mmput(mm);
2211:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:map_files_get_link SourceFile:fs/proc/base.c SourceLine:2262 SourceSnippet:2261: out_mmput:
2262: mmput(mm);
2263: out:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:mem_rw SourceFile:fs/proc/base.c SourceLine:931 SourceSnippet: 930:
931: mmput(mm);
932: free:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:mm_access SourceFile:kernel/fork.c SourceLine:1424 SourceSnippet:1423: } else if (!may_access_mm(mm, task, mode)) {
1424: mmput(mm);
1425: mm = ERR_PTR(-EACCES);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:pagemap_read SourceFile:fs/proc/task_mmu.c SourceLine:2393 SourceSnippet:2392: out_mm:
2393: mmput(mm);
2394: out:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:perf_event_addr_filters_apply SourceFile:kernel/events/core.c SourceLine:11993 SourceSnippet:11992:
11993: mmput(mm);
11994: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_coredump_filter_read SourceFile:fs/proc/base.c SourceLine:2943 SourceSnippet:2942: MMF_DUMP_FILTER_SHIFT));
2943: mmput(mm);
2944: ret = simple_read_from_buffer(buf, count, ppos, buffer, len);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_coredump_filter_write SourceFile:fs/proc/base.c SourceLine:2985 SourceSnippet:2984:
2985: mmput(mm);
2986: out_no_mm:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_map_files_lookup SourceFile:fs/proc/base.c SourceLine:2362 SourceSnippet:2361: out_put_mm:
2362: mmput(mm);
2363: out_put_task:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_map_files_readdir SourceFile:fs/proc/base.c SourceLine:2460 SourceSnippet:2459: out_put_mm:
2460: mmput(mm);
2461: out_put_task:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_mem_open SourceFile:fs/proc/base.c SourceLine:835 SourceSnippet: 834: /* but do not pin its memory */
835: mmput(mm);
836:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_pid_statm SourceFile:fs/proc/array.c SourceLine:696 SourceSnippet: 695: size = task_statm(mm, &shared, &text, &data, &resident);
696: mmput(mm);
697:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:proc_pid_status SourceFile:fs/proc/array.c SourceLine:454 SourceSnippet: 453: task_untag_mask(m, mm);
454: mmput(mm);
455: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:process_vm_rw_core SourceFile:mm/process_vm_access.c SourceLine:229 SourceSnippet: 228:
229: mmput(mm);
230:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ptrace_access_vm SourceFile:kernel/ptrace.c SourceLine:81 SourceSnippet: 80: ret = access_remote_vm(mm, addr, buf, len, gup_flags);
81: mmput(mm);
82:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:register_for_each_vma SourceFile:kernel/events/uprobes.c SourceLine:1327 SourceSnippet:1326: free:
1327: mmput(mm);
1328: info = free_map_info(info);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:show_smaps_rollup SourceFile:fs/proc/task_mmu.c SourceLine:1601 SourceSnippet:1600: out_put_mm:
1601: mmput(mm);
1602: out_put_task:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_get_next SourceFile:kernel/bpf/task_iter.c SourceLine:490 SourceSnippet: 489: if (mmap_read_lock_killable(curr_mm)) {
490: mmput(curr_mm);
491: goto finish;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_get_next SourceFile:kernel/bpf/task_iter.c SourceLine:522 SourceSnippet: 521: if (mmap_read_lock_killable(curr_mm)) {
522: mmput(curr_mm);
523: goto finish;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_get_next SourceFile:kernel/bpf/task_iter.c SourceLine:552 SourceSnippet: 551: mmap_read_unlock(curr_mm);
552: mmput(curr_mm);
553: goto next_task;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:task_vma_seq_stop SourceFile:kernel/bpf/task_iter.c SourceLine:648 SourceSnippet: 647: mmap_read_unlock(info->mm);
648: mmput(info->mm);
649: info->mm = NULL;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:trace_user_stack_print SourceFile:kernel/trace/trace_output.c SourceLine:1506 SourceSnippet:1505: if (mm)
1506: mmput(mm);
1507:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2768 SourceSnippet:2767: spin_unlock(&mmlist_lock);
2768: mmput(prev_mm);
2769: prev_mm = mm;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2772 SourceSnippet:2771: if (retval) {
2772: mmput(prev_mm);
2773: return retval;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2785 SourceSnippet:2784:
2785: mmput(prev_mm);
2786:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:uverbs_user_mmap_disassociate SourceFile:drivers/infiniband/core/uverbs_main.c SourceLine:831 SourceSnippet: 830: mmap_read_unlock(mm);
831: mmput(mm);
832: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:xacct_add_tsk SourceFile:kernel/tsacct.c SourceLine:104 SourceSnippet: 103: stats->hiwater_vm = get_mm_hiwater_vm(mm) * PAGE_SIZE / KB;
104: mmput(mm);
105: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:zap_pages SourceFile:kernel/bpf/arena.c SourceLine:839 SourceSnippet: 838: mmap_read_unlock(mm);
839: mmput(mm);
840:
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_mmput_1425 SourceFile:kernel/fork.c SourceLine:1218 SourceSnippet:1218: EXPORT_SYMBOL_GPL(mmput);
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_mmput SourceFile:kernel/fork.c SourceLine:1218 SourceSnippet:1218: EXPORT_SYMBOL_GPL(mmput);
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_mmput SourceFile:kernel/fork.c SourceLine:1218 SourceSnippet:1218: EXPORT_SYMBOL_GPL(mmput);
]] TruncatedOutput:false]
|
| 147/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 36250
output: 26
thoughts: 1422
Thoughts: **Analyzing a Kernel Memory Management Concurrency Issue**
Okay, here's the situation I'm looking at. I see a potential race condition in the kernel's memory management. It's focused on the interaction of tasks during a `clone` system call (specifically without `CLONE_VM`) and a process exit. The call stack looks like this: `kernel_clone` -> `copy_process` -> `copy_mm` -> `dup_mm`.
My initial thought is to trace the execution flow carefully. Task B appears to be executing `sys_clone` and, within that, calling `dup_mm`. In `copy_mm`, I see `current->mm` being used. Importantly, the code indicates `tsk` (the new child task) is getting its `mm` set through `dup_mm`. Task B is the 'current' task making the system call, with Task A is calling `mmput(mm)`.
The crucial detail is that both Task A and Task B seem to be working on the *same* `mm_struct`, which is where the problem starts. The prompt says that Task B calls `dup_mm` which does not use the CLONE_VM flag and Task A is calling `mmput(mm)` which triggers `__mmput(mm)`. I have to ask: How can this happen? The prompt is saying the `atomic_dec_and_test(&mm->mm_users)` succeeded. But *why*?
My thinking goes through a few possible scenarios. Could A and B be threads of the same process? If they were, and both *were* holding a reference, `mm->mm_users` would be at least 2. `mmput` should only decrement to 1, and `__mmput` wouldn't be called. So, something isn't adding up.
Did Task B *not* have a refcount? This makes no sense, because it is the current task that calls the clone system call! Could Task B have somehow dropped its refcount? Or did it never have one in the first place? And the system call's copy_mm routine states that if oldmm does not exist (`oldmm = current->mm`) then the process returns. That means Task B must have had a mm_struct.
Could Task B be a kernel thread? This is very quickly ruled out. Kernel threads don't execute `sys_clone`, and the check `if (!oldmm)` would fail as `oldmm` would be null if we had a kthread.
Was Task B killed? Would a signal like SIGKILL drop `mm_users`? No, SIGKILL doesn't. Or, did Task B itself call `exit_mm`? Also no, because the `if (!oldmm)` statement in copy_mm would have caused the copy_mm to return if Task B called `exit_mm`.
So, what are the requirements for `mm->mm_users` to drop to 0? The key seems to be figuring out how `mm` is managed. Remember the prompt: "Task B is executing sys_clone (without CLONE_VM, so it calls dup_mm(tsk, current->mm)), and Task A is exiting and calling mmput(mm) which triggers __mmput(mm) because atomic_dec_and_test(&mm->mm_users) succeeded. Both are operating on the exact same struct mm_struct.
How can Task A and Task B be concurrently in these states on the same mm_struct? Does Task B not hold an mm_users refcount, or how did mm->mm_users drop to 0? Is this data race benign or harmful, and why?"
This is a good point to start the thought process over. So how are mm_struct's created in Linux? The code mentions execve, fork without CLONE_VM, and clone with CLONE_VM, all incrementing or setting `mm_users`. How does a task even get a `current->mm`? It's essential to understand the initialization and lifetime management of these `mm_struct` structures. I need to understand all the points in the code where `current->mm` can be set, so I can try to understand how the mm_users can drop to zero, when the code in question states that they are both operating on the same `mm_struct`.
|
| 148/4 |
2026/09/23 15:54 |
tool |
grepper |
0m
Args: map[Expression:current->mm = PathPrefix:kernel/]
Results: map[Output:kernel/exit.c=584=static void exit_mm(void)
--
kernel/exit.c-610- local_irq_disable();
kernel/exit.c:611: current->mm = NULL;
kernel/exit.c-612- membarrier_update_current_mm(NULL);
--
kernel/sched/membarrier.c-111- * d: smp_mb()
kernel/sched/membarrier.c:112: * e: current->mm = NULL
kernel/sched/membarrier.c-113- * b: read rq->curr->mm == NULL
--
kernel/sched/membarrier.c-125- * d: smp_mb()
kernel/sched/membarrier.c:126: * e: current->mm = NULL
kernel/sched/membarrier.c-127- * b: read rq->curr->mm == NULL
kernel/sched/membarrier.c-128- * kthread_use_mm()
kernel/sched/membarrier.c:129: * f: current->mm = mm
kernel/sched/membarrier.c-130- * g: smp_mb()
]
|
| 149/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 38946
output: 18
thoughts: 29
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Kernel Memory Management Deep Dive**
Alright, I need to get to the bottom of how this memory mapping is being assigned. I'm going to leverage my deep understanding of the kernel's architecture to track this down. My first instinct is to dive into the core data structures and memory management paths. I'm thinking, let's start with a broad search. I'll need to look across the relevant kernel source code directories. Specifically, `fs/` (filesystem related code), `mm/` (memory management code, obviously), and other likely locations. The goal here is to pinpoint exactly where a `current->mm =` assignment is happening, or, if we are dealing with a different thread/task context, perhaps `tsk->mm =`. I'm expecting this to lead me right to the critical code responsible for initializing or changing a task's memory space, whether that's during process creation, context switching, or perhaps even in less common scenarios. The trick will be to filter the search results carefully to identify the _right_ assignments.
|
| 150/4 |
2026/09/23 15:54 |
tool |
grepper |
0m
Args: map[Expression:current->mm =]
Results: map[Output:Documentation/mm/active_mm.rst=9=helpers, which abstract this config option.
--
Documentation/mm/active_mm.rst-77-
Documentation/mm/active_mm.rst:78: if (current->mm == &init_mm)
Documentation/mm/active_mm.rst-79-
--
Documentation/translations/zh_CN/mm/active_mm.rst=13=Active MM
--
Documentation/translations/zh_CN/mm/active_mm.rst-75-
Documentation/translations/zh_CN/mm/active_mm.rst:76: if (current->mm == &init_mm)
Documentation/translations/zh_CN/mm/active_mm.rst-77-
--
arch/arc/mm/tlb.c=177=noinline void local_flush_tlb_mm(struct mm_struct *mm)
--
arch/arc/mm/tlb.c-195- destroy_context(mm);
arch/arc/mm/tlb.c:196: if (current->mm == mm)
arch/arc/mm/tlb.c-197- get_new_mmu_context(mm);
--
arch/arc/mm/tlb.c=394=static void create_tlb(struct vm_area_struct *vma, unsigned long vaddr, pte_t *ptep)
--
arch/arc/mm/tlb.c-401- /*
arch/arc/mm/tlb.c:402: * create_tlb() assumes that current->mm == vma->mm, since
arch/arc/mm/tlb.c-403- * -it ASID for TLB entry is fetched from MMU ASID reg (valid for curr)
--
arch/arm/mach-rpc/ecard.c=245=static int ecard_init_mm(void)
--
arch/arm/mach-rpc/ecard.c-252-
arch/arm/mach-rpc/ecard.c:253: current->mm = mm;
arch/arm/mach-rpc/ecard.c-254- current->active_mm = mm;
--
arch/loongarch/include/asm/mmu_context.h=141=drop_mmu_context(struct mm_struct *mm, unsigned int cpu)
--
arch/loongarch/include/asm/mmu_context.h-152-
arch/loongarch/include/asm/mmu_context.h:153: if (!current->mm || (current->mm == mm)) {
arch/loongarch/include/asm/mmu_context.h-154- get_new_mmu_context(mm, cpu, &need_flush);
--
arch/m68k/mm/mcfmmu.c=36=void __init paging_init(void)
--
arch/m68k/mm/mcfmmu.c-71-
arch/m68k/mm/mcfmmu.c:72: current->mm = NULL;
arch/m68k/mm/mcfmmu.c-73-}
--
arch/m68k/mm/sun3mmu.c=36=void __init paging_init(void)
--
arch/m68k/mm/sun3mmu.c-78-
arch/m68k/mm/sun3mmu.c:79: current->mm = NULL;
arch/m68k/mm/sun3mmu.c-80-}
--
arch/m68k/sun3/mmu_emu.c=355=int mmu_emu_handle_fault (unsigned long vaddr, int read_flag, int kernel_fault)
--
arch/m68k/sun3/mmu_emu.c-361-
arch/m68k/sun3/mmu_emu.c:362: if(current->mm == NULL) {
arch/m68k/sun3/mmu_emu.c-363- crp = swapper_pg_dir;
--
arch/microblaze/mm/fault.c=86=void do_page_fault(struct pt_regs *regs, unsigned long address,
--
arch/microblaze/mm/fault.c-113- /* faulthandler_disabled() in user mode is really bad,
arch/microblaze/mm/fault.c:114: as is current->mm == NULL. */
arch/microblaze/mm/fault.c-115- pr_emerg("Page fault in user mode with faulthandler_disabled(), mm = %p\n",
--
arch/nios2/mm/tlb.c=257=void flush_tlb_mm(struct mm_struct *mm)
arch/nios2/mm/tlb.c-258-{
arch/nios2/mm/tlb.c:259: if (current->mm == mm) {
arch/nios2/mm/tlb.c-260- unsigned long mmu_pid = get_pid_from_context(&mm->context);
--
arch/powerpc/mm/book3s64/hash_utils.c=1615=void demote_segment_4k(struct mm_struct *mm, unsigned long addr)
--
arch/powerpc/mm/book3s64/hash_utils.c-1622-#endif
arch/powerpc/mm/book3s64/hash_utils.c:1623: if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {
arch/powerpc/mm/book3s64/hash_utils.c-1624-
--
arch/powerpc/mm/book3s64/hash_utils.c=1718=int hash_page_mm(struct mm_struct *mm, unsigned long ea,
--
arch/powerpc/mm/book3s64/hash_utils.c-1852-#endif
arch/powerpc/mm/book3s64/hash_utils.c:1853: if (current->mm == mm)
arch/powerpc/mm/book3s64/hash_utils.c-1854- check_paca_psize(ea, mm, psize, user_region);
--
arch/powerpc/mm/book3s64/hash_utils.c-1898-
arch/powerpc/mm/book3s64/hash_utils.c:1899: if (current->mm == mm)
arch/powerpc/mm/book3s64/hash_utils.c-1900- check_paca_psize(ea, mm, psize, user_region);
--
arch/powerpc/mm/book3s64/radix_tlb.c=661=static void exit_lazy_flush_tlb(struct mm_struct *mm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-672- */
arch/powerpc/mm/book3s64/radix_tlb.c:673: if (current->mm == mm)
arch/powerpc/mm/book3s64/radix_tlb.c-674- goto out;
--
arch/powerpc/mm/book3s64/radix_tlb.c=761=static enum tlb_flush_type flush_type_needed(struct mm_struct *mm, bool fullmm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-800- */
arch/powerpc/mm/book3s64/radix_tlb.c:801: if (atomic_read(&mm->mm_users) <= 1 && current->mm == mm) {
arch/powerpc/mm/book3s64/radix_tlb.c-802- exit_flush_lazy_tlbs(mm);
--
arch/powerpc/mm/book3s64/radix_tlb.c-818- exit_flush_lazy_tlbs(mm);
arch/powerpc/mm/book3s64/radix_tlb.c:819: if (current->mm == mm)
arch/powerpc/mm/book3s64/radix_tlb.c-820- return FLUSH_TYPE_LOCAL;
--
arch/sparc/include/asm/mman.h=14=static inline void ipi_set_tstate_mcde(void *arg)
--
arch/sparc/include/asm/mman.h-21- */
arch/sparc/include/asm/mman.h:22: if (current->mm == mm) {
arch/sparc/include/asm/mman.h-23- struct pt_regs *regs;
--
arch/um/kernel/skas/process.c=45=unsigned long current_stub_stack(void)
arch/um/kernel/skas/process.c-46-{
arch/um/kernel/skas/process.c:47: if (current->mm == NULL)
arch/um/kernel/skas/process.c-48- return 0;
--
arch/um/kernel/skas/process.c=53=struct mm_id *current_mm_id(void)
arch/um/kernel/skas/process.c-54-{
arch/um/kernel/skas/process.c:55: if (current->mm == NULL)
arch/um/kernel/skas/process.c-56- return NULL;
--
arch/um/kernel/skas/process.c=61=void current_mm_sync(void)
arch/um/kernel/skas/process.c-62-{
arch/um/kernel/skas/process.c:63: if (current->mm == NULL)
arch/um/kernel/skas/process.c-64- return;
--
arch/um/kernel/trap.c=308=unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user,
--
arch/um/kernel/trap.c-344- }
arch/um/kernel/trap.c:345: else if (current->mm == NULL) {
arch/um/kernel/trap.c-346- show_regs(container_of(regs, struct pt_regs, regs));
--
arch/x86/kvm/x86.c=10014=void kvm_arch_destroy_vm(struct kvm *kvm)
arch/x86/kvm/x86.c-10015-{
arch/x86/kvm/x86.c:10016: if (current->mm == kvm->mm) {
arch/x86/kvm/x86.c-10017- /*
--
arch/x86/mm/tlb.c=1640=STATIC_NOPV void native_flush_tlb_local(void)
--
arch/x86/mm/tlb.c-1650-
arch/x86/mm/tlb.c:1651: /* If current->mm == NULL then the read_cr3() "borrows" an mm */
arch/x86/mm/tlb.c-1652- native_write_cr3(__native_read_cr3());
--
drivers/vfio/vfio_iommu_type1.c=3138=static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
--
drivers/vfio/vfio_iommu_type1.c-3145- struct vfio_dma *dma;
drivers/vfio/vfio_iommu_type1.c:3146: bool kthread = current->mm == NULL;
drivers/vfio/vfio_iommu_type1.c-3147- size_t offset;
--
include/trace/events/kmem.h=427=TRACE_EVENT(rss_stat,
--
include/trace/events/kmem.h-448- */
include/trace/events/kmem.h:449: __entry->curr = current->mm == mm && !(current->flags & PF_KTHREAD);
include/trace/events/kmem.h-450- __entry->member = member;
--
kernel/exit.c=584=static void exit_mm(void)
--
kernel/exit.c-610- local_irq_disable();
kernel/exit.c:611: current->mm = NULL;
kernel/exit.c-612- membarrier_update_current_mm(NULL);
--
kernel/sched/membarrier.c-111- * d: smp_mb()
kernel/sched/membarrier.c:112: * e: current->mm = NULL
kernel/sched/membarrier.c-113- * b: read rq->curr->mm == NULL
--
kernel/sched/membarrier.c-125- * d: smp_mb()
kernel/sched/membarrier.c:126: * e: current->mm = NULL
kernel/sched/membarrier.c-127- * b: read rq->curr->mm == NULL
kernel/sched/membarrier.c-128- * kthread_use_mm()
kernel/sched/membarrier.c:129: * f: current->mm = mm
kernel/sched/membarrier.c-130- * g: smp_mb()
--
mm/madvise.c=1889=static inline unsigned long get_untagged_addr(struct mm_struct *mm,
--
mm/madvise.c-1891-{
mm/madvise.c:1892: return current->mm == mm ? untagged_addr(start) :
mm/madvise.c-1893- untagged_addr_remote(mm, start);
--
tools/testing/vma/tests/mmap.c=3=static bool test_mmap_region_basic(void)
--
tools/testing/vma/tests/mmap.c-11-
tools/testing/vma/tests/mmap.c:12: current->mm = &mm;
tools/testing/vma/tests/mmap.c-13-
]
|
| 151/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 42897
output: 36
thoughts: 39
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating `kthread_use_mm`**
Okay, hold on a second. Something's nagging at me. I'm seeing something here, right... `kthread_use_mm`. Hang on, that function name is familiar. I need to get a clear picture of what's going on with it. Where is `kthread_use_mm` actually defined? I need to track down its implementation. Let me dive in and check its definition. I need to understand its behavior thoroughly within the broader context of the kernel's memory management.
|
| 152/4 |
2026/09/23 15:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/kthread.c Name:kthread_use_mm]
Results: map[SourceCode:1611: /**
1612: * kthread_use_mm - make the calling kthread operate on an address space
1613: * @mm: address space to operate on
1614: */
1615: void kthread_use_mm(struct mm_struct *mm)
1616: {
1617: struct mm_struct *active_mm;
1618: struct task_struct *tsk = current;
1619:
1620: WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1621: WARN_ON_ONCE(tsk->mm);
1622:
1623: /*
1624: * It is possible for mm to be the same as tsk->active_mm, but
1625: * we must still mmgrab(mm) and mmdrop_lazy_tlb(active_mm),
1626: * because these references are not equivalent.
1627: */
1628: mmgrab(mm);
1629:
1630: task_lock(tsk);
1631: /* Hold off tlb flush IPIs while switching mm's */
1632: local_irq_disable();
1633: active_mm = tsk->active_mm;
1634: tsk->active_mm = mm;
1635: tsk->mm = mm;
1636: membarrier_update_current_mm(mm);
1637: switch_mm_irqs_off(active_mm, mm, tsk);
1638: local_irq_enable();
1639: task_unlock(tsk);
1640: #ifdef finish_arch_post_lock_switch
1641: finish_arch_post_lock_switch();
1642: #endif
1643:
1644: /*
1645: * When a kthread starts operating on an address space, the loop
1646: * in membarrier_{private,global}_expedited() may not observe
1647: * that tsk->mm, and not issue an IPI. Membarrier requires a
1648: * memory barrier after storing to tsk->mm, before accessing
1649: * user-space memory. A full memory barrier for membarrier
1650: * {PRIVATE,GLOBAL}_EXPEDITED is implicitly provided by
1651: * mmdrop_lazy_tlb().
1652: */
1653: mmdrop_lazy_tlb(active_mm);
1654: }
SourceFile:kernel/kthread.c]
|
| 153/4 |
2026/09/23 15:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 43822
output: 30
thoughts: 387
Thoughts: **My Current Thinking**
Hold on a second! I need to double-check something. That `kthread_use_mm` function... I need to remember, does it use `mmget` (which deals with `mm_users`) or `mmgrab` (which handles `mm_count`)? Let me see... yes, here it is, line 1628... it calls `mmgrab(mm)`. So, it's `mmgrab`, not `mmget`. Okay, got it.
But now I'm thinking about Task B... it seems to be doing something with `dup_mm` (a `memcpy`), then `copy_mm`, `copy_process`, `kernel_clone`, and finally, `sys_clone`. The question then becomes, can a kernel thread actually execute `sys_clone`? Wait, hold on, can it? Or an io_uring worker, or even a usermode helper?
Let me zero in on io_uring. Does an io_uring thread call `sys_clone`, or does it go through `kernel_clone`? I know io_uring doesn't directly call `sys_clone`, but... hmm, then what?
No, `sys_clone` is a system call, so a kernel thread shouldn't be able to invoke it. And an io_uring worker is in kernel space. Wait... a userspace thread... no... why would Task A ever drop `mm_users` to zero? That's really weird.
Okay, time to start digging. I need to find information about this KCSAN report. Let me search the git history and see if there are any related issues. Maybe syzkaller reports or the LKML have something. Let's see... what were the exact keywords? Something like `KCSAN`, `__mmput`, `dup_mm`, and `mmlist`. I should also search for "KCSAN," "mmlist," and "dup_mm" in the git commit log. Let's see what turns up.
|
| 154/4 |
2026/09/23 15:54 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[mmlist KCSAN]]
Results:
|
| 155/4 |
2026/09/23 15:55 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 44691
output: 36
thoughts: 25
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing Kernel Memory Safety with Git Logs**
Alright, I need to dig into potential memory safety issues within the kernel, specifically targeting potential KCSAN (Kernel Concurrency Sanitizer) findings. My initial hunch is that these issues might manifest themselves around `fork.c` and functions related to memory management duplication, like `dup_mm`.
Therefore, my first step is to use `git log` to search for commits that mention "KCSAN" in conjunction with either "fork.c" or "dup_mm." This is a targeted approach; I'm not just looking for any KCSAN reports, but rather those that might pinpoint issues relating to concurrent access during process creation or memory space duplication, which are often sources of subtle, hard-to-find bugs. I expect that a search for those terms will reveal relevant commits. This focused approach will hopefully save me considerable time, as opposed to a broader search.
|
| 156/4 |
2026/09/23 15:55 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[KCSAN] PathPrefix:kernel/fork.c]
Results: map[Output:d9c857aee2eb pid_namespace: avoid optimization of accesses to ->child_reaper
cda099b37d71 fork: Annotate a data race in vm_area_dup()
c17d1a3a8ee4 fork: annotate data race in copy_process()
d5f177d35c24 rcu-tasks: Add an RCU Tasks Trace to simplify protection of tracing hooks
]
|
| 157/4 |
2026/09/23 15:55 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 45078
output: 26
thoughts: 17
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and rendered in the first person:
**Analyzing Commit cda099b37d71**
Alright, let's dive into commit `cda099b37d71`. My initial approach will be to assess its potential impact, given its likely position in the history. First, I want to confirm my understanding of the commit message. I'll mentally reconstruct the surrounding context – what branches were active, what other work was in progress around that timeframe. Based on the hash alone, it's clear this requires focused attention. My brain's already firing up those pattern-matching processes, cross-referencing this with any knowledge of recent bug reports or performance issues. I'll be looking for red flags in terms of scope; did it introduce any fundamental changes, or is it isolated? I will pull up the diff and begin scanning it to determine its area of effect. I'll expect to see this commit has affected which modules. I am beginning to formulate a mental hypothesis about the commit's intent and consequences. My experience tells me which areas are most likely to be problematic and this will be my focus for a deeper inspection.
|
| 158/4 |
2026/09/23 15:55 |
tool |
git-show |
0m
Args:
Results: map[Output:commit cda099b37d7165fc73a63961739acf026444cde2
Author: Qian Cai <cai@lca.pw>
Date: Wed Feb 19 11:00:54 2020 -0800
fork: Annotate a data race in vm_area_dup()
struct vm_area_struct could be accessed concurrently as noticed by
KCSAN,
write to 0xffff9cf8bba08ad8 of 8 bytes by task 14263 on cpu 35:
vma_interval_tree_insert+0x101/0x150:
rb_insert_augmented_cached at include/linux/rbtree_augmented.h:58
(inlined by) vma_interval_tree_insert at mm/interval_tree.c:23
__vma_link_file+0x6e/0xe0
__vma_link_file at mm/mmap.c:629
vma_link+0xa2/0x120
mmap_region+0x753/0xb90
do_mmap+0x45c/0x710
vm_mmap_pgoff+0xc0/0x130
ksys_mmap_pgoff+0x1d1/0x300
__x64_sys_mmap+0x33/0x40
do_syscall_64+0x91/0xc44
entry_SYSCALL_64_after_hwframe+0x49/0xbe
read to 0xffff9cf8bba08a80 of 200 bytes by task 14262 on cpu 122:
vm_area_dup+0x6a/0xe0
vm_area_dup at kernel/fork.c:362
__split_vma+0x72/0x2a0
__split_vma at mm/mmap.c:2661
split_vma+0x5a/0x80
mprotect_fixup+0x368/0x3f0
do_mprotect_pkey+0x263/0x420
__x64_sys_mprotect+0x51/0x70
do_syscall_64+0x91/0xc44
entry_SYSCALL_64_after_hwframe+0x49/0xbe
vm_area_dup() blindly copies all fields of original VMA to the new one.
This includes coping vm_area_struct::shared.rb which is normally
protected by i_mmap_lock. But this is fine because the read value will
be overwritten on the following __vma_link_file() under proper
protection. Thus, mark it as an intentional data race and insert a few
assertions for the fields that should not be modified concurrently.
Signed-off-by: Qian Cai <cai@lca.pw>
Signed-off-by: Paul E. McKenney <paulmck@kernel.org>
diff --git a/kernel/fork.c b/kernel/fork.c
index 142b23645d82..bba10fbcdce7 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -359,7 +359,13 @@ struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
if (new) {
- *new = *orig;
+ ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
+ ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
+ /*
+ * orig->shared.rb may be modified concurrently, but the clone
+ * will be reinitialized.
+ */
+ *new = data_race(*orig);
INIT_LIST_HEAD(&new->anon_vma_chain);
new->vm_next = new->vm_prev = NULL;
}
]
|
| 159/4 |
2026/09/23 15:55 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 46463
output: 26
thoughts: 57
Thoughts: Okay, let's dive into this. Here's my take on those thoughts, as if they're my own:
**Investigating a Potential Data Race in Kernel Forking**
Alright, that commit by `Qian Cai` on the `vm_area_dup()` function caught my eye. A data race annotation? Interesting. I need to understand the implications of this. Let's start with commit `c17d1a3a8ee4` -- that seems like the logical starting point for understanding that specific race condition, if there is a race condition. I'll need to look at the surrounding code to contextualize this.
From there, I should probably expand my search. I should see if there are other commits by `Qian Cai` that touch related areas, particularly around memory management and process creation, as these are often hot spots for concurrency issues. Then, given the nature of the function, I’ll also want to review commits related to KCSAN that might flag race conditions within `kernel/fork.c`. Forking a process and duplicating memory regions are classic areas for potential concurrency bugs, so it's a good place to start the investigation. Time to go digging!
|
| 160/4 |
2026/09/23 15:55 |
tool |
git-show |
0m
Args:
Results: map[Output:commit c17d1a3a8ee4dac7539d5c976b45d9300f6f10bc
Author: Weilong Chen <chenweilong@huawei.com>
Date: Tue Jun 23 12:12:40 2020 +0800
fork: annotate data race in copy_process()
KCSAN reported data race reading and writing nr_threads and max_threads.
The data race is intentional and benign. This is obvious from the comment
above it and based on general consensus when discussing this issue. So
there's no need for any heavy atomic or *_ONCE() machinery here.
In accordance with the newly introduced data_race() annotation consensus,
mark the offending line with data_race(). Here it's actually useful not
just to silence KCSAN but to also clearly communicate that the race is
intentional. This is especially helpful since nr_threads is otherwise
protected by tasklist_lock.
BUG: KCSAN: data-race in copy_process / copy_process
write to 0xffffffff86205cf8 of 4 bytes by task 14779 on cpu 1:
copy_process+0x2eba/0x3c40 kernel/fork.c:2273
_do_fork+0xfe/0x7a0 kernel/fork.c:2421
__do_sys_clone kernel/fork.c:2576 [inline]
__se_sys_clone kernel/fork.c:2557 [inline]
__x64_sys_clone+0x130/0x170 kernel/fork.c:2557
do_syscall_64+0xcc/0x3a0 arch/x86/entry/common.c:294
entry_SYSCALL_64_after_hwframe+0x44/0xa9
read to 0xffffffff86205cf8 of 4 bytes by task 6944 on cpu 0:
copy_process+0x94d/0x3c40 kernel/fork.c:1954
_do_fork+0xfe/0x7a0 kernel/fork.c:2421
__do_sys_clone kernel/fork.c:2576 [inline]
__se_sys_clone kernel/fork.c:2557 [inline]
__x64_sys_clone+0x130/0x170 kernel/fork.c:2557
do_syscall_64+0xcc/0x3a0 arch/x86/entry/common.c:294
entry_SYSCALL_64_after_hwframe+0x44/0xa9
Link: https://groups.google.com/forum/#!msg/syzkaller-upstream-mo
deration/thvp7AHs5Ew/aPdYLXfYBQAJ
Reported-by: syzbot+52fced2d288f8ecd2b20@syzkaller.appspotmail.com
Signed-off-by: Zefan Li <lizefan@huawei.com>
Signed-off-by: Weilong Chen <chenweilong@huawei.com>
Acked-by: Christian Brauner <christian.brauner@ubuntu.com>
Cc: Qian Cai <cai@lca.pw>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Christian Brauner <christian.brauner@ubuntu.com>
Cc: Marco Elver <elver@google.com>
[christian.brauner@ubuntu.com: rewrite commit message]
Link: https://lore.kernel.org/r/20200623041240.154294-1-chenweilong@huawei.com
Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com>
diff --git a/kernel/fork.c b/kernel/fork.c
index 142b23645d82..efc5493203ae 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -1977,7 +1977,7 @@ static __latent_entropy struct task_struct *copy_process(
* to stop root fork bombs.
*/
retval = -EAGAIN;
- if (nr_threads >= max_threads)
+ if (data_race(nr_threads >= max_threads))
goto bad_fork_cleanup_count;
delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
]
|
| 161/4 |
2026/09/23 15:55 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 47997
output: 25
thoughts: 30
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Investigating Potential Data Races: A Focused Git Log Dive**
Right, so we've got a suspected data race or KCSAN issue potentially related to "dup_mm" or "mmlist." My immediate thought is to zero in on relevant commits efficiently. A broad search of the entire codebase is going to be noisy and time-consuming. Instead, I'll leverage `git log` to hunt down the smoking guns. The keywords "dup_mm" and "mmlist" are my initial anchors, clearly suggesting areas of memory management or process duplication. We're looking for commits that touch those areas and also mention "KCSAN" or "data race." This combination of keywords should drastically narrow the search scope. We'll be able to sift through the commits and examine their diffs with more clarity. This will help focus debugging efforts in the right locations. From here, we will identify potential candidates and look deeper at the code in the mentioned commits.
|
| 162/4 |
2026/09/23 15:55 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[dup_mm]]
Results: map[Output:a44a3f175eae RDMA/uverbs: Fix mmap_lock/disassociation_lock circular dependency
2f252a7a6c90 kselftest: alloc_tag: add kselftest for ioctl interface
6b1c66c9cca9 exec_state: relocate dumpable information
c03ce4173c7b fs: aio: set VMA_DONTCOPY_BIT in mmap to fix NULL-pointer-dereference error
43873af772f8 mm: change dup_mmap() recovery
bed76bec3111 mm: relocate the page table ceiling and floor definitions
7db0787000d4 mm: cleanup vma_iter_bulk_alloc
7370f8e1b3a8 mm: use vma_start_write_killable() in dup_mmap()
1367da7eb875 mm: swap: check for stable address space before operating on the VMA
14967a9c7d24 mm/hugetlb: fix copy_hugetlb_page_range() to use ->pt_share_count
26a8f57760c1 mm: move dup_mmap() to mm
6c36ac1e124f mm: establish mm/vma_exec.c for shared exec/mm VMA functionality
fddc45026311 drm/amdkfd: Fix Circular Locking Dependency in 'svm_range_cpu_invalidate_pagetables'
64c37e134b12 kernel: be more careful about dup_mmap() failures and uprobe registering
8ac662f5da19 fork: avoid inappropriate uprobe access to invalid mm
985da552a98e fork: only invoke khugepaged, ksm hooks if no error
f64e67e5d3a4 fork: do not invoke uffd on fork if error occurs
7911b650a070 um: remove LDT support
529ce23a764f mm: switch mm->get_unmapped_area() to a flag
35e351780fa9 fork: defer linking file vma until vma is fully initialized
]
|
| 163/4 |
2026/09/23 15:55 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 48827
output: 24
thoughts: 22
Thoughts: Here's my thought process, as requested:
**Investigating Memory Management in the Kernel**
Okay, time to dig into some kernel memory management. Specifically, I need to understand what's going on with that `mmlist`. My first instinct is to see how `list_del(&mm->mmlist)` is being used, or where `mmlist` itself is referenced, because those are going to be key pieces of information to unravel. Given the scope of this kind of investigation, a `git log` search is the obvious starting point. I can quickly filter by those specific strings to find instances of their usage across commits, which should provide a good historical view of changes and a starting point to see what code is important. Once I have the commit history and context of those references, I can move on to the code itself and work my way outward.
|
| 164/4 |
2026/09/23 15:55 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[mmlist]]
Results: map[Output:3c37cac718fa mm/ksm: avoid missing ksmd wakeups in ksm_enter
b70705744370 mm: extract mm_prepare_for_swap_entries() helper
1367da7eb875 mm: swap: check for stable address space before operating on the VMA
8ac7c87acdca MIPS: vmlinux.lds.S: add missing PAGE_ALIGNED_DATA() section
dd862deb151a mm: swapoff: remove too limiting SWAP_UNUSE_MAX_TRIES
b56a2d8af914 mm: rid swapoff of quadratic complexity
7496fea9a6bf ksm: fix conflict between mmput and scan_get_next_rmap_item
2022b4d18a49 mm: fix swapoff hang after page migration and fork
172703b08cd0 mm: delete non-atomic mm counter implementation
cb5f7b9a4796 tmpfs: make shmem_unuse more preemptible
]
|
| 165/4 |
2026/09/23 15:56 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 49318
output: 25
thoughts: 17
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and rendered in the first person:
**Diving into Commit History**
Right, let's take a look at commit `1367da7eb875`. It's a bit vague, just a commit hash, so the immediate mental checklist starts: *what was the context around this commit? What project, what timeframe, what likely changes were made?* I'll need to remember the project context to assess the implications of the commit. *Was there a particular bug fix or feature implementation going on at that time? Was this a critical change or a small refactor?*
The hash alone doesn't give me much, so I'm already mentally preparing to jump into my version control system, whatever it may be. I'm going to want a clear view of the diff. I'm not looking for a line-by-line breakdown just yet, but first, I will examine the general overview of the changes made, so I need to check the metadata associated with the commit. *What's the commit message? Does it give a clear and concise description of the intention? What about any related issue numbers or pull request links?*
I'll be looking for red flags. Anything that seems overly complicated, overly aggressive, or lacking proper testing will jump out immediately. I'll need to assess the scope. *Are we talking about a simple modification to a single function or a massive architectural overhaul? Is there potential for regression based on its history and context?*
Based on what I see in the initial overview, I'll then zero in on the specific files and sections that pique my interest. I need to understand the impact of these changes. *Are there dependencies that need to be considered? Is there any potential for conflict with other parts of the code base? Were the changes tested appropriately? What are the implications in production?*
Finally, I'll move into a deep dive if the initial overview warrants it. *I want to identify potential bottlenecks, inefficiencies, or security vulnerabilities.* Ultimately, I need to understand the intent of the change and if the change delivered on that intent.
|
| 166/4 |
2026/09/23 15:56 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 1367da7eb875d01102d2ed18654b24d261ff5393
Author: Charan Teja Kalla <charan.kalla@oss.qualcomm.com>
Date: Wed Sep 24 23:41:38 2025 +0530
mm: swap: check for stable address space before operating on the VMA
It is possible to hit a zero entry while traversing the vmas in unuse_mm()
called from swapoff path and accessing it causes the OOPS:
Unable to handle kernel NULL pointer dereference at virtual address
0000000000000446--> Loading the memory from offset 0x40 on the
XA_ZERO_ENTRY as address.
Mem abort info:
ESR = 0x0000000096000005
EC = 0x25: DABT (current EL), IL = 32 bits
SET = 0, FnV = 0
EA = 0, S1PTW = 0
FSC = 0x05: level 1 translation fault
The issue is manifested from the below race between the fork() on a
process and swapoff:
fork(dup_mmap()) swapoff(unuse_mm)
--------------- -----------------
1) Identical mtree is built using
__mt_dup().
2) copy_pte_range()-->
copy_nonpresent_pte():
The dst mm is added into the
mmlist to be visible to the
swapoff operation.
3) Fatal signal is sent to the parent
process(which is the current during the
fork) thus skip the duplication of the
vmas and mark the vma range with
XA_ZERO_ENTRY as a marker for this process
that helps during exit_mmap().
4) swapoff is tried on the
'mm' added to the 'mmlist' as
part of the 2.
5) unuse_mm(), that iterates
through the vma's of this 'mm'
will hit the non-NULL zero entry
and operating on this zero entry
as a vma is resulting into the
oops.
The proper fix would be around not exposing this partially-valid tree to
others when droping the mmap lock, which is being solved with [1]. A
simpler solution would be checking for MMF_UNSTABLE, as it is set if
mm_struct is not fully initialized in dup_mmap().
Thanks to Liam/Lorenzo/David for all the suggestions in fixing this
issue.
Link: https://lkml.kernel.org/r/20250924181138.1762750-1-charan.kalla@oss.qualcomm.com
Link: https://lore.kernel.org/all/20250815191031.3769540-1-Liam.Howlett@oracle.com/ [1]
Fixes: d24062914837 ("fork: use __mt_dup() to duplicate maple tree in dup_mmap()")
Signed-off-by: Charan Teja Kalla <charan.kalla@oss.qualcomm.com>
Suggested-by: David Hildenbrand <david@redhat.com>
Cc: Baoquan He <bhe@redhat.com>
Cc: Barry Song <baohua@kernel.org>
Cc: Chris Li <chrisl@kernel.org>
Cc: Kairui Song <kasong@tencent.com>
Cc: Kemeng Shi <shikemeng@huaweicloud.com>
Cc: Liam Howlett <liam.howlett@oracle.com>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Cc: Nhat Pham <nphamcs@gmail.com>
Cc: Peng Zhang <zhangpeng.00@bytedance.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 890b410d77b6..10760240a3a2 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2389,6 +2389,8 @@ static int unuse_mm(struct mm_struct *mm, unsigned int type)
VMA_ITERATOR(vmi, mm, 0);
mmap_read_lock(mm);
+ if (check_stable_address_space(mm))
+ goto unlock;
for_each_vma(vmi, vma) {
if (vma->anon_vma && !is_vm_hugetlb_page(vma)) {
ret = unuse_vma(vma, type);
@@ -2398,6 +2400,7 @@ static int unuse_mm(struct mm_struct *mm, unsigned int type)
cond_resched();
}
+unlock:
mmap_read_unlock(mm);
return ret;
}
]
|
| 167/4 |
2026/09/23 15:56 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 51172
output: 25
thoughts: 98
Thoughts: **My Investigation Begins: Memory Management & Maple Trees**
Okay, so we're circling a problem related to maple trees and some sort of swapoff scenario. My initial instinct is to dig into the commit history for relevant memory management interactions. I'm thinking, let's start with a focused search using specific kernel functions that signal potential issues. I'll zero in on commit messages containing `atomic_dec_and_test(&mm->mm_users)` or `__mmput`. I'll also include related functions like `dup_mm`, `memcpy`, `copy_mm`, and `CLONE_VM` since they all touch on how virtual memory areas (VMAs) are copied or released.
But hold on, let's broaden the net slightly for now. Before getting hyper-specific, I want to take a wider view. I'll broaden my search parameters to include commits mentioning `__mmput` in the commit message. This should help to give me an idea of the landscape related to this function. This approach gives me a broader base of references, before I drill down, to find the answer.
|
| 168/4 |
2026/09/23 15:56 |
tool |
git-log |
0m
Args: map[Count:30 MessageRegexps:[__mmput]]
Results: map[Output:bde023808364 futex: Fix race on the initial mm->futex.phash.ref allocation
4c92afb4c143 drm/xe/vf: Add drm_dev guards when detaching CCS read/write buffers
1ae415a6eefe drm/xe/vf: Add drm_dev guards when detaching CCS read/write buffers
38205ecbe6b6 exec: free the old mm outside the exec locks
ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
fda4d71651f7 powerpc/pgtable-frag: Fix bad page state in pte_frag_destroy
8821e857759b xdp: produce a warning when calculated tailroom is negative
4ddfab5436b6 KVM: arm64: Reschedule as needed when destroying the stage-2 page-tables
00c14a09a70e hfs/hfsplus: prevent getting negative values of offset/length
d9b05321e21e futex: Move futex_hash_free() back to __mmput()
e9abe311f356 KVM: arm64: Reschedule as needed when destroying the stage-2 page-tables
dde30854bddf mm/debug_vm_pgtable: clear page table entries at destroy_args()
e703b7e24750 futex: Move futex cleanup to __mmdrop()
ee40c9920ac2 mm: fix copy_vma() error handling for hugetlb mappings
7bcfeddb36b7 drm/xe: Fix an out-of-bounds shift when invalidating TLB
b88f48f86500 drm/xe: Fix an out-of-bounds shift when invalidating TLB
dc84bc2aba85 x86/mm/pat: Fix VM_PAT handling when fork() fails in copy_page_range()
7cd1f5f77925 LoongArch: Add architecture specific huge_pte_clear()
66edc3a5894c mm: page_alloc: move mlocked flag clearance into free_pages_prepare()
818f916e3a07 mm: swap: prevent possible data-race in __try_to_reclaim_swap
6d27a31ef195 uprobes: introduce the global struct vm_special_mapping xol_mapping
08e28de1160a uprobes: use vm_special_mapping close() functionality
237f3cf13b20 xsk: validate user input for XDP_{UMEM|COMPLETION}_FILL_RING
04c35ab3bdae x86/mm/pat: fix VM_PAT handling in COW mappings
661779e1fcaf netlink: Fix kernel-infoleak-after-free in __skb_datagram_iter
5a08d0065a91 ipv6: add debug checks in fib6_info_release()
187da0f8250a hugetlb: fix null-ptr-deref in hugetlb_vma_lock_write
ca71fe1ad922 mm, pcp: avoid to drain PCP when process exit
20045f0155ab powerpc/64s/radix: Don't warn on copros in radix__tlb_flush()
804ca14d04df iommufd: Do not access the area pointer after unlocking
]
|
| 169/4 |
2026/09/23 15:56 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 52395
output: 25
thoughts: 33
Thoughts: Okay, let's dive into commit `38205ecbe6b6` and see what's going on.
**Diving into Commit 38205ecbe6b6: "exec: free the old mm outside the exec locks"**
Right, so the commit message immediately suggests a concurrency concern related to memory management (`mm`) during `exec` operations. I need to understand *why* freeing the old memory map outside of the `exec` locks is an improvement. The existing locking scheme must have presented some kind of bottleneck or potential for deadlock, or maybe a simpler, more robust approach was discovered.
My intuition says this probably involves some subtle interaction between process memory space changes and the execution of the new program. I'll be looking for where the `mm` (memory management) structure is freed in relation to the locking around `exec`. Specifically, what *locks* are we talking about? `exec` usually involves several subsystems that need synchronization (e.g. process control, VFS, signal handling, etc.). The commit probably addresses a critical section or contention that was exposed during the old approach. I'll need to trace back from that point.
I need to see what the *previous* code did, what *locks* were involved in the previous approach, and then the *reasoning* in the commit message that explains why this change improves things. I'm expecting to see a change that either increases performance by reducing contention, enhances the robustness of the `exec` implementation, or perhaps both. A brief scan should be enough to start to form a complete understanding. Time to roll up my sleeves and dive in.
|
| 170/4 |
2026/09/23 15:56 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 38205ecbe6b6dc47968ad4e9c978e2117720969e
Author: Christian Brauner <brauner@kernel.org>
Date: Fri May 22 16:03:30 2026 +0200
exec: free the old mm outside the exec locks
exec_mmap() installs the new mm and then tears the old one down while
still holding exec_update_lock for writing -- and with cred_guard_mutex
held all the way to setup_new_exec():
setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm);
mm_update_next_owner(old_mm);
mmput(old_mm);
Neither lock is needed for this. exec_update_lock only exists to make the
mm swap atomic with the later commit_creds(), so that permission-checking
readers (proc, ptrace, the futex robust list, perf, kcmp, mm_access())
never observe the new mm together with the old credentials. Those readers
all operate on task->mm, i.e. the new mm after the swap; none looks at the
detached old mm, its ->owner or signal->maxrss. cred_guard_mutex guards
credential calculation and is equally irrelevant here.
The cost is real: __mmput() runs exit_mmap() over the entire old address
space and can block in exit_aio() waiting for in-flight AIO, all while
holding exec_update_lock for writing and cred_guard_mutex. For execve() of
a large process this blocks ptrace_attach() and every exec_update_lock
reader for the duration of the teardown.
Stash the old mm in bprm->old_mm and release it from setup_new_exec()
after both locks are dropped. setup_new_exec() still runs before
setup_arg_pages() and the segment mappings, so the old address space is
freed before the new one is populated and peak memory is unchanged. The
ordering constraints are kept: old_mm's mmap_lock is still dropped in
exec_mmap() before mm_update_next_owner() (required since commit
31a78f23bac0 ("mm owner: fix race between swapoff and exit")), and
mm_update_next_owner() still precedes mmput(); both run in the execing
task's context, as mm_update_next_owner() requires.
If exec swaps the mm but fails before setup_new_exec() runs the old mm
would leak, so add a backstop in free_bprm(). The lazy-tlb case
(old_mm == NULL, e.g. kernel_execve()) has no address space to
free and is left in exec_mmap().
Link: https://patch.msgid.link/20260522-work-exit_mm-v1-1-bd32d5a560bb@kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
diff --git a/fs/exec.c b/fs/exec.c
index 9e7f25e2cd41..824b46c069ae 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -836,16 +836,18 @@ EXPORT_SYMBOL(read_code);
/*
* Maps the mm_struct mm into the current task struct.
* On success, this function returns with exec_update_lock
- * held for writing.
+ * held for writing. The replaced address space is stashed in
+ * bprm->old_mm for setup_new_exec() to release outside the lock.
*/
-static int exec_mmap(struct mm_struct *mm, struct user_namespace *user_ns)
+static int exec_mmap(struct linux_binprm *bprm)
{
struct task_exec_state *exec_state __free(put_task_exec_state) = NULL;
+ struct mm_struct *mm = bprm->mm;
struct task_struct *tsk;
struct mm_struct *old_mm, *active_mm;
int ret;
- exec_state = alloc_task_exec_state(user_ns);
+ exec_state = alloc_task_exec_state(bprm->user_ns);
if (!exec_state)
return -ENOMEM;
@@ -898,15 +900,22 @@ static int exec_mmap(struct mm_struct *mm, struct user_namespace *user_ns)
if (old_mm) {
mmap_read_unlock(old_mm);
BUG_ON(active_mm != old_mm);
- setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm);
- mm_update_next_owner(old_mm);
- mmput(old_mm);
+ /* Defer teardown to setup_new_exec(), outside the exec locks. */
+ bprm->old_mm = old_mm;
return 0;
}
mmdrop_lazy_tlb(active_mm);
return 0;
}
+/* Release the address space replaced by exec, outside the exec locks. */
+static void exec_mm_put_old(struct mm_struct *old_mm)
+{
+ setmax_mm_hiwater_rss(¤t->signal->maxrss, old_mm);
+ mm_update_next_owner(old_mm);
+ mmput(old_mm);
+}
+
static int de_thread(struct task_struct *tsk)
{
struct signal_struct *sig = tsk->signal;
@@ -1155,7 +1164,7 @@ int begin_new_exec(struct linux_binprm * bprm)
* Release all of the old mmap stuff
*/
acct_arg_size(bprm, 0);
- retval = exec_mmap(bprm->mm, bprm->user_ns);
+ retval = exec_mmap(bprm);
if (retval)
goto out;
@@ -1338,6 +1347,12 @@ void setup_new_exec(struct linux_binprm * bprm)
me->mm->task_size = TASK_SIZE;
up_write(&me->signal->exec_update_lock);
mutex_unlock(&me->signal->cred_guard_mutex);
+
+ /* The exec locks are dropped: release the old address space now. */
+ if (bprm->old_mm) {
+ exec_mm_put_old(bprm->old_mm);
+ bprm->old_mm = NULL;
+ }
}
EXPORT_SYMBOL(setup_new_exec);
@@ -1394,6 +1409,9 @@ static void free_bprm(struct linux_binprm *bprm)
mutex_unlock(¤t->signal->cred_guard_mutex);
abort_creds(bprm->cred);
}
+ /* exec swapped the mm but failed before setup_new_exec() freed it */
+ if (bprm->old_mm)
+ exec_mm_put_old(bprm->old_mm);
do_close_execat(bprm->file);
if (bprm->executable)
fput(bprm->executable);
diff --git a/include/linux/binfmts.h b/include/linux/binfmts.h
index a8379f4eee61..2c77e383e737 100644
--- a/include/linux/binfmts.h
+++ b/include/linux/binfmts.h
@@ -25,6 +25,7 @@ struct linux_binprm {
struct page *page[MAX_ARG_PAGES];
#endif
struct mm_struct *mm;
+ struct mm_struct *old_mm; /* replaced address space, freed by setup_new_exec() */
/* user_ns published to task->exec_state at execve, narrowed by would_dump(). */
struct user_namespace *user_ns;
unsigned long p; /* current top of mem */
]
|
| 171/4 |
2026/09/23 15:56 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 54899
output: 20
thoughts: 1909
Thoughts: **Analyzing a Kernel Data Race: A Deep Dive**
Okay, let's break this down. This looks like a classic kernel data race scenario. My immediate thought is to check the commit history around May 22, 2026, for related fixes, but first, I need a clear understanding of the situation. The prompt outlines a data race detected by KCSAN within the Linux kernel, specifically involving the `mm_struct`.
I'm focusing on these questions:
1. How are Task A and Task B concurrently accessing the same `mm_struct` in these states?
2. Does Task B actually maintain a valid `mm_users` refcount, or how did `mm->mm_users` get to zero?
3. Is this race benign or a real problem, and what's the reason?
My immediate train of thought: Let's consider how `mm->mm_users` could hit zero. Task A is exiting via the usual path: `exit_mm`, `mmput`, and ultimately `__mmput`. This sequence usually implies that the last user of the `mm_struct` is going away. Now, Task B is in `sys_clone` without `CLONE_VM`, within `dup_mm`, which is a copy. But when `copy_process` starts, Task B is running.
My mind immediately starts forming questions: why are Task A and Task B sharing `mm`? If they were created with `CLONE_VM`, they share `mm`. But why would `CLONE_VM` be relevant if Task B is calling `sys_clone` *without* `CLONE_VM`? If Task A and Task B were two threads of the same process, it's possible for Task B to call `fork()` or `clone()` without `CLONE_VM`. This is the most likely scenario now.
So, when `fork()` (or `clone` without `CLONE_VM`) happens, `dup_mm` gets called. Task B is now duplicating `current->mm` for the child. This is confirmed. Now, while Task B is in `dup_mm`, what's Task A doing? Wait. If Task A and Task B are both threads of the same process, then they are sharing mm! Wait, is Task A exiting because it received a fatal signal? Indeed, `syscall_exit_to_user_mode`, `do_group_exit`, `do_exit`, and all of the mm related calls confirm a normal exit. When a fatal signal hits a process, it calls `do_group_exit`, or `complete_signal` sends SIGKILL to all threads in the thread group! But Task B is still alive in the kernel, and has *not* called `exit_mm`! If Task B is still alive, why did the `mmput` in Task A decrement the counter and lead to `__mmput(mm)`?
This is where the race condition starts to crystalize: Task B *should* hold a reference. Why did `atomic_dec_and_test(&mm->mm_users)` return true in Task A, resulting in `__mmput`? My mind now zeroes in on this refcount: How could it have been one when Task A called `mmput`?
Did Task B ever *have* a refcount? Let's trace it back to the clone operation. If `CLONE_VM` was set, we would have seen `mmget(oldmm)` and an increment. If `CLONE_VM` was set, Task A's `mmput` wouldn't have resulted in `__mmput`, as the reference would not be zero.
Could it have been decremented by Task B already? No! Task B is in `dup_mm`. Did Task B call anything else?
Could Task B be some other kind of kernel thread? Could it be an io_uring worker? kthread? vfork? core dump? ptrace? Let's go to the source code and grep for `kthread_use_mm` or `use_mm` or `unuse_mm`. Does io_uring use these? My next step is to research.
|
| 172/4 |
2026/09/23 15:56 |
tool |
grepper |
0m
Args: map[Expression:kthread_use_mm]
Results: map[Output:arch/arm64/kernel/efi.c=169=void arch_efi_call_virt_setup(void)
--
arch/arm64/kernel/efi.c-181- migrate_disable();
arch/arm64/kernel/efi.c:182: kthread_use_mm(&efi_mm);
arch/arm64/kernel/efi.c-183- } else {
--
arch/powerpc/include/asm/book3s/64/kup.h=205=extern u64 __ro_after_init default_iamr;
--
arch/powerpc/include/asm/book3s/64/kup.h-209-
arch/powerpc/include/asm/book3s/64/kup.h:210:/* usage of kthread_use_mm() should inherit the
arch/powerpc/include/asm/book3s/64/kup.h-211- * AMR value of the operating address space. But, the AMR value is
--
arch/powerpc/mm/book3s64/hash_utils.c=2030=static void hash_preload(struct mm_struct *mm, pte_t *ptep, unsigned long ea,
--
arch/powerpc/mm/book3s64/hash_utils.c-2080- * mm_is_thread_local test and update, to prevent preempt running the
arch/powerpc/mm/book3s64/hash_utils.c:2081: * mm on another CPU (XXX: this may be racy vs kthread_use_mm).
arch/powerpc/mm/book3s64/hash_utils.c-2082- */
--
arch/powerpc/mm/book3s64/radix_tlb.c=661=static void exit_lazy_flush_tlb(struct mm_struct *mm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-667- * A kthread could have done a mmget_not_zero() after the flushing CPU
arch/powerpc/mm/book3s64/radix_tlb.c:668: * checked mm_cpumask, and be in the process of kthread_use_mm when
arch/powerpc/mm/book3s64/radix_tlb.c-669- * interrupted here. In that case, current->mm will be set to mm,
arch/powerpc/mm/book3s64/radix_tlb.c:670: * because kthread_use_mm() setting ->mm and switching to the mm is
arch/powerpc/mm/book3s64/radix_tlb.c-671- * done with interrupts off.
--
arch/powerpc/platforms/book3s/vas-api.c=148=void vas_update_csb(struct coprocessor_request_block *crb,
--
arch/powerpc/platforms/book3s/vas-api.c-200-
arch/powerpc/platforms/book3s/vas-api.c:201: kthread_use_mm(task_ref->mm);
arch/powerpc/platforms/book3s/vas-api.c-202- rc = copy_to_user(csb_addr, &csb, sizeof(csb));
--
arch/x86/kvm/xen.c=1922=static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)
--
arch/x86/kvm/xen.c-1938-
arch/x86/kvm/xen.c:1939: kthread_use_mm(kvm->mm);
arch/x86/kvm/xen.c-1940- mm_borrowed = true;
--
drivers/dma/idxd/cdev.c=733=int idxd_copy_cr(struct idxd_wq *wq, ioasid_t pasid, unsigned long addr,
--
drivers/dma/idxd/cdev.c-754- */
drivers/dma/idxd/cdev.c:755: kthread_use_mm(mm);
drivers/dma/idxd/cdev.c-756- left = copy_to_user((void __user *)addr + status_size, cr + status_size,
--
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h=282=int amdgpu_amdkfd_reset_mes_queue(struct amdgpu_device *adev,
--
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h-301- } else if (current->flags & PF_KTHREAD) { \
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h:302: kthread_use_mm(mmptr); \
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h-303- valid = !get_user((dst), (wptr)); \
--
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c=3536=static void copy_context_work_handler(struct work_struct *work)
--
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c-3555-
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:3556: kthread_use_mm(mm);
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c-3557- for (i = 0; i < p->n_pdds; i++) {
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c=100=static void kfd_sdma_activity_worker(struct work_struct *work)
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c-203-
drivers/gpu/drm/amd/amdkfd/kfd_process.c:204: kthread_use_mm(mm);
drivers/gpu/drm/amd/amdkfd/kfd_process.c-205-
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c=2366=static void send_exception_work_handler(struct work_struct *work)
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c-2386-
drivers/gpu/drm/amd/amdkfd/kfd_process.c:2387: kthread_use_mm(mm);
drivers/gpu/drm/amd/amdkfd/kfd_process.c-2388-
--
drivers/gpu/drm/i915/selftests/i915_selftest.c=222=static int __run_selftests(const char *name,
--
drivers/gpu/drm/i915/selftests/i915_selftest.c-254- if (mm) {
drivers/gpu/drm/i915/selftests/i915_selftest.c:255: kthread_use_mm(mm);
drivers/gpu/drm/i915/selftests/i915_selftest.c-256- if (unlikely(!current->mm)) {
--
drivers/gpu/drm/xe/xe_sync.c=76=static void user_fence_worker(struct work_struct *w)
--
drivers/gpu/drm/xe/xe_sync.c-81- if (mmget_not_zero(ufence->mm)) {
drivers/gpu/drm/xe/xe_sync.c:82: kthread_use_mm(ufence->mm);
drivers/gpu/drm/xe/xe_sync.c-83- if (copy_to_user(ufence->addr, &ufence->value, sizeof(ufence->value)))
--
drivers/gpu/drm/xe/xe_vm.c=4568=void xe_vm_snapshot_capture_delayed(struct xe_vm_snapshot *snap)
--
drivers/gpu/drm/xe/xe_vm.c-4592-
drivers/gpu/drm/xe/xe_vm.c:4593: kthread_use_mm(snap->snap[i].mm);
drivers/gpu/drm/xe/xe_vm.c-4594- if (!copy_from_user(snap->snap[i].data, userptr, snap->snap[i].len))
--
drivers/iommu/iommufd/pages.c=2350=int iopt_pages_rw_access(struct iopt_pages *pages, unsigned long start_byte,
--
drivers/iommu/iommufd/pages.c-2392- length, flags);
drivers/iommu/iommufd/pages.c:2393: kthread_use_mm(pages->source_mm);
drivers/iommu/iommufd/pages.c-2394- }
--
drivers/usb/gadget/function/f_fs.c=871=static void ffs_user_copy_worker(struct work_struct *work)
--
drivers/usb/gadget/function/f_fs.c-879- if (mmget_not_zero(io_data->mm)) {
drivers/usb/gadget/function/f_fs.c:880: kthread_use_mm(io_data->mm);
drivers/usb/gadget/function/f_fs.c-881- ret = ffs_copy_to_iter(io_data->buf, ret, &io_data->data);
--
drivers/usb/gadget/legacy/inode.c=467=static void ep_user_copy_worker(struct work_struct *work)
--
drivers/usb/gadget/legacy/inode.c-474- if (mmget_not_zero(mm)) {
drivers/usb/gadget/legacy/inode.c:475: kthread_use_mm(mm);
drivers/usb/gadget/legacy/inode.c-476- ret = copy_to_iter(priv->buf, priv->actual, &priv->to);
--
drivers/vdpa/vdpa_sim/vdpa_sim.c=175=static void vdpasim_work_fn(struct kthread_work *work)
--
drivers/vdpa/vdpa_sim/vdpa_sim.c-182- return;
drivers/vdpa/vdpa_sim/vdpa_sim.c:183: kthread_use_mm(mm);
drivers/vdpa/vdpa_sim/vdpa_sim.c-184- }
--
drivers/vfio/vfio_iommu_type1.c=3138=static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
--
drivers/vfio/vfio_iommu_type1.c-3163- if (kthread)
drivers/vfio/vfio_iommu_type1.c:3164: kthread_use_mm(mm);
drivers/vfio/vfio_iommu_type1.c-3165- else if (current->mm != mm)
--
drivers/vhost/vhost.c=412=static int vhost_run_work_kthread_list(void *data)
--
drivers/vhost/vhost.c-418-
drivers/vhost/vhost.c:419: kthread_use_mm(dev->mm);
drivers/vhost/vhost.c-420-
--
include/linux/iommufd.h=79=enum {
--
include/linux/iommufd.h-81- IOMMUFD_ACCESS_RW_WRITE = 1 << 0,
include/linux/iommufd.h:82: /* Set if the caller is in a kthread then rw will use kthread_use_mm() */
include/linux/iommufd.h-83- IOMMUFD_ACCESS_RW_KTHREAD = 1 << 1,
--
include/linux/kthread.h=280=void kthread_destroy_worker(struct kthread_worker *worker);
include/linux/kthread.h-281-
include/linux/kthread.h:282:void kthread_use_mm(struct mm_struct *mm);
include/linux/kthread.h-283-void kthread_unuse_mm(struct mm_struct *mm);
--
include/trace/events/kmem.h=427=TRACE_EVENT(rss_stat,
--
include/trace/events/kmem.h-445- * Since kthreads (PF_KTHREAD) have no mm_struct of their own
include/trace/events/kmem.h:446: * but can borrow one via kthread_use_mm(), we must filter them
include/trace/events/kmem.h-447- * out to avoid incorrectly attributing the RSS update to them.
--
kernel/fork.c=1358=struct file *get_task_exe_file(struct task_struct *task)
--
kernel/fork.c-1378- * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
kernel/fork.c:1379: * this kernel workthread has transiently adopted a user mm with kthread_use_mm,
kernel/fork.c-1380- * to do its AIO) is not set and if so returns a reference to it, after
--
kernel/kthread.c=1609=EXPORT_SYMBOL(kthread_destroy_worker);
--
kernel/kthread.c-1611-/**
kernel/kthread.c:1612: * kthread_use_mm - make the calling kthread operate on an address space
kernel/kthread.c-1613- * @mm: address space to operate on
kernel/kthread.c-1614- */
kernel/kthread.c:1615:void kthread_use_mm(struct mm_struct *mm)
kernel/kthread.c-1616-{
--
kernel/kthread.c-1654-}
kernel/kthread.c:1655:EXPORT_SYMBOL_GPL(kthread_use_mm);
kernel/kthread.c-1656-
kernel/kthread.c-1657-/**
kernel/kthread.c:1658: * kthread_unuse_mm - reverse the effect of kthread_use_mm()
kernel/kthread.c-1659- * @mm: address space to operate on
--
kernel/sched/membarrier.c-127- * b: read rq->curr->mm == NULL
kernel/sched/membarrier.c:128: * kthread_use_mm()
kernel/sched/membarrier.c-129- * f: current->mm = mm
--
lib/kunit/user_alloc.c=25=int kunit_attach_mm(void)
--
lib/kunit/user_alloc.c-46- /* Attach the mm. It will be cleaned up when the process dies. */
lib/kunit/user_alloc.c:47: kthread_use_mm(mm);
lib/kunit/user_alloc.c-48-
--
mm/oom_kill.c=122=static bool oom_cpuset_eligible(struct task_struct *tsk, struct oom_control *oc)
--
mm/oom_kill.c-129- * The process p may have detached its own ->mm while exiting or through
mm/oom_kill.c:130: * kthread_use_mm(), but one or more of its subthreads may still have a valid
mm/oom_kill.c-131- * pointer. Return p, or any of its subthreads with a valid ->mm, with
--
mm/oom_kill.c=912=static void __oom_kill_process(struct task_struct *victim, const char *message)
--
mm/oom_kill.c-977- /*
mm/oom_kill.c:978: * No kthread_use_mm() user needs to read from the userspace so
mm/oom_kill.c-979- * we are ok to reap it.
--
rust/kernel/task.rs=35=macro_rules! current {
--
rust/kernel/task.rs-43- // `begin_new_exec()` is responsible for safety.
rust/kernel/task.rs:44: // * Rust abstractions for things such as a `kthread_use_mm()` scope must require the
rust/kernel/task.rs-45- // closure to be `Send`, so the `NotThreadSafe` field of `CurrentTask` ensures that the
--
rust/kernel/task.rs=107=unsafe impl Sync for Task {}
--
rust/kernel/task.rs-127-///
rust/kernel/task.rs:128:/// * Calling `kthread_use_mm()` creates a new context, and `kthread_unuse_mm()` returns to the
rust/kernel/task.rs-129-/// old context.
rust/kernel/task.rs-130-///
rust/kernel/task.rs:131:/// This means that a `CurrentTask` obtained before a `kthread_use_mm()` call may be used again
rust/kernel/task.rs-132-/// once `kthread_unuse_mm()` is called, but it must not be used between these two calls.
rust/kernel/task.rs:133:/// Conversely, a `CurrentTask` obtained between a `kthread_use_mm()`/`kthread_unuse_mm()` pair
rust/kernel/task.rs-134-/// must not be used after `kthread_unuse_mm()`.
--
rust/kernel/task.rs=278= pub fn mm(&self) -> Option<&MmWithUser> {
--
rust/kernel/task.rs-290- //
rust/kernel/task.rs:291: // This is safe even if `kthread_use_mm()`/`kthread_unuse_mm()` are used. There are two
rust/kernel/task.rs-292- // relevant cases:
rust/kernel/task.rs:293: // * If the `&CurrentTask` was created before `kthread_use_mm()`, then it cannot be
rust/kernel/task.rs:294: // accessed during the `kthread_use_mm()`/`kthread_unuse_mm()` scope due to the
rust/kernel/task.rs-295- // `NotThreadSafe` field of `CurrentTask`.
rust/kernel/task.rs:296: // * If the `&CurrentTask` was created within a `kthread_use_mm()`/`kthread_unuse_mm()`
rust/kernel/task.rs-297- // scope, then the `&CurrentTask` cannot escape that scope, so the returned `&MmWithUser`
]
|
| 173/4 |
2026/09/23 15:57 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 62571
output: 34
thoughts: 3379
Thoughts: **Analyzing a Data Race in the Linux Kernel: A Deep Dive**
Okay, let's break this down. KCSAN has flagged a data race. The core issue seems to be a conflict between Task A exiting (calling `mmput`) and Task B cloning a process via `sys_clone` (specifically, calling `dup_mm`). I need to understand how they can be simultaneously operating on the same `mm_struct` in these conflicting states.
First, I need to get the basics straight: io_uring doesn't seem directly involved in thread creation. We're dealing with `PF_IO_WORKER` threads, which are created via `copy_process` and `sys_clone`. But, Task B *is* calling `sys_clone` so it must be a user-space process or thread, not an I/O worker.
The crucial question is about `mm_users`. Task A's `mmput` succeeded because `mm->mm_users` dropped to zero. This means `mm->mm_users` was exactly 1. Task A decremented to 0. But *simultaneously*, Task B is in `dup_mm` which copies the `mm_struct`!
The problem is the *refcount* on the `mm_struct`. When Task A calls `mmput`, and `atomic_dec_and_test` returns true, it's implying that `mm->mm_users` was *one*. If Task B were holding a refcount, it should have been at least two.
So, the key questions are: Does Task B have an `mm_users` refcount? If it *doesn't*, how is that possible when it is *actively* copying the memory layout, and if it *does*, how did it drop to 0?
I ruled out `exit_mm()` because it clears `current->mm` *before* `mmput`, meaning that Task B's `current->mm` would be NULL, and it wouldn't be in `dup_mm`.
I know Task B is not a child of vfork. If it were, it would *have* the `mm_users` refcount initially and would get incremented by `mmget`. The vfork scenario leads to an `execve` which would *drop* the reference, which doesn't seem to fit this case.
I ruled out the scenario where Task A and B were the same task (A's and B's pids are different), or that A and B were created by `kthread_use_mm`.
I tried to verify that the decrementing isn't caused by a common `mmput`.
So, where else could the refcount be getting decremented? It doesn't seem to be in `copy_process`.
Now, the potential culprits are other callers to `mmput`: `exit_mm`, `exec_mmap`, failures during `dup_mm` or `copy_process`, and the interesting one: remote access helpers via `get_task_mm(task)` *which may drop the refcount*. This sounds suspicious.
So, could Task B, for some reason, *not* be holding a normal `mm_users` refcount, or, did something, *else* cause the initial drop to 0? And could that something be the `get_task_mm` call? This is the most likely candidate.
|
| 174/4 |
2026/09/23 15:57 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:get_task_mm]
Results: map[SourceCode:1374: /**
1375: * get_task_mm - acquire a reference to the task's mm
1376: * @task: The task.
1377: *
1378: * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1379: * this kernel workthread has transiently adopted a user mm with kthread_use_mm,
1380: * to do its AIO) is not set and if so returns a reference to it, after
1381: * bumping up the use count. User must release the mm via mmput()
1382: * after use. Typically used by /proc and ptrace.
1383: */
1384: struct mm_struct *get_task_mm(struct task_struct *task)
1385: {
1386: struct mm_struct *mm;
1387:
1388: if (task->flags & PF_KTHREAD)
1389: return NULL;
1390:
1391: task_lock(task);
1392: mm = task->mm;
1393: if (mm)
1394: mmget(mm);
1395: task_unlock(task);
1396: return mm;
1397: }
SourceFile:kernel/fork.c]
|
| 175/4 |
2026/09/23 15:57 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 67098
output: 37
thoughts: 426
Thoughts: **Analyzing Potential Concurrency Issues with Memory Management**
Okay, so `get_task_mm` increments the mm refcount, and the caller decrements it with `mmput`. Seems straightforward, right? Paired operations (+1, -1). But, hold on a second. What if we're not dealing with two threads, but rather something else entirely?
Wait! I need to consider all the ways a shared `mm_struct` could be accessed concurrently. How could Task A and Task B possibly be in these states on the *same* `mm_struct`? Something isn't adding up. How can `mm->mm_users` drop to zero? Is this a data race? And if so, is it harmless, or could it lead to problems? Let's dig deeper.
Wait, wait... could this involve `sys_clone`? Specifically, what if Task B was created with `CLONE_VM`? If Task B was created with `CLONE_VM`, but *not* `CLONE_THREAD`, things get really interesting. Or even *with* `CLONE_THREAD`... I need to think this through carefully.
If `CLONE_VM` is used, why would `mm->mm_users` be equal to 1 when Task A exits?! Can `mm->mm_users` *ever* be 1 with two active tasks? Something about this scenario is feeling off.
Wait! This reminds me of `vfork`! What precisely does `vfork()` do again? Let's break it down. Process A calls `vfork()`. Child B runs. While Child B runs, Parent A is blocked, waiting for Child B! `vfork_done` is the key. Parent A sleeps in `wait_for_vfork_done()`! Then, Child B does something... what if Child B exits or execs? Ah, if Child B calls `execve()` - then parent A wakes up! Wait, Parent A is waiting for child B. And what if Parent A is killed by SIGKILL while in `wait_for_vfork_done`?
Wait! What *does* happen if parent A gets SIGKILL while waiting? I need to check how `wait_for_vfork_done` handles this. Let's look at the code. Time to check `wait_for_vfork_done`!
|
| 176/4 |
2026/09/23 15:57 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:wait_for_vfork_done]
Results: map[SourceCode:1445: static int wait_for_vfork_done(struct task_struct *child,
1446: struct completion *vfork)
1447: {
1448: unsigned int state = TASK_KILLABLE|TASK_FREEZABLE;
1449: int killed;
1450:
1451: cgroup_enter_frozen();
1452: killed = wait_for_completion_state(vfork, state);
1453: cgroup_leave_frozen(false);
1454:
1455: if (killed) {
1456: task_lock(child);
1457: child->vfork_done = NULL;
1458: task_unlock(child);
1459: }
1460:
1461: put_task_struct(child);
1462: return killed;
1463: }
SourceFile:kernel/fork.c]
|
| 177/4 |
2026/09/23 15:57 |
llm |
codeexpert-compressor |
0m
Model:
Reply: ### Workspace and Investigation Summary
#### 1. Context and Problem Statement
- **KCSAN Data Race Report Under Investigation**:
- **Task A (task 21217 on cpu 1)**:
```c
__mmput (list_del(&mm->mmlist) at kernel/fork.c:1198)
mmput
exit_mm
do_exit
do_group_exit
get_signal
syscall_exit_to_user_mode
```
- **Task B (task 3876 on cpu 0)**:
```c
dup_mm (memcpy(mm, oldmm, sizeof(*mm)) at kernel/fork.c:1537)
copy_mm
copy_process
kernel_clone
sys_clone
```
- **Core Questions**:
1. How can Task A and Task B concurrently be in these states operating on the *exact same* `struct mm_struct`?
2. Does Task B not hold an `mm_users` refcount, or how did `mm->mm_users` drop to 0 allowing `__mmput()` to run?
3. Is this data race benign or harmful, and why?
---
#### 2. Approaches Tried So Far and Results
- **Examined `kernel/fork.c:copy_mm()`**:
- `oldmm = current->mm; if (!oldmm) return 0;`
- If `clone_flags & CLONE_VM`: calls `mmget(oldmm); mm = oldmm;`
- Else: calls `mm = dup_mm(tsk, current->mm);`
- Shows Task B is calling `dup_mm(tsk, current->mm)` with `oldmm == current->mm`.
- **Examined `kernel/fork.c:dup_mm()`**:
- `mm = allocate_mm(); memcpy(mm, oldmm, sizeof(*mm));` (line 1537 - race report location).
- Note: `dup_mm` does *not* take an additional refcount on `oldmm` or hold locks across `memcpy(mm, oldmm, sizeof(*mm))` against `__mmput(oldmm)`.
- **Examined `kernel/fork.c:__mmput()`**:
- `VM_BUG_ON(atomic_read(&mm->mm_users));`
- Modifies/cleans up `mm`, including `list_del(&mm->mmlist)` under `mmlist_lock` (line 1198 - race report location).
- Frees/tears down page tables, vmas, exe_file, etc.
- **Examined `kernel/exit.c:exit_mm()`**:
- `current->mm = NULL;` under `task_lock` / irq disabled.
- Calls `mmput(mm);` (which tests `atomic_dec_and_test(&mm->mm_users)`).
- **Examined `kernel/exit.c:do_group_exit()` and `kernel/signal.c:zap_other_threads()`**:
- Fatal signal delivery leads to `do_group_exit() -> zap_other_threads(current) -> sigaddset(SIGKILL) / signal_wake_up()`.
- **Examined `kernel/fork.c:copy_process()`**:
- Early check:
```c
spin_lock_irq(¤t->sighand->siglock);
...
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
if (task_sigpending(current))
goto fork_out;
```
- Later, after duplicating various structures (fs, files, signal), it calls `copy_mm(clone_flags, p)` before taking `tasklist_lock`.
- Later, under `current->sighand->siglock` (around line 2495):
```c
if (fatal_signal_pending(current)) {
retval = -EINTR;
goto bad_fork_core_free;
}
```
- **Git log investigations**:
- Searched git log for `dup_mm`, `memcpy`, `mm_users`, `mmlist`, `KCSAN` data races in `kernel/fork.c`.
- Reviewed commit `cda099b37d71` (`vm_area_dup` data race) and `c17d1a3a8ee4` (`copy_process` nr_threads data race). No direct patch found for this exact `dup_mm`/`__mmput` trace under those regexes.
- **Reference search for `mmput`**:
- Listed call sites across the kernel to see where `mm_users` decrements occur.
---
#### 3. Hypotheses, Theories, and Active Lines of Investigation
##### Hypothesis 1: Two sibling threads in a multi-threaded process where one exits while the other forks
- Suppose Process P has threads T1 (Task A) and T2 (Task B) sharing the same `mm` (`CLONE_VM`).
- Initially, `mm->mm_users == 2`.
- Why would `mm->mm_users` drop to 0 if Task B is still alive?
- If Task B is alive and running `sys_clone`, Task B's own reference is counted in `mm->mm_users`.
- If Task B holds 1 ref and Task A holds 1 ref, Task A exiting only drops `mm_users` to 1.
- Unless Task B dropped its ref? But a userspace task's `current->mm` holds a ref on `mm_users` until `exit_mm()` or `execve()`.
- Could another thread have already exited, or did an asynchronous/external drop occur?
##### Hypothesis 2: Fatal Signal / Group Exit racing with fork
- In a multithreaded process, or if Task B received a fatal signal:
- Does a fatal signal cause `exit_mm` in other threads?
- If there are only threads A and B sharing `mm`:
- For `atomic_dec_and_test(&mm->mm_users)` to succeed in Task A, `mm_users` MUST drop from 1 to 0!
- That means at the time Task A calls `mmput(mm)`, `mm->mm_users` was 1.
- How could `mm->mm_users` be 1 when Task B is still executing `sys_clone` and has `current->mm == mm`?
##### Hypothesis 3: How could `mm->mm_users == 1` while Task B is in `copy_process`?
Possibilities:
1. **Task B is NOT a thread sharing `mm` with Task A, but rather...**:
- But the prompt states: *"Task B is executing sys_clone (without CLONE_VM, so it calls dup_mm(tsk, current->mm)), and Task A is exiting and calling mmput(mm)... Both are operating on the exact same struct mm_struct."*
- And: *"How can Task A and Task B be concurrently in these states on the same mm_struct? Does Task B not hold an mm_users refcount, or how did mm->mm_users drop to 0?"*
2. **Did Task B borrow `mm` or is Task B in a special context?**:
- What if Task B is a vfork child? Or did `kthread_use_mm` happen? (Prompt says Task B executes `sys_clone`, which is userspace syscall).
3. **Did Task B drop its `mm_users`?**:
- Where can a task's `mm_users` be decremented without clearing `current->mm`?
- Look closely at `kernel/fork.c`, `kernel/exit.c`, `fs/exec.c`, `mm/oom_kill.c`, or `zap_other_threads`.
4. **Did Task A and Task B share `mm` via something other than `CLONE_VM` refcount? Or did someone do an extra `mmput`?**:
- Or what if Task A was the *last* thread holding `mm_users`, and Task B... wait! Could Task B be doing `sys_clone` on behalf of something else, or did Task B fork before Task A did something?
- Wait, what about `clone(CLONE_VM)` child that doesn't increment `mm_users`? No, `CLONE_VM` does `mmget(oldmm)`.
- What about `vfork`? In `vfork()`, parent is blocked until child execs or exits.
- What if Task B is exiting or being killed concurrently?
- Wait: could Task B's `mm` have been released by `mm_release()`?
- Let's check `mm_release()`! When is `mm_release()` called?
- `mm_release` is called in `do_exit()` before `exit_mm()`, and in `exec_mm_release()`.
- What if Task B is NOT a separate thread from Task A? Could Task A and Task B be two threads, where thread C also existed?
- If thread count was 2, how did `mm_users` hit 0 on Task A if Task B was alive?
- Wait! Could `mm_users` be decremented by something else, or could Task B have had its `mm` detached?
- Or did Task B call `sys_clone` while being killed? Does being killed decrement `mm_users`? No.
- What if Task B is the child of a clone? No, Task B is executing `sys_clone`.
- Let's check if there is a known Linux kernel bug or syzbot / KCSAN report with these exact traces!
---
#### 4. Critical Files and Functions to Inspect Next
- Search lore.kernel.org / git log / syzkaller reports for:
- `dup_mm` AND `__mmput`
- `list_del(&mm->mmlist)` AND `memcpy(mm, oldmm`
- KCSAN reports involving `dup_mm` and `__mmput`
- `kernel/fork.c`:
- Lines 1185–1218 (`__mmput`, `mmput`)
- Lines 1517–1566 (`dup_mm`)
- Lines 1568–1603 (`copy_mm`)
- Check how `oldmm` is protected in `dup_mm` during `copy_process`. Is `mmap_read_lock(oldmm)` taken?
- Notice: In `dup_mm`:
- Line 1537: `memcpy(mm, oldmm, sizeof(*mm));`
- Line 1543: `err = dup_mmap(mm, oldmm);`
- Where is `oldmm->mmap_lock` acquired? In `dup_mmap()`!
- In `dup_mmap(mm, oldmm)`: `mmap_write_lock_killable(oldmm)` or `mmap_read_lock(oldmm)`?
- But `memcpy` at line 1537 happens *before* `dup_mmap()`!
- Does `dup_mm` hold ANY lock on `oldmm` at line 1537? No!
- Why would `__mmput(oldmm)` be running concurrently with `dup_mm(tsk, oldmm)`?
- Need to understand how `oldmm->mm_users` reached 0 while Task B is in `dup_mm(tsk, oldmm)`.
- Is `Task B->mm` holding an `mm_users` count?
- If Task B is a normal thread, it holds `mm_users == 1` for itself.
- If Task A also holds `mm_users == 1`, total `mm_users >= 2`.
- How could `mm->mm_users` drop to 0?
- Could `core_dump` / `coredump` / `zap_threads` / `ptrace` / `io_uring` / `kthread` be involved?
- Or did Task B clone with `CLONE_VM` earlier without something?
- Or did an asynchronous `mmput` happen?
- Or is Task B in `io_uring` or `usermode_helper`?
#### 5. Repetitive Patterns / Cautionary Notes
- Avoid broad `git-log` searches across the whole repo without path prefixes or specific commits; they time out.
- Do not make assumptions about how `mm_users` reached 0; systematically verify in kernel code or search syzkaller/lore archives via grepper if present in tree or git log.
- `set-results` must be called exactly once before the final reply when ready.
Tokens:
input: 43630
output: 2960
thoughts: 0
|
| 178/4 |
2026/09/23 15:57 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21841
output: 34
thoughts: 0
|
| 179/4 |
2026/09/23 15:57 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1440 LineCount:80]
Results: map[Contents:1440: complete(vfork);
1441: }
1442: task_unlock(tsk);
1443: }
1444:
1445: static int wait_for_vfork_done(struct task_struct *child,
1446: struct completion *vfork)
1447: {
1448: unsigned int state = TASK_KILLABLE|TASK_FREEZABLE;
1449: int killed;
1450:
1451: cgroup_enter_frozen();
1452: killed = wait_for_completion_state(vfork, state);
1453: cgroup_leave_frozen(false);
1454:
1455: if (killed) {
1456: task_lock(child);
1457: child->vfork_done = NULL;
1458: task_unlock(child);
1459: }
1460:
1461: put_task_struct(child);
1462: return killed;
1463: }
1464:
1465: /* Please note the differences between mmput and mm_release.
1466: * mmput is called whenever we stop holding onto a mm_struct,
1467: * error success whatever.
1468: *
1469: * mm_release is called after a mm_struct has been removed
1470: * from the current process.
1471: *
1472: * This difference is important for error handling, when we
1473: * only half set up a mm_struct for a new process and need to restore
1474: * the old one. Because we mmput the new mm_struct before
1475: * restoring the old one. . .
1476: * Eric Biederman 10 January 1998
1477: */
1478: static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1479: {
1480: uprobe_free_utask(tsk);
1481:
1482: /* Get rid of any cached register state */
1483: deactivate_mm(tsk, mm);
1484:
1485: /*
1486: * Signal userspace if we're not exiting with a core dump
1487: * because we want to leave the value intact for debugging
1488: * purposes.
1489: */
1490: if (tsk->clear_child_tid) {
1491: if (atomic_read(&mm->mm_users) > 1) {
1492: /*
1493: * We don't check the error code - if userspace has
1494: * not set up a proper pointer then tough luck.
1495: */
1496: put_user(0, tsk->clear_child_tid);
1497: do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1498: 1, NULL, NULL, 0, 0);
1499: }
1500: tsk->clear_child_tid = NULL;
1501: }
1502:
1503: /*
1504: * All done, finally we can wake up parent and return this mm to him.
1505: * Also kthread_stop() uses this completion for synchronization.
1506: */
1507: if (tsk->vfork_done)
1508: complete_vfork_done(tsk);
1509: }
1510:
1511: void mm_exit_exec_release(struct task_struct *tsk, struct mm_struct *mm)
1512: {
1513: futex_exit_exec_release(tsk);
1514: mm_release(tsk, mm);
1515: }
1516:
1517: /**
1518: * dup_mm() - duplicates an existing mm structure
1519: * @tsk: the task_struct with which the new mm will be associated.
]
|
| 180/4 |
2026/09/23 15:57 |
llm |
codeexpert |
3h48m
Model:
Tokens:
input: 23125
output: 1073
thoughts: 36467
|
| 181/4 |
2026/09/23 19:46 |
tool |
set-results |
0m
Args: map[Answer:Based on the analysis of the Linux kernel source code and refcounting invariants:
1. How Task A and Task B reach these states concurrently on the same mm_struct:
- Task A and Task B share the same `struct mm_struct` (created via `clone` with `CLONE_VM`, such as sibling threads in a process or a parent/child sharing VM via `vfork`).
- Task B is executing `sys_clone` without `CLONE_VM` (e.g. a standard `fork()`), which invokes `copy_process() -> copy_mm() -> dup_mm(tsk, current->mm)`. In `dup_mm()`, it allocates a new `mm_struct` and copies `oldmm` (`current->mm`) via `memcpy(mm, oldmm, sizeof(*mm))` at line 1537.
- Concurrently, Task A is exiting due to a fatal signal or group exit (`syscall_exit_to_user_mode -> get_signal -> do_group_exit -> do_exit -> exit_mm`). In `exit_mm()`, Task A clears `current->mm` and calls `mmput(mm)`.
- In `mmput()`, `atomic_dec_and_test(&mm->mm_users)` evaluates to true, transitioning `mm_users` from 1 to 0 and triggering `__mmput(mm)`. Inside `__mmput()`, Task A begins destroying the address space and unlinks `mm->mmlist` via `list_del(&mm->mmlist)` at line 1198.
- Because `dup_mm()` does not hold `mmlist_lock` (or any lock protecting `oldmm` during the raw `memcpy`), KCSAN flags the concurrent write to `mm->mmlist` in Task A and read in Task B.
2. Does Task B hold an mm_users refcount, or how did mm->mm_users drop to 0:
- Under standard kernel invariants, every user task with an active `current->mm` holds a reference counted in `mm->mm_users`. If Task B held an active reference in `mm->mm_users`, the count would have been at least 2, and Task A's `atomic_dec_and_test(&mm->mm_users)` would have decremented the count to 1 and returned false without calling `__mmput()`.
- Because `atomic_dec_and_test(&mm->mm_users)` succeeded in Task A, `mm->mm_users` was exactly 1 before Task A's decrement, meaning Task B did NOT hold an active `mm_users` reference at the time of the race.
- How `mm_users` dropped to 0:
* In a normal multithreaded process, this indicates an unbalanced/premature `mmput` or refcount underflow bug, leaving Task B executing with a borrowed or dangling `current->mm` while only Task A held the single remaining `mm_users` refcount.
* In `vfork()` scenarios (where parent Task A and child Task B share `mm`), if the vfork child is running while parent teardown is triggered (e.g. fatal signal waking parent prematurely from `TASK_KILLABLE` sleep or completion misordering), a race can expose `mm` teardown.
* (Caveat/Unverified): Without the exact reproducer or syscall trace from syzbot/KCSAN, the exact trigger (e.g., specific ioctl/driver `mmput`, asynchronous `io_uring`/binder teardown, or vfork/signal race) causing Task B to run without an active `mm_users` count could not be verified in the tree.
3. Is the data race benign or harmful, and why:
- This data race is severely HARMFUL (critical bug / fatal race):
* Concurrent structure teardown and read: Task A in `__mmput()` is actively destructing `oldmm`. Task B's `memcpy()` reads torn and invalid pointers (e.g., `mmlist` pointers being unlinked).
* Imminent Use-After-Free: Right after `memcpy()`, `dup_mm()` calls `dup_mmap(mm, oldmm)` which iterates over `oldmm`'s VMAs and page tables. Meanwhile, `__mmput()` calls `exit_mmap(oldmm)`, which frees those exact page tables and VMAs. This will cause `dup_mmap()` to dereference already-freed memory, causing memory corruption, NULL pointer dereferences, or kernel panics.
* Invariant violation: `__mmput()` asserts `VM_BUG_ON(atomic_read(&mm->mm_users))`. Executing `dup_mm()` against an `mm_struct` in `__mmput()` completely violates the memory management lifecycle rules.]
Results: map[Answer:Based on the analysis of the Linux kernel source code and refcounting invariants:
1. How Task A and Task B reach these states concurrently on the same mm_struct:
- Task A and Task B share the same `struct mm_struct` (created via `clone` with `CLONE_VM`, such as sibling threads in a process or a parent/child sharing VM via `vfork`).
- Task B is executing `sys_clone` without `CLONE_VM` (e.g. a standard `fork()`), which invokes `copy_process() -> copy_mm() -> dup_mm(tsk, current->mm)`. In `dup_mm()`, it allocates a new `mm_struct` and copies `oldmm` (`current->mm`) via `memcpy(mm, oldmm, sizeof(*mm))` at line 1537.
- Concurrently, Task A is exiting due to a fatal signal or group exit (`syscall_exit_to_user_mode -> get_signal -> do_group_exit -> do_exit -> exit_mm`). In `exit_mm()`, Task A clears `current->mm` and calls `mmput(mm)`.
- In `mmput()`, `atomic_dec_and_test(&mm->mm_users)` evaluates to true, transitioning `mm_users` from 1 to 0 and triggering `__mmput(mm)`. Inside `__mmput()`, Task A begins destroying the address space and unlinks `mm->mmlist` via `list_del(&mm->mmlist)` at line 1198.
- Because `dup_mm()` does not hold `mmlist_lock` (or any lock protecting `oldmm` during the raw `memcpy`), KCSAN flags the concurrent write to `mm->mmlist` in Task A and read in Task B.
2. Does Task B hold an mm_users refcount, or how did mm->mm_users drop to 0:
- Under standard kernel invariants, every user task with an active `current->mm` holds a reference counted in `mm->mm_users`. If Task B held an active reference in `mm->mm_users`, the count would have been at least 2, and Task A's `atomic_dec_and_test(&mm->mm_users)` would have decremented the count to 1 and returned false without calling `__mmput()`.
- Because `atomic_dec_and_test(&mm->mm_users)` succeeded in Task A, `mm->mm_users` was exactly 1 before Task A's decrement, meaning Task B did NOT hold an active `mm_users` reference at the time of the race.
- How `mm_users` dropped to 0:
* In a normal multithreaded process, this indicates an unbalanced/premature `mmput` or refcount underflow bug, leaving Task B executing with a borrowed or dangling `current->mm` while only Task A held the single remaining `mm_users` refcount.
* In `vfork()` scenarios (where parent Task A and child Task B share `mm`), if the vfork child is running while parent teardown is triggered (e.g. fatal signal waking parent prematurely from `TASK_KILLABLE` sleep or completion misordering), a race can expose `mm` teardown.
* (Caveat/Unverified): Without the exact reproducer or syscall trace from syzbot/KCSAN, the exact trigger (e.g., specific ioctl/driver `mmput`, asynchronous `io_uring`/binder teardown, or vfork/signal race) causing Task B to run without an active `mm_users` count could not be verified in the tree.
3. Is the data race benign or harmful, and why:
- This data race is severely HARMFUL (critical bug / fatal race):
* Concurrent structure teardown and read: Task A in `__mmput()` is actively destructing `oldmm`. Task B's `memcpy()` reads torn and invalid pointers (e.g., `mmlist` pointers being unlinked).
* Imminent Use-After-Free: Right after `memcpy()`, `dup_mm()` calls `dup_mmap(mm, oldmm)` which iterates over `oldmm`'s VMAs and page tables. Meanwhile, `__mmput()` calls `exit_mmap(oldmm)`, which frees those exact page tables and VMAs. This will cause `dup_mmap()` to dereference already-freed memory, causing memory corruption, NULL pointer dereferences, or kernel panics.
* Invariant violation: `__mmput()` asserts `VM_BUG_ON(atomic_read(&mm->mm_users))`. Executing `dup_mm()` against an `mm_struct` in `__mmput()` completely violates the memory management lifecycle rules.]
|
| 182/2 |
2026/09/23 19:46 |
llm |
expert |
0m
Model:
Tokens:
input: 62396
output: 32
thoughts: 303
Thoughts: **Deconstructing the Memory Management Scenario**
Okay, I'm looking at this explanation, and something feels off. Hold on, let's step back and compare `dup_mm` to `dup_mmap` and the `mmap_lock`. I need to understand this in detail. Wait a second, even without a refcount bug, what happens if two threads are within the same process? This is where things get interesting, could two threads in the same process potentially have `dup_mm` triggered?
I need to think this through. Hang on...can thread 1 be calling `clone()` while thread 2 is.... Wait, why did thread 2 call `__mmput`? That's really critical. And isn't that only going to happen if thread 2 is the *last* thread? But if thread 2 is indeed the last thread, can thread 1 still even be running?
Hold on, I need to consider... if thread 1 was already killed, or... wait! Could thread 1 (Task 3876) have *already* had its `mm_users` value decremented? That would change everything. I need to be exact here. When exactly does a thread decrement `mm_users`? Aha, it's in `exit_mm()`!
Okay, if thread 1 called `exit_mm()`, could thread 1 still be in `sys_clone`? No! Wait, hold on a second. `exit_mm()` is only called in `do_exit()`! And once a task is in `do_exit()`, it NEVER returns to userspace or calls `sys_clone()`. That clears up that line of thinking.
Wait! I should look at `vfork` now! Let's check `vfork`! What does `vfork()` do, exactly? Let's consult `kernel/fork.c`, starting with how `kernel_clone` works.
|
| 183/2 |
2026/09/23 19:46 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:kernel_clone]
Results: map[SourceCode:2709: /*
2710: * Ok, this is the main fork-routine.
2711: *
2712: * It copies the process, and if successful kick-starts
2713: * it and waits for it to finish using the VM if required.
2714: */
2715: pid_t kernel_clone(struct kernel_clone_args *args)
2716: {
2717: u64 clone_flags = args->flags;
2718: struct completion vfork;
2719: struct pid *pid;
2720: struct task_struct *p;
2721: int trace = 0;
2722: pid_t nr;
2723:
2724: /*
2725: * Creating an empty mount namespace implies creating a new mount
2726: * namespace. Set this before copy_process() so that the
2727: * CLONE_NEWNS|CLONE_FS mutual exclusion check works correctly.
2728: */
2729: if (clone_flags & CLONE_EMPTY_MNTNS) {
2730: clone_flags |= CLONE_NEWNS;
2731: args->flags = clone_flags;
2732: }
2733:
2734: /*
2735: * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2736: * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2737: * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2738: * field in struct clone_args and it still doesn't make sense to have
2739: * them both point at the same memory location. Performing this check
2740: * here has the advantage that we don't need to have a separate helper
2741: * to check for legacy clone().
2742: */
2743: if ((clone_flags & CLONE_PIDFD) &&
2744: (clone_flags & CLONE_PARENT_SETTID) &&
2745: (args->pidfd == args->parent_tid))
2746: return -EINVAL;
2747:
2748: if (!valid_signal(args->exit_signal))
2749: return -EINVAL;
2750:
2751: /*
2752: * Determine whether and which event to report to ptracer. When
2753: * called from kernel_thread or CLONE_UNTRACED is explicitly
2754: * requested, no event is reported; otherwise, report if the event
2755: * for the type of forking is enabled.
2756: */
2757: if (!(clone_flags & CLONE_UNTRACED)) {
2758: if (clone_flags & CLONE_VFORK)
2759: trace = PTRACE_EVENT_VFORK;
2760: else if (args->exit_signal != SIGCHLD)
2761: trace = PTRACE_EVENT_CLONE;
2762: else
2763: trace = PTRACE_EVENT_FORK;
2764:
2765: if (likely(!ptrace_event_enabled(current, trace)))
2766: trace = 0;
2767: }
2768:
2769: p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2770: add_latent_entropy();
2771:
2772: if (IS_ERR(p))
2773: return PTR_ERR(p);
2774:
2775: /*
2776: * Do this prior waking up the new thread - the thread pointer
2777: * might get invalid after that point, if the thread exits quickly.
2778: */
2779: trace_sched_process_fork(current, p);
2780:
2781: pid = get_task_pid(p, PIDTYPE_PID);
2782: nr = pid_vnr(pid);
2783:
2784: if (clone_flags & CLONE_PARENT_SETTID)
2785: put_user(nr, args->parent_tid);
2786:
2787: if (clone_flags & CLONE_VFORK) {
2788: p->vfork_done = &vfork;
2789: init_completion(&vfork);
2790: get_task_struct(p);
2791: }
2792:
2793: if (IS_ENABLED(CONFIG_LRU_GEN_WALKS_MMU) && !(clone_flags & CLONE_VM)) {
2794: /* lock the task to synchronize with memcg migration */
2795: task_lock(p);
2796: lru_gen_add_mm(p->mm);
2797: task_unlock(p);
2798: }
2799:
2800: wake_up_new_task(p);
2801:
2802: /* forking complete and child started to run, tell ptracer */
2803: if (unlikely(trace))
2804: ptrace_event_pid(trace, pid);
2805:
2806: if (clone_flags & CLONE_VFORK) {
2807: if (!wait_for_vfork_done(p, &vfork))
2808: ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2809: }
2810:
2811: put_pid(pid);
2812: return nr;
2813: }
SourceFile:kernel/fork.c]
|
| 184/2 |
2026/09/23 19:46 |
llm |
expert |
0m
Model:
Tokens:
input: 64760
output: 37
thoughts: 279
Thoughts: **Vfork and the Clone Conundrum**
Okay, hold on a second! Let's trace this `vfork` flow, because this smells like a potential race condition. Right, if a task uses `vfork`, the `clone_flags` are set to `CLONE_VM | CLONE_VFORK | SIGCHLD`. In `copy_mm`, we see that since `clone_flags` contains `CLONE_VM`, the `oldmm` is just shared. `mmget(oldmm); tsk->mm = oldmm;`, so the child starts running with the same memory map, the `oldmm`. The parent's then blocked in `wait_for_vfork_done(p, &vfork)`. Fine, child's running.
But here's the kicker: *What if* the child, while *still in vfork*, calls `clone()` *without* `CLONE_VM`? I'm using an example task number, 3876, to think this through. The child calls `sys_clone()` without the `CLONE_VM` flag! That hits `kernel_clone` which in turn goes to `copy_process` and then `copy_mm`. Aha! That's the important bit. Because the child's `current->mm` is *still* the shared `oldmm`! So the `dup_mm` gets called on the *shared* mm!
Now, what is the parent doing *during* all this? It's sleeping in `wait_for_vfork_done`. What if it gets a signal? I mean, can the parent be killed by a SIGKILL while sleeping? Let's go look at `wait_for_vfork_done` to check that... Gotta make sure there's no subtle timing window here!
|
| 185/2 |
2026/09/23 19:46 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:wait_for_vfork_done]
Results: map[SourceCode:1445: static int wait_for_vfork_done(struct task_struct *child,
1446: struct completion *vfork)
1447: {
1448: unsigned int state = TASK_KILLABLE|TASK_FREEZABLE;
1449: int killed;
1450:
1451: cgroup_enter_frozen();
1452: killed = wait_for_completion_state(vfork, state);
1453: cgroup_leave_frozen(false);
1454:
1455: if (killed) {
1456: task_lock(child);
1457: child->vfork_done = NULL;
1458: task_unlock(child);
1459: }
1460:
1461: put_task_struct(child);
1462: return killed;
1463: }
SourceFile:kernel/fork.c]
|
| 186/2 |
2026/09/23 19:46 |
llm |
expert |
0m
Model:
Tokens:
input: 65746
output: 32
thoughts: 1838
Thoughts: **A Deep Dive into `mm_users` and Potential Memory Management Issues**
Okay, here's what's running through my head. First, I see this code snippet in `wait_for_vfork_done` (lines 1448-1463). It's crucial because if the parent process gets killed by SIGKILL while waiting for the vfork child, `wait_for_completion_state` returns a non-zero value, which the function subsequently returns. This is where things can get messy. The parent calls `kernel_clone`, then returns to `__do_sys_clone`, and then to `syscall_exit_to_user_mode`.
Since SIGKILL is pending on the parent, this leads to the signal path: `syscall_exit_to_user_mode_prepare` -> `exit_to_user_mode_loop` -> `arch_do_signal_or_restart` -> `get_signal` -> `do_group_exit(signr)` -> `do_exit` -> `exit_mm` -> `mmput(mm)`. It is here I am going to have to dive into memory management, particularly the `mm_users` field.
The core of the issue is here: `mmput(mm)`. I have to figure out what `mm->mm_users` is at this point. I know the child is still running, which means it took a `mmget(oldmm)` in `copy_mm` during the `vfork` process. So, the child holds one reference and the parent holds one, giving us a `mm_users` of 2.
The parent will call `mmput(mm)` which should decrement `mm_users` from 2 to 1. But, what if the child has already exited? If it has exited it couldn't be in `sys_clone`! Then, what if the child was Task 21217 and the parent was Task 3876?
Okay, if the child, 21217, exits, `mm_users` should decrement from 2 to 1. But the value is not 0!
Wait! Could `mm_users` be 1?! How?! What would that scenario look like?
Let's think: Can `CLONE_VM` be called without an `mmget`? No, `copy_mm` has a `mmget(oldmm)`. Could `mmput` be called somewhere else? Wait! What if Task 21217 was the *only* thread in the process? Then, Task 21217 would have `mm_users == 1`. When 21217 exits, `mm_users` goes from 1 to 0, which triggers `__mmput`! Then who is Task 3876? Why did Task 3876 have `current->mm == 0xffff888104668000`?
Could Task 3876 be a task whose `current->mm` WAS `0xffff888104668000`, but Task 3876 is... wait! Could Task 3876 NOT be part of Task 21217's process? How could Task 3876 have `current->mm == 0xffff888104668000` if it's not part of the same process?
Wait! Can a task share `current->mm` with another process? Only if created with `clone(CLONE_VM)`! But if created with `clone(CLONE_VM)`, `copy_mm` does `mmget(oldmm)`. So, if two tasks share `mm`, why would `mm_users` be 1?
Okay, wait, let's go back to `copy_mm` to check. Look at the code, in particular the arguments to `dup_mm`. The argument `current->mm` to `dup_mm` is Task 3876, the current task, and is calling `kernel_clone` -> `copy_process` -> `copy_mm`! So Task 3876 is *cloning* a new child. It is doing a `memcpy(mm, oldmm, sizeof(*mm))` where `oldmm` is Task 3876's `current->mm`! And Task 21217 is calling `__mmput(mm)` where `mm` is Task 21217's `current->mm`! And both of those mm's are `0xffff88810466800
|
| 187/2 |
2026/09/23 19:47 |
tool |
git-log |
4m
Args: map[CodeRegexp:dup_mm Count:10 Since:5 years]
Results: map[Output:2f252a7a6c90 kselftest: alloc_tag: add kselftest for ioctl interface
eda8c5e77622 mm/memory: add tree limit to free_pgtables()
3e43e260f1e4 mm: perform VMA allocation, freeing, duplication in mm
26a8f57760c1 mm: move dup_mmap() to mm
3104138517fc mm: make vma cache SLAB_TYPESAFE_BY_RCU
8ac662f5da19 fork: avoid inappropriate uprobe access to invalid mm
7f955be9f887 arm64: implement PKEYS support
40b88644dd92 mm: remove arch_unmap()
b7cf2a1d9881 xtensa: remove redundant flush_dcache_page and ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE macros
f5c12105c15f mm,page_owner: fix refcount imbalance
]
|
| 188/2 |
2026/09/23 19:52 |
llm |
expert |
0m
Model:
Tokens:
input: 68905
output: 25
thoughts: 27
Thoughts: Okay, here's my interpretation of what's going on with that commit, presented as a first-person expert perspective:
**Delving into Commit 8ac662f5da19: "fork: avoid inappropriate uprobe access to invalid mm"**
Alright, let's dissect `8ac662f5da19`. The commit message itself is a pretty good clue, but let's dive deeper. It seems we're dealing with a `fork()`-related issue, specifically targeting potential vulnerabilities related to user-space probing (uprobes) and memory management (`mm`). My initial hypothesis is that something within the fork process was allowing, or *could* allow, uprobes to incorrectly access memory space that's not actually valid for the new child process.
Thinking about the context, the `mm` (memory map) in the parent process is copied when `fork()` happens. The child process then gets its *own* `mm`, but the initial content is essentially a snapshot. Now, if we have uprobes hooked into the parent's address space, and something goes wrong during or immediately *after* the fork, perhaps due to a race condition or some other subtle bug, the child's `mm` might not be completely isolated or initialized correctly. This could lead to uprobes inadvertently trying to access memory regions within the invalid `mm` of the parent, or within an invalid portion of the newly cloned `mm`. That's a classic recipe for a security flaw, or at least a severe stability issue.
This commit likely addresses a situation where uprobe accesses were being allowed to happen in the child, using a memory map (mm) that wasn't initialized, or was somehow stale, or even referencing the parent’s `mm`. The fix probably involves adding checks to ensure that uprobe accesses are strictly limited to valid memory regions *within* the context of the child process's own, newly initialized `mm`. Maybe they're adding specific checks in the `fork()` path to validate the memory regions before allowing uprobes to operate on the copied (or newly constructed) memory map. I'd need to examine the diff to be sure, but that's my working theory based on the commit message. The goal is to prevent any invalid or unintended access to memory that is not part of the child's legitimate address space. Safety and integrity are paramount in these kernel areas, so it's good this was flagged and addressed!
|
| 189/2 |
2026/09/23 19:52 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 8ac662f5da19f5873fdd94c48a5cdb45b2e1b58f
Author: Lorenzo Stoakes <ljs@kernel.org>
Date: Tue Dec 10 17:24:12 2024 +0000
fork: avoid inappropriate uprobe access to invalid mm
If dup_mmap() encounters an issue, currently uprobe is able to access the
relevant mm via the reverse mapping (in build_map_info()), and if we are
very unlucky with a race window, observe invalid XA_ZERO_ENTRY state which
we establish as part of the fork error path.
This occurs because uprobe_write_opcode() invokes anon_vma_prepare() which
in turn invokes find_mergeable_anon_vma() that uses a VMA iterator,
invoking vma_iter_load() which uses the advanced maple tree API and thus
is able to observe XA_ZERO_ENTRY entries added to dup_mmap() in commit
d24062914837 ("fork: use __mt_dup() to duplicate maple tree in
dup_mmap()").
This change was made on the assumption that only process tear-down code
would actually observe (and make use of) these values. However this very
unlikely but still possible edge case with uprobes exists and
unfortunately does make these observable.
The uprobe operation prevents races against the dup_mmap() operation via
the dup_mmap_sem semaphore, which is acquired via uprobe_start_dup_mmap()
and dropped via uprobe_end_dup_mmap(), and held across
register_for_each_vma() prior to invoking build_map_info() which does the
reverse mapping lookup.
Currently these are acquired and dropped within dup_mmap(), which exposes
the race window prior to error handling in the invoking dup_mm() which
tears down the mm.
We can avoid all this by just moving the invocation of
uprobe_start_dup_mmap() and uprobe_end_dup_mmap() up a level to dup_mm()
and only release this lock once the dup_mmap() operation succeeds or clean
up is done.
This means that the uprobe code can never observe an incompletely
constructed mm and resolves the issue in this case.
Link: https://lkml.kernel.org/r/20241210172412.52995-1-lorenzo.stoakes@oracle.com
Fixes: d24062914837 ("fork: use __mt_dup() to duplicate maple tree in dup_mmap()")
Signed-off-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Reported-by: syzbot+2d788f4f7cb660dac4b7@syzkaller.appspotmail.com
Closes: https://lore.kernel.org/all/6756d273.050a0220.2477f.003d.GAE@google.com/
Cc: Adrian Hunter <adrian.hunter@intel.com>
Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com>
Cc: Arnaldo Carvalho de Melo <acme@kernel.org>
Cc: Ian Rogers <irogers@google.com>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: Jann Horn <jannh@google.com>
Cc: Jiri Olsa <jolsa@kernel.org>
Cc: Kan Liang <kan.liang@linux.intel.com>
Cc: Liam R. Howlett <Liam.Howlett@Oracle.com>
Cc: Mark Rutland <mark.rutland@arm.com>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Peng Zhang <zhangpeng.00@bytedance.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: David Hildenbrand <david@redhat.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
diff --git a/kernel/fork.c b/kernel/fork.c
index 1450b461d196..9b301180fd41 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -639,11 +639,8 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,
LIST_HEAD(uf);
VMA_ITERATOR(vmi, mm, 0);
- uprobe_start_dup_mmap();
- if (mmap_write_lock_killable(oldmm)) {
- retval = -EINTR;
- goto fail_uprobe_end;
- }
+ if (mmap_write_lock_killable(oldmm))
+ return -EINTR;
flush_cache_dup_mm(oldmm);
uprobe_dup_mmap(oldmm, mm);
/*
@@ -782,8 +779,6 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,
dup_userfaultfd_complete(&uf);
else
dup_userfaultfd_fail(&uf);
-fail_uprobe_end:
- uprobe_end_dup_mmap();
return retval;
fail_nomem_anon_vma_fork:
@@ -1692,9 +1687,11 @@ static struct mm_struct *dup_mm(struct task_struct *tsk,
if (!mm_init(mm, tsk, mm->user_ns))
goto fail_nomem;
+ uprobe_start_dup_mmap();
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
+ uprobe_end_dup_mmap();
mm->hiwater_rss = get_mm_rss(mm);
mm->hiwater_vm = mm->total_vm;
@@ -1709,6 +1706,8 @@ static struct mm_struct *dup_mm(struct task_struct *tsk,
mm->binfmt = NULL;
mm_init_owner(mm, NULL);
mmput(mm);
+ if (err)
+ uprobe_end_dup_mmap();
fail_nomem:
return NULL;
]
|
| 190/2 |
2026/09/23 19:52 |
llm |
expert-compressor |
0m
Model:
Reply: ### Summary of Investigation
#### 1. Data Race Report Breakdown
* **Stack A (Write - Task 21217 on CPU 1):**
* `list_del(&mm->mmlist)` in `__mmput()` (`kernel/fork.c:1198`) via `mmput()` -> `exit_mm()` -> `do_exit()` -> `do_group_exit()` -> `get_signal()`.
* Target address: `0xffff8881046681f8` (size 8 bytes), corresponding to `mm->mmlist.next` / `mmlist.prev` (offset 0x1f8 = 504 bytes within `struct mm_struct`).
* **Stack B (Read - Task 3876 on CPU 0):**
* `memcpy(mm, oldmm, sizeof(*mm))` in `dup_mm()` (`kernel/fork.c:1537`) via `copy_mm()` (`kernel/fork.c:1595`) -> `copy_process()` (`kernel/fork.c:2310`) -> `kernel_clone()` -> `sys_clone`.
* Target address: `0xffff888104668000` (size 1728 bytes, full `struct mm_struct`, offset 0x0 to 0x6c0).
---
#### 2. Approaches Tried & Key Findings
* **Report Layout & Offset Analysis:**
* `struct mm_struct` size is 1728 (0x6c0) bytes.
* Base of `mm_struct`: `0xffff888104668000`.
* `mmlist` offset is 504 (0x1f8).
* Task 3876 is performing a bulk read (`memcpy`) of `oldmm` (`current->mm`).
* Task 21217 is concurrently executing `list_del(&mm->mmlist)` during teardown (`__mmput`).
* **Dead-ends / Hypotheses Ruled Out:**
* *`execve` / `de_thread` / `exec_mm_put_old`:* Commit `38205ecbe6b6` moved old `mm` teardown outside exec locks to `setup_new_exec()`. However, Task 21217's stack trace is definitively in `exit_mm()` (`kernel/exit.c:618`), terminating from a death signal in `get_signal()`, not in `exec_mm_put_old`.
* *`kthread_use_mm` / `PF_KTHREAD` / `io_uring` workers:* Task 3876 entered via `do_syscall_64` executing `sys_clone` without `CLONE_VM`, which is an ordinary userspace task.
* *Slab reuse / UAF after full free:* The write occurs inside `__mmput` *before* `mmdrop(mm)`. The memory has not been freed back to the slab allocator (`mm_cachep`); both tasks are concurrently referencing the active `struct mm_struct`.
* **Investigation into `mm->mm_users` Lifetime & Concurrency:**
* In `dup_mm()` (`kernel/fork.c:1537`):
```c
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
if (!mm_init(mm, tsk))
goto fail_nomem;
uprobe_start_dup_mmap();
err = dup_mmap(mm, oldmm);
```
* `memcpy(mm, oldmm, sizeof(*mm))` copies the entire `struct mm_struct` **without holding any locks on `oldmm`** (`mmap_lock` is only acquired inside `dup_mmap()`, after `memcpy` and `mm_init`).
* `mmlist_lock` is taken by `__mmput` around `list_del(&mm->mmlist)`, but `dup_mm` holds neither `mmlist_lock` nor `mmap_lock` during `memcpy`.
* In `exit_mm()` (`kernel/exit.c:584`):
* Clears `current->mm = NULL`.
* Calls `mmput(mm)`.
* `mmput(mm)` executes `if (atomic_dec_and_test(&mm->mm_users)) __mmput(mm);`.
* In `copy_process()` (`kernel/fork.c:2495`):
* Signal termination check `if (fatal_signal_pending(current))` occurs on line 2495, *after* `copy_mm()` has already executed on line 2310.
---
#### 3. Active Theories & Lines of Investigation
1. **How `atomic_dec_and_test(&mm->mm_users)` hit 0 while Task 3876 has `current->mm == oldmm`:**
* *Thread group death / `vfork` / `CLONE_VM`:*
* If Task 3876 and Task 21217 are threads sharing `oldmm`, why would `mm_users` reach 0?
* If Task 3876 is a child created via `vfork()` (`CLONE_VM | CLONE_VFORK`), `vfork` children share `current->mm` without setting `CLONE_THREAD`. If the child task forks again (`clone()` without `CLONE_VM`), or if the parent/sibling exits, how is `mm_users` tracked?
* If a multithreaded process has a thread dying from a fatal signal (`do_group_exit`), did another thread already drop its `mm` or could an imbalance exist?
* What if `oldmm` had an `mmput` called prematurely, or what if Task 3876 was racing during process exit?
2. **Lockless `memcpy` in `dup_mm`:**
* Regardless of why `__mmput` or `list_del` is running, `dup_mm` performs an unsynchronized 1728-byte `memcpy` of `oldmm`.
* Concurrent modifications to `oldmm` (like `mmlist`, maple tree state, counters, or flags) during `dup_mm` can result in torn or corrupt state copied into the new child's `mm`.
* In `mm_init(mm, tsk)`, `INIT_LIST_HEAD(&mm->mmlist)` reinitializes `mm->mmlist`, but the read of `oldmm->mmlist` during `memcpy` still constitutes an unsynchronized data race with `list_del` / `mmlist_lock`.
* More critically: if `__mmput` is actively tearing down `oldmm` (`ksm_exit`, `exit_mmap`, `mmput`), `dup_mmap(mm, oldmm)` following right after will attempt to lock and traverse `oldmm->mm_mt` (maple tree) and page tables of a destroying or already destroyed address space, leading to Use-After-Free or kernel panic.
---
#### 4. Critical Files and Code Locations
* `kernel/fork.c`:
* `__mmput()` at line 1185 (`list_del(&mm->mmlist)` under `mmlist_lock` at line 1198).
* `mmput()` at line 1211 (`if (atomic_dec_and_test(&mm->mm_users)) __mmput(mm);`).
* `dup_mm()` at line 1527: `memcpy(mm, oldmm, sizeof(*mm))` at line 1537.
* `copy_mm()` at line 1568 (`dup_mm(tsk, current->mm)` at line 1595).
* `copy_process()` at line 2310 (`copy_mm()`), fatal signal check at line 2495.
* `kernel/exit.c`:
* `exit_mm()` at line 584: clears `current->mm = NULL` at 611, calls `mmput(mm)` at 618.
* `do_group_exit()` at line 1130: `zap_other_threads(current)`, calls `do_exit()`.
* `include/linux/mm_types.h`:
* `struct mm_struct` definition at line 1175:
* `mm_users` at line 1223.
* `mmlist` at line 1252 (offset 504 / 0x1f8).
---
#### 5. Next Steps / Watch Out
* Avoid repetitive grep loops on general `current->mm` assignments.
* Investigate exact failure mechanisms:
* Check if `vfork()` child calling `clone()` creates a scenario where `oldmm` is destroyed if the vfork child or parent is terminated by a fatal signal.
* Trace whether this is **HARMFUL** (teardown of `mm_struct` concurrent with `dup_mm` / `dup_mmap` leading to torn state, maple tree corruption, UAF during `exit_mmap` vs `dup_mmap`) or missing synchronization.
* Prepare two-column failure interleaving and call `set-results` before final response.
Tokens:
input: 39610
output: 2164
thoughts: 0
|
| 191/2 |
2026/09/23 19:53 |
llm |
expert |
0m
Model:
Tokens:
input: 23281
output: 32
thoughts: 0
|
| 192/2 |
2026/09/23 19:53 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:__mmput]
Results: map[SourceCode:1185: static inline void __mmput(struct mm_struct *mm)
1186: {
1187: VM_BUG_ON(atomic_read(&mm->mm_users));
1188:
1189: uprobe_clear_state(mm);
1190: exit_aio(mm);
1191: ksm_exit(mm);
1192: khugepaged_exit(mm); /* must run before exit_mmap */
1193: exit_mmap(mm);
1194: mm_put_huge_zero_folio(mm);
1195: set_mm_exe_file(mm, NULL);
1196: if (!list_empty(&mm->mmlist)) {
1197: spin_lock(&mmlist_lock);
1198: list_del(&mm->mmlist);
1199: spin_unlock(&mmlist_lock);
1200: }
1201: if (mm->binfmt)
1202: module_put(mm->binfmt->module);
1203: lru_gen_del_mm(mm);
1204: futex_hash_free(mm);
1205: mmdrop(mm);
1206: }
SourceFile:kernel/fork.c]
|
| 193/2 |
2026/09/23 19:53 |
llm |
expert |
0m
Model:
Tokens:
input: 23681
output: 31
thoughts: 0
|
| 194/2 |
2026/09/23 19:53 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:mmput]
Results: map[SourceCode:1208: /*
1209: * Decrement the use count and release all resources for an mm.
1210: */
1211: void mmput(struct mm_struct *mm)
1212: {
1213: might_sleep();
1214:
1215: if (atomic_dec_and_test(&mm->mm_users))
1216: __mmput(mm);
1217: }
SourceFile:kernel/fork.c]
|
| 195/2 |
2026/09/23 19:53 |
llm |
expert |
0m
Model:
Tokens:
input: 23865
output: 32
thoughts: 0
|
| 196/2 |
2026/09/23 19:53 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mm]
Results: map[SourceCode:1517: /**
1518: * dup_mm() - duplicates an existing mm structure
1519: * @tsk: the task_struct with which the new mm will be associated.
1520: * @oldmm: the mm to duplicate.
1521: *
1522: * Allocates a new mm structure and duplicates the provided @oldmm structure
1523: * content into it.
1524: *
1525: * Return: the duplicated mm or NULL on failure.
1526: */
1527: static struct mm_struct *dup_mm(struct task_struct *tsk,
1528: struct mm_struct *oldmm)
1529: {
1530: struct mm_struct *mm;
1531: int err;
1532:
1533: mm = allocate_mm();
1534: if (!mm)
1535: goto fail_nomem;
1536:
1537: memcpy(mm, oldmm, sizeof(*mm));
1538:
1539: if (!mm_init(mm, tsk))
1540: goto fail_nomem;
1541:
1542: uprobe_start_dup_mmap();
1543: err = dup_mmap(mm, oldmm);
1544: if (err)
1545: goto free_pt;
1546: uprobe_end_dup_mmap();
1547:
1548: mm->hiwater_rss = get_mm_rss(mm);
1549: mm->hiwater_vm = mm->total_vm;
1550:
1551: if (mm->binfmt && !try_module_get(mm->binfmt->module))
1552: goto free_pt;
1553:
1554: return mm;
1555:
1556: free_pt:
1557: /* don't put binfmt in mmput, we haven't got module yet */
1558: mm->binfmt = NULL;
1559: mm_init_owner(mm, NULL);
1560: mmput(mm);
1561: if (err)
1562: uprobe_end_dup_mmap();
1563:
1564: fail_nomem:
1565: return NULL;
1566: }
SourceFile:kernel/fork.c]
|
| 197/2 |
2026/09/23 19:54 |
llm |
expert |
0m
Model:
Tokens:
input: 24595
output: 32
thoughts: 0
|
| 198/2 |
2026/09/23 19:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_mm]
Results: map[SourceCode:1568: static int copy_mm(u64 clone_flags, struct task_struct *tsk)
1569: {
1570: struct mm_struct *mm, *oldmm;
1571:
1572: tsk->min_flt = tsk->maj_flt = 0;
1573: tsk->nvcsw = tsk->nivcsw = 0;
1574: #ifdef CONFIG_DETECT_HUNG_TASK
1575: tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1576: tsk->last_switch_time = 0;
1577: #endif
1578:
1579: tsk->mm = NULL;
1580: tsk->active_mm = NULL;
1581:
1582: /*
1583: * Are we cloning a kernel thread?
1584: *
1585: * We need to steal a active VM for that..
1586: */
1587: oldmm = current->mm;
1588: if (!oldmm)
1589: return 0;
1590:
1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
1597: return -ENOMEM;
1598: }
1599:
1600: tsk->mm = mm;
1601: tsk->active_mm = mm;
1602: return 0;
1603: }
SourceFile:kernel/fork.c]
|
| 199/2 |
2026/09/23 19:54 |
llm |
expert |
0m
Model:
Tokens:
input: 25138
output: 32
thoughts: 0
|
| 200/2 |
2026/09/23 19:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:exit_mm]
Results: map[SourceCode: 580: /*
581: * Turn us into a lazy TLB process if we
582: * aren't already..
583: */
584: static void exit_mm(void)
585: {
586: struct mm_struct *mm = current->mm;
587:
588: mm_exit_exec_release(current, mm);
589: if (!mm)
590: return;
591:
592: exit_mm_sched_cache(mm);
593:
594: mmap_read_lock(mm);
595: mmgrab_lazy_tlb(mm);
596: BUG_ON(mm != current->active_mm);
597: /* more a memory barrier than a real lock */
598: task_lock(current);
599: /*
600: * When a thread stops operating on an address space, the loop
601: * in membarrier_private_expedited() may not observe that
602: * tsk->mm, and the loop in membarrier_global_expedited() may
603: * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
604: * rq->membarrier_state, so those would not issue an IPI.
605: * Membarrier requires a memory barrier after accessing
606: * user-space memory, before clearing tsk->mm or the
607: * rq->membarrier_state.
608: */
609: smp_mb__after_spinlock();
610: local_irq_disable();
611: current->mm = NULL;
612: membarrier_update_current_mm(NULL);
613: enter_lazy_tlb(mm, current);
614: local_irq_enable();
615: task_unlock(current);
616: mmap_read_unlock(mm);
617: mm_update_next_owner(mm);
618: mmput(mm);
619: if (test_thread_flag(TIF_MEMDIE))
620: exit_oom_victim();
621: }
SourceFile:kernel/exit.c]
|
| 201/2 |
2026/09/23 19:54 |
llm |
expert |
0m
Model:
Tokens:
input: 25819
output: 34
thoughts: 0
|
| 202/2 |
2026/09/23 19:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:do_group_exit]
Results: map[SourceCode:1125: /*
1126: * Take down every thread in the group. This is called by fatal signals
1127: * as well as by sys_exit_group (below).
1128: */
1129: void __noreturn
1130: do_group_exit(int exit_code)
1131: {
1132: struct signal_struct *sig = current->signal;
1133:
1134: if (sig->flags & SIGNAL_GROUP_EXIT)
1135: exit_code = sig->group_exit_code;
1136: else if (sig->group_exec_task)
1137: exit_code = 0;
1138: else {
1139: struct sighand_struct *const sighand = current->sighand;
1140:
1141: spin_lock_irq(&sighand->siglock);
1142: if (sig->flags & SIGNAL_GROUP_EXIT)
1143: /* Another thread got here before we took the lock. */
1144: exit_code = sig->group_exit_code;
1145: else if (sig->group_exec_task)
1146: exit_code = 0;
1147: else {
1148: sig->group_exit_code = exit_code;
1149: sig->flags = SIGNAL_GROUP_EXIT;
1150: zap_other_threads(current);
1151: }
1152: spin_unlock_irq(&sighand->siglock);
1153: }
1154:
1155: do_exit(exit_code);
1156: /* NOTREACHED */
1157: }
SourceFile:kernel/exit.c]
|
| 203/2 |
2026/09/23 19:54 |
llm |
expert |
0m
Model:
Tokens:
input: 26359
output: 34
thoughts: 0
|
| 204/2 |
2026/09/23 19:55 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/signal.c Name:zap_other_threads]
Results: map[SourceCode:1368: /*
1369: * Nuke all other threads in the group.
1370: */
1371: int zap_other_threads(struct task_struct *p)
1372: {
1373: struct task_struct *t;
1374: int count = 0;
1375:
1376: p->signal->group_stop_count = 0;
1377: task_clear_jobctl_pending(p, JOBCTL_PENDING_MASK);
1378:
1379: for_other_threads(p, t) {
1380: task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
1381: count++;
1382:
1383: /* Don't bother with already dead threads */
1384: if (t->exit_state)
1385: continue;
1386: sigaddset(&t->pending.signal, SIGKILL);
1387: signal_wake_up(t, 1);
1388: }
1389:
1390: return count;
1391: }
SourceFile:kernel/signal.c]
|
| 205/2 |
2026/09/23 19:55 |
llm |
expert |
0m
Model:
Tokens:
input: 26742
output: 32
thoughts: 0
|
| 206/2 |
2026/09/23 19:55 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_process]
Results: map[SourceCode:2004: /*
2005: * This creates a new process as a copy of the old one,
2006: * but does not actually start it yet.
2007: *
2008: * It copies the registers, and all the appropriate
2009: * parts of the process environment (as per the clone
2010: * flags). The actual kick-off is left to the caller.
2011: */
2012: __latent_entropy struct task_struct *copy_process(
2013: struct pid *pid,
2014: int trace,
2015: int node,
2016: struct kernel_clone_args *args)
2017: {
2018: int pidfd = -1, retval;
2019: struct task_struct *p;
2020: struct multiprocess_signals delayed;
2021: struct file *pidfile = NULL;
2022: const u64 clone_flags = args->flags;
2023: struct nsproxy *nsp = current->nsproxy;
2024:
2025: /*
2026: * Don't allow sharing the root directory with processes in a different
2027: * namespace
2028: */
2029: if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
2030: return ERR_PTR(-EINVAL);
2031:
2032: if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2033: return ERR_PTR(-EINVAL);
2034:
2035: /*
2036: * Thread groups must share signals as well, and detached threads
2037: * can only be started up within the thread group.
2038: */
2039: if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
2040: return ERR_PTR(-EINVAL);
2041:
2042: /*
2043: * Shared signal handlers imply shared VM. By way of the above,
2044: * thread groups also imply shared VM. Blocking this case allows
2045: * for various simplifications in other code.
2046: */
2047: if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2048: return ERR_PTR(-EINVAL);
2049:
2050: /*
2051: * Siblings of global init remain as zombies on exit since they are
2052: * not reaped by their parent (swapper). To solve this and to avoid
2053: * multi-rooted process trees, prevent global and container-inits
2054: * from creating siblings.
2055: */
2056: if ((clone_flags & CLONE_PARENT) &&
2057: current->signal->flags & SIGNAL_UNKILLABLE)
2058: return ERR_PTR(-EINVAL);
2059:
2060: /*
2061: * If the new process will be in a different pid or user namespace
2062: * do not allow it to share a thread group with the forking task.
2063: */
2064: if (clone_flags & CLONE_THREAD) {
2065: if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2066: (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2067: return ERR_PTR(-EINVAL);
2068: }
2069:
2070: if (clone_flags & CLONE_PIDFD) {
2071: /*
2072: * - CLONE_DETACHED is blocked so that we can potentially
2073: * reuse it later for CLONE_PIDFD.
2074: */
2075: if (clone_flags & CLONE_DETACHED)
2076: return ERR_PTR(-EINVAL);
2077: }
2078:
2079: if (clone_flags & CLONE_AUTOREAP) {
2080: if (clone_flags & CLONE_THREAD)
2081: return ERR_PTR(-EINVAL);
2082: if (clone_flags & CLONE_PARENT)
2083: return ERR_PTR(-EINVAL);
2084: if (args->exit_signal)
2085: return ERR_PTR(-EINVAL);
2086: }
2087:
2088: if ((clone_flags & CLONE_PARENT) && current->signal->autoreap)
2089: return ERR_PTR(-EINVAL);
2090:
2091: if (clone_flags & CLONE_NNP) {
2092: if (clone_flags & CLONE_THREAD)
2093: return ERR_PTR(-EINVAL);
2094: }
2095:
2096: if (clone_flags & CLONE_PIDFD_AUTOKILL) {
2097: if (!(clone_flags & CLONE_PIDFD))
2098: return ERR_PTR(-EINVAL);
2099: if (!(clone_flags & CLONE_AUTOREAP))
2100: return ERR_PTR(-EINVAL);
2101: if (clone_flags & CLONE_THREAD)
2102: return ERR_PTR(-EINVAL);
2103: /*
2104: * Without CLONE_NNP the child could escalate privileges
2105: * after being spawned, so require CAP_SYS_ADMIN.
2106: * With CLONE_NNP the child can't gain new privileges,
2107: * so allow unprivileged usage.
2108: */
2109: if (!(clone_flags & CLONE_NNP) &&
2110: !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
2111: return ERR_PTR(-EPERM);
2112: }
2113:
2114: /*
2115: * Force any signals received before this point to be delivered
2116: * before the fork happens. Collect up signals sent to multiple
2117: * processes that happen during the fork and delay them so that
2118: * they appear to happen after the fork.
2119: */
2120: sigemptyset(&delayed.signal);
2121: INIT_HLIST_NODE(&delayed.node);
2122:
2123: spin_lock_irq(¤t->sighand->siglock);
2124: if (!(clone_flags & CLONE_THREAD))
2125: hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
2126: recalc_sigpending();
2127: spin_unlock_irq(¤t->sighand->siglock);
2128: retval = -ERESTARTNOINTR;
2129: if (task_sigpending(current))
2130: goto fork_out;
2131:
2132: retval = -ENOMEM;
2133: p = dup_task_struct(current, node);
2134: if (!p)
2135: goto fork_out;
2136: /*
2137: * Must run before the first fallible op, so error paths never
2138: * free the parent's ret_stack.
2139: */
2140: ftrace_graph_init_task(p);
2141: retval = copy_exec_state(clone_flags, p);
2142: if (retval)
2143: goto bad_fork_free;
2144: p->flags &= ~PF_KTHREAD;
2145: if (args->kthread)
2146: p->flags |= PF_KTHREAD;
2147: if (args->user_worker) {
2148: /*
2149: * Mark us a user worker, and block any signal that isn't
2150: * fatal or STOP
2151: */
2152: p->flags |= PF_USER_WORKER;
2153: siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2154: }
2155: if (args->io_thread)
2156: p->flags |= PF_IO_WORKER;
2157:
2158: if (args->name)
2159: strscpy_pad(p->comm, args->name, sizeof(p->comm));
2160:
2161: p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2162: /*
2163: * TID is cleared in mm_release() when the task exits
2164: */
2165: p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2166:
2167: rt_mutex_init_task(p);
2168: raw_spin_lock_init(&p->blocked_lock);
2169:
2170: lockdep_assert_irqs_enabled();
2171: #ifdef CONFIG_PROVE_LOCKING
2172: DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2173: #endif
2174: retval = copy_creds(p, clone_flags);
2175: if (retval < 0)
2176: goto bad_fork_free;
2177:
2178: retval = -EAGAIN;
2179: if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2180: if (p->real_cred->user != INIT_USER &&
2181: !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2182: goto bad_fork_cleanup_count;
2183: }
2184: current->flags &= ~PF_NPROC_EXCEEDED;
2185:
2186: /*
2187: * If multiple threads are within copy_process(), then this check
2188: * triggers too late. This doesn't hurt, the check is only there
2189: * to stop root fork bombs.
2190: */
2191: retval = -EAGAIN;
2192: if (data_race(nr_threads >= max_threads))
2193: goto bad_fork_cleanup_count;
2194:
2195: delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
2196: p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2197: p->flags |= PF_FORKNOEXEC;
2198: INIT_LIST_HEAD(&p->children);
2199: INIT_LIST_HEAD(&p->sibling);
2200: rcu_copy_process(p);
2201: p->vfork_done = NULL;
2202: spin_lock_init(&p->alloc_lock);
2203:
2204: init_sigpending(&p->pending);
2205:
2206: p->utime = p->stime = p->gtime = 0;
2207: #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2208: p->utimescaled = p->stimescaled = 0;
2209: #endif
2210: prev_cputime_init(&p->prev_cputime);
2211:
2212: #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2213: seqcount_init(&p->vtime.seqcount);
2214: p->vtime.starttime = 0;
2215: p->vtime.state = VTIME_INACTIVE;
2216: #endif
2217:
2218: #ifdef CONFIG_IO_URING
2219: p->io_uring = NULL;
2220: retval = io_uring_fork(p);
2221: if (unlikely(retval))
2222: goto bad_fork_cleanup_delayacct;
2223: retval = -EAGAIN;
2224: #endif
2225:
2226: p->default_timer_slack_ns = current->timer_slack_ns;
2227:
2228: #ifdef CONFIG_PSI
2229: p->psi_flags = 0;
2230: #endif
2231:
2232: task_io_accounting_init(&p->ioac);
2233: acct_clear_integrals(p);
2234:
2235: posix_cputimers_init(&p->posix_cputimers);
2236: tick_dep_init_task(p);
2237:
2238: p->io_context = NULL;
2239: audit_set_context(p, NULL);
2240: cgroup_fork(p);
2241: if (args->kthread) {
2242: if (!set_kthread_struct(p))
2243: goto bad_fork_cleanup_delayacct;
2244: }
2245: #ifdef CONFIG_NUMA
2246: p->mempolicy = mpol_dup(p->mempolicy);
2247: if (IS_ERR(p->mempolicy)) {
2248: retval = PTR_ERR(p->mempolicy);
2249: p->mempolicy = NULL;
2250: goto bad_fork_cleanup_delayacct;
2251: }
2252: #endif
2253: #ifdef CONFIG_CPUSETS
2254: p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2255: seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2256: #endif
2257: #ifdef CONFIG_TRACE_IRQFLAGS
2258: memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2259: p->irqtrace.hardirq_disable_ip = _THIS_IP_;
2260: p->irqtrace.softirq_enable_ip = _THIS_IP_;
2261: p->softirqs_enabled = 1;
2262: p->softirq_context = 0;
2263: #endif
2264:
2265: p->pagefault_disabled = 0;
2266:
2267: lockdep_init_task(p);
2268:
2269: p->blocked_on = NULL; /* not blocked yet */
2270: p->blocked_donor = NULL; /* nobody is boosting p yet */
2271:
2272: #ifdef CONFIG_BCACHE
2273: p->sequential_io = 0;
2274: p->sequential_io_avg = 0;
2275: #endif
2276:
2277: unwind_task_init(p);
2278:
2279: /* Perform scheduler related setup. Assign this task to a CPU. */
2280: retval = sched_fork(clone_flags, p);
2281: if (retval)
2282: goto bad_fork_cleanup_policy;
2283:
2284: retval = perf_event_init_task(p, clone_flags);
2285: if (retval)
2286: goto bad_fork_sched_cancel_fork;
2287: retval = audit_alloc(p);
2288: if (retval)
2289: goto bad_fork_cleanup_perf;
2290: /* copy all the process information */
2291: shm_init_task(p);
2292: retval = security_task_alloc(p, clone_flags);
2293: if (retval)
2294: goto bad_fork_cleanup_audit;
2295: retval = copy_semundo(clone_flags, p);
2296: if (retval)
2297: goto bad_fork_cleanup_security;
2298: retval = copy_files(clone_flags, p, args->no_files);
2299: if (retval)
2300: goto bad_fork_cleanup_semundo;
2301: retval = copy_fs(clone_flags, p, args->umh);
2302: if (retval)
2303: goto bad_fork_cleanup_files;
2304: retval = copy_sighand(clone_flags, p);
2305: if (retval)
2306: goto bad_fork_cleanup_fs;
2307: retval = copy_signal(clone_flags, p);
2308: if (retval)
2309: goto bad_fork_cleanup_sighand;
2310: retval = copy_mm(clone_flags, p);
2311: if (retval)
2312: goto bad_fork_cleanup_signal;
2313: retval = copy_namespaces(clone_flags, p);
2314: if (retval)
2315: goto bad_fork_cleanup_mm;
2316: retval = copy_io(clone_flags, p);
2317: if (retval)
2318: goto bad_fork_cleanup_namespaces;
2319: retval = copy_thread(p, args);
2320: if (retval)
2321: goto bad_fork_cleanup_io;
2322:
2323: stackleak_task_init(p);
2324:
2325: if (pid != &init_struct_pid) {
2326: pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2327: args->set_tid_size);
2328: if (IS_ERR(pid)) {
2329: retval = PTR_ERR(pid);
2330: goto bad_fork_cleanup_thread;
2331: }
2332: }
2333:
2334: /*
2335: * This has to happen after we've potentially unshared the file
2336: * descriptor table (so that the pidfd doesn't leak into the child
2337: * if the fd table isn't shared).
2338: */
2339: if (clone_flags & CLONE_PIDFD) {
2340: unsigned flags = PIDFD_STALE;
2341:
2342: if (clone_flags & CLONE_THREAD)
2343: flags |= PIDFD_THREAD;
2344: if (clone_flags & CLONE_PIDFD_AUTOKILL)
2345: flags |= PIDFD_AUTOKILL;
2346:
2347: /*
2348: * Note that no task has been attached to @pid yet indicate
2349: * that via CLONE_PIDFD.
2350: */
2351: retval = pidfd_prepare(pid, flags, &pidfile);
2352: if (retval < 0)
2353: goto bad_fork_free_pid;
2354: pidfd = retval;
2355:
2356: retval = put_user(pidfd, args->pidfd);
2357: if (retval)
2358: goto bad_fork_put_pidfd;
2359: }
2360:
2361: #ifdef CONFIG_BLOCK
2362: p->plug = NULL;
2363: p->flags &= ~PF_BLOCK_TS;
2364: #endif
2365: futex_init_task(p);
2366:
2367: /*
2368: * sigaltstack should be cleared when sharing the same VM
2369: */
2370: if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2371: sas_ss_reset(p);
2372:
2373: /*
2374: * Syscall tracing and stepping should be turned off in the
2375: * child regardless of CLONE_PTRACE.
2376: */
2377: user_disable_single_step(p);
2378: clear_task_syscall_work(p, SYSCALL_TRACE);
2379: #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2380: clear_task_syscall_work(p, SYSCALL_EMU);
2381: #endif
2382: clear_tsk_latency_tracing(p);
2383:
2384: /* ok, now we should be set up.. */
2385: p->pid = pid_nr(pid);
2386: if (clone_flags & CLONE_THREAD) {
2387: p->group_leader = current->group_leader;
2388: p->tgid = current->tgid;
2389: } else {
2390: p->group_leader = p;
2391: p->tgid = p->pid;
2392: }
2393:
2394: p->nr_dirtied = 0;
2395: p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2396: p->dirty_paused_when = 0;
2397:
2398: p->pdeath_signal = 0;
2399: p->task_works = NULL;
2400: clear_posix_cputimers_work(p);
2401:
2402: #ifdef CONFIG_KRETPROBES
2403: p->kretprobe_instances.first = NULL;
2404: #endif
2405: #ifdef CONFIG_RETHOOK
2406: p->rethooks.first = NULL;
2407: #endif
2408:
2409: /*
2410: * Ensure that the cgroup subsystem policies allow the new process to be
2411: * forked. It should be noted that the new process's css_set can be changed
2412: * between here and cgroup_post_fork() if an organisation operation is in
2413: * progress.
2414: */
2415: retval = cgroup_can_fork(p, args);
2416: if (retval)
2417: goto bad_fork_put_pidfd;
2418:
2419: /*
2420: * Now that the cgroups are pinned, re-clone the parent cgroup and put
2421: * the new task on the correct runqueue. All this *before* the task
2422: * becomes visible.
2423: *
2424: * This isn't part of ->can_fork() because while the re-cloning is
2425: * cgroup specific, it unconditionally needs to place the task on a
2426: * runqueue.
2427: */
2428: retval = sched_cgroup_fork(p, args);
2429: if (retval)
2430: goto bad_fork_cancel_cgroup;
2431:
2432: if (need_futex_hash_allocate_default(clone_flags)) {
2433: retval = futex_hash_allocate_default();
2434: if (retval)
2435: goto bad_fork_cancel_cgroup;
2436: /*
2437: * If we fail beyond this point we don't free the allocated
2438: * futex hash map. We assume that another thread will be created
2439: * and makes use of it. The hash map will be freed once the main
2440: * thread terminates.
2441: */
2442: }
2443: /*
2444: * From this point on we must avoid any synchronous user-space
2445: * communication until we take the tasklist-lock. In particular, we do
2446: * not want user-space to be able to predict the process start-time by
2447: * stalling fork(2) after we recorded the start_time but before it is
2448: * visible to the system.
2449: */
2450:
2451: p->start_time = ktime_get_ns();
2452: p->start_boottime = ktime_get_boottime_ns();
2453:
2454: /*
2455: * Make it visible to the rest of the system, but dont wake it up yet.
2456: * Need tasklist lock for parent etc handling!
2457: */
2458: write_lock_irq(&tasklist_lock);
2459:
2460: /* CLONE_PARENT re-uses the old parent */
2461: if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2462: p->real_parent = current->real_parent;
2463: p->parent_exec_id = current->parent_exec_id;
2464: if (clone_flags & CLONE_THREAD)
2465: p->exit_signal = -1;
2466: else
2467: p->exit_signal = current->group_leader->exit_signal;
2468: } else {
2469: p->real_parent = current;
2470: p->parent_exec_id = current->self_exec_id;
2471: p->exit_signal = args->exit_signal;
2472: }
2473:
2474: klp_copy_process(p);
2475:
2476: sched_core_fork(p);
2477:
2478: spin_lock(¤t->sighand->siglock);
2479:
2480: rv_task_fork(p);
2481:
2482: rseq_fork(p, clone_flags);
2483:
2484: /*
2485: * If zap_pid_ns_processes() was called after alloc_pid(), the new
2486: * child missed SIGKILL. If current is not in the same namespace,
2487: * we can't rely on fatal_signal_pending() below.
2488: */
2489: if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2490: retval = -ENOMEM;
2491: goto bad_fork_core_free;
2492: }
2493:
2494: /* Let kill terminate clone/fork in the middle */
2495: if (fatal_signal_pending(current)) {
2496: retval = -EINTR;
2497: goto bad_fork_core_free;
2498: }
2499:
2500: /* No more failure paths after this point. */
2501:
2502: /*
2503: * Copy seccomp details explicitly here, in case they were changed
2504: * before holding sighand lock.
2505: */
2506: copy_seccomp(p);
2507:
2508: if (clone_flags & CLONE_NNP)
2509: task_set_no_new_privs(p);
2510:
2511: init_task_pid_links(p);
2512: if (likely(p->pid)) {
2513: ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2514:
2515: init_task_pid(p, PIDTYPE_PID, pid);
2516: if (thread_group_leader(p)) {
2517: init_task_pid(p, PIDTYPE_TGID, pid);
2518: init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2519: init_task_pid(p, PIDTYPE_SID, task_session(current));
2520:
2521: if (is_child_reaper(pid)) {
2522: struct pid_namespace *ns = ns_of_pid(pid);
2523:
2524: ASSERT_EXCLUSIVE_WRITER(ns->child_reaper);
2525: WRITE_ONCE(ns->child_reaper, p);
2526: p->signal->flags |= SIGNAL_UNKILLABLE;
2527: }
2528: p->signal->shared_pending.signal = delayed.signal;
2529: p->signal->tty = tty_kref_get(current->signal->tty);
2530: /*
2531: * Inherit has_child_subreaper flag under the same
2532: * tasklist_lock with adding child to the process tree
2533: * for propagate_has_child_subreaper optimization.
2534: */
2535: p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2536: p->real_parent->signal->is_child_subreaper;
2537: if (clone_flags & CLONE_AUTOREAP)
2538: p->signal->autoreap = 1;
2539: list_add_tail(&p->sibling, &p->real_parent->children);
2540: list_add_tail_rcu(&p->tasks, &init_task.tasks);
2541: attach_pid(p, PIDTYPE_TGID);
2542: attach_pid(p, PIDTYPE_PGID);
2543: attach_pid(p, PIDTYPE_SID);
2544: __this_cpu_inc(process_counts);
2545: } else {
2546: current->signal->nr_threads++;
2547: current->signal->quick_threads++;
2548: atomic_inc(¤t->signal->live);
2549: refcount_inc(¤t->signal->sigcnt);
2550: task_join_group_stop(p);
2551: list_add_tail_rcu(&p->thread_node,
2552: &p->signal->thread_head);
2553: }
2554: attach_pid(p, PIDTYPE_PID);
2555: nr_threads++;
2556: }
2557: total_forks++;
2558: hlist_del_init(&delayed.node);
2559: spin_unlock(¤t->sighand->siglock);
2560: syscall_tracepoint_update(p);
2561: write_unlock_irq(&tasklist_lock);
2562:
2563: if (pidfile)
2564: fd_install(pidfd, pidfile);
2565:
2566: proc_fork_connector(p);
2567: /*
2568: * sched_ext needs @p to be associated with its cgroup in its post_fork
2569: * hook. cgroup_post_fork() should come before sched_post_fork().
2570: */
2571: cgroup_post_fork(p, args);
2572: sched_post_fork(p);
2573: perf_event_fork(p);
2574:
2575: trace_task_newtask(p, clone_flags);
2576: uprobe_copy_process(p, clone_flags);
2577: user_events_fork(p, clone_flags);
2578:
2579: copy_oom_score_adj(clone_flags, p);
2580:
2581: return p;
2582:
2583: bad_fork_core_free:
2584: sched_core_free(p);
2585: spin_unlock(¤t->sighand->siglock);
2586: write_unlock_irq(&tasklist_lock);
2587: bad_fork_cancel_cgroup:
2588: cgroup_cancel_fork(p, args);
2589: bad_fork_put_pidfd:
2590: if (clone_flags & CLONE_PIDFD) {
2591: fput(pidfile);
2592: put_unused_fd(pidfd);
2593: }
2594: bad_fork_free_pid:
2595: if (pid != &init_struct_pid)
2596: free_pid(pid);
2597: bad_fork_cleanup_thread:
2598: exit_thread(p);
2599: bad_fork_cleanup_io:
2600: if (p->io_context)
2601: exit_io_context(p);
2602: bad_fork_cleanup_namespaces:
2603: exit_nsproxy_namespaces(p);
2604: bad_fork_cleanup_mm:
2605: if (p->mm) {
2606: mm_clear_owner(p->mm, p);
2607: mmput(p->mm);
2608: }
2609: bad_fork_cleanup_signal:
2610: if (!(clone_flags & CLONE_THREAD))
2611: free_signal_struct(p->signal);
2612: bad_fork_cleanup_sighand:
2613: __cleanup_sighand(p->sighand);
2614: bad_fork_cleanup_fs:
2615: exit_fs(p); /* blocking */
2616: bad_fork_cleanup_files:
2617: exit_files(p); /* blocking */
2618: bad_fork_cleanup_semundo:
2619: exit_sem(p);
2620: bad_fork_cleanup_security:
2621: security_task_free(p);
2622: bad_fork_cleanup_audit:
2623: audit_free(p);
2624: bad_fork_cleanup_perf:
2625: perf_event_free_task(p);
2626: bad_fork_sched_cancel_fork:
2627: sched_cancel_fork(p);
2628: bad_fork_cleanup_policy:
2629: lockdep_free_task(p);
2630: #ifdef CONFIG_NUMA
2631: mpol_put(p->mempolicy);
2632: #endif
2633: bad_fork_cleanup_delayacct:
2634: io_uring_free(p);
2635: delayacct_tsk_free(p);
2636: bad_fork_cleanup_count:
2637: dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2638: exit_cred_namespaces(p);
2639: exit_creds(p);
2640: bad_fork_free:
2641: WRITE_ONCE(p->__state, TASK_DEAD);
2642: exit_task_stack_account(p);
2643: put_task_stack(p);
2644: delayed_free_task(p);
2645: fork_out:
2646: spin_lock_irq(¤t->sighand->siglock);
2647: hlist_del_init(&delayed.node);
2648: spin_unlock_irq(¤t->sighand->siglock);
2649: return ERR_PTR(retval);
2650: }
SourceFile:kernel/fork.c]
|
| 207/2 |
2026/09/23 19:55 |
llm |
expert |
0m
Model:
Tokens:
input: 36822
output: 27
thoughts: 0
|
| 208/2 |
2026/09/23 19:55 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:memcpy\(mm, oldmm Count:5]
Results:
|
| 209/2 |
2026/09/23 20:05 |
llm |
expert |
0m
Model:
Tokens:
input: 36884
output: 38
thoughts: 0
|
| 210/2 |
2026/09/23 20:05 |
tool |
git-log |
0m
Args: map[CodeRegexp:memcpy\(mm, oldmm Count:5 PathPrefix:kernel/fork.c]
Results: map[Output:a0a7ec308f1b [PATCH] unshare system call -v5: unshare vm
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 211/2 |
2026/09/23 20:06 |
llm |
expert |
0m
Model:
Tokens:
input: 36984
output: 42
thoughts: 0
|
| 212/2 |
2026/09/23 20:06 |
tool |
git-log |
0m
Args: map[CodeRegexp:list_del\(&mm->mmlist\) Count:5 PathPrefix:kernel/fork.c]
Results: map[Output:ec8d7c14ea14 mm, oom_reaper: do not mmput synchronously from the oom reaper context
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 213/2 |
2026/09/23 20:06 |
llm |
expert |
0m
Model:
Tokens:
input: 37092
output: 37
thoughts: 0
|
| 214/2 |
2026/09/23 20:06 |
tool |
git-log |
0m
Args: map[MessageRegexps:[KCSAN dup_mm] PathPrefix:kernel/fork.c]
Results:
|
| 215/2 |
2026/09/23 20:06 |
llm |
expert |
0m
Model:
Tokens:
input: 37142
output: 32
thoughts: 0
|
| 216/2 |
2026/09/23 20:07 |
tool |
git-log |
0m
Args: map[MessageRegexps:[dup_mm memcpy] PathPrefix:kernel/]
Results: map[Output:355627f51897 mm, uprobes: fix multiple free of ->uprobes_state.xol_area
2b7e8665b4ff fork: fix incorrect fput of ->exe_file causing use-after-free
4f7d461433bb fork: copy mm's vm usage counters under mmap_sem
404351e67a9f [PATCH] mm: mm_init set_mm_counters
]
|
| 217/2 |
2026/09/23 20:07 |
llm |
expert |
0m
Model:
Tokens:
input: 37301
output: 26
thoughts: 0
|
| 218/2 |
2026/09/23 20:07 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 4f7d461433bb4a4deee61baefdac6cd1a1ecb546
Author: Vladimir Davydov <vdavydov.dev@gmail.com>
Date: Fri Aug 8 14:22:01 2014 -0700
fork: copy mm's vm usage counters under mmap_sem
If a forking process has a thread calling (un)mmap (silly but still),
the child process may have some of its mm's vm usage counters (total_vm
and friends) screwed up, because currently they are copied from oldmm
w/o holding any locks (memcpy in dup_mm).
This patch moves the counters initialization to dup_mmap() to be called
under oldmm->mmap_sem, which eliminates any possibility of race.
Signed-off-by: Vladimir Davydov <vdavydov@parallels.com>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: David Rientjes <rientjes@google.com>
Cc: Christoph Lameter <cl@linux.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/kernel/fork.c b/kernel/fork.c
index 5a547a59a38a..aff84f84b0d3 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -374,6 +374,11 @@ static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
*/
down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
+ mm->total_vm = oldmm->total_vm;
+ mm->shared_vm = oldmm->shared_vm;
+ mm->exec_vm = oldmm->exec_vm;
+ mm->stack_vm = oldmm->stack_vm;
+
rb_link = &mm->mm_rb.rb_node;
rb_parent = NULL;
pprev = &mm->mmap;
]
|
| 219/2 |
2026/09/23 20:07 |
llm |
expert |
0m
Model:
Tokens:
input: 37905
output: 32
thoughts: 0
|
| 220/2 |
2026/09/23 20:07 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_init]
Results: map[SourceCode:1091: static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
1092: {
1093: mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
1094: mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
1095: atomic_set(&mm->mm_users, 1);
1096: atomic_set(&mm->mm_count, 1);
1097: seqcount_init(&mm->write_protect_seq);
1098: mmap_init_lock(mm);
1099: INIT_LIST_HEAD(&mm->mmlist);
1100: mm_pgtables_bytes_init(mm);
1101: mm->map_count = 0;
1102: mm->locked_vm = 0;
1103: atomic64_set(&mm->pinned_vm, 0);
1104: memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1105: spin_lock_init(&mm->page_table_lock);
1106: spin_lock_init(&mm->arg_lock);
1107: mm_init_cpumask(mm);
1108: mm_init_aio(mm);
1109: mm_init_owner(mm, p);
1110: mm_pasid_init(mm);
1111: RCU_INIT_POINTER(mm->exe_file, NULL);
1112: mmu_notifier_subscriptions_init(mm);
1113: init_tlb_flush_pending(mm);
1114: #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
1115: mm->pmd_huge_pte = NULL;
1116: #endif
1117: mm_init_uprobes_state(mm);
1118: hugetlb_count_init(mm);
1119: futex_mm_init(mm);
1120:
1121: mm_flags_clear_all(mm);
1122: if (current->mm) {
1123: unsigned long flags = __mm_flags_get_word(current->mm);
1124:
1125: __mm_flags_overwrite_word(mm, mmf_init_legacy_flags(flags));
1126: mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1127: } else {
1128: __mm_flags_overwrite_word(mm, coredump_filter);
1129: mm->def_flags = 0;
1130: }
1131:
1132: if (mm_alloc_pgd(mm))
1133: goto fail_mm_init;
1134:
1135: if (mm_alloc_id(mm))
1136: goto fail_noid;
1137:
1138: if (init_new_context(p, mm))
1139: goto fail_nocontext;
1140:
1141: if (mm_alloc_cid(mm, p))
1142: goto fail_cid;
1143:
1144: if (mm_alloc_sched(mm))
1145: goto fail_sched;
1146:
1147: if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
1148: NR_MM_COUNTERS))
1149: goto fail_pcpu;
1150:
1151: lru_gen_init_mm(mm);
1152: return mm;
1153:
1154: fail_pcpu:
1155: mm_destroy_sched(mm);
1156: fail_sched:
1157: mm_destroy_cid(mm);
1158: fail_cid:
1159: destroy_context(mm);
1160: fail_nocontext:
1161: mm_free_id(mm);
1162: fail_noid:
1163: mm_free_pgd(mm);
1164: fail_mm_init:
1165: free_mm(mm);
1166: return NULL;
1167: }
SourceFile:kernel/fork.c]
|
| 221/2 |
2026/09/23 20:07 |
llm |
expert |
0m
Model:
Tokens:
input: 39192
output: 33
thoughts: 0
|
| 222/2 |
2026/09/23 20:08 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mmap]
Results: map[SourceCode:1708: __latent_entropy int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
1709: {
1710: struct vm_area_struct *mpnt, *tmp;
1711: int retval;
1712: unsigned long charge = 0;
1713: LIST_HEAD(uf);
1714: VMA_ITERATOR(vmi, mm, 0);
1715:
1716: if (mmap_write_lock_killable(oldmm))
1717: return -EINTR;
1718: flush_cache_dup_mm(oldmm);
1719: uprobe_dup_mmap(oldmm, mm);
1720: /*
1721: * Not linked in yet - no deadlock potential:
1722: */
1723: mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
1724:
1725: /* No ordering required: file already has been exposed. */
1726: dup_mm_exe_file(mm, oldmm);
1727:
1728: mm->total_vm = oldmm->total_vm;
1729: mm->data_vm = oldmm->data_vm;
1730: mm->exec_vm = oldmm->exec_vm;
1731: mm->stack_vm = oldmm->stack_vm;
1732:
1733: /* Use __mt_dup() to efficiently build an identical maple tree. */
1734: retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
1735: if (unlikely(retval))
1736: goto out;
1737:
1738: mt_clear_in_rcu(vmi.mas.tree);
1739: for_each_vma(vmi, mpnt) {
1740: struct file *file;
1741:
1742: retval = vma_start_write_killable(mpnt);
1743: if (retval < 0)
1744: goto loop_out;
1745: if (vma_test(mpnt, VMA_DONTCOPY_BIT)) {
1746: retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
1747: mpnt->vm_end, GFP_KERNEL);
1748: if (retval)
1749: goto loop_out;
1750:
1751: vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
1752: continue;
1753: }
1754: charge = 0;
1755: if (vma_test(mpnt, VMA_ACCOUNT_BIT)) {
1756: unsigned long len = vma_pages(mpnt);
1757:
1758: if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
1759: goto fail_nomem;
1760: charge = len;
1761: }
1762:
1763: tmp = vm_area_dup(mpnt);
1764: if (!tmp)
1765: goto fail_nomem;
1766: retval = vma_dup_policy(mpnt, tmp);
1767: if (retval)
1768: goto fail_nomem_policy;
1769: tmp->vm_mm = mm;
1770: retval = dup_userfaultfd(tmp, &uf);
1771: if (retval)
1772: goto fail_nomem_anon_vma_fork;
1773:
1774: if (vma_test(tmp, VMA_WIPEONFORK_BIT)) {
1775: /*
1776: * VMA_WIPEONFORK_BIT gets a clean slate in the child.
1777: * Don't prepare anon_vma until fault since we don't
1778: * copy page for current vma.
1779: */
1780: tmp->anon_vma = NULL;
1781: } else if (anon_vma_fork(tmp, mpnt))
1782: goto fail_nomem_anon_vma_fork;
1783:
1784: vma_start_write(tmp);
1785: vma_clear_flags_mask(tmp, VMA_LOCKED_MASK);
1786: /*
1787: * Copy/update hugetlb private vma information.
1788: */
1789: if (is_vm_hugetlb_page(tmp))
1790: hugetlb_dup_vma_private(tmp);
1791:
1792: /*
1793: * Link the vma into the MT. After using __mt_dup(), memory
1794: * allocation is not necessary here, so it cannot fail.
1795: */
1796: vma_iter_bulk_store(&vmi, tmp);
1797:
1798: mm->map_count++;
1799:
1800: if (tmp->vm_ops && tmp->vm_ops->open)
1801: tmp->vm_ops->open(tmp);
1802:
1803: file = tmp->vm_file;
1804: if (file) {
1805: struct address_space *mapping = file->f_mapping;
1806:
1807: get_file(file);
1808: i_mmap_lock_write(mapping);
1809: if (vma_is_shared_maywrite(tmp))
1810: mapping_allow_writable(mapping);
1811: flush_dcache_mmap_lock(mapping);
1812: /* insert tmp into the share list, just after mpnt */
1813: mapping_rmap_tree_insert_after(tmp, mpnt, mapping);
1814: flush_dcache_mmap_unlock(mapping);
1815: i_mmap_unlock_write(mapping);
1816: }
1817:
1818: if (!vma_test(tmp, VMA_WIPEONFORK_BIT))
1819: retval = copy_page_range(tmp, mpnt);
1820:
1821: if (retval) {
1822: mpnt = vma_next(&vmi);
1823: goto loop_out;
1824: }
1825: }
1826: /* a new mm has just been created */
1827: retval = arch_dup_mmap(oldmm, mm);
1828: loop_out:
1829: vma_iter_free(&vmi);
1830: if (!retval) {
1831: mt_set_in_rcu(vmi.mas.tree);
1832: ksm_fork(mm, oldmm);
1833: khugepaged_fork(mm, oldmm);
1834: } else {
1835: unsigned long end;
1836:
1837: /*
1838: * The entire maple tree has already been duplicated, but
1839: * replacing the vmas failed at mpnt (which could be NULL if
1840: * all were allocated but the last vma was not fully set up).
1841: * Use the start address of the failure point to clean up the
1842: * partially initialized tree.
1843: */
1844: if (!mm->map_count) {
1845: /* zero vmas were written to the new tree. */
1846: end = 0;
1847: } else if (mpnt) {
1848: /* partial tree failure */
1849: end = mpnt->vm_start;
1850: } else {
1851: /* All vmas were written to the new tree */
1852: end = ULONG_MAX;
1853: }
1854:
1855: /* Hide mm from oom killer because the memory is being freed */
1856: mm_flags_set(MMF_OOM_SKIP, mm);
1857: if (end) {
1858: vma_iter_set(&vmi, 0);
1859: tmp = vma_next(&vmi);
1860: UNMAP_STATE(unmap, &vmi, /* first = */ tmp,
1861: /* vma_start = */ 0, /* vma_end = */ end,
1862: /* prev = */ NULL, /* next = */ NULL);
1863:
1864: /*
1865: * Don't iterate over vmas beyond the failure point for
1866: * both unmap_vma() and free_pgtables().
1867: */
1868: unmap.tree_end = end;
1869: flush_cache_mm(mm);
1870: unmap_region(&unmap);
1871: charge = tear_down_vmas(mm, &vmi, tmp, end);
1872: vm_unacct_memory(charge);
1873: }
1874: __mt_destroy(&mm->mm_mt);
1875: /*
1876: * The mm_struct is going to exit, but the locks will be dropped
1877: * first. Set the mm_struct as unstable is advisable as it is
1878: * not fully initialised.
1879: */
1880: mm_flags_set(MMF_UNSTABLE, mm);
1881: }
1882: out:
1883: mmap_write_unlock(mm);
1884: flush_tlb_mm(oldmm);
1885: mmap_write_unlock(oldmm);
1886: if (!retval)
1887: dup_userfaultfd_complete(&uf);
1888: else
1889: dup_userfaultfd_fail(&uf);
1890: return retval;
1891:
1892: fail_nomem_anon_vma_fork:
1893: mpol_put(vma_policy(tmp));
1894: fail_nomem_policy:
1895: vm_area_free(tmp);
1896: fail_nomem:
1897: retval = -ENOMEM;
1898: vm_unacct_memory(charge);
1899: goto loop_out;
1900: }
SourceFile:mm/mmap.c]
|
| 223/2 |
2026/09/23 20:08 |
llm |
expert |
0m
Model:
Tokens:
input: 42219
output: 34
thoughts: 0
|
| 224/2 |
2026/09/23 20:08 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/mmap.c Name:exit_mmap]
Results: map[SourceCode:1287: /* Release all mmaps. */
1288: void exit_mmap(struct mm_struct *mm)
1289: {
1290: struct mmu_gather tlb;
1291: struct vm_area_struct *vma;
1292: unsigned long nr_accounted = 0;
1293: VMA_ITERATOR(vmi, mm, 0);
1294: struct unmap_desc unmap;
1295:
1296: /* mm's last user has gone, and its about to be pulled down */
1297: mmu_notifier_release(mm);
1298:
1299: mmap_read_lock(mm);
1300: arch_exit_mmap(mm);
1301:
1302: vma = vma_next(&vmi);
1303: if (!vma) {
1304: /* Can happen if dup_mmap() received an OOM */
1305: mmap_read_unlock(mm);
1306: mmap_write_lock(mm);
1307: goto destroy;
1308: }
1309:
1310: unmap_all_init(&unmap, &vmi, vma);
1311: flush_cache_mm(mm);
1312: tlb_gather_mmu_fullmm(&tlb, mm);
1313: /* update_hiwater_rss(mm) here? but nobody should be looking */
1314: /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
1315: unmap_vmas(&tlb, &unmap);
1316: mmap_read_unlock(mm);
1317:
1318: /*
1319: * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
1320: * because the memory has been already freed.
1321: */
1322: mm_flags_set(MMF_OOM_SKIP, mm);
1323: mmap_write_lock(mm);
1324: unmap.mm_wr_locked = true;
1325: mt_clear_in_rcu(&mm->mm_mt);
1326: unmap_pgtable_init(&unmap, &vmi);
1327: free_pgtables(&tlb, &unmap);
1328: tlb_finish_mmu(&tlb);
1329:
1330: /*
1331: * Walk the list again, actually closing and freeing it, with preemption
1332: * enabled, without holding any MM locks besides the unreachable
1333: * mmap_write_lock.
1334: */
1335: nr_accounted = tear_down_vmas(mm, &vmi, vma, ULONG_MAX);
1336:
1337: destroy:
1338: __mt_destroy(&mm->mm_mt);
1339: trace_exit_mmap(mm);
1340: mmap_write_unlock(mm);
1341: vm_unacct_memory(nr_accounted);
1342: }
SourceFile:mm/mmap.c]
|
| 225/2 |
2026/09/23 20:08 |
llm |
expert |
0m
Model:
Tokens:
input: 43170
output: 31
thoughts: 0
|
| 226/2 |
2026/09/23 20:08 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:kernel/fork.c Name:vfork]
Results: map[SourceCode: SourceFile:]
|
| 227/2 |
2026/09/23 20:08 |
llm |
expert |
0m
Model:
Tokens:
input: 43222
output: 23
thoughts: 0
|
| 228/2 |
2026/09/23 20:08 |
tool |
grepper |
0m
Args: map[Expression:SYSCALL_DEFINE.*\(vfork]
Results: map[Output:kernel/fork.c=2850=SYSCALL_DEFINE0(fork)
--
kernel/fork.c-2865-#ifdef __ARCH_WANT_SYS_VFORK
kernel/fork.c:2866:SYSCALL_DEFINE0(vfork)
kernel/fork.c-2867-{
]
|
| 229/2 |
2026/09/23 20:09 |
llm |
expert |
0m
Model:
Tokens:
input: 43338
output: 34
thoughts: 0
|
| 230/2 |
2026/09/23 20:09 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:2860 LineCount:25]
Results: map[Contents:2860: return -EINVAL;
2861: #endif
2862: }
2863: #endif
2864:
2865: #ifdef __ARCH_WANT_SYS_VFORK
2866: SYSCALL_DEFINE0(vfork)
2867: {
2868: struct kernel_clone_args args = {
2869: .flags = CLONE_VFORK | CLONE_VM,
2870: .exit_signal = SIGCHLD,
2871: };
2872:
2873: return kernel_clone(&args);
2874: }
2875: #endif
2876:
2877: #ifdef __ARCH_WANT_SYS_CLONE
2878: #ifdef CONFIG_CLONE_BACKWARDS
2879: SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2880: int __user *, parent_tidptr,
2881: unsigned long, tls,
2882: int __user *, child_tidptr)
2883: #elif defined(CONFIG_CLONE_BACKWARDS2)
2884: SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
]
|
| 231/2 |
2026/09/23 20:09 |
llm |
expert |
0m
Model:
Tokens:
input: 43739
output: 32
thoughts: 0
|
| 232/2 |
2026/09/23 20:09 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_release]
Results: map[SourceCode:1465: /* Please note the differences between mmput and mm_release.
1466: * mmput is called whenever we stop holding onto a mm_struct,
1467: * error success whatever.
1468: *
1469: * mm_release is called after a mm_struct has been removed
1470: * from the current process.
1471: *
1472: * This difference is important for error handling, when we
1473: * only half set up a mm_struct for a new process and need to restore
1474: * the old one. Because we mmput the new mm_struct before
1475: * restoring the old one. . .
1476: * Eric Biederman 10 January 1998
1477: */
1478: static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1479: {
1480: uprobe_free_utask(tsk);
1481:
1482: /* Get rid of any cached register state */
1483: deactivate_mm(tsk, mm);
1484:
1485: /*
1486: * Signal userspace if we're not exiting with a core dump
1487: * because we want to leave the value intact for debugging
1488: * purposes.
1489: */
1490: if (tsk->clear_child_tid) {
1491: if (atomic_read(&mm->mm_users) > 1) {
1492: /*
1493: * We don't check the error code - if userspace has
1494: * not set up a proper pointer then tough luck.
1495: */
1496: put_user(0, tsk->clear_child_tid);
1497: do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1498: 1, NULL, NULL, 0, 0);
1499: }
1500: tsk->clear_child_tid = NULL;
1501: }
1502:
1503: /*
1504: * All done, finally we can wake up parent and return this mm to him.
1505: * Also kthread_stop() uses this completion for synchronization.
1506: */
1507: if (tsk->vfork_done)
1508: complete_vfork_done(tsk);
1509: }
SourceFile:kernel/fork.c]
|
| 233/2 |
2026/09/23 20:09 |
llm |
expert |
0m
Model:
Tokens:
input: 44479
output: 41
thoughts: 0
|
| 234/2 |
2026/09/23 20:10 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:5 Name:complete_vfork_done]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:mm_release SourceFile:kernel/fork.c SourceLine:1508 SourceSnippet:1503: /*
1504: * All done, finally we can wake up parent and return this mm to him.
1505: * Also kthread_stop() uses this completion for synchronization.
1506: */
1507: if (tsk->vfork_done)
1508: complete_vfork_done(tsk);
1509: }
]] TruncatedOutput:false]
|
| 235/2 |
2026/09/23 20:10 |
llm |
expert |
0m
Model:
Tokens:
input: 44692
output: 35
thoughts: 0
|
| 236/2 |
2026/09/23 20:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:complete_vfork_done]
Results: map[SourceCode:1432: static void complete_vfork_done(struct task_struct *tsk)
1433: {
1434: struct completion *vfork;
1435:
1436: task_lock(tsk);
1437: vfork = tsk->vfork_done;
1438: if (likely(vfork)) {
1439: tsk->vfork_done = NULL;
1440: complete(vfork);
1441: }
1442: task_unlock(tsk);
1443: }
SourceFile:kernel/fork.c]
|
| 237/2 |
2026/09/23 20:10 |
llm |
expert |
0m
Model:
Tokens:
input: 44909
output: 38
thoughts: 0
|
| 238/2 |
2026/09/23 20:11 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:5 Name:mm_release]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:mm_exit_exec_release SourceFile:kernel/fork.c SourceLine:1514 SourceSnippet:1511: void mm_exit_exec_release(struct task_struct *tsk, struct mm_struct *mm)
1512: {
1513: futex_exit_exec_release(tsk);
1514: mm_release(tsk, mm);
1515: }
]] TruncatedOutput:false]
|
| 239/2 |
2026/09/23 20:11 |
llm |
expert |
0m
Model:
Tokens:
input: 45102
output: 36
thoughts: 0
|
| 240/2 |
2026/09/23 20:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_exit_exec_release]
Results: map[SourceCode:1511: void mm_exit_exec_release(struct task_struct *tsk, struct mm_struct *mm)
1512: {
1513: futex_exit_exec_release(tsk);
1514: mm_release(tsk, mm);
1515: }
SourceFile:kernel/fork.c]
|
| 241/2 |
2026/09/23 20:11 |
llm |
expert |
0m
Model:
Tokens:
input: 45245
output: 42
thoughts: 0
|
| 242/2 |
2026/09/23 20:11 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:5 Name:mm_exit_exec_release]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:exec_mmap SourceFile:fs/exec.c SourceLine:859 SourceSnippet: 854:
855: /* Notify parent that we're no longer interested in the old VM */
856: tsk = current;
857: old_mm = current->mm;
858: /* Clean up futexes and release the mm */
859: mm_exit_exec_release(tsk, old_mm);
860:
861: ret = down_write_killable(&tsk->signal->exec_update_lock);
862: if (ret)
863: return ret;
864:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:exit_mm SourceFile:kernel/exit.c SourceLine:588 SourceSnippet: 583: */
584: static void exit_mm(void)
585: {
586: struct mm_struct *mm = current->mm;
587:
588: mm_exit_exec_release(current, mm);
589: if (!mm)
590: return;
591:
592: exit_mm_sched_cache(mm);
593:
]] TruncatedOutput:false]
|
| 243/2 |
2026/09/23 20:11 |
llm |
expert |
0m
Model:
Tokens:
input: 45691
output: 44
thoughts: 0
|
| 244/2 |
2026/09/23 20:12 |
tool |
git-log |
0m
Args: map[CodeRegexp:CLONE_VM Count:10 PathPrefix:kernel/fork.c Since:5 years]
Results: map[Output:b61b6f95d672 futex: Also allocate private hash on vfork()
6b1c66c9cca9 exec_state: relocate dumpable information
ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
f7071db2fe3d fork: kill the pointless lower_32_bits() in create_io_thread(), kernel_thread(), and user_mode_thread()
7c4f75a21f63 futex: Allow automatic allocation of process wide futex hash
61dd3f246b3a mm/mglru: add CONFIG_LRU_GEN_WALKS_MMU
2b5f9dad32ed fs/exec: switch timens when a task gets a new mm
bd74fdaea146 mm: multi-gen LRU: support page table walks
33a2d6bc3480 Revert "fs/exec: allow to unshare a time namespace on vfork+exec"
133e2d3e81de fs/exec: allow to unshare a time namespace on vfork+exec
]
|
| 245/2 |
2026/09/23 20:12 |
llm |
expert |
0m
Model:
Tokens:
input: 46018
output: 36
thoughts: 0
|
| 246/2 |
2026/09/23 20:12 |
tool |
git-log |
0m
Args: map[CodeRegexp:wait_for_vfork_done PathPrefix:kernel/fork.c]
Results: map[Output:9f5325aa3727 kernel/fork.c: check error and return early
d68b46fe16ad vfork: make it killable
]
|
| 247/2 |
2026/09/23 20:12 |
llm |
expert |
0m
Model:
Tokens:
input: 46108
output: 25
thoughts: 0
|
| 248/2 |
2026/09/23 20:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d68b46fe16ad59b3a5f51ec73daaa5dc06753798
Author: Oleg Nesterov <oleg@redhat.com>
Date: Mon Mar 5 14:59:13 2012 -0800
vfork: make it killable
Make vfork() killable.
Change do_fork(CLONE_VFORK) to do wait_for_completion_killable(). If it
fails we do not return to the user-mode and never touch the memory shared
with our child.
However, in this case we should clear child->vfork_done before return, we
use task_lock() in do_fork()->wait_for_vfork_done() and
complete_vfork_done() to serialize with each other.
Note: now that we use task_lock() we don't really need completion, we
could turn task->vfork_done into "task_struct *wake_up_me" but this needs
some complications.
NOTE: this and the next patches do not affect in-kernel users of
CLONE_VFORK, kernel threads run with all signals ignored including
SIGKILL/SIGSTOP.
However this is obviously the user-visible change. Not only a fatal
signal can kill the vforking parent, a sub-thread can do execve or
exit_group() and kill the thread sleeping in vfork().
Signed-off-by: Oleg Nesterov <oleg@redhat.com>
Acked-by: Tejun Heo <tj@kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/include/linux/sched.h b/include/linux/sched.h
index 1b25a37f2aee..b6467711f12e 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -2372,7 +2372,7 @@ static inline int thread_group_empty(struct task_struct *p)
* Protects ->fs, ->files, ->mm, ->group_info, ->comm, keyring
* subscriptions and synchronises with wait4(). Also used in procfs. Also
* pins the final release of task.io_context. Also protects ->cpuset and
- * ->cgroup.subsys[].
+ * ->cgroup.subsys[]. And ->vfork_done.
*
* Nests both inside and outside of read_lock(&tasklist_lock).
* It must not be nested with write_lock_irq(&tasklist_lock),
diff --git a/kernel/fork.c b/kernel/fork.c
index cf3d96379608..892c534ce6e3 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -670,10 +670,34 @@ struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
void complete_vfork_done(struct task_struct *tsk)
{
- struct completion *vfork_done = tsk->vfork_done;
+ struct completion *vfork;
- tsk->vfork_done = NULL;
- complete(vfork_done);
+ task_lock(tsk);
+ vfork = tsk->vfork_done;
+ if (likely(vfork)) {
+ tsk->vfork_done = NULL;
+ complete(vfork);
+ }
+ task_unlock(tsk);
+}
+
+static int wait_for_vfork_done(struct task_struct *child,
+ struct completion *vfork)
+{
+ int killed;
+
+ freezer_do_not_count();
+ killed = wait_for_completion_killable(vfork);
+ freezer_count();
+
+ if (killed) {
+ task_lock(child);
+ child->vfork_done = NULL;
+ task_unlock(child);
+ }
+
+ put_task_struct(child);
+ return killed;
}
/* Please note the differences between mmput and mm_release.
@@ -717,7 +741,8 @@ void mm_release(struct task_struct *tsk, struct mm_struct *mm)
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
- * trouble otherwise. Userland only wants this done for a sys_exit.
+ * trouble, say, a killed vfork parent shouldn't touch this mm.
+ * Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid) {
if (!(tsk->flags & PF_SIGNALED) &&
@@ -1551,6 +1576,7 @@ long do_fork(unsigned long clone_flags,
if (clone_flags & CLONE_VFORK) {
p->vfork_done = &vfork;
init_completion(&vfork);
+ get_task_struct(p);
}
/*
@@ -1568,10 +1594,8 @@ long do_fork(unsigned long clone_flags,
ptrace_event(trace, nr);
if (clone_flags & CLONE_VFORK) {
- freezer_do_not_count();
- wait_for_completion(&vfork);
- freezer_count();
- ptrace_event(PTRACE_EVENT_VFORK_DONE, nr);
+ if (!wait_for_vfork_done(p, &vfork))
+ ptrace_event(PTRACE_EVENT_VFORK_DONE, nr);
}
} else {
nr = PTR_ERR(p);
]
|
| 249/2 |
2026/09/23 20:13 |
llm |
expert |
0m
Model:
Tokens:
input: 47688
output: 29
thoughts: 0
|
| 250/2 |
2026/09/23 20:13 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:wait_for_vfork_done Count:5]
Results:
|
| 251/2 |
2026/09/23 20:23 |
llm |
expert |
0m
Model:
Tokens:
input: 47752
output: 32
thoughts: 0
|
| 252/2 |
2026/09/23 20:23 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_mm]
Results: map[SourceCode:1568: static int copy_mm(u64 clone_flags, struct task_struct *tsk)
1569: {
1570: struct mm_struct *mm, *oldmm;
1571:
1572: tsk->min_flt = tsk->maj_flt = 0;
1573: tsk->nvcsw = tsk->nivcsw = 0;
1574: #ifdef CONFIG_DETECT_HUNG_TASK
1575: tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1576: tsk->last_switch_time = 0;
1577: #endif
1578:
1579: tsk->mm = NULL;
1580: tsk->active_mm = NULL;
1581:
1582: /*
1583: * Are we cloning a kernel thread?
1584: *
1585: * We need to steal a active VM for that..
1586: */
1587: oldmm = current->mm;
1588: if (!oldmm)
1589: return 0;
1590:
1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
1597: return -ENOMEM;
1598: }
1599:
1600: tsk->mm = mm;
1601: tsk->active_mm = mm;
1602: return 0;
1603: }
SourceFile:kernel/fork.c]
|
| 253/2 |
2026/09/23 20:23 |
llm |
expert |
0m
Model:
Tokens:
input: 48295
output: 710
thoughts: 0
|
| 254/2 |
2026/09/23 20:24 |
tool |
codeexpert |
15m
Args: map[Question:Consider `vfork()`.
Task A calls `vfork()`:
- `clone_flags = CLONE_VFORK | CLONE_VM`
- In `copy_mm()`: `oldmm = current->mm; mmget(oldmm); mm = oldmm; tsk->mm = mm;`
- Task A waits in `wait_for_vfork_done()`: `wait_for_completion_state(&vfork, TASK_KILLABLE|TASK_FREEZABLE)`.
Now Task B is the vfork child, sharing `oldmm`. Task B has `mm_users` incremented from 1 to 2 by `mmget(oldmm)`.
Suppose Task A is killed by a fatal signal (e.g. SIGKILL sent to Task A):
`wait_for_completion_state(&vfork, ...)` in Task A returns non-zero (killed).
Task A wakes up, proceeds in `kernel_clone()`, and exits!
When Task A exits:
In `exit_mm()`:
Task A does:
`current->mm = NULL;`
`mmput(mm);` -> `atomic_dec_and_test(&mm->mm_users)` -> drops `mm_users` from 2 to 1! Task A does NOT call `__mmput`!
Wait, but if Task B then exits or what?
What if Task B is NOT a vfork child, but Task A was the vfork child?
Suppose Task B is the parent in vfork, and Task A is the vfork child?
If Task B calls `vfork()`: Task B sleeps. Task A is the child.
Task A exits (`do_exit`): in `mm_release()`: `tsk->vfork_done` is completed, waking Task B.
Then Task A calls `exit_mm()`: `atomic_dec_and_test(&mm->mm_users)`: drops `mm_users` from 2 to 1.
What if Task B wakes up before Task A calls `exit_mm()`?
Task B wakes up from `wait_for_vfork_done()`. Task B returns to userspace!
Then Task B calls `sys_clone()` without `CLONE_VM`!
Now Task B has `current->mm == oldmm`.
Task A is still in `exit_mm()`:
Task A calls `mmput(mm)`.
Wait! If Task B is alive, `mm_users` is at least 1 (from Task B).
When Task A calls `mmput(mm)`, `mm_users` was 2 (1 for Task A, 1 for Task B).
When Task A calls `mmput(mm)`, `atomic_dec_and_test` drops it to 1! It does NOT drop to 0!
So how can `__mmput` be called in Task A?
Wait, what if Task B is the child, or what if `atomic_dec_and_test` dropped to 0?
Can you analyze how `mmput(mm)` in Task A can trigger `__mmput` while Task B is in `dup_mm`?]
Results: map[Answer:Based on the Linux kernel implementation of `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mm()`, **Task A's `mmput(mm)` cannot trigger `__mmput(mm)` while Task B is in `dup_mm()`**.
Here is the step-by-step analysis of why this cannot happen, along with the lifecycle of `mm->mm_users` and synchronization between the two tasks:
---
### 1. The Reference Count Invariant (`mm->mm_users`)
- When Task B and Task A share an address space (`mm_struct`) via `vfork()` (`CLONE_VM | CLONE_VFORK`):
```c
if (clone_flags & CLONE_VM) {
mmget(oldmm);
mm = oldmm;
}
```
`mmget(oldmm)` increments `atomic_inc(&oldmm->mm_users)`.
- Prior to exit or exec by either task, both tasks actively reference the `mm_struct` (`current->mm == mm`). Therefore, `mm->mm_users >= 2`.
- `mmput(mm)` is implemented as:
```c
void mmput(struct mm_struct *mm)
{
if (atomic_dec_and_test(&mm->mm_users))
__mmput(mm);
}
```
`__mmput()` is invoked **if and only if** `atomic_dec_and_test(&mm->mm_users)` decrements `mm_users` from 1 to 0.
---
### 2. Analysis of the Race Scenarios
#### Scenario 1: Task A is the vfork parent; Task B is the vfork child
- Task A waits in `wait_for_vfork_done(&vfork)`.
- If Task A is killed by `SIGKILL`, `wait_for_vfork_done()` wakes up due to the fatal signal (`wait_for_completion_killable`).
- Task A exits and calls `exit_mm()`.
- When Task A calls `mmput(mm)`, Task B is still alive and running (holding its active `current->mm`).
- Thus, `mm->mm_users` was at least 2. Task A's `mmput(mm)` decrements it to at least 1.
- `atomic_dec_and_test(&mm->mm_users)` returns `false`. `__mmput()` is **not** called.
#### Scenario 2: Task B is the vfork parent; Task A is the vfork child
- Task B calls `vfork()` and waits in `wait_for_vfork_done(&vfork)`.
- Task A (the child) exits (`do_exit()`):
1. Task A calls `exit_mm()`.
2. Inside `exit_mm()`, `mm_exit_exec_release()` -> `mm_release()` is called:
```c
if (tsk->vfork_done)
complete_vfork_done(tsk);
```
This completes the vfork completion and wakes parent Task B.
3. Task B wakes up, returns from `wait_for_vfork_done()`, and returns to userspace.
4. Task B calls `clone()` without `CLONE_VM` (e.g., standard `fork()`), which invokes `copy_mm()`:
```c
mm = dup_mm(tsk, current->mm);
```
Task B enters `dup_mm(tsk, current->mm)`.
5. Meanwhile, Task A continues in `exit_mm()` and reaches:
```c
mmput(mm);
```
- **Why `__mmput` cannot be called here:**
For Task B to be running in userspace and invoking system calls like `fork()`, Task B's `current->mm` remains valid. Task B still holds its active reference to `mm_users` that was established before or during `vfork()`.
Task B cannot drop its `current->mm` while synchronously executing inside `kernel_clone() -> copy_process() -> copy_mm() -> dup_mm()`.
Consequently, when Task A reaches `mmput(mm)`, `mm->mm_users` is at least 2 (Task A's reference + Task B's reference).
The decrement drops `mm_users` from 2 to 1, returning `false`. `__mmput()` is **not** called.
---
### 3. Locking and Memory Safety
Even looking beyond reference counts:
- `dup_mm()` invokes `dup_mmap(new_mm, oldmm)`.
- The very first step of `dup_mmap()` is acquiring the write lock on `oldmm`:
```c
if (mmap_write_lock_killable(oldmm))
return -EINTR;
```
- Meanwhile, `exit_mm()` acquires `mmap_read_lock(mm)` while detaching `current->mm`.
- Even in the teardown path of an `mm`, `__mmput()` calls `exit_mmap(mm)`, which requires taking `mmap_write_lock(mm)`.
Both the reference counting model and the mmap semaphores prevent concurrent destruction of `oldmm` while another task is reading or duplicating it.
---
### 4. Caveats and Unverified Parts
- This analysis is based on the core lifetime rules of `mm_struct`, `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mmap()`.
- It was not verified whether asynchronous mechanisms outside normal task execution (such as speculative kernel-thread borrowing via `kthread_use_mm()`, or anomalous third-party references from out-of-tree drivers) could cause reference count discrepancies. Under standard in-tree POSIX semantics, `mm_users` cannot reach 0 in Task A while Task B is executing `dup_mm()`.]
|
| 255/3 |
2026/09/23 20:24 |
agent |
codeexpert |
15m
Model:
Results: map[Answer:Based on the Linux kernel implementation of `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mm()`, **Task A's `mmput(mm)` cannot trigger `__mmput(mm)` while Task B is in `dup_mm()`**.
Here is the step-by-step analysis of why this cannot happen, along with the lifecycle of `mm->mm_users` and synchronization between the two tasks:
---
### 1. The Reference Count Invariant (`mm->mm_users`)
- When Task B and Task A share an address space (`mm_struct`) via `vfork()` (`CLONE_VM | CLONE_VFORK`):
```c
if (clone_flags & CLONE_VM) {
mmget(oldmm);
mm = oldmm;
}
```
`mmget(oldmm)` increments `atomic_inc(&oldmm->mm_users)`.
- Prior to exit or exec by either task, both tasks actively reference the `mm_struct` (`current->mm == mm`). Therefore, `mm->mm_users >= 2`.
- `mmput(mm)` is implemented as:
```c
void mmput(struct mm_struct *mm)
{
if (atomic_dec_and_test(&mm->mm_users))
__mmput(mm);
}
```
`__mmput()` is invoked **if and only if** `atomic_dec_and_test(&mm->mm_users)` decrements `mm_users` from 1 to 0.
---
### 2. Analysis of the Race Scenarios
#### Scenario 1: Task A is the vfork parent; Task B is the vfork child
- Task A waits in `wait_for_vfork_done(&vfork)`.
- If Task A is killed by `SIGKILL`, `wait_for_vfork_done()` wakes up due to the fatal signal (`wait_for_completion_killable`).
- Task A exits and calls `exit_mm()`.
- When Task A calls `mmput(mm)`, Task B is still alive and running (holding its active `current->mm`).
- Thus, `mm->mm_users` was at least 2. Task A's `mmput(mm)` decrements it to at least 1.
- `atomic_dec_and_test(&mm->mm_users)` returns `false`. `__mmput()` is **not** called.
#### Scenario 2: Task B is the vfork parent; Task A is the vfork child
- Task B calls `vfork()` and waits in `wait_for_vfork_done(&vfork)`.
- Task A (the child) exits (`do_exit()`):
1. Task A calls `exit_mm()`.
2. Inside `exit_mm()`, `mm_exit_exec_release()` -> `mm_release()` is called:
```c
if (tsk->vfork_done)
complete_vfork_done(tsk);
```
This completes the vfork completion and wakes parent Task B.
3. Task B wakes up, returns from `wait_for_vfork_done()`, and returns to userspace.
4. Task B calls `clone()` without `CLONE_VM` (e.g., standard `fork()`), which invokes `copy_mm()`:
```c
mm = dup_mm(tsk, current->mm);
```
Task B enters `dup_mm(tsk, current->mm)`.
5. Meanwhile, Task A continues in `exit_mm()` and reaches:
```c
mmput(mm);
```
- **Why `__mmput` cannot be called here:**
For Task B to be running in userspace and invoking system calls like `fork()`, Task B's `current->mm` remains valid. Task B still holds its active reference to `mm_users` that was established before or during `vfork()`.
Task B cannot drop its `current->mm` while synchronously executing inside `kernel_clone() -> copy_process() -> copy_mm() -> dup_mm()`.
Consequently, when Task A reaches `mmput(mm)`, `mm->mm_users` is at least 2 (Task A's reference + Task B's reference).
The decrement drops `mm_users` from 2 to 1, returning `false`. `__mmput()` is **not** called.
---
### 3. Locking and Memory Safety
Even looking beyond reference counts:
- `dup_mm()` invokes `dup_mmap(new_mm, oldmm)`.
- The very first step of `dup_mmap()` is acquiring the write lock on `oldmm`:
```c
if (mmap_write_lock_killable(oldmm))
return -EINTR;
```
- Meanwhile, `exit_mm()` acquires `mmap_read_lock(mm)` while detaching `current->mm`.
- Even in the teardown path of an `mm`, `__mmput()` calls `exit_mmap(mm)`, which requires taking `mmap_write_lock(mm)`.
Both the reference counting model and the mmap semaphores prevent concurrent destruction of `oldmm` while another task is reading or duplicating it.
---
### 4. Caveats and Unverified Parts
- This analysis is based on the core lifetime rules of `mm_struct`, `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mmap()`.
- It was not verified whether asynchronous mechanisms outside normal task execution (such as speculative kernel-thread borrowing via `kthread_use_mm()`, or anomalous third-party references from out-of-tree drivers) could cause reference count discrepancies. Under standard in-tree POSIX semantics, `mm_users` cannot reach 0 in Task A while Task B is executing `dup_mm()`.]
Instruction:
You are a capable Linux kernel developer tasked with researching complex questions
about kernel source code. You will be given a concrete question, and need to provide
a concrete answer.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
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: Consider `vfork()`.
Task A calls `vfork()`:
- `clone_flags = CLONE_VFORK | CLONE_VM`
- In `copy_mm()`: `oldmm = current->mm; mmget(oldmm); mm = oldmm; tsk->mm = mm;`
- Task A waits in `wait_for_vfork_done()`: `wait_for_completion_state(&vfork, TASK_KILLABLE|TASK_FREEZABLE)`.
Now Task B is the vfork child, sharing `oldmm`. Task B has `mm_users` incremented from 1 to 2 by `mmget(oldmm)`.
Suppose Task A is killed by a fatal signal (e.g. SIGKILL sent to Task A):
`wait_for_completion_state(&vfork, ...)` in Task A returns non-zero (killed).
Task A wakes up, proceeds in `kernel_clone()`, and exits!
When Task A exits:
In `exit_mm()`:
Task A does:
`current->mm = NULL;`
`mmput(mm);` -> `atomic_dec_and_test(&mm->mm_users)` -> drops `mm_users` from 2 to 1! Task A does NOT call `__mmput`!
Wait, but if Task B then exits or what?
What if Task B is NOT a vfork child, but Task A was the vfork child?
Suppose Task B is the parent in vfork, and Task A is the vfork child?
If Task B calls `vfork()`: Task B sleeps. Task A is the child.
Task A exits (`do_exit`): in `mm_release()`: `tsk->vfork_done` is completed, waking Task B.
Then Task A calls `exit_mm()`: `atomic_dec_and_test(&mm->mm_users)`: drops `mm_users` from 2 to 1.
What if Task B wakes up before Task A calls `exit_mm()`?
Task B wakes up from `wait_for_vfork_done()`. Task B returns to userspace!
Then Task B calls `sys_clone()` without `CLONE_VM`!
Now Task B has `current->mm == oldmm`.
Task A is still in `exit_mm()`:
Task A calls `mmput(mm)`.
Wait! If Task B is alive, `mm_users` is at least 1 (from Task B).
When Task A calls `mmput(mm)`, `mm_users` was 2 (1 for Task A, 1 for Task B).
When Task A calls `mmput(mm)`, `atomic_dec_and_test` drops it to 1! It does NOT drop to 0!
So how can `__mmput` be called in Task A?
Wait, what if Task B is the child, or what if `atomic_dec_and_test` dropped to 0?
Can you analyze how `mmput(mm)` in Task A can trigger `__mmput` while Task B is in `dup_mm`?
|
| 256/4 |
2026/09/23 20:24 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4842
output: 20
thoughts: 929
Thoughts: **Analyzing `vfork()` and Memory Management in the Linux Kernel**
Okay, let's break this down. This prompt is essentially a deep dive into the intricacies of `vfork()` in the Linux kernel and potential race conditions with memory management. It's asking me to trace a specific sequence of events and pinpoint how a call to `mmput()` within a vforking task could trigger the `__mmput()` function while another task is still interacting with the memory management structure via `dup_mm()`. I need to figure out how `mm_users` gets manipulated in this context.
My initial thought is to carefully follow the execution flow, step-by-step. Specifically:
* I understand the basic idea that one task calls `vfork()`, a child is created that shares the memory management structure (`mm`) with the parent.
* I see that the parent waits with `wait_for_vfork_done()` and the child then works.
* I need to consider the scenario where the parent is killed while waiting. The child can then complete.
I need to analyze where `mm_users` is incremented and decremented with `mmget()` and `mmput()` respectively. The prompt is highlighting the fact that the initial state might have `mm_users` is 2 because the child shares the mm.
I understand how `exit_mm()` and `mm_release()` play a role when a task exits and attempts to release the `mm`. This is where `mmput()` comes in, decrementing `mm_users`. Then the question is, how can the final call to `mmput()` in the parent task (which got killed) trigger the freeing of `mm` if the child is still using it, and particularly when the child might be in the middle of a `dup_mm()` call? I need to think about how this affects the `atomic_dec_and_test(&mm->mm_users)` operation and how it affects the final `__mmput()` call which does all the work of releasing the memory.
To answer this question, I'm going to leverage my experience. I'll need to go beyond just the code snippets provided.
I'm thinking this might be a known issue, perhaps a race condition that's been addressed in a kernel patch. My next step is to use tools like `git log` and `grepper` to search the Linux kernel source code for related keywords like `dup_mm`, `vfork`, `mm_release`, `vfork_done`, `wait_for_vfork_done`, and `mmput`. I'm going to look for commits or discussions that touch upon these specific functions in conjunction. I will check for related CVEs or security issues in this area. Perhaps this specific scenario, or a similar one, has already been documented and patched.
|
| 257/4 |
2026/09/23 20:24 |
tool |
grepper |
0m
Args: map[Expression:complete_vfork_done]
Results: map[Output:kernel/fork.c=1411=struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
--
kernel/fork.c-1431-
kernel/fork.c:1432:static void complete_vfork_done(struct task_struct *tsk)
kernel/fork.c-1433-{
--
kernel/fork.c=1478=static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
--
kernel/fork.c-1507- if (tsk->vfork_done)
kernel/fork.c:1508: complete_vfork_done(tsk);
kernel/fork.c-1509-}
]
|
| 258/4 |
2026/09/23 20:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6583
output: 35
thoughts: 44
Thoughts: Here's my thought process, summarized as you requested:
**Debugging a Suspect Fork/vfork Issue in the Kernel**
Okay, so I suspect something fishy is happening around `fork` or `vfork` in the kernel. My first move is to dive straight into the code history to understand recent changes that might be related to the problem. I'm going to leverage `git log` specifically on `kernel/fork.c`, which is the logical place to start. I'm looking for commits that touch on several key functions that are involved in process creation and memory management after a `fork` or `vfork` call. The most obvious candidates I'm interested in are commits touching `complete_vfork_done`, `vfork_done`, `mm_release` (which is critical for cleaning up memory after these operations), and potentially `dup_mm`, which is the process of duplicating the memory map. By searching through the commit history with these keywords, I'm hoping to quickly identify any recent modifications that could have introduced the bug or interact with it.
|
| 259/4 |
2026/09/23 20:25 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[vfork] PathPrefix:kernel/fork.c]
Results: map[Output:b61b6f95d672 futex: Also allocate private hash on vfork()
ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
192d852129b1 sched/mmcid: Avoid full tasklist walks
2b5f9dad32ed fs/exec: switch timens when a task gets a new mm
33a2d6bc3480 Revert "fs/exec: allow to unshare a time namespace on vfork+exec"
133e2d3e81de fs/exec: allow to unshare a time namespace on vfork+exec
40966e316f86 kthread: Ensure struct kthread is present for all kthreads
0258b5fd7c71 coredump: Limit coredumps to a single thread group
67197a4f28d2 mm, oom_adj: don't loop through tasks in __set_oom_adj when not necessary
cad6967ac108 fork: introduce kernel_clone()
]
|
| 260/4 |
2026/09/23 20:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7161
output: 36
thoughts: 34
Thoughts: Here's my thought process, summarized as you requested:
**Digging into Memory Management Shenanigans**
Okay, time to get to work. I need to understand what's happening with memory management, specifically where there might be issues or opportunities for optimization. My first instinct is to dig through the commit history. I'm going to leverage my knowledge of potential problem areas. I'm going to search for a specific set of keywords: `dup_mm`, `__mmput`, `mmput`, and `wait_for_vfork_done`. These terms are often indicative of core memory management operations and potential synchronization problems that I'm interested in reviewing. By finding these key phrases, I can understand what changes have been recently made that might shed light on our current problem. Let's see what the commit messages turn up.
|
| 261/4 |
2026/09/23 20:25 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[dup_mm] PathPrefix:kernel/fork.c]
Results: map[Output:6b1c66c9cca9 exec_state: relocate dumpable information
26a8f57760c1 mm: move dup_mmap() to mm
64c37e134b12 kernel: be more careful about dup_mmap() failures and uprobe registering
8ac662f5da19 fork: avoid inappropriate uprobe access to invalid mm
985da552a98e fork: only invoke khugepaged, ksm hooks if no error
f64e67e5d3a4 fork: do not invoke uffd on fork if error occurs
35e351780fa9 fork: defer linking file vma until vma is fully initialized
d24062914837 fork: use __mt_dup() to duplicate maple tree in dup_mmap()
c9dbe82cb99d kernel/fork: use maple tree for dup_mmap() during forking
d2081b2bf819 mm: khugepaged: make khugepaged_enter() void function
73eb7f9a4ff0 mm: use helper function put_write_access()
cf508b58457c mm: use helper function mapping_allow_writable()
93949bb21b52 mm: don't prepare anon_vma if vma has VM_WIPEONFORK
aad42dd44db0 uprobes: Initialize uprobes earlier
1ed0cc5a01a4 mm: respect arch_dup_mmap() return value
655c79bb40a0 mm: check for SIGKILL inside dup_mmap() loop
07dcd7fe8993 fork: Define usercopy region in mm_struct slab caches
c10e83f598d0 arch, mm: Allow arch_dup_mmap() to fail
355627f51897 mm, uprobes: fix multiple free of ->uprobes_state.xol_area
2b7e8665b4ff fork: fix incorrect fput of ->exe_file causing use-after-free
]
|
| 262/4 |
2026/09/23 20:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7928
output: 35
thoughts: 26
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing Kernel Memory Management Code**
Alright, let's dive in. My immediate thought is to zero in on potential memory management issues related to process forking, specifically within the kernel. I want to check for proper handling of reference counting within the kernel's memory management. The likely target is any potential use of `__mmput` or `mmput` functions in the kernel. My initial scope will be restricted to code directly involved in forking operations: `kernel/fork.c` and anywhere within the `mm/` directory. By targeting these areas, I'm hoping to quickly identify code paths where memory structures related to process memory spaces might be incorrectly released or leaked during the `fork` process.
|
| 263/4 |
2026/09/23 20:26 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[mmput] PathPrefix:kernel/fork.c]
Results: map[Output:ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
d9b05321e21e futex: Move futex_hash_free() back to __mmput()
e703b7e24750 futex: Move futex cleanup to __mmdrop()
dc84bc2aba85 x86/mm/pat: Fix VM_PAT handling when fork() fails in copy_page_range()
08e28de1160a uprobes: use vm_special_mapping close() functionality
85eaeb5058f0 IB/core: Fix a nested dead lock as part of ODP flow
2667ed10d9f0 mm: Fix PASID use-after-free issue
a1b2289cef92 android: binder: drop lru lock in isolate callback
212925802454 mm: oom: let oom_reap_task and exit_mmap run concurrently
355627f51897 mm, uprobes: fix multiple free of ->uprobes_state.xol_area
2b7e8665b4ff fork: fix incorrect fput of ->exe_file causing use-after-free
6e84f31522f9 sched/headers: Prepare for new header dependencies before moving code to <linux/sched/mm.h>
862e3073b3ee mm, oom: get rid of signal_struct::oom_victims
7283094ec3db kernel, oom: fix potential pgd_lock deadlock from __mmdrop
26db62f179d1 oom: keep mm of the killed task available
7ef949d77f95 mm: oom_reaper: remove some bloat
ec8d7c14ea14 mm, oom_reaper: do not mmput synchronously from the oom reaper context
e9714acf8c43 mm: kill vma flag VM_EXECUTABLE and mm->num_exe_file_vmas
61559a8165da uprobes: Fold uprobe_reset_state() into uprobe_dup_mmap()
48d212a2eeca Revert "mm: correctly synchronize rss-counters at exit/exec"
]
|
| 264/4 |
2026/09/23 20:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 8727
output: 32
thoughts: 928
Thoughts: **Analyzing a `vfork()` Scenario: A Deep Dive**
Okay, let's break this down. The prompt wants me to analyze a `vfork()` situation, specifically concerning `mmput` and `__mmput` and the interaction between a parent and child process. I need to be precise, let's re-read the query, again... "Can you analyze how `mmput(mm)` in Task A can trigger `__mmput` while Task B is in `dup_mm`?" Okay, so it's a specific scenario. It's not a general question about whether `__mmput` *can* be called during `dup_mm`; the question seems to be more about how it *could* happen, and if so, how.
I need to meticulously trace the execution. Let me make sure I understand the setup clearly. Task A calls `vfork()`, so `CLONE_VFORK` and `CLONE_VM` are set. In `copy_mm()`, the `oldmm` is captured and incremented, and then `Task A` waits for completion with `wait_for_vfork_done()`. So, the child (Task B) shares the memory.
Now, if Task A gets killed by a fatal signal, say SIGKILL, it's going to wake up and exit, which is the crux of the question. When Task A exits, `exit_mm()` is called. This is the critical point. It appears `mm_users` is at 2 at this point, but `mmput(mm)` is only done once, reducing `mm_users` to 1. But does that drop to 0, which would trigger `__mmput`?
Wait, what if Task B has already started its own `clone()`, and is in `dup_mm`? This is the core of the question! So, it might have `current->mm == oldmm`. If Task A is in the middle of this and calls `mmput(mm)`, how does that interact with a Task B which might be actively in the `dup_mm` process? Is this a race condition? Is `mm_users` at least 1 (from Task B).
Now the question is how `mmput(mm)` in Task A can trigger `__mmput` while Task B is in `dup_mm`. My immediate thought is to consider the possibility that it's possible at all. Let's see what `dup_mm()` actually does, let me inspect the code.
|
| 265/4 |
2026/09/23 20:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mm]
Results: map[SourceCode:1517: /**
1518: * dup_mm() - duplicates an existing mm structure
1519: * @tsk: the task_struct with which the new mm will be associated.
1520: * @oldmm: the mm to duplicate.
1521: *
1522: * Allocates a new mm structure and duplicates the provided @oldmm structure
1523: * content into it.
1524: *
1525: * Return: the duplicated mm or NULL on failure.
1526: */
1527: static struct mm_struct *dup_mm(struct task_struct *tsk,
1528: struct mm_struct *oldmm)
1529: {
1530: struct mm_struct *mm;
1531: int err;
1532:
1533: mm = allocate_mm();
1534: if (!mm)
1535: goto fail_nomem;
1536:
1537: memcpy(mm, oldmm, sizeof(*mm));
1538:
1539: if (!mm_init(mm, tsk))
1540: goto fail_nomem;
1541:
1542: uprobe_start_dup_mmap();
1543: err = dup_mmap(mm, oldmm);
1544: if (err)
1545: goto free_pt;
1546: uprobe_end_dup_mmap();
1547:
1548: mm->hiwater_rss = get_mm_rss(mm);
1549: mm->hiwater_vm = mm->total_vm;
1550:
1551: if (mm->binfmt && !try_module_get(mm->binfmt->module))
1552: goto free_pt;
1553:
1554: return mm;
1555:
1556: free_pt:
1557: /* don't put binfmt in mmput, we haven't got module yet */
1558: mm->binfmt = NULL;
1559: mm_init_owner(mm, NULL);
1560: mmput(mm);
1561: if (err)
1562: uprobe_end_dup_mmap();
1563:
1564: fail_nomem:
1565: return NULL;
1566: }
SourceFile:kernel/fork.c]
|
| 266/4 |
2026/09/23 20:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10925
output: 32
thoughts: 30
Thoughts: Here's my analysis of the provided thought process, tailored for an expert audience:
**Analyzing Memory Management Functions**
Okay, first things first: `dup_mm`. My immediate reaction is to look closely at that function. It's a key piece, and I need to understand its role. But before I dive into the implementation details of `dup_mm` itself, my next thought is, "What are the *callers* of `dup_mm`?" Understanding the contexts where it's used is crucial for grasping its overall purpose and potential side effects within the memory management subsystem. Is this function involved in process creation? Shared memory handling? Knowing the calling functions paints the bigger picture. After thinking about that, I should then check `copy_mm()` since that function is very similar, and I will be looking to see what the difference between `dup_mm()` and `copy_mm()` is. Let's see how these pieces fit together.
|
| 267/4 |
2026/09/23 20:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_mm]
Results: map[SourceCode:1568: static int copy_mm(u64 clone_flags, struct task_struct *tsk)
1569: {
1570: struct mm_struct *mm, *oldmm;
1571:
1572: tsk->min_flt = tsk->maj_flt = 0;
1573: tsk->nvcsw = tsk->nivcsw = 0;
1574: #ifdef CONFIG_DETECT_HUNG_TASK
1575: tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1576: tsk->last_switch_time = 0;
1577: #endif
1578:
1579: tsk->mm = NULL;
1580: tsk->active_mm = NULL;
1581:
1582: /*
1583: * Are we cloning a kernel thread?
1584: *
1585: * We need to steal a active VM for that..
1586: */
1587: oldmm = current->mm;
1588: if (!oldmm)
1589: return 0;
1590:
1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
1597: return -ENOMEM;
1598: }
1599:
1600: tsk->mm = mm;
1601: tsk->active_mm = mm;
1602: return 0;
1603: }
SourceFile:kernel/fork.c]
|
| 268/4 |
2026/09/23 20:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 11698
output: 33
thoughts: 44
Thoughts: Here's my analysis of the provided thought process, tailored for an expert audience:
**Analyzing the `dup_mmap()` Function**
Okay, so the code's referencing `dup_mmap()`. My immediate thought is, "Where's this function defined, and what's the deal with that `oldmm` parameter?" I need to understand its relationship with the memory management structures, specifically how it's duplicating memory mappings. Let's dig into the definition of `dup_mmap()` and dissect its interactions with the existing memory map. Understanding how `oldmm` is handled is key to grasping the core functionality here, especially regarding copy-on-write or actual data duplication strategies. I suspect we'll be looking at how address spaces are copied and what implications this has on sharing and potential modifications.
|
| 269/4 |
2026/09/23 20:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mmap]
Results: map[SourceCode:1708: __latent_entropy int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
1709: {
1710: struct vm_area_struct *mpnt, *tmp;
1711: int retval;
1712: unsigned long charge = 0;
1713: LIST_HEAD(uf);
1714: VMA_ITERATOR(vmi, mm, 0);
1715:
1716: if (mmap_write_lock_killable(oldmm))
1717: return -EINTR;
1718: flush_cache_dup_mm(oldmm);
1719: uprobe_dup_mmap(oldmm, mm);
1720: /*
1721: * Not linked in yet - no deadlock potential:
1722: */
1723: mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
1724:
1725: /* No ordering required: file already has been exposed. */
1726: dup_mm_exe_file(mm, oldmm);
1727:
1728: mm->total_vm = oldmm->total_vm;
1729: mm->data_vm = oldmm->data_vm;
1730: mm->exec_vm = oldmm->exec_vm;
1731: mm->stack_vm = oldmm->stack_vm;
1732:
1733: /* Use __mt_dup() to efficiently build an identical maple tree. */
1734: retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
1735: if (unlikely(retval))
1736: goto out;
1737:
1738: mt_clear_in_rcu(vmi.mas.tree);
1739: for_each_vma(vmi, mpnt) {
1740: struct file *file;
1741:
1742: retval = vma_start_write_killable(mpnt);
1743: if (retval < 0)
1744: goto loop_out;
1745: if (vma_test(mpnt, VMA_DONTCOPY_BIT)) {
1746: retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
1747: mpnt->vm_end, GFP_KERNEL);
1748: if (retval)
1749: goto loop_out;
1750:
1751: vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
1752: continue;
1753: }
1754: charge = 0;
1755: if (vma_test(mpnt, VMA_ACCOUNT_BIT)) {
1756: unsigned long len = vma_pages(mpnt);
1757:
1758: if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
1759: goto fail_nomem;
1760: charge = len;
1761: }
1762:
1763: tmp = vm_area_dup(mpnt);
1764: if (!tmp)
1765: goto fail_nomem;
1766: retval = vma_dup_policy(mpnt, tmp);
1767: if (retval)
1768: goto fail_nomem_policy;
1769: tmp->vm_mm = mm;
1770: retval = dup_userfaultfd(tmp, &uf);
1771: if (retval)
1772: goto fail_nomem_anon_vma_fork;
1773:
1774: if (vma_test(tmp, VMA_WIPEONFORK_BIT)) {
1775: /*
1776: * VMA_WIPEONFORK_BIT gets a clean slate in the child.
1777: * Don't prepare anon_vma until fault since we don't
1778: * copy page for current vma.
1779: */
1780: tmp->anon_vma = NULL;
1781: } else if (anon_vma_fork(tmp, mpnt))
1782: goto fail_nomem_anon_vma_fork;
1783:
1784: vma_start_write(tmp);
1785: vma_clear_flags_mask(tmp, VMA_LOCKED_MASK);
1786: /*
1787: * Copy/update hugetlb private vma information.
1788: */
1789: if (is_vm_hugetlb_page(tmp))
1790: hugetlb_dup_vma_private(tmp);
1791:
1792: /*
1793: * Link the vma into the MT. After using __mt_dup(), memory
1794: * allocation is not necessary here, so it cannot fail.
1795: */
1796: vma_iter_bulk_store(&vmi, tmp);
1797:
1798: mm->map_count++;
1799:
1800: if (tmp->vm_ops && tmp->vm_ops->open)
1801: tmp->vm_ops->open(tmp);
1802:
1803: file = tmp->vm_file;
1804: if (file) {
1805: struct address_space *mapping = file->f_mapping;
1806:
1807: get_file(file);
1808: i_mmap_lock_write(mapping);
1809: if (vma_is_shared_maywrite(tmp))
1810: mapping_allow_writable(mapping);
1811: flush_dcache_mmap_lock(mapping);
1812: /* insert tmp into the share list, just after mpnt */
1813: mapping_rmap_tree_insert_after(tmp, mpnt, mapping);
1814: flush_dcache_mmap_unlock(mapping);
1815: i_mmap_unlock_write(mapping);
1816: }
1817:
1818: if (!vma_test(tmp, VMA_WIPEONFORK_BIT))
1819: retval = copy_page_range(tmp, mpnt);
1820:
1821: if (retval) {
1822: mpnt = vma_next(&vmi);
1823: goto loop_out;
1824: }
1825: }
1826: /* a new mm has just been created */
1827: retval = arch_dup_mmap(oldmm, mm);
1828: loop_out:
1829: vma_iter_free(&vmi);
1830: if (!retval) {
1831: mt_set_in_rcu(vmi.mas.tree);
1832: ksm_fork(mm, oldmm);
1833: khugepaged_fork(mm, oldmm);
1834: } else {
1835: unsigned long end;
1836:
1837: /*
1838: * The entire maple tree has already been duplicated, but
1839: * replacing the vmas failed at mpnt (which could be NULL if
1840: * all were allocated but the last vma was not fully set up).
1841: * Use the start address of the failure point to clean up the
1842: * partially initialized tree.
1843: */
1844: if (!mm->map_count) {
1845: /* zero vmas were written to the new tree. */
1846: end = 0;
1847: } else if (mpnt) {
1848: /* partial tree failure */
1849: end = mpnt->vm_start;
1850: } else {
1851: /* All vmas were written to the new tree */
1852: end = ULONG_MAX;
1853: }
1854:
1855: /* Hide mm from oom killer because the memory is being freed */
1856: mm_flags_set(MMF_OOM_SKIP, mm);
1857: if (end) {
1858: vma_iter_set(&vmi, 0);
1859: tmp = vma_next(&vmi);
1860: UNMAP_STATE(unmap, &vmi, /* first = */ tmp,
1861: /* vma_start = */ 0, /* vma_end = */ end,
1862: /* prev = */ NULL, /* next = */ NULL);
1863:
1864: /*
1865: * Don't iterate over vmas beyond the failure point for
1866: * both unmap_vma() and free_pgtables().
1867: */
1868: unmap.tree_end = end;
1869: flush_cache_mm(mm);
1870: unmap_region(&unmap);
1871: charge = tear_down_vmas(mm, &vmi, tmp, end);
1872: vm_unacct_memory(charge);
1873: }
1874: __mt_destroy(&mm->mm_mt);
1875: /*
1876: * The mm_struct is going to exit, but the locks will be dropped
1877: * first. Set the mm_struct as unstable is advisable as it is
1878: * not fully initialised.
1879: */
1880: mm_flags_set(MMF_UNSTABLE, mm);
1881: }
1882: out:
1883: mmap_write_unlock(mm);
1884: flush_tlb_mm(oldmm);
1885: mmap_write_unlock(oldmm);
1886: if (!retval)
1887: dup_userfaultfd_complete(&uf);
1888: else
1889: dup_userfaultfd_fail(&uf);
1890: return retval;
1891:
1892: fail_nomem_anon_vma_fork:
1893: mpol_put(vma_policy(tmp));
1894: fail_nomem_policy:
1895: vm_area_free(tmp);
1896: fail_nomem:
1897: retval = -ENOMEM;
1898: vm_unacct_memory(charge);
1899: goto loop_out;
1900: }
SourceFile:mm/mmap.c]
|
| 270/4 |
2026/09/23 20:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14942
output: 32
thoughts: 100
Thoughts: **Analyzing Memory Management During Process Exit**
Okay, let's dive in. I'm currently scrutinizing the memory management intricacies around process duplication, specifically focusing on `dup_mmap()`. I see it right there, on line 1716, the call to `mmap_write_lock_killable(oldmm)`. Interesting… it takes a write lock. I need to be clear on *why*. That lock is a critical piece of the puzzle. Now I'm shifting gears. If `dup_mmap()` takes that lock, then what happens when a process exits? I need to understand how these memory regions are cleaned up. My focus now is on `exit_mm()` which I know is in `kernel/exit.c`. Let's see how memory is handled during process termination. This is the central question!
|
| 271/4 |
2026/09/23 20:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:exit_mm]
Results: map[SourceCode: 580: /*
581: * Turn us into a lazy TLB process if we
582: * aren't already..
583: */
584: static void exit_mm(void)
585: {
586: struct mm_struct *mm = current->mm;
587:
588: mm_exit_exec_release(current, mm);
589: if (!mm)
590: return;
591:
592: exit_mm_sched_cache(mm);
593:
594: mmap_read_lock(mm);
595: mmgrab_lazy_tlb(mm);
596: BUG_ON(mm != current->active_mm);
597: /* more a memory barrier than a real lock */
598: task_lock(current);
599: /*
600: * When a thread stops operating on an address space, the loop
601: * in membarrier_private_expedited() may not observe that
602: * tsk->mm, and the loop in membarrier_global_expedited() may
603: * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
604: * rq->membarrier_state, so those would not issue an IPI.
605: * Membarrier requires a memory barrier after accessing
606: * user-space memory, before clearing tsk->mm or the
607: * rq->membarrier_state.
608: */
609: smp_mb__after_spinlock();
610: local_irq_disable();
611: current->mm = NULL;
612: membarrier_update_current_mm(NULL);
613: enter_lazy_tlb(mm, current);
614: local_irq_enable();
615: task_unlock(current);
616: mmap_read_unlock(mm);
617: mm_update_next_owner(mm);
618: mmput(mm);
619: if (test_thread_flag(TIF_MEMDIE))
620: exit_oom_victim();
621: }
SourceFile:kernel/exit.c]
|
| 272/4 |
2026/09/23 20:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15902
output: 36
thoughts: 116
Thoughts: Okay, let's break this down.
**Investigating Memory Management and Process Exit**
Alright, I'm digging into how memory management interacts with process termination, specifically looking at the `exit_mm()` function. My immediate focus is on locking mechanisms and how they are handled across the process of freeing memory resources during an exit operation. Line 594 shows `mmap_read_lock(mm);`, which is the first lock I'm seeing for mmap.
Hold on, something doesn't seem quite right. I just remembered that `dup_mmap()` uses `mmap_write_lock_killable(oldmm)`. That seems like a write lock, and the lock operations on the mmap seem to be unbalanced in operations, and I should know why!
Now, back in `exit_mm(void)` I see the call to `mm_exit_exec_release(current, mm)`. This is where things get interesting. What's the purpose of `mm_exit_exec_release(current, mm)` in the context of the exit process? Is this where we do the heavy lifting of releasing memory, or does it handle the execution of other exit code? Is it just a wrapper for `mm_release`? I'm going to have to dive into `mm_exit_exec_release` or `mm_release` to get a clearer picture of what's going on here. I need to understand this sequence. I'm going to analyze the locking operations to make sure everything is released correctly and ensure the process exits cleanly.
|
| 273/4 |
2026/09/23 20:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:mm_exit_exec_release]
Results: map[SourceCode:1511: void mm_exit_exec_release(struct task_struct *tsk, struct mm_struct *mm)
1512: {
1513: futex_exit_exec_release(tsk);
1514: mm_release(tsk, mm);
1515: }
SourceFile:kernel/fork.c]
|
| 274/4 |
2026/09/23 20:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16495
output: 32
thoughts: 10
Thoughts: Okay, let's dive into this. Here's how I'd approach summarizing the prompt, given my expertise:
**Dissecting `mm_release()`**
Alright, I'm being asked to consider a piece of code, specifically `mm_release()`. Immediately, my mind jumps to the context. `mm_release()`... that strongly suggests we're dealing with memory management at some level. Given the name, I'd expect it to be a function involved in releasing memory or resources associated with a memory manager, probably within a kernel or operating system. I need more information to tell what language it is, whether it's related to a kernel.
So, I need to start asking questions. What specific memory management scheme is this associated with? Is it virtual memory, physical memory, object allocation, or perhaps something else entirely? What data structures are involved? What's the overall architecture in which this function operates? Is it a single function or part of a larger, coordinated set of routines? Are there any associated locks or synchronization mechanisms that I should be aware of, like `mmap()` or shared memory? Are there concerns regarding memory leaks, dangling pointers, or double-frees? This is the initial mental checklist.
Essentially, I want to form a mental model of how this function fits into the bigger picture of memory management. I'd begin to build out its likely interaction with other system components. I'd need to consider edge cases and error handling. I'd consider its performance implications, especially if it's called frequently. Is it a critical path function?
Now, with this understanding, I can explore any documentation, code examples, or specific implementations that are presented.
|
| 275/4 |
2026/09/23 20:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_release]
Results: map[SourceCode:1465: /* Please note the differences between mmput and mm_release.
1466: * mmput is called whenever we stop holding onto a mm_struct,
1467: * error success whatever.
1468: *
1469: * mm_release is called after a mm_struct has been removed
1470: * from the current process.
1471: *
1472: * This difference is important for error handling, when we
1473: * only half set up a mm_struct for a new process and need to restore
1474: * the old one. Because we mmput the new mm_struct before
1475: * restoring the old one. . .
1476: * Eric Biederman 10 January 1998
1477: */
1478: static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1479: {
1480: uprobe_free_utask(tsk);
1481:
1482: /* Get rid of any cached register state */
1483: deactivate_mm(tsk, mm);
1484:
1485: /*
1486: * Signal userspace if we're not exiting with a core dump
1487: * because we want to leave the value intact for debugging
1488: * purposes.
1489: */
1490: if (tsk->clear_child_tid) {
1491: if (atomic_read(&mm->mm_users) > 1) {
1492: /*
1493: * We don't check the error code - if userspace has
1494: * not set up a proper pointer then tough luck.
1495: */
1496: put_user(0, tsk->clear_child_tid);
1497: do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1498: 1, NULL, NULL, 0, 0);
1499: }
1500: tsk->clear_child_tid = NULL;
1501: }
1502:
1503: /*
1504: * All done, finally we can wake up parent and return this mm to him.
1505: * Also kthread_stop() uses this completion for synchronization.
1506: */
1507: if (tsk->vfork_done)
1508: complete_vfork_done(tsk);
1509: }
SourceFile:kernel/fork.c]
|
| 276/4 |
2026/09/23 20:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17599
output: 35
thoughts: 95
Thoughts: Okay, here's my assessment of this section, from my perspective as someone well-versed in kernel internals:
**Completion of the vfork Process: A Synchronization Point**
Alright, I'm zeroing in on lines 1507-1508. Seems we're at the very end of the `vfork` process. It's a clean-up stage, a critical moment. Let's see... the code's comment indicates this is the point where the parent process, which has been blocked, can finally be woken up and we're handing the memory management (mm) back. And look, it mentions `kthread_stop()` utilizing the same completion mechanism for synchronization. Hmm, that's interesting.
The if statement checks if `tsk->vfork_done` is true, implying the child's `vfork` completion is the go-ahead. Then there is a function call to `complete_vfork_done(tsk)`. I need to drill into `complete_vfork_done()` now. Gotta understand the specifics of what that function does to wrap my head around the synchronization being used here. Okay, let's see what that function does...
|
| 277/4 |
2026/09/23 20:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:complete_vfork_done]
Results: map[SourceCode:1432: static void complete_vfork_done(struct task_struct *tsk)
1433: {
1434: struct completion *vfork;
1435:
1436: task_lock(tsk);
1437: vfork = tsk->vfork_done;
1438: if (likely(vfork)) {
1439: tsk->vfork_done = NULL;
1440: complete(vfork);
1441: }
1442: task_unlock(tsk);
1443: }
SourceFile:kernel/fork.c]
|
| 278/4 |
2026/09/23 20:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18165
output: 30
thoughts: 1957
Thoughts: **Analyzing a Potential `mm_users` Race Condition in `vfork()` and `dup_mm()`**
Okay, I'm diving into this `vfork()` scenario. Let's see... the prompt describes Task A calling `vfork()`, sharing memory with Task B, and then potentially being killed. The core issue seems to be how `mm_users` is managed when Task A exits, particularly in relation to Task B's actions, and specifically when `Task B` is within `dup_mm`. My immediate thought is, what's the actual state of `mm_users` when A is exiting, and B is in this `dup_mm` function?
I re-read the sequence carefully: Task A, the vfork child, gets killed and exits, eventually calling `mmput()`. If the signal kills A then `exit_mm()` is triggered. I need to understand if `atomic_dec_and_test(&mm->mm_users)` can return true (i.e. reach 0), triggering `__mmput` in Task A while Task B is inside `dup_mm()`. Wait, how can it be? Isn't `mm_users` held by both A and B? If both A and B are alive, `mm_users` is at least 1. So how is it dropping to 0?
I have to trace the references: when `vfork()` happens, `mm_users` starts at 2. Task B then enters the `sys_clone()` call with no `CLONE_VM`, which calls `dup_mm()`. I can see from the `dup_mm` code that the function creates a new `mm` structure (I'll call it new_mm), but also works with the old mm, which is the shared one between A and B, in the call to `dup_mmap()`. So, I'm thinking, B is now in the middle of creating a private copy of the shared memory region but still has a reference to the shared `mm` while A is exiting. What is the impact?
Let's assume A is exiting, and B is still in `dup_mm`. In this case, `oldmm` is still the same one, as mentioned in the prompt. I have to think through where `mm_users` changes: when `vfork` creates the shared mm, it's 2. Then, the parent and the child both increment `mm_users`, each getting a reference to the `oldmm` via `mmget()`. After the parent or the child exits, we must drop `mm_users` to 0. It is critical that A does not drop `mm_users` to 0! How is B still alive and in `dup_mm` if it is 0?
I have to think about the race condition. Could there be a timing issue where B's reference to `oldmm` is lost before `mmput()` is called by A? If A exits and drops `mm_users` to 1, then the `dup_mm` function of `Task B` creates a new mm. I'm wondering if there's a problem, then. But, `dup_mm` is supposed to allocate a new `mm` that isn't connected to the old one after it completes. But A did not call `__mmput` because the user of `mm` would be Task B! So, why is `__mmput` called?
I need to understand what `dup_mm()` actually does with these references. The code suggests that `dup_mm` gets a new `mm` struct, copies the old one, and then duplicates the memory mappings. I'm focusing on the interaction of these two `mm` structures. `dup_mm()` takes the old and creates the new one. And Task B is executing this code path!
Given this, I have to consider the logic. When Task B is executing `dup_mm()`, who owns the reference to the old memory? Task B! So it's not possible that `mm_users` drops to 0. A does NOT call `__mmput`.
Okay, I need to understand what conditions might allow `mm_users` to hit 0 *while* `Task B` is still in `dup_mm()`. I should search for known kernel issues or bugs related to `vfork()`, `mm_users`, and `dup_mm()`. I should also use the commit history for relevant keywords to understand how others have tackled this.
|
| 279/4 |
2026/09/23 20:29 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[dup_mm mmput]]
Results: map[Output:d155df53f310 x86/mm/pat: clear VM_PAT if copy_p4d_range failed
355627f51897 mm, uprobes: fix multiple free of ->uprobes_state.xol_area
2b7e8665b4ff fork: fix incorrect fput of ->exe_file causing use-after-free
ccd5b3235180 x86/mm: Fix use-after-free of ldt_struct
edfe63ec97ed x86/mtrr: Fix Xorg crashes in Qemu sessions
c79c49826270 xen/pat: Disable PAT using pat_enabled value.
61559a8165da uprobes: Fold uprobe_reset_state() into uprobe_dup_mmap()
dcd4a049b975 mm: check for no mmaps in exit_mmap()
74b6b522ec83 KVM: s390: fix locking order problem in enable_sie
]
|
| 280/4 |
2026/09/23 20:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21393
output: 28
thoughts: 22
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing Kernel Commit Messages Related to `complete_vfork_done` and `vfork_done`**
Right, let's dive into this. My immediate thought is to systematically explore the commit logs. We're talking about a critical synchronization point in `vfork`, so I need to understand its evolution. My initial strategy? A targeted search. I'm going to leverage our tooling – likely `git log` or whatever we're using – and focus searches on commit messages that specifically mention `complete_vfork_done` or simply `vfork_done`. The goal is to quickly pinpoint relevant commits. I'm assuming that these keywords will act as breadcrumbs that lead to changes impacting the synchronization. I need to understand when and how this mechanism changed, if at all, as those modifications might offer clues to the current behavior. This targeted approach is more efficient than a broad sweep, allowing me to hone in on the core of the implementation. I'm expecting this will quickly surface specific commits and, from there, allow me to begin parsing relevant code diffs.
|
| 281/4 |
2026/09/23 20:30 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[complete_vfork_done]]
Results: map[Output:efb29fbfa50c kthread: Don't use to_live_kthread() in kthread_stop()
355f1ecbcc81 thinkpad-acpi: kill hotkey_thread_mutex
f7505d64f2db fork: call complete_vfork_done() after clearing child_tid and flushing rss-counters
57b59c4a1400 coredump_wait: don't call complete_vfork_done()
d68b46fe16ad vfork: make it killable
c415c3b47ea2 vfork: introduce complete_vfork_done()
]
|
| 282/4 |
2026/09/23 20:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21854
output: 25
thoughts: 71
Thoughts: Here's my analysis of the provided commit history, thinking as an expert in the field:
**Diving Deep into vfork and its Killability**
Alright, let's get into it. My initial reaction is to immediately examine those commits, especially considering that `vfork` always comes with significant complexity. It is necessary to examine `d68b46fe16ad vfork: make it killable`, alongside its associated commits, `f7505d64f2db` and `57b59c4a1400`, as this is clearly a critical area. My focus is sharpened because the core issue sounds like a potential race condition or signal handling issue related to how `vfork` is handled. Specifically, it sounds like there are concerns about the child process' ability to be killed without leaving behind orphaned resources. This likely revolves around the subtle differences between `fork` and `vfork` and how they manage the virtual address space and process state. Let's start with `d68b46fe16ad` and see what the specifics were that triggered that commit. We'll trace the logic.
|
| 283/4 |
2026/09/23 20:30 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d68b46fe16ad59b3a5f51ec73daaa5dc06753798
Author: Oleg Nesterov <oleg@redhat.com>
Date: Mon Mar 5 14:59:13 2012 -0800
vfork: make it killable
Make vfork() killable.
Change do_fork(CLONE_VFORK) to do wait_for_completion_killable(). If it
fails we do not return to the user-mode and never touch the memory shared
with our child.
However, in this case we should clear child->vfork_done before return, we
use task_lock() in do_fork()->wait_for_vfork_done() and
complete_vfork_done() to serialize with each other.
Note: now that we use task_lock() we don't really need completion, we
could turn task->vfork_done into "task_struct *wake_up_me" but this needs
some complications.
NOTE: this and the next patches do not affect in-kernel users of
CLONE_VFORK, kernel threads run with all signals ignored including
SIGKILL/SIGSTOP.
However this is obviously the user-visible change. Not only a fatal
signal can kill the vforking parent, a sub-thread can do execve or
exit_group() and kill the thread sleeping in vfork().
Signed-off-by: Oleg Nesterov <oleg@redhat.com>
Acked-by: Tejun Heo <tj@kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/include/linux/sched.h b/include/linux/sched.h
index 1b25a37f2aee..b6467711f12e 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -2372,7 +2372,7 @@ static inline int thread_group_empty(struct task_struct *p)
* Protects ->fs, ->files, ->mm, ->group_info, ->comm, keyring
* subscriptions and synchronises with wait4(). Also used in procfs. Also
* pins the final release of task.io_context. Also protects ->cpuset and
- * ->cgroup.subsys[].
+ * ->cgroup.subsys[]. And ->vfork_done.
*
* Nests both inside and outside of read_lock(&tasklist_lock).
* It must not be nested with write_lock_irq(&tasklist_lock),
diff --git a/kernel/fork.c b/kernel/fork.c
index cf3d96379608..892c534ce6e3 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -670,10 +670,34 @@ struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
void complete_vfork_done(struct task_struct *tsk)
{
- struct completion *vfork_done = tsk->vfork_done;
+ struct completion *vfork;
- tsk->vfork_done = NULL;
- complete(vfork_done);
+ task_lock(tsk);
+ vfork = tsk->vfork_done;
+ if (likely(vfork)) {
+ tsk->vfork_done = NULL;
+ complete(vfork);
+ }
+ task_unlock(tsk);
+}
+
+static int wait_for_vfork_done(struct task_struct *child,
+ struct completion *vfork)
+{
+ int killed;
+
+ freezer_do_not_count();
+ killed = wait_for_completion_killable(vfork);
+ freezer_count();
+
+ if (killed) {
+ task_lock(child);
+ child->vfork_done = NULL;
+ task_unlock(child);
+ }
+
+ put_task_struct(child);
+ return killed;
}
/* Please note the differences between mmput and mm_release.
@@ -717,7 +741,8 @@ void mm_release(struct task_struct *tsk, struct mm_struct *mm)
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
- * trouble otherwise. Userland only wants this done for a sys_exit.
+ * trouble, say, a killed vfork parent shouldn't touch this mm.
+ * Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid) {
if (!(tsk->flags & PF_SIGNALED) &&
@@ -1551,6 +1576,7 @@ long do_fork(unsigned long clone_flags,
if (clone_flags & CLONE_VFORK) {
p->vfork_done = &vfork;
init_completion(&vfork);
+ get_task_struct(p);
}
/*
@@ -1568,10 +1594,8 @@ long do_fork(unsigned long clone_flags,
ptrace_event(trace, nr);
if (clone_flags & CLONE_VFORK) {
- freezer_do_not_count();
- wait_for_completion(&vfork);
- freezer_count();
- ptrace_event(PTRACE_EVENT_VFORK_DONE, nr);
+ if (!wait_for_vfork_done(p, &vfork))
+ ptrace_event(PTRACE_EVENT_VFORK_DONE, nr);
}
} else {
nr = PTR_ERR(p);
]
|
| 284/4 |
2026/09/23 20:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 23751
output: 26
thoughts: 21
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing Commit f7505d64f2db: A Quick Scan**
Alright, let's pull up commit `f7505d64f2db` and take a look. I need to quickly assess its impact and relevance. My initial questions are: what changes are made? What specific files or modules are involved? Does it affect any of the core components I'm most interested in? Is this commit likely to introduce any bugs or regressions based on my current understanding of the codebase? I need to quickly grasp the intention of the modification, even just its primary purpose. And does this commit's author have a history? Are there any patterns or issues?
So, while I'm not going to deep-dive into the entire commit right away, I'm going to start with a broad overview. The goal is to quickly determine if it warrants more thorough scrutiny or if I can tentatively mark it as low-impact.
|
| 285/4 |
2026/09/23 20:30 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f7505d64f2db5da2d7d94873ddf2cd2524847061
Author: Konstantin Khlebnikov <khlebnikov@openvz.org>
Date: Thu May 31 16:26:21 2012 -0700
fork: call complete_vfork_done() after clearing child_tid and flushing rss-counters
Child should wake up the parent from vfork() only after finishing all
operations with shared mm. There is no sense in using
CLONE_CHILD_CLEARTID together with CLONE_VFORK, but it looks more accurate
now.
Signed-off-by: Konstantin Khlebnikov <khlebnikov@openvz.org>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Hugh Dickins <hughd@google.com>
Cc: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Cc: Konstantin Khlebnikov <khlebnikov@openvz.org>
Cc: Markus Trippelsdorf <markus@trippelsdorf.de>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/kernel/fork.c b/kernel/fork.c
index 017fb23d5983..2254fbf23567 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -787,9 +787,6 @@ void mm_release(struct task_struct *tsk, struct mm_struct *mm)
/* Get rid of any cached register state */
deactivate_mm(tsk, mm);
- if (tsk->vfork_done)
- complete_vfork_done(tsk);
-
/*
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
@@ -810,6 +807,13 @@ void mm_release(struct task_struct *tsk, struct mm_struct *mm)
}
tsk->clear_child_tid = NULL;
}
+
+ /*
+ * All done, finally we can wake up parent and return this mm to him.
+ * Also kthread_stop() uses this completion for synchronization.
+ */
+ if (tsk->vfork_done)
+ complete_vfork_done(tsk);
}
/*
]
|
| 286/4 |
2026/09/23 20:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24687
output: 26
thoughts: 574
Thoughts: **Analyzing vfork() and Memory Management in the Kernel**
Okay, hold on a second. Khlebnikov's comment... it's about the child *waking* the parent from `vfork()` only *after* finishing all operations with shared memory. And where is `complete_vfork_done()`? It's buried in `mm_release()`, which, as I recall, is called in `mm_exit_exec_release()`. Aha! And that, in turn, is triggered from within `exit_mm()` – specifically the call to `mm_release()` from within `mm_exit_exec_release()`. So, the whole thing goes like this: `exit_mm()` is what the child calls when it exits. Inside `exit_mm()` is where `mm_exit_exec_release()` is called. Within that call, is `mm_release()`. And *there*, if `tsk->vfork_done` is set, we call `complete_vfork_done(tsk)`. But, *tsk* is the child.
Crucially, the child calls `mm_release()` *before* `exit_mm()` calls `mmput(mm)`. I need to think this through. The child calls `complete_vfork_done()`, and that wakes the parent... which had been blocked in `wait_for_vfork_done()`. Right. So the parent wakes up and what's next? The parent is returning from `wait_for_vfork_done()`, then from `kernel_clone()`, and back to userspace! Or, it's returning from vfork(). Okay, so what is the timing window? Could the parent potentially do something while the child is *still* in `exit_mm()`? What could the parent do? Or what could the child do?
I need to dig deeper here. Let me search the Git log for commits. I'll need to check the commits by Oleg Nesterov, Konstantin Khlebnikov, Jann Horn, and Linus Torvalds. I'll search for anything related to `mmput`, `dup_mm`, `complete_vfork_done`, `vfork_done`, or `mm_users`. Let me try a regex search to be more targeted. I need to be precise here.
|
| 287/4 |
2026/09/23 20:31 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[vfork_done]]
Results: map[Output:1eb69ded8051 kunit: Fix race condition in try-catch completion
3a35c13007de kunit: Handle test faults
331955600ddf x86/shstk: Handle vfork clone failure correctly
33a2d6bc3480 Revert "fs/exec: allow to unshare a time namespace on vfork+exec"
40966e316f86 kthread: Ensure struct kthread is present for all kthreads
efb29fbfa50c kthread: Don't use to_live_kthread() in kthread_stop()
cd42d559e45e kthread: implement probe_kthread_data()
4ecdafc8084f kthread: introduce to_live_kthread()
355f1ecbcc81 thinkpad-acpi: kill hotkey_thread_mutex
f7505d64f2db fork: call complete_vfork_done() after clearing child_tid and flushing rss-counters
]
|
| 288/4 |
2026/09/23 20:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 26046
output: 30
thoughts: 50
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Investigating Memory Management Anomalies in a Concurrency Context**
Right, before diving headfirst into this issue, I need to get a clear picture of its history. My initial instinct is to dig through the Git log. But instead of blindly sifting, I want to be surgical. I'm going to leverage some powerful regular expressions.
I'm thinking, "mm_users" is a good starting point to identify code related to my target area, as are "dup_mm" or "vfork". So, I'll start running some git log searches with combinations of the following: `["mm_users", "dup_mm"]`, `["mm_users", "vfork"]` and `["dup_mm", "vfork"]`. That should pinpoint changesets which may have introduced or exacerbated the problem I'm seeing. This approach allows me to quickly identify related commits, examine the exact code modifications, and establish a timeline. By zeroing in on those specific keywords, I'm expecting to uncover potential culprits or, at the very least, understand the evolution of the relevant code segments.
|
| 289/4 |
2026/09/23 20:31 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[mm_users vfork]]
Results: map[Output:67197a4f28d2 mm, oom_adj: don't loop through tasks in __set_oom_adj when not necessary
]
|
| 290/4 |
2026/09/23 20:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 26426
output: 30
thoughts: 35
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Investigating Potential Resource Duplication with `vfork`**
Alright, I need to get to the bottom of this. My gut tells me there might be some issues related to how we're handling resource duplication, specifically in conjunction with `vfork`. The most efficient way to dig into this in the codebase is, of course, the `git log`. What I'm going to do is refine my search using regular expressions. I'll need to focus the search to isolate commits that might be relevant to the interaction between memory mapping, process creation with `vfork`, and resource duplication.
So, I'll start with two potential regex searches: one looking for commits that involve modifications around `dup_mm` combined with `vfork` and one with `dup_mmap` and `vfork`, to pinpoint potential interactions that lead to subtle bugs. The goal is to see if any specific commits related to `dup_mm` or `dup_mmap` that also touch `vfork` are present in the log. This should help me quickly identify code changes that could be implicated in the issues I'm seeing. If I'm lucky, the commit messages themselves will be descriptive enough to point me in the right direction, or at least suggest areas for more focused investigation.
|
| 291/4 |
2026/09/23 20:32 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[dup_mm vfork]]
Results:
|
| 292/4 |
2026/09/23 20:33 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 26789
output: 31
thoughts: 39
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience:
**Memory Management Investigation: Initial Approach**
Alright, the initial inspection yielded nothing of immediate interest. This suggests the issue isn't blatantly obvious and requires a more targeted approach. Given my understanding of typical memory management problem areas, I'm going to start by focusing on potential reference counting issues, or duplicated memory mappings and their subsequent unmapping. I'll need to explore potential use-after-free, double frees, or leaks. Specifically, I'll begin by searching for instances of the functions or calls related to these areas, namely functions or calls that reference either of these tags `["dup_mm"]`, `["dup_mmap"]`, `["exit_mm"]`, or `["mmput"]`. This will allow me to narrow my focus and hopefully uncover the root cause of the problem quickly. I'm expecting to find either a clear culprit or, perhaps more likely, a set of related code that requires deeper analysis.
|
| 293/4 |
2026/09/23 20:33 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[dup_mmap mmput]]
Results: map[Output:d155df53f310 x86/mm/pat: clear VM_PAT if copy_p4d_range failed
355627f51897 mm, uprobes: fix multiple free of ->uprobes_state.xol_area
2b7e8665b4ff fork: fix incorrect fput of ->exe_file causing use-after-free
edfe63ec97ed x86/mtrr: Fix Xorg crashes in Qemu sessions
c79c49826270 xen/pat: Disable PAT using pat_enabled value.
61559a8165da uprobes: Fold uprobe_reset_state() into uprobe_dup_mmap()
dcd4a049b975 mm: check for no mmaps in exit_mmap()
]
|
| 294/4 |
2026/09/23 20:33 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 27286
output: 32
thoughts: 20
Thoughts: Here's my thought process, summarized as you requested:
**Navigating Memory Management**
Okay, I need to zero in on the relevant memory management calls. Instead of a broad search, let's get specific. Thinking strategically, I'll leverage a search string to efficiently target these areas. The keywords I'll focus on are `["exit_mm", "dup_mmap"]`. These are likely to quickly surface the most relevant code paths and logic related to process termination and address space duplication within the kernel. This focused approach will save time and yield more precise results than a more generalized query.
|
| 295/4 |
2026/09/23 20:34 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[exit_mm dup_mmap]]
Results: map[Output:43873af772f8 mm: change dup_mmap() recovery
bed76bec3111 mm: relocate the page table ceiling and floor definitions
1367da7eb875 mm: swap: check for stable address space before operating on the VMA
64c37e134b12 kernel: be more careful about dup_mmap() failures and uprobe registering
d24062914837 fork: use __mt_dup() to duplicate maple tree in dup_mmap()
d155df53f310 x86/mm/pat: clear VM_PAT if copy_p4d_range failed
c9ae1b10d956 x86/paravirt: Merge activate_mm() and dup_mmap() callbacks
655c79bb40a0 mm: check for SIGKILL inside dup_mmap() loop
edfe63ec97ed x86/mtrr: Fix Xorg crashes in Qemu sessions
a1ea1c032b8f x86: Cleanly separate use of asm-generic/mm_hooks.h
]
|
| 296/4 |
2026/09/23 20:34 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 27747
output: 32
thoughts: 926
Thoughts: **Analyzing a Complex `vfork()` Scenario**
Okay, let me break this down. This `vfork()` scenario is trickier than it first appears. Let's trace it and see where the problem lies. The core of my concern here seems to be about memory management and race conditions between a `vfork()` parent and child when the parent is killed or when they continue using the same memory after the `vfork`.
First, I need to be absolutely certain I understand the context. Specifically, what happens if Task A (the parent in the initial thought process), is killed *while* it's waiting in `wait_for_vfork_done()` after calling `vfork()` and sharing the memory with its child, Task B. It seems the critical question is when and how `mm_users` gets decremented. If I'm reading this correctly, it looks like `Task B` also has `mm_users` incremented from 1 to 2 by `mmget(oldmm)`. Then, in this scenario, if the parent is killed, `mmput()` is called by the exiting parent and decrements the `mm_users` from 2 to 1 and *not* to 0.
But there is a second scenario, where the roles are reversed. It looks like the scenario being investigated is when *Task B* calls `vfork()` and Task A is the child. Then Task A exits, `mm_users` is decremented in `exit_mm()` from 2 to 1. But *then* what happens if Task B wakes up before Task A completely exits? Task B is awake *before* Task A calls `exit_mm()`!
Okay, let's step through the logic carefully, assuming Task B is the parent, Task A the child. Task B calls `vfork()`: The memory is shared. Task B waits. Task A exits, and decrements `mm_users` from 2 to 1. Then Task B wakes up, returns to userspace. Then it calls `sys_clone()` without `CLONE_VM`, now, Task B still has `current->mm == oldmm`. So `mm_users` should be at least 1.
The crucial question is, how does `__mmput` get called in Task A? Since I'm an expert, it is not unreasonable that I would be thinking these thoughts:
I can see the decrement, but I need to understand when `__mmput` gets called here. `mm_users` should never go to 0 because Task B is still alive and also has a reference to the `oldmm`. I need to figure out what triggers the call to `__mmput` in these specific `vfork()` scenarios. Am I missing something? How is the memory actually being released in this race condition?
The main point is the interaction of memory management when parent and child may have a similar `mm` in the `vfork()` context, *especially* when the parent is terminated early.
|
| 297/4 |
2026/09/23 20:34 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:do_exit]
Results: map[SourceCode: 932: void __noreturn do_exit(long code)
933: {
934: struct task_struct *tsk = current;
935: struct kthread *kthread;
936: int group_dead;
937:
938: WARN_ON(irqs_disabled());
939: WARN_ON(tsk->plug);
940:
941: kthread = tsk_is_kthread(tsk);
942: if (unlikely(kthread))
943: kthread_do_exit(kthread, code);
944:
945: kcov_task_exit(tsk);
946: kmsan_task_exit(tsk);
947:
948: synchronize_group_exit(tsk, code);
949: ptrace_event(PTRACE_EVENT_EXIT, code);
950: user_events_exit(tsk);
951:
952: io_uring_files_cancel();
953: sched_mm_cid_exit(tsk);
954: exit_signals(tsk); /* sets PF_EXITING */
955:
956: seccomp_filter_release(tsk);
957:
958: acct_update_integrals(tsk);
959: group_dead = atomic_dec_and_test(&tsk->signal->live);
960: if (group_dead) {
961: /*
962: * If the last thread of global init has exited, panic
963: * immediately to get a useable coredump.
964: */
965: if (unlikely(is_global_init(tsk)))
966: panic("Attempted to kill init! exitcode=0x%08x\n",
967: tsk->signal->group_exit_code ?: (int)code);
968:
969: #ifdef CONFIG_POSIX_TIMERS
970: hrtimer_cancel(&tsk->signal->real_timer);
971: exit_itimers(tsk);
972: #endif
973: if (tsk->mm)
974: setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
975: }
976: acct_collect(code, group_dead);
977: if (group_dead)
978: tty_audit_exit();
979: audit_free(tsk);
980:
981: tsk->exit_code = code;
982: taskstats_exit(tsk, group_dead);
983: trace_sched_process_exit(tsk, group_dead);
984:
985: /*
986: * Since sampling can touch ->mm, make sure to stop everything before we
987: * tear it down.
988: *
989: * Also flushes inherited counters to the parent - before the parent
990: * gets woken up by child-exit notifications.
991: */
992: perf_event_exit_task(tsk);
993: /*
994: * PF_EXITING (above) ensures unwind_deferred_request() will no
995: * longer add new unwinds. While exit_mm() (below) will destroy the
996: * abaility to do unwinds. So flush any pending unwinds here.
997: */
998: unwind_deferred_task_exit(tsk);
999:
1000: exit_mm();
1001:
1002: if (group_dead)
1003: acct_process();
1004:
1005: exit_sem(tsk);
1006: exit_shm(tsk);
1007: exit_files(tsk);
1008: exit_fs(tsk);
1009: if (group_dead)
1010: disassociate_ctty(1);
1011: exit_nsproxy_namespaces(tsk);
1012: exit_task_work(tsk);
1013: exit_thread(tsk);
1014:
1015: sched_autogroup_exit_task(tsk);
1016: cgroup_task_exit(tsk);
1017:
1018: /*
1019: * FIXME: do that only when needed, using sched_exit tracepoint
1020: */
1021: flush_ptrace_hw_breakpoint(tsk);
1022:
1023: exit_tasks_rcu_start();
1024: exit_notify(tsk, group_dead);
1025: proc_exit_connector(tsk);
1026: mpol_put_task_policy(tsk);
1027: #ifdef CONFIG_FUTEX
1028: if (unlikely(current->futex.pi_state_cache))
1029: kfree(current->futex.pi_state_cache);
1030: #endif
1031: /*
1032: * Make sure we are holding no locks:
1033: */
1034: debug_check_no_locks_held();
1035:
1036: if (tsk->io_context)
1037: exit_io_context(tsk);
1038:
1039: if (tsk->splice_pipe)
1040: free_pipe_info(tsk->splice_pipe);
1041:
1042: if (tsk->task_frag.page)
1043: put_page(tsk->task_frag.page);
1044:
1045: exit_task_stack_account(tsk);
1046:
1047: check_stack_usage();
1048: preempt_disable();
1049: if (tsk->nr_dirtied)
1050: __this_cpu_add(dirty_throttle_leaks, tsk->nr_dirtied);
1051: exit_rcu();
1052: exit_tasks_rcu_finish();
1053:
1054: lockdep_free_task(tsk);
1055: do_task_dead();
1056: }
SourceFile:kernel/exit.c]
|
| 298/4 |
2026/09/23 20:34 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 31137
output: 30
thoughts: 2529
Thoughts: **Analyzing `mmput` and `__mmput` in a vfork/clone Scenario**
Okay, let's break this down. We're looking at a scenario with two tasks, Task A and Task B, where `vfork` or `clone` are involved, and specifically at the race condition potential between `mmput` calls. The core question is: can Task A's `mmput` *ever* trigger `__mmput` (effectively freeing the memory map) when Task B is in a `dup_mm` state? It seems like it cannot, or CAN IT?!
My initial thought process went like this: I started by tracing the execution path of `do_exit()` for Task A after `mm_release()` in relation to how Task B's state could affect memory map reference counts (`mm_users`). I focused on the order of operations, particularly the call to `complete_vfork_done` and how that relates to the parent (Task B) waking up. I need to fully understand if the parent task wakes before the child task (Task A) completes the `exit_mm()` process. If Task B wakes up *before* Task A has a chance to drop the reference count, that's important.
I then followed the logic, noting that Task B can become alive by either vfork parent or vfork child. If Task B calls `sys_clone()` *without* `CLONE_VM` right after waking, it will enter `dup_mm()`. This means that it has its own, distinct memory map. Crucially, the problem described keeps emphasizing that if Task B is alive, `mm_users` is at least 1, and so there is a race condition. It is not obvious how `__mmput` can be called from Task A in this case.
Here's the problem: Task A, in `exit_mm()`, calls `mmput(mm)`. I see that if Task B is alive, it means `mm_users` can't go to zero. So how could Task A trigger `__mmput`?
The prompt made me re-read everything! And that gets me thinking about the exact state and timing in `exit_mm()` and `dup_mm()`!
I revisited the states, specifically when `vfork()` is called by Task B (parent) or Task A (child). I went through the `mm_release()` execution, including the order, and then went back to think about multithreaded processes, in case that affects memory maps.
I considered if a signal killed Task A before its `mmput`!
The crucial detail seems to be the order of events when the parent awakens after the `vfork`. Task B could return to userspace, then call `clone()` *without* `CLONE_VM`. This is a crucial distinction. In this case, `dup_mm` gets called. Now, both have the same memory map, but `mm_users` would be 2, one for Task A (exiting) and one for Task B (in userspace).
Then it is still the same problem: when Task A calls `mmput()`, `atomic_dec_and_test` will only take it to 1, and `__mmput` is *not* called. And yet the question implies that the `__mmput()` *could* be called from Task A.
So the main thing now: Is the question saying that `__mmput()` *cannot* be called, or that it *can* be called and that it is a potential race condition?
I need to be very precise in my answer. If the answer is it can, then I need to figure out how!
|
| 299/4 |
2026/09/23 20:34 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[wait_for_vfork_done]]
Results: map[Output:d68b46fe16ad vfork: make it killable
]
|
| 300/4 |
2026/09/23 20:35 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 34515
output: 31
thoughts: 18
Thoughts: Okay, here's my interpretation of those thoughts, summarized from a first-person expert perspective:
**Investigating Potential Resource Leaks in Memory Management**
Alright, let's get down to brass tacks. My initial instinct is to dig into the commit history related to `vfork_done` and `mmput`. These are key functions tied to process creation and memory management, respectively. The mention of both immediately triggers a "memory leak" red flag in my mind. `vfork_done` deals with the aftermath of a `vfork` call, a process that can be notoriously tricky to manage in terms of resource cleanup if handled incorrectly. And `mmput`, well, that's the canonical function for decrementing the reference count of a memory map (mm_struct). A mismatch in increment/decrement logic is the most common reason for resource leaks. So, the goal is to pinpoint commits that touch these functions, especially in conjunction, because changes in one are very likely to affect the other. I want to see how these functions are used, how they interact, and if there are any subtle omissions or incorrect usage patterns that might indicate a vulnerability or a performance problem. I'm thinking of looking for anything related to memory exhaustion, incorrect reference counting, or unexpected process behaviors related to `vfork`.
|
| 301/4 |
2026/09/23 20:35 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[vfork_done mmput]]
Results:
|
| 302/4 |
2026/09/23 20:36 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 34848
output: 33
thoughts: 20
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and rendered in the first person:
**Analyzing Kernel Commit Messages Related to `CLONE_VFORK` and `mmput`**
Right, let's dive in. My initial thought process here is to zero in on specific areas of the kernel that might be undergoing interesting developments or bug fixes related to `CLONE_VFORK` and `mmput`. Searching commit messages is a pretty standard approach, obviously, but it's important to be targeted. I'm assuming that by specifying those two identifiers, the goal is likely to identify changes related to interactions between `vfork` and memory management, particularly around resource cleanup or potential vulnerabilities. Perhaps looking for regressions or performance improvements? This might be the right place to start digging into the intricacies of these features. It'll give me a clear picture of related activity in the kernel source, and where the most recent efforts have been focused. Time to formulate those queries...
|
| 303/4 |
2026/09/23 20:36 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[CLONE_VFORK mmput]]
Results:
|
| 304/4 |
2026/09/23 20:36 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 35124
output: 28
thoughts: 28
Thoughts: Here's my thought process, summarized as you requested:
**Investigating Memory Management in the Kernel with Commit Messages**
Okay, so I'm diving into memory management within the kernel. I need to get a handle on how these clone operations are behaving with respect to memory duplication. My initial thought is to zero in on specific commit messages as a starting point. I'll need to use some targeted searches to unearth relevant code changes.
Specifically, I'm going to look for any commit messages that mention `CLONE_VFORK`, because that tells us about a specific type of process creation with interesting memory behaviors. I also want to look at messages mentioning functions related to memory map duplication. The key phrases I'm thinking of searching for are `dup_mm` or `dup_mmap`. Using these search terms, I should be able to identify key commits that relate to the areas of memory management I am focusing on. This will give me a timeline of changes, and likely allow me to understand specific details that have led to improvements, or potentially introduced, bugs within the cloning mechanism.
|
| 305/4 |
2026/09/23 20:37 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[CLONE_VFORK]]
Results: map[Output:fd44a4a85516 riscv/shstk: If needed allocate a new shadow stack on clone
130e42806773 selftests/harness: Fix tests timeout and race condition
f453cc30027b selftests/harness: Fix vfork() side effects
24cf65a62266 selftests/harness: Share _metadata between forked processes
a86f18903db9 selftests/harness: Fix interleaved scheduling leading to race conditions
331955600ddf x86/shstk: Handle vfork clone failure correctly
b2926a36b97a x86/shstk: Handle thread shadow stack
33a2d6bc3480 Revert "fs/exec: allow to unshare a time namespace on vfork+exec"
133e2d3e81de fs/exec: allow to unshare a time namespace on vfork+exec
67197a4f28d2 mm, oom_adj: don't loop through tasks in __set_oom_adj when not necessary
7f6def9f9b6e usermodehelper: kill the kmod_thread_locker logic
7117bc8888af usermodehelper: don't use CLONE_VFORK for ____call_usermodehelper()
3ab679661721 uprobes: Teach uprobe_copy_process() to handle CLONE_VFORK
7ff6764061ec usermodehelper: cleanup/fix __orderly_poweroff() && argv_free()
0f20784d4ba3 kmod: avoid deadlock from recursive kmod call
f7505d64f2db fork: call complete_vfork_done() after clearing child_tid and flushing rss-counters
57b59c4a1400 coredump_wait: don't call complete_vfork_done()
d68b46fe16ad vfork: make it killable
d47419cd967a call_usermodehelper: simplify/fix UMH_NO_WAIT case
87f76d3aafe5 [IA64] find thread for user rbs address
]
|
| 306/4 |
2026/09/23 20:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 35975
output: 28
thoughts: 920
Thoughts: **Analyzing Potential MM Double-Free Vulnerability in `vfork()` Scenario**
Okay, let's break this down. My goal here is to understand a potential double-free scenario related to `vfork()`. Specifically, I'm trying to determine if `mmput(mm)` called by Task A can trigger `__mmput` *while* Task B is in `dup_mm` (or any other function which increments `mm_users`). The user's query is the fundamental question here.
First, I start by mentally tracing the execution flow. I need to understand when and how `mm_users` is manipulated in the context of `vfork()`. My initial thoughts were to grep for `mmput` calls, specifically within `kernel/fork.c` and `kernel/exit.c` to see how these might interact. Then I considered the case of `exit_mm()` being called.
Thinking carefully about the `vfork()` process, Task A calls `vfork()`. This sets `clone_flags` to `CLONE_VFORK | CLONE_VM`. `copy_mm()` would copy the `oldmm`. Then `mm_users` is set to 2 through `mmget`. Task A then waits on `wait_for_vfork_done()`. Task B, the child, now shares this memory space. Now, what if Task A is killed? When it exits, `exit_mm()` gets called, which decrements `mm_users`. Here's the critical point: *Task A does NOT call `__mmput` at this stage*. It's a single decrement.
I then considered various scenarios: what if Task B exits before Task A? What if Task A is the *child* in the `vfork()` scenario, and Task B is the parent? And then the reverse. What if the order of execution is critical? Specifically, what happens if Task B wakes up *before* Task A gets to `exit_mm()`? Task B could then create its own `mm` potentially.
The core question is this: can Task A's `mmput(mm)` ever drop `mm_users` to zero prematurely, causing `__mmput` to be called and potentially freeing memory that Task B still needs?
I have to carefully analyze the lifecycle of `mm_users`. I need to figure out every place where `mm_users` is incremented or decremented. I'm going to search for modifications to `mm_users` to map this correctly.
Finally, I need to evaluate the possibilities: can this vulnerability even exist? If so, *how*? Or can it *not* exist, and, if not, *why*? I need to analyze the conditions under which `mmput(mm)` could possibly trigger `__mmput` while Task B is in `dup_mm`. My analysis hinges on tracking how many users are sharing this memory space, and the sequence of their exit and memory management calls.
|
| 307/4 |
2026/09/23 20:37 |
tool |
grepper |
0m
Args: map[Expression:mm_users PathPrefix:kernel/fork.c]
Results: map[Output:kernel/fork.c=676=static void cleanup_lazy_tlbs(struct mm_struct *mm)
--
kernel/fork.c-707- * lock, to filter out false-positives in the cpumask.
kernel/fork.c:708: * - After mm_users or mm_count reaches zero, switching away from the
kernel/fork.c-709- * mm could clear mm_cpumask to reduce some IPIs, perhaps together
--
kernel/fork.c=1091=static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
--
kernel/fork.c-1094- mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
kernel/fork.c:1095: atomic_set(&mm->mm_users, 1);
kernel/fork.c-1096- atomic_set(&mm->mm_count, 1);
--
kernel/fork.c=1185=static inline void __mmput(struct mm_struct *mm)
kernel/fork.c-1186-{
kernel/fork.c:1187: VM_BUG_ON(atomic_read(&mm->mm_users));
kernel/fork.c-1188-
--
kernel/fork.c=1211=void mmput(struct mm_struct *mm)
--
kernel/fork.c-1214-
kernel/fork.c:1215: if (atomic_dec_and_test(&mm->mm_users))
kernel/fork.c-1216- __mmput(mm);
--
kernel/fork.c=1229=void mmput_async(struct mm_struct *mm)
kernel/fork.c-1230-{
kernel/fork.c:1231: if (atomic_dec_and_test(&mm->mm_users)) {
kernel/fork.c-1232- INIT_WORK(&mm->async_put_work, mmput_async_fn);
--
kernel/fork.c=1478=static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
--
kernel/fork.c-1490- if (tsk->clear_child_tid) {
kernel/fork.c:1491: if (atomic_read(&mm->mm_users) > 1) {
kernel/fork.c-1492- /*
]
|
| 308/4 |
2026/09/23 20:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 38188
output: 37
thoughts: 24
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:
**Investigating `mmget` and `mmput` Callers**
Alright, time to dig in. My immediate thought is to trace the lineage of `mmget` and `mmput`. I need to understand where these functions are being invoked. I'm especially interested in the contexts that surround these calls, that is, the purpose they serve within the system. What are the calling sequences? Are there any patterns? Ultimately, I want to form an informed picture of the memory management profile, and knowing how these functions are used is a critical first step. The goal is to identify potential bottlenecks, inefficiencies, or areas for optimization within the memory allocation and deallocation strategies. So, let's start by mapping out where `mmget` is called. Let's see how things are tied up.
|
| 309/4 |
2026/09/23 20:37 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:1 Name:mmget]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:____bpf_find_vma SourceFile:kernel/bpf/task_iter.c SourceLine:784 SourceSnippet: 783: if (mm && !(task->flags & PF_KTHREAD)) {
784: mmget(mm);
785: mmput_needed = true;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:bpf_iter_task_vma_new SourceFile:kernel/bpf/task_iter.c SourceLine:913 SourceSnippet: 912: if (kit->data->mm && !(task->flags & PF_KTHREAD))
913: mmget(kit->data->mm);
914: else
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_mm SourceFile:kernel/fork.c SourceLine:1592 SourceSnippet:1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:find_mm_struct SourceFile:mm/migrate.c SourceLine:2563 SourceSnippet:2562: if (!pid) {
2563: mmget(current->mm);
2564: *mem_nodes = cpuset_mems_allowed(current);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:futex_ref_drop SourceFile:kernel/futex/core.c SourceLine:1711 SourceSnippet:1710: */
1711: mmget(mm);
1712:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:get_task_mm SourceFile:kernel/fork.c SourceLine:1394 SourceSnippet:1393: if (mm)
1394: mmget(mm);
1395: task_unlock(task);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2756 SourceSnippet:2755: prev_mm = &init_mm;
2756: mmget(prev_mm);
2757:
]] TruncatedOutput:false]
|
| 310/4 |
2026/09/23 20:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 39147
output: 41
thoughts: 29
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, presented in the first person:
**Focusing on `mmget()` Usage**
Alright, so I'm looking at this code, and the first thing that jumps out is that the calls to `mmget()` are surprisingly limited. That's good, less surface area for potential issues. Now, I want to pivot to investigating `mmget_not_zero()`. It makes sense to check both functions, since `mmget()` likely forms the foundation, and there could be subtle nuances in the logic of the `mmget_not_zero()` variant. I'm thinking, are there any patterns in how `mmget()` is *not* used, and how does `mmget_not_zero()` relate to that? I need to quickly establish the relationship between them and, as always, be on the lookout for unexpected usage scenarios that might be triggered by zero values or other edge cases. Let's see what we can find.
|
| 311/4 |
2026/09/23 20:38 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:1 Name:mmget_not_zero]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:build_map_info SourceFile:kernel/events/uprobes.c SourceLine:1235 SourceSnippet:1234:
1235: if (!mmget_not_zero(vma->vm_mm))
1236: continue;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:do_procmap_query SourceFile:fs/proc/task_mmu.c SourceLine:717 SourceSnippet: 716:
717: if (!mm || !mmget_not_zero(mm))
718: return -ESRCH;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:environ_read SourceFile:fs/proc/base.c SourceLine:1005 SourceSnippet:1004: ret = 0;
1005: if (!mmget_not_zero(mm))
1006: goto free;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ep_user_copy_worker SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:474 SourceSnippet: 473:
474: if (mmget_not_zero(mm)) {
475: kthread_use_mm(mm);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ffs_user_copy_worker SourceFile:drivers/usb/gadget/function/f_fs.c SourceLine:879 SourceSnippet: 878: if (io_data->read && ret > 0) {
879: if (mmget_not_zero(io_data->mm)) {
880: kthread_use_mm(io_data->mm);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ib_umem_odp_alloc_child SourceFile:drivers/infiniband/core/umem_odp.c SourceLine:200 SourceSnippet: 199: */
200: if (!mmget_not_zero(umem->owning_mm)) {
201: ret = -EFAULT;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ib_umem_odp_map_dma_and_lock SourceFile:drivers/infiniband/core/umem_odp.c SourceLine:348 SourceSnippet: 347: owning_process = get_pid_task(umem_odp->tgid, PIDTYPE_PID);
348: if (!owning_process || !mmget_not_zero(owning_mm)) {
349: ret = -EINVAL;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:iommu_sva_handle_mm SourceFile:drivers/iommu/iommu-sva.c SourceLine:234 SourceSnippet: 233:
234: if (!mmget_not_zero(mm))
235: return status;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:m_start SourceFile:fs/proc/task_mmu.c SourceLine:325 SourceSnippet: 324: mm = lock_ctx->mm;
325: if (!mm || !mmget_not_zero(mm)) {
326: put_task_struct(priv->task);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:mem_rw SourceFile:fs/proc/base.c SourceLine:897 SourceSnippet: 896: copied = 0;
897: if (!mmget_not_zero(mm))
898: goto free;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:pagemap_read SourceFile:fs/proc/task_mmu.c SourceLine:2315 SourceSnippet:2314:
2315: if (!mm || !mmget_not_zero(mm))
2316: goto out;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:show_smaps_rollup SourceFile:fs/proc/task_mmu.c SourceLine:1501 SourceSnippet:1500:
1501: if (!mm || !mmget_not_zero(mm)) {
1502: ret = -ESRCH;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:try_to_unuse SourceFile:mm/swapfile.c SourceLine:2765 SourceSnippet:2764: mm = list_entry(p, struct mm_struct, mmlist);
2765: if (!mmget_not_zero(mm))
2766: continue;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:uverbs_user_mmap_disassociate SourceFile:drivers/infiniband/core/uverbs_main.c SourceLine:789 SourceSnippet: 788: mm = priv->vma->vm_mm;
789: ret = mmget_not_zero(mm);
790: if (!ret) {
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:zap_pages SourceFile:kernel/bpf/arena.c SourceLine:819 SourceSnippet: 818: vml->zap_gen = my_gen;
819: if (!mmget_not_zero(vml->vma->vm_mm))
820: continue;
]] TruncatedOutput:false]
|
| 312/4 |
2026/09/23 20:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 41070
output: 38
thoughts: 966
Thoughts: **Analyzing a Memory Management Scenario with `vfork()` and `dup_mm`**
Okay, let's break this down. The prompt sets up a pretty specific situation involving `vfork()`, memory management, and potential race conditions. I need to figure out a sequence where `mmput(mm)` in Task A can somehow trigger `__mmput`, *even* while Task B is in `dup_mm`. The very wording of the question suggests a challenging, and possibly unlikely, scenario.
First, I need to solidify the basic setup. Task A calls `vfork()`. The crucial bit here is `CLONE_VM`, meaning the child (Task B) shares the parent's memory map initially. `mm_users` is at 2: one for A, and one for B. Task A waits on the vfork completion. Then, we are told Task A is killed by a signal.
Now, my mind goes to different cases. What if Task B exits first, or what if Task A, the vfork *child*, exits first? The prompt hints that Task B might not be the vfork child, so, I consider the cases in reverse.
I go through the prompt's analysis. If Task A, the child, exits, its `exit_mm()` decreases `mm_users` from 2 to 1. That's fine, but how does this lead to `__mmput` being triggered? The prompt's wording suggests it must. If Task B is alive, then `mm_users` can't drop to zero.
Ok, so it *must* involve a situation where Task B *isn't* holding a reference.
The question then focuses on *how* Task A's `mmput` can trigger `__mmput` when Task B is in `dup_mm`. The key now is the call to `dup_mm`.
Wait, but `dup_mm` is ONLY called when *not* `CLONE_VM`, and *not* from `execve`! What's the relationship between the two? `execve` creates a new memory map, or initializes it via `bprm_mm_init`. This is *crucial*.
My train of thought goes like this: can Task B call `execve` before Task A's `mmput`? The answer is *no*. Then, `dup_mm` would never be called from `execve`. So, Task A's `mmput` *can't* trigger `__mmput` when Task B is in `dup_mm`.
I must be missing something. The prompt clearly implies this is possible. Perhaps, the question is a bit misleading. The situation must be different.
Let's focus on the prompt. What if Task B is NOT a vfork child? That's what I want to know!
|
| 313/4 |
2026/09/23 20:38 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:1 Name:dup_mm]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_mm SourceFile:kernel/fork.c SourceLine:1595 SourceSnippet:1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
]] TruncatedOutput:false]
|
| 314/4 |
2026/09/23 20:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 42795
output: 32
thoughts: 361
Thoughts: **My Analysis of Memory Management in Task Cloning**
Okay, so `dup_mm` is *only* ever called from `copy_mm()`. That's the starting point. And in this particular scenario, we're talking about a `clone()` call *without* the `CLONE_VM` flag.
So, Task B is the task that is calling `clone()`. And the code inside `copy_mm()` says that Task B is passing `current->mm` as `oldmm` to the `dup_mm()` function. Alright, that's straightforward.
But let's think about this. For Task B to *even be* in a position to call `clone()` and end up in `dup_mm()`, Task B *has* to be running, right? And, since we are talking about a `sys_clone()` system call, Task B must be running in user space. So, for Task B to be running in userspace and make a system call `sys_clone()`, it *must* have `current->mm`. That makes sense.
So what *is* Task B's `current->mm`? It's `oldmm`.
Now, does Task B hold a count on `oldmm->mm_users`? YES! Every running user task that has `current->mm == oldmm` holds 1 reference in `mm_users`! That's crucial for memory management, of course.
The question then becomes: when does a task actually *drop* its `current->mm`? Let's see. It's only in two places, it seems:
1. `exit_mm()`: This is where `current->mm` gets set to `NULL`, and then a `mmput(mm)` is done.
2. `execve` (specifically `begin_new_exec` / `exec_mm`): this one is interesting. Let's look more closely at `exec_mm()`...
|
| 315/4 |
2026/09/23 20:38 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:fs/exec.c Name:exec_mm]
Results: map[SourceCode: SourceFile:]
|
| 316/4 |
2026/09/23 20:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 43754
output: 1368
thoughts: 1861
Thoughts: **Analysis of `mmput(mm)` Triggering `__mmput` During `dup_mm`**
Alright, let's break down this intriguing question. Based on my existing knowledge, it seems impossible for `mmput(mm)` in Task A to directly trigger `__mmput` while Task B is actively within `dup_mm`. Here's the reasoning:
1. **Reference Counting is Key:** The core of the issue lies in `mm_users` reference counting. For Task A's `mmput(mm)` to call `__mmput`, the `mm_users` count must decrement to zero. This signifies the last user of the memory descriptor is releasing it.
2. **`dup_mm` and the Persistent Reference:** When Task B enters `dup_mm`, specifically the `dup_mmap` function (typically called during `fork` or `clone` without `CLONE_VM`), it's essential to recognize that it *inherently* holds a reference to the `oldmm` (the memory descriptor it's duplicating) for the duration of its syscall. `dup_mmap` acquires the `mmap_write_lock` on the `oldmm` at the start, and only releases it at completion.
3. **The Vfork Scenario:** In the typical `vfork` scenario you described, and its parent/child variants, the initial `mm_users` count is at least 2 (Task A and Task B sharing via `CLONE_VM`). As Task B executes `dup_mm()`, its reference to `oldmm` remains valid. Thus, Task A's `mmput(mm)` can decrement the count from 2 to 1 (or N to N-1), *never* to 0.
4. **No Escape:** There's no standard scenario where Task B can drop its reference to `oldmm` *before* completing `dup_mm`. The kernel's design, including lock acquisition within `dup_mmap`, protects against such races. Even if Task B were to be killed by a signal during `dup_mmap`, it would release its reference to the *new* mm it had been creating, not the shared `oldmm`.
5. **`dup_mm` Itself Doesn't Cause the Problem:** The `mmput(mm)` calls within `dup_mm` (in cases of error) are on *new* memory descriptors, not the shared one. These calls are irrelevant to our specific scenario.
6. **Synchronization Prevents Races:** Kernel locks are in place to prevent races. `dup_mmap(mm, oldmm)` acquires `mmap_write_lock_killable(oldmm)` at the very beginning and holds it until completion, preventing `exit_mm()` from racing with the operation. `exit_mm()` itself, acquiring its own `mmap_read_lock(mm)` for its own operations, further avoids race conditions with `dup_mmap()`.
**Caveats & Unverified Aspects:**
* My current assessment is based on a standard understanding of `vfork`, `mmget`, `mmput`, reference counting, and related kernel primitives.
* I'm excluding esoteric kernel pathways (e.g., kernel thread MM stealing, asynchronous OOM reaper behavior), or historical/known kernel bugs that may introduce exceptions to this rule. A deeper dive into such areas might reveal less common, and very specific, corner cases.
**Conclusion:**
Based on the available information and without further specialized research, the scenario described where Task A's `mmput(mm)` would trigger `__mmput` while Task B is in `dup_mm` appears *impossible* within the standard kernel semantics. Task B *must* hold a reference to `oldmm` throughout the `dup_mm` process, which prevents `mm_users` from reaching zero until Task B has completed its `dup_mm` operation and exits/releases.
I'll proceed to call the `set-results` tool now.
|
| 317/4 |
2026/09/23 20:39 |
tool |
set-results |
0m
Args: map[Answer:Based on the Linux kernel implementation of `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mm()`, **Task A's `mmput(mm)` cannot trigger `__mmput(mm)` while Task B is in `dup_mm()`**.
Here is the step-by-step analysis of why this cannot happen, along with the lifecycle of `mm->mm_users` and synchronization between the two tasks:
---
### 1. The Reference Count Invariant (`mm->mm_users`)
- When Task B and Task A share an address space (`mm_struct`) via `vfork()` (`CLONE_VM | CLONE_VFORK`):
```c
if (clone_flags & CLONE_VM) {
mmget(oldmm);
mm = oldmm;
}
```
`mmget(oldmm)` increments `atomic_inc(&oldmm->mm_users)`.
- Prior to exit or exec by either task, both tasks actively reference the `mm_struct` (`current->mm == mm`). Therefore, `mm->mm_users >= 2`.
- `mmput(mm)` is implemented as:
```c
void mmput(struct mm_struct *mm)
{
if (atomic_dec_and_test(&mm->mm_users))
__mmput(mm);
}
```
`__mmput()` is invoked **if and only if** `atomic_dec_and_test(&mm->mm_users)` decrements `mm_users` from 1 to 0.
---
### 2. Analysis of the Race Scenarios
#### Scenario 1: Task A is the vfork parent; Task B is the vfork child
- Task A waits in `wait_for_vfork_done(&vfork)`.
- If Task A is killed by `SIGKILL`, `wait_for_vfork_done()` wakes up due to the fatal signal (`wait_for_completion_killable`).
- Task A exits and calls `exit_mm()`.
- When Task A calls `mmput(mm)`, Task B is still alive and running (holding its active `current->mm`).
- Thus, `mm->mm_users` was at least 2. Task A's `mmput(mm)` decrements it to at least 1.
- `atomic_dec_and_test(&mm->mm_users)` returns `false`. `__mmput()` is **not** called.
#### Scenario 2: Task B is the vfork parent; Task A is the vfork child
- Task B calls `vfork()` and waits in `wait_for_vfork_done(&vfork)`.
- Task A (the child) exits (`do_exit()`):
1. Task A calls `exit_mm()`.
2. Inside `exit_mm()`, `mm_exit_exec_release()` -> `mm_release()` is called:
```c
if (tsk->vfork_done)
complete_vfork_done(tsk);
```
This completes the vfork completion and wakes parent Task B.
3. Task B wakes up, returns from `wait_for_vfork_done()`, and returns to userspace.
4. Task B calls `clone()` without `CLONE_VM` (e.g., standard `fork()`), which invokes `copy_mm()`:
```c
mm = dup_mm(tsk, current->mm);
```
Task B enters `dup_mm(tsk, current->mm)`.
5. Meanwhile, Task A continues in `exit_mm()` and reaches:
```c
mmput(mm);
```
- **Why `__mmput` cannot be called here:**
For Task B to be running in userspace and invoking system calls like `fork()`, Task B's `current->mm` remains valid. Task B still holds its active reference to `mm_users` that was established before or during `vfork()`.
Task B cannot drop its `current->mm` while synchronously executing inside `kernel_clone() -> copy_process() -> copy_mm() -> dup_mm()`.
Consequently, when Task A reaches `mmput(mm)`, `mm->mm_users` is at least 2 (Task A's reference + Task B's reference).
The decrement drops `mm_users` from 2 to 1, returning `false`. `__mmput()` is **not** called.
---
### 3. Locking and Memory Safety
Even looking beyond reference counts:
- `dup_mm()` invokes `dup_mmap(new_mm, oldmm)`.
- The very first step of `dup_mmap()` is acquiring the write lock on `oldmm`:
```c
if (mmap_write_lock_killable(oldmm))
return -EINTR;
```
- Meanwhile, `exit_mm()` acquires `mmap_read_lock(mm)` while detaching `current->mm`.
- Even in the teardown path of an `mm`, `__mmput()` calls `exit_mmap(mm)`, which requires taking `mmap_write_lock(mm)`.
Both the reference counting model and the mmap semaphores prevent concurrent destruction of `oldmm` while another task is reading or duplicating it.
---
### 4. Caveats and Unverified Parts
- This analysis is based on the core lifetime rules of `mm_struct`, `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mmap()`.
- It was not verified whether asynchronous mechanisms outside normal task execution (such as speculative kernel-thread borrowing via `kthread_use_mm()`, or anomalous third-party references from out-of-tree drivers) could cause reference count discrepancies. Under standard in-tree POSIX semantics, `mm_users` cannot reach 0 in Task A while Task B is executing `dup_mm()`.]
Results: map[Answer:Based on the Linux kernel implementation of `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mm()`, **Task A's `mmput(mm)` cannot trigger `__mmput(mm)` while Task B is in `dup_mm()`**.
Here is the step-by-step analysis of why this cannot happen, along with the lifecycle of `mm->mm_users` and synchronization between the two tasks:
---
### 1. The Reference Count Invariant (`mm->mm_users`)
- When Task B and Task A share an address space (`mm_struct`) via `vfork()` (`CLONE_VM | CLONE_VFORK`):
```c
if (clone_flags & CLONE_VM) {
mmget(oldmm);
mm = oldmm;
}
```
`mmget(oldmm)` increments `atomic_inc(&oldmm->mm_users)`.
- Prior to exit or exec by either task, both tasks actively reference the `mm_struct` (`current->mm == mm`). Therefore, `mm->mm_users >= 2`.
- `mmput(mm)` is implemented as:
```c
void mmput(struct mm_struct *mm)
{
if (atomic_dec_and_test(&mm->mm_users))
__mmput(mm);
}
```
`__mmput()` is invoked **if and only if** `atomic_dec_and_test(&mm->mm_users)` decrements `mm_users` from 1 to 0.
---
### 2. Analysis of the Race Scenarios
#### Scenario 1: Task A is the vfork parent; Task B is the vfork child
- Task A waits in `wait_for_vfork_done(&vfork)`.
- If Task A is killed by `SIGKILL`, `wait_for_vfork_done()` wakes up due to the fatal signal (`wait_for_completion_killable`).
- Task A exits and calls `exit_mm()`.
- When Task A calls `mmput(mm)`, Task B is still alive and running (holding its active `current->mm`).
- Thus, `mm->mm_users` was at least 2. Task A's `mmput(mm)` decrements it to at least 1.
- `atomic_dec_and_test(&mm->mm_users)` returns `false`. `__mmput()` is **not** called.
#### Scenario 2: Task B is the vfork parent; Task A is the vfork child
- Task B calls `vfork()` and waits in `wait_for_vfork_done(&vfork)`.
- Task A (the child) exits (`do_exit()`):
1. Task A calls `exit_mm()`.
2. Inside `exit_mm()`, `mm_exit_exec_release()` -> `mm_release()` is called:
```c
if (tsk->vfork_done)
complete_vfork_done(tsk);
```
This completes the vfork completion and wakes parent Task B.
3. Task B wakes up, returns from `wait_for_vfork_done()`, and returns to userspace.
4. Task B calls `clone()` without `CLONE_VM` (e.g., standard `fork()`), which invokes `copy_mm()`:
```c
mm = dup_mm(tsk, current->mm);
```
Task B enters `dup_mm(tsk, current->mm)`.
5. Meanwhile, Task A continues in `exit_mm()` and reaches:
```c
mmput(mm);
```
- **Why `__mmput` cannot be called here:**
For Task B to be running in userspace and invoking system calls like `fork()`, Task B's `current->mm` remains valid. Task B still holds its active reference to `mm_users` that was established before or during `vfork()`.
Task B cannot drop its `current->mm` while synchronously executing inside `kernel_clone() -> copy_process() -> copy_mm() -> dup_mm()`.
Consequently, when Task A reaches `mmput(mm)`, `mm->mm_users` is at least 2 (Task A's reference + Task B's reference).
The decrement drops `mm_users` from 2 to 1, returning `false`. `__mmput()` is **not** called.
---
### 3. Locking and Memory Safety
Even looking beyond reference counts:
- `dup_mm()` invokes `dup_mmap(new_mm, oldmm)`.
- The very first step of `dup_mmap()` is acquiring the write lock on `oldmm`:
```c
if (mmap_write_lock_killable(oldmm))
return -EINTR;
```
- Meanwhile, `exit_mm()` acquires `mmap_read_lock(mm)` while detaching `current->mm`.
- Even in the teardown path of an `mm`, `__mmput()` calls `exit_mmap(mm)`, which requires taking `mmap_write_lock(mm)`.
Both the reference counting model and the mmap semaphores prevent concurrent destruction of `oldmm` while another task is reading or duplicating it.
---
### 4. Caveats and Unverified Parts
- This analysis is based on the core lifetime rules of `mm_struct`, `vfork()`, `copy_mm()`, `exit_mm()`, and `dup_mmap()`.
- It was not verified whether asynchronous mechanisms outside normal task execution (such as speculative kernel-thread borrowing via `kthread_use_mm()`, or anomalous third-party references from out-of-tree drivers) could cause reference count discrepancies. Under standard in-tree POSIX semantics, `mm_users` cannot reach 0 in Task A while Task B is executing `dup_mm()`.]
|
| 318/2 |
2026/09/23 20:39 |
llm |
expert |
0m
Model:
Tokens:
input: 50370
output: 21
thoughts: 1409
Thoughts: **KCSAN Data Race Deep Dive**
Okay, let's dissect this KCSAN report. First, I need to meticulously re-examine the stack traces. Hold on... Right, the KCSAN report flagged a data race. Looking at the stack traces, a write operation of 8 bytes is happening at address `0xffff8881046681f8` by task 21217 on CPU 1, and simultaneously, a read of 1728 bytes from `0xffff888104668000` by task 3876 on CPU 0.
Wait a second, let me do the math. `0xffff888104668000 + 1728` comes out to `0xffff8881046686c0`. Now, the write was at offset `0x1f8`, which is 504 in decimal. And 504 is clearly within the read range of 1728 bytes! So, this read *overlaps* the write. Interesting.
Now, why is `__mmput` involved? And if `mm_users` is involved, how did it go to zero? Hold on, how could `mm_users` possibly reach zero while task 3876 is in `copy_process`? That makes no sense.
Okay, let's explore if `io_uring` is involved. Let me check the `io_uring_fork(p)` call within `copy_process`. Line 2220 has `p->io_uring = NULL;` and `retval = io_uring_fork(p);`. Does io_uring somehow mess with the memory management? Hmm. What if task 3876 is an `io_uring` worker? Or maybe a kernel thread? But hold on, the stack trace for task 3876 is: `sys_clone -> kernel_clone -> copy_process -> copy_mm -> dup_mm`. So task 3876 is just a normal task, a `syz-executor`!
Wait a second. What if task 21217 and task 3876 are *not* sharing the `mm` structure in the typical way? This could open a new avenue of attack!
Wait, how could Task 3876 and Task 21217 possibly have the *same* `mm_struct` address, which is `0xffff888104668000`? This seems highly unusual. How could two tasks possibly have the same `mm_struct` address? This must be at the root of the problem.
And if `mm_users` is zero during `__mmput`, why did `atomic_dec_and_test(&mm->mm_users)` succeed? This is crucial. I need to exhaustively examine every place in the kernel code that decrements `mm_users` and every call to `mmput`. I must find the path where this happens.
|
| 319/2 |
2026/09/23 20:40 |
tool |
grepper |
0m
Args: map[Expression:atomic_dec.*mm_users]
Results: map[Output:kernel/fork.c=1211=void mmput(struct mm_struct *mm)
--
kernel/fork.c-1214-
kernel/fork.c:1215: if (atomic_dec_and_test(&mm->mm_users))
kernel/fork.c-1216- __mmput(mm);
--
kernel/fork.c=1229=void mmput_async(struct mm_struct *mm)
kernel/fork.c-1230-{
kernel/fork.c:1231: if (atomic_dec_and_test(&mm->mm_users)) {
kernel/fork.c-1232- INIT_WORK(&mm->async_put_work, mmput_async_fn);
]
|
| 320/2 |
2026/09/23 20:40 |
llm |
expert |
0m
Model:
Tokens:
input: 52672
output: 39
thoughts: 45
Thoughts: Okay, here's my understanding, formatted as requested:
**Deconstructing Memory Management: A Focused Audit**
Right, let's zero in on this memory management situation. I need to be absolutely certain about how `mm_users` is being decremented. The core of my concern – and it *always* comes down to this – are the places where a memory region is truly released, and the associated counters are managed. My understanding, which I need to verify, is that `mmput` and `mmput_async` are the *exclusive* locations responsible for decrementing `mm_users`. That's the baseline assumption I'm operating under and is key to ensuring there aren't any leaks or incorrect references.
Okay, let's tackle `mmput_async` first. Time to figure out *exactly* where this is called. I need to trace its usage meticulously. This is where the real work begins, right? To prove this crucial point, I'm diving in. Where is this function invoked from within the system? Let's trace back from `mmput_async`, to identify the callers.
|
| 321/2 |
2026/09/23 20:40 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/fork.c IncludeSnippetLines:5 Name:mmput_async]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:____bpf_find_vma SourceFile:kernel/bpf/task_iter.c SourceLine:817 SourceSnippet: 812: }
813: bpf_mmap_unlock_mm(work, mm);
814: out:
815: #ifdef CONFIG_MMU
816: if (mmput_needed)
817: mmput_async(mm);
818: #endif
819: return ret;
820: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__futex_ref_atomic_end SourceFile:kernel/futex/core.c SourceLine:1671 SourceSnippet:1666: ret = atomic_long_add_return(count - LONG_MAX - 1, &mm->futex.phash.atomic);
1667: if (!ret)
1668: wake_up_var(mm);
1669:
1670: WARN_ON_ONCE(ret < 0);
1671: mmput_async(mm);
1672: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:bpf_iter_mmput_async SourceFile:kernel/bpf/task_iter.c SourceLine:836 SourceSnippet: 833: static inline void bpf_iter_mmput_async(struct mm_struct *mm)
834: {
835: #ifdef CONFIG_MMU
836: mmput_async(mm);
837: #else
838: mmput(mm);
839: #endif
840: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ib_umem_odp_map_dma_and_lock SourceFile:drivers/infiniband/core/umem_odp.c SourceLine:416 SourceSnippet: 411: ret = dma_index - start_idx;
412: else
413: mutex_unlock(&umem_odp->umem_mutex);
414:
415: out_put_mm:
416: mmput_async(owning_mm);
417: out_put_task:
418: if (owning_process)
419: put_task_struct(owning_process);
420: return ret;
421: }
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_mmput_async_1426 SourceFile:kernel/fork.c SourceLine:1236 SourceSnippet:1236: EXPORT_SYMBOL_GPL(mmput_async);
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_mmput_async SourceFile:kernel/fork.c SourceLine:1236 SourceSnippet:1236: EXPORT_SYMBOL_GPL(mmput_async);
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_mmput_async SourceFile:kernel/fork.c SourceLine:1236 SourceSnippet:1236: EXPORT_SYMBOL_GPL(mmput_async);
]] TruncatedOutput:false]
|
| 322/2 |
2026/09/23 20:40 |
llm |
expert |
0m
Model:
Tokens:
input: 53999
output: 24
thoughts: 152
Thoughts: **Futex Implementation Deep Dive**
Okay, hold on a second. I need to retrace my steps on this futex implementation. Let's see...I was just looking at `kernel/futex/core.c`, and that `__futex_ref_atomic_end` function is calling `mmput_async(mm)`. That feels... significant. I need to keep that in mind.
Now, wait a minute, I remember seeing something about `futex_hash_allocate_default` during process creation. Where was that again? Ah, right, that was in `copy_process`! And... what's this? I'm now looking at line 2432 of `kernel/fork.c`, where there's a conditional check with `need_futex_hash_allocate_default`. And if that's true, it calls `futex_hash_allocate_default`. Now I'm starting to remember that's where I need to look for memory management issues.
Okay, I need to get a handle on this quickly; I'm going to search for all occurrences of `futex_mm_init` and anything `futex` related in `fork`! This seems like a critical path I need to fully understand.
|
| 323/2 |
2026/09/23 20:41 |
tool |
grepper |
0m
Args: map[Expression:need_futex_hash_allocate_default]
Results: map[Output:kernel/fork.c=1987=static void rv_task_fork(struct task_struct *p)
--
kernel/fork.c-1994-
kernel/fork.c:1995:static bool need_futex_hash_allocate_default(u64 clone_flags)
kernel/fork.c-1996-{
--
kernel/fork.c=2012=__latent_entropy struct task_struct *copy_process(
--
kernel/fork.c-2431-
kernel/fork.c:2432: if (need_futex_hash_allocate_default(clone_flags)) {
kernel/fork.c-2433- retval = futex_hash_allocate_default();
]
|
| 324/2 |
2026/09/23 20:41 |
llm |
expert |
0m
Model:
Tokens:
input: 54640
output: 25
thoughts: 124
Thoughts: Okay, let's dive into this futex situation.
**Futex Commits and Implications**
Hmm, hold on a second. I need to refresh my memory on the latest work with futex. Let me check the recent git commits, specifically focusing on the futex implementation. I recall seeing some interesting changes recently. Let's see... Ah, yes, there are a few that stand out. Specifically, the commits dealing with automatic allocation of process-wide futex hashes, dropping the `CLONE_THREAD` requirement, and allocation on `vfork()`.
Looking at those commit messages:
* `7c4f75a21f63 futex: Allow automatic allocation of process wide futex hash` - This seems important for improved usability, allowing the system to handle the hash allocation.
* `ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc` - *This* is interesting. Removing that `CLONE_THREAD` constraint changes some fundamental assumptions about when and how a private hash is allocated.
* `b61b6f95d672 futex: Also allocate private hash on vfork()` - Ah, this one is directly related to how `vfork()` interacts with futex. This has subtle implications for memory mapping and process creation.
Yes, let's focus in on commits `ee9dce44362b` and `b61b6f95d672`. I need to review those in detail. They probably highlight some important architectural shifts in how the kernel handles futexes in the context of these specific scenarios. I'm going to pull up the patch diffs... I anticipate this might be related to the improvements in scalability and resource usage related to futexes in recent kernel releases.
|
| 325/2 |
2026/09/23 20:41 |
tool |
git-show |
0m
Args:
Results: map[Output:commit ee9dce44362b2d8132c32964656ab6dff7dfbc6a
Author: Davidlohr Bueso <dave@stgolabs.net>
Date: Fri May 1 12:41:23 2026 -0700
futex: Drop CLONE_THREAD requirement for private default hash alloc
Currently need_futex_hash_allocate_default() depends on strict pthread
semantics, abusing CLONE_THREAD. This breaks the non-concurrency
assumptions when doing the mm->futex_ref pcpu allocations, leading to
bugs[0] when sharing the mm in other ways; ie:
BUG: KASAN: slab-use-after-free in futex_hash_put
... where the +1 bias can end up on a percpu counter that mm->futex_ref
no longer points at.
Loosen the check to cover any CLONE_VM clone, except vfork(). Excluding
vfork keeps the existing paths untouched (no overhead), and we can't
race in the first place: either the parent is suspended and the child
runs alone, or mm->futex_ref is already allocated from an earlier
CLONE_VM.
Link: https://lore.kernel.org/all/CAL_bE8LsmCQ-FAtYDuwbJhOkt9p2wwYQwAbMh=PifC=VsiBM6A@mail.gmail.com/ [0]
Fixes: d9b05321e21e ("futex: Move futex_hash_free() back to __mmput()")
Reported-by: Yiming Qian <yimingqian591@gmail.com>
Signed-off-by: Davidlohr Bueso <dave@stgolabs.net>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/kernel/fork.c b/kernel/fork.c
index f1ad69c6dc2d..5f3fdfdb14c7 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -1951,9 +1951,11 @@ static void rv_task_fork(struct task_struct *p)
static bool need_futex_hash_allocate_default(u64 clone_flags)
{
- if ((clone_flags & (CLONE_THREAD | CLONE_VM)) != (CLONE_THREAD | CLONE_VM))
- return false;
- return true;
+ /*
+ * Allocate a default futex hash for any sibling that will
+ * share the parent's mm, except vfork.
+ */
+ return (clone_flags & (CLONE_VM | CLONE_VFORK)) == CLONE_VM;
}
/*
@@ -2380,10 +2382,6 @@ __latent_entropy struct task_struct *copy_process(
if (retval)
goto bad_fork_cancel_cgroup;
- /*
- * Allocate a default futex hash for the user process once the first
- * thread spawns.
- */
if (need_futex_hash_allocate_default(clone_flags)) {
retval = futex_hash_allocate_default();
if (retval)
]
|
| 326/2 |
2026/09/23 20:41 |
llm |
expert |
0m
Model:
Tokens:
input: 56039
output: 27
thoughts: 20
Thoughts: Okay, here's my interpretation of what's going through my mind when I encounter that prompt, rendered in the first person:
**Analyzing the Request: Commit b61b6f95d672**
Alright, a commit hash. That's a good starting point. My initial thought is, "Okay, show me the code." The specific hash, `b61b6f95d672`, immediately signals this is about inspecting a *specific* change within a version control system, likely Git, though it could be a similar system. I immediately start mentally translating that hash into the context of the repository. I'm thinking, "Let's assume this is a standard Git workflow," so my mind is already reaching for the familiar commands: `git show b61b6f95d672`, or perhaps `git log -p -1 b61b6f95d672` if I want the patch format. The request is almost calling on me to review some code. I need to understand what's been committed. Is it bug fix? Enhancement? Refactor? And if it's the latter, maybe it's not a lot to review, since refactoring isn't supposed to change behaviour, just the architecture. I'm primed to dive into the diff.
|
| 327/2 |
2026/09/23 20:42 |
tool |
git-show |
0m
Args:
Results: map[Output:commit b61b6f95d6722ddbbbd09e689fa41b55fd36f9a5
Author: Peter Zijlstra <peterz@infradead.org>
Date: Fri Sep 11 11:04:47 2026 +0200
futex: Also allocate private hash on vfork()
As Jann demonstrated, it is entirely feasible to access the mm through vfork().
Therefore we need to allocate a private hash on vfork() as well as any other
CLONE_VM user.
Specifically, it must be avoided to have (private) futex waiters before
allocating the private hash.
Fixes: ee9dce44362b ("futex: Drop CLONE_THREAD requirement for private default hash alloc")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Link: https://patch.msgid.link/20260911090447.GT788244@noisy.programming.kicks-ass.net
diff --git a/kernel/fork.c b/kernel/fork.c
index a5934a317634..5ef413368912 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -1996,9 +1996,9 @@ static bool need_futex_hash_allocate_default(u64 clone_flags)
{
/*
* Allocate a default futex hash for any sibling that will
- * share the parent's mm, except vfork.
+ * share the parent's mm.
*/
- return (clone_flags & (CLONE_VM | CLONE_VFORK)) == CLONE_VM;
+ return clone_flags & CLONE_VM;
}
/*
]
|
| 328/2 |
2026/09/23 20:42 |
llm |
expert |
0m
Model:
Tokens:
input: 56880
output: 37
thoughts: 90
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Memory Management Research: Leveraging Historical Context**
Right, so Jann's demonstration immediately got my gears turning. Accessing the memory map through `vfork()` – it's definitely a viable technique, and now I'm thinking, let's not just take this at face value. This seems like a potential paradigm shift. I need to delve into the historical context here.
My mind immediately jumps to Jann Horn's past work. I need to go digging through the archives. I want to search the git logs, and maybe also lore, focusing on reports, bugfixes, and code changes centered around `fork()`, `exit()`, and of course `vfork()`, along with any associated flags such as `CLONE_VM`. Jann Horn would undoubtedly have contributed valuable insights on these topics. Beyond Jann, Oleg Nesterov and Lorenzo Stoakes would have been working in this space, so their contributions warrant investigation.
Specifically, I’ll need to target specific keywords within those searches. I'm keen on finding any commits that touch on `dup_mm`, `exit_mm`, or especially the mechanics of `__mmput`. I need to understand how the memory management structures are being handled, copied, and released in these scenarios. Historical analysis is essential; I want to understand how these memory access strategies have evolved. This kind of deep dive into the git history will provide valuable understanding of the risks and rewards of this technique. This approach gives me more context to evaluate the feasibility of this strategy, and to understand any potential pitfalls.
|
| 329/2 |
2026/09/23 20:42 |
tool |
git-log |
0m
Args: map[CodeRegexp:dup_mm\( Count:10 PathPrefix:kernel/fork.c]
Results: map[Output:26a8f57760c1 mm: move dup_mmap() to mm
3f4c8211d982 x86/mm: Use mm_alloc() in poking_init()
a6895399380a kernel/fork.c: simplify copy_mm()
13585fa0668c fork: Provide a function for copying init_mm
d70f2a14b72a include/linux/sched/mm.h: uninline mmdrop_async(), etc
ff252c1fc537 kernel/fork.c: make dup_mm() static
402b08622d9a s390: KVM preparation: provide hook to enable pgstes in user pagetable
ec8c0446b6e2 [PATCH] Optimize D-cache alias handling on fork
2d61b86775a5 [PATCH] disable unshare(CLONE_VM) for now
a0a7ec308f1b [PATCH] unshare system call -v5: unshare vm
]
|
| 330/2 |
2026/09/23 20:42 |
llm |
expert |
0m
Model:
Tokens:
input: 57618
output: 39
thoughts: 35
Thoughts: Okay, here's the summary, rendered as a first-person account reflecting those thoughts:
**Investigating Potential Fork-Related Issues**
Right, before I dive too deep into this particular problem, I need to take a step back and get a better handle on the potential scope of this. I'm going to start by examining the Git history, specifically targeting code related to `fork` and its relatives. My initial instinct is to focus on `vfork` because of the potential for subtle issues related to address space management, but I'll cast a wider net. The ideal starting point for this would be searching the `git log`. Now, I'm thinking, let's use a `MessageRegexps` query with a pattern like `["vfork"]` – I'll target the `kernel/exit.c` or `kernel/fork.c` files. This should give me a good overview of past changes and any previous discussions or fixes related to similar operations within the kernel that could inform my current investigation. Hopefully, that will give me a better overview of previous issues and avoid any blind spots.
|
| 331/2 |
2026/09/23 20:43 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[vfork] PathPrefix:kernel/ Since:5 years]
Results: map[Output:b61b6f95d672 futex: Also allocate private hash on vfork()
bde023808364 futex: Fix race on the initial mm->futex.phash.ref allocation
ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
192d852129b1 sched/mmcid: Avoid full tasklist walks
28b5a1395036 sched/mmcid: Handle vfork()/CLONE_VM correctly
3a35c13007de kunit: Handle test faults
d4ccd54d28d3 exit: Put an upper limit on how often we can oops
2b5f9dad32ed fs/exec: switch timens when a task gets a new mm
33a2d6bc3480 Revert "fs/exec: allow to unshare a time namespace on vfork+exec"
133e2d3e81de fs/exec: allow to unshare a time namespace on vfork+exec
]
|
| 332/2 |
2026/09/23 20:43 |
llm |
expert |
0m
Model:
Tokens:
input: 58191
output: 27
thoughts: 35
Thoughts: Okay, here's my interpretation of those "thoughts", assuming I'm deep in my code and know what those commit hashes mean.
**Diving into the Revision History**
Alright, time to get my hands dirty. Let's pull up the specific commits I know are relevant: `28b5a1395036` and `192d852129b1`. I need to understand the changes made in these revisions. This probably means I'm troubleshooting a specific issue, or maybe tracing a feature implementation, or I'm reviewing code. Seeing those commit hashes immediately tells me where my focus needs to be. Gotta figure out the context. I'm going to look for any clues. Let's get cracking.
|
| 333/2 |
2026/09/23 20:43 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 28b5a1395036d6c7a6c8034d85ad3d7d365f192c
Author: Thomas Gleixner <tglx@kernel.org>
Date: Tue Mar 10 21:28:58 2026 +0100
sched/mmcid: Handle vfork()/CLONE_VM correctly
Matthieu and Jiri reported stalls where a task endlessly loops in
mm_get_cid() when scheduling in.
It turned out that the logic which handles vfork()'ed tasks is broken. It
is invoked when the number of tasks associated to a process is smaller than
the number of MMCID users. It then walks the task list to find the
vfork()'ed task, but accounts all the already processed tasks as well.
If that double processing brings the number of to be handled tasks to 0,
the walk stops and the vfork()'ed task's CID is not fixed up. As a
consequence a subsequent schedule in fails to acquire a (transitional) CID
and the machine stalls.
Cure this by removing the accounting condition and make the fixup always
walk the full task list if it could not find the exact number of users in
the process' thread list.
Fixes: fbd0e71dc370 ("sched/mmcid: Provide CID ownership mode fixup functions")
Closes: https://lore.kernel.org/b24ffcb3-09d5-4e48-9070-0b69bc654281@kernel.org
Reported-by: Matthieu Baerts <matttbe@kernel.org>
Reported-by: Jiri Slaby <jirislaby@kernel.org>
Signed-off-by: Thomas Gleixner <tglx@kernel.org>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Tested-by: Matthieu Baerts (NGI0) <matttbe@kernel.org>
Link: https://patch.msgid.link/20260310202526.048657665@kernel.org
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index d25427855b5d..ee59cd19b9a8 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -10670,10 +10670,7 @@ static void mm_cid_do_fixup_tasks_to_cpus(struct mm_struct *mm)
for_each_process_thread(p, t) {
if (t == current || t->mm != mm)
continue;
- if (mm_cid_fixup_task_to_cpu(t, mm)) {
- if (--users == 0)
- return;
- }
+ mm_cid_fixup_task_to_cpu(t, mm);
}
}
]
|
| 334/2 |
2026/09/23 20:43 |
llm |
expert |
0m
Model:
Tokens:
input: 59203
output: 26
thoughts: 59
Thoughts: Okay, here's my take on those thoughts, framed as my own:
**Investigating a vfork() and Memory Management Mystery**
Hold on a second! This commit message... "As Jann demonstrated, it is entirely feasible to access the mm through vfork()." That's intriguing. I know `vfork()` can be tricky with memory management – it's supposed to be a lightweight fork, and the documentation emphasizes shared memory space. But, "feasible to *access* the mm..."? That suggests something more than just a theoretical possibility. I need to understand how Jann achieved this. I'm especially curious about the implications for memory integrity and potential race conditions.
Right, time to dig into the details. Commit `bde023808364` it is! Let's see what Jann cooked up. I'm expecting some clever use of shared memory segments, careful synchronization, or perhaps some specific kernel configuration that alters the typical `vfork()` behavior. This could be a good little puzzle to solve. I'm ready to dive into the code.
|
| 335/2 |
2026/09/23 20:43 |
tool |
git-show |
0m
Args:
Results: map[Output:commit bde0238083647381d4747355c5a19115a3422b96
Author: Hyunwoo Kim <imv4bel@gmail.com>
Date: Tue Aug 11 23:03:16 2026 +0900
futex: Fix race on the initial mm->futex.phash.ref allocation
futex_hash_allocate() allocates mm->futex.phash.ref without any locking.
Commit d9b05321e21e ("futex: Move futex_hash_free() back to __mmput()")
moved the allocation here and assumed that the process has just a single
thread at this point.
Commit ee9dce44362b ("futex: Drop CLONE_THREAD requirement for private
default hash alloc") widened need_futex_hash_allocate_default() to cover
any CLONE_VM clone, but left out vfork because the parent is suspended and
cannot race.
That no longer holds once vfork is nested. If a vfork child calls vfork
again and is then killed with SIGKILL, the parent is released from its
vfork wait and runs concurrently with the grandchild in the same mm.
Neither of them went through futex_hash_allocate_default().
When both call prctl(PR_FUTEX_HASH, PR_FUTEX_HASH_SET_SLOTS) at the same
time, each one sees mm->futex.phash.ref as NULL and stores its own percpu
counter. Only the last store survives. The counter stored first is no
longer reachable from the mm, so the references on it are not seen by
__futex_ref_atomic_end(). A private hash that still has references is then
considered dead and freed, and a task that still holds one of its buckets
writes into freed memory in futex_q_lock().
Store the counter once with cmpxchg() and let the loser free_percpu() its
own. The initial reference has to be taken before the store, otherwise
another task can install a private hash while the counter is still 0.
Fixes: d9b05321e21e ("futex: Move futex_hash_free() back to __mmput()")
Signed-off-by: Hyunwoo Kim <imv4bel@gmail.com>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Signed-off-by: Thomas Gleixner <tglx@kernel.org>
Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/ansrpP4ImE1MaBY9@v4bel
diff --git a/kernel/futex/core.c b/kernel/futex/core.c
index 2d1dbde54362..b38222e81879 100644
--- a/kernel/futex/core.c
+++ b/kernel/futex/core.c
@@ -1857,14 +1857,18 @@ static int futex_hash_allocate(unsigned int hash_slots, unsigned int flags)
}
if (!mm->futex.phash.ref) {
+ unsigned int __percpu *ref = alloc_percpu(unsigned int);
+
+ if (!ref)
+ return -ENOMEM;
+
/*
- * This will always be allocated by the first thread and
- * therefore requires no locking.
+ * Tasks sharing the mm can run this concurrently, so take the
+ * initial reference before publishing the counter.
*/
- mm->futex.phash.ref = alloc_percpu(unsigned int);
- if (!mm->futex.phash.ref)
- return -ENOMEM;
- this_cpu_inc(*mm->futex.phash.ref); /* 0 -> 1 */
+ this_cpu_inc(*ref); /* 0 -> 1 */
+ if (cmpxchg(&mm->futex.phash.ref, NULL, ref))
+ free_percpu(ref);
}
fph = kvzalloc(struct_size(fph, queues, hash_slots),
]
|
| 336/2 |
2026/09/23 20:43 |
llm |
expert |
0m
Model:
Tokens:
input: 60591
output: 20
thoughts: 3132
Thoughts: **A Deep Dive into a Potential Kernel Data Race**
Okay, so I've been staring at this code and these KCSAN reports, and a nasty race condition is starting to crystallize. The initial clue comes from the `vfork` and `clone` behavior, particularly with the interaction of `CLONE_VM` and how a child process might be killed. It's a bit of a labyrinth, but here's how I see it:
The core of the problem seems to be the concurrent access to the `mm_struct`, especially when a thread in a process exits using `exit_group()`, and another thread is forking using `fork()` which is calling `dup_mm()`. I'm tracing two tasks here, Task 21217 and Task 3876.
* Task 21217 is exiting, and it's doing a `__mmput()`. This function is the killer because it's responsible for freeing all the memory associated with the process's memory map (`mm`). Critically, it does things like `exit_mmap()`, which tears down VMAs and the page tables, unlinks the `mm` from lists and ultimately frees the `mm_struct` itself. `exit_mmap` includes destruction of the maple tree (`mm->mm_mt`) via `__mt_destroy()`, and the VMAs via `tear_down_vmas()`.
* Now, look at Task 3876. This task is calling `clone()` (like `fork()`), but *without* the `CLONE_VM` flag. Therefore, it's NOT sharing memory, so it's calling `dup_mm()`, which is supposed to duplicate the memory map. `dup_mm()` needs to read from the *old* `mm_struct`. But, that's the rub!
Here's the data race. The KCSAN report showed a race between `__mmput()` and `dup_mm()`. Specifically, Task 3876 is performing a `memcpy` to copy the `mm_struct` data from the old `mm` structure. At the same time, Task 21217 is deep within `__mmput()` and *destroying* the very `mm_struct` Task 3876 is trying to copy!
`__mmput()` calls `list_del(&mm->mmlist)` while `dup_mm()` is trying to copy that list! Since `dup_mm()` does not hold a lock to protect `oldmm` from being destroyed, it's reading garbage, or worse, accessing freed memory. Specifically, the KCSAN report showed a race between `memcpy(mm, oldmm, sizeof(*mm))` and `list_del(&mm->mmlist)`, where the `memcpy` was reading `mm->mmlist` at offset `0x1f8`!
Why is this happening? Let's trace it back. What causes `mm_users` to hit 0 and trigger `__mmput()`? The scenario I'm zeroing in on: a multi-threaded process calls `fork()`. The key is what happens when one thread calls `exit_group()`. `exit_group()` is nasty. It sends `SIGKILL` to all *other* threads. Therefore, thread 1, the thread calling `fork()`, is running inside `dup_mm()` while thread 2 is calling `exit_group()` and calling `__mmput()` to destroy the `oldmm` that thread 1 is trying to read.
The race happens because `dup_mm()` doesn't have an appropriate lock protecting the read of the `oldmm` from modification. It's assuming the `current->mm` is valid, but the fact that `atomic_dec_and_test()` succeeded in `mmput()` means the `mm_users` had gone to 0, and therefore `__mmput()` ran! That means the process structure for that `mm` struct is now getting freed up, all while `dup_mm()` is trying to copy the struct. This is a classic Use-After-Free scenario, likely leading to corruption or a crash. The kernel isn't properly synchronizing the destruction of the memory map with the duplication of that map, and the whole situation is a recipe for disaster.
|
| 337/2 |
2026/09/23 20:44 |
tool |
grepper |
0m
Args: map[Expression:kthread_use_mm]
Results: map[Output:arch/arm64/kernel/efi.c=169=void arch_efi_call_virt_setup(void)
--
arch/arm64/kernel/efi.c-181- migrate_disable();
arch/arm64/kernel/efi.c:182: kthread_use_mm(&efi_mm);
arch/arm64/kernel/efi.c-183- } else {
--
arch/powerpc/include/asm/book3s/64/kup.h=205=extern u64 __ro_after_init default_iamr;
--
arch/powerpc/include/asm/book3s/64/kup.h-209-
arch/powerpc/include/asm/book3s/64/kup.h:210:/* usage of kthread_use_mm() should inherit the
arch/powerpc/include/asm/book3s/64/kup.h-211- * AMR value of the operating address space. But, the AMR value is
--
arch/powerpc/mm/book3s64/hash_utils.c=2030=static void hash_preload(struct mm_struct *mm, pte_t *ptep, unsigned long ea,
--
arch/powerpc/mm/book3s64/hash_utils.c-2080- * mm_is_thread_local test and update, to prevent preempt running the
arch/powerpc/mm/book3s64/hash_utils.c:2081: * mm on another CPU (XXX: this may be racy vs kthread_use_mm).
arch/powerpc/mm/book3s64/hash_utils.c-2082- */
--
arch/powerpc/mm/book3s64/radix_tlb.c=661=static void exit_lazy_flush_tlb(struct mm_struct *mm)
--
arch/powerpc/mm/book3s64/radix_tlb.c-667- * A kthread could have done a mmget_not_zero() after the flushing CPU
arch/powerpc/mm/book3s64/radix_tlb.c:668: * checked mm_cpumask, and be in the process of kthread_use_mm when
arch/powerpc/mm/book3s64/radix_tlb.c-669- * interrupted here. In that case, current->mm will be set to mm,
arch/powerpc/mm/book3s64/radix_tlb.c:670: * because kthread_use_mm() setting ->mm and switching to the mm is
arch/powerpc/mm/book3s64/radix_tlb.c-671- * done with interrupts off.
--
arch/powerpc/platforms/book3s/vas-api.c=148=void vas_update_csb(struct coprocessor_request_block *crb,
--
arch/powerpc/platforms/book3s/vas-api.c-200-
arch/powerpc/platforms/book3s/vas-api.c:201: kthread_use_mm(task_ref->mm);
arch/powerpc/platforms/book3s/vas-api.c-202- rc = copy_to_user(csb_addr, &csb, sizeof(csb));
--
arch/x86/kvm/xen.c=1922=static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)
--
arch/x86/kvm/xen.c-1938-
arch/x86/kvm/xen.c:1939: kthread_use_mm(kvm->mm);
arch/x86/kvm/xen.c-1940- mm_borrowed = true;
--
drivers/dma/idxd/cdev.c=733=int idxd_copy_cr(struct idxd_wq *wq, ioasid_t pasid, unsigned long addr,
--
drivers/dma/idxd/cdev.c-754- */
drivers/dma/idxd/cdev.c:755: kthread_use_mm(mm);
drivers/dma/idxd/cdev.c-756- left = copy_to_user((void __user *)addr + status_size, cr + status_size,
--
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h=282=int amdgpu_amdkfd_reset_mes_queue(struct amdgpu_device *adev,
--
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h-301- } else if (current->flags & PF_KTHREAD) { \
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h:302: kthread_use_mm(mmptr); \
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h-303- valid = !get_user((dst), (wptr)); \
--
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c=3536=static void copy_context_work_handler(struct work_struct *work)
--
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c-3555-
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:3556: kthread_use_mm(mm);
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c-3557- for (i = 0; i < p->n_pdds; i++) {
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c=100=static void kfd_sdma_activity_worker(struct work_struct *work)
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c-203-
drivers/gpu/drm/amd/amdkfd/kfd_process.c:204: kthread_use_mm(mm);
drivers/gpu/drm/amd/amdkfd/kfd_process.c-205-
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c=2366=static void send_exception_work_handler(struct work_struct *work)
--
drivers/gpu/drm/amd/amdkfd/kfd_process.c-2386-
drivers/gpu/drm/amd/amdkfd/kfd_process.c:2387: kthread_use_mm(mm);
drivers/gpu/drm/amd/amdkfd/kfd_process.c-2388-
--
drivers/gpu/drm/i915/selftests/i915_selftest.c=222=static int __run_selftests(const char *name,
--
drivers/gpu/drm/i915/selftests/i915_selftest.c-254- if (mm) {
drivers/gpu/drm/i915/selftests/i915_selftest.c:255: kthread_use_mm(mm);
drivers/gpu/drm/i915/selftests/i915_selftest.c-256- if (unlikely(!current->mm)) {
--
drivers/gpu/drm/xe/xe_sync.c=76=static void user_fence_worker(struct work_struct *w)
--
drivers/gpu/drm/xe/xe_sync.c-81- if (mmget_not_zero(ufence->mm)) {
drivers/gpu/drm/xe/xe_sync.c:82: kthread_use_mm(ufence->mm);
drivers/gpu/drm/xe/xe_sync.c-83- if (copy_to_user(ufence->addr, &ufence->value, sizeof(ufence->value)))
--
drivers/gpu/drm/xe/xe_vm.c=4568=void xe_vm_snapshot_capture_delayed(struct xe_vm_snapshot *snap)
--
drivers/gpu/drm/xe/xe_vm.c-4592-
drivers/gpu/drm/xe/xe_vm.c:4593: kthread_use_mm(snap->snap[i].mm);
drivers/gpu/drm/xe/xe_vm.c-4594- if (!copy_from_user(snap->snap[i].data, userptr, snap->snap[i].len))
--
drivers/iommu/iommufd/pages.c=2350=int iopt_pages_rw_access(struct iopt_pages *pages, unsigned long start_byte,
--
drivers/iommu/iommufd/pages.c-2392- length, flags);
drivers/iommu/iommufd/pages.c:2393: kthread_use_mm(pages->source_mm);
drivers/iommu/iommufd/pages.c-2394- }
--
drivers/usb/gadget/function/f_fs.c=871=static void ffs_user_copy_worker(struct work_struct *work)
--
drivers/usb/gadget/function/f_fs.c-879- if (mmget_not_zero(io_data->mm)) {
drivers/usb/gadget/function/f_fs.c:880: kthread_use_mm(io_data->mm);
drivers/usb/gadget/function/f_fs.c-881- ret = ffs_copy_to_iter(io_data->buf, ret, &io_data->data);
--
drivers/usb/gadget/legacy/inode.c=467=static void ep_user_copy_worker(struct work_struct *work)
--
drivers/usb/gadget/legacy/inode.c-474- if (mmget_not_zero(mm)) {
drivers/usb/gadget/legacy/inode.c:475: kthread_use_mm(mm);
drivers/usb/gadget/legacy/inode.c-476- ret = copy_to_iter(priv->buf, priv->actual, &priv->to);
--
drivers/vdpa/vdpa_sim/vdpa_sim.c=175=static void vdpasim_work_fn(struct kthread_work *work)
--
drivers/vdpa/vdpa_sim/vdpa_sim.c-182- return;
drivers/vdpa/vdpa_sim/vdpa_sim.c:183: kthread_use_mm(mm);
drivers/vdpa/vdpa_sim/vdpa_sim.c-184- }
--
drivers/vfio/vfio_iommu_type1.c=3138=static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
--
drivers/vfio/vfio_iommu_type1.c-3163- if (kthread)
drivers/vfio/vfio_iommu_type1.c:3164: kthread_use_mm(mm);
drivers/vfio/vfio_iommu_type1.c-3165- else if (current->mm != mm)
--
drivers/vhost/vhost.c=412=static int vhost_run_work_kthread_list(void *data)
--
drivers/vhost/vhost.c-418-
drivers/vhost/vhost.c:419: kthread_use_mm(dev->mm);
drivers/vhost/vhost.c-420-
--
include/linux/iommufd.h=79=enum {
--
include/linux/iommufd.h-81- IOMMUFD_ACCESS_RW_WRITE = 1 << 0,
include/linux/iommufd.h:82: /* Set if the caller is in a kthread then rw will use kthread_use_mm() */
include/linux/iommufd.h-83- IOMMUFD_ACCESS_RW_KTHREAD = 1 << 1,
--
include/linux/kthread.h=280=void kthread_destroy_worker(struct kthread_worker *worker);
include/linux/kthread.h-281-
include/linux/kthread.h:282:void kthread_use_mm(struct mm_struct *mm);
include/linux/kthread.h-283-void kthread_unuse_mm(struct mm_struct *mm);
--
include/trace/events/kmem.h=427=TRACE_EVENT(rss_stat,
--
include/trace/events/kmem.h-445- * Since kthreads (PF_KTHREAD) have no mm_struct of their own
include/trace/events/kmem.h:446: * but can borrow one via kthread_use_mm(), we must filter them
include/trace/events/kmem.h-447- * out to avoid incorrectly attributing the RSS update to them.
--
kernel/fork.c=1358=struct file *get_task_exe_file(struct task_struct *task)
--
kernel/fork.c-1378- * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
kernel/fork.c:1379: * this kernel workthread has transiently adopted a user mm with kthread_use_mm,
kernel/fork.c-1380- * to do its AIO) is not set and if so returns a reference to it, after
--
kernel/kthread.c=1609=EXPORT_SYMBOL(kthread_destroy_worker);
--
kernel/kthread.c-1611-/**
kernel/kthread.c:1612: * kthread_use_mm - make the calling kthread operate on an address space
kernel/kthread.c-1613- * @mm: address space to operate on
kernel/kthread.c-1614- */
kernel/kthread.c:1615:void kthread_use_mm(struct mm_struct *mm)
kernel/kthread.c-1616-{
--
kernel/kthread.c-1654-}
kernel/kthread.c:1655:EXPORT_SYMBOL_GPL(kthread_use_mm);
kernel/kthread.c-1656-
kernel/kthread.c-1657-/**
kernel/kthread.c:1658: * kthread_unuse_mm - reverse the effect of kthread_use_mm()
kernel/kthread.c-1659- * @mm: address space to operate on
--
kernel/sched/membarrier.c-127- * b: read rq->curr->mm == NULL
kernel/sched/membarrier.c:128: * kthread_use_mm()
kernel/sched/membarrier.c-129- * f: current->mm = mm
--
lib/kunit/user_alloc.c=25=int kunit_attach_mm(void)
--
lib/kunit/user_alloc.c-46- /* Attach the mm. It will be cleaned up when the process dies. */
lib/kunit/user_alloc.c:47: kthread_use_mm(mm);
lib/kunit/user_alloc.c-48-
--
mm/oom_kill.c=122=static bool oom_cpuset_eligible(struct task_struct *tsk, struct oom_control *oc)
--
mm/oom_kill.c-129- * The process p may have detached its own ->mm while exiting or through
mm/oom_kill.c:130: * kthread_use_mm(), but one or more of its subthreads may still have a valid
mm/oom_kill.c-131- * pointer. Return p, or any of its subthreads with a valid ->mm, with
--
mm/oom_kill.c=912=static void __oom_kill_process(struct task_struct *victim, const char *message)
--
mm/oom_kill.c-977- /*
mm/oom_kill.c:978: * No kthread_use_mm() user needs to read from the userspace so
mm/oom_kill.c-979- * we are ok to reap it.
--
rust/kernel/task.rs=35=macro_rules! current {
--
rust/kernel/task.rs-43- // `begin_new_exec()` is responsible for safety.
rust/kernel/task.rs:44: // * Rust abstractions for things such as a `kthread_use_mm()` scope must require the
rust/kernel/task.rs-45- // closure to be `Send`, so the `NotThreadSafe` field of `CurrentTask` ensures that the
--
rust/kernel/task.rs=107=unsafe impl Sync for Task {}
--
rust/kernel/task.rs-127-///
rust/kernel/task.rs:128:/// * Calling `kthread_use_mm()` creates a new context, and `kthread_unuse_mm()` returns to the
rust/kernel/task.rs-129-/// old context.
rust/kernel/task.rs-130-///
rust/kernel/task.rs:131:/// This means that a `CurrentTask` obtained before a `kthread_use_mm()` call may be used again
rust/kernel/task.rs-132-/// once `kthread_unuse_mm()` is called, but it must not be used between these two calls.
rust/kernel/task.rs:133:/// Conversely, a `CurrentTask` obtained between a `kthread_use_mm()`/`kthread_unuse_mm()` pair
rust/kernel/task.rs-134-/// must not be used after `kthread_unuse_mm()`.
--
rust/kernel/task.rs=278= pub fn mm(&self) -> Option<&MmWithUser> {
--
rust/kernel/task.rs-290- //
rust/kernel/task.rs:291: // This is safe even if `kthread_use_mm()`/`kthread_unuse_mm()` are used. There are two
rust/kernel/task.rs-292- // relevant cases:
rust/kernel/task.rs:293: // * If the `&CurrentTask` was created before `kthread_use_mm()`, then it cannot be
rust/kernel/task.rs:294: // accessed during the `kthread_use_mm()`/`kthread_unuse_mm()` scope due to the
rust/kernel/task.rs-295- // `NotThreadSafe` field of `CurrentTask`.
rust/kernel/task.rs:296: // * If the `&CurrentTask` was created within a `kthread_use_mm()`/`kthread_unuse_mm()`
rust/kernel/task.rs-297- // scope, then the `&CurrentTask` cannot escape that scope, so the returned `&MmWithUser`
]
|
| 338/2 |
2026/09/23 20:44 |
llm |
expert |
1m
Model:
Tokens:
input: 69523
output: 37
thoughts: 3168
Thoughts: **Analysis of a Kernel Data Race: A Deep Dive**
Okay, let's break this down. My initial observation is that we're dealing with a nasty data race within the kernel's memory management. The provided stack traces clearly indicate a read-write conflict on a `struct mm_struct` – specifically, on its `mmlist` member, a doubly linked list. Task 3876 is *reading* from this structure during a `memcpy` operation in `copy_mm`, while Task 21217 is concurrently *modifying* it via `list_del` in `__mmput`, which happens during process exit.
The critical issue here isn't just the concurrent access; it's *what* is being accessed. `__mmput` is the destructor for an entire address space! It's tearing down mappings, freeing page tables, and ultimately destroying the very memory region Task 3876 is trying to duplicate. Moreover, the subsequent call to `dup_mmap` will try to acquire a lock and traverse the memory map that's being freed, a recipe for disaster. This is a classic Use-After-Free scenario, compounded by the complexities of concurrent linked-list manipulation.
The race is, without any question, *harmful*. This goes beyond simple data corruption; it threatens the entire system with undefined behavior and likely a crash. The concurrency violation here is fundamental and will lead to either an immediate panic or subtle, hard-to-debug memory corruption that manifests much later.
Now, let's understand the conditions that create this race. Task 21217 is exiting, likely due to a fatal signal. This is causing the `exit_mm` and subsequent `mmput` to be called. Crucially, the code path that invokes `list_del` only executes if `atomic_dec_and_test(&mm->mm_users)` returns true, i.e., `mm_users` is 1! If Task 3876 is supposed to be holding a reference to this `mm_struct`, why is `mm_users` 1?
If Task 3876 and Task 21217 are threads within the same process (`CLONE_VM` is set, `CLONE_THREAD`), the race should *not* happen under "normal" circumstances. `copy_mm` would increment `mm_users` upon a `CLONE_VM` call. Hence the only way for `mm_users` to be 1 is if either a) there is a bug related to refcounting or b) Task 3876 is holding a pointer to a `mm_struct` that it should not be.
Task 3876 is calling `copy_mm`, `copy_process`, and hence *should* have a valid mm_struct and therefore `mm_users >= 2`.
Therefore, the most likely root cause is a situation where Task 3876 has a shared memory descriptor (shared via `CLONE_VM`), *and* this descriptor is being freed by Task 21217!
Let's search the kernel history for related bugs. The goal is to figure out whether this is a known issue, a regression, or a novel problem.
|
| 339/2 |
2026/09/23 20:46 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[mm_users race] PathPrefix:kernel/]
Results: map[Output:7e019dcc470f sched: Improve cache locality of RSEQ concurrency IDs for intermittent workloads
08e28de1160a uprobes: use vm_special_mapping close() functionality
67197a4f28d2 mm, oom_adj: don't loop through tasks in __set_oom_adj when not necessary
212925802454 mm: oom: let oom_reap_task and exit_mmap run concurrently
7283094ec3db kernel, oom: fix potential pgd_lock deadlock from __mmdrop
1c2fb7a4c2ca ksm: fix deadlock with munlock in exit_mmap
31a78f23bac0 mm owner: fix race between swapoff and exit
402b08622d9a s390: KVM preparation: provide hook to enable pgstes in user pagetable
]
|
| 340/2 |
2026/09/23 20:46 |
llm |
expert-compressor |
0m
Model:
Reply: ### Summary of Investigation
#### 1. Data Race Report Breakdown
* **Bug:** KCSAN data-race in `__mmput` vs `copy_mm`
* **Write Stack (Task 21217 on CPU 1):**
* Target address: `0xffff8881046681f8` (offset 0x1f8 = 504 bytes within `struct mm_struct`, corresponding to `mm->mmlist.next` / `mm->mmlist.prev`). Size: 8 bytes.
* Stack trace:
* `__list_del` / `__list_del_entry` / `list_del` (`include/linux/list.h`)
* `__mmput+0xe2/0x1c0` (`kernel/fork.c:1198`) — inside `spin_lock(&mmlist_lock); list_del(&mm->mmlist); spin_unlock(&mmlist_lock);`
* `mmput+0x40/0x50` (`kernel/fork.c:1216`) — inside `if (atomic_dec_and_test(&mm->mm_users)) __mmput(mm);`
* `exit_mm+0x113/0x1a0` (`kernel/exit.c:618`)
* `do_exit+0x438/0x1510` (`kernel/exit.c:1000`)
* `do_group_exit+0xfe/0x140` (`kernel/exit.c:1155`)
* `get_signal+0xe07/0xf10` (`kernel/signal.c:3112`)
* `arch_do_signal_or_restart+0x96/0x480` (`arch/x86/kernel/signal.c:337`)
* `exit_to_user_mode_loop` / `syscall_exit_to_user_mode`
* `do_syscall_64`
* **Read Stack (Task 3876 on CPU 0):**
* Target address: `0xffff888104668000` (base of `struct mm_struct`, covering 1728 bytes = 0x6c0).
* Stack trace:
* `dup_mm` (`kernel/fork.c:1537`) — `memcpy(mm, oldmm, sizeof(*mm))`
* `copy_mm+0xd6/0x340` (`kernel/fork.c:1595`) — `mm = dup_mm(tsk, current->mm)` (clone without `CLONE_VM`)
* `copy_process+0x108a/0x2350` (`kernel/fork.c:2310`)
* `kernel_clone+0x1c0/0x5f0` (`kernel/fork.c:2769`)
* `__do_sys_clone` / `__x64_sys_clone`
* `do_syscall_64`
---
#### 2. Approaches Tried & Key Findings
* **Structural Analysis of the Race:**
* Base object: `struct mm_struct` at `0xffff888104668000`.
* Task 3876 runs `clone()` without `CLONE_VM` -> calls `dup_mm(tsk, current->mm)`.
* In `dup_mm()`:
```c
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm)); // Reads 1728 bytes of oldmm without locks!
if (!mm_init(mm, tsk))
goto fail_nomem;
uprobe_start_dup_mmap();
err = dup_mmap(mm, oldmm);
```
* Task 21217 terminates via signal handling -> `exit_mm()` -> `mmput(mm)`.
* In `mmput()`: `atomic_dec_and_test(&mm->mm_users)` decremented `mm_users` to 0 and called `__mmput()`.
* Inside `__mmput()`, `list_del(&mm->mmlist)` is executed at line 1198 under `mmlist_lock`.
* Because `dup_mm` executes `memcpy(mm, oldmm, sizeof(*mm))` without holding `mmlist_lock` (nor `mmap_lock`, which is taken later in `dup_mmap`), KCSAN flags the concurrent read of `oldmm->mmlist` with the write in `__mmput()`.
* **Lifetime and Concurrency Invariant Investigation:**
* Under standard POSIX / Linux kernel rules:
* Any task with an active `current->mm == mm` holds an `mm_users` reference.
* If Task 3876 and Task 21217 legitimately shared `mm`, `mm_users` must be at least 2.
* In normal scenarios (including `vfork` parent/child wakeups), `mm_users` cannot be 1 while one task is executing `dup_mm` in syscall context.
* However, the KCSAN report proves that Task 21217's `atomic_dec_and_test(&mm->mm_users)` evaluated to true (triggering `__mmput`) while Task 3876 was concurrently reading `oldmm` in `dup_mm`.
* Possibilities for why this occurred:
1. A refcount imbalance or underflow in asynchronous drivers/subsystems (e.g. io_uring worker, kthread, or driver `mmput`).
2. Missing synchronization in `dup_mm()` during `memcpy` of `oldmm` while `oldmm` state is mutating.
3. Premature release of `mm` or signal delivery race.
* **Impact of Concurrent Teardown (`__mmput`) and `dup_mm`:**
* `__mmput` executes:
* `uprobe_clear_state(mm);`
* `exit_aio(mm);`
* `ksm_exit(mm);`
* `khugepaged_exit(mm);`
* `exit_mmap(mm);` -> tears down VMAs and page tables, freeing them (`free_pgtables`, `tear_down_vmas`, `__mt_destroy(&mm->mm_mt)`).
* `list_del(&mm->mmlist);`
* `mmdrop(mm);`
* Concurrently, `dup_mm` after `memcpy`:
* Calls `mm_init(mm, tsk)`
* Calls `dup_mmap(mm, oldmm)`: attempts `mmap_write_lock_killable(oldmm)`, walks maple tree `oldmm->mm_mt`, duplicates VMAs, copies page ranges (`copy_page_range`).
* If `__mmput()` runs concurrently, `oldmm`'s page tables and VMAs are being destroyed/freed, resulting in immediate Use-After-Free (UAF), memory corruption, or NULL pointer dereferences in `dup_mmap()`.
* In addition, the unsynchronized `memcpy(mm, oldmm, sizeof(*mm))` reads partially updated and torn list pointers (`mmlist`), maple tree roots, and counters.
* This is definitively **HARMFUL** (catastrophic lifecycle violation and data corruption / UAF).
---
#### 3. Current Hypotheses & Working Theories
* **Classification: HARMFUL**
* This is not benign diagnostic code or a tolerated hint.
* It represents an unsynchronized read of an `mm_struct` undergoing final teardown (`__mmput`).
* Direct consequences:
1. Read of torn / destroyed pointers in `memcpy(mm, oldmm, sizeof(*mm))`.
2. Imminent Use-After-Free when `dup_mmap(mm, oldmm)` accesses VMAs, maple tree nodes, and page table hierarchies destroyed by `exit_mmap(mm)` inside `__mmput(mm)`.
3. Lifecycle invariant violation: `__mmput()` has `VM_BUG_ON(atomic_read(&mm->mm_users))`; any concurrent user of `oldmm` violates the fundamental refcount invariant of `mm_struct`.
---
#### 4. Critical Files and Complete Code References
* `kernel/fork.c`:
* `__mmput()` (lines 1185-1206):
```c
static inline void __mmput(struct mm_struct *mm)
{
VM_BUG_ON(atomic_read(&mm->mm_users));
uprobe_clear_state(mm);
exit_aio(mm);
ksm_exit(mm);
khugepaged_exit(mm); /* must run before exit_mmap */
exit_mmap(mm);
mm_put_huge_zero_folio(mm);
set_mm_exe_file(mm, NULL);
if (!list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
list_del(&mm->mmlist);
spin_unlock(&mmlist_lock);
}
if (mm->binfmt)
module_put(mm->binfmt->module);
lru_gen_del_mm(mm);
futex_hash_free(mm);
mmdrop(mm);
}
```
* `mmput()` (lines 1211-1217):
```c
void mmput(struct mm_struct *mm)
{
might_sleep();
if (atomic_dec_and_test(&mm->mm_users))
__mmput(mm);
}
```
* `dup_mm()` (lines 1527-1566):
```c
static struct mm_struct *dup_mm(struct task_struct *tsk,
struct mm_struct *oldmm)
{
struct mm_struct *mm;
int err;
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
if (!mm_init(mm, tsk))
goto fail_nomem;
uprobe_start_dup_mmap();
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
uprobe_end_dup_mmap();
...
```
* `kernel/exit.c`:
* `exit_mm()` (lines 584-621): clears `current->mm = NULL;` at line 611, then calls `mmput(mm);` at line 618.
---
#### 5. Next Steps
* Formulate the final response following the protocol strictly:
1. Call `set-results` tool with classification `HARMFUL`.
2. Structure the final response:
* Race Summary: `__mmput` vs `dup_mm` / `copy_mm` on `oldmm` / `mm->mmlist`.
* Synchronization context: Task 21217 in `__mmput` under `mmlist_lock`, Task 3876 in `dup_mm` performing unsynchronized `memcpy(mm, oldmm, sizeof(*mm))` without locks.
* Classification: **HARMFUL**.
* Failure Reasoning & Two-column interleaving showing concurrent teardown leading to UAF / memory corruption.
* Recommended fix.
Tokens:
input: 55052
output: 2738
thoughts: 0
|
| 341/2 |
2026/09/23 20:47 |
llm |
expert |
0m
Model:
Tokens:
input: 24069
output: 44
thoughts: 0
|
| 342/2 |
2026/09/23 20:47 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[CLONE_VM] PathPrefix:kernel/fork.c Since:5 years]
Results: map[Output:b61b6f95d672 futex: Also allocate private hash on vfork()
08cacffeef8f ftrace: fork: Initialize function graph state before copy_exec_state()
6b1c66c9cca9 exec_state: relocate dumpable information
ee9dce44362b futex: Drop CLONE_THREAD requirement for private default hash alloc
2b5f9dad32ed fs/exec: switch timens when a task gets a new mm
33a2d6bc3480 Revert "fs/exec: allow to unshare a time namespace on vfork+exec"
133e2d3e81de fs/exec: allow to unshare a time namespace on vfork+exec
]
|
| 343/2 |
2026/09/23 20:47 |
llm |
expert |
0m
Model:
Tokens:
input: 24302
output: 37
thoughts: 0
|
| 344/2 |
2026/09/23 20:47 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[memcpy.*oldmm] PathPrefix:kernel/fork.c]
Results:
|
| 345/2 |
2026/09/23 20:47 |
llm |
expert |
0m
Model:
Tokens:
input: 24352
output: 32
thoughts: 0
|
| 346/2 |
2026/09/23 20:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mm]
Results: map[SourceCode:1517: /**
1518: * dup_mm() - duplicates an existing mm structure
1519: * @tsk: the task_struct with which the new mm will be associated.
1520: * @oldmm: the mm to duplicate.
1521: *
1522: * Allocates a new mm structure and duplicates the provided @oldmm structure
1523: * content into it.
1524: *
1525: * Return: the duplicated mm or NULL on failure.
1526: */
1527: static struct mm_struct *dup_mm(struct task_struct *tsk,
1528: struct mm_struct *oldmm)
1529: {
1530: struct mm_struct *mm;
1531: int err;
1532:
1533: mm = allocate_mm();
1534: if (!mm)
1535: goto fail_nomem;
1536:
1537: memcpy(mm, oldmm, sizeof(*mm));
1538:
1539: if (!mm_init(mm, tsk))
1540: goto fail_nomem;
1541:
1542: uprobe_start_dup_mmap();
1543: err = dup_mmap(mm, oldmm);
1544: if (err)
1545: goto free_pt;
1546: uprobe_end_dup_mmap();
1547:
1548: mm->hiwater_rss = get_mm_rss(mm);
1549: mm->hiwater_vm = mm->total_vm;
1550:
1551: if (mm->binfmt && !try_module_get(mm->binfmt->module))
1552: goto free_pt;
1553:
1554: return mm;
1555:
1556: free_pt:
1557: /* don't put binfmt in mmput, we haven't got module yet */
1558: mm->binfmt = NULL;
1559: mm_init_owner(mm, NULL);
1560: mmput(mm);
1561: if (err)
1562: uprobe_end_dup_mmap();
1563:
1564: fail_nomem:
1565: return NULL;
1566: }
SourceFile:kernel/fork.c]
|
| 347/2 |
2026/09/23 20:48 |
llm |
expert |
0m
Model:
Tokens:
input: 25082
output: 32
thoughts: 0
|
| 348/2 |
2026/09/23 20:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_mm]
Results: map[SourceCode:1568: static int copy_mm(u64 clone_flags, struct task_struct *tsk)
1569: {
1570: struct mm_struct *mm, *oldmm;
1571:
1572: tsk->min_flt = tsk->maj_flt = 0;
1573: tsk->nvcsw = tsk->nivcsw = 0;
1574: #ifdef CONFIG_DETECT_HUNG_TASK
1575: tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1576: tsk->last_switch_time = 0;
1577: #endif
1578:
1579: tsk->mm = NULL;
1580: tsk->active_mm = NULL;
1581:
1582: /*
1583: * Are we cloning a kernel thread?
1584: *
1585: * We need to steal a active VM for that..
1586: */
1587: oldmm = current->mm;
1588: if (!oldmm)
1589: return 0;
1590:
1591: if (clone_flags & CLONE_VM) {
1592: mmget(oldmm);
1593: mm = oldmm;
1594: } else {
1595: mm = dup_mm(tsk, current->mm);
1596: if (!mm)
1597: return -ENOMEM;
1598: }
1599:
1600: tsk->mm = mm;
1601: tsk->active_mm = mm;
1602: return 0;
1603: }
SourceFile:kernel/fork.c]
|
| 349/2 |
2026/09/23 20:48 |
llm |
expert |
0m
Model:
Tokens:
input: 25625
output: 32
thoughts: 0
|
| 350/2 |
2026/09/23 20:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:__mmput]
Results: map[SourceCode:1185: static inline void __mmput(struct mm_struct *mm)
1186: {
1187: VM_BUG_ON(atomic_read(&mm->mm_users));
1188:
1189: uprobe_clear_state(mm);
1190: exit_aio(mm);
1191: ksm_exit(mm);
1192: khugepaged_exit(mm); /* must run before exit_mmap */
1193: exit_mmap(mm);
1194: mm_put_huge_zero_folio(mm);
1195: set_mm_exe_file(mm, NULL);
1196: if (!list_empty(&mm->mmlist)) {
1197: spin_lock(&mmlist_lock);
1198: list_del(&mm->mmlist);
1199: spin_unlock(&mmlist_lock);
1200: }
1201: if (mm->binfmt)
1202: module_put(mm->binfmt->module);
1203: lru_gen_del_mm(mm);
1204: futex_hash_free(mm);
1205: mmdrop(mm);
1206: }
SourceFile:kernel/fork.c]
|
| 351/2 |
2026/09/23 20:48 |
llm |
expert |
0m
Model:
Tokens:
input: 26025
output: 33
thoughts: 0
|
| 352/2 |
2026/09/23 20:49 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mmap]
Results: map[SourceCode:1708: __latent_entropy int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
1709: {
1710: struct vm_area_struct *mpnt, *tmp;
1711: int retval;
1712: unsigned long charge = 0;
1713: LIST_HEAD(uf);
1714: VMA_ITERATOR(vmi, mm, 0);
1715:
1716: if (mmap_write_lock_killable(oldmm))
1717: return -EINTR;
1718: flush_cache_dup_mm(oldmm);
1719: uprobe_dup_mmap(oldmm, mm);
1720: /*
1721: * Not linked in yet - no deadlock potential:
1722: */
1723: mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
1724:
1725: /* No ordering required: file already has been exposed. */
1726: dup_mm_exe_file(mm, oldmm);
1727:
1728: mm->total_vm = oldmm->total_vm;
1729: mm->data_vm = oldmm->data_vm;
1730: mm->exec_vm = oldmm->exec_vm;
1731: mm->stack_vm = oldmm->stack_vm;
1732:
1733: /* Use __mt_dup() to efficiently build an identical maple tree. */
1734: retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
1735: if (unlikely(retval))
1736: goto out;
1737:
1738: mt_clear_in_rcu(vmi.mas.tree);
1739: for_each_vma(vmi, mpnt) {
1740: struct file *file;
1741:
1742: retval = vma_start_write_killable(mpnt);
1743: if (retval < 0)
1744: goto loop_out;
1745: if (vma_test(mpnt, VMA_DONTCOPY_BIT)) {
1746: retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
1747: mpnt->vm_end, GFP_KERNEL);
1748: if (retval)
1749: goto loop_out;
1750:
1751: vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
1752: continue;
1753: }
1754: charge = 0;
1755: if (vma_test(mpnt, VMA_ACCOUNT_BIT)) {
1756: unsigned long len = vma_pages(mpnt);
1757:
1758: if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
1759: goto fail_nomem;
1760: charge = len;
1761: }
1762:
1763: tmp = vm_area_dup(mpnt);
1764: if (!tmp)
1765: goto fail_nomem;
1766: retval = vma_dup_policy(mpnt, tmp);
1767: if (retval)
1768: goto fail_nomem_policy;
1769: tmp->vm_mm = mm;
1770: retval = dup_userfaultfd(tmp, &uf);
1771: if (retval)
1772: goto fail_nomem_anon_vma_fork;
1773:
1774: if (vma_test(tmp, VMA_WIPEONFORK_BIT)) {
1775: /*
1776: * VMA_WIPEONFORK_BIT gets a clean slate in the child.
1777: * Don't prepare anon_vma until fault since we don't
1778: * copy page for current vma.
1779: */
1780: tmp->anon_vma = NULL;
1781: } else if (anon_vma_fork(tmp, mpnt))
1782: goto fail_nomem_anon_vma_fork;
1783:
1784: vma_start_write(tmp);
1785: vma_clear_flags_mask(tmp, VMA_LOCKED_MASK);
1786: /*
1787: * Copy/update hugetlb private vma information.
1788: */
1789: if (is_vm_hugetlb_page(tmp))
1790: hugetlb_dup_vma_private(tmp);
1791:
1792: /*
1793: * Link the vma into the MT. After using __mt_dup(), memory
1794: * allocation is not necessary here, so it cannot fail.
1795: */
1796: vma_iter_bulk_store(&vmi, tmp);
1797:
1798: mm->map_count++;
1799:
1800: if (tmp->vm_ops && tmp->vm_ops->open)
1801: tmp->vm_ops->open(tmp);
1802:
1803: file = tmp->vm_file;
1804: if (file) {
1805: struct address_space *mapping = file->f_mapping;
1806:
1807: get_file(file);
1808: i_mmap_lock_write(mapping);
1809: if (vma_is_shared_maywrite(tmp))
1810: mapping_allow_writable(mapping);
1811: flush_dcache_mmap_lock(mapping);
1812: /* insert tmp into the share list, just after mpnt */
1813: mapping_rmap_tree_insert_after(tmp, mpnt, mapping);
1814: flush_dcache_mmap_unlock(mapping);
1815: i_mmap_unlock_write(mapping);
1816: }
1817:
1818: if (!vma_test(tmp, VMA_WIPEONFORK_BIT))
1819: retval = copy_page_range(tmp, mpnt);
1820:
1821: if (retval) {
1822: mpnt = vma_next(&vmi);
1823: goto loop_out;
1824: }
1825: }
1826: /* a new mm has just been created */
1827: retval = arch_dup_mmap(oldmm, mm);
1828: loop_out:
1829: vma_iter_free(&vmi);
1830: if (!retval) {
1831: mt_set_in_rcu(vmi.mas.tree);
1832: ksm_fork(mm, oldmm);
1833: khugepaged_fork(mm, oldmm);
1834: } else {
1835: unsigned long end;
1836:
1837: /*
1838: * The entire maple tree has already been duplicated, but
1839: * replacing the vmas failed at mpnt (which could be NULL if
1840: * all were allocated but the last vma was not fully set up).
1841: * Use the start address of the failure point to clean up the
1842: * partially initialized tree.
1843: */
1844: if (!mm->map_count) {
1845: /* zero vmas were written to the new tree. */
1846: end = 0;
1847: } else if (mpnt) {
1848: /* partial tree failure */
1849: end = mpnt->vm_start;
1850: } else {
1851: /* All vmas were written to the new tree */
1852: end = ULONG_MAX;
1853: }
1854:
1855: /* Hide mm from oom killer because the memory is being freed */
1856: mm_flags_set(MMF_OOM_SKIP, mm);
1857: if (end) {
1858: vma_iter_set(&vmi, 0);
1859: tmp = vma_next(&vmi);
1860: UNMAP_STATE(unmap, &vmi, /* first = */ tmp,
1861: /* vma_start = */ 0, /* vma_end = */ end,
1862: /* prev = */ NULL, /* next = */ NULL);
1863:
1864: /*
1865: * Don't iterate over vmas beyond the failure point for
1866: * both unmap_vma() and free_pgtables().
1867: */
1868: unmap.tree_end = end;
1869: flush_cache_mm(mm);
1870: unmap_region(&unmap);
1871: charge = tear_down_vmas(mm, &vmi, tmp, end);
1872: vm_unacct_memory(charge);
1873: }
1874: __mt_destroy(&mm->mm_mt);
1875: /*
1876: * The mm_struct is going to exit, but the locks will be dropped
1877: * first. Set the mm_struct as unstable is advisable as it is
1878: * not fully initialised.
1879: */
1880: mm_flags_set(MMF_UNSTABLE, mm);
1881: }
1882: out:
1883: mmap_write_unlock(mm);
1884: flush_tlb_mm(oldmm);
1885: mmap_write_unlock(oldmm);
1886: if (!retval)
1887: dup_userfaultfd_complete(&uf);
1888: else
1889: dup_userfaultfd_fail(&uf);
1890: return retval;
1891:
1892: fail_nomem_anon_vma_fork:
1893: mpol_put(vma_policy(tmp));
1894: fail_nomem_policy:
1895: vm_area_free(tmp);
1896: fail_nomem:
1897: retval = -ENOMEM;
1898: vm_unacct_memory(charge);
1899: goto loop_out;
1900: }
SourceFile:mm/mmap.c]
|
| 353/2 |
2026/09/23 20:49 |
llm |
expert |
0m
Model:
Tokens:
input: 29052
output: 32
thoughts: 0
|
| 354/2 |
2026/09/23 20:49 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_init]
Results: map[SourceCode:1091: static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
1092: {
1093: mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
1094: mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
1095: atomic_set(&mm->mm_users, 1);
1096: atomic_set(&mm->mm_count, 1);
1097: seqcount_init(&mm->write_protect_seq);
1098: mmap_init_lock(mm);
1099: INIT_LIST_HEAD(&mm->mmlist);
1100: mm_pgtables_bytes_init(mm);
1101: mm->map_count = 0;
1102: mm->locked_vm = 0;
1103: atomic64_set(&mm->pinned_vm, 0);
1104: memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1105: spin_lock_init(&mm->page_table_lock);
1106: spin_lock_init(&mm->arg_lock);
1107: mm_init_cpumask(mm);
1108: mm_init_aio(mm);
1109: mm_init_owner(mm, p);
1110: mm_pasid_init(mm);
1111: RCU_INIT_POINTER(mm->exe_file, NULL);
1112: mmu_notifier_subscriptions_init(mm);
1113: init_tlb_flush_pending(mm);
1114: #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
1115: mm->pmd_huge_pte = NULL;
1116: #endif
1117: mm_init_uprobes_state(mm);
1118: hugetlb_count_init(mm);
1119: futex_mm_init(mm);
1120:
1121: mm_flags_clear_all(mm);
1122: if (current->mm) {
1123: unsigned long flags = __mm_flags_get_word(current->mm);
1124:
1125: __mm_flags_overwrite_word(mm, mmf_init_legacy_flags(flags));
1126: mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1127: } else {
1128: __mm_flags_overwrite_word(mm, coredump_filter);
1129: mm->def_flags = 0;
1130: }
1131:
1132: if (mm_alloc_pgd(mm))
1133: goto fail_mm_init;
1134:
1135: if (mm_alloc_id(mm))
1136: goto fail_noid;
1137:
1138: if (init_new_context(p, mm))
1139: goto fail_nocontext;
1140:
1141: if (mm_alloc_cid(mm, p))
1142: goto fail_cid;
1143:
1144: if (mm_alloc_sched(mm))
1145: goto fail_sched;
1146:
1147: if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
1148: NR_MM_COUNTERS))
1149: goto fail_pcpu;
1150:
1151: lru_gen_init_mm(mm);
1152: return mm;
1153:
1154: fail_pcpu:
1155: mm_destroy_sched(mm);
1156: fail_sched:
1157: mm_destroy_cid(mm);
1158: fail_cid:
1159: destroy_context(mm);
1160: fail_nocontext:
1161: mm_free_id(mm);
1162: fail_noid:
1163: mm_free_pgd(mm);
1164: fail_mm_init:
1165: free_mm(mm);
1166: return NULL;
1167: }
SourceFile:kernel/fork.c]
|
| 355/2 |
2026/09/23 20:49 |
llm |
expert |
0m
Model:
Tokens:
input: 30339
output: 32
thoughts: 0
|
| 356/2 |
2026/09/23 20:50 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/exit.c Name:exit_mm]
Results: map[SourceCode: 580: /*
581: * Turn us into a lazy TLB process if we
582: * aren't already..
583: */
584: static void exit_mm(void)
585: {
586: struct mm_struct *mm = current->mm;
587:
588: mm_exit_exec_release(current, mm);
589: if (!mm)
590: return;
591:
592: exit_mm_sched_cache(mm);
593:
594: mmap_read_lock(mm);
595: mmgrab_lazy_tlb(mm);
596: BUG_ON(mm != current->active_mm);
597: /* more a memory barrier than a real lock */
598: task_lock(current);
599: /*
600: * When a thread stops operating on an address space, the loop
601: * in membarrier_private_expedited() may not observe that
602: * tsk->mm, and the loop in membarrier_global_expedited() may
603: * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
604: * rq->membarrier_state, so those would not issue an IPI.
605: * Membarrier requires a memory barrier after accessing
606: * user-space memory, before clearing tsk->mm or the
607: * rq->membarrier_state.
608: */
609: smp_mb__after_spinlock();
610: local_irq_disable();
611: current->mm = NULL;
612: membarrier_update_current_mm(NULL);
613: enter_lazy_tlb(mm, current);
614: local_irq_enable();
615: task_unlock(current);
616: mmap_read_unlock(mm);
617: mm_update_next_owner(mm);
618: mmput(mm);
619: if (test_thread_flag(TIF_MEMDIE))
620: exit_oom_victim();
621: }
SourceFile:kernel/exit.c]
|
| 357/2 |
2026/09/23 20:50 |
llm |
expert |
0m
Model:
Tokens:
input: 31020
output: 32
thoughts: 0
|
| 358/2 |
2026/09/23 20:50 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:kernel/fork.c Name:mm_struct]
Results: map[Fields:[map[Name: OffsetBits:0 SizeBits:13824] map[Name:flexible_array OffsetBits:13824 SizeBits:0]]]
|
| 359/2 |
2026/09/23 20:50 |
llm |
expert |
0m
Model:
Tokens:
input: 31107
output: 39
thoughts: 0
|
| 360/2 |
2026/09/23 20:50 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:kernel/fork.c FieldOffset:504 Name:mm_struct]
Results: map[Fields:[map[Name: OffsetBits:0 SizeBits:13824]]]
|
| 361/2 |
2026/09/23 20:50 |
llm |
expert |
0m
Model:
Tokens:
input: 31179
output: 36
thoughts: 0
|
| 362/2 |
2026/09/23 20:51 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/mm_types.h Name:mm_struct]
Results: map[SourceCode:1175: struct mm_struct {
1176: struct {
1177: /*
1178: * Fields which are often written to are placed in a separate
1179: * cache line.
1180: */
1181: struct {
1182: /**
1183: * @mm_count: The number of references to &struct
1184: * mm_struct (@mm_users count as 1).
1185: *
1186: * Use mmgrab()/mmdrop() to modify. When this drops to
1187: * 0, the &struct mm_struct is freed.
1188: */
1189: atomic_t mm_count;
1190: } ____cacheline_aligned_in_smp;
1191:
1192: struct maple_tree mm_mt;
1193:
1194: unsigned long mmap_base; /* base of mmap area */
1195: unsigned long mmap_legacy_base; /* base of mmap area in bottom-up allocations */
1196: #ifdef CONFIG_HAVE_ARCH_COMPAT_MMAP_BASES
1197: /* Base addresses for compatible mmap() */
1198: unsigned long mmap_compat_base;
1199: unsigned long mmap_compat_legacy_base;
1200: #endif
1201: unsigned long task_size; /* size of task vm space */
1202: pgd_t * pgd;
1203:
1204: #ifdef CONFIG_MEMBARRIER
1205: /**
1206: * @membarrier_state: Flags controlling membarrier behavior.
1207: *
1208: * This field is close to @pgd to hopefully fit in the same
1209: * cache-line, which needs to be touched by switch_mm().
1210: */
1211: atomic_t membarrier_state;
1212: #endif
1213:
1214: /**
1215: * @mm_users: The number of users including userspace.
1216: *
1217: * Use mmget()/mmget_not_zero()/mmput() to modify. When this
1218: * drops to 0 (i.e. when the task exits and there are no other
1219: * temporary reference holders), we also release a reference on
1220: * @mm_count (which may then free the &struct mm_struct if
1221: * @mm_count also drops to 0).
1222: */
1223: atomic_t mm_users;
1224:
1225: /* MM CID related storage */
1226: struct mm_mm_cid mm_cid;
1227:
1228: /* sched_cache related statistics */
1229: struct sched_cache_stat sc_stat;
1230: #ifdef CONFIG_MMU
1231: atomic_long_t pgtables_bytes; /* size of all page tables */
1232: #endif
1233: int map_count; /* number of VMAs */
1234:
1235: spinlock_t page_table_lock; /* Protects page tables and some
1236: * counters
1237: */
1238: /*
1239: * Typically the current mmap_lock's offset is 56 bytes from
1240: * the last cacheline boundary, which is very optimal, as
1241: * its two hot fields 'count' and 'owner' sit in 2 different
1242: * cachelines, and when mmap_lock is highly contended, both
1243: * of the 2 fields will be accessed frequently, current layout
1244: * will help to reduce cache bouncing.
1245: *
1246: * So please be careful with adding new fields before
1247: * mmap_lock, which can easily push the 2 fields into one
1248: * cacheline.
1249: */
1250: struct rw_semaphore mmap_lock;
1251:
1252: struct list_head mmlist; /* List of maybe swapped mm's. These
1253: * are globally strung together off
1254: * init_mm.mmlist, and are protected
1255: * by mmlist_lock
1256: */
1257: #ifdef CONFIG_PER_VMA_LOCK
1258: struct rcuwait vma_writer_wait;
1259: /*
1260: * This field has lock-like semantics, meaning it is sometimes
1261: * accessed with ACQUIRE/RELEASE semantics.
1262: * Roughly speaking, incrementing the sequence number is
1263: * equivalent to releasing locks on VMAs; reading the sequence
1264: * number can be part of taking a read lock on a VMA.
1265: * Incremented every time mmap_lock is write-locked/unlocked.
1266: * Initialized to 0, therefore odd values indicate mmap_lock
1267: * is write-locked and even values that it's released.
1268: *
1269: * Can be modified under write mmap_lock using RELEASE
1270: * semantics.
1271: * Can be read with no other protection when holding write
1272: * mmap_lock.
1273: * Can be read with ACQUIRE semantics if not holding write
1274: * mmap_lock.
1275: */
1276: seqcount_t mm_lock_seq;
1277: #endif
1278: struct futex_mm_data futex;
1279:
1280: unsigned long hiwater_rss; /* High-watermark of RSS usage */
1281: unsigned long hiwater_vm; /* High-water virtual memory usage */
1282:
1283: unsigned long total_vm; /* Total pages mapped */
1284: unsigned long locked_vm; /* Pages that have PG_mlocked set */
1285: atomic64_t pinned_vm; /* Refcount permanently increased */
1286: unsigned long data_vm; /* VM_WRITE & ~VM_SHARED & ~VM_STACK */
1287: unsigned long exec_vm; /* VM_EXEC & ~VM_WRITE & ~VM_STACK */
1288: unsigned long stack_vm; /* VM_STACK */
1289: union {
1290: /* Temporary while VMA flags are being converted. */
1291: vm_flags_t def_flags;
1292: vma_flags_t def_vma_flags;
1293: };
1294:
1295: /**
1296: * @write_protect_seq: Locked when any thread is write
1297: * protecting pages mapped by this mm to enforce a later COW,
1298: * for instance during page table copying for fork().
1299: */
1300: seqcount_t write_protect_seq;
1301:
1302: spinlock_t arg_lock; /* protect the below fields */
1303:
1304: unsigned long start_code, end_code, start_data, end_data;
1305: unsigned long start_brk, brk, start_stack;
1306: unsigned long arg_start, arg_end, env_start, env_end;
1307:
1308: unsigned long saved_auxv[AT_VECTOR_SIZE]; /* for /proc/PID/auxv */
1309:
1310: #ifdef CONFIG_ARCH_HAS_ELF_CORE_EFLAGS
1311: /* the ABI-related flags from the ELF header. Used for core dump */
1312: unsigned long saved_e_flags;
1313: #endif
1314:
1315: struct percpu_counter rss_stat[NR_MM_COUNTERS];
1316:
1317: struct linux_binfmt *binfmt;
1318:
1319: /* Architecture-specific MM context */
1320: mm_context_t context;
1321:
1322: mm_flags_t flags; /* Must use mm_flags_* hlpers to access */
1323:
1324: #ifdef CONFIG_AIO
1325: spinlock_t ioctx_lock;
1326: struct kioctx_table __rcu *ioctx_table;
1327: #endif
1328: #ifdef CONFIG_MEMCG
1329: /*
1330: * "owner" points to a task that is regarded as the canonical
1331: * user/owner of this mm. All of the following must be true in
1332: * order for it to be changed:
1333: *
1334: * current == mm->owner
1335: * current->mm != mm
1336: * new_owner->mm == mm
1337: * new_owner->alloc_lock is held
1338: */
1339: struct task_struct __rcu *owner;
1340: #endif
1341:
1342: /* store ref to file /proc/<pid>/exe symlink points to */
1343: struct file __rcu *exe_file;
1344: #ifdef CONFIG_MMU_NOTIFIER
1345: struct mmu_notifier_subscriptions *notifier_subscriptions;
1346: #endif
1347: #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
1348: pgtable_t pmd_huge_pte; /* protected by page_table_lock */
1349: #endif
1350: #ifdef CONFIG_NUMA_BALANCING
1351: /*
1352: * numa_next_scan is the next time that PTEs will be remapped
1353: * PROT_NONE to trigger NUMA hinting faults; such faults gather
1354: * statistics and migrate pages to new nodes if necessary.
1355: */
1356: unsigned long numa_next_scan;
1357:
1358: /* Restart point for scanning and remapping PTEs. */
1359: unsigned long numa_scan_offset;
1360:
1361: /* numa_scan_seq prevents two threads remapping PTEs. */
1362: int numa_scan_seq;
1363: #endif
1364: /*
1365: * An operation with batched TLB flushing is going on. Anything
1366: * that can move process memory needs to flush the TLB when
1367: * moving a PROT_NONE mapped page.
1368: */
1369: atomic_t tlb_flush_pending;
1370: #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
1371: /* See flush_tlb_batched_pending() */
1372: atomic_t tlb_flush_batched;
1373: #endif
1374: struct uprobes_state uprobes_state;
1375: #ifdef CONFIG_PREEMPT_RT
1376: struct rcu_head delayed_drop;
1377: #endif
1378: #ifdef CONFIG_HUGETLB_PAGE
1379: atomic_long_t hugetlb_usage;
1380: #endif
1381: struct work_struct async_put_work;
1382:
1383: #ifdef CONFIG_IOMMU_MM_DATA
1384: struct iommu_mm_data *iommu_mm;
1385: #endif
1386: #ifdef CONFIG_KSM
1387: /*
1388: * Represent how many pages of this process are involved in KSM
1389: * merging (not including ksm_zero_pages).
1390: */
1391: unsigned long ksm_merging_pages;
1392: /*
1393: * Represent how many pages are checked for ksm merging
1394: * including merged and not merged.
1395: */
1396: unsigned long ksm_rmap_items;
1397: /*
1398: * Represent how many empty pages are merged with kernel zero
1399: * pages when enabling KSM use_zero_pages.
1400: */
1401: atomic_long_t ksm_zero_pages;
1402: #endif /* CONFIG_KSM */
1403: #ifdef CONFIG_LRU_GEN_WALKS_MMU
1404: struct {
1405: /* this mm_struct is on lru_gen_mm_list */
1406: struct list_head list;
1407: /*
1408: * Set when switching to this mm_struct, as a hint of
1409: * whether it has been used since the last time per-node
1410: * page table walkers cleared the corresponding bits.
1411: */
1412: unsigned long bitmap;
1413: #ifdef CONFIG_MEMCG
1414: /* points to the memcg of "owner" above */
1415: struct mem_cgroup *memcg;
1416: #endif
1417: } lru_gen;
1418: #endif /* CONFIG_LRU_GEN_WALKS_MMU */
1419: #ifdef CONFIG_MM_ID
1420: mm_id_t mm_id;
1421: #endif /* CONFIG_MM_ID */
1422: } __randomize_layout;
1423:
1424: /*
1425: * The mm_cpumask needs to be at the end of mm_struct, because it
1426: * is dynamically sized based on nr_cpu_ids.
1427: */
1428: char flexible_array[] __aligned(__alignof__(unsigned long));
1429: };
SourceFile:include/linux/mm_types.h]
|
| 363/2 |
2026/09/23 20:51 |
llm |
expert |
0m
Model:
Tokens:
input: 35136
output: 32
thoughts: 0
|
| 364/2 |
2026/09/23 20:51 |
tool |
codesearch-definition-comment |
0m
Args: map[ContextFile:kernel/fork.c Name:dup_mm]
Results: map[Comment:1517: /**
1518: * dup_mm() - duplicates an existing mm structure
1519: * @tsk: the task_struct with which the new mm will be associated.
1520: * @oldmm: the mm to duplicate.
1521: *
1522: * Allocates a new mm structure and duplicates the provided @oldmm structure
1523: * content into it.
1524: *
1525: * Return: the duplicated mm or NULL on failure.
1526: */
Kind:function]
|
| 365/2 |
2026/09/23 20:51 |
llm |
expert |
0m
Model:
Tokens:
input: 35333
output: 34
thoughts: 0
|
| 366/2 |
2026/09/23 20:51 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1190 LineCount:20]
Results: map[Contents:1190: exit_aio(mm);
1191: ksm_exit(mm);
1192: khugepaged_exit(mm); /* must run before exit_mmap */
1193: exit_mmap(mm);
1194: mm_put_huge_zero_folio(mm);
1195: set_mm_exe_file(mm, NULL);
1196: if (!list_empty(&mm->mmlist)) {
1197: spin_lock(&mmlist_lock);
1198: list_del(&mm->mmlist);
1199: spin_unlock(&mmlist_lock);
1200: }
1201: if (mm->binfmt)
1202: module_put(mm->binfmt->module);
1203: lru_gen_del_mm(mm);
1204: futex_hash_free(mm);
1205: mmdrop(mm);
1206: }
1207:
1208: /*
1209: * Decrement the use count and release all resources for an mm.
]
|
| 367/2 |
2026/09/23 20:51 |
llm |
expert |
0m
Model:
Tokens:
input: 35681
output: 34
thoughts: 0
|
| 368/2 |
2026/09/23 20:51 |
tool |
read-file |
0m
Args: map[File:kernel/fork.c FirstLine:1530 LineCount:20]
Results: map[Contents:1530: struct mm_struct *mm;
1531: int err;
1532:
1533: mm = allocate_mm();
1534: if (!mm)
1535: goto fail_nomem;
1536:
1537: memcpy(mm, oldmm, sizeof(*mm));
1538:
1539: if (!mm_init(mm, tsk))
1540: goto fail_nomem;
1541:
1542: uprobe_start_dup_mmap();
1543: err = dup_mmap(mm, oldmm);
1544: if (err)
1545: goto free_pt;
1546: uprobe_end_dup_mmap();
1547:
1548: mm->hiwater_rss = get_mm_rss(mm);
1549: mm->hiwater_vm = mm->total_vm;
]
|
| 369/2 |
2026/09/23 20:51 |
llm |
expert |
0m
Model:
Tokens:
input: 35991
output: 15
thoughts: 0
|
| 370/2 |
2026/09/23 20:52 |
tool |
set-results |
0m
Args:
Results:
|
| 371/2 |
2026/09/23 20:52 |
llm |
expert |
0m
Model:
Tokens:
input: 36019
output: 1203
thoughts: 0
|
| 372/1 |
2026/09/23 20:52 |
action |
format-explanation |
0m
Results: map[Explanation:### Race Summary
`__mmput` vs `copy_mm` / `dup_mm` on `oldmm` (specifically `oldmm->mmlist`).
- **Task 21217 (CPU 1)**: Executing `exit_mm()` -> `mmput()` -> `__mmput()`. At
line 1198 (`kernel/fork.c`), it modifies `mm->mmlist` under
`spin_lock(&mmlist_lock)`.
- **Task 3876 (CPU 0)**: Executing `kernel_clone()` -> `copy_process()` ->
`copy_mm()` -> `dup_mm()`. At line 1537 (`kernel/fork.c`), it performs
`memcpy(mm, oldmm, sizeof(*mm))` which reads the entire `oldmm` structure (1728
bytes, including `oldmm->mmlist`) without holding `mmlist_lock` or `mmap_lock`.
---
### Synchronization Context
In `__mmput()`, `list_del(&mm->mmlist)` is executed with `mmlist_lock` held.
However, in `dup_mm()`, `memcpy(mm, oldmm, sizeof(*mm))` reads the entire
`struct mm_struct` without locking (neither `mmlist_lock` nor `mmap_lock` is
held; `dup_mmap` takes `mmap_write_lock_killable(oldmm)` only after `memcpy()`
and `mm_init()`).
More fundamentally, for `__mmput()` to be running on CPU 1,
`atomic_dec_and_test(&mm->mm_users)` in `mmput()` evaluated to `true`,
indicating `mm->mm_users` reached 0. Concurrently, Task 3876 on CPU 0 is cloning
with `oldmm == current->mm` and dereferencing / copying `oldmm`. This indicates
an address space refcount/lifecycle violation.
---
### Final Classification
**HARMFUL**
---
### Failure Reasoning
1. **Teardown & Use-After-Free (UAF):**
When `mmput()` drops `mm_users` to 0, `__mmput()` proceeds to tear down the
entire address space:
- `exit_mmap(mm)` dismantles VMAs and tears down page tables
(`free_pgtables`, `tear_down_vmas`, `__mt_destroy(&mm->mm_mt)`).
- `futex_hash_free(mm)` and `mmdrop(mm)` release and potentially free the
underlying memory.
Concurrently, `dup_mm()` on CPU 0 executes `dup_mmap(mm, oldmm)`. It attempts
to walk `oldmm->mm_mt` via `__mt_dup()`, access `mpnt` VMAs, and copy page
tables (`copy_page_range()`). As `oldmm` is actively torn down and destroyed,
this results in Use-After-Free, page table corruption, kernel panic, or
crash.
2. **Torn/Corrupted Memory Copy:**
`memcpy(mm, oldmm, sizeof(*mm))` copies pointers and fields that are actively
being modified by `__mmput()` and its callees (`exit_aio`, `ksm_exit`,
`khugepaged_exit`, `exit_mmap`, `list_del`). The newly created `mm` ends up
with corrupted or stale pointers to resources already freed or unlinked on
the other CPU.
#### Failure Interleaving
```text
CPU 0 (Task 3876 - clone) CPU 1 (Task 21217 - do_exit)
------------------------- ----------------------------
do_exit()
exit_mm()
current->mm = NULL;
mmput(mm)
atomic_dec_and_test(&mm->mm_users)
== true
__mmput(mm)
exit_mmap(mm)
// Tears down VMAs and page
tables
kernel_clone()
copy_process()
copy_mm()
dup_mm(tsk, current->mm)
// memcpy reads oldmm while
// __mmput modifies it
memcpy(mm, oldmm, sizeof(*mm));
spin_lock(&mmlist_lock);
list_del(&mm->mmlist); // <---
WRITE
spin_unlock(&mmlist_lock);
futex_hash_free(mm);
mmdrop(mm); // frees mm /
structures
mm_init(mm, tsk);
dup_mmap(mm, oldmm);
mmap_write_lock_killable(oldmm);
__mt_dup(&oldmm->mm_mt, ...); // -> CRASH / UAF: maple tree & VMAs
already destroyed!
```
---
### Recommended Fix
The root issue is a lifecycle/refcount violation where `mm_users` is allowed to
drop to 0 while another task is still referencing `current->mm` in
`copy_process()`. Ensure proper `mm_users` accounting across asynchronous
tasks/kthreads borrowing or referencing `mm` (e.g. via `kthread_use_mm` /
`mmget_not_zero`) so that `__mmput()` cannot execute while `current->mm` is
concurrently accessed during `clone`.]
|