AMD: Add Secure AVIC KVM selftests
v2 cover AMD: Add Secure AVIC KVM selftests
This series adds KVM selftests for Secure AVIC.
The Secure AVIC KVM support patch series is at:
https://lore.kernel.org/kvm/[email protected]/
Git tree is available at:
https://github.com/AMDESE/linux-kvm/tree/savic-host-latest
Changes since v1:
v1: https://lore.kernel.org/lkml/[email protected]/
- Drop Secure AVIC APIC regs test as it relied on KVM_GET_LAPIC, KVM_SET_LAPIC IOCTLS. Since commit f65916a ("KVM: TDX: Force APICv active for TDX guest"), these IOCTLs do not work for protected APIC guests.
- Rebase on top of latest kvm next tree.
- Add detailed commit logs.
- Clean up the instruction decoder.
Neeraj Upadhyay (29):
KVM: selftests: Return an unused GHCB from the pool
KVM: selftests: Align GHCB entry struct to page size
KVM: selftests: Add #VC exception handler with error code support
KVM: selftests: Add MSR access support for SEV-ES guests
KVM: selftests: Skip guest memory checks for APIC MMIO mapping
KVM: selftests: Add x86 instruction decoding library
KVM: selftests: Adapt instruction decoder library for userspace
KVM: selftests: Restrict instruction decoder to x86_64 only
KVM: selftests: Remove unneeded functions from instruction decoder
KVM: selftests: Fix missing definitions in x86 instruction decoder
KVM: selftests: Change pt_regs to ex_regs for selftest use
KVM: selftests: Add compilation for instruction decoder library
KVM: selftests: Add MMIO #VC exception handling for SEV-ES guests
KVM: selftests: Add instruction decoding for movabs instructions
KVM: selftests: Add SEV guest support in xapic_state_test
KVM: selftests: Add x2apic mode testing in xapic_ipi_test
KVM: selftests: Add SEV VM support in xapic_ipi_test
KVM: selftests: Add Secure AVIC library
KVM: selftests: Add #VC handler for unaccelerated Secure AVIC MSRs
KVM: selftests: Add IPI handling support for Secure AVIC
KVM: selftests: Add args parameter to kvm_arch_vm_post_create()
KVM: selftests: Add GHCB call for SAVIC backing page notification
KVM: selftests: Add Secure AVIC mode to xapic_ipi_test
KVM: selftests: Add test to verify APIC MSR accesses for SAVIC guest
KVM: selftests: Extend savic_test with idle halt testing
KVM: selftests: Add IOAPIC tests for Secure AVIC
KVM: selftests: Add cross-vCPU IPI testing for SAVIC guests
KVM: selftests: Add NMI test for SAVIC guests
KVM: selftests: Add MSI injection test for SAVIC
Peter Gonda (6):
Add GHCB with setters and getters
Add arch specific additional guest pages Add vm_vaddr_alloc_pages_shared()
Add GHCB allocations and helpers
Add is_sev_enabled() helpers
Add ability for SEV-ES guests to use ucalls via GHCB
tools/arch/x86/include/asm/msr-index.h | 4 +- tools/testing/selftests/kvm/.gitignore | 3 +- tools/testing/selftests/kvm/Makefile.kvm | 14 +- .../testing/selftests/kvm/arm64/set_id_regs.c | 2 +- .../testing/selftests/kvm/include/kvm_util.h | 14 +- .../testing/selftests/kvm/include/x86/apic.h | 57 + .../selftests/kvm/include/x86/insn-eval.h | 48 + .../selftests/kvm/include/x86/processor.h | 8 + .../testing/selftests/kvm/include/x86/savic.h | 25 + tools/testing/selftests/kvm/include/x86/sev.h | 29 + tools/testing/selftests/kvm/include/x86/svm.h | 109 ++ tools/testing/selftests/kvm/lib/kvm_util.c | 109 +- .../testing/selftests/kvm/lib/x86/handlers.S | 4 +- .../testing/selftests/kvm/lib/x86/insn-eval.c | 1238 +++++++++++++++++ .../testing/selftests/kvm/lib/x86/processor.c | 24 +- tools/testing/selftests/kvm/lib/x86/savic.c | 488 +++++++ tools/testing/selftests/kvm/lib/x86/sev.c | 581 +++++++- tools/testing/selftests/kvm/lib/x86/ucall.c | 18 + tools/testing/selftests/kvm/s390/cmma_test.c | 2 +- tools/testing/selftests/kvm/x86/savic_test.c | 1171 ++++++++++++++++ .../selftests/kvm/x86/sev_smoke_test.c | 40 +- .../selftests/kvm/x86/xapic_ipi_test.c | 183 ++- .../selftests/kvm/x86/xapic_state_test.c | 117 +- 23 files changed, 4192 insertions(+), 96 deletions(-) create mode 100644 tools/testing/selftests/kvm/include/x86/insn-eval.h create mode 100644 tools/testing/selftests/kvm/include/x86/savic.h create mode 100644 tools/testing/selftests/kvm/lib/x86/insn-eval.c create mode 100644 tools/testing/selftests/kvm/lib/x86/savic.c create mode 100644 tools/testing/selftests/kvm/x86/savic_test.c
base-commit: a6ad54137af92535cfe32e19e5f3bc1bb7dbd383
Signature · 1 line
2.34.1
RFC PATCH v2 1/35 Add GHCB with setters and getters
From: Peter Gonda <[email protected]>
Move the GHCB definitions from svm.h to the tools/ copy. This allows the SEV-ES selftest to use GHCBs which are required for non-trival VMs to paravirtualize NonAutomaticExits (NAEs) when SEV-ES is enabled. GHCB getters/setters have a warning with address-of-packed-member, so removed this using the CFLAGS.
--- tools/testing/selftests/kvm/Makefile.kvm | 2 +- tools/testing/selftests/kvm/include/x86/svm.h | 106 ++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-)
tools/testing/selftests/kvm/Makefile.kvm +1 -1
@@ -237,7 +237,7 @@ LINUX_TOOL_ARCH_INCLUDE = $(top_srcdir)/tools/arch/$(ARCH)/include CFLAGS += -Wall -Wstrict-prototypes -Wuninitialized -O2 -g -std=gnu99 \ -Wno-gnu-variable-sized-type-not-at-end -MD -MP -DCONFIG_64BIT \ -fno-builtin-memcmp -fno-builtin-memcpy \ - -fno-builtin-memset -fno-builtin-strnlen \ + -fno-builtin-memset -fno-builtin-strnlen -Wno-address-of-packed-member \ -fno-stack-protector -fno-PIE -fno-strict-aliasing \ -I$(LINUX_TOOL_INCLUDE) -I$(LINUX_TOOL_ARCH_INCLUDE) \ -I$(LINUX_HDR_PATH) -Iinclude -I$(<D) -Iinclude/$(ARCH) \
tools/testing/selftests/kvm/include/x86/svm.h +106 -0
110 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 2/35 Add arch specific additional guest pages
In reply to Neeraj UpadhyayFrom: Peter Gonda <[email protected]>
SEV-ES guests need additional pages allocated for their GHCBs. Add arch specific function definition with __weak to allow for overriding for X86 specific SEV-ES functionality.
--- tools/testing/selftests/kvm/include/kvm_util.h | 2 ++ tools/testing/selftests/kvm/lib/kvm_util.c | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +2 -0
@@ -268,6 +268,8 @@ int get_kvm_param_integer(const char *param);int get_kvm_intel_param_integer (const char *param);int get_kvm_amd_param_integer (const char *param); +int kvm_arch_vm_additional_pages_required (struct vm_shape shape, +uint64_t page_size);unsigned int kvm_check_cap (long cap);static inline bool kvm_has_cap (long cap)
tools/testing/selftests/kvm/lib/kvm_util.c +12 -4
@@ -391,11 +391,11 @@ struct kvm_vm *____vm_create(struct vm_shape shape)return vm; } -static uint64_t vm_nr_pages_required (enum vm_guest_mode mode, +static uint64_t vm_nr_pages_required (struct vm_shape shape,uint32_t nr_runnable_vcpus,uint64_t extra_mem_pages) { -uint64_t page_size = vm_guest_mode_params[mode].page_size; +uint64_t page_size = vm_guest_mode_params[shape.mode].page_size;uint64_t nr_pages; TEST_ASSERT(nr_runnable_vcpus,
@@ -427,7 +427,9 @@ static uint64_t vm_nr_pages_required(enum vm_guest_mode mode,/* Account for the number of pages needed by ucall. */ nr_pages +=ucall_nr_pages_required (page_size); -return vm_adjust_num_guest_pages (mode, nr_pages); + nr_pages +=kvm_arch_vm_additional_pages_required (shape, page_size); + +return vm_adjust_num_guest_pages (shape.mode, nr_pages); }void kvm_set_files_rlimit (uint32_t nr_vcpus)
@@ -474,7 +476,7 @@ static bool is_guest_memfd_required(struct vm_shape shape)struct kvm_vm *__vm_create (struct vm_shape shape,uint32_t nr_runnable_vcpus,uint64_t nr_extra_pages) { -uint64_t nr_pages =vm_nr_pages_required (shape.mode, nr_runnable_vcpus, +uint64_t nr_pages =vm_nr_pages_required (shape, nr_runnable_vcpus, nr_extra_pages);struct userspace_mem_region *slot0;struct kvm_vm *vm;
@@ -2334,6 +2336,12 @@ __weak void kvm_arch_vm_post_create(struct kvm_vm *vm) { } +__weak int kvm_arch_vm_additional_pages_required (struct vm_shape shape, +uint64_t page_size) +{ +return 0 ; +} +__weak void kvm_selftest_arch_init (void ) { }
Signature · 1 line
2.34.1
RFC PATCH v2 3/35 Add vm_vaddr_alloc_pages_shared()
In reply to Neeraj UpadhyayFrom: Peter Gonda <[email protected]>
Add a shared page allocation. To be used for SEV-ES GHCBs.
--- tools/testing/selftests/kvm/include/kvm_util.h | 1 + tools/testing/selftests/kvm/lib/kvm_util.c | 6 ++++++ 2 files changed, 7 insertions(+)
tools/testing/selftests/kvm/include/kvm_util.h +1 -0
@@ -696,6 +696,7 @@ vm_vaddr_t vm_vaddr_alloc_shared(struct kvm_vm *vm, size_t sz,vm_vaddr_t vaddr_min, enum kvm_mem_region_type type);vm_vaddr_t vm_vaddr_alloc_pages (struct kvm_vm *vm,int nr_pages); +vm_vaddr_t vm_vaddr_alloc_pages_shared (struct kvm_vm *vm,int nr_pages);vm_vaddr_t __vm_vaddr_alloc_page (struct kvm_vm *vm,enum kvm_mem_region_type type);vm_vaddr_t vm_vaddr_alloc_page (struct kvm_vm *vm);
tools/testing/selftests/kvm/lib/kvm_util.c +6 -0
@@ -1562,6 +1562,12 @@ vm_vaddr_t vm_vaddr_alloc_pages(struct kvm_vm *vm, int nr_pages)return vm_vaddr_alloc (vm, nr_pages *getpagesize (),KVM_UTIL_MIN_VADDR ); } +vm_vaddr_t vm_vaddr_alloc_pages_shared (struct kvm_vm *vm,int nr_pages) +{ +return vm_vaddr_alloc_shared (vm, nr_pages *getpagesize (), +KVM_UTIL_MIN_VADDR ,MEM_REGION_TEST_DATA ); +} +vm_vaddr_t __vm_vaddr_alloc_page (struct kvm_vm *vm,enum kvm_mem_region_type type) {return __vm_vaddr_alloc (vm,getpagesize (),KVM_UTIL_MIN_VADDR , type);
Signature · 1 line
2.34.1
RFC PATCH v2 4/35 Add GHCB allocations and helpers
In reply to Neeraj UpadhyayFrom: Peter Gonda <[email protected]>
Add GHCB management functionality similar to the ucall management. Allows for selftest vCPUs to acquire GHCBs for their usage.
--- tools/testing/selftests/kvm/include/x86/sev.h | 2 + .../testing/selftests/kvm/lib/x86/processor.c | 9 +++ tools/testing/selftests/kvm/lib/x86/sev.c | 78 +++++++++++++++++++ 3 files changed, 89 insertions(+)
tools/testing/selftests/kvm/include/x86/sev.h +2 -0
@@ -46,6 +46,8 @@ static inline bool is_sev_vm(struct kvm_vm *vm)return is_sev_es_vm (vm) || vm->type ==KVM_X86_SEV_VM ; } +int ghcb_nr_pages_required (uint64_t page_size); +void sev_vm_launch (struct kvm_vm *vm,uint32_t policy);void sev_vm_launch_measure (struct kvm_vm *vm,uint8_t *measurement);void sev_vm_launch_finish (struct kvm_vm *vm);
tools/testing/selftests/kvm/lib/x86/processor.c +9 -0
@@ -651,6 +651,15 @@ void kvm_arch_vm_post_create(struct kvm_vm *vm)sync_global_to_guest (vm, guest_tsc_khz); } +int kvm_arch_vm_additional_pages_required (struct vm_shape shape,uint64_t page_size) +{ +if (shape.type ==KVM_X86_SEV_ES_VM || + shape.type ==KVM_X86_SNP_VM ) +return ghcb_nr_pages_required (page_size); + +return 0 ; +} +void vcpu_arch_set_entry_point (struct kvm_vcpu *vcpu,void *guest_code) {struct kvm_regs regs;
tools/testing/selftests/kvm/lib/x86/sev.c +78 -0
91 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 5/35 Add is_sev_enabled() helpers
In reply to Neeraj UpadhyayFrom: Peter Gonda <[email protected]>
Add helper functions for guest code to check the status of SEV and SEV-ES.
--- tools/testing/selftests/kvm/include/x86/sev.h | 17 +++++++++++++++++ .../testing/selftests/kvm/x86/sev_smoke_test.c | 11 +++-------- 2 files changed, 20 insertions(+), 8 deletions(-)
tools/testing/selftests/kvm/include/x86/sev.h +17 -0
@@ -46,6 +46,23 @@ static inline bool is_sev_vm(struct kvm_vm *vm)return is_sev_es_vm (vm) || vm->type ==KVM_X86_SEV_VM ; } +static inline bool is_sev_enabled (void ) +{ +return rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SEV_ENABLED ; +} + +static inline bool is_sev_es_enabled (void ) +{ +return is_sev_enabled () && +rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SEV_ES_ENABLED ; +} + +static inline bool is_sev_snp_enabled (void ) +{ +return is_sev_es_enabled () && +rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SEV_SNP_ENABLED ; +} +int ghcb_nr_pages_required (uint64_t page_size);void sev_vm_launch (struct kvm_vm *vm,uint32_t policy);
tools/testing/selftests/kvm/x86/sev_smoke_test.c +3 -8
@@ -18,11 +18,7 @@static void guest_snp_code (void ) { -uint64_t sev_msr =rdmsr (MSR_AMD64_SEV ); - -GUEST_ASSERT (sev_msr &MSR_AMD64_SEV_ENABLED ); -GUEST_ASSERT (sev_msr &MSR_AMD64_SEV_ES_ENABLED ); -GUEST_ASSERT (sev_msr &MSR_AMD64_SEV_SNP_ENABLED ); +GUEST_ASSERT (is_sev_snp_enabled ());wrmsr (MSR_AMD64_SEV_ES_GHCB ,GHCB_MSR_TERM_REQ );vmgexit ();
@@ -31,8 +27,7 @@ static void guest_snp_code(void)static void guest_sev_es_code (void ) {/* TODO: Check CPUID after GHCB-based hypercall support is added. */ -GUEST_ASSERT (rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SEV_ENABLED ); -GUEST_ASSERT (rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SEV_ES_ENABLED ); +GUEST_ASSERT (is_sev_es_enabled ());/* * TODO: Add GHCB and ucall support for SEV-ES guests. For now, simply
@@ -45,7 +40,7 @@ static void guest_sev_es_code(void)static void guest_sev_code (void ) {GUEST_ASSERT (this_cpu_has (X86_FEATURE_SEV )); -GUEST_ASSERT (rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SEV_ENABLED ); +GUEST_ASSERT (is_sev_enabled ());GUEST_DONE (); }
Signature · 1 line
2.34.1
RFC PATCH v2 6/35 Add ability for SEV-ES guests to use ucalls via GHCB
In reply to Neeraj UpadhyayFrom: Peter Gonda <[email protected]>
Modifies ucall handling for SEV-ES VMs. Instead of using an out instruction and storing the ucall pointer in RDI, SEV-ES guests use a outsb VMGEXIT to move the ucall pointer as the data. Allows for SEV-ES to use ucalls instead of relying the SEV-ES MSR based termination protocol.
--- tools/testing/selftests/kvm/include/x86/sev.h | 2 + tools/testing/selftests/kvm/lib/x86/sev.c | 98 +++++++++++++++++-- tools/testing/selftests/kvm/lib/x86/ucall.c | 18 ++++ .../selftests/kvm/x86/sev_smoke_test.c | 27 +---- 4 files changed, 113 insertions(+), 32 deletions(-)
tools/testing/selftests/kvm/include/x86/sev.h +2 -0
@@ -163,4 +163,6 @@ static inline void snp_launch_update_data(struct kvm_vm *vm, vm_paddr_t gpa, vm_sev_ioctl(vm, KVM_SEV_SNP_LAUNCH_UPDATE, &update_data); } +void sev_es_ucall_port_write (uint32_t port,uint64_t data); +#endif /* SELFTEST_KVM_SEV_H */
tools/testing/selftests/kvm/lib/x86/sev.c +90 -8
156 lines not on this page · raw message
tools/testing/selftests/kvm/lib/x86/ucall.c +18 -0
@@ -5,6 +5,8 @@* Copyright (C) 2018, Red Hat, Inc. */ #include "kvm_util.h" +#include "processor.h" +#include "sev.h" #define UCALL_PIO_PORT ((uint16_t)0x1000)
@@ -21,6 +23,11 @@ void ucall_arch_do_ucall(vm_vaddr_t uc)#define HORRIFIC_L2_UCALL_CLOBBER_HACK \ "rcx", "rsi", "r8", "r9", "r10", "r11" +if (is_sev_es_enabled ()) { +sev_es_ucall_port_write (UCALL_PIO_PORT , uc); +return ; + } + asmvolatile ("push %%rbp\n\t" "push %%r15\n\t" "push %%r14\n\t"
@@ -48,8 +55,19 @@ void *ucall_arch_get_ucall(struct kvm_vcpu *vcpu)if (run->exit_reason ==KVM_EXIT_IO && run->io.port ==UCALL_PIO_PORT ) {struct kvm_regs regs; +uint64_t addr; + +if (is_sev_es_vm (vcpu->vm)) { +TEST_ASSERT ( + run->io.count ==8 && run->io.size ==1 , +"SEV-ES ucall exit requires 8 byte string out\n" ); + + addr = *(uint64_t *)((uint8_t *)(run) + run->io.data_offset); +return (void *)addr; + }vcpu_regs_get (vcpu, ®s); +return (void *)regs.rdi; }return NULL ;
tools/testing/selftests/kvm/x86/sev_smoke_test.c +3 -24
@@ -20,8 +20,7 @@ static void guest_snp_code(void) {GUEST_ASSERT (is_sev_snp_enabled ()); -wrmsr (MSR_AMD64_SEV_ES_GHCB ,GHCB_MSR_TERM_REQ ); -vmgexit (); +GUEST_DONE (); }static void guest_sev_es_code (void )
@@ -29,12 +28,7 @@ static void guest_sev_es_code(void)/* TODO: Check CPUID after GHCB-based hypercall support is added. */ GUEST_ASSERT (is_sev_es_enabled ()); -/* -* TODO: Add GHCB and ucall support for SEV-ES guests. For now, simply -* force "termination" to signal "done" via the GHCB MSR protocol. -*/ -wrmsr (MSR_AMD64_SEV_ES_GHCB ,GHCB_MSR_TERM_REQ ); -vmgexit (); +GUEST_DONE (); }static void guest_sev_code (void )
@@ -103,12 +97,7 @@ static void test_sync_vmsa(uint32_t type, uint64_t policy)vcpu_run (vcpu); -TEST_ASSERT (vcpu->run->exit_reason ==KVM_EXIT_SYSTEM_EVENT , -"Wanted SYSTEM_EVENT, got %s" , -exit_reason_str (vcpu->run->exit_reason)); -TEST_ASSERT_EQ (vcpu->run->system_event.type,KVM_SYSTEM_EVENT_SEV_TERM ); -TEST_ASSERT_EQ (vcpu->run->system_event.ndata,1 ); -TEST_ASSERT_EQ (vcpu->run->system_event.data[0 ],GHCB_MSR_TERM_REQ ); +TEST_ASSERT_KVM_EXIT_REASON (vcpu,KVM_EXIT_IO );compare_xsave ((u8 *)&xsave, (u8 *)hva);
@@ -129,16 +118,6 @@ static void test_sev(void *guest_code, uint32_t type, uint64_t policy)for (;;) {vcpu_run (vcpu); -if (is_sev_es_vm (vm)) { -TEST_ASSERT (vcpu->run->exit_reason ==KVM_EXIT_SYSTEM_EVENT , -"Wanted SYSTEM_EVENT, got %s" , -exit_reason_str (vcpu->run->exit_reason)); -TEST_ASSERT_EQ (vcpu->run->system_event.type,KVM_SYSTEM_EVENT_SEV_TERM ); -TEST_ASSERT_EQ (vcpu->run->system_event.ndata,1 ); -TEST_ASSERT_EQ (vcpu->run->system_event.data[0 ],GHCB_MSR_TERM_REQ ); -break ; - } -switch (get_ucall (vcpu, &uc)) {case UCALL_SYNC :continue ;
Signature · 1 line
2.34.1
RFC PATCH v2 7/35 KVM: selftests: Return an unused GHCB from the pool
In reply to Neeraj UpadhyayThe ghcb_alloc() function in the SEV selftest library always returned the first GHCB from the pool, regardless of whether it was already in use. In a multi-vCPU test, this causes all vCPUs to share and corrupt the same GHCB, leading to unpredictable test failures.
Modify ghcb_alloc() to iterate through the pool and return the first entry that is not currently marked as in_use. Mark the selected entry as in use before returning it to prevent other vCPUs from allocating it.
Additionally, correct a minor bug in the memset call which was incorrectly taking the address of the ghcb pointer instead of using the pointer value itself.
This ensures that each vCPU in a test gets its own unique GHCB, allowing multi-threaded SEV-ES tests to run correctly.
--- tools/testing/selftests/kvm/lib/x86/sev.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
tools/testing/selftests/kvm/lib/x86/sev.c +1 -2
@@ -68,7 +68,6 @@ static void sev_es_terminate(void)static struct ghcb_entry *ghcb_alloc (void ) { -return &ghcb_pool->ghcbs[0 ];struct ghcb_entry *entry;struct ghcb *ghcb;int i;
@@ -81,7 +80,7 @@ static struct ghcb_entry *ghcb_alloc(void) entry = &ghcb_pool->ghcbs[i]; ghcb = &entry->ghcb; -memset (&ghcb,0 ,sizeof (*ghcb)); +memset (ghcb,0 ,sizeof (*ghcb)); ghcb->ghcb_usage =0 ; ghcb->protocol_version =1 ;
Signature · 1 line
2.34.1
RFC PATCH v2 8/35 KVM: selftests: Align GHCB entry struct to page size
In reply to Neeraj UpadhyayThe SEV GHCB specification defines two methods for a guest to register its GHCB page with the hypervisor: an MSR-based protocol and a GPA-based protocol. The hypervisor (KVM) distinguishes between them by inspecting the value written to the MSR_AMD64_SEV_ES_GHCB MSR. If the value has its lower 12 bits as zero, it is treated as a page-aligned Guest Physical Address (GPA). Otherwise, it is interpreted as a command for the MSR-based protocol.
The selftest's ghcb_entry struct is not explicitly page-aligned. When the test guest attemptd to register the GHCB by writing its unaligned GPA to the MSR, KVM would incorrectly interpret the request as a malformed MSR-based command instead of a GPA registration. This caused GHCB initialization to fail.
Fix this by aligning the ghcb_entry struct definition to PAGE_SIZE. This forces the structure to be page-aligned, ensuring its GPA has zero in the lower 12 bits and allowing KVM to correctly recognize it as a GPA registration request.
--- tools/testing/selftests/kvm/lib/x86/sev.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/kvm/lib/x86/sev.c +1 -1
@@ -22,7 +22,7 @@ struct ghcb_entry {/* Host virtual address of this struct. */ struct ghcb_entry *hva; -}; +}__aligned(PAGE_SIZE) ;struct ghcb_header {struct ghcb_entry ghcbs[KVM_MAX_VCPUS ];
Signature · 1 line
2.34.1
RFC PATCH v2 9/35 KVM: selftests: Add #VC exception handler with error code support
In reply to Neeraj UpadhyayThe VMM Communication Exception (#VC, vector 29) pushes an error code onto the stack, similar to exceptions like #PF or #GP.
The generic IDT handler generation macro in the selftests incorrectly assumed that all vectors from 18 to 255 do not have an error code. For new tests (added in subsequent commits) which trigger #VC exception, this incorrect assumption caused the handler to misinterpret the stack frame and the ex_regs fields, leading to stack corruption upon IRET.
Fix this by explicitly defining a handler for vector 29 that correctly accounts for the error code.
This allows selftests to properly catch and handle #VC exceptions, which is a prerequisite for testing features like SEV-ES.
--- tools/testing/selftests/kvm/lib/x86/handlers.S | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
tools/testing/selftests/kvm/lib/x86/handlers.S +3 -1
@@ -76,6 +76,8 @@ idt_handler_code: HANDLERS has_error=1 from=10 to=14 HANDLERS has_error=0 from=15 to=16 HANDLERS has_error=1 from=17 to=17 - HANDLERS has_error=0 from=18 to=255 + HANDLERS has_error=0 from=18 to=28 + HANDLERS has_error=1 from=29 to=29 + HANDLERS has_error=0 from=30 to=255 .section .note.GNU-stack, "", %progbits
Signature · 1 line
2.34.1
RFC PATCH v2 10/35 KVM: selftests: Add MSR access support for SEV-ES guests
In reply to Neeraj UpadhyayFor SEV-ES guests, RDMSR/WRMSR of the intercepted MSRs trap and generate a #VC (VMM Communication) exception. The guest must then handle this exception and communicate the desired MSR operation to the hypervisor using the GHCB protocol.
Add the necessary selftest infrastructure to support this flow, enabling tests to correctly perform MSR operations from within an SEV-ES guest.
Two mechanisms are introduced:
1. #VC Exception Handling: Provide a #VC handler, which inspects the trapping instruction and the register state and does a GHCB request to forward the MSR operation to the host .
2. Paravirtual Interface: Provide a direct, "paravirtual" way to test the MSR GHCB protocol. This allows test code to request an MSR read or write without needing to execute a trapping instruction, simplifying certain test scenarios.
--- tools/testing/selftests/kvm/include/x86/sev.h | 2 + tools/testing/selftests/kvm/lib/x86/sev.c | 83 ++++++++++++++++++- 2 files changed, 84 insertions(+), 1 deletion(-)
tools/testing/selftests/kvm/include/x86/sev.h +2 -0
@@ -165,4 +165,6 @@ static inline void snp_launch_update_data(struct kvm_vm *vm, vm_paddr_t gpa,void sev_es_ucall_port_write (uint32_t port,uint64_t data); +void sev_es_vc_handler (struct ex_regs *regs); +void sev_es_pv_msr_rw (uint64_t msr,uint64_t *data,bool write);#endif /* SELFTEST_KVM_SEV_H */
tools/testing/selftests/kvm/lib/x86/sev.c +82 -1
92 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 11/35 KVM: selftests: Skip guest memory checks for APIC MMIO mapping
In reply to Neeraj UpadhyayThe __virt_pg_map() helper function, used to build guest page tables, calls vm_is_gpa_protected() to determine the correct memory protection attributes for a given Guest Physical Address (GPA). This check works by looking up the GPA in the VM's defined physical memory regions.
This approach fails when mapping the local APIC's base address (0xfee00000), as this is a Memory-Mapped I/O (MMIO) region, not part of the guest's RAM. Consequently, the lookup fails, and virt_pg_map() aborts with the error: "No vm physical memory at 0xfee00000".
Fix this by introducing a special case for the APIC base address. When the physical address being mapped is APIC_DEFAULT_GPA, bypass the vm_is_gpa_protected() call. Since the APIC MMIO region is always treated as shared, explicitly set the shared bit in its Page Table Entry (PTE) and return immediately.
This allows selftests to correctly map the APIC MMIO region, which is necessary for tests involving protected guests.
--- tools/testing/selftests/kvm/lib/x86/processor.c | 6 ++++++ 1 file changed, 6 insertions(+)
tools/testing/selftests/kvm/lib/x86/processor.c +6 -0
@@ -8,6 +8,7 @@#include "kvm_util.h" #include "processor.h" #include "sev.h" +#include "apic.h" #ifndef NUM_INTERRUPTS #define NUM_INTERRUPTS 256
@@ -227,6 +228,11 @@ void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, int level) "PTE already present for 4k page at vaddr: 0x%lx", vaddr); *pte =PTE_PRESENT_MASK |PTE_WRITABLE_MASK | (paddr &PHYSICAL_PAGE_MASK ); +if (paddr ==APIC_DEFAULT_GPA ) { + *pte |= vm->arch.s_bit; +return ; + } +/* * Neither SEV nor TDX supports shared page tables, so only the final * leaf PTE needs manually set the C/S-bit.
Signature · 1 line
2.34.1
RFC PATCH v2 12/35 KVM: selftests: Add x86 instruction decoding library
In reply to Neeraj UpadhyayFor SEV-ES guests, certain MMIO accesses are configured to trap, generating a #VC (VMM Communication) exception. The guest-side instruction.
To perform this emulation correctly, the handler needs to decode the instruction to determine its properties, such as the access size (byte, word, dword), direction (read/write), and the registers involved. This requires an instruction decoding library.
Introduce the kernel's x86 instruction decoder (arch/x86/lib/insn-eval.c) into the selftest library to provide this capability.
For ease of review, add an unmodified snapshot of the kernel file. Subsequent commits will strip it down to only the functionality required for emulating MMIO instruction, reducing its size and complexity for the selftest environment.
--- tools/testing/selftests/kvm/.gitignore | 3 +- .../selftests/kvm/include/x86/insn-eval.h | 47 + .../testing/selftests/kvm/lib/x86/insn-eval.c | 1678 +++++++++++++++++ 3 files changed, 1727 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/kvm/include/x86/insn-eval.h create mode 100644 tools/testing/selftests/kvm/lib/x86/insn-eval.c
tools/testing/selftests/kvm/.gitignore +2 -1
@@ -9,4 +9,5 @@ !config !settings !Makefile -!Makefile.kvm +!Makefile.kvm +
tools/testing/selftests/kvm/include/x86/insn-eval.h new file +47 -0
47 lines not on this page · raw message
tools/testing/selftests/kvm/lib/x86/insn-eval.c new file +1678 -0
1,678 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 13/35 KVM: selftests: Adapt instruction decoder library for userspace
In reply to Neeraj UpadhyayThe insn-eval.c library, recently added for SEV-ES #VC emulation, is from arch/x86/lib/ and contains dependencies on kernel-specific headers and macros (e.g., <linux/kernel.h>, pr_err_ratelimited). These dependencies prevent it from being compiled directly within the userspace selftest framework.
Adapt the library to be buildable in a userspace environment for selftests:
- Replace kernel headers with standard C library and selftest-specific headers.
- Translate a kernel-level warning or error into a selftest failure.
- Remove kernel-specfic annotations.
--- .../selftests/kvm/include/x86/insn-eval.h | 5 +--- .../testing/selftests/kvm/lib/x86/insn-eval.c | 30 +++++++------------ 2 files changed, 12 insertions(+), 23 deletions(-)
tools/testing/selftests/kvm/include/x86/insn-eval.h +1 -4
@@ -6,10 +6,7 @@* of the registers indicated by operands. */ -#include <linux/compiler.h> -#include <linux/bug.h> -#include <linux/err.h> -#include <asm/ptrace.h> +#include <stdbool.h> #define INSN_CODE_SEG_ADDR_SZ (params) ((params >> 4) & 0xf)#define INSN_CODE_SEG_OPND_SZ (params) (params & 0xf)
tools/testing/selftests/kvm/lib/x86/insn-eval.c +11 -19
@@ -3,18 +3,17 @@* * Copyright (C) Intel Corporation 2017 */ -#include <linux/kernel.h> -#include <linux/string.h> -#include <linux/ratelimit.h> -#include <linux/mmu_context.h> -#include <asm/desc_defs.h> -#include <asm/desc.h> +#include <stdio.h> +#include <stdbool.h> +#include <string.h> +#include <errno.h> +#include <asm/inat.h> #include <asm/insn.h> -#include <asm/insn-eval.h> -#include <asm/ldt.h> -#include <asm/msr.h> -#include <asm/vm86.h> + +#include "insn-eval.h" +#include "kselftest.h" +#include "ucall_common.h" #undef pr_fmt#define pr_fmt (fmt) "insn: " fmt
@@ -509,12 +508,12 @@ static int get_regno(struct insn *insn, enum reg_type type)break ;default : -pr_err_ratelimited ("invalid register type: %d\n" , type); +__GUEST_ASSERT (false,"invalid register type: %d\n" , type);return -EINVAL ; }if (regno >= nr_registers) { -WARN_ONCE (1 ,"decoded an instruction with an invalid register" ); +__GUEST_ASSERT (false,"decoded an instruction with an invalid register" );return -EINVAL ; }return regno;
@@ -842,7 +841,6 @@ int insn_get_code_seg_params(struct pt_regs *regs)*/ return INSN_CODE_SEG_PARAMS (4 ,8 );case 3 :/* Invalid setting. CS.L=1, CS.D=1 */ - fallthrough;default :return -EINVAL ; }
@@ -1617,7 +1615,6 @@ enum insn_mmio_type insn_decode_mmio(struct insn *insn, int *bytes)switch (insn->opcode.bytes[0 ]) {case 0x88 :/* MOV m8,r8 */ *bytes =1 ; - fallthrough;case 0x89 :/* MOV m16/m32/m64, r16/m32/m64 */ if (!*bytes) *bytes = insn->opnd_bytes;
@@ -1626,7 +1623,6 @@ enum insn_mmio_type insn_decode_mmio(struct insn *insn, int *bytes)case 0xc6 :/* MOV m8, imm8 */ *bytes =1 ; - fallthrough;case 0xc7 :/* MOV m16/m32/m64, imm16/imm32/imm64 */ if (!*bytes) *bytes = insn->opnd_bytes;
@@ -1635,7 +1631,6 @@ enum insn_mmio_type insn_decode_mmio(struct insn *insn, int *bytes)case 0x8a :/* MOV r8, m8 */ *bytes =1 ; - fallthrough;case 0x8b :/* MOV r16/r32/r64, m16/m32/m64 */ if (!*bytes) *bytes = insn->opnd_bytes;
@@ -1644,7 +1639,6 @@ enum insn_mmio_type insn_decode_mmio(struct insn *insn, int *bytes)case 0xa4 :/* MOVS m8, m8 */ *bytes =1 ; - fallthrough;case 0xa5 :/* MOVS m16/m32/m64, m16/m32/m64 */ if (!*bytes) *bytes = insn->opnd_bytes;
@@ -1655,7 +1649,6 @@ enum insn_mmio_type insn_decode_mmio(struct insn *insn, int *bytes)switch (insn->opcode.bytes[1 ]) {case 0xb6 :/* MOVZX r16/r32/r64, m8 */ *bytes =1 ; - fallthrough;case 0xb7 :/* MOVZX r32/r64, m16 */ if (!*bytes) *bytes =2 ;
@@ -1664,7 +1657,6 @@ enum insn_mmio_type insn_decode_mmio(struct insn *insn, int *bytes)case 0xbe :/* MOVSX r16/r32/r64, m8 */ *bytes =1 ; - fallthrough;case 0xbf :/* MOVSX r32/r64, m16 */ if (!*bytes) *bytes =2 ;
Signature · 1 line
2.34.1
RFC PATCH v2 14/35 KVM: selftests: Restrict instruction decoder to x86_64 only
In reply to Neeraj UpadhyayThe insn-eval.c library was recently imported from the kernel source and contains a significant amount of code to support legacy x86 operating modes, such as 32-bit protected mode, 16-bit addressing, and v8086 mode.
The KVM selftests, particularly for features like SEV-ES, exclusively target the 64-bit architecture with guest kernel running in kernel mode.
Simplify the decoder by removing all logic not relevant to 64-bit mode. This involves:
- Remove all CONFIG_X86_32 and v8086_mode conditional logic.
- Simplify resolve_default_seg to always assume 64-bit segmentation rules (i.e., most segments are ignored).
- Rework insn_get_seg_base to only handle the 64-bit model where FS/GS bases are read from MSRs.
- Delete support for 16-bit address decoding.
- Remove complex segment descriptor lookups, which are not used in the 64-bit flat memory model.
This makes the library smaller and easier to maintain for its intended purpose within the selftests.
--- .../testing/selftests/kvm/lib/x86/insn-eval.c | 254 ++---------------- 1 file changed, 28 insertions(+), 226 deletions(-)
tools/testing/selftests/kvm/lib/x86/insn-eval.c +28 -226
@@ -178,52 +178,7 @@ static bool check_seg_overrides(struct insn *insn, int regoff)*/ static int resolve_default_seg (struct insn *insn,struct pt_regs *regs,int off) { -if (any_64bit_mode (regs)) -return INAT_SEG_REG_IGNORE ; -/* -* Resolve the default segment register as described in Section 3.7.4 -* of the Intel Software Development Manual Vol. 1: -* -* + DS for all references involving r[ABCD]X, and rSI. -* + If used in a string instruction, ES for rDI. Otherwise, DS. -* + AX, CX and DX are not valid register operands in 16-bit address -* encodings but are valid for 32-bit and 64-bit encodings. -* + -EDOM is reserved to identify for cases in which no register -* is used (i.e., displacement-only addressing). Use DS. -* + SS for rSP or rBP. -* + CS for rIP. -*/ - -switch (off) { -case offsetof(struct pt_regs , ax): -case offsetof(struct pt_regs , cx): -case offsetof(struct pt_regs , dx): -/* Need insn to verify address size. */ -if (insn->addr_bytes ==2 ) -return -EINVAL ; - - fallthrough; - -case -EDOM : -case offsetof(struct pt_regs , bx): -case offsetof(struct pt_regs , si): -return INAT_SEG_REG_DS ; - -case offsetof(struct pt_regs , di): -if (is_string_insn (insn)) -return INAT_SEG_REG_ES ; -return INAT_SEG_REG_DS ; - -case offsetof(struct pt_regs , bp): -case offsetof(struct pt_regs , sp): -return INAT_SEG_REG_SS ; - -case offsetof(struct pt_regs , ip): -return INAT_SEG_REG_CS ; - -default : -return -EINVAL ; - } +return INAT_SEG_REG_IGNORE ; }/**
@@ -288,12 +243,8 @@ static int resolve_seg_reg(struct insn *insn, struct pt_regs *regs, int regoff)* be used. Hence, it is not necessary to inspect the instruction, * which may be invalid at this point. */ -if (regoff == offsetof(struct pt_regs , ip)) { -if (any_64bit_mode (regs)) -return INAT_SEG_REG_IGNORE ; -else -return INAT_SEG_REG_CS ; - } +if (regoff == offsetof(struct pt_regs , ip)) +return INAT_SEG_REG_IGNORE ;if (!insn)return -EINVAL ;
@@ -312,11 +263,8 @@ static int resolve_seg_reg(struct insn *insn, struct pt_regs *regs, int regoff)* In long mode, segment override prefixes are ignored, except for * overrides for FS and GS. */ -if (any_64bit_mode (regs)) { -if (idx !=INAT_SEG_REG_FS && - idx !=INAT_SEG_REG_GS ) - idx =INAT_SEG_REG_IGNORE ; - } +if (idx !=INAT_SEG_REG_FS && idx !=INAT_SEG_REG_GS ) + idx =INAT_SEG_REG_IGNORE ;return idx; }
@@ -327,11 +275,9 @@ static int resolve_seg_reg(struct insn *insn, struct pt_regs *regs, int regoff)* @seg_reg_idx: Segment register index to use * * Obtain the segment selector from any of the CS, SS, DS, ES, FS, GS segment -* registers. In CONFIG_X86_32, the segment is obtained from either pt_regs or -* kernel_vm86_regs as applicable. In CONFIG_X86_64, CS and SS are obtained -* from pt_regs. DS, ES, FS and GS are obtained by reading the actual CPU -* registers. This done for only for completeness as in CONFIG_X86_64 segment -* registers are ignored. +* registers. CS and SS are obtained from pt_regs. DS, ES, FS and GS are +* obtained by reading the actual CPU registers. This done for only for +* completeness as in X86_64 segment registers are ignored. * * Returns: *
@@ -344,7 +290,6 @@ static short get_segment_selector(struct pt_regs *regs, int seg_reg_idx) {unsigned short sel; -#ifdef CONFIG_X86_64 switch (seg_reg_idx) {case INAT_SEG_REG_IGNORE :return 0 ;
@@ -367,48 +312,6 @@ static short get_segment_selector(struct pt_regs *regs, int seg_reg_idx)default :return -EINVAL ; } -#else /* CONFIG_X86_32 */ -struct kernel_vm86_regs *vm86regs = (struct kernel_vm86_regs *)regs; - -if (v8086_mode (regs)) { -switch (seg_reg_idx) { -case INAT_SEG_REG_CS : -return (unsigned short )(regs->cs &0xffff ); -case INAT_SEG_REG_SS : -return (unsigned short )(regs->ss &0xffff ); -case INAT_SEG_REG_DS : -return vm86regs->ds; -case INAT_SEG_REG_ES : -return vm86regs->es; -case INAT_SEG_REG_FS : -return vm86regs->fs; -case INAT_SEG_REG_GS : -return vm86regs->gs; -case INAT_SEG_REG_IGNORE : -default : -return -EINVAL ; - } - } - -switch (seg_reg_idx) { -case INAT_SEG_REG_CS : -return (unsigned short )(regs->cs &0xffff ); -case INAT_SEG_REG_SS : -return (unsigned short )(regs->ss &0xffff ); -case INAT_SEG_REG_DS : -return (unsigned short )(regs->ds &0xffff ); -case INAT_SEG_REG_ES : -return (unsigned short )(regs->es &0xffff ); -case INAT_SEG_REG_FS : -return (unsigned short )(regs->fs &0xffff ); -case INAT_SEG_REG_GS : -savesegment (gs, sel); -return sel; -case INAT_SEG_REG_IGNORE : -default : -return -EINVAL ; - } -#endif /* CONFIG_X86_64 */ }static const int pt_regoff[] = {
@@ -420,7 +323,6 @@ static const int pt_regoff[] = { offsetof(struct pt_regs , bp), offsetof(struct pt_regs , si), offsetof(struct pt_regs , di), -#ifdef CONFIG_X86_64 offsetof(struct pt_regs , r8), offsetof(struct pt_regs , r9), offsetof(struct pt_regs, r10),
@@ -429,12 +331,6 @@ static const int pt_regoff[] = { offsetof(struct pt_regs , r13), offsetof(struct pt_regs , r14), offsetof(struct pt_regs, r15), -#else - offsetof(struct pt_regs , ds), - offsetof(struct pt_regs , es), - offsetof(struct pt_regs , fs), - offsetof(struct pt_regs, gs), -#endif };int pt_regs_offset (struct pt_regs *regs,int regno)
@@ -453,9 +349,6 @@ static int get_regno(struct insn *insn, enum reg_type type)* Don't possibly decode a 32-bit instructions as * reading a 64-bit-only register. */ -if (IS_ENABLED (CONFIG_X86_64 ) && !insn->x86_64) - nr_registers -=8 ; -switch (type) {case REG_TYPE_RM : regno =X86_MODRM_RM (insn->modrm.value);
@@ -687,52 +580,33 @@ static bool get_desc(struct desc_struct *out, unsigned short sel)*/ unsigned long insn_get_seg_base (struct pt_regs *regs,int seg_reg_idx) { -struct desc_struct desc; +unsigned long base;short sel; sel =get_segment_selector (regs, seg_reg_idx);if (sel <0 )return -1L ; -if (v8086_mode (regs)) -/* -* Base is simply the segment selector shifted 4 -* bits to the right. -*/ -return (unsigned long )(sel <<4 ); +/* +* Only FS or GS will have a base address, the rest of +* the segments' bases are forced to 0. +*/ -if (any_64bit_mode (regs)) { +if (seg_reg_idx ==INAT_SEG_REG_FS ) { +rdmsrq (MSR_FS_BASE , base); + }else if (seg_reg_idx ==INAT_SEG_REG_GS ) {/* -* Only FS or GS will have a base address, the rest of -* the segments' bases are forced to 0. +* swapgs was called at the kernel entry point. Thus, +* MSR_KERNEL_GS_BASE will have the user-space GS base. */ -unsigned long base; - -if (seg_reg_idx ==INAT_SEG_REG_FS ) { -rdmsrq (MSR_FS_BASE , base); - }else if (seg_reg_idx ==INAT_SEG_REG_GS ) { -/* -* swapgs was called at the kernel entry point. Thus, -* MSR_KERNEL_GS_BASE will have the user-space GS base. -*/ -if (user_mode (regs)) -rdmsrq (MSR_KERNEL_GS_BASE , base); -else -rdmsrq (MSR_GS_BASE , base); - }else { - base =0 ; - } -return base; +if (user_mode (regs)) +rdmsrq (MSR_KERNEL_GS_BASE , base); +else +rdmsrq (MSR_GS_BASE , base); + }else { + base =0 ; } - -/* In protected mode the segment selector cannot be null. */ -if (!sel) -return -1L ; - -if (!get_desc (&desc, sel)) -return -1L ; - -return get_desc_base (&desc); +return base; }/**
@@ -762,26 +636,7 @@ static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx)if (sel <0 )return 0 ; -if (any_64bit_mode (regs) ||v8086_mode (regs)) -return -1L ; - -if (!sel) -return 0 ; - -if (!get_desc (&desc, sel)) -return 0 ; - -/* -* If the granularity bit is set, the limit is given in multiples -* of 4096. This also means that the 12 least significant bits are -* not tested when checking the segment limits. In practice, -* this means that the segment ends in (limit << 12) + 0xfff. -*/ - limit =get_desc_limit (&desc); -if (desc.g) - limit = (limit <<12 ) +0xfff ; - -return limit; +return -1L ; }/**
@@ -805,10 +660,6 @@ int insn_get_code_seg_params(struct pt_regs *regs)struct desc_struct desc;short sel; -if (v8086_mode (regs)) -/* Address and operand size are both 16-bit. */ -return INSN_CODE_SEG_PARAMS (2 ,2 ); - sel =get_segment_selector (regs,INAT_SEG_REG_CS );if (sel <0 )return sel;
@@ -1042,10 +893,7 @@ static int get_eff_addr_modrm(struct insn *insn, struct pt_regs *regs,* following instruction. */ if (*regoff == -EDOM ) { -if (any_64bit_mode (regs)) - tmp = regs->ip + insn->length; -else - tmp =0 ; + tmp = regs->ip + insn->length; }else if (*regoff <0 ) {return -EINVAL ; }else {
@@ -1277,9 +1125,6 @@ static void __user *get_addr_ref_16(struct insn *insn, struct pt_regs *regs) linear_addr = (unsigned long )(eff_addr &0xffff ) + seg_base; -/* Limit linear address to 20 bits */ -if (v8086_mode (regs)) - linear_addr &=0xfffff ; out:return (void __user *)linear_addr;
@@ -1338,27 +1183,6 @@ static void __user *get_addr_ref_32(struct insn *insn, struct pt_regs *regs)if (ret) goto out; -/* -* In protected mode, before computing the linear address, make sure -* the effective address is within the limits of the segment. -* 32-bit addresses can be used in long and virtual-8086 modes if an -* address override prefix is used. In such cases, segment limits are -* not enforced. When in virtual-8086 mode, the segment limit is -1L -* to reflect this situation. -* -* After computed, the effective address is treated as an unsigned -* quantity. -*/ -if (!any_64bit_mode (regs) && ((unsigned int )eff_addr > seg_limit)) - goto out; - -/* -* Even though 32-bit address encodings are allowed in virtual-8086 -* mode, the address range is still limited to [0x-0xffff]. -*/ -if (v8086_mode (regs) && (eff_addr & ~0xffff )) - goto out; -/* * Data type long could be 64 bits in size. Ensure that our 32-bit * effective address is not sign-extended when computing the linear
@@ -1366,9 +1190,6 @@ static void __user *get_addr_ref_32(struct insn *insn, struct pt_regs *regs)*/ linear_addr = (unsigned long )(eff_addr &0xffffffff ) + seg_base; -/* Limit linear address to 20 bits */ -if (v8086_mode (regs)) - linear_addr &=0xfffff ; out:return (void __user *)linear_addr;
@@ -1389,12 +1210,6 @@ static void __user *get_addr_ref_32(struct insn *insn, struct pt_regs *regs)* * -1L on error. */ -#ifndef CONFIG_X86_64 -static void __user *get_addr_ref_64 (struct insn *insn,struct pt_regs *regs) -{ -return (void __user *)-1L ; -} -#else static void __user *get_addr_ref_64 (struct insn *insn,struct pt_regs *regs) {unsigned long linear_addr =-1L , seg_base;
@@ -1431,7 +1246,6 @@ static void __user *get_addr_ref_64(struct insn *insn, struct pt_regs *regs) out:return (void __user *)linear_addr; } -#endif /* CONFIG_X86_64 */ /** * insn_get_addr_ref() - Obtain the linear address referred by instruction
@@ -1472,18 +1286,6 @@ int insn_get_effective_ip(struct pt_regs *regs, unsigned long *ip) {unsigned long seg_base =0 ; -/* -* If not in user-space long mode, a custom code segment could be in -* use. This is true in protected mode (if the process defined a local -* descriptor table), or virtual-8086 mode. In most of the cases -* seg_base will be zero as in USER_CS. -*/ -if (!user_64bit_mode (regs)) { - seg_base =insn_get_seg_base (regs,INAT_SEG_REG_CS ); -if (seg_base ==-1L ) -return -EINVAL ; - } - *ip = seg_base + regs->ip;return 0 ;
@@ -1563,7 +1365,7 @@ bool insn_decode_from_regs(struct insn *insn, struct pt_regs *regs, {int seg_defs; -insn_init (insn, buf, buf_size,user_64bit_mode (regs)); +insn_init (insn, buf, buf_size, true);/* * Override the default operand and address sizes with what is specified
Signature · 1 line
2.34.1
RFC PATCH v2 15/35 KVM: selftests: Remove unneeded functions from instruction decoder
In reply to Neeraj UpadhyayThe instruction decoder library was added to support SEV-ES #VC exception handling, where its only required function is to decode MMIO instructions. The library, as imported from the kernel, contains several high-level helper functions that are not needed for this purpose.
Remove this unneeded code to strip the library down to the minimum required for its purpose within the selftests, reducing its size and maintenance complexity.
While at it, convert the function header comments to not be part of kernel documentation.
--- .../testing/selftests/kvm/lib/x86/insn-eval.c | 297 ++---------------- 1 file changed, 22 insertions(+), 275 deletions(-)
tools/testing/selftests/kvm/lib/x86/insn-eval.c +22 -275
@@ -25,7 +25,7 @@ enum reg_type { REG_TYPE_BASE, }; -/** +/* * is_string_insn() - Determine if instruction is a string instruction * @insn: Instruction containing the opcode to inspect *
@@ -51,7 +51,7 @@ static bool is_string_insn(struct insn *insn) } } -/** +/* * insn_has_rep_prefix() - Determine if instruction has a REP prefix * @insn: Instruction containing the prefix to inspect *
@@ -74,7 +74,7 @@ bool insn_has_rep_prefix(struct insn *insn)return false; } -/** +/* * get_seg_reg_override_idx() - obtain segment register override index * @insn: Valid instruction with segment override prefixes *
@@ -137,7 +137,7 @@ static int get_seg_reg_override_idx(struct insn *insn)return idx; } -/** +/* * check_seg_overrides() - check if segment override prefixes are allowed * @insn: Valid instruction with segment override prefixes * @regoff: Operand offset, in pt_regs, for which the check is performed
@@ -159,7 +159,7 @@ static bool check_seg_overrides(struct insn *insn, int regoff)return true; } -/** +/* * resolve_default_seg() - resolve default segment register index for an operand * @insn: Instruction with opcode and address size. Must be valid. * @regs: Register values as seen when entering kernel mode
@@ -181,7 +181,7 @@ static int resolve_default_seg(struct insn *insn, struct pt_regs *regs, int off)return INAT_SEG_REG_IGNORE ; } -/** +/* * resolve_seg_reg() - obtain segment register index * @insn: Instruction with operands * @regs: Register values as seen when entering kernel mode
@@ -268,8 +268,7 @@ static int resolve_seg_reg(struct insn *insn, struct pt_regs *regs, int regoff)return idx; } - -/** +/* * get_segment_selector() - obtain segment selector * @regs: Register values as seen when entering kernel mode * @seg_reg_idx: Segment register index to use
@@ -423,7 +422,7 @@ static int get_reg_offset(struct insn *insn, struct pt_regs *regs,return pt_regs_offset (regs, regno); } -/** +/* * get_reg_offset_16() - Obtain offset of register indicated by instruction * @insn: Instruction containing ModRM byte * @regs: Register values as seen when entering kernel mode
@@ -497,71 +496,7 @@ static int get_reg_offset_16(struct insn *insn, struct pt_regs *regs,return 0 ; } -/** -* get_desc() - Obtain contents of a segment descriptor -* @out: Segment descriptor contents on success -* @sel: Segment selector -* -* Given a segment selector, obtain a pointer to the segment descriptor. -* Both global and local descriptor tables are supported. -* -* Returns: -* -* True on success, false on failure. -* -* NULL on error. -*/ -static bool get_desc (struct desc_struct *out,unsigned short sel) -{ -struct desc_ptr gdt_desc = {0 ,0 }; -unsigned long desc_base; - -#ifdef CONFIG_MODIFY_LDT_SYSCALL -if ((sel &SEGMENT_TI_MASK ) ==SEGMENT_LDT ) { -bool success = false; -struct ldt_struct *ldt; - -/* Bits [15:3] contain the index of the desired entry. */ - sel >>=3 ; - -/* -* If we're not in a valid context with a real (not just lazy) -* user mm, then don't even try. -*/ -if (!nmi_uaccess_okay ()) -return false; - -mutex_lock (¤t->mm->context.lock); - ldt = current->mm->context.ldt; -if (ldt && sel < ldt->nr_entries) { - *out = ldt->entries[sel]; - success = true; - } - -mutex_unlock (¤t->mm->context.lock); - -return success; - } -#endif -native_store_gdt (&gdt_desc); - -/* -* Segment descriptors have a size of 8 bytes. Thus, the index is -* multiplied by 8 to obtain the memory offset of the desired descriptor -* from the base of the GDT. As bits [15:3] of the segment selector -* contain the index, it can be regarded as multiplied by 8 already. -* All that remains is to clear bits [2:0]. -*/ - desc_base = sel & ~(SEGMENT_RPL_MASK |SEGMENT_TI_MASK ); - -if (desc_base > gdt_desc.size) -return false; - - *out = *(struct desc_struct *)(gdt_desc.address + desc_base); -return true; -} - -/** +/* * insn_get_seg_base() - Obtain base address of segment descriptor. * @regs: Register values as seen when entering kernel mode * @seg_reg_idx: Index of the segment register pointing to seg descriptor
@@ -609,7 +544,7 @@ unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx)return base; } -/** +/* * get_seg_limit() - Obtain the limit of a segment descriptor * @regs: Register values as seen when entering kernel mode * @seg_reg_idx: Index of the segment register pointing to seg descriptor
@@ -628,8 +563,6 @@ unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx)*/ static unsigned long get_seg_limit (struct pt_regs *regs,int seg_reg_idx) { -struct desc_struct desc; -unsigned long limit;short sel; sel =get_segment_selector (regs, seg_reg_idx);
@@ -639,82 +572,7 @@ static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx)return -1L ; } -/** -* insn_get_code_seg_params() - Obtain code segment parameters -* @regs: Structure with register values as seen when entering kernel mode -* -* Obtain address and operand sizes of the code segment. It is obtained from the -* selector contained in the CS register in regs. In protected mode, the default -* address is determined by inspecting the L and D bits of the segment -* descriptor. In virtual-8086 mode, the default is always two bytes for both -* address and operand sizes. -* -* Returns: -* -* An int containing ORed-in default parameters on success. -* -* -EINVAL on error. -*/ -int insn_get_code_seg_params (struct pt_regs *regs) -{ -struct desc_struct desc; -short sel; - - sel =get_segment_selector (regs,INAT_SEG_REG_CS ); -if (sel <0 ) -return sel; - -if (!get_desc (&desc, sel)) -return -EINVAL ; - -/* -* The most significant byte of the Type field of the segment descriptor -* determines whether a segment contains data or code. If this is a data -* segment, return error. -*/ -if (!(desc.type &BIT (3 ))) -return -EINVAL ; - -switch ((desc.l <<1 ) | desc.d) { -case 0 :/* -* Legacy mode. CS.L=0, CS.D=0. Address and operand size are -* both 16-bit. -*/ -return INSN_CODE_SEG_PARAMS (2 ,2 ); -case 1 :/* -* Legacy mode. CS.L=0, CS.D=1. Address and operand size are -* both 32-bit. -*/ -return INSN_CODE_SEG_PARAMS (4 ,4 ); -case 2 :/* -* IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; -* operand size is 32-bit. -*/ -return INSN_CODE_SEG_PARAMS (4 ,8 ); -case 3 :/* Invalid setting. CS.L=1, CS.D=1 */ -default : -return -EINVAL ; - } -} - -/** -* insn_get_modrm_rm_off() - Obtain register in r/m part of the ModRM byte -* @insn: Instruction containing the ModRM byte -* @regs: Register values as seen when entering kernel mode -* -* Returns: -* -* The register indicated by the r/m part of the ModRM byte. The -* register is obtained as an offset from the base of pt_regs. In specific -* cases, the returned value can be -EDOM to indicate that the particular value -* of ModRM does not refer to a register and shall be ignored. -*/ -int insn_get_modrm_rm_off (struct insn *insn,struct pt_regs *regs) -{ -return get_reg_offset (insn, regs,REG_TYPE_RM ); -} - -/** +/* * insn_get_modrm_reg_off() - Obtain register in reg part of the ModRM byte * @insn: Instruction containing the ModRM byte * @regs: Register values as seen when entering kernel mode
@@ -729,7 +587,7 @@ int insn_get_modrm_reg_off(struct insn *insn, struct pt_regs *regs)return get_reg_offset (insn, regs,REG_TYPE_REG ); } -/** +/* * insn_get_modrm_reg_ptr() - Obtain register pointer based on ModRM byte * @insn: Instruction containing the ModRM byte * @regs: Register values as seen when entering kernel mode
@@ -749,7 +607,7 @@ unsigned long *insn_get_modrm_reg_ptr(struct insn *insn, struct pt_regs *regs)return (void *)regs + offset; } -/** +/* * get_seg_base_limit() - obtain base address and limit of a segment * @insn: Instruction. Must be valid. * @regs: Register values as seen when entering kernel mode
@@ -797,7 +655,7 @@ static int get_seg_base_limit(struct insn *insn, struct pt_regs *regs,return 0 ; } -/** +/* * get_eff_addr_reg() - Obtain effective address from register operand * @insn: Instruction. Must be valid. * @regs: Register values as seen when entering kernel mode
@@ -847,7 +705,7 @@ static int get_eff_addr_reg(struct insn *insn, struct pt_regs *regs,return 0 ; } -/** +/* * get_eff_addr_modrm() - Obtain referenced effective address via ModRM * @insn: Instruction. Must be valid. * @regs: Register values as seen when entering kernel mode
@@ -911,7 +769,7 @@ static int get_eff_addr_modrm(struct insn *insn, struct pt_regs *regs,return 0 ; } -/** +/* * get_eff_addr_modrm_16() - Obtain referenced effective address via ModRM * @insn: Instruction. Must be valid. * @regs: Register values as seen when entering kernel mode
@@ -979,7 +837,7 @@ static int get_eff_addr_modrm_16(struct insn *insn, struct pt_regs *regs,return 0 ; } -/** +/* * get_eff_addr_sib() - Obtain referenced effective address via SIB * @insn: Instruction. Must be valid. * @regs: Register values as seen when entering kernel mode
@@ -1068,7 +926,7 @@ static int get_eff_addr_sib(struct insn *insn, struct pt_regs *regs,return 0 ; } -/** +/* * get_addr_ref_16() - Obtain the 16-bit address referred by instruction * @insn: Instruction containing ModRM byte and displacement * @regs: Register values as seen when entering kernel mode
@@ -1130,7 +988,7 @@ static void __user *get_addr_ref_16(struct insn *insn, struct pt_regs *regs)return (void __user *)linear_addr; } -/** +/* * get_addr_ref_32() - Obtain a 32-bit linear address * @insn: Instruction with ModRM, SIB bytes and displacement * @regs: Register values as seen when entering kernel mode
@@ -1195,7 +1053,7 @@ static void __user *get_addr_ref_32(struct insn *insn, struct pt_regs *regs)return (void __user *)linear_addr; } -/** +/* * get_addr_ref_64() - Obtain a 64-bit linear address * @insn: Instruction struct with ModRM and SIB bytes and displacement * @regs: Structure with register values as seen when entering kernel mode
@@ -1247,7 +1105,7 @@ static void __user *get_addr_ref_64(struct insn *insn, struct pt_regs *regs)return (void __user *)linear_addr; } -/** +/* * insn_get_addr_ref() - Obtain the linear address referred by instruction * @insn: Instruction structure containing ModRM byte and displacement * @regs: Structure with register values as seen when entering kernel mode
@@ -1282,118 +1140,7 @@ void __user *insn_get_addr_ref(struct insn *insn, struct pt_regs *regs) } } -int insn_get_effective_ip (struct pt_regs *regs,unsigned long *ip) -{ -unsigned long seg_base =0 ; - - *ip = seg_base + regs->ip; - -return 0 ; -} - -/** -* insn_fetch_from_user() - Copy instruction bytes from user-space memory -* @regs: Structure with register values as seen when entering kernel mode -* @buf: Array to store the fetched instruction -* -* Gets the linear address of the instruction and copies the instruction bytes -* to the buf. -* -* Returns: -* -* - number of instruction bytes copied. -* - 0 if nothing was copied. -* - -EINVAL if the linear address of the instruction could not be calculated -*/ -int insn_fetch_from_user (struct pt_regs *regs,unsigned char buf[MAX_INSN_SIZE ]) -{ -unsigned long ip; -int not_copied; - -if (insn_get_effective_ip (regs, &ip)) -return -EINVAL ; - - not_copied =copy_from_user (buf, (void __user *)ip,MAX_INSN_SIZE ); - -return MAX_INSN_SIZE - not_copied; -} - -/** -* insn_fetch_from_user_inatomic() - Copy instruction bytes from user-space memory -* while in atomic code -* @regs: Structure with register values as seen when entering kernel mode -* @buf: Array to store the fetched instruction -* -* Gets the linear address of the instruction and copies the instruction bytes -* to the buf. This function must be used in atomic context. -* -* Returns: -* -* - number of instruction bytes copied. -* - 0 if nothing was copied. -* - -EINVAL if the linear address of the instruction could not be calculated. -*/ -int insn_fetch_from_user_inatomic (struct pt_regs *regs,unsigned char buf[MAX_INSN_SIZE ]) -{ -unsigned long ip; -int not_copied; - -if (insn_get_effective_ip (regs, &ip)) -return -EINVAL ; - - not_copied =__copy_from_user_inatomic (buf, (void __user *)ip,MAX_INSN_SIZE ); - -return MAX_INSN_SIZE - not_copied; -} - -/** -* insn_decode_from_regs() - Decode an instruction -* @insn: Structure to store decoded instruction -* @regs: Structure with register values as seen when entering kernel mode -* @buf: Buffer containing the instruction bytes -* @buf_size: Number of instruction bytes available in buf -* -* Decodes the instruction provided in buf and stores the decoding results in -* insn. Also determines the correct address and operand sizes. -* -* Returns: -* -* True if instruction was decoded, False otherwise. -*/ -bool insn_decode_from_regs (struct insn *insn,struct pt_regs *regs, -unsigned char buf[MAX_INSN_SIZE ],int buf_size) -{ -int seg_defs; - -insn_init (insn, buf, buf_size, true); - -/* -* Override the default operand and address sizes with what is specified -* in the code segment descriptor. The instruction decoder only sets -* the address size it to either 4 or 8 address bytes and does nothing -* for the operand bytes. This OK for most of the cases, but we could -* have special cases where, for instance, a 16-bit code segment -* descriptor is used. -* If there is an address override prefix, the instruction decoder -* correctly updates these values, even for 16-bit defaults. -*/ - seg_defs =insn_get_code_seg_params (regs); -if (seg_defs == -EINVAL ) -return false; - - insn->addr_bytes =INSN_CODE_SEG_ADDR_SZ (seg_defs); - insn->opnd_bytes =INSN_CODE_SEG_OPND_SZ (seg_defs); - -if (insn_get_length (insn)) -return false; - -if (buf_size < insn->length) -return false; - -return true; -} - -/** +/* * insn_decode_mmio() - Decode a MMIO instruction * @insn: Structure to store decoded instruction * @bytes: Returns size of memory operand
Signature · 1 line
2.34.1
RFC PATCH v2 16/35 KVM: selftests: Fix missing definitions in x86 instruction decoder
In reply to Neeraj UpadhyayThe insn-eval x86 selftest lib uses kernel-internal macros savesegment and rdmsrq, which are typically defined in kernel headers like <asm/segment.h> and <asm/msr.h>. These headers are not available in the userspace build environment for selftests, leading to build failures.
Fix this by providing local definitions for the missing symbols and replacing with the functional equivalent definitions available to the selftest.
--- tools/testing/selftests/kvm/lib/x86/insn-eval.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)
tools/testing/selftests/kvm/lib/x86/insn-eval.c +11 -3
@@ -18,6 +18,9 @@#undef pr_fmt#define pr_fmt (fmt) "insn: " fmt +#define savesegment (seg, value) \ + asm("mov %%" #seg ",%0":"=r" (value) : : "memory") +enum reg_type {REG_TYPE_RM =0 ,REG_TYPE_REG ,
@@ -25,6 +28,11 @@ enum reg_type { REG_TYPE_BASE, }; +static __always_inline int user_mode(struct pt_regs *regs) +{ +return !!(regs->cs &3 ); +} +/* * is_string_insn() - Determine if instruction is a string instruction * @insn: Instruction containing the opcode to inspect
@@ -528,16 +536,16 @@ unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx)*/ if (seg_reg_idx ==INAT_SEG_REG_FS ) { -rdmsrq (MSR_FS_BASE , base); + base =rdmsr (MSR_FS_BASE ); }else if (seg_reg_idx ==INAT_SEG_REG_GS ) {/* * swapgs was called at the kernel entry point. Thus, * MSR_KERNEL_GS_BASE will have the user-space GS base. */ if (user_mode (regs)) -rdmsrq (MSR_KERNEL_GS_BASE , base); + base =rdmsr (MSR_KERNEL_GS_BASE );else -rdmsrq (MSR_GS_BASE , base); + base =rdmsr (MSR_GS_BASE ); }else { base =0 ; }
Signature · 1 line
2.34.1
RFC PATCH v2 17/35 KVM: selftests: Change pt_regs to ex_regs for selftest use
In reply to Neeraj Upadhyay--- .../selftests/kvm/include/x86/insn-eval.h | 24 +-- .../selftests/kvm/include/x86/processor.h | 2 + .../testing/selftests/kvm/lib/x86/insn-eval.c | 159 +++++++++--------- 3 files changed, 96 insertions(+), 89 deletions(-)
tools/testing/selftests/kvm/include/x86/insn-eval.h +13 -11
@@ -8,25 +8,27 @@#include <stdbool.h> +#include "processor.h" +#define INSN_CODE_SEG_ADDR_SZ (params) ((params >> 4) & 0xf)#define INSN_CODE_SEG_OPND_SZ (params) (params & 0xf)#define INSN_CODE_SEG_PARAMS (oper_sz, addr_sz) (oper_sz | (addr_sz << 4)) -int pt_regs_offset (struct pt_regs *regs,int regno); +int ex_regs_offset (struct ex_regs *regs,int regno);bool insn_has_rep_prefix (struct insn *insn); -void __user *insn_get_addr_ref (struct insn *insn,struct pt_regs *regs); -int insn_get_modrm_rm_off (struct insn *insn,struct pt_regs *regs); -int insn_get_modrm_reg_off (struct insn *insn,struct pt_regs *regs); -unsigned long *insn_get_modrm_reg_ptr (struct insn *insn,struct pt_regs *regs); -unsigned long insn_get_seg_base (struct pt_regs *regs,int seg_reg_idx); -int insn_get_code_seg_params (struct pt_regs *regs); -int insn_get_effective_ip (struct pt_regs *regs,unsigned long *ip); -int insn_fetch_from_user (struct pt_regs *regs, +void __user *insn_get_addr_ref (struct insn *insn,struct ex_regs *regs); +int insn_get_modrm_rm_off (struct insn *insn,struct ex_regs *regs); +int insn_get_modrm_reg_off (struct insn *insn,struct ex_regs *regs); +unsigned long *insn_get_modrm_reg_ptr (struct insn *insn,struct ex_regs *regs); +unsigned long insn_get_seg_base (struct ex_regs *regs,int seg_reg_idx); +int insn_get_code_seg_params (struct ex_regs *regs); +int insn_get_effective_ip (struct ex_regs *regs,unsigned long *ip); +int insn_fetch_from_user (struct ex_regs *regs,unsigned char buf[MAX_INSN_SIZE ]); -int insn_fetch_from_user_inatomic (struct pt_regs *regs, +int insn_fetch_from_user_inatomic (struct ex_regs *regs,unsigned char buf[MAX_INSN_SIZE ]); -bool insn_decode_from_regs (struct insn *insn,struct pt_regs *regs, +bool insn_decode_from_regs (struct insn *insn,struct ex_regs *regs,unsigned char buf[MAX_INSN_SIZE ],int buf_size);enum insn_mmio_type {
tools/testing/selftests/kvm/include/x86/processor.h +2 -0
@@ -1161,6 +1161,8 @@ struct ex_regs {uint64_t rip;uint64_t cs;uint64_t rflags; +uint64_t rsp; +uint64_t ss; };struct idt_entry {
tools/testing/selftests/kvm/lib/x86/insn-eval.c +81 -78
420 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 18/35 KVM: selftests: Add compilation for instruction decoder library
In reply to Neeraj UpadhyayThe x86 instruction decoder library (insn-eval.c) has been adapted for selftests, but it is not yet compiled and linked into the KVM selftest binaries.
Update Makefile.kvm to build the instruction decoder and its dependencies, making them available to x86 KVM selftests.
With these changes, the instruction decoder library is fully integrated into the selftest build process and can be used for decoding instructions for emulating MMIO accesses for SEV-ES guests.
--- tools/testing/selftests/kvm/Makefile.kvm | 10 ++++++++++ 1 file changed, 10 insertions(+)
tools/testing/selftests/kvm/Makefile.kvm +10 -0
@@ -22,6 +22,7 @@ LIBKVM_STRING += lib/string_override.c LIBKVM_x86 += lib/x86/apic.c LIBKVM_x86 += lib/x86/handlers.S LIBKVM_x86 += lib/x86/hyperv.c +LIBKVM_x86 += lib/x86/insn-eval.c LIBKVM_x86 += lib/x86/memstress.c LIBKVM_x86 += lib/x86/pmu.c LIBKVM_x86 += lib/x86/processor.c
@@ -249,6 +250,15 @@ ifeq ($(ARCH),x86) ifeq ($(shell echo "void foo(void) { }" | $(CC) -march=x86-64-v2 -x c - -c -o /dev/null 2>/dev/null; echo "$$?"),0) CFLAGS += -march=x86-64-v2 endif +tools_lib_dir := $(top_srcdir)/tools/arch/x86/lib +inat_tables_script = $(top_srcdir)/tools/arch/x86/tools/gen-insn-attr-x86.awk +inat_tables_maps = $(top_srcdir)/tools/arch/x86/lib/x86-opcode-map.txt +$(shell awk -f $(inat_tables_script) $(inat_tables_maps) > $(tools_lib_dir)/inat-tables.c) +LIBKVM_x86 += $(tools_lib_dir)/insn.c +LIBKVM_x86 += $(tools_lib_dir)/inat.c +EXTRA_CLEAN += $(tools_lib_dir)/inat-tables.c +EXTRA_CLEAN += $(tools_lib_dir)/insn.o +EXTRA_CLEAN += $(tools_lib_dir)/inat.o endif ifeq ($(ARCH),arm64) tools_dir := $(top_srcdir)/tools
Signature · 1 line
2.34.1
RFC PATCH v2 19/35 KVM: selftests: Add MMIO #VC exception handling for SEV-ES guests
In reply to Neeraj UpadhyayIn SEV-ES encrypted guests, access to memory-mapped I/O (MMIO) regions like the local APIC triggers a #VC (Virtualization Exception) with a nested page fault (SVM_EXIT_NPF) exit type. To emulate the MMIO, the guest must provide a #VC handler to process these faults.
Implement MMIO handling for SEV-ES guests within the selftest framework. Extend the #VC handler to catch SVM_EXIT_NPF exceptions.
Additionally, add a new paravirtualized (PV) interface . This function allows guest code to request an MMIO operation directly via a VMGEXIT, bypassing the more expensive #VC exception path. This is useful for contexts outside the #VC handler where an MMIO access is known to be required.
This functionality is a prerequisite for enabling local xAPIC access in SEV-ES selftests, which is required for testing interrupts flow for SEV-ES guests.
--- tools/testing/selftests/kvm/include/x86/sev.h | 1 + tools/testing/selftests/kvm/lib/x86/sev.c | 259 +++++++++++++++++- 2 files changed, 256 insertions(+), 4 deletions(-)
tools/testing/selftests/kvm/include/x86/sev.h +1 -0
@@ -167,4 +167,5 @@ void sev_es_ucall_port_write(uint32_t port, uint64_t data);void sev_es_vc_handler (struct ex_regs *regs);void sev_es_pv_msr_rw (uint64_t msr,uint64_t *data,bool write); +void sev_es_pv_mmio_rw (uint32_t *reg_gpa,uint32_t *data,bool write);#endif /* SELFTEST_KVM_SEV_H */
tools/testing/selftests/kvm/lib/x86/sev.c +255 -4
290 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 20/35 KVM: selftests: Add instruction decoding for movabs instructions
In reply to Neeraj UpadhyayCompilers can generate movabs instructions for MMIO accesses, when accessing fixed addresses like the local APIC base. The movabs instruction is unique in that it moves data between the accumulator (RAX) and a memory location specified by an absolute 64-bit address encoded directly in the instruction stream.
The existing MMIO #VC handler in the SEV-ES selftest was unable to process these instructions because its decoding logic relied on ModR/M and SIB bytes, which movabs does not use. This would cause MMIO emulation to fail for such instructions.
Extend insn_decode_mmio() to recognize the movabs opcodes (0xa1, 0xa3). This allows the SEV-ES #VC handler to correctly emulate movabs instructions, improving the robustness of MMIO testing for features like the xAPIC.
--- .../selftests/kvm/include/x86/insn-eval.h | 2 ++ .../testing/selftests/kvm/lib/x86/insn-eval.c | 8 +++++ tools/testing/selftests/kvm/lib/x86/sev.c | 35 ++++++++++++++----- 3 files changed, 36 insertions(+), 9 deletions(-)
tools/testing/selftests/kvm/include/x86/insn-eval.h +2 -0
@@ -35,10 +35,12 @@ enum insn_mmio_type {INSN_MMIO_DECODE_FAILED ,INSN_MMIO_WRITE ,INSN_MMIO_WRITE_IMM , +INSN_MMIO_WRITE_MOV_ABS ,INSN_MMIO_READ ,INSN_MMIO_READ_ZERO_EXTEND ,INSN_MMIO_READ_SIGN_EXTEND ,INSN_MMIO_MOVS , + INSN_MMIO_READ_MOV_ABS, };enum insn_mmio_type insn_decode_mmio (struct insn *insn,int *bytes);
tools/testing/selftests/kvm/lib/x86/insn-eval.c +8 -0
@@ -1224,6 +1224,14 @@ enum insn_mmio_type insn_decode_mmio(struct insn *insn, int *bytes)break ; }break ; +case 0xa1 : + type =INSN_MMIO_READ_MOV_ABS ; + *bytes = insn->opnd_bytes; +break ; +case 0xa3 : + type =INSN_MMIO_WRITE_MOV_ABS ; + *bytes = insn->opnd_bytes; +break ; }return type;
tools/testing/selftests/kvm/lib/x86/sev.c +26 -9
@@ -469,9 +469,11 @@ void sev_es_pv_mmio_rw(uint32_t *reg_gpa, uint32_t *data, bool write) }static void do_mmio (struct ghcb_entry *entry,struct ex_regs *regs, -struct insn *insn,unsigned int bytes,bool read) +struct insn *insn,unsigned int bytes,bool read, +void *ref) { -void *ref =insn_get_addr_ref (insn, regs); +if (!ref) + ref =insn_get_addr_ref (insn, regs);register_ghcb_page (entry->gpa);__sev_es_hv_mmio_rw (entry, ref, bytes, !read);
@@ -600,11 +602,12 @@ static void sev_es_vc_mmio_handler(struct ex_regs *regs)char buffer[MAX_INSN_SIZE ];struct ghcb_entry *entry;enum insn_mmio_type mmio; -unsigned long *reg_data; +unsigned long *reg_data =NULL ;unsigned int bytes;struct ghcb *ghcb;uint8_t sign_byte;struct insn insn; +void *abs_ref;int ret;memcpy (buffer, (uint8_t *)regs->rip,MAX_INSN_SIZE );
@@ -616,7 +619,9 @@ static void sev_es_vc_mmio_handler(struct ex_regs *regs) mmio =insn_decode_mmio (&insn, (int *)&bytes);__GUEST_ASSERT (!(mmio ==INSN_MMIO_DECODE_FAILED )," MMIO decode failed\n" ); -if (mmio !=INSN_MMIO_WRITE_IMM && mmio !=INSN_MMIO_MOVS ) { +if (mmio ==INSN_MMIO_WRITE_MOV_ABS || mmio ==INSN_MMIO_READ_MOV_ABS ) { + reg_data = ®s->rax; + }else if (mmio !=INSN_MMIO_WRITE_IMM && mmio !=INSN_MMIO_MOVS ) { reg_data =insn_get_modrm_reg_ptr (&insn, regs);__GUEST_ASSERT (reg_data,"insn_get_modrm_reg_ptr failed\n" ); }
@@ -627,25 +632,37 @@ static void sev_es_vc_mmio_handler(struct ex_regs *regs)switch (mmio) {case INSN_MMIO_WRITE :memcpy (ghcb->shared_buffer, reg_data, bytes); -do_mmio (entry, regs, &insn, bytes, false); +do_mmio (entry, regs, &insn, bytes, false,NULL );break ;case INSN_MMIO_WRITE_IMM :memcpy (ghcb->shared_buffer, insn.immediate1.bytes, bytes); -do_mmio (entry, regs, &insn, bytes, false); +do_mmio (entry, regs, &insn, bytes, false,NULL ); +break ; +case INSN_MMIO_WRITE_MOV_ABS : + abs_ref = (void *)*(uint64_t *)((uint8_t *)regs->rip +1 ); +memcpy (ghcb->shared_buffer, reg_data, bytes); +do_mmio (entry, regs, &insn, bytes, false, abs_ref);break ;case INSN_MMIO_READ : -do_mmio (entry, regs, &insn, bytes, true); +do_mmio (entry, regs, &insn, bytes, true,NULL ); +if (bytes ==4 ) + *reg_data =0 ; +memcpy (reg_data, ghcb->shared_buffer, bytes); +break ; +case INSN_MMIO_READ_MOV_ABS : + abs_ref = (void *)*(uint64_t *)((char *)regs->rip +1 ); +do_mmio (entry, regs, &insn, bytes, true, abs_ref);if (bytes ==4 ) *reg_data =0 ;memcpy (reg_data, ghcb->shared_buffer, bytes);break ;case INSN_MMIO_READ_ZERO_EXTEND : -do_mmio (entry, regs, &insn, bytes, true); +do_mmio (entry, regs, &insn, bytes, true,NULL );memset (reg_data,0 , insn.opnd_bytes);memcpy (reg_data, ghcb->shared_buffer, bytes);break ;case INSN_MMIO_READ_SIGN_EXTEND : -do_mmio (entry, regs, &insn, bytes, true); +do_mmio (entry, regs, &insn, bytes, true,NULL );if (bytes ==1 ) {uint8_t *val = (uint8_t *)ghcb->shared_buffer;
Signature · 1 line
2.34.1
RFC PATCH v2 21/35 KVM: selftests: Add SEV guest support in xapic_state_test
In reply to Neeraj UpadhyayThe xapic_state_test validates the behavior of the local APIC across different states and modes (xAPIC vs. x2APIC). Previously, this test only ran on standard, unencrypted VMs.
With the recent addition of a #VC handler to emulate MMIO accesses for SEV-ES guests, the necessary infrastructure is in place to test APIC functionality within encrypted environments.
Extend xapic_state_test to support SEV, SEV-ES, and SNP guests. This provides crucial regression testing for APIC functionality in these confidential computing environments.
The test functions are refactored to handle the new VM setup flow, enabling existing APIC tests to run transparently on encrypted guests.
--- .../selftests/kvm/x86/xapic_state_test.c | 117 ++++++++++++++++-- 1 file changed, 109 insertions(+), 8 deletions(-)
tools/testing/selftests/kvm/x86/xapic_state_test.c +109 -8
@@ -9,6 +9,7 @@#include "kvm_util.h" #include "processor.h" #include "test_util.h" +#include "sev.h" struct xapic_vcpu {struct kvm_vcpu *vcpu;
@@ -160,6 +161,27 @@ static void __test_apic_id(struct kvm_vcpu *vcpu, uint64_t apic_base) expected, apic_id); } +static inline bool is_sev_vm_type (int type) +{ +return type ==KVM_X86_SEV_VM || + type ==KVM_X86_SEV_ES_VM || + type ==KVM_X86_SNP_VM ; +} + +static inline uint64_t get_sev_policy (int vm_type) +{ +switch (vm_type) { +case KVM_X86_SEV_VM : +return SEV_POLICY_NO_DBG ; +case KVM_X86_SEV_ES_VM : +return SEV_POLICY_ES ; +case KVM_X86_SNP_VM : +return snp_default_policy (); +default : +return 0 ; + } +} +/* * Verify that KVM switches the APIC_ID between xAPIC and x2APIC when userspace * stuffs MSR_IA32_APICBASE. Setting the APIC_ID when x2APIC is enabled and
@@ -168,16 +190,22 @@ static void __test_apic_id(struct kvm_vcpu *vcpu, uint64_t apic_base)* attempted to transition from x2APIC to xAPIC without disabling the APIC is * architecturally disallowed. */ -static void test_apic_id (void ) +static void test_apic_id (int vm_type) {const uint32_t NR_VCPUS =3 ;struct kvm_vcpu *vcpus[NR_VCPUS ];uint64_t apic_base;struct kvm_vm *vm;int i; +struct vm_shape shape = { + .mode =VM_MODE_DEFAULT , + .type = vm_type, + }; - vm =vm_create_with_vcpus (NR_VCPUS ,NULL , vcpus); + vm =__vm_create_with_vcpus (shape,NR_VCPUS ,0 ,NULL , vcpus);vm_enable_cap (vm,KVM_CAP_X2APIC_API ,KVM_X2APIC_API_USE_32BIT_IDS ); +if (is_sev_vm (vm)) +vm_sev_launch (vm,get_sev_policy (vm_type),NULL );for (i =0 ; i <NR_VCPUS ; i++) { apic_base =vcpu_get_msr (vcpus[i],MSR_IA32_APICBASE );
@@ -195,15 +223,21 @@ static void test_apic_id(void)kvm_vm_free (vm); } -static void test_x2apic_id (void ) +static void test_x2apic_id (int vm_type) {struct kvm_lapic_state lapic = {};struct kvm_vcpu *vcpu;struct kvm_vm *vm;int i; +bool is_sev =is_sev_vm_type (vm_type); - vm =vm_create_with_one_vcpu (&vcpu,NULL ); +if (is_sev) + vm =vm_sev_create_with_one_vcpu (vm_type,NULL , &vcpu); +else + vm =vm_create_with_one_vcpu (&vcpu,NULL );vcpu_set_msr (vcpu,MSR_IA32_APICBASE ,MSR_IA32_APICBASE_ENABLE |X2APIC_ENABLE ); +if (is_sev) +vm_sev_launch (vm,get_sev_policy (vm_type),NULL );/* * Try stuffing a modified x2APIC ID, KVM should ignore the value and
@@ -222,6 +256,46 @@ static void test_x2apic_id(void)kvm_vm_free (vm); } +void get_cmdline_args (int argc,char *argv[],int *vm_type) +{ +for (;;) { +int opt =getopt (argc, argv,"t:" ); + +if (opt ==-1 ) +break ; +switch (opt) { +case 't' : + *vm_type =parse_size (optarg); +switch (*vm_type) { +case KVM_X86_DEFAULT_VM : +break ; +case KVM_X86_SEV_VM : +TEST_REQUIRE (kvm_cpu_has (X86_FEATURE_SEV )); +break ; +case KVM_X86_SEV_ES_VM : +TEST_REQUIRE (kvm_cpu_has (X86_FEATURE_SEV_ES )); +break ; +case KVM_X86_SNP_VM : +TEST_REQUIRE (kvm_cpu_has (X86_FEATURE_SEV_SNP )); +break ; +default : +TEST_ASSERT (false,"Unsupported VM type :%d" , + *vm_type); + } +break ; +default : +TEST_ASSERT (false, +"Usage: -t <vm type>. Default is %d.\n" +"Supported values:\n" +"0 - default\n" +"2 - SEV\n" +"3 - SEV-ES\n" +"4 - SNP" , +KVM_X86_DEFAULT_VM ); + } + } +} +int main (int argc,char *argv[]) {struct xapic_vcpu x = {
@@ -229,8 +303,24 @@ int main(int argc, char *argv[]) .is_x2apic = true, };struct kvm_vm *vm; +int vm_type =KVM_X86_DEFAULT_VM ; +bool is_sev; + +get_cmdline_args (argc, argv, &vm_type); + is_sev =is_sev_vm_type (vm_type); + +if (is_sev) + vm =vm_sev_create_with_one_vcpu (vm_type, x2apic_guest_code, + &x.vcpu); +else + vm =vm_create_with_one_vcpu (&x.vcpu, x2apic_guest_code); + +if (is_sev_es_vm (vm)) +vm_install_exception_handler (vm,29 , sev_es_vc_handler); + +if (is_sev) +vm_sev_launch (vm,get_sev_policy (vm_type),NULL ); - vm =vm_create_with_one_vcpu (&x.vcpu, x2apic_guest_code);test_icr (&x);kvm_vm_free (vm);
@@ -239,7 +329,15 @@ int main(int argc, char *argv[])* the guest in order to test AVIC. KVM disallows changing CPUID after * KVM_RUN and AVIC is disabled if _any_ vCPU is allowed to use x2APIC. */ - vm =vm_create_with_one_vcpu (&x.vcpu, xapic_guest_code); +if (is_sev) + vm =vm_sev_create_with_one_vcpu (vm_type, xapic_guest_code, + &x.vcpu); +else + vm =vm_create_with_one_vcpu (&x.vcpu, xapic_guest_code); + +if (is_sev_es_vm (vm)) +vm_install_exception_handler (vm,29 , sev_es_vc_handler); + x.is_x2apic = false;/*
@@ -254,9 +352,12 @@ int main(int argc, char *argv[])vcpu_clear_cpuid_feature (x.vcpu,X86_FEATURE_X2APIC );virt_pg_map (vm,APIC_DEFAULT_GPA ,APIC_DEFAULT_GPA ); +if (is_sev) +vm_sev_launch (vm,get_sev_policy (vm_type),NULL ); +test_icr (&x);kvm_vm_free (vm); -test_apic_id (); -test_x2apic_id (); +test_apic_id (vm_type); +test_x2apic_id (vm_type); }
Signature · 1 line
2.34.1
RFC PATCH v2 22/35 KVM: selftests: Add x2apic mode testing in xapic_ipi_test
In reply to Neeraj UpadhyayRefactor the test to support both xAPIC and x2APIC modes.
The xapic_ipi_test selftest was hardcoded to use xAPIC mode, relying exclusively on MMIO to access the local APIC registers. This limits its ability to test IPI functionality in environments where x2APIC mode is required or preferred, such as for guests with Secure AVIC enabled.
This change makes the IPI test more versatile and prepares it for future extensions to test features that depend on x2APIC.
--- .../selftests/kvm/x86/xapic_ipi_test.c | 65 +++++++++++++++---- 1 file changed, 51 insertions(+), 14 deletions(-)
tools/testing/selftests/kvm/x86/xapic_ipi_test.c +51 -14
@@ -50,6 +50,29 @@*/ static volatile uint64_t ipis_rcvd; +static bool x2apic; + +static void apic_enable (void ) +{ +if (x2apic) +x2apic_enable (); +else +xapic_enable (); +} + +static uint32_t apic_read_reg (unsigned int reg) +{ +return x2apic ?x2apic_read_reg (reg) :xapic_read_reg (reg); +} + +static void apic_write_reg (unsigned int reg,uint64_t val) +{ +if (x2apic) +x2apic_write_reg (reg, val); +else +xapic_write_reg (reg, (uint32_t )val); +} +/* Data struct shared between host main thread and vCPUs */ struct test_data_page {uint32_t halter_apic_id;
@@ -89,10 +112,10 @@ void verify_apic_base_addr(void)static void halter_guest_code (struct test_data_page *data) {verify_apic_base_addr (); -xapic_enable (); +apic_enable (); - data->halter_apic_id =GET_APIC_ID_FIELD (xapic_read_reg (APIC_ID )); - data->halter_lvr =xapic_read_reg (APIC_LVR ); + data->halter_apic_id =GET_APIC_ID_FIELD (apic_read_reg (APIC_ID )); + data->halter_lvr =apic_read_reg (APIC_LVR );/* * Loop forever HLTing and recording halts & wakes. Disable interrupts
@@ -103,8 +126,8 @@ static void halter_guest_code(struct test_data_page *data)* TPR and PPR for diagnostic purposes in case the test fails. */ for (;;) { - data->halter_tpr =xapic_read_reg (APIC_TASKPRI ); - data->halter_ppr =xapic_read_reg (APIC_PROCPRI ); + data->halter_tpr =apic_read_reg (APIC_TASKPRI ); + data->halter_ppr =apic_read_reg (APIC_PROCPRI ); data->hlt_count++;safe_halt ();cli ();
@@ -120,7 +143,7 @@ static void halter_guest_code(struct test_data_page *data)static void guest_ipi_handler (struct ex_regs *regs) { ipis_rcvd++; -xapic_write_reg (APIC_EOI ,77 ); +apic_write_reg (APIC_EOI ,77 ); }static void sender_guest_code (struct test_data_page *data)
@@ -133,7 +156,7 @@ static void sender_guest_code(struct test_data_page *data)uint64_t tsc_start;verify_apic_base_addr (); -xapic_enable (); +apic_enable ();/* * Init interrupt command register for sending IPIs
@@ -160,8 +183,12 @@ static void sender_guest_code(struct test_data_page *data)* First IPI can be sent unconditionally because halter vCPU * starts earlier. */ -xapic_write_reg (APIC_ICR2 , icr2_val); -xapic_write_reg (APIC_ICR , icr_val); +if (!x2apic) { +apic_write_reg (APIC_ICR2 , icr2_val); +apic_write_reg (APIC_ICR , icr_val); + }else { +apic_write_reg (APIC_ICR , (uint64_t )icr2_val <<32 | icr_val); + } data->ipis_sent++;/*
@@ -357,10 +384,10 @@ void do_migrations(struct test_data_page *data, int run_secs, int delay_usecs, }void get_cmdline_args (int argc,char *argv[],int *run_secs, -bool *migrate,int *delay_usecs) +bool *migrate,int *delay_usecs,bool *x2apic) {for (;;) { -int opt =getopt (argc, argv,"s:d:m" ); +int opt =getopt (argc, argv,"s:d:v:me:" );if (opt ==-1 )break ;
@@ -374,13 +401,18 @@ void get_cmdline_args(int argc, char *argv[], int *run_secs,case 'd' : *delay_usecs =parse_size (optarg);break ; +case 'e' : + *x2apic =parse_size (optarg) ==1 ; +break ;default :TEST_ASSERT (false,"Usage: -s <runtime seconds>. Default is %d seconds.\n" "-m adds calls to migrate_pages while vCPUs are running." " Default is no migrations.\n" "-d <delay microseconds> - delay between migrate_pages() calls." -" Default is %d microseconds." , +" Default is %d microseconds.\n" +"-e <apic mode> - APIC mode 0 - xapic , 1 - x2apic" +" Default is xAPIC.\n" ,DEFAULT_RUN_SECS ,DEFAULT_DELAY_USECS ); } }
@@ -401,7 +433,10 @@ int main(int argc, char *argv[])struct kvm_vm *vm;uint64_t *pipis_rcvd; -get_cmdline_args (argc, argv, &run_secs, &migrate, &delay_usecs); +get_cmdline_args (argc, argv, &run_secs, &migrate, &delay_usecs, &x2apic); +if (x2apic) + migrate =0 ; +if (run_secs <=0 ) run_secs =DEFAULT_RUN_SECS ;if (delay_usecs <=0 )
@@ -411,7 +446,9 @@ int main(int argc, char *argv[])vm_install_exception_handler (vm,IPI_VECTOR , guest_ipi_handler); -virt_pg_map (vm,APIC_DEFAULT_GPA ,APIC_DEFAULT_GPA ); +sync_global_to_guest (vm, x2apic); +if (!x2apic) +virt_pg_map (vm,APIC_DEFAULT_GPA ,APIC_DEFAULT_GPA ); params[1 ].vcpu =vm_vcpu_add (vm,1 , sender_guest_code);
Signature · 1 line
2.34.1
RFC PATCH v2 23/35 KVM: selftests: Add SEV VM support in xapic_ipi_test
In reply to Neeraj UpadhyayExtend the xapic_ipi_test to support SEV, SEV-ES, and SNP guests. This is important for validating IPI functionality within confidential computing environments. The test now works in both xAPIC and x2APIC modes for these encrypted guest types.
The test now uses SEV-specific VM creation and launch helpers when an encrypted guest is selected. For SEV-ES guests, install the generic for xAPIC mode to function.
In an encrypted guest, memory is private by default and inaccessible to the host. To allow the host to monitor guest activity, convert the page used for statistics (test_data_page) to a shared (unencrypted) memory region. Add a convenience wrapper, vm_vaddr_alloc_page_shared(), to simplify the allocation of a single shared page.
With these changes, the IPI selftest can now provide comprehensive coverage across both standard and confidential VM types.
--- .../testing/selftests/kvm/include/kvm_util.h | 1 + tools/testing/selftests/kvm/lib/kvm_util.c | 19 ++++ .../selftests/kvm/x86/xapic_ipi_test.c | 94 ++++++++++++++++--- 3 files changed, 100 insertions(+), 14 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +1 -0
@@ -700,6 +700,7 @@ vm_vaddr_t vm_vaddr_alloc_pages_shared(struct kvm_vm *vm, int nr_pages);vm_vaddr_t __vm_vaddr_alloc_page (struct kvm_vm *vm,enum kvm_mem_region_type type);vm_vaddr_t vm_vaddr_alloc_page (struct kvm_vm *vm); +vm_vaddr_t vm_vaddr_alloc_page_shared (struct kvm_vm *vm);void virt_map (struct kvm_vm *vm,uint64_t vaddr,uint64_t paddr,unsigned int npages);
tools/testing/selftests/kvm/lib/kvm_util.c +19 -0
@@ -1592,6 +1592,25 @@ vm_vaddr_t vm_vaddr_alloc_page(struct kvm_vm *vm)return vm_vaddr_alloc_pages (vm,1 ); } +/* +* VM Virtual Address Allocate shared Page +* +* Input Args: +* vm - Virtual Machine +* +* Output Args: None +* +* Return: +* Starting guest virtual address +* +* Allocates at least one system page (in shared state) worth of bytes within the +* virtual address space of the vm. +*/ +vm_vaddr_t vm_vaddr_alloc_page_shared (struct kvm_vm *vm) +{ +return vm_vaddr_alloc_pages_shared (vm,1 ); +} +/* * Map a range of VM virtual address to the VM's physical address *
tools/testing/selftests/kvm/x86/xapic_ipi_test.c +80 -14
195 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 24/35 KVM: selftests: Add Secure AVIC library
In reply to Neeraj UpadhyayAdd a new library to the KVM selftest framework to manage and enable Secure AVIC, providing the foundation for testing this feature.
Secure AVIC (SAVIC) is an AMD SEV-SNP feature that provides each vCPU with a guest-owned APIC backing page in memory. This allow SEV-SNP guests to prevent the hypervisor from generating unexpected interrupts to a vCPU or otherwise violate architectural assumptions around APIC behavior.
The core of the new library (lib/x86/savic.c) revolves around the management of these APIC backing pages:
- Allocate pool of APIC backing pages during the SNP VM launch sequence if the VMSA features report SAVIC support.
- Update kvm_arch_vm_additional_pages_required() helper to ensure sufficient memory is pre-allocated for these pages during VM creation.
The library exposes a set of helpers for guest code:
- savic_enable(): The primary function for a vCPU to switch into Secure AVIC mode.
- savic_read/write_reg(): Allow the guest to interact with its local APIC state via the backing page once SAVIC is active.
- savic_hv_read/write_reg(): Helpers that wrap the PV MSR interface for communicating with KVM's view of the APIC state.
This infrastructure is a prerequisite for writing selftests that verify the correctness of Secure AVIC.
--- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../testing/selftests/kvm/include/x86/apic.h | 6 + .../testing/selftests/kvm/include/x86/savic.h | 19 ++ tools/testing/selftests/kvm/include/x86/svm.h | 3 + .../testing/selftests/kvm/lib/x86/processor.c | 7 +- tools/testing/selftests/kvm/lib/x86/savic.c | 205 ++++++++++++++++++ tools/testing/selftests/kvm/lib/x86/sev.c | 15 ++ 7 files changed, 254 insertions(+), 2 deletions(-) create mode 100644 tools/testing/selftests/kvm/include/x86/savic.h create mode 100644 tools/testing/selftests/kvm/lib/x86/savic.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
@@ -26,6 +26,7 @@ LIBKVM_x86 += lib/x86/insn-eval.c LIBKVM_x86 += lib/x86/memstress.c LIBKVM_x86 += lib/x86/pmu.c LIBKVM_x86 += lib/x86/processor.c +LIBKVM_x86 += lib/x86/savic.c LIBKVM_x86 += lib/x86/sev.c LIBKVM_x86 += lib/x86/svm.c LIBKVM_x86 += lib/x86/ucall.c
tools/testing/selftests/kvm/include/x86/apic.h +6 -0
@@ -29,6 +29,7 @@#define APIC_TASKPRI 0x80#define APIC_PROCPRI 0xA0#define APIC_EOI 0xB0 +#define APIC_LDR 0xD0#define APIC_SPIV 0xF0#define APIC_SPIV_FOCUS_DISABLED (1 << 9)#define APIC_SPIV_APIC_ENABLED (1 << 8)
@@ -60,10 +61,15 @@#define APIC_ICR2 0x310#define SET_APIC_DEST_FIELD (x) ((x) << 24)#define APIC_LVTT 0x320 +#define APIC_LVTTHMR 0x330 +#define APIC_LVTPC 0x340 +#define APIC_LVT0 0x350#define APIC_LVT_TIMER_ONESHOT (0 << 17)#define APIC_LVT_TIMER_PERIODIC (1 << 17)#define APIC_LVT_TIMER_TSCDEADLINE (2 << 17)#define APIC_LVT_MASKED (1 << 16) +#define APIC_LVT1 0x360 +#define APIC_LVTERR 0x370#define APIC_TMICT 0x380#define APIC_TMCCT 0x390#define APIC_TDCR 0x3E0
tools/testing/selftests/kvm/include/x86/savic.h new file +19 -0
@@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Helpers used for Secure AVIC guests +* +*/ +#ifndef SELFTEST_KVM_SAVIC_H +#define SELFTEST_KVM_SAVIC_H + +struct guest_apic_page ; + +void guest_apic_pages_init (struct kvm_vm *vm); +void set_savic_control_msr (struct guest_apic_page *apic_page,bool enable,bool enable_nmi); +void savic_write_reg (struct guest_apic_page *apic_page,uint32_t reg,uint64_t val); +uint64_t savic_read_reg (struct guest_apic_page *apic_page,uint32_t reg); +void savic_hv_write_reg (uint32_t reg,uint64_t val); +uint64_t savic_hv_read_reg (uint32_t reg); +void savic_enable (void ); +int savic_nr_pages_required (uint64_t page_size); +#endif
tools/testing/selftests/kvm/include/x86/svm.h +3 -0
@@ -179,6 +179,9 @@ struct __attribute__ ((__packed__)) vmcb_control_area {#define SVM_NESTED_CTL_NP_ENABLE BIT(0)#define SVM_NESTED_CTL_SEV_ENABLE BIT(1) +#define SVM_FEAT_SECURE_AVIC 16 +#define SVM_FEAT_ALLOWED_SEV_FEATURES_VALID 63 +struct __attribute__ ((__packed__ ))vmcb_seg {u16 selector;u16 attrib;
tools/testing/selftests/kvm/lib/x86/processor.c +5 -2
@@ -659,10 +659,13 @@ void kvm_arch_vm_post_create(struct kvm_vm *vm)int kvm_arch_vm_additional_pages_required (struct vm_shape shape,uint64_t page_size) { -if (shape.type ==KVM_X86_SEV_ES_VM || - shape.type ==KVM_X86_SNP_VM ) +if (shape.type ==KVM_X86_SEV_ES_VM )return ghcb_nr_pages_required (page_size); +if (shape.type ==KVM_X86_SNP_VM ) +return ghcb_nr_pages_required (page_size) + +savic_nr_pages_required (page_size); +return 0 ; }
tools/testing/selftests/kvm/lib/x86/savic.c new file +205 -0
205 lines not on this page · raw message
tools/testing/selftests/kvm/lib/x86/sev.c +15 -0
@@ -276,6 +276,18 @@ struct kvm_vm *vm_sev_create_with_one_vcpu(uint32_t type, void *guest_code,return vm; } +static bool is_savic_enabled (void ) +{ +u64 supported_vmsa_features; +int kvm_fd =open_kvm_dev_path_or_exit (); + +kvm_device_attr_get (kvm_fd,KVM_X86_GRP_SEV , +KVM_X86_SEV_VMSA_FEATURES , + &supported_vmsa_features); + +return supported_vmsa_features &BIT_ULL (SVM_FEAT_SECURE_AVIC ); +} +void vm_sev_launch (struct kvm_vm *vm,uint64_t policy,uint8_t *measurement) {if (is_sev_es_vm (vm))
@@ -284,6 +296,9 @@ void vm_sev_launch(struct kvm_vm *vm, uint64_t policy, uint8_t *measurement)if (is_sev_snp_vm (vm)) {vm_enable_cap (vm,KVM_CAP_EXIT_HYPERCALL ,BIT (KVM_HC_MAP_GPA_RANGE )); +if (is_savic_enabled ()) +guest_apic_pages_init (vm); +snp_vm_launch_start (vm, policy);snp_vm_launch_update (vm);
Signature · 1 line
2.34.1
RFC PATCH v2 25/35 KVM: selftests: Add #VC handler for unaccelerated Secure AVIC MSRs
In reply to Neeraj UpadhyayWhen Secure AVIC (SAVIC) is enabled for an SEV-SNP guest, most APIC register accesses are accelerated via a guest-visible backing page. However, not all APIC registers are handled this way. Accesses to certain "unaccelerated" registers via RDMSR or WRMSR are designed to trigger a #VC (Virtualization Exception) with the new exit code SVM_EXIT_AVIC_UNACCELERATED_ACCESS.
Without a handler for this exit code, any guest attempt to access these MSRs would result in an unhandled fault, crashing the guest. Implement the necessary #VC handler to emulate these accesses.
The new handler (handle_savic_unaccel_access) emulates the MSR operation. For MSR reads/writes, it applies different strategies based on the register:
- Read/Write APIC timer, APIC Spurious Interrupt Vector and LVT registers' from the hypervisor using the existing paravirtual MSR interface as LVT and APIC timers are emulated by the hypervisor.
- Propagate EOI write to the hypervisor. This is required for acknowledging emulated IOAPIC interrupts.
- Keep APIC_ID in-sync between the guest and the hypervisor.
- For rest of the valid APIC register writes, write the value only in the APIC backing page of the guest vCPU.
This emulation provides the necessary glue to allow guest code to run seamlessly when SAVIC is active, enabling comprehensive testing of APIC functionality in this mode.
--- .../testing/selftests/kvm/include/x86/apic.h | 1 + .../testing/selftests/kvm/include/x86/savic.h | 1 + tools/testing/selftests/kvm/lib/x86/savic.c | 145 ++++++++++++++++++ 3 files changed, 147 insertions(+)
tools/testing/selftests/kvm/include/x86/apic.h +1 -0
@@ -33,6 +33,7 @@#define APIC_SPIV 0xF0#define APIC_SPIV_FOCUS_DISABLED (1 << 9)#define APIC_SPIV_APIC_ENABLED (1 << 8) +#define APIC_TMR 0x180#define APIC_IRR 0x200#define APIC_ICR 0x300#define APIC_LVTCMCI 0x2f0
tools/testing/selftests/kvm/include/x86/savic.h +1 -0
@@ -16,4 +16,5 @@ void savic_hv_write_reg(uint32_t reg, uint64_t val);uint64_t savic_hv_read_reg (uint32_t reg);void savic_enable (void );int savic_nr_pages_required (uint64_t page_size); +void savic_vc_handler (struct ex_regs *regs);#endif
tools/testing/selftests/kvm/lib/x86/savic.c +145 -0
154 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 26/35 KVM: selftests: Add IPI handling support for Secure AVIC
In reply to Neeraj UpadhyayWhen a guest vCPU has Secure AVIC (SAVIC) enabled, an attempt to send an Inter-Processor Interrupt (IPI) by writing to the Interrupt Command Register (APIC_ICR) does not complete in hardware. Instead, it triggers a #VC exception with the exit code SVM_EXIT_AVIC_INCOMPLETE_IPI. This design delegates the responsibility of IPI delivery to the guest's #VC handler.
Implement the necessary #VC handler to process these IPI requests, enabling multi-vCPU IPI communication for SAVIC guests.
Add support for all IPI modes: physical and logical destination modes, as well as "broadcast" and "broadcast-but-self" destination shorthands. Inject the IPI into each target vCPU by directly setting the appropriate bit in the Interrupt Request Register (IRR) of its backing page. In addition, propagate the ICR write to the hypervisor via a VMGEXIT. This is crucial for KVM to perform actions like waking up a halted vCPU.
APIC_ICR based NMI delivery is also supported via a the NMIReq field in the backing page.
This functionality is a prerequisite for testing IPIs in SAVIC guests. It allows selftests like xapic_ipi_test to correctly validate IPI delivery for SAVIC enabled guests.
--- tools/testing/selftests/kvm/lib/x86/savic.c | 111 ++++++++++++++++++++ 1 file changed, 111 insertions(+)
tools/testing/selftests/kvm/lib/x86/savic.c +111 -0
@@ -42,6 +42,12 @@ enum lapic_lvt_entry {#define MSR_AMD64_SECURE_AVIC_ALLOWED_NMI_BIT 1#define SVM_EXIT_AVIC_UNACCELERATED_ACCESS 0x402 +#define SVM_EXIT_AVIC_INCOMPLETE_IPI 0x401 + +#define REG_OFF (VEC ) (VEC / 32 * 16) +#define VEC_POS (VEC ) (VEC % 32) + +#define SAVIC_NMI_REQ_OFFSET 0x278/* * Initial pool of guest apic backing page.
@@ -335,6 +341,104 @@ static void handle_savic_unaccel_access(struct ex_regs *regs) } } +static void send_ipi (int cpu,int vector,bool nmi) +{ +struct guest_apic_page *apic_page; + + apic_page = &apic_page_pool->guest_apic_page[cpu]; + +if (nmi) +savic_write_reg (apic_page,SAVIC_NMI_REQ_OFFSET ,1 ); +else +savic_write_reg (apic_page,APIC_IRR +REG_OFF (vector),BIT (VEC_POS (vector))); +} + +static bool is_cpu_present (int cpu) +{ +struct guest_apic_page *apic_page; + +if (cpu >=KVM_MAX_VCPUS ) +return false; + + apic_page = &apic_page_pool->guest_apic_page[cpu]; + +return savic_read_reg (apic_page,APIC_ID ) !=0 ; +} + +static void savic_send_ipi_all_but (int vector,bool nmi) +{ +int cpu; +int mycpu =x2apic_read_reg (APIC_ID ); + +for (cpu =0 ; cpu <KVM_MAX_VCPUS ; cpu++) { +if (cpu == mycpu) +continue ; +if (!(cpu ==0 ||is_cpu_present (cpu))) +break ; +send_ipi (cpu, vector, nmi); + } +} + +static bool ipi_match_dest (uint32_t dest,bool logical,int dest_cpu) +{ +struct guest_apic_page *apic_page; + + apic_page = &apic_page_pool->guest_apic_page[dest_cpu]; +uint32_t ldr; + +if (logical) { + ldr =savic_read_reg (apic_page,APIC_LDR ); +return ((ldr >>16 ) == (dest >>16 )) && + (ldr & dest &0xffff ) !=0 ; + }else { +return dest ==savic_read_reg (apic_page,APIC_ID ); + } +} + +static void savic_send_ipi_target (uint32_t dest,int vector,bool logical, +bool nmi) +{ +int cpu; +int mycpu =x2apic_read_reg (APIC_ID ); + +for (cpu =0 ; cpu <KVM_MAX_VCPUS ; cpu++) { +if (cpu == mycpu) +continue ; +if (!(cpu ==0 ||is_cpu_present (cpu))) +break ; +if (ipi_match_dest (dest, logical, cpu)) +send_ipi (cpu, vector, nmi); + } +} + +static void savic_handle_icr_write (uint64_t icr_data) +{ +int dsh = icr_data &APIC_DEST_ALLBUT ; +int vector = icr_data &APIC_VECTOR_MASK ; +bool logical = icr_data &APIC_DEST_LOGICAL ; +bool nmi = (icr_data &APIC_DM_FIXED_MASK ) ==APIC_DM_NMI ; +uint64_t self_icr_data =APIC_DEST_SELF |APIC_INT_ASSERT | vector; + +if (nmi) + self_icr_data |=APIC_DM_NMI ; + +switch (dsh) { +case APIC_DEST_ALLINC : +savic_send_ipi_all_but (vector, nmi); +savic_hv_write_reg (APIC_ICR , icr_data); +x2apic_write_reg (APIC_ICR , self_icr_data); +break ; +case APIC_DEST_ALLBUT : +savic_send_ipi_all_but (vector, nmi); +savic_hv_write_reg (APIC_ICR , icr_data); +break ; +default : +savic_send_ipi_target (icr_data >>32 , vector, logical, nmi); +savic_hv_write_reg (APIC_ICR , icr_data); +break ; + } +} +void savic_vc_handler (struct ex_regs *regs) {uint64_t exit_code = regs->error_code;
@@ -343,6 +447,13 @@ void savic_vc_handler(struct ex_regs *regs)case SVM_EXIT_AVIC_UNACCELERATED_ACCESS :handle_savic_unaccel_access (regs);break ; +case SVM_EXIT_AVIC_INCOMPLETE_IPI : +uint64_t icr_data = regs->rax | (regs->rdx <<32 ); +uint32_t reg = (regs->rcx -APIC_BASE_MSR ) <<4 ; + +GUEST_ASSERT (reg ==APIC_ICR ); +savic_handle_icr_write (icr_data); +break ;default :sev_es_vc_handler (regs);break ;
Signature · 1 line
2.34.1
RFC PATCH v2 27/35 KVM: selftests: Add args parameter to kvm_arch_vm_post_create()
In reply to Neeraj UpadhyayThe kvm_arch_vm_post_create() hook allows for architecture-specific setup to be performed immediately after a VM is created. However, it currently lacks a mechanism to pass custom configuration data from the test down to this setup phase.
This is a limitation for features that require non-default initialization. For example, to test SEV-SNP with Secure AVIC (SAVIC), the desired VMSA features must be configured via the KVM_SEV_INIT2 ioctl. This ioctl is called within the x86 implementation of kvm_arch_vm_post_create(), but it currently uses hardcoded default values.
To make this configurable, extend kvm_arch_vm_post_create() with a generic "void *args" parameter. The x86 implementation of kvm_arch_vm_post_create() now uses this argument to populate the "struct kvm_sev_init" for the "KVM_SEV_INIT2" ioctl.
This refactoring makes the VM creation process more flexible and is a prerequisite for adding selftests for Secure AVIC guests.
--- .../testing/selftests/kvm/arm64/set_id_regs.c | 2 +- .../testing/selftests/kvm/include/kvm_util.h | 9 +++- tools/testing/selftests/kvm/include/x86/sev.h | 3 ++ tools/testing/selftests/kvm/lib/kvm_util.c | 51 +++++++++++++------ .../testing/selftests/kvm/lib/x86/processor.c | 6 ++- tools/testing/selftests/kvm/lib/x86/sev.c | 13 +++-- tools/testing/selftests/kvm/s390/cmma_test.c | 2 +- 7 files changed, 63 insertions(+), 23 deletions(-)
tools/testing/selftests/kvm/arm64/set_id_regs.c +1 -1
@@ -749,7 +749,7 @@ static void test_reset_preserves_id_regs(struct kvm_vcpu *vcpu)ksft_test_result_pass ("%s\n" , __func__); } -void kvm_arch_vm_post_create (struct kvm_vm *vm) +void kvm_arch_vm_post_create (struct kvm_vm *vm,void *args) {if (vm_check_cap (vm,KVM_CAP_ARM_MTE )) {vm_enable_cap (vm,KVM_CAP_ARM_MTE ,0 );
tools/testing/selftests/kvm/include/kvm_util.h +8 -1
@@ -992,6 +992,9 @@ static inline vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,struct kvm_vm *____vm_create (struct vm_shape shape);struct kvm_vm *__vm_create (struct vm_shape shape,uint32_t nr_runnable_vcpus,uint64_t nr_extra_pages); +struct kvm_vm *__vm_create_with_args (struct vm_shape shape, +uint32_t nr_runnable_vcpus,uint64_t nr_extra_pages, +void *args);static inline struct kvm_vm *vm_create_barebones (void ) {
@@ -1016,6 +1019,10 @@ static inline struct kvm_vm *vm_create(uint32_t nr_runnable_vcpus)struct kvm_vm *__vm_create_with_vcpus (struct vm_shape shape,uint32_t nr_vcpus,uint64_t extra_mem_pages,void *guest_code,struct kvm_vcpu *vcpus[]); +struct kvm_vm *___vm_create_with_vcpus (struct vm_shape shape, +uint32_t nr_vcpus,uint64_t extra_mem_pages, +void *guest_code,struct kvm_vcpu *vcpus[], +void *args); static inline struct kvm_vm *vm_create_with_vcpus(uint32_t nr_vcpus, void *guest_code,
@@ -1261,7 +1268,7 @@ static inline int __vm_disable_nx_huge_pages(struct kvm_vm *vm)*/ void kvm_selftest_arch_init (void ); -void kvm_arch_vm_post_create (struct kvm_vm *vm); +void kvm_arch_vm_post_create (struct kvm_vm *vm,void *args);bool vm_is_gpa_protected (struct kvm_vm *vm,vm_paddr_t paddr);
tools/testing/selftests/kvm/include/x86/sev.h +3 -0
@@ -72,6 +72,9 @@ void snp_vm_launch_start(struct kvm_vm *vm, uint64_t policy);void snp_vm_launch_update (struct kvm_vm *vm);void snp_vm_launch_finish (struct kvm_vm *vm); +struct kvm_vm *_vm_sev_create_with_one_vcpu (uint32_t type,void *guest_code, +struct kvm_vcpu **cpu, +void *init_args);struct kvm_vm *vm_sev_create_with_one_vcpu (uint32_t type,void *guest_code,struct kvm_vcpu **cpu);void vm_sev_launch (struct kvm_vm *vm,uint64_t policy,uint8_t *measurement);
tools/testing/selftests/kvm/lib/kvm_util.c +36 -15
75 lines not on this page · raw message
tools/testing/selftests/kvm/lib/x86/processor.c +4 -2
@@ -9,6 +9,7 @@#include "processor.h" #include "sev.h" #include "apic.h" +#include "savic.h" #ifndef NUM_INTERRUPTS #define NUM_INTERRUPTS 256
@@ -631,7 +632,7 @@ void assert_on_unhandled_exception(struct kvm_vcpu *vcpu)REPORT_GUEST_ASSERT (uc); } -void kvm_arch_vm_post_create (struct kvm_vm *vm) +void kvm_arch_vm_post_create (struct kvm_vm *vm,void *sev_init_args) {int r;
@@ -648,7 +649,8 @@ void kvm_arch_vm_post_create(struct kvm_vm *vm)if (is_sev_vm (vm)) {struct kvm_sev_init init = {0 }; -vm_sev_ioctl (vm,KVM_SEV_INIT2 , &init); +vm_sev_ioctl (vm,KVM_SEV_INIT2 , sev_init_args ? + (struct kvm_sev_init *)sev_init_args : &init); } r =__vm_ioctl (vm,KVM_GET_TSC_KHZ ,NULL );
tools/testing/selftests/kvm/lib/x86/sev.c +10 -3
@@ -260,8 +260,9 @@ void snp_vm_launch_finish(struct kvm_vm *vm)vm_sev_ioctl (vm,KVM_SEV_SNP_LAUNCH_FINISH , &launch_finish); } -struct kvm_vm *vm_sev_create_with_one_vcpu (uint32_t type,void *guest_code, -struct kvm_vcpu **cpu) +struct kvm_vm *_vm_sev_create_with_one_vcpu (uint32_t type,void *guest_code, +struct kvm_vcpu **cpu, +void *init_args) {struct vm_shape shape = { .mode =VM_MODE_DEFAULT ,
@@ -270,7 +271,7 @@ struct kvm_vm *vm_sev_create_with_one_vcpu(uint32_t type, void *guest_code,struct kvm_vm *vm;struct kvm_vcpu *cpus[1 ]; - vm =__vm_create_with_vcpus (shape,1 ,0 , guest_code, cpus); + vm =___vm_create_with_vcpus (shape,1 ,0 , guest_code, cpus, init_args); *cpu = cpus[0 ];return vm;
@@ -288,6 +289,12 @@ static bool is_savic_enabled(void)return supported_vmsa_features &BIT_ULL (SVM_FEAT_SECURE_AVIC ); } +struct kvm_vm *vm_sev_create_with_one_vcpu (uint32_t type,void *guest_code, +struct kvm_vcpu **cpu) +{ +return _vm_sev_create_with_one_vcpu (type, guest_code, cpu,NULL ); +} +void vm_sev_launch (struct kvm_vm *vm,uint64_t policy,uint8_t *measurement) {if (is_sev_es_vm (vm))
tools/testing/selftests/kvm/s390/cmma_test.c +1 -1
@@ -145,7 +145,7 @@ static void finish_vm_setup(struct kvm_vm *vm) slot0 =memslot2region (vm,0 );ucall_init (vm, slot0->region.guest_phys_addr + slot0->region.memory_size); -kvm_arch_vm_post_create (vm); +kvm_arch_vm_post_create (vm,NULL ); }static struct kvm_vm *create_vm_two_memslots (void )
Signature · 1 line
2.34.1
RFC PATCH v2 28/35 KVM: selftests: Add GHCB call for SAVIC backing page notification
In reply to Neeraj UpadhyayWhen a vCPU enables Secure AVIC (SAVIC), the hardware needs to directly access the guest's APIC backing page. For this to work correctly, the hypervisor must be aware of the guest physical address (GPA) of this page so it can ensure the page is mapped and pinned in the nested page tables (NPT) while the vCPU is running.
Introduce a paravirtual GHCB call that the guest uses to notify the hypervisor of the backing page's GPA before activating SAVIC.
--- tools/testing/selftests/kvm/include/x86/sev.h | 1 + tools/testing/selftests/kvm/lib/x86/savic.c | 1 + tools/testing/selftests/kvm/lib/x86/sev.c | 25 ++++++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-)
tools/testing/selftests/kvm/include/x86/sev.h +1 -0
@@ -171,4 +171,5 @@ void sev_es_ucall_port_write(uint32_t port, uint64_t data);void sev_es_vc_handler (struct ex_regs *regs);void sev_es_pv_msr_rw (uint64_t msr,uint64_t *data,bool write);void sev_es_pv_mmio_rw (uint32_t *reg_gpa,uint32_t *data,bool write); +void sev_es_savic_notify_gpa (uint64_t gpa);#endif /* SELFTEST_KVM_SEV_H */
tools/testing/selftests/kvm/lib/x86/savic.c +1 -0
@@ -203,6 +203,7 @@ void savic_enable(void) apic_page = &apic_page_pool->guest_apic_page[apic_id];savic_init_backing_page (apic_page, apic_id); +sev_es_savic_notify_gpa (apic_page->gpa);set_savic_control_msr (apic_page, true, true); savic_ctrl_msr_val =rdmsr (MSR_AMD64_SECURE_AVIC_CONTROL ); exp_msr_val = apic_page->gpa | BIT_ULL(MSR_AMD64_SECURE_AVIC_EN_BIT) |
tools/testing/selftests/kvm/lib/x86/sev.c +24 -1
@@ -8,6 +8,7 @@#include "linux/bitmap.h" #include "svm.h" #include "svm_util.h" +#include "savic.h" #define IOIO_TYPE_STR (1 << 2)#define IOIO_SEG_DS (1 << 11 | 1 << 10)
@@ -17,7 +18,8 @@#define SW_EXIT_CODE_IOIO 0x7b#define SW_EXIT_CODE_MSR 0x7c#define SVM_VMGEXIT_MMIO_READ 0x80000001 -#define SVM_VMGEXIT_MMIO_WRITE 0x80000002 +#define SVM_VMGEXIT_MMIO_WRITE 0x80000002 +#define SVM_VMGEXIT_SECURE_AVIC 0x8000001astruct ghcb_entry {struct ghcb ghcb;
@@ -727,3 +729,24 @@ void sev_es_vc_handler(struct ex_regs *regs)__GUEST_ASSERT (0 ,"No VC handler\n" ); } } + +void sev_es_savic_notify_gpa (uint64_t gpa) +{ +struct ghcb_entry *entry; +struct ghcb *ghcb; +int ret; + + entry =ghcb_alloc (); + ghcb = &entry->ghcb; + +register_ghcb_page (entry->gpa); +ghcb_set_sw_exit_code (ghcb,SVM_VMGEXIT_SECURE_AVIC ); +ghcb_set_rax (ghcb,-1ULL ); +ghcb_set_rbx (ghcb, gpa); +ghcb_set_sw_exit_info_1 (ghcb,0 ); +ghcb_set_sw_exit_info_2 (ghcb,0 ); +do_vmg_exit (entry->gpa); + ret = ghcb->save.sw_exit_info_1 &0xffffffff ; +__GUEST_ASSERT (!ret,"Secure AVIC GPA notification failed, ret: %d" , ret); +ghcb_free (entry); +}
Signature · 1 line
2.34.1
RFC PATCH v2 29/35 KVM: selftests: Add Secure AVIC mode to xapic_ipi_test
In reply to Neeraj UpadhyayExtend the xapic_ipi_test to validate Inter-Processor Interrupt (IPI) functionality in SEV-SNP guests with Secure AVIC (SAVIC) enabled.
Secure AVIC alters how IPIs are handled. Instead of relying solely on KVM's APIC emulation/AVIC hardware, an attempt to send an IPI triggers a #VC(INCOMPLETE_IPI) exception, delegating the IPI delivery logic to the guest's #VC handler. This new execution model requires dedicated test coverage.
With these changes, the existing IPI test framework can now run on SAVIC-enabled vCPUs, verifying that the guest-side emulation correctly delivers interrupts between cores and providing critical test coverage for this SEV-SNP feature.
--- tools/arch/x86/include/asm/msr-index.h | 4 +- .../selftests/kvm/include/x86/processor.h | 1 + .../selftests/kvm/x86/xapic_ipi_test.c | 72 +++++++++++++------ 3 files changed, 56 insertions(+), 21 deletions(-)
tools/arch/x86/include/asm/msr-index.h +3 -1
@@ -698,7 +698,9 @@#define MSR_AMD64_SNP_VMSA_REG_PROT BIT_ULL(MSR_AMD64_SNP_VMSA_REG_PROT_BIT)#define MSR_AMD64_SNP_SMT_PROT_BIT 17#define MSR_AMD64_SNP_SMT_PROT BIT_ULL(MSR_AMD64_SNP_SMT_PROT_BIT) -#define MSR_AMD64_SNP_RESV_BIT 18 +#define MSR_AMD64_SNP_SECURE_AVIC_BIT 18 +#define MSR_AMD64_SNP_SECURE_AVIC BIT_ULL(MSR_AMD64_SNP_SECURE_AVIC_BIT) +#define MSR_AMD64_SNP_RESV_BIT 19#define MSR_AMD64_SNP_RESERVED_MASK GENMASK_ULL(63, MSR_AMD64_SNP_RESV_BIT)#define MSR_AMD64_RMP_BASE 0xc0010132#define MSR_AMD64_RMP_END 0xc0010133
tools/testing/selftests/kvm/include/x86/processor.h +1 -0
@@ -204,6 +204,7 @@ struct kvm_x86_cpu_feature {#define X86_FEATURE_SEV KVM_X86_CPU_FEATURE(0x8000001F, 0, EAX, 1)#define X86_FEATURE_SEV_ES KVM_X86_CPU_FEATURE(0x8000001F, 0, EAX, 3)#define X86_FEATURE_SEV_SNP KVM_X86_CPU_FEATURE(0x8000001F, 0, EAX, 4) +#define X86_FEATURE_SECURE_AVIC KVM_X86_CPU_FEATURE(0x8000001F, 0, EAX, 26)#define X86_FEATURE_PERFMON_V2 KVM_X86_CPU_FEATURE(0x80000022, 0, EAX, 0)#define X86_FEATURE_LBR_PMC_FREEZE KVM_X86_CPU_FEATURE(0x80000022, 0, EAX, 2)
tools/testing/selftests/kvm/x86/xapic_ipi_test.c +52 -20
161 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 30/35 KVM: selftests: Add test to verify APIC MSR accesses for SAVIC guest
In reply to Neeraj UpadhyayWhen Secure AVIC (SAVIC) is enabled in an SEV-SNP guest, a hybrid model for APIC register access is used. Some registers are accelerated by the hardware, while others trigger a #VC exception for emulation by the guest's #VC handler. This complex interaction requires dedicated testing to ensure correctness.
Add savic_test.c, a new selftest designed to validate APIC MSR accesses in SAVIC mode. The test creates an SEV-SNP VM with SAVIC enabled and systematically performs rdmsr/wrmsr operations on a comprehensive set of APIC registers.
The test verifies several key behaviors:
* Ensure that accesses to unaccelerated MSRs (e.g., APIC_TMICT, APIC_LVTT) correctly trigger a #VC exception and are properly emulated by the savic_vc_handler().
* Confirm that architecturally invalid operations, such as writing to a read-only register (APIC_LVR) or reading a write-only register (APIC_EOI), generate the expected #GP fault.
* Verify that the state in the guest's APIC backing page is consistent with values read via RDMSR after a write.
* Validate that register writes are correctly propagated (or intentionally not propagated) to the hypervisor's internal state, ensuring proper synchronization for registers like APIC_SPIV versus accelerated registers like APIC_TASKPRI.
This test provides essential coverage for the SAVIC feature, ensuring its MSR handling mechanism is implemented correctly.
--- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../testing/selftests/kvm/include/x86/apic.h | 1 + .../testing/selftests/kvm/include/x86/savic.h | 4 + tools/testing/selftests/kvm/lib/x86/savic.c | 20 +- tools/testing/selftests/kvm/x86/savic_test.c | 291 ++++++++++++++++++ 5 files changed, 312 insertions(+), 5 deletions(-) create mode 100644 tools/testing/selftests/kvm/x86/savic_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
@@ -96,6 +96,7 @@ TEST_GEN_PROGS_x86 += x86/pmu_counters_test TEST_GEN_PROGS_x86 += x86/pmu_event_filter_test TEST_GEN_PROGS_x86 += x86/private_mem_conversions_test TEST_GEN_PROGS_x86 += x86/private_mem_kvm_exits_test +TEST_GEN_PROGS_x86 += x86/savic_test TEST_GEN_PROGS_x86 += x86/set_boot_cpu_id TEST_GEN_PROGS_x86 += x86/set_sregs_test TEST_GEN_PROGS_x86 += x86/smaller_maxphyaddr_emulation_test
tools/testing/selftests/kvm/include/x86/apic.h +1 -0
@@ -33,6 +33,7 @@#define APIC_SPIV 0xF0#define APIC_SPIV_FOCUS_DISABLED (1 << 9)#define APIC_SPIV_APIC_ENABLED (1 << 8) +#define APIC_ISR 0x100#define APIC_TMR 0x180#define APIC_IRR 0x200#define APIC_ICR 0x300
tools/testing/selftests/kvm/include/x86/savic.h +4 -0
@@ -6,6 +6,9 @@#ifndef SELFTEST_KVM_SAVIC_H #define SELFTEST_KVM_SAVIC_H +#define APIC_REG_OFF (VEC ) (VEC / 32 * 16) +#define APIC_VEC_POS (VEC ) (VEC % 32) +struct guest_apic_page ;void guest_apic_pages_init (struct kvm_vm *vm);
@@ -17,4 +20,5 @@ uint64_t savic_hv_read_reg(uint32_t reg);void savic_enable (void );int savic_nr_pages_required (uint64_t page_size);void savic_vc_handler (struct ex_regs *regs); +struct guest_apic_page *get_guest_apic_page (void );#endif
tools/testing/selftests/kvm/lib/x86/savic.c +15 -5
@@ -8,6 +8,7 @@#include "apic.h" #include "kvm_util.h" #include "sev.h" +#include "savic.h" struct apic_page {u8 apic_regs[PAGE_SIZE ];
@@ -44,9 +45,6 @@ enum lapic_lvt_entry {#define SVM_EXIT_AVIC_UNACCELERATED_ACCESS 0x402#define SVM_EXIT_AVIC_INCOMPLETE_IPI 0x401 -#define REG_OFF (VEC ) (VEC / 32 * 16) -#define VEC_POS (VEC ) (VEC % 32) -#define SAVIC_NMI_REQ_OFFSET 0x278/*
@@ -104,6 +102,11 @@ void set_savic_control_msr(struct guest_apic_page *apic_page, bool enable, boolwrmsr (MSR_AMD64_SECURE_AVIC_CONTROL , val); } +struct guest_apic_page *get_guest_apic_page (void ) +{ +return &apic_page_pool->guest_apic_page[x2apic_read_reg (APIC_ID )]; +} +/* * Write APIC reg offset in the guest APIC backing page. *
@@ -175,11 +178,17 @@ static void savic_init_backing_page(struct guest_apic_page *apic_page, uint32_t regval =savic_hv_read_reg (APIC_LDR );savic_write_reg (apic_page,APIC_LDR , regval); -for (i =LVT_THERMAL_MONITOR ; i <APIC_MAX_NR_LVT_ENTRIES ; i++) { +for (i =LVT_TIMER ; i <APIC_MAX_NR_LVT_ENTRIES ; i++) { regval =savic_hv_read_reg (APIC_LVTx (i));savic_write_reg (apic_page,APIC_LVTx (i), regval); } + regval =savic_hv_read_reg (APIC_TMICT ); +savic_write_reg (apic_page,APIC_TMICT , regval); + + regval =savic_hv_read_reg (APIC_TDCR ); +savic_write_reg (apic_page,APIC_TDCR , regval); + regval =savic_hv_read_reg (APIC_LVT0 );savic_write_reg (apic_page,APIC_LVT0 , regval);
@@ -351,7 +360,8 @@ static void send_ipi(int cpu, int vector, bool nmi)if (nmi)savic_write_reg (apic_page,SAVIC_NMI_REQ_OFFSET ,1 );else -savic_write_reg (apic_page,APIC_IRR +REG_OFF (vector),BIT (VEC_POS (vector))); +savic_write_reg (apic_page,APIC_IRR +APIC_REG_OFF (vector), +BIT (APIC_VEC_POS (vector))); }static bool is_cpu_present (int cpu)
tools/testing/selftests/kvm/x86/savic_test.c new file +291 -0
291 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 31/35 KVM: selftests: Extend savic_test with idle halt testing
In reply to Neeraj UpadhyayAdd a test case to savic_test.c to verify the correct handling of HLT instructions in Secure AVIC (SAVIC) enabled guests.
This validation is crucial for the SAVIC feature. With SAVIC, the IRR is managed in the guest's private memory (the APIC backing page), making it invisible to the hypervisor. In the absence of idle HLT intercept, the hypervisor would be unaware of pending interrupts in the IRR and would incorrectly block the vCPU.
Additionally, verify the corresponding ISR and EOI behavior for the delivered interrupt within the SAVIC model.
--- tools/testing/selftests/kvm/x86/savic_test.c | 57 +++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-)
tools/testing/selftests/kvm/x86/savic_test.c +55 -2
@@ -14,7 +14,10 @@#include "savic.h" #define NR_SAVIC_VCPUS 1 +#define IDLE_HLT_INTR_VECTOR 0x30 +#define NUM_ITERATIONS 2000 +static bool irq_received;static struct kvm_vcpu *vcpus[NR_SAVIC_VCPUS ];static pthread_t threads[NR_SAVIC_VCPUS ];
@@ -24,6 +27,7 @@ static pthread_t threads[NR_SAVIC_VCPUS];enum savic_test_state { SAVIC_TEST_STATE(SAVIC_APIC_MSR_ACCESSES), + SAVIC_TEST_STATE(SAVIC_IDLE_HALT), };#define SAVIC_GUEST_SYNC (sync, func) ({\
@@ -89,7 +93,8 @@ static void guest_verify_host_guest_reg(struct guest_apic_page *apage, uint32_t hval =savic_hv_read_reg (reg);__GUEST_ASSERT (gval == val,"Unexpected Guest %s 0x%lx, expected val:0x%lx\n" , regname, gval, val); -__GUEST_ASSERT (gval == gval2,"Unexpected Guest %s backing page value : 0x%lx, msr read val:0x%lx\n" , +__GUEST_ASSERT (gval == gval2, +"Unexpected %s Guest backing page value : 0x%lx, msr read val:0x%lx\n" , regname, gval, gval2);switch (reg) {
@@ -161,6 +166,7 @@ static void guest_savic_apic_msr_accesses(int id) val =savic_read_reg (apage,APIC_IRR +APIC_REG_OFF (vec));GUEST_ASSERT ((val &BIT_ULL (APIC_VEC_POS (vec))) ==BIT_ULL (APIC_VEC_POS (vec)));savic_wrmsr (APIC_TASKPRI ,0x0 ); +savic_write_reg (apage,APIC_IRR +APIC_REG_OFF (vec),0 );/* Triggers GP fault */ savic_rdmsr (APIC_EOI );
@@ -219,6 +225,43 @@ static void guest_savic_apic_msr_accesses(int id) } } +static void guest_idle_hlt_intr_handler (struct ex_regs *regs) +{ +struct guest_apic_page *apage =get_guest_apic_page (); +uint32_t isr, reg; + +WRITE_ONCE (irq_received, true); + reg =APIC_ISR +APIC_REG_OFF (IDLE_HLT_INTR_VECTOR ); + isr =savic_read_reg (apage, reg); +__GUEST_ASSERT (isr &BIT (APIC_VEC_POS (IDLE_HLT_INTR_VECTOR )), +"Idle halt vector not set in APIC_ISR" ); +x2apic_write_reg (APIC_EOI ,0 ); + isr =savic_read_reg (apage, reg); +__GUEST_ASSERT (!(isr &BIT (APIC_VEC_POS (IDLE_HLT_INTR_VECTOR ))), +"Idle halt vector set in APIC_ISR after EOI" ); +} + +static void guest_savic_idle_halt (int id) +{ +uint32_t icr_val; +uint32_t irr; +int i; + +x2apic_write_reg (APIC_TASKPRI ,0 ); + icr_val = (APIC_DEST_SELF |APIC_INT_ASSERT |IDLE_HLT_INTR_VECTOR ); + +for (i =0 ; i <NUM_ITERATIONS ; i++) { + asmvolatile ("cli" ); +x2apic_write_reg (APIC_ICR , icr_val); + irr =x2apic_read_reg (APIC_IRR +APIC_REG_OFF (IDLE_HLT_INTR_VECTOR )); +__GUEST_ASSERT (irr &BIT (APIC_VEC_POS (IDLE_HLT_INTR_VECTOR )), +"Idle halt vector not set in APIC_IRR" ); + asmvolatile ("sti; hlt;" : : :"memory" ); +GUEST_ASSERT (READ_ONCE (irq_received)); +WRITE_ONCE (irq_received, false); + } +} +static void guest_code (int id) {GUEST_ASSERT (rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SNP_SECURE_AVIC );
@@ -229,6 +272,8 @@ static void guest_code(int id)SAVIC_GUEST_SYNC (SAVIC_APIC_MSR_ACCESSES , guest_savic_apic_msr_accesses); +SAVIC_GUEST_SYNC (SAVIC_IDLE_HALT , guest_savic_idle_halt); +GUEST_DONE (); }
@@ -260,6 +305,12 @@ static void *vcpu_thread(void *arg)return NULL ; } +static void install_exception_handlers (struct kvm_vm *vm) +{ +vm_install_exception_handler (vm,IDLE_HLT_INTR_VECTOR , guest_idle_hlt_intr_handler); +vm_install_exception_handler (vm,29 , savic_vc_handler); +} +int main (int argc,char *argv[]) {struct kvm_sev_init args = {
@@ -270,14 +321,16 @@ int main(int argc, char *argv[])TEST_REQUIRE (kvm_cpu_has (X86_FEATURE_SEV_SNP ));TEST_REQUIRE (kvm_cpu_has (X86_FEATURE_SECURE_AVIC )); +TEST_REQUIRE (this_cpu_has (X86_FEATURE_IDLE_HLT )); vm =_vm_sev_create_with_one_vcpu (KVM_X86_SNP_VM , guest_code, &vcpus[0 ], &args);virt_pg_map (vm,APIC_DEFAULT_GPA ,APIC_DEFAULT_GPA ); +install_exception_handlers (vm); +vcpu_args_set (vcpus[0 ],1 , vcpus[0 ]->id); -vm_install_exception_handler (vm,29 , savic_vc_handler);vm_sev_launch (vm,snp_default_policy (),NULL ); r =pthread_create (&threads[0 ],NULL , vcpu_thread, vcpus[0 ]);
Signature · 1 line
2.34.1
RFC PATCH v2 32/35 KVM: selftests: Add IOAPIC tests for Secure AVIC
In reply to Neeraj UpadhyayExtend the Secure AVIC (SAVIC) selftest to validate the delivery of external interrupts via the IOAPIC. This is a critical validation step, as the interrupt injection path for SAVIC guests is different from traditional APIC modes and requires explicit guest cooperation.
In SAVIC mode, for the hardware to inject an external interrupt, the guest must first grant permission for the corresponding vector. This is done by setting a bit in a designated "allowed IRR" region within its private APIC backing page. If the vector is not allowed, the interrupt is dropped by the hardware.
Add a new test case to savic_test.c and verify this entire flow of IOAPIC interrupt injection for both edge and level-triggered interrupts. Also test the special-cased RTC GSI (IRQ 8).
To support this, add new helpers for reading/writing the IOAPIC MMIO region and updating the IOAPIC redirection table.
--- .../testing/selftests/kvm/include/kvm_util.h | 1 + .../testing/selftests/kvm/include/x86/apic.h | 49 ++++ .../testing/selftests/kvm/include/x86/savic.h | 1 + tools/testing/selftests/kvm/lib/kvm_util.c | 17 ++ .../testing/selftests/kvm/lib/x86/processor.c | 2 +- tools/testing/selftests/kvm/lib/x86/savic.c | 11 + tools/testing/selftests/kvm/x86/savic_test.c | 253 +++++++++++++++++- 7 files changed, 330 insertions(+), 4 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +1 -0
@@ -952,6 +952,7 @@ void *vcpu_map_dirty_ring(struct kvm_vcpu *vcpu);void vcpu_args_set (struct kvm_vcpu *vcpu,unsigned int num, ...);void kvm_irq_line (struct kvm_vm *vm,uint32_t irq,int level); +void kvm_irq_line_status (struct kvm_vm *vm,uint32_t irq,int level);int _kvm_irq_line (struct kvm_vm *vm,uint32_t irq,int level);#define KVM_MAX_IRQ_ROUTES 4096
tools/testing/selftests/kvm/include/x86/apic.h +49 -0
60 lines not on this page · raw message
tools/testing/selftests/kvm/include/x86/savic.h +1 -0
@@ -21,4 +21,5 @@ void savic_enable(void);int savic_nr_pages_required (uint64_t page_size);void savic_vc_handler (struct ex_regs *regs);struct guest_apic_page *get_guest_apic_page (void ); +void savic_allow_vector (int vec);#endif
tools/testing/selftests/kvm/lib/kvm_util.c +17 -0
@@ -1964,6 +1964,23 @@ void kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level)TEST_ASSERT (ret >=0 ,KVM_IOCTL_ERROR (KVM_IRQ_LINE , ret)); } +int _kvm_irq_line_status (struct kvm_vm *vm,uint32_t irq,int level) +{ +struct kvm_irq_level irq_level = { + .irq = irq, + .level = level, + }; + +return __vm_ioctl (vm,KVM_IRQ_LINE_STATUS , &irq_level); +} + +void kvm_irq_line_status (struct kvm_vm *vm,uint32_t irq,int level) +{ +int ret =_kvm_irq_line_status (vm, irq, level); + +TEST_ASSERT (ret >=0 ,KVM_IOCTL_ERROR (KVM_IRQ_LINE_STATUS , ret)); +} +struct kvm_irq_routing *kvm_gsi_routing_create (void ) {struct kvm_irq_routing *routing;
tools/testing/selftests/kvm/lib/x86/processor.c +1 -1
@@ -229,7 +229,7 @@ void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, int level) "PTE already present for 4k page at vaddr: 0x%lx", vaddr); *pte =PTE_PRESENT_MASK |PTE_WRITABLE_MASK | (paddr &PHYSICAL_PAGE_MASK ); -if (paddr ==APIC_DEFAULT_GPA ) { +if (paddr ==APIC_DEFAULT_GPA || paddr ==IOAPIC_DEFAULT_GPA ) { *pte |= vm->arch.s_bit;return ; }
tools/testing/selftests/kvm/lib/x86/savic.c +11 -0
@@ -45,6 +45,7 @@ enum lapic_lvt_entry {#define SVM_EXIT_AVIC_UNACCELERATED_ACCESS 0x402#define SVM_EXIT_AVIC_INCOMPLETE_IPI 0x401 +#define SAVIC_ALLOWED_IRR (APIC_IRR + 0x4)#define SAVIC_NMI_REQ_OFFSET 0x278/*
@@ -107,6 +108,16 @@ struct guest_apic_page *get_guest_apic_page(void)return &apic_page_pool->guest_apic_page[x2apic_read_reg (APIC_ID )]; } +void savic_allow_vector (int vec) +{ +struct guest_apic_page *apage =get_guest_apic_page (); + +savic_write_reg (apage,SAVIC_ALLOWED_IRR +APIC_REG_OFF (vec), +savic_read_reg (apage,SAVIC_ALLOWED_IRR +APIC_REG_OFF (vec)) | +BIT_ULL (APIC_VEC_POS (vec))); + +} +/* * Write APIC reg offset in the guest APIC backing page. *
tools/testing/selftests/kvm/x86/savic_test.c +250 -3
326 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 33/35 KVM: selftests: Add cross-vCPU IPI testing for SAVIC guests
In reply to Neeraj UpadhyayExtend the savic_test to validate Inter-Processor Interrupt (IPI) delivery between vCPUs in a Secure AVIC (SAVIC) enabled guest.
When a vCPU in SAVIC mode sends an IPI, the hardware triggers a #VC(INCOMPLETE_IPI) exception. The responsibility of routing and delivering the IPI to the target vCPU(s) falls to the guest's #VC handler. Exercise this guest-side emulation logic thoroughly.
Extend the test to use multiple vCPUsand verify IPIs using various destination modes and shorthands, including:
Fixed (physical) destination
Fixed-logical destination
Broadcast to all vCPUs (including self)
Broadcast to all vCPUs (excluding self)
This provides essential test coverage, ensuring that the SAVIC IPI emulation mechanism is robust and correct across all standard addressing modes.
--- tools/testing/selftests/kvm/x86/savic_test.c | 305 ++++++++++++++++++- 1 file changed, 299 insertions(+), 6 deletions(-)
tools/testing/selftests/kvm/x86/savic_test.c +299 -6
@@ -13,7 +13,7 @@#include "test_util.h" #include "savic.h" -#define NR_SAVIC_VCPUS 1 +#define NR_SAVIC_VCPUS 2#define NUM_ITERATIONS 2000#define IDLE_HLT_INTR_VECTOR 0x30
@@ -22,6 +22,10 @@#define IOAPIC_NUM_LEVEL_VECTORS 2#define RTC_GSI 8#define RTC_GSI_IRQ 0x85 +#define FIXED_IPI_VEC 0x31 +#define FIXED_LOGICAL_IPI_VEC 0x32 +#define BROADCAST_ALL_IPI_VEC 0x33 +#define BROADCAST_NOSELF_IPI_VEC 0x34static bool irq_received;static struct kvm_vcpu *vcpus[NR_SAVIC_VCPUS ];
@@ -36,6 +40,7 @@ enum savic_test_state {SAVIC_TEST_STATE (SAVIC_IDLE_HALT ),SAVIC_TEST_STATE (SAVIC_IOAPIC ),SAVIC_TEST_STATE (SAVIC_IOAPIC2 ), + SAVIC_TEST_STATE(SAVIC_IPI), };/* Data struct shared between host main thread and vCPUs */
@@ -45,6 +50,18 @@ struct test_data_page {uint64_t ioapic_lirq1_count;uint64_t ioapic_lirq2_count;uint64_t ioapic_rtc_gsi_irq_count; +uint64_t fixed_ipi_wake_count; +uint64_t fixed_ipi_hlt_count; +uint64_t fixed_logical_ipi_hlt_count; +uint64_t fixed_logical_ipi_wake_count; +uint64_t broadcast_ipi_hlt_count; +uint64_t broadcast_ipi_wake_count; +uint64_t broadcast_noself_ipi_hlt_count; +uint64_t broadcast_noself_ipi_wake_count; +uint64_t fixed_ipi_count; +uint64_t fixed_logical_ipi_count; +uint64_t broadcast_ipi_count; +uint64_t broadcast_noself_ipi_count; };static struct test_data_page *test_data[NR_SAVIC_VCPUS ];
@@ -452,6 +469,247 @@ static void guest_setup_ioapic(int id)savic_allow_vector (vec); } +static void savic_fixed_ipi (bool logical) +{ +uint64_t last_wake_cnt, last_hlt_cnt; +uint64_t last_fixed_ipi_cnt; +uint64_t tsc_start; +uint64_t *fixed_ipi_p; +uint64_t *fixed_ipi_hlt_cnt_p; +uint64_t *fixed_ipi_wake_cnt_p; +int vec; +int i, j; + +for (i =1 ; i <NR_SAVIC_VCPUS ; i++) { +struct test_data_page *data = test_data[i]; +uint64_t dst_apic_id = i; + +if (logical) { + fixed_ipi_p = &data->fixed_logical_ipi_count; + fixed_ipi_hlt_cnt_p = &data->fixed_logical_ipi_hlt_count; + fixed_ipi_wake_cnt_p = &data->fixed_logical_ipi_wake_count; + vec =FIXED_LOGICAL_IPI_VEC |APIC_DEST_LOGICAL ; + dst_apic_id =1 << i; + }else { + fixed_ipi_p = &data->fixed_ipi_count; + fixed_ipi_hlt_cnt_p = &data->fixed_ipi_hlt_count; + fixed_ipi_wake_cnt_p = &data->fixed_ipi_wake_count; + vec =FIXED_IPI_VEC ; + dst_apic_id = i; + } + + last_wake_cnt =READ_ONCE (*fixed_ipi_wake_cnt_p); +while (!READ_ONCE (*fixed_ipi_hlt_cnt_p)) + ; + + last_hlt_cnt =READ_ONCE (*fixed_ipi_hlt_cnt_p); + last_fixed_ipi_cnt =READ_ONCE (*fixed_ipi_p); + +for (j =0 ; j <NUM_ITERATIONS ; j++) { + tsc_start =rdtsc (); +x2apic_write_reg (APIC_ICR , dst_apic_id <<32 | +APIC_INT_ASSERT | vec); +while (rdtsc () - tsc_start <1000000000 ) { +if (READ_ONCE (*fixed_ipi_wake_cnt_p) != last_wake_cnt && +READ_ONCE (*fixed_ipi_hlt_cnt_p) != last_hlt_cnt && +READ_ONCE (*fixed_ipi_p) != last_fixed_ipi_cnt) +break ; + } + +__GUEST_ASSERT (READ_ONCE (*fixed_ipi_wake_cnt_p) != last_wake_cnt && +READ_ONCE (*fixed_ipi_hlt_cnt_p) != last_hlt_cnt && +READ_ONCE (*fixed_ipi_p) != last_fixed_ipi_cnt, +"wakeup_cnt: %ld last_wake_cnt: %ld hlt_count: %ld last_hlt_cnt: %ld d_ipi_count: %ld last_d_ipi_count: %ld" , +READ_ONCE (*fixed_ipi_wake_cnt_p), last_wake_cnt, +READ_ONCE (*fixed_ipi_hlt_cnt_p), last_hlt_cnt, +READ_ONCE (*fixed_ipi_p), last_fixed_ipi_cnt); + + last_wake_cnt =READ_ONCE (*fixed_ipi_wake_cnt_p); + last_hlt_cnt =READ_ONCE (*fixed_ipi_hlt_cnt_p); + last_fixed_ipi_cnt =READ_ONCE (*fixed_ipi_p); + } + } +} + +static void savic_send_broadcast (int dsh) +{ +uint64_t last_wake_cnt[NR_SAVIC_VCPUS ], last_hlt_cnt[NR_SAVIC_VCPUS ]; +uint64_t last_ipi_cnt[NR_SAVIC_VCPUS ]; +uint64_t tsc_start; +uint64_t *broadcast_ipi_p; +uint64_t *broadcast_ipi_hlt_cnt_p; +uint64_t *broadcast_ipi_wake_cnt_p; +struct test_data_page *data; +int i, j; +int vec; + +if (dsh ==APIC_DEST_ALLINC ) + vec =BROADCAST_ALL_IPI_VEC ; +else + vec =BROADCAST_NOSELF_IPI_VEC ; + +for (i =1 ; i <NR_SAVIC_VCPUS ; i++) { + data = test_data[i]; + +if (dsh ==APIC_DEST_ALLINC ) + broadcast_ipi_hlt_cnt_p = &data->broadcast_ipi_hlt_count; +else + broadcast_ipi_hlt_cnt_p = &data->broadcast_noself_ipi_hlt_count; + +while (!READ_ONCE (*broadcast_ipi_hlt_cnt_p)) + ; + } + +for (j =0 ; j <NUM_ITERATIONS ; j++) { +for (i =1 ; i <NR_SAVIC_VCPUS ; i++) { + data = test_data[i]; + +if (dsh ==APIC_DEST_ALLINC ) { + last_hlt_cnt[i] =READ_ONCE (data->broadcast_ipi_hlt_count); + last_ipi_cnt[i] =READ_ONCE (data->broadcast_ipi_count); + last_wake_cnt[i] =READ_ONCE (data->broadcast_ipi_wake_count); + }else { + last_hlt_cnt[i] =READ_ONCE (data->broadcast_noself_ipi_hlt_count); + last_ipi_cnt[i] =READ_ONCE (data->broadcast_noself_ipi_count); + last_wake_cnt[i] =READ_ONCE (data->broadcast_noself_ipi_wake_count); + } + } + +x2apic_write_reg (APIC_ICR ,APIC_INT_ASSERT | dsh | vec); + + tsc_start =rdtsc (); + +for (i =1 ; i <NR_SAVIC_VCPUS ; i++) { + data = test_data[i]; + +if (dsh ==APIC_DEST_ALLINC ) { + broadcast_ipi_p = &data->broadcast_ipi_count; + broadcast_ipi_hlt_cnt_p = &data->broadcast_ipi_hlt_count; + broadcast_ipi_wake_cnt_p = &data->broadcast_ipi_wake_count; + }else { + broadcast_ipi_p = &data->broadcast_noself_ipi_count; + broadcast_ipi_hlt_cnt_p = &data->broadcast_noself_ipi_hlt_count; + broadcast_ipi_wake_cnt_p = &data->broadcast_noself_ipi_wake_count; + } + +while (rdtsc () - tsc_start <1000000000 ) { +if (READ_ONCE (*broadcast_ipi_wake_cnt_p) != last_wake_cnt[i] && +READ_ONCE (*broadcast_ipi_hlt_cnt_p) != last_hlt_cnt[i] && +READ_ONCE (*broadcast_ipi_p) != last_ipi_cnt[i]) +break ; + } + +__GUEST_ASSERT (READ_ONCE (*broadcast_ipi_wake_cnt_p) != last_wake_cnt[i] && +READ_ONCE (*broadcast_ipi_hlt_cnt_p) != last_hlt_cnt[i] && +READ_ONCE (*broadcast_ipi_p) != last_ipi_cnt[i], +"wakeup_cnt: %ld last_wake_cnt: %ld hlt_count: %ld last_hlt_cnt: %ld b_ipi_count: %ld last_b_ipi_count: %ld" , +READ_ONCE (*broadcast_ipi_wake_cnt_p), last_wake_cnt[i], +READ_ONCE (*broadcast_ipi_hlt_cnt_p), last_hlt_cnt[i], +READ_ONCE (*broadcast_ipi_p), last_ipi_cnt[i]); + + last_wake_cnt[i] =READ_ONCE (*broadcast_ipi_wake_cnt_p); + last_hlt_cnt[i] =READ_ONCE (*broadcast_ipi_hlt_cnt_p); + last_ipi_cnt[i] =READ_ONCE (*broadcast_ipi_p); + } + } +} + +void savic_ipi (int id) +{ +savic_fixed_ipi (false); +savic_fixed_ipi (true); + + asmvolatile ("sti;" :::"memory" ); +x2apic_write_reg (APIC_TASKPRI ,0 ); +savic_send_broadcast (APIC_DEST_ALLINC ); +savic_send_broadcast (APIC_DEST_ALLBUT ); +} + +void guest_fixed_ipi_handler (struct ex_regs *regs) +{ +struct test_data_page *data = test_data[x2apic_read_reg (APIC_ID )]; + +WRITE_ONCE (data->fixed_ipi_count, data->fixed_ipi_count +1 ); +x2apic_write_reg (APIC_EOI ,0x00 ); +} + +void guest_fixed_logical_ipi_handler (struct ex_regs *regs) +{ +struct test_data_page *data = test_data[x2apic_read_reg (APIC_ID )]; + +WRITE_ONCE (data->fixed_logical_ipi_count, data->fixed_logical_ipi_count +1 ); +x2apic_write_reg (APIC_EOI ,0x00 ); +} + +void guest_broadcast_ipi_handler (struct ex_regs *regs) +{ +struct test_data_page *data = test_data[x2apic_read_reg (APIC_ID )]; + +WRITE_ONCE (data->broadcast_ipi_count, data->broadcast_ipi_count +1 ); +x2apic_write_reg (APIC_EOI ,0x00 ); +} + +void guest_broadcast_noself_ipi_handler (struct ex_regs *regs) +{ +struct test_data_page *data = test_data[x2apic_read_reg (APIC_ID )]; + +WRITE_ONCE (data->broadcast_noself_ipi_count, data->broadcast_noself_ipi_count +1 ); +x2apic_write_reg (APIC_EOI ,0x00 ); +} + +static void ipi_guest_code (int id,unsigned long secondary_entry) +{ +struct test_data_page *data; +uint64_t *ipi_count_p, *hlt_count_p, *wake_count_p; +int i; + +x2apic_enable (); + id =x2apic_read_reg (APIC_ID ); + data = test_data[id]; +savic_enable (); +x2apic_write_reg (APIC_TASKPRI ,0 ); + +uint64_t *ipi_count_types[][3 ] = { + { + &data->fixed_ipi_hlt_count, + &data->fixed_ipi_count, + &data->fixed_ipi_wake_count + }, + { + &data->fixed_logical_ipi_hlt_count, + &data->fixed_logical_ipi_count, + &data->fixed_logical_ipi_wake_count + }, + { + &data->broadcast_ipi_hlt_count, + &data->broadcast_ipi_count, + &data->broadcast_ipi_wake_count + }, + { + &data->broadcast_noself_ipi_hlt_count, + &data->broadcast_noself_ipi_count, + &data->broadcast_noself_ipi_wake_count + }, + }; + +for (i =0 ; i <ARRAY_SIZE (ipi_count_types); i++) { + hlt_count_p = ipi_count_types[i][0 ]; + ipi_count_p = ipi_count_types[i][1 ]; + wake_count_p = ipi_count_types[i][2 ]; + +while (READ_ONCE (*ipi_count_p) !=NUM_ITERATIONS ) { + asmvolatile ("cli" ); +WRITE_ONCE (*hlt_count_p, *hlt_count_p +1 ); + asmvolatile ("sti; hlt" : : :"memory" ); +WRITE_ONCE (*wake_count_p, *wake_count_p +1 ); + } + +WRITE_ONCE (*hlt_count_p, *hlt_count_p +1 ); + } + +GUEST_DONE (); +} +static void guest_code (int id) {GUEST_ASSERT (rdmsr (MSR_AMD64_SEV ) &MSR_AMD64_SNP_SECURE_AVIC );
@@ -468,6 +726,8 @@ static void guest_code(int id)SAVIC_GUEST_SYNC (SAVIC_IOAPIC , savic_ioapic);SAVIC_GUEST_SYNC (SAVIC_IOAPIC2 , savic_ioapic2); +SAVIC_GUEST_SYNC (SAVIC_IPI , savic_ipi); +GUEST_DONE (); }
@@ -536,6 +796,11 @@ static void install_exception_handlers(struct kvm_vm *vm)vm_install_exception_handler (vm,IOAPIC_VECTOR_START +2 , ioapic_level_irq1_intr_handler);vm_install_exception_handler (vm,IOAPIC_VECTOR_START +3 , ioapic_level_irq2_intr_handler);vm_install_exception_handler (vm,RTC_GSI_IRQ , ioapic_rtc_gsi_intr_handler); +vm_install_exception_handler (vm,FIXED_IPI_VEC , guest_fixed_ipi_handler); +vm_install_exception_handler (vm,FIXED_LOGICAL_IPI_VEC , guest_fixed_logical_ipi_handler); +vm_install_exception_handler (vm,BROADCAST_ALL_IPI_VEC , guest_broadcast_ipi_handler); +vm_install_exception_handler (vm,BROADCAST_NOSELF_IPI_VEC , + guest_broadcast_noself_ipi_handler); }int main (int argc,char *argv[])
@@ -547,19 +812,28 @@ int main(int argc, char *argv[])vm_vaddr_t test_data_page_vaddr;struct kvm_vm *vm;int i, r; +struct vm_shape shape = { + .mode =VM_MODE_DEFAULT , + .type =KVM_X86_SNP_VM , + };TEST_REQUIRE (kvm_cpu_has (X86_FEATURE_SEV_SNP ));TEST_REQUIRE (kvm_cpu_has (X86_FEATURE_SECURE_AVIC ));TEST_REQUIRE (this_cpu_has (X86_FEATURE_IDLE_HLT )); - vm =_vm_sev_create_with_one_vcpu (KVM_X86_SNP_VM , guest_code, &vcpus[0 ], &args); + vm =__vm_create_with_args (shape,NR_SAVIC_VCPUS ,0 , &args); + + vcpus[0 ] =vm_vcpu_add (vm,0 , guest_code); +for (i =1 ; i <NR_SAVIC_VCPUS ; ++i) + vcpus[i] =vm_vcpu_add (vm, i, ipi_guest_code);virt_pg_map (vm,APIC_DEFAULT_GPA ,APIC_DEFAULT_GPA );virt_pg_map (vm,IOAPIC_DEFAULT_GPA ,IOAPIC_DEFAULT_GPA );install_exception_handlers (vm); -vcpu_args_set (vcpus[0 ],1 , vcpus[0 ]->id); +for (i =0 ; i <NR_SAVIC_VCPUS ; i++) +vcpu_args_set (vcpus[i],1 , vcpus[i]->id);for (i =0 ; i <NR_SAVIC_VCPUS ; i++) { test_data_page_vaddr =vm_vaddr_alloc_page_shared (vm);
@@ -572,10 +846,13 @@ int main(int argc, char *argv[])vm_sev_launch (vm,snp_default_policy (),NULL ); - r =pthread_create (&threads[0 ],NULL , vcpu_thread, vcpus[0 ]); -TEST_ASSERT (r ==0 ,"pthread_create failed errno=%d" , errno); +for (i =0 ; i <NR_SAVIC_VCPUS ; i++) { + r =pthread_create (&threads[i],NULL , vcpu_thread, vcpus[i]); +TEST_ASSERT (r ==0 ,"pthread_create failed errno=%d" , errno); + } -pthread_join (threads[0 ],NULL ); +for (i =0 ; i <NR_SAVIC_VCPUS ; i++) +pthread_join (threads[i],NULL );for (i =0 ; i <NR_SAVIC_VCPUS ; i++) {struct test_data_page *shared_state = shared_data[i];
@@ -583,6 +860,22 @@ int main(int argc, char *argv[])fprintf (stderr,"VCPU %d ioapic edge irq1 count: %ld edge irq2 count: %ld\n" , i, shared_state->ioapic_eirq1_count, shared_state->ioapic_eirq2_count);fprintf (stderr,"VCPU %d ioapic level irq1 count: %ld level irq2 count: %ld\n" , i, shared_state->ioapic_lirq1_count, shared_state->ioapic_lirq2_count);fprintf (stderr,"VCPU %d ioapic RTC GSI irq1 count: %ld\n" , i, shared_state->ioapic_rtc_gsi_irq_count); +fprintf (stderr,"vCPU %d fixed IPI counts wake: %ld hlt: %ld num-IPI: %ld\n" , + i, shared_state->fixed_ipi_wake_count, + shared_state->fixed_ipi_hlt_count, + shared_state->fixed_ipi_count); +fprintf (stderr,"vCPU %d fixed-logical IPI counts wake: %ld hlt: %ld num-IPI: %ld\n" , + i, shared_state->fixed_logical_ipi_wake_count, + shared_state->fixed_logical_ipi_hlt_count, + shared_state->fixed_logical_ipi_count); +fprintf (stderr,"vCPU %d broadcast IPI counts wake: %ld hlt: %ld num-IPI: %ld\n" , + i, shared_state->broadcast_ipi_wake_count, + shared_state->broadcast_ipi_hlt_count, + shared_state->broadcast_ipi_count); +fprintf (stderr,"vCPU %d broadcast exluding self IPI counts wake: %ld hlt: %ld num-IPI: %ld\n" , + i, shared_state->broadcast_noself_ipi_wake_count, + shared_state->broadcast_noself_ipi_hlt_count, + shared_state->broadcast_noself_ipi_count); }kvm_vm_free (vm);
Signature · 1 line
2.34.1
RFC PATCH v2 34/35 KVM: selftests: Add NMI test for SAVIC guests
In reply to Neeraj UpadhyayExtend the Secure AVIC (SAVIC) selftest to validate the handling of Non-Maskable Interrupts (NMIs).
In SAVIC mode, NMI delivery requires explicit coordination between the guest and the hypervisor: the guest must explicitly permit the host to inject NMIs by setting the AllowedNMI bit in the MSR_AMD64_SECURE_AVIC_CONTROL. If this bit is clear, host-injected NMIs are dropped. After handling an NMI, the guest must notify the hypervisor by issuing a VMGEXIT with a new NMI_COMPLETE exit code. This unblocks the hardware's NMI-pending state, allowing subsequent NMIs to be delivered.
ICR-based NMIs : NMIs sent via the Interrupt Command Register (ICR) are handled by the guest's #VC handler, following the same INCOMPLETE_IPI exception path as regular IPIs.
Add a comprehensive set of test cases to savic_test.c to validate this entire flow:
* Verify that a host-injected NMI is correctly dropped when the AllowedNMI bit is clear.
* Test that if a second NMI is injected while one is already pending, it is correctly blocked by the hardware and delivered only after the guest signals completion of the first NMI via the new sev_es_nmi_complete() GHCB call.
* Add tests for cross-vCPU NMIs sent via the ICR, covering all destination modes (fixed-physical, fixed-logical, broadcast-all, and broadcast-excluding-self) to ensure the guest's #VC handler correctly routes them.
--- .../selftests/kvm/include/x86/processor.h | 5 + tools/testing/selftests/kvm/include/x86/sev.h | 1 + tools/testing/selftests/kvm/lib/x86/savic.c | 15 +- tools/testing/selftests/kvm/lib/x86/sev.c | 22 + tools/testing/selftests/kvm/x86/savic_test.c | 388 ++++++++++++++---- 5 files changed, 351 insertions(+), 80 deletions(-)
tools/testing/selftests/kvm/include/x86/processor.h +5 -0
@@ -924,6 +924,11 @@ static inline void vcpu_xcrs_set(struct kvm_vcpu *vcpu, struct kvm_xcrs *xcrs)vcpu_ioctl (vcpu,KVM_SET_XCRS , xcrs); } +static inline void vcpu_nmi (struct kvm_vcpu *vcpu) +{ +vcpu_ioctl (vcpu,KVM_NMI ,NULL ); +} +const struct kvm_cpuid_entry2 *get_cpuid_entry (const struct kvm_cpuid2 *cpuid,uint32_t function,uint32_t index);const struct kvm_cpuid2 *kvm_get_supported_cpuid (void );
tools/testing/selftests/kvm/include/x86/sev.h +1 -0
@@ -172,4 +172,5 @@ void sev_es_vc_handler(struct ex_regs *regs);void sev_es_pv_msr_rw (uint64_t msr,uint64_t *data,bool write);void sev_es_pv_mmio_rw (uint32_t *reg_gpa,uint32_t *data,bool write);void sev_es_savic_notify_gpa (uint64_t gpa); +void sev_es_nmi_complete (void );#endif /* SELFTEST_KVM_SEV_H */
tools/testing/selftests/kvm/lib/x86/savic.c +10 -5
@@ -90,13 +90,15 @@ int savic_nr_pages_required(uint64_t page_size)*/ void set_savic_control_msr (struct guest_apic_page *apic_page,bool enable,bool enable_nmi) { -uint64_t val = apic_page->gpa |BIT_ULL (MSR_AMD64_SECURE_AVIC_EN_BIT ); +uint64_t val;if (!enable) {wrmsr (MSR_AMD64_SECURE_AVIC_CONTROL ,0 );return ; } + val = apic_page->gpa |BIT_ULL (MSR_AMD64_SECURE_AVIC_EN_BIT ); +if (enable_nmi) val |=BIT_ULL (MSR_AMD64_SECURE_AVIC_ALLOWED_NMI_BIT );
@@ -440,15 +442,18 @@ static void savic_handle_icr_write(uint64_t icr_data)bool logical = icr_data &APIC_DEST_LOGICAL ;bool nmi = (icr_data &APIC_DM_FIXED_MASK ) ==APIC_DM_NMI ;uint64_t self_icr_data =APIC_DEST_SELF |APIC_INT_ASSERT | vector; - -if (nmi) - self_icr_data |=APIC_DM_NMI ; +struct guest_apic_page *apic_page;switch (dsh) {case APIC_DEST_ALLINC :savic_send_ipi_all_but (vector, nmi);savic_hv_write_reg (APIC_ICR , icr_data); -x2apic_write_reg (APIC_ICR , self_icr_data); +if (nmi) { + apic_page = &apic_page_pool->guest_apic_page[x2apic_read_reg (APIC_ID )]; +savic_write_reg (apic_page,SAVIC_NMI_REQ_OFFSET ,1 ); + }else { +x2apic_write_reg (APIC_ICR , self_icr_data); + }break ;case APIC_DEST_ALLBUT :savic_send_ipi_all_but (vector, nmi);
tools/testing/selftests/kvm/lib/x86/sev.c +22 -0
@@ -20,6 +20,7 @@#define SVM_VMGEXIT_MMIO_READ 0x80000001#define SVM_VMGEXIT_MMIO_WRITE 0x80000002#define SVM_VMGEXIT_SECURE_AVIC 0x8000001a +#define SVM_VMGEXIT_NMI_COMPLETE 0x80000003struct ghcb_entry {struct ghcb ghcb;
@@ -750,3 +751,24 @@ void sev_es_savic_notify_gpa(uint64_t gpa)__GUEST_ASSERT (!ret,"Secure AVIC GPA notification failed, ret: %d" , ret);ghcb_free (entry); } + +void sev_es_nmi_complete (void ) +{ +struct ghcb_entry *entry; +struct ghcb *ghcb; +int ret; + + entry =ghcb_alloc (); + ghcb = &entry->ghcb; +register_ghcb_page (entry->gpa); + +ghcb_set_sw_exit_code (ghcb,SVM_VMGEXIT_NMI_COMPLETE ); +ghcb_set_sw_exit_info_1 (ghcb,0 ); +ghcb_set_sw_exit_info_2 (ghcb,0 ); + +do_vmg_exit (entry->gpa); + ret = ghcb->save.sw_exit_info_1 &0xffffffff ; +__GUEST_ASSERT (!ret,"NMI completion failed, ret: %d" , ret); + +ghcb_free (entry); +}
tools/testing/selftests/kvm/x86/savic_test.c +313 -75
641 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC PATCH v2 35/35 KVM: selftests: Add MSI injection test for SAVIC
In reply to Neeraj UpadhyayExtend the Secure AVIC (SAVIC) selftest to validate the injection of Message-Signaled Interrupts (MSIs) from the host.
In SAVIC mode, the delivery of external interrupts, including MSIs, requires explicit cooperation from the guest. For an interrupt to be successfully injected by the hardware, the guest must first grant permission by setting the corresponding vector bit in the 'ALLOWED IRR' region of its private APIC backing page. If the vector is not explicitly allowed, the hardware will drop the interrupt.
Add a new test case to Secure AVIC selftest that verifies this permission model for MSIs. Verify that:
1. If the host injects an MSI while the guest has not yet allowed the vector, the interrupt is correctly dropped and not received.
2. The guest then updates the ALLOWED_IRR to permit the MSI vector. When the host injects the same MSI again, the interrupt is successfully delivered and handled.
This two-stage approach provides robust validation of the SAVIC MSI delivery mechanism, ensuring both the blocking and permissive paths work as expected.
--- tools/testing/selftests/kvm/x86/savic_test.c | 49 ++++++++++++++++++++ 1 file changed, 49 insertions(+)
tools/testing/selftests/kvm/x86/savic_test.c +49 -0
@@ -22,6 +22,7 @@#define IOAPIC_NUM_LEVEL_VECTORS 2#define RTC_GSI 8#define RTC_GSI_IRQ 0x85 +#define MSI_VECTOR 0x40#define FIXED_IPI_VEC 0x31#define FIXED_LOGICAL_IPI_VEC 0x32#define BROADCAST_ALL_IPI_VEC 0x33
@@ -40,6 +41,7 @@ enum savic_test_state {SAVIC_TEST_STATE (SAVIC_IDLE_HALT ),SAVIC_TEST_STATE (SAVIC_IOAPIC ),SAVIC_TEST_STATE (SAVIC_IOAPIC2 ), +SAVIC_TEST_STATE (SAVIC_MSI ),SAVIC_TEST_STATE (SAVIC_IPI ),SAVIC_TEST_STATE (SAVIC_NMI ), SAVIC_TEST_STATE(SAVIC_NMI2),
@@ -57,6 +59,7 @@ struct test_data_page {uint64_t ioapic_lirq1_count;uint64_t ioapic_lirq2_count;uint64_t ioapic_rtc_gsi_irq_count; +uint64_t msi_irq_count;uint64_t fixed_phys_ipi_wake_count;uint64_t fixed_phys_ipi_hlt_count;uint64_t fixed_logical_ipi_hlt_count;
@@ -807,6 +810,34 @@ static void guest_nmi_handler(struct ex_regs *regs)sev_es_nmi_complete (); } +static void savic_msi_not_allowed (int id) +{ +struct test_data_page *data =get_test_data (); + +savic_allow_vector (MSI_VECTOR ); + +__GUEST_ASSERT (READ_ONCE (data->msi_irq_count) ==0 , +"Invalid MSI IRQ count: %ld, should be 0" , +READ_ONCE (data->msi_irq_count)); +} + +static void savic_msi_allowed (int id) +{ +struct test_data_page *data =get_test_data (); + +__GUEST_ASSERT (READ_ONCE (data->msi_irq_count) ==1 , +"Invalid MSI IRQ count: %ld" , +READ_ONCE (data->msi_irq_count)); +} + +static void msi_intr_handler (struct ex_regs *regs) +{ +struct test_data_page *data =get_test_data (); + +WRITE_ONCE (data->msi_irq_count, data->msi_irq_count +1 ); +x2apic_write_reg (APIC_EOI ,0x00 ); +} +static void ipi_guest_code (int id) {struct test_data_page *data;
@@ -901,6 +932,9 @@ static void guest_code(int id)SAVIC_GUEST_SYNC (SAVIC_IOAPIC , savic_ioapic);SAVIC_GUEST_SYNC (SAVIC_IOAPIC2 , savic_ioapic2); +SAVIC_GUEST_SYNC (SAVIC_MSI , savic_msi_not_allowed); +SAVIC_GUEST_SYNC (SAVIC_MSI , savic_msi_allowed); +SAVIC_GUEST_SYNC (SAVIC_IPI , savic_ipi);/* Disable host NMI injection in control MSR. */
@@ -953,6 +987,17 @@ static void host_send_ioapic_irq(struct kvm_vm *vm, int id)kvm_irq_line_status (vm,RTC_GSI ,0 ); } +static void host_send_msi (struct kvm_vm *vm) +{ +struct kvm_msi msi = { + .address_lo =0 , + .address_hi =0 , + .data =MSI_VECTOR , + }; + +__vm_ioctl (vm,KVM_SIGNAL_MSI , &msi); +} +static void host_send_nmi (int id) {vcpu_nmi (vcpus[id]);
@@ -968,6 +1013,9 @@ static void host_test_savic(struct kvm_vm *vm, int id, enum savic_test_state tescase SAVIC_IOAPIC2_START :host_send_ioapic_irq (vm, id);break ; +case SAVIC_MSI_START : +host_send_msi (vm); +break ;case SAVIC_NMI_START :case SAVIC_NMI2_START :case SAVIC_NMI3_START :
@@ -1021,6 +1069,7 @@ static void install_exception_handlers(struct kvm_vm *vm)vm_install_exception_handler (vm,BROADCAST_NOSELF_IPI_VEC , guest_broadcast_noself_ipi_handler);vm_install_exception_handler (vm,NMI_VECTOR , guest_nmi_handler); +vm_install_exception_handler (vm,MSI_VECTOR , msi_intr_handler); }int main (int argc,char *argv[])
Signature · 1 line
2.34.1