KVM TDX basic feature support
Subsystems (17)
PATCH v7 79/102 KVM: TDX: Implement methods to inject NMI
In reply to [email protected]From: Isaku Yamahata <[email protected]>
TDX vcpu control structure defines one bit for pending NMI for VMM to inject NMI by setting the bit without knowing TDX vcpu NMI states. Because the vcpu state is protected, VMM can't know about NMI states of TDX vcpu. The TDX module handles actual injection and NMI states transition.
Add methods for NMI and treat NMI can be injected always.
--- arch/x86/kvm/vmx/main.c | 62 +++++++++++++++++++++++++++++++++++--- arch/x86/kvm/vmx/tdx.c | 5 +++ arch/x86/kvm/vmx/x86_ops.h | 2 ++ 3 files changed, 64 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/main.c +57 -5
@@ -247,6 +247,58 @@ static void vt_flush_tlb_guest(struct kvm_vcpu *vcpu)vmx_flush_tlb_guest (vcpu); } +static void vt_inject_nmi (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return tdx_inject_nmi (vcpu); + +vmx_inject_nmi (vcpu); +} + +static int vt_nmi_allowed (struct kvm_vcpu *vcpu,bool for_injection) +{ +/* +* The TDX module manages NMI windows and NMI reinjection, and hides NMI +* blocking, all KVM can do is throw an NMI over the wall. +*/ +if (is_td_vcpu (vcpu)) +return true; + +return vmx_nmi_allowed (vcpu, for_injection); +} + +static bool vt_get_nmi_mask (struct kvm_vcpu *vcpu) +{ +/* +* Assume NMIs are always unmasked. KVM could query PEND_NMI and treat +* NMIs as masked if a previous NMI is still pending, but SEAMCALLs are +* expensive and the end result is unchanged as the only relevant usage +* of get_nmi_mask() is to limit the number of pending NMIs, i.e. it +* only changes whether KVM or the TDX module drops an NMI. +*/ +if (is_td_vcpu (vcpu)) +return false; + +return vmx_get_nmi_mask (vcpu); +} + +static void vt_set_nmi_mask (struct kvm_vcpu *vcpu,bool masked) +{ +if (is_td_vcpu (vcpu)) +return ; + +vmx_set_nmi_mask (vcpu, masked); +} + +static void vt_enable_nmi_window (struct kvm_vcpu *vcpu) +{ +/* Refer the comment in vt_get_nmi_mask(). */ +if (is_td_vcpu (vcpu)) +return ; + +vmx_enable_nmi_window (vcpu); +} +static void vt_load_mmu_pgd (struct kvm_vcpu *vcpu,hpa_t root_hpa,int pgd_level) {
@@ -399,14 +451,14 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .get_interrupt_shadow = vt_get_interrupt_shadow, .patch_hypercall = vmx_patch_hypercall, .inject_irq = vt_inject_irq, - .inject_nmi = vmx_inject_nmi, + .inject_nmi = vt_inject_nmi, .queue_exception = vmx_queue_exception, .cancel_injection = vt_cancel_injection, .interrupt_allowed = vt_interrupt_allowed, - .nmi_allowed = vmx_nmi_allowed, - .get_nmi_mask = vmx_get_nmi_mask, - .set_nmi_mask = vmx_set_nmi_mask, - .enable_nmi_window = vmx_enable_nmi_window, + .nmi_allowed = vt_nmi_allowed, + .get_nmi_mask = vt_get_nmi_mask, + .set_nmi_mask = vt_set_nmi_mask, + .enable_nmi_window = vt_enable_nmi_window, .enable_irq_window = vt_enable_irq_window, .update_cr8_intercept = vmx_update_cr8_intercept, .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
arch/x86/kvm/vmx/tdx.c +5 -0
@@ -815,6 +815,11 @@ fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)return EXIT_FASTPATH_NONE ; } +void tdx_inject_nmi (struct kvm_vcpu *vcpu) +{ +td_management_write8 (to_tdx (vcpu),TD_VCPU_PEND_NMI ,1 ); +} +void tdx_load_mmu_pgd (struct kvm_vcpu *vcpu,hpa_t root_hpa,int pgd_level) {td_vmcs_write64 (to_tdx (vcpu),SHARED_EPT_POINTER , root_hpa &PAGE_MASK );
arch/x86/kvm/vmx/x86_ops.h +2 -0
@@ -150,6 +150,7 @@ bool tdx_protected_apic_has_interrupt(struct kvm_vcpu *vcpu);void tdx_deliver_interrupt (struct kvm_lapic *apic,int delivery_mode,int trig_mode,int vector); +void tdx_inject_nmi (struct kvm_vcpu *vcpu);int tdx_vm_ioctl (struct kvm *kvm,void __user *argp);int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp);
@@ -180,6 +181,7 @@ static inline bool tdx_protected_apic_has_interrupt(struct kvm_vcpu *vcpu) { retstatic inline void tdx_deliver_interrupt (struct kvm_lapic *apic,int delivery_mode,int trig_mode,int vector) {} +static inline void tdx_inject_nmi (struct kvm_vcpu *vcpu) {}static inline int tdx_vm_ioctl (struct kvm *kvm,void __user *argp) {return -EOPNOTSUPP ; }static inline int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp) {return -EOPNOTSUPP ; }
Signature · 1 line
2.25.1
PATCH v7 80/102 KVM: VMX: Modify NMI and INTR handlers to take intr_info as function argument
In reply to [email protected]From: Sean Christopherson <[email protected]>
TDX uses different ABI to get information about VM exit. Pass intr_info to the NMI and INTR handlers instead of pulling it from vcpu_vmx in preparation for sharing the bulk of the handlers with TDX.
When the guest TD exits to VMM, RAX holds status and exit reason, RCX holds exit qualification etc rather than the VMCS fields because VMM doesn't have access to the VMCS. The eventual code will be
VMX:
- get exit reason, intr_info, exit_qualification, and etc from VMCS
- call NMI/INTR handlers (common code)
TDX:
- get exit reason, intr_info, exit_qualification, and etc from guest registers
- call NMI/INTR handlers (common code)
--- arch/x86/kvm/vmx/vmx.c | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
arch/x86/kvm/vmx/vmx.c +8 -9
@@ -6677,28 +6677,27 @@ static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)rdmsrl (MSR_IA32_XFD_ERR , vcpu->arch.guest_fpu.xfd_err); } -static void handle_exception_nmi_irqoff (struct vcpu_vmx *vmx) +static void handle_exception_nmi_irqoff (struct kvm_vcpu *vcpu,u32 intr_info) {const unsigned long nmi_entry = (unsigned long )asm_exc_nmi_noist; -u32 intr_info =vmx_get_intr_info (&vmx->vcpu);/* if exit due to PF check for async PF */ if (is_page_fault (intr_info)) - vmx->vcpu.arch.apf.host_apf_flags =kvm_read_and_reset_apf_flags (); + vcpu->arch.apf.host_apf_flags =kvm_read_and_reset_apf_flags ();/* if exit due to NM, handle before interrupts are enabled */ else if (is_nm_fault (intr_info)) -handle_nm_fault_irqoff (&vmx->vcpu); +handle_nm_fault_irqoff (vcpu);/* Handle machine checks before interrupts are enabled */ else if (is_machine_check (intr_info))kvm_machine_check ();/* We need to handle NMIs before interrupts are enabled */ else if (is_nmi (intr_info)) -handle_interrupt_nmi_irqoff (&vmx->vcpu, nmi_entry); +handle_interrupt_nmi_irqoff (vcpu, nmi_entry); } -static void handle_external_interrupt_irqoff (struct kvm_vcpu *vcpu) +static void handle_external_interrupt_irqoff (struct kvm_vcpu *vcpu, +u32 intr_info) { -u32 intr_info =vmx_get_intr_info (vcpu);unsigned int vector = intr_info &INTR_INFO_VECTOR_MASK ;gate_desc *desc = (gate_desc *)host_idt_base + vector;
@@ -6718,9 +6717,9 @@ void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)return ;if (vmx->exit_reason.basic ==EXIT_REASON_EXTERNAL_INTERRUPT ) -handle_external_interrupt_irqoff (vcpu); +handle_external_interrupt_irqoff (vcpu,vmx_get_intr_info (vcpu));else if (vmx->exit_reason.basic ==EXIT_REASON_EXCEPTION_NMI ) -handle_exception_nmi_irqoff (vmx); +handle_exception_nmi_irqoff (vcpu,vmx_get_intr_info (vcpu)); }/*
Signature · 1 line
2.25.1
PATCH v7 81/102 KVM: VMX: Move NMI/exception handler to common helper
In reply to [email protected]From: Sean Christopherson <[email protected]>
TDX mostly handles NMI/exception exit mostly the same to VMX case. The difference is how to retrieve exit qualification. To share the code with TDX, move NMI/exception to a common header, common.h.
--- arch/x86/kvm/vmx/common.h | 70 ++++++++++++++++++++++++++++++++++ arch/x86/kvm/vmx/vmx.c | 79 ++++----------------------------------- 2 files changed, 78 insertions(+), 71 deletions(-)
arch/x86/kvm/vmx/common.h +70 -0
@@ -4,8 +4,78 @@#include <linux/kvm_host.h> +#include <asm/traps.h> +#include "posted_intr.h" #include "mmu.h" +#include "vmcs.h" +#include "x86.h" + +extern unsigned long vmx_host_idt_base; +void vmx_do_interrupt_nmi_irqoff (unsigned long entry); + +static inline void vmx_handle_interrupt_nmi_irqoff (struct kvm_vcpu *vcpu, +unsigned long entry) +{ +bool is_nmi = entry == (unsigned long )asm_exc_nmi_noist; + +kvm_before_interrupt (vcpu, is_nmi ?KVM_HANDLING_NMI :KVM_HANDLING_IRQ ); +vmx_do_interrupt_nmi_irqoff (entry); +kvm_after_interrupt (vcpu); +} + +static inline void vmx_handle_nm_fault_irqoff (struct kvm_vcpu *vcpu) +{ +/* +* Save xfd_err to guest_fpu before interrupt is enabled, so the +* MSR value is not clobbered by the host activity before the guest +* has chance to consume it. +* +* Do not blindly read xfd_err here, since this exception might +* be caused by L1 interception on a platform which doesn't +* support xfd at all. +* +* Do it conditionally upon guest_fpu::xfd. xfd_err matters +* only when xfd contains a non-zero value. +* +* Queuing exception is done in vmx_handle_exit. See comment there. +*/ +if (vcpu->arch.guest_fpu.fpstate->xfd) +rdmsrl (MSR_IA32_XFD_ERR , vcpu->arch.guest_fpu.xfd_err); +} + +static inline void vmx_handle_exception_nmi_irqoff (struct kvm_vcpu *vcpu, +u32 intr_info) +{ +const unsigned long nmi_entry = (unsigned long )asm_exc_nmi_noist; + +/* if exit due to PF check for async PF */ +if (is_page_fault (intr_info)) + vcpu->arch.apf.host_apf_flags =kvm_read_and_reset_apf_flags (); +/* if exit due to NM, handle before interrupts are enabled */ +else if (is_nm_fault (intr_info)) +vmx_handle_nm_fault_irqoff (vcpu); +/* Handle machine checks before interrupts are enabled */ +else if (is_machine_check (intr_info)) +kvm_machine_check (); +/* We need to handle NMIs before interrupts are enabled */ +else if (is_nmi (intr_info)) +vmx_handle_interrupt_nmi_irqoff (vcpu, nmi_entry); +} + +static inline void vmx_handle_external_interrupt_irqoff (struct kvm_vcpu *vcpu, +u32 intr_info) +{ +unsigned int vector = intr_info &INTR_INFO_VECTOR_MASK ; +gate_desc *desc = (gate_desc *)vmx_host_idt_base + vector; + +if (KVM_BUG (!is_external_intr (intr_info), vcpu->kvm, +"KVM: unexpected VM-Exit interrupt info: 0x%x" , intr_info)) +return ; + +vmx_handle_interrupt_nmi_irqoff (vcpu,gate_offset (desc)); + vcpu->arch.at_instruction_boundary = true; +}static inline int __vmx_handle_ept_violation (struct kvm_vcpu *vcpu,gpa_t gpa,unsigned long exit_qualification)
arch/x86/kvm/vmx/vmx.c +8 -71
118 lines not on this page · raw message
Signature · 1 line
2.25.1
PATCH v7 82/102 KVM: x86: Split core of hypercall emulation to helper function
In reply to [email protected]From: Sean Christopherson <[email protected]>
By necessity, TDX will use a different register ABI for hypercalls. Break out the core functionality so that it may be reused for TDX.
--- arch/x86/include/asm/kvm_host.h | 4 +++ arch/x86/kvm/x86.c | 54 ++++++++++++++++++++------------- 2 files changed, 37 insertions(+), 21 deletions(-)
arch/x86/include/asm/kvm_host.h +4 -0
@@ -1948,6 +1948,10 @@ static inline void kvm_clear_apicv_inhibit(struct kvm *kvm,kvm_set_or_clear_apicv_inhibit (kvm, reason, false); } +unsigned long __kvm_emulate_hypercall (struct kvm_vcpu *vcpu,unsigned long nr, +unsigned long a0,unsigned long a1, +unsigned long a2,unsigned long a3, +int op_64_bit);int kvm_emulate_hypercall (struct kvm_vcpu *vcpu); int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
arch/x86/kvm/x86.c +33 -21
76 lines not on this page · raw message
Signature · 1 line
2.25.1
PATCH v7 83/102 KVM: TDX: Add a place holder to handle TDX VM exit
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Wire up handle_exit and handle_exit_irqoff methods and add a place holder to handle VM exit. Add helper functions to get exit info, exit qualification, etc.
--- arch/x86/kvm/vmx/main.c | 33 ++++++++++++++-- arch/x86/kvm/vmx/tdx.c | 81 ++++++++++++++++++++++++++++++++++++++ arch/x86/kvm/vmx/x86_ops.h | 11 ++++++ 3 files changed, 122 insertions(+), 3 deletions(-)
arch/x86/kvm/vmx/main.c +30 -3
@@ -188,6 +188,23 @@ static bool vt_protected_apic_has_interrupt(struct kvm_vcpu *vcpu)return tdx_protected_apic_has_interrupt (vcpu); } +static int vt_handle_exit (struct kvm_vcpu *vcpu, +enum exit_fastpath_completion fastpath) +{ +if (is_td_vcpu (vcpu)) +return tdx_handle_exit (vcpu, fastpath); + +return vmx_handle_exit (vcpu, fastpath); +} + +static void vt_handle_exit_irqoff (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return tdx_handle_exit_irqoff (vcpu); + +vmx_handle_exit_irqoff (vcpu); +} +static void vt_apicv_post_state_restore (struct kvm_vcpu *vcpu) {struct pi_desc *pi =vcpu_to_pi_desc (vcpu);
@@ -371,6 +388,16 @@ static void vt_request_immediate_exit(struct kvm_vcpu *vcpu)vmx_request_immediate_exit (vcpu); } +static void vt_get_exit_info (struct kvm_vcpu *vcpu,u32 *reason, +u64 *info1,u64 *info2,u32 *intr_info,u32 *error_code) +{ +if (is_td_vcpu (vcpu)) +return tdx_get_exit_info (vcpu, reason, info1, info2, intr_info, + error_code); + +return vmx_get_exit_info (vcpu, reason, info1, info2, intr_info, error_code); +} +static int vt_mem_enc_ioctl (struct kvm *kvm,void __user *argp) {if (!is_td (kvm))
@@ -444,7 +471,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .vcpu_pre_run = vt_vcpu_pre_run, .vcpu_run = vt_vcpu_run, - .handle_exit = vmx_handle_exit, + .handle_exit = vt_handle_exit, .skip_emulated_instruction = vmx_skip_emulated_instruction, .update_emulated_instruction = vmx_update_emulated_instruction, .set_interrupt_shadow = vt_set_interrupt_shadow,
@@ -479,7 +506,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .set_identity_map_addr = vmx_set_identity_map_addr, .get_mt_mask = vmx_get_mt_mask, - .get_exit_info = vmx_get_exit_info, + .get_exit_info = vt_get_exit_info, .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
@@ -493,7 +520,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .load_mmu_pgd = vt_load_mmu_pgd, .check_intercept = vmx_check_intercept, - .handle_exit_irqoff = vmx_handle_exit_irqoff, + .handle_exit_irqoff = vt_handle_exit_irqoff, .request_immediate_exit = vt_request_immediate_exit,
arch/x86/kvm/vmx/tdx.c +81 -0
99 lines not on this page · raw message
arch/x86/kvm/vmx/x86_ops.h +11 -0
@@ -147,10 +147,15 @@ void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu);void tdx_vcpu_put (struct kvm_vcpu *vcpu);void tdx_vcpu_load (struct kvm_vcpu *vcpu,int cpu);bool tdx_protected_apic_has_interrupt (struct kvm_vcpu *vcpu); +void tdx_handle_exit_irqoff (struct kvm_vcpu *vcpu); +int tdx_handle_exit (struct kvm_vcpu *vcpu, +enum exit_fastpath_completion fastpath);void tdx_deliver_interrupt (struct kvm_lapic *apic,int delivery_mode,int trig_mode,int vector);void tdx_inject_nmi (struct kvm_vcpu *vcpu); +void tdx_get_exit_info (struct kvm_vcpu *vcpu,u32 *reason, +u64 *info1,u64 *info2,u32 *intr_info,u32 *error_code);int tdx_vm_ioctl (struct kvm *kvm,void __user *argp);int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp);
@@ -178,10 +183,16 @@ static inline void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu) {}static inline void tdx_vcpu_put (struct kvm_vcpu *vcpu) {}static inline void tdx_vcpu_load (struct kvm_vcpu *vcpu,int cpu) {}static inline bool tdx_protected_apic_has_interrupt (struct kvm_vcpu *vcpu) {return false; } +static inline void tdx_handle_exit_irqoff (struct kvm_vcpu *vcpu) {} +static inline int tdx_handle_exit (struct kvm_vcpu *vcpu, +enum exit_fastpath_completion fastpath) {return 0 ; }static inline void tdx_deliver_interrupt (struct kvm_lapic *apic,int delivery_mode,int trig_mode,int vector) {}static inline void tdx_inject_nmi (struct kvm_vcpu *vcpu) {} +static inline void tdx_get_exit_info ( +struct kvm_vcpu *vcpu,u32 *reason,u64 *info1,u64 *info2, +u32 *intr_info,u32 *error_code) {}static inline int tdx_vm_ioctl (struct kvm *kvm,void __user *argp) {return -EOPNOTSUPP ; }static inline int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp) {return -EOPNOTSUPP ; }
Signature · 1 line
2.25.1
PATCH v7 84/102 KVM: TDX: handle EXIT_REASON_OTHER_SMI
In reply to [email protected]From: Isaku Yamahata <[email protected]>
If the control reaches EXIT_REASON_OTHER_SMI, #SMI is delivered and handled right after returning from the TDX module to KVM nothing needs to be done in KVM. Continue TDX vcpu execution.
--- arch/x86/include/uapi/asm/vmx.h | 1 + arch/x86/kvm/vmx/tdx.c | 7 +++++++ 2 files changed, 8 insertions(+)
arch/x86/include/uapi/asm/vmx.h +1 -0
@@ -34,6 +34,7 @@#define EXIT_REASON_TRIPLE_FAULT 2#define EXIT_REASON_INIT_SIGNAL 3#define EXIT_REASON_SIPI_SIGNAL 4 +#define EXIT_REASON_OTHER_SMI 6#define EXIT_REASON_INTERRUPT_WINDOW 7#define EXIT_REASON_NMI_WINDOW 8
arch/x86/kvm/vmx/tdx.c +7 -0
@@ -1209,6 +1209,13 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)WARN_ON_ONCE (fastpath !=EXIT_FASTPATH_NONE );switch (exit_reason.basic) { +case EXIT_REASON_OTHER_SMI : +/* +* If reach here, it's not a Machine Check System Management +* Interrupt(MSMI). #SMI is delivered and handled right after +* SEAMRET, nothing needs to be done in KVM. +*/ +return 1 ;default :break ; }
Signature · 1 line
2.25.1
PATCH v7 85/102 KVM: TDX: handle ept violation/misconfig exit
In reply to [email protected]From: Isaku Yamahata <[email protected]>
On EPT violation, call a common function, __vmx_handle_ept_violation() to trigger x86 MMU code. On EPT misconfiguration, exit to ring 3 with KVM_EXIT_UNKNOWN. because EPT misconfiguration can't happen as MMIO is trigged by TDG.VP.VMCALL. No point to set a misconfiguration value for the fast path.
--- arch/x86/kvm/vmx/tdx.c | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+)
arch/x86/kvm/vmx/tdx.c +46 -0
@@ -1191,6 +1191,48 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,__vmx_deliver_posted_interrupt (vcpu, &tdx->pi_desc, vector); } +static int tdx_handle_ept_violation (struct kvm_vcpu *vcpu) +{ +unsigned long exit_qual; + +if (kvm_is_private_gpa (vcpu->kvm,tdexit_gpa (vcpu))) { +/* +* Always treat SEPT violations as write faults. Ignore the +* EXIT_QUALIFICATION reported by TDX-SEAM for SEPT violations. +* TD private pages are always RWX in the SEPT tables, +* i.e. they're always mapped writable. Just as importantly, +* treating SEPT violations as write faults is necessary to +* avoid COW allocations, which will cause TDAUGPAGE failures +* due to aliasing a single HPA to multiple GPAs. +*/ +#define TDX_SEPT_VIOLATION_EXIT_QUAL EPT_VIOLATION_ACC_WRITE + exit_qual =TDX_SEPT_VIOLATION_EXIT_QUAL ; + }else { + exit_qual =tdexit_exit_qual (vcpu);; +if (exit_qual &EPT_VIOLATION_ACC_INSTR ) { +pr_warn ("kvm: TDX instr fetch to shared GPA = 0x%lx @ RIP = 0x%lx\n" , +tdexit_gpa (vcpu),kvm_rip_read (vcpu)); + vcpu->run->exit_reason =KVM_EXIT_EXCEPTION ; + vcpu->run->ex.exception =PF_VECTOR ; + vcpu->run->ex.error_code = exit_qual; +return 0 ; + } + } + +trace_kvm_page_fault (tdexit_gpa (vcpu), exit_qual); +return __vmx_handle_ept_violation (vcpu,tdexit_gpa (vcpu), exit_qual); +} + +static int tdx_handle_ept_misconfig (struct kvm_vcpu *vcpu) +{ +WARN_ON (1 ); + + vcpu->run->exit_reason =KVM_EXIT_UNKNOWN ; + vcpu->run->hw.hardware_exit_reason =EXIT_REASON_EPT_MISCONFIG ; + +return 0 ; +} +int tdx_handle_exit (struct kvm_vcpu *vcpu,fastpath_t fastpath) {union tdx_exit_reason exit_reason =to_tdx (vcpu)->exit_reason;
@@ -1209,6 +1251,10 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)WARN_ON_ONCE (fastpath !=EXIT_FASTPATH_NONE );switch (exit_reason.basic) { +case EXIT_REASON_EPT_VIOLATION : +return tdx_handle_ept_violation (vcpu); +case EXIT_REASON_EPT_MISCONFIG : +return tdx_handle_ept_misconfig (vcpu);case EXIT_REASON_OTHER_SMI :/* * If reach here, it's not a Machine Check System Management
Signature · 1 line
2.25.1
PATCH v7 86/102 KVM: TDX: handle EXCEPTION_NMI and EXTERNAL_INTERRUPT
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Because guest TD state is protected, exceptions in guest TDs can't be intercepted. TDX VMM doesn't need to handle exceptions. tdx_handle_exit_irqoff() handles NMI and machine check. Ignore NMI and machine check and continue guest TD execution.
For external interrupt, increment stats same to the VMX case.
--- arch/x86/kvm/vmx/tdx.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)
arch/x86/kvm/vmx/tdx.c +23 -0
@@ -852,6 +852,25 @@ void tdx_handle_exit_irqoff(struct kvm_vcpu *vcpu) tdexit_intr_info(vcpu)); } +static int tdx_handle_exception (struct kvm_vcpu *vcpu) +{ +u32 intr_info =tdexit_intr_info (vcpu); + +if (is_nmi (intr_info) ||is_machine_check (intr_info)) +return 1 ; + +kvm_pr_unimpl ("unexpected exception 0x%x(exit_reason 0x%llx qual 0x%lx)\n" , + intr_info, +to_tdx (vcpu)->exit_reason.full,tdexit_exit_qual (vcpu)); +return -EFAULT ; +} + +static int tdx_handle_external_interrupt (struct kvm_vcpu *vcpu) +{ + ++vcpu->stat.irq_exits; +return 1 ; +} +static int tdx_handle_triple_fault (struct kvm_vcpu *vcpu) { vcpu->run->exit_reason =KVM_EXIT_SHUTDOWN ;
@@ -1251,6 +1270,10 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)WARN_ON_ONCE (fastpath !=EXIT_FASTPATH_NONE );switch (exit_reason.basic) { +case EXIT_REASON_EXCEPTION_NMI : +return tdx_handle_exception (vcpu); +case EXIT_REASON_EXTERNAL_INTERRUPT : +return tdx_handle_external_interrupt (vcpu);case EXIT_REASON_EPT_VIOLATION :return tdx_handle_ept_violation (vcpu);case EXIT_REASON_EPT_MISCONFIG :
Signature · 1 line
2.25.1
PATCH v7 87/102 KVM: TDX: Add a place holder for handler of TDX hypercalls (TDG.VP.VMCALL)
In reply to [email protected]From: Isaku Yamahata <[email protected]>
The TDX module specification defines TDG.VP.VMCALL API (TDVMCALL for short) for the guest TD to call hypercall to VMM. When the guest TD issues TDG.VP.VMCALL, the guest TD exits to VMM with a new exit reason of TDVMCALL. The arguments from the guest TD and returned values from the VMM are passed in the guest registers. The guest RCX registers indicates which registers are used. Define helper functions to access those registers as ABI.
Define the TDVMCALL exit reason, which is carved out from the VMX exit reason namespace as the TDVMCALL exit from TDX guest to TDX-SEAM is really just a VM-Exit. Add a place holder to handle TDVMCALL exit.
--- arch/x86/include/uapi/asm/vmx.h | 4 ++- arch/x86/kvm/vmx/tdx.c | 56 ++++++++++++++++++++++++++++++++- arch/x86/kvm/vmx/tdx.h | 13 ++++++++ 3 files changed, 71 insertions(+), 2 deletions(-)
arch/x86/include/uapi/asm/vmx.h +3 -1
@@ -93,6 +93,7 @@#define EXIT_REASON_TPAUSE 68#define EXIT_REASON_BUS_LOCK 74#define EXIT_REASON_NOTIFY 75 +#define EXIT_REASON_TDCALL 77#define VMX_EXIT_REASONS \ { EXIT_REASON_EXCEPTION_NMI, "EXCEPTION_NMI" }, \
@@ -156,7 +157,8 @@ { EXIT_REASON_UMWAIT, "UMWAIT" }, \ { EXIT_REASON_TPAUSE, "TPAUSE" }, \ { EXIT_REASON_BUS_LOCK, "BUS_LOCK" }, \ - { EXIT_REASON_NOTIFY, "NOTIFY" } + { EXIT_REASON_NOTIFY, "NOTIFY" }, \ + { EXIT_REASON_TDCALL, "TDCALL" } #define VMX_EXIT_REASON_FLAGS \ { VMX_EXIT_REASONS_FAILED_VMENTRY, "FAILED_VMENTRY" }
arch/x86/kvm/vmx/tdx.c +55 -1
86 lines not on this page · raw message
arch/x86/kvm/vmx/tdx.h +13 -0
@@ -95,6 +95,19 @@ struct vcpu_tdx {struct list_head cpu_list; +union { +struct { +union { +struct { +u16 gpr_mask; +u16 xmm_mask; + }; +u32 regs_mask; + }; +u32 reserved; + }; +u64 rcx; + } tdvmcall;union tdx_exit_reason exit_reason;bool initialized;
Signature · 1 line
2.25.1
PATCH v7 88/102 KVM: TDX: handle KVM hypercall with TDG.VP.VMCALL
In reply to [email protected]From: Isaku Yamahata <[email protected]>
The TDX Guest-Host communication interface (GHCI) specification defines
the ABI for the guest TD to issue hypercall. It reserves vendor specific
arguments for VMM specific use. Use it as KVM hypercall and handle it.
--- arch/x86/kvm/vmx/tdx.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)
arch/x86/kvm/vmx/tdx.c +31 -0
@@ -919,8 +919,39 @@ static int tdx_handle_triple_fault(struct kvm_vcpu *vcpu)return 0 ; } +static int tdx_emulate_vmcall (struct kvm_vcpu *vcpu) +{ +unsigned long nr, a0, a1, a2, a3, ret; + +/* +* ABI for KVM tdvmcall argument: +* In Guest-Hypervisor Communication Interface(GHCI) specification, +* Non-zero leaf number (R10 != 0) is defined to indicate +* vendor-specific. KVM uses this for KVM hypercall. NOTE: KVM +* hypercall number starts from one. Zero isn't used for KVM hypercall +* number. +* +* R10: KVM hypercall number +* arguments: R11, R12, R13, R14. +*/ + nr =kvm_r10_read (vcpu); + a0 =kvm_r11_read (vcpu); + a1 =kvm_r12_read (vcpu); + a2 =kvm_r13_read (vcpu); + a3 =kvm_r14_read (vcpu); + + ret =__kvm_emulate_hypercall (vcpu, nr, a0, a1, a2, a3, true); + +tdvmcall_set_return_code (vcpu, ret); + +return 1 ; +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) { +if (tdvmcall_exit_type (vcpu)) +return tdx_emulate_vmcall (vcpu); +switch (tdvmcall_leaf (vcpu)) {default :break ;
Signature · 1 line
2.25.1
PATCH v7 89/102 KVM: TDX: Handle TDX PV CPUID hypercall
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Wire up TDX PV CPUID hypercall to the KVM backend function.
--- arch/x86/kvm/vmx/tdx.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+)
arch/x86/kvm/vmx/tdx.c +22 -0
@@ -947,12 +947,34 @@ static int tdx_emulate_vmcall(struct kvm_vcpu *vcpu)return 1 ; } +static int tdx_emulate_cpuid (struct kvm_vcpu *vcpu) +{ +u32 eax, ebx, ecx, edx; + +/* EAX and ECX for cpuid is stored in R12 and R13. */ + eax =tdvmcall_a0_read (vcpu); + ecx =tdvmcall_a1_read (vcpu); + +kvm_cpuid (vcpu, &eax, &ebx, &ecx, &edx, true); + +tdvmcall_a0_write (vcpu, eax); +tdvmcall_a1_write (vcpu, ebx); +tdvmcall_a2_write (vcpu, ecx); +tdvmcall_a3_write (vcpu, edx); + +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); + +return 1 ; +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) {if (tdvmcall_exit_type (vcpu))return tdx_emulate_vmcall (vcpu);switch (tdvmcall_leaf (vcpu)) { +case EXIT_REASON_CPUID : +return tdx_emulate_cpuid (vcpu);default :break ; }
Signature · 1 line
2.25.1
PATCH v7 90/102 KVM: TDX: Handle TDX PV HLT hypercall
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Wire up TDX PV HLT hypercall to the KVM backend function.
--- arch/x86/kvm/vmx/tdx.c | 42 +++++++++++++++++++++++++++++++++++++++++- arch/x86/kvm/vmx/tdx.h | 3 +++ 2 files changed, 44 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/tdx.c +41 -1
@@ -654,7 +654,32 @@ void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)bool tdx_protected_apic_has_interrupt (struct kvm_vcpu *vcpu) { -return pi_has_pending_interrupt (vcpu); +bool ret =pi_has_pending_interrupt (vcpu); +struct vcpu_tdx *tdx =to_tdx (vcpu); + +if (ret || vcpu->arch.mp_state !=KVM_MP_STATE_HALTED ) +return true; + +if (tdx->interrupt_disabled_hlt) +return false; + +/* +* This is for the case where the virtual interrupt is recognized, +* i.e. set in vmcs.RVI, between the STI and "HLT". KVM doesn't have +* access to RVI and the interrupt is no longer in the PID (because it +* was "recognized". It doesn't get delivered in the guest because the +* TDCALL completes before interrupts are enabled. +* +* TDX modules sets RVI while in an STI interrupt shadow. +* - TDExit(typically TDG.VP.VMCALL<HLT>) from the guest to TDX module. +* The interrupt shadow at this point is gone. +* - It knows that there is an interrupt that can be delivered +* (RVI > PPR && EFLAGS.IF=1, the other conditions of 29.2.2 don't +* matter) +* - It forwards the TDExit nevertheless, to a clueless hypervisor that +* has no way to glean either RVI or PPR. +*/ +return !!xchg (&tdx->buggy_hlt_workaround,0 ); }void tdx_prepare_switch_to_guest (struct kvm_vcpu *vcpu)
@@ -967,6 +992,17 @@ static int tdx_emulate_cpuid(struct kvm_vcpu *vcpu)return 1 ; } +static int tdx_emulate_hlt (struct kvm_vcpu *vcpu) +{ +struct vcpu_tdx *tdx =to_tdx (vcpu); + +/* See tdx_protected_apic_has_interrupt() to avoid heavy seamcall */ + tdx->interrupt_disabled_hlt =tdvmcall_a0_read (vcpu);; + +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +return kvm_emulate_halt_noskip (vcpu); +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) {if (tdvmcall_exit_type (vcpu))
@@ -975,6 +1011,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)switch (tdvmcall_leaf (vcpu)) {case EXIT_REASON_CPUID :return tdx_emulate_cpuid (vcpu); +case EXIT_REASON_HLT : +return tdx_emulate_hlt (vcpu);default :break ; }
@@ -1311,6 +1349,8 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,struct kvm_vcpu *vcpu = apic->vcpu;struct vcpu_tdx *tdx =to_tdx (vcpu); +/* See comment in tdx_protected_apic_has_interrupt(). */ + tdx->buggy_hlt_workaround =1 ;/* TDX supports only posted interrupt. No lapic emulation. */ __vmx_deliver_posted_interrupt (vcpu, &tdx->pi_desc, vector); }
arch/x86/kvm/vmx/tdx.h +3 -0
@@ -116,6 +116,9 @@ struct vcpu_tdx {bool host_state_need_restore;u64 msr_host_kernel_gs_base; +bool interrupt_disabled_hlt; +unsigned int buggy_hlt_workaround; +/* * Dummy to make pmu_intel not corrupt memory. * TODO: Support PMU for TDX. Future work.
Signature · 1 line
2.25.1
PATCH v7 91/102 KVM: TDX: Handle TDX PV port io hypercall
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Wire up TDX PV port IO hypercall to the KVM backend function.
--- arch/x86/kvm/vmx/tdx.c | 57 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+)
arch/x86/kvm/vmx/tdx.c +57 -0
@@ -1003,6 +1003,61 @@ static int tdx_emulate_hlt(struct kvm_vcpu *vcpu)return kvm_emulate_halt_noskip (vcpu); } +static int tdx_complete_pio_in (struct kvm_vcpu *vcpu) +{ +struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt; +unsigned long val =0 ; +int ret; + +WARN_ON (vcpu->arch.pio.count !=1 ); + + ret = ctxt->ops->pio_in_emulated (ctxt, vcpu->arch.pio.size, + vcpu->arch.pio.port, &val,1 ); +WARN_ON (!ret); + +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +tdvmcall_set_return_val (vcpu, val); + +return 1 ; +} + +static int tdx_emulate_io (struct kvm_vcpu *vcpu) +{ +struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt; +unsigned long val =0 ; +unsigned int port; +int size, ret; +bool write; + + ++vcpu->stat.io_exits; + + size =tdvmcall_a0_read (vcpu); + write =tdvmcall_a1_read (vcpu); + port =tdvmcall_a2_read (vcpu); + +if (size !=1 && size !=2 && size !=4 ) { +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_INVALID_OPERAND ); +return 1 ; + } + +if (write) { + val =tdvmcall_a3_read (vcpu); + ret = ctxt->ops->pio_out_emulated (ctxt, size, port, &val,1 ); + +/* No need for a complete_userspace_io callback. */ + vcpu->arch.pio.count =0 ; + }else { + ret = ctxt->ops->pio_in_emulated (ctxt, size, port, &val,1 ); +if (!ret) + vcpu->arch.complete_userspace_io = tdx_complete_pio_in; +else +tdvmcall_set_return_val (vcpu, val); + } +if (ret) +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +return ret; +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) {if (tdvmcall_exit_type (vcpu))
@@ -1013,6 +1068,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)return tdx_emulate_cpuid (vcpu);case EXIT_REASON_HLT :return tdx_emulate_hlt (vcpu); +case EXIT_REASON_IO_INSTRUCTION : +return tdx_emulate_io (vcpu);default :break ; }
Signature · 1 line
2.25.1
PATCH v7 92/102 KVM: TDX: Handle TDX PV MMIO hypercall
In reply to [email protected]From: Sean Christopherson <[email protected]>
Export kvm_io_bus_read and kvm_mmio tracepoint and wire up TDX PV MMIO hypercall to the KVM backend functions.
kvm_io_bus_read/write() searches KVM device emulated in kernel of the given MMIO address and emulates the MMIO. As TDX PV MMIO also needs it, export kvm_io_bus_read(). kvm_io_bus_write() is already exported. TDX PV MMIO emulates some of MMIO itself. To add trace point consistently with x86 kvm, export kvm_mmio tracepoint.
--- arch/x86/kvm/vmx/tdx.c | 114 +++++++++++++++++++++++++++++++++++++++++ arch/x86/kvm/x86.c | 1 + virt/kvm/kvm_main.c | 2 + 3 files changed, 117 insertions(+)
arch/x86/kvm/vmx/tdx.c +114 -0
@@ -1058,6 +1058,118 @@ static int tdx_emulate_io(struct kvm_vcpu *vcpu)return ret; } +static int tdx_complete_mmio (struct kvm_vcpu *vcpu) +{ +unsigned long val =0 ; +gpa_t gpa; +int size; + +WARN_ON (vcpu->mmio_needed !=1 ); + vcpu->mmio_needed =0 ; + +if (!vcpu->mmio_is_write) { + gpa = vcpu->mmio_fragments[0 ].gpa; + size = vcpu->mmio_fragments[0 ].len; + +memcpy (&val, vcpu->run->mmio.data, size); +tdvmcall_set_return_val (vcpu, val); +trace_kvm_mmio (KVM_TRACE_MMIO_READ , size, gpa, &val); + } +return 1 ; +} + +static inline int tdx_mmio_write (struct kvm_vcpu *vcpu,gpa_t gpa,int size, +unsigned long val) +{ +if (kvm_iodevice_write (vcpu, &vcpu->arch.apic->dev, gpa, size, &val) && +kvm_io_bus_write (vcpu,KVM_MMIO_BUS , gpa, size, &val)) +return -EOPNOTSUPP ; + +trace_kvm_mmio (KVM_TRACE_MMIO_WRITE , size, gpa, &val); +return 0 ; +} + +static inline int tdx_mmio_read (struct kvm_vcpu *vcpu,gpa_t gpa,int size) +{ +unsigned long val; + +if (kvm_iodevice_read (vcpu, &vcpu->arch.apic->dev, gpa, size, &val) && +kvm_io_bus_read (vcpu,KVM_MMIO_BUS , gpa, size, &val)) +return -EOPNOTSUPP ; + +tdvmcall_set_return_val (vcpu, val); +trace_kvm_mmio (KVM_TRACE_MMIO_READ , size, gpa, &val); +return 0 ; +} + +static int tdx_emulate_mmio (struct kvm_vcpu *vcpu) +{ +struct kvm_memory_slot *slot; +int size, write, r; +unsigned long val; +gpa_t gpa; + +WARN_ON (vcpu->mmio_needed); + + size =tdvmcall_a0_read (vcpu); + write =tdvmcall_a1_read (vcpu); + gpa =tdvmcall_a2_read (vcpu); + val = write ?tdvmcall_a3_read (vcpu) :0 ; + +if (size !=1 && size !=2 && size !=4 && size !=8 ) + goto error; +if (write !=0 && write !=1 ) + goto error; + +/* Strip the shared bit, allow MMIO with and without it set. */ + gpa = gpa & ~gfn_to_gpa (kvm_gfn_shared_mask (vcpu->kvm)); + +if (size >8u || ((gpa + size -1 ) ^ gpa) &PAGE_MASK ) + goto error; + + slot =kvm_vcpu_gfn_to_memslot (vcpu,gpa_to_gfn (gpa)); +if (slot && !(slot->flags &KVM_MEMSLOT_INVALID )) + goto error; + +if (!kvm_io_bus_write (vcpu,KVM_FAST_MMIO_BUS , gpa,0 ,NULL )) { +trace_kvm_fast_mmio (gpa); +return 1 ; + } + +if (write) + r =tdx_mmio_write (vcpu, gpa, size, val); +else + r =tdx_mmio_read (vcpu, gpa, size); +if (!r) { +/* Kernel completed device emulation. */ +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +return 1 ; + } + +/* Request the device emulation to userspace device model. */ + vcpu->mmio_needed =1 ; + vcpu->mmio_is_write = write; + vcpu->arch.complete_userspace_io = tdx_complete_mmio; + + vcpu->run->mmio.phys_addr = gpa; + vcpu->run->mmio.len = size; + vcpu->run->mmio.is_write = write; + vcpu->run->exit_reason =KVM_EXIT_MMIO ; + +if (write) { +memcpy (vcpu->run->mmio.data, &val, size); + }else { + vcpu->mmio_fragments[0 ].gpa = gpa; + vcpu->mmio_fragments[0 ].len = size; +trace_kvm_mmio (KVM_TRACE_MMIO_READ_UNSATISFIED , size, gpa,NULL ); + } +return 0 ; + +error: +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +return 1 ; +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) {if (tdvmcall_exit_type (vcpu))
@@ -1070,6 +1182,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)return tdx_emulate_hlt (vcpu);case EXIT_REASON_IO_INSTRUCTION :return tdx_emulate_io (vcpu); +case EXIT_REASON_EPT_VIOLATION : +return tdx_emulate_mmio (vcpu);default :break ; }
arch/x86/kvm/x86.c +1 -0
@@ -13208,6 +13208,7 @@ bool kvm_arch_dirty_log_supported(struct kvm *kvm)EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_entry);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_exit); +EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_mmio);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_fast_mmio);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_inj_virq);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_page_fault);
virt/kvm/kvm_main.c +2 -0
@@ -2303,6 +2303,7 @@ struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfnreturn NULL ; } +EXPORT_SYMBOL_GPL (kvm_vcpu_gfn_to_memslot);bool kvm_is_visible_gfn (struct kvm *kvm,gfn_t gfn) {
@@ -5185,6 +5186,7 @@ int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, r =__kvm_io_bus_read (vcpu, bus, &range, val);return r <0 ? r :0 ; } +EXPORT_SYMBOL_GPL (kvm_io_bus_read);/* Caller must hold slots_lock. */ int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
Signature · 1 line
2.25.1
PATCH v7 93/102 KVM: TDX: Implement callbacks for MSR operations for TDX
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Implements set_msr/get_msr/has_emulated_msr methods for TDX to handle hypercall from guest TD for paravirtualized rdmsr and wrmsr. The TDX module virtualizes MSRs. For some MSRs, it injects #VE to the guest TD upon RDMSR or WRMSR. The exact list of such MSRs are defined in the spec.
Upon #VE, the guest TD may execute hypercalls, TDG.VP.VMCALL<INSTRUCTION.RDMSR> and TDG.VP.VMCALL<INSTRUCTION.WRMSR>, which are defined in GHCI (Guest-Host Communication Interface) so that the host VMM (e.g. KVM) can virtualizes the MSRs.
--- arch/x86/kvm/vmx/main.c | 34 +++++++++++++++++-- arch/x86/kvm/vmx/tdx.c | 68 ++++++++++++++++++++++++++++++++++++++ arch/x86/kvm/vmx/x86_ops.h | 6 ++++ 3 files changed, 105 insertions(+), 3 deletions(-)
arch/x86/kvm/vmx/main.c +31 -3
@@ -205,6 +205,34 @@ static void vt_handle_exit_irqoff(struct kvm_vcpu *vcpu)vmx_handle_exit_irqoff (vcpu); } +static int vt_set_msr (struct kvm_vcpu *vcpu,struct msr_data *msr_info) +{ +if (unlikely (is_td_vcpu (vcpu))) +return tdx_set_msr (vcpu, msr_info); + +return vmx_set_msr (vcpu, msr_info); +} + +/* +* The kvm parameter can be NULL (module initialization, or invocation before +* VM creation). Be sure to check the kvm parameter before using it. +*/ +static bool vt_has_emulated_msr (struct kvm *kvm,u32 index) +{ +if (kvm &&is_td (kvm)) +return tdx_is_emulated_msr (index, true); + +return vmx_has_emulated_msr (kvm, index); +} + +static int vt_get_msr (struct kvm_vcpu *vcpu,struct msr_data *msr_info) +{ +if (unlikely (is_td_vcpu (vcpu))) +return tdx_get_msr (vcpu, msr_info); + +return vmx_get_msr (vcpu, msr_info); +} +static void vt_apicv_post_state_restore (struct kvm_vcpu *vcpu) {struct pi_desc *pi =vcpu_to_pi_desc (vcpu);
@@ -422,7 +450,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .hardware_enable = vt_hardware_enable, .hardware_disable = vt_hardware_disable, - .has_emulated_msr = vmx_has_emulated_msr, + .has_emulated_msr = vt_has_emulated_msr, .is_vm_type_supported = vt_is_vm_type_supported, .vm_size = sizeof(struct kvm_vmx),
@@ -442,8 +470,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .update_exception_bitmap = vmx_update_exception_bitmap, .get_msr_feature = vmx_get_msr_feature, - .get_msr = vmx_get_msr, - .set_msr = vmx_set_msr, + .get_msr = vt_get_msr, + .set_msr = vt_set_msr, .get_segment_base = vmx_get_segment_base, .get_segment = vmx_get_segment, .set_segment = vmx_set_segment,
arch/x86/kvm/vmx/tdx.c +68 -0
74 lines not on this page · raw message
arch/x86/kvm/vmx/x86_ops.h +6 -0
@@ -156,6 +156,9 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,void tdx_inject_nmi (struct kvm_vcpu *vcpu);void tdx_get_exit_info (struct kvm_vcpu *vcpu,u32 *reason,u64 *info1,u64 *info2,u32 *intr_info,u32 *error_code); +bool tdx_is_emulated_msr (u32 index,bool write); +int tdx_get_msr (struct kvm_vcpu *vcpu,struct msr_data *msr); +int tdx_set_msr (struct kvm_vcpu *vcpu,struct msr_data *msr);int tdx_vm_ioctl (struct kvm *kvm,void __user *argp);int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp);
@@ -193,6 +196,9 @@ static inline void tdx_inject_nmi(struct kvm_vcpu *vcpu) {}static inline void tdx_get_exit_info (struct kvm_vcpu *vcpu,u32 *reason,u64 *info1,u64 *info2,u32 *intr_info,u32 *error_code) {} +static inline bool tdx_is_emulated_msr (u32 index,bool write) {return false; } +static inline int tdx_get_msr (struct kvm_vcpu *vcpu,struct msr_data *msr) {return 1 ; } +static inline int tdx_set_msr (struct kvm_vcpu *vcpu,struct msr_data *msr) {return 1 ; }static inline int tdx_vm_ioctl (struct kvm *kvm,void __user *argp) {return -EOPNOTSUPP ; }static inline int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp) {return -EOPNOTSUPP ; }
Signature · 1 line
2.25.1
PATCH v7 94/102 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Wire up TDX PV rdmsr/wrmsr hypercall to the KVM backend function.
--- arch/x86/kvm/vmx/tdx.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+)
arch/x86/kvm/vmx/tdx.c +37 -0
@@ -1170,6 +1170,39 @@ static int tdx_emulate_mmio(struct kvm_vcpu *vcpu)return 1 ; } +static int tdx_emulate_rdmsr (struct kvm_vcpu *vcpu) +{ +u32 index =tdvmcall_a0_read (vcpu); +u64 data; + +if (kvm_get_msr (vcpu, index, &data)) { +trace_kvm_msr_read_ex (index); +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_INVALID_OPERAND ); +return 1 ; + } +trace_kvm_msr_read (index, data); + +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +tdvmcall_set_return_val (vcpu, data); +return 1 ; +} + +static int tdx_emulate_wrmsr (struct kvm_vcpu *vcpu) +{ +u32 index =tdvmcall_a0_read (vcpu); +u64 data =tdvmcall_a1_read (vcpu); + +if (kvm_set_msr (vcpu, index, data)) { +trace_kvm_msr_write_ex (index, data); +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_INVALID_OPERAND ); +return 1 ; + } + +trace_kvm_msr_write (index, data); +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +return 1 ; +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) {if (tdvmcall_exit_type (vcpu))
@@ -1184,6 +1217,10 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)return tdx_emulate_io (vcpu);case EXIT_REASON_EPT_VIOLATION :return tdx_emulate_mmio (vcpu); +case EXIT_REASON_MSR_READ : +return tdx_emulate_rdmsr (vcpu); +case EXIT_REASON_MSR_WRITE : +return tdx_emulate_wrmsr (vcpu);default :break ; }
Signature · 1 line
2.25.1
PATCH v7 95/102 KVM: TDX: Handle TDX PV report fatal error hypercall
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Wire up TDX PV report fatal error hypercall to KVM_SYSTEM_EVENT_CRASH KVM exit event.
--- arch/x86/kvm/vmx/tdx.c | 20 ++++++++++++++++++++ include/uapi/linux/kvm.h | 1 + 2 files changed, 21 insertions(+)
arch/x86/kvm/vmx/tdx.c +20 -0
@@ -1203,6 +1203,24 @@ static int tdx_emulate_wrmsr(struct kvm_vcpu *vcpu)return 1 ; } +static int tdx_report_fatal_error (struct kvm_vcpu *vcpu) +{ +/* +* Exit to userspace device model for teardown. +* Because guest TD is already panicing, returning an error to guerst TD +* doesn't make sense. No argument check is done. +*/ + + vcpu->run->exit_reason =KVM_EXIT_SYSTEM_EVENT ; + vcpu->run->system_event.type =KVM_SYSTEM_EVENT_TDX ; + vcpu->run->system_event.ndata =3 ; + vcpu->run->system_event.data[0 ] =TDG_VP_VMCALL_REPORT_FATAL_ERROR ; + vcpu->run->system_event.data[1 ] =tdvmcall_a0_read (vcpu); + vcpu->run->system_event.data[2 ] =tdvmcall_a1_read (vcpu); + +return 0 ; +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) {if (tdvmcall_exit_type (vcpu))
@@ -1221,6 +1239,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)return tdx_emulate_rdmsr (vcpu);case EXIT_REASON_MSR_WRITE :return tdx_emulate_wrmsr (vcpu); +case TDG_VP_VMCALL_REPORT_FATAL_ERROR : +return tdx_report_fatal_error (vcpu);default :break ; }
include/uapi/linux/kvm.h +1 -0
@@ -448,6 +448,7 @@ struct kvm_run {#define KVM_SYSTEM_EVENT_WAKEUP 4#define KVM_SYSTEM_EVENT_SUSPEND 5#define KVM_SYSTEM_EVENT_SEV_TERM 6 +#define KVM_SYSTEM_EVENT_TDX 7__u32 type;__u32 ndata;union {
Signature · 1 line
2.25.1
PATCH v7 96/102 KVM: TDX: Handle TDX PV map_gpa hypercall
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Wire up TDX PV map_gpa hypercall to the kvm/mmu backend.
--- arch/x86/kvm/vmx/tdx.c | 60 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+)
arch/x86/kvm/vmx/tdx.c +60 -0
@@ -1221,6 +1221,64 @@ static int tdx_report_fatal_error(struct kvm_vcpu *vcpu)return 0 ; } +static int tdx_map_gpa (struct kvm_vcpu *vcpu) +{ +struct kvm *kvm = vcpu->kvm; +gpa_t gpa =tdvmcall_a0_read (vcpu); +gpa_t size =tdvmcall_a1_read (vcpu); +gpa_t end = gpa + size; +bool allow_private =kvm_is_private_gpa (kvm, gpa); + +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_INVALID_OPERAND ); +if (!IS_ALIGNED (gpa,4096 ) || !IS_ALIGNED (size,4096 ) || + end < gpa || + end >kvm_gfn_shared_mask (kvm) << (PAGE_SHIFT +1 ) || +kvm_is_private_gpa (kvm, gpa) !=kvm_is_private_gpa (kvm, end)) +return 1 ; + +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); + +#define TDX_MAP_GPA_SIZE_MAX (16 * 1024 * 1024) +while (gpa < end) { +gfn_t s =gpa_to_gfn (gpa); +gfn_t e =gpa_to_gfn ( +min (roundup (gpa +1 ,TDX_MAP_GPA_SIZE_MAX ), end)); +int ret =kvm_mmu_map_gpa (vcpu, &s, e, allow_private); + +if (ret == -EAGAIN ) + e = s; +else if (ret) { +tdvmcall_set_return_code (vcpu, +TDG_VP_VMCALL_INVALID_OPERAND ); +break ; + } + + gpa =gfn_to_gpa (e); + +/* +* TODO: +* Interrupt this hypercall invocation to return remaining +* region to the guest and let the guest to resume the +* hypercall. +* +* The TDX Guest-Hypervisor Communication Interface(GHCI) +* specification and guest implementation need to be updated. +* +* if (gpa < end && need_resched()) { +* size = end - gpa; +* tdvmcall_a0_write(vcpu, gpa); +* tdvmcall_a1_write(vcpu, size); +* tdvmcall_set_return_code(vcpu, TDG_VP_VMCALL_INTERRUPTED_RESUME); +* break; +* } +*/ +if (gpa < end &&need_resched ()) +cond_resched (); + } + +return 1 ; +} +static int handle_tdvmcall (struct kvm_vcpu *vcpu) {if (tdvmcall_exit_type (vcpu))
@@ -1241,6 +1299,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)return tdx_emulate_wrmsr (vcpu);case TDG_VP_VMCALL_REPORT_FATAL_ERROR :return tdx_report_fatal_error (vcpu); +case TDG_VP_VMCALL_MAP_GPA : +return tdx_map_gpa (vcpu);default :break ; }
Signature · 1 line
2.25.1
PATCH v7 97/102 KVM: TDX: Handle TDG.VP.VMCALL<GetTdVmCallInfo> hypercall
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Implement TDG.VP.VMCALL<GetTdVmCallInfo> hypercall. If the input value is zero, return success code and zero in output registers.
TDG.VP.VMCALL<GetTdVmCallInfo> hypercall is a subleaf of TDG.VP.VMCALL to enumerate which TDG.VP.VMCALL sub leaves are supported. This hypercall is for future enhancement of the Guest-Host-Communication Interface (GHCI) specification. The GHCI version of 344426-001US defines it to require input R12 to be zero and to return zero in output registers, R11, R12, R13, and R14 so that guest TD enumerates no enhancement.
--- arch/x86/kvm/vmx/tdx.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
arch/x86/kvm/vmx/tdx.c +16 -0
@@ -1203,6 +1203,20 @@ static int tdx_emulate_wrmsr(struct kvm_vcpu *vcpu)return 1 ; } +static int tdx_get_td_vm_call_info (struct kvm_vcpu *vcpu) +{ +if (tdvmcall_a0_read (vcpu)) +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_INVALID_OPERAND ); +else { +tdvmcall_set_return_code (vcpu,TDG_VP_VMCALL_SUCCESS ); +kvm_r11_write (vcpu,0 ); +tdvmcall_a0_write (vcpu,0 ); +tdvmcall_a1_write (vcpu,0 ); +tdvmcall_a2_write (vcpu,0 ); + } +return 1 ; +} +static int tdx_report_fatal_error (struct kvm_vcpu *vcpu) {/*
@@ -1297,6 +1311,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)return tdx_emulate_rdmsr (vcpu);case EXIT_REASON_MSR_WRITE :return tdx_emulate_wrmsr (vcpu); +case TDG_VP_VMCALL_GET_TD_VM_CALL_INFO : +return tdx_get_td_vm_call_info (vcpu);case TDG_VP_VMCALL_REPORT_FATAL_ERROR :return tdx_report_fatal_error (vcpu);case TDG_VP_VMCALL_MAP_GPA :
Signature · 1 line
2.25.1
PATCH v7 98/102 KVM: TDX: Silently discard SMI request
In reply to [email protected]From: Isaku Yamahata <[email protected]>
TDX doesn't support system-management mode (SMM) and system-management interrupt (SMI) in guest TDs. Because guest state (vcpu state, memory state) is protected, it must go through the TDX module APIs to change guest state, injecting SMI and changing vcpu mode into SMM. The TDX module doesn't provide a way for VMM to inject SMI into guest TD and a way for VMM to switch guest vcpu mode into SMM.
We have two options in KVM when handling SMM or SMI in the guest TD or the device model (e.g. QEMU): 1) silently ignore the request or 2) return a meaningful error.
For simplicity, we implemented the option 1).
--- arch/x86/kvm/lapic.c | 7 +++++-- arch/x86/kvm/vmx/main.c | 43 ++++++++++++++++++++++++++++++++++---- arch/x86/kvm/vmx/tdx.c | 27 ++++++++++++++++++++++++ arch/x86/kvm/vmx/x86_ops.h | 8 +++++++ arch/x86/kvm/x86.c | 3 ++- 5 files changed, 81 insertions(+), 7 deletions(-)
arch/x86/kvm/lapic.c +5 -2
@@ -1146,8 +1146,11 @@ static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,case APIC_DM_SMI : result =1 ; -kvm_make_request (KVM_REQ_SMI , vcpu); -kvm_vcpu_kick (vcpu); +if (static_call (kvm_x86_has_emulated_msr)(vcpu->kvm, +MSR_IA32_SMBASE )) { +kvm_make_request (KVM_REQ_SMI , vcpu); +kvm_vcpu_kick (vcpu); + }break ;case APIC_DM_NMI :
arch/x86/kvm/vmx/main.c +39 -4
55 lines not on this page · raw message
arch/x86/kvm/vmx/tdx.c +27 -0
@@ -1828,6 +1828,33 @@ int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)return 1 ; } +int tdx_smi_allowed (struct kvm_vcpu *vcpu,bool for_injection) +{ +/* SMI isn't supported for TDX. */ +WARN_ON_ONCE (1 ); +return false; +} + +int tdx_enter_smm (struct kvm_vcpu *vcpu,char *smstate) +{ +/* smi_allowed() is always false for TDX as above. */ +WARN_ON_ONCE (1 ); +return 0 ; +} + +int tdx_leave_smm (struct kvm_vcpu *vcpu,const char *smstate) +{ +WARN_ON_ONCE (1 ); +return 0 ; +} + +void tdx_enable_smi_window (struct kvm_vcpu *vcpu) +{ +/* SMI isn't supported for TDX. Silently discard SMI request. */ +WARN_ON_ONCE (1 ); + vcpu->arch.smi_pending = false; +} +int tdx_dev_ioctl (void __user *argp) {struct kvm_tdx_capabilities __user *user_caps;
arch/x86/kvm/vmx/x86_ops.h +8 -0
@@ -159,6 +159,10 @@ void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,bool tdx_is_emulated_msr (u32 index,bool write);int tdx_get_msr (struct kvm_vcpu *vcpu,struct msr_data *msr);int tdx_set_msr (struct kvm_vcpu *vcpu,struct msr_data *msr); +int tdx_smi_allowed (struct kvm_vcpu *vcpu,bool for_injection); +int tdx_enter_smm (struct kvm_vcpu *vcpu,char *smstate); +int tdx_leave_smm (struct kvm_vcpu *vcpu,const char *smstate); +void tdx_enable_smi_window (struct kvm_vcpu *vcpu);int tdx_vm_ioctl (struct kvm *kvm,void __user *argp);int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp);
@@ -199,6 +203,10 @@ static inline void tdx_get_exit_info(static inline bool tdx_is_emulated_msr (u32 index,bool write) {return false; }static inline int tdx_get_msr (struct kvm_vcpu *vcpu,struct msr_data *msr) {return 1 ; }static inline int tdx_set_msr (struct kvm_vcpu *vcpu,struct msr_data *msr) {return 1 ; } +static inline int tdx_smi_allowed (struct kvm_vcpu *vcpu,bool for_injection) {return false; } +static inline int tdx_enter_smm (struct kvm_vcpu *vcpu,char *smstate) {return 0 ; } +static inline int tdx_leave_smm (struct kvm_vcpu *vcpu,const char *smstate) {return 0 ; } +static inline void tdx_enable_smi_window (struct kvm_vcpu *vcpu) {}static inline int tdx_vm_ioctl (struct kvm *kvm,void __user *argp) {return -EOPNOTSUPP ; }static inline int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp) {return -EOPNOTSUPP ; }
arch/x86/kvm/x86.c +2 -1
@@ -4816,7 +4816,8 @@ static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)static int kvm_vcpu_ioctl_smi (struct kvm_vcpu *vcpu) { -kvm_make_request (KVM_REQ_SMI , vcpu); +if (static_call (kvm_x86_has_emulated_msr)(vcpu->kvm,MSR_IA32_SMBASE )) +kvm_make_request (KVM_REQ_SMI , vcpu);return 0 ; }
Signature · 1 line
2.25.1
PATCH v7 99/102 KVM: TDX: Silently ignore INIT/SIPI
In reply to [email protected]From: Isaku Yamahata <[email protected]>
The TDX module API doesn't provide API for VMM to inject INIT IPI and SIPI. Instead it defines the different protocols to boot application processors. Ignore INIT and SIPI events for the TDX guest.
There are two options. 1) (silently) ignore INIT/SIPI request or 2) return error to guest TDs somehow. Given that TDX guest is paravirtualized to boot AP, the option 1 is chosen for simplicity.
--- arch/x86/include/asm/kvm-x86-ops.h | 1 + arch/x86/include/asm/kvm_host.h | 2 ++ arch/x86/kvm/lapic.c | 16 +++++++++++----- arch/x86/kvm/svm/svm.c | 1 + arch/x86/kvm/vmx/main.c | 22 +++++++++++++++++++++- 5 files changed, 36 insertions(+), 6 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
@@ -136,6 +136,7 @@ KVM_X86_OP_OPTIONAL(migrate_timers)KVM_X86_OP (msr_filter_changed) KVM_X86_OP(complete_emulated_msr) KVM_X86_OP(vcpu_deliver_sipi_vector) +KVM_X86_OP(vcpu_deliver_init) KVM_X86_OP_OPTIONAL_RET0(vcpu_get_apicv_inhibit_reasons);KVM_X86_OP (check_processor_compatibility)
arch/x86/include/asm/kvm_host.h +2 -0
@@ -1649,6 +1649,7 @@ struct kvm_x86_ops {int (*complete_emulated_msr)(struct kvm_vcpu *vcpu,int err);void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector); +void (*vcpu_deliver_init)(struct kvm_vcpu *vcpu);/* * Returns vCPU specific APICv inhibit reasons
@@ -1858,6 +1859,7 @@ int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu);void kvm_get_segment (struct kvm_vcpu *vcpu,struct kvm_segment *var,int seg);int kvm_load_segment_descriptor (struct kvm_vcpu *vcpu,u16 selector,int seg);void kvm_vcpu_deliver_sipi_vector (struct kvm_vcpu *vcpu,u8 vector); +void kvm_vcpu_deliver_init (struct kvm_vcpu *vcpu);int kvm_task_switch (struct kvm_vcpu *vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code);
arch/x86/kvm/lapic.c +11 -5
@@ -2996,6 +2996,16 @@ int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)return 0 ; } +void kvm_vcpu_deliver_init (struct kvm_vcpu *vcpu) +{ +kvm_vcpu_reset (vcpu, true); +if (kvm_vcpu_is_bsp (vcpu)) + vcpu->arch.mp_state =KVM_MP_STATE_RUNNABLE ; +else + vcpu->arch.mp_state =KVM_MP_STATE_INIT_RECEIVED ; +} +EXPORT_SYMBOL_GPL (kvm_vcpu_deliver_init); +int kvm_apic_accept_events (struct kvm_vcpu *vcpu) {struct kvm_lapic *apic = vcpu->arch.apic;
@@ -3043,11 +3053,7 @@ int kvm_apic_accept_events(struct kvm_vcpu *vcpu)if (test_bit (KVM_APIC_INIT , &pe)) {clear_bit (KVM_APIC_INIT , &apic->pending_events); -kvm_vcpu_reset (vcpu, true); -if (kvm_vcpu_is_bsp (apic->vcpu)) - vcpu->arch.mp_state =KVM_MP_STATE_RUNNABLE ; -else - vcpu->arch.mp_state =KVM_MP_STATE_INIT_RECEIVED ; +static_call (kvm_x86_vcpu_deliver_init)(vcpu); }if (test_bit (KVM_APIC_SIPI , &pe)) {clear_bit (KVM_APIC_SIPI , &apic->pending_events);
arch/x86/kvm/svm/svm.c +1 -0
@@ -4829,6 +4829,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = { .complete_emulated_msr = svm_complete_emulated_msr, .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector, + .vcpu_deliver_init = kvm_vcpu_deliver_init, .vcpu_get_apicv_inhibit_reasons = avic_vcpu_get_apicv_inhibit_reasons, };
arch/x86/kvm/vmx/main.c +21 -1
@@ -295,6 +295,25 @@ static void vt_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,vmx_deliver_interrupt (apic, delivery_mode, trig_mode, vector); } +static void vt_vcpu_deliver_sipi_vector (struct kvm_vcpu *vcpu,u8 vector) +{ +if (is_td_vcpu (vcpu)) +return ; + +kvm_vcpu_deliver_sipi_vector (vcpu, vector); +} + +static void vt_vcpu_deliver_init (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) { +/* TDX doesn't support INIT. Ignore INIT event */ + vcpu->arch.mp_state =KVM_MP_STATE_RUNNABLE ; +return ; + } + +kvm_vcpu_deliver_init (vcpu); +} +static void vt_flush_tlb_all (struct kvm_vcpu *vcpu) {if (is_td_vcpu (vcpu))
@@ -616,7 +635,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .msr_filter_changed = vmx_msr_filter_changed, .complete_emulated_msr = kvm_complete_insn_gp, - .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector, + .vcpu_deliver_sipi_vector = vt_vcpu_deliver_sipi_vector, + .vcpu_deliver_init = vt_vcpu_deliver_init, .dev_mem_enc_ioctl = tdx_dev_ioctl, .mem_enc_ioctl = vt_mem_enc_ioctl,
Signature · 1 line
2.25.1
PATCH v7 100/102 KVM: TDX: Add methods to ignore accesses to CPU state
In reply to [email protected]From: Sean Christopherson <[email protected]>
TDX protects TDX guest state from VMM. Implements to access methods for TDX guest state to ignore them or return zero.
--- arch/x86/kvm/vmx/main.c | 463 +++++++++++++++++++++++++++++++++---- arch/x86/kvm/vmx/tdx.c | 55 ++++- arch/x86/kvm/vmx/x86_ops.h | 17 ++ 3 files changed, 490 insertions(+), 45 deletions(-)
arch/x86/kvm/vmx/main.c +420 -43
@@ -268,6 +268,46 @@ static void vt_enable_smi_window(struct kvm_vcpu *vcpu)vmx_enable_smi_window (vcpu); } +static bool vt_can_emulate_instruction (struct kvm_vcpu *vcpu,int emul_type, +void *insn,int insn_len) +{ +if (is_td_vcpu (vcpu)) +return false; + +return vmx_can_emulate_instruction (vcpu, emul_type, insn, insn_len); +} + +static int vt_check_intercept (struct kvm_vcpu *vcpu, +struct x86_instruction_info *info, +enum x86_intercept_stage stage, +struct x86_exception *exception) +{ +/* +* This call back is triggered by the x86 instruction emulator. TDX +* doesn't allow guest memory inspection. +*/ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return X86EMUL_UNHANDLEABLE ; + +return vmx_check_intercept (vcpu, info, stage, exception); +} + +static bool vt_apic_init_signal_blocked (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return true; + +return vmx_apic_init_signal_blocked (vcpu); +} + +static void vt_set_virtual_apic_mode (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return tdx_set_virtual_apic_mode (vcpu); + +return vmx_set_virtual_apic_mode (vcpu); +} +static void vt_apicv_post_state_restore (struct kvm_vcpu *vcpu) {struct pi_desc *pi =vcpu_to_pi_desc (vcpu);
@@ -275,6 +315,31 @@ static void vt_apicv_post_state_restore(struct kvm_vcpu *vcpu)memset (pi->pir,0 ,sizeof (pi->pir)); } +static void vt_hwapic_irr_update (struct kvm_vcpu *vcpu,int max_irr) +{ +if (is_td_vcpu (vcpu)) +return ; + +return vmx_hwapic_irr_update (vcpu, max_irr); +} + +static void vt_hwapic_isr_update (struct kvm_vcpu *vcpu,int max_isr) +{ +if (is_td_vcpu (vcpu)) +return ; + +return vmx_hwapic_isr_update (vcpu, max_isr); +} + +static bool vt_guest_apic_has_interrupt (struct kvm_vcpu *vcpu) +{ +/* TDX doesn't support L2 at the moment. */ +if (WARN_ON_ONCE (is_td_vcpu (vcpu))) +return false; + +return vmx_guest_apic_has_interrupt (vcpu); +} +static int vt_sync_pir_to_irr (struct kvm_vcpu *vcpu) {if (is_td_vcpu (vcpu))
@@ -314,6 +379,177 @@ static void vt_vcpu_deliver_init(struct kvm_vcpu *vcpu)kvm_vcpu_deliver_init (vcpu); } +static void vt_vcpu_after_set_cpuid (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return ; + +return vmx_vcpu_after_set_cpuid (vcpu); +} + +static void vt_update_exception_bitmap (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return ; + +vmx_update_exception_bitmap (vcpu); +} + +static u64 vt_get_segment_base (struct kvm_vcpu *vcpu,int seg) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return tdx_get_segment_base (vcpu, seg); + +return vmx_get_segment_base (vcpu, seg); +} + +static void vt_get_segment (struct kvm_vcpu *vcpu,struct kvm_segment *var, +int seg) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return tdx_get_segment (vcpu, var, seg); + +vmx_get_segment (vcpu, var, seg); +} + +static void vt_set_segment (struct kvm_vcpu *vcpu,struct kvm_segment *var, +int seg) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_set_segment (vcpu, var, seg); +} + +static int vt_get_cpl (struct kvm_vcpu *vcpu) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return tdx_get_cpl (vcpu); + +return vmx_get_cpl (vcpu); +} + +static void vt_get_cs_db_l_bits (struct kvm_vcpu *vcpu,int *db,int *l) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_get_cs_db_l_bits (vcpu, db, l); +} + +static void vt_set_cr0 (struct kvm_vcpu *vcpu,unsigned long cr0) +{ +if (is_td_vcpu (vcpu)) +return ; + +vmx_set_cr0 (vcpu, cr0); +} + +static void vt_set_cr4 (struct kvm_vcpu *vcpu,unsigned long cr4) +{ +if (is_td_vcpu (vcpu)) +return ; + +vmx_set_cr4 (vcpu, cr4); +} + +static int vt_set_efer (struct kvm_vcpu *vcpu,u64 efer) +{ +if (is_td_vcpu (vcpu)) +return 0 ; + +return vmx_set_efer (vcpu, efer); +} + +static void vt_get_idt (struct kvm_vcpu *vcpu,struct desc_ptr *dt) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) { +memset (dt,0 ,sizeof (*dt)); +return ; + } + +vmx_get_idt (vcpu, dt); +} + +static void vt_set_idt (struct kvm_vcpu *vcpu,struct desc_ptr *dt) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_set_idt (vcpu, dt); +} + +static void vt_get_gdt (struct kvm_vcpu *vcpu,struct desc_ptr *dt) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) { +memset (dt,0 ,sizeof (*dt)); +return ; + } + +vmx_get_gdt (vcpu, dt); +} + +static void vt_set_gdt (struct kvm_vcpu *vcpu,struct desc_ptr *dt) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_set_gdt (vcpu, dt); +} + +static void vt_set_dr7 (struct kvm_vcpu *vcpu,unsigned long val) +{ +if (is_td_vcpu (vcpu)) +return ; + +vmx_set_dr7 (vcpu, val); +} + +static void vt_sync_dirty_debug_regs (struct kvm_vcpu *vcpu) +{ +/* +* MOV-DR exiting is always cleared for TD guest, even in debug mode. +* Thus KVM_DEBUGREG_WONT_EXIT can never be set and it should never +* reach here for TD vcpu. +*/ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_sync_dirty_debug_regs (vcpu); +} + +static void vt_cache_reg (struct kvm_vcpu *vcpu,enum kvm_reg reg) +{ +if (is_td_vcpu (vcpu)) +return tdx_cache_reg (vcpu, reg); + +return vmx_cache_reg (vcpu, reg); +} + +static unsigned long vt_get_rflags (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return tdx_get_rflags (vcpu); + +return vmx_get_rflags (vcpu); +} + +static void vt_set_rflags (struct kvm_vcpu *vcpu,unsigned long rflags) +{ +if (is_td_vcpu (vcpu)) +return ; + +vmx_set_rflags (vcpu, rflags); +} + +static bool vt_get_if_flag (struct kvm_vcpu *vcpu) +{ +if (is_td_vcpu (vcpu)) +return false; + +return vmx_get_if_flag (vcpu); +} +static void vt_flush_tlb_all (struct kvm_vcpu *vcpu) {if (is_td_vcpu (vcpu))
@@ -430,6 +666,15 @@ static u32 vt_get_interrupt_shadow(struct kvm_vcpu *vcpu)return vmx_get_interrupt_shadow (vcpu); } +static void vt_patch_hypercall (struct kvm_vcpu *vcpu, +unsigned char *hypercall) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_patch_hypercall (vcpu, hypercall); +} +static void vt_inject_irq (struct kvm_vcpu *vcpu,bool reinjected) {if (is_td_vcpu (vcpu))
@@ -438,6 +683,14 @@ static void vt_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)vmx_inject_irq (vcpu, reinjected); } +static void vt_queue_exception (struct kvm_vcpu *vcpu) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_queue_exception (vcpu); +} +static void vt_cancel_injection (struct kvm_vcpu *vcpu) {if (is_td_vcpu (vcpu))
@@ -470,6 +723,130 @@ static void vt_request_immediate_exit(struct kvm_vcpu *vcpu)vmx_request_immediate_exit (vcpu); } +static void vt_update_cr8_intercept (struct kvm_vcpu *vcpu,int tpr,int irr) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_update_cr8_intercept (vcpu, tpr, irr); +} + +static void vt_set_apic_access_page_addr (struct kvm_vcpu *vcpu) +{ +if (WARN_ON_ONCE (is_td_vcpu (vcpu))) +return ; + +vmx_set_apic_access_page_addr (vcpu); +} + +static void vt_refresh_apicv_exec_ctrl (struct kvm_vcpu *vcpu) +{ +if (WARN_ON_ONCE (is_td_vcpu (vcpu))) +return ; + +vmx_refresh_apicv_exec_ctrl (vcpu); +} + +static void vt_load_eoi_exitmap (struct kvm_vcpu *vcpu,u64 *eoi_exit_bitmap) +{ +if (is_td_vcpu (vcpu)) +return ; + +vmx_load_eoi_exitmap (vcpu, eoi_exit_bitmap); +} + +static int vt_set_tss_addr (struct kvm *kvm,unsigned int addr) +{ +if (is_td (kvm)) +return 0 ; + +return vmx_set_tss_addr (kvm, addr); +} + +static int vt_set_identity_map_addr (struct kvm *kvm,u64 ident_addr) +{ +if (is_td (kvm)) +return 0 ; + +return vmx_set_identity_map_addr (kvm, ident_addr); +} + +static u64 vt_get_mt_mask (struct kvm_vcpu *vcpu,gfn_t gfn,bool is_mmio) +{ +if (is_td_vcpu (vcpu)) { +if (is_mmio) +return MTRR_TYPE_UNCACHABLE <<VMX_EPT_MT_EPTE_SHIFT ; +return MTRR_TYPE_WRBACK <<VMX_EPT_MT_EPTE_SHIFT ; + } + +return vmx_get_mt_mask (vcpu, gfn, is_mmio); +} + +static u64 vt_get_l2_tsc_offset (struct kvm_vcpu *vcpu) +{ +/* TDX doesn't support L2 guest at the moment. */ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return 0 ; + +return vmx_get_l2_tsc_offset (vcpu); +} + +static u64 vt_get_l2_tsc_multiplier (struct kvm_vcpu *vcpu) +{ +/* TDX doesn't support L2 guest at the moment. */ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return 0 ; + +return vmx_get_l2_tsc_multiplier (vcpu); +} + +static void vt_write_tsc_offset (struct kvm_vcpu *vcpu,u64 offset) +{ +/* In TDX, tsc offset can't be changed. */ +if (is_td_vcpu (vcpu)) +return ; + +vmx_write_tsc_offset (vcpu, offset); +} + +static void vt_write_tsc_multiplier (struct kvm_vcpu *vcpu,u64 multiplier) +{ +/* In TDX, tsc multiplier can't be changed. */ +if (is_td_vcpu (vcpu)) +return ; + +vmx_write_tsc_multiplier (vcpu, multiplier); +} + +static void vt_update_cpu_dirty_logging (struct kvm_vcpu *vcpu) +{ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_update_cpu_dirty_logging (vcpu); +} + +#ifdef CONFIG_X86_64 +static int vt_set_hv_timer (struct kvm_vcpu *vcpu,u64 guest_deadline_tsc, +bool *expired) +{ +/* VMX-preemption timer isn't available for TDX. */ +if (is_td_vcpu (vcpu)) +return -EINVAL ; + +return vmx_set_hv_timer (vcpu, guest_deadline_tsc, expired); +} + +static void vt_cancel_hv_timer (struct kvm_vcpu *vcpu) +{ +/* VMX-preemption timer can't be set. Set vt_set_hv_timer(). */ +if (KVM_BUG_ON (is_td_vcpu (vcpu), vcpu->kvm)) +return ; + +vmx_cancel_hv_timer (vcpu); +} +#endif +static void vt_get_exit_info (struct kvm_vcpu *vcpu,u32 *reason,u64 *info1,u64 *info2,u32 *intr_info,u32 *error_code) {
@@ -522,29 +899,29 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .vcpu_load = vt_vcpu_load, .vcpu_put = vt_vcpu_put, - .update_exception_bitmap = vmx_update_exception_bitmap, + .update_exception_bitmap = vt_update_exception_bitmap, .get_msr_feature = vmx_get_msr_feature, .get_msr = vt_get_msr, .set_msr = vt_set_msr, - .get_segment_base = vmx_get_segment_base, - .get_segment = vmx_get_segment, - .set_segment = vmx_set_segment, - .get_cpl = vmx_get_cpl, - .get_cs_db_l_bits = vmx_get_cs_db_l_bits, - .set_cr0 = vmx_set_cr0, + .get_segment_base = vt_get_segment_base, + .get_segment = vt_get_segment, + .set_segment = vt_set_segment, + .get_cpl = vt_get_cpl, + .get_cs_db_l_bits = vt_get_cs_db_l_bits, + .set_cr0 = vt_set_cr0, .is_valid_cr4 = vmx_is_valid_cr4, - .set_cr4 = vmx_set_cr4, - .set_efer = vmx_set_efer, - .get_idt = vmx_get_idt, - .set_idt = vmx_set_idt, - .get_gdt = vmx_get_gdt, - .set_gdt = vmx_set_gdt, - .set_dr7 = vmx_set_dr7, - .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs, - .cache_reg = vmx_cache_reg, - .get_rflags = vmx_get_rflags, - .set_rflags = vmx_set_rflags, - .get_if_flag = vmx_get_if_flag, + .set_cr4 = vt_set_cr4, + .set_efer = vt_set_efer, + .get_idt = vt_get_idt, + .set_idt = vt_set_idt, + .get_gdt = vt_get_gdt, + .set_gdt = vt_set_gdt, + .set_dr7 = vt_set_dr7, + .sync_dirty_debug_regs = vt_sync_dirty_debug_regs, + .cache_reg = vt_cache_reg, + .get_rflags = vt_get_rflags, + .set_rflags = vt_set_rflags, + .get_if_flag = vt_get_if_flag, .flush_tlb_all = vt_flush_tlb_all, .flush_tlb_current = vt_flush_tlb_current,
@@ -558,10 +935,10 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .update_emulated_instruction = vmx_update_emulated_instruction, .set_interrupt_shadow = vt_set_interrupt_shadow, .get_interrupt_shadow = vt_get_interrupt_shadow, - .patch_hypercall = vmx_patch_hypercall, + .patch_hypercall = vt_patch_hypercall, .inject_irq = vt_inject_irq, .inject_nmi = vt_inject_nmi, - .queue_exception = vmx_queue_exception, + .queue_exception = vt_queue_exception, .cancel_injection = vt_cancel_injection, .interrupt_allowed = vt_interrupt_allowed, .nmi_allowed = vt_nmi_allowed,
@@ -569,39 +946,39 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .set_nmi_mask = vt_set_nmi_mask, .enable_nmi_window = vt_enable_nmi_window, .enable_irq_window = vt_enable_irq_window, - .update_cr8_intercept = vmx_update_cr8_intercept, - .set_virtual_apic_mode = vmx_set_virtual_apic_mode, - .set_apic_access_page_addr = vmx_set_apic_access_page_addr, - .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl, - .load_eoi_exitmap = vmx_load_eoi_exitmap, + .update_cr8_intercept = vt_update_cr8_intercept, + .set_virtual_apic_mode = vt_set_virtual_apic_mode, + .set_apic_access_page_addr = vt_set_apic_access_page_addr, + .refresh_apicv_exec_ctrl = vt_refresh_apicv_exec_ctrl, + .load_eoi_exitmap = vt_load_eoi_exitmap, .apicv_post_state_restore = vt_apicv_post_state_restore, .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons, - .hwapic_irr_update = vmx_hwapic_irr_update, - .hwapic_isr_update = vmx_hwapic_isr_update, - .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt, + .hwapic_irr_update = vt_hwapic_irr_update, + .hwapic_isr_update = vt_hwapic_isr_update, + .guest_apic_has_interrupt = vt_guest_apic_has_interrupt, .sync_pir_to_irr = vt_sync_pir_to_irr, .deliver_interrupt = vt_deliver_interrupt, .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt, .protected_apic_has_interrupt = vt_protected_apic_has_interrupt, - .set_tss_addr = vmx_set_tss_addr, - .set_identity_map_addr = vmx_set_identity_map_addr, - .get_mt_mask = vmx_get_mt_mask, + .set_tss_addr = vt_set_tss_addr, + .set_identity_map_addr = vt_set_identity_map_addr, + .get_mt_mask = vt_get_mt_mask, .get_exit_info = vt_get_exit_info, - .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid, + .vcpu_after_set_cpuid = vt_vcpu_after_set_cpuid, .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit, - .get_l2_tsc_offset = vmx_get_l2_tsc_offset, - .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier, - .write_tsc_offset = vmx_write_tsc_offset, - .write_tsc_multiplier = vmx_write_tsc_multiplier, + .get_l2_tsc_offset = vt_get_l2_tsc_offset, + .get_l2_tsc_multiplier = vt_get_l2_tsc_multiplier, + .write_tsc_offset = vt_write_tsc_offset, + .write_tsc_multiplier = vt_write_tsc_multiplier, .load_mmu_pgd = vt_load_mmu_pgd, - .check_intercept = vmx_check_intercept, + .check_intercept = vt_check_intercept, .handle_exit_irqoff = vt_handle_exit_irqoff, .request_immediate_exit = vt_request_immediate_exit,
@@ -609,7 +986,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .sched_in = vt_sched_in, .cpu_dirty_log_size = PML_ENTITY_NUM, - .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging, + .update_cpu_dirty_logging = vt_update_cpu_dirty_logging, .nested_ops = &vmx_nested_ops,
@@ -617,8 +994,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .pi_start_assignment = vmx_pi_start_assignment, #ifdef CONFIG_X86_64 - .set_hv_timer = vmx_set_hv_timer, - .cancel_hv_timer = vmx_cancel_hv_timer, + .set_hv_timer = vt_set_hv_timer, + .cancel_hv_timer = vt_cancel_hv_timer, #endif .setup_mce = vmx_setup_mce,
@@ -628,8 +1005,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .leave_smm = vt_leave_smm, .enable_smi_window = vt_enable_smi_window, - .can_emulate_instruction = vmx_can_emulate_instruction, - .apic_init_signal_blocked = vmx_apic_init_signal_blocked, + .can_emulate_instruction = vt_can_emulate_instruction, + .apic_init_signal_blocked = vt_apic_init_signal_blocked, .migrate_timers = vmx_migrate_timers, .msr_filter_changed = vmx_msr_filter_changed,
arch/x86/kvm/vmx/tdx.c +53 -2
73 lines not on this page · raw message
arch/x86/kvm/vmx/x86_ops.h +17 -0
@@ -163,6 +163,14 @@ int tdx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection);int tdx_enter_smm (struct kvm_vcpu *vcpu,char *smstate);int tdx_leave_smm (struct kvm_vcpu *vcpu,const char *smstate);void tdx_enable_smi_window (struct kvm_vcpu *vcpu); +void tdx_set_virtual_apic_mode (struct kvm_vcpu *vcpu); + +int tdx_get_cpl (struct kvm_vcpu *vcpu); +void tdx_cache_reg (struct kvm_vcpu *vcpu,enum kvm_reg reg); +unsigned long tdx_get_rflags (struct kvm_vcpu *vcpu); +bool tdx_is_emulated_msr (u32 index,bool write); +u64 tdx_get_segment_base (struct kvm_vcpu *vcpu,int seg); +void tdx_get_segment (struct kvm_vcpu *vcpu,struct kvm_segment *var,int seg);int tdx_vm_ioctl (struct kvm *kvm,void __user *argp);int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp);
@@ -203,10 +211,19 @@ static inline void tdx_get_exit_info(static inline bool tdx_is_emulated_msr (u32 index,bool write) {return false; }static inline int tdx_get_msr (struct kvm_vcpu *vcpu,struct msr_data *msr) {return 1 ; }static inline int tdx_set_msr (struct kvm_vcpu *vcpu,struct msr_data *msr) {return 1 ; } +static inline int tdx_smi_allowed (struct kvm_vcpu *vcpu,bool for_injection) {return false; }static inline int tdx_enter_smm (struct kvm_vcpu *vcpu,char *smstate) {return 0 ; }static inline int tdx_leave_smm (struct kvm_vcpu *vcpu,const char *smstate) {return 0 ; }static inline void tdx_enable_smi_window (struct kvm_vcpu *vcpu) {} +static inline void tdx_set_virtual_apic_mode (struct kvm_vcpu *vcpu) {} + +static inline int tdx_get_cpl (struct kvm_vcpu *vcpu) {return 0 ; } +static inline void tdx_cache_reg (struct kvm_vcpu *vcpu,enum kvm_reg reg) {} +static inline unsigned long tdx_get_rflags (struct kvm_vcpu *vcpu) {return 0 ; } +static inline u64 tdx_get_segment_base (struct kvm_vcpu *vcpu,int seg) {return 0 ;} +static inline void tdx_get_segment ( +struct kvm_vcpu *vcpu,struct kvm_segment *var,int seg) {}static inline int tdx_vm_ioctl (struct kvm *kvm,void __user *argp) {return -EOPNOTSUPP ; }static inline int tdx_vcpu_ioctl (struct kvm_vcpu *vcpu,void __user *argp) {return -EOPNOTSUPP ; }
Signature · 1 line
2.25.1
PATCH v7 101/102 Documentation/virtual/kvm: Document on Trust Domain Extensions(TDX)
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Add documentation to Intel Trusted Domain Extensions(TDX) support.
--- Documentation/virt/kvm/api.rst | 9 +- Documentation/virt/kvm/intel-tdx.rst | 381 +++++++++++++++++++++++++++ 2 files changed, 389 insertions(+), 1 deletion(-) create mode 100644 Documentation/virt/kvm/intel-tdx.rst
Documentation/virt/kvm/api.rst +8 -1
@@ -1402,6 +1402,9 @@ It is recommended to use this API instead of the KVM_SET_MEMORY_REGION ioctl. The KVM_SET_MEMORY_REGION does not allow fine grained control over memory allocation and is deprecated. +For TDX guest, deleting/moving memory region loses guest memory contents. +Read only region isn't supported. Only as-id 0 is supported. + 4.36 KVM_SET_TSS_ADDR ---------------------
@@ -4688,7 +4691,7 @@ H_GET_CPU_CHARACTERISTICS hypercall. :Capability: basic :Architectures: x86 -:Type: vm +:Type: vm ioctl, vcpu ioctl :Parameters: an opaque platform specific structure (in/out) :Returns: 0 on success; -1 on error
@@ -4700,6 +4703,10 @@ Currently, this ioctl is used for issuing Secure Encrypted Virtualization (SEV) commands on AMD Processors. The SEV commands are defined in Documentation/virt/kvm/amd-memory-encryption.rst. +Currently, this ioctl is used for issuing Trusted Domain Extensions +(TDX) commands on Intel Processors. The TDX commands are defined in +Documentation/virt/kvm/intel-tdx.rst. + 4.111 KVM_MEMORY_ENCRYPT_REG_REGION -----------------------------------
Documentation/virt/kvm/intel-tdx.rst new file +381 -0
381 lines not on this page · raw message
Signature · 1 line
2.25.1
Re: [PATCH v7 101/102] Documentation/virtual/kvm: Document on Trust Domain Extensions(TDX)
Quoted 16 lines
Documentation/virt/kvm/intel-tdx.rst new file +15
-0+ +- Wrapping kvm x86_ops: The current choice + Introduce dedicated file for arch/x86/kvm/vmx/main.c (the name, + main.c, is just chosen to show main entry points for callbacks.) and + wrapper functions around all the callbacks with + "if (is-tdx) tdx-callback() else vmx-callback()". + + Pros: + - No major change in common x86 KVM code. The change is (mostly) + contained under arch/x86/kvm/vmx/. + - When TDX is disabled(CONFIG_INTEL_TDX_HOST=n), the overhead is + optimized out. + - Micro optimization by avoiding function pointer. + Cons: + - Many boiler plates in arch/x86/kvm/vmx/main.c.
Documentation/virt/kvm/intel-tdx.rst line 250
Quoted 10 lines
Documentation/virt/kvm/intel-tdx.rst new file +10
-0+ +Alternative: +- Introduce another callback layer under arch/x86/kvm/vmx. + Pros: + - No major change in common x86 KVM code. The change is (mostly) + contained under arch/x86/kvm/vmx/. + - clear separation on callbacks. + Cons: + - overhead in VMX even when TDX is disabled(CONFIG_INTEL_TDX_HOST=n). +
Why putting "Alternative" in the documentation? You may put it to the cover letter so people can judge whether the design is reasonable, but it should not be in the documentation.
Signature · 2 lines
Thanks, -Kai
PATCH v7 102/102 KVM: x86: design documentation on TDX support of x86 KVM TDP MMU
In reply to [email protected]From: Isaku Yamahata <[email protected]>
Add a high level design document on TDX changes to TDP MMU.
--- Documentation/virt/kvm/tdx-tdp-mmu.rst | 466 +++++++++++++++++++++++++ 1 file changed, 466 insertions(+) create mode 100644 Documentation/virt/kvm/tdx-tdp-mmu.rst
Documentation/virt/kvm/tdx-tdp-mmu.rst new file +466 -0
@@ -0,0 +1,466 @@ +.. SPDX-License-Identifier: GPL-2.0 + +Design of TDP MMU for TDX support +================================= +This document describes a (high level) design for TDX support of KVM TDP MMU of +x86 KVM. + +In this document, we use "TD" or "guest TD" to differentiate it from the current +"VM" (Virtual Machine), which is supported by KVM today. + + +Background of TDX +================= +TD private memory is designed to hold TD private content, encrypted by the CPU +using the TD ephemeral key. An encryption engine holds a table of encryption +keys, and an encryption key is selected for each memory transaction based on a +Host Key Identifier (HKID). By design, the host VMM does not have access to the +encryption keys. + +In the first generation of MKTME, HKID is "stolen" from the physical address by +allocating a configurable number of bits from the top of the physical address. +The HKID space is partitioned into shared HKIDs for legacy MKTME accesses and +private HKIDs for SEAM-mode-only accesses. We use 0 for the shared HKID on the +host so that MKTME can be opaque or bypassed on the host. + +During TDX non-root operation (i.e. guest TD), memory accesses can be qualified +as either shared or private, based on the value of a new SHARED bit in the Guest +Physical Address (GPA). The CPU translates shared GPAs using the usual VMX EPT +(Extended Page Table) or "Shared EPT" (in this document), which resides in the +host VMM memory. The Shared EPT is directly managed by the host VMM - the same +as with the current VMX. Since guest TDs usually require I/O, and the data +exchange needs to be done via shared memory, thus KVM needs to use the current +EPT functionality even for TDs. + +The CPU translates private GPAs using a separate Secure EPT. The Secure EPT +pages are encrypted and integrity-protected with the TD's ephemeral private key. +Secure EPT can be managed _indirectly_ by the host VMM, using the TDX interface +functions (SEAMCALLs), and thus conceptually Secure EPT is a subset of EPT +because not all functionalities are available. + +Since the execution of such interface functions takes much longer time than +accessing memory directly, in KVM we use the existing TDP code to mirror the +Secure EPT for the TD. And we think there are at least two options today in +terms of the timing for executing such SEAMCALLs: + +1. synchronous, i.e. while walking the TDP page tables, or +2. post-walk, i.e. record what needs to be done to the real Secure EPT during + the walk, and execute SEAMCALLs later. + +The option 1 seems to be more intuitive and simpler, but the Secure EPT +concurrency rules are different from the ones of the TDP or EPT. For example, +MEM.SEPT.RD acquire shared access to the whole Secure EPT tree of the target + +Secure EPT(SEPT) operations +--------------------------- +Secure EPT is an Extended Page Table for GPA-to-HPA translation of TD private +HPA. A Secure EPT is designed to be encrypted with the TD's ephemeral private +key. SEPT pages are allocated by the host VMM via Intel TDX functions, but their +content is intended to be hidden and is not architectural. + +Unlike the conventional EPT, the CPU can't directly read/write its entry. +Instead, TDX SEAMCALL API is used. Several SEAMCALLs correspond to operation on +the EPT entry. + +* TDH.MEM.SEPT.ADD(): + Add a secure EPT page from the secure EPT tree. This corresponds to updating + the non-leaf EPT entry with present bit set + +* TDH.MEM.SEPT.REMOVE(): + Remove the secure page from the secure EPT tree. There is no corresponding + to the EPT operation. + +* TDH.MEM.SEPT.RD(): + Read the secure EPT entry. This corresponds to reading the EPT entry as + memory. Please note that this is much slower than direct memory reading. + +* TDH.MEM.PAGE.ADD() and TDH.MEM.PAGE.AUG(): + Add a private page to the secure EPT tree. This corresponds to updating the + leaf EPT entry with present bit set. + +* THD.MEM.PAGE.REMOVE(): + Remove a private page from the secure EPT tree. There is no corresponding + to the EPT operation. + +* TDH.MEM.RANGE.BLOCK(): + This (mostly) corresponds to clearing the present bit of the leaf EPT entry. + Note that the private page is still linked in the secure EPT. To remove it + from the secure EPT, TDH.MEM.SEPT.REMOVE() and TDH.MEM.PAGE.REMOVE() needs to + be called. + +* TDH.MEM.TRACK(): + Increment the TLB epoch counter. This (mostly) corresponds to EPT TLB flush. + Note that the private page is still linked in the secure EPT. To remove it + from the secure EPT, tdh_mem_page_remove() needs to be called. + + +Adding private page +------------------- +The procedure of populating the private page looks as follows. + +1. TDH.MEM.SEPT.ADD(512G level) +2. TDH.MEM.SEPT.ADD(1G level) +3. TDH.MEM.SEPT.ADD(2M level) +4. TDH.MEM.PAGE.AUG(4K level) + +Those operations correspond to updating the EPT entries. + +Dropping private page and TLB shootdown +--------------------------------------- +The procedure of dropping the private page looks as follows. + +1. TDH.MEM.RANGE.BLOCK(4K level) + This mostly corresponds to clear the present bit in the EPT entry. This + prevents (or blocks) TLB entry from creating in the future. Note that the + private page is still linked in the secure EPT tree and the existing cache + entry in the TLB isn't flushed. +2. TDH.MEM.TRACK(range) and TLB shootdown + This mostly corresponds to the EPT TLB shootdown. Because all vcpus share + the same Secure EPT, all vcpus need to flush TLB. + * TDH.MEM.TRACK(range) by one vcpu. It increments the global internal TLB + epoch counter. + * send IPI to remote vcpus + * Other vcpu exits to VMM from guest TD and then re-enter. TDH.VP.ENTER(). + * TDH.VP.ENTER() checks the TLB epoch counter and If its TLB is old, flush + TLB. + Note that only single vcpu issues tdh_mem_track(). + Note that the private page is still linked in the secure EPT tree, unlike the + conventional EPT. +3. TDH.MEM.PAGE.PROMOTE, TDH.MEM.PAGEDEMOTE(), TDH.MEM.PAGE.RELOCATE(), or + TDH.MEM.PAGE.REMOVE() + There is no corresponding operation to the conventional EPT. + * When changing page size (e.g. 4K <-> 2M) TDH.MEM.PAGE.PROMOTE() or + TDH.MEM.PAGE.DEMOTE() is used. During those operation, the guest page is + kept referenced in the Secure EPT. + * When migrating page, TDH.MEM.PAGE.RELOCATE(). This requires both source + page and destination page. + * when destroying TD, TDH.MEM.PAGE.REMOVE() removes the private page from the + secure EPT tree. In this case TLB shootdown is not needed because vcpus + don't run any more. + +The basic idea for TDX support +============================== +Because shared EPT is the same as the existing EPT, use the existing logic for +shared EPT. On the other hand, secure EPT requires additional operations +instead of directly reading/writing of the EPT entry. + +On EPT violation, The KVM mmu walks down the EPT tree from the root, determines +the EPT entry to operate, and updates the entry. If necessary, a TLB shootdown +is done. Because it's very slow to directly walk secure EPT by TDX SEAMCALL, +TDH.MEM.SEPT.RD(), the mirror of secure EPT is created and maintained. Add +hooks to KVM MMU to reuse the existing code. + +EPT violation on shared GPA +--------------------------- +(1) EPT violation on shared GPA or zapping shared GPA + walk down shared EPT tree (the existing code) + | + | + V +shared EPT tree (CPU refers.) +(2) update the EPT entry. (the existing code) + TLB shootdown in the case of zapping. + + +EPT violation on private GPA +---------------------------- +(1) EPT violation on private GPA or zapping private GPA + walk down the mirror of secure EPT tree (mostly same as the existing code) + | + | + V +mirror of secure EPT tree (KVM MMU software only. reuse of the existing code) +(2) update the (mirrored) EPT entry. (mostly same as the existing code) +(3) call the hooks with what EPT entry is changed + | + NEW: hooks in KVM MMU + | + V +secure EPT root(CPU refers) +(4) the TDX backend calls necessary TDX SEAMCALLs to update real secure EPT. + +The major modification is to add hooks for the TDX backend for additional +operations and to pass down which EPT, shared EPT, or private EPT is used, and +twist the behavior if we're operating on private EPT. + +The following depicts the relationship. +:: + + KVM | TDX module + | | | + -------------+---------- | | + | | | | + V V | | + shared GPA private GPA | | + CPU shared EPT pointer KVM private EPT pointer | CPU secure EPT pointer + | | | | + | | | | + V V | V + shared EPT private EPT<-------mirror----->Secure EPT + | | | | + | \--------------------+------\ | + | | | | + V | V V + shared guest page | private guest page + | + | + non-encrypted memory | encrypted memory + | + +shared EPT: CPU and KVM walk with shared GPA + Maintained by the existing code +private EPT: KVM walks with private GPA + Maintained by the twisted existing code +secure EPT: CPU walks with private GPA. + Maintained by TDX module with TDX SEAMCALLs via hooks + + +Tracking private EPT page +========================= +Shared EPT pages are managed by struct kvm_mmu_page. They are linked in a list +structure. When necessary, the list is traversed to operate on. Private EPT +pages have different characteristics. For example, private pages can't be +swapped out. When shrinking memory, we'd like to traverse only shared EPT pages +and skip private EPT pages. Likewise, page migration isn't supported for +private pages (yet). Introduce an additional list to track shared EPT pages and +track private EPT pages independently. + +At the beginning of EPT violation, the fault handler knows fault GPA, thus it +knows which EPT to operate on, private or shared. If it's private EPT, +an additional task is done. Something like "if (private) { callback a hook }". +Since the fault handler has deep function calls, it's cumbersome to hold the +information of which EPT is operating. Options to mitigate it are + +1. Pass the information as an argument for the function call. +2. Record the information in struct kvm_mmu_page somehow. +3. Record the information in vcpu structure. + +Option 2 was chosen. Because option 1 requires modifying all the functions. It +would affect badly to the normal case. Option 3 doesn't work well because in +some cases, we need to walk both private and shared EPT. + +The role of the EPT page can be utilized and one bit can be curved out from +unused bits in struct kvm_mmu_page_role. When allocating the EPT page, +initialize the information. Mostly struct kvm_mmu_page is available because +we're operating on EPT pages. + + +The conversion of private GPA and shared GPA +============================================ +A page of a given GPA can be assigned to only private GPA xor shared GPA at one +time. The GPA can't be accessed simultaneously via both private GPA and shared +GPA. On guest startup, all the GPAs are assigned as private. Guest converts +the range of GPA to shared (or private) from private (or shared) by MapGPA +hypercall. MapGPA hypercall takes the start GPA and the size of the region. If +the given start GPA is shared, VMM converts the region into shared (if it's +already shared, nop). If the start GPA is private, VMM converts the region into +private. It implies the guest won't access the unmapped region. private(or +shared) region after converting to shared(or private). + +If the guest TD triggers an EPT violation on the already converted region, the +access won't be allowed (loop in EPT violation) until other vcpu converts back +the region. + +KVM MMU records which GPA is allowed to access, private or shared. It steals +software usable bit from MMU present mask. SPTE_SHARED_MASK. The bit is +recorded in both shared EPT and the mirror of secure EPT. + +* If SPTE_SHARED_MASK cleared in the shared EPT and the mirror of secure EPT: + Private GPA is allowed. Shared GPA is not allowed. + +* SPTE_SHARED_MASK set in the shared EPT and the mirror of secure EPT: + Private GPA is not allowed. Shared GPA is allowed. + +The default is that SPTE_SHARED_MASK is cleared so that the existing KVM +MMU code (mostly) works. + +The reason why the bit is recorded in both shared and private EPT is to optimize +for EPT violation path by penalizing MapGPA hypercall. + +The state machine of EPT entry +------------------------------ +(private EPT entry, shared EPT entry) = + (non-present, non-present): private mapping is allowed + (present, non-present): private mapping is mapped + (non-present | SPTE_SHARED_MASK, non-present | SPTE_SHARED_MASK): + shared mapping is allowed + (non-present | SPTE_SHARED_MASK, present | SPTE_SHARED_MASK): + shared mapping is mapped + (present | SPTE_SHARED_MASK, any) invalid combination + +* map_gpa(private GPA): Mark the region that private GPA is allowed(NEW) + private EPT entry: clear SPTE_SHARED_MASK + present: nop + non-present: nop + non-present | SPTE_SHARED_MASK -> non-present (clear SPTE_SHARED_MASK) + + shared EPT entry: zap the entry, clear SPTE_SHARED_MASK + present: invalid + non-present -> non-present: nop + present | SPTE_SHARED_MASK -> non-present + non-present | SPTE_SHARED_MASK -> non-present + +* map_gpa(shared GPA): Mark the region that shared GPA is allowed(NEW) + private EPT entry: zap and set SPTE_SHARED_MASK + present -> non-present | SPTE_SHARED_MASK + non-present -> non-present | SPTE_SHARED_MASK + non-present | SPTE_SHARED_MASK: nop + + shared EPT entry: set SPTE_SHARED_MASK + present: invalid + non-present -> non-present | SPTE_SHARED_MASK + present | SPTE_SHARED_MASK -> present | SPTE_SHARED_MASK: nop + non-present | SPTE_SHARED_MASK -> non-present | SPTE_SHARED_MASK: nop + +* map(private GPA) + private EPT entry + present: nop + non-present -> present + non-present | SPTE_SHARED_MASK: nop. looping on EPT violation(NEW) + + shared EPT entry: nop + +* map(shared GPA) + private EPT entry: nop + + shared EPT entry + present: invalid + present | SPTE_SHARED_MASK: nop + non-present | SPTE_SHARED_MASK -> present | SPTE_SHARED_MASK + non-present: nop. looping on EPT violation(NEW) + +* zap(private GPA) + private EPT entry: zap the entry with keeping SPTE_SHARED_MASK + present -> non-present + present | SPTE_SHARED_MASK: invalid + non-present: nop as is_shadow_present_pte() is checked + non-present | SPTE_SHARED_MASK: nop as is_shadow_present_pte() is + checked + + shared EPT entry: nop + +* zap(shared GPA) + private EPT entry: nop + + shared EPT entry: zap + any -> non-present + present: invalid + present | SPTE_SHARED_MASK -> non-present | SPTE_SHARED_MASK + non-present: nop as is_shadow_present_pte() is checked + non-present | SPTE_SHARED_MASK: nop as is_shadow_present_pte() is + checked + + +The original TDP MMU and race condition +======================================= +Because vcpus share the EPT, once the EPT entry is zapped, we need to shootdown +TLB. Send IPI to remote vcpus. Remote vcpus flush their down TLBs. Until TLB +shootdown is done, vcpus may reference the zapped guest page. + +TDP MMU uses read lock of mmu_lock to mitigate vcpu contention. When read lock +is obtained, it depends on the atomic update of the EPT entry. (On the other +hand legacy MMU uses write lock.) When vcpu is populating/zapping the EPT entry +with a read lock held, other vcpu may be populating or zapping the same EPT +entry at the same time. + +To avoid the race condition, the entry is frozen. It means the EPT entry is set +to the special value, REMOVED_SPTE which clears the present bit. And then after +TLB shootdown, update the EPT entry to the final value. + +Concurrent zapping +------------------ +1. read lock +2. freeze the EPT entry (atomically set the value to REMOVED_SPTE) + If other vcpu froze the entry, restart page fault. +3. TLB shootdown + * send IPI to remote vcpus + * TLB flush (local and remote) + For each entry update, TLB shootdown is needed because of the + concurrency. +4. atomically set the EPT entry to the final value +5. read unlock + +Concurrent populating +--------------------- +In the case of populating the non-present EPT entry, atomically update the EPT +entry. +1. read lock +2. atomically update the EPT entry + If other vcpu frozen the entry or updated the entry, restart page fault. +3. read unlock + +In the case of updating the present EPT entry (e.g. page migration), the +operation is split into two. Zapping the entry and populating the entry. +1. read lock +2. zap the EPT entry. follow the concurrent zapping case. +3. populate the non-present EPT entry. +4. read unlock + +Non-concurrent batched zapping +------------------------------ +In some cases, zapping the ranges is done exclusively with a write lock held. +In this case, the TLB shootdown is batched into one. + +1. write lock +2. zap the EPT entries by traversing them +3. TLB shootdown +4. write unlock + + +For Secure EPT, TDX SEAMCALLs are needed in addition to updating the mirrored +EPT entry. + +TDX concurrent zapping +---------------------- +Add a hook for TDX SEAMCALLs at the step of the TLB shootdown. + +1. read lock +2. freeze the EPT entry(set the value to REMOVED_SPTE) +3. TLB shootdown via a hook + * TLB.MEM.RANGE.BLOCK() + * TLB.MEM.TRACK() + * send IPI to remote vcpus +4. set the EPT entry to the final value +5. read unlock + +TDX concurrent populating +------------------------- +TDX SEAMCALLs are required in addition to operating the mirrored EPT entry. The +frozen entry is utilized by following the zapping case to avoid the race +condition. A hook can be added. + +1. read lock +2. freeze the EPT entry +3. hook + * TDH_MEM_SEPT_ADD() for non-leaf or TDH_MEM_PAGE_AUG() for leaf. +4. set the EPT entry to the final value +5. read unlock + +Without freezing the entry, the following race can happen. Suppose two vcpus +are faulting on the same GPA and the 2M and 4K level entries aren't populated +yet. + +* vcpu 1: update 2M level EPT entry +* vcpu 2: update 4K level EPT entry +* vcpu 2: TDX SEAMCALL to update 4K secure EPT entry => error +* vcpu 1: TDX SEAMCALL to update 2M secure EPT entry + + +TDX non-concurrent batched zapping +---------------------------------- +For simplicity, the procedure of concurrent populating is utilized. The +procedure can be optimized later. + + +Co-existing with unmapping guest private memory +=============================================== +TODO. This needs to be addressed. + + +Restrictions or future work +=========================== +The following features aren't supported yet at the moment. + +* optimizing non-concurrent zap +* Large page +* Page migration
Signature · 1 line
2.25.1
Hi. Because my description on large page support was terse, I wrote up more detailed one. Any feedback/thoughts on large page support?
TDP MMU large page support design
Two main discussion points
* how to track page status. private vs shared, no-largepage vs can-be-largepage
* how to trigger merging mapping from 4KB/2MB to 2MB/1GB
Expected private-vs-shared page usage
-------------------------------------
On TD boot all pages are private and TD converts pages into shared if necessary.
* Most of the guest pages remain private.
* Only limited pages are converted at kernel boot
** bounce buffer for IO (virt-io). It's allocated as swiotlb. Its size is
64MB or 6% of total guest memory.
** KVM PV shared page. (the current guest TD doesn't use KVM PV shared page.)
* Only a small number of pages are dynamically converted from private to shared and vice versa. This usage is very limited. e.g. GetQuote, the lack of swiotlb buffer
Theory of Secure-EPT operations related to large page
-----------------------------------------------------
TDX Secure-EPT has differences from VMX EPT. To add a page to Secure-EPT
* Here is the operation to resolve the EPT violation.
1. TD: Accepts GPA. TD needs to accept GPA before accessing GPA because TD needs to detect that VMM unmaps GPA and maps GPA again.
2. EPT violation is triggered. TD exit to VMM.
3. VMM: allocate a page for GPA and TDH.MEM.PAGE.AUG it to GPA. Resume TD vcpu. (3a. TD: #VE<EPT violation> is injected. #VE handler accepts the page)
4. TD: resume #VE and continue TD vcpu execution
TD may choose step 1. In that case, After step 3. #VE is injected into TD and, TD #VE handler needs to accept the page.
When adding a page to Secure-EPT again, the page contexts are cleared and the page is encrypted. If a page is disassociated from Secure-EPT and added again, the page content is lost.
* TDG.VP.VMCALL<MapGPA> hypercall
The page associated with GPA can be private or shared. TD converts the GPA by TDG.VP.VMCALL<MapGPA> hypercall from private to shared or vice versa. VMM tracks whether the given GPA is private or shared.
* mapping merge(promote)/split(demote)
The page can be mapped as large page (2MB or 1GB) in addition to 4KB. The mapping can be merged(4KB/2MB -> 2MB/1GB) or split(2MB/1GB -> 4KB/2MB) by TDX SEAMCALL TDH.MEM.PAGE.PROMOTE and TDH.MEM.PAGE.DEMOTE.
The merge of mapping requires all the pages needs to be mapped, unlike VMX EPT because of encryption. This implies the current KVM implementation doesn't work for TDX when merging mapping as follows
- EPT violation and host page is 2MB mappable.
some of the 4KB pages of the given 2MB page are already mapped, some not. i.e. 2MB EPT -> 4KB EPT -> 4K pages
- KVM page fault handler zap 2MB EPT entry and populate 2MB EPT entry
zap: 2MB EPT: non present
populate 2MB: -> 2MB page
If VMM zaps 2MB Secure-EPT entry, the page contents will be lost for TDX. Mapping merge requires all pages are already mapped.
Instead, the following steps are needed.
- EPT violation and host page is 2MB mappable.
some of the 4KB pages of the given 2MB page are already mapped. Some not. i.e. 2MB EPT -> 4KB EPT -> 4K pages
- VMM checks all 4KB GPAs are private. If not, it can't be mapped as a large page. (****)
- VMM checks all 4KB GPAs are already mapped. If not, give up mapping merge. (or map missing 4KB pages.)
- mapping merge by TDH.MEM.PAGE.PROMOTE
The mapping split for TDX Secure-EPT works similarly to the VMX EPT case.
EPT violation and MapGPA
------------------------
- EPT violation is a fast path
- MapGPA is not a fast path.
=> Keep the EPT violation path optimized and complicates the MapGPA path. For (****) check, we don't want to scan the 4KB mapping on EPT violation. Instead, the MapGPA path scans it and records the result as the page can be mapped as 2MB due to private/shared.
Tracking private/shared and large page mappable
-----------------------------------------------
VMM needs to track that page is mapped as private or shared at 4KB granularity. For efficiency of EPT violation path (****), at 2MB and 1GB level, VMM should track the page can be mapped as a large page (regarding private/shared). VMM updates it on MapGPA and references it on the EPT violation path. (****)
For 4KB pages, 1 bit is needed. private or shared. Let's call it shared-mask bit. For 2MB/1GB pages, 2 bit is needed. large page mappable or not. private or shared if mappable. Let's call it no-largepage bit.
Option A.)
Allocate array for pages in struct kvm_arch_memory_slot on TD creation.
struct kvm_arch_memory_slot {
+struct kvm_page_attr *page_attr[KVM_NR_PAGE_SIZES];}
pros:
+straight forward implementation
+SPTE_SHARED_MASK is not needed
cons:
-memory overhead is high
-not optimized for expected usage
-one more look-up on EPT violation
Option B.) Steal two software usable bits from SPTE and record them in SPTE.
SPTE_SHARED_MASK, SPTE_NOLARGE_PAGE_MASK
pros:
+optimized for EPT violation
cons:
-2bits used in SPTE entry
-complicates the MapGPA path.
Option C.) Steal one software usable bit from SPTE and record it in SPTE.
SPTE_SHARED_MASK
For 2MB/1GB, allocate bitmap in kvm_mmu_page.
struct kvm_mmu_page {
bitmap nolarge
} pros:
+optimized for EPT violation
cons:
-complicates the MapGPA path.
-information is scattered in SPTE and struct kvm_mmu_page
How to update those bits
------------------------
- MapGPA
- at 4KB level, set or clear shared-mask bit.
- Scan 512 4KB bit, at 2MB level
- set or clear shared-mask bit, clear no-largepage bit or
- clear shared-mask bit, set no-largepage bit
- increment/decrement lpageinfo to prevent/allow large page
- similar for 1GB level
Note: This logic might a bit tricky.
- EPT violation
- If 2MB large page is allowed, check if no-largepage bit
- If no-largepage bit is set, => go down to 4KB page
- If no-largepage bit is cleared => try to map 2MB page
- If 4KB level is not mapped, map 2MB page
- If some 4KB level is already mapped, go down to 4KB. Don't try to merge mapping. Or it's possible to try to merge mapping.
Note: 512 4KB entry scanning is not done at EPT violation because it's fast
path.
Map merging
-----------
Map merging is necessary for TD migration. (Map split is the easy part.) The current KVM implementation zaps the range (mmu notification or lpage recovery worker) and expects large page mapping on the next EPT violation.
Option A.) Keep the code similar to map merging logic.
Zap 2MB EPT entry in some sense and trigger map merging logic on the next EPT violation. To keep encrypted page contents, zapped EPT entries needs to keep the page. Steal one more bits from SPTE. SPTE_PRIVATE_BLOCKED_MASK. It means that the page is zapped from SPTE. but it still alive and references page.
Option B.) In the callback, directly merge mapping somehow. In this case, mmu notifier usage doesn't make sense.
NOTE:
- Implement map merging in MapGPA. This doesn't work for dirty page logging.
- We can utilize kvm_nx_lpage_recovery_worker
- We can utilize THP. Probably doesn't work well for fd-based private memory.
Thanks,
Isaku Yamayhata
Quoted 775 lines · On Mon, Jun 27, 2022 at 02:52:52PM -0700, [email protected] wrote:
From: Isaku Yamahata <[email protected]>
KVM TDX basic feature support
Hello. This is v7 the patch series vof KVM TDX support.
This is based on v5.19-rc1 + kvm/queue branch + TDX HOST patch series. The tree can be found at https://github.com/intel/tdx/tree/kvm-upstream
How to run/test: It's describe at https://github.com/intel/tdx/wiki/TDX-KVMMajor changes from v6:
- rebased to v5.19 baseTODO:
- integrate fd-based guest memory. As the discussion is still on-going, I intentionally dropped fd-based guest memory support yet. The integration can be found at https://github.com/intel/tdx/tree/kvm-upstream-workaround.
- 2M large page support. It's work-in-progress.
For large page support, there are several design choices. Here is the design options. Any thoughts/feedback?KVM MMU Large page support for TDX
* What needs to be done
- Track private or shared of each page size (4KB, 2MB, 1GB) based on TDG.VP.VMCALL<MapGPA>. For largepages(2MB, 1GB), it can be mixed (some lower-size pages are private and some shared.) In this case, the page can't be large.
- if necessary, split large page on TDG.VP.VMCALL<MapGPA>
(split on dirty page tracking is future work)
- resolving KVM page fault
When resolving a private page and the page is large in the host, GPA can be resolved as a large page in Secure-EPT. Even if the page is large on the host side, sometimes a 4KB page can be resolved because it's up to guest TD to accept at 4KB, 2MB, or 1GB.
- collapsing pages into a large page.
At this point, it's okay to not implement this. When dirty page tracking is supported, this needs to be supported.
- On MapGPA, the page can be collapsed into a large page
- handle zapping SPTE and try to collapse the pages on the next KVM page fault Unlike the EPT case, some trick is needed.
- For performance, optimize KVM page fault path at the cost of complicating MapGPA path.* options to track private or shared
At each page size (4KB, 2MB, and 1GB), track private, shared, or mixed (2MB and 1GB case). For 4KB each page, 1 bit per page is needed. private or shared. For large pages (2MB and 1GB), 2 bits per large page is needed. (private, shared, or mixed). When resolving KVM page fault, we don't want to check the lower-size pages to check if the given GPA can be a large for performance. On MapGPA check it instead.Option A). enhance
kvm_arch_memory_slot
enumkvm_page_type{
KVM_PAGE_TYPE_INVALID,
KVM_PAGE_TYPE_SHARED,
KVM_PAGE_TYPE_PRIVATE,
KVM_PAGE_TYPE_MIXED,
};struct kvm_page_attr { enum kvm_page_type type; };struct
kvm_arch_memory_slot{
+ structkvm_page_attr*page_attr[KVM_NR_PAGE_SIZES];Option B). steal one more bit
SPTE_MIXED_MASKin addition toSPTE_SHARED_MASKIf !SPTE_MIXED_MASK, it can be large page.Option C). use
SPTE_SHARED_MASKandkvm_mmu_page::mixedbitmapkvm_mmu_page::mixedbitmap of 1GB, root indicates mixed for 2MB, 1GB.* comparison
A).
+ straightforward to implement
+SPTE_SHARED_MASKisn't needed
- memory overhead compared to B). or C).
- more memory reference on KVM page faultB).
+ simpler than C) (complex than A)?)
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- Waste precious SPTE bits.C).
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- complicates MapGPA
- scattered data structureThanks,
Isaku YamahataChanges from v6:
- rebased to v5.19Changes from v5:
- export__seamcalland use it
- move mutex lock from callee function ofsmp_call_on_cputo the caller.
- renamemmu_prezap=>flush_shadow_all_private()andtdx_mmu_release_hkid
- updated comment
- drop the use oftdh_mng_key.reclaimid(): as the function is for backward compatibility to only return success
- structkvm_tdx_cmd: metadata => flags, added__u64error.
- make this ioctl systemwide ioctl
- ABI change to structkvm_init_vm
-guest_tsc_khz: usekvm->arch.default_tsc_khz
- renameBUILD_BUG_ON_MEMCPYtoMEMCPY_SAME_SIZE
- drop exportingkvm_set_tsc_khz().
- fixkvm_tdp_page_fault()for mtrr emulation
- rename it tokvm_gfn_shared_mask(), droppedkvm_gpa_shared_mask()
- dropkvm_is_private_gfn(), keptkvm_is_private_gpa()
keep kvm_{gfn, gpa}_private(),kvm_gpa_private()
- update commit message
- renameshadow_init_value=>shadow_nonprsent_value
- addedept_violation_ve_testmode
-shadow_nonpresent_value=>SHADOW_NONPRESENT_VALUEintdp_mmu.c
- legacy MMU case
=> -mmu_topup_shadow_page_cache(),kvm_mmu_create()
- FNAME(sync_page)(structkvm_vcpu*vcpu, structkvm_mmu_page*sp)
- #VE warning:
- rename:REMOVED_SPTE=>__REMOVED_SPTE,SHADOW_REMOVED_SPTE=>REMOVED_SPTE
- merge into Like we discussed, this patch should be merged with patch "KVM: x86/mmu: Allow non-zero init value for shadow PTE".
- fix pointed by Sagi. check !is_private check => (kvm_gfn_shared_mask&& !is_private)
- introducekvm_gfn_for_root(kvm, root, gfn)
- addonly_sharedargument tokvm_tdp_mmu_handle_gfn()
- usekvm_arch_dirty_log_supported()
- renameSPTE_PRIVATE_PROHIBITtoSPTE_SHARED_MASK.
- rename:is_private_prohibit_spte()=>spte_shared_mask()
- fix:shadow_nonpresent_value=>SHADOW_NONPRESENT_VALUEin comment
- dropped this patch as the change was merged into kvm/queue
- updatevt_apicv_post_state_restore()
- useis_64_bit_hypercall()
- comment: expand MSMI -> Machine Check System Management Interrupt
- fixedTDX_SEPT_PFERR
- tdvmcall_p[1234]_{write, read}() => tdvmcall_a[0123]_{read,write}()
- renametdmvcall_exit_readon()=>tdvmcall_leaf()
- remove optional zero check of argument.
- do a check for static_call(kvm_x86_has_emulated_msr)(kvm,MSR_IA32_SMBASE) inkvm_vcpu_ioctl_smiand__apic_accept_irq.
-WARN_ON_ONCEintdx_smi_allowedandtdx_enable_smi_window.
- introducevcpu_deliver_inittox86_ops
- sprinkeledKVM_BUG_ON()Changes from v4:
- rebased to TDX host kernel patch series.
- include all the patches to make this patch series working.
- add [MARKER] patches to mark the patch layer clear.---
* What's TDX?
TDX stands for Trust Domain Extensions, which extends Intel Virtual Machines Extensions (VMX) to introduce a kind of virtual machine guest called a Trust Domain (TD) for confidential computing.A TD runs in a CPU mode that is designed to protect the confidentiality of its memory contents and its CPU state from any other software, including the hosting Virtual Machine Monitor (VMM), unless explicitly shared by the TD itself.
We have more detailed explanations below (***). We have the high-level design of TDX KVM below (****).
In this patch series, we use "TD" or "guest TD" to differentiate it from the current "VM" (Virtual Machine), which is supported by KVM today.
* The organization of this patch series
This patch series is on top of the patches series "TDX host kernel support":
https://lore.kernel.org/lkml/[email protected]/this patch series is available at
https://github.com/intel/tdx/releases/tag/kvm-upstream
The corresponding patches to qemu are available at
https://github.com/intel/qemu-tdx/commits/tdx-upstreamThe relations of the layers are depicted as follows.
The arrows below show the order of patch reviews we would like to have.The below layers are chosen so that the device model, for example, qemu can exercise each layering step by step. Check if TDX is supported, create TD VM, create TD vcpu, allow vcpu running, populate TD guest private memory, and handle vcpu exits/hypercalls/interrupts to run TD fully.
TDX vcpu
interrupt/exits/hypercall<------------\^ | | | TD finalization | ^ | | | TDX EPT violation<------------\ | ^ | | | | | TD vcpu enter/exit | | ^ | | | | | TD vcpu creation/destruction | \-------KVM TDP MMU MapGPA ^ | ^ | | | TD VM creation/destruction \---------------KVM TDP MMU hooks^ ^
| |
TDX architectural definitions KVM TDP refactoring for TDX
^ ^
| |
TDX, VMX <--------TDX host kernel KVM MMU GPA stolen bits
coexistence supportThe followings are explanations of each layer. Each layer has a dummy commit that starts with [MARKER] in subject. It is intended to help to identify where each layer starts.
TDX host kernel support:
https://lore.kernel.org/lkml/[email protected]/
The guts of system-wide initialization of TDX module. There is an independent patch series for host x86. TDX KVM patches call functions this patch series provides to initialize the TDX module.TDX, VMX coexistence:
Infrastructure to allow TDX to coexist with VMX and trigger the initialization of the TDX module.
This layer starts with
"KVM: VMX: Move outvmx_x86_opsto 'main.c' to wrap VMX and TDX"
TDX architectural definitions:
Add TDX architectural definitions and helper functions
This layer starts with
"[MARKER] The start of TDX KVM patch series: TDX architectural definitions".
TD VM creation/destruction:
Guest TD creation/destroy allocation and releasing of TDX specific vm and vcpu structure. Create an initial guest memory image with TDX measurement.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD VM creation/destruction".
TD vcpu creation/destruction:
guest TD creation/destroy Allocation and releasing of TDX specific vm and vcpu structure. Create an initial guest memory image with TDX measurement.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu creation/destruction"
TDX EPT violation:
Create an initial guest memory image with TDX measurement. Handle secure EPT violations to populate guest pages with TDX SEAMCALLs. This layer starts with
"[MARKER] The start of TDX KVM patch series: TDX EPT violation"
TD vcpu enter/exit:
Allow TDX vcpu to enter into TD and exit from TD. Save CPU state before entering into TD. Restore CPU state after exiting from TD.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu enter/exit"
TD vcpu interrupts/exit/hypercall:
Handle various exits/hypercalls and allow interrupts to be injected so that TD vcpu can continue running.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu exits/interrupts/hypercalls"KVM MMU GPA shared bit:
Introduce framework to handle shared bit repurposed bit of GPA TDX repurposed a bit of GPA to indicate shared or private. If it's shared, it's the same as the conventional VMX EPT case. VMM can access shared guest pages. If it's private, it's handled by Secure-EPT and the guest page is encrypted.
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM MMU GPA stolen bits"
KVM TDP refactoring for TDX:
TDX Secure EPT requires different constants. e.g. initial value EPT entry value etc. Various refactoring for those differences. This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP refactoring for TDX"
KVM TDP MMU hooks:
Introduce framework to TDP MMU to add hooks in addition to direct EPT access TDX added Secure EPT which is an enhancement to VMX EPT. Unlike conventional VMX EPT, CPU can't directly read/write Secure EPT. Instead, use TDX SEAMCALLs to operate on Secure EPT.
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP MMU hooks"
KVM TDP MMU MapGPA:
Introduce framework to handle switching guest pages from private/shared to shared/private. For a given GPA, a guest page can be assigned to a private GPA or a shared GPA exclusively. With TDX MapGPA hypercall, guest TD converts GPA assignments from private (or shared) to shared (or private).
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP MMU MapGPA "KVM guest private memory: (not shown in the above diagram)
[PATCH v4 00/12] KVM: mm: fd-based approach for supporting KVM guest private
memory: https://lkml.org/lkml/2022/1/18/395
Guest private memory requires different memory management in KVM. The patch proposes a way for it. Integration with TDX KVM.(***)
* TDX module
A CPU-attested software module called the "TDX module" is designed to implement the TDX architecture, and it is loaded by the UEFI firmware today. It can be loaded by the kernel or driver at runtime, but in this patch series we assume that the TDX module is already loaded and initialized.The TDX module provides two main new logical modes of operation built upon the new SEAM (Secure Arbitration Mode) root and non-root CPU modes added to the VMX architecture. TDX root mode is mostly identical to the VMX root operation mode, and the TDX functions (described later) are triggered by the new SEAMCALL instruction with the desired interface function selected by an input operand (leaf number, in RAX). TDX non-root mode is used for TD guest operation. TDX non-root operation (i.e. "guest TD" mode) is similar to the VMX non-root operation (i.e. guest VM), with changes and restrictions to better assure that no other software or hardware has direct visibility of the TD memory and state.
TDX transitions between TDX root operation and TDX non-root operation include TD Entries, from TDX root to TDX non-root mode, and TD Exits from TDX non-root to TDX root mode. A TD Exit might be asynchronous, triggered by some external event (e.g., external interrupt or SMI) or an exception, or it might be synchronous, triggered by a TDCALL (TDG.VP.VMCALL) function.
TD VCPUs can be entered using SEAMCALL(TDH.VP.ENTER) by KVM. TDH.VP.ENTER is one of the TDX interface functions as mentioned above, and "TDH" stands for Trust Domain Host. Those host-side TDX interface functions are categorized into various areas just for better organization, such as SYS (TDX module management), MNG (TD management), VP (VCPU), PHYSMEM (physical memory), MEM (private memory), etc. For example, SEAMCALL(TDH.SYS.INFO) returns the TDX module information.
TDCS (Trust Domain Control Structure) is the main control structure of a guest TD, and encrypted (using the guest TD's ephemeral private key). At a high level, TDCS holds information for controlling TD operation as a whole, execution, EPTP, MSR bitmaps, etc that KVM needs to set it up. Note that MSR bitmaps are held as part of TDCS (unlike VMX) because they are meant to have the same value for all VCPUs of the same TD.
Trust Domain Virtual Processor State (TDVPS) is the root control structure of a TD VCPU. It helps the TDX module control the operation of the VCPU, and holds the VCPU state while the VCPU is not running. TDVPS is opaque to software and DMA access, accessible only by using the TDX module interface functions (such as TDH.VP.RD, TDH.VP.WR). TDVPS includes TD VMCS, and TD VMCS auxiliary structures, such as virtual APIC page, virtualization exception information, etc.
Several VMX control structures (such as Shared EPT and Posted interrupt descriptor) are directly managed and accessed by the host VMM. These control structures are pointed to by fields in the TD VMCS.
The above means that 1) KVM needs to allocate different data structures for TDs,
2) KVM can reuse the existing code for TDs for some operations, 3) it needs to define TD-specific handling for others. 3) Redirect operations to . 3) Redirect operations to the TDX specific callbacks, like "if (is_td_vcpu(vcpu))tdx_callback()elsevmx_callback();".*TD Private Memory
TD private memory is designed to hold TD private content, encrypted by the CPU using the TD ephemeral key. An encryption engine holds a table of encryption keys, and an encryption key is selected for each memory transaction based on a Host Key Identifier (HKID). By design, the host VMM does not have access to the encryption keys.In the first generation of MKTME, HKID is "stolen" from the physical address by allocating a configurable number of bits from the top of the physical address. The HKID space is partitioned into shared HKIDs for legacy MKTME accesses and private HKIDs for SEAM-mode-only accesses. We use 0 for the shared HKID on the host so that MKTME can be opaque or bypassed on the host.
During TDX non-root operation (i.e. guest TD), memory accesses can be qualified as either shared or private, based on the value of a new SHARED bit in the Guest Physical Address (GPA). The CPU translates shared GPAs using the usual VMX EPT (Extended Page Table) or "Shared EPT" (in this document), which resides in host VMM memory. The Shared EPT is directly managed by the host VMM - the same as with the current VMX. Since guest TDs usually require I/O, and the data exchange needs to be done via shared memory, thus KVM needs to use the current EPT functionality even for TDs.
* Secure EPT and Minoring using the TDP code
The CPU translates private GPAs using a separate Secure EPT. The Secure EPT pages are encrypted and integrity-protected with the TD's ephemeral private key. Secure EPT can be managed _indirectly_ by the host VMM, using the TDX interface functions, and thus conceptually Secure EPT is a subset of EPT (why "subset"). Since execution of such interface functions takes much longer time than accessing memory directly, in KVM we use the existing TDP code to minor the Secure EPT for the TD.This way, we can effectively walk Secure EPT without using the TDX interface functions.
* VM life cycle and TDX specific operations
The userspace VMM, such as QEMU, needs to build and treat TDs differently. For example, a TD needs to boot in private memory, and the host software cannot copy the initial image to private memory.* TSC Virtualization
The TDX module helps TDs maintain reliable TSC (Time Stamp Counter) values (e.g. consistent among the TD VCPUs) and the virtual TSC frequency is determined by TD configuration, i.e. when the TD is created, not per VCPU. The current KVM owns TSC virtualization for VMs, but the TDX module does for TDs.* MCE support for TDs
The TDX module doesn't allow VMM to inject MCE. Instead PV way is needed for TD to communicate with VMM. For now, KVM silently ignores MCE request by VMM. MSRs related to MCE (e.g, MCE bank registers) can be naturally emulated by paravirtualizing MSR access.[1] For details, the specifications, [2], [3], [4], [5], [6], [7], are available.
* Restrictions or future work
Some features are not included to reduce patch size. Those features are addressed as future independent patch series.
- large page (2M, 1G)
- qemu gdb stub
- guest PMU
- and more* Prerequisites
It's required to load the TDX module and initialize it. It's out of the scope of this patch series. Another independent patch for the common x86 code is planned. It definesCONFIG_INTEL_TDX_HOSTand this patch series usesCONFIG_INTEL_TDX_HOST. It's assumed that WithCONFIG_INTEL_TDX_HOST=y, the TDX module is initialized and ready for KVM to use the TDX module APIs for TDX guest life cycle like tdh.mng.init are ready to use.Concretely Global initialization, LP (Logical Processor) initialization, global configuration, the key configuration, and TDMR and PAMT initialization are done. The state of the TDX module is
SYS_READY. Please refer to the TDX module specification, the chapter Intel TDX Module Lifecycle State Machine** Detecting the TDX module readiness.
TDX host patch series implements the detection of the TDX module availability and its initialization so that KVM can use it. Also it manages Host KeyID (HKID) assigned to guest TD.
The assumed APIs the TDX host patch series provides are
- intseamrr_enabled()
Check if required cpu feature (SEAM mode) is available. This only check CPU feature availability. At this point, the TDX module may not be ready for KVM to use.
- intinit_tdx(void);
Initialization of TDX module so that the TDX module is ready for KVM to use.
- const structtdsysinfo_struct*tdx_get_sysinfo(void);
Return the system wide information about the TDX module. NULL if the TDX isn't initialized.
- u32tdx_get_global_keyid(void);
Return global key id that is used for the TDX module itself.
- inttdx_keyid_alloc(void);
Allocate HKID for guest TD.
- voidtdx_keyid_free(int keyid);
Free HKID for guest TD.(****)
* TDX KVM high-level design
- Host key ID management
Host Key ID (HKID) needs to be assigned to each TDX guest for memory encryption. It is assumed The TDX host patch series implements necessary functions, u32tdx_get_global_keyid(void), inttdx_keyid_alloc(void)and,
voidtdx_keyid_free(int keyid).- Data structures and VM type
Because TDX is different from VMX, define its own VM/VCPU structures, structkvm_tdxand structvcpu_tdxinstead of structkvm_vmxand structvcpu_vmx. To identify the VM, introduce VM-type to specify which VM type, VMX (default) or TDX, is used.- VM life cycle and TDX specific operations
Re-purpose the existingKVM_MEMORY_ENCRYPT_OPto add TDX specific operations. New commands are used to get the TDX system parameters, set TDX specific VM/VCPU parameters, set initial guest memory and measurement.The creation of TDX VM requires five additional operations in addition to the conventional VM creation.
- Get KVM system capability to check if TDX VM type is supported
- VM creation (KVM_CREATE_VM)
- New: Get the TDX specific system parameters.KVM_TDX_GET_CAPABILITY.
- New: Set TDX specific VM parameters.KVM_TDX_INIT_VM.
- VCPU creation (KVM_CREATE_VCPU)
- New: Set TDX specific VCPU parameters.KVM_TDX_INIT_VCPU.
- New: Initialize guest memory as boot state and extend the measurement with the memory.KVM_TDX_INIT_MEM_REGION.
- New: Finalize VM.KVM_TDX_FINALIZE. Complete measurement of the initial TDX VM contents.
- VCPU RUN (KVM_VCPU_RUN)- Protected guest state
Because the guest state (CPU state and guest memory) is protected, the KVM VMM can't operate on them. For example, accessing CPU registers, injecting exceptions, and accessing guest memory. Those operations are handled as silently ignored, returning zero or initial reset value when it's requested via KVM API ioctls.VM/VCPU state and callbacks for TDX specific operations. Define tdx specific VM state and VCPU state instead of VMX ones. Redirect operations to TDX specific callbacks. "if (tdx)
tdx_op()elsevmx_op()".Operations on the CPU state
silently ignore operations on the guest state. For example, the write to CPU registers is ignored and the read from CPU registers returns 0.. ignore access to CPU registers except for allowed ones.
. TSC: add a check if tsc is immutable and return an error. Because the KVM
implementation updates the internal tsc state and it's difficult to back out those changes. Instead, skip the logic.
. dirty logging: add check if dirty logging is supported.
. exceptions/SMI/MCE/SIPI/INIT: silently ignoreNote: virtual external interrupt and NMI can be injected into TDX guests.
- KVM MMU integration
One bit of the guest physical address (bit 51 or 47) is repurposed to indicate if the guest physical address is private (the bit is cleared) or shared (the bit is set). The bits are called stolen bits.- Stolen bits framework
systematically tracks which guest physical address, shared or private, is used.- Shared EPT and secure EPT
There are two EPTs. Shared EPT (the conventional one) and Secure EPT(the new one). Shared EPT is handled the same for the stolen bit set. Secure EPT points to private guest pages. To resolve EPT violation, KVM walks one of two EPTs based on faulted GPA. Because it's costly to access secure EPT during walking EPTs with SEAMCALLs for the private guest physical address, another private EPT is used as a shadow of Secure-EPT with the existing logic at the cost of extra memory.The following depicts the relationship.
KVM | TDX module | | | -------------+---------- | | | | | | V V | | shared GPA private GPA | | CPU shared EPT pointer KVM private EPT pointer | CPU secure EPT pointer | | | | | | | | V V | V shared EPT private EPT--------mirror----->Secure EPT | | | | | \--------------------+------\ | | | | | V | V V shared guest page | private guest page | | non-encrypted memory | encrypted memory |- Operating on Secure EPT
Use the TDX module APIs to operate on Secure EPT. To call the TDX API during resolving EPT violation, add hooks to additional operation and wiring it to TDX backend.* References
[1] TDX specification
https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html
[2] Intel Trust Domain Extensions (Intel TDX)
https://cdrdv2.intel.com/v1/dl/getContent/726790
[3] Intel CPU Architectural Extensions Specification
https://www.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-cpu-architectural-specification.pdf
[4] Intel TDX Module 1.0 Specification
https://www.intel.com/content/dam/develop/external/us/en/documents/tdx-module-1.0-public-spec-v0.931.pdf
[5] Intel TDX Loader Interface Specification
https://www.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-seamldr-interface-specification.pdf
[6] Intel TDX Guest-Hypervisor Communication Interface
https://cdrdv2.intel.com/v1/dl/getContent/726790
[7] Intel TDX Virtual Firmware Design Guide
https://www.intel.com/content/dam/develop/external/us/en/documents/tdx-virtual-firmware-design-guide-rev-1.01.pdf
[8] intel public github
kvm TDX branch: https://github.com/intel/tdx/tree/kvm
TDX guest branch: https://github.com/intel/tdx/tree/guest
qemu TDX https://github.com/intel/qemu-tdx
[9] TDVF
https://github.com/tianocore/edk2-staging/tree/TDVF
This was merged into EDK2 main branch. https://github.com/tianocore/edk2Chao Gao (3):
KVM: x86: Movecheck_processor_compatibilityfrom init ops to runtime
ops
Partially revert "KVM: Pass kvm_init()'s opaque param to additional
arch funcs"
KVM: x86: Allow to update cached values inkvm_user_return_msrsw/o
wrmsrIsaku Yamahata (72):
KVM: Refactor CPU compatibility check on module initialiization x86/virt/vmx/tdx: exportplatform_tdx_enabled()
KVM: TDX: Detect CPU feature on kernel module initialization
KVM: x86: Refactor KVM VMX module init/exit functions
KVM: TDX: Add placeholders for TDX VM/vcpu structure x86/virt/tdx: Add a helper function to return system wide info about
TDX module
KVM: TDX: Initialize TDX module when loading kvm_intel.ko
KVM: TDX: Make TDX VM type supported
[MARKER] The start of TDX KVM patch series: TDX architectural
definitions
KVM: TDX: Define TDX architectural definitions
KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module
KVM: TDX: Add helper functions to print TDX SEAMCALL error [MARKER] The start of TDX KVM patch series: TD VM creation/destruction x86/cpu: Add helper functions to allocate/free TDX private host key id
KVM: TDX: Add place holder for TDX VM specificmem_enc_opioctl
KVM: TDX: Makepmu_intel.cignore guest TD case
[MARKER] The start of TDX KVM patch series: TD vcpu
creation/destruction
KVM: TDX: allocate/free TDX vcpu structure
KVM: TDX: allocate/free TDX vcpu structure
[MARKER] The start of TDX KVM patch series: KVM MMU GPA shared bits
KVM: x86/mmu: introduce config for PRIVATE KVM MMU [MARKER] The start of TDX KVM patch series: KVM TDP refactoring for
TDX
KVM: x86/mmu: Disallow fast page fault on private GPA
KVM: VMX: Introduce test mode related to EPT violation VE [MARKER] The start of TDX KVM patch series: KVM TDP MMU hooks
KVM: x86/mmu: Focibly use TDP MMU for TDX
KVM: x86/mmu: Add a private pointer to structkvm_mmu_page
KVM: x86/tdp_mmu: refactorkvm_tdp_mmu_map()
KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU [MARKER] The start of TDX KVM patch series: TDX EPT violation
KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs
KVM: TDX: don't requestKVM_REQ_APIC_PAGE_RELOAD
KVM: TDX: TDP MMU TDX support
[MARKER] The start of TDX KVM patch series: KVM TDP MMU MapGPA
KVM: x86/mmu: steal software usable git to record if GFN is for shared
or not
KVM: x86/tdp_mmu: implement MapGPA hypercall for TDX [MARKER] The start of TDX KVM patch series: TD finalization
KVM: TDX: Create initial guest memory
KVM: TDX: Finalize VM initialization
[MARKER] The start of TDX KVM patch series: TD vcpu enter/exit
KVM: TDX: Add helper assembly function to TDX vcpu
KVM: TDX: Implement TDX vcpu enter/exit path
KVM: TDX:vcpu_run: save/restore host state(host kernel gs)
KVM: TDX: restore host xsave state when exit from the guest TD
KVM: TDX: restore user ret MSRs
[MARKER] The start of TDX KVM patch series: TD vcpu
exits/interrupts/hypercalls
KVM: TDX: complete interrupts after tdexit
KVM: TDX: restore debug store when TD exit
KVM: TDX: handle vcpu migration over logical processor
KVM: x86: Add aswitch_db_regsflag to handle TDX's auto-switched
behavior
KVM: TDX: remove use of structvcpu_vmxfromposted_interrupt.c
KVM: TDX: Implement interrupt injection
KVM: TDX: Implements vcpurequest_immediate_exit
KVM: TDX: Implement methods to inject NMI
KVM: TDX: Add a place holder to handle TDX VM exit
KVM: TDX: handleEXIT_REASON_OTHER_SMI
KVM: TDX: handle ept violation/misconfig exit
KVM: TDX: handleEXCEPTION_NMIandEXTERNAL_INTERRUPT
KVM: TDX: Add a place holder for handler of TDX hypercalls(TDG.VP.VMCALL)KVM: TDX: handle KVM hypercall with TDG.VP.VMCALL
KVM: TDX: Handle TDX PV CPUID hypercall
KVM: TDX: Handle TDX PV HLT hypercall
KVM: TDX: Handle TDX PV port io hypercall
KVM: TDX: Implement callbacks for MSR operations for TDX
KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall
KVM: TDX: Handle TDX PV report fatal error hypercall
KVM: TDX: Handle TDX PVmap_gpahypercall
KVM: TDX: Handle TDG.VP.VMCALL<GetTdVmCallInfo> hypercall
KVM: TDX: Silently discard SMI request
KVM: TDX: Silently ignore INIT/SIPIDocumentation/virtual/kvm: Document on Trust Domain Extensions(TDX)
KVM: x86: design documentation on TDX support of x86 KVM TDP MMURick Edgecombe (1):
KVM: x86/mmu: Add address conversion functions for TDX shared bitsSean Christopherson (25):
KVM: VMX: Move outvmx_x86_opsto 'main.c' to wrap VMX and TDX
KVM: Enable hardware before doing arch VM initialization
KVM: x86: Introducevm_typeto differentiate default VMs from
confidential VMs
KVM: TDX: Add TDX "architectural" error codes
KVM: TDX: Stub intdx.hwith structs, accessors, and VMCS helpers
KVM: TDX: create/destroy VM structure
KVM: TDX: x86: Add ioctl to get TDX systemwide parameters
KVM: TDX: Do TDX specific vcpu initialization
KVM: x86/mmu: Explicitly check for MMIO spte in fast page fault
KVM: x86/mmu: Allow non-zero value for non-present SPTE
KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis
KVM: x86/mmu: Allow per-VM override of the TDP max page level
KVM: x86/mmu: Zap only leaf SPTEs for deleted/moved memslot for
private mmu
KVM: x86/mmu: Disallow dirty logging for x86 TDX
KVM: VMX: Split out guts of EPT violation to common/exposed function
KVM: VMX: Move setting of EPT MMU masks to common VT-x code
KVM: TDX: Addload_mmu_pgdmethod for TDX
KVM: x86/mmu: Introducekvm_mmu_map_tdp_page()for use by TDX
KVM: TDX: Add support for find pending IRQ in a protected local APIC
KVM: x86: Assume timer IRQ was injected if APIC state is proteced
KVM: VMX: Modify NMI and INTR handlers to takeintr_infoas function
argument
KVM: VMX: Move NMI/exception handler to common helper
KVM: x86: Split core of hypercall emulation to helper function
KVM: TDX: Handle TDX PV MMIO hypercall
KVM: TDX: Add methods to ignore accesses to CPU stateXiaoyao Li (1):
KVM: TDX: initialize VM with TDX specific parametersDocumentation/virt/kvm/api.rst | 30 +- .../virt/kvm/intel-tdx-layer-status.rst | 33 + Documentation/virt/kvm/intel-tdx.rst | 381 +++ Documentation/virt/kvm/tdx-tdp-mmu.rst | 466 ++++ arch/arm64/kvm/arm.c | 2 +- arch/mips/kvm/mips.c | 14 +- arch/powerpc/kvm/powerpc.c | 2 +- arch/riscv/kvm/main.c | 2 +- arch/s390/kvm/kvm-s390.c | 2 +- arch/x86/events/intel/ds.c | 1 + arch/x86/include/asm/kvm-x86-ops.h | 10 + arch/x86/include/asm/kvm_host.h | 56 +- arch/x86/include/asm/tdx.h | 67 + arch/x86/include/asm/vmx.h | 14 + arch/x86/include/uapi/asm/kvm.h | 95 + arch/x86/include/uapi/asm/vmx.h | 5 +- arch/x86/kvm/Kconfig | 4 + arch/x86/kvm/Makefile | 3 +- arch/x86/kvm/irq.c | 3 + arch/x86/kvm/lapic.c | 37 +- arch/x86/kvm/lapic.h | 2 + arch/x86/kvm/mmu.h | 42 +- arch/x86/kvm/mmu/mmu.c | 360 ++- arch/x86/kvm/mmu/mmu_internal.h | 123 +- arch/x86/kvm/mmu/paging_tmpl.h | 5 +- arch/x86/kvm/mmu/spte.c | 46 +- arch/x86/kvm/mmu/spte.h | 65 +- arch/x86/kvm/mmu/tdp_iter.c | 1 + arch/x86/kvm/mmu/tdp_iter.h | 5 +- arch/x86/kvm/mmu/tdp_mmu.c | 690 ++++- arch/x86/kvm/mmu/tdp_mmu.h | 12 +- arch/x86/kvm/svm/svm.c | 13 +- arch/x86/kvm/vmx/common.h | 174 ++ arch/x86/kvm/vmx/evmcs.c | 2 +- arch/x86/kvm/vmx/evmcs.h | 2 +- arch/x86/kvm/vmx/main.c | 1071 +++++++ arch/x86/kvm/vmx/pmu_intel.c | 39 +- arch/x86/kvm/vmx/pmu_intel.h | 28 + arch/x86/kvm/vmx/posted_intr.c | 43 +- arch/x86/kvm/vmx/posted_intr.h | 13 + arch/x86/kvm/vmx/tdx.c | 2465 +++++++++++++++++ arch/x86/kvm/vmx/tdx.h | 275 ++ arch/x86/kvm/vmx/tdx_arch.h | 157 ++ arch/x86/kvm/vmx/tdx_errno.h | 29 + arch/x86/kvm/vmx/tdx_error.c | 22 + arch/x86/kvm/vmx/tdx_ops.h | 188 ++ arch/x86/kvm/vmx/vmenter.S | 146 + arch/x86/kvm/vmx/vmx.c | 737 ++--- arch/x86/kvm/vmx/vmx.h | 39 +- arch/x86/kvm/vmx/x86_ops.h | 235 ++ arch/x86/kvm/x86.c | 148 +- arch/x86/virt/vmx/tdx/seamcall.S | 2 + arch/x86/virt/vmx/tdx/tdx.c | 54 +- arch/x86/virt/vmx/tdx/tdx.h | 52 - include/linux/kvm_host.h | 4 +- include/uapi/linux/kvm.h | 2 + tools/arch/x86/include/uapi/asm/kvm.h | 95 + tools/include/uapi/linux/kvm.h | 1 + virt/kvm/kvm_main.c | 67 +- 59 files changed, 7877 insertions(+), 804 deletions(-) create mode 100644 Documentation/virt/kvm/intel-tdx-layer-status.rst create mode 100644 Documentation/virt/kvm/intel-tdx.rst create mode 100644 Documentation/virt/kvm/tdx-tdp-mmu.rst create mode 100644 arch/x86/kvm/vmx/common.h create mode 100644 arch/x86/kvm/vmx/main.c create mode 100644 arch/x86/kvm/vmx/pmu_intel.h create mode 100644 arch/x86/kvm/vmx/tdx.c create mode 100644 arch/x86/kvm/vmx/tdx.h create mode 100644 arch/x86/kvm/vmx/tdx_arch.h create mode 100644 arch/x86/kvm/vmx/tdx_errno.h create mode 100644 arch/x86/kvm/vmx/tdx_error.c create mode 100644 arch/x86/kvm/vmx/tdx_ops.h create mode 100644 arch/x86/kvm/vmx/x86_ops.hSignature · 1 line
2.25.1
Signature · 1 line
Isaku Yamahata <[email protected]>
Quoted 7 lines · Isaku Yamahata
Hi. Because my description on large page support was terse, I wrote up more detailed one. Any feedback/thoughts on large page support?
TDP MMU large page support design
Two main discussion points
* how to track page status. private vs shared, no-largepage vs can-be-largepage
...
Quoted 7 lines
Tracking private/shared and large page mappable
-----------------------------------------------
VMM needs to track that page is mapped as private or shared at 4KB granularity. For efficiency of EPT violation path (****), at 2MB and 1GB level, VMM should track the page can be mapped as a large page (regarding private/shared). VMM updates it on MapGPA and references it on the EPT violation path. (****)
Isaku,
+ Peng Chao
Doesn't UPM guarantee that 2MB/1GB large page in CR3 should be either all private or all shared?
KVM always retrieves the mapping level in CR3 and enforces that EPT's page level is not greater than that in CR3. My point is if UPM already enforces no mixed pages in a large page, then KVM needn't do that again (UPM can be trusted).
Maybe I am misunderstanding something?
Quoted 23 lines · Chao Gao
Quoted 7 lines · Isaku Yamahata
Hi. Because my description on large page support was terse, I wrote up more detailed one. Any feedback/thoughts on large page support?
TDP MMU large page support design
Two main discussion points
* how to track page status. private vs shared, no-largepage vs can-be-largepage...
Quoted 7 lines
Tracking private/shared and large page mappable
-----------------------------------------------
VMM needs to track that page is mapped as private or shared at 4KB granularity. For efficiency of EPT violation path (****), at 2MB and 1GB level, VMM should track the page can be mapped as a large page (regarding private/shared). VMM updates it on MapGPA and references it on the EPT violation path. (****)Isaku,
+ Peng Chao
Quoted 7 lines
Doesn't UPM guarantee that 2MB/1GB large page in CR3 should be either all private or all shared?
KVM always retrieves the mapping level in CR3 and enforces that EPT's page level is not greater than that in CR3. My point is if UPM already enforces no mixed pages in a large page, then KVM needn't do that again (UPM can be trusted).
The backing store in the UMP can tell KVM which page level it can support for a given private gpa, similar to host_pfn_mapping_level() for shared address.
However, this solely represents the backing store's capability, KVM still needs additional info to decide whether that can be safely mapped as 2M/1G, e.g. all the following pages in the 2M/1G range should be all private, currently this is not something backing store can tell.
Actually, in UPM v7 we let KVM record this info so one possible solution is making use of it.
https://lkml.org/lkml/2022/7/6/259
Then to map a page as 2M, KVM needs to check:
- Memory backing store support that level
- All pages in 2M range are private as we recorded through KVM_MEMORY_ENCRYPT_{UN,}REG_REGION
- No existing partial 4K map(s) in 2M range
Chao
Quoted 2 lines
Maybe I am misunderstanding something?
Quoted 32 lines · Chao Peng
Quoted 23 lines · Chao Gao
Quoted 7 lines · Isaku Yamahata
Hi. Because my description on large page support was terse, I wrote up more detailed one. Any feedback/thoughts on large page support?
TDP MMU large page support design
Two main discussion points
* how to track page status. private vs shared, no-largepage vs can-be-largepage...
Quoted 7 lines
Tracking private/shared and large page mappable
-----------------------------------------------
VMM needs to track that page is mapped as private or shared at 4KB granularity. For efficiency of EPT violation path (****), at 2MB and 1GB level, VMM should track the page can be mapped as a large page (regarding private/shared). VMM updates it on MapGPA and references it on the EPT violation path. (****)Isaku,
+ Peng Chao
Quoted 7 lines
Doesn't UPM guarantee that 2MB/1GB large page in CR3 should be either all private or all shared?
KVM always retrieves the mapping level in CR3 and enforces that EPT's page level is not greater than that in CR3. My point is if UPM already enforces no mixed pages in a large page, then KVM needn't do that again (UPM can be trusted).
Quoted 8 lines
The backing store in the UMP can tell KVM which page level it can support for a given private gpa, similar to
host_pfn_mapping_level()for shared address.However, this solely represents the backing store's capability, KVM still needs additional info to decide whether that can be safely mapped as 2M/1G, e.g. all the following pages in the 2M/1G range should be all private, currently this is not something backing store can tell.
This argument applies to shared GPA. The shared pages is backed by normal file mapping with UPM. When KVM is mapping shared GPA, the same check is needed. So I think KVM has to track all private or all shared or no-largepage at 2MB/1GB level. If UPM tracks shared-or-private at 4KB level, probably KVM may not need to track it at 4KB level.
Quoted 10 lines
Actually, in UPM v7 we let KVM record this info so one possible solution is making use of it.
https://lkml.org/lkml/2022/7/6/259
Then to map a page as 2M, KVM needs to check:
- Memory backing store support that level
- All pages in 2M range are private as we recorded through KVM_MEMORY_ENCRYPT_{UN,}REG_REGION
- No existing partial 4K map(s) in 2M range
Signature · 1 line
Isaku Yamahata <[email protected]>
Quoted 44 lines · Isaku Yamahata
Quoted 32 lines · Chao Peng
Quoted 23 lines · Chao Gao
Quoted 7 lines · Isaku Yamahata
Hi. Because my description on large page support was terse, I wrote up more detailed one. Any feedback/thoughts on large page support?
TDP MMU large page support design
Two main discussion points
* how to track page status. private vs shared, no-largepage vs can-be-largepage...
Quoted 7 lines
Tracking private/shared and large page mappable
-----------------------------------------------
VMM needs to track that page is mapped as private or shared at 4KB granularity. For efficiency of EPT violation path (****), at 2MB and 1GB level, VMM should track the page can be mapped as a large page (regarding private/shared). VMM updates it on MapGPA and references it on the EPT violation path. (****)Isaku,
+ Peng Chao
Quoted 7 lines
Doesn't UPM guarantee that 2MB/1GB large page in CR3 should be either all private or all shared?
KVM always retrieves the mapping level in CR3 and enforces that EPT's page level is not greater than that in CR3. My point is if UPM already enforces no mixed pages in a large page, then KVM needn't do that again (UPM can be trusted).
Quoted 8 lines
The backing store in the UMP can tell KVM which page level it can support for a given private gpa, similar to
host_pfn_mapping_level()for shared address.However, this solely represents the backing store's capability, KVM still needs additional info to decide whether that can be safely mapped as 2M/1G, e.g. all the following pages in the 2M/1G range should be all private, currently this is not something backing store can tell.
Quoted 5 lines
This argument applies to shared GPA. The shared pages is backed by normal file mapping with UPM. When KVM is mapping shared GPA, the same check is needed. So I think KVM has to track all private or all shared or no-largepage at 2MB/1GB level. If UPM tracks shared-or-private at 4KB level, probably KVM may not need to track it at 4KB level.
Right, the same also applies to shared memory. All the info we need is whether pages of a 2M range is all private/shared but not mixed. UPM v7 has code tracking that in KVM and previously versions we track that in the backing store which has been discussed not a good idea.
Chao
Quoted 14 lines
Quoted 12 lines
Actually, in UPM v7 we let KVM record this info so one possible solution is making use of it.
https://lkml.org/lkml/2022/7/6/259
Then to map a page as 2M, KVM needs to check:
- Memory backing store support that level
- All pages in 2M range are private as we recorded through KVM_MEMORY_ENCRYPT_{UN,}REG_REGION
- No existing partial 4K map(s) in 2M rangeSignature · 1 line
Isaku Yamahata <[email protected]>
Quoted 78 lines · Isaku Yamahata
Hi. Because my description on large page support was terse, I wrote up more detailed one. Any feedback/thoughts on large page support?
TDP MMU large page support design
Two main discussion points
* how to track page status. private vs shared, no-largepage vs can-be-largepage
* how to trigger merging mapping from 4KB/2MB to 2MB/1GBExpected private-vs-shared page usage
-------------------------------------
On TD boot all pages are private and TD converts pages into shared if necessary.
* Most of the guest pages remain private.
* Only limited pages are converted at kernel boot
** bounce buffer for IO (virt-io). It's allocated as swiotlb. Its size is
64MB or 6% of total guest memory.
** KVM PV shared page. (the current guest TD doesn't use KVM PV shared page.)
* Only a small number of pages are dynamically converted from private to shared and vice versa. This usage is very limited. e.g. GetQuote, the lack of swiotlb bufferTheory of Secure-EPT operations related to large page
-----------------------------------------------------
TDX Secure-EPT has differences from VMX EPT. To add a page to Secure-EPT* Here is the operation to resolve the EPT violation.
1. TD: Accepts GPA. TD needs to accept GPA before accessing GPA because TD needs to detect that VMM unmaps GPA and maps GPA again.
2. EPT violation is triggered. TD exit to VMM.
3. VMM: allocate a page for GPA and TDH.MEM.PAGE.AUG it to GPA. Resume TD vcpu. (3a. TD: #VE<EPT violation> is injected. #VE handler accepts the page)
4. TD: resume #VE and continue TD vcpu executionTD may choose step 1. In that case, After step 3. #VE is injected into TD and, TD #VE handler needs to accept the page.
When adding a page to Secure-EPT again, the page contexts are cleared and the page is encrypted. If a page is disassociated from Secure-EPT and added again, the page content is lost.
* TDG.VP.VMCALL<MapGPA> hypercall
The page associated with GPA can be private or shared. TD converts the GPA by TDG.VP.VMCALL<MapGPA> hypercall from private to shared or vice versa. VMM tracks whether the given GPA is private or shared.* mapping merge(promote)/split(demote)
The page can be mapped as large page (2MB or 1GB) in addition to 4KB. The mapping can bemerged(4KB/2MB -> 2MB/1GB)orsplit(2MB/1GB -> 4KB/2MB)by TDX SEAMCALL TDH.MEM.PAGE.PROMOTE and TDH.MEM.PAGE.DEMOTE.
The merge of mapping requires all the pages needs to be mapped, unlike VMX EPT because of encryption. This implies the current KVM implementation doesn't work for TDX when merging mapping as follows- EPT violation and host page is 2MB mappable.
some of the 4KB pages of the given 2MB page are already mapped, some not. i.e. 2MB EPT -> 4KB EPT -> 4K pages
- KVM page fault handler zap 2MB EPT entry and populate 2MB EPT entry
zap: 2MB EPT: non present
populate 2MB: -> 2MB pageIf VMM zaps 2MB Secure-EPT entry, the page contents will be lost for TDX. Mapping merge requires all pages are already mapped.
Instead, the following steps are needed.
- EPT violation and host page is 2MB mappable.
some of the 4KB pages of the given 2MB page are already mapped. Some not. i.e. 2MB EPT -> 4KB EPT -> 4K pages
- VMM checks all 4KB GPAs are private. If not, it can't be mapped as a large page. (****)
- VMM checks all 4KB GPAs are already mapped. If not, give up mapping merge. (or map missing 4KB pages.)
- mapping merge by TDH.MEM.PAGE.PROMOTEThe mapping split for TDX Secure-EPT works similarly to the VMX EPT case.
Quoted 8 lines
EPT violation and MapGPA
------------------------
- EPT violation is a fast path
- MapGPA is not a fast path.
=> Keep the EPT violation path optimized and complicates the MapGPA path. For (****) check, we don't want to scan the 4KB mapping on EPT violation. Instead, the MapGPA path scans it and records the result as the page can be mapped as 2MB due to private/shared.
This sounds reasonable, Instead of tracking that in MapGPA, maybe KVM_MEMORY_ENCRYPT_{UN,}REG_REGION introduced in UPM v7 is a better place to put the scan code in.
https://lkml.org/lkml/2022/7/6/259
Both the MapGPA (explicit conversion) and the EPT violation (implicit conversion) can cause invocation to these two ioctls and need update to this info.
Quoted 9 lines
Tracking private/shared and large page mappable
-----------------------------------------------
VMM needs to track that page is mapped as private or shared at 4KB granularity. For efficiency of EPT violation path (****), at 2MB and 1GB level, VMM should track the page can be mapped as a large page (regarding private/shared). VMM updates it on MapGPA and references it on the EPT violation path. (****)
Quoted 3 lines
For 4KB pages, 1 bit is needed. private or shared. Let's call it shared-mask bit. For 2MB/1GB pages, 2 bit is needed. large page mappable or not. private or shared if mappable. Let's call it no-largepage bit.
I'm just thinking maybe we don't need introduce new bits, instead we reuse lpage_info where we already use it to track whether a page can be mapped at specified page level in kvm_mmu_max_mapping_level(). Then in the above two ioctls we do a scan for each level and update lpage_info. For example, we should disallow_lpage if private/shared pages are mixed in that page level.
It's however a bit tricky to manage lpage_info.disallow_lpage in these two ioctls with current code. We can't simply do disallow_lpage++ and disallow_lpage--. One possible solution can treat disallow_lpage as a mask instead of a count. Then we define bits like below for use:
- USER_GFN_UNALIGNED set when memslot user_address/private_offset/gfn is not aligned on the page level
- PAGE_TRACKING set during page tracking
- PRIVITE_SHARED_MIXED set when private/shared pages are mixed
In page fault handler the page can be mapped at that level only when all bits are zero and in above two ioctls we just switch on/off bit PRIVITE_SHARED_MIXED.
Currently UMP don't have this code yet, but can be added if feasible.
Chao
Quoted 863 lines
Option A.)
Allocate array for pages in structkvm_arch_memory_sloton TD creation.struct kvm_arch_memory_slot { +struct kvm_page_attr *page_attr[KVM_NR_PAGE_SIZES];}
pros:
+straight forward implementation
+SPTE_SHARED_MASK is not needed
cons:
-memory overhead is high
-not optimized for expected usage
-one more look-up on EPT violationOption B.) Steal two software usable bits from SPTE and record them in SPTE.
SPTE_SHARED_MASK,SPTE_NOLARGE_PAGE_MASK
pros:
+optimized for EPT violation
cons:
-2bits used in SPTE entry
-complicates the MapGPA path.Option C.) Steal one software usable bit from SPTE and record it in SPTE.
SPTE_SHARED_MASK For 2MB/1GB, allocate bitmap in kvm_mmu_page. struct kvm_mmu_page { bitmap nolarge }pros:
+optimized for EPT violation
cons:
-complicates the MapGPA path.
-information is scattered in SPTE and structkvm_mmu_pageHow to update those bits
------------------------
- MapGPA
- at 4KB level, set or clear shared-mask bit.
- Scan 512 4KB bit, at 2MB level
- set or clear shared-mask bit, clear no-largepage bit or
- clear shared-mask bit, set no-largepage bit
- increment/decrement lpageinfo to prevent/allow large page
- similar for 1GB level
Note: This logic might a bit tricky.- EPT violation
- If 2MB large page is allowed, check if no-largepage bit
- If no-largepage bit is set, => go down to 4KB page
- If no-largepage bit is cleared => try to map 2MB page
- If 4KB level is not mapped, map 2MB page
- If some 4KB level is already mapped, go down to 4KB. Don't try to merge mapping. Or it's possible to try to merge mapping.
Note: 512 4KB entry scanning is not done at EPT violation because it's fast
path.Map merging
-----------
Map merging is necessary for TD migration. (Map split is the easy part.) The current KVM implementation zaps the range (mmu notification or lpage recovery worker) and expects large page mapping on the next EPT violation.Option A.) Keep the code similar to map merging logic.
Zap 2MB EPT entry in some sense and trigger map merging logic on the next EPT violation. To keep encrypted page contents, zapped EPT entries needs to keep the page. Steal one more bits from SPTE.SPTE_PRIVATE_BLOCKED_MASK. It means that the page is zapped from SPTE. but it still alive and references page.Option B.) In the callback, directly merge mapping somehow. In this case, mmu notifier usage doesn't make sense.
NOTE:
- Implement map merging in MapGPA. This doesn't work for dirty page logging.
- We can utilizekvm_nx_lpage_recovery_worker
- We can utilize THP. Probably doesn't work well for fd-based private memory.Thanks,
Isaku YamayhataQuoted 775 lines · On Mon, Jun 27, 2022 at 02:52:52PM -0700, [email protected] wrote:
From: Isaku Yamahata <[email protected]>
KVM TDX basic feature support
Hello. This is v7 the patch series vof KVM TDX support.
This is based on v5.19-rc1 + kvm/queue branch + TDX HOST patch series. The tree can be found at https://github.com/intel/tdx/tree/kvm-upstream
How to run/test: It's describe at https://github.com/intel/tdx/wiki/TDX-KVMMajor changes from v6:
- rebased to v5.19 baseTODO:
- integrate fd-based guest memory. As the discussion is still on-going, I intentionally dropped fd-based guest memory support yet. The integration can be found at https://github.com/intel/tdx/tree/kvm-upstream-workaround.
- 2M large page support. It's work-in-progress.
For large page support, there are several design choices. Here is the design options. Any thoughts/feedback?KVM MMU Large page support for TDX
* What needs to be done
- Track private or shared of each page size (4KB, 2MB, 1GB) based on TDG.VP.VMCALL<MapGPA>. For largepages(2MB, 1GB), it can be mixed (some lower-size pages are private and some shared.) In this case, the page can't be large.
- if necessary, split large page on TDG.VP.VMCALL<MapGPA>
(split on dirty page tracking is future work)
- resolving KVM page fault
When resolving a private page and the page is large in the host, GPA can be resolved as a large page in Secure-EPT. Even if the page is large on the host side, sometimes a 4KB page can be resolved because it's up to guest TD to accept at 4KB, 2MB, or 1GB.
- collapsing pages into a large page.
At this point, it's okay to not implement this. When dirty page tracking is supported, this needs to be supported.
- On MapGPA, the page can be collapsed into a large page
- handle zapping SPTE and try to collapse the pages on the next KVM page fault Unlike the EPT case, some trick is needed.
- For performance, optimize KVM page fault path at the cost of complicating MapGPA path.* options to track private or shared
At each page size (4KB, 2MB, and 1GB), track private, shared, or mixed (2MB and 1GB case). For 4KB each page, 1 bit per page is needed. private or shared. For large pages (2MB and 1GB), 2 bits per large page is needed. (private, shared, or mixed). When resolving KVM page fault, we don't want to check the lower-size pages to check if the given GPA can be a large for performance. On MapGPA check it instead.Option A). enhance
kvm_arch_memory_slot
enumkvm_page_type{
KVM_PAGE_TYPE_INVALID,
KVM_PAGE_TYPE_SHARED,
KVM_PAGE_TYPE_PRIVATE,
KVM_PAGE_TYPE_MIXED,
};struct kvm_page_attr { enum kvm_page_type type; };struct
kvm_arch_memory_slot{
+ structkvm_page_attr*page_attr[KVM_NR_PAGE_SIZES];Option B). steal one more bit
SPTE_MIXED_MASKin addition toSPTE_SHARED_MASKIf !SPTE_MIXED_MASK, it can be large page.Option C). use
SPTE_SHARED_MASKandkvm_mmu_page::mixedbitmapkvm_mmu_page::mixedbitmap of 1GB, root indicates mixed for 2MB, 1GB.* comparison
A).
+ straightforward to implement
+SPTE_SHARED_MASKisn't needed
- memory overhead compared to B). or C).
- more memory reference on KVM page faultB).
+ simpler than C) (complex than A)?)
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- Waste precious SPTE bits.C).
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- complicates MapGPA
- scattered data structureThanks,
Isaku YamahataChanges from v6:
- rebased to v5.19Changes from v5:
- export__seamcalland use it
- move mutex lock from callee function ofsmp_call_on_cputo the caller.
- renamemmu_prezap=>flush_shadow_all_private()andtdx_mmu_release_hkid
- updated comment
- drop the use oftdh_mng_key.reclaimid(): as the function is for backward compatibility to only return success
- structkvm_tdx_cmd: metadata => flags, added__u64error.
- make this ioctl systemwide ioctl
- ABI change to structkvm_init_vm
-guest_tsc_khz: usekvm->arch.default_tsc_khz
- renameBUILD_BUG_ON_MEMCPYtoMEMCPY_SAME_SIZE
- drop exportingkvm_set_tsc_khz().
- fixkvm_tdp_page_fault()for mtrr emulation
- rename it tokvm_gfn_shared_mask(), droppedkvm_gpa_shared_mask()
- dropkvm_is_private_gfn(), keptkvm_is_private_gpa()
keep kvm_{gfn, gpa}_private(),kvm_gpa_private()
- update commit message
- renameshadow_init_value=>shadow_nonprsent_value
- addedept_violation_ve_testmode
-shadow_nonpresent_value=>SHADOW_NONPRESENT_VALUEintdp_mmu.c
- legacy MMU case
=> -mmu_topup_shadow_page_cache(),kvm_mmu_create()
- FNAME(sync_page)(structkvm_vcpu*vcpu, structkvm_mmu_page*sp)
- #VE warning:
- rename:REMOVED_SPTE=>__REMOVED_SPTE,SHADOW_REMOVED_SPTE=>REMOVED_SPTE
- merge into Like we discussed, this patch should be merged with patch "KVM: x86/mmu: Allow non-zero init value for shadow PTE".
- fix pointed by Sagi. check !is_private check => (kvm_gfn_shared_mask&& !is_private)
- introducekvm_gfn_for_root(kvm, root, gfn)
- addonly_sharedargument tokvm_tdp_mmu_handle_gfn()
- usekvm_arch_dirty_log_supported()
- renameSPTE_PRIVATE_PROHIBITtoSPTE_SHARED_MASK.
- rename:is_private_prohibit_spte()=>spte_shared_mask()
- fix:shadow_nonpresent_value=>SHADOW_NONPRESENT_VALUEin comment
- dropped this patch as the change was merged into kvm/queue
- updatevt_apicv_post_state_restore()
- useis_64_bit_hypercall()
- comment: expand MSMI -> Machine Check System Management Interrupt
- fixedTDX_SEPT_PFERR
- tdvmcall_p[1234]_{write, read}() => tdvmcall_a[0123]_{read,write}()
- renametdmvcall_exit_readon()=>tdvmcall_leaf()
- remove optional zero check of argument.
- do a check for static_call(kvm_x86_has_emulated_msr)(kvm,MSR_IA32_SMBASE) inkvm_vcpu_ioctl_smiand__apic_accept_irq.
-WARN_ON_ONCEintdx_smi_allowedandtdx_enable_smi_window.
- introducevcpu_deliver_inittox86_ops
- sprinkeledKVM_BUG_ON()Changes from v4:
- rebased to TDX host kernel patch series.
- include all the patches to make this patch series working.
- add [MARKER] patches to mark the patch layer clear.---
* What's TDX?
TDX stands for Trust Domain Extensions, which extends Intel Virtual Machines Extensions (VMX) to introduce a kind of virtual machine guest called a Trust Domain (TD) for confidential computing.A TD runs in a CPU mode that is designed to protect the confidentiality of its memory contents and its CPU state from any other software, including the hosting Virtual Machine Monitor (VMM), unless explicitly shared by the TD itself.
We have more detailed explanations below (***). We have the high-level design of TDX KVM below (****).
In this patch series, we use "TD" or "guest TD" to differentiate it from the current "VM" (Virtual Machine), which is supported by KVM today.
* The organization of this patch series
This patch series is on top of the patches series "TDX host kernel support":
https://lore.kernel.org/lkml/[email protected]/this patch series is available at
https://github.com/intel/tdx/releases/tag/kvm-upstream
The corresponding patches to qemu are available at
https://github.com/intel/qemu-tdx/commits/tdx-upstreamThe relations of the layers are depicted as follows.
The arrows below show the order of patch reviews we would like to have.The below layers are chosen so that the device model, for example, qemu can exercise each layering step by step. Check if TDX is supported, create TD VM, create TD vcpu, allow vcpu running, populate TD guest private memory, and handle vcpu exits/hypercalls/interrupts to run TD fully.
TDX vcpu
interrupt/exits/hypercall<------------\^ | | | TD finalization | ^ | | | TDX EPT violation<------------\ | ^ | | | | | TD vcpu enter/exit | | ^ | | | | | TD vcpu creation/destruction | \-------KVM TDP MMU MapGPA ^ | ^ | | | TD VM creation/destruction \---------------KVM TDP MMU hooks^ ^
| |
TDX architectural definitions KVM TDP refactoring for TDX
^ ^
| |
TDX, VMX <--------TDX host kernel KVM MMU GPA stolen bits
coexistence supportThe followings are explanations of each layer. Each layer has a dummy commit that starts with [MARKER] in subject. It is intended to help to identify where each layer starts.
TDX host kernel support:
https://lore.kernel.org/lkml/[email protected]/
The guts of system-wide initialization of TDX module. There is an independent patch series for host x86. TDX KVM patches call functions this patch series provides to initialize the TDX module.TDX, VMX coexistence:
Infrastructure to allow TDX to coexist with VMX and trigger the initialization of the TDX module.
This layer starts with
"KVM: VMX: Move outvmx_x86_opsto 'main.c' to wrap VMX and TDX"
TDX architectural definitions:
Add TDX architectural definitions and helper functions
This layer starts with
"[MARKER] The start of TDX KVM patch series: TDX architectural definitions".
TD VM creation/destruction:
Guest TD creation/destroy allocation and releasing of TDX specific vm and vcpu structure. Create an initial guest memory image with TDX measurement.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD VM creation/destruction".
TD vcpu creation/destruction:
guest TD creation/destroy Allocation and releasing of TDX specific vm and vcpu structure. Create an initial guest memory image with TDX measurement.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu creation/destruction"
TDX EPT violation:
Create an initial guest memory image with TDX measurement. Handle secure EPT violations to populate guest pages with TDX SEAMCALLs. This layer starts with
"[MARKER] The start of TDX KVM patch series: TDX EPT violation"
TD vcpu enter/exit:
Allow TDX vcpu to enter into TD and exit from TD. Save CPU state before entering into TD. Restore CPU state after exiting from TD.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu enter/exit"
TD vcpu interrupts/exit/hypercall:
Handle various exits/hypercalls and allow interrupts to be injected so that TD vcpu can continue running.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu exits/interrupts/hypercalls"KVM MMU GPA shared bit:
Introduce framework to handle shared bit repurposed bit of GPA TDX repurposed a bit of GPA to indicate shared or private. If it's shared, it's the same as the conventional VMX EPT case. VMM can access shared guest pages. If it's private, it's handled by Secure-EPT and the guest page is encrypted.
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM MMU GPA stolen bits"
KVM TDP refactoring for TDX:
TDX Secure EPT requires different constants. e.g. initial value EPT entry value etc. Various refactoring for those differences. This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP refactoring for TDX"
KVM TDP MMU hooks:
Introduce framework to TDP MMU to add hooks in addition to direct EPT access TDX added Secure EPT which is an enhancement to VMX EPT. Unlike conventional VMX EPT, CPU can't directly read/write Secure EPT. Instead, use TDX SEAMCALLs to operate on Secure EPT.
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP MMU hooks"
KVM TDP MMU MapGPA:
Introduce framework to handle switching guest pages from private/shared to shared/private. For a given GPA, a guest page can be assigned to a private GPA or a shared GPA exclusively. With TDX MapGPA hypercall, guest TD converts GPA assignments from private (or shared) to shared (or private).
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP MMU MapGPA "KVM guest private memory: (not shown in the above diagram)
[PATCH v4 00/12] KVM: mm: fd-based approach for supporting KVM guest private
memory: https://lkml.org/lkml/2022/1/18/395
Guest private memory requires different memory management in KVM. The patch proposes a way for it. Integration with TDX KVM.(***)
* TDX module
A CPU-attested software module called the "TDX module" is designed to implement the TDX architecture, and it is loaded by the UEFI firmware today. It can be loaded by the kernel or driver at runtime, but in this patch series we assume that the TDX module is already loaded and initialized.The TDX module provides two main new logical modes of operation built upon the new SEAM (Secure Arbitration Mode) root and non-root CPU modes added to the VMX architecture. TDX root mode is mostly identical to the VMX root operation mode, and the TDX functions (described later) are triggered by the new SEAMCALL instruction with the desired interface function selected by an input operand (leaf number, in RAX). TDX non-root mode is used for TD guest operation. TDX non-root operation (i.e. "guest TD" mode) is similar to the VMX non-root operation (i.e. guest VM), with changes and restrictions to better assure that no other software or hardware has direct visibility of the TD memory and state.
TDX transitions between TDX root operation and TDX non-root operation include TD Entries, from TDX root to TDX non-root mode, and TD Exits from TDX non-root to TDX root mode. A TD Exit might be asynchronous, triggered by some external event (e.g., external interrupt or SMI) or an exception, or it might be synchronous, triggered by a TDCALL (TDG.VP.VMCALL) function.
TD VCPUs can be entered using SEAMCALL(TDH.VP.ENTER) by KVM. TDH.VP.ENTER is one of the TDX interface functions as mentioned above, and "TDH" stands for Trust Domain Host. Those host-side TDX interface functions are categorized into various areas just for better organization, such as SYS (TDX module management), MNG (TD management), VP (VCPU), PHYSMEM (physical memory), MEM (private memory), etc. For example, SEAMCALL(TDH.SYS.INFO) returns the TDX module information.
TDCS (Trust Domain Control Structure) is the main control structure of a guest TD, and encrypted (using the guest TD's ephemeral private key). At a high level, TDCS holds information for controlling TD operation as a whole, execution, EPTP, MSR bitmaps, etc that KVM needs to set it up. Note that MSR bitmaps are held as part of TDCS (unlike VMX) because they are meant to have the same value for all VCPUs of the same TD.
Trust Domain Virtual Processor State (TDVPS) is the root control structure of a TD VCPU. It helps the TDX module control the operation of the VCPU, and holds the VCPU state while the VCPU is not running. TDVPS is opaque to software and DMA access, accessible only by using the TDX module interface functions (such as TDH.VP.RD, TDH.VP.WR). TDVPS includes TD VMCS, and TD VMCS auxiliary structures, such as virtual APIC page, virtualization exception information, etc.
Several VMX control structures (such as Shared EPT and Posted interrupt descriptor) are directly managed and accessed by the host VMM. These control structures are pointed to by fields in the TD VMCS.
The above means that 1) KVM needs to allocate different data structures for TDs,
2) KVM can reuse the existing code for TDs for some operations, 3) it needs to define TD-specific handling for others. 3) Redirect operations to . 3) Redirect operations to the TDX specific callbacks, like "if (is_td_vcpu(vcpu))tdx_callback()elsevmx_callback();".*TD Private Memory
TD private memory is designed to hold TD private content, encrypted by the CPU using the TD ephemeral key. An encryption engine holds a table of encryption keys, and an encryption key is selected for each memory transaction based on a Host Key Identifier (HKID). By design, the host VMM does not have access to the encryption keys.In the first generation of MKTME, HKID is "stolen" from the physical address by allocating a configurable number of bits from the top of the physical address. The HKID space is partitioned into shared HKIDs for legacy MKTME accesses and private HKIDs for SEAM-mode-only accesses. We use 0 for the shared HKID on the host so that MKTME can be opaque or bypassed on the host.
During TDX non-root operation (i.e. guest TD), memory accesses can be qualified as either shared or private, based on the value of a new SHARED bit in the Guest Physical Address (GPA). The CPU translates shared GPAs using the usual VMX EPT (Extended Page Table) or "Shared EPT" (in this document), which resides in host VMM memory. The Shared EPT is directly managed by the host VMM - the same as with the current VMX. Since guest TDs usually require I/O, and the data exchange needs to be done via shared memory, thus KVM needs to use the current EPT functionality even for TDs.
* Secure EPT and Minoring using the TDP code
The CPU translates private GPAs using a separate Secure EPT. The Secure EPT pages are encrypted and integrity-protected with the TD's ephemeral private key. Secure EPT can be managed _indirectly_ by the host VMM, using the TDX interface functions, and thus conceptually Secure EPT is a subset of EPT (why "subset"). Since execution of such interface functions takes much longer time than accessing memory directly, in KVM we use the existing TDP code to minor the Secure EPT for the TD.This way, we can effectively walk Secure EPT without using the TDX interface functions.
* VM life cycle and TDX specific operations
The userspace VMM, such as QEMU, needs to build and treat TDs differently. For example, a TD needs to boot in private memory, and the host software cannot copy the initial image to private memory.* TSC Virtualization
The TDX module helps TDs maintain reliable TSC (Time Stamp Counter) values (e.g. consistent among the TD VCPUs) and the virtual TSC frequency is determined by TD configuration, i.e. when the TD is created, not per VCPU. The current KVM owns TSC virtualization for VMs, but the TDX module does for TDs.* MCE support for TDs
The TDX module doesn't allow VMM to inject MCE. Instead PV way is needed for TD to communicate with VMM. For now, KVM silently ignores MCE request by VMM. MSRs related to MCE (e.g, MCE bank registers) can be naturally emulated by paravirtualizing MSR access.[1] For details, the specifications, [2], [3], [4], [5], [6], [7], are available.
* Restrictions or future work
Some features are not included to reduce patch size. Those features are addressed as future independent patch series.
- large page (2M, 1G)
- qemu gdb stub
- guest PMU
- and more* Prerequisites
It's required to load the TDX module and initialize it. It's out of the scope of this patch series. Another independent patch for the common x86 code is planned. It definesCONFIG_INTEL_TDX_HOSTand this patch series usesCONFIG_INTEL_TDX_HOST. It's assumed that WithCONFIG_INTEL_TDX_HOST=y, the TDX module is initialized and ready for KVM to use the TDX module APIs for TDX guest life cycle like tdh.mng.init are ready to use.Concretely Global initialization, LP (Logical Processor) initialization, global configuration, the key configuration, and TDMR and PAMT initialization are done. The state of the TDX module is
SYS_READY. Please refer to the TDX module specification, the chapter Intel TDX Module Lifecycle State Machine** Detecting the TDX module readiness.
TDX host patch series implements the detection of the TDX module availability and its initialization so that KVM can use it. Also it manages Host KeyID (HKID) assigned to guest TD.
The assumed APIs the TDX host patch series provides are
- intseamrr_enabled()
Check if required cpu feature (SEAM mode) is available. This only check CPU feature availability. At this point, the TDX module may not be ready for KVM to use.
- intinit_tdx(void);
Initialization of TDX module so that the TDX module is ready for KVM to use.
- const structtdsysinfo_struct*tdx_get_sysinfo(void);
Return the system wide information about the TDX module. NULL if the TDX isn't initialized.
- u32tdx_get_global_keyid(void);
Return global key id that is used for the TDX module itself.
- inttdx_keyid_alloc(void);
Allocate HKID for guest TD.
- voidtdx_keyid_free(int keyid);
Free HKID for guest TD.(****)
* TDX KVM high-level design
- Host key ID management
Host Key ID (HKID) needs to be assigned to each TDX guest for memory encryption. It is assumed The TDX host patch series implements necessary functions, u32tdx_get_global_keyid(void), inttdx_keyid_alloc(void)and,
voidtdx_keyid_free(int keyid).- Data structures and VM type
Because TDX is different from VMX, define its own VM/VCPU structures, structkvm_tdxand structvcpu_tdxinstead of structkvm_vmxand structvcpu_vmx. To identify the VM, introduce VM-type to specify which VM type, VMX (default) or TDX, is used.- VM life cycle and TDX specific operations
Re-purpose the existingKVM_MEMORY_ENCRYPT_OPto add TDX specific operations. New commands are used to get the TDX system parameters, set TDX specific VM/VCPU parameters, set initial guest memory and measurement.The creation of TDX VM requires five additional operations in addition to the conventional VM creation.
- Get KVM system capability to check if TDX VM type is supported
- VM creation (KVM_CREATE_VM)
- New: Get the TDX specific system parameters.KVM_TDX_GET_CAPABILITY.
- New: Set TDX specific VM parameters.KVM_TDX_INIT_VM.
- VCPU creation (KVM_CREATE_VCPU)
- New: Set TDX specific VCPU parameters.KVM_TDX_INIT_VCPU.
- New: Initialize guest memory as boot state and extend the measurement with the memory.KVM_TDX_INIT_MEM_REGION.
- New: Finalize VM.KVM_TDX_FINALIZE. Complete measurement of the initial TDX VM contents.
- VCPU RUN (KVM_VCPU_RUN)- Protected guest state
Because the guest state (CPU state and guest memory) is protected, the KVM VMM can't operate on them. For example, accessing CPU registers, injecting exceptions, and accessing guest memory. Those operations are handled as silently ignored, returning zero or initial reset value when it's requested via KVM API ioctls.VM/VCPU state and callbacks for TDX specific operations. Define tdx specific VM state and VCPU state instead of VMX ones. Redirect operations to TDX specific callbacks. "if (tdx)
tdx_op()elsevmx_op()".Operations on the CPU state
silently ignore operations on the guest state. For example, the write to CPU registers is ignored and the read from CPU registers returns 0.. ignore access to CPU registers except for allowed ones.
. TSC: add a check if tsc is immutable and return an error. Because the KVM
implementation updates the internal tsc state and it's difficult to back out those changes. Instead, skip the logic.
. dirty logging: add check if dirty logging is supported.
. exceptions/SMI/MCE/SIPI/INIT: silently ignoreNote: virtual external interrupt and NMI can be injected into TDX guests.
- KVM MMU integration
One bit of the guest physical address (bit 51 or 47) is repurposed to indicate if the guest physical address is private (the bit is cleared) or shared (the bit is set). The bits are called stolen bits.- Stolen bits framework
systematically tracks which guest physical address, shared or private, is used.- Shared EPT and secure EPT
There are two EPTs. Shared EPT (the conventional one) and Secure EPT(the new one). Shared EPT is handled the same for the stolen bit set. Secure EPT points to private guest pages. To resolve EPT violation, KVM walks one of two EPTs based on faulted GPA. Because it's costly to access secure EPT during walking EPTs with SEAMCALLs for the private guest physical address, another private EPT is used as a shadow of Secure-EPT with the existing logic at the cost of extra memory.The following depicts the relationship.
KVM | TDX module | | | -------------+---------- | | | | | | V V | | shared GPA private GPA | | CPU shared EPT pointer KVM private EPT pointer | CPU secure EPT pointer | | | | | | | | V V | V shared EPT private EPT--------mirror----->Secure EPT | | | | | \--------------------+------\ | | | | | V | V V shared guest page | private guest page | | non-encrypted memory | encrypted memory |- Operating on Secure EPT
Use the TDX module APIs to operate on Secure EPT. To call the TDX API during resolving EPT violation, add hooks to additional operation and wiring it to TDX backend.* References
[1] TDX specification
https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html
[2] Intel Trust Domain Extensions (Intel TDX)
https://cdrdv2.intel.com/v1/dl/getContent/726790
[3] Intel CPU Architectural Extensions Specification
https://www.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-cpu-architectural-specification.pdf
[4] Intel TDX Module 1.0 Specification
https://www.intel.com/content/dam/develop/external/us/en/documents/tdx-module-1.0-public-spec-v0.931.pdf
[5] Intel TDX Loader Interface Specification
https://www.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-seamldr-interface-specification.pdf
[6] Intel TDX Guest-Hypervisor Communication Interface
https://cdrdv2.intel.com/v1/dl/getContent/726790
[7] Intel TDX Virtual Firmware Design Guide
https://www.intel.com/content/dam/develop/external/us/en/documents/tdx-virtual-firmware-design-guide-rev-1.01.pdf
[8] intel public github
kvm TDX branch: https://github.com/intel/tdx/tree/kvm
TDX guest branch: https://github.com/intel/tdx/tree/guest
qemu TDX https://github.com/intel/qemu-tdx
[9] TDVF
https://github.com/tianocore/edk2-staging/tree/TDVF
This was merged into EDK2 main branch. https://github.com/tianocore/edk2Chao Gao (3):
KVM: x86: Movecheck_processor_compatibilityfrom init ops to runtime
ops
Partially revert "KVM: Pass kvm_init()'s opaque param to additional
arch funcs"
KVM: x86: Allow to update cached values inkvm_user_return_msrsw/o
wrmsrIsaku Yamahata (72):
KVM: Refactor CPU compatibility check on module initialiization x86/virt/vmx/tdx: exportplatform_tdx_enabled()
KVM: TDX: Detect CPU feature on kernel module initialization
KVM: x86: Refactor KVM VMX module init/exit functions
KVM: TDX: Add placeholders for TDX VM/vcpu structure x86/virt/tdx: Add a helper function to return system wide info about
TDX module
KVM: TDX: Initialize TDX module when loading kvm_intel.ko
KVM: TDX: Make TDX VM type supported
[MARKER] The start of TDX KVM patch series: TDX architectural
definitions
KVM: TDX: Define TDX architectural definitions
KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module
KVM: TDX: Add helper functions to print TDX SEAMCALL error [MARKER] The start of TDX KVM patch series: TD VM creation/destruction x86/cpu: Add helper functions to allocate/free TDX private host key id
KVM: TDX: Add place holder for TDX VM specificmem_enc_opioctl
KVM: TDX: Makepmu_intel.cignore guest TD case
[MARKER] The start of TDX KVM patch series: TD vcpu
creation/destruction
KVM: TDX: allocate/free TDX vcpu structure
KVM: TDX: allocate/free TDX vcpu structure
[MARKER] The start of TDX KVM patch series: KVM MMU GPA shared bits
KVM: x86/mmu: introduce config for PRIVATE KVM MMU [MARKER] The start of TDX KVM patch series: KVM TDP refactoring for
TDX
KVM: x86/mmu: Disallow fast page fault on private GPA
KVM: VMX: Introduce test mode related to EPT violation VE [MARKER] The start of TDX KVM patch series: KVM TDP MMU hooks
KVM: x86/mmu: Focibly use TDP MMU for TDX
KVM: x86/mmu: Add a private pointer to structkvm_mmu_page
KVM: x86/tdp_mmu: refactorkvm_tdp_mmu_map()
KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU [MARKER] The start of TDX KVM patch series: TDX EPT violation
KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs
KVM: TDX: don't requestKVM_REQ_APIC_PAGE_RELOAD
KVM: TDX: TDP MMU TDX support
[MARKER] The start of TDX KVM patch series: KVM TDP MMU MapGPA
KVM: x86/mmu: steal software usable git to record if GFN is for shared
or not
KVM: x86/tdp_mmu: implement MapGPA hypercall for TDX [MARKER] The start of TDX KVM patch series: TD finalization
KVM: TDX: Create initial guest memory
KVM: TDX: Finalize VM initialization
[MARKER] The start of TDX KVM patch series: TD vcpu enter/exit
KVM: TDX: Add helper assembly function to TDX vcpu
KVM: TDX: Implement TDX vcpu enter/exit path
KVM: TDX:vcpu_run: save/restore host state(host kernel gs)
KVM: TDX: restore host xsave state when exit from the guest TD
KVM: TDX: restore user ret MSRs
[MARKER] The start of TDX KVM patch series: TD vcpu
exits/interrupts/hypercalls
KVM: TDX: complete interrupts after tdexit
KVM: TDX: restore debug store when TD exit
KVM: TDX: handle vcpu migration over logical processor
KVM: x86: Add aswitch_db_regsflag to handle TDX's auto-switched
behavior
KVM: TDX: remove use of structvcpu_vmxfromposted_interrupt.c
KVM: TDX: Implement interrupt injection
KVM: TDX: Implements vcpurequest_immediate_exit
KVM: TDX: Implement methods to inject NMI
KVM: TDX: Add a place holder to handle TDX VM exit
KVM: TDX: handleEXIT_REASON_OTHER_SMI
KVM: TDX: handle ept violation/misconfig exit
KVM: TDX: handleEXCEPTION_NMIandEXTERNAL_INTERRUPT
KVM: TDX: Add a place holder for handler of TDX hypercalls(TDG.VP.VMCALL)KVM: TDX: handle KVM hypercall with TDG.VP.VMCALL
KVM: TDX: Handle TDX PV CPUID hypercall
KVM: TDX: Handle TDX PV HLT hypercall
KVM: TDX: Handle TDX PV port io hypercall
KVM: TDX: Implement callbacks for MSR operations for TDX
KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall
KVM: TDX: Handle TDX PV report fatal error hypercall
KVM: TDX: Handle TDX PVmap_gpahypercall
KVM: TDX: Handle TDG.VP.VMCALL<GetTdVmCallInfo> hypercall
KVM: TDX: Silently discard SMI request
KVM: TDX: Silently ignore INIT/SIPIDocumentation/virtual/kvm: Document on Trust Domain Extensions(TDX)
KVM: x86: design documentation on TDX support of x86 KVM TDP MMURick Edgecombe (1):
KVM: x86/mmu: Add address conversion functions for TDX shared bitsSean Christopherson (25):
KVM: VMX: Move outvmx_x86_opsto 'main.c' to wrap VMX and TDX
KVM: Enable hardware before doing arch VM initialization
KVM: x86: Introducevm_typeto differentiate default VMs from
confidential VMs
KVM: TDX: Add TDX "architectural" error codes
KVM: TDX: Stub intdx.hwith structs, accessors, and VMCS helpers
KVM: TDX: create/destroy VM structure
KVM: TDX: x86: Add ioctl to get TDX systemwide parameters
KVM: TDX: Do TDX specific vcpu initialization
KVM: x86/mmu: Explicitly check for MMIO spte in fast page fault
KVM: x86/mmu: Allow non-zero value for non-present SPTE
KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis
KVM: x86/mmu: Allow per-VM override of the TDP max page level
KVM: x86/mmu: Zap only leaf SPTEs for deleted/moved memslot for
private mmu
KVM: x86/mmu: Disallow dirty logging for x86 TDX
KVM: VMX: Split out guts of EPT violation to common/exposed function
KVM: VMX: Move setting of EPT MMU masks to common VT-x code
KVM: TDX: Addload_mmu_pgdmethod for TDX
KVM: x86/mmu: Introducekvm_mmu_map_tdp_page()for use by TDX
KVM: TDX: Add support for find pending IRQ in a protected local APIC
KVM: x86: Assume timer IRQ was injected if APIC state is proteced
KVM: VMX: Modify NMI and INTR handlers to takeintr_infoas function
argument
KVM: VMX: Move NMI/exception handler to common helper
KVM: x86: Split core of hypercall emulation to helper function
KVM: TDX: Handle TDX PV MMIO hypercall
KVM: TDX: Add methods to ignore accesses to CPU stateXiaoyao Li (1):
KVM: TDX: initialize VM with TDX specific parametersDocumentation/virt/kvm/api.rst | 30 +- .../virt/kvm/intel-tdx-layer-status.rst | 33 + Documentation/virt/kvm/intel-tdx.rst | 381 +++ Documentation/virt/kvm/tdx-tdp-mmu.rst | 466 ++++ arch/arm64/kvm/arm.c | 2 +- arch/mips/kvm/mips.c | 14 +- arch/powerpc/kvm/powerpc.c | 2 +- arch/riscv/kvm/main.c | 2 +- arch/s390/kvm/kvm-s390.c | 2 +- arch/x86/events/intel/ds.c | 1 + arch/x86/include/asm/kvm-x86-ops.h | 10 + arch/x86/include/asm/kvm_host.h | 56 +- arch/x86/include/asm/tdx.h | 67 + arch/x86/include/asm/vmx.h | 14 + arch/x86/include/uapi/asm/kvm.h | 95 + arch/x86/include/uapi/asm/vmx.h | 5 +- arch/x86/kvm/Kconfig | 4 + arch/x86/kvm/Makefile | 3 +- arch/x86/kvm/irq.c | 3 + arch/x86/kvm/lapic.c | 37 +- arch/x86/kvm/lapic.h | 2 + arch/x86/kvm/mmu.h | 42 +- arch/x86/kvm/mmu/mmu.c | 360 ++- arch/x86/kvm/mmu/mmu_internal.h | 123 +- arch/x86/kvm/mmu/paging_tmpl.h | 5 +- arch/x86/kvm/mmu/spte.c | 46 +- arch/x86/kvm/mmu/spte.h | 65 +- arch/x86/kvm/mmu/tdp_iter.c | 1 + arch/x86/kvm/mmu/tdp_iter.h | 5 +- arch/x86/kvm/mmu/tdp_mmu.c | 690 ++++- arch/x86/kvm/mmu/tdp_mmu.h | 12 +- arch/x86/kvm/svm/svm.c | 13 +- arch/x86/kvm/vmx/common.h | 174 ++ arch/x86/kvm/vmx/evmcs.c | 2 +- arch/x86/kvm/vmx/evmcs.h | 2 +- arch/x86/kvm/vmx/main.c | 1071 +++++++ arch/x86/kvm/vmx/pmu_intel.c | 39 +- arch/x86/kvm/vmx/pmu_intel.h | 28 + arch/x86/kvm/vmx/posted_intr.c | 43 +- arch/x86/kvm/vmx/posted_intr.h | 13 + arch/x86/kvm/vmx/tdx.c | 2465 +++++++++++++++++ arch/x86/kvm/vmx/tdx.h | 275 ++ arch/x86/kvm/vmx/tdx_arch.h | 157 ++ arch/x86/kvm/vmx/tdx_errno.h | 29 + arch/x86/kvm/vmx/tdx_error.c | 22 + arch/x86/kvm/vmx/tdx_ops.h | 188 ++ arch/x86/kvm/vmx/vmenter.S | 146 + arch/x86/kvm/vmx/vmx.c | 737 ++--- arch/x86/kvm/vmx/vmx.h | 39 +- arch/x86/kvm/vmx/x86_ops.h | 235 ++ arch/x86/kvm/x86.c | 148 +- arch/x86/virt/vmx/tdx/seamcall.S | 2 + arch/x86/virt/vmx/tdx/tdx.c | 54 +- arch/x86/virt/vmx/tdx/tdx.h | 52 - include/linux/kvm_host.h | 4 +- include/uapi/linux/kvm.h | 2 + tools/arch/x86/include/uapi/asm/kvm.h | 95 + tools/include/uapi/linux/kvm.h | 1 + virt/kvm/kvm_main.c | 67 +- 59 files changed, 7877 insertions(+), 804 deletions(-) create mode 100644 Documentation/virt/kvm/intel-tdx-layer-status.rst create mode 100644 Documentation/virt/kvm/intel-tdx.rst create mode 100644 Documentation/virt/kvm/tdx-tdp-mmu.rst create mode 100644 arch/x86/kvm/vmx/common.h create mode 100644 arch/x86/kvm/vmx/main.c create mode 100644 arch/x86/kvm/vmx/pmu_intel.h create mode 100644 arch/x86/kvm/vmx/tdx.c create mode 100644 arch/x86/kvm/vmx/tdx.h create mode 100644 arch/x86/kvm/vmx/tdx_arch.h create mode 100644 arch/x86/kvm/vmx/tdx_errno.h create mode 100644 arch/x86/kvm/vmx/tdx_error.c create mode 100644 arch/x86/kvm/vmx/tdx_ops.h create mode 100644 arch/x86/kvm/vmx/x86_ops.hSignature · 1 line
2.25.1Signature · 1 line
Isaku Yamahata <[email protected]>
Quoted 127 lines · Chao Peng
Quoted 78 lines · Isaku Yamahata
Hi. Because my description on large page support was terse, I wrote up more detailed one. Any feedback/thoughts on large page support?
TDP MMU large page support design
Two main discussion points
* how to track page status. private vs shared, no-largepage vs can-be-largepage
* how to trigger merging mapping from 4KB/2MB to 2MB/1GBExpected private-vs-shared page usage
-------------------------------------
On TD boot all pages are private and TD converts pages into shared if necessary.
* Most of the guest pages remain private.
* Only limited pages are converted at kernel boot
** bounce buffer for IO (virt-io). It's allocated as swiotlb. Its size is
64MB or 6% of total guest memory.
** KVM PV shared page. (the current guest TD doesn't use KVM PV shared page.)
* Only a small number of pages are dynamically converted from private to shared and vice versa. This usage is very limited. e.g. GetQuote, the lack of swiotlb bufferTheory of Secure-EPT operations related to large page
-----------------------------------------------------
TDX Secure-EPT has differences from VMX EPT. To add a page to Secure-EPT* Here is the operation to resolve the EPT violation.
1. TD: Accepts GPA. TD needs to accept GPA before accessing GPA because TD needs to detect that VMM unmaps GPA and maps GPA again.
2. EPT violation is triggered. TD exit to VMM.
3. VMM: allocate a page for GPA and TDH.MEM.PAGE.AUG it to GPA. Resume TD vcpu. (3a. TD: #VE<EPT violation> is injected. #VE handler accepts the page)
4. TD: resume #VE and continue TD vcpu executionTD may choose step 1. In that case, After step 3. #VE is injected into TD and, TD #VE handler needs to accept the page.
When adding a page to Secure-EPT again, the page contexts are cleared and the page is encrypted. If a page is disassociated from Secure-EPT and added again, the page content is lost.
* TDG.VP.VMCALL<MapGPA> hypercall
The page associated with GPA can be private or shared. TD converts the GPA by TDG.VP.VMCALL<MapGPA> hypercall from private to shared or vice versa. VMM tracks whether the given GPA is private or shared.* mapping merge(promote)/split(demote)
The page can be mapped as large page (2MB or 1GB) in addition to 4KB. The mapping can bemerged(4KB/2MB -> 2MB/1GB)orsplit(2MB/1GB -> 4KB/2MB)by TDX SEAMCALL TDH.MEM.PAGE.PROMOTE and TDH.MEM.PAGE.DEMOTE.
The merge of mapping requires all the pages needs to be mapped, unlike VMX EPT because of encryption. This implies the current KVM implementation doesn't work for TDX when merging mapping as follows- EPT violation and host page is 2MB mappable.
some of the 4KB pages of the given 2MB page are already mapped, some not. i.e. 2MB EPT -> 4KB EPT -> 4K pages
- KVM page fault handler zap 2MB EPT entry and populate 2MB EPT entry
zap: 2MB EPT: non present
populate 2MB: -> 2MB pageIf VMM zaps 2MB Secure-EPT entry, the page contents will be lost for TDX. Mapping merge requires all pages are already mapped.
Instead, the following steps are needed.
- EPT violation and host page is 2MB mappable.
some of the 4KB pages of the given 2MB page are already mapped. Some not. i.e. 2MB EPT -> 4KB EPT -> 4K pages
- VMM checks all 4KB GPAs are private. If not, it can't be mapped as a large page. (****)
- VMM checks all 4KB GPAs are already mapped. If not, give up mapping merge. (or map missing 4KB pages.)
- mapping merge by TDH.MEM.PAGE.PROMOTEThe mapping split for TDX Secure-EPT works similarly to the VMX EPT case.
Quoted 8 lines
EPT violation and MapGPA
------------------------
- EPT violation is a fast path
- MapGPA is not a fast path.
=> Keep the EPT violation path optimized and complicates the MapGPA path. For (****) check, we don't want to scan the 4KB mapping on EPT violation. Instead, the MapGPA path scans it and records the result as the page can be mapped as 2MB due to private/shared.This sounds reasonable, Instead of tracking that in MapGPA, maybe KVM_MEMORY_ENCRYPT_{UN,}REG_REGION introduced in UPM v7 is a better place to put the scan code in.
https://lkml.org/lkml/2022/7/6/259
Both the MapGPA (explicit conversion) and the EPT violation (implicit conversion) can cause invocation to these two ioctls and need update to this info.
Quoted 9 lines
Tracking private/shared and large page mappable
-----------------------------------------------
VMM needs to track that page is mapped as private or shared at 4KB granularity. For efficiency of EPT violation path (****), at 2MB and 1GB level, VMM should track the page can be mapped as a large page (regarding private/shared). VMM updates it on MapGPA and references it on the EPT violation path. (****)Quoted 3 lines
For 4KB pages, 1 bit is needed. private or shared. Let's call it shared-mask bit. For 2MB/1GB pages, 2 bit is needed. large page mappable or not. private or shared if mappable. Let's call it no-largepage bit.
I'm just thinking maybe we don't need introduce new bits, instead we reuse
lpage_infowhere we already use it to track whether a page can be mapped at specified page level inkvm_mmu_max_mapping_level(). Then in the above two ioctls we do a scan for each level and updatelpage_info. For example, we shoulddisallow_lpageif private/shared pages are mixed in that page level.It's however a bit tricky to manage lpage_info.disallow_lpage in these two ioctls with current code. We can't simply do disallow_lpage++ and disallow_lpage--. One possible solution can treat
disallow_lpageas a mask instead of a count. Then we define bits like below for use:
-USER_GFN_UNALIGNEDset when memslot user_address/private_offset/gfn is not aligned on the page level
-PAGE_TRACKINGset during page tracking
-PRIVITE_SHARED_MIXEDset when private/shared pages are mixed
Quoted 3 lines
In page fault handler the page can be mapped at that level only when all bits are zero and in above two ioctls we just switch on/off bit
PRIVITE_SHARED_MIXED.
So steal 1 or 2 bits from kvm_lpage_info.disallow_lpage instead of adding one more array in struct kvm_arch_memory_slot. Nice idea. Let's call it option A.1). We increment/decrement disallow_lpage with option A.). With option A.1), it automatically handled.
pros:
+SPTE_SHARED_MASK is not needed
cons:
-one more look-up on EPT violation
Quoted 1 line
Currently UMP don't have this code yet, but can be added if feasible.
Anyway let me integrate UPM v7.
Thanks,
Quoted 864 lines
Chao
Quoted 863 lines
Option A.)
Allocate array for pages in structkvm_arch_memory_sloton TD creation.struct kvm_arch_memory_slot { +struct kvm_page_attr *page_attr[KVM_NR_PAGE_SIZES];}
pros:
+straight forward implementation
+SPTE_SHARED_MASK is not needed
cons:
-memory overhead is high
-not optimized for expected usage
-one more look-up on EPT violationOption B.) Steal two software usable bits from SPTE and record them in SPTE.
SPTE_SHARED_MASK,SPTE_NOLARGE_PAGE_MASK
pros:
+optimized for EPT violation
cons:
-2bits used in SPTE entry
-complicates the MapGPA path.Option C.) Steal one software usable bit from SPTE and record it in SPTE.
SPTE_SHARED_MASK For 2MB/1GB, allocate bitmap in kvm_mmu_page. struct kvm_mmu_page { bitmap nolarge }pros:
+optimized for EPT violation
cons:
-complicates the MapGPA path.
-information is scattered in SPTE and structkvm_mmu_pageHow to update those bits
------------------------
- MapGPA
- at 4KB level, set or clear shared-mask bit.
- Scan 512 4KB bit, at 2MB level
- set or clear shared-mask bit, clear no-largepage bit or
- clear shared-mask bit, set no-largepage bit
- increment/decrement lpageinfo to prevent/allow large page
- similar for 1GB level
Note: This logic might a bit tricky.- EPT violation
- If 2MB large page is allowed, check if no-largepage bit
- If no-largepage bit is set, => go down to 4KB page
- If no-largepage bit is cleared => try to map 2MB page
- If 4KB level is not mapped, map 2MB page
- If some 4KB level is already mapped, go down to 4KB. Don't try to merge mapping. Or it's possible to try to merge mapping.
Note: 512 4KB entry scanning is not done at EPT violation because it's fast
path.Map merging
-----------
Map merging is necessary for TD migration. (Map split is the easy part.) The current KVM implementation zaps the range (mmu notification or lpage recovery worker) and expects large page mapping on the next EPT violation.Option A.) Keep the code similar to map merging logic.
Zap 2MB EPT entry in some sense and trigger map merging logic on the next EPT violation. To keep encrypted page contents, zapped EPT entries needs to keep the page. Steal one more bits from SPTE.SPTE_PRIVATE_BLOCKED_MASK. It means that the page is zapped from SPTE. but it still alive and references page.Option B.) In the callback, directly merge mapping somehow. In this case, mmu notifier usage doesn't make sense.
NOTE:
- Implement map merging in MapGPA. This doesn't work for dirty page logging.
- We can utilizekvm_nx_lpage_recovery_worker
- We can utilize THP. Probably doesn't work well for fd-based private memory.Thanks,
Isaku YamayhataQuoted 775 lines · On Mon, Jun 27, 2022 at 02:52:52PM -0700, [email protected] wrote:
From: Isaku Yamahata <[email protected]>
KVM TDX basic feature support
Hello. This is v7 the patch series vof KVM TDX support.
This is based on v5.19-rc1 + kvm/queue branch + TDX HOST patch series. The tree can be found at https://github.com/intel/tdx/tree/kvm-upstream
How to run/test: It's describe at https://github.com/intel/tdx/wiki/TDX-KVMMajor changes from v6:
- rebased to v5.19 baseTODO:
- integrate fd-based guest memory. As the discussion is still on-going, I intentionally dropped fd-based guest memory support yet. The integration can be found at https://github.com/intel/tdx/tree/kvm-upstream-workaround.
- 2M large page support. It's work-in-progress.
For large page support, there are several design choices. Here is the design options. Any thoughts/feedback?KVM MMU Large page support for TDX
* What needs to be done
- Track private or shared of each page size (4KB, 2MB, 1GB) based on TDG.VP.VMCALL<MapGPA>. For largepages(2MB, 1GB), it can be mixed (some lower-size pages are private and some shared.) In this case, the page can't be large.
- if necessary, split large page on TDG.VP.VMCALL<MapGPA>
(split on dirty page tracking is future work)
- resolving KVM page fault
When resolving a private page and the page is large in the host, GPA can be resolved as a large page in Secure-EPT. Even if the page is large on the host side, sometimes a 4KB page can be resolved because it's up to guest TD to accept at 4KB, 2MB, or 1GB.
- collapsing pages into a large page.
At this point, it's okay to not implement this. When dirty page tracking is supported, this needs to be supported.
- On MapGPA, the page can be collapsed into a large page
- handle zapping SPTE and try to collapse the pages on the next KVM page fault Unlike the EPT case, some trick is needed.
- For performance, optimize KVM page fault path at the cost of complicating MapGPA path.* options to track private or shared
At each page size (4KB, 2MB, and 1GB), track private, shared, or mixed (2MB and 1GB case). For 4KB each page, 1 bit per page is needed. private or shared. For large pages (2MB and 1GB), 2 bits per large page is needed. (private, shared, or mixed). When resolving KVM page fault, we don't want to check the lower-size pages to check if the given GPA can be a large for performance. On MapGPA check it instead.Option A). enhance
kvm_arch_memory_slot
enumkvm_page_type{
KVM_PAGE_TYPE_INVALID,
KVM_PAGE_TYPE_SHARED,
KVM_PAGE_TYPE_PRIVATE,
KVM_PAGE_TYPE_MIXED,
};struct kvm_page_attr { enum kvm_page_type type; };struct
kvm_arch_memory_slot{
+ structkvm_page_attr*page_attr[KVM_NR_PAGE_SIZES];Option B). steal one more bit
SPTE_MIXED_MASKin addition toSPTE_SHARED_MASKIf !SPTE_MIXED_MASK, it can be large page.Option C). use
SPTE_SHARED_MASKandkvm_mmu_page::mixedbitmapkvm_mmu_page::mixedbitmap of 1GB, root indicates mixed for 2MB, 1GB.* comparison
A).
+ straightforward to implement
+SPTE_SHARED_MASKisn't needed
- memory overhead compared to B). or C).
- more memory reference on KVM page faultB).
+ simpler than C) (complex than A)?)
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- Waste precious SPTE bits.C).
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- complicates MapGPA
- scattered data structureThanks,
Isaku YamahataChanges from v6:
- rebased to v5.19Changes from v5:
- export__seamcalland use it
- move mutex lock from callee function ofsmp_call_on_cputo the caller.
- renamemmu_prezap=>flush_shadow_all_private()andtdx_mmu_release_hkid
- updated comment
- drop the use oftdh_mng_key.reclaimid(): as the function is for backward compatibility to only return success
- structkvm_tdx_cmd: metadata => flags, added__u64error.
- make this ioctl systemwide ioctl
- ABI change to structkvm_init_vm
-guest_tsc_khz: usekvm->arch.default_tsc_khz
- renameBUILD_BUG_ON_MEMCPYtoMEMCPY_SAME_SIZE
- drop exportingkvm_set_tsc_khz().
- fixkvm_tdp_page_fault()for mtrr emulation
- rename it tokvm_gfn_shared_mask(), droppedkvm_gpa_shared_mask()
- dropkvm_is_private_gfn(), keptkvm_is_private_gpa()
keep kvm_{gfn, gpa}_private(),kvm_gpa_private()
- update commit message
- renameshadow_init_value=>shadow_nonprsent_value
- addedept_violation_ve_testmode
-shadow_nonpresent_value=>SHADOW_NONPRESENT_VALUEintdp_mmu.c
- legacy MMU case
=> -mmu_topup_shadow_page_cache(),kvm_mmu_create()
- FNAME(sync_page)(structkvm_vcpu*vcpu, structkvm_mmu_page*sp)
- #VE warning:
- rename:REMOVED_SPTE=>__REMOVED_SPTE,SHADOW_REMOVED_SPTE=>REMOVED_SPTE
- merge into Like we discussed, this patch should be merged with patch "KVM: x86/mmu: Allow non-zero init value for shadow PTE".
- fix pointed by Sagi. check !is_private check => (kvm_gfn_shared_mask&& !is_private)
- introducekvm_gfn_for_root(kvm, root, gfn)
- addonly_sharedargument tokvm_tdp_mmu_handle_gfn()
- usekvm_arch_dirty_log_supported()
- renameSPTE_PRIVATE_PROHIBITtoSPTE_SHARED_MASK.
- rename:is_private_prohibit_spte()=>spte_shared_mask()
- fix:shadow_nonpresent_value=>SHADOW_NONPRESENT_VALUEin comment
- dropped this patch as the change was merged into kvm/queue
- updatevt_apicv_post_state_restore()
- useis_64_bit_hypercall()
- comment: expand MSMI -> Machine Check System Management Interrupt
- fixedTDX_SEPT_PFERR
- tdvmcall_p[1234]_{write, read}() => tdvmcall_a[0123]_{read,write}()
- renametdmvcall_exit_readon()=>tdvmcall_leaf()
- remove optional zero check of argument.
- do a check for static_call(kvm_x86_has_emulated_msr)(kvm,MSR_IA32_SMBASE) inkvm_vcpu_ioctl_smiand__apic_accept_irq.
-WARN_ON_ONCEintdx_smi_allowedandtdx_enable_smi_window.
- introducevcpu_deliver_inittox86_ops
- sprinkeledKVM_BUG_ON()Changes from v4:
- rebased to TDX host kernel patch series.
- include all the patches to make this patch series working.
- add [MARKER] patches to mark the patch layer clear.---
* What's TDX?
TDX stands for Trust Domain Extensions, which extends Intel Virtual Machines Extensions (VMX) to introduce a kind of virtual machine guest called a Trust Domain (TD) for confidential computing.A TD runs in a CPU mode that is designed to protect the confidentiality of its memory contents and its CPU state from any other software, including the hosting Virtual Machine Monitor (VMM), unless explicitly shared by the TD itself.
We have more detailed explanations below (***). We have the high-level design of TDX KVM below (****).
In this patch series, we use "TD" or "guest TD" to differentiate it from the current "VM" (Virtual Machine), which is supported by KVM today.
* The organization of this patch series
This patch series is on top of the patches series "TDX host kernel support":
https://lore.kernel.org/lkml/[email protected]/this patch series is available at
https://github.com/intel/tdx/releases/tag/kvm-upstream
The corresponding patches to qemu are available at
https://github.com/intel/qemu-tdx/commits/tdx-upstreamThe relations of the layers are depicted as follows.
The arrows below show the order of patch reviews we would like to have.The below layers are chosen so that the device model, for example, qemu can exercise each layering step by step. Check if TDX is supported, create TD VM, create TD vcpu, allow vcpu running, populate TD guest private memory, and handle vcpu exits/hypercalls/interrupts to run TD fully.
TDX vcpu
interrupt/exits/hypercall<------------\^ | | | TD finalization | ^ | | | TDX EPT violation<------------\ | ^ | | | | | TD vcpu enter/exit | | ^ | | | | | TD vcpu creation/destruction | \-------KVM TDP MMU MapGPA ^ | ^ | | | TD VM creation/destruction \---------------KVM TDP MMU hooks^ ^
| |
TDX architectural definitions KVM TDP refactoring for TDX
^ ^
| |
TDX, VMX <--------TDX host kernel KVM MMU GPA stolen bits
coexistence supportThe followings are explanations of each layer. Each layer has a dummy commit that starts with [MARKER] in subject. It is intended to help to identify where each layer starts.
TDX host kernel support:
https://lore.kernel.org/lkml/[email protected]/
The guts of system-wide initialization of TDX module. There is an independent patch series for host x86. TDX KVM patches call functions this patch series provides to initialize the TDX module.TDX, VMX coexistence:
Infrastructure to allow TDX to coexist with VMX and trigger the initialization of the TDX module.
This layer starts with
"KVM: VMX: Move outvmx_x86_opsto 'main.c' to wrap VMX and TDX"
TDX architectural definitions:
Add TDX architectural definitions and helper functions
This layer starts with
"[MARKER] The start of TDX KVM patch series: TDX architectural definitions".
TD VM creation/destruction:
Guest TD creation/destroy allocation and releasing of TDX specific vm and vcpu structure. Create an initial guest memory image with TDX measurement.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD VM creation/destruction".
TD vcpu creation/destruction:
guest TD creation/destroy Allocation and releasing of TDX specific vm and vcpu structure. Create an initial guest memory image with TDX measurement.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu creation/destruction"
TDX EPT violation:
Create an initial guest memory image with TDX measurement. Handle secure EPT violations to populate guest pages with TDX SEAMCALLs. This layer starts with
"[MARKER] The start of TDX KVM patch series: TDX EPT violation"
TD vcpu enter/exit:
Allow TDX vcpu to enter into TD and exit from TD. Save CPU state before entering into TD. Restore CPU state after exiting from TD.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu enter/exit"
TD vcpu interrupts/exit/hypercall:
Handle various exits/hypercalls and allow interrupts to be injected so that TD vcpu can continue running.
This layer starts with
"[MARKER] The start of TDX KVM patch series: TD vcpu exits/interrupts/hypercalls"KVM MMU GPA shared bit:
Introduce framework to handle shared bit repurposed bit of GPA TDX repurposed a bit of GPA to indicate shared or private. If it's shared, it's the same as the conventional VMX EPT case. VMM can access shared guest pages. If it's private, it's handled by Secure-EPT and the guest page is encrypted.
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM MMU GPA stolen bits"
KVM TDP refactoring for TDX:
TDX Secure EPT requires different constants. e.g. initial value EPT entry value etc. Various refactoring for those differences. This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP refactoring for TDX"
KVM TDP MMU hooks:
Introduce framework to TDP MMU to add hooks in addition to direct EPT access TDX added Secure EPT which is an enhancement to VMX EPT. Unlike conventional VMX EPT, CPU can't directly read/write Secure EPT. Instead, use TDX SEAMCALLs to operate on Secure EPT.
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP MMU hooks"
KVM TDP MMU MapGPA:
Introduce framework to handle switching guest pages from private/shared to shared/private. For a given GPA, a guest page can be assigned to a private GPA or a shared GPA exclusively. With TDX MapGPA hypercall, guest TD converts GPA assignments from private (or shared) to shared (or private).
This layer starts with
"[MARKER] The start of TDX KVM patch series: KVM TDP MMU MapGPA "KVM guest private memory: (not shown in the above diagram)
[PATCH v4 00/12] KVM: mm: fd-based approach for supporting KVM guest private
memory: https://lkml.org/lkml/2022/1/18/395
Guest private memory requires different memory management in KVM. The patch proposes a way for it. Integration with TDX KVM.(***)
* TDX module
A CPU-attested software module called the "TDX module" is designed to implement the TDX architecture, and it is loaded by the UEFI firmware today. It can be loaded by the kernel or driver at runtime, but in this patch series we assume that the TDX module is already loaded and initialized.The TDX module provides two main new logical modes of operation built upon the new SEAM (Secure Arbitration Mode) root and non-root CPU modes added to the VMX architecture. TDX root mode is mostly identical to the VMX root operation mode, and the TDX functions (described later) are triggered by the new SEAMCALL instruction with the desired interface function selected by an input operand (leaf number, in RAX). TDX non-root mode is used for TD guest operation. TDX non-root operation (i.e. "guest TD" mode) is similar to the VMX non-root operation (i.e. guest VM), with changes and restrictions to better assure that no other software or hardware has direct visibility of the TD memory and state.
TDX transitions between TDX root operation and TDX non-root operation include TD Entries, from TDX root to TDX non-root mode, and TD Exits from TDX non-root to TDX root mode. A TD Exit might be asynchronous, triggered by some external event (e.g., external interrupt or SMI) or an exception, or it might be synchronous, triggered by a TDCALL (TDG.VP.VMCALL) function.
TD VCPUs can be entered using SEAMCALL(TDH.VP.ENTER) by KVM. TDH.VP.ENTER is one of the TDX interface functions as mentioned above, and "TDH" stands for Trust Domain Host. Those host-side TDX interface functions are categorized into various areas just for better organization, such as SYS (TDX module management), MNG (TD management), VP (VCPU), PHYSMEM (physical memory), MEM (private memory), etc. For example, SEAMCALL(TDH.SYS.INFO) returns the TDX module information.
TDCS (Trust Domain Control Structure) is the main control structure of a guest TD, and encrypted (using the guest TD's ephemeral private key). At a high level, TDCS holds information for controlling TD operation as a whole, execution, EPTP, MSR bitmaps, etc that KVM needs to set it up. Note that MSR bitmaps are held as part of TDCS (unlike VMX) because they are meant to have the same value for all VCPUs of the same TD.
Trust Domain Virtual Processor State (TDVPS) is the root control structure of a TD VCPU. It helps the TDX module control the operation of the VCPU, and holds the VCPU state while the VCPU is not running. TDVPS is opaque to software and DMA access, accessible only by using the TDX module interface functions (such as TDH.VP.RD, TDH.VP.WR). TDVPS includes TD VMCS, and TD VMCS auxiliary structures, such as virtual APIC page, virtualization exception information, etc.
Several VMX control structures (such as Shared EPT and Posted interrupt descriptor) are directly managed and accessed by the host VMM. These control structures are pointed to by fields in the TD VMCS.
The above means that 1) KVM needs to allocate different data structures for TDs,
2) KVM can reuse the existing code for TDs for some operations, 3) it needs to define TD-specific handling for others. 3) Redirect operations to . 3) Redirect operations to the TDX specific callbacks, like "if (is_td_vcpu(vcpu))tdx_callback()elsevmx_callback();".*TD Private Memory
TD private memory is designed to hold TD private content, encrypted by the CPU using the TD ephemeral key. An encryption engine holds a table of encryption keys, and an encryption key is selected for each memory transaction based on a Host Key Identifier (HKID). By design, the host VMM does not have access to the encryption keys.In the first generation of MKTME, HKID is "stolen" from the physical address by allocating a configurable number of bits from the top of the physical address. The HKID space is partitioned into shared HKIDs for legacy MKTME accesses and private HKIDs for SEAM-mode-only accesses. We use 0 for the shared HKID on the host so that MKTME can be opaque or bypassed on the host.
During TDX non-root operation (i.e. guest TD), memory accesses can be qualified as either shared or private, based on the value of a new SHARED bit in the Guest Physical Address (GPA). The CPU translates shared GPAs using the usual VMX EPT (Extended Page Table) or "Shared EPT" (in this document), which resides in host VMM memory. The Shared EPT is directly managed by the host VMM - the same as with the current VMX. Since guest TDs usually require I/O, and the data exchange needs to be done via shared memory, thus KVM needs to use the current EPT functionality even for TDs.
* Secure EPT and Minoring using the TDP code
The CPU translates private GPAs using a separate Secure EPT. The Secure EPT pages are encrypted and integrity-protected with the TD's ephemeral private key. Secure EPT can be managed _indirectly_ by the host VMM, using the TDX interface functions, and thus conceptually Secure EPT is a subset of EPT (why "subset"). Since execution of such interface functions takes much longer time than accessing memory directly, in KVM we use the existing TDP code to minor the Secure EPT for the TD.This way, we can effectively walk Secure EPT without using the TDX interface functions.
* VM life cycle and TDX specific operations
The userspace VMM, such as QEMU, needs to build and treat TDs differently. For example, a TD needs to boot in private memory, and the host software cannot copy the initial image to private memory.* TSC Virtualization
The TDX module helps TDs maintain reliable TSC (Time Stamp Counter) values (e.g. consistent among the TD VCPUs) and the virtual TSC frequency is determined by TD configuration, i.e. when the TD is created, not per VCPU. The current KVM owns TSC virtualization for VMs, but the TDX module does for TDs.* MCE support for TDs
The TDX module doesn't allow VMM to inject MCE. Instead PV way is needed for TD to communicate with VMM. For now, KVM silently ignores MCE request by VMM. MSRs related to MCE (e.g, MCE bank registers) can be naturally emulated by paravirtualizing MSR access.[1] For details, the specifications, [2], [3], [4], [5], [6], [7], are available.
* Restrictions or future work
Some features are not included to reduce patch size. Those features are addressed as future independent patch series.
- large page (2M, 1G)
- qemu gdb stub
- guest PMU
- and more* Prerequisites
It's required to load the TDX module and initialize it. It's out of the scope of this patch series. Another independent patch for the common x86 code is planned. It definesCONFIG_INTEL_TDX_HOSTand this patch series usesCONFIG_INTEL_TDX_HOST. It's assumed that WithCONFIG_INTEL_TDX_HOST=y, the TDX module is initialized and ready for KVM to use the TDX module APIs for TDX guest life cycle like tdh.mng.init are ready to use.Concretely Global initialization, LP (Logical Processor) initialization, global configuration, the key configuration, and TDMR and PAMT initialization are done. The state of the TDX module is
SYS_READY. Please refer to the TDX module specification, the chapter Intel TDX Module Lifecycle State Machine** Detecting the TDX module readiness.
TDX host patch series implements the detection of the TDX module availability and its initialization so that KVM can use it. Also it manages Host KeyID (HKID) assigned to guest TD.
The assumed APIs the TDX host patch series provides are
- intseamrr_enabled()
Check if required cpu feature (SEAM mode) is available. This only check CPU feature availability. At this point, the TDX module may not be ready for KVM to use.
- intinit_tdx(void);
Initialization of TDX module so that the TDX module is ready for KVM to use.
- const structtdsysinfo_struct*tdx_get_sysinfo(void);
Return the system wide information about the TDX module. NULL if the TDX isn't initialized.
- u32tdx_get_global_keyid(void);
Return global key id that is used for the TDX module itself.
- inttdx_keyid_alloc(void);
Allocate HKID for guest TD.
- voidtdx_keyid_free(int keyid);
Free HKID for guest TD.(****)
* TDX KVM high-level design
- Host key ID management
Host Key ID (HKID) needs to be assigned to each TDX guest for memory encryption. It is assumed The TDX host patch series implements necessary functions, u32tdx_get_global_keyid(void), inttdx_keyid_alloc(void)and,
voidtdx_keyid_free(int keyid).- Data structures and VM type
Because TDX is different from VMX, define its own VM/VCPU structures, structkvm_tdxand structvcpu_tdxinstead of structkvm_vmxand structvcpu_vmx. To identify the VM, introduce VM-type to specify which VM type, VMX (default) or TDX, is used.- VM life cycle and TDX specific operations
Re-purpose the existingKVM_MEMORY_ENCRYPT_OPto add TDX specific operations. New commands are used to get the TDX system parameters, set TDX specific VM/VCPU parameters, set initial guest memory and measurement.The creation of TDX VM requires five additional operations in addition to the conventional VM creation.
- Get KVM system capability to check if TDX VM type is supported
- VM creation (KVM_CREATE_VM)
- New: Get the TDX specific system parameters.KVM_TDX_GET_CAPABILITY.
- New: Set TDX specific VM parameters.KVM_TDX_INIT_VM.
- VCPU creation (KVM_CREATE_VCPU)
- New: Set TDX specific VCPU parameters.KVM_TDX_INIT_VCPU.
- New: Initialize guest memory as boot state and extend the measurement with the memory.KVM_TDX_INIT_MEM_REGION.
- New: Finalize VM.KVM_TDX_FINALIZE. Complete measurement of the initial TDX VM contents.
- VCPU RUN (KVM_VCPU_RUN)- Protected guest state
Because the guest state (CPU state and guest memory) is protected, the KVM VMM can't operate on them. For example, accessing CPU registers, injecting exceptions, and accessing guest memory. Those operations are handled as silently ignored, returning zero or initial reset value when it's requested via KVM API ioctls.VM/VCPU state and callbacks for TDX specific operations. Define tdx specific VM state and VCPU state instead of VMX ones. Redirect operations to TDX specific callbacks. "if (tdx)
tdx_op()elsevmx_op()".Operations on the CPU state
silently ignore operations on the guest state. For example, the write to CPU registers is ignored and the read from CPU registers returns 0.. ignore access to CPU registers except for allowed ones.
. TSC: add a check if tsc is immutable and return an error. Because the KVM
implementation updates the internal tsc state and it's difficult to back out those changes. Instead, skip the logic.
. dirty logging: add check if dirty logging is supported.
. exceptions/SMI/MCE/SIPI/INIT: silently ignoreNote: virtual external interrupt and NMI can be injected into TDX guests.
- KVM MMU integration
One bit of the guest physical address (bit 51 or 47) is repurposed to indicate if the guest physical address is private (the bit is cleared) or shared (the bit is set). The bits are called stolen bits.- Stolen bits framework
systematically tracks which guest physical address, shared or private, is used.- Shared EPT and secure EPT
There are two EPTs. Shared EPT (the conventional one) and Secure EPT(the new one). Shared EPT is handled the same for the stolen bit set. Secure EPT points to private guest pages. To resolve EPT violation, KVM walks one of two EPTs based on faulted GPA. Because it's costly to access secure EPT during walking EPTs with SEAMCALLs for the private guest physical address, another private EPT is used as a shadow of Secure-EPT with the existing logic at the cost of extra memory.The following depicts the relationship.
KVM | TDX module | | | -------------+---------- | | | | | | V V | | shared GPA private GPA | | CPU shared EPT pointer KVM private EPT pointer | CPU secure EPT pointer | | | | | | | | V V | V shared EPT private EPT--------mirror----->Secure EPT | | | | | \--------------------+------\ | | | | | V | V V shared guest page | private guest page | | non-encrypted memory | encrypted memory |- Operating on Secure EPT
Use the TDX module APIs to operate on Secure EPT. To call the TDX API during resolving EPT violation, add hooks to additional operation and wiring it to TDX backend.* References
[1] TDX specification
https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html
[2] Intel Trust Domain Extensions (Intel TDX)
https://cdrdv2.intel.com/v1/dl/getContent/726790
[3] Intel CPU Architectural Extensions Specification
https://www.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-cpu-architectural-specification.pdf
[4] Intel TDX Module 1.0 Specification
https://www.intel.com/content/dam/develop/external/us/en/documents/tdx-module-1.0-public-spec-v0.931.pdf
[5] Intel TDX Loader Interface Specification
https://www.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-seamldr-interface-specification.pdf
[6] Intel TDX Guest-Hypervisor Communication Interface
https://cdrdv2.intel.com/v1/dl/getContent/726790
[7] Intel TDX Virtual Firmware Design Guide
https://www.intel.com/content/dam/develop/external/us/en/documents/tdx-virtual-firmware-design-guide-rev-1.01.pdf
[8] intel public github
kvm TDX branch: https://github.com/intel/tdx/tree/kvm
TDX guest branch: https://github.com/intel/tdx/tree/guest
qemu TDX https://github.com/intel/qemu-tdx
[9] TDVF
https://github.com/tianocore/edk2-staging/tree/TDVF
This was merged into EDK2 main branch. https://github.com/tianocore/edk2Chao Gao (3):
KVM: x86: Movecheck_processor_compatibilityfrom init ops to runtime
ops
Partially revert "KVM: Pass kvm_init()'s opaque param to additional
arch funcs"
KVM: x86: Allow to update cached values inkvm_user_return_msrsw/o
wrmsrIsaku Yamahata (72):
KVM: Refactor CPU compatibility check on module initialiization x86/virt/vmx/tdx: exportplatform_tdx_enabled()
KVM: TDX: Detect CPU feature on kernel module initialization
KVM: x86: Refactor KVM VMX module init/exit functions
KVM: TDX: Add placeholders for TDX VM/vcpu structure x86/virt/tdx: Add a helper function to return system wide info about
TDX module
KVM: TDX: Initialize TDX module when loading kvm_intel.ko
KVM: TDX: Make TDX VM type supported
[MARKER] The start of TDX KVM patch series: TDX architectural
definitions
KVM: TDX: Define TDX architectural definitions
KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module
KVM: TDX: Add helper functions to print TDX SEAMCALL error [MARKER] The start of TDX KVM patch series: TD VM creation/destruction x86/cpu: Add helper functions to allocate/free TDX private host key id
KVM: TDX: Add place holder for TDX VM specificmem_enc_opioctl
KVM: TDX: Makepmu_intel.cignore guest TD case
[MARKER] The start of TDX KVM patch series: TD vcpu
creation/destruction
KVM: TDX: allocate/free TDX vcpu structure
KVM: TDX: allocate/free TDX vcpu structure
[MARKER] The start of TDX KVM patch series: KVM MMU GPA shared bits
KVM: x86/mmu: introduce config for PRIVATE KVM MMU [MARKER] The start of TDX KVM patch series: KVM TDP refactoring for
TDX
KVM: x86/mmu: Disallow fast page fault on private GPA
KVM: VMX: Introduce test mode related to EPT violation VE [MARKER] The start of TDX KVM patch series: KVM TDP MMU hooks
KVM: x86/mmu: Focibly use TDP MMU for TDX
KVM: x86/mmu: Add a private pointer to structkvm_mmu_page
KVM: x86/tdp_mmu: refactorkvm_tdp_mmu_map()
KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU [MARKER] The start of TDX KVM patch series: TDX EPT violation
KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs
KVM: TDX: don't requestKVM_REQ_APIC_PAGE_RELOAD
KVM: TDX: TDP MMU TDX support
[MARKER] The start of TDX KVM patch series: KVM TDP MMU MapGPA
KVM: x86/mmu: steal software usable git to record if GFN is for shared
or not
KVM: x86/tdp_mmu: implement MapGPA hypercall for TDX [MARKER] The start of TDX KVM patch series: TD finalization
KVM: TDX: Create initial guest memory
KVM: TDX: Finalize VM initialization
[MARKER] The start of TDX KVM patch series: TD vcpu enter/exit
KVM: TDX: Add helper assembly function to TDX vcpu
KVM: TDX: Implement TDX vcpu enter/exit path
KVM: TDX:vcpu_run: save/restore host state(host kernel gs)
KVM: TDX: restore host xsave state when exit from the guest TD
KVM: TDX: restore user ret MSRs
[MARKER] The start of TDX KVM patch series: TD vcpu
exits/interrupts/hypercalls
KVM: TDX: complete interrupts after tdexit
KVM: TDX: restore debug store when TD exit
KVM: TDX: handle vcpu migration over logical processor
KVM: x86: Add aswitch_db_regsflag to handle TDX's auto-switched
behavior
KVM: TDX: remove use of structvcpu_vmxfromposted_interrupt.c
KVM: TDX: Implement interrupt injection
KVM: TDX: Implements vcpurequest_immediate_exit
KVM: TDX: Implement methods to inject NMI
KVM: TDX: Add a place holder to handle TDX VM exit
KVM: TDX: handleEXIT_REASON_OTHER_SMI
KVM: TDX: handle ept violation/misconfig exit
KVM: TDX: handleEXCEPTION_NMIandEXTERNAL_INTERRUPT
KVM: TDX: Add a place holder for handler of TDX hypercalls(TDG.VP.VMCALL)KVM: TDX: handle KVM hypercall with TDG.VP.VMCALL
KVM: TDX: Handle TDX PV CPUID hypercall
KVM: TDX: Handle TDX PV HLT hypercall
KVM: TDX: Handle TDX PV port io hypercall
KVM: TDX: Implement callbacks for MSR operations for TDX
KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall
KVM: TDX: Handle TDX PV report fatal error hypercall
KVM: TDX: Handle TDX PVmap_gpahypercall
KVM: TDX: Handle TDG.VP.VMCALL<GetTdVmCallInfo> hypercall
KVM: TDX: Silently discard SMI request
KVM: TDX: Silently ignore INIT/SIPIDocumentation/virtual/kvm: Document on Trust Domain Extensions(TDX)
KVM: x86: design documentation on TDX support of x86 KVM TDP MMURick Edgecombe (1):
KVM: x86/mmu: Add address conversion functions for TDX shared bitsSean Christopherson (25):
KVM: VMX: Move outvmx_x86_opsto 'main.c' to wrap VMX and TDX
KVM: Enable hardware before doing arch VM initialization
KVM: x86: Introducevm_typeto differentiate default VMs from
confidential VMs
KVM: TDX: Add TDX "architectural" error codes
KVM: TDX: Stub intdx.hwith structs, accessors, and VMCS helpers
KVM: TDX: create/destroy VM structure
KVM: TDX: x86: Add ioctl to get TDX systemwide parameters
KVM: TDX: Do TDX specific vcpu initialization
KVM: x86/mmu: Explicitly check for MMIO spte in fast page fault
KVM: x86/mmu: Allow non-zero value for non-present SPTE
KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis
KVM: x86/mmu: Allow per-VM override of the TDP max page level
KVM: x86/mmu: Zap only leaf SPTEs for deleted/moved memslot for
private mmu
KVM: x86/mmu: Disallow dirty logging for x86 TDX
KVM: VMX: Split out guts of EPT violation to common/exposed function
KVM: VMX: Move setting of EPT MMU masks to common VT-x code
KVM: TDX: Addload_mmu_pgdmethod for TDX
KVM: x86/mmu: Introducekvm_mmu_map_tdp_page()for use by TDX
KVM: TDX: Add support for find pending IRQ in a protected local APIC
KVM: x86: Assume timer IRQ was injected if APIC state is proteced
KVM: VMX: Modify NMI and INTR handlers to takeintr_infoas function
argument
KVM: VMX: Move NMI/exception handler to common helper
KVM: x86: Split core of hypercall emulation to helper function
KVM: TDX: Handle TDX PV MMIO hypercall
KVM: TDX: Add methods to ignore accesses to CPU stateXiaoyao Li (1):
KVM: TDX: initialize VM with TDX specific parametersDocumentation/virt/kvm/api.rst | 30 +- .../virt/kvm/intel-tdx-layer-status.rst | 33 + Documentation/virt/kvm/intel-tdx.rst | 381 +++ Documentation/virt/kvm/tdx-tdp-mmu.rst | 466 ++++ arch/arm64/kvm/arm.c | 2 +- arch/mips/kvm/mips.c | 14 +- arch/powerpc/kvm/powerpc.c | 2 +- arch/riscv/kvm/main.c | 2 +- arch/s390/kvm/kvm-s390.c | 2 +- arch/x86/events/intel/ds.c | 1 + arch/x86/include/asm/kvm-x86-ops.h | 10 + arch/x86/include/asm/kvm_host.h | 56 +- arch/x86/include/asm/tdx.h | 67 + arch/x86/include/asm/vmx.h | 14 + arch/x86/include/uapi/asm/kvm.h | 95 + arch/x86/include/uapi/asm/vmx.h | 5 +- arch/x86/kvm/Kconfig | 4 + arch/x86/kvm/Makefile | 3 +- arch/x86/kvm/irq.c | 3 + arch/x86/kvm/lapic.c | 37 +- arch/x86/kvm/lapic.h | 2 + arch/x86/kvm/mmu.h | 42 +- arch/x86/kvm/mmu/mmu.c | 360 ++- arch/x86/kvm/mmu/mmu_internal.h | 123 +- arch/x86/kvm/mmu/paging_tmpl.h | 5 +- arch/x86/kvm/mmu/spte.c | 46 +- arch/x86/kvm/mmu/spte.h | 65 +- arch/x86/kvm/mmu/tdp_iter.c | 1 + arch/x86/kvm/mmu/tdp_iter.h | 5 +- arch/x86/kvm/mmu/tdp_mmu.c | 690 ++++- arch/x86/kvm/mmu/tdp_mmu.h | 12 +- arch/x86/kvm/svm/svm.c | 13 +- arch/x86/kvm/vmx/common.h | 174 ++ arch/x86/kvm/vmx/evmcs.c | 2 +- arch/x86/kvm/vmx/evmcs.h | 2 +- arch/x86/kvm/vmx/main.c | 1071 +++++++ arch/x86/kvm/vmx/pmu_intel.c | 39 +- arch/x86/kvm/vmx/pmu_intel.h | 28 + arch/x86/kvm/vmx/posted_intr.c | 43 +- arch/x86/kvm/vmx/posted_intr.h | 13 + arch/x86/kvm/vmx/tdx.c | 2465 +++++++++++++++++ arch/x86/kvm/vmx/tdx.h | 275 ++ arch/x86/kvm/vmx/tdx_arch.h | 157 ++ arch/x86/kvm/vmx/tdx_errno.h | 29 + arch/x86/kvm/vmx/tdx_error.c | 22 + arch/x86/kvm/vmx/tdx_ops.h | 188 ++ arch/x86/kvm/vmx/vmenter.S | 146 + arch/x86/kvm/vmx/vmx.c | 737 ++--- arch/x86/kvm/vmx/vmx.h | 39 +- arch/x86/kvm/vmx/x86_ops.h | 235 ++ arch/x86/kvm/x86.c | 148 +- arch/x86/virt/vmx/tdx/seamcall.S | 2 + arch/x86/virt/vmx/tdx/tdx.c | 54 +- arch/x86/virt/vmx/tdx/tdx.h | 52 - include/linux/kvm_host.h | 4 +- include/uapi/linux/kvm.h | 2 + tools/arch/x86/include/uapi/asm/kvm.h | 95 + tools/include/uapi/linux/kvm.h | 1 + virt/kvm/kvm_main.c | 67 +- 59 files changed, 7877 insertions(+), 804 deletions(-) create mode 100644 Documentation/virt/kvm/intel-tdx-layer-status.rst create mode 100644 Documentation/virt/kvm/intel-tdx.rst create mode 100644 Documentation/virt/kvm/tdx-tdp-mmu.rst create mode 100644 arch/x86/kvm/vmx/common.h create mode 100644 arch/x86/kvm/vmx/main.c create mode 100644 arch/x86/kvm/vmx/pmu_intel.h create mode 100644 arch/x86/kvm/vmx/tdx.c create mode 100644 arch/x86/kvm/vmx/tdx.h create mode 100644 arch/x86/kvm/vmx/tdx_arch.h create mode 100644 arch/x86/kvm/vmx/tdx_errno.h create mode 100644 arch/x86/kvm/vmx/tdx_error.c create mode 100644 arch/x86/kvm/vmx/tdx_ops.h create mode 100644 arch/x86/kvm/vmx/x86_ops.hSignature · 1 line
2.25.1Signature · 1 line
Isaku Yamahata <[email protected]>
Signature · 1 line
Isaku Yamahata <[email protected]>
Sean Christopherson
maintainerQuoted 12 lines · On Mon, Jun 27, 2022, [email protected] wrote:
From: Isaku Yamahata <[email protected]>
KVM TDX basic feature support
Hello. This is v7 the patch series vof KVM TDX support.
This is based on v5.19-rc1 + kvm/queue branch + TDX HOST patch series. The tree can be found at https://github.com/intel/tdx/tree/kvm-upstream
How to run/test: It's describe at https://github.com/intel/tdx/wiki/TDX-KVMMajor changes from v6:
- rebased to v5.19 base
Quoted 7 lines
TODO:
- integrate fd-based guest memory. As the discussion is still on-going, I intentionally dropped fd-based guest memory support yet. The integration can be found at https://github.com/intel/tdx/tree/kvm-upstream-workaround.
- 2M large page support. It's work-in-progress.
For large page support, there are several design choices. Here is the design options. Any thoughts/feedback?
Apologies, I didn't read beyond the intro paragraph. In case something like this comes up again, it's probably best to send a standalone email tagged RFC, I doubt I'm the only one that missed this embedded RFC.
Quoted 1 line
KVM MMU Large page support for TDX
...
Quoted 43 lines
* options to track private or shared
At each page size (4KB, 2MB, and 1GB), track private, shared, or mixed (2MB and 1GB case). For 4KB each page, 1 bit per page is needed. private or shared. For large pages (2MB and 1GB), 2 bits per large page is needed. (private, shared, or mixed). When resolving KVM page fault, we don't want to check the lower-size pages to check if the given GPA can be a large for performance. On MapGPA check it instead.Option A). enhance
kvm_arch_memory_slot
enumkvm_page_type{
KVM_PAGE_TYPE_INVALID,
KVM_PAGE_TYPE_SHARED,
KVM_PAGE_TYPE_PRIVATE,
KVM_PAGE_TYPE_MIXED,
};struct kvm_page_attr { enum kvm_page_type type; };struct
kvm_arch_memory_slot{
+ structkvm_page_attr*page_attr[KVM_NR_PAGE_SIZES];Option B). steal one more bit
SPTE_MIXED_MASKin addition toSPTE_SHARED_MASKIf !SPTE_MIXED_MASK, it can be large page.Option C). use
SPTE_SHARED_MASKandkvm_mmu_page::mixedbitmapkvm_mmu_page::mixedbitmap of 1GB, root indicates mixed for 2MB, 1GB.* comparison
A).
+ straightforward to implement
+SPTE_SHARED_MASKisn't needed
- memory overhead compared to B). or C).
- more memory reference on KVM page faultB).
+ simpler than C) (complex than A)?)
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- Waste precious SPTE bits.
Quoted 5 lines
C).
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- complicates MapGPA
- scattered data structure
Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.
+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM series
I believe xa_for_each_range() can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain that xa_for_each_range() works the way I think it does.
Quoted 21 lines · Sean Christopherson
Quoted 12 lines · On Mon, Jun 27, 2022, [email protected] wrote:
From: Isaku Yamahata <[email protected]>
KVM TDX basic feature support
Hello. This is v7 the patch series vof KVM TDX support.
This is based on v5.19-rc1 + kvm/queue branch + TDX HOST patch series. The tree can be found at https://github.com/intel/tdx/tree/kvm-upstream
How to run/test: It's describe at https://github.com/intel/tdx/wiki/TDX-KVMMajor changes from v6:
- rebased to v5.19 baseQuoted 7 lines
TODO:
- integrate fd-based guest memory. As the discussion is still on-going, I intentionally dropped fd-based guest memory support yet. The integration can be found at https://github.com/intel/tdx/tree/kvm-upstream-workaround.
- 2M large page support. It's work-in-progress.
For large page support, there are several design choices. Here is the design options. Any thoughts/feedback?
Quoted 33 lines
Apologies, I didn't read beyond the intro paragraph. In case something like this comes up again, it's probably best to send a standalone email tagged RFC, I doubt I'm the only one that missed this embedded RFC.
Quoted 1 line
KVM MMU Large page support for TDX
...
Quoted 25 lines
* options to track private or shared
At each page size (4KB, 2MB, and 1GB), track private, shared, or mixed (2MB and 1GB case). For 4KB each page, 1 bit per page is needed. private or shared. For large pages (2MB and 1GB), 2 bits per large page is needed. (private, shared, or mixed). When resolving KVM page fault, we don't want to check the lower-size pages to check if the given GPA can be a large for performance. On MapGPA check it instead.Option A). enhance
kvm_arch_memory_slot
enumkvm_page_type{
KVM_PAGE_TYPE_INVALID,
KVM_PAGE_TYPE_SHARED,
KVM_PAGE_TYPE_PRIVATE,
KVM_PAGE_TYPE_MIXED,
};struct kvm_page_attr { enum kvm_page_type type; };struct
kvm_arch_memory_slot{
+ structkvm_page_attr*page_attr[KVM_NR_PAGE_SIZES];Option B). steal one more bit
SPTE_MIXED_MASKin addition toSPTE_SHARED_MASKIf !SPTE_MIXED_MASK, it can be large page.
I don't think this is a good option, since it requires all the mappings exist all the time both in shared spte tree and private spte tree.
Quoted 17 lines
Quoted 17 lines
Option C). use
SPTE_SHARED_MASKandkvm_mmu_page::mixedbitmapkvm_mmu_page::mixedbitmap of 1GB, root indicates mixed for 2MB, 1GB.* comparison
A).
+ straightforward to implement
+SPTE_SHARED_MASKisn't needed
- memory overhead compared to B). or C).
- more memory reference on KVM page faultB).
+ simpler than C) (complex than A)?)
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- Waste precious SPTE bits.
Quoted 8 lines
Quoted 5 lines
C).
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- complicates MapGPA
- scattered data structureOption D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.
UPM v7[1] introduces "struct xarray mem_attr_array" to track the shared/private attr of a range.
So in kvm_vm_ioctl_set_encrypted_region() it needs to
- increase the lpage_info counter when a 2m/1g range changed from identical to mixed, and
- decrease the counter when mixed -> identical
[1]: https://lore.kernel.org/all/[email protected]/
Quoted 9 lines
+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM seriesI believe
xa_for_each_range()can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain thatxa_for_each_range()works the way I think it does.
On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...
Quoted 4 lines
Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.
Quoted 8 lines
+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM seriesI believe
xa_for_each_range()can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain thatxa_for_each_range()works the way I think it does.
Hi Sean,
Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259
Everything sounds good, the only trick bit is inc/dec disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.
Any feedback is welcome.
Thanks,
Chao
-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memory
Update lpage_info when handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.
Reserve a bit in disallow_lpage to indicate a large page has private/share pages mixed.
--- arch/x86/include/asm/kvm_host.h | 8 +++ arch/x86/kvm/mmu/mmu.c | 120 +++++++++++++++++++++++++++++++- include/linux/kvm_host.h | 14 ++++ virt/kvm/kvm_main.c | 12 +++- 4 files changed, 150 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +8 -0
@@ -38,6 +38,7 @@#define __KVM_HAVE_ARCH_VCPU_DEBUGFS#define __KVM_HAVE_ZAP_GFN_RANGE +#define __KVM_HAVE_ARCH_UPDATE_MEM_ATTR#define KVM_MAX_VCPUS 1024
@@ -935,6 +936,13 @@ struct kvm_vcpu_arch {#endif }; +/* +* Use a bit in disallow_lpage to indicate private/shared pages mixed at the +* level. The remaining bits will be used as a reference count for other users. +*/ +#define KVM_LPAGE_PRIVATE_SHARED_MIXED (1U << 31) +#define KVM_LPAGE_COUNT_MAX ((1U << 31) - 1) +struct kvm_lpage_info {int disallow_lpage; };
arch/x86/kvm/mmu/mmu.c +119 -1
133 lines not on this page · raw message
include/linux/kvm_host.h +14 -0
@@ -2282,6 +2282,10 @@ static inline void kvm_handle_signal_exit(struct kvm_vcpu *vcpu)#define KVM_DIRTY_RING_MAX_ENTRIES 65536#ifdef CONFIG_HAVE_KVM_PRIVATE_MEM + +#define KVM_MEM_ATTR_SHARED 0x0001 +#define KVM_MEM_ATTR_PRIVATE 0x0002 +static inline int kvm_private_mem_get_pfn (struct kvm_memory_slot *slot,gfn_t gfn,kvm_pfn_t *pfn,int *order) {
@@ -2307,6 +2311,16 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return !!xa_load (&kvm->mem_attr_array, gfn); } +#ifdef __KVM_HAVE_ARCH_UPDATE_MEM_ATTR +void kvm_arch_update_mem_attr (struct kvm *kvm,unsigned int attr, +gfn_t start,gfn_t end); +#else +static inline void kvm_arch_update_mem_attr (struct kvm *kvm,unsigned int attr, +gfn_t start,gfn_t end) +{ +} +#endif +#endif /* CONFIG_HAVE_KVM_PRIVATE_MEM */ #endif
virt/kvm/kvm_main.c +9 -3
@@ -863,12 +863,12 @@ static int kvm_init_mmu_notifier(struct kvm *kvm)#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */ #ifdef CONFIG_HAVE_KVM_PRIVATE_MEM -#define KVM_MEM_ATTR_PRIVATE 0x0001static int kvm_vm_ioctl_set_encrypted_region (struct kvm *kvm,unsigned int ioctl,struct kvm_enc_region *region) {unsigned long start, end;void *entry; +int attr;int r;if (region->size ==0 || region->addr + region->size < region->addr)
@@ -879,13 +879,19 @@ static int kvm_vm_ioctl_set_encrypted_region(struct kvm *kvm, unsigned int ioctl start = region->addr >>PAGE_SHIFT ; end = (region->addr + region->size -1 ) >>PAGE_SHIFT ; - entry = ioctl ==KVM_MEMORY_ENCRYPT_REG_REGION ? -xa_mk_value (KVM_MEM_ATTR_PRIVATE ) :NULL ; +if (ioctl ==KVM_MEMORY_ENCRYPT_REG_REGION ) { + attr =KVM_MEM_ATTR_PRIVATE ; + entry =xa_mk_value (KVM_MEM_ATTR_PRIVATE ); + }else { + attr =KVM_MEM_ATTR_SHARED ; + entry =NULL ; + } r =xa_err (xa_store_range (&kvm->mem_attr_array, start, end, entry,GFP_KERNEL_ACCOUNT ));kvm_zap_gfn_range (kvm, start, end +1 ); +kvm_arch_update_mem_attr (kvm, attr, start, end +1 );return r; }
Signature · 1 line
2
Quoted 62 lines · Chao Peng
On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...Quoted 4 lines
Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.
Quoted 8 lines
+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM seriesI believe
xa_for_each_range()can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain thatxa_for_each_range()works the way I think it does.Hi Sean,
Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259
Everything sounds good, the only trick bit is inc/dec
disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.Any feedback is welcome.
Thanks,
Chao-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memoryUpdate
lpage_infowhen handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.Reserve a bit in
disallow_lpageto indicate a large page has private/share pages mixed.Signed-off-by Chao Peng <[email protected]>---
arch/x86/kvm/mmu/mmu.c +19
-0+static void update_mem_lpage_info (struct kvm *kvm, +struct kvm_memory_slot *slot, +unsigned int attr, +gfn_t start,gfn_t end) +{ +unsigned long lpage_start, lpage_end; +unsigned long gfn, pages, mask; +int level; + +for (level =PG_LEVEL_2M ; level <=KVM_MAX_HUGEPAGE_LEVEL ; level++) { + pages =KVM_PAGES_PER_HPAGE (level); + mask = ~(pages -1 ); + lpage_start = start & mask; + lpage_end = end & mask; + +/* +* We only need to scan the head and tail page, for middle pages +* we know they are not mixed. +*/
arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334
Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10
-0+update_mixed (lpage_info_slot (lpage_start, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_start, + lpage_start + pages)); + +if (lpage_start == lpage_end) +return ; + +for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) { +update_mixed (lpage_info_slot (gfn, slot, level), false); + }
Boundary check missing here for the case when gfn reaches lpage_end.
if (gfn == lpage_end) return;
arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7340
Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +6
-0+ +update_mixed (lpage_info_slot (lpage_end, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_end, + lpage_end + pages)); + } +}
Regards
Nikunj
Quoted 76 lines · Nikunj A. Dadhania
Quoted 62 lines · Chao Peng
On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...Quoted 4 lines
Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.
Quoted 8 lines
+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM seriesI believe
xa_for_each_range()can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain thatxa_for_each_range()works the way I think it does.Hi Sean,
Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259
Everything sounds good, the only trick bit is inc/dec
disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.Any feedback is welcome.
Thanks,
Chao-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memoryUpdate
lpage_infowhen handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.Reserve a bit in
disallow_lpageto indicate a large page has private/share pages mixed.Signed-off-by Chao Peng <[email protected]>---
arch/x86/kvm/mmu/mmu.c +19
-0+static void update_mem_lpage_info (struct kvm *kvm, +struct kvm_memory_slot *slot, +unsigned int attr, +gfn_t start,gfn_t end) +{ +unsigned long lpage_start, lpage_end; +unsigned long gfn, pages, mask; +int level; + +for (level =PG_LEVEL_2M ; level <=KVM_MAX_HUGEPAGE_LEVEL ; level++) { + pages =KVM_PAGES_PER_HPAGE (level); + mask = ~(pages -1 ); + lpage_start = start & mask; + lpage_end = end & mask; + +/* +* We only need to scan the head and tail page, for middle pages +* we know they are not mixed. +*/ arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334
Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10
-0+update_mixed (lpage_info_slot (lpage_start, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_start, + lpage_start + pages)); + +if (lpage_start == lpage_end) +return ; + +for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) { +update_mixed (lpage_info_slot (gfn, slot, level), false); + }Boundary check missing here for the case when gfn reaches
lpage_end.
Quoted 2 lines
if (gfn == lpage_end) return;
In this case, it's actually the tail page that I want to scan for with below code.
It's also possible I misunderstand something here.
Chao
Quoted 10 lines
arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7340
Quoted 7 lines
arch/x86/kvm/mmu/mmu.c +6
-0+ +update_mixed (lpage_info_slot (lpage_end, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_end, + lpage_end + pages)); + } +}Regards
Nikunj
Quoted 77 lines · Chao Peng
Quoted 76 lines · Nikunj A. Dadhania
Quoted 62 lines · Chao Peng
On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...Quoted 4 lines
Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.
Quoted 8 lines
+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM seriesI believe
xa_for_each_range()can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain thatxa_for_each_range()works the way I think it does.Hi Sean,
Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259
Everything sounds good, the only trick bit is inc/dec
disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.Any feedback is welcome.
Thanks,
Chao-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memoryUpdate
lpage_infowhen handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.Reserve a bit in
disallow_lpageto indicate a large page has private/share pages mixed.Signed-off-by Chao Peng <[email protected]>---
arch/x86/kvm/mmu/mmu.c +19
-0+static void update_mem_lpage_info (struct kvm *kvm, +struct kvm_memory_slot *slot, +unsigned int attr, +gfn_t start,gfn_t end) +{ +unsigned long lpage_start, lpage_end; +unsigned long gfn, pages, mask; +int level; + +for (level =PG_LEVEL_2M ; level <=KVM_MAX_HUGEPAGE_LEVEL ; level++) { + pages =KVM_PAGES_PER_HPAGE (level); + mask = ~(pages -1 ); + lpage_start = start & mask; + lpage_end = end & mask; + +/* +* We only need to scan the head and tail page, for middle pages +* we know they are not mixed. +*/ arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334
Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10
-0+update_mixed (lpage_info_slot (lpage_start, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_start, + lpage_start + pages)); + +if (lpage_start == lpage_end) +return ; + +for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) { +update_mixed (lpage_info_slot (gfn, slot, level), false); + }Boundary check missing here for the case when gfn reaches
lpage_end.
Quoted 5 lines
Quoted 2 lines
if (gfn == lpage_end) return;In this case, it's actually the tail page that I want to scan for with below code.
What if you do not have the tail lpage?
For example: memslot base_gfn = 0x1000 and npages is 0x800, so memslot range is 0x1000 to 0x17ff.
Assume a case when this function is called with start = 1000 and end = 1800. For 2M, page mask is 0x1ff. start and end both are 2M aligned.
First update_mixed takes care of 0x1000-0x1200
Loop update_mixed: goes over from 0x1200 - 0x1800, there are no pages left for last update_mixed to process.
Quoted 9 lines
It's also possible I misunderstand something here.
Chao
Quoted 5 lines
arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7338
Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +4
-0+ +update_mixed (lpage_info_slot (lpage_end, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_end, + lpage_end + pages));
lpage_info_slot some times causes a crash, as I noticed that lpage_info_slot() returns out-of-bound index.
Regards
Nikunj
Quoted 89 lines · Nikunj A. Dadhania
Quoted 77 lines · Chao Peng
Quoted 76 lines · Nikunj A. Dadhania
Quoted 62 lines · Chao Peng
On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...Quoted 4 lines
Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.
Quoted 8 lines
+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM seriesI believe
xa_for_each_range()can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain thatxa_for_each_range()works the way I think it does.Hi Sean,
Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259
Everything sounds good, the only trick bit is inc/dec
disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.Any feedback is welcome.
Thanks,
Chao-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memoryUpdate
lpage_infowhen handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.Reserve a bit in
disallow_lpageto indicate a large page has private/share pages mixed.Signed-off-by Chao Peng <[email protected]>---
arch/x86/kvm/mmu/mmu.c +19
-0+static void update_mem_lpage_info (struct kvm *kvm, +struct kvm_memory_slot *slot, +unsigned int attr, +gfn_t start,gfn_t end) +{ +unsigned long lpage_start, lpage_end; +unsigned long gfn, pages, mask; +int level; + +for (level =PG_LEVEL_2M ; level <=KVM_MAX_HUGEPAGE_LEVEL ; level++) { + pages =KVM_PAGES_PER_HPAGE (level); + mask = ~(pages -1 ); + lpage_start = start & mask; + lpage_end = end & mask; + +/* +* We only need to scan the head and tail page, for middle pages +* we know they are not mixed. +*/ arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334
Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10
-0+update_mixed (lpage_info_slot (lpage_start, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_start, + lpage_start + pages)); + +if (lpage_start == lpage_end) +return ; + +for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) { +update_mixed (lpage_info_slot (gfn, slot, level), false); + }Boundary check missing here for the case when gfn reaches
lpage_end.Quoted 5 lines
Quoted 2 lines
if (gfn == lpage_end) return;In this case, it's actually the tail page that I want to scan for with below code.
What if you do not have the tail lpage?
For example: memslot
base_gfn=0x1000and npages is0x800, so memslot range is0x1000to0x17ff.
Quoted 6 lines
Assume a case when this function is called with start = 1000 and end = 1800. For 2M, page mask is
0x1ff. start and end both are 2M aligned.First
update_mixedtakes care of 0x1000-0x1200
Loopupdate_mixed: goes over from0x1200-0x1800, there are no pages left for lastupdate_mixedto process.
Oops, good catch. I would fix it differently by playing with lpage_end:
lpage_end = (end - 1) & mask;
Thanks,
Chao
Quoted 17 lines
Quoted 10 lines
It's also possible I misunderstand something here.
Chao
Quoted 5 lines
arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7338
Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +4
-0+ +update_mixed (lpage_info_slot (lpage_end, slot, level), +mem_attr_is_mixed (kvm, attr, lpage_end, + lpage_end + pages));
lpage_info_slotsome times causes a crash, as I noticed thatlpage_info_slot()returns out-of-bound index.Regards
Nikunj