* [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity
@ 2026-12-02 0:27 Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 01/13] sched/mmcid: Move the execve() hooks into exec_mmap() Mathieu Desnoyers
` (12 more replies)
0 siblings, 13 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
Hi Thomas, Peter,
This series fixes bugs of the rseq concurrency IDs (mm_cid) in
execve(), in mode switches and in affinity changes. Either the tasks
own the CIDs of an mm (per task mode), or its CPUs do (per CPU mode).
The kernel switches between these modes as the number of users
changes. The series also adds selftests for mm_cid.
Four kernel patches come first. Patches 1 to 3 are fixes, marked for
stable. Patch 4 is an optimization. The kernel patches:
1 Move the execve() hooks into exec_mmap(). A task whose execve()
fails then no longer leaves and rejoins the CID management of its
mm. So it no longer returns to user space with an mm_cid of
0x80000000, leaks a CID, or loops in mm_get_cid().
2 Start a new mm with no allowed CPUs. Each task adds its own when
it joins. An affinity change made during execve() or fork() is
then no longer lost, except in a short race which patch 3 closes.
3 Take pi_lock in sched_mm_cid_fork() and sched_mm_cid_exit().
mm_update_cpus_allowed() then uses p->mm only while the task is
an active user of it. This fixes the use after free reported by
Weiming Shi, and the same window in kthreads that switch borrowed
mms.
4 Give no CID to io_uring and vhost workers. An SQPOLL thread then
no longer adds its CPUs to the mm, so a process in a cpuset keeps
compact IDs.
Patch 1 is Thomas's exec_mmap() patch from the v1 thread. Patches 2
and 3 are his affinity patch, split in two as he asked. Karl
Mehltretter proposed the placement of patch 1. Thomas agreed that I
carry the patches with small fixes folded in, and with a Suggested-by:
tag. "Changes since v1" lists these fixes.
The selftests are all in tools/testing/selftests/rseq. Each mm_cid must
stay below the number of possible CPUs. That number is the only bound:
user space sizes its per-CID data by it. The kernel also aims at
smaller IDs: below max_cids, the thread count or the CPU count of the
process. It does not promise them. A missed target makes the per-CID
data less compact, and breaks nothing. So most cases only print a note
when they miss a target. Two cases fail on one, because the bug they
check shows only that way:
- case 2 of mm_cid_execve_test: a leaked CID;
- case 2 of mm_cid_exec_affinity_test: a lost affinity change.
The selftest patches:
5 mm_cid_execve_test: the mm_cid after a failed execve(). Fails on
tip, passes from patch 1 on.
6 mm_cid_transition_test: each thread increments a counter indexed
by its mm_cid, while the number of threads crosses the mode
thresholds. Cases 1 and 2 fail on tip, pass from patch 1 on.
7 mm_cid_bound_test: the largest mm_cid stays below the number of
possible CPUs while the thread count rises and falls.
8 mm_cid_exec_affinity_test: an affinity change during execve().
Case 2 fails on tip, passes from patch 2 on.
9 A case of mm_cid_bound_test: the IDs after the affinity is
widened.
10 mm_cid_window_test: two cases, each aimed at a narrow window of a
mode switch. Case 1 fails on tip, passes from patch 1 on.
11 A case of mm_cid_execve_test: a single thread must not leak a CID
after an affinity change during a failed execve(). Fails on tip,
passes from patch 1 on.
12 A case of mm_cid_bound_test: an io_uring SQPOLL thread in a
cpuset. Its target is met from patch 4 on.
13 A case of mm_cid_bound_test: clone3() into a wider cpuset. It
covers the recompute of pcpu_thrs in the join (patch 2).
Changes since v1
================
- Thomas's two patches replace the v1 patches 1 and 3 to 5. These
small fixes are folded in:
- patch 1: the comment on the last user in sched_mm_cid_exit() loses
its last sentence. It said that sched_mm_cid_after_execve() handles
a stale transit after a failed execve(). With the hooks in
exec_mmap(), a failed execve() no longer rejoins the mm.
- patch 2: when a join widens the mm in per CPU mode, it also
recomputes pcpu_thrs. A Spin model found a race which needs it.
- patch 2: the comment above __mm_update_cpus_allowed() is reworded.
It names its caller sched_mm_cid_add_user() and its return value.
Patch 3 adds the active bit to it.
- patch 3: the !CONFIG_SCHED_MM_CID stub of mm_update_cpus_allowed()
gets its missing braces.
- patch 3: comments on the new pi_lock rule, in the "Serialization
rules" block and in mm_update_cpus_allowed().
- v1 patch 6, from Weiming Shi, is dropped: patch 3 fixes the same
use after free. Patch 3 credits him with Reported-by: and a Closes:
link. It also keeps the other Reported-by: of his v3 patch.
- v1 patch 2 is now patch 4, with no Fixes: and no Cc: stable. In my
reply to the Sashiko review, I planned to also skip user workers in
set_cpus_allowed_common(). This is no longer needed. With patch 4, a
worker never joins, so it is never active. With patch 3,
mm_update_cpus_allowed() ignores a task which is not active.
- v1 patches 7, 9, 10, 12, 14 and 15 are now patches 5 to 10.
- Case 2 of mm_cid_execve_test (v1 patch 8) is dropped. It tested a
detail of the v1 implementation. With patch 1, a failed execve() no
longer leaves the CID management of the mm. Case 2 is now the case
of v1 patch 17 (patch 11).
- v1 patch 11 (a transition case with affinity changes by another
process) found no bug, and is dropped.
- v1 patch 16 (mm_cid_teardown_test) is dropped. It aimed at the use
after free which patch 3 fixes. A test cannot see that bug without
KASAN, and this one did not reproduce it with KASAN.
- v1 patch 13 is dropped. Its two transition cases aimed at two past
fixes. With each fix undone, its case did not fail. The fixes:
- commit b2e48c429ec5 ("sched/mmcid: Prevent CID stalls due to
concurrent forks");
- commit 4327fb13fa47 ("sched/mmcid: Prevent live lock on task to CPU
mode transition").
- Case 1 of mm_cid_execve_test and case 1 of mm_cid_window_test now
fail only on an mm_cid at or above the number of possible CPUs. In
v1 they failed at the number of allowed CPUs. That value now only
gets a note.
- New: the io_uring SQPOLL case (patch 12). The Sashiko review of v1
led to it.
- New: the clone3() case (patch 13).
- The selftest changelogs now name the patch that makes each failing
case pass.
Testing
=======
The five tests have 15 cases. They ran on twelve x86-64 QEMU guests
with lockdep and 2 to 64 CPUs. Some cases skip on the small guests.
They ran three times on tip, and three times after each kernel patch.
No guest reported a kernel warning. The table shows the results of the
list above as counts. It gives each failing case, with the number of
guests where it failed in each of the three runs. "execve 1" is case 1
of mm_cid_execve_test.
kernel failing cases
tip execve 1 (12, 12, 12), execve 2 (7, 10, 9),
transition 1 (12, 12, 12),
transition 2 (10, 10, 10),
exec_affinity 2 (8, 8, 8: all the guests that
run it), window 1 (12, 12, 12)
+ patch 1 exec_affinity 2 (1, 1, 1: a guest with 16 CPUs)
+ patches 1-2 none
+ patches 1-3 none
+ patches 1-4 none
Some changelogs describe more checks:
- patch 1: a reproducer of the loop in mm_get_cid();
- patch 2: a clone3() test on tip, which is not in the series;
- patches 10 and 13: runs on kernels with a fix undone.
A Spin model checked the CID management with patches 1 to 3. It
models the mm_cid code of kernel/sched/core.c and kernel/sched/sched.h,
and its hooks in fork, exit and exec_mmap(). Each lock section is one
step. In the model:
- tasks fork, exit and call execve();
- the CPUs switch tasks at any time;
- another task changes the affinity of any task.
The model is small. 2 or 3 CPUs run 2 to 4 tasks. The number of
possible CPUs, 2 to 8, sets the size of the CID space and of the CPU
masks. 35 searches visited every state. They cover:
- 2 CPUs and 3 tasks, with one affinity change, or two without
execve();
- 2 CPUs and 4 tasks, without affinity changes;
- 3 CPUs and 2 tasks;
- 3 CPUs and 3 tasks, without execve() and without affinity changes.
No state they reach violates these properties:
- The CIDs are unique and below the number of possible CPUs.
- mm_get_cid() never loops.
- No affinity change is lost.
- The affinity update never reads a freed mm.
Larger searches ran out of memory, among them 3 CPUs with 3 tasks
and execve(), and two affinity changes with execve(). They found
no violation in the states they visited. With one of patches 1 to 3
removed, the model reaches the bugs which that patch fixes.
The Spin model does not cover memory ordering. Five herd7 tests
checked the active check of patch 3 under the kernel memory model.
The two which model the code pass. Each of the other three changes
one thing, and fails:
- two drop pi_lock from the join or the leave;
- one sets the task active before exec_mmap() stores the new p->mm.
Neither the model nor the herd7 tests are part of the series.
How this was developed
======================
An LLM coding assistant worked under my direction. It wrote the
changelogs, the tests, the code of patch 4 and the small fixes folded
into patches 1 to 3. It also wrote the Spin model and the herd7
tests. I reviewed all of it. The rest of the code of patches 1 to 3 is
Thomas's.
Based on tip sched/urgent, edf8ee401674.
Links:
- v1: https://lore.kernel.org/all/cover.1794932121.git.mathieu.desnoyers@efficios.com/
- Thomas's exec_mmap() patch:
https://lore.kernel.org/all/87ecc2qs9i.ffs@fw13/
- Thomas's affinity patch:
https://lore.kernel.org/all/87v75fqnsi.ffs@fw13/
- Karl's proposal to move the hooks into exec_mmap():
https://lore.kernel.org/all/awyrCYBrJS-CuBE8@gmail.com/
- Weiming Shi, "[PATCH v3] sched/mmcid: Synchronize MM teardown with
affinity updates":
https://lore.kernel.org/all/20261110183809.3308868-1-bestswngs@gmail.com/
Mathieu Desnoyers (13):
sched/mmcid: Move the execve() hooks into exec_mmap()
sched/mmcid: Add the allowed CPUs of each joining task to the mm
sched/mmcid: Serialize joins and exits with affinity changes by
pi_lock
sched/mmcid: Give no concurrency ID to user workers
selftests/rseq: Test the concurrency ID after a failed execve
selftests/rseq: Test the concurrency IDs across ownership mode
switches
selftests/rseq: Test the upper bound of the concurrency IDs
selftests/rseq: Test an affinity change by another process during
execve
selftests/rseq: Test the concurrency IDs after the affinity is widened
selftests/rseq: Test two race windows of the concurrency ID mode
switches
selftests/rseq: Test the last user after an affinity change during
execve
selftests/rseq: Test the concurrency IDs with an io_uring SQPOLL
thread
selftests/rseq: Test the concurrency IDs after clone3() into a wider
cpuset
fs/exec.c | 14 +-
include/linux/mm_types.h | 5 +-
kernel/sched/core.c | 106 +-
tools/testing/selftests/rseq/.gitignore | 5 +
tools/testing/selftests/rseq/Makefile | 5 +-
.../selftests/rseq/mm_cid_bound_test.c | 932 ++++++++++++++++++
.../rseq/mm_cid_exec_affinity_test.c | 288 ++++++
.../selftests/rseq/mm_cid_execve_test.c | 618 ++++++++++++
.../selftests/rseq/mm_cid_transition_test.c | 388 ++++++++
.../selftests/rseq/mm_cid_window_test.c | 525 ++++++++++
10 files changed, 2853 insertions(+), 33 deletions(-)
create mode 100644 tools/testing/selftests/rseq/mm_cid_bound_test.c
create mode 100644 tools/testing/selftests/rseq/mm_cid_exec_affinity_test.c
create mode 100644 tools/testing/selftests/rseq/mm_cid_execve_test.c
create mode 100644 tools/testing/selftests/rseq/mm_cid_transition_test.c
create mode 100644 tools/testing/selftests/rseq/mm_cid_window_test.c
base-commit: edf8ee40167473828c1ae20ab9c6442f2e66dded
--
2.47.3
^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v2 01/13] sched/mmcid: Move the execve() hooks into exec_mmap()
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 02/13] sched/mmcid: Add the allowed CPUs of each joining task to the mm Mathieu Desnoyers
` (11 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter, stable
bprm_execve() makes the task leave the CID management of its mm at the
start of execve(). The task joins again at the end: the new mm on
success, the old one on failure.
sched_mm_cid_fork() handles the join. It is written for a fork() child,
which does not run yet. In per CPU mode the child gets no CID there. It
takes the CID of its CPU when it is scheduled in. When the join
switches the mode, the forking task runs the fixups. These are
mm_cid_fixup_tasks_to_cpus() and mm_cid_fixup_cpus_to_tasks(). A
successful execve() fits this design. The task is the first user of a
new mm, and the first user gets its CID at once.
A failed execve() does not fit. The task rejoins its old mm while it
runs. A failure before de_thread() leaves the other threads alive. The
CPUs can also still own CIDs of the old mm. This has three effects:
1. In per CPU mode, the task returns to user space with no CID. It
reads an mm_cid of 0x80000000 until its next context switch. A
program that indexes per-CID data with it would read out of bounds.
mm_cid_execve_test of this series found it.
2. Per CPU mode can last down to one user. This happens with two or
three possible CPUs, or when the mm counts one allowed CPU. The mm
can count one allowed CPU while its task runs on other CPUs.
mm_update_cpus_allowed() ignores an affinity change while the mm has
no user, as inside a failed execve(). When that last user leaves,
sched_mm_cid_exit() frees only the CID of its own CPU. Other CPUs
keep theirs. The rejoin then takes a new CID, and a CID leaks. Case 2
of mm_cid_execve_test of this series shows it: a single thread reads
mm_cid 1. The comment above run_child_widened() in that test has the
sequence as a diagram. On an earlier tip, a guest with two CPUs
locked up after such a leak. This was not reproduced on tip
sched/urgent.
3. The rejoin can switch the mm to per CPU mode. If the other users
hold every CID, only the fixups can free one. The task runs them
itself, and it can be preempted before them. A and B are two threads
on CPUs 0 and 1 of a machine with two possible CPUs. The mm is in
per task mode. C is the vfork() child of B:
CPU 0 CPU 1
A: execve()
sched_mm_cid_before_execve(A)
users 2 -> 1, frees the CID of A
B: vfork()
sched_mm_cid_fork(C)
users 1 -> 2, C takes a CID
B and C hold both CIDs
A: execve() fails
sched_mm_cid_after_execve(A)
sched_mm_cid_fork(A)
users 2 -> 3, switch to per CPU mode
A: is preempted before
mm_cid_fixup_tasks_to_cpus()
A: is scheduled in again
mm_cid_schedin(A)
no CID on A or on CPU 0
mm_get_cid() loops
A model in the Spin model checker found this. A reproducer makes a
SCHED_FIFO task wake every 50us to preempt A. On tip sched/urgent,
it hung each of four guests with two CPUs. On a fifth guest, the
QEMU monitor showed a CPU in mm_get_cid() under __schedule().
Fix this by moving both hooks into exec_mmap(). The task leaves the old
mm after mm_exit_exec_release(). By then, de_thread() has killed the
other threads. Another process may still share the old mm: a vfork()
parent, or a task created with CLONE_VM and without CLONE_THREAD. The
leave is then an ordinary exit of one user. The task joins the new mm
once it is installed.
In between, only down_write_killable() and mmap_read_lock_killable()
can fail, and only with a pending SIGKILL. The task then dies. A tracer
cannot cancel a SIGKILL. It could cancel the SIGSEGV which
bprm_execve() forces on other failures past the point of no return. So
a task never rejoins its old mm. The last user no longer needs to free
the CID of its CPU in sched_mm_cid_exit().
Karl Mehltretter found that earlier versions of this change broke under
ptrace and with vfork(). He proposed the placement in exec_mmap().
With this change, mm_cid_execve_test, mm_cid_transition_test and
mm_cid_window_test no longer read 0x80000000 on guests with 2 to 64
CPUs. Case 2 of mm_cid_execve_test no longer leaks a CID. The
SCHED_FIFO reproducer completed 20000 attempts on each of four guests
with two CPUs.
Fixes: 653fda7ae73d ("sched/mmcid: Switch over to the new mechanism")
Suggested-by: Thomas Gleixner <tglx@kernel.org>
Suggested-by: Karl Mehltretter <kmehltretter@gmail.com>
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
Link: https://lore.kernel.org/all/awyrCYBrJS-CuBE8@gmail.com/
---
fs/exec.c | 13 ++++++++++---
kernel/sched/core.c | 12 ++++++------
2 files changed, 16 insertions(+), 9 deletions(-)
diff --git a/fs/exec.c b/fs/exec.c
index 8d2b14e1d455..d188f014871d 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -858,6 +858,15 @@ static int exec_mmap(struct linux_binprm *bprm)
/* Clean up futexes and release the mm */
mm_exit_exec_release(tsk, old_mm);
+ /*
+ * The below lock acquisitions can only fail due to a SIGKILL. In
+ * that case the task will die and even PTRACE won't be able to
+ * resurrect it. So this is the safest place to leave MM CID
+ * management as there is no way that this will go back to user
+ * space.
+ */
+ sched_mm_cid_before_execve(current);
+
ret = down_write_killable(&tsk->signal->exec_update_lock);
if (ret)
return ret;
@@ -908,6 +917,7 @@ static int exec_mmap(struct linux_binprm *bprm)
} else {
mmdrop_lazy_tlb(active_mm);
}
+ sched_mm_cid_after_execve(current);
futex_exec_done(tsk);
return 0;
}
@@ -1853,7 +1863,6 @@ static int bprm_execve(struct linux_binprm *bprm)
*/
check_unsafe_exec(bprm);
current->in_execve = 1;
- sched_mm_cid_before_execve(current);
sched_exec();
@@ -1866,7 +1875,6 @@ static int bprm_execve(struct linux_binprm *bprm)
if (retval < 0)
goto out;
- sched_mm_cid_after_execve(current);
rseq_execve(current);
/* execve succeeded */
current->in_execve = 0;
@@ -1885,7 +1893,6 @@ static int bprm_execve(struct linux_binprm *bprm)
if (bprm->point_of_no_return && !fatal_signal_pending(current))
force_fatal_sig(SIGSEGV);
- sched_mm_cid_after_execve(current);
rseq_force_update();
current->in_execve = 0;
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 07ec834d54fd..3ad27670d67f 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -11060,7 +11060,7 @@ static void sched_mm_cid_fork(struct task_struct *t)
if (!mm->mm_cid.users) {
sched_mm_cid_add_user(t, mm);
t->mm_cid.cid = mm_get_cid(mm);
- /* Required for execve() */
+ /* Required for execve() as the task is running */
pcp->cid = t->mm_cid.cid;
return;
}
@@ -11158,10 +11158,10 @@ void sched_mm_cid_exit(struct task_struct *t)
}
/* Last user */
scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) {
- /* Required across execve() */
- if (t == current)
- mm_cid_transit_to_task(t, this_cpu_ptr(mm->mm_cid.pcpu));
- /* Ignore mode change. There is nothing to do. */
+ /*
+ * Ignore mode change. There is nothing to do as the MM
+ * is going away in the common case.
+ */
sched_mm_cid_remove_user(t);
}
}
@@ -11178,7 +11178,7 @@ void sched_mm_cid_exit(struct task_struct *t)
cancel_work_sync(&mm->mm_cid.work);
}
-/* Deactivate MM CID allocation across execve() */
+/* Deactivate MM CID allocation across execve() switching the MM */
void sched_mm_cid_before_execve(struct task_struct *t)
{
sched_mm_cid_exit(t);
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 02/13] sched/mmcid: Add the allowed CPUs of each joining task to the mm
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 01/13] sched/mmcid: Move the execve() hooks into exec_mmap() Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 03/13] sched/mmcid: Serialize joins and exits with affinity changes by pi_lock Mathieu Desnoyers
` (10 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter, stable
max_cids, the CID range of an mm, depends on the number of CPUs its
tasks may run on. The mm keeps the union of the allowed CPUs of its
tasks. This set only grows. mm_init_cid() copies the allowed CPUs of
one task into a new mm. A task becomes a user of the mm when it joins
it in sched_mm_cid_fork(). Later affinity changes reach the mm through
mm_update_cpus_allowed(). Since
commit b0c3d51b54f8 ("sched/mmcid: Provide precomputed maximal value"),
it does nothing for an mm with no user.
So a change made between the copy and the join is lost. In this
sequence, task C runs on CPU 0 only and calls execve(). Its parent P
widens the affinity of C to CPUs 0-63:
P (parent) C (in execve())
exec_mmap()
tsk->mm = new mm
mm_init_cid(new mm, C)
allowed CPUs of mm = 0
nr_cpus_allowed = 1
sched_setaffinity(C, CPUs 0-63)
set_cpus_allowed_common()
C->cpus_mask = CPUs 0-63
mm_update_cpus_allowed(new mm)
mm_cid.users == 0: return
sched_mm_cid_after_execve()
sched_mm_cid_fork()
mm_cid.users = 1
nr_cpus_allowed stays 1
max_cids and pcpu_thrs of the new mm then derive from one allowed CPU.
So the mm switches to per CPU mode as soon as it has two threads. It
switches back only below pcpu_thrs users, which is 1, so it stays in
per CPU mode. There, each CPU keeps the CID it took. The CIDs stay
below the number of possible CPUs, but they are no longer compact.
Per-CID data in user space then spreads over more memory. In testing on
a 64-CPU guest, C ran one thread per CPU, then stopped all but two.
They read mm_cid 1 and 63, instead of values below 2.
A fork() child has the same window, between dup_mm() and
sched_mm_cid_fork(). clone3() with CLONE_INTO_CGROUP into a cpuset with
more CPUs hits it: cpuset_fork() changes the affinity of the child
there. In testing on tip sched/urgent, a process in a cpuset of two
CPUs created a child this way, into a cpuset of all CPUs. The child ran
one thread per CPU, then stopped all but two. In 43 of 80 attempts on
guests with 4 to 64 CPUs, one of the two read an mm_cid of 2 or more.
A child created by a parent already in the cpuset of all CPUs never
did.
Fix this by starting a new mm with no allowed CPUs. Each task adds its
own in sched_mm_cid_add_user() when it joins. The new mm of execve()
comes from mm_alloc(), which already calls mm_init_cid(). So
exec_mmap() no longer calls it.
When the join widens the mm in per CPU mode, it also recomputes
pcpu_thrs, as mm_update_cpus_allowed() does. Otherwise a race leaves a
stale threshold. An affinity change can store the new CPUs of a task
just before the task joins. The join adds them to the mm. The update
then finds nothing to add, and returns before its own recompute. The
mm would stay in per CPU mode too long. A Spin model of the CID
management found this race.
With this change, mm_cid_exec_affinity_test of this series passes on
guests with 4 to 64 CPUs. In the clone3() test above, no attempt read
an mm_cid of 2 or more, with this patch alone on tip sched/urgent.
"sched/mmcid: Serialize joins and exits with affinity changes by
pi_lock" relies on this change. It no longer updates the mm of a task
that has not joined yet, so the join must add the CPUs of the task.
Fixes: b0c3d51b54f8 ("sched/mmcid: Provide precomputed maximal value")
Suggested-by: Thomas Gleixner <tglx@kernel.org>
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
fs/exec.c | 1 -
include/linux/mm_types.h | 5 ++--
kernel/sched/core.c | 52 ++++++++++++++++++++++++++++++----------
3 files changed, 42 insertions(+), 16 deletions(-)
diff --git a/fs/exec.c b/fs/exec.c
index d188f014871d..20dea1509726 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -892,7 +892,6 @@ static int exec_mmap(struct linux_binprm *bprm)
tsk->active_mm = mm;
tsk->mm = mm;
sched_cache_exec_mmap(tsk, mm);
- mm_init_cid(mm, tsk);
exec_state = task_exec_state_replace(tsk, exec_state);
/*
* This prevents preemption while active_mm is being loaded and
diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h
index 1ed35d258d2e..dd2ecb900c45 100644
--- a/include/linux/mm_types.h
+++ b/include/linux/mm_types.h
@@ -1624,14 +1624,14 @@ static inline unsigned long *mm_cidmask(struct mm_struct *mm)
return (unsigned long *)cid_bitmap;
}
-void mm_init_cid(struct mm_struct *mm, struct task_struct *p);
+void mm_init_cid(struct mm_struct *mm);
static inline int mm_alloc_cid_noprof(struct mm_struct *mm, struct task_struct *p)
{
mm->mm_cid.pcpu = alloc_percpu_noprof(struct mm_cid_pcpu);
if (!mm->mm_cid.pcpu)
return -ENOMEM;
- mm_init_cid(mm, p);
+ mm_init_cid(mm);
return 0;
}
# define mm_alloc_cid(...) alloc_hooks(mm_alloc_cid_noprof(__VA_ARGS__))
@@ -1651,7 +1651,6 @@ static inline unsigned int mm_cid_size(void)
/* Use 2 * NR_CPUS as worse case for static allocation. */
# define MM_CID_STATIC_SIZE (2 * sizeof(cpumask_t))
#else /* CONFIG_SCHED_MM_CID */
-static inline void mm_init_cid(struct mm_struct *mm, struct task_struct *p) { }
static inline int mm_alloc_cid(struct mm_struct *mm, struct task_struct *p) { return 0; }
static inline void mm_destroy_cid(struct mm_struct *mm) { }
static inline unsigned int mm_cid_size(void)
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 3ad27670d67f..80239800c566 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -10889,26 +10889,45 @@ static bool mm_update_max_cids(struct mm_struct *mm)
return true;
}
-static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk)
+/*
+ * Add @affmsk to the allowed CPUs of @mm. Return true if the set grew.
+ * Called from mm_update_cpus_allowed() on an affinity change, and from
+ * sched_mm_cid_add_user() when a task joins the MM CID management.
+ */
+static inline bool __mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk)
{
- struct cpumask *mm_allowed;
- struct mm_mm_cid *mc;
+ struct cpumask *mm_allowed = mm_cpus_allowed(mm);
+ struct mm_mm_cid *mc = &mm->mm_cid;
unsigned int weight;
- if (!mm || !READ_ONCE(mm->mm_cid.users))
- return;
+ lockdep_assert_held(&mc->lock);
+
/*
* mm::mm_cid::mm_cpus_allowed is the superset of each threads
* allowed CPUs mask which means it can only grow.
*/
- mc = &mm->mm_cid;
- guard(raw_spinlock)(&mc->lock);
- mm_allowed = mm_cpus_allowed(mm);
weight = cpumask_weighted_or(mm_allowed, mm_allowed, affmsk);
if (weight == mc->nr_cpus_allowed)
- return;
+ return false;
WRITE_ONCE(mc->nr_cpus_allowed, weight);
+ return true;
+}
+
+static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk)
+{
+ struct mm_mm_cid *mc;
+
+ if (!mm || !READ_ONCE(mm->mm_cid.users))
+ return;
+
+ mc = &mm->mm_cid;
+ guard(raw_spinlock)(&mc->lock);
+
+ /* Apply the update and check whether deferred work if required */
+ if (!__mm_update_cpus_allowed(mm, affmsk))
+ return;
+
__mm_update_max_cids(mc);
if (!cid_on_cpu(mc->mode))
return;
@@ -11035,6 +11054,15 @@ static void mm_cid_fixup_tasks_to_cpus(void)
static bool sched_mm_cid_add_user(struct task_struct *t, struct mm_struct *mm)
{
lockdep_assert_held(&mm->mm_cid.lock);
+ /*
+ * Update allowed CPUs to take any affinity change, which happened
+ * before sched_mm_cid_fork() acquired the locks, into account.
+ * In per CPU mode, also recompute pcpu_thrs for the wider set, as
+ * mm_update_cpus_allowed() does.
+ */
+ if (__mm_update_cpus_allowed(mm, &t->cpus_mask) &&
+ cid_on_cpu(mm->mm_cid.mode))
+ mm->mm_cid.pcpu_thrs = mm_cid_calc_pcpu_thrs(&mm->mm_cid);
t->mm_cid.active = 1;
hlist_add_head(&t->mm_cid.node, &mm->mm_cid.user_list);
@@ -11226,11 +11254,11 @@ static void mm_cid_irq_work(struct irq_work *work)
schedule_work(&mm->mm_cid.work);
}
-void mm_init_cid(struct mm_struct *mm, struct task_struct *p)
+void mm_init_cid(struct mm_struct *mm)
{
mm->mm_cid.max_cids = 0;
mm->mm_cid.mode = 0;
- mm->mm_cid.nr_cpus_allowed = p->nr_cpus_allowed;
+ mm->mm_cid.nr_cpus_allowed = 0;
mm->mm_cid.users = 0;
mm->mm_cid.pcpu_thrs = 0;
mm->mm_cid.update_deferred = 0;
@@ -11239,7 +11267,7 @@ void mm_init_cid(struct mm_struct *mm, struct task_struct *p)
mm->mm_cid.irq_work = IRQ_WORK_INIT_HARD(mm_cid_irq_work);
INIT_WORK(&mm->mm_cid.work, mm_cid_work_fn);
INIT_HLIST_HEAD(&mm->mm_cid.user_list);
- cpumask_copy(mm_cpus_allowed(mm), &p->cpus_mask);
+ cpumask_clear(mm_cpus_allowed(mm));
bitmap_zero(mm_cidmask(mm), num_possible_cpus());
}
#else /* CONFIG_SCHED_MM_CID */
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 03/13] sched/mmcid: Serialize joins and exits with affinity changes by pi_lock
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 01/13] sched/mmcid: Move the execve() hooks into exec_mmap() Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 02/13] sched/mmcid: Add the allowed CPUs of each joining task to the mm Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 04/13] sched/mmcid: Give no concurrency ID to user workers Mathieu Desnoyers
` (9 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter, co+cab19e2ebe4d535a,
stable
An mm keeps the union of the allowed CPUs of its tasks, to bound its
CIDs. set_cpus_allowed_common() adds the new CPUs of a task to p->mm
with mm_update_cpus_allowed(). Commit 7e019dcc470f ("sched: Improve
cache locality of RSEQ concurrency IDs for intermittent workloads") put
this update under p->pi_lock and the runqueue lock. These locks do not
keep p->mm alive.
In this example, task T runs execve() on CPU 0. Its old mm has no other
user. Task A calls sched_setaffinity() on T from CPU 1. The kernel has
CONFIG_FUTEX=n.
CPU 0 (T) CPU 1 (A)
sched_setaffinity(T)
task_rq_lock(T)
set_cpus_allowed_common()
mm = T->mm (the old mm)
exec_mmap()
sched_mm_cid_before_execve()
T leaves the old mm
T->mm = the new mm
sched_mm_cid_after_execve()
T joins the new mm
futex_exec_done(): empty
setup_new_exec()
mmput(the old mm): the old mm is freed
mm_update_cpus_allowed(mm)
reads mm->mm_cid.users:
use after free
Weiming Shi reported this with KASAN. Any process which may change the
affinity of T can trigger it. Without KASAN, the update would write to
freed memory.
Since commit c5f0bc9fd1ce ("futex/pi: Plug private futex exec() race"),
this needs CONFIG_FUTEX=n. Otherwise futex_exec_done() takes
T->pi_lock, and CPU 0 waits there for CPU 1.
Two more windows of this kind exist. Neither was reproduced on a
kernel:
- A kthread can switch to another mm with kthread_unuse_mm() and
kthread_use_mm(). It then drops its lazy reference on the old mm in
mmdrop_lazy_tlb(). No rq lock is held there. So the old mm can be
freed under the same update, on any architecture. A review of the code
found this.
- The Spin model reaches the same window in exit_mm(), with
CONFIG_MMU_LAZY_TLB_SHOOTDOWN (powerpc). Elsewhere, the lazy TLB
reference of the task keeps the mm alive until a context switch.
A Spin model of the CID management reaches a second race after
"sched/mmcid: Add the allowed CPUs of each joining task to the mm". It
was not reproduced on a kernel. Here task T on CPU 0 is the first
task to join mm M. It joins in execve() or as a fork() child. Task A
widens the CPUs of T from CPU 1.
CPU 0 (T) CPU 1 (A)
sched_mm_cid_fork(T)
takes M->mm_cid.lock
sched_mm_cid_add_user()
__mm_update_cpus_allowed(M, &T->cpus_mask)
M gets the old CPUs of T
sched_setaffinity(T)
task_rq_lock(T)
set_cpus_allowed_common()
T->cpus_mask = the new CPUs
mm_update_cpus_allowed(M)
M->mm_cid.users == 0: return
M->mm_cid.users = 1
releases M->mm_cid.lock
M misses the new CPUs. Its IDs are then no longer compact, as described
in that patch.
Fix both by taking p->pi_lock around mm_cid.lock in sched_mm_cid_fork()
and sched_mm_cid_exit(). p->mm_cid.active then changes only under
pi_lock. mm_update_cpus_allowed() takes the task instead of the mm. It
does nothing when the task is not active. A task leaves the CID
management of its mm before it switches or drops the mm. It joins the
new mm after the switch. A kthread never joins. So while pi_lock is
held, the mm of an active task cannot change. This also closes the two
windows above: neither a kthread nor an exited task is active. A join
reads the allowed CPUs under pi_lock, so it sees every earlier affinity
change. A later change finds the task active and updates the mm.
An affinity change to a task which is not active yet no longer reaches
the mm. Examples are sched_setaffinity() on a new task, and clone3()
with CLONE_INTO_CGROUP into another cpuset. The join widens the mm
instead, and recomputes pcpu_thrs in per CPU mode.
The same model reaches the use after free without this change, and not
with it. No test of this series reproduces the use after free.
Fixes: 7e019dcc470f ("sched: Improve cache locality of RSEQ concurrency IDs for intermittent workloads")
Reported-by: Weiming Shi <bestswngs@gmail.com>
Reported-by: <co+cab19e2ebe4d535a@bugs.sh>
Closes: https://lore.kernel.org/all/20261110183809.3308868-1-bestswngs@gmail.com/
Suggested-by: Thomas Gleixner <tglx@kernel.org>
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
kernel/sched/core.c | 50 +++++++++++++++++++++++++++++++++------------
1 file changed, 37 insertions(+), 13 deletions(-)
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 80239800c566..575813b1ae97 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -2839,7 +2839,7 @@ int push_cpu_stop(void *arg)
return 0;
}
-static inline void mm_update_cpus_allowed(struct mm_struct *mm, const cpumask_t *affmask);
+static inline void mm_update_cpus_allowed(struct task_struct *p, const struct cpumask *affmsk);
/*
* sched_class::set_cpus_allowed must do the below, but is not required to
@@ -2854,7 +2854,7 @@ void set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx
cpumask_copy(&p->cpus_mask, ctx->new_mask);
p->nr_cpus_allowed = cpumask_weight(ctx->new_mask);
- mm_update_cpus_allowed(p->mm, ctx->new_mask);
+ mm_update_cpus_allowed(p, ctx->new_mask);
/*
* Swap in a new user_cpus_ptr if SCA_USER flag set
@@ -10712,6 +10712,11 @@ void call_trace_sched_update_nr_running(struct rq *rq, int count)
* mm_update_cpus_allowed(). Nests in mm_cid::mutex
* and runqueue lock.
*
+ * task::pi_lock: Serializes the updates of task::mm_cid::active
+ * with mm_update_cpus_allowed(). task::mm_cid::active
+ * is written with task::pi_lock and mm::mm_cid::lock
+ * held. task::pi_lock is taken first.
+ *
* The mm_cidmask bitmap is not protected by any of the mm::mm_cid locks
* and can only be modified with atomic operations.
*
@@ -10891,8 +10896,9 @@ static bool mm_update_max_cids(struct mm_struct *mm)
/*
* Add @affmsk to the allowed CPUs of @mm. Return true if the set grew.
- * Called from mm_update_cpus_allowed() on an affinity change, and from
- * sched_mm_cid_add_user() when a task joins the MM CID management.
+ * Called from mm_update_cpus_allowed() on an affinity change of an active
+ * task, and from sched_mm_cid_add_user() when a task joins the MM CID
+ * management.
*/
static inline bool __mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk)
{
@@ -10914,18 +10920,28 @@ static inline bool __mm_update_cpus_allowed(struct mm_struct *mm, const struct c
return true;
}
-static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk)
+static inline void mm_update_cpus_allowed(struct task_struct *p, const struct cpumask *affmsk)
{
- struct mm_mm_cid *mc;
+ lockdep_assert_held(&p->pi_lock);
- if (!mm || !READ_ONCE(mm->mm_cid.users))
+ /*
+ * p::mm_cid::active is updated with pi_lock and mm_cid::lock held. So
+ * pi_lock is sufficient to check the active bit. If the active bit is
+ * not set then the task is either not involved or exiting.
+ *
+ * An active task leaves the MM CID management before it drops or
+ * replaces p->mm. So while pi_lock is held, p->mm of an active task
+ * stays valid.
+ */
+ if (!p->mm_cid.active)
return;
- mc = &mm->mm_cid;
+ struct mm_mm_cid *mc = &p->mm->mm_cid;
+
guard(raw_spinlock)(&mc->lock);
/* Apply the update and check whether deferred work if required */
- if (!__mm_update_cpus_allowed(mm, affmsk))
+ if (!__mm_update_cpus_allowed(p->mm, affmsk))
return;
__mm_update_max_cids(mc);
@@ -11081,9 +11097,12 @@ static void sched_mm_cid_fork(struct task_struct *t)
WARN_ON_ONCE(t->mm_cid.cid != MM_CID_UNSET);
guard(mutex)(&mm->mm_cid.mutex);
- scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) {
+ /* Protect against concurrent affinity changes */
+ scoped_guard(raw_spinlock_irq, &t->pi_lock) {
struct mm_cid_pcpu *pcp = this_cpu_ptr(mm->mm_cid.pcpu);
+ guard(raw_spinlock)(&mm->mm_cid.lock);
+
/* First user ? */
if (!mm->mm_cid.users) {
sched_mm_cid_add_user(t, mm);
@@ -11117,6 +11136,7 @@ static void sched_mm_cid_fork(struct task_struct *t)
static bool sched_mm_cid_remove_user(struct task_struct *t)
{
+ lockdep_assert_held(&t->pi_lock);
lockdep_assert_held(&t->mm->mm_cid.lock);
t->mm_cid.active = 0;
@@ -11170,7 +11190,9 @@ void sched_mm_cid_exit(struct task_struct *t)
scoped_guard(mutex, &mm->mm_cid.mutex) {
/* mm_cid::mutex is sufficient to protect mm_cid::users */
if (likely(mm->mm_cid.users > 1)) {
- scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) {
+ /* Protect against concurrent affinity changes */
+ scoped_guard(raw_spinlock_irq, &t->pi_lock) {
+ guard(raw_spinlock)(&mm->mm_cid.lock);
if (!__sched_mm_cid_exit(t))
return;
/*
@@ -11184,8 +11206,10 @@ void sched_mm_cid_exit(struct task_struct *t)
mm_cid_fixup_cpus_to_tasks(mm);
return;
}
+
/* Last user */
- scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) {
+ scoped_guard(raw_spinlock_irq, &t->pi_lock) {
+ guard(raw_spinlock)(&mm->mm_cid.lock);
/*
* Ignore mode change. There is nothing to do as the MM
* is going away in the common case.
@@ -11271,7 +11295,7 @@ void mm_init_cid(struct mm_struct *mm)
bitmap_zero(mm_cidmask(mm), num_possible_cpus());
}
#else /* CONFIG_SCHED_MM_CID */
-static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) { }
+static inline void mm_update_cpus_allowed(struct task_struct *p, const struct cpumask *affmsk) { }
static inline void sched_mm_cid_fork(struct task_struct *t) { }
#endif /* !CONFIG_SCHED_MM_CID */
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 04/13] sched/mmcid: Give no concurrency ID to user workers
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (2 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 03/13] sched/mmcid: Serialize joins and exits with affinity changes by pi_lock Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 05/13] selftests/rseq: Test the concurrency ID after a failed execve Mathieu Desnoyers
` (8 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
The workers of io_uring and vhost are PF_USER_WORKER tasks. They are
threads of the process they work for, created with CLONE_VM. They run
a kernel function until they exit. They never return to user space and
have no rseq area, so nothing reads their CID.
But sched_mm_cid_fork() makes them users of the CIDs, like every task
with an mm. The kernel aims to keep the CIDs below the smaller of two
counts: the users, and the CPUs they may run on. User space can then
keep compact per-CPU data indexed by CID. A worker adds to both counts.
In per task mode, it also keeps a CID which the threads of the process
cannot use.
An io_uring SQPOLL thread without a fixed CPU sets its affinity to all
online CPUs when it starts. set_cpus_allowed_ptr() does not limit this
to the cpuset of the process. The allowed CPUs of the mm only grow, so
they stay wide after the worker exits. The CIDs then spread over more
values than the process has CPUs. They stay below the number of
possible CPUs, so nothing breaks.
In testing, a process in a cpuset of two CPUs created an io_uring with
an SQPOLL thread. Its three threads then read mm_cid values up to 3.
The Sashiko AI review found this case.
Skip user workers in sched_mm_cid_fork(). Their mm_cid.active then
stays 0, so mm_update_cpus_allowed() ignores their affinity changes.
Kernel threads are already skipped, as they have no mm. With this
change, the three threads read mm_cid values of at most 1.
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
kernel/sched/core.c | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 575813b1ae97..cee702c981e5 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -11091,7 +11091,11 @@ static void sched_mm_cid_fork(struct task_struct *t)
struct mm_struct *mm = t->mm;
bool percpu;
- if (!mm)
+ /*
+ * A user worker (io_uring, vhost) never returns to user space and
+ * has no rseq area. It needs no CID.
+ */
+ if (!mm || (t->flags & PF_USER_WORKER))
return;
WARN_ON_ONCE(t->mm_cid.cid != MM_CID_UNSET);
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 05/13] selftests/rseq: Test the concurrency ID after a failed execve
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (3 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 04/13] sched/mmcid: Give no concurrency ID to user workers Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 06/13] selftests/rseq: Test the concurrency IDs across ownership mode switches Mathieu Desnoyers
` (7 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
A failed execve() returns to user space in the same mm. The mm_cid that
the task reads there must be a valid ID. No test checks this.
In per CPU mode, the CPUs own the CIDs of the mm, not the tasks. A task
that joins the CID management of the mm then gets no CID. It takes the
CID of its CPU when it is scheduled in. On tip sched/urgent, a failed
execve() makes the task leave the CID management of its mm and join it
again. The task then returns to user space before it is scheduled in
again, and reads an mm_cid of 0x80000000.
Add mm_cid_execve_test. Its main thread calls execve() on a file that no
binfmt handler recognises, while four other threads run. The call fails
with ENOEXEC before de_thread() kills the other threads. The main thread
reads its mm_cid after each call. The value must stay below the number
of possible CPUs, the only bound. The kernel also aims at a value below
the number of allowed CPUs. That is a target: the test prints a note
when it misses it, and does not fail.
Per CPU mode needs more threads than the mm has CIDs. The allowed CPUs
of an mm only grow. So the test narrows its affinity to two CPUs before
it forks the process under test. Five threads are then enough on any
machine.
On tip sched/urgent, the test fails on guests with 2 to 64 CPUs:
mm_cid 2147483648 (0x80000000) after a failed execve, round 0 of 100
not ok 1 mm_cid after a failed execve
It passes after "sched/mmcid: Move the execve() hooks into exec_mmap()".
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
tools/testing/selftests/rseq/.gitignore | 1 +
tools/testing/selftests/rseq/Makefile | 3 +-
.../selftests/rseq/mm_cid_execve_test.c | 319 ++++++++++++++++++
3 files changed, 322 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/rseq/mm_cid_execve_test.c
diff --git a/tools/testing/selftests/rseq/.gitignore b/tools/testing/selftests/rseq/.gitignore
index 9b6eb6c3922f..1d94aaf15f4e 100644
--- a/tools/testing/selftests/rseq/.gitignore
+++ b/tools/testing/selftests/rseq/.gitignore
@@ -9,6 +9,7 @@ param_test_compare_twice
param_test_mm_cid
param_test_mm_cid_benchmark
param_test_mm_cid_compare_twice
+mm_cid_execve_test
syscall_errors_test
slice_test
legacy_check
diff --git a/tools/testing/selftests/rseq/Makefile b/tools/testing/selftests/rseq/Makefile
index aba6317f6cb8..ee40f80c079c 100644
--- a/tools/testing/selftests/rseq/Makefile
+++ b/tools/testing/selftests/rseq/Makefile
@@ -19,7 +19,8 @@ LDLIBS += -lpthread -ldl
OVERRIDE_TARGETS = 1
TEST_GEN_PROGS = basic_test basic_percpu_ops_test basic_percpu_ops_mm_cid_test \
- param_test_benchmark param_test_mm_cid_benchmark
+ param_test_benchmark param_test_mm_cid_benchmark \
+ mm_cid_execve_test
TEST_GEN_PROGS_EXTENDED = librseq.so \
param_test \
diff --git a/tools/testing/selftests/rseq/mm_cid_execve_test.c b/tools/testing/selftests/rseq/mm_cid_execve_test.c
new file mode 100644
index 000000000000..1a27494297bc
--- /dev/null
+++ b/tools/testing/selftests/rseq/mm_cid_execve_test.c
@@ -0,0 +1,319 @@
+// SPDX-License-Identifier: LGPL-2.1
+/*
+ * Check the concurrency ID that a thread reads after a failed execve(2).
+ *
+ * A failed execve(2) returns to user space in the same mm. The other
+ * threads still use CIDs of that mm. The mm_cid that the task reads must
+ * be a valid ID: below the number of possible CPUs. The kernel also aims
+ * at an ID below the number of allowed CPUs. That is a target: the test
+ * prints a note when it is missed.
+ *
+ * Before "sched/mmcid: Move the execve() hooks into exec_mmap()", the task
+ * left the CID management of the mm in execve(2) and joined it again on
+ * failure. In per CPU mode, it then returned to user space with no CID, and
+ * read 0x80000000.
+ *
+ * Per CPU mode needs more threads than the mm has CIDs. The number of CIDs
+ * follows the union of the allowed CPUs of the threads, which only grows.
+ * The affinity is therefore narrowed before the fork(2) that creates the
+ * process under test. A few threads are then enough on any machine.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <limits.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "rseq.h"
+#include "kselftest.h"
+
+#define NARROW_CPUS 2
+#define THREADS 4
+#define ROUNDS 100
+
+/* Exit status of the process under test. */
+#define CHILD_PASS 0
+#define CHILD_FAIL 1
+#define CHILD_SKIP 2
+#define CHILD_ERROR 3
+
+static int stop;
+static int nr_possible;
+
+/*
+ * Stay alive as a user of the CIDs of the mm until stop is set. A thread
+ * needs no rseq area for that.
+ */
+static void *waiter(void *arg)
+{
+ while (!RSEQ_READ_ONCE(stop))
+ (void)sched_yield();
+ return NULL;
+}
+
+/* Join @t. Return 0, or the error number after reporting it. */
+static int join_thread(pthread_t t)
+{
+ int err = pthread_join(t, NULL);
+
+ if (err)
+ fprintf(stderr, "pthread_join: %s\n", strerror(err));
+ return err;
+}
+
+/* Remove @path. Return 0, or -1 after reporting the error. */
+static int remove_file(const char *path)
+{
+ if (unlink(path)) {
+ fprintf(stderr, "unlink %s: %s\n", path, strerror(errno));
+ return -1;
+ }
+ return 0;
+}
+
+/*
+ * Return the directory of the test's executable, stored in @buf. Return "."
+ * if it cannot be read.
+ */
+static const char *test_dir(char *buf, size_t len)
+{
+ ssize_t n = readlink("/proc/self/exe", buf, len - 1);
+ char *slash;
+
+ if (n <= 0)
+ return ".";
+ buf[n] = '\0';
+ slash = strrchr(buf, '/');
+ if (!slash)
+ return ".";
+ *slash = '\0';
+ return slash == buf ? "/" : buf;
+}
+
+/*
+ * Create a file that no binfmt handler recognises, and leave its path in
+ * @path. execve(2) on it fails with ENOEXEC in bprm_execve(), before
+ * begin_new_exec() kills the other threads. A path that does not exist
+ * would fail before bprm_execve(). Before "sched/mmcid: Move the execve()
+ * hooks into exec_mmap()", bprm_execve() called the CID hooks.
+ *
+ * The directory must allow execution, so try the directory of the test
+ * first, then /tmp. Run execve(2) once to check for ENOEXEC. Return 0 on
+ * success, or -1.
+ */
+static int make_unknown_format_file(char *path, size_t len)
+{
+ char self[PATH_MAX];
+ const char *const dirs[] = { test_dir(self, sizeof(self)), "/tmp" };
+ static const char junk[] = "not a binary of any known format\n";
+ unsigned int i;
+
+ for (i = 0; i < ARRAY_SIZE(dirs); i++) {
+ char *const av[] = { path, NULL };
+ bool written;
+ int fd;
+
+ snprintf(path, len, "%s/mm_cid_execve_test.XXXXXX", dirs[i]);
+ fd = mkstemp(path);
+ if (fd < 0)
+ continue;
+ written = write(fd, junk, sizeof(junk) - 1) == (ssize_t)sizeof(junk) - 1 &&
+ !fchmod(fd, 0755);
+ /* An open file would make execve(2) fail with ETXTBSY. */
+ if (close(fd) || !written) {
+ remove_file(path);
+ continue;
+ }
+ if (execve(path, av, NULL) == -1 && errno == ENOEXEC)
+ return 0;
+ remove_file(path);
+ }
+ return -1;
+}
+
+/*
+ * The process under test. Start THREADS threads on a narrow set of CPUs.
+ * Then fail execve(2) in a loop and read the mm_cid after each call.
+ * Return a CHILD_* status.
+ */
+static int run_child(void)
+{
+ pthread_t thread[THREADS];
+ char path[PATH_MAX];
+ unsigned int nr_allowed, worst = 0;
+ cpu_set_t mask;
+ int i, err = 0, started = 0, ret = CHILD_PASS;
+
+ /* The kernel aims at IDs below the allowed CPUs: a target. */
+ if (sched_getaffinity(0, sizeof(mask), &mask)) {
+ fprintf(stderr, "sched_getaffinity: %s\n", strerror(errno));
+ return CHILD_ERROR;
+ }
+ nr_allowed = CPU_COUNT(&mask);
+
+ if (make_unknown_format_file(path, sizeof(path))) {
+ fprintf(stderr, "no directory to run an unknown format file from: %s\n",
+ strerror(errno));
+ return CHILD_SKIP;
+ }
+
+ for (i = 0; i < THREADS; i++) {
+ err = pthread_create(&thread[i], NULL, waiter, NULL);
+ if (err)
+ break;
+ started++;
+ }
+ if (started < THREADS) {
+ fprintf(stderr, "pthread_create: %s\n", strerror(err));
+ ret = CHILD_ERROR;
+ goto out;
+ }
+
+ for (i = 0; i < ROUNDS; i++) {
+ char *const av[] = { path, NULL };
+ unsigned int cid;
+
+ if (!execve(path, av, NULL)) {
+ fprintf(stderr, "execve(%s) succeeded, expected ENOEXEC\n", path);
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ if (errno != ENOEXEC) {
+ fprintf(stderr, "execve(%s): %s, expected ENOEXEC\n",
+ path, strerror(errno));
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ cid = rseq_current_mm_cid();
+ if (cid > worst)
+ worst = cid;
+ /* The number of possible CPUs is the only bound. */
+ if (cid >= (unsigned int)nr_possible) {
+ fprintf(stderr, "mm_cid %u (0x%x) after a failed execve, round %d of %d\n",
+ cid, cid, i, ROUNDS);
+ ret = CHILD_FAIL;
+ goto out;
+ }
+ }
+ fprintf(stderr, "%d threads, %d failed execve, largest mm_cid %u, %d possible CPUs%s\n",
+ started + 1, ROUNDS, worst, nr_possible,
+ worst >= nr_allowed ? ", reaches the number of allowed CPUs" : "");
+out:
+ RSEQ_WRITE_ONCE(stop, 1);
+ for (i = 0; i < started; i++) {
+ if (join_thread(thread[i]) && ret == CHILD_PASS)
+ ret = CHILD_ERROR;
+ }
+ if (remove_file(path) && ret == CHILD_PASS)
+ ret = CHILD_ERROR;
+ return ret;
+}
+
+static int read_nr_possible(void)
+{
+ int first, last, total = 0;
+ char sep;
+ FILE *f;
+
+ f = fopen("/sys/devices/system/cpu/possible", "r");
+ if (!f)
+ return -1;
+ /* A list of ranges: "0-63" or "0,2-5". */
+ while (fscanf(f, "%d", &first) == 1) {
+ last = first;
+ sep = '\n';
+ if (fscanf(f, "%c", &sep) == 1 && sep == '-') {
+ if (fscanf(f, "%d", &last) != 1)
+ break;
+ if (fscanf(f, "%c", &sep) != 1)
+ sep = '\n';
+ }
+ total += last - first + 1;
+ if (sep != ',')
+ break;
+ }
+ fclose(f);
+ return total;
+}
+
+/* Keep the first @nr CPUs of @src in @dst. */
+static int narrow_cpus(cpu_set_t *dst, const cpu_set_t *src, int nr)
+{
+ int cpu, taken = 0;
+
+ CPU_ZERO(dst);
+ for (cpu = 0; cpu < CPU_SETSIZE && taken < nr; cpu++) {
+ if (!CPU_ISSET(cpu, src))
+ continue;
+ CPU_SET(cpu, dst);
+ taken++;
+ }
+ return taken;
+}
+
+int main(void)
+{
+ cpu_set_t allowed, narrow;
+ int status = 0;
+ pid_t child;
+
+ ksft_print_header();
+ ksft_set_plan(1);
+
+ if (!rseq_available())
+ ksft_exit_skip("rseq is unavailable\n");
+ /* glibc before 2.35 registers no rseq area. */
+ if (rseq_register_current_thread())
+ ksft_exit_fail_msg("rseq_register_current_thread: %s\n", strerror(errno));
+ if (!rseq_mm_cid_available())
+ ksft_exit_skip("the rseq mm_cid field is unavailable\n");
+ if (sched_getaffinity(0, sizeof(allowed), &allowed))
+ ksft_exit_fail_msg("sched_getaffinity: %s\n", strerror(errno));
+ nr_possible = read_nr_possible();
+ if (nr_possible <= 0)
+ ksft_exit_skip("cannot read the possible CPUs\n");
+ if (!narrow_cpus(&narrow, &allowed, NARROW_CPUS))
+ ksft_exit_skip("no CPU to run on\n");
+
+ /*
+ * Narrow before the fork(2). The mm of the child starts with these
+ * allowed CPUs, and a later narrowing does not shrink them.
+ */
+ if (sched_setaffinity(0, sizeof(narrow), &narrow))
+ ksft_exit_skip("sched_setaffinity: %s\n", strerror(errno));
+ child = fork();
+ if (!child)
+ _exit(run_child());
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ if (sched_setaffinity(0, sizeof(allowed), &allowed))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ if (!WIFEXITED(status))
+ ksft_exit_fail_msg("the process under test was killed by signal %d\n",
+ WTERMSIG(status));
+
+ switch (WEXITSTATUS(status)) {
+ case CHILD_PASS:
+ ksft_test_result_pass("mm_cid after a failed execve\n");
+ break;
+ case CHILD_SKIP:
+ ksft_test_result_skip("mm_cid after a failed execve\n");
+ break;
+ case CHILD_FAIL:
+ ksft_test_result_fail("mm_cid after a failed execve\n");
+ break;
+ default:
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ }
+ ksft_finished();
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 06/13] selftests/rseq: Test the concurrency IDs across ownership mode switches
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (4 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 05/13] selftests/rseq: Test the concurrency ID after a failed execve Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 07/13] selftests/rseq: Test the upper bound of the concurrency IDs Mathieu Desnoyers
` (6 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
Either the tasks or the CPUs own the concurrency IDs (CIDs) of an mm.
This is its ownership mode. The kernel switches to per CPU mode when
the mm has more users than CIDs. It switches back to per task mode when
the user count drops below a lower threshold. An affinity change that
widens the allowed CPUs of the mm raises that threshold.
No test switches the mode back and forth while threads use their CIDs.
Add mm_cid_transition_test. Its worker threads count in an array
indexed by their mm_cid, with no lock. Two workers that run with the
same mm_cid at the same time can lose counts. One worker also fails
execve() in a loop, and another calls vfork() in a loop. The test has
three cases:
- Case 1 creates and ends 1 to 16 workers per round, on at most four
CPUs. 16 workers exceed the CIDs on any machine.
- Case 2 does the same on all CPUs.
- Case 3 starts three workers on two CPUs, with no execve() worker. The
main thread then widens its own affinity to all CPUs. This can switch
the mm back to per task mode while the workers count.
A case fails when counts are lost, or when an mm_cid is not below the
number of possible CPUs.
On tip sched/urgent, a thread reads an mm_cid of 0x80000000. Case 1
fails on guests with 2 to 64 CPUs:
thread count changes: mm_cid 2147483648 (0x80000000), 8 possible CPUs
not ok 1 thread count changes on at most 4 CPUs
Case 2 fails on the same guests, except those with 18 CPUs or more
(here 48 and 64).
There, the mm has at least as many CIDs as users, and stays in per task
mode.
Both pass after "sched/mmcid: Move the execve() hooks into
exec_mmap()". Case 3 passes on tip sched/urgent, and with each of
patches 1 to 4 added in turn.
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
tools/testing/selftests/rseq/.gitignore | 1 +
tools/testing/selftests/rseq/Makefile | 2 +-
.../selftests/rseq/mm_cid_transition_test.c | 388 ++++++++++++++++++
3 files changed, 390 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/rseq/mm_cid_transition_test.c
diff --git a/tools/testing/selftests/rseq/.gitignore b/tools/testing/selftests/rseq/.gitignore
index 1d94aaf15f4e..e8afb37121d7 100644
--- a/tools/testing/selftests/rseq/.gitignore
+++ b/tools/testing/selftests/rseq/.gitignore
@@ -10,6 +10,7 @@ param_test_mm_cid
param_test_mm_cid_benchmark
param_test_mm_cid_compare_twice
mm_cid_execve_test
+mm_cid_transition_test
syscall_errors_test
slice_test
legacy_check
diff --git a/tools/testing/selftests/rseq/Makefile b/tools/testing/selftests/rseq/Makefile
index ee40f80c079c..ac32d6af3b99 100644
--- a/tools/testing/selftests/rseq/Makefile
+++ b/tools/testing/selftests/rseq/Makefile
@@ -20,7 +20,7 @@ OVERRIDE_TARGETS = 1
TEST_GEN_PROGS = basic_test basic_percpu_ops_test basic_percpu_ops_mm_cid_test \
param_test_benchmark param_test_mm_cid_benchmark \
- mm_cid_execve_test
+ mm_cid_execve_test mm_cid_transition_test
TEST_GEN_PROGS_EXTENDED = librseq.so \
param_test \
diff --git a/tools/testing/selftests/rseq/mm_cid_transition_test.c b/tools/testing/selftests/rseq/mm_cid_transition_test.c
new file mode 100644
index 000000000000..eef1a0922ca4
--- /dev/null
+++ b/tools/testing/selftests/rseq/mm_cid_transition_test.c
@@ -0,0 +1,388 @@
+// SPDX-License-Identifier: LGPL-2.1
+/*
+ * Check the concurrency IDs while the kernel switches their ownership
+ * mode.
+ *
+ * The tasks own the IDs of an mm while there are few threads. The CPUs
+ * own them once there are more threads than IDs. The kernel switches mode
+ * when the thread count crosses a threshold. An affinity change that
+ * widens the allowed CPUs can also switch it back to per task mode.
+ *
+ * The main thread starts worker threads. It stops them after a while and
+ * waits for them to exit. Each worker does this:
+ * - It counts in an array indexed by its mm_cid, in an rseq critical
+ * section with no lock. Two workers that run with the same mm_cid at
+ * the same time can lose counts.
+ * - Except in case 3, worker 0 also fails execve(2) in a loop. Before
+ * "sched/mmcid: Move the execve() hooks into exec_mmap()", each failure
+ * left the CID management of the mm and joined it again.
+ * - Worker 1 also calls vfork(2) in a loop. The child is a user of the
+ * CIDs of the mm until it exits.
+ *
+ * Cases 1 and 2 run rounds of 1 to 16 workers, on at most four CPUs and on
+ * all CPUs. Case 3 starts three workers on two CPUs. The main thread then
+ * widens its own affinity while the workers count.
+ *
+ * The test fails when counts are lost, or when an mm_cid is not below the
+ * number of possible CPUs. A kernel that loops in mm_get_cid() shows as a
+ * timeout.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <limits.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "rseq.h"
+#include "kselftest.h"
+
+#define MAX_CIDS CPU_SETSIZE
+#define MAX_WORKERS 16
+#define ROUNDS 200
+#define WIDEN_RUNS 100
+#define ROUND_US 500
+#define MAX_TRIES 1000000
+
+#define CHILD_PASS 0
+#define CHILD_FAIL 1
+#define CHILD_ERROR 2
+
+struct worker {
+ pthread_t thread;
+ intptr_t counted;
+ unsigned int bad_cid;
+ bool execs;
+ bool vforks;
+};
+
+static intptr_t counts[MAX_CIDS];
+static struct worker workers[MAX_WORKERS];
+static int stop;
+static int nr_possible;
+static cpu_set_t all_cpus;
+static char exec_path[PATH_MAX];
+
+/*
+ * Add one to the count of the current mm_cid. Record an mm_cid not below
+ * the possible CPUs in @w instead.
+ */
+static void count_one(struct worker *w)
+{
+ for (;;) {
+ unsigned int cid = rseq_current_mm_cid();
+
+ if (cid >= (unsigned int)nr_possible || cid >= MAX_CIDS) {
+ w->bad_cid = cid;
+ return;
+ }
+ if (!rseq_addv(RSEQ_MO_RELAXED, RSEQ_PERCPU_MM_CID, &counts[cid], 1, cid)) {
+ w->counted++;
+ return;
+ }
+ }
+}
+
+static int join_failed;
+
+/* Join @t. Report an error and set join_failed if that fails. */
+static void join_thread(pthread_t t)
+{
+ int err = pthread_join(t, NULL);
+
+ if (err) {
+ fprintf(stderr, "pthread_join: %s\n", strerror(err));
+ RSEQ_WRITE_ONCE(join_failed, 1);
+ }
+}
+
+/* Remove @path. Return 0, or -1 after reporting the error. */
+static int remove_file(const char *path)
+{
+ if (unlink(path)) {
+ fprintf(stderr, "unlink %s: %s\n", path, strerror(errno));
+ return -1;
+ }
+ return 0;
+}
+
+static void *worker_fn(void *arg)
+{
+ struct worker *w = arg;
+ char *const av[] = { exec_path, NULL };
+ int i;
+
+ if (rseq_register_current_thread())
+ abort();
+ while (!RSEQ_READ_ONCE(stop) && w->bad_cid == UINT_MAX) {
+ for (i = 0; i < 100; i++)
+ count_one(w);
+ if (w->execs && execve(exec_path, av, NULL) == -1 && errno != ENOEXEC) {
+ fprintf(stderr, "execve: %s, expected ENOEXEC\n", strerror(errno));
+ abort();
+ }
+ if (w->vforks) {
+ pid_t pid = vfork();
+
+ if (!pid)
+ _exit(0);
+ if (pid < 0 || waitpid(pid, NULL, 0) != pid) {
+ fprintf(stderr, "vfork: %s\n", strerror(errno));
+ abort();
+ }
+ }
+ }
+ rseq_unregister_current_thread();
+ return NULL;
+}
+
+/*
+ * Run @nr workers for a while. Unless @widen_us is negative, widen the
+ * affinity of this thread to all CPUs @widen_us after the start. Return 0,
+ * or -1 on an error.
+ */
+static int run_round(int nr, int widen_us)
+{
+ int i, started = 0, widened = 1;
+
+ RSEQ_WRITE_ONCE(stop, 0);
+ for (i = 0; i < nr; i++) {
+ int err, tries = 0;
+
+ workers[i].execs = i == 0 && exec_path[0];
+ workers[i].vforks = i == 1;
+ /* clone(CLONE_FS) fails with EAGAIN while a thread is in execve. */
+ do {
+ err = pthread_create(&workers[i].thread, NULL, worker_fn, &workers[i]);
+ if (err == EAGAIN)
+ sched_yield();
+ } while (err == EAGAIN && ++tries < MAX_TRIES);
+ if (err)
+ break;
+ started++;
+ }
+ if (widen_us >= 0) {
+ usleep(widen_us);
+ /* The union of allowed CPUs of the mm grows. */
+ if (sched_setaffinity(0, sizeof(all_cpus), &all_cpus)) {
+ fprintf(stderr, "sched_setaffinity: %s\n", strerror(errno));
+ widened = 0;
+ }
+ }
+ usleep(ROUND_US);
+ RSEQ_WRITE_ONCE(stop, 1);
+ for (i = 0; i < started; i++)
+ join_thread(workers[i].thread);
+ return started == nr && widened && !RSEQ_READ_ONCE(join_failed) ? 0 : -1;
+}
+
+/*
+ * Compare the sum of the array with the counts of the workers, and report
+ * any mm_cid not below the possible CPUs. Return a CHILD_* status.
+ */
+static int check_counts(const char *what)
+{
+ intptr_t counted = 0, total = 0;
+ int i, ret = CHILD_PASS;
+
+ for (i = 0; i < MAX_WORKERS; i++) {
+ counted += workers[i].counted;
+ if (workers[i].bad_cid != UINT_MAX) {
+ fprintf(stderr, "%s: mm_cid %u (0x%x), %d possible CPUs\n",
+ what, workers[i].bad_cid, workers[i].bad_cid, nr_possible);
+ ret = CHILD_FAIL;
+ }
+ }
+ for (i = 0; i < MAX_CIDS; i++)
+ total += counts[i];
+ if (total != counted) {
+ fprintf(stderr, "%s: %ld counts lost out of %ld: two threads ran with one mm_cid\n",
+ what, (long)(counted - total), (long)counted);
+ ret = CHILD_FAIL;
+ }
+ return ret;
+}
+
+static void init_workers(void)
+{
+ int i;
+
+ for (i = 0; i < MAX_WORKERS; i++)
+ workers[i].bad_cid = UINT_MAX;
+}
+
+/*
+ * Create a file in @dir that no binfmt handler recognises, and leave its
+ * path in exec_path. execve(2) on it fails with ENOEXEC in bprm_execve(),
+ * before the other threads are killed. Return 0, or -1.
+ */
+static int make_unknown_format_file(const char *dir)
+{
+ static const char junk[] = "not a binary of any known format\n";
+ char *const av[] = { exec_path, NULL };
+ bool written;
+ int fd;
+
+ snprintf(exec_path, sizeof(exec_path), "%s/mm_cid_transition_test.XXXXXX", dir);
+ fd = mkstemp(exec_path);
+ if (fd < 0)
+ goto fail;
+ written = write(fd, junk, sizeof(junk) - 1) == (ssize_t)sizeof(junk) - 1 &&
+ !fchmod(fd, 0755);
+ if (close(fd) || !written)
+ goto unlink;
+ if (execve(exec_path, av, NULL) == -1 && errno == ENOEXEC)
+ return 0;
+unlink:
+ remove_file(exec_path);
+fail:
+ exec_path[0] = '\0';
+ return -1;
+}
+
+/* Rounds of 1 to MAX_WORKERS threads: the count crosses both thresholds. */
+static int run_child_rounds(int unused)
+{
+ int round, ret;
+
+ init_workers();
+ /* Without the file the rounds run with no execve. */
+ if (make_unknown_format_file("/tmp") && make_unknown_format_file("."))
+ fprintf(stderr, "no unknown format file: the rounds run without execve\n");
+ for (round = 0; round < ROUNDS; round++) {
+ if (run_round(1 + (round * 7) % MAX_WORKERS, -1)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ }
+ ret = check_counts("thread count changes");
+out:
+ if (exec_path[0] && remove_file(exec_path) && ret == CHILD_PASS)
+ ret = CHILD_ERROR;
+ return ret;
+}
+
+/* Run one round that widens the allowed CPUs @delay_us after its start. */
+static int run_child_widen(int delay_us)
+{
+ init_workers();
+ if (run_round(3, delay_us))
+ return CHILD_ERROR;
+ return check_counts("affinity change");
+}
+
+static int read_nr_possible(void)
+{
+ int first, last, total = 0;
+ char sep;
+ FILE *f;
+
+ f = fopen("/sys/devices/system/cpu/possible", "r");
+ if (!f)
+ return -1;
+ /* A list of ranges: "0-63" or "0,2-5". */
+ while (fscanf(f, "%d", &first) == 1) {
+ last = first;
+ sep = '\n';
+ if (fscanf(f, "%c", &sep) == 1 && sep == '-') {
+ if (fscanf(f, "%d", &last) != 1)
+ break;
+ if (fscanf(f, "%c", &sep) != 1)
+ sep = '\n';
+ }
+ total += last - first + 1;
+ if (sep != ',')
+ break;
+ }
+ fclose(f);
+ return total;
+}
+
+/* Keep the first @nr CPUs of @src in @dst. */
+static int narrow_cpus(cpu_set_t *dst, const cpu_set_t *src, int nr)
+{
+ int cpu, taken = 0;
+
+ CPU_ZERO(dst);
+ for (cpu = 0; cpu < CPU_SETSIZE && taken < nr; cpu++) {
+ if (!CPU_ISSET(cpu, src))
+ continue;
+ CPU_SET(cpu, dst);
+ taken++;
+ }
+ return taken;
+}
+
+/*
+ * Run @fn(@arg) in a new process and return its exit status. The affinity
+ * is @narrow when its mm is created. The union of allowed CPUs of an mm
+ * starts there and only grows.
+ */
+static int run_under_test(int (*fn)(int), int arg, const cpu_set_t *narrow)
+{
+ int status = 0;
+ pid_t child;
+
+ if (sched_setaffinity(0, sizeof(*narrow), narrow))
+ ksft_exit_skip("sched_setaffinity: %s\n", strerror(errno));
+ child = fork();
+ if (!child)
+ _exit(fn(arg));
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ if (sched_setaffinity(0, sizeof(all_cpus), &all_cpus))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ if (!WIFEXITED(status))
+ ksft_exit_fail_msg("the process under test was killed by signal %d\n",
+ WTERMSIG(status));
+ if (WEXITSTATUS(status) > CHILD_FAIL)
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ return WEXITSTATUS(status);
+}
+
+int main(void)
+{
+ cpu_set_t narrow;
+ int status, i;
+
+ ksft_print_header();
+ ksft_set_plan(3);
+
+ if (!rseq_available())
+ ksft_exit_skip("rseq is unavailable\n");
+ if (rseq_register_current_thread())
+ ksft_exit_fail_msg("rseq_register_current_thread: %s\n", strerror(errno));
+ if (!rseq_mm_cid_available())
+ ksft_exit_skip("the rseq mm_cid field is unavailable\n");
+ if (sched_getaffinity(0, sizeof(all_cpus), &all_cpus))
+ ksft_exit_fail_msg("sched_getaffinity: %s\n", strerror(errno));
+ nr_possible = read_nr_possible();
+ if (nr_possible <= 0)
+ ksft_exit_skip("cannot read the possible CPUs\n");
+
+ narrow_cpus(&narrow, &all_cpus, 4);
+ status = run_under_test(run_child_rounds, 0, &narrow);
+ ksft_test_result(status == CHILD_PASS, "thread count changes on at most 4 CPUs\n");
+
+ status = run_under_test(run_child_rounds, 0, &all_cpus);
+ ksft_test_result(status == CHILD_PASS, "thread count changes on all CPUs\n");
+
+ narrow_cpus(&narrow, &all_cpus, 2);
+ for (i = 0; i < WIDEN_RUNS; i++) {
+ status = run_under_test(run_child_widen, (i * 13) % ROUND_US, &narrow);
+ if (status != CHILD_PASS)
+ break;
+ }
+ ksft_test_result(status == CHILD_PASS, "affinity change widens the allowed CPUs\n");
+ ksft_finished();
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 07/13] selftests/rseq: Test the upper bound of the concurrency IDs
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (5 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 06/13] selftests/rseq: Test the concurrency IDs across ownership mode switches Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 08/13] selftests/rseq: Test an affinity change by another process during execve Mathieu Desnoyers
` (5 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
User space sizes its per-CID data by the number of possible CPUs. The
kernel keeps each mm_cid below that number. mm_cid_transition_test
checks this bound with rounds of 1 to 16 threads. On all the CPUs of
a large machine, they never outnumber the CPUs.
The kernel also aims at compact IDs. It tries to keep the IDs below
max_cids:
opt_cids = min(threads, allowed CPUs)
max_cids = min(opt_cids + opt_cids / 4, possible CPUs)
Add mm_cid_bound_test. It runs a process on 2 CPUs, on 4 CPUs and on
all allowed CPUs. The process grows from one thread to twice its
CPUs plus two, then shrinks back to one. After each step, every thread
visits every CPU of the process and reads its mm_cid there. The
largest value must stay below the number of possible CPUs.
The test prints the largest value of each step. It notes the steps
where this value reaches max_cids or min(threads, allowed CPUs). These
notes do not make it fail.
The test passes on guests with 2 to 64 CPUs, on tip sched/urgent and
after each kernel patch of this series. The 4-CPU case is skipped on
smaller guests.
With 64 possible CPUs, some steps get a note while the process
shrinks. Two of them, from a run with the four kernel patches:
# 35 threads on 64 CPUs: largest mm_cid 63 on CPU 62, max_cids 43, min(threads, CPUs) 35, reaches min(threads, CPUs), reaches max_cids
# 20 threads on 64 CPUs: largest mm_cid 24 on CPU 63, max_cids 25, min(threads, CPUs) 20, reaches min(threads, CPUs)
Their causes differ:
- At 35 threads, the mm is in per CPU mode. Every CPU ran a thread,
so every CPU owns an ID. The mm leaves that mode below pcpu_thrs:
32 threads here.
- At 20 threads, the mm is in per task mode. A thread keeps its ID
while the ID is below max_cids.
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
tools/testing/selftests/rseq/.gitignore | 1 +
tools/testing/selftests/rseq/Makefile | 3 +-
.../selftests/rseq/mm_cid_bound_test.c | 355 ++++++++++++++++++
3 files changed, 358 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/rseq/mm_cid_bound_test.c
diff --git a/tools/testing/selftests/rseq/.gitignore b/tools/testing/selftests/rseq/.gitignore
index e8afb37121d7..ff63ada38d5f 100644
--- a/tools/testing/selftests/rseq/.gitignore
+++ b/tools/testing/selftests/rseq/.gitignore
@@ -9,6 +9,7 @@ param_test_compare_twice
param_test_mm_cid
param_test_mm_cid_benchmark
param_test_mm_cid_compare_twice
+mm_cid_bound_test
mm_cid_execve_test
mm_cid_transition_test
syscall_errors_test
diff --git a/tools/testing/selftests/rseq/Makefile b/tools/testing/selftests/rseq/Makefile
index ac32d6af3b99..b643ce9cb585 100644
--- a/tools/testing/selftests/rseq/Makefile
+++ b/tools/testing/selftests/rseq/Makefile
@@ -20,7 +20,8 @@ OVERRIDE_TARGETS = 1
TEST_GEN_PROGS = basic_test basic_percpu_ops_test basic_percpu_ops_mm_cid_test \
param_test_benchmark param_test_mm_cid_benchmark \
- mm_cid_execve_test mm_cid_transition_test
+ mm_cid_execve_test mm_cid_transition_test \
+ mm_cid_bound_test
TEST_GEN_PROGS_EXTENDED = librseq.so \
param_test \
diff --git a/tools/testing/selftests/rseq/mm_cid_bound_test.c b/tools/testing/selftests/rseq/mm_cid_bound_test.c
new file mode 100644
index 000000000000..4cb011b490f8
--- /dev/null
+++ b/tools/testing/selftests/rseq/mm_cid_bound_test.c
@@ -0,0 +1,355 @@
+// SPDX-License-Identifier: LGPL-2.1
+/*
+ * The upper bound of the concurrency IDs while the thread count changes.
+ *
+ * A process grows to more threads than it has CPUs, then shrinks back to
+ * one thread. After each step every thread visits every allowed CPU and
+ * reads its mm_cid there. The largest value must stay below the number of
+ * possible CPUs. That is the upper bound of an mm_cid, and it sizes the
+ * per-CID data of user space.
+ *
+ * The kernel also aims at compact IDs. Its target is max_cids:
+ *
+ * opt_cids = min(threads, allowed CPUs)
+ * max_cids = min(opt_cids + opt_cids / 4, possible CPUs)
+ *
+ * The slack above opt_cids gives the switch between the two ownership
+ * modes some hysteresis. Threads that come and go near the limit then do
+ * not cause a costly mode switch each time.
+ *
+ * The test prints the steps where the largest mm_cid reaches max_cids,
+ * or reaches min(threads, allowed CPUs). These notes do not make it fail.
+ *
+ * The steps cross both ownership modes of the kernel. The tasks own the
+ * IDs at first. The CPUs own them once there are more threads than
+ * max_cids. The tasks own them again once the thread count drops below a
+ * threshold.
+ *
+ * The number of IDs follows the union of the allowed CPUs of the threads,
+ * which only grows. The affinity is therefore narrowed before the fork(2)
+ * that creates the process under test.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "rseq.h"
+#include "kselftest.h"
+
+#define MAX_THREADS 1024
+#define MAX_STEPS 64
+
+/*
+ * Exit status of the process under test: a mask of the bound and of the
+ * targets exceeded.
+ */
+#define OVER_POSSIBLE 1
+#define OVER_MAX_CIDS 2
+#define OVER_STRICT 4
+#define CHILD_ERROR 64
+
+struct worker {
+ pthread_t thread;
+ int stop;
+ unsigned int ack;
+ unsigned int max_cid;
+ int max_cpu;
+};
+
+static struct worker workers[MAX_THREADS];
+static unsigned int epoch;
+static cpu_set_t allowed;
+static int nr_allowed;
+static int nr_possible;
+
+/* Visit each allowed CPU and record the largest mm_cid read there. */
+static void tour(struct worker *w)
+{
+ cpu_set_t one;
+ int cpu;
+
+ w->max_cid = 0;
+ w->max_cpu = -1;
+ for (cpu = 0; cpu < CPU_SETSIZE; cpu++) {
+ unsigned int cid;
+
+ if (!CPU_ISSET(cpu, &allowed))
+ continue;
+ CPU_ZERO(&one);
+ CPU_SET(cpu, &one);
+ if (sched_setaffinity(0, sizeof(one), &one))
+ continue;
+ cid = rseq_current_mm_cid();
+ if (cid >= w->max_cid) {
+ w->max_cid = cid;
+ w->max_cpu = cpu;
+ }
+ }
+ if (sched_setaffinity(0, sizeof(allowed), &allowed)) {
+ fprintf(stderr, "sched_setaffinity: %s\n", strerror(errno));
+ abort();
+ }
+}
+
+static void *worker_fn(void *arg)
+{
+ struct worker *w = arg;
+ unsigned int seen = RSEQ_READ_ONCE(w->ack);
+
+ if (rseq_register_current_thread())
+ abort();
+ while (!RSEQ_READ_ONCE(w->stop)) {
+ unsigned int e = RSEQ_READ_ONCE(epoch);
+
+ if (e == seen) {
+ usleep(200);
+ continue;
+ }
+ tour(w);
+ seen = e;
+ /* Publish max_cid and max_cpu to measure(). */
+ rseq_smp_store_release(&w->ack, e);
+ }
+ rseq_unregister_current_thread();
+ return NULL;
+}
+
+/* Run one tour on every thread. Return the largest mm_cid, and its CPU. */
+static unsigned int measure(int nr_workers, int *cpu)
+{
+ unsigned int e = RSEQ_READ_ONCE(epoch) + 1;
+ unsigned int max_cid;
+ struct worker self;
+ int i;
+
+ RSEQ_WRITE_ONCE(epoch, e);
+ tour(&self);
+ max_cid = self.max_cid;
+ *cpu = self.max_cpu;
+ for (i = 0; i < nr_workers; i++) {
+ while (rseq_smp_load_acquire(&workers[i].ack) != e)
+ usleep(200);
+ if (workers[i].max_cid > max_cid) {
+ max_cid = workers[i].max_cid;
+ *cpu = workers[i].max_cpu;
+ }
+ }
+ return max_cid;
+}
+
+/*
+ * Create or join threads to reach @target. Return 0, or the error number
+ * after reporting it.
+ */
+static int set_workers(int *nr_workers, int target)
+{
+ int err;
+
+ while (*nr_workers < target) {
+ struct worker *w = &workers[*nr_workers];
+
+ w->stop = 0;
+ w->ack = RSEQ_READ_ONCE(epoch);
+ err = pthread_create(&w->thread, NULL, worker_fn, w);
+ if (err) {
+ fprintf(stderr, "pthread_create: %s\n", strerror(err));
+ return err;
+ }
+ (*nr_workers)++;
+ }
+ while (*nr_workers > target) {
+ struct worker *w = &workers[*nr_workers - 1];
+
+ RSEQ_WRITE_ONCE(w->stop, 1);
+ err = pthread_join(w->thread, NULL);
+ if (err) {
+ fprintf(stderr, "pthread_join: %s\n", strerror(err));
+ return err;
+ }
+ (*nr_workers)--;
+ }
+ return 0;
+}
+
+static unsigned int min_u(unsigned int a, unsigned int b)
+{
+ return a < b ? a : b;
+}
+
+/* The process under test. Return a mask of the OVER_* values. */
+static int run_child(const int *steps, int nr_steps)
+{
+ int nr_workers = 0, ret = 0, i;
+
+ if (sched_getaffinity(0, sizeof(allowed), &allowed))
+ return CHILD_ERROR;
+ nr_allowed = CPU_COUNT(&allowed);
+
+ for (i = 0; i < nr_steps; i++) {
+ unsigned int threads = steps[i], opt, max_cids, strict, cid;
+ int cpu, over = 0, err;
+
+ err = set_workers(&nr_workers, threads - 1);
+ if (err) {
+ ret |= CHILD_ERROR;
+ break;
+ }
+ /* The first tour lets every thread schedule on every CPU. */
+ measure(nr_workers, &cpu);
+ cid = measure(nr_workers, &cpu);
+
+ opt = min_u(threads, nr_allowed);
+ strict = opt;
+ max_cids = min_u(opt + opt / 4, nr_possible);
+ if (cid >= (unsigned int)nr_possible)
+ over |= OVER_POSSIBLE;
+ if (cid >= max_cids)
+ over |= OVER_MAX_CIDS;
+ if (cid >= strict)
+ over |= OVER_STRICT;
+ ksft_print_msg(
+ "%4u threads on %d CPUs: largest mm_cid %u on CPU %d, max_cids %u, min(threads, CPUs) %u%s%s%s\n",
+ threads, nr_allowed, cid, cpu, max_cids, strict,
+ over & OVER_STRICT ? ", reaches min(threads, CPUs)" : "",
+ over & OVER_MAX_CIDS ? ", reaches max_cids" : "",
+ over & OVER_POSSIBLE ? ", at or above the possible CPUs" : "");
+ ret |= over;
+ }
+ if (set_workers(&nr_workers, 0))
+ ret |= CHILD_ERROR;
+ return ret;
+}
+
+/* Keep the first @nr CPUs of @src in @dst. */
+static int narrow_cpus(cpu_set_t *dst, const cpu_set_t *src, int nr)
+{
+ int cpu, taken = 0;
+
+ CPU_ZERO(dst);
+ for (cpu = 0; cpu < CPU_SETSIZE && taken < nr; cpu++) {
+ if (!CPU_ISSET(cpu, src))
+ continue;
+ CPU_SET(cpu, dst);
+ taken++;
+ }
+ return taken;
+}
+
+static int read_nr_possible(void)
+{
+ int first, last, total = 0;
+ char sep;
+ FILE *f;
+
+ f = fopen("/sys/devices/system/cpu/possible", "r");
+ if (!f)
+ return -1;
+ /* A list of ranges: "0-63" or "0,2-5". */
+ while (fscanf(f, "%d", &first) == 1) {
+ last = first;
+ sep = '\n';
+ if (fscanf(f, "%c", &sep) == 1 && sep == '-') {
+ if (fscanf(f, "%d", &last) != 1)
+ break;
+ if (fscanf(f, "%c", &sep) != 1)
+ sep = '\n';
+ }
+ total += last - first + 1;
+ if (sep != ',')
+ break;
+ }
+ fclose(f);
+ return total;
+}
+
+/* Thread counts from 1 up to twice the CPUs plus two, and back to 1. */
+static int make_steps(int *steps, int cpus)
+{
+ int top = 2 * cpus + 2, stride = 1, n = 0, t;
+
+ if (top > MAX_THREADS)
+ top = MAX_THREADS;
+ /* Every count on a small set of CPUs, a fraction on a large one. */
+ while (2 * (top / stride) + 1 > MAX_STEPS)
+ stride++;
+ for (t = 1; t < top; t += stride)
+ steps[n++] = t;
+ steps[n++] = top;
+ for (t = top - stride; t > 1; t -= stride)
+ steps[n++] = t;
+ steps[n++] = 1;
+ return n;
+}
+
+static void test_ramp(const cpu_set_t *all, int cpus, const char *name)
+{
+ int steps[MAX_STEPS + 2], nr_steps, status = 0;
+ cpu_set_t narrow;
+ pid_t child;
+
+ if (narrow_cpus(&narrow, all, cpus) < cpus) {
+ ksft_test_result_skip("%s: below the possible CPUs\n", name);
+ return;
+ }
+ nr_steps = make_steps(steps, cpus);
+
+ /* Narrowed before the fork(2): the union of allowed CPUs only grows. */
+ if (sched_setaffinity(0, sizeof(narrow), &narrow))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ child = fork();
+ if (!child)
+ _exit(run_child(steps, nr_steps));
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ if (sched_setaffinity(0, sizeof(*all), all))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ if (!WIFEXITED(status) || (WEXITSTATUS(status) & CHILD_ERROR))
+ ksft_exit_fail_msg("the process under test failed to run\n");
+
+ status = WEXITSTATUS(status);
+ /* The targets are reported. Only the bound decides the result. */
+ if (status & OVER_MAX_CIDS)
+ ksft_print_msg("%s: some steps reach max_cids\n", name);
+ if (status & OVER_STRICT)
+ ksft_print_msg("%s: some steps reach min(threads, CPUs)\n", name);
+ ksft_test_result(!(status & OVER_POSSIBLE),
+ "%s: below the possible CPUs\n", name);
+}
+
+int main(void)
+{
+ cpu_set_t all;
+ int nr_all;
+
+ ksft_print_header();
+ ksft_set_plan(3);
+
+ if (!rseq_available())
+ ksft_exit_skip("rseq is unavailable\n");
+ if (rseq_register_current_thread())
+ ksft_exit_fail_msg("rseq_register_current_thread: %s\n", strerror(errno));
+ if (!rseq_mm_cid_available())
+ ksft_exit_skip("the rseq mm_cid field is unavailable\n");
+ if (sched_getaffinity(0, sizeof(all), &all))
+ ksft_exit_fail_msg("sched_getaffinity: %s\n", strerror(errno));
+ nr_possible = read_nr_possible();
+ if (nr_possible <= 0)
+ ksft_exit_skip("cannot read the possible CPUs\n");
+ nr_all = CPU_COUNT(&all);
+ ksft_print_msg("%d possible CPUs, %d allowed\n", nr_possible, nr_all);
+
+ test_ramp(&all, 2, "2 CPUs");
+ test_ramp(&all, 4, "4 CPUs");
+ test_ramp(&all, nr_all, "all CPUs");
+ ksft_finished();
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 08/13] selftests/rseq: Test an affinity change by another process during execve
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (6 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 07/13] selftests/rseq: Test the upper bound of the concurrency IDs Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 09/13] selftests/rseq: Test the concurrency IDs after the affinity is widened Mathieu Desnoyers
` (4 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
The number of concurrency IDs of an mm follows the CPUs its threads
are allowed on. Another process can widen the affinity of a task while
the task is in execve(). The new mm must then include the new CPUs, or
its IDs are no longer compact. No test checks this.
On tip sched/urgent, the change is lost when it lands between
mm_init_cid() and the join of the new mm. In this sequence, the parent
is the test process and the child is single-threaded. CPU 0 and CPU 1
stand for the first two CPUs the test may use.
parent child
------ -----
sched_setaffinity(self, CPU 0)
fork()
(allowed on CPU 0 only)
sched_setaffinity(self, CPU 1)
execve()
bprm_execve()
... exec_mmap()
mm_init_cid(new mm)
nr_cpus_allowed = 1
sched_setaffinity(child, all CPUs)
set_cpus_allowed_common()
mm_update_cpus_allowed(new mm)
users == 0: return
sched_mm_cid_after_execve()
sched_mm_cid_fork()
users = 1
The new mm keeps one allowed CPU, so max_cids is 1. Two threads then
switch it to per CPU mode, and it does not switch back. Each CPU keeps
the CID it took.
Add mm_cid_exec_affinity_test. It runs this sequence up to 60 times, with a
different delay before the parent widens the affinity. The new program
runs one thread per CPU, then keeps two. Both must read an mm_cid below
2. The header comment of the test has the details. A first case allows
all CPUs from the start. It passes on tip sched/urgent and with each
kernel patch of this series. Both cases are skipped with fewer than 4
CPUs.
The second case fails on tip sched/urgent, on every guest with 4 to 64
CPUs. On the 64-CPU guest:
mm_cid 1 and 63 with 2 threads, largest spinner mm_cid 63 with 64 threads
# attempt 4, 148 us delay before the affinity change
not ok 2 affinity widened by another process during execve
With "sched/mmcid: Move the execve() hooks into exec_mmap()" alone, the
case still fails at times: on one 16-CPU guest in each of three runs.
That patch moves sched_mm_cid_after_execve() into exec_mmap(), a few
lines after mm_init_cid(). The change can still land in between. The
case passes on every guest after "sched/mmcid: Add the allowed CPUs of
each joining task to the mm".
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
tools/testing/selftests/rseq/.gitignore | 1 +
tools/testing/selftests/rseq/Makefile | 2 +-
.../rseq/mm_cid_exec_affinity_test.c | 288 ++++++++++++++++++
3 files changed, 290 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/rseq/mm_cid_exec_affinity_test.c
diff --git a/tools/testing/selftests/rseq/.gitignore b/tools/testing/selftests/rseq/.gitignore
index ff63ada38d5f..4c02ff8dccca 100644
--- a/tools/testing/selftests/rseq/.gitignore
+++ b/tools/testing/selftests/rseq/.gitignore
@@ -12,6 +12,7 @@ param_test_mm_cid_compare_twice
mm_cid_bound_test
mm_cid_execve_test
mm_cid_transition_test
+mm_cid_exec_affinity_test
syscall_errors_test
slice_test
legacy_check
diff --git a/tools/testing/selftests/rseq/Makefile b/tools/testing/selftests/rseq/Makefile
index b643ce9cb585..006e2e281ca8 100644
--- a/tools/testing/selftests/rseq/Makefile
+++ b/tools/testing/selftests/rseq/Makefile
@@ -21,7 +21,7 @@ OVERRIDE_TARGETS = 1
TEST_GEN_PROGS = basic_test basic_percpu_ops_test basic_percpu_ops_mm_cid_test \
param_test_benchmark param_test_mm_cid_benchmark \
mm_cid_execve_test mm_cid_transition_test \
- mm_cid_bound_test
+ mm_cid_bound_test mm_cid_exec_affinity_test
TEST_GEN_PROGS_EXTENDED = librseq.so \
param_test \
diff --git a/tools/testing/selftests/rseq/mm_cid_exec_affinity_test.c b/tools/testing/selftests/rseq/mm_cid_exec_affinity_test.c
new file mode 100644
index 000000000000..3aa82f141df4
--- /dev/null
+++ b/tools/testing/selftests/rseq/mm_cid_exec_affinity_test.c
@@ -0,0 +1,288 @@
+// SPDX-License-Identifier: LGPL-2.1
+/*
+ * The concurrency IDs after another process widens the affinity of a task
+ * during its execve(2).
+ *
+ * The kernel sizes the ID range of an mm from the CPUs which its threads
+ * are allowed on. A task in execve(2) cannot change its own affinity, but
+ * another task can. The new mm must count the CPUs of that change.
+ *
+ * A child allowed on one CPU runs this test again with execve(2). The
+ * parent runs on another CPU. It widens the affinity of the child to all
+ * CPUs after a delay, which starts when the child is about to call
+ * execve(2). The delay differs on each attempt, so that some changes land
+ * during the execve(2).
+ *
+ * The new program waits until it is allowed on all CPUs. It runs one
+ * thread per CPU: the main thread and spinners. It lets them spread. Then
+ * it stops all spinners but the one with the largest mm_cid. A thread
+ * whose mm_cid is not below max_cids takes a free one below it when it is
+ * scheduled in. With two threads, max_cids is 2, so both must read an
+ * mm_cid below 2. If the new mm missed the change, it counts one CPU and
+ * stays in per CPU mode. The kept spinner can then keep its large mm_cid.
+ * A first case runs the same program with all CPUs allowed from the
+ * start.
+ *
+ * The new program does not change its own affinity. Such a change would
+ * add its CPUs to the mm, and hide a lost change.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "rseq.h"
+#include "kselftest.h"
+
+#define MIN_CPUS 4
+#define MAX_SPINNERS 64
+#define ATTEMPTS 60
+#define MAX_DELAY_US 1500
+#define SPREAD_US 50000
+#define SETTLE_US 50000
+#define WIDE_WAIT_US 5000000
+
+#define CHILD_PASS 0
+#define CHILD_FAIL 1
+#define CHILD_ERROR 2
+
+struct spinner {
+ pthread_t thread;
+ unsigned int cid;
+ int stop;
+};
+
+static struct spinner spinners[MAX_SPINNERS];
+static int nap;
+
+static void *spinner_fn(void *arg)
+{
+ struct spinner *s = arg;
+
+ if (rseq_register_current_thread())
+ abort();
+ while (!RSEQ_READ_ONCE(s->stop)) {
+ RSEQ_WRITE_ONCE(s->cid, rseq_current_mm_cid());
+ /* Sleep, so that the next read follows a schedule in. */
+ if (RSEQ_READ_ONCE(nap))
+ usleep(1000);
+ }
+ rseq_unregister_current_thread();
+ return NULL;
+}
+
+/* Stop @s and join it. Return 0, or -1 after reporting a join error. */
+static int stop_spinner(struct spinner *s)
+{
+ int err;
+
+ RSEQ_WRITE_ONCE(s->stop, 1);
+ err = pthread_join(s->thread, NULL);
+ if (err) {
+ fprintf(stderr, "pthread_join: %s\n", strerror(err));
+ return -1;
+ }
+ return 0;
+}
+
+/*
+ * The program under test, after the execve(2). Wait for @want allowed
+ * CPUs, then check the IDs of two threads. Return a CHILD_* status.
+ */
+static int check_main(int want)
+{
+ unsigned int spread_cid = 0, cid, own;
+ int nr = want < MAX_SPINNERS ? want : MAX_SPINNERS;
+ int i, err, started = 0, keep = 0, waited = 0, failed = 0;
+ cpu_set_t mask;
+
+ for (;;) {
+ if (sched_getaffinity(0, sizeof(mask), &mask))
+ return CHILD_ERROR;
+ if (CPU_COUNT(&mask) == want)
+ break;
+ if (waited >= WIDE_WAIT_US) {
+ fprintf(stderr, "allowed on %d CPUs, expected %d\n",
+ CPU_COUNT(&mask), want);
+ return CHILD_ERROR;
+ }
+ usleep(100);
+ waited += 100;
+ }
+ if (rseq_register_current_thread())
+ return CHILD_ERROR;
+
+ /* One thread per CPU, this one included. */
+ for (i = 0; i < nr - 1; i++) {
+ err = pthread_create(&spinners[i].thread, NULL, spinner_fn, &spinners[i]);
+ if (err) {
+ fprintf(stderr, "pthread_create: %s\n", strerror(err));
+ break;
+ }
+ started++;
+ }
+ if (started)
+ usleep(SPREAD_US);
+
+ /* Keep the thread with the largest mm_cid. */
+ for (i = 0; i < started; i++) {
+ cid = RSEQ_READ_ONCE(spinners[i].cid);
+ if (cid >= spread_cid) {
+ spread_cid = cid;
+ keep = i;
+ }
+ }
+ for (i = 0; i < started; i++) {
+ if (i != keep && stop_spinner(&spinners[i]))
+ failed = 1;
+ }
+ if (failed || started < nr - 1) {
+ if (started)
+ stop_spinner(&spinners[keep]);
+ return CHILD_ERROR;
+ }
+
+ RSEQ_WRITE_ONCE(nap, 1);
+ usleep(SETTLE_US);
+ cid = RSEQ_READ_ONCE(spinners[keep].cid);
+ own = rseq_current_mm_cid();
+ if (stop_spinner(&spinners[keep]))
+ return CHILD_ERROR;
+
+ if (cid >= 2 || own >= 2) {
+ fprintf(stderr,
+ "mm_cid %u and %u with 2 threads, largest spinner mm_cid %u with %d threads\n",
+ own, cid, spread_cid, nr);
+ return CHILD_FAIL;
+ }
+ return CHILD_PASS;
+}
+
+static void busy_wait_us(int us)
+{
+ struct timespec start, now;
+
+ clock_gettime(CLOCK_MONOTONIC, &start);
+ do {
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ } while ((now.tv_sec - start.tv_sec) * 1000000L +
+ (now.tv_nsec - start.tv_nsec) / 1000 < us);
+}
+
+/*
+ * Run the program under test in a new process that starts on the CPUs in
+ * @start. Widen its affinity to @all after @delay_us, unless @delay_us is
+ * negative. Run on the CPUs in @beside meanwhile. Return a CHILD_* status.
+ */
+static int run_attempt(const cpu_set_t *start, const cpu_set_t *beside,
+ const cpu_set_t *all, int delay_us)
+{
+ char want[16], arg0[] = "mm_cid_exec_affinity_test", arg1[] = "check";
+ char *const av[] = { arg0, arg1, want, NULL };
+ int go[2], status = 0;
+ pid_t child;
+ char c = 0;
+
+ snprintf(want, sizeof(want), "%d", CPU_COUNT(all));
+ if (pipe2(go, O_CLOEXEC))
+ ksft_exit_fail_msg("pipe2: %s\n", strerror(errno));
+ if (sched_setaffinity(0, sizeof(*start), start))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ child = fork();
+ if (!child) {
+ if (write(go[1], &c, 1) != 1)
+ _exit(CHILD_ERROR);
+ execv("/proc/self/exe", av);
+ _exit(CHILD_ERROR);
+ }
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ /* On the CPU of the child, the change would wait for its execve(2). */
+ if (sched_setaffinity(0, sizeof(*beside), beside))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ close(go[1]);
+ if (read(go[0], &c, 1) == 1 && delay_us >= 0) {
+ busy_wait_us(delay_us);
+ /* The child is in execve(2), or about to enter or leave it. */
+ if (sched_setaffinity(child, sizeof(*all), all))
+ ksft_print_msg("sched_setaffinity on the child: %s\n", strerror(errno));
+ }
+ close(go[0]);
+ if (sched_setaffinity(0, sizeof(*all), all))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ if (!WIFEXITED(status))
+ ksft_exit_fail_msg("the process under test was killed by signal %d\n",
+ WTERMSIG(status));
+ return WEXITSTATUS(status);
+}
+
+int main(int argc, char **argv)
+{
+ cpu_set_t all, one, beside;
+ int status, i, cpu;
+
+ if (argc == 3 && !strcmp(argv[1], "check"))
+ return check_main(atoi(argv[2]));
+
+ ksft_print_header();
+ ksft_set_plan(2);
+
+ if (!rseq_available())
+ ksft_exit_skip("rseq is unavailable\n");
+ if (rseq_register_current_thread())
+ ksft_exit_fail_msg("rseq_register_current_thread: %s\n", strerror(errno));
+ if (!rseq_mm_cid_available())
+ ksft_exit_skip("the rseq mm_cid field is unavailable\n");
+ if (sched_getaffinity(0, sizeof(all), &all))
+ ksft_exit_fail_msg("sched_getaffinity: %s\n", strerror(errno));
+ if (CPU_COUNT(&all) < MIN_CPUS) {
+ ksft_test_result_skip("all CPUs allowed before execve: fewer than %d CPUs\n",
+ MIN_CPUS);
+ ksft_test_result_skip("affinity widened during execve: fewer than %d CPUs\n",
+ MIN_CPUS);
+ ksft_finished();
+ }
+
+ /* The child starts on the first CPU, the parent runs on the second. */
+ CPU_ZERO(&one);
+ CPU_ZERO(&beside);
+ for (cpu = 0; cpu < CPU_SETSIZE; cpu++) {
+ if (!CPU_ISSET(cpu, &all))
+ continue;
+ if (!CPU_COUNT(&one)) {
+ CPU_SET(cpu, &one);
+ } else {
+ CPU_SET(cpu, &beside);
+ break;
+ }
+ }
+
+ status = run_attempt(&all, &all, &all, -1);
+ if (status == CHILD_ERROR)
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ ksft_test_result(status == CHILD_PASS, "all CPUs allowed before execve\n");
+
+ for (i = 0; i < ATTEMPTS; i++) {
+ status = run_attempt(&one, &beside, &all, (i * 37) % MAX_DELAY_US);
+ if (status == CHILD_ERROR)
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ if (status != CHILD_PASS) {
+ ksft_print_msg("attempt %d, %d us delay before the affinity change\n",
+ i, (i * 37) % MAX_DELAY_US);
+ break;
+ }
+ }
+ ksft_test_result(status == CHILD_PASS,
+ "affinity widened by another process during execve\n");
+ ksft_finished();
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 09/13] selftests/rseq: Test the concurrency IDs after the affinity is widened
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (7 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 08/13] selftests/rseq: Test an affinity change by another process during execve Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 10/13] selftests/rseq: Test two race windows of the concurrency ID mode switches Mathieu Desnoyers
` (3 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
Either the tasks or the CPUs own the concurrency IDs of an mm. When an
affinity change widens the allowed CPUs of the mm, the IDs go back to
the tasks if the thread count is below pcpu_thrs.
Commit 7dbc307b6c72 ("sched/mmcid: Fix affinity-triggered switch back
to per-task mode") fixed how pcpu_thrs is computed. Before it,
pcpu_thrs was never above the thread count, so the CPUs kept the IDs.
mm_cid_transition_test widens the affinity, but it only checks the
bound. No test checks that the IDs go back to the tasks.
Add a case to mm_cid_bound_test. Three threads start on two CPUs, so
the CPUs own the IDs. Each thread then widens its own affinity to all
CPUs. It visits each CPU and reads its mm_cid there. Once the tasks own
the IDs, the kernel aims at an mm_cid below 3. That is a target, not a
bound. The case prints when the target is missed. It fails only when an
mm_cid reaches the number of possible CPUs.
The case needs 8 possible CPUs, all allowed. With fewer possible CPUs,
pcpu_thrs is at most 3 and the CPUs keep the IDs.
This case is the first to change the allowed CPUs while the workers
run. So the workers now read the epoch with acquire semantics: the
epoch publishes the new allowed CPUs.
The target is met on guests with 8 to 64 CPUs, on tip sched/urgent and
after each kernel patch of this series:
# 3 threads widened to 64 CPUs: largest mm_cid 2 on CPU 63
A v7.1.8 kernel does not have the commit above. There, the target is
missed on a machine with 384 CPUs. The case still passes there:
3 threads widened to 384 CPUs: largest mm_cid 383 on CPU 383, above the thread count target
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
.../selftests/rseq/mm_cid_bound_test.c | 94 ++++++++++++++++++-
1 file changed, 91 insertions(+), 3 deletions(-)
diff --git a/tools/testing/selftests/rseq/mm_cid_bound_test.c b/tools/testing/selftests/rseq/mm_cid_bound_test.c
index 4cb011b490f8..9795cc030e7f 100644
--- a/tools/testing/selftests/rseq/mm_cid_bound_test.c
+++ b/tools/testing/selftests/rseq/mm_cid_bound_test.c
@@ -28,6 +28,11 @@
* The number of IDs follows the union of the allowed CPUs of the threads,
* which only grows. The affinity is therefore narrowed before the fork(2)
* that creates the process under test.
+ *
+ * The widening case starts three threads on two CPUs, so the CPUs own the
+ * IDs. The threads are then allowed on all CPUs. The kernel aims at giving
+ * the IDs back to the tasks, so that three threads read an mm_cid below 3.
+ * That is a target too: the case prints when it is missed.
*/
#define _GNU_SOURCE
@@ -46,6 +51,9 @@
#define MAX_THREADS 1024
#define MAX_STEPS 64
+#define WIDEN_THREADS 3
+#define WIDEN_MIN_CPUS 8
+#define WIDEN_SETTLE_US 20000
/*
* Exit status of the process under test: a mask of the bound and of the
@@ -67,6 +75,7 @@ struct worker {
static struct worker workers[MAX_THREADS];
static unsigned int epoch;
static cpu_set_t allowed;
+static cpu_set_t all_cpus;
static int nr_allowed;
static int nr_possible;
@@ -107,7 +116,8 @@ static void *worker_fn(void *arg)
if (rseq_register_current_thread())
abort();
while (!RSEQ_READ_ONCE(w->stop)) {
- unsigned int e = RSEQ_READ_ONCE(epoch);
+ /* Read allowed after the epoch that publishes it. */
+ unsigned int e = rseq_smp_load_acquire(&epoch);
if (e == seen) {
usleep(200);
@@ -130,7 +140,8 @@ static unsigned int measure(int nr_workers, int *cpu)
struct worker self;
int i;
- RSEQ_WRITE_ONCE(epoch, e);
+ /* Publish allowed to the workers with the new epoch. */
+ rseq_smp_store_release(&epoch, e);
tour(&self);
max_cid = self.max_cid;
*cpu = self.max_cpu;
@@ -228,6 +239,49 @@ static int run_child(const int *steps, int nr_steps)
return ret;
}
+/*
+ * The process under test of the widening case. It starts on two CPUs.
+ * Return a mask of the OVER_* values.
+ */
+static int run_child_widen(void)
+{
+ int nr_workers = 0, ret = 0, cpu, err;
+ unsigned int cid;
+
+ if (sched_getaffinity(0, sizeof(allowed), &allowed))
+ return CHILD_ERROR;
+ nr_allowed = CPU_COUNT(&allowed);
+
+ err = set_workers(&nr_workers, WIDEN_THREADS - 1);
+ if (err)
+ return CHILD_ERROR;
+ measure(nr_workers, &cpu);
+ cid = measure(nr_workers, &cpu);
+ ksft_print_msg("%4d threads on %d CPUs: largest mm_cid %u on CPU %d\n",
+ WIDEN_THREADS, nr_allowed, cid, cpu);
+
+ /* Each thread widens its own affinity at the end of its next tour. */
+ allowed = all_cpus;
+ nr_allowed = CPU_COUNT(&allowed);
+ if (sched_setaffinity(0, sizeof(allowed), &allowed))
+ ret |= CHILD_ERROR;
+ measure(nr_workers, &cpu);
+ /* The kernel changes the owners of the IDs from a work item. */
+ usleep(WIDEN_SETTLE_US);
+ measure(nr_workers, &cpu);
+ cid = measure(nr_workers, &cpu);
+ if (cid >= (unsigned int)nr_possible)
+ ret |= OVER_POSSIBLE;
+ if (cid >= WIDEN_THREADS)
+ ret |= OVER_STRICT;
+ ksft_print_msg("%4d threads widened to %d CPUs: largest mm_cid %u on CPU %d%s\n",
+ WIDEN_THREADS, nr_allowed, cid, cpu,
+ ret & OVER_STRICT ? ", above the thread count target" : "");
+ if (set_workers(&nr_workers, 0))
+ ret |= CHILD_ERROR;
+ return ret;
+}
+
/* Keep the first @nr CPUs of @src in @dst. */
static int narrow_cpus(cpu_set_t *dst, const cpu_set_t *src, int nr)
{
@@ -326,13 +380,46 @@ static void test_ramp(const cpu_set_t *all, int cpus, const char *name)
"%s: below the possible CPUs\n", name);
}
+static void test_widen(const cpu_set_t *all)
+{
+ const char *name = "widened from 2 CPUs: below the possible CPUs";
+ cpu_set_t narrow;
+ int status = 0;
+ pid_t child;
+
+ /* With fewer CPUs the kernel keeps the CPUs as owners of the IDs. */
+ if (CPU_COUNT(all) < WIDEN_MIN_CPUS || nr_possible < WIDEN_MIN_CPUS) {
+ ksft_test_result_skip("%s: fewer than %d CPUs\n", name, WIDEN_MIN_CPUS);
+ return;
+ }
+ narrow_cpus(&narrow, all, 2);
+ all_cpus = *all;
+ if (sched_setaffinity(0, sizeof(narrow), &narrow))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ child = fork();
+ if (!child)
+ _exit(run_child_widen());
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ if (sched_setaffinity(0, sizeof(*all), all))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ if (!WIFEXITED(status) || (WEXITSTATUS(status) & CHILD_ERROR))
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ /* The thread count is a target. Only the bound decides the result. */
+ if (WEXITSTATUS(status) & OVER_STRICT)
+ ksft_print_msg("widened from 2 CPUs: above the thread count target\n");
+ ksft_test_result(!(WEXITSTATUS(status) & OVER_POSSIBLE), "%s\n", name);
+}
+
int main(void)
{
cpu_set_t all;
int nr_all;
ksft_print_header();
- ksft_set_plan(3);
+ ksft_set_plan(4);
if (!rseq_available())
ksft_exit_skip("rseq is unavailable\n");
@@ -351,5 +438,6 @@ int main(void)
test_ramp(&all, 2, "2 CPUs");
test_ramp(&all, 4, "4 CPUs");
test_ramp(&all, nr_all, "all CPUs");
+ test_widen(&all);
ksft_finished();
}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 10/13] selftests/rseq: Test two race windows of the concurrency ID mode switches
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (8 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 09/13] selftests/rseq: Test the concurrency IDs after the affinity is widened Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 11/13] selftests/rseq: Test the last user after an affinity change during execve Mathieu Desnoyers
` (2 subsequent siblings)
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
Two bugs of the concurrency ID mode switches show only when a task is
scheduled inside a narrow window. The header comment of the new test
draws each sequence as a diagram:
- Case 1: a failed execve() rejoins the mm and switches it to per CPU
mode. This needs a kernel where a failed execve() leaves the mm.
- Case 2: a thread migrates while the mm switches to per CPU mode. This
is the sequence of commit 4327fb13fa47 ("sched/mmcid: Prevent live
lock on task to CPU mode transition").
Without a delay in the kernel, a test reaches these windows only by
chance. Add mm_cid_window_test, with one case for each window. Each case
makes 40 attempts, each with another delay. Case 1 runs on 2 CPUs. It
fails on an mm_cid at or above the number of possible CPUs, or when the
failed execve() takes more than 100ms. An mm_cid of 2 or more only gets
a note, as in mm_cid_execve_test. Case 2 needs 3 to 256 CPUs, all
possible CPUs allowed. It fails when the moving thread has not moved
after 2s.
On tip sched/urgent, case 1 fails on guests with 2 to 64 CPUs. It fails
on another bug of the same rejoin, which mm_cid_execve_test also finds.
Unless the task is scheduled out in the window, it returns to user space
with no ID. Its mm_cid is 0x80000000, printed in decimal:
mm_cid 2147483648 after a failed execve, 2 possible CPUs
not ok 1 failed execve switches to per CPU mode
Case 1 passes after "sched/mmcid: Move the execve() hooks into
exec_mmap()". A failed execve() then no longer leaves the mm. Case 1
stays as a guard: if the rejoin comes back, it fails on 0x80000000
again. Case 2 passes on tip sched/urgent and after each of patches 1
to 4.
A kernel that makes a thread sleep in the window hits it on every
attempt. The test header names the places. Case 2 was checked this way,
on a kernel with patches 1 to 4 and two changes:
- The switch to per CPU mode skipped its transit phase. This undoes
the fix of the commit above.
- sched_mm_cid_fork() slept 3ms in fsleep(), after the mode change and
before mm_cid_fixup_tasks_to_cpus().
Case 2 then hung eight guests with 3 to 16 CPUs. RCU stall reports
showed a test thread looping in __schedule(). With the fsleep() alone,
case 2 passed on the same eight guests.
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
tools/testing/selftests/rseq/.gitignore | 1 +
tools/testing/selftests/rseq/Makefile | 3 +-
.../selftests/rseq/mm_cid_window_test.c | 525 ++++++++++++++++++
3 files changed, 528 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/rseq/mm_cid_window_test.c
diff --git a/tools/testing/selftests/rseq/.gitignore b/tools/testing/selftests/rseq/.gitignore
index 4c02ff8dccca..0065f51f53ab 100644
--- a/tools/testing/selftests/rseq/.gitignore
+++ b/tools/testing/selftests/rseq/.gitignore
@@ -13,6 +13,7 @@ mm_cid_bound_test
mm_cid_execve_test
mm_cid_transition_test
mm_cid_exec_affinity_test
+mm_cid_window_test
syscall_errors_test
slice_test
legacy_check
diff --git a/tools/testing/selftests/rseq/Makefile b/tools/testing/selftests/rseq/Makefile
index 006e2e281ca8..d72502fc7652 100644
--- a/tools/testing/selftests/rseq/Makefile
+++ b/tools/testing/selftests/rseq/Makefile
@@ -21,7 +21,8 @@ OVERRIDE_TARGETS = 1
TEST_GEN_PROGS = basic_test basic_percpu_ops_test basic_percpu_ops_mm_cid_test \
param_test_benchmark param_test_mm_cid_benchmark \
mm_cid_execve_test mm_cid_transition_test \
- mm_cid_bound_test mm_cid_exec_affinity_test
+ mm_cid_bound_test mm_cid_exec_affinity_test \
+ mm_cid_window_test
TEST_GEN_PROGS_EXTENDED = librseq.so \
param_test \
diff --git a/tools/testing/selftests/rseq/mm_cid_window_test.c b/tools/testing/selftests/rseq/mm_cid_window_test.c
new file mode 100644
index 000000000000..32527fd3015f
--- /dev/null
+++ b/tools/testing/selftests/rseq/mm_cid_window_test.c
@@ -0,0 +1,525 @@
+// SPDX-License-Identifier: LGPL-2.1
+/*
+ * Two race windows of the concurrency ID mode switches.
+ *
+ * Each case drives its threads through one sequence in which the kernel
+ * used to loop in mm_get_cid(), looking for a free ID. The window is
+ * narrow, so an attempt rarely lands in it. Each attempt uses another
+ * delay. On a kernel with the bug, an attempt that misses the window
+ * passes. A kernel that loops shows as a timeout.
+ *
+ * Case 1 needs a kernel where a failed execve(2) leaves the mm and
+ * rejoins it, as before "sched/mmcid: Move the execve() hooks into
+ * exec_mmap()". The process runs on two CPUs, in per task mode. A and B
+ * are its two threads, on CPU 0 and CPU 1. C is the vfork(2) child of B,
+ * so it shares the mm. The mm uses two IDs, 0 and 1. On a machine with
+ * two possible CPUs, these are the only IDs.
+ *
+ * CPU 0 CPU 1
+ *
+ * A: execve(2)
+ * sched_mm_cid_before_execve()
+ * drops the ID of A
+ * B: vfork(2)
+ * sched_mm_cid_fork(C)
+ * C takes the free ID
+ * B: waits for C
+ * C: spins, never schedules
+ * A: execve(2) fails with ELOOP
+ * sched_mm_cid_after_execve()
+ * sched_mm_cid_fork(A): 3 users,
+ * sets MM_CID_ONCPU | MM_CID_TRANSIT
+ * A: is scheduled out, and in again
+ * mm_cid_schedin()
+ * mm_get_cid() loops: B and C
+ * hold both IDs
+ * A: mm_cid_fixup_tasks_to_cpus()
+ * is never reached
+ *
+ * Only that fixup could free an ID, and it runs in A. With more possible
+ * CPUs, mm_get_cid() does not loop. It takes an ID of 2 or more. That ID is
+ * below the number of possible CPUs, the only bound, so the case prints a
+ * note and passes.
+ *
+ * Before that change, sched_mm_cid_fork() gives A no ID in per CPU mode.
+ * Unless A is scheduled out in the window, it returns to user space with
+ * no ID and reads an mm_cid of 0x80000000. Case 1 then fails on that
+ * value. Since that change, a failed execve(2) stays in the mm and the
+ * sequence cannot happen. Case 1 stays as a guard against a return of the
+ * rejoin.
+ *
+ * Case 2 is the sequence of commit 4327fb13fa47 ("sched/mmcid: Prevent
+ * live lock on task to CPU mode transition"). The diagram shows a kernel
+ * without the transit phase which that commit added. The process is
+ * allowed on all possible CPUs, so the mm has one ID per CPU. M is its
+ * main thread, on CPU 0. T1 and T2 are two of the threads which M starts,
+ * one on each other CPU.
+ *
+ * CPU 0 CPU 1 CPU 2
+ *
+ * M: starts one spinning
+ * thread on each other
+ * CPU: every ID is taken
+ * T1: spins T2: spins
+ * M: pthread_create()
+ * sched_mm_cid_fork():
+ * one user too many,
+ * switches to per CPU
+ * mode
+ * T1: usleep(), then
+ * mm_cid_schedin():
+ * CPU 1 takes the
+ * ID of T1
+ * T1: sched_setaffinity()
+ * to CPU 2
+ * T2: preempted,
+ * keeps its ID
+ * T1: mm_cid_schedin()
+ * mm_get_cid()
+ * loops, with the
+ * rq lock held
+ * M: mm_cid_fixup_tasks_to_cpus()
+ * waits for the rq lock
+ * of CPU 2
+ *
+ * With that commit, T1 drops its ID when it leaves CPU 1. mm_get_cid() on
+ * CPU 2 then takes it.
+ *
+ * A kernel with an added sleep inside the window hits it on every
+ * attempt. The thread which switches the mode, A in case 1 and M in case
+ * 2, would sleep in these places:
+ * - in sched_mm_cid_fork(), after the mode change and before
+ * mm_cid_fixup_tasks_to_cpus() (both cases);
+ * - in sched_mm_cid_after_execve(), before sched_mm_cid_fork(), on a
+ * kernel where a failed execve(2) rejoins the mm (case 1).
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <limits.h>
+#include <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "rseq.h"
+#include "kselftest.h"
+
+#define ATTEMPTS 40
+#define MAX_DELAY_US 400
+#define SPIN_MS 300
+#define SLOW_MS 100
+#define MAX_SPINNERS 256
+#define MOVE_WAIT_MS 2000
+
+#define CHILD_PASS 0
+#define CHILD_FAIL 1
+#define CHILD_SKIP 2
+#define CHILD_ERROR 3
+
+static int go, done, moved, ready, stop;
+static int pin_failed;
+static int delay_us;
+static int nr_possible;
+static int cpus[MAX_SPINNERS], nr_cpus;
+static char exec_path[PATH_MAX];
+
+static long long now_us(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
+}
+
+static void busy_wait_us(int us)
+{
+ long long end = now_us() + us;
+
+ while (now_us() < end)
+ ;
+}
+
+/* Join @t. Return 0, or the error number after reporting it. */
+static int join_thread(pthread_t t)
+{
+ int err = pthread_join(t, NULL);
+
+ if (err)
+ fprintf(stderr, "pthread_join: %s\n", strerror(err));
+ return err;
+}
+
+/* Remove @path. Return 0, or -1 after reporting the error. */
+static int remove_file(const char *path)
+{
+ if (unlink(path)) {
+ fprintf(stderr, "unlink %s: %s\n", path, strerror(errno));
+ return -1;
+ }
+ return 0;
+}
+
+static int pin(int cpu)
+{
+ cpu_set_t set;
+
+ CPU_ZERO(&set);
+ CPU_SET(cpu, &set);
+ return sched_setaffinity(0, sizeof(set), &set);
+}
+
+/* Fill @cpus with the allowed CPUs. Return their number. */
+static int read_allowed_cpus(void)
+{
+ cpu_set_t set;
+ int cpu;
+
+ if (sched_getaffinity(0, sizeof(set), &set))
+ return -1;
+ nr_cpus = 0;
+ for (cpu = 0; cpu < CPU_SETSIZE && nr_cpus < MAX_SPINNERS; cpu++) {
+ if (CPU_ISSET(cpu, &set))
+ cpus[nr_cpus++] = cpu;
+ }
+ return CPU_COUNT(&set);
+}
+
+/*
+ * Create a script that names itself as its interpreter. execve(2) on it
+ * follows the interpreter a few times and fails with ELOOP. On a kernel
+ * where a failed execve(2) rejoins the mm, that keeps the task out of its
+ * mm longer than a file of unknown format. Return 0, or -1 if execve(2) on
+ * it does not fail with ELOOP.
+ */
+static int make_loop_script(void)
+{
+ char *const av[] = { exec_path, NULL };
+ FILE *f;
+
+ snprintf(exec_path, sizeof(exec_path), "/tmp/mm_cid_window_test.%d", getpid());
+ f = fopen(exec_path, "w");
+ if (!f)
+ return -1;
+ fprintf(f, "#!%s\n", exec_path);
+ if (fclose(f) || chmod(exec_path, 0755))
+ goto unlink;
+ if (execve(exec_path, av, NULL) == -1 && errno == ELOOP)
+ return 0;
+unlink:
+ remove_file(exec_path);
+ return -1;
+}
+
+/* Run thread B of case 1: call vfork(2) after a delay and wait for C. */
+static void *vfork_thread(void *arg)
+{
+ pid_t pid;
+
+ if (pin(cpus[1])) {
+ RSEQ_WRITE_ONCE(pin_failed, 1);
+ return NULL;
+ }
+ while (!RSEQ_READ_ONCE(go))
+ ;
+ busy_wait_us(delay_us);
+ pid = vfork();
+ if (!pid) {
+ long long end = now_us() + SPIN_MS * 1000;
+
+ /* Hold an ID on this CPU without scheduling. */
+ while (!RSEQ_READ_ONCE(done) && now_us() < end)
+ ;
+ _exit(0);
+ }
+ if (pid < 0 || waitpid(pid, NULL, 0) != pid) {
+ fprintf(stderr, "vfork: %s\n", strerror(errno));
+ abort();
+ }
+ return NULL;
+}
+
+/*
+ * Run one attempt of case 1 in a new mm on two CPUs. Return a CHILD_*
+ * status.
+ */
+static int run_child_join(int us)
+{
+ char *const av[] = { exec_path, NULL };
+ long long start, end;
+ unsigned int cid;
+ pthread_t b;
+ int err, exec_errno;
+
+ delay_us = us;
+ if (read_allowed_cpus() != 2 || pin(cpus[0]))
+ return CHILD_ERROR;
+ if (make_loop_script()) {
+ fprintf(stderr, "cannot run a script from /tmp\n");
+ return CHILD_SKIP;
+ }
+ if (pthread_create(&b, NULL, vfork_thread, NULL)) {
+ remove_file(exec_path);
+ return CHILD_ERROR;
+ }
+ usleep(200);
+ start = now_us();
+ RSEQ_WRITE_ONCE(go, 1);
+ execve(exec_path, av, NULL);
+ exec_errno = errno;
+ end = now_us();
+ cid = rseq_current_mm_cid();
+ RSEQ_WRITE_ONCE(done, 1);
+ err = join_thread(b);
+ if (remove_file(exec_path) || err)
+ return CHILD_ERROR;
+ if (exec_errno != ELOOP) {
+ fprintf(stderr, "execve(%s): %s, expected ELOOP\n",
+ exec_path, strerror(exec_errno));
+ return CHILD_ERROR;
+ }
+
+ /* B did not run its part if it could not pin itself. */
+ if (pin_failed) {
+ fprintf(stderr, "a thread could not pin itself\n");
+ return CHILD_ERROR;
+ }
+ /* The number of possible CPUs is the only bound. Two is a target. */
+ if (cid >= (unsigned int)nr_possible) {
+ fprintf(stderr, "mm_cid %u after a failed execve, %d possible CPUs\n",
+ cid, nr_possible);
+ return CHILD_FAIL;
+ }
+ if (cid >= 2)
+ fprintf(stderr,
+ "mm_cid %u after a failed execve, reaches the 2 allowed CPUs\n",
+ cid);
+ if (end - start > SLOW_MS * 1000) {
+ fprintf(stderr, "the failed execve took %lld ms\n", (end - start) / 1000);
+ return CHILD_FAIL;
+ }
+ return CHILD_PASS;
+}
+
+/* Spin on the CPU cpus[@arg], as a thread of case 2. Thread 1 also moves. */
+static void *spinner(void *arg)
+{
+ int nr = (long)arg;
+
+ if (pin(cpus[nr])) {
+ RSEQ_WRITE_ONCE(pin_failed, 1);
+ return NULL;
+ }
+ __atomic_add_fetch(&ready, 1, __ATOMIC_RELAXED);
+ while (!RSEQ_READ_ONCE(stop)) {
+ if (nr != 1 || !RSEQ_READ_ONCE(go) || RSEQ_READ_ONCE(moved))
+ continue;
+ busy_wait_us(delay_us);
+ /* Schedule out and in on this CPU, with the new mode set. */
+ usleep(1000);
+ /* Move to the CPU of thread 2, which still holds its own ID. */
+ if (pin(cpus[2]))
+ RSEQ_WRITE_ONCE(pin_failed, 1);
+ RSEQ_WRITE_ONCE(moved, 1);
+ }
+ return NULL;
+}
+
+static void *idler(void *arg)
+{
+ while (!RSEQ_READ_ONCE(stop))
+ usleep(1000);
+ return NULL;
+}
+
+/*
+ * Run one attempt of case 2 in a new mm on all CPUs. Return a CHILD_*
+ * status.
+ */
+static int run_child_migrate(int us)
+{
+ static pthread_t threads[MAX_SPINNERS];
+ int i, started = 0, waited = 0, ret = CHILD_PASS;
+ pthread_t extra;
+
+ delay_us = us;
+ if (read_allowed_cpus() < 3 || pin(cpus[0]))
+ return CHILD_ERROR;
+ for (i = 1; i < nr_cpus; i++) {
+ if (pthread_create(&threads[i], NULL, spinner, (void *)(long)i))
+ break;
+ started++;
+ }
+ if (started < nr_cpus - 1) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ /*
+ * Wait until every thread runs on its CPU and holds an ID. A thread
+ * whose pin failed sets pin_failed and never gets ready.
+ */
+ while (RSEQ_READ_ONCE(ready) < started && !RSEQ_READ_ONCE(pin_failed))
+ usleep(100);
+ if (RSEQ_READ_ONCE(pin_failed))
+ goto out;
+ usleep(1000);
+ RSEQ_WRITE_ONCE(go, 1);
+ if (pthread_create(&extra, NULL, idler, NULL)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ while (!RSEQ_READ_ONCE(moved) && waited++ < MOVE_WAIT_MS)
+ usleep(1000);
+ if (!RSEQ_READ_ONCE(moved)) {
+ fprintf(stderr, "the moving thread did not move\n");
+ ret = CHILD_FAIL;
+ }
+ RSEQ_WRITE_ONCE(stop, 1);
+ if (join_thread(extra) && ret == CHILD_PASS)
+ ret = CHILD_ERROR;
+out:
+ RSEQ_WRITE_ONCE(stop, 1);
+ for (i = 1; i <= started; i++) {
+ if (join_thread(threads[i]) && ret == CHILD_PASS)
+ ret = CHILD_ERROR;
+ }
+ /* The sequence did not run as written if a thread could not pin itself. */
+ if (pin_failed) {
+ fprintf(stderr, "a thread could not pin itself\n");
+ ret = CHILD_ERROR;
+ }
+ return ret;
+}
+
+static int read_nr_possible(void)
+{
+ int first, last, total = 0;
+ char sep;
+ FILE *f;
+
+ f = fopen("/sys/devices/system/cpu/possible", "r");
+ if (!f)
+ return -1;
+ /* A list of ranges: "0-63" or "0,2-5". */
+ while (fscanf(f, "%d", &first) == 1) {
+ last = first;
+ sep = '\n';
+ if (fscanf(f, "%c", &sep) == 1 && sep == '-') {
+ if (fscanf(f, "%d", &last) != 1)
+ break;
+ if (fscanf(f, "%c", &sep) != 1)
+ sep = '\n';
+ }
+ total += last - first + 1;
+ if (sep != ',')
+ break;
+ }
+ fclose(f);
+ return total;
+}
+
+/*
+ * Run @fn(@arg) in a new process that starts on the CPUs in @start, and
+ * return its exit status. The new process dies with this one.
+ */
+static int run_under_test(int (*fn)(int), int arg, const cpu_set_t *start,
+ const cpu_set_t *all)
+{
+ int status = 0;
+ pid_t child;
+
+ if (sched_setaffinity(0, sizeof(*start), start))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ child = fork();
+ if (!child) {
+ if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
+ fprintf(stderr, "prctl(PR_SET_PDEATHSIG): %s\n", strerror(errno));
+ _exit(CHILD_ERROR);
+ }
+ _exit(fn(arg));
+ }
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ if (sched_setaffinity(0, sizeof(*all), all))
+ ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ if (!WIFEXITED(status))
+ ksft_exit_fail_msg("the process under test was killed by signal %d\n",
+ WTERMSIG(status));
+ if (WEXITSTATUS(status) == CHILD_ERROR)
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ return WEXITSTATUS(status);
+}
+
+static void report(int status, const char *name)
+{
+ if (status == CHILD_SKIP)
+ ksft_test_result_skip("%s\n", name);
+ else
+ ksft_test_result(status == CHILD_PASS, "%s\n", name);
+}
+
+int main(void)
+{
+ const char *join = "failed execve switches to per CPU mode";
+ const char *migrate = "thread migrates during the switch to per CPU mode";
+ cpu_set_t all, two;
+ int status, i, cpu, nr_all;
+
+ ksft_print_header();
+ ksft_set_plan(2);
+
+ if (!rseq_available())
+ ksft_exit_skip("rseq is unavailable\n");
+ if (rseq_register_current_thread())
+ ksft_exit_fail_msg("rseq_register_current_thread: %s\n", strerror(errno));
+ if (!rseq_mm_cid_available())
+ ksft_exit_skip("the rseq mm_cid field is unavailable\n");
+ if (sched_getaffinity(0, sizeof(all), &all))
+ ksft_exit_fail_msg("sched_getaffinity: %s\n", strerror(errno));
+ nr_all = CPU_COUNT(&all);
+ nr_possible = read_nr_possible();
+ if (nr_possible <= 0)
+ ksft_exit_skip("cannot read the possible CPUs\n");
+
+ if (nr_all < 2) {
+ ksft_test_result_skip("%s: fewer than 2 CPUs\n", join);
+ } else {
+ CPU_ZERO(&two);
+ for (cpu = 0; cpu < CPU_SETSIZE && CPU_COUNT(&two) < 2; cpu++) {
+ if (CPU_ISSET(cpu, &all))
+ CPU_SET(cpu, &two);
+ }
+ for (i = 0; i < ATTEMPTS; i++) {
+ status = run_under_test(run_child_join, (i * 37) % MAX_DELAY_US,
+ &two, &all);
+ if (status != CHILD_PASS)
+ break;
+ }
+ report(status, join);
+ }
+
+ /* Every ID is taken only when one thread spins on each possible CPU. */
+ if (nr_all < 3 || nr_all > MAX_SPINNERS || nr_all != nr_possible) {
+ ksft_test_result_skip("%s: needs 3 to %d CPUs, all of them allowed\n",
+ migrate, MAX_SPINNERS);
+ } else {
+ for (i = 0; i < ATTEMPTS; i++) {
+ status = run_under_test(run_child_migrate, (i * 37) % MAX_DELAY_US,
+ &all, &all);
+ if (status != CHILD_PASS)
+ break;
+ }
+ report(status, migrate);
+ }
+ ksft_finished();
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 11/13] selftests/rseq: Test the last user after an affinity change during execve
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (9 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 10/13] selftests/rseq: Test two race windows of the concurrency ID mode switches Mathieu Desnoyers
@ 2026-12-02 0:27 ` Mathieu Desnoyers
2026-12-02 0:28 ` [PATCH v2 12/13] selftests/rseq: Test the concurrency IDs with an io_uring SQPOLL thread Mathieu Desnoyers
2026-12-02 0:28 ` [PATCH v2 13/13] selftests/rseq: Test the concurrency IDs after clone3() into a wider cpuset Mathieu Desnoyers
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:27 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
On tip sched/urgent, a failed execve() makes the task leave the mm and
join it again. If the task leaves as the last user in per CPU mode, the
other CPUs keep their CIDs. The rejoin then leaks a CID.
Per CPU mode lasts down to one thread only when mm_cid_calc_pcpu_thrs()
returns 1. It does with two or three possible CPUs, or when
mm->mm_cid.nr_cpus_allowed is 1. With one allowed CPU, no other CPU
should own a CID.
Another CPU can own one when the mm misses an affinity change, on a
machine of any size. mm_update_cpus_allowed() ignores a change while the
mm has no user. A single-threaded process has no user inside a failed
execve().
Add a case to mm_cid_execve_test which leaks a CID this way. A helper
process changes the affinity of the process under test during its failed
execve() calls. The comment above run_child_widened() has the sequence
as a diagram. The process must read mm_cid 0 on both CPUs at the end.
Each affinity change must land inside an execve(). So the case runs up
to 100 times, each time with another delay. An attempt that cannot set
up the sequence skips, and the next one runs. The case skips only when
every attempt skips.
On tip sched/urgent, the case ran three times on 12 guests with 2 to 64
CPUs. It failed on 7, 10 and 9 guests:
single thread, mm_cid 1 on CPU 0 after a move from CPU 1 to CPU 0
not ok 2 mm_cid of a single thread after its affinity was widened during execve
It passes on every guest after "sched/mmcid: Move the execve() hooks
into exec_mmap()". A failed execve() then no longer leaves the mm, so
the affinity changes reach it.
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
.../selftests/rseq/mm_cid_execve_test.c | 361 ++++++++++++++++--
1 file changed, 330 insertions(+), 31 deletions(-)
diff --git a/tools/testing/selftests/rseq/mm_cid_execve_test.c b/tools/testing/selftests/rseq/mm_cid_execve_test.c
index 1a27494297bc..74b7ecdacd9a 100644
--- a/tools/testing/selftests/rseq/mm_cid_execve_test.c
+++ b/tools/testing/selftests/rseq/mm_cid_execve_test.c
@@ -13,6 +13,13 @@
* failure. In per CPU mode, it then returned to user space with no CID, and
* read 0x80000000.
*
+ * A second case covers the last user of the mm. The kernel keeps per CPU
+ * mode down to one thread when the mm counts one allowed CPU. The case
+ * makes such a thread run on a second CPU, which the mm does not count.
+ * Before "sched/mmcid: Move the execve() hooks into exec_mmap()", this
+ * leaked a CID. The comment above run_child_widened() has the sequence as
+ * a diagram.
+ *
* Per CPU mode needs more threads than the mm has CIDs. The number of CIDs
* follows the union of the allowed CPUs of the threads, which only grows.
* The affinity is therefore narrowed before the fork(2) that creates the
@@ -24,12 +31,15 @@
#include <limits.h>
#include <pthread.h>
#include <sched.h>
+#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
+#include <time.h>
#include <unistd.h>
#include "rseq.h"
@@ -38,6 +48,8 @@
#define NARROW_CPUS 2
#define THREADS 4
#define ROUNDS 100
+#define ATTEMPTS 50
+#define MOVE_EXECS 300
/* Exit status of the process under test. */
#define CHILD_PASS 0
@@ -217,6 +229,245 @@ static int run_child(void)
return ret;
}
+/* Run on @cpu and return the mm_cid read there. */
+static unsigned int cid_on_cpu(int cpu)
+{
+ cpu_set_t one;
+
+ CPU_ZERO(&one);
+ CPU_SET(cpu, &one);
+ if (sched_setaffinity(0, sizeof(one), &one))
+ return UINT_MAX;
+ return rseq_current_mm_cid();
+}
+
+/* What the process under test and its helper share in run_child_widened(). */
+struct widen_shared {
+ int phase;
+ int widened;
+};
+
+static int widen_cpu[NARROW_CPUS];
+
+static uint64_t now_ms(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
+/* Spin until @sh->phase reaches @phase. Return false after two seconds. */
+static bool widen_wait(struct widen_shared *sh, int phase)
+{
+ uint64_t end = now_ms() + 2000;
+
+ while (RSEQ_READ_ONCE(sh->phase) < phase) {
+ if (now_ms() > end)
+ return false;
+ }
+ return true;
+}
+
+/*
+ * The helper of run_child_widened(). @pid is the process under test, which
+ * starts on the CPU @a.
+ * - Phase 1: widen the affinity of @pid to @a and @b, @delay_us after the
+ * start of its first execve(2) loop.
+ * - Phase 2: keep the CPU @a busy, so that the scheduler moves @pid to @b.
+ * - Phase 3: move @pid back to @a, @delay_us after the start of its second
+ * execve(2) loop.
+ * Return the exit status of the helper.
+ */
+static int widen_helper(struct widen_shared *sh, pid_t pid, int a, int b, int delay_us)
+{
+ cpu_set_t set;
+
+ /* Run beside the process under test, not on its CPU. */
+ CPU_ZERO(&set);
+ CPU_SET(b, &set);
+ if (sched_setaffinity(0, sizeof(set), &set) || !widen_wait(sh, 1))
+ return 1;
+ usleep(delay_us);
+ CPU_SET(a, &set);
+ if (sched_setaffinity(pid, sizeof(set), &set))
+ return 1;
+ RSEQ_WRITE_ONCE(sh->widened, 1);
+
+ if (!widen_wait(sh, 2))
+ return 1;
+ CPU_ZERO(&set);
+ CPU_SET(a, &set);
+ if (sched_setaffinity(0, sizeof(set), &set) || !widen_wait(sh, 3))
+ return 1;
+ usleep(delay_us);
+ return !!sched_setaffinity(pid, sizeof(set), &set);
+}
+
+/*
+ * Fail execve(2) on @path MOVE_EXECS times. Return 0, or -1 after reporting
+ * an error other than ENOEXEC.
+ */
+static int fail_execs(char *path)
+{
+ int i;
+
+ for (i = 0; i < MOVE_EXECS; i++) {
+ char *const av[] = { path, NULL };
+
+ if (execve(path, av, NULL) == -1 && errno != ENOEXEC) {
+ fprintf(stderr, "execve(%s): %s, expected ENOEXEC\n",
+ path, strerror(errno));
+ return -1;
+ }
+ }
+ return 0;
+}
+
+/*
+ * The second process under test, P. The test forks it with one allowed
+ * CPU, A, so its mm counts one allowed CPU. B is a second CPU. P forks a
+ * helper process, H, to make the affinity changes. A change made by P
+ * itself would reach the mm. T is a thread of P. T can run on A or on B,
+ * with the same outcome.
+ *
+ * Before "sched/mmcid: Move the execve() hooks into exec_mmap()", a failed
+ * execve(2) left the mm and rejoined it. P then leaked a CID:
+ *
+ * CPU A CPU B
+ *
+ * H: sched_setaffinity(H, {B})
+ * P: execve(), fails with ENOEXEC
+ * sched_mm_cid_before_execve()
+ * mm_cid.users = 0
+ * H: sched_setaffinity(P, {A, B})
+ * mm_update_cpus_allowed()
+ * mm_cid.users is 0: return
+ * nr_cpus_allowed stays 1
+ * H: spins
+ * sched_mm_cid_after_execve()
+ * mm_cid.users = 1, P gets CID 0
+ * P: pthread_create(T)
+ * sched_mm_cid_fork(T)
+ * users 2 > max_cids 1: per CPU mode
+ * A owns CID 0
+ * T: exits
+ * sched_mm_cid_exit(T)
+ * users 1, not below pcpu_thrs 1:
+ * still per CPU mode
+ * H: sched_setaffinity(H, {A})
+ * H: spins
+ * P: moved to B by the scheduler
+ * mm_cid_schedin(): B owns CID 1
+ * P: execve(), fails with ENOEXEC
+ * sched_mm_cid_before_execve()
+ * mm_cid.users = 0
+ * CID 1 freed, A keeps CID 0
+ * H: sched_setaffinity(P, {A})
+ * P: moved to A
+ * sched_mm_cid_after_execve()
+ * mm_get_cid(): CID 0 taken, so CID 1
+ * A now owns CID 1: CID 0 leaks
+ * P: reads mm_cid 1 on A
+ *
+ * Since that change, a failed execve(2) stays in the mm. Both changes of
+ * H then reach it.
+ *
+ * P must read 0 on both CPUs at the end. Each change of H has to land
+ * while P is inside an execve(2). So the case runs many times, each time
+ * with another delay.
+ *
+ * Return a CHILD_* status.
+ */
+static int run_child_widened(int delay_us)
+{
+ int a = widen_cpu[0], b = widen_cpu[1], i, status, ret = CHILD_PASS;
+ struct widen_shared *sh;
+ pid_t helper, self = getpid();
+ char path[PATH_MAX];
+ pthread_t thread;
+ uint64_t end;
+
+ sh = mmap(NULL, sizeof(*sh), PROT_READ | PROT_WRITE,
+ MAP_SHARED | MAP_ANONYMOUS, -1, 0);
+ if (sh == MAP_FAILED)
+ return CHILD_ERROR;
+ if (make_unknown_format_file(path, sizeof(path))) {
+ fprintf(stderr, "no directory to run an unknown format file from\n");
+ return CHILD_SKIP;
+ }
+ helper = fork();
+ if (helper < 0) {
+ remove_file(path);
+ return CHILD_ERROR;
+ }
+ if (!helper)
+ _exit(widen_helper(sh, self, a, b, delay_us));
+
+ RSEQ_WRITE_ONCE(sh->phase, 1);
+ if (fail_execs(path)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ end = now_ms() + 2000;
+ while (!RSEQ_READ_ONCE(sh->widened) && now_ms() < end)
+ ;
+ if (!RSEQ_READ_ONCE(sh->widened)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+
+ if (pthread_create(&thread, NULL, waiter, NULL)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ RSEQ_WRITE_ONCE(stop, 1);
+ if (join_thread(thread)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+
+ /* No affinity change by this process: it would reach the mm. */
+ RSEQ_WRITE_ONCE(sh->phase, 2);
+ end = now_ms() + 2000;
+ while (sched_getcpu() != b && now_ms() < end)
+ ;
+ if (sched_getcpu() != b) {
+ fprintf(stderr, "the scheduler did not move the process to CPU %d\n", b);
+ ret = CHILD_SKIP;
+ goto out;
+ }
+
+ RSEQ_WRITE_ONCE(sh->phase, 3);
+ if (fail_execs(path)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+out:
+ if (ret != CHILD_PASS)
+ kill(helper, SIGKILL);
+ if (waitpid(helper, &status, 0) != helper ||
+ (ret == CHILD_PASS && (!WIFEXITED(status) || WEXITSTATUS(status))))
+ ret = CHILD_ERROR;
+ if (remove_file(path) && ret == CHILD_PASS)
+ ret = CHILD_ERROR;
+
+ /* The first visit lets the kernel settle, the second one is judged. */
+ for (i = 0; i < 2 * NARROW_CPUS && ret == CHILD_PASS; i++) {
+ unsigned int cid = cid_on_cpu(widen_cpu[i % NARROW_CPUS]);
+
+ if (cid == UINT_MAX) {
+ ret = CHILD_ERROR;
+ } else if (i >= NARROW_CPUS && cid) {
+ fprintf(stderr,
+ "single thread, mm_cid %u on CPU %d after a move from CPU %d to CPU %d\n",
+ cid, widen_cpu[i % NARROW_CPUS], b, a);
+ ret = CHILD_FAIL;
+ }
+ }
+ return ret;
+}
+
static int read_nr_possible(void)
{
int first, last, total = 0;
@@ -259,61 +510,109 @@ static int narrow_cpus(cpu_set_t *dst, const cpu_set_t *src, int nr)
return taken;
}
-int main(void)
+/*
+ * Run @fn(@arg) in a new process and return its exit status. The affinity
+ * is @narrow when its mm is created. The union of allowed CPUs of an mm
+ * starts there and only grows.
+ */
+static int run_under_test(int (*fn)(int), int arg, const cpu_set_t *narrow,
+ const cpu_set_t *allowed)
{
- cpu_set_t allowed, narrow;
int status = 0;
pid_t child;
- ksft_print_header();
- ksft_set_plan(1);
-
- if (!rseq_available())
- ksft_exit_skip("rseq is unavailable\n");
- /* glibc before 2.35 registers no rseq area. */
- if (rseq_register_current_thread())
- ksft_exit_fail_msg("rseq_register_current_thread: %s\n", strerror(errno));
- if (!rseq_mm_cid_available())
- ksft_exit_skip("the rseq mm_cid field is unavailable\n");
- if (sched_getaffinity(0, sizeof(allowed), &allowed))
- ksft_exit_fail_msg("sched_getaffinity: %s\n", strerror(errno));
- nr_possible = read_nr_possible();
- if (nr_possible <= 0)
- ksft_exit_skip("cannot read the possible CPUs\n");
- if (!narrow_cpus(&narrow, &allowed, NARROW_CPUS))
- ksft_exit_skip("no CPU to run on\n");
-
- /*
- * Narrow before the fork(2). The mm of the child starts with these
- * allowed CPUs, and a later narrowing does not shrink them.
- */
- if (sched_setaffinity(0, sizeof(narrow), &narrow))
+ if (sched_setaffinity(0, sizeof(*narrow), narrow))
ksft_exit_skip("sched_setaffinity: %s\n", strerror(errno));
child = fork();
if (!child)
- _exit(run_child());
+ _exit(fn(arg));
if (child < 0)
ksft_exit_fail_msg("fork: %s\n", strerror(errno));
- if (sched_setaffinity(0, sizeof(allowed), &allowed))
+ if (sched_setaffinity(0, sizeof(*allowed), allowed))
ksft_exit_fail_msg("sched_setaffinity: %s\n", strerror(errno));
if (waitpid(child, &status, 0) != child)
ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
if (!WIFEXITED(status))
ksft_exit_fail_msg("the process under test was killed by signal %d\n",
WTERMSIG(status));
+ return WEXITSTATUS(status);
+}
- switch (WEXITSTATUS(status)) {
+static void report(int status, const char *name)
+{
+ switch (status) {
case CHILD_PASS:
- ksft_test_result_pass("mm_cid after a failed execve\n");
+ ksft_test_result_pass("%s\n", name);
break;
case CHILD_SKIP:
- ksft_test_result_skip("mm_cid after a failed execve\n");
+ ksft_test_result_skip("%s\n", name);
break;
case CHILD_FAIL:
- ksft_test_result_fail("mm_cid after a failed execve\n");
+ ksft_test_result_fail("%s\n", name);
break;
default:
ksft_exit_fail_msg("the process under test failed to run\n");
}
+}
+
+static int run_child_threads(int unused)
+{
+ return run_child();
+}
+
+int main(void)
+{
+ static const char widened[] =
+ "mm_cid of a single thread after its affinity was widened during execve";
+ cpu_set_t allowed, narrow, one;
+ int status, i, cpu, nr = 0, passed = 0;
+
+ ksft_print_header();
+ ksft_set_plan(2);
+
+ if (!rseq_available())
+ ksft_exit_skip("rseq is unavailable\n");
+ /* glibc before 2.35 registers no rseq area. */
+ if (rseq_register_current_thread())
+ ksft_exit_fail_msg("rseq_register_current_thread: %s\n", strerror(errno));
+ if (!rseq_mm_cid_available())
+ ksft_exit_skip("the rseq mm_cid field is unavailable\n");
+ if (sched_getaffinity(0, sizeof(allowed), &allowed))
+ ksft_exit_fail_msg("sched_getaffinity: %s\n", strerror(errno));
+ nr_possible = read_nr_possible();
+ if (nr_possible <= 0)
+ ksft_exit_skip("cannot read the possible CPUs\n");
+ if (!narrow_cpus(&narrow, &allowed, NARROW_CPUS))
+ ksft_exit_skip("no CPU to run on\n");
+
+ status = run_under_test(run_child_threads, 0, &narrow, &allowed);
+ report(status, "mm_cid after a failed execve");
+
+ for (cpu = 0; cpu < CPU_SETSIZE && nr < NARROW_CPUS; cpu++) {
+ if (CPU_ISSET(cpu, &narrow))
+ widen_cpu[nr++] = cpu;
+ }
+ if (nr < NARROW_CPUS) {
+ ksft_test_result_skip("%s: fewer than %d CPUs\n", widened, NARROW_CPUS);
+ ksft_finished();
+ }
+ narrow_cpus(&one, &allowed, 1);
+ /*
+ * Both changes of the helper have to land inside an execve. An attempt
+ * that skips does not end the case. The case skips only when every
+ * attempt skips.
+ */
+ for (i = 0; i < 2 * ATTEMPTS; i++) {
+ status = run_under_test(run_child_widened, (i * 37) % 1000, &one, &allowed);
+ if (status == CHILD_PASS)
+ passed++;
+ else if (status != CHILD_SKIP)
+ break;
+ }
+ if (i == 2 * ATTEMPTS && passed < i)
+ ksft_print_msg("%d of %d attempts skipped\n", i - passed, i);
+ if (status == CHILD_SKIP && passed)
+ status = CHILD_PASS;
+ report(status, widened);
ksft_finished();
}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 12/13] selftests/rseq: Test the concurrency IDs with an io_uring SQPOLL thread
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (10 preceding siblings ...)
2026-12-02 0:27 ` [PATCH v2 11/13] selftests/rseq: Test the last user after an affinity change during execve Mathieu Desnoyers
@ 2026-12-02 0:28 ` Mathieu Desnoyers
2026-12-02 0:28 ` [PATCH v2 13/13] selftests/rseq: Test the concurrency IDs after clone3() into a wider cpuset Mathieu Desnoyers
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:28 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
An io_uring SQPOLL thread is a user worker of the process that creates
the ring. When it starts, it calls set_cpus_allowed_ptr() with all
online CPUs, unless the ring pins it to one CPU with
IORING_SETUP_SQ_AFF. It counts as a user of the CIDs, so these CPUs
widen the allowed CPUs of the mm. A process limited by a cpuset then
gets CIDs for more CPUs than its threads may use.
Add the case "io_uring SQPOLL thread in a cpuset of 2 CPUs" to
mm_cid_bound_test. A process in a cpuset of two CPUs creates a ring with
an SQPOLL thread, then starts two worker threads. The main thread and
the two workers must read an mm_cid below 2. As in the other cases of
this test, that is a target: a miss is printed. The case fails only at
or above the number of possible CPUs.
Two details of the setup matter:
- The process is forked in the cpuset, not moved there. The allowed
CPUs of an mm only grow, so a moved process keeps those it had.
- The ring is created before the main thread calls sched_setaffinity()
to visit the CPUs. The SQPOLL thread would otherwise inherit the mask
which sched_setaffinity() requested. set_cpus_allowed_ptr() keeps a
task within that mask. So the thread would stay on the two CPUs and
hide the widening.
The test declares its own copy of struct io_uring_params. The
tools/include of these tests hides the uapi stddef.h which
<linux/io_uring.h> needs. The case needs more than 2 CPUs, root, the
cgroup v2 cpuset controller and io_uring. It skips without them.
The case ran three times on ten guests with 3 to 64 CPUs. On tip
sched/urgent, the target was missed in 27 of the 30 runs. On the 64-CPU
guest:
# 3 threads on 2 CPUs and SQPOLL: largest mm_cid 3 on CPU 1, above the CPU count target
It was met in all 30 runs after "sched/mmcid: Give no concurrency ID
to user workers", with a largest mm_cid of 1.
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
.../selftests/rseq/mm_cid_bound_test.c | 248 +++++++++++++++++-
1 file changed, 247 insertions(+), 1 deletion(-)
diff --git a/tools/testing/selftests/rseq/mm_cid_bound_test.c b/tools/testing/selftests/rseq/mm_cid_bound_test.c
index 9795cc030e7f..e39f0aafad31 100644
--- a/tools/testing/selftests/rseq/mm_cid_bound_test.c
+++ b/tools/testing/selftests/rseq/mm_cid_bound_test.c
@@ -33,16 +33,28 @@
* IDs. The threads are then allowed on all CPUs. The kernel aims at giving
* the IDs back to the tasks, so that three threads read an mm_cid below 3.
* That is a target too: the case prints when it is missed.
+ *
+ * The io_uring case runs three threads and an io_uring SQPOLL thread in a
+ * cpuset of two CPUs. The SQPOLL thread is a user worker (PF_USER_WORKER).
+ * It never returns to user space and reads no mm_cid. It allows itself
+ * all online CPUs, and these must not widen the allowed CPUs of the mm.
+ * The CPUs then keep owning the IDs, and the three threads read an mm_cid
+ * below 2. That is a target as well. The case needs root and the
+ * cgroup v2 cpuset controller.
*/
#define _GNU_SOURCE
#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
@@ -54,6 +66,29 @@
#define WIDEN_THREADS 3
#define WIDEN_MIN_CPUS 8
#define WIDEN_SETTLE_US 20000
+#define URING_CPUS 2
+#define CHILD_SKIP 32
+
+/*
+ * struct io_uring_params of <linux/io_uring.h>. The tools/include of
+ * these tests hides the uapi stddef.h that this header needs.
+ */
+#define IORING_SETUP_SQPOLL (1U << 1)
+struct uring_params {
+ unsigned int sq_entries;
+ unsigned int cq_entries;
+ unsigned int flags;
+ unsigned int sq_thread_cpu;
+ unsigned int sq_thread_idle;
+ unsigned int features;
+ unsigned int wq_fd;
+ unsigned int resv[3];
+ unsigned int sq_off[8];
+ unsigned long long sq_user_addr;
+ unsigned int cq_off[8];
+ unsigned long long cq_user_addr;
+};
+_Static_assert(sizeof(struct uring_params) == 120, "struct io_uring_params");
/*
* Exit status of the process under test: a mask of the bound and of the
@@ -282,6 +317,57 @@ static int run_child_widen(void)
return ret;
}
+/*
+ * The process under test of the io_uring case. It starts on two CPUs.
+ * Return a mask of the OVER_* values, or CHILD_SKIP without io_uring.
+ */
+static int run_child_uring(void)
+{
+ struct uring_params params;
+ int nr_workers = 0, ret = 0, cpu, fd;
+ unsigned int cid;
+
+ if (sched_getaffinity(0, sizeof(allowed), &allowed))
+ return CHILD_ERROR;
+ nr_allowed = CPU_COUNT(&allowed);
+
+ /*
+ * Create the ring before tour() calls sched_setaffinity(). The SQPOLL
+ * thread inherits the mask which sched_setaffinity() requested, and
+ * its set_cpus_allowed_ptr() stays within it. It would then stay on
+ * the two CPUs and not widen the mm.
+ */
+ memset(¶ms, 0, sizeof(params));
+ params.flags = IORING_SETUP_SQPOLL;
+ params.sq_thread_idle = 1000;
+ fd = syscall(__NR_io_uring_setup, 4, ¶ms);
+ if (fd < 0) {
+ ksft_print_msg("io_uring_setup: %s\n", strerror(errno));
+ return CHILD_SKIP;
+ }
+ if (set_workers(&nr_workers, WIDEN_THREADS - 1)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ measure(nr_workers, &cpu);
+ /* The kernel changes the owners of the IDs from a work item. */
+ usleep(WIDEN_SETTLE_US);
+ measure(nr_workers, &cpu);
+ cid = measure(nr_workers, &cpu);
+ if (cid >= (unsigned int)nr_possible)
+ ret |= OVER_POSSIBLE;
+ if (cid >= URING_CPUS)
+ ret |= OVER_STRICT;
+ ksft_print_msg("%4d threads on %d CPUs and SQPOLL: largest mm_cid %u on CPU %d%s\n",
+ WIDEN_THREADS, nr_allowed, cid, cpu,
+ ret & OVER_STRICT ? ", above the CPU count target" : "");
+out:
+ if (set_workers(&nr_workers, 0))
+ ret |= CHILD_ERROR;
+ close(fd);
+ return ret;
+}
+
/* Keep the first @nr CPUs of @src in @dst. */
static int narrow_cpus(cpu_set_t *dst, const cpu_set_t *src, int nr)
{
@@ -413,13 +499,172 @@ static void test_widen(const cpu_set_t *all)
ksft_test_result(!(WEXITSTATUS(status) & OVER_POSSIBLE), "%s\n", name);
}
+/* Write @val to the file @name of the directory @dir. Return 0 or -1. */
+static int write_file(const char *dir, const char *name, const char *val)
+{
+ char path[PATH_MAX];
+ ssize_t len = strlen(val);
+ int fd, ret = 0;
+
+ snprintf(path, sizeof(path), "%s/%s", dir, name);
+ fd = open(path, O_WRONLY);
+ if (fd < 0)
+ return -1;
+ if (write(fd, val, len) != len)
+ ret = -1;
+ close(fd);
+ return ret;
+}
+
+/* Read the file @name of @dir into @buf. Return 0 or -1. */
+static int read_file(const char *dir, const char *name, char *buf, size_t size)
+{
+ char path[PATH_MAX];
+ ssize_t len;
+ int fd;
+
+ snprintf(path, sizeof(path), "%s/%s", dir, name);
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -1;
+ len = read(fd, buf, size - 1);
+ close(fd);
+ if (len < 0)
+ return -1;
+ buf[len] = '\0';
+ return 0;
+}
+
+/* Find the mount point of cgroup v2 in @root. Return 0 or -1. */
+static int find_cgroup2(char *root, size_t size)
+{
+ char line[PATH_MAX + 128], dir[PATH_MAX], type[64];
+ FILE *f = fopen("/proc/self/mounts", "r");
+ int ret = -1;
+
+ while (f && ret && fgets(line, sizeof(line), f)) {
+ if (sscanf(line, "%*s %4095s %63s", dir, type) == 2 &&
+ !strcmp(type, "cgroup2")) {
+ snprintf(root, size, "%s", dir);
+ ret = 0;
+ }
+ }
+ if (f)
+ fclose(f);
+ return ret;
+}
+
+/*
+ * Make the cpuset @cg of two CPUs of @all, under the cgroup v2 root
+ * @root. Set *@added if the cpuset controller had to be enabled. Return
+ * 0, or -1 if the system has no such cpuset.
+ */
+static int make_cpuset(const char *root, char *cg, size_t size,
+ const cpu_set_t *all, bool *added)
+{
+ char buf[256], cpus[32];
+ cpu_set_t two;
+ int cpu, n = 0;
+
+ *added = false;
+ if (read_file(root, "cgroup.controllers", buf, sizeof(buf)) ||
+ !strstr(buf, "cpuset"))
+ return -1;
+ if (read_file(root, "cgroup.subtree_control", buf, sizeof(buf)))
+ return -1;
+ if (!strstr(buf, "cpuset")) {
+ if (write_file(root, "cgroup.subtree_control", "+cpuset"))
+ return -1;
+ *added = true;
+ }
+ snprintf(cg, size, "%s/mm_cid_bound_test", root);
+ if (mkdir(cg, 0755) && errno != EEXIST)
+ return -1;
+ narrow_cpus(&two, all, URING_CPUS);
+ for (cpu = 0; cpu < CPU_SETSIZE; cpu++) {
+ if (CPU_ISSET(cpu, &two))
+ n += snprintf(cpus + n, sizeof(cpus) - n, n ? ",%d" : "%d", cpu);
+ }
+ return write_file(cg, "cpuset.cpus", cpus);
+}
+
+static void remove_cpuset(const char *root, const char *cg, bool added)
+{
+ if (rmdir(cg))
+ ksft_print_msg("rmdir %s: %s\n", cg, strerror(errno));
+ if (added && write_file(root, "cgroup.subtree_control", "-cpuset"))
+ ksft_print_msg("the cpuset controller stays enabled\n");
+}
+
+static void test_uring(const cpu_set_t *all)
+{
+ const char *name = "io_uring SQPOLL thread in a cpuset of 2 CPUs: below the possible CPUs";
+ char root[PATH_MAX], cg[PATH_MAX + 32] = "";
+ bool added = false;
+ int status = 0;
+ pid_t child;
+
+ /* No CPU outside the cpuset: the SQPOLL thread cannot widen the mm. */
+ if (CPU_COUNT(all) <= URING_CPUS) {
+ ksft_test_result_skip("%s: needs more than %d CPUs\n", name, URING_CPUS);
+ return;
+ }
+ /* A cpuset, not sched_setaffinity(): see run_child_uring(). */
+ if (find_cgroup2(root, sizeof(root))) {
+ ksft_test_result_skip("%s: no cgroup v2\n", name);
+ return;
+ }
+ if (make_cpuset(root, cg, sizeof(cg), all, &added)) {
+ ksft_print_msg("cpuset of 2 CPUs: %s\n", strerror(errno));
+ if (cg[0])
+ rmdir(cg);
+ if (added)
+ write_file(root, "cgroup.subtree_control", "-cpuset");
+ ksft_test_result_skip("%s: no cgroup v2 cpuset\n", name);
+ return;
+ }
+ child = fork();
+ if (!child) {
+ pid_t pid;
+
+ if (write_file(cg, "cgroup.procs", "0"))
+ _exit(CHILD_ERROR);
+ /*
+ * The allowed CPUs of an mm only grow, so this one keeps all
+ * CPUs. A new mm starts with the two CPUs of the cpuset.
+ */
+ pid = fork();
+ if (!pid)
+ _exit(run_child_uring());
+ if (pid < 0 || waitpid(pid, &status, 0) != pid ||
+ !WIFEXITED(status))
+ _exit(CHILD_ERROR);
+ _exit(WEXITSTATUS(status));
+ }
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ remove_cpuset(root, cg, added);
+ if (!WIFEXITED(status) || (WEXITSTATUS(status) & CHILD_ERROR))
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ if (WEXITSTATUS(status) & CHILD_SKIP) {
+ ksft_test_result_skip("%s: no io_uring\n", name);
+ return;
+ }
+ /* The CPU count is a target. Only the bound decides the result. */
+ if (WEXITSTATUS(status) & OVER_STRICT)
+ ksft_print_msg("SQPOLL in a cpuset of 2 CPUs: above the CPU count target\n");
+ ksft_test_result(!(WEXITSTATUS(status) & OVER_POSSIBLE), "%s\n", name);
+}
+
int main(void)
{
cpu_set_t all;
int nr_all;
ksft_print_header();
- ksft_set_plan(4);
+ ksft_set_plan(5);
if (!rseq_available())
ksft_exit_skip("rseq is unavailable\n");
@@ -439,5 +684,6 @@ int main(void)
test_ramp(&all, 4, "4 CPUs");
test_ramp(&all, nr_all, "all CPUs");
test_widen(&all);
+ test_uring(&all);
ksft_finished();
}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [PATCH v2 13/13] selftests/rseq: Test the concurrency IDs after clone3() into a wider cpuset
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
` (11 preceding siblings ...)
2026-12-02 0:28 ` [PATCH v2 12/13] selftests/rseq: Test the concurrency IDs with an io_uring SQPOLL thread Mathieu Desnoyers
@ 2026-12-02 0:28 ` Mathieu Desnoyers
12 siblings, 0 replies; 14+ messages in thread
From: Mathieu Desnoyers @ 2026-12-02 0:28 UTC (permalink / raw)
To: tglx, peterz
Cc: Mathieu Desnoyers, linux-kernel, mingo, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, paulmck, boqun, shuah, kees, viro,
brauner, jack, oleg, bestswngs, xmei5, xujiakai24, linux-mm,
linux-fsdevel, linux-kselftest, kmehltretter
In per CPU mode, the CIDs go back to the tasks once the user count of
the mm drops below pcpu_thrs. This threshold grows with the allowed CPUs
of the mm. So mm_update_cpus_allowed() recomputes it when an affinity
change widens the mm.
clone3(CLONE_INTO_CGROUP) sets the CPUs of the new task in
cpuset_fork(), before the task joins in sched_mm_cid_fork(). Since
"sched/mmcid: Serialize joins and exits with affinity changes by
pi_lock", mm_update_cpus_allowed() ignores this change: the task has
not joined the mm yet. The join then widens the mm, and recomputes
pcpu_thrs (see "sched/mmcid: Add the allowed CPUs of each joining task
to the mm"). No later affinity change can do it, because the mm is
already wide.
Add the case "join from a wider cpuset" to mm_cid_bound_test. The
diagram shows it on a guest with 64 CPUs, with a join which does not
recompute pcpu_thrs. T0 is the main thread of the process under test,
forked in a cpuset of CPUs 0 and 1. T1 and T2 are its other threads.
C is a task which shares the mm of T0, created in a cpuset of all CPUs.
T0 T1, T2 C
-------------------------------------------- ------------- -------------------------
pthread_create(T1), pthread_create(T2)
sched_mm_cid_fork(T2): 3 users >
max_cids 2: per CPU mode, pcpu_thrs 2
tour(): visits CPUs 0 and 1 tour(): same
sched_setaffinity(all CPUs): the cpuset
keeps T0 on CPUs 0 and 1
clone3(CLONE_VM | CLONE_VFORK |
CLONE_INTO_CGROUP)
cpuset_fork(C):
set_cpus_allowed_ptr(C, CPUs 0-63)
mm_update_cpus_allowed(C):
C not active, return
sched_mm_cid_fork(C): nr_cpus_allowed
2 -> 64, 4 users >= pcpu_thrs 2:
stays in per CPU mode
waits for C (CLONE_VFORK) exit()
sched_mm_cid_exit(C):
3 users >= pcpu_thrs 2:
stays in per CPU mode
writes 0 to cgroup.procs of the wide cpuset
set_cpus_allowed_ptr(T0, T1, T2)
mm_update_cpus_allowed():
mm has 64 CPUs, return
tour(): visits CPUs 0 to 63 tour(): same
The CPUs keep the IDs, so the threads read mm_cid values up to 63. With
the recompute, the join sets pcpu_thrs to 32, and the mm goes back to
per task mode. The target is then an mm_cid below 3. As in the "widened
from 2 CPUs" case, a missed target only prints a note. The case fails
only on an mm_cid at or above the number of possible CPUs.
The case needs at least 8 CPUs, root and the cgroup v2 cpuset
controller. C runs on the stack of T0, as after vfork(2), so it must not
return or call a function. So clone3() and exit() are issued from inline
assembly, on x86-64 and arm64 only. The arm64 code was only compile-
tested.
The target is met on x86-64 guests with 8 to 64 CPUs, on tip
sched/urgent and after each kernel patch of this series. On tip, the
affinity change in cpuset_fork() still recomputes pcpu_thrs. To check
that the case catches a join without the recompute, the recompute was
removed from a kernel with the four kernel patches. The largest mm_cid
was then the CPU count minus one, on guests with 8, 16 and 64 CPUs:
# 3 threads after a join on 64 CPUs: largest mm_cid 63 on CPU 63, above the thread count target
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
.../selftests/rseq/mm_cid_bound_test.c | 245 +++++++++++++++++-
1 file changed, 244 insertions(+), 1 deletion(-)
diff --git a/tools/testing/selftests/rseq/mm_cid_bound_test.c b/tools/testing/selftests/rseq/mm_cid_bound_test.c
index e39f0aafad31..f6b554969cdc 100644
--- a/tools/testing/selftests/rseq/mm_cid_bound_test.c
+++ b/tools/testing/selftests/rseq/mm_cid_bound_test.c
@@ -41,6 +41,17 @@
* The CPUs then keep owning the IDs, and the three threads read an mm_cid
* below 2. That is a target as well. The case needs root and the
* cgroup v2 cpuset controller.
+ *
+ * The join case starts three threads in a cpuset of two CPUs, so the CPUs
+ * own the IDs. The main thread then creates a task with
+ * clone3(CLONE_VM | CLONE_VFORK | CLONE_INTO_CGROUP), into a cpuset of
+ * all CPUs. The kernel gives the new task all CPUs before it joins the mm
+ * in sched_mm_cid_fork(). So the join widens the allowed CPUs of the mm.
+ * The new task exits at once. The three threads then move to the cpuset
+ * of all CPUs. This adds no CPU to the mm: the join already added them.
+ * The kernel aims at giving the IDs back to the tasks, as in the widening
+ * case. The case prints when an mm_cid is not below 3. The case needs
+ * root and the cgroup v2 cpuset controller.
*/
#define _GNU_SOURCE
@@ -49,6 +60,7 @@
#include <limits.h>
#include <pthread.h>
#include <sched.h>
+#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
@@ -69,6 +81,29 @@
#define URING_CPUS 2
#define CHILD_SKIP 32
+#ifndef __NR_clone3
+#define __NR_clone3 435
+#endif
+#ifndef CLONE_INTO_CGROUP
+#define CLONE_INTO_CGROUP 0x200000000ULL
+#endif
+
+/* struct clone_args of <linux/sched.h>, up to its cgroup field. */
+struct clone_args_v2 {
+ unsigned long long flags;
+ unsigned long long pidfd;
+ unsigned long long child_tid;
+ unsigned long long parent_tid;
+ unsigned long long exit_signal;
+ unsigned long long stack;
+ unsigned long long stack_size;
+ unsigned long long tls;
+ unsigned long long set_tid;
+ unsigned long long set_tid_size;
+ unsigned long long cgroup;
+};
+_Static_assert(sizeof(struct clone_args_v2) == 88, "struct clone_args");
+
/*
* struct io_uring_params of <linux/io_uring.h>. The tools/include of
* these tests hides the uapi stddef.h that this header needs.
@@ -368,6 +403,121 @@ static int run_child_uring(void)
return ret;
}
+static int write_file_at(int dirfd, const char *name, const char *val);
+
+/*
+ * Create a task that shares the mm, in the cgroup of the directory
+ * @cgfd, and wait until it exits. The task runs on the stack of the
+ * caller, as after vfork(2), so it exits at once without a function
+ * call. Return its pid, or -errno.
+ */
+static long clone_vm_into_cgroup(int cgfd)
+{
+ struct clone_args_v2 args = {
+ .flags = CLONE_VM | CLONE_VFORK | CLONE_INTO_CGROUP,
+ .exit_signal = SIGCHLD,
+ .cgroup = cgfd,
+ };
+#if defined(__x86_64__)
+ long ret;
+
+ asm volatile ("syscall\n\t"
+ "test %%rax, %%rax\n\t"
+ "jnz 1f\n\t"
+ "mov %[nr_exit], %%eax\n\t"
+ "xor %%edi, %%edi\n\t"
+ "syscall\n\t"
+ "1:"
+ : "=a" (ret)
+ : "0" ((long)__NR_clone3), "D" (&args), "S" (sizeof(args)),
+ [nr_exit] "i" (__NR_exit)
+ : "rcx", "r11", "memory");
+ return ret;
+#elif defined(__aarch64__)
+ register long x0 asm("x0") = (long)&args;
+ register long x1 asm("x1") = sizeof(args);
+ register long x8 asm("x8") = __NR_clone3;
+
+ asm volatile ("svc #0\n\t"
+ "cbnz x0, 1f\n\t"
+ "mov x8, %[nr_exit]\n\t"
+ "svc #0\n\t"
+ "1:"
+ : "+r" (x0), "+r" (x8)
+ : "r" (x1), [nr_exit] "i" (__NR_exit)
+ : "memory");
+ return x0;
+#else
+ (void)args;
+ return -EOPNOTSUPP;
+#endif
+}
+
+/*
+ * The process under test of the join case. It starts on two CPUs, in
+ * a cpuset. @widefd is the directory of a cgroup of all CPUs. Return a
+ * mask of the OVER_* values, or CHILD_SKIP without clone3().
+ */
+static int run_child_join(int widefd)
+{
+ int nr_workers = 0, ret = 0, cpu, status;
+ unsigned int cid;
+ long pid;
+
+ if (sched_getaffinity(0, sizeof(allowed), &allowed))
+ return CHILD_ERROR;
+ nr_allowed = CPU_COUNT(&allowed);
+
+ if (set_workers(&nr_workers, WIDEN_THREADS - 1))
+ return CHILD_ERROR;
+ measure(nr_workers, &cpu);
+ cid = measure(nr_workers, &cpu);
+ ksft_print_msg("%4d threads on %d CPUs: largest mm_cid %u on CPU %d\n",
+ WIDEN_THREADS, nr_allowed, cid, cpu);
+
+ /*
+ * The new task inherits the affinity which tour() requested last:
+ * the two CPUs. The kernel would intersect it with the wide cpuset,
+ * and the new task would not widen the mm. So request all CPUs. The
+ * cpuset still keeps this thread on the two CPUs.
+ */
+ if (sched_setaffinity(0, sizeof(all_cpus), &all_cpus)) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ pid = clone_vm_into_cgroup(widefd);
+ if (pid < 0) {
+ ksft_print_msg("clone3: %s\n", strerror(-pid));
+ ret = CHILD_SKIP;
+ goto out;
+ }
+ if (waitpid(pid, &status, 0) != pid) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+
+ /* Move the process into the wide cgroup of the new task. */
+ if (write_file_at(widefd, "cgroup.procs", "0")) {
+ ret = CHILD_ERROR;
+ goto out;
+ }
+ allowed = all_cpus;
+ nr_allowed = CPU_COUNT(&allowed);
+ measure(nr_workers, &cpu);
+ cid = measure(nr_workers, &cpu);
+ if (cid >= (unsigned int)nr_possible)
+ ret |= OVER_POSSIBLE;
+ if (cid >= WIDEN_THREADS)
+ ret |= OVER_STRICT;
+ ksft_print_msg("%4d threads after a join on %d CPUs: largest mm_cid %u on CPU %d%s\n",
+ WIDEN_THREADS, nr_allowed, cid, cpu,
+ ret & OVER_STRICT ? ", above the thread count target" : "");
+out:
+ if (set_workers(&nr_workers, 0))
+ ret |= CHILD_ERROR;
+ return ret;
+}
+
/* Keep the first @nr CPUs of @src in @dst. */
static int narrow_cpus(cpu_set_t *dst, const cpu_set_t *src, int nr)
{
@@ -516,6 +666,21 @@ static int write_file(const char *dir, const char *name, const char *val)
return ret;
}
+/* Write @val to the file @name of the directory fd @dirfd. Return 0 or -1. */
+static int write_file_at(int dirfd, const char *name, const char *val)
+{
+ ssize_t len = strlen(val);
+ int fd, ret = 0;
+
+ fd = openat(dirfd, name, O_WRONLY);
+ if (fd < 0)
+ return -1;
+ if (write(fd, val, len) != len)
+ ret = -1;
+ close(fd);
+ return ret;
+}
+
/* Read the file @name of @dir into @buf. Return 0 or -1. */
static int read_file(const char *dir, const char *name, char *buf, size_t size)
{
@@ -658,13 +823,90 @@ static void test_uring(const cpu_set_t *all)
ksft_test_result(!(WEXITSTATUS(status) & OVER_POSSIBLE), "%s\n", name);
}
+static void test_join(const cpu_set_t *all)
+{
+ const char *name = "join from a wider cpuset: below the possible CPUs";
+ char root[PATH_MAX], cg[PATH_MAX + 32] = "", wide[PATH_MAX + 32];
+ bool added = false;
+ int status = 0, widefd;
+ pid_t child;
+
+ /* With fewer CPUs the kernel keeps the CPUs as owners of the IDs. */
+ if (CPU_COUNT(all) < WIDEN_MIN_CPUS || nr_possible < WIDEN_MIN_CPUS) {
+ ksft_test_result_skip("%s: fewer than %d CPUs\n", name, WIDEN_MIN_CPUS);
+ return;
+ }
+ if (find_cgroup2(root, sizeof(root))) {
+ ksft_test_result_skip("%s: no cgroup v2\n", name);
+ return;
+ }
+ if (make_cpuset(root, cg, sizeof(cg), all, &added)) {
+ ksft_print_msg("cpuset of 2 CPUs: %s\n", strerror(errno));
+ if (cg[0])
+ rmdir(cg);
+ if (added)
+ write_file(root, "cgroup.subtree_control", "-cpuset");
+ ksft_test_result_skip("%s: no cgroup v2 cpuset\n", name);
+ return;
+ }
+ /* A cpuset with no CPUs of its own has all the CPUs of the root. */
+ snprintf(wide, sizeof(wide), "%s/mm_cid_bound_test_wide", root);
+ if (mkdir(wide, 0755) && errno != EEXIST) {
+ ksft_print_msg("mkdir %s: %s\n", wide, strerror(errno));
+ remove_cpuset(root, cg, added);
+ ksft_exit_fail_msg("cannot make a cpuset of all CPUs\n");
+ }
+ widefd = open(wide, O_RDONLY | O_DIRECTORY);
+ if (widefd < 0) {
+ ksft_print_msg("open %s: %s\n", wide, strerror(errno));
+ rmdir(wide);
+ remove_cpuset(root, cg, added);
+ ksft_exit_fail_msg("cannot make a cpuset of all CPUs\n");
+ }
+ all_cpus = *all;
+
+ child = fork();
+ if (!child) {
+ pid_t pid;
+
+ if (write_file(cg, "cgroup.procs", "0"))
+ _exit(CHILD_ERROR);
+ /* A new mm starts with the two CPUs of the cpuset. */
+ pid = fork();
+ if (!pid)
+ _exit(run_child_join(widefd));
+ if (pid < 0 || waitpid(pid, &status, 0) != pid ||
+ !WIFEXITED(status))
+ _exit(CHILD_ERROR);
+ _exit(WEXITSTATUS(status));
+ }
+ if (child < 0)
+ ksft_exit_fail_msg("fork: %s\n", strerror(errno));
+ if (waitpid(child, &status, 0) != child)
+ ksft_exit_fail_msg("waitpid: %s\n", strerror(errno));
+ close(widefd);
+ if (rmdir(wide))
+ ksft_print_msg("rmdir %s: %s\n", wide, strerror(errno));
+ remove_cpuset(root, cg, added);
+ if (!WIFEXITED(status) || (WEXITSTATUS(status) & CHILD_ERROR))
+ ksft_exit_fail_msg("the process under test failed to run\n");
+ if (WEXITSTATUS(status) & CHILD_SKIP) {
+ ksft_test_result_skip("%s: no clone3() into a cgroup\n", name);
+ return;
+ }
+ /* The thread count is a target. Only the bound decides the result. */
+ if (WEXITSTATUS(status) & OVER_STRICT)
+ ksft_print_msg("join from a wider cpuset: above the thread count target\n");
+ ksft_test_result(!(WEXITSTATUS(status) & OVER_POSSIBLE), "%s\n", name);
+}
+
int main(void)
{
cpu_set_t all;
int nr_all;
ksft_print_header();
- ksft_set_plan(5);
+ ksft_set_plan(6);
if (!rseq_available())
ksft_exit_skip("rseq is unavailable\n");
@@ -685,5 +927,6 @@ int main(void)
test_ramp(&all, nr_all, "all CPUs");
test_widen(&all);
test_uring(&all);
+ test_join(&all);
ksft_finished();
}
--
2.47.3
^ permalink raw reply related [flat|nested] 14+ messages in thread
end of thread, other threads:[~2026-12-02 0:29 UTC | newest]
Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-02 0:27 [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 01/13] sched/mmcid: Move the execve() hooks into exec_mmap() Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 02/13] sched/mmcid: Add the allowed CPUs of each joining task to the mm Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 03/13] sched/mmcid: Serialize joins and exits with affinity changes by pi_lock Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 04/13] sched/mmcid: Give no concurrency ID to user workers Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 05/13] selftests/rseq: Test the concurrency ID after a failed execve Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 06/13] selftests/rseq: Test the concurrency IDs across ownership mode switches Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 07/13] selftests/rseq: Test the upper bound of the concurrency IDs Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 08/13] selftests/rseq: Test an affinity change by another process during execve Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 09/13] selftests/rseq: Test the concurrency IDs after the affinity is widened Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 10/13] selftests/rseq: Test two race windows of the concurrency ID mode switches Mathieu Desnoyers
2026-12-02 0:27 ` [PATCH v2 11/13] selftests/rseq: Test the last user after an affinity change during execve Mathieu Desnoyers
2026-12-02 0:28 ` [PATCH v2 12/13] selftests/rseq: Test the concurrency IDs with an io_uring SQPOLL thread Mathieu Desnoyers
2026-12-02 0:28 ` [PATCH v2 13/13] selftests/rseq: Test the concurrency IDs after clone3() into a wider cpuset Mathieu Desnoyers
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox