[PATCH v1 4/4] KVM: arm64: Add compile-time type check for register in __vcpu_rmw_sys_reg()

Fuad Tabba tabba at google.com
Mon Oct 27 04:39:43 PDT 2025


Although it is less likely that the 'r' (register) and 'val' (value)
parameters in __vcpu_rmw_sys_reg() would be swapped, it is still
possible. The register ID is an int/enum, whereas the value is a u64, as
in other similar functions and macros. The cost of adding a compile-time
check to prevent this is minimal.

To prevent this class of bugs, add a compile-time type compatibility
check to prevent the 'r' parameter from having a 'u64' type.

No functional change intended.

Signed-off-by: Fuad Tabba <tabba at google.com>
---
 arch/arm64/include/asm/kvm_host.h | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)

diff --git a/arch/arm64/include/asm/kvm_host.h b/arch/arm64/include/asm/kvm_host.h
index 2b7c8ba8802d..9758ba502ed5 100644
--- a/arch/arm64/include/asm/kvm_host.h
+++ b/arch/arm64/include/asm/kvm_host.h
@@ -1147,15 +1147,16 @@ u64 kvm_vcpu_apply_reg_masks(const struct kvm_vcpu *, enum vcpu_sysreg, u64);
 		ctxt_sys_reg(ctxt, (r)) = __v;					\
 	} while (0)
 
-#define __vcpu_rmw_sys_reg(v, r, op, val)				\
-	do {								\
-		const struct kvm_cpu_context *ctxt = &(v)->arch.ctxt;	\
-		u64 __v = ctxt_sys_reg(ctxt, (r));			\
-		__v op (val);						\
-		if (vcpu_has_nv((v)) && (r) >= __SANITISED_REG_START__)	\
-			__v = kvm_vcpu_apply_reg_masks((v), (r), __v);	\
-									\
-		ctxt_sys_reg(ctxt, (r)) = __v;				\
+#define __vcpu_rmw_sys_reg(v, r, op, val)					\
+	do {									\
+		const struct kvm_cpu_context *ctxt = &(v)->arch.ctxt;		\
+		u64 __v = ctxt_sys_reg(ctxt, (r));				\
+		BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(typeof(r), u64));\
+		__v op (val);							\
+		if (vcpu_has_nv((v)) && (r) >= __SANITISED_REG_START__)		\
+			__v = kvm_vcpu_apply_reg_masks((v), (r), __v);		\
+										\
+		ctxt_sys_reg(ctxt, (r)) = __v;					\
 	} while (0)
 
 #define __vcpu_sys_reg(v,r)						\
-- 
2.51.1.838.g19442a804e-goog




More information about the linux-arm-kernel mailing list