Skip to contentSkip to conversation

membarrier: fixes, selftests and documentation

PATCH In review Mathieu Desnoyers 2 participants 19 messages Nov 27

Subsystems (16)
lore
Share & tools
lore

Mathieu Desnoyers

author maintainer
#0 lore raw

v2 cover membarrier: fixes, selftests and documentation

This series comes from a review of the membarrier system call. The review covered the code, its selftests and the fixes applied over time. It also covered the barrier and core serialization requirements of each architecture.

The series fixes four kernel issues:

- Patch 1: update the runqueue membarrier state when the scheduler switches from a kernel thread or an exited task which borrowed the mm. MEMBARRIER_CMD_GLOBAL_EXPEDITED no longer skips a registered process.

- Patch 2: report a registration in MEMBARRIER_CMD_GET_REGISTRATIONS only when it completed. An rseq or sync core registration is no longer reported as a private expedited registration as well.

- Patch 8 and patch 9: add a full memory barrier in switch_mm() for registered processes, on LoongArch and on parisc. The expedited commands need it after the store to rq->curr.

Patch 1 and patch 2 were reproduced from user-space on v7.4-rc2.

Patch 8 and patch 9 were found by reading the code and the architecture manuals. Feedback from the LoongArch and parisc maintainers is welcome.

The series fixes and extends the selftests:

- Patch 3: rebuild the tests when membarrier_test_impl.h changes.

- Patch 4: issue the sync core command in the test which is named after it.

- Patch 5: run the tests on nohz_full kernels, which only lack MEMBARRIER_CMD_GLOBAL.

- Patch 6: add membarrier_test_ipi. It checks which CPUs each expedited command interrupts. Two of its test cases fail without patch 1.

- Patch 7: add membarrier_test_cmd. It checks the command arguments and the registrations across fork, exec and CLONE_VM. Two of its tests fail without patch 2.

- Patch 13: add litmus tests of the memory ordering scenarios, for the Linux kernel memory model. One variant shows the LoongArch and parisc issue.

- Patch 14: add the selftests to the MEMBARRIER SUPPORT entry of MAINTAINERS.

- Patch 15: add membarrier_test_barrier, a stress test for x86-64. BPF programs on kprobes count, for each thread, the memory barriers which membarrier relies on. The test also checks the barriers of the scheduler. Two of its test cases fail without patch 1. It adds no kernel code.

- Patch 16: extend membarrier_test_barrier to the sync core command. It counts the core serializing instructions in the same way.

The series updates the documentation:

- Patch 10: add the missing architectures to the list of barriers after the store to rq->curr.

- Patch 11: describe what the sync core command relies on for x86 with FRED and for arm64 with FEAT_ExS.

- Patch 12: remove two stale x86 entry comments.

The sync core requirements were checked against the architecture manuals of x86 (Intel SDM and AMD APM), arm, arm64, powerpc, s390 and riscv. These are the architectures which support the sync core command. No return path to user-space was found to miss its documented serialization.

Testing:

- The six membarrier test programs pass in an x86-64 KVM guest with 8 CPUs and lockdep.

- With nohz_full=2-7, the six programs pass. Only the MEMBARRIER_CMD_GLOBAL test is skipped.

- With nosmp and with maxcpus=2, membarrier_test_ipi is skipped because it needs 3 CPUs. membarrier_test_barrier skips the two test cases which need 3 CPUs. The four other programs pass.

- With pti=on, membarrier_test_barrier passes and does not check the core serialization.

- Patch 8 and patch 9 are compile-tested only: LoongArch and parisc (32-bit, SMP), default configuration.

- herd7 reports the expected result for each of the 13 litmus tests.

The series is based on v7.4-rc2.

Changes since RFC v1:

- Patch 15: fix three issues reported by Sashiko in membarrier_test_barrier. The lazy TLB test case now sees the target switch back to its CPU. The test is skipped, instead of failing, on a kernel without CONFIG_BPF_EVENTS or CONFIG_KPROBE_EVENTS. A test case no longer reuses the counter slots of the previous one.

- Patch 16: context changes only.

RFC v1: https://lore.kernel.org/lkml/[email protected]/

An LLM coding assistant did this work at my request: the review, the reproducers, the fixes, the tests and the changelogs. I actively steered it and reviewed the result.

Thanks,

Mathieu

Mathieu Desnoyers (16):
sched/membarrier: Fix stale runqueue state after a lazy mm switch sched/membarrier: Report only completed registrations selftests/membarrier: Rebuild the tests when their header changes selftests/membarrier: Issue the sync core command in its test selftests/membarrier: Run the tests on nohz_full kernels selftests/membarrier: Test which CPUs the expedited commands interrupt selftests/membarrier: Test command arguments and registration lifetime
LoongArch: membarrier: Add full memory barrier in switch_mm()
parisc: membarrier: Add full memory barrier in switch_mm() Documentation/membarrier: Update the per-architecture barrier list Documentation/features: Update the membarrier sync core requirements x86/entry: Remove stale membarrier sync core comments selftests/membarrier: Add litmus tests of the memory ordering
MAINTAINERS: Add the membarrier selftests to MEMBARRIER SUPPORT selftests/membarrier: Check the memory barriers of each thread selftests/membarrier: Check the core serialization of the sync core
command

 .../membarrier-sync-core/arch-support.txt     |   35 +-
 Documentation/scheduler/membarrier.rst        |   14 +-
 MAINTAINERS                                   |    1 +
 arch/loongarch/Kconfig                        |    1 +
 arch/loongarch/include/asm/membarrier.h       |   33 +
 arch/loongarch/include/asm/mmu_context.h      |    4 +
 arch/parisc/Kconfig                           |    1 +
 arch/parisc/include/asm/membarrier.h          |   33 +
 arch/parisc/include/asm/mmu_context.h         |    2 +
 arch/x86/entry/entry_32.S                     |    5 -
 arch/x86/entry/entry_64.S                     |    4 -
 arch/x86/include/asm/sync_core.h              |    2 +-
 kernel/sched/core.c                           |   16 +-
 kernel/sched/membarrier.c                     |   32 +-
 kernel/sched/sched.h                          |   15 +
 tools/testing/selftests/membarrier/.gitignore |    6 +
 tools/testing/selftests/membarrier/Makefile   |   20 +
 tools/testing/selftests/membarrier/config     |    9 +
 .../selftests/membarrier/litmus/README        |   52 +
 .../litmus/ipi-after-thread-no-exit-mb.litmus |   36 +
 .../ipi-after-thread-no-handler-mb.litmus     |   36 +
 .../membarrier/litmus/ipi-after-thread.litmus |   47 +
 .../ipi-before-thread-no-entry-mb.litmus      |   37 +
 .../ipi-before-thread-no-handler-mb.litmus    |   37 +
 .../litmus/ipi-before-thread.litmus           |   46 +
 .../litmus/sched-in-no-entry-mb.litmus        |   34 +
 .../membarrier/litmus/sched-in-no-mb.litmus   |   33 +
 .../membarrier/litmus/sched-in-release.litmus |   38 +
 .../membarrier/litmus/sched-in.litmus         |   51 +
 .../litmus/sched-out-no-exit-mb.litmus        |   34 +
 .../litmus/sched-out-no-sched-mb.litmus       |   34 +
 .../membarrier/litmus/sched-out.litmus        |   49 +
 .../membarrier/membarrier_test_barrier.bpf.c  |  173 +++
 .../membarrier/membarrier_test_barrier.c      | 1364 +++++++++++++++++
 .../membarrier/membarrier_test_barrier.h      |   54 +
 .../membarrier/membarrier_test_cmd.c          |  352 +++++
 .../membarrier/membarrier_test_impl.h         |   14 +-
 .../membarrier/membarrier_test_ipi.c          |  739 +++++++++
 38 files changed, 3443 insertions(+), 50 deletions(-)
 create mode 100644 arch/loongarch/include/asm/membarrier.h
 create mode 100644 arch/parisc/include/asm/membarrier.h
 create mode 100644 tools/testing/selftests/membarrier/config
 create mode 100644 tools/testing/selftests/membarrier/litmus/README
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-after-thread-no-exit-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-after-thread-no-handler-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-after-thread.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-before-thread-no-entry-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-before-thread-no-handler-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-before-thread.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in-no-entry-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in-no-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in-release.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-out-no-exit-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-out-no-sched-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-out.litmus
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_barrier.bpf.c
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_barrier.c
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_barrier.h
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_cmd.c
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_ipi.c

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.47.3
author maintainer
#1 lore raw

PATCH v2 1/16 sched/membarrier: Fix stale runqueue state after a lazy mm switch

MEMBARRIER_CMD_GLOBAL_EXPEDITED sends an IPI to each CPU which runs a registered process. It finds those CPUs with rq->membarrier_state, a per-runqueue copy of the membarrier state of the mm.

Commit 227a4aadc75b ("sched/membarrier: Fix p->mm->membarrier_state racy load") added the copy. The scheduler updates it when it switches between two mm. A registration sends an IPI to update the runqueues which keep running the mm.

membarrier_switch_mm() compares the previous active_mm with the next mm. So it also skips the update when the previous task only borrowed the mm. This is a kernel thread in lazy TLB mode, or a task past exit_mm(). The copy can be stale in two such cases.

Case 1: a process registers while a lazy TLB kernel thread borrows its mm on another CPU. T is a thread of a process with mm M, which is not registered yet. S is a thread of another process.

CPU 0 CPU 1

T runs in user-space

    rq->membarrier_state == 0
  T migrates to CPU 1
  context_switch(T -> idle)
    idle borrows M as its active_mm
                                               context_switch(-> T)
                                               T: MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED
                                                 sets the state of M
                                                 sets rq->membarrier_state of CPU 1
                                                 CPU 0 runs idle: no IPI
                                               T migrates to CPU 0
  context_switch(idle -> T)
    membarrier_switch_mm(rq, idle->active_mm, T->mm)
      prev_mm == next_mm: no update

T runs in user-space
rq->membarrier_state == 0 (stale)
S: MEMBARRIER_CMD_GLOBAL_EXPEDITED
CPU 0: state not set, no IPI

