[PATCH v12 03/23] KVM: selftests: Expose functions to get default sregs values

Sagi Shahar
2025-10-28T21:20:59Z

TDX can't set sregs values directly using KVM_SET_SREGS. Expose the
default values of certain sregs used by TDX VMs so they can be set
manually.

Reviewed-by: Binbin Wu <binbin.wu@linux.intel.com>
Signed-off-by: Sagi Shahar <sagis@google.com>
---
.../selftests/kvm/include/x86/processor.h | 33 +++++++++++++++++++
.../testing/selftests/kvm/lib/x86/processor.c | 12 +++----
2 files changed, 38 insertions(+), 7 deletions(-)

diff --git a/tools/testing/selftests/kvm/include/x86/processor.h b/tools/testing/selftests/kvm/include/x86/processor.h
index dd21e11e1908..9caeb3de7df6 100644
--- a/tools/testing/selftests/kvm/include/x86/processor.h
+++ b/tools/testing/selftests/kvm/include/x86/processor.h
@@ -27,6 +27,10 @@ extern uint64_t guest_tsc_khz;
#define MAX_NR_CPUID_ENTRIES 100
#endif

+#ifndef NUM_INTERRUPTS
+#define NUM_INTERRUPTS 256
+#endif
+
#define NONCANONICAL 0xaaaaaaaaaaaaaaaaull

/* Forced emulation prefix, used to invoke the emulator unconditionally. */
@@ -1498,4 +1502,33 @@ void virt_map_level(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,

bool sys_clocksource_is_based_on_tsc(void);

+static inline uint16_t kvm_get_default_idt_limit(void)
+{
+ return NUM_INTERRUPTS * sizeof(struct idt_entry) - 1;
+}
+
+static inline uint16_t kvm_get_default_gdt_limit(void)
+{
+ return getpagesize() - 1;
+}
+
+static inline uint64_t kvm_get_default_cr0(void)
+{
+ return X86_CR0_PE | X86_CR0_NE | X86_CR0_PG;
+}
+
+static inline uint64_t kvm_get_default_cr4(void)
+{
+ uint64_t cr4 = X86_CR4_PAE | X86_CR4_OSFXSR;
+
+ if (kvm_cpu_has(X86_FEATURE_XSAVE))
+ cr4 |= X86_CR4_OSXSAVE;
+ return cr4;
+}
+
+static inline uint64_t kvm_get_default_efer(void)
+{
+ return EFER_LME | EFER_LMA | EFER_NX;
+}
+
#endif /* SELFTEST_KVM_PROCESSOR_H */
diff --git a/tools/testing/selftests/kvm/lib/x86/processor.c b/tools/testing/selftests/kvm/lib/x86/processor.c
index b418502c5ecc..2d1544e8af6c 100644
--- a/tools/testing/selftests/kvm/lib/x86/processor.c
+++ b/tools/testing/selftests/kvm/lib/x86/processor.c
@@ -532,15 +532,13 @@ static void vcpu_init_sregs(struct kvm_vm *vm, struct kvm_vcpu *vcpu)
vcpu_sregs_get(vcpu, &sregs);

sregs.idt.base = vm->arch.idt;
- sregs.idt.limit = NUM_INTERRUPTS * sizeof(struct idt_entry) - 1;
+ sregs.idt.limit = kvm_get_default_idt_limit();
sregs.gdt.base = vm->arch.gdt;
- sregs.gdt.limit = getpagesize() - 1;
+ sregs.gdt.limit = kvm_get_default_gdt_limit();

- sregs.cr0 = X86_CR0_PE | X86_CR0_NE | X86_CR0_PG;
- sregs.cr4 |= X86_CR4_PAE | X86_CR4_OSFXSR;
- if (kvm_cpu_has(X86_FEATURE_XSAVE))
- sregs.cr4 |= X86_CR4_OSXSAVE;
- sregs.efer |= (EFER_LME | EFER_LMA | EFER_NX);
+ sregs.cr0 = kvm_get_default_cr0();
+ sregs.cr4 |= kvm_get_default_cr4();
+ sregs.efer |= kvm_get_default_efer();

kvm_seg_set_unusable(&sregs.ldt);
kvm_seg_set_kernel_code_64bit(&sregs.cs);
--
2.51.1.851.g4ebd6896fd-goog