* [PATCH v7 1/6] riscv: build kernel atomics from LR/SC when Zaamo is disabled
2026-11-18 16:23 [PATCH v7 0/6] riscv: restrict the ISA used for atomics to avoid unsupported or slow AMO Vladimir Kondratiev
@ 2026-11-18 16:23 ` Vladimir Kondratiev
2026-11-18 16:23 ` [PATCH v7 2/6] riscv: accept the atomic extensions this kernel was built with Vladimir Kondratiev
` (4 subsequent siblings)
5 siblings, 0 replies; 7+ messages in thread
From: Vladimir Kondratiev @ 2026-11-18 16:23 UTC (permalink / raw)
To: Paul Walmsley, Palmer Dabbelt, Albert Ou, Alexandre Ghiti,
Will Deacon, Peter Zijlstra, Mark Rutland, Gary Guo, Yury Norov,
Rasmus Villemoes, Chao-ying Fu, Conor Dooley, torvalds, olof,
aleksa.paunovic, arikalo, Boqun Feng, Alexei Starovoitov,
Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
Luke Nelson, Xi Wang, Björn Töpel, Pu Lehui,
Puranjay Mohan, Masami Hiramatsu, Oleg Nesterov, Miguel Ojeda,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan, Shuah Khan, Randy Dunlap,
Andrew Jones, Boqun Feng
Cc: Jisheng Zhang, linux-riscv, linux-kernel, Vladimir.Kondratiev,
bpf, linux-trace-kernel, linux-doc, Jonathan Corbet,
Charlie Jenkins, Nam Cao, rust-for-linux, Vladimir Kondratiev
The A extension is Zaamo plus Zalrsc. On some CPUs Zaamo is present
only formally. MIPS P8700 traps every AMO instruction into M-mode and
emulates it there, so the extension is supported but very slow. A
typical uncontended atomic increment costs:
native AMO 2..5 cycles
LR/SC, private L1 reservation monitor 6..12 cycles
LR/SC, PoC (L2) reservation monitor about 40 cycles
AMO emulated by an M-mode trap about 600 cycles
The last two were measured on the eyeq7h hardware. On such a CPU the
kernel must use LR/SC for every atomic.
Add RISCV_ISA_ZAAMO, default y. The default keeps "a" in -march and
the generated code unchanged. When it is disabled, -march carries
_zalrsc instead of "a", and atomic_*, bitops, xchg, futex and the
early boot code use LR/SC loops. The sequence is chosen with the
preprocessor, on CONFIG_RISCV_ISA_ZAAMO like the other ISA options in
the headers, because the assembler rejects AMO mnemonics once -march
lacks Zaamo. A kernel built this way runs on any hart that implements
A; it just does not use AMO. It is therefore a plain option, not a
NONPORTABLE one, and the hart keeps advertising "a" to userspace,
which is true.
The LR/SC loops follow the ordering convention of the existing ones
in cmpxchg.h, from commit 5ce6c1f3535f ("riscv/atomic: Strengthen
implementations with fences") and commit 1d84afaf0252 ("riscv: Fix
fully ordered LR/SC xchg[8|16]() implementations"): a fully ordered
operation is lr, sc.rl and a trailing fence rw,rw; acquire is lr.aq
with a plain sc; release is a plain lr with sc.rl. The futex loop is
bounded to 128 retries and returns -EAGAIN after that, as arm64 does,
because userspace can keep the word changing from another thread and
futex_wake_op() retries on -EAGAIN anyway.
Zabha, Zacas and the ssamoswap instruction of Zicfiss are AMO
instructions, so RISCV_ISA_ZABHA, RISCV_ISA_ZACAS and RISCV_USER_CFI
depend on RISCV_ISA_ZAAMO. The riscv64imac Rust target emits AMO too,
so RUSTC_SUPPORTS_RISCV depends on it as well.
The choice is made at compile time rather than with alternatives.
Nearly every CPU has a native A extension, and an alternative would
inflate all those kernels with the nops needed to pad one AMO to the
size of an LR/SC loop, at every atomic site, for the benefit of a few.
Turning Zaamo off needs a compiler that accepts _zaamo and _zalrsc in
-march. GCC 15.1 is the first release that does.
TOOLCHAIN_HAS_ZALRSC_ZAAMO checks for it; with an older compiler the
option stays at y.
Three sets of extensions provide every atomic Linux needs. "a" is what
the kernel supports today. Zalrsc plus Ziccrse is what this patch adds:
every atomic is a constrained LR/SC loop, and Ziccrse is the
forward-progress guarantee for such loops. Zaamo plus Zacas would do
as well, with CAS loops in place of LR/SC as on x86, and is left for
whoever has such hardware.
Suggested-by: Chao-ying Fu <chao-ying.fu@globalfoundries.com>
Signed-off-by: Vladimir Kondratiev <vladimir.kondratiev@mobileye.com>
---
arch/riscv/Kconfig | 36 +++++++++++++++++++
arch/riscv/Makefile | 15 +++++---
arch/riscv/include/asm/atomic.h | 53 +++++++++++++++++++++++++++-
arch/riscv/include/asm/bitops.h | 76 ++++++++++++++++++++++++++++++++++++++--
arch/riscv/include/asm/cmpxchg.h | 39 +++++++++++++++++----
arch/riscv/include/asm/futex.h | 58 ++++++++++++++++++++++++++++++
arch/riscv/kernel/entry.S | 7 ++++
arch/riscv/kernel/head.S | 12 +++++++
8 files changed, 281 insertions(+), 15 deletions(-)
diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig
index 5874ca30f4f6..3c3679701a60 100644
--- a/arch/riscv/Kconfig
+++ b/arch/riscv/Kconfig
@@ -237,6 +237,8 @@ config RISCV
config RUSTC_SUPPORTS_RISCV
def_bool y
depends on 64BIT
+ # The riscv64imac target emits AMO instructions
+ depends on RISCV_ISA_ZAAMO
config CLANG_SUPPORTS_DYNAMIC_FTRACE
def_bool CC_IS_CLANG
@@ -706,6 +708,7 @@ config RISCV_ISA_ZABHA
bool "Zabha extension support for atomic byte/halfword operations"
depends on TOOLCHAIN_HAS_ZABHA
depends on RISCV_ALTERNATIVE
+ depends on RISCV_ISA_ZAAMO
default y
help
Enable the use of the Zabha ISA-extension to implement kernel
@@ -723,6 +726,7 @@ config TOOLCHAIN_HAS_ZACAS
config RISCV_ISA_ZACAS
bool "Zacas extension support for atomic CAS"
depends on RISCV_ALTERNATIVE
+ depends on RISCV_ISA_ZAAMO
default y
help
Enable the use of the Zacas ISA-extension to implement kernel atomic
@@ -730,6 +734,36 @@ config RISCV_ISA_ZACAS
If you don't know what to do here, say Y.
+config TOOLCHAIN_HAS_ZALRSC_ZAAMO
+ bool
+ default y
+ depends on !64BIT || $(cc-option,-mabi=lp64 -march=rv64im_zaamo_zalrsc)
+ depends on !32BIT || $(cc-option,-mabi=ilp32 -march=rv32im_zaamo_zalrsc)
+
+config RISCV_ISA_ZAAMO
+ bool "Zaamo extension support for AMO atomics" if TOOLCHAIN_HAS_ZALRSC_ZAAMO
+ default y
+ help
+ Use AMO instructions for kernel atomic memory operations. When
+ disabled, those operations are built from LR/SC and the kernel
+ is compiled with zalrsc instead of the A extension.
+
+ Disable this for a CPU where AMO is much slower than LR/SC. That
+ is the case when AMO instructions are emulated by a trap into
+ M-mode, as on the MIPS P8700: an emulated atomic costs hundreds
+ of cycles where LR/SC costs tens.
+
+ A kernel built without Zaamo runs on any CPU that implements the
+ A extension. Zabha, Zacas, userspace control flow integrity and
+ Rust need Zaamo and are unavailable without it.
+
+ The compiler must accept _zaamo and _zalrsc in -march to make
+ this choice. GCC 15.1 is the first release that does. With an
+ older compiler the option stays enabled and -march keeps the A
+ extension.
+
+ If you don't know what to do here, say Y.
+
config TOOLCHAIN_HAS_ZBB
bool
default y
@@ -1206,6 +1240,8 @@ config RISCV_USER_CFI
depends on 64BIT && MMU && \
$(cc-option,-mabi=lp64 -march=rv64ima_zicfiss_zicfilp -fcf-protection=full)
depends on RISCV_ALTERNATIVE
+ # ssamoswap is an AMO instruction
+ depends on RISCV_ISA_ZAAMO
select RISCV_SBI
select ARCH_HAS_USER_SHADOW_STACK
select ARCH_USES_HIGH_VMA_FLAGS
diff --git a/arch/riscv/Makefile b/arch/riscv/Makefile
index 44f5a439741a..59c5123c5485 100644
--- a/arch/riscv/Makefile
+++ b/arch/riscv/Makefile
@@ -58,8 +58,9 @@ ifeq ($(CONFIG_SHADOW_CALL_STACK),y)
endif
# ISA string setting
-riscv-march-$(CONFIG_ARCH_RV32I) := rv32ima
-riscv-march-$(CONFIG_ARCH_RV64I) := rv64ima
+riscv-march-$(CONFIG_ARCH_RV32I) := rv32im
+riscv-march-$(CONFIG_ARCH_RV64I) := rv64im
+riscv-march-$(CONFIG_RISCV_ISA_ZAAMO) := $(riscv-march-y)a
riscv-march-$(CONFIG_FPU) := $(riscv-march-y)fd
riscv-march-$(CONFIG_RISCV_ISA_C) := $(riscv-march-y)c
riscv-march-$(CONFIG_RISCV_ISA_V) := $(riscv-march-y)v
@@ -75,9 +76,15 @@ else
riscv-march-$(CONFIG_TOOLCHAIN_NEEDS_EXPLICIT_ZICSR_ZIFENCEI) := $(riscv-march-y)_zicsr_zifencei
endif
-KBUILD_BASE_ISA = -march=$(shell echo $(riscv-march-y) | sed -E 's/(rv32ima|rv64ima)fd([^v_]*)v?/\1\2/')
+KBUILD_BASE_ISA = -march=$(shell echo $(riscv-march-y) | sed -E 's/(rv32ima?|rv64ima?)fd([^v_]*)v?/\1\2/')
export KBUILD_BASE_ISA
+# Without Zaamo only the LR/SC half of "a" is used. The compiler accepts
+# _zalrsc here, see TOOLCHAIN_HAS_ZALRSC_ZAAMO.
+ifneq ($(CONFIG_RISCV_ISA_ZAAMO),y)
+riscv-march-y := $(riscv-march-y)_zalrsc
+endif
+
# Remove F,D,V from isa string for all. Keep extensions between "fd" and "v" by
# matching non-v and non-multi-letter extensions out with the filter ([^v_]*)
KBUILD_CFLAGS += $(KBUILD_BASE_ISA)
@@ -85,7 +92,7 @@ KBUILD_CFLAGS += $(KBUILD_BASE_ISA)
KBUILD_AFLAGS += -march=$(riscv-march-y)
# For C code built with floating-point support, exclude V but keep F and D.
-CC_FLAGS_FPU := -march=$(shell echo $(riscv-march-y) | sed -E 's/(rv32ima|rv64ima)([^v_]*)v?/\1\2/')
+CC_FLAGS_FPU := -march=$(shell echo $(riscv-march-y) | sed -E 's/(rv32ima?|rv64ima?)([^v_]*)v?/\1\2/')
KBUILD_CFLAGS += -mno-save-restore
diff --git a/arch/riscv/include/asm/atomic.h b/arch/riscv/include/asm/atomic.h
index 616b8b332ac5..cca1fc3a68ff 100644
--- a/arch/riscv/include/asm/atomic.h
+++ b/arch/riscv/include/asm/atomic.h
@@ -50,6 +50,7 @@ static __always_inline void arch_atomic64_set(atomic64_t *v, s64 i)
* have the AQ or RL bits set. These don't return anything, so there's only
* one version to worry about.
*/
+#ifdef CONFIG_RISCV_ISA_ZAAMO
#define ATOMIC_OP(op, asm_op, I, asm_type, c_type, prefix) \
static __always_inline \
void arch_atomic##prefix##_##op(c_type i, atomic##prefix##_t *v) \
@@ -59,7 +60,23 @@ void arch_atomic##prefix##_##op(c_type i, atomic##prefix##_t *v) \
: "+A" (v->counter) \
: "r" (I) \
: "memory"); \
-} \
+}
+#else
+#define ATOMIC_OP(op, asm_op, I, asm_type, c_type, prefix) \
+static __always_inline \
+void arch_atomic##prefix##_##op(c_type i, atomic##prefix##_t *v) \
+{ \
+ register c_type ret, temp; \
+ __asm__ __volatile__ ( \
+ "1: lr." #asm_type " %1, %0\n" \
+ " " #asm_op " %2, %1, %3\n" \
+ " sc." #asm_type " %2, %2, %0\n" \
+ " bnez %2, 1b\n" \
+ : "+A" (v->counter), "=&r" (ret), "=&r" (temp) \
+ : "r" (I) \
+ : "memory"); \
+}
+#endif
#ifdef CONFIG_GENERIC_ATOMIC64
#define ATOMIC_OPS(op, asm_op, I) \
@@ -84,6 +101,7 @@ ATOMIC_OPS(xor, xor, i)
* There's two flavors of these: the arithmetic ops have both fetch and return
* versions, while the logical ops only have fetch versions.
*/
+#ifdef CONFIG_RISCV_ISA_ZAAMO
#define ATOMIC_FETCH_OP(op, asm_op, I, asm_type, c_type, prefix) \
static __always_inline \
c_type arch_atomic##prefix##_fetch_##op##_relaxed(c_type i, \
@@ -108,6 +126,39 @@ c_type arch_atomic##prefix##_fetch_##op(c_type i, atomic##prefix##_t *v) \
: "memory"); \
return ret; \
}
+#else
+#define ATOMIC_FETCH_OP(op, asm_op, I, asm_type, c_type, prefix) \
+static __always_inline \
+c_type arch_atomic##prefix##_fetch_##op##_relaxed(c_type i, \
+ atomic##prefix##_t *v) \
+{ \
+ register c_type ret, temp; \
+ __asm__ __volatile__ ( \
+ "1: lr." #asm_type " %1, %0\n" \
+ " " #asm_op " %2, %1, %3\n" \
+ " sc." #asm_type " %2, %2, %0\n" \
+ " bnez %2, 1b\n" \
+ : "+A" (v->counter), "=&r" (ret), "=&r" (temp) \
+ : "r" (I) \
+ : "memory"); \
+ return ret; \
+} \
+static __always_inline \
+c_type arch_atomic##prefix##_fetch_##op(c_type i, atomic##prefix##_t *v) \
+{ \
+ register c_type ret, temp; \
+ __asm__ __volatile__ ( \
+ "1: lr." #asm_type " %1, %0\n" \
+ " " #asm_op " %2, %1, %3\n" \
+ " sc." #asm_type ".rl %2, %2, %0\n" \
+ " bnez %2, 1b\n" \
+ RISCV_FULL_BARRIER \
+ : "+A" (v->counter), "=&r" (ret), "=&r" (temp) \
+ : "r" (I) \
+ : "memory"); \
+ return ret; \
+}
+#endif
#define ATOMIC_OP_RETURN(op, asm_op, c_op, I, asm_type, c_type, prefix) \
static __always_inline \
diff --git a/arch/riscv/include/asm/bitops.h b/arch/riscv/include/asm/bitops.h
index 3c1a15be54d8..adcd70525774 100644
--- a/arch/riscv/include/asm/bitops.h
+++ b/arch/riscv/include/asm/bitops.h
@@ -170,12 +170,17 @@ static __always_inline int variable_fls(unsigned int x)
#if (BITS_PER_LONG == 64)
#define __AMO(op) "amo" #op ".d"
+#define __LR "lr.d"
+#define __SC "sc.d"
#elif (BITS_PER_LONG == 32)
#define __AMO(op) "amo" #op ".w"
+#define __LR "lr.w"
+#define __SC "sc.w"
#else
#error "Unexpected BITS_PER_LONG"
#endif
+#ifdef CONFIG_RISCV_ISA_ZAAMO
#define __test_and_op_bit_ord(op, mod, nr, addr, ord) \
({ \
unsigned long __res, __mask; \
@@ -195,10 +200,58 @@ static __always_inline int variable_fls(unsigned int x)
: "r" (mod(BIT_MASK(nr))) \
: "memory");
-#define __test_and_op_bit(op, mod, nr, addr) \
+#define __test_and_op_bit(op, mod, nr, addr) \
__test_and_op_bit_ord(op, mod, nr, addr, .aqrl)
+#define __test_and_op_bit_acquire(op, mod, nr, addr) \
+ __test_and_op_bit_ord(op, mod, nr, addr, .aq)
#define __op_bit(op, mod, nr, addr) \
__op_bit_ord(op, mod, nr, addr, )
+#define __op_bit_release(op, mod, nr, addr) \
+ __op_bit_ord(op, mod, nr, addr, .rl)
+#else
+/*
+ * Fully ordered LR/SC is lr, sc.rl and a full fence; acquire is lr.aq and
+ * release is sc.rl, with no ordering on the other instruction. This is how
+ * the LR/SC loops in asm/atomic.h and asm/cmpxchg.h are built.
+ */
+#define __test_and_op_bit_lrsc(op, mod, nr, addr, lr_sfx, sc_sfx, append) \
+({ \
+ unsigned long __res, __mask, __temp; \
+ __mask = BIT_MASK(nr); \
+ __asm__ __volatile__ ( \
+ "1: " __LR lr_sfx " %0, %1\n" \
+ #op " %2, %0, %3\n" \
+ __SC sc_sfx " %2, %2, %1\n" \
+ "bnez %2, 1b\n" \
+ append \
+ : "=&r" (__res), "+A" (addr[BIT_WORD(nr)]), "=&r" (__temp) \
+ : "r" (mod(__mask)) \
+ : "memory"); \
+ ((__res & __mask) != 0); \
+})
+
+#define __op_bit_lrsc(op, mod, nr, addr, lr_sfx, sc_sfx) \
+do { \
+ unsigned long __res, __temp; \
+ __asm__ __volatile__ ( \
+ "1: " __LR lr_sfx " %0, %1\n" \
+ #op " %2, %0, %3\n" \
+ __SC sc_sfx " %2, %2, %1\n" \
+ "bnez %2, 1b\n" \
+ : "=&r" (__res), "+A" (addr[BIT_WORD(nr)]), "=&r" (__temp) \
+ : "r" (mod(BIT_MASK(nr))) \
+ : "memory"); \
+} while (0)
+
+#define __test_and_op_bit(op, mod, nr, addr) \
+ __test_and_op_bit_lrsc(op, mod, nr, addr, "", ".rl", RISCV_FULL_BARRIER)
+#define __test_and_op_bit_acquire(op, mod, nr, addr) \
+ __test_and_op_bit_lrsc(op, mod, nr, addr, ".aq", "", "")
+#define __op_bit(op, mod, nr, addr) \
+ __op_bit_lrsc(op, mod, nr, addr, "", "")
+#define __op_bit_release(op, mod, nr, addr) \
+ __op_bit_lrsc(op, mod, nr, addr, "", ".rl")
+#endif
/* Bitmask modifiers */
#define __NOP(x) (x)
@@ -297,7 +350,7 @@ static __always_inline void arch_change_bit(int nr, volatile unsigned long *addr
static __always_inline int arch_test_and_set_bit_lock(
unsigned long nr, volatile unsigned long *addr)
{
- return __test_and_op_bit_ord(or, __NOP, nr, addr, .aq);
+ return __test_and_op_bit_acquire(or, __NOP, nr, addr);
}
/**
@@ -310,7 +363,7 @@ static __always_inline int arch_test_and_set_bit_lock(
static __always_inline void arch_clear_bit_unlock(
unsigned long nr, volatile unsigned long *addr)
{
- __op_bit_ord(and, __NOT, nr, addr, .rl);
+ __op_bit_release(and, __NOT, nr, addr);
}
/**
@@ -337,20 +390,37 @@ static __always_inline void arch___clear_bit_unlock(
static __always_inline bool arch_xor_unlock_is_negative_byte(unsigned long mask,
volatile unsigned long *addr)
{
+#ifdef CONFIG_RISCV_ISA_ZAAMO
unsigned long res;
__asm__ __volatile__ (
__AMO(xor) ".rl %0, %2, %1"
: "=r" (res), "+A" (*addr)
: "r" (__NOP(mask))
: "memory");
+#else
+ unsigned long res, temp;
+
+ __asm__ __volatile__ (
+ "1: " __LR " %0, %1\n"
+ "xor %2, %0, %3\n"
+ __SC ".rl %2, %2, %1\n"
+ "bnez %2, 1b\n"
+ : "=&r" (res), "+A" (*addr), "=&r" (temp)
+ : "r" (__NOP(mask))
+ : "memory");
+#endif
return (res & BIT(7)) != 0;
}
#undef __test_and_op_bit
+#undef __test_and_op_bit_acquire
#undef __op_bit
+#undef __op_bit_release
#undef __NOP
#undef __NOT
#undef __AMO
+#undef __LR
+#undef __SC
#include <asm-generic/bitops/instrumented-atomic.h>
#include <asm-generic/bitops/instrumented-lock.h>
diff --git a/arch/riscv/include/asm/cmpxchg.h b/arch/riscv/include/asm/cmpxchg.h
index 662e160b0522..f0199432948a 100644
--- a/arch/riscv/include/asm/cmpxchg.h
+++ b/arch/riscv/include/asm/cmpxchg.h
@@ -57,16 +57,39 @@
} \
})
-#define __arch_xchg(sfx, prepend, append, r, p, n) \
+/*
+ * Word and double-word xchg is one amoswap, or an LR/SC loop without
+ * Zaamo. Each form uses its own pair of ordering arguments, as in
+ * __arch_xchg_masked() above.
+ */
+#ifdef CONFIG_RISCV_ISA_ZAAMO
+#define __arch_xchg(w, sc_sfx, swap_sfx, prepend, sc_append, \
+ swap_append, r, p, n) \
({ \
__asm__ __volatile__ ( \
prepend \
- " amoswap" sfx " %0, %2, %1\n" \
- append \
+ " amoswap" w swap_sfx " %0, %2, %1\n" \
+ swap_append \
: "=r" (r), "+A" (*(p)) \
: "r" (n) \
: "memory"); \
})
+#else
+#define __arch_xchg(w, sc_sfx, swap_sfx, prepend, sc_append, \
+ swap_append, r, p, n) \
+({ \
+ __typeof__(*(p)) __temp; \
+ __asm__ __volatile__ ( \
+ prepend \
+ "1: lr" w " %0, %1\n" \
+ " sc" w sc_sfx " %2, %3, %1\n" \
+ " bnez %2, 1b\n" \
+ sc_append \
+ : "=&r" (r), "+A" (*(p)), "=&r" (__temp) \
+ : "r" (n) \
+ : "memory"); \
+})
+#endif
#define _arch_xchg(ptr, new, sc_sfx, swap_sfx, prepend, \
sc_append, swap_append) \
@@ -87,12 +110,14 @@
__ret, __ptr, __new); \
break; \
case 4: \
- __arch_xchg(".w" swap_sfx, prepend, swap_append, \
- __ret, __ptr, __new); \
+ __arch_xchg(".w", sc_sfx, swap_sfx, \
+ prepend, sc_append, swap_append, \
+ __ret, __ptr, __new); \
break; \
case 8: \
- __arch_xchg(".d" swap_sfx, prepend, swap_append, \
- __ret, __ptr, __new); \
+ __arch_xchg(".d", sc_sfx, swap_sfx, \
+ prepend, sc_append, swap_append, \
+ __ret, __ptr, __new); \
break; \
default: \
BUILD_BUG(); \
diff --git a/arch/riscv/include/asm/futex.h b/arch/riscv/include/asm/futex.h
index 6f3bc9bdb85e..e79d28af55cd 100644
--- a/arch/riscv/include/asm/futex.h
+++ b/arch/riscv/include/asm/futex.h
@@ -12,6 +12,7 @@
#include <linux/errno.h>
#include <asm/asm.h>
#include <asm/asm-extable.h>
+#include <asm/fence.h>
/* We don't even really need the extable code, but for now keep it simple */
#ifndef CONFIG_MMU
@@ -19,6 +20,7 @@
#define __disable_user_access() do { } while (0)
#endif
+#ifdef CONFIG_RISCV_ISA_ZAAMO
#define __futex_atomic_op(insn, ret, oldval, uaddr, oparg) \
{ \
__enable_user_access(); \
@@ -32,6 +34,39 @@
: "memory"); \
__disable_user_access(); \
}
+#else
+/*
+ * Bound the number of LR/SC retries, as arm64 does for LL/SC: a user can
+ * keep the word changing from another thread forever. futex_wake_op()
+ * retries on -EAGAIN after dropping the hash bucket locks.
+ */
+#define FUTEX_MAX_LOOPS 128
+
+#define __futex_atomic_op(insn, ret, oldval, uaddr, oparg) \
+{ \
+ int temp, loops = FUTEX_MAX_LOOPS; \
+ \
+ __enable_user_access(); \
+ __asm__ __volatile__ ( \
+ "1: lr.w %[ov], %[u] \n" \
+ " " insn " \n" \
+ "2: sc.w.rl %[t], %[t], %[u] \n" \
+ " beqz %[t], 3f \n" \
+ " addi %[l], %[l], -1 \n" \
+ " bnez %[l], 1b \n" \
+ " li %[r], %[ea] \n" \
+ "3: \n" \
+ RISCV_FULL_BARRIER \
+ _ASM_EXTABLE_UACCESS_ERR(1b, 3b, %[r]) \
+ _ASM_EXTABLE_UACCESS_ERR(2b, 3b, %[r]) \
+ : [r] "+r" (ret), [ov] "=&r" (oldval), \
+ [t] "=&r" (temp), [l] "+&r" (loops), \
+ [u] "+m" (*(uaddr)) \
+ : [op] "Jr" (oparg), [ea] "I" (-EAGAIN) \
+ : "memory"); \
+ __disable_user_access(); \
+}
+#endif
static inline int
arch_futex_atomic_op_inuser(int op, int oparg, int *oval, u32 __user *uaddr)
@@ -43,6 +78,7 @@ arch_futex_atomic_op_inuser(int op, int oparg, int *oval, u32 __user *uaddr)
uaddr = untagged_addr(uaddr);
switch (op) {
+#ifdef CONFIG_RISCV_ISA_ZAAMO
case FUTEX_OP_SET:
__futex_atomic_op("amoswap.w.aqrl %[ov],%z[op],%[u]",
ret, oldval, uaddr, oparg);
@@ -63,6 +99,28 @@ arch_futex_atomic_op_inuser(int op, int oparg, int *oval, u32 __user *uaddr)
__futex_atomic_op("amoxor.w.aqrl %[ov],%z[op],%[u]",
ret, oldval, uaddr, oparg);
break;
+#else
+ case FUTEX_OP_SET:
+ __futex_atomic_op("mv %[t], %z[op]",
+ ret, oldval, uaddr, oparg);
+ break;
+ case FUTEX_OP_ADD:
+ __futex_atomic_op("add %[t], %[ov], %z[op]",
+ ret, oldval, uaddr, oparg);
+ break;
+ case FUTEX_OP_OR:
+ __futex_atomic_op("or %[t], %[ov], %z[op]",
+ ret, oldval, uaddr, oparg);
+ break;
+ case FUTEX_OP_ANDN:
+ __futex_atomic_op("and %[t], %[ov], %z[op]",
+ ret, oldval, uaddr, ~oparg);
+ break;
+ case FUTEX_OP_XOR:
+ __futex_atomic_op("xor %[t], %[ov], %z[op]",
+ ret, oldval, uaddr, oparg);
+ break;
+#endif
default:
ret = -ENOSYS;
}
diff --git a/arch/riscv/kernel/entry.S b/arch/riscv/kernel/entry.S
index 61b7a7716697..ba2db6804a6c 100644
--- a/arch/riscv/kernel/entry.S
+++ b/arch/riscv/kernel/entry.S
@@ -73,7 +73,14 @@
beq a2, zero, .Lnew_valid_map_cpus_restore_context
/* Atomically reset the current cpu bit in new_valid_map_cpus */
+#ifdef CONFIG_RISCV_ISA_ZAAMO
amoxor.d a0, a1, (a0)
+#else
+1: lr.d a2, (a0)
+ xor a2, a1, a2
+ sc.d a2, a2, (a0)
+ bnez a2, 1b
+#endif
/*
* A sfence.vma is required here. Even if we had Svvptc, there's no
diff --git a/arch/riscv/kernel/head.S b/arch/riscv/kernel/head.S
index f6a8ca49e627..dc3862ed29c4 100644
--- a/arch/riscv/kernel/head.S
+++ b/arch/riscv/kernel/head.S
@@ -265,7 +265,19 @@ SYM_CODE_START(_start_kernel)
/* Pick one hart to run the main boot sequence */
la a3, hart_lottery
li a2, 1
+#ifdef CONFIG_RISCV_ISA_ZAAMO
amoadd.w a3, a2, (a3)
+#else
+ /*
+ * hart_lottery is a small 32-bit counter. add is valid on RV32
+ * and RV64; sc.w stores the low 32 bits.
+ */
+1: lr.w t0, (a3)
+ add t1, t0, a2
+ sc.w t1, t1, (a3)
+ bnez t1, 1b
+ mv a3, t0
+#endif
bnez a3, .Lsecondary_start
#endif /* CONFIG_RISCV_BOOT_SPINWAIT */
--
2.43.0
^ permalink raw reply [flat|nested] 7+ messages in thread* [PATCH v7 2/6] riscv: accept the atomic extensions this kernel was built with
2026-11-18 16:23 [PATCH v7 0/6] riscv: restrict the ISA used for atomics to avoid unsupported or slow AMO Vladimir Kondratiev
2026-11-18 16:23 ` [PATCH v7 1/6] riscv: build kernel atomics from LR/SC when Zaamo is disabled Vladimir Kondratiev
@ 2026-11-18 16:23 ` Vladimir Kondratiev
2026-11-18 16:23 ` [PATCH v7 3/6] riscv: report the A extension when Zaamo and Zalrsc are both present Vladimir Kondratiev
` (3 subsequent siblings)
5 siblings, 0 replies; 7+ messages in thread
From: Vladimir Kondratiev @ 2026-11-18 16:23 UTC (permalink / raw)
To: Paul Walmsley, Palmer Dabbelt, Albert Ou, Alexandre Ghiti,
Will Deacon, Peter Zijlstra, Mark Rutland, Gary Guo, Yury Norov,
Rasmus Villemoes, Chao-ying Fu, Conor Dooley, torvalds, olof,
aleksa.paunovic, arikalo, Boqun Feng, Alexei Starovoitov,
Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
Luke Nelson, Xi Wang, Björn Töpel, Pu Lehui,
Puranjay Mohan, Masami Hiramatsu, Oleg Nesterov, Miguel Ojeda,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan, Shuah Khan, Randy Dunlap,
Andrew Jones, Boqun Feng
Cc: Jisheng Zhang, linux-riscv, linux-kernel, Vladimir.Kondratiev,
bpf, linux-trace-kernel, linux-doc, Jonathan Corbet,
Charlie Jenkins, Nam Cao, rust-for-linux, Vladimir Kondratiev
riscv_early_of_processor_hartid() rejects a hart unless its
riscv,isa-extensions property contains "a". A hart that lists "zaamo"
and "zalrsc" instead of "a" is rejected, and so is one that lists only
"zalrsc", even when the kernel was built to use only LR/SC.
Accept "a" as before. Without it, require "zalrsc", which every kernel
uses for cmpxchg, and "zaamo" when RISCV_ISA_ZAAMO is enabled. The
default build therefore needs "a", or "zaamo" together with "zalrsc";
a kernel built without Zaamo needs only "zalrsc".
The legacy "riscv,isa" fallback keeps its rv{32,64}ima check.
Once such a hart can boot, hwprobe must stop telling userspace that
the base behaviour is IMA regardless of the hardware: report
RISCV_HWPROBE_BASE_BEHAVIOR_IMA only when every selected hart has A.
A hart with Zalrsc alone still shows what it has through
RISCV_HWPROBE_EXT_ZALRSC in RISCV_HWPROBE_KEY_IMA_EXT_0.
Signed-off-by: Vladimir Kondratiev <vladimir.kondratiev@mobileye.com>
---
Documentation/arch/riscv/hwprobe.rst | 4 +++-
arch/riscv/kernel/cpu.c | 23 ++++++++++++++++++++---
arch/riscv/kernel/sys_hwprobe.c | 23 ++++++++++++++++++-----
3 files changed, 41 insertions(+), 9 deletions(-)
diff --git a/Documentation/arch/riscv/hwprobe.rst b/Documentation/arch/riscv/hwprobe.rst
index bb1e0cbab36f..63d7ef028bf8 100644
--- a/Documentation/arch/riscv/hwprobe.rst
+++ b/Documentation/arch/riscv/hwprobe.rst
@@ -61,7 +61,9 @@ The following keys are defined:
* :c:macro:`RISCV_HWPROBE_BASE_BEHAVIOR_IMA`: Support for rv32ima or
rv64ima, as defined by version 2.2 of the user ISA and version 1.10 of the
privileged ISA, with the following known exceptions (more exceptions may be
- added, but only if it can be demonstrated that the user ABI is not broken):
+ added, but only if it can be demonstrated that the user ABI is not broken).
+ This bit is clear on a hart that implements Zalrsc without Zaamo; such a
+ hart lists its atomic support in :c:macro:`RISCV_HWPROBE_KEY_IMA_EXT_0`.
* The ``fence.i`` instruction cannot be directly executed by userspace
programs (it may still be executed in userspace via a
diff --git a/arch/riscv/kernel/cpu.c b/arch/riscv/kernel/cpu.c
index 3dbc8cc557dd..9ba0d49c87bc 100644
--- a/arch/riscv/kernel/cpu.c
+++ b/arch/riscv/kernel/cpu.c
@@ -82,12 +82,29 @@ int __init riscv_early_of_processor_hartid(struct device_node *node, unsigned lo
return -ENODEV;
if (of_property_match_string(node, "riscv,isa-extensions", "i") < 0 ||
- of_property_match_string(node, "riscv,isa-extensions", "m") < 0 ||
- of_property_match_string(node, "riscv,isa-extensions", "a") < 0) {
- pr_warn("CPU with hartid=%lu does not support ima", *hart);
+ of_property_match_string(node, "riscv,isa-extensions", "m") < 0) {
+ pr_warn("CPU with hartid=%lu does not support im", *hart);
return -ENODEV;
}
+ /*
+ * Require the atomic extensions this kernel was built with. "a"
+ * covers both; otherwise LR/SC is always needed and AMO is needed
+ * when the kernel uses it.
+ */
+ if (of_property_match_string(node, "riscv,isa-extensions", "a") < 0) {
+ if (of_property_match_string(node, "riscv,isa-extensions", "zalrsc") < 0) {
+ pr_warn("CPU with hartid=%lu does not support zalrsc", *hart);
+ return -ENODEV;
+ }
+
+ if (IS_ENABLED(CONFIG_RISCV_ISA_ZAAMO) &&
+ of_property_match_string(node, "riscv,isa-extensions", "zaamo") < 0) {
+ pr_warn("CPU with hartid=%lu does not support zaamo", *hart);
+ return -ENODEV;
+ }
+ }
+
return 0;
old_interface:
diff --git a/arch/riscv/kernel/sys_hwprobe.c b/arch/riscv/kernel/sys_hwprobe.c
index 7818e1d32622..52c4c2085d0a 100644
--- a/arch/riscv/kernel/sys_hwprobe.c
+++ b/arch/riscv/kernel/sys_hwprobe.c
@@ -213,6 +213,18 @@ static void hwprobe_isa_ext1(struct riscv_hwprobe *pair,
pair->value &= ~missing;
}
+static bool hwprobe_all_cpus_have(const struct cpumask *cpus, unsigned long ext)
+{
+ int cpu;
+
+ for_each_cpu(cpu, cpus) {
+ if (!__riscv_isa_extension_available(hart_isa[cpu].isa, ext))
+ return false;
+ }
+
+ return true;
+}
+
static bool hwprobe_ext0_has(const struct cpumask *cpus, u64 ext)
{
struct riscv_hwprobe pair;
@@ -306,13 +318,14 @@ static void hwprobe_one_pair(struct riscv_hwprobe *pair,
hwprobe_arch_id(pair, cpus);
break;
/*
- * The kernel already assumes that the base single-letter ISA
- * extensions are supported on all harts, and only supports the
- * IMA base, so just cheat a bit here and tell that to
- * userspace.
+ * The kernel requires I and M on every hart, so IMA holds when
+ * every selected hart has A as well. A hart that lists only
+ * Zalrsc boots on a kernel built without Zaamo, but it has no
+ * AMO instructions and must not be reported as IMA.
*/
case RISCV_HWPROBE_KEY_BASE_BEHAVIOR:
- pair->value = RISCV_HWPROBE_BASE_BEHAVIOR_IMA;
+ if (hwprobe_all_cpus_have(cpus, RISCV_ISA_EXT_A))
+ pair->value = RISCV_HWPROBE_BASE_BEHAVIOR_IMA;
break;
case RISCV_HWPROBE_KEY_IMA_EXT_0:
--
2.43.0
^ permalink raw reply [flat|nested] 7+ messages in thread* [PATCH v7 3/6] riscv: report the A extension when Zaamo and Zalrsc are both present
2026-11-18 16:23 [PATCH v7 0/6] riscv: restrict the ISA used for atomics to avoid unsupported or slow AMO Vladimir Kondratiev
2026-11-18 16:23 ` [PATCH v7 1/6] riscv: build kernel atomics from LR/SC when Zaamo is disabled Vladimir Kondratiev
2026-11-18 16:23 ` [PATCH v7 2/6] riscv: accept the atomic extensions this kernel was built with Vladimir Kondratiev
@ 2026-11-18 16:23 ` Vladimir Kondratiev
2026-11-18 16:24 ` [PATCH v7 4/6] riscv, bpf: emit LR/SC loops when Zaamo is disabled Vladimir Kondratiev
` (2 subsequent siblings)
5 siblings, 0 replies; 7+ messages in thread
From: Vladimir Kondratiev @ 2026-11-18 16:23 UTC (permalink / raw)
To: Paul Walmsley, Palmer Dabbelt, Albert Ou, Alexandre Ghiti,
Will Deacon, Peter Zijlstra, Mark Rutland, Gary Guo, Yury Norov,
Rasmus Villemoes, Chao-ying Fu, Conor Dooley, torvalds, olof,
aleksa.paunovic, arikalo, Boqun Feng, Alexei Starovoitov,
Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
Luke Nelson, Xi Wang, Björn Töpel, Pu Lehui,
Puranjay Mohan, Masami Hiramatsu, Oleg Nesterov, Miguel Ojeda,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan, Shuah Khan, Randy Dunlap,
Andrew Jones, Boqun Feng
Cc: Jisheng Zhang, linux-riscv, linux-kernel, Vladimir.Kondratiev,
bpf, linux-trace-kernel, linux-doc, Jonathan Corbet,
Charlie Jenkins, Nam Cao, rust-for-linux, Vladimir Kondratiev
A hart may describe its atomics as "a", or as "zaamo" and "zalrsc".
The two are the same thing: the A extension is defined as Zaamo plus
Zalrsc. The kernel already expands "a" into both sub-extensions, but
not the other way round, so a hart that lists the sub-extensions ends
up without RISCV_ISA_EXT_A. /proc/cpuinfo then shows rv64imfdc... and
the A bit is missing from ELF hwcap, although the hardware is the
same as one that lists "a".
Set A in the source ISA bitmap when both Zaamo and Zalrsc are there,
before the bitmap is resolved, so that hwcap and cpuinfo do not depend
on how the firmware spelled it. This covers the "riscv,isa" string and
ACPI as well as "riscv,isa-extensions".
Signed-off-by: Vladimir Kondratiev <vladimir.kondratiev@mobileye.com>
---
arch/riscv/kernel/cpufeature.c | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/arch/riscv/kernel/cpufeature.c b/arch/riscv/kernel/cpufeature.c
index 7329792978cc..45684e129be1 100644
--- a/arch/riscv/kernel/cpufeature.c
+++ b/arch/riscv/kernel/cpufeature.c
@@ -682,6 +682,15 @@ static void __init riscv_resolve_isa(unsigned long *source_isa,
int max_loop_count = riscv_isa_ext_count, ret;
unsigned int bit;
+ /*
+ * "a" is exactly Zaamo plus Zalrsc. A hart that lists both has A,
+ * however the firmware spelled it, so report it the same way in
+ * ELF hwcap and /proc/cpuinfo.
+ */
+ if (test_bit(RISCV_ISA_EXT_ZAAMO, source_isa) &&
+ test_bit(RISCV_ISA_EXT_ZALRSC, source_isa))
+ set_bit(RISCV_ISA_EXT_A, source_isa);
+
do {
loop = false;
if (max_loop_count-- < 0) {
--
2.43.0
^ permalink raw reply [flat|nested] 7+ messages in thread* [PATCH v7 4/6] riscv, bpf: emit LR/SC loops when Zaamo is disabled
2026-11-18 16:23 [PATCH v7 0/6] riscv: restrict the ISA used for atomics to avoid unsupported or slow AMO Vladimir Kondratiev
` (2 preceding siblings ...)
2026-11-18 16:23 ` [PATCH v7 3/6] riscv: report the A extension when Zaamo and Zalrsc are both present Vladimir Kondratiev
@ 2026-11-18 16:24 ` Vladimir Kondratiev
2026-11-18 16:24 ` [PATCH v7 5/6] riscv: hwprobe: update the vDSO data after the boot-time speed probes Vladimir Kondratiev
2026-11-18 16:24 ` [PATCH v7 6/6] riscv: hwprobe: report whether AMO is faster than LR/SC Vladimir Kondratiev
5 siblings, 0 replies; 7+ messages in thread
From: Vladimir Kondratiev @ 2026-11-18 16:24 UTC (permalink / raw)
To: Paul Walmsley, Palmer Dabbelt, Albert Ou, Alexandre Ghiti,
Will Deacon, Peter Zijlstra, Mark Rutland, Gary Guo, Yury Norov,
Rasmus Villemoes, Chao-ying Fu, Conor Dooley, torvalds, olof,
aleksa.paunovic, arikalo, Boqun Feng, Alexei Starovoitov,
Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
Luke Nelson, Xi Wang, Björn Töpel, Pu Lehui,
Puranjay Mohan, Masami Hiramatsu, Oleg Nesterov, Miguel Ojeda,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan, Shuah Khan, Randy Dunlap,
Andrew Jones, Boqun Feng
Cc: Jisheng Zhang, linux-riscv, linux-kernel, Vladimir.Kondratiev,
bpf, linux-trace-kernel, linux-doc, Jonathan Corbet,
Charlie Jenkins, Nam Cao, rust-for-linux, Vladimir Kondratiev
A kernel built with CONFIG_RISCV_ISA_ZAAMO disabled is meant for a
hart where AMO instructions are emulated by an M-mode trap. The BPF JIT
still encodes amo* instructions for the BPF atomic read-modify-write
operations, so every such operation takes that trap.
Emit an LR/SC loop for BPF_ADD, BPF_AND, BPF_OR, BPF_XOR, their
BPF_FETCH forms and BPF_XCHG when Zaamo is disabled, on RV32 and RV64.
The sequences follow the Zalrsc variants in
arch/riscv/include/asm/atomic.h and the existing LR/SC loop of
emit_cmpxchg(): a relaxed op discards the old value; a fetch op is
fully ordered with a plain lr, sc.rl and a trailing fence rw,rw, and
returns the old value. BPF_CMPXCHG is unchanged; it already uses
amocas with Zacas and an LR/SC loop otherwise.
The JIT encodes instructions as integers, so no assembler constraint
applies and both paths stay compiled. The choice is a plain
IS_ENABLED() test, the same compile-time decision the rest of the
kernel makes. The hart advertises "a" either way, so a runtime
extension check would not tell the two cases apart.
An arena (BPF_PROBE_ATOMIC) access needs an exception table entry for
each instruction that may fault. The verifier reserves one entry per
atomic instruction, but an LR/SC loop can fault on either the lr or the
sc. Count the extra entries once the instruction offsets converge,
before the image is allocated, and add an entry for the sc that shares
the fixup of the lr, so a fault skips the retry and the result move.
Co-developed-by: Chao-ying Fu <chao-ying.fu@globalfoundries.com>
Signed-off-by: Chao-ying Fu <chao-ying.fu@globalfoundries.com>
Signed-off-by: Vladimir Kondratiev <vladimir.kondratiev@mobileye.com>
---
arch/riscv/net/bpf_jit.h | 1 +
arch/riscv/net/bpf_jit_comp32.c | 84 +++++++++++++++++++++++++++++--
arch/riscv/net/bpf_jit_comp64.c | 109 +++++++++++++++++++++++++++++++++++++++-
arch/riscv/net/bpf_jit_core.c | 29 +++++++++++
4 files changed, 217 insertions(+), 6 deletions(-)
diff --git a/arch/riscv/net/bpf_jit.h b/arch/riscv/net/bpf_jit.h
index 419b9d795f2a..8c1301289ea8 100644
--- a/arch/riscv/net/bpf_jit.h
+++ b/arch/riscv/net/bpf_jit.h
@@ -79,6 +79,7 @@ struct rv_jit_context {
int nexentries;
int ex_insn_off;
int ex_jmp_off;
+ int ex_sc_off; /* sc in an lr/sc pair; 0 if unused */
unsigned long flags;
int stack_size;
int tcc_offset;
diff --git a/arch/riscv/net/bpf_jit_comp32.c b/arch/riscv/net/bpf_jit_comp32.c
index a9e0bd5cc81d..0fa0c013549a 100644
--- a/arch/riscv/net/bpf_jit_comp32.c
+++ b/arch/riscv/net/bpf_jit_comp32.c
@@ -874,11 +874,70 @@ static int emit_load_r64(const s8 *dst, const s8 *src, s16 off,
return 0;
}
-static int emit_bpf_atomic(s8 dst, const s8 *src, const s8 *rs,
- struct rv_jit_context *ctx,
- const struct bpf_insn *insn)
+/*
+ * Read-modify-write via lr/sc for kernels built without Zaamo. T0 holds
+ * the address. T1/T2 are not BPF registers; the address was copied out of
+ * lo(rd) before this is called, so clobbering T2 is fine. A fetch op
+ * (including XCHG) is fully ordered as in asm/atomic.h: plain lr, sc.rl
+ * and a trailing fence rw,rw.
+ */
+static int emit_bpf_atomic_lrsc(s8 dst, const s8 *rs, s32 imm,
+ struct rv_jit_context *ctx)
+{
+ bool is_fetch = (imm & BPF_FETCH) || (imm == BPF_XCHG);
+ bool xchg = imm == BPF_XCHG;
+ u8 rl = is_fetch ? 1 : 0;
+ u8 old = RV_REG_T1;
+ u8 tmp = RV_REG_T2;
+ int lr_off, jmp_off;
+ s32 op = xchg ? BPF_XCHG : imm & ~BPF_FETCH;
+
+ switch (op) {
+ case BPF_ADD:
+ case BPF_AND:
+ case BPF_OR:
+ case BPF_XOR:
+ case BPF_XCHG:
+ break;
+ default:
+ return -1;
+ }
+
+ lr_off = ctx->ninsns;
+ emit(rv_lr_w(old, 0, dst, 0, 0), ctx);
+
+ switch (op) {
+ case BPF_ADD:
+ emit(rv_add(tmp, old, lo(rs)), ctx);
+ break;
+ case BPF_AND:
+ emit(rv_and(tmp, old, lo(rs)), ctx);
+ break;
+ case BPF_OR:
+ emit(rv_or(tmp, old, lo(rs)), ctx);
+ break;
+ case BPF_XOR:
+ emit(rv_xor(tmp, old, lo(rs)), ctx);
+ break;
+ }
+
+ if (xchg)
+ emit(rv_sc_w(tmp, lo(rs), dst, 0, rl), ctx);
+ else
+ emit(rv_sc_w(tmp, tmp, dst, 0, rl), ctx);
+
+ jmp_off = ninsns_rvoff(lr_off - ctx->ninsns);
+ emit(rv_bne(tmp, RV_REG_ZERO, jmp_off >> 1), ctx);
+ if (is_fetch) {
+ emit_fence_rw_rw(ctx);
+ emit(rv_addi(lo(rs), old, 0), ctx);
+ }
+ return 0;
+}
+
+static int emit_bpf_atomic_amo(s8 dst, const s8 *rs, s32 imm,
+ struct rv_jit_context *ctx)
{
- s32 imm = insn->imm;
bool is_fetch = (imm & BPF_FETCH) || (imm == BPF_XCHG);
s8 fetch_reg = is_fetch ? lo(rs) : RV_REG_ZERO;
int aq = is_fetch ? 1 : 0;
@@ -907,6 +966,23 @@ static int emit_bpf_atomic(s8 dst, const s8 *src, const s8 *rs,
default:
return -1;
}
+ return 0;
+}
+
+static int emit_bpf_atomic(s8 dst, const s8 *src, const s8 *rs,
+ struct rv_jit_context *ctx,
+ const struct bpf_insn *insn)
+{
+ s32 imm = insn->imm;
+ bool is_fetch = (imm & BPF_FETCH) || (imm == BPF_XCHG);
+ int ret;
+
+ if (IS_ENABLED(CONFIG_RISCV_ISA_ZAAMO))
+ ret = emit_bpf_atomic_amo(dst, rs, imm, ctx);
+ else
+ ret = emit_bpf_atomic_lrsc(dst, rs, imm, ctx);
+ if (ret)
+ return ret;
if (is_fetch) {
emit(rv_addi(hi(rs), RV_REG_ZERO, 0), ctx);
diff --git a/arch/riscv/net/bpf_jit_comp64.c b/arch/riscv/net/bpf_jit_comp64.c
index 01fe66774f02..4807b5800f62 100644
--- a/arch/riscv/net/bpf_jit_comp64.c
+++ b/arch/riscv/net/bpf_jit_comp64.c
@@ -573,6 +573,80 @@ static int emit_atomic_ld_st(u8 rd, u8 rs, const struct bpf_insn *insn,
return 0;
}
+/*
+ * Read-modify-write via lr/sc for kernels built without Zaamo, matching
+ * the Zalrsc sequences in arch/riscv/include/asm/atomic.h. A relaxed op
+ * discards the old value. A fetch op (including XCHG) is fully ordered
+ * the way emit_cmpxchg() is: plain lr, sc.rl and a trailing fence rw,rw.
+ * It writes the old value back to val. T2/T3 are not BPF registers; addr
+ * may already be T1.
+ */
+static void emit_atomic_lrsc(u8 addr, u8 val, bool is64, s32 imm,
+ struct rv_jit_context *ctx)
+{
+ bool fetch = imm & BPF_FETCH;
+ u8 rl = fetch ? 1 : 0;
+ u8 old = RV_REG_T2;
+ u8 tmp = RV_REG_T3;
+ int lr_off, jmp_off;
+ s32 op = imm == BPF_XCHG ? BPF_XCHG : imm & ~BPF_FETCH;
+
+ lr_off = ctx->ninsns;
+ ctx->ex_insn_off = ctx->ninsns;
+ emit(is64 ? rv_lr_d(old, 0, addr, 0, 0) :
+ rv_lr_w(old, 0, addr, 0, 0), ctx);
+
+ if (op != BPF_XCHG) {
+ if (!is64 && op == BPF_ADD)
+ emit(rv_addw(tmp, old, val), ctx);
+ else if (op == BPF_ADD)
+ emit_add(tmp, old, val, ctx);
+ else if (op == BPF_AND)
+ emit_and(tmp, old, val, ctx);
+ else if (op == BPF_OR)
+ emit_or(tmp, old, val, ctx);
+ else if (op == BPF_XOR)
+ emit_xor(tmp, old, val, ctx);
+
+ ctx->ex_sc_off = ctx->ninsns;
+ emit(is64 ? rv_sc_d(tmp, tmp, addr, 0, rl) :
+ rv_sc_w(tmp, tmp, addr, 0, rl), ctx);
+ } else {
+ ctx->ex_sc_off = ctx->ninsns;
+ emit(is64 ? rv_sc_d(tmp, val, addr, 0, rl) :
+ rv_sc_w(tmp, val, addr, 0, rl), ctx);
+ }
+
+ /* Branch offset is relative to this instruction, back to the lr. */
+ jmp_off = ninsns_rvoff(lr_off - ctx->ninsns);
+ emit(rv_bne(tmp, RV_REG_ZERO, jmp_off >> 1), ctx);
+
+ if (fetch) {
+ emit_fence_rw_rw(ctx);
+ emit_mv(val, old, ctx);
+ if (!is64)
+ emit_zextw(val, val, ctx);
+ }
+ ctx->ex_jmp_off = ctx->ninsns;
+}
+
+static bool is_atomic_lrsc_op(s32 imm)
+{
+ switch (imm) {
+ case BPF_ADD:
+ case BPF_AND:
+ case BPF_OR:
+ case BPF_XOR:
+ case BPF_ADD | BPF_FETCH:
+ case BPF_AND | BPF_FETCH:
+ case BPF_OR | BPF_FETCH:
+ case BPF_XOR | BPF_FETCH:
+ case BPF_XCHG:
+ return true;
+ }
+ return false;
+}
+
static int emit_atomic_rmw(u8 rd, u8 rs, const struct bpf_insn *insn,
struct rv_jit_context *ctx)
{
@@ -601,6 +675,12 @@ static int emit_atomic_rmw(u8 rd, u8 rs, const struct bpf_insn *insn,
rd = RV_REG_T1;
}
+ /* Without Zaamo, every op except cmpxchg is an lr/sc loop. */
+ if (!IS_ENABLED(CONFIG_RISCV_ISA_ZAAMO) && is_atomic_lrsc_op(imm)) {
+ emit_atomic_lrsc(rd, rs, is64, imm, ctx);
+ return 0;
+ }
+
switch (imm) {
/* lock *(u32/u64 *)(dst_reg + off16) <op>= src_reg */
case BPF_ADD:
@@ -732,8 +812,8 @@ bool ex_handler_bpf(const struct exception_table_entry *ex,
}
/* For accesses to BTF pointers, add an entry to the exception table */
-static int add_exception_handler(const struct bpf_insn *insn, int dst_reg,
- struct rv_jit_context *ctx)
+static int add_exception_handler_one(const struct bpf_insn *insn, int dst_reg,
+ struct rv_jit_context *ctx)
{
struct exception_table_entry *ex;
unsigned long pc;
@@ -804,6 +884,31 @@ static int add_exception_handler(const struct bpf_insn *insn, int dst_reg,
return 0;
}
+/*
+ * An lr/sc pair faults on either instruction. Both entries share the fixup
+ * that follows the loop, so a probe fault skips the retry and the result move.
+ */
+static int add_exception_handler(const struct bpf_insn *insn, int dst_reg,
+ struct rv_jit_context *ctx)
+{
+ int sc_off = ctx->ex_sc_off;
+ int jmp_off = ctx->ex_jmp_off;
+ int ret;
+
+ ctx->ex_sc_off = 0;
+ /* Offset discovery runs before the image exists. Entries are added later. */
+ if (!ctx->insns)
+ return 0;
+
+ ret = add_exception_handler_one(insn, dst_reg, ctx);
+ if (ret || sc_off <= 0)
+ return ret;
+
+ ctx->ex_insn_off = sc_off;
+ ctx->ex_jmp_off = jmp_off;
+ return add_exception_handler_one(insn, dst_reg, ctx);
+}
+
static int gen_jump_or_nops(void *target, void *ip, u32 *insns, bool is_call)
{
s64 rvoff;
diff --git a/arch/riscv/net/bpf_jit_core.c b/arch/riscv/net/bpf_jit_core.c
index cbfcd287ea16..cba0d34c3e6f 100644
--- a/arch/riscv/net/bpf_jit_core.c
+++ b/arch/riscv/net/bpf_jit_core.c
@@ -16,6 +16,34 @@
/* Number of iterations to try until offsets converge. */
#define NR_JIT_ITERATIONS 32
+/*
+ * The verifier reserves one extable slot per BPF_PROBE_ATOMIC. Without
+ * Zaamo a read-modify-write atomic is an lr/sc loop that can fault on
+ * either instruction, so reserve a second slot for the sc.
+ */
+static void rv_jit_add_lrsc_exentries(struct bpf_prog *prog)
+{
+ const struct bpf_insn *insn = prog->insnsi;
+ int i;
+
+ if (IS_ENABLED(CONFIG_RISCV_ISA_ZAAMO) || __riscv_xlen != 64)
+ return;
+
+ for (i = 0; i < prog->len; i++, insn++) {
+ if (BPF_CLASS(insn->code) != BPF_STX ||
+ BPF_MODE(insn->code) != BPF_PROBE_ATOMIC ||
+ bpf_atomic_is_load_store(insn))
+ continue;
+ if (BPF_SIZE(insn->code) != BPF_W &&
+ BPF_SIZE(insn->code) != BPF_DW)
+ continue;
+ /* amocas is a single faulting instruction. */
+ if (insn->imm == BPF_CMPXCHG && rv_ext_enabled(ZACAS))
+ continue;
+ prog->aux->num_exentries++;
+ }
+}
+
static int build_body(struct rv_jit_context *ctx, bool extra_pass, int *offset)
{
const struct bpf_prog *prog = ctx->prog;
@@ -100,6 +128,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
if (ctx->ninsns == prev_ninsns) {
if (jit_data->header)
break;
+ rv_jit_add_lrsc_exentries(prog);
/* obtain the actual image size */
extable_size = prog->aux->num_exentries *
sizeof(struct exception_table_entry);
--
2.43.0
^ permalink raw reply [flat|nested] 7+ messages in thread* [PATCH v7 5/6] riscv: hwprobe: update the vDSO data after the boot-time speed probes
2026-11-18 16:23 [PATCH v7 0/6] riscv: restrict the ISA used for atomics to avoid unsupported or slow AMO Vladimir Kondratiev
` (3 preceding siblings ...)
2026-11-18 16:24 ` [PATCH v7 4/6] riscv, bpf: emit LR/SC loops when Zaamo is disabled Vladimir Kondratiev
@ 2026-11-18 16:24 ` Vladimir Kondratiev
2026-11-18 16:24 ` [PATCH v7 6/6] riscv: hwprobe: report whether AMO is faster than LR/SC Vladimir Kondratiev
5 siblings, 0 replies; 7+ messages in thread
From: Vladimir Kondratiev @ 2026-11-18 16:24 UTC (permalink / raw)
To: Paul Walmsley, Palmer Dabbelt, Albert Ou, Alexandre Ghiti,
Will Deacon, Peter Zijlstra, Mark Rutland, Gary Guo, Yury Norov,
Rasmus Villemoes, Chao-ying Fu, Conor Dooley, torvalds, olof,
aleksa.paunovic, arikalo, Boqun Feng, Alexei Starovoitov,
Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
Luke Nelson, Xi Wang, Björn Töpel, Pu Lehui,
Puranjay Mohan, Masami Hiramatsu, Oleg Nesterov, Miguel Ojeda,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan, Shuah Khan, Randy Dunlap,
Andrew Jones, Boqun Feng
Cc: Jisheng Zhang, linux-riscv, linux-kernel, Vladimir.Kondratiev,
bpf, linux-trace-kernel, linux-doc, Jonathan Corbet,
Charlie Jenkins, Nam Cao, rust-for-linux, Vladimir Kondratiev
init_hwprobe_vdso_data() fills the vDSO copy of the hwprobe answers at
arch_initcall_sync. The misaligned access speed probes run later, at
fs_initcall_sync, so the vDSO keeps RISCV_HWPROBE_MISALIGNED_*_UNKNOWN
for RISCV_HWPROBE_KEY_MISALIGNED_SCALAR_PERF and _VECTOR_PERF, and
every hwprobe() call that the vDSO answers itself, which is the common
"all CPUs" case, returns UNKNOWN where the syscall would return the
measured value.
This was handled by filling the vDSO data lazily on the first syscall,
which commit 7e14e42edfaa ("Revert "riscv: hwprobe: Fix stale vDSO
data for late-initialized keys at boot"") removed once the probes
became synchronous; the ordering between the two initcalls was left
as it was.
Split the filling out of the initcall into
riscv_hwprobe_update_vdso_data() and call it again at the end of
check_unaligned_access_all_cpus(). That still runs before
rootfs_initcall() enables usermode helpers, so no userspace can read
the vDSO data before it is complete.
Fixes: 7e14e42edfaa ("Revert "riscv: hwprobe: Fix stale vDSO data for late-initialized keys at boot"")
Signed-off-by: Vladimir Kondratiev <vladimir.kondratiev@mobileye.com>
---
arch/riscv/include/asm/hwprobe.h | 6 ++++++
arch/riscv/kernel/sys_hwprobe.c | 16 +++++++++++-----
arch/riscv/kernel/unaligned_access_speed.c | 8 +++++---
3 files changed, 22 insertions(+), 8 deletions(-)
diff --git a/arch/riscv/include/asm/hwprobe.h b/arch/riscv/include/asm/hwprobe.h
index 9b04377c0f98..1cc83cecbc05 100644
--- a/arch/riscv/include/asm/hwprobe.h
+++ b/arch/riscv/include/asm/hwprobe.h
@@ -43,4 +43,10 @@ static inline bool riscv_hwprobe_pair_cmp(struct riscv_hwprobe *pair,
return pair->value == other_pair->value;
}
+#ifdef CONFIG_MMU
+void riscv_hwprobe_update_vdso_data(void);
+#else
+static inline void riscv_hwprobe_update_vdso_data(void) {}
+#endif
+
#endif
diff --git a/arch/riscv/kernel/sys_hwprobe.c b/arch/riscv/kernel/sys_hwprobe.c
index 52c4c2085d0a..2c64a13c5155 100644
--- a/arch/riscv/kernel/sys_hwprobe.c
+++ b/arch/riscv/kernel/sys_hwprobe.c
@@ -534,17 +534,18 @@ static int do_riscv_hwprobe(struct riscv_hwprobe __user *pairs,
#ifdef CONFIG_MMU
-static int __init init_hwprobe_vdso_data(void)
+/*
+ * Fill the vDSO data with the answers for the "all CPUs" case, to save a
+ * syscall in the common case. Called once the ISA is known, and again by
+ * the boot-time probes whose results feed some of the keys.
+ */
+void __init riscv_hwprobe_update_vdso_data(void)
{
struct vdso_arch_data *avd = vdso_k_arch_data;
u64 id_bitsmash = 0;
struct riscv_hwprobe pair;
int key;
- /*
- * Initialize vDSO data with the answers for the "all CPUs" case, to
- * save a syscall in the common case.
- */
for (key = 0; key <= RISCV_HWPROBE_MAX_KEY; key++) {
pair.key = key;
hwprobe_one_pair(&pair, cpu_online_mask);
@@ -568,6 +569,11 @@ static int __init init_hwprobe_vdso_data(void)
* vDSO should defer to the kernel for exotic cpu masks.
*/
avd->homogeneous_cpus = id_bitsmash != 0 && id_bitsmash != -1;
+}
+
+static int __init init_hwprobe_vdso_data(void)
+{
+ riscv_hwprobe_update_vdso_data();
return 0;
}
diff --git a/arch/riscv/kernel/unaligned_access_speed.c b/arch/riscv/kernel/unaligned_access_speed.c
index 67f1a0371659..3a6f85e3f94c 100644
--- a/arch/riscv/kernel/unaligned_access_speed.c
+++ b/arch/riscv/kernel/unaligned_access_speed.c
@@ -393,13 +393,15 @@ static int __init check_unaligned_access_all_cpus(void)
modify_unaligned_access_branches(cpu_online_mask);
cpus_read_unlock();
+ /* The vDSO was filled before the probes ran; give it the results. */
+ riscv_hwprobe_update_vdso_data();
+
return 0;
}
/*
* Run after clocksource_done_booting() so measure_cycles() uses a stable
- * clocksource, but before rootfs_initcall() enables usermode helpers. Those
- * helpers can reach hwprobe and populate the vDSO cache, so async hwprobe
- * probes must be registered first.
+ * clocksource, but before rootfs_initcall() enables usermode helpers, which
+ * can reach hwprobe and must see the results in the vDSO data.
*/
fs_initcall_sync(check_unaligned_access_all_cpus);
--
2.43.0
^ permalink raw reply [flat|nested] 7+ messages in thread* [PATCH v7 6/6] riscv: hwprobe: report whether AMO is faster than LR/SC
2026-11-18 16:23 [PATCH v7 0/6] riscv: restrict the ISA used for atomics to avoid unsupported or slow AMO Vladimir Kondratiev
` (4 preceding siblings ...)
2026-11-18 16:24 ` [PATCH v7 5/6] riscv: hwprobe: update the vDSO data after the boot-time speed probes Vladimir Kondratiev
@ 2026-11-18 16:24 ` Vladimir Kondratiev
5 siblings, 0 replies; 7+ messages in thread
From: Vladimir Kondratiev @ 2026-11-18 16:24 UTC (permalink / raw)
To: Paul Walmsley, Palmer Dabbelt, Albert Ou, Alexandre Ghiti,
Will Deacon, Peter Zijlstra, Mark Rutland, Gary Guo, Yury Norov,
Rasmus Villemoes, Chao-ying Fu, Conor Dooley, torvalds, olof,
aleksa.paunovic, arikalo, Boqun Feng, Alexei Starovoitov,
Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
Luke Nelson, Xi Wang, Björn Töpel, Pu Lehui,
Puranjay Mohan, Masami Hiramatsu, Oleg Nesterov, Miguel Ojeda,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan, Shuah Khan, Randy Dunlap,
Andrew Jones, Boqun Feng
Cc: Jisheng Zhang, linux-riscv, linux-kernel, Vladimir.Kondratiev,
bpf, linux-trace-kernel, linux-doc, Jonathan Corbet,
Charlie Jenkins, Nam Cao, rust-for-linux, Vladimir Kondratiev,
Jesse Taube
On a CPU that traps AMO instructions into firmware and emulates them
there, such as MIPS P8700, an uncontended AMO costs about 600 cycles
where the equivalent LR/SC sequence costs about 40. Userspace built for
the A extension uses AMO for every atomic and pays that on every one.
It cannot tell from the ISA string: such a CPU still has Zaamo, and
correctly so.
Give userspace the same kind of hint the kernel gives for misaligned
access. At boot, time AMO_SPEED_ITERS amoadd.w against the same number
of lr.w/addi/sc.w loops on each CPU, take the best sample from an 8 ms
window of each, and report the result through a new hwprobe key,
RISCV_HWPROBE_KEY_AMO_PERF:
RISCV_HWPROBE_AMO_FAST AMO is at least as fast as LR/SC
RISCV_HWPROBE_AMO_SLOW LR/SC is faster; use it where possible
RISCV_HWPROBE_AMO_UNSUPPORTED the CPU has no Zaamo
RISCV_HWPROBE_AMO_UNKNOWN not measured, or differs across CPUs
Only the direction of the difference is reported, not its size: the
question a program can act on is which sequence to pick. Each CPU logs
its ratio, and a kernel whose own atomics are AMO warns once when the
CPU turns out to be slow, pointing at RISCV_ISA_ZAAMO.
The amoadd.w is spelled with .insn through a new AMOADD_W() in
insn-def.h, so the file assembles when -march has no Zaamo, and the
probe is skipped on a CPU whose ISA lacks the extension. CPUs that come
online later are measured by a hotplug callback. amo_speed={slow|fast}
on the command line skips the measurement, as unaligned_scalar_speed=
does; a CPU without Zaamo is reported unsupported either way. The
probe runs at the same initcall level as the misaligned access probe,
for the same reasons, and refreshes the vDSO hwprobe data when done.
Tested on the eyeq7h hardware, with the DT advertising "a":
[ 0.163714] cpu10: AMO speed is 0.07x LR/SC speed (slow)
[ 0.163727] cpu11: AMO speed is 0.07x LR/SC speed (slow)
[ 0.163724] cpu6: AMO speed is 0.07x LR/SC speed (slow)
and, with CONFIG_RISCV_ISA_ZAAMO set:
[ 0.163729] AMO is slow but kernel atomics use it, consider disabling RISCV_ISA_ZAAMO
Reviewed-by: Jesse Taube <jtaubepe@redhat.com>
Signed-off-by: Vladimir Kondratiev <vladimir.kondratiev@mobileye.com>
---
Documentation/admin-guide/kernel-parameters.txt | 7 +
Documentation/arch/riscv/hwprobe.rst | 18 +++
arch/riscv/Kconfig | 13 ++
arch/riscv/include/asm/cpufeature.h | 4 +
arch/riscv/include/asm/hwprobe.h | 2 +-
arch/riscv/include/asm/insn-def.h | 5 +
arch/riscv/include/uapi/asm/hwprobe.h | 5 +
arch/riscv/kernel/Makefile | 1 +
arch/riscv/kernel/amo_speed.c | 183 ++++++++++++++++++++++++
arch/riscv/kernel/sys_hwprobe.c | 37 +++++
10 files changed, 274 insertions(+), 1 deletion(-)
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index e75344f4e0cd..9bc5baff20ff 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -513,6 +513,13 @@ Kernel parameters
Format: <a>,<b>
See also Documentation/input/joydev/joystick.rst
+ amo_speed= [RISCV]
+ Format: {slow | fast}
+ Allow skipping the AMO instruction speed test. This is
+ useful for testing alternative code paths and to skip
+ the test in environments where it runs too slowly. All
+ CPUs must have the same AMO speed.
+
analog.map= [HW,JOY] Analog joystick and gamepad support
Specifies type or capabilities of an analog joystick
connected to one of 16 gameports
diff --git a/Documentation/arch/riscv/hwprobe.rst b/Documentation/arch/riscv/hwprobe.rst
index 63d7ef028bf8..84aef6a0a79c 100644
--- a/Documentation/arch/riscv/hwprobe.rst
+++ b/Documentation/arch/riscv/hwprobe.rst
@@ -425,3 +425,21 @@ The following keys are defined:
* :c:macro:`RISCV_HWPROBE_EXT_ZA64RS`: The Za64rs extension is supported,
as defined in the RISC-V Profiles specification starting from commit
b1d80660 ("Updated to ratified state.")
+
+* :c:macro:`RISCV_HWPROBE_KEY_AMO_PERF`: An enum value describing the
+ performance of the AMO instructions of the Zaamo extension, relative to
+ the equivalent LR/SC sequence, on the selected set of processors.
+
+ * :c:macro:`RISCV_HWPROBE_AMO_UNKNOWN`: The performance of AMO instructions
+ is unknown.
+
+ * :c:macro:`RISCV_HWPROBE_AMO_SLOW`: An uncontended AMO instruction takes
+ longer than the equivalent LR/SC sequence. This is the case when AMO
+ instructions are trapped and emulated by firmware. Code that can choose
+ should use LR/SC.
+
+ * :c:macro:`RISCV_HWPROBE_AMO_FAST`: An uncontended AMO instruction is at
+ least as fast as the equivalent LR/SC sequence.
+
+ * :c:macro:`RISCV_HWPROBE_AMO_UNSUPPORTED`: AMO instructions are not
+ supported, the Zaamo extension is absent.
diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig
index 3c3679701a60..dfd6237f879b 100644
--- a/arch/riscv/Kconfig
+++ b/arch/riscv/Kconfig
@@ -764,6 +764,19 @@ config RISCV_ISA_ZAAMO
If you don't know what to do here, say Y.
+config RISCV_PROBE_AMO_SPEED
+ bool "Probe AMO instruction speed at boot"
+ default y
+ help
+ During boot, time an uncontended AMO instruction against the
+ equivalent LR/SC sequence on every CPU, and report which one is
+ faster to userspace through the hwprobe syscall, as
+ RISCV_HWPROBE_KEY_AMO_PERF. On a CPU that traps AMO instructions
+ into firmware and emulates them there, LR/SC is much faster, and
+ code that can choose should use it.
+
+ If you don't know what to do here, say Y.
+
config TOOLCHAIN_HAS_ZBB
bool
default y
diff --git a/arch/riscv/include/asm/cpufeature.h b/arch/riscv/include/asm/cpufeature.h
index 5efa72823475..92cab4a7a0f1 100644
--- a/arch/riscv/include/asm/cpufeature.h
+++ b/arch/riscv/include/asm/cpufeature.h
@@ -83,6 +83,10 @@ static inline bool unaligned_ctl_available(void)
}
#endif
+#ifdef CONFIG_RISCV_PROBE_AMO_SPEED
+DECLARE_PER_CPU(long, amo_speed);
+#endif
+
#if defined(CONFIG_RISCV_MISALIGNED)
DECLARE_PER_CPU(long, misaligned_access_speed);
bool misaligned_traps_can_delegate(void);
diff --git a/arch/riscv/include/asm/hwprobe.h b/arch/riscv/include/asm/hwprobe.h
index 1cc83cecbc05..a7eb17c8180f 100644
--- a/arch/riscv/include/asm/hwprobe.h
+++ b/arch/riscv/include/asm/hwprobe.h
@@ -8,7 +8,7 @@
#include <uapi/asm/hwprobe.h>
-#define RISCV_HWPROBE_MAX_KEY 16
+#define RISCV_HWPROBE_MAX_KEY 17
static inline bool riscv_hwprobe_key_is_valid(__s64 key)
{
diff --git a/arch/riscv/include/asm/insn-def.h b/arch/riscv/include/asm/insn-def.h
index 8fcc848c196e..5ca5c0b8ad66 100644
--- a/arch/riscv/include/asm/insn-def.h
+++ b/arch/riscv/include/asm/insn-def.h
@@ -219,6 +219,11 @@ ALTERNATIVE("nop", "fence rw, rw", SIFIVE_VENDOR_ID, \
__ASM_STR(.error "hlv.d requires 64-bit support")
#endif
+/* Spelled out so that it assembles when -march lacks Zaamo */
+#define AMOADD_W(dest, addr, val) \
+ INSN_R(OPCODE_AMO, FUNC3(2), FUNC7(0), \
+ RD(dest), RS1(addr), RS2(val))
+
#define LB_AQ(dest, addr) \
INSN_R(OPCODE_AMO, FUNC3(0), FUNC7(26), \
RD(dest), RS1(addr), __RS2(0))
diff --git a/arch/riscv/include/uapi/asm/hwprobe.h b/arch/riscv/include/uapi/asm/hwprobe.h
index e6a394fbe7fc..a5f726f94204 100644
--- a/arch/riscv/include/uapi/asm/hwprobe.h
+++ b/arch/riscv/include/uapi/asm/hwprobe.h
@@ -122,6 +122,11 @@ struct riscv_hwprobe {
#define RISCV_HWPROBE_EXT_ZICCIF _BITULL(3)
#define RISCV_HWPROBE_EXT_ZICCRSE _BITULL(4)
#define RISCV_HWPROBE_EXT_ZA64RS _BITULL(5)
+#define RISCV_HWPROBE_KEY_AMO_PERF 17
+#define RISCV_HWPROBE_AMO_UNKNOWN 0
+#define RISCV_HWPROBE_AMO_SLOW 1
+#define RISCV_HWPROBE_AMO_FAST 2
+#define RISCV_HWPROBE_AMO_UNSUPPORTED 3
/* Increase RISCV_HWPROBE_MAX_KEY when adding items. */
diff --git a/arch/riscv/kernel/Makefile b/arch/riscv/kernel/Makefile
index ebe1c3588177..fc935c877e82 100644
--- a/arch/riscv/kernel/Makefile
+++ b/arch/riscv/kernel/Makefile
@@ -79,6 +79,7 @@ obj-$(CONFIG_RISCV_MISALIGNED) += traps_misaligned.o
obj-$(CONFIG_RISCV_MISALIGNED) += unaligned_access_speed.o
obj-$(CONFIG_RISCV_PROBE_UNALIGNED_ACCESS) += copy-unaligned.o
obj-$(CONFIG_RISCV_PROBE_VECTOR_UNALIGNED_ACCESS) += vec-copy-unaligned.o
+obj-$(CONFIG_RISCV_PROBE_AMO_SPEED) += amo_speed.o
obj-$(CONFIG_FPU) += fpu.o
obj-$(CONFIG_FPU) += kernel_mode_fpu.o
diff --git a/arch/riscv/kernel/amo_speed.c b/arch/riscv/kernel/amo_speed.c
new file mode 100644
index 000000000000..8cd66941c3a6
--- /dev/null
+++ b/arch/riscv/kernel/amo_speed.c
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Measure whether AMO instructions are faster than the equivalent LR/SC
+ * sequence. They are not on a CPU that traps them into firmware and
+ * emulates them there, such as MIPS P8700, where an AMO costs hundreds of
+ * cycles and LR/SC tens. The result goes to userspace through hwprobe,
+ * so code that can choose between the two knows which one to use.
+ */
+
+#include <linux/cpu.h>
+#include <linux/smp.h>
+#include <linux/timekeeping.h>
+#include <asm/cpufeature.h>
+#include <asm/hwprobe.h>
+#include <asm/insn-def.h>
+#include <asm/timex.h>
+
+/* Time window for each measurement, and atomics per sample within it */
+#define AMO_SPEED_NS 8000000
+#define AMO_SPEED_ITERS 1024
+
+DEFINE_PER_CPU(long, amo_speed) = RISCV_HWPROBE_AMO_UNKNOWN;
+
+static DEFINE_PER_CPU_ALIGNED(u32, amo_speed_word);
+static long amo_speed_param = RISCV_HWPROBE_AMO_UNKNOWN;
+
+static void amo_speed_amo(u32 *word, unsigned long n)
+{
+ unsigned long tmp;
+
+ asm volatile(
+ "1:\n"
+ AMOADD_W(%[tmp], %[word], %[one])
+ " addi %[n], %[n], -1\n"
+ " bnez %[n], 1b\n"
+ : [tmp] "=&r" (tmp), [n] "+&r" (n), "+m" (*word)
+ : [word] "r" (word), [one] "r" (1UL)
+ : "memory");
+}
+
+static void amo_speed_lrsc(u32 *word, unsigned long n)
+{
+ unsigned long tmp;
+
+ asm volatile(
+ "1: lr.w %[tmp], (%[word])\n"
+ " addi %[tmp], %[tmp], 1\n"
+ " sc.w %[tmp], %[tmp], (%[word])\n"
+ " bnez %[tmp], 1b\n"
+ " addi %[n], %[n], -1\n"
+ " bnez %[n], 1b\n"
+ : [tmp] "=&r" (tmp), [n] "+&r" (n), "+m" (*word)
+ : [word] "r" (word)
+ : "memory");
+}
+
+/*
+ * For a fixed amount of time, repeatedly run func and take the best time
+ * in cycles as the measurement.
+ */
+static u64 amo_speed_measure(void (*func)(u32 *word, unsigned long n),
+ u32 *word)
+{
+ u64 start_cycles, end_cycles, cycles = -1ULL;
+ u64 start_ns;
+
+ /* Do a warmup. */
+ func(word, AMO_SPEED_ITERS);
+
+ preempt_disable();
+
+ start_ns = ktime_get_mono_fast_ns();
+ while (ktime_get_mono_fast_ns() < start_ns + AMO_SPEED_NS) {
+ start_cycles = get_cycles64();
+ /* Ensure the CSR read can't reorder WRT to the atomics. */
+ mb();
+ func(word, AMO_SPEED_ITERS);
+ /* Ensure the atomics end before the end time is snapped. */
+ mb();
+ end_cycles = get_cycles64();
+ if ((end_cycles - start_cycles) < cycles)
+ cycles = end_cycles - start_cycles;
+ }
+
+ preempt_enable();
+
+ return cycles;
+}
+
+/*
+ * Settle the speed of one CPU: unsupported without Zaamo, the command
+ * line value if one was given, otherwise measure. Runs on that CPU.
+ */
+static void check_amo_speed(void *unused)
+{
+ int cpu = smp_processor_id();
+ u32 *word = this_cpu_ptr(&amo_speed_word);
+ u64 amo_cycles, lrsc_cycles;
+ long speed;
+ int ratio;
+
+ if (per_cpu(amo_speed, cpu) != RISCV_HWPROBE_AMO_UNKNOWN)
+ return;
+
+ if (!riscv_cpu_has_extension_unlikely(cpu, RISCV_ISA_EXT_ZAAMO)) {
+ per_cpu(amo_speed, cpu) = RISCV_HWPROBE_AMO_UNSUPPORTED;
+ return;
+ }
+
+ if (amo_speed_param != RISCV_HWPROBE_AMO_UNKNOWN) {
+ per_cpu(amo_speed, cpu) = amo_speed_param;
+ return;
+ }
+
+ amo_cycles = amo_speed_measure(amo_speed_amo, word);
+ lrsc_cycles = amo_speed_measure(amo_speed_lrsc, word);
+
+ /* Don't divide by zero. */
+ if (!amo_cycles || !lrsc_cycles) {
+ pr_warn("cpu%d: rdtime lacks granularity needed to measure AMO speed\n",
+ cpu);
+ return;
+ }
+
+ if (amo_cycles <= lrsc_cycles)
+ speed = RISCV_HWPROBE_AMO_FAST;
+ else
+ speed = RISCV_HWPROBE_AMO_SLOW;
+
+ ratio = div64_u64(lrsc_cycles * 100, amo_cycles);
+ pr_info("cpu%d: AMO speed is %d.%02dx LR/SC speed (%s)\n",
+ cpu, ratio / 100, ratio % 100,
+ speed == RISCV_HWPROBE_AMO_FAST ? "fast" : "slow");
+
+ per_cpu(amo_speed, cpu) = speed;
+
+ if (speed == RISCV_HWPROBE_AMO_SLOW && IS_ENABLED(CONFIG_RISCV_ISA_ZAAMO))
+ pr_warn_once("AMO is slow but kernel atomics use it, consider disabling RISCV_ISA_ZAAMO\n");
+}
+
+static int amo_speed_online_cpu(unsigned int cpu)
+{
+ check_amo_speed(NULL);
+ return 0;
+}
+
+static int __init set_amo_speed_param(char *str)
+{
+ if (!strcmp(str, "slow"))
+ amo_speed_param = RISCV_HWPROBE_AMO_SLOW;
+ else if (!strcmp(str, "fast"))
+ amo_speed_param = RISCV_HWPROBE_AMO_FAST;
+ else
+ return 0;
+
+ return 1;
+}
+__setup("amo_speed=", set_amo_speed_param);
+
+static int __init check_amo_speed_all_cpus(void)
+{
+ if (amo_speed_param != RISCV_HWPROBE_AMO_UNKNOWN)
+ pr_info("AMO speed set to '%s' (%lu) by command line\n",
+ amo_speed_param == RISCV_HWPROBE_AMO_FAST ? "fast" : "slow",
+ amo_speed_param);
+
+ on_each_cpu(check_amo_speed, NULL, 1);
+
+ cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "riscv:amo_speed",
+ amo_speed_online_cpu, NULL);
+
+ /* The vDSO was filled before the probe ran; give it the result. */
+ riscv_hwprobe_update_vdso_data();
+
+ return 0;
+}
+
+/*
+ * Same level as the unaligned access probe: after clocksource_done_booting()
+ * so that amo_speed_measure() uses a stable clocksource, but before
+ * rootfs_initcall() enables usermode helpers that can reach hwprobe.
+ */
+fs_initcall_sync(check_amo_speed_all_cpus);
diff --git a/arch/riscv/kernel/sys_hwprobe.c b/arch/riscv/kernel/sys_hwprobe.c
index 2c64a13c5155..32ce3ac8bc4a 100644
--- a/arch/riscv/kernel/sys_hwprobe.c
+++ b/arch/riscv/kernel/sys_hwprobe.c
@@ -269,6 +269,39 @@ static u64 hwprobe_misaligned(const struct cpumask *cpus)
}
#endif
+#ifdef CONFIG_RISCV_PROBE_AMO_SPEED
+static u64 hwprobe_amo(const struct cpumask *cpus)
+{
+ int cpu;
+ u64 perf = -1ULL;
+
+ for_each_cpu(cpu, cpus) {
+ int this_perf = per_cpu(amo_speed, cpu);
+
+ if (perf == -1ULL)
+ perf = this_perf;
+
+ if (perf != this_perf) {
+ perf = RISCV_HWPROBE_AMO_UNKNOWN;
+ break;
+ }
+ }
+
+ if (perf == -1ULL)
+ return RISCV_HWPROBE_AMO_UNKNOWN;
+
+ return perf;
+}
+#else
+static u64 hwprobe_amo(const struct cpumask *cpus)
+{
+ if (!hwprobe_ext0_has(cpus, RISCV_HWPROBE_EXT_ZAAMO))
+ return RISCV_HWPROBE_AMO_UNSUPPORTED;
+
+ return RISCV_HWPROBE_AMO_UNKNOWN;
+}
+#endif
+
#ifdef CONFIG_RISCV_VECTOR_MISALIGNED
static u64 hwprobe_vec_misaligned(const struct cpumask *cpus)
{
@@ -345,6 +378,10 @@ static void hwprobe_one_pair(struct riscv_hwprobe *pair,
pair->value = hwprobe_vec_misaligned(cpus);
break;
+ case RISCV_HWPROBE_KEY_AMO_PERF:
+ pair->value = hwprobe_amo(cpus);
+ break;
+
case RISCV_HWPROBE_KEY_ZICBOZ_BLOCK_SIZE:
if (hwprobe_ext0_has(cpus, RISCV_HWPROBE_EXT_ZICBOZ))
pair->value = riscv_cboz_block_size;
--
2.43.0
^ permalink raw reply [flat|nested] 7+ messages in thread