From 889c68b648ebb1b75a9fa3d780960e53c110d0bc Mon Sep 17 00:00:00 2001 From: Oleksii Kurochko Date: Tue, 31 Mar 2026 21:04:17 +0200 Subject: [PATCH] xen/riscv: add csr_read_safe() helper Accessing some CSRs may trap when the corresponding extension is not implemented or enabled. Introduce csr_read_safe() which attempts to read a CSR and relies on the exception table mechanism to safely recover if the access faults. This helper allows Xen to probe CSR availability without taking a fatal trap and will be used for feature detection during early boot as we can't always rely on what is in riscv,isa string in DTS. While touching the header, reorder the include directives to follow the usual Xen style. Signed-off-by: Oleksii Kurochko Reviewed-by: Jan Beulich --- xen/arch/riscv/include/asm/csr.h | 35 +++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/xen/arch/riscv/include/asm/csr.h b/xen/arch/riscv/include/asm/csr.h index 01876f8289..27d4b7942f 100644 --- a/xen/arch/riscv/include/asm/csr.h +++ b/xen/arch/riscv/include/asm/csr.h @@ -6,8 +6,10 @@ #ifndef ASM__RISCV__CSR_H #define ASM__RISCV__CSR_H -#include #include + +#include +#include #include #ifndef __ASSEMBLER__ @@ -78,6 +80,37 @@ : "memory" ); \ }) +static always_inline bool csr_read_safe(unsigned long csr, + unsigned long *val) +{ +#ifdef CONFIG_CC_HAS_ASM_GOTO_OUTPUT + asm_inline goto ( + "1: csrr %[val], %[csr]\n" + ASM_EXTABLE(1b, %l[fault]) + : [val] "=r" (*val) + : [csr] "i" (csr) + : + : fault ); + + return true; + + fault: + return false; +#else + bool allowed = false; + + asm_inline volatile ( + "1: csrr %[val], %[csr]\n" + " li %[allowed], 1\n" + "2:\n" + ASM_EXTABLE(1b, 2b) + : [val] "=&r" (*val), [allowed] "+r" (allowed) + : [csr] "i" (csr) ); + + return allowed; +#endif +} + #endif /* __ASSEMBLER__ */ #endif /* ASM__RISCV__CSR_H */