[RFC PATCH 18/19] X86: SVM: Check injected vectors before waiting for timer expiry

From: Neeraj Upadhyay
Date: Fri Feb 28 2025 - 04:25:05 EST


For Secure AVIC guests, call kvm_wait_lapic_expire() only when
the vector for LVTT is set in requested_IRR.

KVM always assumes a timer IRQ was injected if APIC state is
protected. For Secure AVIC guests, check to-be-injected vectors
in the requested_IRR to avoid unnecessary wait calls.

Signed-off-by: Neeraj Upadhyay <Neeraj.Upadhyay@xxxxxxx>
---
arch/x86/kvm/svm/sev.c | 8 ++++++++
arch/x86/kvm/svm/svm.c | 3 ++-
arch/x86/kvm/svm/svm.h | 2 ++
3 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index a7e916891226..881311227504 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -5334,3 +5334,11 @@ bool sev_savic_has_pending_interrupt(struct kvm_vcpu *vcpu)
return READ_ONCE(to_svm(vcpu)->sev_savic_has_pending_ipi) ||
kvm_apic_has_interrupt(vcpu) != -1;
}
+
+bool sev_savic_timer_int_injected(struct kvm_vcpu *vcpu)
+{
+ u32 reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVTT);
+ int vec = reg & APIC_VECTOR_MASK;
+
+ return to_svm(vcpu)->vmcb->control.requested_irr[vec / 32] & BIT(vec % 32);
+}
diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
index 08d5dc55e175..1323ec14f76a 100644
--- a/arch/x86/kvm/svm/svm.c
+++ b/arch/x86/kvm/svm/svm.c
@@ -4292,7 +4292,8 @@ static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu,
clgi();
kvm_load_guest_xsave_state(vcpu);

- kvm_wait_lapic_expire(vcpu);
+ if (!sev_savic_active(vcpu->kvm) || sev_savic_timer_int_injected(vcpu))
+ kvm_wait_lapic_expire(vcpu);

/*
* If this vCPU has touched SPEC_CTRL, restore the guest's value if
diff --git a/arch/x86/kvm/svm/svm.h b/arch/x86/kvm/svm/svm.h
index be87b9a0284f..b129ae089186 100644
--- a/arch/x86/kvm/svm/svm.h
+++ b/arch/x86/kvm/svm/svm.h
@@ -765,6 +765,7 @@ static inline bool sev_savic_active(struct kvm *kvm)
}
void sev_savic_set_requested_irr(struct vcpu_svm *svm, bool reinjected);
bool sev_savic_has_pending_interrupt(struct kvm_vcpu *vcpu);
+bool sev_savic_timer_int_injected(struct kvm_vcpu *vcpu);
#else
static inline struct page *snp_safe_alloc_page_node(int node, gfp_t gfp)
{
@@ -798,6 +799,7 @@ static inline int sev_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn)
static inline bool sev_savic_active(struct kvm *kvm) { return false; }
static inline void sev_savic_set_requested_irr(struct vcpu_svm *svm, bool reinjected) {}
static inline bool sev_savic_has_pending_interrupt(struct kvm_vcpu *vcpu) { return false; }
+static inline bool sev_savic_timer_int_injected(struct kvm_vcpu *vcpu) { return true; }
#endif

/* vmenter.S */
--
2.34.1