[RFC PATCH 09/13] KVM: SVM: Introduce helper function avic_get_apic_id

From: Suravee Suthikulpanit
Date: Sun Feb 20 2022 - 21:23:23 EST


This function returns the currently programmed guest physical
APIC ID of a vCPU in both xAPIC and x2APIC modes.
In case of invalid APIC ID based on the current mode,
the function returns X2APIC_BROADCAST.

Signed-off-by: Suravee Suthikulpanit <suravee.suthikulpanit@xxxxxxx>
---
arch/x86/kvm/svm/avic.c | 29 ++++++++++++++++++++++++++---
1 file changed, 26 insertions(+), 3 deletions(-)

diff --git a/arch/x86/kvm/svm/avic.c b/arch/x86/kvm/svm/avic.c
index 55b3b703b93b..3543b7a4514a 100644
--- a/arch/x86/kvm/svm/avic.c
+++ b/arch/x86/kvm/svm/avic.c
@@ -450,16 +450,35 @@ static void avic_invalidate_logical_id_entry(struct kvm_vcpu *vcpu)
clear_bit(AVIC_LOGICAL_ID_ENTRY_VALID_BIT, (unsigned long *)entry);
}

+static inline u32 avic_get_apic_id(struct kvm_vcpu *vcpu)
+{
+ u32 apic_id = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
+
+ if (!apic_x2apic_mode(vcpu->arch.apic)) {
+ /*
+ * In case of xAPIC, we do not support
+ * APIC ID larger than 254.
+ */
+ if (vcpu->vcpu_id >= APIC_BROADCAST)
+ return X2APIC_BROADCAST;
+ return apic_id >> 24;
+ } else
+ return apic_id;
+}
+
static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
{
int ret = 0;
struct vcpu_svm *svm = to_svm(vcpu);
u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
- u32 id = kvm_xapic_id(vcpu->arch.apic);
+ u32 id = avic_get_apic_id(vcpu);

if (ldr == svm->ldr_reg)
return 0;

+ if (id == X2APIC_BROADCAST)
+ return -EINVAL;
+
avic_invalidate_logical_id_entry(vcpu);

if (ldr)
@@ -475,7 +494,10 @@ static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
{
u64 *old, *new;
struct vcpu_svm *svm = to_svm(vcpu);
- u32 id = kvm_xapic_id(vcpu->arch.apic);
+ u32 id = avic_get_apic_id(vcpu);
+
+ if (id == X2APIC_BROADCAST)
+ return 1;

if (vcpu->vcpu_id == id)
return 0;
@@ -497,7 +519,8 @@ static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
* APIC ID table entry if already setup the LDR.
*/
if (svm->ldr_reg)
- avic_handle_ldr_update(vcpu);
+ if (avic_handle_ldr_update(vcpu))
+ return 1;

return 0;
}
--
2.25.1