[RFC PATCH 1/8] arm64: kpkeys: Avoid unnecessary writes to POR_EL1

From: Kevin Brodsky
Date: Mon Feb 03 2025 - 05:28:57 EST


Nested uses of kpkeys guards are about to be introduced, which means
that kpkeys_set_level() may not actually need to change the value of
POR_EL1. Since updating POR_EL1 requires an expensive ISB, let's
skip the write if the value is unchanged, by returning
KPKEYS_PKEY_REG_INVAL. This will cause the matching
kpkeys_restore_pkey_reg() call to bail out without calling
arch_kpkeys_restore_pkey_reg().

Signed-off-by: Kevin Brodsky <kevin.brodsky@xxxxxxx>
---
arch/arm64/include/asm/kpkeys.h | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/arch/arm64/include/asm/kpkeys.h b/arch/arm64/include/asm/kpkeys.h
index 4854e1f3babd..3f16584d495a 100644
--- a/arch/arm64/include/asm/kpkeys.h
+++ b/arch/arm64/include/asm/kpkeys.h
@@ -27,8 +27,12 @@ static inline u64 por_set_kpkeys_level(u64 por, int level)
static inline int arch_kpkeys_set_level(int level)
{
u64 prev_por = read_sysreg_s(SYS_POR_EL1);
+ u64 new_por = por_set_kpkeys_level(prev_por, level);

- write_sysreg_s(por_set_kpkeys_level(prev_por, level), SYS_POR_EL1);
+ if (new_por == prev_por)
+ return KPKEYS_PKEY_REG_INVAL;
+
+ write_sysreg_s(new_por, SYS_POR_EL1);
isb();

return prev_por;
--
2.47.0