[PATCH v3 1/2] KVM: selftests: Add a helper to read a vCPU's APIC ID
From: Hemanth Selam
Date: Thu Aug 27 2026 - 00:48:23 EST
Reading a vCPU's APIC ID from the host means open coding KVM_GET_LAPIC and
picking the field out of the register block, which several tests already
do. Add a helper next to the other APIC definitions so that a test that
needs to target a vCPU, e.g. to send it an IPI, can just ask for its ID.
Handle both APIC modes, since where KVM reports the ID depends on the mode
and, for x2APIC, on whether userspace enabled KVM_X2APIC_API_USE_32BIT_IDS:
read APIC_ID for xAPIC, where the guest can rename itself, and use the vCPU
ID for x2APIC, which KVM keeps equal to it.
Assisted-by: Cursor:claude-opus-5
Signed-off-by: Hemanth Selam <hemanth.selam@xxxxxxxxx>
---
.../testing/selftests/kvm/include/x86/apic.h | 20 +++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/tools/testing/selftests/kvm/include/x86/apic.h b/tools/testing/selftests/kvm/include/x86/apic.h
index 31887bdc3d6c..df8815bd57af 100644
--- a/tools/testing/selftests/kvm/include/x86/apic.h
+++ b/tools/testing/selftests/kvm/include/x86/apic.h
@@ -79,6 +79,26 @@ void apic_disable(void);
void xapic_enable(void);
void x2apic_enable(void);
+/*
+ * Reads the APIC ID of a vCPU from the host, e.g. to target an IPI at it.
+ *
+ * In xAPIC mode the guest can change its own ID, so read it back from KVM,
+ * where it lives in bits 31:24 of APIC_ID. In x2APIC mode KVM ties the ID to
+ * the vCPU ID, and reports it in APIC_ID either as-is or shifted left by 24
+ * depending on KVM_X2APIC_API_USE_32BIT_IDS, so use the vCPU ID instead of
+ * having to know which format the VM opted into.
+ */
+static inline u32 vcpu_get_apic_id(struct kvm_vcpu *vcpu)
+{
+ struct kvm_lapic_state lapic;
+
+ if (vcpu_get_msr(vcpu, MSR_IA32_APICBASE) & MSR_IA32_APICBASE_EXTD)
+ return vcpu->id;
+
+ vcpu_ioctl(vcpu, KVM_GET_LAPIC, &lapic);
+ return GET_APIC_ID_FIELD(*(u32 *)&lapic.regs[APIC_ID]);
+}
+
static inline u32 get_bsp_flag(void)
{
return rdmsr(MSR_IA32_APICBASE) & MSR_IA32_APICBASE_BSP;
--
2.43.7