Case 2: a thread exits and the CPU then runs another thread of the same process. A and B are threads of a registered process with mm M. S is a thread of another process.

CPU 0 CPU 1

B exits
exit_mm()

    B->mm = NULL
    membarrier_update_current_mm(NULL)
      rq->membarrier_state = 0
  context_switch(B -> A)
    membarrier_switch_mm(rq, B->active_mm, A->mm)
      prev_mm == next_mm: no update

A runs in user-space
rq->membarrier_state == 0 (stale)
S: MEMBARRIER_CMD_GLOBAL_EXPEDITED
CPU 0: state not set, no IPI

kthread_unuse_mm() clears the copy in the same way as exit_mm().

In both cases, the registered process runs without the promised memory barrier. This lasts until the CPU switches to the process from another mm.

User-space sees this as a memory ordering failure. The registered processes omit memory barriers from their fast paths. The caller issues MEMBARRIER_CMD_GLOBAL_EXPEDITED where it needs those barriers. An example is RCU-like synchronization over shared memory. Without the IPI, the caller would miss a recent store of a registered process. It would then, for example, free memory which that process still uses. A thread exit in a registered multi-threaded process is enough to trigger case 2.

Both cases were reproduced on v7.4-rc2: 1000 commands send no IPI to the registered process.

Fix this by passing prev->mm rather than prev->active_mm. It is NULL for a kernel thread and for an exited task, which forces the update. The update is still skipped between two user tasks of the same mm.

Fixes 227a4aadc75b ("sched/membarrier: Fix p->mm->membarrier_state racy load")
---
 kernel/sched/core.c  |  6 +++++-
 kernel/sched/sched.h | 15 +++++++++++++++
 2 files changed, 20 insertions(+), 1 deletion(-)
