[PATCH v12 09/10] riscv: implement preemptible this_cpu cmpxchg128

From: Yunhui Cui

Date: Fri Dec 04 2026 - 04:02:24 EST


Apply the recoverable per-CPU address handling to native 128-bit
compare-and-exchange. Use AMOCAS.Q to provide an atomic 128-bit update,
with a local-IRQ-protected fallback where native support is unavailable.

Signed-off-by: Yunhui Cui <cuiyunhui@xxxxxxxxxxxxx>
---
arch/riscv/include/asm/percpu.h | 49 +++++++++++++++++++++++++++++++++
1 file changed, 49 insertions(+)

diff --git a/arch/riscv/include/asm/percpu.h b/arch/riscv/include/asm/percpu.h
index d669adf3530d2..f8d174a5cafe1 100644
--- a/arch/riscv/include/asm/percpu.h
+++ b/arch/riscv/include/asm/percpu.h
@@ -415,6 +415,38 @@ __percpu_cmpxchg_case_##sz(void __percpu *pcp, unsigned long old, \
__PERCPU_8_16_CMPXCHG_CASE(8, .b)
__PERCPU_8_16_CMPXCHG_CASE(16, .h)

+#ifdef system_has_cmpxchg128
+static __always_inline u128
+__percpu_cmpxchg128_case(void __percpu *pcp, u128 old, u128 new)
+{
+ __PCPU_OP_CONTEXT();
+ union __u128_halves old_halves = { .full = old };
+ union __u128_halves new_halves = { .full = new };
+
+ register unsigned long new_lo asm("t1") = new_halves.low;
+ register unsigned long new_hi asm("t2") = new_halves.high;
+ register unsigned long old_lo asm("t3") = old_halves.low;
+ register unsigned long old_hi asm("t4") = old_halves.high;
+
+ asm volatile (__PCPU_GPRS_BEGIN(gprs, pcp, off, addr, pcpu_offset)
+ ".option push\n"
+ ".option arch, +zacas\n"
+ "amocas.q %[old_lo], %[new_lo], 0(%[addr])\n"
+ ".option pop\n"
+ __PCPU_GPRS_END(gprs)
+ : [gprs] "=m" (__ti->pcpu_gprs),
+ [off] "=&r" (__off), [addr] "=&r" (__addr),
+ [old_lo] "+&r" (old_lo), [old_hi] "+&r" (old_hi)
+ : [pcpu_offset] "m" (__ti->pcpu_offset),
+ [pcp] "r" (pcp), [new_lo] "r" (new_lo),
+ [new_hi] "r" (new_hi)
+ : "memory");
+
+ return ((u128)old_hi << 64) | old_lo;
+}
+
+#endif
+
#define this_cpu_read_1(pcp) _pcp_wrap_return(__percpu_read_8, pcp)
#define this_cpu_read_2(pcp) _pcp_wrap_return(__percpu_read_16, pcp)
#define this_cpu_read_4(pcp) _pcp_wrap_return(__percpu_read_32, pcp)
@@ -494,6 +526,23 @@ __PERCPU_8_16_CMPXCHG_CASE(16, .h)
#define this_cpu_cmpxchg64(pcp, o, n) this_cpu_cmpxchg_8(pcp, o, n)
#endif

+#ifdef system_has_cmpxchg128
+#define this_cpu_cmpxchg128(pcp, o, n) \
+({ \
+ __auto_type __pcpu_cmpxchg128_ptr = &(pcp); \
+ u128 __pcpu_cmpxchg128_old = (u128)(o); \
+ u128 __pcpu_cmpxchg128_new = (u128)(n); \
+ \
+ system_has_cmpxchg128() ? \
+ __percpu_cmpxchg128_case(__pcpu_cmpxchg128_ptr, \
+ __pcpu_cmpxchg128_old, \
+ __pcpu_cmpxchg128_new) : \
+ this_cpu_generic_cmpxchg(*__pcpu_cmpxchg128_ptr, \
+ __pcpu_cmpxchg128_old, \
+ __pcpu_cmpxchg128_new); \
+})
+#endif
+
#undef __PERCPU_AMO
#undef PERCPU_RW_OPS
#undef __PERCPU_AMO_OP_CASE
--
2.39.5