mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
To: tglx@kernel.org, peterz@infradead.org
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>,
	linux-kernel@vger.kernel.org, mingo@redhat.com,
	juri.lelli@redhat.com, vincent.guittot@linaro.org,
	dietmar.eggemann@arm.com, rostedt@goodmis.org,
	bsegall@google.com, mgorman@suse.de, vschneid@redhat.com,
	kprateek.nayak@amd.com, paulmck@kernel.org, boqun@kernel.org,
	shuah@kernel.org, kees@kernel.org, viro@zeniv.linux.org.uk,
	brauner@kernel.org, jack@suse.cz, oleg@redhat.com,
	bestswngs@gmail.com, xmei5@asu.edu, xujiakai24@mails.ucas.ac.cn,
	linux-mm@kvack.org, linux-fsdevel@vger.kernel.org,
	linux-kselftest@vger.kernel.org, kmehltretter@gmail.com
Subject: [PATCH v2 11/13] selftests/rseq: Test the last user after an affinity change during execve
Date: Tue,  1 Dec 2026 19:27:59 -0500	[thread overview]
Message-ID: <5a475e60a2f8e3d94f91d2d8f3ed27bab66cb6cc.1796169827.git.mathieu.desnoyers@efficios.com> (raw)
In-Reply-To: <cover.1796169827.git.mathieu.desnoyers@efficios.com>

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


  parent reply	other threads:[~2026-12-02  0:28 UTC|newest]

Thread overview: 15+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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 ` Mathieu Desnoyers [this message]
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
2026-12-02  2:49 ` [PATCH v2 00/13] sched/mmcid: fixes for execve, mode switches and affinity Karl Mehltretter

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=5a475e60a2f8e3d94f91d2d8f3ed27bab66cb6cc.1796169827.git.mathieu.desnoyers@efficios.com \
    --to=mathieu.desnoyers@efficios.com \
    --cc=bestswngs@gmail.com \
    --cc=boqun@kernel.org \
    --cc=brauner@kernel.org \
    --cc=bsegall@google.com \
    --cc=dietmar.eggemann@arm.com \
    --cc=jack@suse.cz \
    --cc=juri.lelli@redhat.com \
    --cc=kees@kernel.org \
    --cc=kmehltretter@gmail.com \
    --cc=kprateek.nayak@amd.com \
    --cc=linux-fsdevel@vger.kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-kselftest@vger.kernel.org \
    --cc=linux-mm@kvack.org \
    --cc=mgorman@suse.de \
    --cc=mingo@redhat.com \
    --cc=oleg@redhat.com \
    --cc=paulmck@kernel.org \
    --cc=peterz@infradead.org \
    --cc=rostedt@goodmis.org \
    --cc=shuah@kernel.org \
    --cc=tglx@kernel.org \
    --cc=vincent.guittot@linaro.org \
    --cc=viro@zeniv.linux.org.uk \
    --cc=vschneid@redhat.com \
    --cc=xmei5@asu.edu \
    --cc=xujiakai24@mails.ucas.ac.cn \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®