kernel/sched/core.c +5 -1
index 1a088d4576f5..df6d15cf7109 100644
@@ -5551,7 +5551,11 @@ context_switch(struct rq *rq, struct task_struct *prev,
 		else
 			prev->active_mm = NULL;
 	} else {					// to user
-		membarrier_switch_mm(rq, prev->active_mm, next->mm);
+		/*
+		 * Pass prev->mm, not prev->active_mm: see
+		 * membarrier_switch_mm().
+		 */
+		membarrier_switch_mm(rq, prev->mm, next->mm);
 		/*
 		 * sys_membarrier() requires an smp_mb() between setting
 		 * rq->curr / membarrier_switch_mm() and returning to userspace.
kernel/sched/sched.h +15 -0
index 1d76950dbb0a..68353796a7f9 100644
@@ -3907,6 +3907,21 @@ static inline bool sched_energy_enabled(void) { return false; }
  * - prior user-space memory accesses and store to rq->membarrier_state,
  * - store to rq->membarrier_state and following user-space memory accesses.
  * In the same way it provides those guarantees around store to rq->curr.
+ *
+ * @prev_mm is the mm of the previous task. It is NULL for a kernel
+ * thread and for a task past exit_mm().
+ *
+ * The update is skipped only between two user tasks of the same mm.
+ * rq->membarrier_state is up to date in that case. It was set when
+ * the first of those tasks was scheduled in, or later by the
+ * registration IPI.
+ *
+ * It must not be skipped when the previous task only borrowed the mm
+ * as its active_mm. rq->membarrier_state can be stale then:
+ *
+ * - exit_mm() and kthread_unuse_mm() clear it,
+ * - a registration does not send an IPI to a CPU which runs a lazy
+ *   TLB kernel thread.
  */
 static inline void membarrier_switch_mm(struct rq *rq,
 					struct mm_struct *prev_mm,
Signature · 1 line
2.47.3
author maintainer
#2 lore raw

PATCH v2 2/16 sched/membarrier: Report only completed registrations

In reply to Mathieu Desnoyers

MEMBARRIER_CMD_GET_REGISTRATIONS returns the registration commands which the process issued.

Each registration has two state bits: one is set when the registration starts and the "ready" one when it completes. The command reports a registration when either bit is set.

The sync core and rseq registrations also set MEMBARRIER_STATE_PRIVATE_EXPEDITED, without its "ready" bit. They set it because their commands need the same scheduler barriers as MEMBARRIER_CMD_PRIVATE_EXPEDITED. So a process which only issued MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_RSEQ is reported as having issued MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED as well. Yet MEMBARRIER_CMD_PRIVATE_EXPEDITED returns -EPERM for that process.

A registration which failed with -ENOMEM would be reported the same way.

User-space gets a wrong registration mask. The command was added for CRIU, which saves the registrations of a process at checkpoint. A restored process would carry a registration which the original process did not issue. A program which trusts the mask would issue MEMBARRIER_CMD_PRIVATE_EXPEDITED and get -EPERM.

Fix this by reporting a registration only when its "ready" bit is set.

This changes the mask which user-space reads. MEMBARRIER_CMD_GET_REGISTRATIONS no longer reports MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED for a process which only issued the sync core or the rseq registration. The result of every other command is unchanged.

Fixes 544a4f2ecd45 ("sched/membarrier: Introduce MEMBARRIER_CMD_GET_REGISTRATIONS")
---
 kernel/sched/membarrier.c | 29 ++++++++++++++---------------
 1 file changed, 14 insertions(+), 15 deletions(-)
kernel/sched/membarrier.c +14 -15
index cb957b8f1946..46e823a3d668 100644
@@ -566,15 +566,17 @@ static int membarrier_get_registrations(void)
 	struct task_struct *p = current;
 	struct mm_struct *mm = p->mm;
 	int registrations_mask = 0, membarrier_state, i;
-	static const int states[] = {
-		MEMBARRIER_STATE_GLOBAL_EXPEDITED |
-			MEMBARRIER_STATE_GLOBAL_EXPEDITED_READY,
-		MEMBARRIER_STATE_PRIVATE_EXPEDITED |
-			MEMBARRIER_STATE_PRIVATE_EXPEDITED_READY,
-		MEMBARRIER_STATE_PRIVATE_EXPEDITED_SYNC_CORE |
-			MEMBARRIER_STATE_PRIVATE_EXPEDITED_SYNC_CORE_READY,
-		MEMBARRIER_STATE_PRIVATE_EXPEDITED_RSEQ |
-			MEMBARRIER_STATE_PRIVATE_EXPEDITED_RSEQ_READY
+	/*
+	 * Only the "ready" state tells that a registration command
+	 * completed. The other state of each pair is not specific to
+	 * one registration command: the sync core and rseq
+	 * registrations also set MEMBARRIER_STATE_PRIVATE_EXPEDITED.
+	 */
+	static const int ready_states[] = {
+		MEMBARRIER_STATE_GLOBAL_EXPEDITED_READY,
+		MEMBARRIER_STATE_PRIVATE_EXPEDITED_READY,
+		MEMBARRIER_STATE_PRIVATE_EXPEDITED_SYNC_CORE_READY,
+		MEMBARRIER_STATE_PRIVATE_EXPEDITED_RSEQ_READY
 	};
 	static const int registration_cmds[] = {
 		MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED,
@@ -582,16 +584,13 @@ static int membarrier_get_registrations(void)
 		MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE,
 		MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_RSEQ
 	};
-	BUILD_BUG_ON(ARRAY_SIZE(states) != ARRAY_SIZE(registration_cmds));
+	BUILD_BUG_ON(ARRAY_SIZE(ready_states) != ARRAY_SIZE(registration_cmds));
 
 	membarrier_state = atomic_read(&mm->membarrier_state);
-	for (i = 0; i < ARRAY_SIZE(states); ++i) {
-		if (membarrier_state & states[i]) {
+	for (i = 0; i < ARRAY_SIZE(ready_states); ++i) {
+		if (membarrier_state & ready_states[i])
 			registrations_mask |= registration_cmds[i];
-			membarrier_state &= ~states[i];
-		}
 	}
-	WARN_ON_ONCE(membarrier_state != 0);
 	return registrations_mask;
 }
 
Signature · 1 line
2.47.3
author maintainer
#3 lore raw

PATCH v2 3/16 selftests/membarrier: Rebuild the tests when their header changes

In reply to Mathieu Desnoyers

membarrier_test_impl.h holds the test code of membarrier_test_single_thread and membarrier_test_multi_thread. The Makefile does not list it as a prerequisite. A change to the header does not rebuild the two tests, and a stale binary is run.

Add the header to LOCAL_HDRS. lib.mk makes each test depend on these headers and keeps them out of the compiler command line.

Also add membarrier_rseq_stress to .gitignore.

---
 tools/testing/selftests/membarrier/.gitignore | 1 +
 tools/testing/selftests/membarrier/Makefile   | 2 ++
 2 files changed, 3 insertions(+)
tools/testing/selftests/membarrier/.gitignore +1 -0
index f2fbba178601..031920478205 100644
@@ -1,3 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-only
 membarrier_test_multi_thread
 membarrier_test_single_thread
+membarrier_rseq_stress
tools/testing/selftests/membarrier/Makefile +2 -0
index 829f95c83515..20bb66380090 100644
@@ -6,4 +6,6 @@ TEST_GEN_PROGS := membarrier_test_single_thread \
 		membarrier_test_multi_thread \
 		membarrier_rseq_stress
 
+LOCAL_HDRS += membarrier_test_impl.h
+
 include ../lib.mk
Signature · 1 line
2.47.3
author maintainer
#4 lore raw

PATCH v2 4/16 selftests/membarrier: Issue the sync core command in its test

In reply to Mathieu Desnoyers

test_membarrier_private_expedited_sync_core_success() is meant to check that MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE succeeds after its registration. It issues MEMBARRIER_CMD_PRIVATE_EXPEDITED instead. No test issues the sync core command with success.

Issue the sync core command.

While at it, pass the third system call argument. It was left uninitialized.

Fixes 460e8c3340a2 ("membarrier/selftest: Test private expedited sync core command")
---
 tools/testing/selftests/membarrier/membarrier_test_impl.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/testing/selftests/membarrier/membarrier_test_impl.h +2 -2
index b4dcbb32538d..4b9d1771916e 100644
@@ -13,7 +13,7 @@ static int registrations;
 
 static int sys_membarrier(int cmd, int flags)
 {
-	return syscall(__NR_membarrier, cmd, flags);
+	return syscall(__NR_membarrier, cmd, flags, 0);
 }
 
 static int membarrier_get_registrations(void)
@@ -221,7 +221,7 @@ static int test_membarrier_register_private_expedited_sync_core_success(void)
 
 static int test_membarrier_private_expedited_sync_core_success(void)
 {
-	int cmd = MEMBARRIER_CMD_PRIVATE_EXPEDITED, flags = 0;
+	int cmd = MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE, flags = 0;
 	const char *test_name = "sys membarrier MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE";
 
 	if (sys_membarrier(cmd, flags) != 0) {
Signature · 1 line
2.47.3
author maintainer
#5 lore raw

PATCH v2 5/16 selftests/membarrier: Run the tests on nohz_full kernels

In reply to Mathieu Desnoyers

A nohz_full kernel does not provide MEMBARRIER_CMD_GLOBAL. The tests skip everything when the query mask lacks this command. The other commands are available on such a kernel and are never tested there.

Skip only the MEMBARRIER_CMD_GLOBAL test.

---
 .../selftests/membarrier/membarrier_test_impl.h        | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
tools/testing/selftests/membarrier/membarrier_test_impl.h +7 -3
index 4b9d1771916e..49f5fdb56dab 100644
@@ -97,6 +97,13 @@ static int test_membarrier_global_success(void)
 	int cmd = MEMBARRIER_CMD_GLOBAL, flags = 0;
 	const char *test_name = "sys membarrier MEMBARRIER_CMD_GLOBAL";
 
+	/* A nohz_full kernel does not provide MEMBARRIER_CMD_GLOBAL. */
+	if (!(sys_membarrier(MEMBARRIER_CMD_QUERY, 0) & cmd)) {
+		ksft_test_result_skip("%s test: Command not available\n",
+				      test_name);
+		return 0;
+	}
+
 	if (sys_membarrier(cmd, flags) != 0) {
 		ksft_exit_fail_msg(
 			"%s test: flags = %d, errno = %d\n",
@@ -356,9 +363,6 @@ static int test_membarrier_query(void)
 		}
 		ksft_exit_fail_msg("sys_membarrier() failed\n");
 	}
-	if (!(ret & MEMBARRIER_CMD_GLOBAL))
-		ksft_exit_skip(
-			"sys_membarrier unsupported: CMD_GLOBAL not found.\n");
 
 	ksft_test_result_pass("sys_membarrier available\n");
 	return 0;
Signature · 1 line
2.47.3
author maintainer
#6 lore raw

PATCH v2 6/16 selftests/membarrier: Test which CPUs the expedited commands interrupt

In reply to Mathieu Desnoyers

The existing tests only check the return value of each command. They cannot tell whether a command reached the threads it must reach.

Add membarrier_test_ipi. A test cannot observe a missing memory barrier reliably. It can observe a missing IPI in /proc/interrupts. The comment at the top of the file describes the method. The test cases are:

- global expedited reaches a registered process and skips an unregistered one,
- global expedited reaches a registered process after one of its threads exits,
- global expedited reaches a process which registered on another CPU and came back to a CPU which stayed idle meanwhile,
- global expedited reaches each thread of a process which registered while multi-threaded,
- global expedited reaches a forked child and skips a process after exec,
- private expedited, sync core and rseq reach each thread,
- rseq with MEMBARRIER_CMD_FLAG_CPU reaches only the CPU it names,
- private expedited skips another registered process,
- private expedited reaches a CLONE_VM task of another thread group.

Each test case runs in its own process, because a membarrier registration cannot be undone.

The thread exit and idle CPU cases fail without commit "sched/membarrier: Fix stale runqueue state after a lazy mm switch".

The test is skipped with fewer than 3 allowed CPUs. It is also skipped when /proc/interrupts has no function call interrupt count.

---
 tools/testing/selftests/membarrier/.gitignore |   1 +
 tools/testing/selftests/membarrier/Makefile   |   1 +
 .../membarrier/membarrier_test_ipi.c          | 739 ++++++++++++++++++
 3 files changed, 741 insertions(+)
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_ipi.c
tools/testing/selftests/membarrier/.gitignore +1 -0
index 031920478205..58969a5e4613 100644
@@ -2,3 +2,4 @@
 membarrier_test_multi_thread
 membarrier_test_single_thread
 membarrier_rseq_stress
+membarrier_test_ipi
tools/testing/selftests/membarrier/Makefile +1 -0
index 20bb66380090..ee5b9deb808b 100644
@@ -4,6 +4,7 @@ LDLIBS += -lpthread
 
 TEST_GEN_PROGS := membarrier_test_single_thread \
 		membarrier_test_multi_thread \
+		membarrier_test_ipi \
 		membarrier_rseq_stress
 
 LOCAL_HDRS += membarrier_test_impl.h
tools/testing/selftests/membarrier/membarrier_test_ipi.c new file +739 -0

739 lines not on this page · raw message

Signature · 1 line
2.47.3
author maintainer
#7 lore raw

PATCH v2 7/16 selftests/membarrier: Test command arguments and registration lifetime

In reply to Mathieu Desnoyers

The existing tests issue each command once with valid arguments, in one fixed order of registrations. They miss the following:

- the query mask is not compared with the commands which the kernel accepts. Commit 809232619f5b ("sched/membarrier: Fix membarrier-rseq fence command missing from query bitmask") fixed such a mismatch,
- only MEMBARRIER_CMD_QUERY is tested with an invalid flag,
- only the stress test issues the rseq command. Its registration, its -EPERM result and its CPU argument are not checked,
- each registration is not tested alone. Commit fc0d77387cb5 ("sched/membarrier: Fix private expedited registration check") fixed an interaction between two registrations,
- the registrations are not tested across fork, exec and CLONE_VM.

Add membarrier_test_cmd for those. It uses the kselftest harness, which runs each test in its own process. A registration cannot be undone, so each test needs a new process.

The sync core and rseq registration tests fail without commit "sched/membarrier: Report only completed registrations".

---
 tools/testing/selftests/membarrier/.gitignore |   1 +
 tools/testing/selftests/membarrier/Makefile   |   1 +
 .../membarrier/membarrier_test_cmd.c          | 352 ++++++++++++++++++
 3 files changed, 354 insertions(+)
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_cmd.c
tools/testing/selftests/membarrier/.gitignore +1 -0
index 58969a5e4613..45b995b884a6 100644
@@ -3,3 +3,4 @@ membarrier_test_multi_thread
 membarrier_test_single_thread
 membarrier_rseq_stress
 membarrier_test_ipi
+membarrier_test_cmd
tools/testing/selftests/membarrier/Makefile +1 -0
index ee5b9deb808b..c7fa0573e978 100644
@@ -5,6 +5,7 @@ LDLIBS += -lpthread
 TEST_GEN_PROGS := membarrier_test_single_thread \
 		membarrier_test_multi_thread \
 		membarrier_test_ipi \
+		membarrier_test_cmd \
 		membarrier_rseq_stress
 
 LOCAL_HDRS += membarrier_test_impl.h
tools/testing/selftests/membarrier/membarrier_test_cmd.c new file +352 -0

352 lines not on this page · raw message

Signature · 1 line
2.47.3
author maintainer
#8 lore raw

PATCH v2 8/16 LoongArch: membarrier: Add full memory barrier in switch_mm()

In reply to Mathieu Desnoyers

The expedited membarrier commands need a full memory barrier after the scheduler stores to rq->curr, before the CPU returns to user-space. membarrier() skips the IPI to a CPU which it sees running another mm. This barrier orders the user-space accesses of the incoming thread after that check. See scenario (A) in kernel/sched/membarrier.c.

LoongArch has no dedicated barrier. It used to get it from spin_unlock() in finish_lock_switch(), which was a full barrier ("dbar 0").

This is no longer true. Commit e031a5f3f1ed ("LoongArch: Support dbar with different hints") made smp_store_release() an ordering barrier ("dbar 0b10010"). It does not order a previous store with a following load. That commit kept a full barrier in queued_spin_unlock(). Commit 9c68ece8b2a5 ("LoongArch: Define the __io_aw() hook as mmiowb()") then removed it.

Nothing else is a full barrier on a switch between two user processes. switch_mm_irqs_off() writes CSRs and sets a bit in the mm cpumask with a plain "amor". finish_task() uses smp_store_release().

The LoongArch manual lists the instructions which order memory
accesses: DBAR, IBAR, the AM*_DB instructions and LL/SC pairs. A CSR write and ERTN are not among them.

This was found by reading the code and the architecture manual. On Loongson-3A6000 or newer, a thread which is scheduled in would run user-space code without the barrier which membarrier promised to the caller. User-space would see a memory ordering failure: the caller of an expedited membarrier command would miss a recent store of that thread. Older processors treat every dbar hint as "dbar 0" and are not affected.

Do as powerpc and riscv: add membarrier_arch_switch_mm() and call it from switch_mm_irqs_off() when the mm changes. It issues smp_mb() only when the next mm registered for an expedited command.

Compile-tested only.

Fixes 9c68ece8b2a5 ("LoongArch: Define the __io_aw() hook as mmiowb()")
---
 arch/loongarch/Kconfig                   |  1 +
 arch/loongarch/include/asm/membarrier.h  | 33 ++++++++++++++++++++++++
 arch/loongarch/include/asm/mmu_context.h |  4 +++
 3 files changed, 38 insertions(+)
 create mode 100644 arch/loongarch/include/asm/membarrier.h
arch/loongarch/Kconfig +1 -0
index b5ed4881d3c0..be6e7545d646 100644
@@ -22,6 +22,7 @@ config LOONGARCH
 	select ARCH_HAS_FORTIFY_SOURCE
 	select ARCH_HAS_KCOV
 	select ARCH_HAS_KERNEL_FPU_SUPPORT if 64BIT && CPU_HAS_FPU
+	select ARCH_HAS_MEMBARRIER_CALLBACKS
 	select ARCH_HAS_NMI_SAFE_THIS_CPU_OPS
 	select ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
 	select ARCH_HAS_PREEMPT_LAZY
arch/loongarch/include/asm/membarrier.h new file +33 -0
new file mode 100644
index 000000000000..1789f878821f
@@ -0,0 +1,33 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _ASM_LOONGARCH_MEMBARRIER_H
+#define _ASM_LOONGARCH_MEMBARRIER_H
+
+static inline void membarrier_arch_switch_mm(struct mm_struct *prev,
+					     struct mm_struct *next,
+					     struct task_struct *tsk)
+{
+	/*
+	 * Only need the full barrier when switching between processes.
+	 * Barrier when switching from kernel to userspace is not
+	 * required here, given that it is implied by mmdrop(). Barrier
+	 * when switching from userspace to kernel is not needed after
+	 * store to rq->curr.
+	 */
+	if (IS_ENABLED(CONFIG_SMP) &&
+	    likely(!(atomic_read(&next->membarrier_state) &
+		     (MEMBARRIER_STATE_PRIVATE_EXPEDITED |
+		      MEMBARRIER_STATE_GLOBAL_EXPEDITED))))
+		return;
+
+	/*
+	 * The membarrier system call requires a full memory barrier
+	 * after storing to rq->curr, before going back to user-space.
+	 *
+	 * Nothing else provides it on this path. spin_unlock() and
+	 * smp_store_release() are ordering barriers ("dbar 0b10010"):
+	 * they do not order a previous store with a following load.
+	 */
+	smp_mb();
+}
+
+#endif /* _ASM_LOONGARCH_MEMBARRIER_H */
arch/loongarch/include/asm/mmu_context.h +4 -0
index 304363bd3935..dba62dd7a131 100644
@@ -9,6 +9,7 @@
 
 #include <linux/errno.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/mm_types.h>
 #include <linux/smp.h>
 #include <linux/slab.h>
@@ -91,6 +92,9 @@ static inline void switch_mm_irqs_off(struct mm_struct *prev, struct mm_struct *
 	bool need_flush = false;
 	unsigned int cpu = smp_processor_id();
 
+	if (prev != next)
+		membarrier_arch_switch_mm(prev, next, tsk);
+
 	/* Check if our ASID is of an older version and thus invalid */
 	if (!asid_valid(next, cpu))
 		get_new_mmu_context(next, cpu, &need_flush);
Signature · 1 line
2.47.3
author maintainer
#9 lore raw

PATCH v2 9/16 parisc: membarrier: Add full memory barrier in switch_mm()

In reply to Mathieu Desnoyers

The expedited membarrier commands need a full memory barrier after the scheduler stores to rq->curr, before the CPU returns to user-space. membarrier() skips the IPI to a CPU which it sees running another mm. This barrier orders the user-space accesses of the incoming thread after that check. See scenario (A) in kernel/sched/membarrier.c.

parisc has no dedicated barrier. It used to get it from smp_store_release() in finish_task() and from spin_unlock() in finish_lock_switch(). The first one issued a SYNC instruction. The second one issued an LDCW instruction, which is strongly ordered.

Both are ordered stores since v5.9:

- commit 157e9afcc4fa ("Revert "parisc: Revert "Release spinlocks using ordered store"""),
- commit e96ebd589deb ("parisc: Implement __smp_store_release and __smp_load_acquire barriers").

Linux runs with the PSW O bit clear. The PA-RISC 2.0 architecture then allows plain loads and stores to be weakly ordered. It orders an ordered store before a following ordered load, not before a following plain load. So an ordered store is not a full barrier.

Nothing else is a full barrier on a switch between two user processes. switch_mm_irqs_off() only writes control and space registers.

The PA-RISC 2.0 manual lists the strongly ordered accesses: I/O space, pages with the TLB U-bit set, LDCW, LDCD, the TLB purges and SYNC. MTCTL, MTSP and RFI are not among them.

This was found by reading the code and the architecture manual. On a PA-RISC 2.0 SMP machine, a thread which is scheduled in would run user-space code without the promised barrier. User-space would see a memory ordering failure: the caller of an expedited membarrier command would miss a recent store of that thread. PA-RISC 1.1 is strongly ordered and not affected.

Do as powerpc and riscv: add membarrier_arch_switch_mm() and call it from switch_mm_irqs_off() when the mm changes. It issues smp_mb() only when the next mm registered for an expedited command.

Compile-tested only.

Fixes 157e9afcc4fa ("Revert "parisc: Revert "Release spinlocks using ordered store""")
Fixes e96ebd589deb ("parisc: Implement __smp_store_release and __smp_load_acquire barriers")
---
 arch/parisc/Kconfig                   |  1 +
 arch/parisc/include/asm/membarrier.h  | 33 +++++++++++++++++++++++++++
 arch/parisc/include/asm/mmu_context.h |  2 ++
 3 files changed, 36 insertions(+)
 create mode 100644 arch/parisc/include/asm/membarrier.h
arch/parisc/Kconfig +1 -0
index 77f67028ad89..3d6b4cc8d6a5 100644
@@ -13,6 +13,7 @@ config PARISC
 	select ARCH_HAS_DMA_ALLOC if PA11
 	select ARCH_HAS_DMA_OPS
 	select ARCH_HAS_ELF_RANDOMIZE
+	select ARCH_HAS_MEMBARRIER_CALLBACKS
 	select ARCH_HAS_STRICT_KERNEL_RWX
 	select ARCH_HAS_STRICT_MODULE_RWX
 	select ARCH_HAS_UBSAN
arch/parisc/include/asm/membarrier.h new file +33 -0
new file mode 100644
index 000000000000..822dcadaf9bb
@@ -0,0 +1,33 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _ASM_PARISC_MEMBARRIER_H
+#define _ASM_PARISC_MEMBARRIER_H
+
+static inline void membarrier_arch_switch_mm(struct mm_struct *prev,
+					     struct mm_struct *next,
+					     struct task_struct *tsk)
+{
+	/*
+	 * Only need the full barrier when switching between processes.
+	 * Barrier when switching from kernel to userspace is not
+	 * required here, given that it is implied by mmdrop(). Barrier
+	 * when switching from userspace to kernel is not needed after
+	 * store to rq->curr.
+	 */
+	if (IS_ENABLED(CONFIG_SMP) &&
+	    likely(!(atomic_read(&next->membarrier_state) &
+		     (MEMBARRIER_STATE_PRIVATE_EXPEDITED |
+		      MEMBARRIER_STATE_GLOBAL_EXPEDITED))))
+		return;
+
+	/*
+	 * The membarrier system call requires a full memory barrier
+	 * after storing to rq->curr, before going back to user-space.
+	 *
+	 * Nothing else provides it on this path. spin_unlock() and
+	 * smp_store_release() are ordered stores. PA-RISC 2.0 does not
+	 * order an ordered store with a following weakly ordered load.
+	 */
+	smp_mb();
+}
+
+#endif /* _ASM_PARISC_MEMBARRIER_H */
arch/parisc/include/asm/mmu_context.h +2 -0
index c9187fe836a3..42ff1b9444f1 100644
@@ -4,6 +4,7 @@
 
 #include <linux/mm.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/atomic.h>
 #include <linux/spinlock.h>
 #include <asm-generic/mm_hooks.h>
@@ -51,6 +52,7 @@ static inline void switch_mm_irqs_off(struct mm_struct *prev,
 		struct mm_struct *next, struct task_struct *tsk)
 {
 	if (prev != next) {
+		membarrier_arch_switch_mm(prev, next, tsk);
 #ifdef CONFIG_TLB_PTLOCK
 		/* put physical address of page_table_lock in cr28 (tr4)
 		   for TLB faults */
Signature · 1 line
2.47.3
author maintainer
#10 lore raw

PATCH v2 10/16 Documentation/membarrier: Update the per-architecture barrier list

In reply to Mathieu Desnoyers

membarrier.rst lists how each architecture provides the full memory barrier after the store to rq->curr. The list misses several SMP architectures.

Add csky, openrisc, sh and xtensa. They use the generic smp_store_release(). It issues smp_mb() before the store. finish_task() uses it.

LoongArch and parisc now provide the barrier with membarrier_arch_switch_mm(). Add them next to powerpc and riscv.

State the rule which both broke: an architecture which weakens smp_store_release() or spin_unlock() must provide the barrier another way.

Update the matching comment in __schedule().

---
 Documentation/scheduler/membarrier.rst | 14 ++++++++++----
 kernel/sched/core.c                    | 10 ++++++----
 2 files changed, 16 insertions(+), 8 deletions(-)
Documentation/scheduler/membarrier.rst +10 -4
index 2387804b1c63..c5f6f4f57331 100644
@@ -28,12 +28,18 @@ architectures are as follows.
  - alpha, arc, arm, hexagon, mips rely on the full barrier implied by
    spin_unlock() in finish_lock_switch().
 
+ - csky, openrisc, sh, xtensa rely on the generic smp_store_release(),
+   which issues a full barrier before the store.  finish_task() uses it.
+
  - arm64 relies on the full barrier implied by switch_to().
 
- - powerpc, riscv, s390, sparc, x86 rely on the full barrier implied by
-   switch_mm(), if mm is not NULL; they rely on the full barrier implied
-   by mmdrop(), otherwise.  On powerpc and riscv, switch_mm() relies on
-   membarrier_arch_switch_mm().
+ - loongarch, parisc, powerpc, riscv, s390, sparc, x86 rely on the full
+   barrier implied by switch_mm(), if mm is not NULL; they rely on the full
+   barrier implied by mmdrop(), otherwise.  On loongarch, parisc, powerpc and
+   riscv, switch_mm() relies on membarrier_arch_switch_mm().
+
+An architecture which overrides smp_store_release() or spin_unlock() with
+something weaker than a full barrier must provide this barrier another way.
 
 The barrier matches a full barrier in the proximity of the membarrier system call
 entry, cf. membarrier_{private,global}_expedited().
kernel/sched/core.c +6 -4
index df6d15cf7109..9985c95ecd73 100644
@@ -7367,10 +7367,12 @@ static void __sched notrace __schedule(int sched_mode)
 		 * Here are the schemes providing that barrier on the
 		 * various architectures:
 		 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC,
-		 *   RISC-V.  switch_mm() relies on membarrier_arch_switch_mm()
-		 *   on PowerPC and on RISC-V.
-		 * - finish_lock_switch() for weakly-ordered
-		 *   architectures where spin_unlock is a full barrier,
+		 *   RISC-V, LoongArch, PA-RISC.  switch_mm() relies on
+		 *   membarrier_arch_switch_mm() on PowerPC, RISC-V,
+		 *   LoongArch and PA-RISC.
+		 * - finish_task() and finish_lock_switch() for weakly-ordered
+		 *   architectures where smp_store_release() or spin_unlock
+		 *   is a full barrier,
 		 * - switch_to() for arm64 (weakly-ordered, spin_unlock
 		 *   is a RELEASE barrier),
 		 *
Signature · 1 line
2.47.3
author maintainer
#11 lore raw

PATCH v2 11/16 Documentation/features: Update the membarrier sync core requirements

In reply to Mathieu Desnoyers

The x86 text says that the return from interrupt uses IRET, which serializes the core after the IPI. This is not what the code relies on, and it is not always true:

- Since commit a493d1ca1a03 ("x86/membarrier: Get rid of a dubious optimization"), the IPI handler issues a core serializing instruction right away. The interrupted thread can be rescheduled before the return from interrupt, and another thread of the mm can then return to user-space through SYSRET.

- With FRED, the kernel returns through ERETS and ERETU. The Intel SDM does not list them as serializing instructions. It states that ERETU has the instruction ordering guarantees of SYSRET. The AMD APM does not describe these two instructions.

Describe what x86 relies on instead: sync_core_before_usermode() and the writes to CR3.

On arm64 with FEAT_ExS, an exception return is a context synchronization event only when SCTLR_ELx.EOS is set. The kernel sets it. Document that the sync core command depends on it.

---
 .../membarrier-sync-core/arch-support.txt     | 35 +++++++++++++------
 1 file changed, 24 insertions(+), 11 deletions(-)
Documentation/features/sched/membarrier-sync-core/arch-support.txt +24 -11
index 7425d2b994a3..2782b0d25f43 100644
@@ -10,6 +10,10 @@
 # Rely on implicit context synchronization as a result of exception return
 # when returning from IPI handler, and when returning to user-space.
 #
+# On arm64 with FEAT_ExS, an exception return is a context synchronization
+# event only when SCTLR_ELx.EOS is set. The kernel sets it, cf.
+# SCTLR_EL1_EOS in INIT_SCTLR_EL1_MMU_ON. It must stay set.
+#
 # * riscv
 #
 # riscv uses xRET as return from interrupt and to return to user-space.
@@ -28,19 +32,28 @@
 #
 # * x86
 #
-# x86-32 uses IRET as return from interrupt, which takes care of the IPI.
-# However, it uses both IRET and SYSEXIT to go back to user-space. The IRET
-# instruction is core serializing, but not SYSEXIT.
+# x86-32 returns to user-space through either IRET or SYSEXIT. x86-64 returns
+# to user-space through either SYSRETL (compat code), SYSRETQ or IRET, or
+# through ERETU when FRED is enabled. It returns from interrupt through IRET,
+# or through ERETS or ERETU when FRED is enabled.
+#
+# The IRET instruction is core serializing. SYSRET{L,Q}, SYSEXIT, ERETS and
+# ERETU are not. Therefore x86 does not rely on the return instruction:
+#
+#  - the IPI handler calls sync_core_before_usermode(), which issues a core
+#    serializing instruction right away (cf. ipi_sync_core()). The thread may
+#    otherwise be rescheduled before the return from interrupt, and a thread
+#    of the same mm may return to user-space through SYSRET,
+#
+#  - write_cr3() performed by switch_mm() provides core serialization after
+#    changing the current mm,
 #
-# x86-64 uses IRET as return from interrupt, which takes care of the IPI.
-# However, it can return to user-space through either SYSRETL (compat code),
-# SYSRETQ, or IRET.
+#  - the special case of kthread -> uthread (temporarily keeping current mm
+#    into active_mm) issues a sync_core_before_usermode().
 #
-# Given that neither SYSRET{L,Q}, nor SYSEXIT, are core serializing, we rely
-# instead on write_cr3() performed by switch_mm() to provide core serialization
-# after changing the current mm, and deal with the special case of kthread ->
-# uthread (temporarily keeping current mm into active_mm) by issuing a
-# sync_core_before_usermode() in that specific case.
+# With page table isolation, sync_core_before_usermode() does nothing: each
+# return to user-space writes to CR3, which is core serializing. Page table
+# isolation and FRED are mutually exclusive.
 #
     -----------------------
     |         arch |status|
Signature · 1 line
2.47.3
author maintainer
#12 lore raw

PATCH v2 12/16 x86/entry: Remove stale membarrier sync core comments

In reply to Mathieu Desnoyers

Two comments state that the membarrier sync core command relies on the IRET which returns from the IPI handler. This is no longer true since commit a493d1ca1a03 ("x86/membarrier: Get rid of a dubious optimization"): sync_core_before_usermode() serializes the core in the IPI handler.

Remove both comments.

The comment of sync_core_before_usermode() lists the instructions which return to user-space without serializing the core. Fix a typo in it ("sysrel") and add ERETU, which FRED uses.

---
 arch/x86/entry/entry_32.S        | 5 -----
 arch/x86/entry/entry_64.S        | 4 ----
 arch/x86/include/asm/sync_core.h | 2 +-
 3 files changed, 1 insertion(+), 10 deletions(-)
arch/x86/entry/entry_32.S +0 -5
index 92c0b4a94e0a..d47bb08afb24 100644
@@ -954,11 +954,6 @@ restore_all_switch_stack:
 	RESTORE_REGS pop=4			# skip orig_eax/error_code
 	CLEAR_CPU_BUFFERS
 .Lirq_return:
-	/*
-	 * ARCH_HAS_MEMBARRIER_SYNC_CORE rely on IRET core serialization
-	 * when returning from IPI handler and when returning from
-	 * scheduler to user-space.
-	 */
 	iret
 
 .Lasm_iret_error:
arch/x86/entry/entry_64.S +0 -4
index 253f0a585927..b8661064232c 100644
@@ -626,10 +626,6 @@ SYM_INNER_LABEL(restore_regs_and_return_to_kernel, SYM_L_GLOBAL)
 #endif
 	POP_REGS
 	addq	$8, %rsp	/* skip regs->orig_ax */
-	/*
-	 * ARCH_HAS_MEMBARRIER_SYNC_CORE rely on IRET core serialization
-	 * when returning from IPI handler.
-	 */
 #ifdef CONFIG_XEN_PV
 SYM_INNER_LABEL(early_xen_iret_patch, SYM_L_GLOBAL)
 	ANNOTATE_NOENDBR
arch/x86/include/asm/sync_core.h +1 -1
index df22113db9cd..0ab91f7e2020 100644
@@ -91,7 +91,7 @@ static __always_inline void sync_core(void)
 /*
  * Ensure that a core serializing instruction is issued before returning
  * to user-mode. x86 implements return to user-space through sysexit,
- * sysrel, and sysretq, which are not core serializing.
+ * sysretl, sysretq and eretu, which are not core serializing.
  */
 static inline void sync_core_before_usermode(void)
 {
Signature · 1 line
2.47.3
author maintainer
#13 lore raw

PATCH v2 13/16 selftests/membarrier: Add litmus tests of the memory ordering

In reply to Mathieu Desnoyers

membarrier relies on memory barriers in the system call, in its IPI handler and in the scheduler. The comment at the top of kernel/sched/membarrier.c describes the scenarios. A test on real hardware can check that the kernel executes a barrier. It cannot show that the barrier is needed: a missing barrier may never fail in practice.

Check these scenarios with the Linux kernel memory model instead. The litmus tests cover:

- a thread which runs after the IPI, scenario (A),
- a thread which ran before the IPI, scenario (B),
- a thread which is scheduled in while membarrier() sees another task in rq->curr, scenarios (A) and (C),
- a thread which is scheduled out before membarrier() loads rq->curr, scenarios (B) and (C).

herd7 reports "Never" for these 4 tests. 9 variants drop one barrier each, and herd7 reports "Sometimes" for them. One of the variants replaces the full barrier after the store to rq->curr with smp_store_release(). This is the LoongArch and parisc case.

The README describes the model and how to run the tests.

---
 kernel/sched/membarrier.c                     |  3 ++
 .../selftests/membarrier/litmus/README        | 52 +++++++++++++++++++
 .../litmus/ipi-after-thread-no-exit-mb.litmus | 36 +++++++++++++
 .../ipi-after-thread-no-handler-mb.litmus     | 36 +++++++++++++
 .../membarrier/litmus/ipi-after-thread.litmus | 47 +++++++++++++++++
 .../ipi-before-thread-no-entry-mb.litmus      | 37 +++++++++++++
 .../ipi-before-thread-no-handler-mb.litmus    | 37 +++++++++++++
 .../litmus/ipi-before-thread.litmus           | 46 ++++++++++++++++
 .../litmus/sched-in-no-entry-mb.litmus        | 34 ++++++++++++
 .../membarrier/litmus/sched-in-no-mb.litmus   | 33 ++++++++++++
 .../membarrier/litmus/sched-in-release.litmus | 38 ++++++++++++++
 .../membarrier/litmus/sched-in.litmus         | 51 ++++++++++++++++++
 .../litmus/sched-out-no-exit-mb.litmus        | 34 ++++++++++++
 .../litmus/sched-out-no-sched-mb.litmus       | 34 ++++++++++++
 .../membarrier/litmus/sched-out.litmus        | 49 +++++++++++++++++
 15 files changed, 567 insertions(+)
 create mode 100644 tools/testing/selftests/membarrier/litmus/README
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-after-thread-no-exit-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-after-thread-no-handler-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-after-thread.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-before-thread-no-entry-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-before-thread-no-handler-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/ipi-before-thread.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in-no-entry-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in-no-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in-release.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-in.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-out-no-exit-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-out-no-sched-mb.litmus
 create mode 100644 tools/testing/selftests/membarrier/litmus/sched-out.litmus
kernel/sched/membarrier.c +3 -0
index 46e823a3d668..5dd88ac0957b 100644
@@ -133,6 +133,9 @@
  * Using the scenario from (A), we can show that (a) needs to be paired
  * with (g). Using the scenario from (B), we can show that (c) needs to
  * be paired with (d).
+ *
+ * The litmus tests in tools/testing/selftests/membarrier/litmus check
+ * these scenarios with the Linux kernel memory model.
  */
 
 /*
tools/testing/selftests/membarrier/litmus/README new file +52 -0

52 lines not on this page · raw message

tools/testing/selftests/membarrier/litmus/ipi-after-thread-no-exit-mb.litmus new file +36 -0
new file mode 100644
index 000000000000..fb67beaba996
@@ -0,0 +1,36 @@
+C ipi-after-thread-no-exit-mb
+
+(*
+ * Result: Sometimes
+ *
+ * ipi-after-thread without the barrier (c) at the end of membarrier().
+ * The load of x by P0 can then be done before the IPI completes.
+ *)
+
+{}
+
+P0(int *x, int *y, int *req, int *ack)
+{
+	int r_ack;
+	int r1;
+	int r2;
+
+	r2 = READ_ONCE(*y);
+	smp_mb();
+	WRITE_ONCE(*req, 1);
+	r_ack = READ_ONCE(*ack);
+	r1 = READ_ONCE(*x);
+}
+
+P1(int *x, int *y, int *req, int *ack)
+{
+	int r_req;
+
+	WRITE_ONCE(*x, 1);
+	WRITE_ONCE(*y, 1);
+	r_req = READ_ONCE(*req);
+	smp_mb();
+	WRITE_ONCE(*ack, 1);
+}
+
+exists (0:r2=1 /\ 1:r_req=1 /\ 0:r_ack=1 /\ 0:r1=0)
tools/testing/selftests/membarrier/litmus/ipi-after-thread-no-handler-mb.litmus new file +36 -0
new file mode 100644
index 000000000000..687e883850a9
@@ -0,0 +1,36 @@
+C ipi-after-thread-no-handler-mb
+
+(*
+ * Result: Sometimes
+ *
+ * ipi-after-thread without the barrier in the IPI handler. The store to
+ * x by P1 can then be delayed past the acknowledgment.
+ *)
+
+{}
+
+P0(int *x, int *y, int *req, int *ack)
+{
+	int r_ack;
+	int r1;
+	int r2;
+
+	r2 = READ_ONCE(*y);
+	smp_mb();
+	WRITE_ONCE(*req, 1);
+	r_ack = READ_ONCE(*ack);
+	smp_mb();
+	r1 = READ_ONCE(*x);
+}
+
+P1(int *x, int *y, int *req, int *ack)
+{
+	int r_req;
+
+	WRITE_ONCE(*x, 1);
+	WRITE_ONCE(*y, 1);
+	r_req = READ_ONCE(*req);
+	WRITE_ONCE(*ack, 1);
+}
+
+exists (0:r2=1 /\ 1:r_req=1 /\ 0:r_ack=1 /\ 0:r1=0)
tools/testing/selftests/membarrier/litmus/ipi-after-thread.litmus new file +47 -0

47 lines not on this page · raw message

tools/testing/selftests/membarrier/litmus/ipi-before-thread-no-entry-mb.litmus new file +37 -0
new file mode 100644
index 000000000000..9685e34e224a
@@ -0,0 +1,37 @@
+C ipi-before-thread-no-entry-mb
+
+(*
+ * Result: Sometimes
+ *
+ * ipi-before-thread without the barrier (a) at the start of
+ * membarrier(). The store to x can be delayed past the IPI. P1 and P0
+ * then both read 0.
+ *)
+
+{}
+
+P0(int *x, int *y, int *req, int *ack)
+{
+	int r_ack;
+	int r2;
+
+	WRITE_ONCE(*x, 1);
+	WRITE_ONCE(*req, 1);
+	r_ack = READ_ONCE(*ack);
+	smp_mb();
+	r2 = READ_ONCE(*y);
+}
+
+P1(int *x, int *y, int *req, int *ack)
+{
+	int r_req;
+	int r1;
+
+	r_req = READ_ONCE(*req);
+	smp_mb();
+	WRITE_ONCE(*ack, 1);
+	WRITE_ONCE(*y, 1);
+	r1 = READ_ONCE(*x);
+}
+
+exists (1:r_req=1 /\ 0:r_ack=1 /\ 1:r1=0 /\ 0:r2=0)
tools/testing/selftests/membarrier/litmus/ipi-before-thread-no-handler-mb.litmus new file +37 -0
new file mode 100644
index 000000000000..1559bce76ea5
@@ -0,0 +1,37 @@
+C ipi-before-thread-no-handler-mb
+
+(*
+ * Result: Sometimes
+ *
+ * ipi-before-thread without the barrier in the IPI handler. The load of
+ * x by P1 can then be done before the handler loads req. This is why
+ * ipi_mb() issues smp_mb() rather than rely on the interrupt alone.
+ *)
+
+{}
+
+P0(int *x, int *y, int *req, int *ack)
+{
+	int r_ack;
+	int r2;
+
+	WRITE_ONCE(*x, 1);
+	smp_mb();
+	WRITE_ONCE(*req, 1);
+	r_ack = READ_ONCE(*ack);
+	smp_mb();
+	r2 = READ_ONCE(*y);
+}
+
+P1(int *x, int *y, int *req, int *ack)
+{
+	int r_req;
+	int r1;
+
+	r_req = READ_ONCE(*req);
+	WRITE_ONCE(*ack, 1);
+	WRITE_ONCE(*y, 1);
+	r1 = READ_ONCE(*x);
+}
+
+exists (1:r_req=1 /\ 0:r_ack=1 /\ 1:r1=0 /\ 0:r2=0)
tools/testing/selftests/membarrier/litmus/ipi-before-thread.litmus new file +46 -0

46 lines not on this page · raw message

tools/testing/selftests/membarrier/litmus/sched-in-no-entry-mb.litmus new file +34 -0
new file mode 100644
index 000000000000..a40837fad005
@@ -0,0 +1,34 @@
+C sched-in-no-entry-mb
+
+(*
+ * Result: Sometimes
+ *
+ * sched-in without the barrier (a) at the start of membarrier(). The
+ * store to x can be delayed past the load of rq->curr. P0 sees no
+ * thread and sends no IPI. The thread reads x == 0.
+ *)
+
+{}
+
+P0(int *x, int *y, int *curr)
+{
+	int r_curr;
+	int r2;
+
+	WRITE_ONCE(*x, 1);
+	r_curr = READ_ONCE(*curr);
+	smp_mb();
+	r2 = READ_ONCE(*y);
+}
+
+P1(int *x, int *y, int *curr)
+{
+	int r1;
+
+	WRITE_ONCE(*curr, 1);
+	smp_mb();
+	WRITE_ONCE(*y, 1);
+	r1 = READ_ONCE(*x);
+}
+
+exists (0:r_curr=0 /\ 1:r1=0 /\ 0:r2=0)
tools/testing/selftests/membarrier/litmus/sched-in-no-mb.litmus new file +33 -0
new file mode 100644
index 000000000000..6840cb26e13d
@@ -0,0 +1,33 @@
+C sched-in-no-mb
+
+(*
+ * Result: Sometimes
+ *
+ * sched-in without the full barrier after the store to rq->curr. P0
+ * sees no thread and sends no IPI. The thread reads x == 0.
+ *)
+
+{}
+
+P0(int *x, int *y, int *curr)
+{
+	int r_curr;
+	int r2;
+
+	WRITE_ONCE(*x, 1);
+	smp_mb();
+	r_curr = READ_ONCE(*curr);
+	smp_mb();
+	r2 = READ_ONCE(*y);
+}
+
+P1(int *x, int *y, int *curr)
+{
+	int r1;
+
+	WRITE_ONCE(*curr, 1);
+	WRITE_ONCE(*y, 1);
+	r1 = READ_ONCE(*x);
+}
+
+exists (0:r_curr=0 /\ 1:r1=0 /\ 0:r2=0)
tools/testing/selftests/membarrier/litmus/sched-in-release.litmus new file +38 -0
new file mode 100644
index 000000000000..d2df75b388fe
@@ -0,0 +1,38 @@
+C sched-in-release
+
+(*
+ * Result: Sometimes
+ *
+ * sched-in with smp_store_release() in place of the full barrier after
+ * the store to rq->curr. This is finish_task() on an architecture where
+ * smp_store_release() is weaker than a full barrier. It does not order
+ * the store to rq->curr before the loads of the thread.
+ *)
+
+{
+	int on_cpu = 1;
+}
+
+P0(int *x, int *y, int *curr)
+{
+	int r_curr;
+	int r2;
+
+	WRITE_ONCE(*x, 1);
+	smp_mb();
+	r_curr = READ_ONCE(*curr);
+	smp_mb();
+	r2 = READ_ONCE(*y);
+}
+
+P1(int *x, int *y, int *curr, int *on_cpu)
+{
+	int r1;
+
+	WRITE_ONCE(*curr, 1);
+	smp_store_release(on_cpu, 0);
+	WRITE_ONCE(*y, 1);
+	r1 = READ_ONCE(*x);
+}
+
+exists (0:r_curr=0 /\ 1:r1=0 /\ 0:r2=0)
tools/testing/selftests/membarrier/litmus/sched-in.litmus new file +51 -0

51 lines not on this page · raw message

tools/testing/selftests/membarrier/litmus/sched-out-no-exit-mb.litmus new file +34 -0
new file mode 100644
index 000000000000..e4bb1ee7a935
@@ -0,0 +1,34 @@
+C sched-out-no-exit-mb
+
+(*
+ * Result: Sometimes
+ *
+ * sched-out without the barrier (c) at the end of membarrier(). The
+ * load of x by P0 can then be done before it loads rq->curr.
+ *)
+
+{
+	int curr = 1;
+}
+
+P0(int *x, int *y, int *curr)
+{
+	int r_curr;
+	int r1;
+	int r2;
+
+	r2 = READ_ONCE(*y);
+	smp_mb();
+	r_curr = READ_ONCE(*curr);
+	r1 = READ_ONCE(*x);
+}
+
+P1(int *x, int *y, int *curr)
+{
+	WRITE_ONCE(*x, 1);
+	WRITE_ONCE(*y, 1);
+	smp_mb();
+	WRITE_ONCE(*curr, 0);
+}
+
+exists (0:r2=1 /\ 0:r_curr=0 /\ 0:r1=0)
tools/testing/selftests/membarrier/litmus/sched-out-no-sched-mb.litmus new file +34 -0
new file mode 100644
index 000000000000..7b690db2b4be
@@ -0,0 +1,34 @@
+C sched-out-no-sched-mb
+
+(*
+ * Result: Sometimes
+ *
+ * sched-out without the full barrier before the store to rq->curr. The
+ * store to x by the thread can then be delayed past it.
+ *)
+
+{
+	int curr = 1;
+}
+
+P0(int *x, int *y, int *curr)
+{
+	int r_curr;
+	int r1;
+	int r2;
+
+	r2 = READ_ONCE(*y);
+	smp_mb();
+	r_curr = READ_ONCE(*curr);
+	smp_mb();
+	r1 = READ_ONCE(*x);
+}
+
+P1(int *x, int *y, int *curr)
+{
+	WRITE_ONCE(*x, 1);
+	WRITE_ONCE(*y, 1);
+	WRITE_ONCE(*curr, 0);
+}
+
+exists (0:r2=1 /\ 0:r_curr=0 /\ 0:r1=0)
tools/testing/selftests/membarrier/litmus/sched-out.litmus new file +49 -0

49 lines not on this page · raw message

Signature · 1 line
2.47.3
author maintainer
#14 lore raw

PATCH v2 14/16 MAINTAINERS: Add the membarrier selftests to MEMBARRIER SUPPORT

In reply to Mathieu Desnoyers

The MEMBARRIER SUPPORT entry does not list the membarrier selftests. get_maintainer.pl does not report the membarrier maintainers for a change to these tests.

Add tools/testing/selftests/membarrier/ to the entry.

---
 MAINTAINERS | 1 +
 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
index 222b7fc2c3aa..2ee220ccc5e8 100644
@@ -17435,6 +17435,7 @@ F:	arch/*/include/asm/membarrier.h
 F:	arch/*/include/asm/sync_core.h
 F:	include/uapi/linux/membarrier.h
 F:	kernel/sched/membarrier.c
+F:	tools/testing/selftests/membarrier/
 
 MEMBLOCK AND MEMORY MANAGEMENT INITIALIZATION
 M:	Mike Rapoport <[email protected]>
Signature · 1 line
2.47.3
author maintainer
#15 lore raw

PATCH v2 15/16 selftests/membarrier: Check the memory barriers of each thread

In reply to Mathieu Desnoyers

An expedited membarrier command promises that each targeted thread executes a memory barrier during the call. User-space relies on this to leave the barriers out of its fast paths. The kernel keeps the promise with memory barriers in the system call, in its IPI handlers and in the scheduler. If one of them is missing, user-space only sees a rare memory ordering failure.

membarrier_test_ipi checks this promise through the interrupt counts of each CPU. It needs its target threads to stay on their CPU, and it only sees the IPIs. It does not see what the scheduler does.

Add membarrier_test_barrier. It counts, for each thread, the memory barriers which membarrier relies on. It then checks that an expedited command makes each targeted thread execute one. The comment at the top of the file describes the method. No kernel code is added.

The counting works as follows:

- The test lists the kernel functions which hold the instructions, and the kind of instruction to look for in each. It finds them by their bytes in the kernel text, which it reads from /proc/kcore. The kernel refuses a kprobe which is not on the first byte of an instruction, so a wrong match is dropped.

- A BPF program is attached to each instruction with a kprobe. It increments counters of the thread on whose behalf the instruction is executed. For a barrier after the store to rq->curr, this is the thread which is scheduled in.

- A BPF program on the sched_switch tracepoint counts two events for a thread. It was scheduled out. It was scheduled in after a task of another mm or after a kernel thread. The scheduler then owes it a barrier after the store to rq->curr. The program counts a miss if the thread is scheduled out again without it.

- The counters are in a BPF array map, which the test maps in memory.

The test lists the instructions for x86-64 only. They are the smp_mb() of the system call and of the IPI handlers, and the barriers of switch_mm_irqs_off() and finish_task_switch(). This list depends on what the compiler inlines into those functions.

The kernel turns a kprobe into a jump when it can. The handler of such a probe runs with interrupts enabled. The probe of an IPI handler which interrupts it is then skipped. So the test writes 0 to /proc/sys/debug/kprobes-optimization while it runs. It restores the value when it exits.

Each check of a target works as follows:

- The caller pauses for one microsecond between two calls.
- The target reads its counters during two pauses. It can then tell that exactly one call ran in between.
- The IPI counter of the target must have changed.
- A check where the target was scheduled out is dropped: the scheduler covers that target.

The test cases are those of membarrier_test_ipi. Each of them also checks the two memory barriers of the system call, and the barrier of the scheduler after the store to rq->curr.

The thread exit and lazy TLB test cases fail without commit "sched/membarrier: Fix stale runqueue state after a lazy mm switch".

The test needs root. It also needs a kernel with BPF, BTF, kprobes and /proc/kcore. It is skipped otherwise. The Makefile builds it only when clang is found. membarrier_test_ipi stays: it needs none of this.

---
Changes since RFC v1:
- Register a target with the BPF program before it moves to its CPU. The lazy TLB test case now sees the target scheduled in after the idle thread.
- Skip the test, instead of failing, on a kernel without CONFIG_BPF_EVENTS or CONFIG_KPROBE_EVENTS.
- Do not reuse the counter slots of the previous test case. A task which is still exiting can count in its slot.
- All three reported by Sashiko.

---
 tools/testing/selftests/membarrier/.gitignore |    3 +
 tools/testing/selftests/membarrier/Makefile   |   18 +-
 tools/testing/selftests/membarrier/config     |    9 +
 .../membarrier/membarrier_test_barrier.bpf.c  |  168 +++
 .../membarrier/membarrier_test_barrier.c      | 1270 +++++++++++++++++
 .../membarrier/membarrier_test_barrier.h      |   48 +
 6 files changed, 1515 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/membarrier/config
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_barrier.bpf.c
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_barrier.c
 create mode 100644 tools/testing/selftests/membarrier/membarrier_test_barrier.h
tools/testing/selftests/membarrier/.gitignore +3 -0
index 45b995b884a6..161723de5ec5 100644
@@ -4,3 +4,6 @@ membarrier_test_single_thread
 membarrier_rseq_stress
 membarrier_test_ipi
 membarrier_test_cmd
+membarrier_test_barrier
+/tools
+*.bpf.o
tools/testing/selftests/membarrier/Makefile +17 -1
index c7fa0573e978..ad85f5acd541 100644
@@ -8,6 +8,22 @@ TEST_GEN_PROGS := membarrier_test_single_thread \
 		membarrier_test_cmd \
 		membarrier_rseq_stress
 
-LOCAL_HDRS += membarrier_test_impl.h
+LOCAL_HDRS += membarrier_test_impl.h membarrier_test_barrier.h
+
+# membarrier_test_barrier loads BPF programs. Build it only when clang
+# is there, so that the other tests do not need it.
+CLANG ?= clang
+ifneq ($(shell command -v $(CLANG) 2>/dev/null),)
+TEST_GEN_PROGS += membarrier_test_barrier
+TEST_GEN_FILES += membarrier_test_barrier.bpf.o
+else
+$(warning membarrier selftests: skipping membarrier_test_barrier, needs clang)
+endif
 
 include ../lib.mk
+include ../net/bpf.mk
+
+$(OUTPUT)/membarrier_test_barrier.bpf.o: membarrier_test_barrier.h
+$(OUTPUT)/membarrier_test_barrier: $(BPFOBJ)
+$(OUTPUT)/membarrier_test_barrier: CFLAGS += -I$(SCRATCH_DIR)/include
+$(OUTPUT)/membarrier_test_barrier: LDLIBS += -lelf -lz
tools/testing/selftests/membarrier/config new file +9 -0
new file mode 100644
index 000000000000..721da75da204
@@ -0,0 +1,9 @@
+CONFIG_BPF=y
+CONFIG_BPF_EVENTS=y
+CONFIG_BPF_JIT=y
+CONFIG_BPF_SYSCALL=y
+CONFIG_DEBUG_INFO_BTF=y
+CONFIG_KPROBES=y
+CONFIG_KPROBE_EVENTS=y
+CONFIG_MEMBARRIER=y
+CONFIG_PROC_KCORE=y
tools/testing/selftests/membarrier/membarrier_test_barrier.bpf.c new file +168 -0

168 lines not on this page · raw message

tools/testing/selftests/membarrier/membarrier_test_barrier.c new file +1270 -0

1,270 lines not on this page · raw message

tools/testing/selftests/membarrier/membarrier_test_barrier.h new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.47.3
#16 lore raw

Re: [PATCH v2 15/16] selftests/membarrier: Check the memory barriers of each thread

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] selftests/membarrier: run_target() reads missed-barrier stat before sched-out --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] selftests/membarrier: run_target() reads missed-barrier stat before sched-out
--

commit 2ae7bc75d862920739dabb87323389a8eebbf751
Author: Mathieu Desnoyers <[email protected]>

selftests/membarrier: Check the memory barriers of each thread

This commit adds membarrier_test_barrier, a BPF- and kprobe-based selftest that counts per-thread memory barriers executed in the membarrier syscall, IPI handlers, and scheduler paths.

Quoted 6 lines
tools/testing/selftests/membarrier/membarrier_test_barrier.c new file +0 -0
new file mode 100644
index 0000000000000..88c5dbf5d7c79
@@ -0,0 +1,1270 @@

[ ... ]

Quoted 34 lines
tools/testing/selftests/membarrier/membarrier_test_barrier.c new file +34 -0
+/* Run the checks of a target. */
+static void run_target(const struct target *target)
+{
+	struct target_stats *stats = &shared->stats[target->idx];
+	const uint64_t *counters;
+	long deadline = now_ms() + target->ms;
+	unsigned long checks = 0;
+	uint64_t first_ipi, first_sched_in;
+
+	/*
+	 * Register before moving to the CPU. The BPF program then sees
+	 * the target scheduled in there, as in the lazy TLB test case.
+	 */
+	counters = map_counters();
+	if (!counters) {
+		setup_error("register_thread");
+		atomic_fetch_add(&shared->ready, 1);
+		return;
+	}
+	if (target->cpu >= 0 && pin_to_cpu(target->cpu))
+		setup_error("sched_setaffinity");
+	atomic_fetch_add(&shared->ready, 1);
+	while (!atomic_load(&shared->registered) && !atomic_load(&shared->stop))
+		sched_yield();
+	first_ipi = counter(counters, MBT_IPI);
+	first_sched_in = counter(counters, MBT_SCHED_IN);
+	while (!atomic_load(&shared->stop)) {
+		if (check_call(counters, stats) && target->thread_exit &&
+		    !(++checks % 16)) {
+			pthread_t thread;
+
+			if (pthread_create(&thread, NULL, thread_nop, NULL) ||
+			    pthread_join(thread, NULL))
+				setup_error("thread exit");

tools/testing/selftests/membarrier/membarrier_test_barrier.c line 703

Quoted 10 lines
tools/testing/selftests/membarrier/membarrier_test_barrier.c new file +10 -0
+		}
+		if (target->ms && now_ms() >= deadline)
+			break;
+	}
+	atomic_fetch_add(&stats->ipis, counter(counters, MBT_IPI) - first_ipi);
+	atomic_fetch_add(&stats->sched_in,
+			 counter(counters, MBT_SCHED_IN) - first_sched_in);
+	atomic_fetch_add(&stats->sched_in_missed,
+			 counter(counters, MBT_SCHED_IN_MISSED));
+}

[Severity: Medium]
Can run_target() read MBT_SCHED_IN_MISSED before the target thread has scheduled out to flush state->owed?

In membarrier_test_barrier.bpf.c, sched_switch only increments MBT_SCHED_IN_MISSED when the CPU leaves the thread on a subsequent context switch:

tools/testing/selftests/membarrier/membarrier_test_barrier.bpf.c:sched_switch() {
	...
	/* The CPU leaves the thread which it last switched to. */
	if (state->owed & OWES_BARRIER)
		count(state->slot, 1U << MBT_SCHED_IN_MISSED);
	count(slot_of(prev), 1U << MBT_SCHED_OUT);
	...
}

In global_expedited_lazy_tlb, shared->registered is already 1 when run_target() is called, so after pin_to_cpu(target->cpu) switches the child in after the idle thread on cpus[1], the child spins in user space for ROUND_MS and reads MBT_SCHED_IN_MISSED while still running on cpus[1]. If the child is not preempted during that round, the schedule-out on cpus[1] only happens at _exit(0) after run_target() has already recorded stats->sched_in_missed, so a missing scheduler barrier on that switch-in will go undetected.

Also, sampling first_sched_in after pin_to_cpu(target->cpu) subtracts out the MBT_SCHED_IN increment from that initial migration onto target->cpu when computing stats->sched_in. Should first_sched_in be read before pin_to_cpu(), and should run_target() force a schedule-out (e.g. via sched_yield() or migrating off target->cpu) before reading MBT_SCHED_IN_MISSED?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
author maintainer
#17 lore raw

Re: [PATCH v2 15/16] selftests/membarrier: Check the memory barriers of each thread

Quoted 3 lines

[Severity: Medium]
Can run_target() read MBT_SCHED_IN_MISSED before the target thread has scheduled out to flush state->owed?

[...]

Quoted 4 lines

If the child is not preempted during that round, the schedule-out on cpus[1] only happens at _exit(0) after run_target() has already recorded stats->sched_in_missed, so a missing scheduler barrier on that switch-in will go undetected.

Yes. The BPF program counts a missed barrier only when the CPU leaves the thread. So the last switch-in of a target is never checked. This holds for every test case, not only for the lazy TLB one.

I checked it with a variant of the test which does not probe the barriers of a switch-in. Each switch-in then counts as a missed barrier. global_expedited_lazy_tlb ran about 47 rounds. Before the fix, it counted 48 missed barriers. After the fix, it counted 95, so one more per round.

Planned fix for the next round: run_target() waits until the CPU leaves the target before it reads MBT_SCHED_IN_MISSED. It sleeps until the BPF program has counted a schedule-out.

Quoted 6 lines

Also, sampling first_sched_in after pin_to_cpu(target->cpu) subtracts out the MBT_SCHED_IN increment from that initial migration onto target->cpu when computing stats->sched_in. Should first_sched_in be read before pin_to_cpu(), and should run_target() force a schedule-out (e.g. via sched_yield() or migrating off target->cpu) before reading MBT_SCHED_IN_MISSED?

No change planned for first_sched_in. Only EXPECT_NO_IPI uses stats->sched_in. It allows one IPI for each switch-in, and run_target() starts counting both at the same point. The switch-in onto target->cpu happens before the caller starts, so no IPI can follow it.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
author maintainer
#18 lore raw

PATCH v2 16/16 selftests/membarrier: Check the core serialization of the sync core command

In reply to Mathieu Desnoyers

MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE promises more than a memory barrier. Each running sibling thread of the caller executes a core serializing instruction after the call starts, and before it runs user-space code again. A thread which is not running executes one before it resumes user-space. This supports memory reclaim by a JIT compiler.

On x86, the kernel serializes the core in the IPI handler and in the scheduler. membarrier_test_barrier counts the memory barriers of each thread, but not these instructions.

Count them as well. These are the instructions, for x86-64:

- sync_core() in ipi_sync_core(),
- the writes to CR3 in switch_mm_irqs_off(),
- sync_core() in finish_task_switch().

sync_core() issues SERIALIZE or IRET. An IRET cannot be probed, so the instruction before it is probed instead.

The sync core test case then checks two more things:

- A call makes each target execute a core serializing instruction in the IPI handler. A check where the target was scheduled out is dropped.

- A target can be scheduled in after a task of another mm or after a kernel thread. The scheduler then executes a core serializing instruction before the target is scheduled out again.

These checks are skipped with page table isolation. The kernel then serializes the core with the write to CR3 of each return to user-space, in entry code which cannot be probed.

---
 .../membarrier/membarrier_test_barrier.bpf.c  |  11 +-
 .../membarrier/membarrier_test_barrier.c      | 102 +++++++++++++++++-
 .../membarrier/membarrier_test_barrier.h      |   6 ++
 3 files changed, 112 insertions(+), 7 deletions(-)
tools/testing/selftests/membarrier/membarrier_test_barrier.bpf.c +8 -3
index 46cfba13f00f..ce18089f8dab 100644
@@ -1,7 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 /*
- * Count the memory barriers which membarrier relies on, for each
- * registered thread.
+ * Count the memory barriers and the core serializing instructions which
+ * membarrier relies on, for each registered thread.
  *
  * See membarrier_test_barrier.c.
  */
@@ -40,6 +40,7 @@ struct {
 
 /* What the scheduler owes to the thread which it switched to. */
 #define OWES_BARRIER	1
+#define OWES_SYNC_CORE	2
 
 struct cpu_state {
 	/* Slot, plus one, of the thread which this CPU last switched to. */
@@ -111,6 +112,8 @@ int barrier_site(struct pt_regs *ctx)
 		slot = state->slot;
 		if (mask & (1U << MBT_SWITCH_MM))
 			state->owed &= ~OWES_BARRIER;
+		if (mask & (1U << MBT_SYNC_CORE_SWITCH))
+			state->owed &= ~OWES_SYNC_CORE;
 	} else {
 		slot = slot_of(bpf_get_current_task_btf());
 	}
@@ -131,13 +134,15 @@ int BPF_PROG(sched_switch, bool preempt, struct task_struct *prev,
 	/* The CPU leaves the thread which it last switched to. */
 	if (state->owed & OWES_BARRIER)
 		count(state->slot, 1U << MBT_SCHED_IN_MISSED);
+	if (state->owed & OWES_SYNC_CORE)
+		count(state->slot, 1U << MBT_SYNC_CORE_IN_MISSED);
 	count(slot_of(prev), 1U << MBT_SCHED_OUT);
 	slot = slot_of(next);
 	state->slot = slot;
 	state->owed = 0;
 	/* The cases which need a barrier after the store to rq->curr. */
 	if (slot && next->mm && prev->mm != next->mm) {
-		state->owed = OWES_BARRIER;
+		state->owed = OWES_BARRIER | OWES_SYNC_CORE;
 		count(slot, 1U << MBT_SCHED_IN);
 	}
 	return 0;
tools/testing/selftests/membarrier/membarrier_test_barrier.c +98 -4

214 lines not on this page · raw message

tools/testing/selftests/membarrier/membarrier_test_barrier.h +6 -0
index d615ad1d9e8a..7c31d8cba544 100644
@@ -24,6 +24,12 @@ enum {
 	 * the scheduler executed no memory barrier in between.
 	 */
 	MBT_SCHED_IN_MISSED,
+	/* Core serializing instruction of the membarrier IPI handler. */
+	MBT_SYNC_CORE,
+	/* Core serializing instruction of the scheduler. */
+	MBT_SYNC_CORE_SWITCH,
+	/* Like MBT_SCHED_IN_MISSED, for a core serializing instruction. */
+	MBT_SYNC_CORE_IN_MISSED,
 	MBT_NR_COUNTERS,
 };
 
Signature · 1 line
2.47.3