[PATCH 01/10] KVM: arm64: Add scoped resource management (guard) for hyp_spinlock

Fuad Tabba posted 10 patches 3 weeks ago
[PATCH 01/10] KVM: arm64: Add scoped resource management (guard) for hyp_spinlock
Posted by Fuad Tabba 3 weeks ago
The Linux kernel recently introduced scoped resource management macros
in <linux/cleanup.h>, enabling RAII-like patterns such as guard() and
scoped_guard(). These macros significantly reduce the risk of resource
leaks, deadlocks, and messy unwinding paths.

The arm64 KVM EL2 hypervisor heavily relies on its own locking
primitive, hyp_spinlock_t. Managing these locks carefully across
complex failure paths is critical, as missing an unlock at EL2
typically results in a lethal system-wide panic.

Add support for the guard(hyp_spinlock) and scoped_guard(hyp_spinlock)
macros by including <linux/cleanup.h> and using the DEFINE_LOCK_GUARD_1
infrastructure in the spinlock header. This paves the way for converting
error-prone manual locking into automatic scoped management.

Change-Id: Iba6d43c081b5fdf2496dc599fd6a781294493cb9
Signed-off-by: Fuad Tabba <tabba@google.com>
---
 arch/arm64/kvm/hyp/include/nvhe/spinlock.h | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/arch/arm64/kvm/hyp/include/nvhe/spinlock.h b/arch/arm64/kvm/hyp/include/nvhe/spinlock.h
index 7c7ea8c55405..2681f8d2fde5 100644
--- a/arch/arm64/kvm/hyp/include/nvhe/spinlock.h
+++ b/arch/arm64/kvm/hyp/include/nvhe/spinlock.h
@@ -16,6 +16,7 @@
 #include <asm/alternative.h>
 #include <asm/lse.h>
 #include <asm/rwonce.h>
+#include <linux/cleanup.h>
 
 typedef union hyp_spinlock {
 	u32	__val;
@@ -98,6 +99,10 @@ static inline void hyp_spin_unlock(hyp_spinlock_t *lock)
 	: "memory");
 }
 
+DEFINE_LOCK_GUARD_1(hyp_spinlock, hyp_spinlock_t,
+		    hyp_spin_lock(_T->lock),
+		    hyp_spin_unlock(_T->lock))
+
 static inline bool hyp_spin_is_locked(hyp_spinlock_t *lock)
 {
 	hyp_spinlock_t lockval = READ_ONCE(*lock);

-- 
2.53.0.851.ga537e3e6e9-goog