Skip to contentSkip to conversation

KVM TDX basic feature support

RFC PATCH Applied [email protected] 11 participants 310 messages Mar 4, 2022 – Apr 29, 2022 1 message not in the archive Page 2 of 3

Subsystems (8)
Documentation x86 KVM perf events +4 more subsystems

v5 of 19 Applied Latest is v19 →

lore
Share & tools
lore
maintainer Reviewed-by on v5 1/104
#2 lore raw

Re: [RFC PATCH v5 001/104] KVM: VMX: Move out vmx_x86_ops to 'main.c' to wrap VMX and TDX

In reply to [email protected]
Quoted 73 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

KVM accesses Virtual Machine Control Structure (VMCS) with VMX instructions to operate on VM. TDX defines its data structure and TDX SEAMCALL APIs for VMM to operate on Trust Domain (TD) instead.

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. TDVPS is composed of Trust Domain Virtual Processor Root (TDVPR) which is the root page of TDVPS and Trust Domain Virtual Processor eXtension (TDVPX) pages which extend TDVPR to help provide enough physical space for the logical TDVPS structure.

Also, we have a new structure, Trust Domain Control Structure (TDCS) 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. 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. TDCS is a multi-page logical structure composed of multiple Trust Domain Control Extension (TDCX) physical pages. Trust Domain Root (TDR) is the root control structure of a guest TD and is encrypted using the TDX global private key. It holds a minimal set of state variables that enable guest TD control even during times when the TD's private key is not known, or when the TD's key management state does not permit access to memory encrypted using the TD's private key.

The following shows the relationship between those structures.

         TDR--> TDCS                     per-TD
          |       \--> TDCX
          \
           \--> TDVPS                    per-TD VCPU
                  \--> TDVPR and TDVPX

The existing global struct kvm_x86_ops already defines an interface which fits with TDX. But kvm_x86_ops is system-wide, not per-VM structure. To allow VMX to coexist with TDs, the kvm_x86_ops callbacks will have wrappers "if (tdx) tdx_op() else vmx_op()" to switch VMX or TDX at run time.

To split the runtime switch, the VMX implementation, and the TDX implementation, add main.c, and move out the vmx_x86_ops hooks in preparation for adding TDX, which can coexist with VMX, i.e. KVM can run both VMs and TDs. Use 'vt' for the naming scheme as a nod to VT-x and as a concatenation of VmxTdx.

The current code looks as follows.
In vmx.c
static vmx_op() { ... }

   static struct kvm_x86_ops vmx_x86_ops = {
         .op = vmx_op,

initialization code

The eventually converted code will look like
In vmx.c, keep the VMX operations.
vmx_op() { ... }
VMX initialization
In tdx.c, define the TDX operations.
tdx_op() { ... }
TDX initialization
In x86_ops.h, declare the VMX and TDX operations.

   vmx_op();
   tdx_op();
In main.c, define common wrappers for VMX and VMX.
   static vt_ops() { if (tdx) tdx_ops() else vmx_ops() }
   static struct kvm_x86_ops vt_x86_ops = {
         .op = vt_op,

initialization to call VMX and TDX initialization

Quoted 7 lines

Opportunistically, fix the name inconsistency from vmx_create_vcpu() and vmx_free_vcpu() to vmx_vcpu_create() and vxm_vcpu_free().

Quoted 1,305 lines
---
  arch/x86/kvm/Makefile      |   2 +-
  arch/x86/kvm/vmx/main.c    | 154 ++++++++++++++++
  arch/x86/kvm/vmx/vmx.c     | 360 +++++++++++--------------------------
  arch/x86/kvm/vmx/x86_ops.h | 126 +++++++++++++
  4 files changed, 385 insertions(+), 257 deletions(-)

create mode 100644 arch/x86/kvm/vmx/main.c
create mode 100644 arch/x86/kvm/vmx/x86_ops.h

arch/x86/kvm/Makefile +1 -1
index 30f244b64523..ee4d0999f20f 100644
@@ -22,7 +22,7 @@ kvm-$(CONFIG_X86_64) += mmu/tdp_iter.o mmu/tdp_mmu.o
  kvm-$(CONFIG_KVM_XEN)	+= xen.o
 
  kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
-			   vmx/evmcs.o vmx/nested.o vmx/posted_intr.o
+			   vmx/evmcs.o vmx/nested.o vmx/posted_intr.o vmx/main.o
  kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
 
  kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o svm/sev.o
arch/x86/kvm/vmx/main.c new file +154 -0
new file mode 100644
index 000000000000..b08ea9c42a11
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/moduleparam.h>
+
+#include "x86_ops.h"
+#include "vmx.h"
+#include "nested.h"
+#include "pmu.h"
+
+struct kvm_x86_ops vt_x86_ops __initdata = {
+	.name = "kvm_intel",
+
+	.hardware_unsetup = vmx_hardware_unsetup,
+
+	.hardware_enable = vmx_hardware_enable,
+	.hardware_disable = vmx_hardware_disable,
+	.cpu_has_accelerated_tpr = report_flexpriority,
+	.has_emulated_msr = vmx_has_emulated_msr,
+
+	.vm_size = sizeof(struct kvm_vmx),
+	.vm_init = vmx_vm_init,
+
+	.vcpu_create = vmx_vcpu_create,
+	.vcpu_free = vmx_vcpu_free,
+	.vcpu_reset = vmx_vcpu_reset,
+
+	.prepare_guest_switch = vmx_prepare_switch_to_guest,
+	.vcpu_load = vmx_vcpu_load,
+	.vcpu_put = vmx_vcpu_put,
+
+	.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_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,
+	.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,
+
+	.tlb_flush_all = vmx_flush_tlb_all,
+	.tlb_flush_current = vmx_flush_tlb_current,
+	.tlb_flush_gva = vmx_flush_tlb_gva,
+	.tlb_flush_guest = vmx_flush_tlb_guest,
+
+	.vcpu_pre_run = vmx_vcpu_pre_run,
+	.run = vmx_vcpu_run,
+	.handle_exit = vmx_handle_exit,
+	.skip_emulated_instruction = vmx_skip_emulated_instruction,
+	.update_emulated_instruction = vmx_update_emulated_instruction,
+	.set_interrupt_shadow = vmx_set_interrupt_shadow,
+	.get_interrupt_shadow = vmx_get_interrupt_shadow,
+	.patch_hypercall = vmx_patch_hypercall,
+	.set_irq = vmx_inject_irq,
+	.set_nmi = vmx_inject_nmi,
+	.queue_exception = vmx_queue_exception,
+	.cancel_injection = vmx_cancel_injection,
+	.interrupt_allowed = vmx_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,
+	.enable_irq_window = vmx_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,
+	.apicv_post_state_restore = vmx_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,
+	.sync_pir_to_irr = vmx_sync_pir_to_irr,
+	.deliver_interrupt = vmx_deliver_interrupt,
+	.dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
+
+	.set_tss_addr = vmx_set_tss_addr,
+	.set_identity_map_addr = vmx_set_identity_map_addr,
+	.get_mt_mask = vmx_get_mt_mask,
+
+	.get_exit_info = vmx_get_exit_info,
+
+	.vcpu_after_set_cpuid = vmx_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,
+
+	.load_mmu_pgd = vmx_load_mmu_pgd,
+
+	.check_intercept = vmx_check_intercept,
+	.handle_exit_irqoff = vmx_handle_exit_irqoff,
+
+	.request_immediate_exit = vmx_request_immediate_exit,
+
+	.sched_in = vmx_sched_in,
+
+	.cpu_dirty_log_size = PML_ENTITY_NUM,
+	.update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
+
+	.pmu_ops = &intel_pmu_ops,
+	.nested_ops = &vmx_nested_ops,
+
+	.update_pi_irte = pi_update_irte,
+	.start_assignment = vmx_pi_start_assignment,
+
+#ifdef CONFIG_X86_64
+	.set_hv_timer = vmx_set_hv_timer,
+	.cancel_hv_timer = vmx_cancel_hv_timer,
+#endif
+
+	.setup_mce = vmx_setup_mce,
+
+	.smi_allowed = vmx_smi_allowed,
+	.enter_smm = vmx_enter_smm,
+	.leave_smm = vmx_leave_smm,
+	.enable_smi_window = vmx_enable_smi_window,
+
+	.can_emulate_instruction = vmx_can_emulate_instruction,
+	.apic_init_signal_blocked = vmx_apic_init_signal_blocked,
+	.migrate_timers = vmx_migrate_timers,
+
+	.msr_filter_changed = vmx_msr_filter_changed,
+	.complete_emulated_msr = kvm_complete_insn_gp,
+
+	.vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
+};
+
+struct kvm_x86_init_ops vt_init_ops __initdata = {
+	.cpu_has_kvm_support = vmx_cpu_has_kvm_support,
+	.disabled_by_bios = vmx_disabled_by_bios,
+	.check_processor_compatibility = vmx_check_processor_compat,
+	.hardware_setup = vmx_hardware_setup,
+	.handle_intel_pt_intr = NULL,
+
+	.runtime_ops = &vt_x86_ops,
+};
arch/x86/kvm/vmx/vmx.c +104 -256
index efda5e4d6247..f6f5d0dac579 100644
@@ -66,6 +66,7 @@
  #include "vmcs12.h"
  #include "vmx.h"
  #include "x86.h"
+#include "x86_ops.h"
 
  MODULE_AUTHOR("Qumranet");
  MODULE_LICENSE("GPL");
@@ -541,7 +542,7 @@ static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
  	return flexpriority_enabled && lapic_in_kernel(vcpu);
  }
 
-static inline bool report_flexpriority(void)
+bool report_flexpriority(void)
  {
  	return flexpriority_enabled;
  }
@@ -1316,7 +1317,7 @@ void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
   * Switches to specified vcpu, until a matching vcpu_put(), but assumes
   * vcpu mutex is already taken.
   */
-static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
+void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -1327,7 +1328,7 @@ static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  	vmx->host_debugctlmsr = get_debugctlmsr();
  }
 
-static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
+void vmx_vcpu_put(struct kvm_vcpu *vcpu)
  {
  	vmx_vcpu_pi_put(vcpu);
 
@@ -1381,7 +1382,7 @@ void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  		vmx->emulation_required = vmx_emulation_required(vcpu);
  }
 
-static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
+bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
  {
  	return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
  }
@@ -1487,8 +1488,8 @@ static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
  	return 0;
  }
 
-static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
-					void *insn, int insn_len)
+bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
+				void *insn, int insn_len)
  {
  	/*
  	 * Emulation of instructions in SGX enclaves is impossible as RIP does
@@ -1572,7 +1573,7 @@ static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
   * Recognizes a pending MTF VM-exit and records the nested state for later
   * delivery.
   */
-static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
+void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
  {
  	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
@@ -1595,7 +1596,7 @@ static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
  		vmx->nested.mtf_pending = false;
  }
 
-static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
+int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
  {
  	vmx_update_emulated_instruction(vcpu);
  	return skip_emulated_instruction(vcpu);
@@ -1614,7 +1615,7 @@ static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
  		vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
  }
 
-static void vmx_queue_exception(struct kvm_vcpu *vcpu)
+void vmx_queue_exception(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	unsigned nr = vcpu->arch.exception.nr;
@@ -1727,12 +1728,12 @@ u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
  	return kvm_default_tsc_scaling_ratio;
  }
 
-static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
+void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
  {
  	vmcs_write64(TSC_OFFSET, offset);
  }
 
-static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
+void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
  {
  	vmcs_write64(TSC_MULTIPLIER, multiplier);
  }
@@ -1756,7 +1757,7 @@ static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
  	return !(val & ~valid_bits);
  }
 
-static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
+int vmx_get_msr_feature(struct kvm_msr_entry *msr)
  {
  	switch (msr->index) {
  	case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
@@ -1776,7 +1777,7 @@ static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
   * Returns 0 on success, non-0 otherwise.
   * Assumes vcpu_load() was already called.
   */
-static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
+int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	struct vmx_uret_msr *msr;
@@ -1954,7 +1955,7 @@ static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
   * Returns 0 on success, non-0 otherwise.
   * Assumes vcpu_load() was already called.
   */
-static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
+int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	struct vmx_uret_msr *msr;
@@ -2267,7 +2268,7 @@ static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  	return ret;
  }
 
-static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
+void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
  {
  	unsigned long guest_owned_bits;
 
@@ -2310,12 +2311,12 @@ static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
  	}
  }
 
-static __init int cpu_has_kvm_support(void)
+__init int vmx_cpu_has_kvm_support(void)
  {
  	return cpu_has_vmx();
  }
 
-static __init int vmx_disabled_by_bios(void)
+__init int vmx_disabled_by_bios(void)
  {
  	return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
  	       !boot_cpu_has(X86_FEATURE_VMX);
@@ -2341,7 +2342,7 @@ static int kvm_cpu_vmxon(u64 vmxon_pointer)
  	return -EFAULT;
  }
 
-static int hardware_enable(void)
+int vmx_hardware_enable(void)
  {
  	int cpu = raw_smp_processor_id();
  	u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
@@ -2382,7 +2383,7 @@ static void vmclear_local_loaded_vmcss(void)
  		__loaded_vmcs_clear(v);
  }
 
-static void hardware_disable(void)
+void vmx_hardware_disable(void)
  {
  	vmclear_local_loaded_vmcss();
 
@@ -2924,7 +2925,7 @@ static void exit_lmode(struct kvm_vcpu *vcpu)
 
  #endif
 
-static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
+void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -2954,7 +2955,7 @@ static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
  	return to_vmx(vcpu)->vpid;
  }
 
-static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
+void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
  {
  	struct kvm_mmu *mmu = vcpu->arch.mmu;
  	u64 root_hpa = mmu->root_hpa;
@@ -2970,7 +2971,7 @@ static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
  		vpid_sync_context(vmx_get_current_vpid(vcpu));
  }
 
-static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
+void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
  {
  	/*
  	 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
@@ -2979,7 +2980,7 @@ static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
  	vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
  }
 
-static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
+void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
  {
  	/*
  	 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
@@ -3134,8 +3135,7 @@ u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
  	return eptp;
  }
 
-static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
-			     int root_level)
+void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
  {
  	struct kvm *kvm = vcpu->kvm;
  	bool update_guest_cr3 = true;
@@ -3163,8 +3163,7 @@ static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
  		vmcs_writel(GUEST_CR3, guest_cr3);
  }
 
-
-static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
+bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  {
  	/*
  	 * We operate under the default treatment of SMM, so VMX cannot be
@@ -3280,7 +3279,7 @@ void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
  	var->g = (ar >> 15) & 1;
  }
 
-static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
+u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
  {
  	struct kvm_segment s;
 
@@ -3360,14 +3359,14 @@ void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
  	vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
  }
 
-static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
+void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
  {
  	__vmx_set_segment(vcpu, var, seg);
 
  	to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
  }
 
-static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
+void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  {
  	u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
 
@@ -3375,25 +3374,25 @@ static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  	*l = (ar >> 13) & 1;
  }
 
-static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  {
  	dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
  	dt->address = vmcs_readl(GUEST_IDTR_BASE);
  }
 
-static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  {
  	vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
  	vmcs_writel(GUEST_IDTR_BASE, dt->address);
  }
 
-static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  {
  	dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
  	dt->address = vmcs_readl(GUEST_GDTR_BASE);
  }
 
-static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  {
  	vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
  	vmcs_writel(GUEST_GDTR_BASE, dt->address);
@@ -3889,7 +3888,7 @@ void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
  	}
  }
 
-static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
+bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	void *vapic_page;
@@ -3909,7 +3908,7 @@ static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
  	return ((rvi & 0xf0) > (vppr & 0xf0));
  }
 
-static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
+void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	u32 i;
@@ -4041,8 +4040,8 @@ static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
  	return 0;
  }
 
-static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
-				  int trig_mode, int vector)
+void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
+			   int trig_mode, int vector)
  {
  	struct kvm_vcpu *vcpu = apic->vcpu;
 
@@ -4185,7 +4184,7 @@ static u32 vmx_vmexit_ctrl(void)
  		~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
  }
 
-static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
+void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -4508,7 +4507,7 @@ static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
  	vmx->pi_desc.sn = 1;
  }
 
-static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
+void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -4565,12 +4564,12 @@ static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  	vpid_sync_context(vmx->vpid);
  }
 
-static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
+void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
  {
  	exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
  }
 
-static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
+void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
  {
  	if (!enable_vnmi ||
  	    vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
@@ -4581,7 +4580,7 @@ static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
  	exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
  }
 
-static void vmx_inject_irq(struct kvm_vcpu *vcpu)
+void vmx_inject_irq(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	uint32_t intr;
@@ -4609,7 +4608,7 @@ static void vmx_inject_irq(struct kvm_vcpu *vcpu)
  	vmx_clear_hlt(vcpu);
  }
 
-static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
+void vmx_inject_nmi(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -4687,7 +4686,7 @@ bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
  		 GUEST_INTR_STATE_NMI));
  }
 
-static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
+int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  {
  	if (to_vmx(vcpu)->nested.nested_run_pending)
  		return -EBUSY;
@@ -4709,7 +4708,7 @@ bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
  		(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
  }
 
-static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
+int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  {
  	if (to_vmx(vcpu)->nested.nested_run_pending)
  		return -EBUSY;
@@ -4724,7 +4723,7 @@ static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  	return !vmx_interrupt_blocked(vcpu);
  }
 
-static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
+int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
  {
  	void __user *ret;
 
@@ -4744,7 +4743,7 @@ static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
  	return init_rmode_tss(kvm, ret);
  }
 
-static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
+int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
  {
  	to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
  	return 0;
@@ -5023,8 +5022,7 @@ static int handle_io(struct kvm_vcpu *vcpu)
  	return kvm_fast_pio(vcpu, size, port, in);
  }
 
-static void
-vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
+void vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
  {
  	/*
  	 * Patch in the VMCALL instruction:
@@ -5234,7 +5232,7 @@ static int handle_dr(struct kvm_vcpu *vcpu)
  	return kvm_complete_insn_gp(vcpu, err);
  }
 
-static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
+void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
  {
  	get_debugreg(vcpu->arch.db[0], 0);
  	get_debugreg(vcpu->arch.db[1], 1);
@@ -5253,7 +5251,7 @@ static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
  	set_debugreg(DR6_RESERVED, 6);
  }
 
-static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
+void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
  {
  	vmcs_writel(GUEST_DR7, val);
  }
@@ -5519,7 +5517,7 @@ static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
  	return 1;
  }
 
-static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
+int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
  {
  	if (vmx_emulation_required_with_pending_exception(vcpu)) {
  		kvm_prepare_emulation_failure_exit(vcpu);
@@ -5756,9 +5754,8 @@ static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
  static const int kvm_vmx_max_exit_handlers =
  	ARRAY_SIZE(kvm_vmx_exit_handlers);
 
-static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
-			      u64 *info1, u64 *info2,
-			      u32 *intr_info, u32 *error_code)
+void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
+		u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -6191,7 +6188,7 @@ static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
  	return 0;
  }
 
-static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
+int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
  {
  	int ret = __vmx_handle_exit(vcpu, exit_fastpath);
 
@@ -6279,7 +6276,7 @@ static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
  		: "eax", "ebx", "ecx", "edx");
  }
 
-static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
+void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
  {
  	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  	int tpr_threshold;
@@ -6349,7 +6346,7 @@ void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
  	vmx_update_msr_bitmap_x2apic(vcpu);
  }
 
-static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
+void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
  {
  	struct page *page;
 
@@ -6377,7 +6374,7 @@ static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
  	put_page(page);
  }
 
-static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
+void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
  {
  	u16 status;
  	u8 old;
@@ -6411,7 +6408,7 @@ static void vmx_set_rvi(int vector)
  	}
  }
 
-static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
+void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
  {
  	/*
  	 * When running L2, updating RVI is only relevant when
@@ -6425,7 +6422,7 @@ static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
  		vmx_set_rvi(max_irr);
  }
 
-static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
+int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	int max_irr;
@@ -6471,7 +6468,7 @@ static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
  	return max_irr;
  }
 
-static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
+void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
  {
  	if (!kvm_vcpu_apicv_active(vcpu))
  		return;
@@ -6482,7 +6479,7 @@ static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
  	vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
  }
 
-static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
+void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -6554,7 +6551,7 @@ static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
  	handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
  }
 
-static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
+void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -6571,7 +6568,7 @@ static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
   * 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 vmx_has_emulated_msr(struct kvm *kvm, u32 index)
+bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
  {
  	switch (index) {
  	case MSR_IA32_SMBASE:
@@ -6692,7 +6689,7 @@ static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
  				  IDT_VECTORING_ERROR_CODE);
  }
 
-static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
+void vmx_cancel_injection(struct kvm_vcpu *vcpu)
  {
  	__vmx_complete_interrupts(vcpu,
  				  vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
@@ -6788,7 +6785,7 @@ static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
  	guest_state_exit_irqoff();
  }
 
-static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
+fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	unsigned long cr4;
@@ -6969,7 +6966,7 @@ static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
  	return vmx_exit_handlers_fastpath(vcpu);
  }
 
-static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
+void vmx_vcpu_free(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -6980,7 +6977,7 @@ static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
  	free_loaded_vmcs(vmx->loaded_vmcs);
  }
 
-static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
+int vmx_vcpu_create(struct kvm_vcpu *vcpu)
  {
  	struct vmx_uret_msr *tsx_ctrl;
  	struct vcpu_vmx *vmx;
@@ -7085,7 +7082,7 @@ static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
  #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
  #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
 
-static int vmx_vm_init(struct kvm *kvm)
+int vmx_vm_init(struct kvm *kvm)
  {
  	if (!ple_gap)
  		kvm->arch.pause_in_guest = true;
@@ -7116,7 +7113,7 @@ static int vmx_vm_init(struct kvm *kvm)
  	return 0;
  }
 
-static int __init vmx_check_processor_compat(void)
+int __init vmx_check_processor_compat(void)
  {
  	struct vmcs_config vmcs_conf;
  	struct vmx_capability vmx_cap;
@@ -7139,7 +7136,7 @@ static int __init vmx_check_processor_compat(void)
  	return 0;
  }
 
-static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
+u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
  {
  	u8 cache;
 
@@ -7328,7 +7325,7 @@ static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
  		vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
  }
 
-static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
+void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -7433,7 +7430,7 @@ static __init void vmx_set_cpu_caps(void)
  		kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
  }
 
-static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
+void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
  {
  	to_vmx(vcpu)->req_immediate_exit = true;
  }
@@ -7472,10 +7469,10 @@ static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
  	return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
  }
 
-static int vmx_check_intercept(struct kvm_vcpu *vcpu,
-			       struct x86_instruction_info *info,
-			       enum x86_intercept_stage stage,
-			       struct x86_exception *exception)
+int vmx_check_intercept(struct kvm_vcpu *vcpu,
+		       struct x86_instruction_info *info,
+		       enum x86_intercept_stage stage,
+		       struct x86_exception *exception)
  {
  	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
 
@@ -7540,8 +7537,8 @@ static inline int u64_shl_div_u64(u64 a, unsigned int shift,
  	return 0;
  }
 
-static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
-			    bool *expired)
+int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
+		bool *expired)
  {
  	struct vcpu_vmx *vmx;
  	u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
@@ -7580,13 +7577,13 @@ static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
  	return 0;
  }
 
-static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
+void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
  {
  	to_vmx(vcpu)->hv_deadline_tsc = -1;
  }
  #endif
 
-static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
+void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
  {
  	if (!kvm_pause_in_guest(vcpu->kvm))
  		shrink_ple_window(vcpu);
@@ -7612,7 +7609,7 @@ void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
  		secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
  }
 
-static void vmx_setup_mce(struct kvm_vcpu *vcpu)
+void vmx_setup_mce(struct kvm_vcpu *vcpu)
  {
  	if (vcpu->arch.mcg_cap & MCG_LMCE_P)
  		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
@@ -7622,7 +7619,7 @@ static void vmx_setup_mce(struct kvm_vcpu *vcpu)
  			~FEAT_CTL_LMCE_ENABLED;
  }
 
-static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
+int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  {
  	/* we need a nested vmexit to enter SMM, postpone if run is pending */
  	if (to_vmx(vcpu)->nested.nested_run_pending)
@@ -7630,7 +7627,7 @@ static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  	return !is_smm(vcpu);
  }
 
-static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
+int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
@@ -7644,7 +7641,7 @@ static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
  	return 0;
  }
 
-static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
+int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
  {
  	struct vcpu_vmx *vmx = to_vmx(vcpu);
  	int ret;
@@ -7665,17 +7662,17 @@ static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
  	return 0;
  }
 
-static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
+void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
  {
  	/* RSM will cause a vmexit anyway.  */
  }
 
-static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
+bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
  {
  	return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
  }
 
-static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
+void vmx_migrate_timers(struct kvm_vcpu *vcpu)
  {
  	if (is_guest_mode(vcpu)) {
  		struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
@@ -7685,7 +7682,7 @@ static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
  	}
  }
 
-static void hardware_unsetup(void)
+void vmx_hardware_unsetup(void)
  {
  	kvm_set_posted_intr_wakeup_handler(NULL);
 
@@ -7695,7 +7692,7 @@ static void hardware_unsetup(void)
  	free_kvm_area();
  }
 
-static bool vmx_check_apicv_inhibit_reasons(ulong bit)
+bool vmx_check_apicv_inhibit_reasons(ulong bit)
  {
  	ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
  			  BIT(APICV_INHIBIT_REASON_ABSENT) |
@@ -7705,143 +7702,6 @@ static bool vmx_check_apicv_inhibit_reasons(ulong bit)
  	return supported & BIT(bit);
  }
 
-static struct kvm_x86_ops vmx_x86_ops __initdata = {
-	.name = "kvm_intel",
-
-	.hardware_unsetup = hardware_unsetup,
-
-	.hardware_enable = hardware_enable,
-	.hardware_disable = hardware_disable,
-	.cpu_has_accelerated_tpr = report_flexpriority,
-	.has_emulated_msr = vmx_has_emulated_msr,
-
-	.vm_size = sizeof(struct kvm_vmx),
-	.vm_init = vmx_vm_init,
-
-	.vcpu_create = vmx_create_vcpu,
-	.vcpu_free = vmx_free_vcpu,
-	.vcpu_reset = vmx_vcpu_reset,
-
-	.prepare_guest_switch = vmx_prepare_switch_to_guest,
-	.vcpu_load = vmx_vcpu_load,
-	.vcpu_put = vmx_vcpu_put,
-
-	.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_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,
-	.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,
-
-	.tlb_flush_all = vmx_flush_tlb_all,
-	.tlb_flush_current = vmx_flush_tlb_current,
-	.tlb_flush_gva = vmx_flush_tlb_gva,
-	.tlb_flush_guest = vmx_flush_tlb_guest,
-
-	.vcpu_pre_run = vmx_vcpu_pre_run,
-	.run = vmx_vcpu_run,
-	.handle_exit = vmx_handle_exit,
-	.skip_emulated_instruction = vmx_skip_emulated_instruction,
-	.update_emulated_instruction = vmx_update_emulated_instruction,
-	.set_interrupt_shadow = vmx_set_interrupt_shadow,
-	.get_interrupt_shadow = vmx_get_interrupt_shadow,
-	.patch_hypercall = vmx_patch_hypercall,
-	.set_irq = vmx_inject_irq,
-	.set_nmi = vmx_inject_nmi,
-	.queue_exception = vmx_queue_exception,
-	.cancel_injection = vmx_cancel_injection,
-	.interrupt_allowed = vmx_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,
-	.enable_irq_window = vmx_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,
-	.apicv_post_state_restore = vmx_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,
-	.sync_pir_to_irr = vmx_sync_pir_to_irr,
-	.deliver_interrupt = vmx_deliver_interrupt,
-	.dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
-
-	.set_tss_addr = vmx_set_tss_addr,
-	.set_identity_map_addr = vmx_set_identity_map_addr,
-	.get_mt_mask = vmx_get_mt_mask,
-
-	.get_exit_info = vmx_get_exit_info,
-
-	.vcpu_after_set_cpuid = vmx_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,
-
-	.load_mmu_pgd = vmx_load_mmu_pgd,
-
-	.check_intercept = vmx_check_intercept,
-	.handle_exit_irqoff = vmx_handle_exit_irqoff,
-
-	.request_immediate_exit = vmx_request_immediate_exit,
-
-	.sched_in = vmx_sched_in,
-
-	.cpu_dirty_log_size = PML_ENTITY_NUM,
-	.update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
-
-	.pmu_ops = &intel_pmu_ops,
-	.nested_ops = &vmx_nested_ops,
-
-	.update_pi_irte = pi_update_irte,
-	.start_assignment = vmx_pi_start_assignment,
-
-#ifdef CONFIG_X86_64
-	.set_hv_timer = vmx_set_hv_timer,
-	.cancel_hv_timer = vmx_cancel_hv_timer,
-#endif
-
-	.setup_mce = vmx_setup_mce,
-
-	.smi_allowed = vmx_smi_allowed,
-	.enter_smm = vmx_enter_smm,
-	.leave_smm = vmx_leave_smm,
-	.enable_smi_window = vmx_enable_smi_window,
-
-	.can_emulate_instruction = vmx_can_emulate_instruction,
-	.apic_init_signal_blocked = vmx_apic_init_signal_blocked,
-	.migrate_timers = vmx_migrate_timers,
-
-	.msr_filter_changed = vmx_msr_filter_changed,
-	.complete_emulated_msr = kvm_complete_insn_gp,
-
-	.vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
-};
-
  static unsigned int vmx_handle_intel_pt_intr(void)
  {
  	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
@@ -7882,9 +7742,7 @@ static __init void vmx_setup_user_return_msrs(void)
  		kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
  }
 
-static struct kvm_x86_init_ops vmx_init_ops __initdata;
-
-static __init int hardware_setup(void)
+__init int vmx_hardware_setup(void)
  {
  	unsigned long host_bndcfgs;
  	struct desc_ptr dt;
@@ -7944,16 +7802,16 @@ static __init int hardware_setup(void)
  	 * using the APIC_ACCESS_ADDR VMCS field.
  	 */
  	if (!flexpriority_enabled)
-		vmx_x86_ops.set_apic_access_page_addr = NULL;
+		vt_x86_ops.set_apic_access_page_addr = NULL;
 
  	if (!cpu_has_vmx_tpr_shadow())
-		vmx_x86_ops.update_cr8_intercept = NULL;
+		vt_x86_ops.update_cr8_intercept = NULL;
 
  #if IS_ENABLED(CONFIG_HYPERV)
  	if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
  	    && enable_ept) {
-		vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
-		vmx_x86_ops.tlb_remote_flush_with_range =
+		vt_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
+		vt_x86_ops.tlb_remote_flush_with_range =
  				hv_remote_flush_tlb_with_range;
  	}
  #endif
@@ -7969,7 +7827,7 @@ static __init int hardware_setup(void)
  	if (!cpu_has_vmx_apicv())
  		enable_apicv = 0;
  	if (!enable_apicv)
-		vmx_x86_ops.sync_pir_to_irr = NULL;
+		vt_x86_ops.sync_pir_to_irr = NULL;
 
  	if (cpu_has_vmx_tsc_scaling()) {
  		kvm_has_tsc_control = true;
@@ -7996,7 +7854,7 @@ static __init int hardware_setup(void)
  		enable_pml = 0;
 
  	if (!enable_pml)
-		vmx_x86_ops.cpu_dirty_log_size = 0;
+		vt_x86_ops.cpu_dirty_log_size = 0;
 
  	if (!cpu_has_vmx_preemption_timer())
  		enable_preemption_timer = false;
@@ -8023,9 +7881,9 @@ static __init int hardware_setup(void)
  	}
 
  	if (!enable_preemption_timer) {
-		vmx_x86_ops.set_hv_timer = NULL;
-		vmx_x86_ops.cancel_hv_timer = NULL;
-		vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
+		vt_x86_ops.set_hv_timer = NULL;
+		vt_x86_ops.cancel_hv_timer = NULL;
+		vt_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
  	}
 
  	kvm_mce_cap_supported |= MCG_LMCE_P;
@@ -8035,9 +7893,9 @@ static __init int hardware_setup(void)
  	if (!enable_ept || !cpu_has_vmx_intel_pt())
  		pt_mode = PT_MODE_SYSTEM;
  	if (pt_mode == PT_MODE_HOST_GUEST)
-		vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
+		vt_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
  	else
-		vmx_init_ops.handle_intel_pt_intr = NULL;
+		vt_init_ops.handle_intel_pt_intr = NULL;
 
  	setup_default_sgx_lepubkeyhash();
 
@@ -8061,16 +7919,6 @@ static __init int hardware_setup(void)
  	return r;
  }
 
-static struct kvm_x86_init_ops vmx_init_ops __initdata = {
-	.cpu_has_kvm_support = cpu_has_kvm_support,
-	.disabled_by_bios = vmx_disabled_by_bios,
-	.check_processor_compatibility = vmx_check_processor_compat,
-	.hardware_setup = hardware_setup,
-	.handle_intel_pt_intr = NULL,
-
-	.runtime_ops = &vmx_x86_ops,
-};
-
  static void vmx_cleanup_l1d_flush(void)
  {
  	if (vmx_l1d_flush_pages) {
@@ -8149,7 +7997,7 @@ static int __init vmx_init(void)
  		}
 
  		if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
-			vmx_x86_ops.enable_direct_tlbflush
+			vt_x86_ops.enable_direct_tlbflush
  				= hv_enable_direct_tlbflush;
 
  	} else {
@@ -8157,8 +8005,8 @@ static int __init vmx_init(void)
  	}
  #endif
 
-	r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
-		     __alignof__(struct vcpu_vmx), THIS_MODULE);
+	r = kvm_init(&vt_init_ops, sizeof(struct vcpu_vmx),
+		__alignof__(struct vcpu_vmx), THIS_MODULE);
  	if (r)
  		return r;
 
arch/x86/kvm/vmx/x86_ops.h new file +126 -0
new file mode 100644
index 000000000000..40c64fb1f505
@@ -0,0 +1,126 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __KVM_X86_VMX_X86_OPS_H
+#define __KVM_X86_VMX_X86_OPS_H
+
+#include <linux/kvm_host.h>
+
+#include <asm/virtext.h>
+
+#include "x86.h"
+
+extern struct kvm_x86_init_ops vt_init_ops __initdata;
+
+__init int vmx_cpu_has_kvm_support(void);
+__init int vmx_disabled_by_bios(void);
+int __init vmx_check_processor_compat(void);
+__init int vmx_hardware_setup(void);
+
+extern struct kvm_x86_ops vt_x86_ops __initdata;
+extern struct kvm_x86_init_ops vt_init_ops __initdata;
+
+void vmx_hardware_unsetup(void);
+int vmx_hardware_enable(void);
+void vmx_hardware_disable(void);
+bool report_flexpriority(void);
+int vmx_vm_init(struct kvm *kvm);
+int vmx_vcpu_create(struct kvm_vcpu *vcpu);
+int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu);
+fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu);
+void vmx_vcpu_free(struct kvm_vcpu *vcpu);
+void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
+void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu);
+void vmx_vcpu_put(struct kvm_vcpu *vcpu);
+int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath);
+void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu);
+int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu);
+void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu);
+int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info);
+int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection);
+int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate);
+int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate);
+void vmx_enable_smi_window(struct kvm_vcpu *vcpu);
+bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
+				void *insn, int insn_len);
+int vmx_check_intercept(struct kvm_vcpu *vcpu,
+			struct x86_instruction_info *info,
+			enum x86_intercept_stage stage,
+			struct x86_exception *exception);
+bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu);
+void vmx_migrate_timers(struct kvm_vcpu *vcpu);
+void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu);
+void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu);
+bool vmx_check_apicv_inhibit_reasons(ulong bit);
+void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr);
+void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr);
+bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu);
+int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu);
+void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
+			   int trig_mode, int vector);
+void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu);
+bool vmx_has_emulated_msr(struct kvm *kvm, u32 index);
+void vmx_msr_filter_changed(struct kvm_vcpu *vcpu);
+void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu);
+void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu);
+int vmx_get_msr_feature(struct kvm_msr_entry *msr);
+int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info);
+u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg);
+void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
+void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
+int vmx_get_cpl(struct kvm_vcpu *vcpu);
+void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l);
+void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
+void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level);
+void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
+bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
+int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer);
+void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt);
+void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt);
+void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt);
+void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt);
+void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val);
+void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu);
+void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg);
+unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu);
+void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
+bool vmx_get_if_flag(struct kvm_vcpu *vcpu);
+void vmx_flush_tlb_all(struct kvm_vcpu *vcpu);
+void vmx_flush_tlb_current(struct kvm_vcpu *vcpu);
+void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr);
+void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu);
+void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask);
+u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu);
+void vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall);
+void vmx_inject_irq(struct kvm_vcpu *vcpu);
+void vmx_inject_nmi(struct kvm_vcpu *vcpu);
+void vmx_queue_exception(struct kvm_vcpu *vcpu);
+void vmx_cancel_injection(struct kvm_vcpu *vcpu);
+int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection);
+int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection);
+bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
+void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
+void vmx_enable_nmi_window(struct kvm_vcpu *vcpu);
+void vmx_enable_irq_window(struct kvm_vcpu *vcpu);
+void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr);
+void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu);
+void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu);
+void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap);
+int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
+int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr);
+u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio);
+void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
+		u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code);
+u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu);
+u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu);
+void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset);
+void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier);
+void vmx_request_immediate_exit(struct kvm_vcpu *vcpu);
+void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu);
+void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu);
+#ifdef CONFIG_X86_64
+int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
+		bool *expired);
+void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu);
+#endif
+void vmx_setup_mce(struct kvm_vcpu *vcpu);
+
+#endif /* __KVM_X86_VMX_X86_OPS_H */
maintainer
#5 lore raw

Re: [RFC PATCH v5 003/104] KVM: TDX: Detect CPU feature on kernel module initialization

In reply to [email protected]
Quoted 95 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX requires several initialization steps for KVM to create guest TDs. Detect CPU feature, enable VMX (TDX is based on VMX), detect TDX module availability, and initialize TDX module. This patch implements the first step to detect CPU feature. Because VMX isn't enabled yet by VMXON instruction on KVM kernel module initialization, defer further initialization step until VMX is enabled by hardware_enable callback.

Introduce a module parameter, enable_tdx, to explicitly enable TDX KVM support. It's off by default to keep same behavior for those who don't use TDX. Implement CPU feature detection at KVM kernel module initialization as hardware_setup callback to check if CPU feature is available and get some CPU parameters.

---
  arch/x86/kvm/Makefile      |  1 +
  arch/x86/kvm/vmx/main.c    | 15 ++++++++++-
  arch/x86/kvm/vmx/tdx.c     | 53 ++++++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/x86_ops.h |  6 +++++
  4 files changed, 74 insertions(+), 1 deletion(-)

create mode 100644 arch/x86/kvm/vmx/tdx.c

arch/x86/kvm/Makefile +1 -0
index ee4d0999f20f..e2c05195cb95 100644
@@ -24,6 +24,7 @@ kvm-$(CONFIG_KVM_XEN)	+= xen.o
  kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
  			   vmx/evmcs.o vmx/nested.o vmx/posted_intr.o vmx/main.o
  kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o
 
  kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o svm/sev.o
 
arch/x86/kvm/vmx/main.c +14 -1
index b08ea9c42a11..b79fcc8d81dd 100644
@@ -6,6 +6,19 @@
  #include "nested.h"
  #include "pmu.h"
 
+static __init int vt_hardware_setup(void)
+{
+	int ret;
+
+	ret = vmx_hardware_setup();
+	if (ret)
+		return ret;
+
+	tdx_hardware_setup(&vt_x86_ops);
+
+	return 0;
+}
+
  struct kvm_x86_ops vt_x86_ops __initdata = {
  	.name = "kvm_intel",
 
@@ -147,7 +160,7 @@ struct kvm_x86_init_ops vt_init_ops __initdata = {
  	.cpu_has_kvm_support = vmx_cpu_has_kvm_support,
  	.disabled_by_bios = vmx_disabled_by_bios,
  	.check_processor_compatibility = vmx_check_processor_compat,
-	.hardware_setup = vmx_hardware_setup,
+	.hardware_setup = vt_hardware_setup,
  	.handle_intel_pt_intr = NULL,
 
  	.runtime_ops = &vt_x86_ops,
arch/x86/kvm/vmx/tdx.c new file +20 -0
new file mode 100644
index 000000000000..1acf08c310c4
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/cpu.h>
+
+#include <asm/tdx.h>
+
+#include "capabilities.h"
+#include "x86_ops.h"
+
+#undef pr_fmt
+#define pr_fmt(fmt) "tdx: " fmt
+
+static bool __read_mostly enable_tdx = true;
+module_param_named(tdx, enable_tdx, bool, 0644);
+
+static u64 hkid_mask __ro_after_init;
+static u8 hkid_start_pos __ro_after_init;
+
+static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	u32 max_pa;

arch/x86/kvm/vmx/tdx.c line 30

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	if (!platform_has_tdx()) {
+		pr_warn("Cannot enable TDX with SEAMRR disabled\n");
+		return -ENODEV;
+	}

This will cause a pr_warn in the logs on all machines that don't have TDX. Perhaps you can restrict the pr_warn() to machines that have __seamrr_enabled() == true?

Paolo

Quoted 37 lines
arch/x86/kvm/vmx/tdx.c new file +22 -0
+	if (WARN_ON_ONCE(x86_ops->tlb_remote_flush))
+		return -EIO;
+
+	max_pa = cpuid_eax(0x80000008) & 0xff;
+	hkid_start_pos = boot_cpu_data.x86_phys_bits;
+	hkid_mask = GENMASK_ULL(max_pa - 1, hkid_start_pos);
+
+	return 0;
+}
+
+void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	/*
+	 * This function is called at the initialization.  No need to protect
+	 * enable_tdx.
+	 */
+	if (!enable_tdx)
+		return;
+
+	if (__tdx_hardware_setup(&vt_x86_ops))
+		enable_tdx = false;
+}
arch/x86/kvm/vmx/x86_ops.h +6 -0
index 40c64fb1f505..ccf98e79d8c3 100644
@@ -123,4 +123,10 @@ void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu);
  #endif
  void vmx_setup_mce(struct kvm_vcpu *vcpu);
 
+#ifdef CONFIG_INTEL_TDX_HOST
+void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
+#else
+static inline void tdx_hardware_setup(struct kvm_x86_ops *x86_ops) {}
+#endif
+
  #endif /* __KVM_X86_VMX_X86_OPS_H */
maintainer
#11 lore raw

Re: [RFC PATCH v5 005/104] KVM: x86: Refactor KVM VMX module init/exit functions

In reply to [email protected]
Quoted 125 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Currently, KVM VMX module initialization/exit functions are a single function each. Refactor KVM VMX module initialization functions into KVM common part and VMX part so that TDX specific part can be added cleanly. Opportunistically refactor module exit function as well.

The current module initialization flow is, 1.) calculate the sizes of VMX kvm structure and VMX vcpu structure, 2.) report those sizes to the KVM common layer and KVM common initialization, and 3.) VMX specific system-wide initialization.

Refactor the KVM VMX module initialization function into functions with a wrapper function to separate VMX logic in vmx.c from a file, main.c, common among VMX and TDX. We have a wrapper function,
"vt_init() {vmx_pre_kvm_init(); kvm_init(); vmx_init(); }" in main.c, and vmx_pre_kvm_init() and vmx_init() in vmx.c. vmx_pre_kvm_init() calculates the sizes of VMX kvm structure and KVM vcpu structure, kvm_init() does system-wide initialization of the KVM common layer, and vmx_init() does system-wide VMX initialization.

The KVM architecture common layer allocates struct kvm with reported size for architecture-specific code. The KVM VMX module defines its structure as struct vmx_kvm { struct kvm; VMX specific members;} and uses it as struct vmx kvm. Similar for vcpu structure. TDX KVM patches will define TDX specific kvm and vcpu structures, add tdx_pre_kvm_init() to report the sizes of them to the KVM common layer.

The current module exit function is also a single function, a combination of VMX specific logic and common KVM logic. Refactor it into VMX specific logic and KVM common logic. This is just refactoring to keep the VMX specific logic in vmx.c from main.c.

---
  arch/x86/kvm/vmx/main.c    | 33 +++++++++++++
  arch/x86/kvm/vmx/vmx.c     | 97 +++++++++++++++++++-------------------
  arch/x86/kvm/vmx/x86_ops.h |  5 +-
  3 files changed, 86 insertions(+), 49 deletions(-)
arch/x86/kvm/vmx/main.c +33 -0
index b79fcc8d81dd..8ff13c7881f2 100644
@@ -165,3 +165,36 @@ struct kvm_x86_init_ops vt_init_ops __initdata = {
 
  	.runtime_ops = &vt_x86_ops,
  };
+
+static int __init vt_init(void)
+{
+	unsigned int vcpu_size = 0, vcpu_align = 0;
+	int r;
+
+	vmx_pre_kvm_init(&vcpu_size, &vcpu_align);
+
+	r = kvm_init(&vt_init_ops, vcpu_size, vcpu_align, THIS_MODULE);
+	if (r)
+		goto err_vmx_post_exit;
+
+	r = vmx_init();
+	if (r)
+		goto err_kvm_exit;
+
+	return 0;
+
+err_kvm_exit:
+	kvm_exit();
+err_vmx_post_exit:
+	vmx_post_kvm_exit();
+	return r;
+}
+module_init(vt_init);
+
+static void vt_exit(void)
+{
+	vmx_exit();
+	kvm_exit();
+	vmx_post_kvm_exit();
+}
+module_exit(vt_exit);
arch/x86/kvm/vmx/vmx.c +1 -34
index f6f5d0dac579..7838cd177f0e 100644
@@ -7929,47 +7929,12 @@ static void vmx_cleanup_l1d_flush(void)
  	l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
  }
 
-static void vmx_exit(void)
+void __init vmx_pre_kvm_init(unsigned int *vcpu_size, unsigned int *vcpu_align)
  {
-#ifdef CONFIG_KEXEC_CORE
-	RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
-	synchronize_rcu();
-#endif
-
-	kvm_exit();
-
-#if IS_ENABLED(CONFIG_HYPERV)
-	if (static_branch_unlikely(&enable_evmcs)) {
-		int cpu;
-		struct hv_vp_assist_page *vp_ap;
-		/*
-		 * Reset everything to support using non-enlightened VMCS
-		 * access later (e.g. when we reload the module with
-		 * enlightened_vmcs=0)
-		 */
-		for_each_online_cpu(cpu) {
-			vp_ap =	hv_get_vp_assist_page(cpu);
-
-			if (!vp_ap)
-				continue;
-
-			vp_ap->nested_control.features.directhypercall = 0;
-			vp_ap->current_nested_vmcs = 0;
-			vp_ap->enlighten_vmentry = 0;
-		}
-
-		static_branch_disable(&enable_evmcs);
-	}
-#endif
-	vmx_cleanup_l1d_flush();
-
-	allow_smaller_maxphyaddr = false;

arch/x86/kvm/vmx/vmx.c static void vmx_cleanup_l1d_flush(void) · line 7937

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +4 -6
-}
-module_exit(vmx_exit);
-
-static int __init vmx_init(void)
-{
-	int r, cpu;
+	if (sizeof(struct vcpu_vmx) > *vcpu_size)
+		*vcpu_size = sizeof(struct vcpu_vmx);
+	if (__alignof__(struct vcpu_vmx) > *vcpu_align)
+		*vcpu_align = __alignof__(struct vcpu_vmx);

Please keep these four lines in vt_init, and rename the rest of vmx_pre_kvm_init to hv_vp_assist_page_init. Likewise, rename vmx_post_kvm_exit to hv_vp_assist_page_exit.

Adjusting the vcpu_size and vcpu_align for TDX (I guess) can be added later when TDX ops are introduced.

Paolo

Quoted 91 lines
arch/x86/kvm/vmx/vmx.c +44 -8
  #if IS_ENABLED(CONFIG_HYPERV)
  	/*
@@ -8004,11 +7969,38 @@ static int __init vmx_init(void)
  		enlightened_vmcs = false;
  	}
  #endif
+}
 
-	r = kvm_init(&vt_init_ops, sizeof(struct vcpu_vmx),
-		__alignof__(struct vcpu_vmx), THIS_MODULE);
-	if (r)
-		return r;
+void vmx_post_kvm_exit(void)
+{
+#if IS_ENABLED(CONFIG_HYPERV)
+	if (static_branch_unlikely(&enable_evmcs)) {
+		int cpu;
+		struct hv_vp_assist_page *vp_ap;
+		/*
+		 * Reset everything to support using non-enlightened VMCS
+		 * access later (e.g. when we reload the module with
+		 * enlightened_vmcs=0)
+		 */
+		for_each_online_cpu(cpu) {
+			vp_ap =	hv_get_vp_assist_page(cpu);
+
+			if (!vp_ap)
+				continue;
+
+			vp_ap->nested_control.features.directhypercall = 0;
+			vp_ap->current_nested_vmcs = 0;
+			vp_ap->enlighten_vmentry = 0;
+		}
+
+		static_branch_disable(&enable_evmcs);
+	}
+#endif
+}
+
+int __init vmx_init(void)
+{
+	int r, cpu;
 
  	/*
  	 * Must be called after kvm_init() so enable_ept is properly set
@@ -8018,10 +8010,8 @@ static int __init vmx_init(void)
  	 * mitigation mode.
  	 */
  	r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
-	if (r) {
-		vmx_exit();
+	if (r)
  		return r;
-	}
 
  	for_each_possible_cpu(cpu) {
  		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
@@ -8045,4 +8035,15 @@ static int __init vmx_init(void)
 
  	return 0;
  }
-module_init(vmx_init);
+
+void vmx_exit(void)
+{
+#ifdef CONFIG_KEXEC_CORE
+	RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
+	synchronize_rcu();
+#endif
+
+	vmx_cleanup_l1d_flush();
+
+	allow_smaller_maxphyaddr = false;
+}
arch/x86/kvm/vmx/x86_ops.h +4 -1
index ccf98e79d8c3..7da541e1c468 100644
@@ -8,7 +8,10 @@
 
  #include "x86.h"
 
-extern struct kvm_x86_init_ops vt_init_ops __initdata;
+void __init vmx_pre_kvm_init(unsigned int *vcpu_size, unsigned int *vcpu_align);
+int __init vmx_init(void);
+void vmx_exit(void);
+void vmx_post_kvm_exit(void);
 
  __init int vmx_cpu_has_kvm_support(void);
  __init int vmx_disabled_by_bios(void);
maintainer
#14 lore raw

Re: [RFC PATCH v5 006/104] KVM: TDX: Add placeholders for TDX VM/vcpu structure

In reply to [email protected]

arch/x86/kvm/vmx/tdx.c void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 64

Quoted 9 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +9 -0
+void __init tdx_pre_kvm_init(unsigned int *vcpu_size,
+			unsigned int *vcpu_align, unsigned int *vm_size)
+{
+	*vcpu_size = sizeof(struct vcpu_tdx);
+	*vcpu_align = __alignof__(struct vcpu_tdx);
+
+	if (sizeof(struct kvm_tdx) > *vm_size)
+		*vm_size = sizeof(struct kvm_tdx);
+}

No need for this function, I would just do

	vcpu_size = max(sizeof vcpu_vmx, sizeof vcpu_tdx);
	vcpu_align = max(...);
	vt_x86_ops.vm_size = max(...);

in vt_init.

Paolo

maintainer Reviewed-by on v5 7/104
#16 lore raw

Re: [RFC PATCH v5 007/104] x86/virt/tdx: Add a helper function to return system wide info about TDX module

In reply to [email protected]
Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
---
  arch/x86/include/asm/tdx.h | 55 ++++++++++++++++++++++++++++++++++++++
  arch/x86/virt/vmx/tdx.c    | 16 +++++++++--
  arch/x86/virt/vmx/tdx.h    | 52 -----------------------------------
  3 files changed, 69 insertions(+), 54 deletions(-)

Patch looks good, but place these definitions in arch/x86/include/asm/tdx.h already in Kai's series if possible.

Apart from that,

Paolo

maintainer Reviewed-by on v5 4/104
#9 lore raw

Re: [RFC PATCH v5 004/104] KVM: Enable hardware before doing arch VM initialization

In reply to [email protected]
Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Swap the order of hardware_enable_all() and kvm_arch_init_vm() to accommodate Intel's TDX, which needs VMX to be enabled during VM init in order to make SEAMCALLs.

Quoted 6 lines

This also provides consistent ordering between kvm_create_vm() and kvm_destroy_vm() with respect to calling kvm_arch_destroy_vm() and hardware_disable_all().

and please submit this as a preparation patch that can be committed separately.

Paolo

Quoted 46 lines
---
  virt/kvm/kvm_main.c | 14 +++++++-------
  1 file changed, 7 insertions(+), 7 deletions(-)
virt/kvm/kvm_main.c +7 -7
index 0afc016cc54d..52f72a366beb 100644
@@ -1105,19 +1105,19 @@ static struct kvm *kvm_create_vm(unsigned long type)
  		rcu_assign_pointer(kvm->buses[i],
  			kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
  		if (!kvm->buses[i])
-			goto out_err_no_arch_destroy_vm;
+			goto out_err_no_disable;
  	}
 
  	kvm->max_halt_poll_ns = halt_poll_ns;
 
-	r = kvm_arch_init_vm(kvm, type);
-	if (r)
-		goto out_err_no_arch_destroy_vm;
-
  	r = hardware_enable_all();
  	if (r)
  		goto out_err_no_disable;
 
+	r = kvm_arch_init_vm(kvm, type);
+	if (r)
+		goto out_err_no_arch_destroy_vm;
+
  #ifdef CONFIG_HAVE_KVM_IRQFD
  	INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
  #endif
@@ -1145,10 +1145,10 @@ static struct kvm *kvm_create_vm(unsigned long type)
  		mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
  #endif
  out_err_no_mmu_notifier:
-	hardware_disable_all();
-out_err_no_disable:
  	kvm_arch_destroy_vm(kvm);
  out_err_no_arch_destroy_vm:
+	hardware_disable_all();
+out_err_no_disable:
  	WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
  	for (i = 0; i < KVM_NR_BUSES; i++)
  		kfree(kvm_get_bus(kvm, i));
maintainer
#307 lore raw
In reply to Christoph Hellwig
Quoted 2 lines · Christoph Hellwig

A series of 104 patches is completely unreviewably, please split it into reasonable chunks.

It is split into 5-15 patch chunks, and I'm going to review it mostly according to the separation. It's just posted together because it doesn't really accomplish anything until all the chunks are merged together.

From the cover letter:

Quoted 57 lines
Quoted 57 lines

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 out vmx_x86_ops to '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 stolen bits:
Introduce framework to handle stolen 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"

Quoted 8 lines
Quoted 8 lines

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 "

Paolo

maintainer
#19 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to [email protected]

arch/x86/kvm/vmx/tdx.c line 97

Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	if (!tdx_module_initialized) {
+		if (enable_tdx) {
+			ret = __tdx_module_setup();
+			if (ret)
+				enable_tdx = false;

"enable_tdx = false" isn't great to do only when a VM is created. Does it make sense to anticipate this to the point when the kvm_intel.ko module is loaded?

Paolo

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+			else
+				tdx_module_initialized = true;
+		} else
+			ret = -EOPNOTSUPP;
+	}
+
maintainer Reviewed-by on v5 9/104
#33 lore raw

Re: [RFC PATCH v5 009/104] KVM: x86: Introduce vm_type to differentiate default VMs from confidential VMs

In reply to [email protected]
Quoted 19 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Unlike default VMs, confidential VMs (Intel TDX and AMD SEV-ES) don't allow some operations (e.g., memory read/write, register state access, etc).

Introduce vm_type to track the type of the VM to x86 KVM. Other arch KVMs already use vm_type, KVM_INIT_VM accepts vm_type, and x86 KVM callback vm_init accepts vm_type. So follow them. Further, a different policy can be made based on vm_type. Define KVM_X86_DEFAULT_VM for default VM as default and define KVM_X86_TDX_VM for Intel TDX VM. The wrapper function will be defined as "bool is_td(kvm) { return vm_type == VM_TYPE_TDX; }"

Add a capability KVM_CAP_VM_TYPES to effectively allow device model, e.g. qemu, to query what VM types are supported by KVM. This (introduce a new capability and add vm_type) is chosen to align with other arch KVMs that have VM types already. Other arch KVMs uses different name to query supported vm types and there is no common name for it, so new name was chosen.

Quoted 4 lines
Quoted 241 lines
---
  Documentation/virt/kvm/api.rst        | 15 +++++++++++++++
  arch/x86/include/asm/kvm-x86-ops.h    |  1 +
  arch/x86/include/asm/kvm_host.h       |  2 ++
  arch/x86/include/uapi/asm/kvm.h       |  3 +++
  arch/x86/kvm/svm/svm.c                |  6 ++++++
  arch/x86/kvm/vmx/main.c               |  1 +
  arch/x86/kvm/vmx/tdx.h                |  6 +-----
  arch/x86/kvm/vmx/vmx.c                |  5 +++++
  arch/x86/kvm/vmx/x86_ops.h            |  1 +
  arch/x86/kvm/x86.c                    |  9 ++++++++-
  include/uapi/linux/kvm.h              |  1 +
  tools/arch/x86/include/uapi/asm/kvm.h |  3 +++
  tools/include/uapi/linux/kvm.h        |  1 +
  13 files changed, 48 insertions(+), 6 deletions(-)
Documentation/virt/kvm/api.rst +15 -0
index 9f3172376ec3..b1e142719ec0 100644
@@ -147,15 +147,30 @@ described as 'basic' will be available.
  The new VM has no virtual cpus and no memory.
  You probably want to use 0 as machine type.
 
+X86:
+^^^^
+
+Supported vm type can be queried from KVM_CAP_VM_TYPES, which returns the
+bitmap of supported vm types. The 1-setting of bit @n means vm type with
+value @n is supported.
+
+S390:
+^^^^^
+
  In order to create user controlled virtual machines on S390, check
  KVM_CAP_S390_UCONTROL and use the flag KVM_VM_S390_UCONTROL as
  privileged user (CAP_SYS_ADMIN).
 
+MIPS:
+^^^^^
+
  To use hardware assisted virtualization on MIPS (VZ ASE) rather than
  the default trap & emulate implementation (which changes the virtual
  memory layout to fit in user mode), check KVM_CAP_MIPS_VZ and use the
  flag KVM_VM_MIPS_VZ.
 
+ARM64:
+^^^^^^
 
  On arm64, the physical address size for a VM (IPA Size limit) is limited
  to 40bits by default. The limit can be configured if the host supports the
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index d39e0de06be2..8125d43d3566 100644
@@ -18,6 +18,7 @@ KVM_X86_OP_NULL(hardware_unsetup)
  KVM_X86_OP_NULL(cpu_has_accelerated_tpr)
  KVM_X86_OP(has_emulated_msr)
  KVM_X86_OP(vcpu_after_set_cpuid)
+KVM_X86_OP(is_vm_type_supported)
  KVM_X86_OP(vm_init)
  KVM_X86_OP_NULL(vm_destroy)
  KVM_X86_OP(vcpu_create)
arch/x86/include/asm/kvm_host.h +2 -0
index b61e46743184..8de357a9ad30 100644
@@ -1048,6 +1048,7 @@ struct kvm_x86_msr_filter {
  #define APICV_INHIBIT_REASON_ABSENT	7
 
  struct kvm_arch {
+	unsigned long vm_type;
  	unsigned long n_used_mmu_pages;
  	unsigned long n_requested_mmu_pages;
  	unsigned long n_max_mmu_pages;
@@ -1322,6 +1323,7 @@ struct kvm_x86_ops {
  	bool (*has_emulated_msr)(struct kvm *kvm, u32 index);
  	void (*vcpu_after_set_cpuid)(struct kvm_vcpu *vcpu);
 
+	bool (*is_vm_type_supported)(unsigned long vm_type);
  	unsigned int vm_size;
  	int (*vm_init)(struct kvm *kvm);
  	void (*vm_destroy)(struct kvm *kvm);
arch/x86/include/uapi/asm/kvm.h +3 -0
index bf6e96011dfe..71a5851475e7 100644
@@ -525,4 +525,7 @@ struct kvm_pmu_event_filter {
  #define KVM_VCPU_TSC_CTRL 0 /* control group for the timestamp counter (TSC) */
  #define   KVM_VCPU_TSC_OFFSET 0 /* attribute for the TSC offset */
 
+#define KVM_X86_DEFAULT_VM	0
+#define KVM_X86_TDX_VM		1
+
  #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/svm/svm.c +6 -0
index fd3a00c892c7..778075b71dc3 100644
@@ -4512,6 +4512,11 @@ static void svm_vm_destroy(struct kvm *kvm)
  	sev_vm_destroy(kvm);
  }
 
+static bool svm_is_vm_type_supported(unsigned long type)
+{
+	return type == KVM_X86_DEFAULT_VM;
+}
+
  static int svm_vm_init(struct kvm *kvm)
  {
  	if (!pause_filter_count || !pause_filter_thresh)
@@ -4539,6 +4544,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
  	.vcpu_free = svm_free_vcpu,
  	.vcpu_reset = svm_vcpu_reset,
 
+	.is_vm_type_supported = svm_is_vm_type_supported,
  	.vm_size = sizeof(struct kvm_svm),
  	.vm_init = svm_vm_init,
  	.vm_destroy = svm_vm_destroy,
arch/x86/kvm/vmx/main.c +1 -0
index 28a7597d0782..77da926ee505 100644
@@ -29,6 +29,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.cpu_has_accelerated_tpr = report_flexpriority,
  	.has_emulated_msr = vmx_has_emulated_msr,
 
+	.is_vm_type_supported = vmx_is_vm_type_supported,
  	.vm_size = sizeof(struct kvm_vmx),
  	.vm_init = vmx_vm_init,
 
arch/x86/kvm/vmx/tdx.h +1 -5
index d448e019602c..616fbf79b129 100644
@@ -15,11 +15,7 @@ struct vcpu_tdx {
 
  static inline bool is_td(struct kvm *kvm)
  {
-	/*
-	 * TDX VM type isn't defined yet.
-	 * return kvm->arch.vm_type == KVM_X86_TDX_VM;
-	 */
-	return false;
+	return kvm->arch.vm_type == KVM_X86_TDX_VM;
  }
 
  static inline bool is_td_vcpu(struct kvm_vcpu *vcpu)
arch/x86/kvm/vmx/vmx.c +5 -0
index 7838cd177f0e..3c7b3f245fee 100644
@@ -7079,6 +7079,11 @@ int vmx_vcpu_create(struct kvm_vcpu *vcpu)
  	return err;
  }
 
+bool vmx_is_vm_type_supported(unsigned long type)
+{
+	return type == KVM_X86_DEFAULT_VM;
+}
+
  #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
  #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
 
arch/x86/kvm/vmx/x86_ops.h +1 -0
index 1bad27e592b5..f7327bc73be0 100644
@@ -25,6 +25,7 @@ void vmx_hardware_unsetup(void);
  int vmx_hardware_enable(void);
  void vmx_hardware_disable(void);
  bool report_flexpriority(void);
+bool vmx_is_vm_type_supported(unsigned long type);
  int vmx_vm_init(struct kvm *kvm);
  int vmx_vcpu_create(struct kvm_vcpu *vcpu);
  int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu);
arch/x86/kvm/x86.c +8 -1
index aa2942060154..f6438750d190 100644
@@ -4344,6 +4344,11 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
  			r = sizeof(struct kvm_xsave);
  		break;
  	}
+	case KVM_CAP_VM_TYPES:
+		r = BIT(KVM_X86_DEFAULT_VM);
+		if (static_call(kvm_x86_is_vm_type_supported)(KVM_X86_TDX_VM))
+			r |= BIT(KVM_X86_TDX_VM);
+		break;
  	default:
  		break;
  	}
@@ -11583,9 +11588,11 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  	int ret;
  	unsigned long flags;
 
-	if (type)
+	if (!static_call(kvm_x86_is_vm_type_supported)(type))
  		return -EINVAL;
 
+	kvm->arch.vm_type = type;
+
  	ret = kvm_page_track_init(kvm);
  	if (ret)
  		return ret;
include/uapi/linux/kvm.h +1 -0
index 507ee1f2aa96..bb3e29770f76 100644
@@ -1135,6 +1135,7 @@ struct kvm_ppc_resize_hpt {
  #define KVM_CAP_XSAVE2 208
  #define KVM_CAP_SYS_ATTRIBUTES 209
  #define KVM_CAP_PPC_AIL_MODE_3 210
+#define KVM_CAP_VM_TYPES 21
 
  #ifdef KVM_CAP_IRQ_ROUTING
 
tools/arch/x86/include/uapi/asm/kvm.h +3 -0
index bf6e96011dfe..71a5851475e7 100644
@@ -525,4 +525,7 @@ struct kvm_pmu_event_filter {
  #define KVM_VCPU_TSC_CTRL 0 /* control group for the timestamp counter (TSC) */
  #define   KVM_VCPU_TSC_OFFSET 0 /* attribute for the TSC offset */
 
+#define KVM_X86_DEFAULT_VM	0
+#define KVM_X86_TDX_VM		1
+
  #endif /* _ASM_X86_KVM_H */
tools/include/uapi/linux/kvm.h +1 -0
index 507ee1f2aa96..1a99d0aae852 100644
@@ -1135,6 +1135,7 @@ struct kvm_ppc_resize_hpt {
  #define KVM_CAP_XSAVE2 208
  #define KVM_CAP_SYS_ATTRIBUTES 209
  #define KVM_CAP_PPC_AIL_MODE_3 210
+#define KVM_CAP_VM_TYPES 211
 
  #ifdef KVM_CAP_IRQ_ROUTING
 
maintainer Reviewed-by on v5 13/104
#43 lore raw

Re: [RFC PATCH v5 013/104] KVM: TDX: Add TDX "architectural" error codes

In reply to [email protected]
Quoted 8 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Add error codes for the TDX SEAMCALLs both for TDX VMM side for TDH SEAMCALL and TDX guest side for TDG.VP.VMCALL. KVM issues the TDX SEAMCALLs and checks its error code. KVM handles hypercall from the TDX guest and may return an error. So error code for the TDX guest is also needed.

Quoted 6 lines

TDX SEAMCALL uses bits 31:0 to return more information, so these error codes will only exactly match RAX[63:32]. Error codes for TDG.VP.VMCALL is defined by TDX Guest-Host-Communication interface spec.

Quoted 40 lines
---
  arch/x86/kvm/vmx/tdx_errno.h | 29 +++++++++++++++++++++++++++++
  1 file changed, 29 insertions(+)

create mode 100644 arch/x86/kvm/vmx/tdx_errno.h

arch/x86/kvm/vmx/tdx_errno.h new file +29 -0
new file mode 100644
index 000000000000..5c878488795d
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* architectural status code for SEAMCALL */
+
+#ifndef __KVM_X86_TDX_ERRNO_H
+#define __KVM_X86_TDX_ERRNO_H
+
+#define TDX_SEAMCALL_STATUS_MASK		0xFFFFFFFF00000000ULL
+
+/*
+ * TDX SEAMCALL Status Codes (returned in RAX)
+ */
+#define TDX_SUCCESS				0x0000000000000000ULL
+#define TDX_NON_RECOVERABLE_VCPU		0x4000000100000000ULL
+#define TDX_INTERRUPTED_RESUMABLE		0x8000000300000000ULL
+#define TDX_LIFECYCLE_STATE_INCORRECT		0xC000060700000000ULL
+#define TDX_VCPU_NOT_ASSOCIATED			0x8000070200000000ULL
+#define TDX_KEY_GENERATION_FAILED		0x8000080000000000ULL
+#define TDX_KEY_STATE_INCORRECT			0xC000081100000000ULL
+#define TDX_KEY_CONFIGURED			0x0000081500000000ULL
+#define TDX_EPT_WALK_FAILED			0xC0000B0000000000ULL
+
+/*
+ * TDG.VP.VMCALL Status Codes (returned in R10)
+ */
+#define TDG_VP_VMCALL_SUCCESS			0x0000000000000000ULL
+#define TDG_VP_VMCALL_INVALID_OPERAND		0x8000000000000000ULL
+#define TDG_VP_VMCALL_TDREPORT_FAILED		0x8000000000000001ULL
+
+#endif /* __KVM_X86_TDX_ERRNO_H */
maintainer
#45 lore raw

Re: [RFC PATCH v5 014/104] KVM: TDX: Add a function for KVM to invoke SEAMCALL

In reply to [email protected]
Quoted 103 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add an assembly function for KVM to call the TDX module because __seamcall defined in arch/x86/virt/vmx/seamcall.S doesn't fit for the KVM use case.

TDX module API returns extended error information in registers, rcx, rdx, r8, r9, r10, and r11 in addition to success case. KVM uses those extended error information in addition to the status code returned in RAX. Update the assembly code to optionally return those outputs even in the error case and define the specific version for KVM to call the TDX module.

SEAMCALL to the SEAM module (P-SEAMLDR or TDX module) can result in the error of VmFailInvalid indicated by CF=1 when VMX isn't enabled by VMXON instruction. Because KVM guarantees that VMX is enabled, VmFailInvalid error won't happen. Don't check the error for KVM.

---
  arch/x86/kvm/Makefile       |  2 +-
  arch/x86/kvm/vmx/seamcall.S | 55 +++++++++++++++++++++++++++++++++++++
  arch/x86/virt/tdxcall.S     |  8 ++++--
  3 files changed, 62 insertions(+), 3 deletions(-)

create mode 100644 arch/x86/kvm/vmx/seamcall.S

arch/x86/kvm/Makefile +1 -1
index e2c05195cb95..e8f83a7d0dc3 100644
@@ -24,7 +24,7 @@ kvm-$(CONFIG_KVM_XEN)	+= xen.o
  kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
  			   vmx/evmcs.o vmx/nested.o vmx/posted_intr.o vmx/main.o
  kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
-kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o vmx/seamcall.o
 
  kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o svm/sev.o
 
arch/x86/kvm/vmx/seamcall.S new file +55 -0
new file mode 100644
index 000000000000..4a15017fc7dd
@@ -0,0 +1,55 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#include <linux/linkage.h>
+#include <asm/export.h>
+#include <asm/frame.h>
+
+#include "../../virt/tdxcall.S"
+
+/*
+ * kvm_seamcall()  - Host-side interface functions to SEAM software (TDX module)
+ *
+ * Transform function call register arguments into the SEAMCALL register
+ * ABI.  Return the completion status of the SEAMCALL.  Additional output
+ * operands are saved in @out (if it is provided by the user).
+ * It doesn't check TDX_SEAMCALL_VMFAILINVALID unlike __semcall() because KVM
+ * guarantees that VMX is enabled so that TDX_SEAMCALL_VMFAILINVALID doesn't
+ * happen.  In the case of error completion status code, extended error code may
+ * be stored in leaf specific output registers.
+ *
+ *-------------------------------------------------------------------------
+ * SEAMCALL ABI:
+ *-------------------------------------------------------------------------
+ * Input Registers:
+ *
+ * RAX                 - SEAMCALL Leaf number.
+ * RCX,RDX,R8-R9       - SEAMCALL Leaf specific input registers.
+ *
+ * Output Registers:
+ *
+ * RAX                 - SEAMCALL completion status code.
+ * RCX,RDX,R8-R11      - SEAMCALL Leaf specific output registers.
+ *
+ *-------------------------------------------------------------------------
+ *
+ * kvm_seamcall() function ABI:
+ *
+ * @fn  (RDI)          - SEAMCALL Leaf number, moved to RAX
+ * @rcx (RSI)          - Input parameter 1, moved to RCX
+ * @rdx (RDX)          - Input parameter 2, moved to RDX
+ * @r8  (RCX)          - Input parameter 3, moved to R8
+ * @r9  (R8)           - Input parameter 4, moved to R9
+ *
+ * @out (R9)           - struct tdx_module_output pointer
+ *                       stored temporarily in R12 (not
+ *                       shared with the TDX module). It
+ *                       can be NULL.
+ *
+ * Return (via RAX) the completion status of the SEAMCALL
+ */
+SYM_FUNC_START(kvm_seamcall)
+        FRAME_BEGIN
+        TDX_MODULE_CALL host=1 error_check=0
+        FRAME_END
+        ret
+SYM_FUNC_END(kvm_seamcall)
+EXPORT_SYMBOL_GPL(kvm_seamcall)
arch/x86/virt/tdxcall.S +0 -0
index 90569faedacc..2e614b6b5f1e 100644

arch/x86/virt/tdxcall.S line 16

Quoted 5 lines
arch/x86/virt/tdxcall.S +1 -1
@@ -13,7 +13,7 @@
  #define tdcall		.byte 0x66,0x0f,0x01,0xcc
  #define seamcall	.byte 0x66,0x0f,0x01,0xcf
 
-.macro TDX_MODULE_CALL host:req
+.macro TDX_MODULE_CALL host:req error_check=1

Perhaps name this argument ext_error_out and reverse it (that is, 0 is the current behavior while 1 is what KVM needs).

Paolo

Quoted 27 lines
arch/x86/virt/tdxcall.S +5 -1
  	/*
  	 * R12 will be used as temporary storage for struct tdx_module_output
  	 * pointer. Since R12-R15 registers are not used by TDCALL/SEAMCALL
@@ -51,9 +51,11 @@
  	 *
  	 * Set %rax to TDX_SEAMCALL_VMFAILINVALID for VMfailInvalid.
  	 * This value will never be used as actual SEAMCALL error code.
-	 */
+	*/
+	.if \error_check
  	jnc .Lno_vmfailinvalid
  	mov $TDX_SEAMCALL_VMFAILINVALID, %rax
+	.endif
  .Lno_vmfailinvalid:
  	.else
  	tdcall
@@ -66,8 +68,10 @@
  	pop %r12
 
  	/* Check for success: 0 - Successful, otherwise failed */
+	.if \error_check
  	test %rax, %rax
  	jnz .Lno_output_struct
+	.endif
 
  	/*
  	 * Since this function can be initiated without an output pointer,
maintainer
#48 lore raw

Re: [RFC PATCH v5 015/104] KVM: TDX: add a helper function for KVM to issue SEAMCALL

In reply to [email protected]
Quoted 11 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TODO: Consolidate seamcall helper function with TDX host/guest patch series. For now, this is kept to make this patch series compile/work.

A VMM interacts with the TDX module using a new instruction (SEAMCALL). A TDX VMM uses SEAMCALLs where a VMX VMM would have directly interacted with VMX instructions. For instance, a TDX VMM does not have full access to the VM control structure corresponding to VMX VMCS. Instead, a VMM induces the TDX module to act on behalf via SEAMCALLs.

Quoted 10 lines

Add a helper function for KVM C code to execute SEAMCALL instruction to hide its SEAMCALL ABI details. Although the x86 TDX host patch series defines a similar wrapper, the KVM TDX patch series defines its own because KVM TDX case is performance-critical, unlike the x86 TDX one that does one-time initialization. The difference is that the KVM TDX one is defined as a static inline function without an error check that is known to not happen so that compiler can optimize it better. The wrapper fiction in the x86 TDX host patch is defined as a function written in assembly code with error check so that it can detect errors that can occur only during the initialization.

I assume whatever survives of this patch will be merged in the previous one.

Paolo

Quoted 37 lines
---
  arch/x86/kvm/vmx/seamcall.h | 23 +++++++++++++++++++++++
  1 file changed, 23 insertions(+)

create mode 100644 arch/x86/kvm/vmx/seamcall.h

arch/x86/kvm/vmx/seamcall.h new file +23 -0
new file mode 100644
index 000000000000..604792e9a59f
@@ -0,0 +1,23 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __KVM_VMX_SEAMCALL_H
+#define __KVM_VMX_SEAMCALL_H
+
+#ifdef CONFIG_INTEL_TDX_HOST
+
+#ifdef __ASSEMBLY__
+
+.macro seamcall
+	.byte 0x66, 0x0f, 0x01, 0xcf
+.endm
+
+#else
+
+struct tdx_module_output;
+u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9, u64 r10,
+		struct tdx_module_output *out);
+
+#endif /* !__ASSEMBLY__ */
+
+#endif	/* CONFIG_INTEL_TDX_HOST */
+
+#endif /* __KVM_VMX_SEAMCALL_H */
maintainer Reviewed-by on v5 17/104
#51 lore raw

Re: [RFC PATCH v5 017/104] KVM: TDX: Add helper functions to print TDX SEAMCALL error

In reply to [email protected]
Quoted 57 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add helper functions to print out errors from the TDX module in a uniform manner.

---
  arch/x86/kvm/Makefile        |  2 +-
  arch/x86/kvm/vmx/seamcall.h  |  2 ++
  arch/x86/kvm/vmx/tdx_error.c | 22 ++++++++++++++++++++++
  3 files changed, 25 insertions(+), 1 deletion(-)

create mode 100644 arch/x86/kvm/vmx/tdx_error.c

arch/x86/kvm/Makefile +1 -1
index e8f83a7d0dc3..3d6550c73fb5 100644
@@ -24,7 +24,7 @@ kvm-$(CONFIG_KVM_XEN)	+= xen.o
  kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
  			   vmx/evmcs.o vmx/nested.o vmx/posted_intr.o vmx/main.o
  kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
-kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o vmx/seamcall.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o vmx/seamcall.o vmx/tdx_error.o
 
  kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o svm/sev.o
 
arch/x86/kvm/vmx/seamcall.h +2 -0
index 604792e9a59f..5ac419cd8e27 100644
@@ -16,6 +16,8 @@ struct tdx_module_output;
  u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9, u64 r10,
  		struct tdx_module_output *out);
 
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_output *out);
+
  #endif /* !__ASSEMBLY__ */
 
  #endif	/* CONFIG_INTEL_TDX_HOST */
arch/x86/kvm/vmx/tdx_error.c new file +12 -0
new file mode 100644
index 000000000000..61ed855d1188
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+/* functions to record TDX SEAMCALL error */
+
+#include <linux/kernel.h>
+#include <linux/bug.h>
+
+#include "tdx_ops.h"
+
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_output *out)
+{
+	if (!out) {
+		pr_err_ratelimited("SEAMCALL[%lld] failed: 0x%llx\n",

arch/x86/kvm/vmx/tdx_error.c line 22

Quoted 10 lines
arch/x86/kvm/vmx/tdx_error.c new file +10 -0
+				op, error_code);
+		return;
+	}
+
+	pr_err_ratelimited(
+		"SEAMCALL[%lld] failed: 0x%llx "
+		"RCX 0x%llx, RDX 0x%llx, R8 0x%llx, R9 0x%llx, R10 0x%llx, R11 0x%llx\n",
+		op, error_code,
+		out->rcx, out->rdx, out->r8, out->r9, out->r10, out->r11);
+}
maintainer Reviewed-by on v5 12/104
#41 lore raw

Re: [RFC PATCH v5 012/104] KVM: TDX: Define TDX architectural definitions

In reply to [email protected]
Quoted 7 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Define architectural definitions for KVM to issue the TDX SEAMCALLs.

Structures and values that are architecturally defined in the TDX module specifications the chapter of ABI Reference.

Quoted 7 lines
---
  arch/x86/kvm/vmx/tdx_arch.h | 158 ++++++++++++++++++++++++++++++++++++
  1 file changed, 158 insertions(+)

create mode 100644 arch/x86/kvm/vmx/tdx_arch.h

Quoted 164 lines
arch/x86/kvm/vmx/tdx_arch.h new file +158 -0
new file mode 100644
index 000000000000..3824491d22dc
@@ -0,0 +1,158 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* architectural constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_ARCH_H
+#define __KVM_X86_TDX_ARCH_H
+
+#include <linux/types.h>
+
+/*
+ * TDX SEAMCALL API function leaves
+ */
+#define TDH_VP_ENTER			0
+#define TDH_MNG_ADDCX			1
+#define TDH_MEM_PAGE_ADD		2
+#define TDH_MEM_SEPT_ADD		3
+#define TDH_VP_ADDCX			4
+#define TDH_MEM_PAGE_AUG		6
+#define TDH_MEM_RANGE_BLOCK		7
+#define TDH_MNG_KEY_CONFIG		8
+#define TDH_MNG_CREATE			9
+#define TDH_VP_CREATE			10
+#define TDH_MNG_RD			11
+#define TDH_MR_EXTEND			16
+#define TDH_MR_FINALIZE			17
+#define TDH_VP_FLUSH			18
+#define TDH_MNG_VPFLUSHDONE		19
+#define TDH_MNG_KEY_FREEID		20
+#define TDH_MNG_INIT			21
+#define TDH_VP_INIT			22
+#define TDH_VP_RD			26
+#define TDH_MNG_KEY_RECLAIMID		27
+#define TDH_PHYMEM_PAGE_RECLAIM		28
+#define TDH_MEM_PAGE_REMOVE		29
+#define TDH_MEM_TRACK			38
+#define TDH_MEM_RANGE_UNBLOCK		39
+#define TDH_PHYMEM_CACHE_WB		40
+#define TDH_PHYMEM_PAGE_WBINVD		41
+#define TDH_VP_WR			43
+#define TDH_SYS_LP_SHUTDOWN		44
+
+#define TDG_VP_VMCALL_GET_TD_VM_CALL_INFO		0x10000
+#define TDG_VP_VMCALL_MAP_GPA				0x10001
+#define TDG_VP_VMCALL_GET_QUOTE				0x10002
+#define TDG_VP_VMCALL_REPORT_FATAL_ERROR		0x10003
+#define TDG_VP_VMCALL_SETUP_EVENT_NOTIFY_INTERRUPT	0x10004
+
+/* TDX control structure (TDR/TDCS/TDVPS) field access codes */
+#define TDX_NON_ARCH			BIT_ULL(63)
+#define TDX_CLASS_SHIFT			56
+#define TDX_FIELD_MASK			GENMASK_ULL(31, 0)
+
+#define __BUILD_TDX_FIELD(non_arch, class, field)	\
+	(((non_arch) ? TDX_NON_ARCH : 0) |		\
+	 ((u64)(class) << TDX_CLASS_SHIFT) |		\
+	 ((u64)(field) & TDX_FIELD_MASK))
+
+#define BUILD_TDX_FIELD(class, field)			\
+	__BUILD_TDX_FIELD(false, (class), (field))
+
+#define BUILD_TDX_FIELD_NON_ARCH(class, field)		\
+	__BUILD_TDX_FIELD(true, (class), (field))
+
+
+/* @field is the VMCS field encoding */
+#define TDVPS_VMCS(field)		BUILD_TDX_FIELD(0, (field))
+
+enum tdx_guest_other_state {
+	TD_VCPU_STATE_DETAILS_NON_ARCH = 0x100,
+};
+
+union tdx_vcpu_state_details {
+	struct {
+		u64 vmxip	: 1;
+		u64 reserved	: 63;
+	};
+	u64 full;
+};
+
+/* @field is any of enum tdx_guest_other_state */
+#define TDVPS_STATE(field)		BUILD_TDX_FIELD(17, (field))
+#define TDVPS_STATE_NON_ARCH(field)	BUILD_TDX_FIELD_NON_ARCH(17, (field))
+
+/* Management class fields */
+enum tdx_guest_management {
+	TD_VCPU_PEND_NMI = 11,
+};
+
+/* @field is any of enum tdx_guest_management */
+#define TDVPS_MANAGEMENT(field)		BUILD_TDX_FIELD(32, (field))
+
+enum tdx_tdcs_execution_control {
+	TD_TDCS_EXEC_TSC_OFFSET = 10,
+};
+
+/* @field is any of enum tdx_tdcs_execution_control */
+#define TDCS_EXEC(field)		BUILD_TDX_FIELD(17, (field))
+
+#define TDX_EXTENDMR_CHUNKSIZE		256
+
+struct tdx_cpuid_value {
+	u32 eax;
+	u32 ebx;
+	u32 ecx;
+	u32 edx;
+} __packed;
+
+#define TDX_TD_ATTRIBUTE_DEBUG		BIT_ULL(0)
+#define TDX_TD_ATTRIBUTE_PKS		BIT_ULL(30)
+#define TDX_TD_ATTRIBUTE_KL		BIT_ULL(31)
+#define TDX_TD_ATTRIBUTE_PERFMON	BIT_ULL(63)
+
+#define TDX_TD_XFAM_LBR			BIT_ULL(15)
+#define TDX_TD_XFAM_AMX			(BIT_ULL(17) | BIT_ULL(18))
+
+/*
+ * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
+ */
+struct td_params {
+	u64 attributes;
+	u64 xfam;
+	u32 max_vcpus;
+	u32 reserved0;
+
+	u64 eptp_controls;
+	u64 exec_controls;
+	u16 tsc_frequency;
+	u8  reserved1[38];
+
+	u64 mrconfigid[6];
+	u64 mrowner[6];
+	u64 mrownerconfig[6];
+	u64 reserved2[4];
+
+	union {
+		struct tdx_cpuid_value cpuid_values[0];
+		u8 reserved3[768];
+	};
+} __packed __aligned(1024);
+
+/*
+ * Guest uses MAX_PA for GPAW when set.
+ * 0: GPA.SHARED bit is GPA[47]
+ * 1: GPA.SHARED bit is GPA[51]
+ */
+#define TDX_EXEC_CONTROL_MAX_GPAW      BIT_ULL(0)
+
+/*
+ * TDX requires the frequency to be defined in units of 25MHz, which is the
+ * frequency of the core crystal clock on TDX-capable platforms, i.e. the TDX
+ * module can only program frequencies that are multiples of 25MHz.  The
+ * frequency must be between 100mhz and 10ghz (inclusive).
+ */
+#define TDX_TSC_KHZ_TO_25MHZ(tsc_in_khz)	((tsc_in_khz) / (25 * 1000))
+#define TDX_TSC_25MHZ_TO_KHZ(tsc_in_25mhz)	((tsc_in_25mhz) * (25 * 1000))
+#define TDX_MIN_TSC_FREQUENCY_KHZ		(100 * 1000)
+#define TDX_MAX_TSC_FREQUENCY_KHZ		(10 * 1000 * 1000)
+
+#endif /* __KVM_X86_TDX_ARCH_H */
#46 lore raw

Re: [RFC PATCH v5 014/104] KVM: TDX: Add a function for KVM to invoke SEAMCALL

In reply to [email protected]
Quoted 10 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add an assembly function for KVM to call the TDX module because __seamcall defined in arch/x86/virt/vmx/seamcall.S doesn't fit for the KVM use case.

TDX module API returns extended error information in registers, rcx, rdx, r8, r9, r10, and r11 in addition to success case. KVM uses those extended error information in addition to the status code returned in RAX. Update the assembly code to optionally return those outputs even in the error case and define the specific version for KVM to call the TDX module.

+Kirill.

Kirill's patches hasn't been merged yet. Can Kirill just change his patch so you don't have to change the assembly code again? Btw this change is reasonable for host kernel support series as well. Sorry that I failed to notice.

Btw, SEAMCALL C function is already implemented in host kernel support series:

https://lore.kernel.org/kvm/269a053607357eedd9a1e8ddf0e7240ae0c3985c.1647167475.git.kai.huang@intel.com/

I think maybe you can just export __seamcall() and use it?

Quoted 5 lines

SEAMCALL to the SEAM module (P-SEAMLDR or TDX module) can result in the error of VmFailInvalid indicated by CF=1 when VMX isn't enabled by VMXON instruction. Because KVM guarantees that VMX is enabled, VmFailInvalid error won't happen. Don't check the error for KVM.

Perhaps you can introduce kvm_seamcall() which calls __seamcall(), but WARN() if it returns VMfailInvalid?

Quoted 111 lines
---
 arch/x86/kvm/Makefile       |  2 +-
 arch/x86/kvm/vmx/seamcall.S | 55 +++++++++++++++++++++++++++++++++++++
 arch/x86/virt/tdxcall.S     |  8 ++++--
 3 files changed, 62 insertions(+), 3 deletions(-)
 create mode 100644 arch/x86/kvm/vmx/seamcall.S
arch/x86/kvm/Makefile +1 -1
index e2c05195cb95..e8f83a7d0dc3 100644
@@ -24,7 +24,7 @@ kvm-$(CONFIG_KVM_XEN)	+= xen.o
 kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
 			   vmx/evmcs.o vmx/nested.o vmx/posted_intr.o vmx/main.o
 kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
-kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o vmx/seamcall.o
 
 kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o svm/sev.o
 
arch/x86/kvm/vmx/seamcall.S new file +55 -0
new file mode 100644
index 000000000000..4a15017fc7dd
@@ -0,0 +1,55 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#include <linux/linkage.h>
+#include <asm/export.h>
+#include <asm/frame.h>
+
+#include "../../virt/tdxcall.S"
+
+/*
+ * kvm_seamcall()  - Host-side interface functions to SEAM software (TDX module)
+ *
+ * Transform function call register arguments into the SEAMCALL register
+ * ABI.  Return the completion status of the SEAMCALL.  Additional output
+ * operands are saved in @out (if it is provided by the user).
+ * It doesn't check TDX_SEAMCALL_VMFAILINVALID unlike __semcall() because KVM
+ * guarantees that VMX is enabled so that TDX_SEAMCALL_VMFAILINVALID doesn't
+ * happen.  In the case of error completion status code, extended error code may
+ * be stored in leaf specific output registers.
+ *
+ *-------------------------------------------------------------------------
+ * SEAMCALL ABI:
+ *-------------------------------------------------------------------------
+ * Input Registers:
+ *
+ * RAX                 - SEAMCALL Leaf number.
+ * RCX,RDX,R8-R9       - SEAMCALL Leaf specific input registers.
+ *
+ * Output Registers:
+ *
+ * RAX                 - SEAMCALL completion status code.
+ * RCX,RDX,R8-R11      - SEAMCALL Leaf specific output registers.
+ *
+ *-------------------------------------------------------------------------
+ *
+ * kvm_seamcall() function ABI:
+ *
+ * @fn  (RDI)          - SEAMCALL Leaf number, moved to RAX
+ * @rcx (RSI)          - Input parameter 1, moved to RCX
+ * @rdx (RDX)          - Input parameter 2, moved to RDX
+ * @r8  (RCX)          - Input parameter 3, moved to R8
+ * @r9  (R8)           - Input parameter 4, moved to R9
+ *
+ * @out (R9)           - struct tdx_module_output pointer
+ *                       stored temporarily in R12 (not
+ *                       shared with the TDX module). It
+ *                       can be NULL.
+ *
+ * Return (via RAX) the completion status of the SEAMCALL
+ */
+SYM_FUNC_START(kvm_seamcall)
+        FRAME_BEGIN
+        TDX_MODULE_CALL host=1 error_check=0
+        FRAME_END
+        ret
+SYM_FUNC_END(kvm_seamcall)
+EXPORT_SYMBOL_GPL(kvm_seamcall)
arch/x86/virt/tdxcall.S +4 -2
index 90569faedacc..2e614b6b5f1e 100644
@@ -13,7 +13,7 @@
 #define tdcall		.byte 0x66,0x0f,0x01,0xcc
 #define seamcall	.byte 0x66,0x0f,0x01,0xcf
 
-.macro TDX_MODULE_CALL host:req
+.macro TDX_MODULE_CALL host:req error_check=1
 	/*
 	 * R12 will be used as temporary storage for struct tdx_module_output
 	 * pointer. Since R12-R15 registers are not used by TDCALL/SEAMCALL
@@ -51,9 +51,11 @@
 	 *
 	 * Set %rax to TDX_SEAMCALL_VMFAILINVALID for VMfailInvalid.
 	 * This value will never be used as actual SEAMCALL error code.
-	 */
+	*/
+	.if \error_check
 	jnc .Lno_vmfailinvalid
 	mov $TDX_SEAMCALL_VMFAILINVALID, %rax
+	.endif
 .Lno_vmfailinvalid:
 	.else
 	tdcall

arch/x86/virt/tdxcall.S line 75

Quoted 8 lines
arch/x86/virt/tdxcall.S +2 -0
@@ -66,8 +68,10 @@
 	pop %r12
 
 	/* Check for success: 0 - Successful, otherwise failed */
+	.if \error_check
 	test %rax, %rax
 	jnz .Lno_output_struct
+	.endif
 

Checking VMfailInvalid, and checking whether %rax is 0 are totally different things. I don't think it's good to use one single 'error_check' to handle.

As I mentioned above, I think checking whether %rax is 0 can be just removed in Kirill's patch. But I don't have strong opinion on whether you should add another parameter to determine whether to check VMfailInvalid, or you should just call __seamcall() which is implemented in host support series.

#17 lore raw

Re: [RFC PATCH v5 007/104] x86/virt/tdx: Add a helper function to return system wide info about TDX module

In reply to Paolo Bonzini
Quoted 8 lines · Paolo Bonzini
Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
---
  arch/x86/include/asm/tdx.h | 55 ++++++++++++++++++++++++++++++++++++++
  arch/x86/virt/vmx/tdx.c    | 16 +++++++++--
  arch/x86/virt/vmx/tdx.h    | 52 -----------------------------------
  3 files changed, 69 insertions(+), 54 deletions(-)
Quoted 8 lines

Patch looks good, but place these definitions in arch/x86/include/asm/tdx.h already in Kai's series if possible.

Apart from that,

Paolo

Does it make more sense for me to just include this patch (and couple of other patches such as exporting information of TDX KeyIDs) to host kernel support series?

Signature · 2 lines
Thanks,
-Kai
#35 lore raw

Re: [RFC PATCH v5 010/104] KVM: TDX: Make TDX VM type supported

In reply to [email protected]
Quoted 7 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

As first step TDX VM support, return that TDX VM type supported to device model, e.g. qemu. The callback to create guest TD is vm_init callback for KVM_CREATE_VM. Add a place holder function and call a function to initialize TDX module on demand because in that callback VMX is enabled by hardware_enable callback (vmx_hardware_enable).

Should we put this patch at the end of series until all changes required to run TD are introduced? This patch essentially tells userspace KVM is ready to support a TD but actually it's not ready. And this might also cause bisect issue I suppose?

Signature · 2 lines
Thanks,
-Kai
Quoted 116 lines
---
 arch/x86/kvm/vmx/main.c    | 24 ++++++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.c     |  5 +++++
 arch/x86/kvm/vmx/vmx.c     |  5 -----
 arch/x86/kvm/vmx/x86_ops.h |  3 ++-
 4 files changed, 29 insertions(+), 8 deletions(-)
arch/x86/kvm/vmx/main.c +22 -2
index 77da926ee505..8103d1c32cc9 100644
@@ -5,6 +5,12 @@
 #include "vmx.h"
 #include "nested.h"
 #include "pmu.h"
+#include "tdx.h"
+
+static bool vt_is_vm_type_supported(unsigned long type)
+{
+	return type == KVM_X86_DEFAULT_VM || tdx_is_vm_type_supported(type);
+}
 
 static __init int vt_hardware_setup(void)
 {
@@ -19,6 +25,20 @@ static __init int vt_hardware_setup(void)
 	return 0;
 }
 
+static int vt_vm_init(struct kvm *kvm)
+{
+	int ret;
+
+	if (is_td(kvm)) {
+		ret = tdx_module_setup();
+		if (ret)
+			return ret;
+		return -EOPNOTSUPP;	/* Not ready to create guest TD yet. */
+	}
+
+	return vmx_vm_init(kvm);
+}
+
 struct kvm_x86_ops vt_x86_ops __initdata = {
 	.name = "kvm_intel",
 
@@ -29,9 +49,9 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.cpu_has_accelerated_tpr = report_flexpriority,
 	.has_emulated_msr = vmx_has_emulated_msr,
 
-	.is_vm_type_supported = vmx_is_vm_type_supported,
+	.is_vm_type_supported = vt_is_vm_type_supported,
 	.vm_size = sizeof(struct kvm_vmx),
-	.vm_init = vmx_vm_init,
+	.vm_init = vt_vm_init,
 
 	.vcpu_create = vmx_vcpu_create,
 	.vcpu_free = vmx_vcpu_free,
arch/x86/kvm/vmx/tdx.c +5 -0
index 8adc87ad1807..e8d293a3c11c 100644
@@ -105,6 +105,11 @@ int tdx_module_setup(void)
 	return ret;
 }
 
+bool tdx_is_vm_type_supported(unsigned long type)
+{
+	return type == KVM_X86_TDX_VM && READ_ONCE(enable_tdx);
+}
+
 static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 {
 	u32 max_pa;
arch/x86/kvm/vmx/vmx.c +0 -5
index 3c7b3f245fee..7838cd177f0e 100644
@@ -7079,11 +7079,6 @@ int vmx_vcpu_create(struct kvm_vcpu *vcpu)
 	return err;
 }
 
-bool vmx_is_vm_type_supported(unsigned long type)
-{
-	return type == KVM_X86_DEFAULT_VM;
-}
-
 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
 
arch/x86/kvm/vmx/x86_ops.h +2 -1
index f7327bc73be0..78331dbc29f7 100644
@@ -25,7 +25,6 @@ void vmx_hardware_unsetup(void);
 int vmx_hardware_enable(void);
 void vmx_hardware_disable(void);
 bool report_flexpriority(void);
-bool vmx_is_vm_type_supported(unsigned long type);
 int vmx_vm_init(struct kvm *kvm);
 int vmx_vcpu_create(struct kvm_vcpu *vcpu);
 int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu);
@@ -130,10 +129,12 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 #ifdef CONFIG_INTEL_TDX_HOST
 void __init tdx_pre_kvm_init(unsigned int *vcpu_size,
 			unsigned int *vcpu_align, unsigned int *vm_size);
+bool tdx_is_vm_type_supported(unsigned long type);
 void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 #else
 static inline void tdx_pre_kvm_init(
 	unsigned int *vcpu_size, unsigned int *vcpu_align, unsigned int *vm_size) {}
+static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
 static inline void tdx_hardware_setup(struct kvm_x86_ops *x86_ops) {}
 #endif
 
#6 lore raw

Re: [RFC PATCH v5 003/104] KVM: TDX: Detect CPU feature on kernel module initialization

In reply to Paolo Bonzini

Thanks for comment.

Quoted 11 lines · Paolo Bonzini
Quoted 10 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

(quoted diff) +9 -0
+static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	u32 max_pa;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
Quoted 8 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+	if (!platform_has_tdx()) {
+		pr_warn("Cannot enable TDX with SEAMRR disabled\n");
+		return -ENODEV;
+	}

This will cause a pr_warn in the logs on all machines that don't have TDX. Perhaps you can restrict the pr_warn() to machines that have __seamrr_enabled() == true?

Makes sense. I'll include the following change.

arch/x86/include/asm/tdx.h +2 -0
index 73bb472bd515..aa02c98afd11 100644
@@ -134,6 +134,7 @@ struct tdsysinfo_struct {
        };
 } __packed __aligned(TDSYSINFO_STRUCT_ALIGNMENT);
 
+bool __seamrr_enabled(void);
 void tdx_detect_cpu(struct cpuinfo_x86 *c);
 int tdx_detect(void);
 int tdx_init(void);
@@ -143,6 +144,7 @@ u32 tdx_get_global_keyid(void);
 int tdx_keyid_alloc(void);
 void tdx_keyid_free(int keyid);
 #else
+static inline bool __seamrr_enabled(void) { return false; }
 static inline void tdx_detect_cpu(struct cpuinfo_x86 *c) { }
 static inline int tdx_detect(void) { return -ENODEV; }
 static inline int tdx_init(void) { return -ENODEV; }
arch/x86/kvm/vmx/tdx.c +2 -1
index 66dffe815e63..880d8291b380 100644
@@ -2625,7 +2625,8 @@ static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
        }
 
        if (!platform_has_tdx()) {
-               pr_warn("Cannot enable TDX with SEAMRR disabled\n");
+               if (__seamrr_enabled())
+                       pr_warn("Cannot enable TDX with SEAMRR disabled\n");
                return -ENODEV;
        }
 
arch/x86/virt/vmx/tdx.c +2 -1
index d99961b7cb02..bb578a72b2da 100644
@@ -186,10 +186,11 @@ static const struct kernel_param_ops tdx_trace_ops = {
 module_param_cb(tdx_trace_level, &tdx_trace_ops, &tdx_trace_level, 0644);
 MODULE_PARM_DESC(tdx_trace_level, "TDX module trace level");
 
-static bool __seamrr_enabled(void)
+bool __seamrr_enabled(void)
 {
        return (seamrr_mask & SEAMRR_ENABLED_BITS) == SEAMRR_ENABLED_BITS;
 }
+EXPORT_SYMBOL_GPL(__seamrr_enabled);
 
 static void detect_seam_bsp(struct cpuinfo_x86 *c)
 {
Signature · 1 line
Isaku Yamahata <[email protected]>
#12 lore raw

Re: [RFC PATCH v5 005/104] KVM: x86: Refactor KVM VMX module init/exit functions

In reply to Paolo Bonzini

Thanks for review.

Quoted 13 lines · Paolo Bonzini

arch/x86/kvm/vmx/vmx.c static void vmx_cleanup_l1d_flush(void) · line 7937

Quoted 7 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/vmx.c +4 -3
-static int __init vmx_init(void)
-{
-	int r, cpu;
+	if (sizeof(struct vcpu_vmx) > *vcpu_size)
+		*vcpu_size = sizeof(struct vcpu_vmx);
+	if (__alignof__(struct vcpu_vmx) > *vcpu_align)
+		*vcpu_align = __alignof__(struct vcpu_vmx);

Please keep these four lines in vt_init, and rename the rest of vmx_pre_kvm_init to hv_vp_assist_page_init. Likewise, rename vmx_post_kvm_exit to hv_vp_assist_page_exit.

Quoted 2 lines

Adjusting the vcpu_size and vcpu_align for TDX (I guess) can be added later when TDX ops are introduced.

sure. I'll make it like
vcpu_size = max(sizeof(struct vcpu_vmx), sizeof(vcpu_tdx));
...

Thanks,

Signature · 1 line
Isaku Yamahata <[email protected]>
#20 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to Paolo Bonzini
Quoted 11 lines · Paolo Bonzini

arch/x86/kvm/vmx/tdx.c line 97

Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	if (!tdx_module_initialized) {
+		if (enable_tdx) {
+			ret = __tdx_module_setup();
+			if (ret)
+				enable_tdx = false;

"enable_tdx = false" isn't great to do only when a VM is created. Does it make sense to anticipate this to the point when the kvm_intel.ko module is loaded?

It's possible. I have the following two reasons to chose to defer TDX module initialization until creating first TD. Given those reasons, do you still want the initialization at loading kvm_intel.ko module? If yes, I'll change it.

- memory over head: The initialization of TDX module requires to allocate physically contiguous memory whose size is about 0.43% of the system memory. If user don't use TD, it will be wasted.

- VMXON on all pCPUs: The TDX module initialization requires to enable VMX (VMXON) on all present pCPUs. vmx_hardware_enable() which is called on creating guest does it. It naturally fits with the TDX module initialization at creating first TD. I wanted to avoid code to enable VMXON on loading the kvm_intel.ko.

Signature · 1 line
Isaku Yamahata <[email protected]>
#36 lore raw

Re: [RFC PATCH v5 010/104] KVM: TDX: Make TDX VM type supported

In reply to Kai Huang
Quoted 9 lines · Kai Huang
Quoted 7 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

As first step TDX VM support, return that TDX VM type supported to device model, e.g. qemu. The callback to create guest TD is vm_init callback for KVM_CREATE_VM. Add a place holder function and call a function to initialize TDX module on demand because in that callback VMX is enabled by hardware_enable callback (vmx_hardware_enable).

Quoted 4 lines

Should we put this patch at the end of series until all changes required to run TD are introduced? This patch essentially tells userspace KVM is ready to support a TD but actually it's not ready. And this might also cause bisect issue I suppose?

The intention is that developers can exercise the new code step-by-step even if the TDX KVM isn't complete.
How about introducing new config and remove it at the last of the patch series?

arch/x86/kvm/Kconfig +14 -0
index 2b1548da00eb..a3287440aa9e 100644
@@ -98,6 +98,20 @@ config X86_SGX_KVM
 
          If unsure, say N.
 
+config X86_TDX_KVM_EXPERIMENTAL
+       bool "EXPERIMENTAL Trust Domian Extensions (TDX) KVM support"
+       default n
+       depends on INTEL_TDX_HOST
+       depends on KVM_INTEL
+       help
+         Enable experimental TDX KVM support.  TDX KVM needs many patches and
+         the patches will be merged step by step, not at once. Even if TDX KVM
+         support is incomplete, enable TDX KVM support so that developper can
+         exercise TDX KVM code.  TODO: Remove this configuration once the
+         (first step of) TDX KVM support is complete.
+
+         If unsure, say N.
+
 config KVM_AMD
        tristate "KVM for AMD processors support"
        depends on KVM
arch/x86/kvm/vmx/tdx.c +4 -0
index b16e2ed3b204..e31d6902e49c 100644
@@ -170,7 +170,11 @@ int tdx_module_setup(void)
 
 bool tdx_is_vm_type_supported(unsigned long type)
 {
+#ifdef CONFIG_X86_TDX_KVM_EXPERIMENTAL
        return type == KVM_X86_TDX_VM && READ_ONCE(enable_tdx);
+#else
+       return false;
+#endif
 }
 
 static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
Signature · 1 line
Isaku Yamahata <[email protected]>
#37 lore raw

Re: [RFC PATCH v5 010/104] KVM: TDX: Make TDX VM type supported

Quoted 12 lines · Isaku Yamahata
Quoted 9 lines · Kai Huang
Quoted 7 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

As first step TDX VM support, return that TDX VM type supported to device model, e.g. qemu. The callback to create guest TD is vm_init callback for KVM_CREATE_VM. Add a place holder function and call a function to initialize TDX module on demand because in that callback VMX is enabled by hardware_enable callback (vmx_hardware_enable).

Quoted 7 lines
Quoted 4 lines

Should we put this patch at the end of series until all changes required to run TD are introduced? This patch essentially tells userspace KVM is ready to support a TD but actually it's not ready. And this might also cause bisect issue I suppose?

The intention is that developers can exercise the new code step-by-step even if the TDX KVM isn't complete.

What is the purpose/value to allow developers to exercise the new code step-by- step? Userspace cannot create TD successfully anyway until all patches are ready.

Signature · 2 lines
Thanks,
-Kai
maintainer
#38 lore raw

Re: [RFC PATCH v5 010/104] KVM: TDX: Make TDX VM type supported

Quoted 5 lines · Kai Huang
Quoted 2 lines

The intention is that developers can exercise the new code step-by-step even if the TDX KVM isn't complete.

What is the purpose/value to allow developers to exercise the new code step-by- step? Userspace cannot create TD successfully anyway until all patches are ready.

We can move this to the end when the patch is committed, but I think there is value in showing that the series works (for partial definitions of "work") at every step of the enablement process.

Paolo

#239 lore raw

Re: [RFC PATCH v5 083/104] KVM: x86: Split core of hypercall emulation to helper function

In reply to [email protected]
Quoted 91 lines · On Fri, Mar 4, 2022 at 12:00 PM <[email protected]> wrote:

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
index 8dab9f16f559..33b75b0e3de1 100644
@@ -1818,6 +1818,10 @@ void kvm_request_apicv_update(struct kvm *kvm, bool activate,
 void __kvm_request_apicv_update(struct kvm *kvm, bool activate,
                                unsigned long bit);
 
+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 +16 -21
index 314ae43e07bf..9acb33a17445 100644
@@ -9090,26 +9090,15 @@ static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
        return kvm_skip_emulated_instruction(vcpu);
 }
 
-int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
+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)
 {
-       unsigned long nr, a0, a1, a2, a3, ret;
-       int op_64_bit;
-
-       if (kvm_xen_hypercall_enabled(vcpu->kvm))
-               return kvm_xen_hypercall(vcpu);
-
-       if (kvm_hv_hypercall_enabled(vcpu))
-               return kvm_hv_hypercall(vcpu);
-
-       nr = kvm_rax_read(vcpu);
-       a0 = kvm_rbx_read(vcpu);
-       a1 = kvm_rcx_read(vcpu);
-       a2 = kvm_rdx_read(vcpu);
-       a3 = kvm_rsi_read(vcpu);
+       unsigned long ret;
 
        trace_kvm_hypercall(nr, a0, a1, a2, a3);
 
-       op_64_bit = is_64_bit_hypercall(vcpu);
        if (!op_64_bit) {
                nr &= 0xFFFFFFFF;
                a0 &= 0xFFFFFFFF;
@@ -9118,11 +9107,6 @@ int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
                a3 &= 0xFFFFFFFF;
        }
 
-       if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
-               ret = -KVM_EPERM;
-               goto out;
-       }
-
        ret = -KVM_ENOSYS;
 
        switch (nr) {
@@ -9181,6 +9165,34 @@ int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
                ret = -KVM_ENOSYS;
                break;
        }
+       return ret;
+}
+EXPORT_SYMBOL_GPL(__kvm_emulate_hypercall);
+
+int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
+{
+       unsigned long nr, a0, a1, a2, a3, ret;
+       int op_64_bit;
+
+       if (kvm_xen_hypercall_enabled(vcpu->kvm))
+               return kvm_xen_hypercall(vcpu);

arch/x86/kvm/x86.c int kvm_emulate_hypercall(struct kvm_vcpu *vcpu) · line 9188

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+
+       if (kvm_hv_hypercall_enabled(vcpu))
+               return kvm_hv_hypercall(vcpu);
+
+       nr = kvm_rax_read(vcpu);
+       a0 = kvm_rbx_read(vcpu);
+       a1 = kvm_rcx_read(vcpu);
+       a2 = kvm_rdx_read(vcpu);
+       a3 = kvm_rsi_read(vcpu);
+       op_64_bit = is_64_bit_mode(vcpu);

I think this should be "op_64_bit = is_64_bit_hypercall(vcpu);" is_64_bit_mode was replaced with is_64_bit_hypercall to support protected guests here:
https://lore.kernel.org/all/[email protected]/T/

Without it, op_64_bit will be set to 0 for TD VMs which will cause the upper 32 bit of the registers to be cleared in __kvm_emulate_hypercall

Quoted 11 lines
arch/x86/kvm/x86.c +7 -1
+
+       if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
+               ret = -KVM_EPERM;
+               goto out;
+       }
+
+       ret = __kvm_emulate_hypercall(vcpu, nr, a0, a1, a2, a3, op_64_bit);
 out:
        if (!op_64_bit)
                ret = (u32)ret;
--
Quoted 2 lines

2.25.1

Sagi

#196 lore raw

Re: [RFC PATCH v5 064/104] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to [email protected]
Quoted 88 lines · On Fri, Mar 4, 2022 at 11:50 AM <[email protected]> wrote:

From: Isaku Yamahata <[email protected]>

This patch implements running TDX vcpu. Once vcpu runs on the logical processor (LP), the TDX vcpu is associated with it. When the TDX vcpu moves to another LP, the TDX vcpu needs to flush its status on the LP. When destroying TDX vcpu, it needs to complete flush and flush cpu memory cache. Track which LP the TDX vcpu run and flush it as necessary.

Do nothing on sched_in event as TDX doesn't support pause loop.

TDX vcpu execution requires restoring PMU debug store after returning back to KVM because the TDX module unconditionally resets the value. To reuse the existing code, export perf_restore_debug_store.

---
 arch/x86/kvm/vmx/main.c    | 10 +++++++++-
 arch/x86/kvm/vmx/tdx.c     | 34 ++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h     | 33 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h |  2 ++
 arch/x86/kvm/x86.c         |  1 +
 5 files changed, 79 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/main.c +9 -1
index f571b07c2aae..2e5a7a72d560 100644
@@ -89,6 +89,14 @@ static void vt_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
        return vmx_vcpu_reset(vcpu, init_event);
 }
 
+static fastpath_t vt_vcpu_run(struct kvm_vcpu *vcpu)
+{
+       if (is_td_vcpu(vcpu))
+               return tdx_vcpu_run(vcpu);
+
+       return vmx_vcpu_run(vcpu);
+}
+
 static void vt_flush_tlb_all(struct kvm_vcpu *vcpu)
 {
        if (is_td_vcpu(vcpu))
@@ -200,7 +208,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
        .tlb_flush_guest = vt_flush_tlb_guest,
 
        .vcpu_pre_run = vmx_vcpu_pre_run,
-       .run = vmx_vcpu_run,
+       .run = vt_vcpu_run,
        .handle_exit = vmx_handle_exit,
        .skip_emulated_instruction = vmx_skip_emulated_instruction,
        .update_emulated_instruction = vmx_update_emulated_instruction,
arch/x86/kvm/vmx/tdx.c +21 -0
index 85d5f961d97e..ebe4f9bf19e7 100644
@@ -10,6 +10,9 @@
 #include "vmx.h"
 #include "x86.h"
 
+#include <trace/events/kvm.h>
+#include "trace.h"
+
 #undef pr_fmt
 #define pr_fmt(fmt) "tdx: " fmt
 
@@ -509,6 +512,37 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
        vcpu->kvm->vm_bugged = true;
 }
 
+u64 __tdx_vcpu_run(hpa_t tdvpr, void *regs, u32 regs_mask);
+
+static noinstr void tdx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
+                                       struct vcpu_tdx *tdx)
+{
+       guest_enter_irqoff();
+       tdx->exit_reason.full = __tdx_vcpu_run(tdx->tdvpr.pa, vcpu->arch.regs, 0);
+       guest_exit_irqoff();
+}
+
+fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
+{
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+       if (unlikely(vcpu->kvm->vm_bugged)) {
+               tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
+               return EXIT_FASTPATH_NONE;
+       }

arch/x86/kvm/vmx/tdx.c void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) · line 542

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+       trace_kvm_entry(vcpu);
+
+       tdx_vcpu_enter_exit(vcpu, tdx);
+
+       vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
+       trace_kvm_exit(vcpu, KVM_ISA_VMX);
+
+       if (tdx->exit_reason.error || tdx->exit_reason.non_recoverable)
+               return EXIT_FASTPATH_NONE;

Looks like the above if statement has no effect. Just checking if this is intentional.

Quoted 91 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+       return EXIT_FASTPATH_NONE;
+}
+
 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/tdx.h +33 -0
index bf9865a88991..e950404ce5de 100644
@@ -44,12 +44,45 @@ struct kvm_tdx {
        spinlock_t seamcall_lock;
 };
 
+union tdx_exit_reason {
+       struct {
+               /* 31:0 mirror the VMX Exit Reason format */
+               u64 basic               : 16;
+               u64 reserved16          : 1;
+               u64 reserved17          : 1;
+               u64 reserved18          : 1;
+               u64 reserved19          : 1;
+               u64 reserved20          : 1;
+               u64 reserved21          : 1;
+               u64 reserved22          : 1;
+               u64 reserved23          : 1;
+               u64 reserved24          : 1;
+               u64 reserved25          : 1;
+               u64 bus_lock_detected   : 1;
+               u64 enclave_mode        : 1;
+               u64 smi_pending_mtf     : 1;
+               u64 smi_from_vmx_root   : 1;
+               u64 reserved30          : 1;
+               u64 failed_vmentry      : 1;
+
+               /* 63:32 are TDX specific */
+               u64 details_l1          : 8;
+               u64 class               : 8;
+               u64 reserved61_48       : 14;
+               u64 non_recoverable     : 1;
+               u64 error               : 1;
+       };
+       u64 full;
+};
+
 struct vcpu_tdx {
        struct kvm_vcpu vcpu;
 
        struct tdx_td_page tdvpr;
        struct tdx_td_page *tdvpx;
 
+       union tdx_exit_reason exit_reason;
+
        bool initialized;
 };
 
arch/x86/kvm/vmx/x86_ops.h +2 -0
index 922a3799336e..44404dd25737 100644
@@ -140,6 +140,7 @@ void tdx_vm_free(struct kvm *kvm);
 int tdx_vcpu_create(struct kvm_vcpu *vcpu);
 void tdx_vcpu_free(struct kvm_vcpu *vcpu);
 void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
+fastpath_t tdx_vcpu_run(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);
@@ -160,6 +161,7 @@ static inline void tdx_vm_free(struct kvm *kvm) {}
 static inline int tdx_vcpu_create(struct kvm_vcpu *vcpu) { return -EOPNOTSUPP; }
 static inline void tdx_vcpu_free(struct kvm_vcpu *vcpu) {}
 static inline void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) {}
+static inline fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu) { return EXIT_FASTPATH_NONE; }
 
 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 +1 -1
index da411bcd8cbc..66400810d54f 100644
@@ -300,6 +300,7 @@ const struct kvm_stats_header kvm_vcpu_stats_header = {
 };
 
 u64 __read_mostly host_xcr0;
+EXPORT_SYMBOL_GPL(host_xcr0);
 u64 __read_mostly supported_xcr0;
 EXPORT_SYMBOL_GPL(supported_xcr0);
 
--

2.25.1

#215 lore raw

Re: [RFC PATCH v5 073/104] KVM: TDX: track LP tdx vcpu run and teardown vcpus on descroing the guest TD

In reply to [email protected]
Quoted 119 lines · On Fri, Mar 4, 2022 at 11:50 AM <[email protected]> wrote:

From: Isaku Yamahata <[email protected]>

When shutting down the machine, (VMX or TDX) vcpus needs to be shutdown on each pcpu. Do the similar for TDX with TDX SEAMCALL APIs.

---
 arch/x86/kvm/vmx/main.c    | 23 +++++++++++--
 arch/x86/kvm/vmx/tdx.c     | 70 ++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.h     |  2 ++
 arch/x86/kvm/vmx/x86_ops.h |  4 +++
 4 files changed, 95 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +21 -2
index 2cd5ba0e8788..882358ac270b 100644
@@ -13,6 +13,25 @@ static bool vt_is_vm_type_supported(unsigned long type)
        return type == KVM_X86_DEFAULT_VM || tdx_is_vm_type_supported(type);
 }
 
+static int vt_hardware_enable(void)
+{
+       int ret;
+
+       ret = vmx_hardware_enable();
+       if (ret)
+               return ret;
+
+       tdx_hardware_enable();
+       return 0;
+}
+
+static void vt_hardware_disable(void)
+{
+       /* Note, TDX *and* VMX need to be disabled if TDX is enabled. */
+       tdx_hardware_disable();
+       vmx_hardware_disable();
+}
+
 static __init int vt_hardware_setup(void)
 {
        int ret;
@@ -199,8 +218,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
        .hardware_unsetup = vt_hardware_unsetup,
 
-       .hardware_enable = vmx_hardware_enable,
-       .hardware_disable = vmx_hardware_disable,
+       .hardware_enable = vt_hardware_enable,
+       .hardware_disable = vt_hardware_disable,
        .cpu_has_accelerated_tpr = report_flexpriority,
        .has_emulated_msr = vmx_has_emulated_msr,
 
arch/x86/kvm/vmx/tdx.c +28 -0
index a6b1a8ce888d..690298fb99c7 100644
@@ -48,6 +48,14 @@ struct tdx_capabilities tdx_caps;
 static DEFINE_MUTEX(tdx_lock);
 static struct mutex *tdx_mng_key_config_lock;
 
+/*
+ * A per-CPU list of TD vCPUs associated with a given CPU.  Used when a CPU
+ * is brought down to invoke TDH_VP_FLUSH on the approapriate TD vCPUS.
+ * Protected by interrupt mask.  This list is manipulated in process context
+ * of vcpu and IPI callback.  See tdx_flush_vp_on_cpu().
+ */
+static DEFINE_PER_CPU(struct list_head, associated_tdvcpus);
+
 static u64 hkid_mask __ro_after_init;
 static u8 hkid_start_pos __ro_after_init;
 
@@ -87,6 +95,8 @@ static inline bool is_td_finalized(struct kvm_tdx *kvm_tdx)
 
 static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
 {
+       list_del(&to_tdx(vcpu)->cpu_list);
+
        /*
         * Ensure tdx->cpu_list is updated is before setting vcpu->cpu to -1,
         * otherwise, a different CPU can see vcpu->cpu = -1 and add the vCPU
@@ -97,6 +107,22 @@ static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
        vcpu->cpu = -1;
 }
 
+void tdx_hardware_enable(void)
+{
+       INIT_LIST_HEAD(&per_cpu(associated_tdvcpus, raw_smp_processor_id()));
+}
+
+void tdx_hardware_disable(void)
+{
+       int cpu = raw_smp_processor_id();
+       struct list_head *tdvcpus = &per_cpu(associated_tdvcpus, cpu);
+       struct vcpu_tdx *tdx, *tmp;
+
+       /* Safe variant needed as tdx_disassociate_vp() deletes the entry. */
+       list_for_each_entry_safe(tdx, tmp, tdvcpus, cpu_list)
+               tdx_disassociate_vp(&tdx->vcpu);
+}
+
 static void tdx_clear_page(unsigned long page)
 {
        const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
@@ -230,9 +256,11 @@ void tdx_mmu_prezap(struct kvm *kvm)
        struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
        cpumask_var_t packages;
        bool cpumask_allocated;
+       struct kvm_vcpu *vcpu;
        u64 err;
        int ret;
        int i;
+       unsigned long j;
 
        if (!is_hkid_assigned(kvm_tdx))
                return;

arch/x86/kvm/vmx/tdx.c void tdx_mmu_prezap(struct kvm *kvm) · line 283

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +5 -0
@@ -248,6 +276,17 @@ void tdx_mmu_prezap(struct kvm *kvm)
                return;
        }
 
+       kvm_for_each_vcpu(j, vcpu, kvm)
+               tdx_flush_vp_on_cpu(vcpu);
+
+       mutex_lock(&tdx_lock);
+       err = tdh_mng_vpflushdone(kvm_tdx->tdr.pa);

Hi Isaku,

I am wondering about the impact of the failures on these functions. Is there any other function which recovers any failures here? When I look at the tdx_flush_vp function, it seems like it can fail due to task migration so tdx_flush_vp_on_cpu might also fail and if it fails, tdh_mng_vpflushdone returns err. Since tdx_vm_teardown does not return any error , how the VMM can free the keyid used in this TD. Will they be forever in "used state"?
Also if tdx_vm_teardown fails, the kvm_tdx->hkid is never set to -1 which will prevent tdx_vcpu_free to free and reclaim the resources allocated for the vcpu.

-Erdem

Quoted 92 lines
arch/x86/kvm/vmx/tdx.c +35 -2
+       mutex_unlock(&tdx_lock);
+       if (WARN_ON_ONCE(err)) {
+               pr_tdx_error(TDH_MNG_VPFLUSHDONE, err, NULL);
+               return;
+       }
+
        cpumask_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
        for_each_online_cpu(i) {
                if (cpumask_allocated &&
@@ -472,8 +511,22 @@ int tdx_vcpu_create(struct kvm_vcpu *vcpu)
 
 void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 {
-       if (vcpu->cpu != cpu)
-               tdx_flush_vp_on_cpu(vcpu);
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+       if (vcpu->cpu == cpu)
+               return;
+
+       tdx_flush_vp_on_cpu(vcpu);
+
+       local_irq_disable();
+       /*
+        * Pairs with the smp_wmb() in tdx_disassociate_vp() to ensure
+        * vcpu->cpu is read before tdx->cpu_list.
+        */
+       smp_rmb();
+
+       list_add(&tdx->cpu_list, &per_cpu(associated_tdvcpus, cpu));
+       local_irq_enable();
 }
 
 void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
@@ -522,6 +575,19 @@ void tdx_vcpu_free(struct kvm_vcpu *vcpu)
                tdx_reclaim_td_page(&tdx->tdvpx[i]);
        kfree(tdx->tdvpx);
        tdx_reclaim_td_page(&tdx->tdvpr);
+
+       /*
+        * kvm_free_vcpus()
+        *   -> kvm_unload_vcpu_mmu()
+        *
+        * does vcpu_load() for every vcpu after they already disassociated
+        * from the per cpu list when tdx_vm_teardown(). So we need to
+        * disassociate them again, otherwise the freed vcpu data will be
+        * accessed when do list_{del,add}() on associated_tdvcpus list
+        * later.
+        */
+       tdx_flush_vp_on_cpu(vcpu);
+       WARN_ON(vcpu->cpu != -1);
 }
 
 void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
arch/x86/kvm/vmx/tdx.h +2 -0
index 8b1cf9c158e3..180360a65545 100644
@@ -81,6 +81,8 @@ struct vcpu_tdx {
        struct tdx_td_page tdvpr;
        struct tdx_td_page *tdvpx;
 
+       struct list_head cpu_list;
+
        union tdx_exit_reason exit_reason;
 
        bool initialized;
arch/x86/kvm/vmx/x86_ops.h +4 -1
index ceafd6e18f4e..aae0f4449ec5 100644
@@ -132,6 +132,8 @@ void __init tdx_pre_kvm_init(unsigned int *vcpu_size,
 bool tdx_is_vm_type_supported(unsigned long type);
 void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 void tdx_hardware_unsetup(void);
+void tdx_hardware_enable(void);
+void tdx_hardware_disable(void);
 
 int tdx_vm_init(struct kvm *kvm);
 void tdx_mmu_prezap(struct kvm *kvm);
@@ -156,6 +158,8 @@ static inline void tdx_pre_kvm_init(
 static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
 static inline void tdx_hardware_setup(struct kvm_x86_ops *x86_ops) {}
 static inline void tdx_hardware_unsetup(void) {}
+static inline void tdx_hardware_enable(void) {}
+static inline void tdx_hardware_disable(void) {}
 
 static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
 static inline void tdx_mmu_prezap(struct kvm *kvm) {}
--

2.25.1

#240 lore raw

Re: [RFC PATCH v5 083/104] KVM: x86: Split core of hypercall emulation to helper function

In reply to Sagi Shahar
Quoted 79 lines · Sagi Shahar
Quoted 63 lines
arch/x86/kvm/x86.c +16 -21
index 314ae43e07bf..9acb33a17445 100644
@@ -9090,26 +9090,15 @@ static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
        return kvm_skip_emulated_instruction(vcpu);
 }
 
-int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
+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)
 {
-       unsigned long nr, a0, a1, a2, a3, ret;
-       int op_64_bit;
-
-       if (kvm_xen_hypercall_enabled(vcpu->kvm))
-               return kvm_xen_hypercall(vcpu);
-
-       if (kvm_hv_hypercall_enabled(vcpu))
-               return kvm_hv_hypercall(vcpu);
-
-       nr = kvm_rax_read(vcpu);
-       a0 = kvm_rbx_read(vcpu);
-       a1 = kvm_rcx_read(vcpu);
-       a2 = kvm_rdx_read(vcpu);
-       a3 = kvm_rsi_read(vcpu);
+       unsigned long ret;
 
        trace_kvm_hypercall(nr, a0, a1, a2, a3);
 
-       op_64_bit = is_64_bit_hypercall(vcpu);
        if (!op_64_bit) {
                nr &= 0xFFFFFFFF;
                a0 &= 0xFFFFFFFF;
@@ -9118,11 +9107,6 @@ int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
                a3 &= 0xFFFFFFFF;
        }
 
-       if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
-               ret = -KVM_EPERM;
-               goto out;
-       }
-
        ret = -KVM_ENOSYS;
 
        switch (nr) {
@@ -9181,6 +9165,34 @@ int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
                ret = -KVM_ENOSYS;
                break;
        }
+       return ret;
+}
+EXPORT_SYMBOL_GPL(__kvm_emulate_hypercall);
+
+int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
+{
+       unsigned long nr, a0, a1, a2, a3, ret;
+       int op_64_bit;
+
+       if (kvm_xen_hypercall_enabled(vcpu->kvm))
+               return kvm_xen_hypercall(vcpu);

arch/x86/kvm/x86.c int kvm_emulate_hypercall(struct kvm_vcpu *vcpu) · line 9188

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+
+       if (kvm_hv_hypercall_enabled(vcpu))
+               return kvm_hv_hypercall(vcpu);
+
+       nr = kvm_rax_read(vcpu);
+       a0 = kvm_rbx_read(vcpu);
+       a1 = kvm_rcx_read(vcpu);
+       a2 = kvm_rdx_read(vcpu);
+       a3 = kvm_rsi_read(vcpu);
+       op_64_bit = is_64_bit_mode(vcpu);

I think this should be "op_64_bit = is_64_bit_hypercall(vcpu);" is_64_bit_mode was replaced with is_64_bit_hypercall to support protected guests here:
https://lore.kernel.org/all/[email protected]/T/

Quoted 2 lines

Without it, op_64_bit will be set to 0 for TD VMs which will cause the upper 32 bit of the registers to be cleared in __kvm_emulate_hypercall

Oops, thanks for pointing it out. I'll fix it up with next respin.

Signature · 1 line
Isaku Yamahata <[email protected]>
#197 lore raw

Re: [RFC PATCH v5 064/104] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to Erdem Aktas
Quoted 28 lines · Erdem Aktas
Quoted 27 lines · On Fri, Mar 4, 2022 at 11:50 AM <[email protected]> wrote:
arch/x86/kvm/vmx/tdx.c +23 -0
@@ -509,6 +512,37 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
        vcpu->kvm->vm_bugged = true;
 }
 
+u64 __tdx_vcpu_run(hpa_t tdvpr, void *regs, u32 regs_mask);
+
+static noinstr void tdx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
+                                       struct vcpu_tdx *tdx)
+{
+       guest_enter_irqoff();
+       tdx->exit_reason.full = __tdx_vcpu_run(tdx->tdvpr.pa, vcpu->arch.regs, 0);
+       guest_exit_irqoff();
+}
+
+fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
+{
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+       if (unlikely(vcpu->kvm->vm_bugged)) {
+               tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
+               return EXIT_FASTPATH_NONE;
+       }
+
+       trace_kvm_entry(vcpu);
+
+       tdx_vcpu_enter_exit(vcpu, tdx);
+
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) · line 542

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+       vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
+       trace_kvm_exit(vcpu, KVM_ISA_VMX);
+
+       if (tdx->exit_reason.error || tdx->exit_reason.non_recoverable)
+               return EXIT_FASTPATH_NONE;

Looks like the above if statement has no effect. Just checking if this is intentional.

I'm not sure if I get your point. tdx->exit_reason is updated by the above tdx_cpu_enter_exit(). So it makes sense to check .error or .non_recoverable.

Signature · 1 line
Isaku Yamahata <[email protected]>
#216 lore raw

Re: [RFC PATCH v5 073/104] KVM: TDX: track LP tdx vcpu run and teardown vcpus on descroing the guest TD

In reply to Erdem Aktas
Quoted 68 lines · Erdem Aktas
Quoted 67 lines · On Fri, Mar 4, 2022 at 11:50 AM <[email protected]> wrote:
arch/x86/kvm/vmx/tdx.c +28 -0
index a6b1a8ce888d..690298fb99c7 100644
@@ -48,6 +48,14 @@ struct tdx_capabilities tdx_caps;
 static DEFINE_MUTEX(tdx_lock);
 static struct mutex *tdx_mng_key_config_lock;
 
+/*
+ * A per-CPU list of TD vCPUs associated with a given CPU.  Used when a CPU
+ * is brought down to invoke TDH_VP_FLUSH on the approapriate TD vCPUS.
+ * Protected by interrupt mask.  This list is manipulated in process context
+ * of vcpu and IPI callback.  See tdx_flush_vp_on_cpu().
+ */
+static DEFINE_PER_CPU(struct list_head, associated_tdvcpus);
+
 static u64 hkid_mask __ro_after_init;
 static u8 hkid_start_pos __ro_after_init;
 
@@ -87,6 +95,8 @@ static inline bool is_td_finalized(struct kvm_tdx *kvm_tdx)
 
 static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
 {
+       list_del(&to_tdx(vcpu)->cpu_list);
+
        /*
         * Ensure tdx->cpu_list is updated is before setting vcpu->cpu to -1,
         * otherwise, a different CPU can see vcpu->cpu = -1 and add the vCPU
@@ -97,6 +107,22 @@ static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
        vcpu->cpu = -1;
 }
 
+void tdx_hardware_enable(void)
+{
+       INIT_LIST_HEAD(&per_cpu(associated_tdvcpus, raw_smp_processor_id()));
+}
+
+void tdx_hardware_disable(void)
+{
+       int cpu = raw_smp_processor_id();
+       struct list_head *tdvcpus = &per_cpu(associated_tdvcpus, cpu);
+       struct vcpu_tdx *tdx, *tmp;
+
+       /* Safe variant needed as tdx_disassociate_vp() deletes the entry. */
+       list_for_each_entry_safe(tdx, tmp, tdvcpus, cpu_list)
+               tdx_disassociate_vp(&tdx->vcpu);
+}
+
 static void tdx_clear_page(unsigned long page)
 {
        const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
@@ -230,9 +256,11 @@ void tdx_mmu_prezap(struct kvm *kvm)
        struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
        cpumask_var_t packages;
        bool cpumask_allocated;
+       struct kvm_vcpu *vcpu;
        u64 err;
        int ret;
        int i;
+       unsigned long j;
 
        if (!is_hkid_assigned(kvm_tdx))
                return;
@@ -248,6 +276,17 @@ void tdx_mmu_prezap(struct kvm *kvm)
                return;
        }
 
Quoted 7 lines

arch/x86/kvm/vmx/tdx.c void tdx_mmu_prezap(struct kvm *kvm) · line 283

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+       kvm_for_each_vcpu(j, vcpu, kvm)
+               tdx_flush_vp_on_cpu(vcpu);
+
+       mutex_lock(&tdx_lock);
+       err = tdh_mng_vpflushdone(kvm_tdx->tdr.pa);

Hi Isaku,

Hi.

Quoted 10 lines

I am wondering about the impact of the failures on these functions. Is there any other function which recovers any failures here? When I look at the tdx_flush_vp function, it seems like it can fail due to task migration so tdx_flush_vp_on_cpu might also fail and if it fails, tdh_mng_vpflushdone returns err. Since tdx_vm_teardown does not return any error , how the VMM can free the keyid used in this TD. Will they be forever in "used state"?
Also if tdx_vm_teardown fails, the kvm_tdx->hkid is never set to -1 which will prevent tdx_vcpu_free to free and reclaim the resources allocated for the vcpu.

mmu_prezap() is called via release callback of mmu notifier when the last mmu reference of this process is dropped. It is after all kvm vcpu fd and kvm vm fd were closed. vcpu will never run. But we still hold kvm_vcpu structures. There is no race between tdh_vp_flush()/tdh_mng_vpflushdone() here and process migration. tdh_vp_flush()/tdh_mng_vp_flushdone() should success.

The cpuid check in tdx_flush_vp() is for vcpu_load() which may race with process migration.

Anyway what if one of those TDX seamcalls fails? HKID is leaked and will be never used because there is no good way to free and use HKID safely. Such failure is due to unknown issue and probably a bug.

One mitigation is to add pr_err() when HKID leak happens. I'll add such message on next respin.

thanks,

Signature · 1 line
Isaku Yamahata <[email protected]>
#198 lore raw

Re: [RFC PATCH v5 064/104] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to Isaku Yamahata
Quoted 41 lines · Isaku Yamahata
Quoted 28 lines · Erdem Aktas
Quoted 27 lines · On Fri, Mar 4, 2022 at 11:50 AM <[email protected]> wrote:
arch/x86/kvm/vmx/tdx.c +23 -0
@@ -509,6 +512,37 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
        vcpu->kvm->vm_bugged = true;
 }
 
+u64 __tdx_vcpu_run(hpa_t tdvpr, void *regs, u32 regs_mask);
+
+static noinstr void tdx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
+                                       struct vcpu_tdx *tdx)
+{
+       guest_enter_irqoff();
+       tdx->exit_reason.full = __tdx_vcpu_run(tdx->tdvpr.pa, vcpu->arch.regs, 0);
+       guest_exit_irqoff();
+}
+
+fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
+{
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+       if (unlikely(vcpu->kvm->vm_bugged)) {
+               tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
+               return EXIT_FASTPATH_NONE;
+       }
+
+       trace_kvm_entry(vcpu);
+
+       tdx_vcpu_enter_exit(vcpu, tdx);
+
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) · line 542

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+       vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
+       trace_kvm_exit(vcpu, KVM_ISA_VMX);
+
+       if (tdx->exit_reason.error || tdx->exit_reason.non_recoverable)
+               return EXIT_FASTPATH_NONE;

Looks like the above if statement has no effect. Just checking if this is intentional.

Quoted 4 lines

I'm not sure if I get your point. tdx->exit_reason is updated by the above tdx_cpu_enter_exit(). So it makes sense to check .error or .non_recoverable. --
Isaku Yamahata <[email protected]>

What I mean is, if there is an error, it returns EXIT_FASTPATH_NONE but if there is no error, it still returns EXIT_FASTPATH_NONE.

The code is like below, the if-statement might be there as a placeholder to check errors but it has no impact on what is returned from this function.

       if (tdx->exit_reason.error || tdx->exit_reason.non_recoverable)
               return EXIT_FASTPATH_NONE;
       return EXIT_FASTPATH_NONE;
#217 lore raw

Re: [RFC PATCH v5 073/104] KVM: TDX: track LP tdx vcpu run and teardown vcpus on descroing the guest TD

In reply to Isaku Yamahata

So the tdh_vp_flush should always succeed while vm is being torn down. Thanks Isaku for the explanation, and I think it would be great to add the error message.

-Erdem

Quoted 113 lines · Isaku Yamahata
Quoted 68 lines · Erdem Aktas
Quoted 67 lines · On Fri, Mar 4, 2022 at 11:50 AM <[email protected]> wrote:
arch/x86/kvm/vmx/tdx.c +28 -0
index a6b1a8ce888d..690298fb99c7 100644
@@ -48,6 +48,14 @@ struct tdx_capabilities tdx_caps;
 static DEFINE_MUTEX(tdx_lock);
 static struct mutex *tdx_mng_key_config_lock;
 
+/*
+ * A per-CPU list of TD vCPUs associated with a given CPU.  Used when a CPU
+ * is brought down to invoke TDH_VP_FLUSH on the approapriate TD vCPUS.
+ * Protected by interrupt mask.  This list is manipulated in process context
+ * of vcpu and IPI callback.  See tdx_flush_vp_on_cpu().
+ */
+static DEFINE_PER_CPU(struct list_head, associated_tdvcpus);
+
 static u64 hkid_mask __ro_after_init;
 static u8 hkid_start_pos __ro_after_init;
 
@@ -87,6 +95,8 @@ static inline bool is_td_finalized(struct kvm_tdx *kvm_tdx)
 
 static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
 {
+       list_del(&to_tdx(vcpu)->cpu_list);
+
        /*
         * Ensure tdx->cpu_list is updated is before setting vcpu->cpu to -1,
         * otherwise, a different CPU can see vcpu->cpu = -1 and add the vCPU
@@ -97,6 +107,22 @@ static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
        vcpu->cpu = -1;
 }
 
+void tdx_hardware_enable(void)
+{
+       INIT_LIST_HEAD(&per_cpu(associated_tdvcpus, raw_smp_processor_id()));
+}
+
+void tdx_hardware_disable(void)
+{
+       int cpu = raw_smp_processor_id();
+       struct list_head *tdvcpus = &per_cpu(associated_tdvcpus, cpu);
+       struct vcpu_tdx *tdx, *tmp;
+
+       /* Safe variant needed as tdx_disassociate_vp() deletes the entry. */
+       list_for_each_entry_safe(tdx, tmp, tdvcpus, cpu_list)
+               tdx_disassociate_vp(&tdx->vcpu);
+}
+
 static void tdx_clear_page(unsigned long page)
 {
        const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
@@ -230,9 +256,11 @@ void tdx_mmu_prezap(struct kvm *kvm)
        struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
        cpumask_var_t packages;
        bool cpumask_allocated;
+       struct kvm_vcpu *vcpu;
        u64 err;
        int ret;
        int i;
+       unsigned long j;
 
        if (!is_hkid_assigned(kvm_tdx))
                return;
@@ -248,6 +276,17 @@ void tdx_mmu_prezap(struct kvm *kvm)
                return;
        }
 
Quoted 7 lines

arch/x86/kvm/vmx/tdx.c void tdx_mmu_prezap(struct kvm *kvm) · line 283

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+       kvm_for_each_vcpu(j, vcpu, kvm)
+               tdx_flush_vp_on_cpu(vcpu);
+
+       mutex_lock(&tdx_lock);
+       err = tdh_mng_vpflushdone(kvm_tdx->tdr.pa);

Hi Isaku,

Hi.

Quoted 10 lines

I am wondering about the impact of the failures on these functions. Is there any other function which recovers any failures here? When I look at the tdx_flush_vp function, it seems like it can fail due to task migration so tdx_flush_vp_on_cpu might also fail and if it fails, tdh_mng_vpflushdone returns err. Since tdx_vm_teardown does not return any error , how the VMM can free the keyid used in this TD. Will they be forever in "used state"?
Also if tdx_vm_teardown fails, the kvm_tdx->hkid is never set to -1 which will prevent tdx_vcpu_free to free and reclaim the resources allocated for the vcpu.

mmu_prezap() is called via release callback of mmu notifier when the last mmu reference of this process is dropped. It is after all kvm vcpu fd and kvm vm fd were closed. vcpu will never run. But we still hold kvm_vcpu structures. There is no race between tdh_vp_flush()/tdh_mng_vpflushdone() here and process migration. tdh_vp_flush()/tdh_mng_vp_flushdone() should success.

The cpuid check in tdx_flush_vp() is for vcpu_load() which may race with process migration.

Anyway what if one of those TDX seamcalls fails? HKID is leaked and will be never used because there is no good way to free and use HKID safely. Such failure is due to unknown issue and probably a bug.

One mitigation is to add pr_err() when HKID leak happens. I'll add such message on next respin.

thanks,
--
Isaku Yamahata <[email protected]>

#199 lore raw

Re: [RFC PATCH v5 064/104] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to Erdem Aktas
Quoted 51 lines · Erdem Aktas
Quoted 41 lines · Isaku Yamahata
Quoted 28 lines · Erdem Aktas
Quoted 27 lines · On Fri, Mar 4, 2022 at 11:50 AM <[email protected]> wrote:
arch/x86/kvm/vmx/tdx.c +23 -0
@@ -509,6 +512,37 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
        vcpu->kvm->vm_bugged = true;
 }
 
+u64 __tdx_vcpu_run(hpa_t tdvpr, void *regs, u32 regs_mask);
+
+static noinstr void tdx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
+                                       struct vcpu_tdx *tdx)
+{
+       guest_enter_irqoff();
+       tdx->exit_reason.full = __tdx_vcpu_run(tdx->tdvpr.pa, vcpu->arch.regs, 0);
+       guest_exit_irqoff();
+}
+
+fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
+{
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+       if (unlikely(vcpu->kvm->vm_bugged)) {
+               tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
+               return EXIT_FASTPATH_NONE;
+       }
+
+       trace_kvm_entry(vcpu);
+
+       tdx_vcpu_enter_exit(vcpu, tdx);
+
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) · line 542

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+       vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
+       trace_kvm_exit(vcpu, KVM_ISA_VMX);
+
+       if (tdx->exit_reason.error || tdx->exit_reason.non_recoverable)
+               return EXIT_FASTPATH_NONE;

Looks like the above if statement has no effect. Just checking if this is intentional.

Quoted 4 lines

I'm not sure if I get your point. tdx->exit_reason is updated by the above tdx_cpu_enter_exit(). So it makes sense to check .error or .non_recoverable. --
Isaku Yamahata <[email protected]>

What I mean is, if there is an error, it returns EXIT_FASTPATH_NONE but if there is no error, it still returns EXIT_FASTPATH_NONE.

Quoted 7 lines

The code is like below, the if-statement might be there as a placeholder to check errors but it has no impact on what is returned from this function.

       if (tdx->exit_reason.error || tdx->exit_reason.non_recoverable)
               return EXIT_FASTPATH_NONE;
       return EXIT_FASTPATH_NONE;

Got it. It doesn't make sense. I'll fix it with the next respin.

Signature · 1 line
Isaku Yamahata <[email protected]>
#21 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to Isaku Yamahata
Quoted 15 lines · Isaku Yamahata
Quoted 11 lines · Paolo Bonzini

arch/x86/kvm/vmx/tdx.c line 97

Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	if (!tdx_module_initialized) {
+		if (enable_tdx) {
+			ret = __tdx_module_setup();
+			if (ret)
+				enable_tdx = false;

"enable_tdx = false" isn't great to do only when a VM is created. Does it make sense to anticipate this to the point when the kvm_intel.ko module is loaded?

Quoted 3 lines

It's possible. I have the following two reasons to chose to defer TDX module initialization until creating first TD. Given those reasons, do you still want the initialization at loading kvm_intel.ko module? If yes, I'll change it.

Yes, TDX module setup needs to be done at load time. The loss of memory is unfortunate, e.g. if the host is part of a pool that _might_ run TDX guests, but the alternatives are worse. If TDX fails to initialize, e.g. due to low mem, then the host will be unable to run TDX guests despite saying "I support TDX". Or this gem :-)

/*
* TDH.SYS.KEY.CONFIG may fail with entropy error (which is
* a recoverable error). Assume this is exceedingly rare and
* just return error if encountered instead of retrying. */

The CPU overhead of initializing the TDX module is also non-trivial, and it doesn't affect just this CPU, e.g. all CPUs need to do certain SEAMCALLs and at least one WBINVD. The can cause noisy neighbor problems.

Quoted 8 lines

- memory over head: The initialization of TDX module requires to allocate physically contiguous memory whose size is about 0.43% of the system memory. If user don't use TD, it will be wasted.

- VMXON on all pCPUs: The TDX module initialization requires to enable VMX (VMXON) on all present pCPUs. vmx_hardware_enable() which is called on creating guest does it. It naturally fits with the TDX module initialization at creating first TD. I wanted to avoid code to enable VMXON on loading the kvm_intel.ko.

That's a solvable problem, though making it work without exporting hardware_enable_all() could get messy.

#22 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

Quoted 9 lines
Quoted 6 lines

- VMXON on all pCPUs: The TDX module initialization requires to enable VMX (VMXON) on all present pCPUs. vmx_hardware_enable() which is called on creating guest does it. It naturally fits with the TDX module initialization at creating first TD. I wanted to avoid code to enable VMXON on loading the kvm_intel.ko.

That's a solvable problem, though making it work without exporting hardware_enable_all() could get messy.

Could you elaborate a little bit on how to resolve?

Signature · 2 lines
Thanks,
-Kai
#66 lore raw

Re: [RFC PATCH v5 023/104] x86/cpu: Add helper functions to allocate/free MKTME keyid

In reply to [email protected]
Quoted 5 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

MKTME keyid is assigned to guest TD. The memory controller encrypts guest TD memory with key id. Add helper functions to allocate/free MKTME keyid so that TDX KVM assign keyid.

Using MKTME keyid is wrong, at least not accurate I think. We should use explicitly use "TDX private KeyID", which is clearly documented in the spec:

https://software.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-cpu-architectural-specification.pdf

Also, description of IA32_MKTME_KEYID_PARTITIONING MSR clearly says TDX private KeyIDs span the range (NUM_MKTME_KIDS+1) through (NUM_MKTME_KIDS+NUM_TDX_PRIV_KIDS). So please just use TDX private KeyID here.

Quoted 3 lines

Also export MKTME global keyid that is used to encrypt TDX module and its memory.

This needs explanation why the global keyID needs to be exported.

Quoted 82 lines
---
 arch/x86/include/asm/tdx.h |  6 ++++++
 arch/x86/virt/vmx/tdx.c    | 33 ++++++++++++++++++++++++++++++++-
 2 files changed, 38 insertions(+), 1 deletion(-)
arch/x86/include/asm/tdx.h +6 -0
index 9a8dc6afcb63..73bb472bd515 100644
@@ -139,6 +139,9 @@ int tdx_detect(void);
 int tdx_init(void);
 bool platform_has_tdx(void);
 const struct tdsysinfo_struct *tdx_get_sysinfo(void);
+u32 tdx_get_global_keyid(void);
+int tdx_keyid_alloc(void);
+void tdx_keyid_free(int keyid);
 #else
 static inline void tdx_detect_cpu(struct cpuinfo_x86 *c) { }
 static inline int tdx_detect(void) { return -ENODEV; }
@@ -146,6 +149,9 @@ static inline int tdx_init(void) { return -ENODEV; }
 static inline bool platform_has_tdx(void) { return false; }
 struct tdsysinfo_struct;
 static inline const struct tdsysinfo_struct *tdx_get_sysinfo(void) { return NULL; }
+static inline u32 tdx_get_global_keyid(void) { return 0; };
+static inline int tdx_keyid_alloc(void) { return -EOPNOTSUPP; }
+static inline void tdx_keyid_free(int keyid) { }
 #endif /* CONFIG_INTEL_TDX_HOST */
 
 #endif /* !__ASSEMBLY__ */
arch/x86/virt/vmx/tdx.c +32 -1
index e45f188479cb..d714106321d4 100644
@@ -113,7 +113,13 @@ static int tdx_cmr_num;
 static struct tdsysinfo_struct tdx_sysinfo;
 
 /* TDX global KeyID to protect TDX metadata */
-static u32 tdx_global_keyid;
+static u32 __read_mostly tdx_global_keyid;
+
+u32 tdx_get_global_keyid(void)
+{
+	return tdx_global_keyid;
+}
+EXPORT_SYMBOL_GPL(tdx_get_global_keyid);
 
 static bool enable_tdx_host;
 
@@ -189,6 +195,31 @@ static void detect_seam(struct cpuinfo_x86 *c)
 		detect_seam_ap(c);
 }
 
+/* TDX KeyID pool */
+static DEFINE_IDA(tdx_keyid_pool);
+
+int tdx_keyid_alloc(void)
+{
+	if (WARN_ON_ONCE(!tdx_keyid_start || !tdx_keyid_num))
+		return -EINVAL;
+
+	/* The first keyID is reserved for the global key. */
+	return ida_alloc_range(&tdx_keyid_pool, tdx_keyid_start + 1,
+			       tdx_keyid_start + tdx_keyid_num - 1,
+			       GFP_KERNEL);
+}
+EXPORT_SYMBOL_GPL(tdx_keyid_alloc);
+
+void tdx_keyid_free(int keyid)
+{
+	/* keyid = 0 is reserved. */
+	if (!keyid || keyid <= 0)
+		return;
+
+	ida_free(&tdx_keyid_pool, keyid);
+}
+EXPORT_SYMBOL_GPL(tdx_keyid_free);
+
 static void detect_tdx_keyids_bsp(struct cpuinfo_x86 *c)
 {
 	u64 keyid_part;
#27 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to [email protected]
Quoted 10 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Memory used for TDX is encrypted with an encryption key. An encryption key is assigned to guest TD, and TDX memory is encrypted. VMM calculates Trust Domain Memory Range (TDMR), a range of memory pages that can hold TDX memory encrypted with an encryption key. VMM allocates memory regions for Physical Address Metadata Table (PAMT) which the TDX module uses to track page states. Used for TDX memory, assigned to which guest TD, etc. VMM gives PAMT regions to the TDX module and initializes it which is also encrypted.

Not sure why above are related to this patch. Perhaps you can just say TDX module is detected and initialized on demand via tdx_detect() and tdx_init().

Quoted 4 lines

TDX requires more initialization steps in addition to VMX. As a preparation step, check if the CPU feature is available and enable VMX because the TDX module API requires VMX to be enabled to be functional.

Those are not reflected in this patch either.

Quoted 6 lines

The next step is basic platform initialization. Check if TDX module API is available, call system-wide initialization API (TDH.SYS.INIT), and call LP initialization API (TDH.SYS.LP.INIT). Lastly, get system-wide parameters (TDH.SYS.INFO), allocate PAMT for TDX module to track page states (TDH.SYS.CONFIG), configure encryption key (TDH.SYS.KEY.CONFIG), and initialize PAMT (TDH.SYS.TDMR.INIT).

Again, not sure why those are related.

Quoted 5 lines

A TDX host patch series implements those details and it provides APIs, seamrr_enabled() to check if CPU feature is available, init_tdx() to initialize the TDX module, tdx_get_tdsysinfo() to get TDX system parameters.

init_tdx() -> tdx_init().

"A TDX host patch series" should not be in the formal commit message, I suppose.

Quoted 5 lines

Add a wrapper function to initialize the TDX module and get system-wide parameters via those APIs. Because TDX requires VMX enabled, It will be called on-demand when the first guest TD is created via x86 KVM init_vm callback.

Why not just merge this patch with the change where you implement the init_vm callback? Then you can just declare this patch as "detect and initialize TDX module when first VM is created", or something like that..

Quoted 28 lines
---
 arch/x86/kvm/vmx/tdx.c | 89 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h |  4 ++
 2 files changed, 93 insertions(+)
arch/x86/kvm/vmx/tdx.c +13 -0
index 8ed3ec342e28..8adc87ad1807 100644
@@ -13,9 +13,98 @@
 static bool __read_mostly enable_tdx = true;
 module_param_named(tdx, enable_tdx, bool, 0644);
 
+#define TDX_MAX_NR_CPUID_CONFIGS					\
+	((sizeof(struct tdsysinfo_struct) -				\
+		offsetof(struct tdsysinfo_struct, cpuid_configs))	\
+		/ sizeof(struct tdx_cpuid_config))
+
+struct tdx_capabilities {
+	u8 tdcs_nr_pages;
+	u8 tdvpx_nr_pages;
+
+	u64 attrs_fixed0;
+	u64 attrs_fixed1;
+	u64 xfam_fixed0;
+	u64 xfam_fixed1;

arch/x86/kvm/vmx/tdx.c line 38

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+
+	u32 nr_cpuid_configs;
+	struct tdx_cpuid_config cpuid_configs[TDX_MAX_NR_CPUID_CONFIGS];
+};
+
+/* Capabilities of KVM + the TDX module. */
+struct tdx_capabilities tdx_caps;
+
 static u64 hkid_mask __ro_after_init;
 static u8 hkid_start_pos __ro_after_init;

The two seems are not used in this patch.

Please make sure each patch can compile w/o warning.

Quoted 43 lines
arch/x86/kvm/vmx/tdx.c +42 -0
+static int __tdx_module_setup(void)
+{
+	const struct tdsysinfo_struct *tdsysinfo;
+	int ret = 0;
+
+	BUILD_BUG_ON(sizeof(*tdsysinfo) != 1024);
+	BUILD_BUG_ON(TDX_MAX_NR_CPUID_CONFIGS != 37);
+
+	ret = tdx_detect();
+	if (ret) {
+		pr_info("Failed to detect TDX module.\n");
+		return ret;
+	}
+
+	ret = tdx_init();
+	if (ret) {
+		pr_info("Failed to initialize TDX module.\n");
+		return ret;
+	}
+
+	tdsysinfo = tdx_get_sysinfo();
+	if (tdx_caps.nr_cpuid_configs > TDX_MAX_NR_CPUID_CONFIGS)
+		return -EIO;
+
+	tdx_caps = (struct tdx_capabilities) {
+		.tdcs_nr_pages = tdsysinfo->tdcs_base_size / PAGE_SIZE,
+		/*
+		 * TDVPS = TDVPR(4K page) + TDVPX(multiple 4K pages).
+		 * -1 for TDVPR.
+		 */
+		.tdvpx_nr_pages = tdsysinfo->tdvps_base_size / PAGE_SIZE - 1,
+		.attrs_fixed0 = tdsysinfo->attributes_fixed0,
+		.attrs_fixed1 = tdsysinfo->attributes_fixed1,
+		.xfam_fixed0 =	tdsysinfo->xfam_fixed0,
+		.xfam_fixed1 = tdsysinfo->xfam_fixed1,
+		.nr_cpuid_configs = tdsysinfo->num_cpuid_config,
+	};
+	if (!memcpy(tdx_caps.cpuid_configs, tdsysinfo->cpuid_configs,
+			tdsysinfo->num_cpuid_config *
+			sizeof(struct tdx_cpuid_config)))
+		return -EIO;
+

arch/x86/kvm/vmx/tdx.c line 91

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	return 0;
+}
+
+int tdx_module_setup(void)
+{
+	static DEFINE_MUTEX(tdx_init_lock);
+	static bool __read_mostly tdx_module_initialized;
+	int ret = 0;
+
+	mutex_lock(&tdx_init_lock);

It took me a while to figure out why this mutex is needed. Please see my above suggestion to merge this patch to the change that implements init_vm() callback.

arch/x86/kvm/vmx/tdx.c line 95

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+	if (!tdx_module_initialized) {
+		if (enable_tdx) {
+			ret = __tdx_module_setup();

I think you can move tdx_detect() and tdx_init() out of your mutex. They are internally protected by mutex.

Quoted 37 lines
arch/x86/kvm/vmx/tdx.c +12 -0
+			if (ret)
+				enable_tdx = false;
+			else
+				tdx_module_initialized = true;
+		} else
+			ret = -EOPNOTSUPP;
+	}
+
+	mutex_unlock(&tdx_init_lock);
+	return ret;
+}
+
 static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 {
 	u32 max_pa;
arch/x86/kvm/vmx/tdx.h +4 -0
index daf6bfc6502a..d448e019602c 100644
@@ -3,6 +3,8 @@
 #define __KVM_X86_TDX_H
 
 #ifdef CONFIG_INTEL_TDX_HOST
+int tdx_module_setup(void);
+
 struct kvm_tdx {
 	struct kvm kvm;
 };
@@ -35,6 +37,8 @@ static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
 	return container_of(vcpu, struct vcpu_tdx, vcpu);
 }
 #else
+static inline int tdx_module_setup(void) { return -ENODEV; };
+
 struct kvm_tdx;
 struct vcpu_tdx;
 
#60 lore raw

Re: [RFC PATCH v5 021/104] KVM: x86: Introduce hooks to free VM callback prezap and vm_free

In reply to [email protected]
Quoted 61 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Kai Huang <[email protected]>

Before tearing down private page tables, TDX requires some resources of the guest TD to be destroyed (i.e. keyID must have been reclaimed, etc). Add prezap callback before tearing down private page tables for it.

TDX needs to free some resources after other resources (i.e. vcpu related resources). Add vm_free callback at the end of kvm_arch_destroy_vm().

---
 arch/x86/include/asm/kvm-x86-ops.h | 2 ++
 arch/x86/include/asm/kvm_host.h    | 2 ++
 arch/x86/kvm/x86.c                 | 8 ++++++++
 3 files changed, 12 insertions(+)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 8125d43d3566..ef48dcc98cfc 100644
@@ -20,7 +20,9 @@ KVM_X86_OP(has_emulated_msr)
 KVM_X86_OP(vcpu_after_set_cpuid)
 KVM_X86_OP(is_vm_type_supported)
 KVM_X86_OP(vm_init)
+KVM_X86_OP_NULL(mmu_prezap)
 KVM_X86_OP_NULL(vm_destroy)
+KVM_X86_OP_NULL(vm_free)
 KVM_X86_OP(vcpu_create)
 KVM_X86_OP(vcpu_free)
 KVM_X86_OP(vcpu_reset)
arch/x86/include/asm/kvm_host.h +2 -0
index 8de357a9ad30..5ff7a0fba311 100644
@@ -1326,7 +1326,9 @@ struct kvm_x86_ops {
 	bool (*is_vm_type_supported)(unsigned long vm_type);
 	unsigned int vm_size;
 	int (*vm_init)(struct kvm *kvm);
+	void (*mmu_prezap)(struct kvm *kvm);
 	void (*vm_destroy)(struct kvm *kvm);
+	void (*vm_free)(struct kvm *kvm);
 
 	/* Create, but do not attach this VCPU */
 	int (*vcpu_create)(struct kvm_vcpu *vcpu);
arch/x86/kvm/x86.c +1 -0
index f6438750d190..a48f5c69fadb 100644
@@ -11779,6 +11779,7 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_page_track_cleanup(kvm);
 	kvm_xen_destroy_vm(kvm);
 	kvm_hv_destroy_vm(kvm);
+	static_call_cond(kvm_x86_vm_free)(kvm);
 }
 
 static void memslot_rmap_free(struct kvm_memory_slot *slot)
@@ -12036,6 +12037,13 @@ void kvm_arch_commit_memory_region(struct kvm *kvm,
 
 void kvm_arch_flush_shadow_all(struct kvm *kvm)
 {

arch/x86/kvm/x86.c void kvm_arch_commit_memory_region(struct kvm *kvm, · line 12049

Quoted 10 lines
arch/x86/kvm/x86.c +7 -0
+	/*
+	 * kvm_mmu_zap_all() zaps both private and shared page tables.  Before
+	 * tearing down private page tables, TDX requires some TD resources to
+	 * be destroyed (i.e. keyID must have been reclaimed, etc).  Invoke
+	 * kvm_x86_mmu_prezap() for this.
+	 */
+	static_call_cond(kvm_x86_mmu_prezap)(kvm);
 	kvm_mmu_zap_all(kvm);
 }
 

The two callbacks are introduced here but they are actually implemented in 2 patches later (patch 24 KVM: TDX: create/destroy VM structure). Why not just squash this patch to patch 24? Or at least you can put this patch right before patch 24.

Please feel free to remove my SoB and From if this bothers you to squash.

#72 lore raw

Re: [RFC PATCH v5 024/104] KVM: TDX: create/destroy VM structure

In reply to [email protected]
Quoted 66 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

As the first step to create TDX guest, create/destroy VM struct. Assign Host Key ID (HKID) to the TDX guest for memory encryption and allocate extra pages for the TDX guest. On destruction, free allocated pages, and HKID.

Add a second kvm_x86_ops hook in kvm_arch_vm_destroy() to support TDX's destruction path, which needs to first put the VM into a teardown state, then free per-vCPU resources, and finally free per-VM resources.

---
 arch/x86/kvm/vmx/main.c      |  16 +-
 arch/x86/kvm/vmx/tdx.c       | 312 +++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h       |   2 +
 arch/x86/kvm/vmx/tdx_errno.h |   2 +-
 arch/x86/kvm/vmx/tdx_ops.h   |   8 +
 arch/x86/kvm/vmx/x86_ops.h   |   8 +
 6 files changed, 346 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/main.c +15 -1
index 6111c6485d8e..5c3a904a30e8 100644
@@ -39,12 +39,24 @@ static int vt_vm_init(struct kvm *kvm)
 		ret = tdx_module_setup();
 		if (ret)
 			return ret;
-		return -EOPNOTSUPP;	/* Not ready to create guest TD yet. */
+		return tdx_vm_init(kvm);
 	}
 
 	return vmx_vm_init(kvm);
 }
 
+static void vt_mmu_prezap(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_mmu_prezap(kvm);
+}
+
+static void vt_vm_free(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_vm_free(kvm);
+}
+
 struct kvm_x86_ops vt_x86_ops __initdata = {
 	.name = "kvm_intel",
 
@@ -58,6 +70,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.is_vm_type_supported = vt_is_vm_type_supported,
 	.vm_size = sizeof(struct kvm_vmx),
 	.vm_init = vt_vm_init,
+	.mmu_prezap = vt_mmu_prezap,
+	.vm_free = vt_vm_free,
 
 	.vcpu_create = vmx_vcpu_create,
 	.vcpu_free = vmx_vcpu_free,
arch/x86/kvm/vmx/tdx.c +0 -0
index 1c8222f54764..702953fd365f 100644

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 36

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +3 -0
@@ -31,14 +31,324 @@ struct tdx_capabilities {
 	struct tdx_cpuid_config cpuid_configs[TDX_MAX_NR_CPUID_CONFIGS];
 };
 
+/* KeyID used by TDX module */
+static u32 tdx_global_keyid __read_mostly;
+

It's really not clear why you need to know tdx_global_keyid in the context of creating/destroying a TD.

Quoted 29 lines
arch/x86/kvm/vmx/tdx.c +21 -0
 /* Capabilities of KVM + the TDX module. */
 struct tdx_capabilities tdx_caps;
 
+static DEFINE_MUTEX(tdx_lock);
 static struct mutex *tdx_mng_key_config_lock;
 
 static u64 hkid_mask __ro_after_init;
 static u8 hkid_start_pos __ro_after_init;
 
+static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
+{
+	pa &= ~hkid_mask;
+	pa |= (u64)hkid << hkid_start_pos;
+
+	return pa;
+}
+
+static inline bool is_td_created(struct kvm_tdx *kvm_tdx)
+{
+	return kvm_tdx->tdr.added;
+}
+
+static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
+{
+	tdx_keyid_free(kvm_tdx->hkid);
+	kvm_tdx->hkid = -1;
+}
+
+static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 75

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+{
+	return kvm_tdx->hkid > 0;
+}
+
+static void tdx_clear_page(unsigned long page)
+{
+	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
+	unsigned long i;
+
+	/* Zeroing the page is only necessary for systems with MKTME-i. */

"only necessary for systems with MKTME-i" because of what?

Please be more clear that on MKTME-i system, when re-assign one page from old keyid to a new keyid, MOVDIR64B is required to clear/write the page with new keyid to prevent integrity error when read on the page with new keyid.

However, the new keyid is essentially 0, but in practice integrity check for keyid 0 is disabled in current generation of MKTME-i, so I guess we are also safe even we don't use MOVDIR64B to clear page for TDX here. But I agree it's better to do.

Quoted 11 lines
arch/x86/kvm/vmx/tdx.c +11 -0
+	if (!static_cpu_has(X86_FEATURE_MOVDIR64B))
+		return;
+
+	for (i = 0; i < 4096; i += 64)
+		/* MOVDIR64B [rdx], es:rdi */
+		asm (".byte 0x66, 0x0f, 0x38, 0xf8, 0x3a"
+		     : : "d" (zero_page), "D" (page + i) : "memory");
+}
+
+static int __tdx_reclaim_page(unsigned long va, hpa_t pa, bool do_wb, u16 hkid)
+{

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 96

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	struct tdx_module_output out;
+	u64 err;
+
+	err = tdh_phymem_page_reclaim(pa, &out);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
+		return -EIO;
+	}
+
+	if (do_wb) {

In the callers, please add some comments explaining why do_wb is needed, and why is not needed.

Quoted 76 lines
arch/x86/kvm/vmx/tdx.c +76 -0
+		err = tdh_phymem_page_wbinvd(set_hkid_to_hpa(pa, hkid));
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err, NULL);
+			return -EIO;
+		}
+	}
+
+	tdx_clear_page(va);
+	return 0;
+}
+
+static int tdx_reclaim_page(unsigned long va, hpa_t pa)
+{
+	return __tdx_reclaim_page(va, pa, false, 0);
+}
+
+static int tdx_alloc_td_page(struct tdx_td_page *page)
+{
+	page->va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!page->va)
+		return -ENOMEM;
+
+	page->pa = __pa(page->va);
+	return 0;
+}
+
+static void tdx_mark_td_page_added(struct tdx_td_page *page)
+{
+	WARN_ON_ONCE(page->added);
+	page->added = true;
+}
+
+static void tdx_reclaim_td_page(struct tdx_td_page *page)
+{
+	if (page->added) {
+		if (tdx_reclaim_page(page->va, page->pa))
+			return;
+
+		page->added = false;
+	}
+	free_page(page->va);
+}
+
+static int tdx_do_tdh_phymem_cache_wb(void *param)
+{
+	u64 err = 0;
+
+	/*
+	 * We can destroy multiple the guest TDs simultaneously.  Prevent
+	 * tdh_phymem_cache_wb from returning TDX_BUSY by serialization.
+	 */
+	mutex_lock(&tdx_lock);
+	do {
+		err = tdh_phymem_cache_wb(!!err);
+	} while (err == TDX_INTERRUPTED_RESUMABLE);
+	mutex_unlock(&tdx_lock);
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+void tdx_mmu_prezap(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	bool cpumask_allocated;
+	u64 err;
+	int ret;
+	int i;

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 182

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx))
+		goto free_hkid;
+
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_key_reclaimid(kvm_tdx->tdr.pa);
+	mutex_unlock(&tdx_lock);

Please add a comment explaining why the mutex is needed.

Quoted 55 lines
arch/x86/kvm/vmx/tdx.c +55 -0
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_RECLAIMID, err, NULL);
+		return;
+	}
+
+	cpumask_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+	for_each_online_cpu(i) {
+		if (cpumask_allocated &&
+			cpumask_test_and_set_cpu(topology_physical_package_id(i),
+						packages))
+			continue;
+
+		ret = smp_call_on_cpu(i, tdx_do_tdh_phymem_cache_wb, NULL, 1);
+		if (ret)
+			break;
+	}
+	free_cpumask_var(packages);
+
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_key_freeid(kvm_tdx->tdr.pa);
+	mutex_unlock(&tdx_lock);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_FREEID, err, NULL);
+		return;
+	}
+
+free_hkid:
+	tdx_hkid_free(kvm_tdx);
+}
+
+void tdx_vm_free(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	int i;
+
+	/* Can't reclaim or free TD pages if teardown failed. */
+	if (is_hkid_assigned(kvm_tdx))
+		return;
+
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++)
+		tdx_reclaim_td_page(&kvm_tdx->tdcs[i]);
+	kfree(kvm_tdx->tdcs);
+
+	if (kvm_tdx->tdr.added &&
+		__tdx_reclaim_page(kvm_tdx->tdr.va, kvm_tdx->tdr.pa, true,
+				tdx_global_keyid))
+		return;
+
+	free_page(kvm_tdx->tdr.va);
+}
+
+static int tdx_do_tdh_mng_key_config(void *param)
+{
+	hpa_t *tdr_p = param;
+	int cpu, cur_pkg;

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 247

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+
+	cpu = raw_smp_processor_id();
+	cur_pkg = topology_physical_package_id(cpu);
+
+	mutex_lock(&tdx_mng_key_config_lock[cur_pkg]);
+	do {
+		err = tdh_mng_key_config(*tdr_p);
+	} while (err == TDX_KEY_GENERATION_FAILED);
+	mutex_unlock(&tdx_mng_key_config_lock[cur_pkg]);

Why not squashing patch 20 ("KVM: TDX: allocate per-package mutex") into this patch?

Quoted 30 lines
arch/x86/kvm/vmx/tdx.c +30 -0
+
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+int tdx_vm_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	int ret, i;
+	u64 err;
+
+	/* vCPUs can't be created until after KVM_TDX_INIT_VM. */
+	kvm->max_vcpus = 0;
+
+	kvm_tdx->hkid = tdx_keyid_alloc();
+	if (kvm_tdx->hkid < 0)
+		return -EBUSY;
+
+	ret = tdx_alloc_td_page(&kvm_tdx->tdr);
+	if (ret)
+		goto free_hkid;
+
+	kvm_tdx->tdcs = kcalloc(tdx_caps.tdcs_nr_pages, sizeof(*kvm_tdx->tdcs),
+				GFP_KERNEL_ACCOUNT);
+	if (!kvm_tdx->tdcs)

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 287

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		goto free_tdr;
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		ret = tdx_alloc_td_page(&kvm_tdx->tdcs[i]);
+		if (ret)
+			goto free_tdcs;
+	}
+
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(kvm_tdx->tdr.pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);

Please add comment explaining why locking is needed.

Quoted 68 lines
arch/x86/kvm/vmx/tdx.c +64 -0
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_tdcs;
+	}
+	tdx_mark_td_page_added(&kvm_tdx->tdr);
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	for_each_online_cpu(i) {
+		if (cpumask_test_and_set_cpu(topology_physical_package_id(i),
+						packages))
+			continue;
+
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				&kvm_tdx->tdr.pa, 1);
+		if (ret)
+			break;
+	}
+	free_cpumask_var(packages);
+	if (ret)
+		goto teardown;
+
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr.pa, kvm_tdx->tdcs[i].pa);
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+		tdx_mark_td_page_added(&kvm_tdx->tdcs[i]);
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.
+	 */
+teardown:
+	tdx_mmu_prezap(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_tdcs:
+	/* @i points at the TDCS page that failed allocation. */
+	for (--i; i >= 0; i--)
+		free_page(kvm_tdx->tdcs[i].va);
+	kfree(kvm_tdx->tdcs);
+free_tdr:
+	free_page(kvm_tdx->tdr.va);
+free_hkid:
+	tdx_hkid_free(kvm_tdx);
+	return ret;
+}
+
 static int __tdx_module_setup(void)
 {
 	const struct tdsysinfo_struct *tdsysinfo;

arch/x86/kvm/vmx/tdx.c static int __tdx_module_setup(void) · line 373

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +2 -0
@@ -59,6 +369,8 @@ static int __tdx_module_setup(void)
 		return ret;
 	}
 
+	tdx_global_keyid = tdx_get_global_keyid();
+

Again, really confusing why this is needed.

Quoted 47 lines
arch/x86/kvm/vmx/tdx.c +0 -0
 	tdsysinfo = tdx_get_sysinfo();
 	if (tdx_caps.nr_cpuid_configs > TDX_MAX_NR_CPUID_CONFIGS)
 		return -EIO;
arch/x86/kvm/vmx/tdx.h +2 -0
index e4bb8831764e..860136ed70f5 100644
@@ -19,6 +19,8 @@ struct kvm_tdx {
 
 	struct tdx_td_page tdr;
 	struct tdx_td_page *tdcs;
+
+	int hkid;
 };
 
 struct vcpu_tdx {
arch/x86/kvm/vmx/tdx_errno.h +1 -1
index 5c878488795d..590fcfdd1899 100644
@@ -12,11 +12,11 @@
 #define TDX_SUCCESS				0x0000000000000000ULL
 #define TDX_NON_RECOVERABLE_VCPU		0x4000000100000000ULL
 #define TDX_INTERRUPTED_RESUMABLE		0x8000000300000000ULL
-#define TDX_LIFECYCLE_STATE_INCORRECT		0xC000060700000000ULL
 #define TDX_VCPU_NOT_ASSOCIATED			0x8000070200000000ULL
 #define TDX_KEY_GENERATION_FAILED		0x8000080000000000ULL
 #define TDX_KEY_STATE_INCORRECT			0xC000081100000000ULL
 #define TDX_KEY_CONFIGURED			0x0000081500000000ULL
+#define TDX_NO_HKID_READY_TO_WBCACHE		0x0000082100000000ULL
 #define TDX_EPT_WALK_FAILED			0xC0000B0000000000ULL
 
 /*
arch/x86/kvm/vmx/tdx_ops.h +1 -0
index 0bed43879b82..3dd5b4c3f04c 100644
@@ -6,6 +6,7 @@
 
 #include <linux/compiler.h>
 
+#include <asm/cacheflush.h>
 #include <asm/asm.h>
 #include <asm/kvm_host.h>
 
@@ -15,8 +16,14 @@
 

arch/x86/kvm/vmx/tdx_ops.h line 26

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h +6 -0
 #ifdef CONFIG_INTEL_TDX_HOST
 
+static inline void tdx_clflush_page(hpa_t addr)
+{
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+}
+
 static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
 {
+	tdx_clflush_page(addr);

Please add comment to explain why clflush is needed.

And you don't need the tdx_clflush_page() wrapper -- it's not a TDX specific ops. You can just use clflush_cache_range().

Quoted 36 lines
arch/x86/kvm/vmx/tdx_ops.h +1 -0
 	return kvm_seamcall(TDH_MNG_ADDCX, addr, tdr, 0, 0, 0, NULL);
 }
 
@@ -56,6 +63,7 @@ static inline u64 tdh_mng_key_config(hpa_t tdr)
 
 static inline u64 tdh_mng_create(hpa_t tdr, int hkid)
 {
+	tdx_clflush_page(tdr);
 	return kvm_seamcall(TDH_MNG_CREATE, tdr, hkid, 0, 0, 0, NULL);
 }
 
arch/x86/kvm/vmx/x86_ops.h +8 -0
index da32b4b86b19..2b2738c768d6 100644
@@ -132,12 +132,20 @@ void __init tdx_pre_kvm_init(unsigned int *vcpu_size,
 bool tdx_is_vm_type_supported(unsigned long type);
 void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 void tdx_hardware_unsetup(void);
+
+int tdx_vm_init(struct kvm *kvm);
+void tdx_mmu_prezap(struct kvm *kvm);
+void tdx_vm_free(struct kvm *kvm);
 #else
 static inline void tdx_pre_kvm_init(
 	unsigned int *vcpu_size, unsigned int *vcpu_align, unsigned int *vm_size) {}
 static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
 static inline void tdx_hardware_setup(struct kvm_x86_ops *x86_ops) {}
 static inline void tdx_hardware_unsetup(void) {}
+
+static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
+static inline void tdx_mmu_prezap(struct kvm *kvm) {}
+static inline void tdx_vm_free(struct kvm *kvm) {}
 #endif
 
 #endif /* __KVM_X86_VMX_X86_OPS_H */
#88 lore raw

Re: [RFC PATCH v5 027/104] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]
Quoted 57 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Xiaoyao Li <[email protected]>

TDX requires additional parameters for TDX VM for confidential execution to protect its confidentiality of its memory contents and its CPU state from any other software, including VMM. When creating guest TD VM before creating vcpu, the number of vcpu, TSC frequency (that is same among vcpus. and it can't be changed.) CPUIDs which is emulated by the TDX module. It means guest can trust those CPUIDs. and sha384 values for measurement.

Add new subcommand, KVM_TDX_INIT_VM, to pass parameters for TDX guest. It assigns encryption key to the TDX guest for memory encryption. TDX encrypts memory per-guest bases. It assigns Device model passes per-VM parameters for the TDX guest. The maximum number of vcpus, tsc frequency (TDX guest has fised VM-wide TSC frequency. not per-vcpu. The TDX guest can not change it.), attributes (production or debug), available extended features (which is reflected into guest XCR0, IA32_XSS MSR), cpuids, sha384 measurements, and etc.

---
 arch/x86/include/asm/kvm_host.h       |   2 +
 arch/x86/include/uapi/asm/kvm.h       |  12 ++
 arch/x86/kvm/vmx/tdx.c                | 200 ++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h                |  26 ++++
 arch/x86/kvm/x86.c                    |   3 +-
 arch/x86/kvm/x86.h                    |   2 +
 tools/arch/x86/include/uapi/asm/kvm.h |  12 ++
 7 files changed, 256 insertions(+), 1 deletion(-)
arch/x86/include/asm/kvm_host.h +2 -0
index 5ff7a0fba311..290e200f012c 100644
@@ -1234,6 +1234,8 @@ struct kvm_arch {
 	hpa_t	hv_root_tdp;
 	spinlock_t hv_root_tdp_lock;
 #endif
+
+	gfn_t gfn_shared_mask;
 };
 
 struct kvm_vm_stat {
arch/x86/include/uapi/asm/kvm.h +1 -0
index 70f9be4ea575..6e26dde0dce6 100644
@@ -531,6 +531,7 @@ struct kvm_pmu_event_filter {
 /* Trust Domain eXtension sub-ioctl() commands. */
 enum kvm_tdx_cmd_id {
 	KVM_TDX_CAPABILITIES = 0,
+	KVM_TDX_INIT_VM,
 
 	KVM_TDX_CMD_NR_MAX,
 };

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_capabilities { · line 569

Quoted 8 lines
arch/x86/include/uapi/asm/kvm.h +5 -0
@@ -561,4 +562,15 @@ struct kvm_tdx_capabilities {
 	struct kvm_tdx_cpuid_config cpuid_configs[0];
 };
 
+struct kvm_tdx_init_vm {
+	__u32 max_vcpus;
+	__u32 tsc_khz;
+	__u64 attributes;
+	__u64 cpuid;

Is it better to append all CPUIDs directly into this structure, perhaps at end of this structure, to make it more consistent with TD_PARAMS?

Also, I think somewhere in commit message or comments we should explain why CPUIDs are passed here (why existing KVM_SET_CUPID2 is not sufficient).

Quoted 48 lines
arch/x86/include/uapi/asm/kvm.h +6 -0
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha348 digest */
+	__u64 reserved[43];	/* must be zero for future extensibility */
+};
+
 #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/tdx.c +33 -0
index 20b45bb0b032..236faaca68a0 100644
@@ -387,6 +387,203 @@ static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 	return 0;
 }
 
+static struct kvm_cpuid_entry2 *tdx_find_cpuid_entry(struct kvm_tdx *kvm_tdx,
+						u32 function, u32 index)
+{
+	struct kvm_cpuid_entry2 *e;
+	int i;
+
+	for (i = 0; i < kvm_tdx->cpuid_nent; i++) {
+		e = &kvm_tdx->cpuid_entries[i];
+
+		if (e->function == function && (e->index == index ||
+		    !(e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX)))
+			return e;
+	}
+	return NULL;
+}
+
+static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
+			struct kvm_tdx_init_vm *init_vm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	struct tdx_cpuid_config *config;
+	struct kvm_cpuid_entry2 *entry;
+	struct tdx_cpuid_value *value;
+	u64 guest_supported_xcr0;
+	u64 guest_supported_xss;
+	u32 guest_tsc_khz;
+	int max_pa;
+	int i;
+
+	/* init_vm->reserved must be zero */
+	if (find_first_bit((unsigned long *)init_vm->reserved,
+			   sizeof(init_vm->reserved) * 8) !=
+	    sizeof(init_vm->reserved) * 8)

arch/x86/kvm/vmx/tdx.c static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 432

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		return -EINVAL;
+
+	td_params->max_vcpus = init_vm->max_vcpus;
+
+	td_params->attributes = init_vm->attributes;
+	if (td_params->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+		pr_warn("TD doesn't support perfmon. KVM needs to save/restore "
+			"host perf registers properly.\n");
+		return -EOPNOTSUPP;
+	}

PERFMON can be supported but it's not support in this series, so perhaps add a comment to explain it's a TODO?

arch/x86/kvm/vmx/tdx.c static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 434

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+
+	/* TODO: Enforce consistent CPUID features for all vCPUs. */

I guess you have to enforce when you do KVM_SET_CPUID2 after vcpu is created? Then I guess this comment shouldn't be here, because the enforcement isn't something you can do here in setup_tdparams().

Quoted 21 lines
arch/x86/kvm/vmx/tdx.c +21 -0
+	for (i = 0; i < tdx_caps.nr_cpuid_configs; i++) {
+		config = &tdx_caps.cpuid_configs[i];
+
+		entry = tdx_find_cpuid_entry(kvm_tdx, config->leaf,
+					     config->sub_leaf);
+		if (!entry)
+			continue;
+
+		/*
+		 * Non-configurable bits must be '0', even if they are fixed to
+		 * '1' by the TDX module, i.e. mask off non-configurable bits.
+		 */
+		value = &td_params->cpuid_values[i];
+		value->eax = entry->eax & config->eax;
+		value->ebx = entry->ebx & config->ebx;
+		value->ecx = entry->ecx & config->ecx;
+		value->edx = entry->edx & config->edx;
+	}
+
+	max_pa = 36;
+	entry = tdx_find_cpuid_entry(kvm_tdx, 0x80000008, 0);

arch/x86/kvm/vmx/tdx.c static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 465

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	if (entry)
+		max_pa = entry->eax & 0xff;
+
+	td_params->eptp_controls = VMX_EPTP_MT_WB;
+	if (cpu_has_vmx_ept_5levels() && max_pa > 48) {
+		td_params->eptp_controls |= VMX_EPTP_PWL_5;
+		td_params->exec_controls |= TDX_EXEC_CONTROL_MAX_GPAW;
+	} else {
+		td_params->eptp_controls |= VMX_EPTP_PWL_4;
+	}

Not quite sure, but could we support >48 GPA with 4-level EPT?

#108 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to [email protected]
Quoted 122 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Rick Edgecombe <[email protected]>

Add support in KVM's MMU for aliasing multiple GPAs (from a hardware perspective) to a single GPA (from a memslot perspective). GPA aliasing will be used to repurpose GPA bits as attribute bits, e.g. to expose an execute-only permission bit to the guest. To keep the implementation simple (relatively speaking), GPA aliasing is only supported via TDP.

Today KVM assumes two things that are broken by GPA aliasing.
1. GPAs coming from hardware can be simply shifted to get the GFNs.
2. GPA bits 51:MAXPHYADDR are reserved to zero.

With GPA aliasing, translating a GPA to GFN requires masking off the repurposed bit, and a repurposed bit may reside in 51:MAXPHYADDR.

To support GPA aliasing, introduce the concept of per-VM GPA stolen bits, that is, bits stolen from the GPA to act as new virtualized attribute bits. A bit in the mask will cause the MMU code to create aliases of the GPA. It can also be used to find the GFN out of a GPA coming from a tdp fault.

To handle case (1) from above, retain any stolen bits when passing a GPA in KVM's MMU code, but strip them when converting to a GFN so that the GFN contains only the "real" GFN, i.e. never has repurposed bits set.

GFNs (without stolen bits) continue to be used to:
- Specify physical memory by userspace via memslots
- Map GPAs to TDP PTEs via RMAP
- Specify dirty tracking and write protection
- Look up MTRR types
- Inject async page faults

Since there are now multiple aliases for the same aliased GPA, when userspace memory backing the memslots is paged out, both aliases need to be modified. Fortunately, this happens automatically. Since rmap supports multiple mappings for the same GFN for PTE shadowing based paging, by adding/removing each alias PTE with its GFN, kvm_handle_hva() based operations will be applied to both aliases.

In the case of the rmap being removed in the future, the needed information could be recovered by iterating over the stolen bits and walking the TDP page tables.

For TLB flushes that are address based, make sure to flush both aliases in the case of stolen bits.

Only support stolen bits in 64 bit guest paging modes (long, PAE). Features that use this infrastructure should restrict the stolen bits to exclude the other paging modes. Don't support stolen bits for shadow EPT.

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/mmu.h              | 51 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu/mmu.c          | 19 ++++++++++--
 arch/x86/kvm/mmu/paging_tmpl.h  | 25 +++++++++-------
 4 files changed, 84 insertions(+), 13 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index 208b29b0e637..d8b78d6abc10 100644
@@ -1235,7 +1235,9 @@ struct kvm_arch {
 	spinlock_t hv_root_tdp_lock;
 #endif
 
+#ifdef CONFIG_KVM_MMU_PRIVATE
 	gfn_t gfn_shared_mask;
+#endif
 };
 
 struct kvm_vm_stat {
arch/x86/kvm/mmu.h +41 -0
index e9fbb2c8bbe2..3fb530359f81 100644
@@ -365,4 +365,55 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
 		return gpa;
 	return translate_nested_gpa(vcpu, gpa, access, exception);
 }
+
+static inline gfn_t kvm_gfn_stolen_mask(struct kvm *kvm)
+{
+#ifdef CONFIG_KVM_MMU_PRIVATE
+	return kvm->arch.gfn_shared_mask;
+#else
+	return 0;
+#endif
+}
+
+static inline gpa_t kvm_gpa_stolen_mask(struct kvm *kvm)
+{
+	return gfn_to_gpa(kvm_gfn_stolen_mask(kvm));
+}
+
+static inline gpa_t kvm_gpa_unalias(struct kvm *kvm, gpa_t gpa)
+{
+	return gpa & ~kvm_gpa_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_unalias(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_shared(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn | kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_private(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gpa_t kvm_gpa_private(struct kvm *kvm, gpa_t gpa)
+{
+	return gpa & ~kvm_gpa_stolen_mask(kvm);
+}
+
+static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn)

arch/x86/kvm/mmu.h static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu, · line 418

Quoted 10 lines
arch/x86/kvm/mmu.h +10 -0
+{
+	gfn_t mask = kvm_gfn_stolen_mask(kvm);
+
+	return mask && !(gfn & mask);
+}
+
+static inline bool kvm_is_private_gpa(struct kvm *kvm, gpa_t gpa)
+{
+	return kvm_is_private_gfn(kvm, gpa_to_gfn(gpa));
+}

The patch title and commit message say nothing about private/shared, but only mention stolen bits in general. It's weird to introduce those *private* related helpers here.

I think you can just ditch the concept of stolen bit infrastructure, but just adopt what TDX needs.

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 279

Quoted 11 lines
arch/x86/kvm/mmu.h +0 -0
 #endif
arch/x86/kvm/mmu/mmu.c +1 -1
index 8e24f73bf60b..b68191aa39bf 100644
@@ -276,11 +276,24 @@ static inline bool kvm_available_flush_tlb_with_range(void)
 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
 		struct kvm_tlb_range *range)
 {
-	int ret = -ENOTSUPP;
+	int ret = -EOPNOTSUPP;

Change doesn't belong to this patch.

Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +2 -1
+	u64 gfn_stolen_mask;
 
-	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
+	/*

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 292

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	 * Fall back to the big hammer flush if there is more than one
+	 * GPA alias that needs to be flushed.
+	 */
+	gfn_stolen_mask = kvm_gfn_stolen_mask(kvm);
+	if (hweight64(gfn_stolen_mask) > 1)
+		goto generic_flush;
+
+	if (range && kvm_available_flush_tlb_with_range()) {
+		/* Callback should flush both private GFN and shared GFN. */
+		range->start_gfn = kvm_gfn_unalias(kvm, range->start_gfn);

This seems wrong. It seems the intention of this function is to flush TLB for all aliases for a given GFN range. Here it seems you are unconditionally change to range to always exclude the stolen bits.

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 294

Quoted 2 lines
arch/x86/kvm/mmu/mmu.c +1 -0
 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
+	}

And you always fall through to do big hammer flush, which is obviously not intended.

Quoted 111 lines
arch/x86/kvm/mmu/mmu.c +2 -1
+generic_flush:
 	if (ret)
 		kvm_flush_remote_tlbs(kvm);
 }
@@ -4010,7 +4023,7 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
 	unsigned long mmu_seq;
 	int r;
 
-	fault->gfn = fault->addr >> PAGE_SHIFT;
+	fault->gfn = kvm_gfn_unalias(vcpu->kvm, gpa_to_gfn(fault->addr));
 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
 
 	if (page_fault_handle_page_track(vcpu, fault))
arch/x86/kvm/mmu/paging_tmpl.h +14 -9
index 5b5bdac97c7b..70aec31dee06 100644
@@ -25,7 +25,8 @@
 	#define guest_walker guest_walker64
 	#define FNAME(name) paging##64_##name
 	#define PT_BASE_ADDR_MASK GUEST_PT64_BASE_ADDR_MASK
-	#define PT_LVL_ADDR_MASK(lvl) PT64_LVL_ADDR_MASK(lvl)
+	#define PT_LVL_ADDR_MASK(vcpu, lvl) (~kvm_gpa_stolen_mask(vcpu->kvm) & \
+					     PT64_LVL_ADDR_MASK(lvl))
 	#define PT_LVL_OFFSET_MASK(lvl) PT64_LVL_OFFSET_MASK(lvl)
 	#define PT_INDEX(addr, level) PT64_INDEX(addr, level)
 	#define PT_LEVEL_BITS PT64_LEVEL_BITS
@@ -44,7 +45,7 @@
 	#define guest_walker guest_walker32
 	#define FNAME(name) paging##32_##name
 	#define PT_BASE_ADDR_MASK PT32_BASE_ADDR_MASK
-	#define PT_LVL_ADDR_MASK(lvl) PT32_LVL_ADDR_MASK(lvl)
+	#define PT_LVL_ADDR_MASK(vcpu, lvl) PT32_LVL_ADDR_MASK(lvl)
 	#define PT_LVL_OFFSET_MASK(lvl) PT32_LVL_OFFSET_MASK(lvl)
 	#define PT_INDEX(addr, level) PT32_INDEX(addr, level)
 	#define PT_LEVEL_BITS PT32_LEVEL_BITS
@@ -58,7 +59,7 @@
 	#define guest_walker guest_walkerEPT
 	#define FNAME(name) ept_##name
 	#define PT_BASE_ADDR_MASK GUEST_PT64_BASE_ADDR_MASK
-	#define PT_LVL_ADDR_MASK(lvl) PT64_LVL_ADDR_MASK(lvl)
+	#define PT_LVL_ADDR_MASK(vcpu, lvl) PT64_LVL_ADDR_MASK(lvl)
 	#define PT_LVL_OFFSET_MASK(lvl) PT64_LVL_OFFSET_MASK(lvl)
 	#define PT_INDEX(addr, level) PT64_INDEX(addr, level)
 	#define PT_LEVEL_BITS PT64_LEVEL_BITS
@@ -75,7 +76,7 @@
 #define PT_GUEST_ACCESSED_MASK (1 << PT_GUEST_ACCESSED_SHIFT)
 
 #define gpte_to_gfn_lvl FNAME(gpte_to_gfn_lvl)
-#define gpte_to_gfn(pte) gpte_to_gfn_lvl((pte), PG_LEVEL_4K)
+#define gpte_to_gfn(vcpu, pte) gpte_to_gfn_lvl(vcpu, pte, PG_LEVEL_4K)
 
 /*
  * The guest_walker structure emulates the behavior of the hardware page
@@ -96,9 +97,9 @@ struct guest_walker {
 	struct x86_exception fault;
 };
 
-static gfn_t gpte_to_gfn_lvl(pt_element_t gpte, int lvl)
+static gfn_t gpte_to_gfn_lvl(struct kvm_vcpu *vcpu, pt_element_t gpte, int lvl)
 {
-	return (gpte & PT_LVL_ADDR_MASK(lvl)) >> PAGE_SHIFT;
+	return (gpte & PT_LVL_ADDR_MASK(vcpu, lvl)) >> PAGE_SHIFT;
 }
 
 static inline void FNAME(protect_clean_gpte)(struct kvm_mmu *mmu, unsigned *access,
@@ -395,7 +396,7 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 		--walker->level;
 
 		index = PT_INDEX(addr, walker->level);
-		table_gfn = gpte_to_gfn(pte);
+		table_gfn = gpte_to_gfn(vcpu, pte);
 		offset    = index * sizeof(pt_element_t);
 		pte_gpa   = gfn_to_gpa(table_gfn) + offset;
 
@@ -460,7 +461,7 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 	if (unlikely(errcode))
 		goto error;
 
-	gfn = gpte_to_gfn_lvl(pte, walker->level);
+	gfn = gpte_to_gfn_lvl(vcpu, pte, walker->level);
 	gfn += (addr & PT_LVL_OFFSET_MASK(walker->level)) >> PAGE_SHIFT;
 
 	if (PTTYPE == 32 && walker->level > PG_LEVEL_4K && is_cpuid_PSE36())
@@ -555,12 +556,14 @@ FNAME(prefetch_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
 	gfn_t gfn;
 	kvm_pfn_t pfn;
 
+	WARN_ON(gpte & kvm_gpa_stolen_mask(vcpu->kvm));
+
 	if (FNAME(prefetch_invalid_gpte)(vcpu, sp, spte, gpte))
 		return false;
 
 	pgprintk("%s: gpte %llx spte %p\n", __func__, (u64)gpte, spte);
 
-	gfn = gpte_to_gfn(gpte);
+	gfn = gpte_to_gfn(vcpu, gpte);
 	pte_access = sp->role.access & FNAME(gpte_access)(gpte);
 	FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
 
@@ -656,6 +659,8 @@ static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
 	WARN_ON_ONCE(gw->gfn != base_gfn);
 	direct_access = gw->pte_access;
 
+	WARN_ON(fault->addr & kvm_gpa_stolen_mask(vcpu->kvm));
+
 	top_level = vcpu->arch.mmu->root_level;
 	if (top_level == PT32E_ROOT_LEVEL)
 		top_level = PT32_ROOT_LEVEL;

arch/x86/kvm/mmu/paging_tmpl.h static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1091

Quoted 8 lines
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
@@ -1080,7 +1085,7 @@ static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 			continue;
 		}
 
-		gfn = gpte_to_gfn(gpte);
+		gfn = gpte_to_gfn(vcpu, gpte);
 		pte_access = sp->role.access;
 		pte_access &= FNAME(gpte_access)(gpte);
 		FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);

In commit message you mentioned "Don't support stolen bits for shadow EPT" (you actually mean shadow MMU I suppose), yet there's bunch of code change to shadow MMU.

#103 lore raw

Re: [RFC PATCH v5 032/104] KVM: x86/mmu: introduce config for PRIVATE KVM MMU

In reply to [email protected]
Quoted 17 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To Keep the case of non TDX intact, introduce a new config option for private KVM MMU support. At the moment, this is synonym for CONFIG_INTEL_TDX_HOST && CONFIG_KVM_INTEL. The new flag make it clear that the config is only for x86 KVM MMU.

---
 arch/x86/kvm/Kconfig | 4 ++++
 1 file changed, 4 insertions(+)
arch/x86/kvm/Kconfig +0 -0
index 2b1548da00eb..2db590845927 100644

arch/x86/kvm/Kconfig config KVM_MMU_AUDIT · line 143

Quoted 8 lines
arch/x86/kvm/Kconfig +4 -0
@@ -136,4 +136,8 @@ config KVM_MMU_AUDIT
 config KVM_EXTERNAL_WRITE_TRACKING
 	bool
 
+config KVM_MMU_PRIVATE
+	def_bool y
+	depends on INTEL_TDX_HOST && KVM_INTEL
+
 endif # VIRTUALIZATION

I am really not sure why need this. Roughly looking at MMU related patches this new config option is hardly used. You have many code changes related to handling private/shared but they are not under this config option.

Signature · 2 lines
Thanks,
-Kai
#23 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to Sean Christopherson
Quoted 20 lines · Sean Christopherson
Quoted 15 lines · Isaku Yamahata
Quoted 11 lines · Paolo Bonzini

arch/x86/kvm/vmx/tdx.c line 97

Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	if (!tdx_module_initialized) {
+		if (enable_tdx) {
+			ret = __tdx_module_setup();
+			if (ret)
+				enable_tdx = false;

"enable_tdx = false" isn't great to do only when a VM is created. Does it make sense to anticipate this to the point when the kvm_intel.ko module is loaded?

Quoted 3 lines

It's possible. I have the following two reasons to chose to defer TDX module initialization until creating first TD. Given those reasons, do you still want the initialization at loading kvm_intel.ko module? If yes, I'll change it.

Quoted 5 lines

Yes, TDX module setup needs to be done at load time. The loss of memory is unfortunate, e.g. if the host is part of a pool that _might_ run TDX guests, but the alternatives are worse. If TDX fails to initialize, e.g. due to low mem, then the host will be unable to run TDX guests despite saying "I support TDX". Or this gem :-)

Ok.

Quoted 11 lines
Quoted 8 lines

- memory over head: The initialization of TDX module requires to allocate physically contiguous memory whose size is about 0.43% of the system memory. If user don't use TD, it will be wasted.

- VMXON on all pCPUs: The TDX module initialization requires to enable VMX (VMXON) on all present pCPUs. vmx_hardware_enable() which is called on creating guest does it. It naturally fits with the TDX module initialization at creating first TD. I wanted to avoid code to enable VMXON on loading the kvm_intel.ko.

That's a solvable problem, though making it work without exporting hardware_enable_all() could get messy.

Could you please explain any reason why it's bad idea to export it?

Signature · 1 line
Isaku Yamahata <[email protected]>
#24 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

+Chao Gao

Quoted 11 lines · Isaku Yamahata
Quoted 8 lines · Sean Christopherson
Quoted 4 lines · Isaku Yamahata

- VMXON on all pCPUs: The TDX module initialization requires to enable VMX (VMXON) on all present pCPUs. vmx_hardware_enable() which is called on creating guest does it. It naturally fits with the TDX module initialization at creating first TD. I wanted to avoid code to enable VMXON on loading the kvm_intel.ko.

That's a solvable problem, though making it work without exporting hardware_enable_all() could get messy.

Could you please explain any reason why it's bad idea to export it?

I'd really prefer to keep the hardware enable/disable logic internal to kvm_main.c so that all architectures share a common flow, and so that kvm_main.c is the sole owner. I'm worried that exposing the helper will lead to other arch/vendor usage, and that will end up with what is effectively duplicate flows. Deduplicating arch code into generic KVM is usually very difficult.

This might also be a good opportunity to make KVM slightly more robust. Ooh, and we can kill two birds with one stone. There's an in-flight series to add compatibility checks to hotplug[*]. But rather than special case hotplug, what if we instead do hardware enable/disable during module load, and move the compatibility check into the hardware_enable path? That fixes the hotplug issue, gives TDX a window for running post-VMXON code in kvm_init(), and makes the broadcast IPI less wasteful on architectures that don't have compatiblity checks.

I'm thinking something like this, maybe as a modificatyion to patch 6 in Chao's series, or more likely as a patch 7 so that the hotplug compat checks still get in even if the early hardware enable doesn't work on all architectures for some reason.

virt/kvm/kvm_main.c +12 -19
index 69c318fdff61..c6572a056072 100644
@@ -4838,8 +4838,13 @@ static void hardware_enable_nolock(void *junk)
 
        cpumask_set_cpu(cpu, cpus_hardware_enabled);
 
+       r = kvm_arch_check_processor_compat();
+       if (r)
+               goto out;
+
        r = kvm_arch_hardware_enable();
 
+out:
        if (r) {
                cpumask_clear_cpu(cpu, cpus_hardware_enabled);
                atomic_inc(&hardware_enable_failed);
@@ -5636,18 +5641,6 @@ void kvm_unregister_perf_callbacks(void)
 }
 #endif
 
-struct kvm_cpu_compat_check {
-       void *opaque;
-       int *ret;
-};
-
-static void check_processor_compat(void *data)
-{
-       struct kvm_cpu_compat_check *c = data;
-
-       *c->ret = kvm_arch_check_processor_compat(c->opaque);
-}
-
 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
                  struct module *module)
 {
@@ -5679,13 +5672,13 @@ int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
        if (r < 0)
                goto out_free_1;
 
-       c.ret = &r;
-       c.opaque = opaque;
-       for_each_online_cpu(cpu) {
-               smp_call_function_single(cpu, check_processor_compat, &c, 1);
-               if (r < 0)
-                       goto out_free_2;
-       }
+       r = hardware_enable_all();
+       if (r)
+               goto out_free_2;
+
+       kvm_arch_post_hardware_enable_setup();
+
+       hardware_disable_all();
 
        r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
                                      kvm_starting_cpu, kvm_dying_cpu);

[*] https://lore.kernel.org/all/[email protected]

#28 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to Kai Huang
Quoted 11 lines · Kai Huang
Quoted 6 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a wrapper function to initialize the TDX module and get system-wide parameters via those APIs. Because TDX requires VMX enabled, It will be called on-demand when the first guest TD is created via x86 KVM init_vm callback.

Why not just merge this patch with the change where you implement the init_vm callback? Then you can just declare this patch as "detect and initialize TDX module when first VM is created", or something like that..

Ok. Anyway in the next respoin, tdx module initialization will be done when loading kvm_intel.ko. So the whole part will be changed and will be a part of module loading.

Signature · 1 line
Isaku Yamahata <[email protected]>
#61 lore raw

Re: [RFC PATCH v5 021/104] KVM: x86: Introduce hooks to free VM callback prezap and vm_free

In reply to Kai Huang
Quoted 69 lines · Kai Huang
Quoted 68 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Kai Huang <[email protected]>

Before tearing down private page tables, TDX requires some resources of the guest TD to be destroyed (i.e. keyID must have been reclaimed, etc). Add prezap callback before tearing down private page tables for it.

TDX needs to free some resources after other resources (i.e. vcpu related resources). Add vm_free callback at the end of kvm_arch_destroy_vm().

---
 arch/x86/include/asm/kvm-x86-ops.h | 2 ++
 arch/x86/include/asm/kvm_host.h    | 2 ++
 arch/x86/kvm/x86.c                 | 8 ++++++++
 3 files changed, 12 insertions(+)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 8125d43d3566..ef48dcc98cfc 100644
@@ -20,7 +20,9 @@ KVM_X86_OP(has_emulated_msr)
 KVM_X86_OP(vcpu_after_set_cpuid)
 KVM_X86_OP(is_vm_type_supported)
 KVM_X86_OP(vm_init)
+KVM_X86_OP_NULL(mmu_prezap)
 KVM_X86_OP_NULL(vm_destroy)
+KVM_X86_OP_NULL(vm_free)
 KVM_X86_OP(vcpu_create)
 KVM_X86_OP(vcpu_free)
 KVM_X86_OP(vcpu_reset)
arch/x86/include/asm/kvm_host.h +2 -0
index 8de357a9ad30..5ff7a0fba311 100644
@@ -1326,7 +1326,9 @@ struct kvm_x86_ops {
 	bool (*is_vm_type_supported)(unsigned long vm_type);
 	unsigned int vm_size;
 	int (*vm_init)(struct kvm *kvm);
+	void (*mmu_prezap)(struct kvm *kvm);
 	void (*vm_destroy)(struct kvm *kvm);
+	void (*vm_free)(struct kvm *kvm);
 
 	/* Create, but do not attach this VCPU */
 	int (*vcpu_create)(struct kvm_vcpu *vcpu);
arch/x86/kvm/x86.c +8 -0
index f6438750d190..a48f5c69fadb 100644
@@ -11779,6 +11779,7 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_page_track_cleanup(kvm);
 	kvm_xen_destroy_vm(kvm);
 	kvm_hv_destroy_vm(kvm);
+	static_call_cond(kvm_x86_vm_free)(kvm);
 }
 
 static void memslot_rmap_free(struct kvm_memory_slot *slot)
@@ -12036,6 +12037,13 @@ void kvm_arch_commit_memory_region(struct kvm *kvm,
 
 void kvm_arch_flush_shadow_all(struct kvm *kvm)
 {
+	/*
+	 * kvm_mmu_zap_all() zaps both private and shared page tables.  Before
+	 * tearing down private page tables, TDX requires some TD resources to
+	 * be destroyed (i.e. keyID must have been reclaimed, etc).  Invoke
+	 * kvm_x86_mmu_prezap() for this.
+	 */
+	static_call_cond(kvm_x86_mmu_prezap)(kvm);
Quoted 8 lines

arch/x86/kvm/x86.c void kvm_arch_commit_memory_region(struct kvm *kvm, · line 12049

Quoted 3 lines
arch/x86/kvm/x86.c +0 -0
 	kvm_mmu_zap_all(kvm);
 }
 

The two callbacks are introduced here but they are actually implemented in 2 patches later (patch 24 KVM: TDX: create/destroy VM structure). Why not just squash this patch to patch 24? Or at least you can put this patch right before patch 24.

Ok. I'll squash this patch into it.

Signature · 1 line
Isaku Yamahata <[email protected]>
#67 lore raw

Re: [RFC PATCH v5 023/104] x86/cpu: Add helper functions to allocate/free MKTME keyid

In reply to Kai Huang
Quoted 18 lines · Kai Huang
Quoted 5 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

MKTME keyid is assigned to guest TD. The memory controller encrypts guest TD memory with key id. Add helper functions to allocate/free MKTME keyid so that TDX KVM assign keyid.

Using MKTME keyid is wrong, at least not accurate I think. We should use explicitly use "TDX private KeyID", which is clearly documented in the spec:

https://software.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-cpu-architectural-specification.pdf

Also, description of IA32_MKTME_KEYID_PARTITIONING MSR clearly says TDX private KeyIDs span the range (NUM_MKTME_KIDS+1) through (NUM_MKTME_KIDS+NUM_TDX_PRIV_KIDS). So please just use TDX private KeyID here.

Quoted 1 line
Quoted 4 lines
Quoted 2 lines

Also export MKTME global keyid that is used to encrypt TDX module and its memory.

This needs explanation why the global keyID needs to be exported.

How about the followings?

TDX private host key id is assigned to guest TD. The memory controller encrypts guest TD memory with the assigned host key id (HIKD). Add helper functions to allocate/free TDX private host key id so that TDX KVM manage it.

Also export the global TDX private host key id that is used to encrypt TDX module, its memory and some dynamic data (e.g. TDR). When VMM releasing encrypted page to reuse it, the page needs to be flushed with the used host key id. VMM needs the global TDX private host key id to flush such pages TDX module accesses with the global TDX private host key id.

Thanks,

Signature · 1 line
Isaku Yamahata <[email protected]>
#73 lore raw

Re: [RFC PATCH v5 024/104] KVM: TDX: create/destroy VM structure

In reply to Kai Huang
Quoted 12 lines · Kai Huang
Quoted 11 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

arch/x86/kvm/vmx/tdx.c +0 -0
index 1c8222f54764..702953fd365f 100644
@@ -31,14 +31,324 @@ struct tdx_capabilities {
 	struct tdx_cpuid_config cpuid_configs[TDX_MAX_NR_CPUID_CONFIGS];
 };
 
Quoted 6 lines

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 36

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+/* KeyID used by TDX module */
+static u32 tdx_global_keyid __read_mostly;
+

It's really not clear why you need to know tdx_global_keyid in the context of creating/destroying a TD.

TDX module mpas TDR with TDX global key id. This page includes key id assigned to this TD. Then, TDX modules maps other TD-related pages with the HKID. TDR requires the TDX global key id for cache flush unlike other TD-related pages.
I'll add a comment.

Quoted 42 lines
Quoted 29 lines
arch/x86/kvm/vmx/tdx.c +21 -0
 /* Capabilities of KVM + the TDX module. */
 struct tdx_capabilities tdx_caps;
 
+static DEFINE_MUTEX(tdx_lock);
 static struct mutex *tdx_mng_key_config_lock;
 
 static u64 hkid_mask __ro_after_init;
 static u8 hkid_start_pos __ro_after_init;
 
+static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
+{
+	pa &= ~hkid_mask;
+	pa |= (u64)hkid << hkid_start_pos;
+
+	return pa;
+}
+
+static inline bool is_td_created(struct kvm_tdx *kvm_tdx)
+{
+	return kvm_tdx->tdr.added;
+}
+
+static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
+{
+	tdx_keyid_free(kvm_tdx->hkid);
+	kvm_tdx->hkid = -1;
+}
+
+static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 75

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+{
+	return kvm_tdx->hkid > 0;
+}
+
+static void tdx_clear_page(unsigned long page)
+{
+	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
+	unsigned long i;
+
+	/* Zeroing the page is only necessary for systems with MKTME-i. */

"only necessary for systems with MKTME-i" because of what?

Quoted 3 lines

Please be more clear that on MKTME-i system, when re-assign one page from old keyid to a new keyid, MOVDIR64B is required to clear/write the page with new keyid to prevent integrity error when read on the page with new keyid.

Let me borrow this sentence as a comment on it.

Quoted 7 lines
Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+static int __tdx_reclaim_page(unsigned long va, hpa_t pa, bool do_wb, u16 hkid)
+{
+	struct tdx_module_output out;
+	u64 err;
+
+	err = tdh_phymem_page_reclaim(pa, &out);
+	if (WARN_ON_ONCE(err)) {
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 96

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+		pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
+		return -EIO;
+	}
+
+	if (do_wb) {

In the callers, please add some comments explaining why do_wb is needed, and why is not needed.

Will do.

Quoted 9 lines
Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+static int tdx_do_tdh_mng_key_config(void *param)
+{
+	hpa_t *tdr_p = param;
+	int cpu, cur_pkg;
+	u64 err;
+
+	cpu = raw_smp_processor_id();
+	cur_pkg = topology_physical_package_id(cpu);
+
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 247

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	mutex_lock(&tdx_mng_key_config_lock[cur_pkg]);
+	do {
+		err = tdh_mng_key_config(*tdr_p);
+	} while (err == TDX_KEY_GENERATION_FAILED);
+	mutex_unlock(&tdx_mng_key_config_lock[cur_pkg]);

Why not squashing patch 20 ("KVM: TDX: allocate per-package mutex") into this patch?

Will do.

Quoted 34 lines
Quoted 34 lines
arch/x86/kvm/vmx/tdx.c +34 -0
+
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+int tdx_vm_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	int ret, i;
+	u64 err;
+
+	/* vCPUs can't be created until after KVM_TDX_INIT_VM. */
+	kvm->max_vcpus = 0;
+
+	kvm_tdx->hkid = tdx_keyid_alloc();
+	if (kvm_tdx->hkid < 0)
+		return -EBUSY;
+
+	ret = tdx_alloc_td_page(&kvm_tdx->tdr);
+	if (ret)
+		goto free_hkid;
+
+	kvm_tdx->tdcs = kcalloc(tdx_caps.tdcs_nr_pages, sizeof(*kvm_tdx->tdcs),
+				GFP_KERNEL_ACCOUNT);
+	if (!kvm_tdx->tdcs)
+		goto free_tdr;
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		ret = tdx_alloc_td_page(&kvm_tdx->tdcs[i]);
+		if (ret)
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 287

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+			goto free_tdcs;
+	}
+
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(kvm_tdx->tdr.pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);

Please add comment explaining why locking is needed.

I'll add a comment on tdx_lock. Not each TDX seamcalls.

Quoted 27 lines
Quoted 14 lines
arch/x86/kvm/vmx/tdx_ops.h +1 -0
index 0bed43879b82..3dd5b4c3f04c 100644
@@ -6,6 +6,7 @@
 
 #include <linux/compiler.h>
 
+#include <asm/cacheflush.h>
 #include <asm/asm.h>
 #include <asm/kvm_host.h>
 
@@ -15,8 +16,14 @@
 

arch/x86/kvm/vmx/tdx_ops.h line 26

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h +6 -0
 #ifdef CONFIG_INTEL_TDX_HOST
 
+static inline void tdx_clflush_page(hpa_t addr)
+{
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+}
+
 static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
 {
+	tdx_clflush_page(addr);

Please add comment to explain why clflush is needed.

Quoted 2 lines

And you don't need the tdx_clflush_page() wrapper -- it's not a TDX specific ops. You can just use clflush_cache_range().

Will remove it.

The plan was to enhance tdx_cflush_page(addr, page_level) to support large page to avoid repeating page_level_to_size. Defer it to large page support.

Signature · 1 line
Isaku Yamahata <[email protected]>
#74 lore raw

Re: [RFC PATCH v5 024/104] KVM: TDX: create/destroy VM structure

Quoted 9 lines · Isaku Yamahata
Quoted 3 lines

It's really not clear why you need to know tdx_global_keyid in the context of
creating/destroying a TD.

TDX module mpas TDR with TDX global key id. This page includes key id assigned to this TD.  Then, TDX modules maps other TD-related pages with the HKID. TDR requires the TDX global key id for cache flush unlike other TD-related pages.
I'll add a comment.

Sorry I forgot this. Thanks.

Signature · 2 lines
Thanks,
-Kai
#104 lore raw

Re: [RFC PATCH v5 032/104] KVM: x86/mmu: introduce config for PRIVATE KVM MMU

In reply to Kai Huang
Quoted 21 lines · Kai Huang
Quoted 20 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To Keep the case of non TDX intact, introduce a new config option for private KVM MMU support. At the moment, this is synonym for CONFIG_INTEL_TDX_HOST && CONFIG_KVM_INTEL. The new flag make it clear that the config is only for x86 KVM MMU.

---
 arch/x86/kvm/Kconfig | 4 ++++
 1 file changed, 4 insertions(+)
arch/x86/kvm/Kconfig +0 -0
index 2b1548da00eb..2db590845927 100644
@@ -136,4 +136,8 @@ config KVM_MMU_AUDIT
 config KVM_EXTERNAL_WRITE_TRACKING
 	bool
 
Quoted 9 lines

arch/x86/kvm/Kconfig config KVM_MMU_AUDIT · line 143

Quoted 5 lines
arch/x86/kvm/Kconfig +4 -0
+config KVM_MMU_PRIVATE
+	def_bool y
+	depends on INTEL_TDX_HOST && KVM_INTEL
+
 endif # VIRTUALIZATION

I am really not sure why need this. Roughly looking at MMU related patches this new config option is hardly used. You have many code changes related to handling private/shared but they are not under this config option.

I don't want to use CONFIG_INTEL_TDX_HOST in KVM MMU code. I think the change to KVM MMU should be a sort of independent from TDX. But it seems failed based on your feedback.

Signature · 1 line
Isaku Yamahata <[email protected]>
#109 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to Kai Huang
Quoted 190 lines · Kai Huang
Quoted 122 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Rick Edgecombe <[email protected]>

Add support in KVM's MMU for aliasing multiple GPAs (from a hardware perspective) to a single GPA (from a memslot perspective). GPA aliasing will be used to repurpose GPA bits as attribute bits, e.g. to expose an execute-only permission bit to the guest. To keep the implementation simple (relatively speaking), GPA aliasing is only supported via TDP.

Today KVM assumes two things that are broken by GPA aliasing.
1. GPAs coming from hardware can be simply shifted to get the GFNs.
2. GPA bits 51:MAXPHYADDR are reserved to zero.

With GPA aliasing, translating a GPA to GFN requires masking off the repurposed bit, and a repurposed bit may reside in 51:MAXPHYADDR.

To support GPA aliasing, introduce the concept of per-VM GPA stolen bits, that is, bits stolen from the GPA to act as new virtualized attribute bits. A bit in the mask will cause the MMU code to create aliases of the GPA. It can also be used to find the GFN out of a GPA coming from a tdp fault.

To handle case (1) from above, retain any stolen bits when passing a GPA in KVM's MMU code, but strip them when converting to a GFN so that the GFN contains only the "real" GFN, i.e. never has repurposed bits set.

GFNs (without stolen bits) continue to be used to:
- Specify physical memory by userspace via memslots
- Map GPAs to TDP PTEs via RMAP
- Specify dirty tracking and write protection
- Look up MTRR types
- Inject async page faults

Since there are now multiple aliases for the same aliased GPA, when userspace memory backing the memslots is paged out, both aliases need to be modified. Fortunately, this happens automatically. Since rmap supports multiple mappings for the same GFN for PTE shadowing based paging, by adding/removing each alias PTE with its GFN, kvm_handle_hva() based operations will be applied to both aliases.

In the case of the rmap being removed in the future, the needed information could be recovered by iterating over the stolen bits and walking the TDP page tables.

For TLB flushes that are address based, make sure to flush both aliases in the case of stolen bits.

Only support stolen bits in 64 bit guest paging modes (long, PAE). Features that use this infrastructure should restrict the stolen bits to exclude the other paging modes. Don't support stolen bits for shadow EPT.

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/mmu.h              | 51 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu/mmu.c          | 19 ++++++++++--
 arch/x86/kvm/mmu/paging_tmpl.h  | 25 +++++++++-------
 4 files changed, 84 insertions(+), 13 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index 208b29b0e637..d8b78d6abc10 100644
@@ -1235,7 +1235,9 @@ struct kvm_arch {
 	spinlock_t hv_root_tdp_lock;
 #endif
 
+#ifdef CONFIG_KVM_MMU_PRIVATE
 	gfn_t gfn_shared_mask;
+#endif
 };
 
 struct kvm_vm_stat {
arch/x86/kvm/mmu.h +41 -0
index e9fbb2c8bbe2..3fb530359f81 100644
@@ -365,4 +365,55 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
 		return gpa;
 	return translate_nested_gpa(vcpu, gpa, access, exception);
 }
+
+static inline gfn_t kvm_gfn_stolen_mask(struct kvm *kvm)
+{
+#ifdef CONFIG_KVM_MMU_PRIVATE
+	return kvm->arch.gfn_shared_mask;
+#else
+	return 0;
+#endif
+}
+
+static inline gpa_t kvm_gpa_stolen_mask(struct kvm *kvm)
+{
+	return gfn_to_gpa(kvm_gfn_stolen_mask(kvm));
+}
+
+static inline gpa_t kvm_gpa_unalias(struct kvm *kvm, gpa_t gpa)
+{
+	return gpa & ~kvm_gpa_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_unalias(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_shared(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn | kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_private(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gpa_t kvm_gpa_private(struct kvm *kvm, gpa_t gpa)
+{
+	return gpa & ~kvm_gpa_stolen_mask(kvm);
+}
+
+static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn)

arch/x86/kvm/mmu.h static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu, · line 418

Quoted 10 lines
arch/x86/kvm/mmu.h +10 -0
+{
+	gfn_t mask = kvm_gfn_stolen_mask(kvm);
+
+	return mask && !(gfn & mask);
+}
+
+static inline bool kvm_is_private_gpa(struct kvm *kvm, gpa_t gpa)
+{
+	return kvm_is_private_gfn(kvm, gpa_to_gfn(gpa));
+}

The patch title and commit message say nothing about private/shared, but only mention stolen bits in general. It's weird to introduce those *private* related helpers here.

I think you can just ditch the concept of stolen bit infrastructure, but just adopt what TDX needs.

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 279

Quoted 11 lines
arch/x86/kvm/mmu.h +0 -0
 #endif
arch/x86/kvm/mmu/mmu.c +1 -1
index 8e24f73bf60b..b68191aa39bf 100644
@@ -276,11 +276,24 @@ static inline bool kvm_available_flush_tlb_with_range(void)
 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
 		struct kvm_tlb_range *range)
 {
-	int ret = -ENOTSUPP;
+	int ret = -EOPNOTSUPP;

Change doesn't belong to this patch.

Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +2 -1
+	u64 gfn_stolen_mask;
 
-	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
+	/*

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 292

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	 * Fall back to the big hammer flush if there is more than one
+	 * GPA alias that needs to be flushed.
+	 */
+	gfn_stolen_mask = kvm_gfn_stolen_mask(kvm);
+	if (hweight64(gfn_stolen_mask) > 1)
+		goto generic_flush;
+
+	if (range && kvm_available_flush_tlb_with_range()) {
+		/* Callback should flush both private GFN and shared GFN. */
+		range->start_gfn = kvm_gfn_unalias(kvm, range->start_gfn);

This seems wrong. It seems the intention of this function is to flush TLB for all aliases for a given GFN range. Here it seems you are unconditionally change to range to always exclude the stolen bits.

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 294

Quoted 2 lines
arch/x86/kvm/mmu/mmu.c +1 -0
 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
+	}

And you always fall through to do big hammer flush, which is obviously not intended.

Quoted 9 lines
arch/x86/kvm/mmu/mmu.c +1 -0
+generic_flush:
 	if (ret)
 		kvm_flush_remote_tlbs(kvm);
 }
@@ -4010,7 +4023,7 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
 	unsigned long mmu_seq;
 	int r;
 
Quoted 5 lines

arch/x86/kvm/mmu/mmu.c static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault · line 4029

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +1 -1
-	fault->gfn = fault->addr >> PAGE_SHIFT;
+	fault->gfn = kvm_gfn_unalias(vcpu->kvm, gpa_to_gfn(fault->addr));
 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
 
 	if (page_fault_handle_page_track(vcpu, fault))

Looking at code more, I think this patch is broken. There are couple of issues if I understand correctly:

- Rick's original patch has stolen_bits_mask encoded in 'struct kvm_mmu_page', so basically a new page table is allocated for different aliasing GPA. Sean suggested to use role.private instead of stolen_bits_mask so I changed but that was lost in this patch too. Therefore essentially, with this patch, all aliasing GFNs share the same page table and the same mapping. There's slight difference between TDP MMU and legacy MMU, that the former purely uses 'fault-

Quoted 1 line

gfn' (which doesn't have aliasing bit) to iterate page table and the latter

uses 'fault->addr' (which contains the aliasing bit), but this makes little difference. With this patch, all aliasing GFNs share page table and the mapping. This is not what we want, and this is wrong.

- The original change to get GFN w/o aliasing for MTRR check (below) is lost. And there are some other changes that are also lost (such as don't support aliasing for private (user-invisible, not TDX private) memory slot), but it's not immediately apparent to me whether this is an issue.

@@ -3833,7 +3865,7 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
max_level > PG_LEVEL_4K;
max_level--) {
int page_num = KVM_PAGES_PER_HPAGE(max_level);
- gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
+ gfn_t base = vcpu_gpa_to_gfn_unalias(vcpu, gpa) & ~(page_num -
1);

Another thing is above change to kvm_flush_remote_tlbs_with_range() to make it flush TLBs for mappings for all aliasing for a given GFN range doesn't fit for TDX. TDX private mapping and shared mapping cannot co-exist therefore when a page that has multiple aliasing mapped to it is taken out, only one mapping is valid (not to mention private page cannot be taken out). This is one of the reasons that I think this GPA stolen bits infrastructure isn't that mandatory for TDX. I think it's OK to ditch this infrastructure and adopt what TDX needs (the concept of private/shared mapping).

Signature · 2 lines
Thanks,
-Kai
#105 lore raw

Re: [RFC PATCH v5 032/104] KVM: x86/mmu: introduce config for PRIVATE KVM MMU

In reply to Isaku Yamahata
Quoted 34 lines · Isaku Yamahata
Quoted 21 lines · Kai Huang
Quoted 20 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To Keep the case of non TDX intact, introduce a new config option for private KVM MMU support. At the moment, this is synonym for CONFIG_INTEL_TDX_HOST && CONFIG_KVM_INTEL. The new flag make it clear that the config is only for x86 KVM MMU.

---
 arch/x86/kvm/Kconfig | 4 ++++
 1 file changed, 4 insertions(+)
arch/x86/kvm/Kconfig +0 -0
index 2b1548da00eb..2db590845927 100644
@@ -136,4 +136,8 @@ config KVM_MMU_AUDIT
 config KVM_EXTERNAL_WRITE_TRACKING
 	bool
 
Quoted 9 lines

arch/x86/kvm/Kconfig config KVM_MMU_AUDIT · line 143

Quoted 5 lines
arch/x86/kvm/Kconfig +4 -0
+config KVM_MMU_PRIVATE
+	def_bool y
+	depends on INTEL_TDX_HOST && KVM_INTEL
+
 endif # VIRTUALIZATION

I am really not sure why need this. Roughly looking at MMU related patches this new config option is hardly used. You have many code changes related to handling private/shared but they are not under this config option.

Quoted 3 lines

I don't want to use CONFIG_INTEL_TDX_HOST in KVM MMU code. I think the change to KVM MMU should be a sort of independent from TDX. But it seems failed based on your feedback.

Why do you need to use any config? As I said majority of your changes to MMU are not under any config. But I'll leave this to maintainer/reviewers.

Signature · 2 lines
Thanks,
-Kai
#110 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to Kai Huang

Added Peng Chao.

Quoted 138 lines · Kai Huang
Quoted 122 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Rick Edgecombe <[email protected]>

Add support in KVM's MMU for aliasing multiple GPAs (from a hardware perspective) to a single GPA (from a memslot perspective). GPA aliasing will be used to repurpose GPA bits as attribute bits, e.g. to expose an execute-only permission bit to the guest. To keep the implementation simple (relatively speaking), GPA aliasing is only supported via TDP.

Today KVM assumes two things that are broken by GPA aliasing.
1. GPAs coming from hardware can be simply shifted to get the GFNs.
2. GPA bits 51:MAXPHYADDR are reserved to zero.

With GPA aliasing, translating a GPA to GFN requires masking off the repurposed bit, and a repurposed bit may reside in 51:MAXPHYADDR.

To support GPA aliasing, introduce the concept of per-VM GPA stolen bits, that is, bits stolen from the GPA to act as new virtualized attribute bits. A bit in the mask will cause the MMU code to create aliases of the GPA. It can also be used to find the GFN out of a GPA coming from a tdp fault.

To handle case (1) from above, retain any stolen bits when passing a GPA in KVM's MMU code, but strip them when converting to a GFN so that the GFN contains only the "real" GFN, i.e. never has repurposed bits set.

GFNs (without stolen bits) continue to be used to:
- Specify physical memory by userspace via memslots
- Map GPAs to TDP PTEs via RMAP
- Specify dirty tracking and write protection
- Look up MTRR types
- Inject async page faults

Since there are now multiple aliases for the same aliased GPA, when userspace memory backing the memslots is paged out, both aliases need to be modified. Fortunately, this happens automatically. Since rmap supports multiple mappings for the same GFN for PTE shadowing based paging, by adding/removing each alias PTE with its GFN, kvm_handle_hva() based operations will be applied to both aliases.

In the case of the rmap being removed in the future, the needed information could be recovered by iterating over the stolen bits and walking the TDP page tables.

For TLB flushes that are address based, make sure to flush both aliases in the case of stolen bits.

Only support stolen bits in 64 bit guest paging modes (long, PAE). Features that use this infrastructure should restrict the stolen bits to exclude the other paging modes. Don't support stolen bits for shadow EPT.

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/mmu.h              | 51 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu/mmu.c          | 19 ++++++++++--
 arch/x86/kvm/mmu/paging_tmpl.h  | 25 +++++++++-------
 4 files changed, 84 insertions(+), 13 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index 208b29b0e637..d8b78d6abc10 100644
@@ -1235,7 +1235,9 @@ struct kvm_arch {
 	spinlock_t hv_root_tdp_lock;
 #endif
 
+#ifdef CONFIG_KVM_MMU_PRIVATE
 	gfn_t gfn_shared_mask;
+#endif
 };
 
 struct kvm_vm_stat {
arch/x86/kvm/mmu.h +41 -0
index e9fbb2c8bbe2..3fb530359f81 100644
@@ -365,4 +365,55 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
 		return gpa;
 	return translate_nested_gpa(vcpu, gpa, access, exception);
 }
+
+static inline gfn_t kvm_gfn_stolen_mask(struct kvm *kvm)
+{
+#ifdef CONFIG_KVM_MMU_PRIVATE
+	return kvm->arch.gfn_shared_mask;
+#else
+	return 0;
+#endif
+}
+
+static inline gpa_t kvm_gpa_stolen_mask(struct kvm *kvm)
+{
+	return gfn_to_gpa(kvm_gfn_stolen_mask(kvm));
+}
+
+static inline gpa_t kvm_gpa_unalias(struct kvm *kvm, gpa_t gpa)
+{
+	return gpa & ~kvm_gpa_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_unalias(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_shared(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn | kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_private(struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_stolen_mask(kvm);
+}
+
+static inline gpa_t kvm_gpa_private(struct kvm *kvm, gpa_t gpa)
+{
+	return gpa & ~kvm_gpa_stolen_mask(kvm);
+}
+
+static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn)

arch/x86/kvm/mmu.h static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu, · line 418

Quoted 10 lines
arch/x86/kvm/mmu.h +10 -0
+{
+	gfn_t mask = kvm_gfn_stolen_mask(kvm);
+
+	return mask && !(gfn & mask);
+}
+
+static inline bool kvm_is_private_gpa(struct kvm *kvm, gpa_t gpa)
+{
+	return kvm_is_private_gfn(kvm, gpa_to_gfn(gpa));
+}

The patch title and commit message say nothing about private/shared, but only mention stolen bits in general. It's weird to introduce those *private* related helpers here.

Quoted 2 lines

I think you can just ditch the concept of stolen bit infrastructure, but just adopt what TDX needs.

Sure, this patch heavily changed from the original patch Now. One suggestion is that private/shared is characteristic to kvm page fault, not gpa/gfn. It's TDX specific.

- Add a helper function to check if KVM MMU is TD or VM. Right now kvm_gfn_stolen_mask() is used. Probably kvm_mmu_has_private_bit(). (any better name?)
- Let's keep address conversion functions: address => unalias/shared/private
- Add struct kvm_page_fault.is_private
see how kvm_is_private_{gpa, gfn}() can be removed (or reduced).

Quoted 4 lines
Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +0 -0
index 8e24f73bf60b..b68191aa39bf 100644
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 279

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +1 -1
@@ -276,11 +276,24 @@ static inline bool kvm_available_flush_tlb_with_range(void)
 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
 		struct kvm_tlb_range *range)
 {
-	int ret = -ENOTSUPP;
+	int ret = -EOPNOTSUPP;

Change doesn't belong to this patch.

Will fix it.

Quoted 18 lines
Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +2 -1
+	u64 gfn_stolen_mask;
 
-	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
+	/*

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 292

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	 * Fall back to the big hammer flush if there is more than one
+	 * GPA alias that needs to be flushed.
+	 */
+	gfn_stolen_mask = kvm_gfn_stolen_mask(kvm);
+	if (hweight64(gfn_stolen_mask) > 1)
+		goto generic_flush;
+
+	if (range && kvm_available_flush_tlb_with_range()) {
+		/* Callback should flush both private GFN and shared GFN. */
+		range->start_gfn = kvm_gfn_unalias(kvm, range->start_gfn);

This seems wrong. It seems the intention of this function is to flush TLB for all aliases for a given GFN range. Here it seems you are unconditionally change to range to always exclude the stolen bits.

Ooh, right. This alias knowledge is in TDX. This unalias should be dropped and put it in tdx.c. I'll fix it.

Quoted 5 lines

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 294

Quoted 2 lines
arch/x86/kvm/mmu/mmu.c +1 -0
 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
+	}

And you always fall through to do big hammer flush, which is obviously not intended.

Please notice "if (ret)". If it succeeded, big hammer flush is skipped.

Quoted 113 lines
Quoted 113 lines
arch/x86/kvm/mmu/mmu.c +2 -1
+generic_flush:
 	if (ret)
 		kvm_flush_remote_tlbs(kvm);
 }
@@ -4010,7 +4023,7 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
 	unsigned long mmu_seq;
 	int r;
 
-	fault->gfn = fault->addr >> PAGE_SHIFT;
+	fault->gfn = kvm_gfn_unalias(vcpu->kvm, gpa_to_gfn(fault->addr));
 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
 
 	if (page_fault_handle_page_track(vcpu, fault))
arch/x86/kvm/mmu/paging_tmpl.h +14 -9
index 5b5bdac97c7b..70aec31dee06 100644
@@ -25,7 +25,8 @@
 	#define guest_walker guest_walker64
 	#define FNAME(name) paging##64_##name
 	#define PT_BASE_ADDR_MASK GUEST_PT64_BASE_ADDR_MASK
-	#define PT_LVL_ADDR_MASK(lvl) PT64_LVL_ADDR_MASK(lvl)
+	#define PT_LVL_ADDR_MASK(vcpu, lvl) (~kvm_gpa_stolen_mask(vcpu->kvm) & \
+					     PT64_LVL_ADDR_MASK(lvl))
 	#define PT_LVL_OFFSET_MASK(lvl) PT64_LVL_OFFSET_MASK(lvl)
 	#define PT_INDEX(addr, level) PT64_INDEX(addr, level)
 	#define PT_LEVEL_BITS PT64_LEVEL_BITS
@@ -44,7 +45,7 @@
 	#define guest_walker guest_walker32
 	#define FNAME(name) paging##32_##name
 	#define PT_BASE_ADDR_MASK PT32_BASE_ADDR_MASK
-	#define PT_LVL_ADDR_MASK(lvl) PT32_LVL_ADDR_MASK(lvl)
+	#define PT_LVL_ADDR_MASK(vcpu, lvl) PT32_LVL_ADDR_MASK(lvl)
 	#define PT_LVL_OFFSET_MASK(lvl) PT32_LVL_OFFSET_MASK(lvl)
 	#define PT_INDEX(addr, level) PT32_INDEX(addr, level)
 	#define PT_LEVEL_BITS PT32_LEVEL_BITS
@@ -58,7 +59,7 @@
 	#define guest_walker guest_walkerEPT
 	#define FNAME(name) ept_##name
 	#define PT_BASE_ADDR_MASK GUEST_PT64_BASE_ADDR_MASK
-	#define PT_LVL_ADDR_MASK(lvl) PT64_LVL_ADDR_MASK(lvl)
+	#define PT_LVL_ADDR_MASK(vcpu, lvl) PT64_LVL_ADDR_MASK(lvl)
 	#define PT_LVL_OFFSET_MASK(lvl) PT64_LVL_OFFSET_MASK(lvl)
 	#define PT_INDEX(addr, level) PT64_INDEX(addr, level)
 	#define PT_LEVEL_BITS PT64_LEVEL_BITS
@@ -75,7 +76,7 @@
 #define PT_GUEST_ACCESSED_MASK (1 << PT_GUEST_ACCESSED_SHIFT)
 
 #define gpte_to_gfn_lvl FNAME(gpte_to_gfn_lvl)
-#define gpte_to_gfn(pte) gpte_to_gfn_lvl((pte), PG_LEVEL_4K)
+#define gpte_to_gfn(vcpu, pte) gpte_to_gfn_lvl(vcpu, pte, PG_LEVEL_4K)
 
 /*
  * The guest_walker structure emulates the behavior of the hardware page
@@ -96,9 +97,9 @@ struct guest_walker {
 	struct x86_exception fault;
 };
 
-static gfn_t gpte_to_gfn_lvl(pt_element_t gpte, int lvl)
+static gfn_t gpte_to_gfn_lvl(struct kvm_vcpu *vcpu, pt_element_t gpte, int lvl)
 {
-	return (gpte & PT_LVL_ADDR_MASK(lvl)) >> PAGE_SHIFT;
+	return (gpte & PT_LVL_ADDR_MASK(vcpu, lvl)) >> PAGE_SHIFT;
 }
 
 static inline void FNAME(protect_clean_gpte)(struct kvm_mmu *mmu, unsigned *access,
@@ -395,7 +396,7 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 		--walker->level;
 
 		index = PT_INDEX(addr, walker->level);
-		table_gfn = gpte_to_gfn(pte);
+		table_gfn = gpte_to_gfn(vcpu, pte);
 		offset    = index * sizeof(pt_element_t);
 		pte_gpa   = gfn_to_gpa(table_gfn) + offset;
 
@@ -460,7 +461,7 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 	if (unlikely(errcode))
 		goto error;
 
-	gfn = gpte_to_gfn_lvl(pte, walker->level);
+	gfn = gpte_to_gfn_lvl(vcpu, pte, walker->level);
 	gfn += (addr & PT_LVL_OFFSET_MASK(walker->level)) >> PAGE_SHIFT;
 
 	if (PTTYPE == 32 && walker->level > PG_LEVEL_4K && is_cpuid_PSE36())
@@ -555,12 +556,14 @@ FNAME(prefetch_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
 	gfn_t gfn;
 	kvm_pfn_t pfn;
 
+	WARN_ON(gpte & kvm_gpa_stolen_mask(vcpu->kvm));
+
 	if (FNAME(prefetch_invalid_gpte)(vcpu, sp, spte, gpte))
 		return false;
 
 	pgprintk("%s: gpte %llx spte %p\n", __func__, (u64)gpte, spte);
 
-	gfn = gpte_to_gfn(gpte);
+	gfn = gpte_to_gfn(vcpu, gpte);
 	pte_access = sp->role.access & FNAME(gpte_access)(gpte);
 	FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
 
@@ -656,6 +659,8 @@ static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
 	WARN_ON_ONCE(gw->gfn != base_gfn);
 	direct_access = gw->pte_access;
 
+	WARN_ON(fault->addr & kvm_gpa_stolen_mask(vcpu->kvm));
+
 	top_level = vcpu->arch.mmu->root_level;
 	if (top_level == PT32E_ROOT_LEVEL)
 		top_level = PT32_ROOT_LEVEL;
@@ -1080,7 +1085,7 @@ static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 			continue;
 		}
 
Quoted 9 lines

arch/x86/kvm/mmu/paging_tmpl.h static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1091

Quoted 5 lines
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
-		gfn = gpte_to_gfn(gpte);
+		gfn = gpte_to_gfn(vcpu, gpte);
 		pte_access = sp->role.access;
 		pte_access &= FNAME(gpte_access)(gpte);
 		FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);

In commit message you mentioned "Don't support stolen bits for shadow EPT" (you actually mean shadow MMU I suppose), yet there's bunch of code change to shadow MMU.

Those are not needed. I'll drop them.

Signature · 1 line
Isaku Yamahata <[email protected]>
#26 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to a message not in the archive

The original reply was sent to Sean only by mistake. Add others back.

Quoted 48 lines · Chao Gao
Quoted 21 lines · Sean Christopherson

+Chao Gao

Quoted 11 lines · Isaku Yamahata
Quoted 8 lines · Sean Christopherson
Quoted 4 lines · Isaku Yamahata

- VMXON on all pCPUs: The TDX module initialization requires to enable VMX (VMXON) on all present pCPUs. vmx_hardware_enable() which is called on creating guest does it. It naturally fits with the TDX module initialization at creating first TD. I wanted to avoid code to enable VMXON on loading the kvm_intel.ko.

That's a solvable problem, though making it work without exporting hardware_enable_all() could get messy.

Could you please explain any reason why it's bad idea to export it?

I'd really prefer to keep the hardware enable/disable logic internal to kvm_main.c so that all architectures share a common flow, and so that kvm_main.c is the sole owner. I'm worried that exposing the helper will lead to other arch/vendor usage, and that will end up with what is effectively duplicate flows. Deduplicating arch code into generic KVM is usually very difficult.

Quoted 7 lines

This might also be a good opportunity to make KVM slightly more robust. Ooh, and we can kill two birds with one stone. There's an in-flight series to add compatibility checks to hotplug[*]. But rather than special case hotplug, what if we instead do hardware enable/disable during module load, and move the compatibility check into the hardware_enable path? That fixes the hotplug issue, gives TDX a window for running post-VMXON code in kvm_init(), and makes the broadcast IPI less wasteful on architectures that don't have compatiblity checks.

Sounds good. But more time is wasted on compat checks on architectures that have them because they are done each time of enabling hardware. A solution for this is caching the result of kvm_arch_check_processor_compat().

Quoted 7 lines

I'm thinking something like this, maybe as a modificatyion to patch 6 in Chao's series, or more likely as a patch 7 so that the hotplug compat checks still get in even

if the early hardware enable doesn't work on all architectures for some reason.

By "early", do you mean hardware enable during module loading or during CPU hotplug?

And if below change is put into my series, kvm_arch_post_hardware_enable_setup() will be an empty function for all architectures until TDX series gets merged. So, I prefer to drop kvm_arch_post_hardware_enable_setup() and let TDX series introduce it.

#122 lore raw

Re: [RFC PATCH v5 037/104] KVM: x86/mmu: Allow non-zero init value for shadow PTE

In reply to [email protected]
Quoted 5 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TDX will run with EPT violation #VEs enabled for shared EPT, which means KVM needs to set the "suppress #VE" bit in unused PTEs to avoid unintentionally reflecting not-present EPT violations into the guest.

This sentence is hard to interpret. Please add more sentences to elaborate "TDX will run with EPT violation #VEs enabled for shared EPT". Also, this patch is the first time to introduce "shared EPT", perhaps you should also explain it here. Or even you can move patch 43 ("KVM: TDX: Add load_mmu_pgd method for TDX") before this one.

"reflecting non-present EPT violations into the guest" could be hard to interpret. Perhaps you can be more explicit to say VMM wants to get EPT violation for normal (shared) memory access rather than to cause #VE to guest.

Mentioning you want EPT violation instead of #VE for normal (shared) memory access also completes your statement of wanting #VE for MMIO below, so that people can have a clear picture when to get a #VE when not.

Quoted 5 lines

Because guest memory is protected with TDX, VMM can't parse instructions in the guest memory. Instead, MMIO hypercall is used to pass necessary information to VMM.

Quoted 7 lines

To make unmodified device driver work, guest TD expects #VE on accessing shared GPA. The #VE handler converts MMIO access into MMIO hypercall with the EPT entry of enabled "#VE" by clearing "suppress #VE" bit. Before VMM enabling #VE, it needs to figure out the given GPA is for MMIO by EPT violation. So the execution flow looks like

- allocate unused shared EPT entry with suppress #VE bit set.

allocate -> Allocate

Quoted 4 lines

- EPT violation on that GPA.
- VMM figures out the faulted GPA is for MMIO.
- VMM clears the suppress #VE bit.
- Guest TD gets #VE, and converts MMIO access into MMIO hypercall.

Here you have described both normal memory access and MMIO, it's good time to summarize the purpose of this patch: For both cases you want PTE with "suppress #VE" bit set initially when it is allocated, therefore allow non-zero init value for PTE.

Quoted 27 lines
---
 arch/x86/kvm/mmu.h      |  1 +
 arch/x86/kvm/mmu/mmu.c  | 50 +++++++++++++++++++++++++++++++++++------
 arch/x86/kvm/mmu/spte.c | 10 +++++++++
 arch/x86/kvm/mmu/spte.h |  2 ++
 4 files changed, 56 insertions(+), 7 deletions(-)
arch/x86/kvm/mmu.h +1 -0
index 3fb530359f81..0ae91b8b25df 100644
@@ -66,6 +66,7 @@ static __always_inline u64 rsvd_bits(int s, int e)
 
 void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask);
 void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only);
+void kvm_mmu_set_spte_init_value(u64 init_value);
 
 void kvm_init_mmu(struct kvm_vcpu *vcpu);
 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
arch/x86/kvm/mmu/mmu.c +0 -0
index 9907cb759fd1..a474f2e76d78 100644

arch/x86/kvm/mmu/mmu.c static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep) · line 622

Quoted 8 lines
arch/x86/kvm/mmu/mmu.c +2 -2
@@ -617,9 +617,9 @@ static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
 	int level = sptep_to_sp(sptep)->role.level;
 
 	if (!spte_has_volatile_bits(old_spte))
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, shadow_init_value);
 	else
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep, shadow_init_value);

I guess it's better to have some comment here. Allow non-zero init value for shadow PTE doesn't necessarily mean the initial value should be used when one PTE is zapped. I think mmu_spte_clear_track_bits() is only called for mapping of normal (shared) memory but not MMIO? Then perhaps it's better to have a comment to explain we want "suppress #VE" set to get a real EPT violation for normal memory access from guest?

arch/x86/kvm/mmu/mmu.c static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep) · line 655

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +1 -1
 	if (!is_shadow_present_pte(old_spte))
 		return old_spte;
@@ -651,7 +651,7 @@ static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
  */
 static void mmu_spte_clear_no_track(u64 *sptep)
 {
-	__update_clear_spte_fast(sptep, 0ull);
+	__update_clear_spte_fast(sptep, shadow_init_value);
 }

Similar here. Seems mmu_spte_clear_no_track() is used to zap non-leaf PTE which doesn't require state tracking, so theoretically it can be set to 0. But this seems is also called to zap MMIO PTE so looks need to set to shadow_init_value. Anyway looks deserve a comment?

Btw, Above two changes to mmu_spte_clear_track_bits() and mmu_spte_clear_track_bits() seems a little bit out-of-scope of what this patch claims to do. Allow non-zero init value for shadow PTE doesn't necessarily mean the initial value should be used when one PTE is zapped. Maybe we can further improve the patch title and commit message a little bit. Such as: Allow non- zero value for empty (or invalid?) PTE? Non-present seems doesn't fit here.

Quoted 56 lines
arch/x86/kvm/mmu/mmu.c +37 -2
 static u64 mmu_spte_get_lockless(u64 *sptep)
@@ -737,6 +737,42 @@ static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
 	}
 }
 
+static inline void kvm_init_shadow_page(void *page)
+{
+#ifdef CONFIG_X86_64
+	int ign;
+
+	asm volatile (
+		"rep stosq\n\t"
+		: "=c"(ign), "=D"(page)
+		: "a"(shadow_init_value), "c"(4096/8), "D"(page)
+		: "memory"
+	);
+#else
+	BUG();
+#endif
+}
+
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+	struct kvm_mmu_memory_cache *mc = &vcpu->arch.mmu_shadow_page_cache;
+	int start, end, i, r;
+
+	if (shadow_init_value)
+		start = kvm_mmu_memory_cache_nr_free_objects(mc);
+
+	r = kvm_mmu_topup_memory_cache(mc, PT64_ROOT_MAX_LEVEL);
+	if (r)
+		return r;
+
+	if (shadow_init_value) {
+		end = kvm_mmu_memory_cache_nr_free_objects(mc);
+		for (i = start; i < end; i++)
+			kvm_init_shadow_page(mc->objects[i]);
+	}
+	return 0;
+}
+
 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 {
 	int r;
@@ -746,8 +782,7 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
 	if (r)
 		return r;
-	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
-				       PT64_ROOT_MAX_LEVEL);
+	r = mmu_topup_shadow_page_cache(vcpu);
 	if (r)
 		return r;
 	if (maybe_indirect) {

arch/x86/kvm/mmu/mmu.c static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 3184

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +1 -1
@@ -3146,7 +3181,7 @@ static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 {
 	struct kvm_mmu_page *sp;
 	int ret = RET_PF_INVALID;
-	u64 spte = 0ull;
+	u64 spte = shadow_init_value;

I don't quite understand this change. 'spte' is set to the last level PTE of the given GFN if mapping is found. Otherwise fast_page_fault() returns RET_PF_INVALID. In both cases, the initial value doesn't matter.

Am I wrong?

Quoted 61 lines
arch/x86/kvm/mmu/mmu.c +2 -1
 	u64 *sptep = NULL;
 	uint retry_count = 0;
 
@@ -5598,7 +5633,8 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
 
-	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
+	if (!shadow_init_value)
+		vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
 
 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
arch/x86/kvm/mmu/spte.c +10 -0
index 73cfe62fdad1..5071e8332db2 100644
@@ -35,6 +35,7 @@ u64 __read_mostly shadow_mmio_access_mask;
 u64 __read_mostly shadow_present_mask;
 u64 __read_mostly shadow_me_mask;
 u64 __read_mostly shadow_acc_track_mask;
+u64 __read_mostly shadow_init_value;
 
 u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
 u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
@@ -223,6 +224,14 @@ u64 kvm_mmu_changed_pte_notifier_make_spte(u64 old_spte, kvm_pfn_t new_pfn)
 	return new_spte;
 }
 
+void kvm_mmu_set_spte_init_value(u64 init_value)
+{
+	if (WARN_ON(!IS_ENABLED(CONFIG_X86_64) && init_value))
+		init_value = 0;
+	shadow_init_value = init_value;
+}
+EXPORT_SYMBOL_GPL(kvm_mmu_set_spte_init_value);
+
 static u8 kvm_get_shadow_phys_bits(void)
 {
 	/*
@@ -367,6 +376,7 @@ void kvm_mmu_reset_all_pte_masks(void)
 	shadow_present_mask	= PT_PRESENT_MASK;
 	shadow_acc_track_mask	= 0;
 	shadow_me_mask		= sme_me_mask;
+	shadow_init_value	= 0;
 
 	shadow_host_writable_mask = DEFAULT_SPTE_HOST_WRITEABLE;
 	shadow_mmu_writable_mask  = DEFAULT_SPTE_MMU_WRITEABLE;
arch/x86/kvm/mmu/spte.h +2 -0
index be6a007a4af3..8e13a35ab8c9 100644
@@ -171,6 +171,8 @@ extern u64 __read_mostly shadow_mmio_access_mask;
 extern u64 __read_mostly shadow_present_mask;
 extern u64 __read_mostly shadow_me_mask;
 
+extern u64 __read_mostly shadow_init_value;
+
 /*
  * SPTEs in MMUs without A/D bits are marked with SPTE_TDP_AD_DISABLED_MASK;
  * shadow_acc_track_mask is the set of bits to be cleared in non-accessed
#129 lore raw

Re: [RFC PATCH v5 038/104] KVM: x86/mmu: Allow per-VM override of the TDP max page level

In reply to [email protected]
Quoted 6 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Quoted 7 lines

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it.

For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

Do not support large page for TD is the reason that you want this change, but not the result. Please refine a little bit.

Quoted 47 lines
---
 arch/x86/include/asm/kvm_host.h | 1 +
 arch/x86/kvm/mmu.h              | 2 +-
 arch/x86/kvm/mmu/mmu.c          | 2 ++
 3 files changed, 4 insertions(+), 1 deletion(-)
arch/x86/include/asm/kvm_host.h +1 -0
index d8b78d6abc10..d33d79f2af2d 100644
@@ -1053,6 +1053,7 @@ struct kvm_arch {
 	unsigned long n_requested_mmu_pages;
 	unsigned long n_max_mmu_pages;
 	unsigned int indirect_shadow_pages;
+	int tdp_max_page_level;
 	u8 mmu_valid_gen;
 	struct hlist_head mmu_page_hash[KVM_NUM_MMU_PAGES];
 	struct list_head active_mmu_pages;
arch/x86/kvm/mmu.h +1 -1
index 0ae91b8b25df..650989c37f2e 100644
@@ -192,7 +192,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 		.is_tdp = likely(vcpu->arch.mmu->page_fault == kvm_tdp_page_fault),
 		.nx_huge_page_workaround_enabled = is_nx_huge_page_enabled(),
 
-		.max_level = KVM_MAX_HUGEPAGE_LEVEL,
+		.max_level = vcpu->kvm->arch.tdp_max_page_level,
 		.req_level = PG_LEVEL_4K,
 		.goal_level = PG_LEVEL_4K,
 	};
arch/x86/kvm/mmu/mmu.c +2 -0
index a474f2e76d78..e9212394a530 100644
@@ -5782,6 +5782,8 @@ void kvm_mmu_init_vm(struct kvm *kvm)
 	node->track_write = kvm_mmu_pte_write;
 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
 	kvm_page_track_register_notifier(kvm, node);
+
+	kvm->arch.tdp_max_page_level = KVM_MAX_HUGEPAGE_LEVEL;
 }
 
 void kvm_mmu_uninit_vm(struct kvm *kvm)
#29 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to Isaku Yamahata
Quoted 11 lines · Isaku Yamahata
Quoted 8 lines · Kai Huang
Quoted 6 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a wrapper function to initialize the TDX module and get system-wide parameters via those APIs. Because TDX requires VMX enabled, It will be called on-demand when the first guest TD is created via x86 KVM init_vm callback.

Quoted 7 lines
Quoted 3 lines

Why not just merge this patch with the change where you implement the init_vm callback? Then you can just declare this patch as "detect and initialize TDX module when first VM is created", or something like that..

Ok. Anyway in the next respoin, tdx module initialization will be done when loading kvm_intel.ko. So the whole part will be changed and will be a part of module loading.

Will we change the GET_TDX_CAPABILITIES ioctl back to KVM scope?

#123 lore raw

Re: [RFC PATCH v5 037/104] KVM: x86/mmu: Allow non-zero init value for shadow PTE

In reply to Kai Huang
Quoted 12 lines · Kai Huang
Quoted 12 lines
arch/x86/kvm/mmu/mmu.c +0 -0
@@ -617,9 +617,9 @@ static int mmu_spte_clear_track_bits(struct kvm *kvm,
 u64 *sptep)
   	int level = sptep_to_sp(sptep)->role.level;


   if (!spte_has_volatile_bits(old_spte))

arch/x86/kvm/mmu/mmu.c +1 -1
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, shadow_init_value);

   else

arch/x86/kvm/mmu/mmu.c +1 -1
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep,
Quoted 8 lines
Quoted 1 line

shadow_init_value);

I guess it's better to have some comment here.  Allow non-zero init value for shadow PTE doesn't necessarily mean the initial value should be used when one PTE is zapped.  I think mmu_spte_clear_track_bits() is only called for mapping of normal (shared) memory but not MMIO? Then perhaps it's better to have a comment to explain we want "suppress #VE" set to get a real EPT violation for normal memory access from guest?

Btw, I think the relevant part of TDP MMU change should be included in this patch too otherwise TDP MMU is broken with this patch.

Actually in this series legacy MMU is not supported to work with TDX, so above change to legacy MMU doesn't matter actually. Instead, TDP MMU change should be here.

Signature · 2 lines
Thanks,
-Kai
#130 lore raw

Re: [RFC PATCH v5 038/104] KVM: x86/mmu: Allow per-VM override of the TDP max page level

In reply to Kai Huang
Quoted 11 lines · Kai Huang
Quoted 10 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it.

Quoted 6 lines
Quoted 3 lines

For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

Do not support large page for TD is the reason that you want this change, but not the result. Please refine a little bit.

Not supporting huge pages was fine for the PoC, but I'd prefer not to merge TDX without support for huge pages. Has any work been put into enabling huge pages? If so, what's the technical blocker? If not...

#30 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to Xiaoyao Li
Quoted 16 lines · Xiaoyao Li
Quoted 15 lines · Isaku Yamahata
Quoted 11 lines · Kai Huang
Quoted 6 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a wrapper function to initialize the TDX module and get system-wide parameters via those APIs. Because TDX requires VMX enabled, It will be called on-demand when the first guest TD is created via x86 KVM init_vm callback.

Why not just merge this patch with the change where you implement the init_vm callback? Then you can just declare this patch as "detect and initialize TDX module when first VM is created", or something like that..

Quoted 5 lines
Quoted 3 lines

Ok. Anyway in the next respoin, tdx module initialization will be done when loading kvm_intel.ko. So the whole part will be changed and will be a part of module loading.

Will we change the GET_TDX_CAPABILITIES ioctl back to KVM scope?

No because it system scoped KVM_TDX_CAPABILITIES requires one more callback for it. We can reduce the change.

Or do you have any use case for system scoped KVM_TDX_CAPABILITIES?

Signature · 1 line
Isaku Yamahata <[email protected]>
#131 lore raw

Re: [RFC PATCH v5 038/104] KVM: x86/mmu: Allow per-VM override of the TDP max page level

In reply to Sean Christopherson
Quoted 16 lines · Sean Christopherson
Quoted 15 lines · Kai Huang
Quoted 13 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it.

For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

Quoted 6 lines
Quoted 2 lines

Do not support large page for TD is the reason that you want this change, but not the result. Please refine a little bit.

Not supporting huge pages was fine for the PoC, but I'd prefer not to merge TDX without support for huge pages. Has any work been put into enabling huge pages? If so, what's the technical blocker? If not...

I wanted to get feedback on the approach (always set SPTE to REMOVED_SPTE, callback, set the SPTE to the final value instead of relying atomic update SPTE) before going further for large page.

Signature · 1 line
Isaku Yamahata <[email protected]>
#132 lore raw

Re: [RFC PATCH v5 038/104] KVM: x86/mmu: Allow per-VM override of the TDP max page level

Quoted 22 lines · Isaku Yamahata
Quoted 19 lines · Sean Christopherson
Quoted 17 lines · Kai Huang
Quoted 6 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Quoted 7 lines

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it.

For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

Do not support large page for TD is the reason that you want this change, but not the result. Please refine a little bit.

Quoted 7 lines
Quoted 3 lines

Not supporting huge pages was fine for the PoC, but I'd prefer not to merge TDX without support for huge pages. Has any work been put into enabling huge pages? If so, what's the technical blocker? If not...

I wanted to get feedback on the approach (always set SPTE to REMOVED_SPTE, callback, set the SPTE to the final value instead of relying atomic update SPTE) before going further for large page.

Pretty please with a cherry on top, send an email calling out which areas and patches you'd like "immediate" feedback on. Putting that information in the cover letter would have been extremely helpful. I realize it's hard to balance providing context for folks who don't know TDX with "instructions" for reviewers, but one of the most helpful things you can do for reviewers is to make it explicitly clear
what _your_ expectations and wants are, _why_ you posted the series. Usually that
information is implied, i.e. you want your patches merged, but that's obviously not the case here.

#133 lore raw

Re: [RFC PATCH v5 038/104] KVM: x86/mmu: Allow per-VM override of the TDP max page level

In reply to Sean Christopherson
Quoted 16 lines · Sean Christopherson
Quoted 15 lines · Kai Huang
Quoted 13 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it.

For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

Quoted 6 lines
Quoted 2 lines

Do not support large page for TD is the reason that you want this change, but not the result. Please refine a little bit.

Not supporting huge pages was fine for the PoC, but I'd prefer not to merge TDX without support for huge pages. Has any work been put into enabling huge pages? If so, what's the technical blocker? If not...

Hi Sean,

Is there any reason large page support must be included in the initial merge of TDX? Large page is more about performance improvement I think. Given this series is already very big, perhaps we can do it later.

Signature · 2 lines
Thanks,
-Kai
#134 lore raw

Re: [RFC PATCH v5 038/104] KVM: x86/mmu: Allow per-VM override of the TDP max page level

Quoted 24 lines · Kai Huang
Quoted 16 lines · Sean Christopherson
Quoted 15 lines · Kai Huang
Quoted 13 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it.

For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

Quoted 6 lines
Quoted 2 lines

Do not support large page for TD is the reason that you want this change, but not the result. Please refine a little bit.

Not supporting huge pages was fine for the PoC, but I'd prefer not to merge TDX without support for huge pages. Has any work been put into enabling huge pages? If so, what's the technical blocker? If not...

Quoted 5 lines

Hi Sean,

Is there any reason large page support must be included in the initial merge of TDX? Large page is more about performance improvement I think. Given this series is already very big, perhaps we can do it later.

I'm ok punting 1gb for now, but I want to have a high level of confidence that 2mb pages will work without requiring significant churn in KVM on top of the initial TDX support. I suspect gaining that level of confidence will mean getting 95%+ of the way to a fully working code base. IIRC, 2mb wasn't expected to be terrible, it was 1gb support where things started to get messy.

#31 lore raw

Re: [RFC PATCH v5 008/104] KVM: TDX: Add a function to initialize TDX module

In reply to Isaku Yamahata
Quoted 23 lines · Isaku Yamahata
Quoted 20 lines · Xiaoyao Li
Quoted 18 lines · Isaku Yamahata
Quoted 11 lines · Kai Huang
Quoted 6 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a wrapper function to initialize the TDX module and get system-wide parameters via those APIs. Because TDX requires VMX enabled, It will be called on-demand when the first guest TD is created via x86 KVM init_vm callback.

Why not just merge this patch with the change where you implement the init_vm callback? Then you can just declare this patch as "detect and initialize TDX module when first VM is created", or something like that..

Ok. Anyway in the next respoin, tdx module initialization will be done when loading kvm_intel.ko. So the whole part will be changed and will be a part of module loading.

Quoted 6 lines
Quoted 1 line

Will we change the GET_TDX_CAPABILITIES ioctl back to KVM scope?

No because it system scoped KVM_TDX_CAPABILITIES requires one more callback for it. We can reduce the change.

Or do you have any use case for system scoped KVM_TDX_CAPABILITIES?

No. Just to confirm.

on the other hand, vm-scope IOCTL seems more flexible if different capabilities are reported per VM in the future.

#135 lore raw

Re: [RFC PATCH v5 038/104] KVM: x86/mmu: Allow per-VM override of the TDP max page level

In reply to Sean Christopherson
Quoted 31 lines · Sean Christopherson
Quoted 24 lines · Kai Huang
Quoted 16 lines · Sean Christopherson
Quoted 15 lines · Kai Huang
Quoted 13 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it.

For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

Quoted 6 lines
Quoted 2 lines

Do not support large page for TD is the reason that you want this change, but not the result. Please refine a little bit.

Not supporting huge pages was fine for the PoC, but I'd prefer not to merge TDX without support for huge pages. Has any work been put into enabling huge pages? If so, what's the technical blocker? If not...

Quoted 5 lines

Hi Sean,

Is there any reason large page support must be included in the initial merge of TDX? Large page is more about performance improvement I think. Given this series is already very big, perhaps we can do it later.

Quoted 5 lines

I'm ok punting 1gb for now, but I want to have a high level of confidence that 2mb pages will work without requiring significant churn in KVM on top of the initial TDX support. I suspect gaining that level of confidence will mean getting 95%+ of the way to a fully working code base. IIRC, 2mb wasn't expected to be terrible, it was 1gb support where things started to get messy.

OK no argument here :)

Signature · 2 lines
Thanks,
-Kai
maintainer Reviewed-by on v5 23/104
#70 lore raw

Re: [RFC PATCH v5 023/104] x86/cpu: Add helper functions to allocate/free MKTME keyid

In reply to [email protected]
Quoted 80 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

MKTME keyid is assigned to guest TD. The memory controller encrypts guest TD memory with key id. Add helper functions to allocate/free MKTME keyid so that TDX KVM assign keyid.

Also export MKTME global keyid that is used to encrypt TDX module and its memory.

---
  arch/x86/include/asm/tdx.h |  6 ++++++
  arch/x86/virt/vmx/tdx.c    | 33 ++++++++++++++++++++++++++++++++-
  2 files changed, 38 insertions(+), 1 deletion(-)
arch/x86/include/asm/tdx.h +6 -0
index 9a8dc6afcb63..73bb472bd515 100644
@@ -139,6 +139,9 @@ int tdx_detect(void);
  int tdx_init(void);
  bool platform_has_tdx(void);
  const struct tdsysinfo_struct *tdx_get_sysinfo(void);
+u32 tdx_get_global_keyid(void);
+int tdx_keyid_alloc(void);
+void tdx_keyid_free(int keyid);
  #else
  static inline void tdx_detect_cpu(struct cpuinfo_x86 *c) { }
  static inline int tdx_detect(void) { return -ENODEV; }
@@ -146,6 +149,9 @@ static inline int tdx_init(void) { return -ENODEV; }
  static inline bool platform_has_tdx(void) { return false; }
  struct tdsysinfo_struct;
  static inline const struct tdsysinfo_struct *tdx_get_sysinfo(void) { return NULL; }
+static inline u32 tdx_get_global_keyid(void) { return 0; };
+static inline int tdx_keyid_alloc(void) { return -EOPNOTSUPP; }
+static inline void tdx_keyid_free(int keyid) { }
  #endif /* CONFIG_INTEL_TDX_HOST */
 
  #endif /* !__ASSEMBLY__ */
arch/x86/virt/vmx/tdx.c +25 -1
index e45f188479cb..d714106321d4 100644
@@ -113,7 +113,13 @@ static int tdx_cmr_num;
  static struct tdsysinfo_struct tdx_sysinfo;
 
  /* TDX global KeyID to protect TDX metadata */
-static u32 tdx_global_keyid;
+static u32 __read_mostly tdx_global_keyid;
+
+u32 tdx_get_global_keyid(void)
+{
+	return tdx_global_keyid;
+}
+EXPORT_SYMBOL_GPL(tdx_get_global_keyid);
 
  static bool enable_tdx_host;
 
@@ -189,6 +195,31 @@ static void detect_seam(struct cpuinfo_x86 *c)
  		detect_seam_ap(c);
  }
 
+/* TDX KeyID pool */
+static DEFINE_IDA(tdx_keyid_pool);
+
+int tdx_keyid_alloc(void)
+{
+	if (WARN_ON_ONCE(!tdx_keyid_start || !tdx_keyid_num))
+		return -EINVAL;
+
+	/* The first keyID is reserved for the global key. */
+	return ida_alloc_range(&tdx_keyid_pool, tdx_keyid_start + 1,
+			       tdx_keyid_start + tdx_keyid_num - 1,
+			       GFP_KERNEL);
+}
+EXPORT_SYMBOL_GPL(tdx_keyid_alloc);
+
+void tdx_keyid_free(int keyid)
+{
+	/* keyid = 0 is reserved. */

arch/x86/virt/vmx/tdx.c static void detect_seam(struct cpuinfo_x86 *c) · line 225

Quoted 10 lines
arch/x86/virt/vmx/tdx.c +7 -0
+	if (!keyid || keyid <= 0)
+		return;
+
+	ida_free(&tdx_keyid_pool, keyid);
+}
+EXPORT_SYMBOL_GPL(tdx_keyid_free);
+
  static void detect_tdx_keyids_bsp(struct cpuinfo_x86 *c)
  {
  	u64 keyid_part;
maintainer
#79 lore raw

Re: [RFC PATCH v5 025/104] KVM: TDX: Add place holder for TDX VM specific mem_enc_op ioctl

In reply to [email protected]
Quoted 35 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a place holder function for TDX specific VM-scoped ioctl as mem_enc_op. TDX specific sub-commands will be added to retrieve/pass TDX specific parameters.

KVM_MEMORY_ENCRYPT_OP was introduced for VM-scoped operations specific for guest state-protected VM. It defined subcommands for technology-specific operations under KVM_MEMORY_ENCRYPT_OP. Despite its name, the subcommands are not limited to memory encryption, but various technology-specific operations are defined. It's natural to repurpose KVM_MEMORY_ENCRYPT_OP for TDX specific operations and define subcommands.

TDX requires VM-scoped, and VCPU-scoped TDX-specific operations for device model, for example, qemu. Getting system-wide parameters, TDX-specific VM initialization, and TDX-specific vCPU initialization. Which requires KVM vCPU-scoped operations in addition to the existing VM-scoped operations.

---
  arch/x86/include/uapi/asm/kvm.h       | 11 +++++++++++
  arch/x86/kvm/vmx/main.c               | 10 ++++++++++
  arch/x86/kvm/vmx/tdx.c                | 24 ++++++++++++++++++++++++
  arch/x86/kvm/vmx/x86_ops.h            |  4 ++++
  tools/arch/x86/include/uapi/asm/kvm.h | 11 +++++++++++
  5 files changed, 60 insertions(+)
arch/x86/include/uapi/asm/kvm.h +0 -0
index 71a5851475e7..2ad61caf4e0b 100644
@@ -528,4 +528,15 @@ struct kvm_pmu_event_filter {
  #define KVM_X86_DEFAULT_VM	0
  #define KVM_X86_TDX_VM		1
 

arch/x86/include/uapi/asm/kvm.h struct kvm_pmu_event_filter { · line 540

Quoted 10 lines
arch/x86/include/uapi/asm/kvm.h +10 -0
+/* Trust Domain eXtension sub-ioctl() commands. */
+enum kvm_tdx_cmd_id {
+	KVM_TDX_CMD_NR_MAX,
+};
+
+struct kvm_tdx_cmd {
+	__u32 id;
+	__u32 metadata;
+	__u64 data;
+};

Please include some initial documentation here already, for example it is not clear what "metadata" is.

Also please add

	u32 error;
	u32 unused;

for two reasons: 1) consistency with kvm_sev_cmd 2) error codes should be returned to userspace and not just sent through pr_tdx_error.

Paolo

maintainer
#82 lore raw

Re: [RFC PATCH v5 026/104] KVM: TDX: x86: Add vm ioctl to get TDX systemwide parameters

In reply to [email protected]
Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:

Implement a VM-scoped subcomment to get system-wide parameters. Although this is system-wide parameters not per-VM, this subcomand is VM-scoped because
- Device model needs TDX system-wide parameters after creating KVM VM.
- This subcommands requires to initialize TDX module. For lazy initialization of the TDX module, vm-scope ioctl is better.

Since there was agreement to install the TDX module on load, please place this ioctl on the /dev/kvm file descriptor.

At least for SEV, there were cases where the system-wide parameters are needed outside KVM, so it's better to avoid requiring a VM file descriptor.

Thanks,

Paolo

maintainer Reviewed-by on v5 35/104
#118 lore raw

Re: [RFC PATCH v5 035/104] KVM: x86/mmu: Disallow dirty logging for x86 TDX

In reply to [email protected]
Quoted 68 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TDX doesn't support dirty logging. Report dirty logging isn't supported so that device model, for example qemu, can properly handle it.

---
  arch/x86/kvm/x86.c       |  5 +++++
  include/linux/kvm_host.h |  1 +
  virt/kvm/kvm_main.c      | 15 ++++++++++++---
  3 files changed, 18 insertions(+), 3 deletions(-)
arch/x86/kvm/x86.c +5 -0
index c52a052e208c..da411bcd8cbc 100644
@@ -12876,6 +12876,11 @@ int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
  }
  EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
 
+bool kvm_arch_dirty_log_supported(struct kvm *kvm)
+{
+	return kvm->arch.vm_type != KVM_X86_TDX_VM;
+}
+
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
include/linux/kvm_host.h +1 -0
index a56044a31bc6..86f984e0c93f 100644
@@ -1423,6 +1423,7 @@ bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu);
  int kvm_arch_post_init_vm(struct kvm *kvm);
  void kvm_arch_pre_destroy_vm(struct kvm *kvm);
  int kvm_arch_create_vm_debugfs(struct kvm *kvm);
+bool kvm_arch_dirty_log_supported(struct kvm *kvm);
 
  #ifndef __KVM_HAVE_ARCH_VM_ALLOC
  /*
virt/kvm/kvm_main.c +11 -2
index 3adee9c6b370..ae3bf553f215 100644
@@ -1423,9 +1423,18 @@ static void kvm_replace_memslot(struct kvm *kvm,
  	}
  }
 
-static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
+bool __weak kvm_arch_dirty_log_supported(struct kvm *kvm)
  {
-	u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
+	return true;
+}
+
+static int check_memory_region_flags(struct kvm *kvm,
+				     const struct kvm_userspace_memory_region *mem)
+{
+	u32 valid_flags = 0;
+
+	if (kvm_arch_dirty_log_supported(kvm))
+		valid_flags |= KVM_MEM_LOG_DIRTY_PAGES;
 
  #ifdef __KVM_HAVE_READONLY_MEM
  	valid_flags |= KVM_MEM_READONLY;

virt/kvm/kvm_main.c int __kvm_set_memory_region(struct kvm *kvm, · line 1841

Quoted 8 lines
virt/kvm/kvm_main.c +1 -1
@@ -1826,7 +1835,7 @@ int __kvm_set_memory_region(struct kvm *kvm,
  	int as_id, id;
  	int r;
 
-	r = check_memory_region_flags(mem);
+	r = check_memory_region_flags(kvm, mem);
  	if (r)
  		return r;
 
maintainer
#120 lore raw

Re: [RFC PATCH v5 036/104] KVM: x86/mmu: Explicitly check for MMIO spte in fast page fault

In reply to [email protected]
Quoted 9 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Explicitly check for an MMIO spte in the fast page fault flow. TDX will use a not-present entry for MMIO sptes, which can be mistaken for an access-tracked spte since both have SPTE_SPECIAL_MASK set.

The fast page fault handles the case of changing access bits without obtaining mmu_lock. For example, clear write protect bit for dirty page tracking. MMIO emulation is handled in a slow path. So it doesn't affect

"MMIO sptes are handled in handle_mmio_page_fault for non-TDX VMs, so this patch does not affect them. TDX will handle MMIO emulation through a hypercall instead".

For this comment, it is not necessary to talk about the slow path, since that is just where MMIO sptes are installed. If the slow path is reached, fast_page_fault must not have seen is_mmio_spte(spte).

arch/x86/kvm/mmu/mmu.c static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 3173

Quoted 9 lines
arch/x86/kvm/mmu/mmu.c +1 -1
@@ -3167,7 +3167,7 @@ static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  			break;
 
  		sp = sptep_to_sp(sptep);
-		if (!is_last_spte(spte, sp->role.level))
+		if (!is_last_spte(spte, sp->role.level) || is_mmio_spte(spte))
  			break;
 
  		/*

I would include the check a couple lines before:

	if (!is_shadow_present_pte(spte) || is_mmio_spte(spte))

This matches what is in the commit message: the problem is that MMIO SPTEs are present in the TDX case, so you need to check them even if is_shadow_present_pte(spte) returns true.

Paolo

maintainer
#57 lore raw

Re: [RFC PATCH v5 020/104] KVM: TDX: allocate per-package mutex

In reply to [email protected]
Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Several TDX SEAMCALLs are per-package scope (concretely per memory controller) and they need to be serialized per-package. Allocate mutex for it.

Quoted 6 lines
---
  arch/x86/kvm/vmx/main.c    |  8 +++++++-
  arch/x86/kvm/vmx/tdx.c     | 18 ++++++++++++++++++
  arch/x86/kvm/vmx/x86_ops.h |  2 ++
  3 files changed, 27 insertions(+), 1 deletion(-)

Please define here the lock/unlock functions as well:

static inline int tdx_mng_key_lock(void)

{
	int cpu = get_cpu();
	cur_pkg = topology_physical_package_id(cpu);

	mutex_lock(&tdx_mng_key_config_lock[cur_pkg]);
	return cur_pkg;
}

static inline void tdx_mng_key_unlock(int cur_pkg)

{
	mutex_unlock(&tdx_mng_key_config_lock[cur_pkg]);
	put_cpu();
}

Thanks,

Paolo

Quoted 96 lines
arch/x86/kvm/vmx/main.c +7 -1
index 8103d1c32cc9..6111c6485d8e 100644
@@ -25,6 +25,12 @@ static __init int vt_hardware_setup(void)
  	return 0;
  }
 
+static void vt_hardware_unsetup(void)
+{
+	tdx_hardware_unsetup();
+	vmx_hardware_unsetup();
+}
+
  static int vt_vm_init(struct kvm *kvm)
  {
  	int ret;
@@ -42,7 +48,7 @@ static int vt_vm_init(struct kvm *kvm)
  struct kvm_x86_ops vt_x86_ops __initdata = {
  	.name = "kvm_intel",
 
-	.hardware_unsetup = vmx_hardware_unsetup,
+	.hardware_unsetup = vt_hardware_unsetup,
 
  	.hardware_enable = vmx_hardware_enable,
  	.hardware_disable = vmx_hardware_disable,
arch/x86/kvm/vmx/tdx.c +18 -0
index e8d293a3c11c..1c8222f54764 100644
@@ -34,6 +34,8 @@ struct tdx_capabilities {
  /* Capabilities of KVM + the TDX module. */
  struct tdx_capabilities tdx_caps;
 
+static struct mutex *tdx_mng_key_config_lock;
+
  static u64 hkid_mask __ro_after_init;
  static u8 hkid_start_pos __ro_after_init;
 
@@ -112,7 +114,9 @@ bool tdx_is_vm_type_supported(unsigned long type)
 
  static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  {
+	int max_pkgs;
  	u32 max_pa;
+	int i;
 
  	if (!enable_ept) {
  		pr_warn("Cannot enable TDX with EPT disabled\n");
@@ -127,6 +131,14 @@ static int __init __tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  	if (WARN_ON_ONCE(x86_ops->tlb_remote_flush))
  		return -EIO;
 
+	max_pkgs = topology_max_packages();
+	tdx_mng_key_config_lock = kcalloc(max_pkgs, sizeof(*tdx_mng_key_config_lock),
+				   GFP_KERNEL);
+	if (!tdx_mng_key_config_lock)
+		return -ENOMEM;
+	for (i = 0; i < max_pkgs; i++)
+		mutex_init(&tdx_mng_key_config_lock[i]);
+
  	max_pa = cpuid_eax(0x80000008) & 0xff;
  	hkid_start_pos = boot_cpu_data.x86_phys_bits;
  	hkid_mask = GENMASK_ULL(max_pa - 1, hkid_start_pos);
@@ -147,6 +159,12 @@ void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  		enable_tdx = false;
  }
 
+void tdx_hardware_unsetup(void)
+{
+	/* kfree accepts NULL. */
+	kfree(tdx_mng_key_config_lock);
+}
+
  void __init tdx_pre_kvm_init(unsigned int *vcpu_size,
  			unsigned int *vcpu_align, unsigned int *vm_size)
  {
arch/x86/kvm/vmx/x86_ops.h +2 -0
index 78331dbc29f7..da32b4b86b19 100644
@@ -131,11 +131,13 @@ void __init tdx_pre_kvm_init(unsigned int *vcpu_size,
  			unsigned int *vcpu_align, unsigned int *vm_size);
  bool tdx_is_vm_type_supported(unsigned long type);
  void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
+void tdx_hardware_unsetup(void);
  #else
  static inline void tdx_pre_kvm_init(
  	unsigned int *vcpu_size, unsigned int *vcpu_align, unsigned int *vm_size) {}
  static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
  static inline void tdx_hardware_setup(struct kvm_x86_ops *x86_ops) {}
+static inline void tdx_hardware_unsetup(void) {}
  #endif
 
  #endif /* __KVM_X86_VMX_X86_OPS_H */
maintainer
#89 lore raw

Re: [RFC PATCH v5 027/104] KVM: TDX: initialize VM with TDX specific parameters

In reply to Kai Huang
Quoted 9 lines · Kai Huang

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_capabilities { · line 569

Quoted 6 lines
arch/x86/include/uapi/asm/kvm.h +5 -0
+struct kvm_tdx_init_vm {
+	__u32 max_vcpus;
+	__u32 tsc_khz;
+	__u64 attributes;
+	__u64 cpuid;

Is it better to append all CPUIDs directly into this structure, perhaps at end of this structure, to make it more consistent with TD_PARAMS?

Quoted 3 lines

Also, I think somewhere in commit message or comments we should explain why CPUIDs are passed here (why existing KVM_SET_CUPID2 is not sufficient).

Indeed, it would be easier to use the existing cpuid data in struct kvm_vcpu, because right now there is no way to ensure that they are consistent.

Why is KVM_SET_CPUID2 not enough? Are there any modifications done by KVM that affect the measurement?

Thanks,

Paolo

maintainer Applied
#64 lore raw

Re: [RFC PATCH v5 022/104] KVM: Add max_vcpus field in common 'struct kvm'

In reply to [email protected]
Quoted 111 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

For TDX guests, the maximum number of vcpus needs to be specified when the TDX guest VM is initialized (creating the TDX data corresponding to TDX guest) before creating vcpu. It needs to record the maximum number of vcpus on VM creation (KVM_CREATE_VM) and return error if the number of vcpus exceeds it

Because there is already max_vcpu member in arm64 struct kvm_arch, move it to common struct kvm and initialize it to KVM_MAX_VCPUS before kvm_arch_init_vm() instead of adding it to x86 struct kvm_arch.

---
  arch/arm64/include/asm/kvm_host.h | 3 ---
  arch/arm64/kvm/arm.c              | 6 +++---
  arch/arm64/kvm/vgic/vgic-init.c   | 6 +++---
  include/linux/kvm_host.h          | 1 +
  virt/kvm/kvm_main.c               | 3 ++-
  5 files changed, 9 insertions(+), 10 deletions(-)
arch/arm64/include/asm/kvm_host.h +0 -3
index 5bc01e62c08a..27249d634605 100644
@@ -107,9 +107,6 @@ struct kvm_arch {
  	/* VTCR_EL2 value for this VM */
  	u64    vtcr;
 
-	/* The maximum number of vCPUs depends on the used GIC model */
-	int max_vcpus;
-
  	/* Interrupt controller */
  	struct vgic_dist	vgic;
 
arch/arm64/kvm/arm.c +3 -3
index ecc5958e27fe..defec2cd94bd 100644
@@ -153,7 +153,7 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  	kvm_vgic_early_init(kvm);
 
  	/* The maximum number of VCPUs is limited by the host's GIC model */
-	kvm->arch.max_vcpus = kvm_arm_default_max_vcpus();
+	kvm->max_vcpus = kvm_arm_default_max_vcpus();
 
  	set_default_spectre(kvm);
 
@@ -229,7 +229,7 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
  	case KVM_CAP_MAX_VCPUS:
  	case KVM_CAP_MAX_VCPU_ID:
  		if (kvm)
-			r = kvm->arch.max_vcpus;
+			r = kvm->max_vcpus;
  		else
  			r = kvm_arm_default_max_vcpus();
  		break;
@@ -305,7 +305,7 @@ int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
  	if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
  		return -EBUSY;
 
-	if (id >= kvm->arch.max_vcpus)
+	if (id >= kvm->max_vcpus)
  		return -EINVAL;
 
  	return 0;
arch/arm64/kvm/vgic/vgic-init.c +3 -3
index fc00304fe7d8..77feafd5c0e3 100644
@@ -98,11 +98,11 @@ int kvm_vgic_create(struct kvm *kvm, u32 type)
  	ret = 0;
 
  	if (type == KVM_DEV_TYPE_ARM_VGIC_V2)
-		kvm->arch.max_vcpus = VGIC_V2_MAX_CPUS;
+		kvm->max_vcpus = VGIC_V2_MAX_CPUS;
  	else
-		kvm->arch.max_vcpus = VGIC_V3_MAX_CPUS;
+		kvm->max_vcpus = VGIC_V3_MAX_CPUS;
 
-	if (atomic_read(&kvm->online_vcpus) > kvm->arch.max_vcpus) {
+	if (atomic_read(&kvm->online_vcpus) > kvm->max_vcpus) {
  		ret = -E2BIG;
  		goto out_unlock;
  	}
include/linux/kvm_host.h +1 -0
index f11039944c08..a56044a31bc6 100644
@@ -715,6 +715,7 @@ struct kvm {
  	 * and is accessed atomically.
  	 */
  	atomic_t online_vcpus;
+	int max_vcpus;
  	int created_vcpus;
  	int last_boosted_vcpu;
  	struct list_head vm_list;
virt/kvm/kvm_main.c +1 -0
index 52f72a366beb..3adee9c6b370 100644
@@ -1075,6 +1075,7 @@ static struct kvm *kvm_create_vm(unsigned long type)
  	spin_lock_init(&kvm->gpc_lock);
 
  	INIT_LIST_HEAD(&kvm->devices);
+	kvm->max_vcpus = KVM_MAX_VCPUS;
 
  	BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
 

virt/kvm/kvm_main.c static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id) · line 3725

Quoted 8 lines
virt/kvm/kvm_main.c +1 -1
@@ -3718,7 +3719,7 @@ static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
  		return -EINVAL;
 
  	mutex_lock(&kvm->lock);
-	if (kvm->created_vcpus == KVM_MAX_VCPUS) {
+	if (kvm->created_vcpus >= kvm->max_vcpus) {
  		mutex_unlock(&kvm->lock);
  		return -EINVAL;
  	}

Queued this one already, thanks.

Paolo

maintainer
#62 lore raw

Re: [RFC PATCH v5 021/104] KVM: x86: Introduce hooks to free VM callback prezap and vm_free

In reply to [email protected]
Quoted 59 lines · On 3/4/22 20:48, [email protected] wrote:

From: Kai Huang <[email protected]>

Before tearing down private page tables, TDX requires some resources of the guest TD to be destroyed (i.e. keyID must have been reclaimed, etc). Add prezap callback before tearing down private page tables for it.

TDX needs to free some resources after other resources (i.e. vcpu related resources). Add vm_free callback at the end of kvm_arch_destroy_vm().

---
  arch/x86/include/asm/kvm-x86-ops.h | 2 ++
  arch/x86/include/asm/kvm_host.h    | 2 ++
  arch/x86/kvm/x86.c                 | 8 ++++++++
  3 files changed, 12 insertions(+)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 8125d43d3566..ef48dcc98cfc 100644
@@ -20,7 +20,9 @@ KVM_X86_OP(has_emulated_msr)
  KVM_X86_OP(vcpu_after_set_cpuid)
  KVM_X86_OP(is_vm_type_supported)
  KVM_X86_OP(vm_init)
+KVM_X86_OP_NULL(mmu_prezap)
  KVM_X86_OP_NULL(vm_destroy)
+KVM_X86_OP_NULL(vm_free)
  KVM_X86_OP(vcpu_create)
  KVM_X86_OP(vcpu_free)
  KVM_X86_OP(vcpu_reset)
arch/x86/include/asm/kvm_host.h +2 -0
index 8de357a9ad30..5ff7a0fba311 100644
@@ -1326,7 +1326,9 @@ struct kvm_x86_ops {
  	bool (*is_vm_type_supported)(unsigned long vm_type);
  	unsigned int vm_size;
  	int (*vm_init)(struct kvm *kvm);
+	void (*mmu_prezap)(struct kvm *kvm);
  	void (*vm_destroy)(struct kvm *kvm);
+	void (*vm_free)(struct kvm *kvm);
 
  	/* Create, but do not attach this VCPU */
  	int (*vcpu_create)(struct kvm_vcpu *vcpu);
arch/x86/kvm/x86.c +1 -0
index f6438750d190..a48f5c69fadb 100644
@@ -11779,6 +11779,7 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
  	kvm_page_track_cleanup(kvm);
  	kvm_xen_destroy_vm(kvm);
  	kvm_hv_destroy_vm(kvm);
+	static_call_cond(kvm_x86_vm_free)(kvm);
  }
 
  static void memslot_rmap_free(struct kvm_memory_slot *slot)
@@ -12036,6 +12037,13 @@ void kvm_arch_commit_memory_region(struct kvm *kvm,
 

arch/x86/kvm/x86.c void kvm_arch_commit_memory_region(struct kvm *kvm, · line 12047

Quoted 10 lines
arch/x86/kvm/x86.c +7 -0
  void kvm_arch_flush_shadow_all(struct kvm *kvm)
  {
+	/*
+	 * kvm_mmu_zap_all() zaps both private and shared page tables.  Before
+	 * tearing down private page tables, TDX requires some TD resources to
+	 * be destroyed (i.e. keyID must have been reclaimed, etc).  Invoke
+	 * kvm_x86_mmu_prezap() for this.
+	 */
+	static_call_cond(kvm_x86_mmu_prezap)(kvm);
  	kvm_mmu_zap_all(kvm);

Please rename the hook to (*flush_shadow_all_private).

Otherwise ok,

Paolo

Quoted 2 lines
arch/x86/kvm/x86.c +0 -0
  }
 
maintainer
#93 lore raw

Re: [RFC PATCH v5 027/104] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]

arch/x86/kvm/vmx/tdx.c static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 432

Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
+	td_params->attributes = init_vm->attributes;
+	if (td_params->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+		pr_warn("TD doesn't support perfmon. KVM needs to save/restore "
+			"host perf registers properly.\n");
+		return -EOPNOTSUPP;
+	}

Why does KVM have to hardcode this (and LBR/AMX below)? Is the level of hardware support available from tdx_caps, for example through the CPUID configs (0xA for this one, 0xD for LBR and AMX)?

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	/* PT can be exposed to TD guest regardless of KVM's XSS support */
+	guest_supported_xss &= (supported_xss | XFEATURE_MASK_PT);
+	td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+	if (td_params->xfam & TDX_TD_XFAM_LBR) {
+		pr_warn("TD doesn't support LBR. KVM needs to save/restore "
+			"IA32_LBR_DEPTH properly.\n");
+		return -EOPNOTSUPP;
+	}
+
+	if (td_params->xfam & TDX_TD_XFAM_AMX) {

arch/x86/kvm/vmx/tdx.c static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 499

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+		pr_warn("TD doesn't support AMX. KVM needs to save/restore "
+			"IA32_XFD, IA32_XFD_ERR properly.\n");
+		return -EOPNOTSUPP;
+	}
 
 
+	if (init_vm->tsc_khz)
+		guest_tsc_khz = init_vm->tsc_khz;
+	else
+		guest_tsc_khz = max_tsc_khz;

You can just use kvm->arch.default_tsc_khz in the latest kvm/queue.

arch/x86/kvm/vmx/tdx.c static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 511

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+#define BUILD_BUG_ON_MEMCPY(dst, src)				\
+	do {							\
+		BUILD_BUG_ON(sizeof(dst) != sizeof(src));	\
+		memcpy((dst), (src), sizeof(dst));		\
+	} while (0)
+
+	BUILD_BUG_ON_MEMCPY(td_params->mrconfigid, init_vm->mrconfigid);
+	BUILD_BUG_ON_MEMCPY(td_params->mrowner, init_vm->mrowner);
+	BUILD_BUG_ON_MEMCPY(td_params->mrownerconfig, init_vm->mrownerconfig);
+

Please rename to MEMCPY_SAME_SIZE.

Thanks,

Paolo

maintainer
#75 lore raw

Re: [RFC PATCH v5 024/104] KVM: TDX: create/destroy VM structure

In reply to [email protected]
Quoted 32 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

As the first step to create TDX guest, create/destroy VM struct. Assign Host Key ID (HKID) to the TDX guest for memory encryption and allocate extra pages for the TDX guest. On destruction, free allocated pages, and HKID.

Add a second kvm_x86_ops hook in kvm_arch_vm_destroy() to support TDX's destruction path, which needs to first put the VM into a teardown state, then free per-vCPU resources, and finally free per-VM resources.

---
  arch/x86/kvm/vmx/main.c      |  16 +-
  arch/x86/kvm/vmx/tdx.c       | 312 +++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/tdx.h       |   2 +
  arch/x86/kvm/vmx/tdx_errno.h |   2 +-
  arch/x86/kvm/vmx/tdx_ops.h   |   8 +
  arch/x86/kvm/vmx/x86_ops.h   |   8 +
  6 files changed, 346 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/main.c +1 -1
index 6111c6485d8e..5c3a904a30e8 100644
@@ -39,12 +39,24 @@ static int vt_vm_init(struct kvm *kvm)
  		ret = tdx_module_setup();
  		if (ret)
  			return ret;
-		return -EOPNOTSUPP;	/* Not ready to create guest TD yet. */
+		return tdx_vm_init(kvm);

arch/x86/kvm/vmx/main.c static int vt_vm_init(struct kvm *kvm) · line 52

Quoted 10 lines
arch/x86/kvm/vmx/main.c +5 -0
  	}
 
  	return vmx_vm_init(kvm);
  }
 
+static void vt_mmu_prezap(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_mmu_prezap(kvm);
+}

Please rename the function to explain what it does, for example tdx_mmu_release_hkid.

Paolo

Quoted 447 lines
arch/x86/kvm/vmx/main.c +8 -0
+static void vt_vm_free(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_vm_free(kvm);
+}
 
+
  struct kvm_x86_ops vt_x86_ops __initdata = {
  	.name = "kvm_intel",
@@ -58,6 +70,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.is_vm_type_supported = vt_is_vm_type_supported,
  	.vm_size = sizeof(struct kvm_vmx),
  	.vm_init = vt_vm_init,
+	.mmu_prezap = vt_mmu_prezap,
+	.vm_free = vt_vm_free,
 
  	.vcpu_create = vmx_vcpu_create,
  	.vcpu_free = vmx_vcpu_free,
arch/x86/kvm/vmx/tdx.c +312 -0
index 1c8222f54764..702953fd365f 100644
@@ -31,14 +31,324 @@ struct tdx_capabilities {
  	struct tdx_cpuid_config cpuid_configs[TDX_MAX_NR_CPUID_CONFIGS];
  };
 
+/* KeyID used by TDX module */
+static u32 tdx_global_keyid __read_mostly;
+
  /* Capabilities of KVM + the TDX module. */
  struct tdx_capabilities tdx_caps;
 
+static DEFINE_MUTEX(tdx_lock);
  static struct mutex *tdx_mng_key_config_lock;
 
  static u64 hkid_mask __ro_after_init;
  static u8 hkid_start_pos __ro_after_init;
 
+static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
+{
+	pa &= ~hkid_mask;
+	pa |= (u64)hkid << hkid_start_pos;
+
+	return pa;
+}
+
+static inline bool is_td_created(struct kvm_tdx *kvm_tdx)
+{
+	return kvm_tdx->tdr.added;
+}
+
+static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
+{
+	tdx_keyid_free(kvm_tdx->hkid);
+	kvm_tdx->hkid = -1;
+}
+
+static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)
+{
+	return kvm_tdx->hkid > 0;
+}
+
+static void tdx_clear_page(unsigned long page)
+{
+	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
+	unsigned long i;
+
+	/* Zeroing the page is only necessary for systems with MKTME-i. */
+	if (!static_cpu_has(X86_FEATURE_MOVDIR64B))
+		return;
+
+	for (i = 0; i < 4096; i += 64)
+		/* MOVDIR64B [rdx], es:rdi */
+		asm (".byte 0x66, 0x0f, 0x38, 0xf8, 0x3a"
+		     : : "d" (zero_page), "D" (page + i) : "memory");
+}
+
+static int __tdx_reclaim_page(unsigned long va, hpa_t pa, bool do_wb, u16 hkid)
+{
+	struct tdx_module_output out;
+	u64 err;
+
+	err = tdh_phymem_page_reclaim(pa, &out);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
+		return -EIO;
+	}
+
+	if (do_wb) {
+		err = tdh_phymem_page_wbinvd(set_hkid_to_hpa(pa, hkid));
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err, NULL);
+			return -EIO;
+		}
+	}
+
+	tdx_clear_page(va);
+	return 0;
+}
+
+static int tdx_reclaim_page(unsigned long va, hpa_t pa)
+{
+	return __tdx_reclaim_page(va, pa, false, 0);
+}
+
+static int tdx_alloc_td_page(struct tdx_td_page *page)
+{
+	page->va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!page->va)
+		return -ENOMEM;
+
+	page->pa = __pa(page->va);
+	return 0;
+}
+
+static void tdx_mark_td_page_added(struct tdx_td_page *page)
+{
+	WARN_ON_ONCE(page->added);
+	page->added = true;
+}
+
+static void tdx_reclaim_td_page(struct tdx_td_page *page)
+{
+	if (page->added) {
+		if (tdx_reclaim_page(page->va, page->pa))
+			return;
+
+		page->added = false;
+	}
+	free_page(page->va);
+}
+
+static int tdx_do_tdh_phymem_cache_wb(void *param)
+{
+	u64 err = 0;
+
+	/*
+	 * We can destroy multiple the guest TDs simultaneously.  Prevent
+	 * tdh_phymem_cache_wb from returning TDX_BUSY by serialization.
+	 */
+	mutex_lock(&tdx_lock);
+	do {
+		err = tdh_phymem_cache_wb(!!err);
+	} while (err == TDX_INTERRUPTED_RESUMABLE);
+	mutex_unlock(&tdx_lock);
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+void tdx_mmu_prezap(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	bool cpumask_allocated;
+	u64 err;
+	int ret;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx))
+		goto free_hkid;
+
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_key_reclaimid(kvm_tdx->tdr.pa);
+	mutex_unlock(&tdx_lock);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_RECLAIMID, err, NULL);
+		return;
+	}
+
+	cpumask_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+	for_each_online_cpu(i) {
+		if (cpumask_allocated &&
+			cpumask_test_and_set_cpu(topology_physical_package_id(i),
+						packages))
+			continue;
+
+		ret = smp_call_on_cpu(i, tdx_do_tdh_phymem_cache_wb, NULL, 1);
+		if (ret)
+			break;
+	}
+	free_cpumask_var(packages);
+
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_key_freeid(kvm_tdx->tdr.pa);
+	mutex_unlock(&tdx_lock);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_FREEID, err, NULL);
+		return;
+	}
+
+free_hkid:
+	tdx_hkid_free(kvm_tdx);
+}
+
+void tdx_vm_free(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	int i;
+
+	/* Can't reclaim or free TD pages if teardown failed. */
+	if (is_hkid_assigned(kvm_tdx))
+		return;
+
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++)
+		tdx_reclaim_td_page(&kvm_tdx->tdcs[i]);
+	kfree(kvm_tdx->tdcs);
+
+	if (kvm_tdx->tdr.added &&
+		__tdx_reclaim_page(kvm_tdx->tdr.va, kvm_tdx->tdr.pa, true,
+				tdx_global_keyid))
+		return;
+
+	free_page(kvm_tdx->tdr.va);
+}
+
+static int tdx_do_tdh_mng_key_config(void *param)
+{
+	hpa_t *tdr_p = param;
+	int cpu, cur_pkg;
+	u64 err;
+
+	cpu = raw_smp_processor_id();
+	cur_pkg = topology_physical_package_id(cpu);
+
+	mutex_lock(&tdx_mng_key_config_lock[cur_pkg]);
+	do {
+		err = tdh_mng_key_config(*tdr_p);
+	} while (err == TDX_KEY_GENERATION_FAILED);
+	mutex_unlock(&tdx_mng_key_config_lock[cur_pkg]);
+
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+int tdx_vm_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	int ret, i;
+	u64 err;
+
+	/* vCPUs can't be created until after KVM_TDX_INIT_VM. */
+	kvm->max_vcpus = 0;
+
+	kvm_tdx->hkid = tdx_keyid_alloc();
+	if (kvm_tdx->hkid < 0)
+		return -EBUSY;
+
+	ret = tdx_alloc_td_page(&kvm_tdx->tdr);
+	if (ret)
+		goto free_hkid;
+
+	kvm_tdx->tdcs = kcalloc(tdx_caps.tdcs_nr_pages, sizeof(*kvm_tdx->tdcs),
+				GFP_KERNEL_ACCOUNT);
+	if (!kvm_tdx->tdcs)
+		goto free_tdr;
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		ret = tdx_alloc_td_page(&kvm_tdx->tdcs[i]);
+		if (ret)
+			goto free_tdcs;
+	}
+
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(kvm_tdx->tdr.pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_tdcs;
+	}
+	tdx_mark_td_page_added(&kvm_tdx->tdr);
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	for_each_online_cpu(i) {
+		if (cpumask_test_and_set_cpu(topology_physical_package_id(i),
+						packages))
+			continue;
+
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				&kvm_tdx->tdr.pa, 1);
+		if (ret)
+			break;
+	}
+	free_cpumask_var(packages);
+	if (ret)
+		goto teardown;
+
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr.pa, kvm_tdx->tdcs[i].pa);
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+		tdx_mark_td_page_added(&kvm_tdx->tdcs[i]);
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.
+	 */
+teardown:
+	tdx_mmu_prezap(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_tdcs:
+	/* @i points at the TDCS page that failed allocation. */
+	for (--i; i >= 0; i--)
+		free_page(kvm_tdx->tdcs[i].va);
+	kfree(kvm_tdx->tdcs);
+free_tdr:
+	free_page(kvm_tdx->tdr.va);
+free_hkid:
+	tdx_hkid_free(kvm_tdx);
+	return ret;
+}
+
  static int __tdx_module_setup(void)
  {
  	const struct tdsysinfo_struct *tdsysinfo;
@@ -59,6 +369,8 @@ static int __tdx_module_setup(void)
  		return ret;
  	}
 
+	tdx_global_keyid = tdx_get_global_keyid();
+
  	tdsysinfo = tdx_get_sysinfo();
  	if (tdx_caps.nr_cpuid_configs > TDX_MAX_NR_CPUID_CONFIGS)
  		return -EIO;
arch/x86/kvm/vmx/tdx.h +2 -0
index e4bb8831764e..860136ed70f5 100644
@@ -19,6 +19,8 @@ struct kvm_tdx {
 
  	struct tdx_td_page tdr;
  	struct tdx_td_page *tdcs;
+
+	int hkid;
  };
 
  struct vcpu_tdx {
arch/x86/kvm/vmx/tdx_errno.h +1 -1
index 5c878488795d..590fcfdd1899 100644
@@ -12,11 +12,11 @@
  #define TDX_SUCCESS				0x0000000000000000ULL
  #define TDX_NON_RECOVERABLE_VCPU		0x4000000100000000ULL
  #define TDX_INTERRUPTED_RESUMABLE		0x8000000300000000ULL
-#define TDX_LIFECYCLE_STATE_INCORRECT		0xC000060700000000ULL
  #define TDX_VCPU_NOT_ASSOCIATED			0x8000070200000000ULL
  #define TDX_KEY_GENERATION_FAILED		0x8000080000000000ULL
  #define TDX_KEY_STATE_INCORRECT			0xC000081100000000ULL
  #define TDX_KEY_CONFIGURED			0x0000081500000000ULL
+#define TDX_NO_HKID_READY_TO_WBCACHE		0x0000082100000000ULL
  #define TDX_EPT_WALK_FAILED			0xC0000B0000000000ULL
 
  /*
arch/x86/kvm/vmx/tdx_ops.h +8 -0
index 0bed43879b82..3dd5b4c3f04c 100644
@@ -6,6 +6,7 @@
 
  #include <linux/compiler.h>
 
+#include <asm/cacheflush.h>
  #include <asm/asm.h>
  #include <asm/kvm_host.h>
 
@@ -15,8 +16,14 @@
 
  #ifdef CONFIG_INTEL_TDX_HOST
 
+static inline void tdx_clflush_page(hpa_t addr)
+{
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+}
+
  static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
  {
+	tdx_clflush_page(addr);
  	return kvm_seamcall(TDH_MNG_ADDCX, addr, tdr, 0, 0, 0, NULL);
  }
 
@@ -56,6 +63,7 @@ static inline u64 tdh_mng_key_config(hpa_t tdr)
 
  static inline u64 tdh_mng_create(hpa_t tdr, int hkid)
  {
+	tdx_clflush_page(tdr);
  	return kvm_seamcall(TDH_MNG_CREATE, tdr, hkid, 0, 0, 0, NULL);
  }
 
arch/x86/kvm/vmx/x86_ops.h +8 -0
index da32b4b86b19..2b2738c768d6 100644
@@ -132,12 +132,20 @@ void __init tdx_pre_kvm_init(unsigned int *vcpu_size,
  bool tdx_is_vm_type_supported(unsigned long type);
  void __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
  void tdx_hardware_unsetup(void);
+
+int tdx_vm_init(struct kvm *kvm);
+void tdx_mmu_prezap(struct kvm *kvm);
+void tdx_vm_free(struct kvm *kvm);
  #else
  static inline void tdx_pre_kvm_init(
  	unsigned int *vcpu_size, unsigned int *vcpu_align, unsigned int *vm_size) {}
  static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
  static inline void tdx_hardware_setup(struct kvm_x86_ops *x86_ops) {}
  static inline void tdx_hardware_unsetup(void) {}
+
+static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
+static inline void tdx_mmu_prezap(struct kvm *kvm) {}
+static inline void tdx_vm_free(struct kvm *kvm) {}
  #endif
 
  #endif /* __KVM_X86_VMX_X86_OPS_H */
maintainer
#99 lore raw

Re: [RFC PATCH v5 029/104] KVM: TDX: allocate/free TDX vcpu structure

In reply to [email protected]

arch/x86/kvm/vmx/tdx.c int tdx_vm_init(struct kvm *kvm) · line 443

Quoted 10 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +10 -0
+	/*
+	 * In TDX case, tsc frequency is per-VM and determined by the parameter
+	 * tdh_mng_init().  Forcibly set it instead of max_tsc_khz set by
+	 * kvm_arch_vcpu_create().
+	 *
+	 * This function is called after kvm_arch_vcpu_create() calling
+	 * kvm_set_tsc_khz().
+	 */
+	kvm_set_tsc_khz(vcpu, kvm_tdx->tsc_khz);
+

I think this is not needed anymore, now that there is kvm->arch.default_tsc_khz. If so, exporting the function is not needed either.

Paolo

maintainer Reviewed-by on v5 39/104
#137 lore raw

Re: [RFC PATCH v5 039/104] KVM: x86/mmu: Disallow fast page fault on private GPA

In reply to [email protected]
Quoted 16 lines · On 3/4/22 20:48, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX requires TDX SEAMCALL to operate Secure EPT instead of direct memory access and TDX SEAMCALL is heavy operation. Fast page fault on private GPA doesn't make sense. Disallow fast page fault on private GPA.

---
  arch/x86/kvm/mmu/mmu.c | 7 +++++++
  1 file changed, 7 insertions(+)
arch/x86/kvm/mmu/mmu.c +0 -0
index e9212394a530..d8c1505155b0 100644

arch/x86/kvm/mmu/mmu.c static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 3190

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +3 -0
@@ -3185,6 +3185,13 @@ static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  	u64 *sptep = NULL;
  	uint retry_count = 0;
 
+	/*
+	 * TDX private mapping doesn't support fast page fault because the EPT
+	 * entry needs TDX SEAMCALL. not direct memory access.

"the EPT entry is read/written with TDX SEAMCALLs instead of direct memory access".

Quoted 7 lines
arch/x86/kvm/mmu/mmu.c +4 -0
+	 */
+	if (kvm_is_private_gpa(vcpu->kvm, fault->addr))
+		return ret;
+
  	if (!page_fault_can_be_fast(fault))
  		return ret;
 
maintainer
#174 lore raw

Re: [RFC PATCH v5 049/104] KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs

In reply to [email protected]
Quoted 4 lines · On 3/4/22 20:49, [email protected] wrote:

static void handle_changed_spte_dirty_log(struct kvm *kvm, int as_id, gfn_t gfn,

arch/x86/kvm/mmu/tdp_mmu.c +1 -0
+					  bool private_spte,
  					  u64 old_spte, u64 new_spte, int level)
  {

arch/x86/kvm/mmu/tdp_mmu.c static void handle_changed_spte_acc_track(u64 old_spte, u64 new_spte, int level) · line 272

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -0
  	bool pfn_changed;
  	struct kvm_memory_slot *slot;
 
+	/*
+	 * TDX doesn't support live migration.  Never mark private page as
+	 * dirty in log-dirty bitmap, since it's not possible for userspace
+	 * hypervisor to live migrate private page anyway.
+	 */
+	if (private_spte)
+		return;

This should not be needed, patch 35 will block it anyway because kvm_slot_dirty_track_enabled() will return false.

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +5 -1
@@ -1215,7 +1227,23 @@ static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm,
  	 * into this helper allow blocking; it'd be dead, wasteful code.
  	 */
  	for_each_tdp_mmu_root(kvm, root, range->slot->as_id) {
-		tdp_root_for_each_leaf_pte(iter, root, range->start, range->end)
+		/*
+		 * For TDX shared mapping, set GFN shared bit to the range,
+		 * so the handler() doesn't need to set it, to avoid duplicated
+		 * code in multiple handler()s.
+		 */

arch/x86/kvm/mmu/tdp_mmu.c static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm, · line 1244

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10 -0
+		gfn_t start;
+		gfn_t end;
+
+		if (is_private_sp(root)) {
+			start = kvm_gfn_private(kvm, range->start);
+			end = kvm_gfn_private(kvm, range->end);
+		} else {
+			start = kvm_gfn_shared(kvm, range->start);
+			end = kvm_gfn_shared(kvm, range->end);
+		}

I think this could be a separate function kvm_gfn_for_root(kvm, root, ...).

arch/x86/kvm/mmu/tdp_mmu.c static bool age_gfn_range(struct kvm *kvm, struct tdp_iter *iter, · line 1275

Quoted 12 lines
arch/x86/kvm/mmu/tdp_mmu.c +8 -0
@@ -1237,6 +1265,15 @@ static bool age_gfn_range(struct kvm *kvm, struct tdp_iter *iter,
  	if (!is_accessed_spte(iter->old_spte))
  		return false;
 
+	/*
+	 * First TDX generation doesn't support clearing A bit for private
+	 * mapping, since there's no secure EPT API to support it.  However
+	 * it's a legitimate request for TDX guest, so just return w/o a
+	 * WARN().
+	 */
+	if (is_private_spte(iter->sptep))
+		return false;

Please add instead a "bool only_shared" argument to kvm_tdp_mmu_handle_gfn, since you can check "only_shared && is_private_sp(root)" just once (instead of checking it once per PTE).

Quoted 18 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -0
  	new_spte = iter->old_spte;
 
  	if (spte_ad_enabled(new_spte)) {
@@ -1281,6 +1318,13 @@ static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
  	/* Huge pages aren't expected to be modified without first being zapped. */
  	WARN_ON(pte_huge(range->pte) || range->start + 1 != range->end);
 
+	/*
+	 * .change_pte() callback should not happen for private page, because
+	 * for now TDX private pages are pinned during VM's life time.
+	 */
+	if (WARN_ON(is_private_spte(iter->sptep)))
+		return false;
+
  	if (iter->level != PG_LEVEL_4K ||
  	    !is_shadow_present_pte(iter->old_spte))
  		return false;

arch/x86/kvm/mmu/tdp_mmu.c static bool wrprot_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root, · line 1385

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -0
@@ -1332,6 +1376,16 @@ static bool wrprot_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
  	u64 new_spte;
  	bool spte_set = false;
 
+	/*
+	 * First TDX generation doesn't support write protecting private
+	 * mappings, since there's no secure EPT API to support it.  It
+	 * is a bug to reach here for TDX guest.
+	 */
+	if (WARN_ON(is_private_sp(root)))
+		return spte_set;

Isn't this function unreachable even for the shared address range? If so, this WARN should be in kvm_tdp_mmu_wrprot_slot, and also it should check if !kvm_arch_dirty_log_supported(kvm).

Review static bool wrprot_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root, · line 1387

Quoted 2 lines
(quoted diff) +2 -0
+	start = kvm_gfn_shared(kvm, start);
+	end = kvm_gfn_shared(kvm, end);

... and then these two lines are unnecessary.

Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
  	rcu_read_lock();
 
  	BUG_ON(min_level > KVM_MAX_HUGEPAGE_LEVEL);

arch/x86/kvm/mmu/tdp_mmu.c static bool clear_dirty_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root, · line 1461

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -0
@@ -1398,6 +1452,16 @@ static bool clear_dirty_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
  	u64 new_spte;
  	bool spte_set = false;
 
+	/*
+	 * First TDX generation doesn't support clearing dirty bit,
+	 * since there's no secure EPT API to support it.  It is a
+	 * bug to reach here for TDX guest.
+	 */
+	if (WARN_ON(is_private_sp(root)))
+		return spte_set;

Same here, can you check it in kvm_tdp_mmu_clear_dirty_slot?

Review static bool clear_dirty_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root, · line 1463

Quoted 2 lines
(quoted diff) +2 -0
+	start = kvm_gfn_shared(kvm, start);
+	end = kvm_gfn_shared(kvm, end);

Same here.

Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
  	rcu_read_lock();
 
  	tdp_root_for_each_leaf_pte(iter, root, start, end) {

arch/x86/kvm/mmu/tdp_mmu.c static void clear_dirty_pt_masked(struct kvm *kvm, struct kvm_mmu_page *root, · line 1540

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -0
@@ -1467,6 +1531,15 @@ static void clear_dirty_pt_masked(struct kvm *kvm, struct kvm_mmu_page *root,
  	struct tdp_iter iter;
  	u64 new_spte;
 
+	/*
+	 * First TDX generation doesn't support clearing dirty bit,
+	 * since there's no secure EPT API to support it.  It is a
+	 * bug to reach here for TDX guest.
+	 */
+	if (WARN_ON(is_private_sp(root)))
+		return;

IIRC this is reachable from userspace, so WARN_ON is not possible. But, again please check

	if (!kvm_arch_dirty_log_supported(kvm))
		return;

in kvm_tdp_mmu_clear_dirty_pt_masked.

arch/x86/kvm/mmu/tdp_mmu.c static void clear_dirty_pt_masked(struct kvm *kvm, struct kvm_mmu_page *root, · line 1541

Quoted 1 line
arch/x86/kvm/mmu/tdp_mmu.c +1 -0
+	gfn = kvm_gfn_shared(kvm, gfn);

Also unnecessary, I think.

Quoted 6 lines
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
  	rcu_read_lock();
 
  	tdp_root_for_each_leaf_pte(iter, root, gfn + __ffs(mask),
@@ -1530,6 +1603,16 @@ static void zap_collapsible_spte_range(struct kvm *kvm,
  	struct tdp_iter iter;
  	kvm_pfn_t pfn;

arch/x86/kvm/mmu/tdp_mmu.c static void zap_collapsible_spte_range(struct kvm *kvm, · line 1614

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +9 -0
 
+	/*
+	 * This should only be reachable in case of log-dirty, which TD
+	 * private mapping doesn't support so far.  Give a WARN() if it
+	 * hits private mapping.
+	 */
+	if (WARN_ON(is_private_sp(root)))
+		return;
+	start = kvm_gfn_shared(kvm, start);
+	end = kvm_gfn_shared(kvm, end);

I think this is not a big deal and you can leave it as is. Alternatively, please move the WARN to kvm_tdp_mmu_zap_collapsible_sptes(). It is also only reachable if you can set KVM_MEM_LOG_DIRTY_PAGES in the first place.

Paolo

Quoted 30 lines
arch/x86/kvm/mmu/tdp_mmu.c +11 -2
  	rcu_read_lock();
 
  	tdp_root_for_each_pte(iter, root, start, end) {
@@ -1543,8 +1626,9 @@ static void zap_collapsible_spte_range(struct kvm *kvm,
 
  		pfn = spte_to_pfn(iter.old_spte);
  		if (kvm_is_reserved_pfn(pfn) ||
-		    iter.level >= kvm_mmu_max_mapping_level(kvm, slot, iter.gfn,
-							    pfn, PG_LEVEL_NUM))
+		    iter.level >= kvm_mmu_max_mapping_level(kvm, slot,
+			    tdp_iter_gfn_unalias(kvm, &iter), pfn,
+			    PG_LEVEL_NUM))
  			continue;
 
  		/* Note, a successful atomic zap also does a remote TLB flush. */
@@ -1590,6 +1674,14 @@ static bool write_protect_gfn(struct kvm *kvm, struct kvm_mmu_page *root,
 
  	BUG_ON(min_level > KVM_MAX_HUGEPAGE_LEVEL);
 
+	/*
+	 * First TDX generation doesn't support write protecting private
+	 * mappings, since there's no secure EPT API to support it.  It
+	 * is a bug to reach here for TDX guest.
+	 */
+	if (WARN_ON(is_private_sp(root)))
+		return spte_set;
+
  	rcu_read_lock();
 
  	for_each_tdp_pte_min_level(iter, root->spt, root->role.level,
maintainer Reviewed-by on v5 47/104
#161 lore raw

Re: [RFC PATCH v5 047/104] KVM: x86/mmu: add a private pointer to struct kvm_mmu_page

In reply to [email protected]
Quoted 185 lines · On 3/4/22 20:49, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a private pointer to kvm_mmu_page for private EPT.

To resolve KVM page fault on private GPA, it will allocate additional page for Secure EPT in addition to private EPT. Add memory allocator for it and topup its memory allocator before resolving KVM page fault similar to shared EPT page. Allocation of those memory will be done for TDP MMU by alloc_tdp_mmu_page(). Freeing those memory will be done for TDP MMU on behalf of kvm_tdp_mmu_zap_all() called by kvm_mmu_zap_all(). Private EPT page needs to carry one more page used for Secure EPT in addition to the private EPT page. Add private pointer to struct kvm_mmu_page for that purpose and Add helper functions to allocate/free a page for Secure EPT. Also add helper functions to check if a given kvm_mmu_page is private.

---
  arch/x86/include/asm/kvm_host.h |  1 +
  arch/x86/kvm/mmu/mmu.c          |  9 ++++
  arch/x86/kvm/mmu/mmu_internal.h | 84 +++++++++++++++++++++++++++++++++
  arch/x86/kvm/mmu/tdp_mmu.c      |  3 ++
  4 files changed, 97 insertions(+)
arch/x86/include/asm/kvm_host.h +1 -0
index fcab2337819c..0c8cc7d73371 100644
@@ -689,6 +689,7 @@ struct kvm_vcpu_arch {
  	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
  	struct kvm_mmu_memory_cache mmu_gfn_array_cache;
  	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	struct kvm_mmu_memory_cache mmu_private_sp_cache;
 
  	/*
  	 * QEMU userspace and the guest each have their own FPU state.
arch/x86/kvm/mmu/mmu.c +9 -0
index 6e9847b1124b..8def8b97978f 100644
@@ -758,6 +758,13 @@ static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
  	struct kvm_mmu_memory_cache *mc = &vcpu->arch.mmu_shadow_page_cache;
  	int start, end, i, r;
 
+	if (kvm_gfn_stolen_mask(vcpu->kvm)) {
+		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_private_sp_cache,
+					       PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
+	}
+
  	if (shadow_init_value)
  		start = kvm_mmu_memory_cache_nr_free_objects(mc);
 
@@ -799,6 +806,7 @@ static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
  {
  	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
  	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_sp_cache);
  	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
  	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
  }
@@ -1791,6 +1799,7 @@ static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct
  	if (!direct)
  		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
  	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
+	kvm_mmu_init_private_sp(sp);
 
  	/*
  	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
arch/x86/kvm/mmu/mmu_internal.h +84 -0
index da6166b5c377..80f7a74a71dc 100644
@@ -53,6 +53,10 @@ struct kvm_mmu_page {
  	u64 *spt;
  	/* hold the gfn of each spte inside spt */
  	gfn_t *gfns;
+#ifdef CONFIG_KVM_MMU_PRIVATE
+	/* associated private shadow page, e.g. SEPT page */
+	void *private_sp;
+#endif
  	/* Currently serving as active root */
  	union {
  		int root_count;
@@ -104,6 +108,86 @@ static inline int kvm_mmu_page_as_id(struct kvm_mmu_page *sp)
  	return kvm_mmu_role_as_id(sp->role);
  }
 
+/*
+ * TDX vcpu allocates page for root Secure EPT page and assigns to CPU secure
+ * EPT pointer.  KVM doesn't need to allocate and link to the secure EPT.
+ * Dummy value to make is_pivate_sp() return true.
+ */
+#define KVM_MMU_PRIVATE_SP_ROOT	((void *)1)
+
+#ifdef CONFIG_KVM_MMU_PRIVATE
+static inline bool is_private_sp(struct kvm_mmu_page *sp)
+{
+	return !!sp->private_sp;
+}
+
+static inline bool is_private_spte(u64 *sptep)
+{
+	return is_private_sp(sptep_to_sp(sptep));
+}
+
+static inline void *kvm_mmu_private_sp(struct kvm_mmu_page *sp)
+{
+	return sp->private_sp;
+}
+
+static inline void kvm_mmu_init_private_sp(struct kvm_mmu_page *sp)
+{
+	sp->private_sp = NULL;
+}
+
+/* Valid sp->role.level is required. */
+static inline void kvm_mmu_alloc_private_sp(struct kvm_vcpu *vcpu,
+					struct kvm_mmu_page *sp)
+{
+	if (vcpu->arch.mmu->shadow_root_level == sp->role.level)
+		sp->private_sp = KVM_MMU_PRIVATE_SP_ROOT;
+	else
+		sp->private_sp =
+			kvm_mmu_memory_cache_alloc(
+				&vcpu->arch.mmu_private_sp_cache);
+	/*
+	 * Because mmu_private_sp_cache is topped up before staring kvm page
+	 * fault resolving, the allocation above shouldn't fail.
+	 */
+	WARN_ON_ONCE(!sp->private_sp);
+}
+
+static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
+{
+	if (sp->private_sp != KVM_MMU_PRIVATE_SP_ROOT)
+		free_page((unsigned long)sp->private_sp);
+}
+#else
+static inline bool is_private_sp(struct kvm_mmu_page *sp)
+{
+	return false;
+}
+
+static inline bool is_private_spte(u64 *sptep)
+{
+	return false;
+}
+
+static inline void *kvm_mmu_private_sp(struct kvm_mmu_page *sp)
+{
+	return NULL;
+}
+
+static inline void kvm_mmu_init_private_sp(struct kvm_mmu_page *sp)
+{
+}
+
+static inline void kvm_mmu_alloc_private_sp(struct kvm_vcpu *vcpu,
+					struct kvm_mmu_page *sp)
+{
+}
+
+static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
+{
+}
+#endif
+
  static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
  {
  	/*
arch/x86/kvm/mmu/tdp_mmu.c +2 -0
index 8db262440d5c..a68f3a22836b 100644
@@ -59,6 +59,8 @@ static bool zap_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
 
  static void tdp_mmu_free_sp(struct kvm_mmu_page *sp)
  {
+	if (is_private_sp(sp))
+		kvm_mmu_free_private_sp(sp);
  	free_page((unsigned long)sp->spt);
  	kmem_cache_free(mmu_page_header_cache, sp);
  }

arch/x86/kvm/mmu/tdp_mmu.c static struct kvm_mmu_page *alloc_tdp_mmu_page(struct kvm_vcpu *vcpu, gfn_t gfn, · line 192

Quoted 7 lines
arch/x86/kvm/mmu/tdp_mmu.c +1 -0
@@ -184,6 +186,7 @@ static struct kvm_mmu_page *alloc_tdp_mmu_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  	sp->role.word = page_role_for_level(vcpu, level).word;
  	sp->gfn = gfn;
  	sp->tdp_mmu_page = true;
+	kvm_mmu_init_private_sp(sp);
 
  	trace_kvm_mmu_get_page(sp, true);
 
maintainer Reviewed-by on v5 76/104
#225 lore raw

Re: [RFC PATCH v5 076/104] KVM: x86: Add option to force LAPIC expiration wait

In reply to [email protected]
Quoted 8 lines · On 3/4/22 20:49, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Add an option to skip the IRR check-in kvm_wait_lapic_expire(). This will be used by TDX to wait if there is an outstanding notification for a TD, i.e. a virtual interrupt is being triggered via posted interrupt processing. KVM TDX doesn't emulate PI processing, i.e. there will never be a bit set in IRR/ISR, so the default behavior for APICv of querying the IRR doesn't work as intended.

Would be better to explain "doesn't work as intended" more verbosely. Otherwise,

Paolo

Quoted 67 lines
---
  arch/x86/kvm/lapic.c   | 4 ++--
  arch/x86/kvm/lapic.h   | 2 +-
  arch/x86/kvm/svm/svm.c | 2 +-
  arch/x86/kvm/vmx/vmx.c | 2 +-
  4 files changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/lapic.c +2 -2
index 9322e6340a74..d49f029ef0e3 100644
@@ -1620,12 +1620,12 @@ static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
  		__wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
  }
 
-void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
+void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu, bool force_wait)
  {
  	if (lapic_in_kernel(vcpu) &&
  	    vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
  	    vcpu->arch.apic->lapic_timer.timer_advance_ns &&
-	    lapic_timer_int_injected(vcpu))
+	    (force_wait || lapic_timer_int_injected(vcpu)))
  		__kvm_wait_lapic_expire(vcpu);
  }
  EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
arch/x86/kvm/lapic.h +1 -1
index 2b44e533fc8d..2a0119ef9e96 100644
@@ -233,7 +233,7 @@ static inline int kvm_lapic_latched_init(struct kvm_vcpu *vcpu)
 
  bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector);
 
-void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu);
+void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu, bool force_wait);
 
  void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
  			      unsigned long *vcpu_bitmap);
arch/x86/kvm/svm/svm.c +1 -1
index c7eec23e9ebe..a46415845f48 100644
@@ -3766,7 +3766,7 @@ static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu)
  	clgi();
  	kvm_load_guest_xsave_state(vcpu);
 
-	kvm_wait_lapic_expire(vcpu);
+	kvm_wait_lapic_expire(vcpu, false);
 
  	/*
  	 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
arch/x86/kvm/vmx/vmx.c +1 -1
index 00f88aa25047..9b7bd52d19a9 100644
@@ -6838,7 +6838,7 @@ fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
  	if (enable_preemption_timer)
  		vmx_update_hv_timer(vcpu);
 
-	kvm_wait_lapic_expire(vcpu);
+	kvm_wait_lapic_expire(vcpu, false);
 
  	/*
  	 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
maintainer
#219 lore raw

Re: [RFC PATCH v5 074/104] KVM: x86: Add a switch_db_regs flag to handle TDX's auto-switched behavior

In reply to [email protected]
Quoted 11 lines · On 3/4/22 20:49, [email protected] wrote:
  	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
arch/x86/kvm/vmx/tdx.c +1 -0
+	vcpu->arch.switch_db_regs = KVM_DEBUGREG_AUTO_SWITCH;
  	vcpu->arch.cr0_guest_owned_bits = -1ul;
  	vcpu->arch.cr4_guest_owned_bits = -1ul;
arch/x86/kvm/x86.c +0 -0
index 45e8a02e99bf..89d04cd64cd0 100644

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 10090

Quoted 8 lines
arch/x86/kvm/x86.c +1 -1
@@ -10084,7 +10084,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	if (vcpu->arch.guest_fpu.xfd_err)
  		wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
 
-	if (unlikely(vcpu->arch.switch_db_regs)) {
+	if (unlikely(vcpu->arch.switch_db_regs & ~KVM_DEBUGREG_AUTO_SWITCH)) {
  		set_debugreg(0, 7);
  		set_debugreg(vcpu->arch.eff_db[0], 0);
  		set_debugreg(vcpu->arch.eff_db[1], 1);

I'm confused. I'm probably missing something obvious, but where does KVM_DEBUGREG_AUTO_SWITCH affect the behavior of KVM? vcpu_enter_guest would still write %db0-%db3 if KVM_DEBUGREG_BP_ENABLED is set, for example.

Do you mean:

	if (unlikely(vcpu->arch.switch_db_regs) &&
	    !unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH)) {

?

Paolo

Quoted 8 lines
arch/x86/kvm/x86.c +1 -0
@@ -10126,6 +10126,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	 */
  	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
  		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
+		WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
  		static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
  		kvm_update_dr0123(vcpu);
  		kvm_update_dr7(vcpu);
maintainer
#124 lore raw

Re: [RFC PATCH v5 037/104] KVM: x86/mmu: Allow non-zero init value for shadow PTE

In reply to Kai Huang
Quoted 2 lines · Kai Huang

Btw, I think the relevant part of TDP MMU change should be included in this patch too otherwise TDP MMU is broken with this patch.

I agree.

Paolo

Quoted 3 lines

Actually in this series legacy MMU is not supported to work with TDX, so above change to legacy MMU doesn't matter actually. Instead, TDP MMU change should be here.

#294 lore raw

Re: [RFC PATCH v5 101/104] KVM: TDX: Silently ignore INIT/SIPI

In reply to Paolo Bonzini
Quoted 18 lines · Paolo Bonzini
Quoted 8 lines · On 3/4/22 20:49, [email protected] wrote:

+        if (kvm_init_sipi_unsupported(vcpu->kvm))
+            /*
+             * TDX doesn't support INIT.  Ignore INIT event.  In the +             * case of SIPI, the callback of
+             * vcpu_deliver_sipi_vector ignores it.
+             */
              vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; -        else

Quoted 8 lines

-            vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED; +        else {
+            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; +        }

Quoted 1 line

Should you check vcpu->arch.guest_state_protected instead of special-casing TDX?  KVM_APIC_INIT is not valid for SEV-ES either, if I remember correctly.

While the INIT doesn't update any actual state that is in the encrypted VMSA, SEV-ES still calls kvm_vcpu_reset() to allow KVM to set any internal tracking state, etc. I haven't ever tested SEV-ES where that is bypassed.

Thanks,
Tom

Quoted 2 lines

Paolo

maintainer
#106 lore raw

Re: [RFC PATCH v5 032/104] KVM: x86/mmu: introduce config for PRIVATE KVM MMU

In reply to Kai Huang
Quoted 6 lines · Kai Huang
Quoted 3 lines

I don't want to use CONFIG_INTEL_TDX_HOST in KVM MMU code. I think the change to KVM MMU should be a sort of independent from TDX. But it seems failed based on your feedback.

Why do you need to use any config? As I said majority of your changes to MMU are not under any config. But I'll leave this to maintainer/reviewers.

There are few uses, but the effect should be pretty large, because the config symbol replaces variable accesses with constants:

+static inline gfn_t kvm_gfn_stolen_mask(struct kvm *kvm) +{
+#ifdef CONFIG_KVM_MMU_PRIVATE
+ return kvm->arch.gfn_shared_mask;
+#else
+ return 0;
+#endif
+}

Please keep it.

Paolo

maintainer Reviewed-by on v5 37/104
#127 lore raw

Re: [RFC PATCH v5 037/104] KVM: x86/mmu: Allow non-zero init value for shadow PTE

In reply to [email protected]

arch/x86/kvm/mmu/mmu.c static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep) · line 655

Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:
  static void mmu_spte_clear_no_track(u64 *sptep)
  {
arch/x86/kvm/mmu/mmu.c +1 -1
-	__update_clear_spte_fast(sptep, 0ull);
+	__update_clear_spte_fast(sptep, shadow_init_value);
  }

Please WARN_ON_ONCE if shadow_init_value is nonzero, and then keep 0ull as the argument.

I have not thought much of the steps that are needed if were to flip both bit 0 and bit 63, so let's at least document that with a WARN.

Otherwise,

Paolo

maintainer Reviewed-by on v5 40/104
#139 lore raw

Re: [RFC PATCH v5 040/104] KVM: VMX: Split out guts of EPT violation to common/exposed function

In reply to [email protected]
Quoted 117 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

The difference of TDX EPT violation is how to retrieve information, GPA, and exit qualification. To share the code to handle EPT violation, split out the guts of EPT violation handler so that VMX/TDX exit handler can call it after retrieving GPA and exit qualification.

---
  arch/x86/kvm/vmx/common.h | 35 +++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/vmx.c    | 34 ++++++----------------------------
  2 files changed, 41 insertions(+), 28 deletions(-)

create mode 100644 arch/x86/kvm/vmx/common.h

arch/x86/kvm/vmx/common.h new file +35 -0
new file mode 100644
index 000000000000..1052b3c93eb8
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef __KVM_X86_VMX_COMMON_H
+#define __KVM_X86_VMX_COMMON_H
+
+#include <linux/kvm_host.h>
+
+#include "mmu.h"
+
+static inline int __vmx_handle_ept_violation(struct kvm_vcpu *vcpu, gpa_t gpa,
+					     unsigned long exit_qualification)
+{
+	u64 error_code;
+
+	/* Is it a read fault? */
+	error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
+		     ? PFERR_USER_MASK : 0;
+	/* Is it a write fault? */
+	error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
+		      ? PFERR_WRITE_MASK : 0;
+	/* Is it a fetch fault? */
+	error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
+		      ? PFERR_FETCH_MASK : 0;
+	/* ept page table entry is present? */
+	error_code |= (exit_qualification &
+		       (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
+			EPT_VIOLATION_EXECUTABLE))
+		      ? PFERR_PRESENT_MASK : 0;
+
+	error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
+	       PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
+
+	return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
+}
+
+#endif /* __KVM_X86_VMX_COMMON_H */
arch/x86/kvm/vmx/vmx.c +5 -27
index 7838cd177f0e..0edeeed0b4c8 100644
@@ -50,6 +50,7 @@
  #include <asm/vmx.h>
 
  #include "capabilities.h"
+#include "common.h"
  #include "cpuid.h"
  #include "evmcs.h"
  #include "hyperv.h"
@@ -5381,11 +5382,10 @@ static int handle_task_switch(struct kvm_vcpu *vcpu)
 
  static int handle_ept_violation(struct kvm_vcpu *vcpu)
  {
-	unsigned long exit_qualification;
-	gpa_t gpa;
-	u64 error_code;
+	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
+	gpa_t gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
 
-	exit_qualification = vmx_get_exit_qual(vcpu);
+	trace_kvm_page_fault(gpa, exit_qualification);
 
  	/*
  	 * EPT violation happened while executing iret from NMI,
@@ -5394,31 +5394,9 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)
  	 * AAK134, BY25.
  	 */
  	if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
-			enable_vnmi &&
-			(exit_qualification & INTR_INFO_UNBLOCK_NMI))
+	    enable_vnmi && (exit_qualification & INTR_INFO_UNBLOCK_NMI))
  		vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
 
-	gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
-	trace_kvm_page_fault(gpa, exit_qualification);
-
-	/* Is it a read fault? */
-	error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
-		     ? PFERR_USER_MASK : 0;
-	/* Is it a write fault? */
-	error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
-		      ? PFERR_WRITE_MASK : 0;
-	/* Is it a fetch fault? */
-	error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
-		      ? PFERR_FETCH_MASK : 0;
-	/* ept page table entry is present? */
-	error_code |= (exit_qualification &
-		       (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
-			EPT_VIOLATION_EXECUTABLE))
-		      ? PFERR_PRESENT_MASK : 0;
-
-	error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
-	       PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
-
  	vcpu->arch.exit_qualification = exit_qualification;
 
  	/*

arch/x86/kvm/vmx/vmx.c static int handle_ept_violation(struct kvm_vcpu *vcpu) · line 5416

Quoted 8 lines
arch/x86/kvm/vmx/vmx.c +1 -1
@@ -5432,7 +5410,7 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)
  	if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
  		return kvm_emulate_instruction(vcpu, 0);
 
-	return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
+	return __vmx_handle_ept_violation(vcpu, gpa, exit_qualification);
  }
 
  static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
maintainer
#291 lore raw

Re: [RFC PATCH v5 100/104] KVM: TDX: Silently discard SMI request

In reply to [email protected]
Quoted 9 lines · On 3/4/22 20:49, [email protected] wrote:

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.

Quoted 5 lines

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).

Please also:

1) return zero from vmx_has_emulated_msr(MSR_IA32_SMBASE) for TDX virtual machines.

2) do a check for static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE) in kvm_vcpu_ioctl_smi and __apic_accept_irq.

3) WARN_ON_ONCE in tdx_smi_allowed and tdx_enable_smi_window.

Paolo

maintainer
#111 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to Isaku Yamahata
Quoted 7 lines · Isaku Yamahata

Sure, this patch heavily changed from the original patch Now. One suggestion is that private/shared is characteristic to kvm page fault, not gpa/gfn. It's TDX specific.

- Add a helper function to check if KVM MMU is TD or VM. Right now kvm_gfn_stolen_mask() is used. Probably kvm_mmu_has_private_bit(). (any better name?)

I think use of kvm_gfn_stolen_mask() should be minimized anyway. I would rename it to to kvm_{gfn,gpa}_private_mask and not return bool.

Quoted 1 line

- Let's keep address conversion functions: address => unalias/shared/private

unalias is the same as private. It doesn't seem to have a lot of uses.
I would just inline "x & ~gfn_private_mask", or "x &
~kvm_gfn_private_mask(kvm)"; or the same with gpa of course.

The shared and private conversion functions should remain.

Quoted 2 lines

- Add struct kvm_page_fault.is_private
see how kvm_is_private_{gpa, gfn}() can be removed (or reduced).

Agreed.

Paolo

maintainer
#113 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to Kai Huang
Quoted 6 lines · Kai Huang

arch/x86/kvm/mmu/mmu.c static inline bool kvm_available_flush_tlb_with_range(void) · line 292

Quoted 3 lines
arch/x86/kvm/mmu/mmu.c +3 -0
+	if (range && kvm_available_flush_tlb_with_range()) {
+		/* Callback should flush both private GFN and shared GFN. */
+		range->start_gfn = kvm_gfn_unalias(kvm, range->start_gfn);

This seems wrong. It seems the intention of this function is to flush TLB for all aliases for a given GFN range. Here it seems you are unconditionally change to range to always exclude the stolen bits.

He passes the "low" range with bits cleared, and expects the callback to take care of both. That seems okay (apart from the incorrect fallthrough that you pointed out).

Quoted 11 lines

arch/x86/kvm/mmu/paging_tmpl.h static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1091

Quoted 7 lines
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
-		gfn = gpte_to_gfn(gpte);
+		gfn = gpte_to_gfn(vcpu, gpte);
 		pte_access = sp->role.access;
 		pte_access &= FNAME(gpte_access)(gpte);
 		FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);

In commit message you mentioned "Don't support stolen bits for shadow EPT" (you actually mean shadow MMU I suppose), yet there's bunch of code change to shadow MMU.

It's a bit ugly, but it's uglier to keep two versions of gpte_to_gfn.

Perhaps the commit message can be rephrased to "Stolen bits are not supported in the shadow MMU; they will be used only for TDX which uses the TDP MMU exclusively as it does not support nested virtualization. Therefore, the gfn_shared_mask will always be zero in that case".

Paolo

maintainer
#141 lore raw

Re: [RFC PATCH v5 041/104] KVM: VMX: Move setting of EPT MMU masks to common VT-x code

In reply to [email protected]
Quoted 41 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

EPT MMU masks are used commonly for VMX and TDX. The value needs to be initialized in common code before both VMX/TDX-specific initialization code.

---
  arch/x86/kvm/vmx/main.c | 5 +++++
  arch/x86/kvm/vmx/vmx.c  | 4 ----
  2 files changed, 5 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +5 -0
index 3eb9db6d83ac..51aaafe6b432 100644
@@ -4,6 +4,7 @@
  #include "x86_ops.h"
  #include "vmx.h"
  #include "nested.h"
+#include "mmu.h"
  #include "pmu.h"
  #include "tdx.h"
 
@@ -22,6 +23,10 @@ static __init int vt_hardware_setup(void)
 
  	tdx_hardware_setup(&vt_x86_ops);
 
+	if (enable_ept)
+		kvm_mmu_set_ept_masks(enable_ept_ad_bits,
+				      cpu_has_vmx_ept_execute_only());
+
  	return 0;
  }
 
arch/x86/kvm/vmx/vmx.c +0 -0
index 0edeeed0b4c8..07fd892768be 100644

arch/x86/kvm/vmx/vmx.c __init int vmx_hardware_setup(void) · line 7822

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +0 -4
@@ -7817,10 +7817,6 @@ __init int vmx_hardware_setup(void)
 
  	set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
 
-	if (enable_ept)
-		kvm_mmu_set_ept_masks(enable_ept_ad_bits,
-				      cpu_has_vmx_ept_execute_only());
-
  	kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
  			  ept_caps_to_lpage_level(vmx_capability.ept));
 

RB

maintainer Reviewed-by on v5 43/104
#151 lore raw

Re: [RFC PATCH v5 043/104] KVM: TDX: Add load_mmu_pgd method for TDX

In reply to [email protected]
Quoted 91 lines · On 3/4/22 20:48, [email protected] wrote:

From: Sean Christopherson <[email protected]>

For virtual IO, the guest TD shares guest pages with VMM without encryption. Shared EPT is used to map guest pages in unprotected way.

Add the VMCS field encoding for the shared EPTP, which will be used by TDX to have separate EPT walks for private GPAs (existing EPTP) versus shared GPAs (new shared EPTP).

Set shared EPT pointer value for the TDX guest to initialize TDX MMU.

---
  arch/x86/include/asm/vmx.h |  1 +
  arch/x86/kvm/vmx/main.c    | 11 ++++++++++-
  arch/x86/kvm/vmx/tdx.c     |  5 +++++
  arch/x86/kvm/vmx/x86_ops.h |  4 ++++
  4 files changed, 20 insertions(+), 1 deletion(-)
arch/x86/include/asm/vmx.h +1 -0
index 88d9b8cc7dde..a2402d1bde04 100644
@@ -221,6 +221,7 @@ enum vmcs_field {
  	ENCLS_EXITING_BITMAP_HIGH	= 0x0000202F,
  	TSC_MULTIPLIER                  = 0x00002032,
  	TSC_MULTIPLIER_HIGH             = 0x00002033,
+	SHARED_EPT_POINTER		= 0x0000203C,
  	GUEST_PHYSICAL_ADDRESS          = 0x00002400,
  	GUEST_PHYSICAL_ADDRESS_HIGH     = 0x00002401,
  	VMCS_LINK_POINTER               = 0x00002800,
arch/x86/kvm/vmx/main.c +10 -1
index b242a9dc9e29..6969e3557bd4 100644
@@ -89,6 +89,15 @@ static void vt_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  	return vmx_vcpu_reset(vcpu, init_event);
  }
 
+static void vt_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
+			int pgd_level)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_load_mmu_pgd(vcpu, root_hpa, pgd_level);
+
+	vmx_load_mmu_pgd(vcpu, root_hpa, pgd_level);
+}
+
  static int vt_mem_enc_op(struct kvm *kvm, void __user *argp)
  {
  	if (!is_td(kvm))
@@ -205,7 +214,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.write_tsc_offset = vmx_write_tsc_offset,
  	.write_tsc_multiplier = vmx_write_tsc_multiplier,
 
-	.load_mmu_pgd = vmx_load_mmu_pgd,
+	.load_mmu_pgd = vt_load_mmu_pgd,
 
  	.check_intercept = vmx_check_intercept,
  	.handle_exit_irqoff = vmx_handle_exit_irqoff,
arch/x86/kvm/vmx/tdx.c +5 -0
index c3434b33c452..51098e10b6a0 100644
@@ -496,6 +496,11 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  	vcpu->kvm->vm_bugged = true;
  }
 
+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);
+}
+
  static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
  {
  	struct kvm_tdx_capabilities __user *user_caps;
arch/x86/kvm/vmx/x86_ops.h +2 -0
index 81f246493ec7..ad9b1c883761 100644
@@ -143,6 +143,8 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
 
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
  int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
+
+void tdx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level);
  #else
  static inline void tdx_pre_kvm_init(
  	unsigned int *vcpu_size, unsigned int *vcpu_align, unsigned int *vm_size) {}

arch/x86/kvm/vmx/x86_ops.h static inline void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) {} · line 169

Quoted 8 lines
arch/x86/kvm/vmx/x86_ops.h +2 -0
@@ -160,6 +162,8 @@ static inline void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) {}
 
  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; }
+
+static inline void tdx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level) {}
  #endif
 
  #endif /* __KVM_X86_VMX_X86_OPS_H */
maintainer
#143 lore raw

Re: [RFC PATCH v5 042/104] KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis

In reply to [email protected]

arch/x86/kvm/vmx/main.c static __init int vt_hardware_setup(void) · line 31

Quoted 7 lines · On 3/4/22 20:48, [email protected] wrote:
arch/x86/kvm/vmx/main.c +5 -1
+	if (enable_ept) {
+		const u64 init_value = enable_tdx ? VMX_EPT_SUPPRESS_VE_BIT : 0ull;
  		kvm_mmu_set_ept_masks(enable_ept_ad_bits,
-				      cpu_has_vmx_ept_execute_only());
+				      cpu_has_vmx_ept_execute_only(), init_value);
+		kvm_mmu_set_spte_init_value(init_value);
+	}

I think kvm-intel.ko should use VMX_EPT_SUPPRESS_VE_BIT unconditionally as the init value. The bit is ignored anyway if the "EPT-violation #VE" execution control is 0. Otherwise looks good, but I have a couple more crazy ideas:

1) there could even be a test mode where KVM enables the execution control, traps #VE in the exception bitmap, and shouts loudly if it gets a #VE. That might avoid hard-to-find bugs due to forgetting about VMX_EPT_SUPPRESS_VE_BIT.

2) or even, perhaps the init_value for the TDP MMU could set bit 63 _unconditionally_, because KVM always sets the NX bit on AMD hardware. That would remove the whole infrastructure to keep shadow_init_value, because it would be constant 0 in mmu.c and constant BIT(63) in tdp_mmu.c.

Sean, what do you think?

Paolo

maintainer
#154 lore raw

Re: [RFC PATCH v5 045/104] KVM: x86/tdp_mmu: make REMOVED_SPTE include shadow_initial value

In reply to [email protected]
Quoted 33 lines · On 3/4/22 20:49, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDP MMU uses REMOVED_SPTE = 0x5a0ULL as special constant to indicate the intermediate value to indicate one thread is operating on it and the value should be semi-arbitrary value. For TDX (more correctly to use #VE), the value should include suppress #VE value which is shadow_init_value.

Define SHADOW_REMOVED_SPTE as shadow_init_value | REMOVED_SPTE, and replace REMOVED_SPTE with SHADOW_REMOVED_SPTE to use suppress #VE bit properly for TDX.

---
  arch/x86/kvm/mmu/spte.h    | 14 ++++++++++++--
  arch/x86/kvm/mmu/tdp_mmu.c | 23 ++++++++++++++++-------
  2 files changed, 28 insertions(+), 9 deletions(-)
arch/x86/kvm/mmu/spte.h +3 -1
index bde843bce878..e88f796724b4 100644
@@ -194,7 +194,9 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
   * If a thread running without exclusive control of the MMU lock must perform a
   * multi-part operation on an SPTE, it can set the SPTE to REMOVED_SPTE as a
   * non-present intermediate value. Other threads which encounter this value
- * should not modify the SPTE.
+ * should not modify the SPTE.  When TDX is enabled, shadow_init_value, which
+ * is "suppress #VE" bit set, is also set to removed SPTE, because TDX module
+ * always enables "EPT violation #VE".
   *
   * Use a semi-arbitrary value that doesn't set RWX bits, i.e. is not-present on
   * bot AMD and Intel CPUs, and doesn't set PFN bits, i.e. doesn't create a L1TF

arch/x86/kvm/mmu/spte.h extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask; · line 218

Quoted 10 lines
arch/x86/kvm/mmu/spte.h +7 -0
@@ -207,9 +209,17 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  /* Removed SPTEs must not be misconstrued as shadow present PTEs. */
  static_assert(!(REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
 
+/*
+ * See above comment around REMOVED_SPTE.  SHADOW_REMOVED_SPTE is the actual
+ * intermediate value set to the removed SPET.  When TDX is enabled, it sets
+ * the "suppress #VE" bit, otherwise it's REMOVED_SPTE.
+ */
+extern u64 __read_mostly shadow_init_value;
+#define SHADOW_REMOVED_SPTE	(shadow_init_value | REMOVED_SPTE)

Please rename the existing REMOVED_SPTE to REMOVED_SPTE_MASK, and call this simply REMOVED_SPTE. This also makes the patch smaller.

Paolo

Quoted 75 lines
arch/x86/kvm/mmu/spte.h +0 -0
  }
 
  /*
arch/x86/kvm/mmu/tdp_mmu.c +16 -7
index ebd0a02620e8..b6ec2f112c26 100644
@@ -338,7 +338,7 @@ static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
  			 * value to the removed SPTE value.
  			 */
  			for (;;) {
-				old_child_spte = xchg(sptep, REMOVED_SPTE);
+				old_child_spte = xchg(sptep, SHADOW_REMOVED_SPTE);
  				if (!is_removed_spte(old_child_spte))
  					break;
  				cpu_relax();
@@ -365,10 +365,10 @@ static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
  			 * the two branches consistent and simplifies
  			 * the function.
  			 */
-			WRITE_ONCE(*sptep, REMOVED_SPTE);
+			WRITE_ONCE(*sptep, SHADOW_REMOVED_SPTE);
  		}
  		handle_changed_spte(kvm, kvm_mmu_page_as_id(sp), gfn,
-				    old_child_spte, REMOVED_SPTE, level,
+				    old_child_spte, SHADOW_REMOVED_SPTE, level,
  				    shared);
  	}
 
@@ -537,7 +537,7 @@ static inline bool tdp_mmu_zap_spte_atomic(struct kvm *kvm,
  	 * immediately installing a present entry in its place
  	 * before the TLBs are flushed.
  	 */
-	if (!tdp_mmu_set_spte_atomic(kvm, iter, REMOVED_SPTE))
+	if (!tdp_mmu_set_spte_atomic(kvm, iter, SHADOW_REMOVED_SPTE))
  		return false;
 
  	kvm_flush_remote_tlbs_with_address(kvm, iter->gfn,
@@ -550,8 +550,16 @@ static inline bool tdp_mmu_zap_spte_atomic(struct kvm *kvm,
  	 * special removed SPTE value. No bookkeeping is needed
  	 * here since the SPTE is going from non-present
  	 * to non-present.
+	 *
+	 * Set non-present value to shadow_init_value, rather than 0.
+	 * It is because when TDX is enabled, TDX module always
+	 * enables "EPT-violation #VE", so KVM needs to set
+	 * "suppress #VE" bit in EPT table entries, in order to get
+	 * real EPT violation, rather than TDVMCALL.  KVM sets
+	 * shadow_init_value (which sets "suppress #VE" bit) so it
+	 * can be set when EPT table entries are zapped.
  	 */
-	WRITE_ONCE(*rcu_dereference(iter->sptep), 0);
+	WRITE_ONCE(*rcu_dereference(iter->sptep), shadow_init_value);
 
  	return true;
  }
@@ -748,7 +756,8 @@ static bool zap_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
  			continue;
 
  		if (!shared) {
-			tdp_mmu_set_spte(kvm, &iter, 0);
+			/* see comments in tdp_mmu_zap_spte_atomic() */
+			tdp_mmu_set_spte(kvm, &iter, shadow_init_value);
  			flush = true;
  		} else if (!tdp_mmu_zap_spte_atomic(kvm, &iter)) {
  			/*
@@ -1135,7 +1144,7 @@ static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
  	 * invariant that the PFN of a present * leaf SPTE can never change.
  	 * See __handle_changed_spte().
  	 */
-	tdp_mmu_set_spte(kvm, iter, 0);
+	tdp_mmu_set_spte(kvm, iter, shadow_init_value);
 
  	if (!pte_write(range->pte)) {
  		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
maintainer
#112 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to Isaku Yamahata
Quoted 7 lines · Isaku Yamahata

Sure, this patch heavily changed from the original patch Now. One suggestion is that private/shared is characteristic to kvm page fault, not gpa/gfn. It's TDX specific.

- Add a helper function to check if KVM MMU is TD or VM. Right now kvm_gfn_stolen_mask() is used. Probably kvm_mmu_has_private_bit(). (any better name?)

I think use of kvm_gfn_stolen_mask() should be minimized anyway. I would rename it to to kvm_{gfn,gpa}_private_mask and not return bool.

Quoted 1 line

- Let's keep address conversion functions: address => unalias/shared/private

unalias is the same as private. It doesn't seem to have a lot of uses.
I would just inline "x & ~gfn_private_mask", or "x &
~kvm_gfn_private_mask(kvm)"; or the same with gpa of course.

The shared and private conversion functions should remain.

Quoted 2 lines

- Add struct kvm_page_fault.is_private
see how kvm_is_private_{gpa, gfn}() can be removed (or reduced).

Agreed.

Paolo

maintainer
#126 lore raw

Re: [RFC PATCH v5 037/104] KVM: x86/mmu: Allow non-zero init value for shadow PTE

In reply to Kai Huang
Quoted 9 lines · Kai Huang

arch/x86/kvm/mmu/mmu.c static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep) · line 622

Quoted 9 lines
arch/x86/kvm/mmu/mmu.c +2 -2
@@ -617,9 +617,9 @@ static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
  	int level = sptep_to_sp(sptep)->role.level;
 
  	if (!spte_has_volatile_bits(old_spte))
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, shadow_init_value);
  	else
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep, shadow_init_value);

(FWIW this one should also assume that the init_value is zero, and WARN if not).

Quoted 22 lines

I guess it's better to have some comment here. Allow non-zero init value for shadow PTE doesn't necessarily mean the initial value should be used when one PTE is zapped. I think mmu_spte_clear_track_bits() is only called for mapping of normal (shared) memory but not MMIO? Then perhaps it's better to have a comment to explain we want "suppress #VE" set to get a real EPT violation for normal memory access from guest?

arch/x86/kvm/mmu/mmu.c static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep) · line 655

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +1 -1
  	if (!is_shadow_present_pte(old_spte))
  		return old_spte;
@@ -651,7 +651,7 @@ static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
   */
  static void mmu_spte_clear_no_track(u64 *sptep)
  {
-	__update_clear_spte_fast(sptep, 0ull);
+	__update_clear_spte_fast(sptep, shadow_init_value);
  }

Similar here. Seems mmu_spte_clear_no_track() is used to zap non-leaf PTE which doesn't require state tracking, so theoretically it can be set to 0. But this seems is also called to zap MMIO PTE so looks need to set to shadow_init_value. Anyway looks deserve a comment?

Quoted 6 lines

Btw, Above two changes to mmu_spte_clear_track_bits() and mmu_spte_clear_track_bits() seems a little bit out-of-scope of what this patch claims to do. Allow non-zero init value for shadow PTE doesn't necessarily mean the initial value should be used when one PTE is zapped. Maybe we can further improve the patch title and commit message a little bit. Such as: Allow non- zero value for empty (or invalid?) PTE? Non-present seems doesn't fit here.

I think shadow_init_value is not named well. Let's rename it to shadow_nonpresent_value, and the commit to "Allow non-zero value for non-present SPTE". That explains why it's used for zapping.

Paolo

maintainer
#228 lore raw

Re: [RFC PATCH v5 077/104] KVM: TDX: Use vcpu_to_pi_desc() uniformly in posted_intr.c

In reply to [email protected]
Quoted 39 lines · On 3/4/22 20:49, [email protected] wrote:

From: Yuan Yao <[email protected]>

The helper function, vcpu_to_pi_desc(), is defined to get the posted interrupt descriptor from vcpu. There is one place that doesn't use it, but direct reference to vmx_vcpu->pi_desc. It's inconsistent.

For TDX, TDX vcpu structure will be defined and the helper function, vcpu_to_pi_desc(), will return tdx_vcpu->pi_desc for TDX case instead of vmx_vcpu->pi_desc. The direct reference to vmx_vcpu->pi_desc doesn't work for TDX.

Replace vmx_vcpu->pi_desc with the helper function, vcpu_pi_desc() for consistency and TDX.

---
  arch/x86/kvm/vmx/posted_intr.c | 2 +-
  arch/x86/kvm/vmx/x86_ops.h     | 3 +++
  2 files changed, 4 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/posted_intr.c +1 -1
index aa1fe9085d77..c8a81c916eed 100644
@@ -311,7 +311,7 @@ int pi_update_irte(struct kvm *kvm, unsigned int host_irq, uint32_t guest_irq,
  			continue;
  		}
 
-		vcpu_info.pi_desc_addr = __pa(&to_vmx(vcpu)->pi_desc);
+		vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
  		vcpu_info.vector = irq.vector;
 
  		trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
arch/x86/kvm/vmx/x86_ops.h +0 -0
index aae0f4449ec5..0f1a28f67e60 100644

arch/x86/kvm/vmx/x86_ops.h void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu); · line 155

Quoted 9 lines
arch/x86/kvm/vmx/x86_ops.h +3 -0
@@ -147,6 +147,9 @@ 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);
 
+void tdx_apicv_post_state_restore(struct kvm_vcpu *vcpu);
+int tdx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector);
+
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
  int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
 

Applied the first hunk, the second should be squashed somewhere else.

Paolo

maintainer
#299 lore raw

Re: [RFC PATCH v5 102/104] KVM: TDX: Add methods to ignore accesses to CPU state

In reply to [email protected]
Quoted 7 lines · On 3/4/22 20:49, [email protected] wrote:

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.

For most of these, it would be interesting to see which paths actually can be hit. For SEV, it's all cut out by

        if (vcpu->arch.guest_state_protected)
                return 0;

in functions such as __set_sregs_common. Together with the fact that TDX does not get to e.g. handle_set_cr0, this should prevent most such calls from happening. So most of these should be KVM_BUG_ON or WARN_ON, not just returns.

Thanks,

Paolo

Quoted 682 lines
---
  arch/x86/kvm/vmx/main.c    | 465 +++++++++++++++++++++++++++++++++----
  arch/x86/kvm/vmx/tdx.c     |  44 ++++
  arch/x86/kvm/vmx/x86_ops.h |  17 ++
  3 files changed, 483 insertions(+), 43 deletions(-)
arch/x86/kvm/vmx/main.c +422 -43
index de9b4a270f20..0515998f7fa5 100644
@@ -228,6 +228,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)
  {
  	if (is_td_vcpu(vcpu))
@@ -236,6 +276,31 @@ static void vt_apicv_post_state_restore(struct kvm_vcpu *vcpu)
  	return vmx_apicv_post_state_restore(vcpu);
  }
 
+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))
@@ -272,6 +337,179 @@ static void vt_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
  	kvm_vcpu_deliver_sipi_vector(vcpu, vector);
  }
 
+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 (is_td_vcpu(vcpu))
+		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 (is_td_vcpu(vcpu))
+		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 (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_segment(vcpu, var, seg);
+}
+
+static int vt_get_cpl(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		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 (is_td_vcpu(vcpu))
+		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 (is_td_vcpu(vcpu)) {
+		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 (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_idt(vcpu, dt);
+}
+
+static void vt_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+{
+	if (is_td_vcpu(vcpu)) {
+		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 (is_td_vcpu(vcpu))
+		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)) {
+		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))
@@ -388,6 +626,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)
  {
  	if (is_td_vcpu(vcpu))
@@ -396,6 +643,14 @@ static void vt_inject_irq(struct kvm_vcpu *vcpu)
  	vmx_inject_irq(vcpu);
  }
 
+static void vt_queue_exception(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_queue_exception(vcpu);
+}
+
  static void vt_cancel_injection(struct kvm_vcpu *vcpu)
  {
  	if (is_td_vcpu(vcpu))
@@ -428,6 +683,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 (is_td_vcpu(vcpu))
+		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 (is_td_vcpu(vcpu))
+		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)
  {
@@ -480,29 +859,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,
 
  	.tlb_flush_all = vt_flush_tlb_all,
  	.tlb_flush_current = vt_flush_tlb_current,
@@ -516,10 +895,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,
  	.set_irq = vt_inject_irq,
  	.set_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,
@@ -527,39 +906,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,
  	.apicv_has_pending_interrupt = vt_apicv_has_pending_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,
@@ -567,7 +946,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,
 
  	.pmu_ops = &intel_pmu_ops,
  	.nested_ops = &vmx_nested_ops,
@@ -576,8 +955,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.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,
@@ -587,8 +966,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 +44 -0
index 7bbf6271967b..55a6fd218fc7 100644
@@ -3,6 +3,7 @@
  #include <linux/mmu_context.h>
 
  #include <asm/fpu/xcr.h>
+#include <asm/virtext.h>
  #include <asm/tdx.h>
 
  #include "capabilities.h"
@@ -1717,6 +1718,49 @@ void tdx_enable_smi_window(struct kvm_vcpu *vcpu)
  	vcpu->arch.smi_pending = false;
  }
 
+void tdx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
+{
+	/* Only x2APIC mode is supported for TD. */
+	WARN_ON_ONCE(kvm_get_apic_mode(vcpu) != LAPIC_MODE_X2APIC);
+}
+
+int tdx_get_cpl(struct kvm_vcpu *vcpu)
+{
+	return 0;
+}
+
+void tdx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
+{
+	kvm_register_mark_available(vcpu, reg);
+	switch (reg) {
+	case VCPU_REGS_RSP:
+	case VCPU_REGS_RIP:
+	case VCPU_EXREG_PDPTR:
+	case VCPU_EXREG_CR0:
+	case VCPU_EXREG_CR3:
+	case VCPU_EXREG_CR4:
+		break;
+	default:
+		KVM_BUG_ON(1, vcpu->kvm);
+		break;
+	}
+}
+
+unsigned long tdx_get_rflags(struct kvm_vcpu *vcpu)
+{
+	return 0;
+}
+
+u64 tdx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
+{
+	return 0;
+}
+
+void tdx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
+{
+	memset(var, 0, sizeof(*var));
+}
+
  static int tdx_capabilities(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
  {
  	struct kvm_tdx_capabilities __user *user_caps;
arch/x86/kvm/vmx/x86_ops.h +17 -0
index 19d793609cc4..7cd29b586e43 100644
@@ -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; }
maintainer Reviewed-by on v5 46/104
#159 lore raw

Re: [RFC PATCH v5 046/104] KVM: x86/tdp_mmu: refactor kvm_tdp_mmu_map()

In reply to [email protected]
Quoted 7 lines · On 3/4/22 20:49, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Factor out non-leaf SPTE population logic from kvm_tdp_mmu_map(). MapGPA hypercall needs to populate non-leaf SPTE to record which GPA, private or shared, is allowed in the leaf EPT entry.

and feel free to rebase/resubmit this one, with subject "KVM: x86/tdp_mmu: extract tdp_mmu_populate_nonleaf()".

Paolo

Quoted 85 lines
---
  arch/x86/kvm/mmu/tdp_mmu.c | 48 ++++++++++++++++++++++++--------------
  1 file changed, 30 insertions(+), 18 deletions(-)
arch/x86/kvm/mmu/tdp_mmu.c +30 -18
index b6ec2f112c26..8db262440d5c 100644
@@ -955,6 +955,31 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
  	return ret;
  }
 
+static bool tdp_mmu_populate_nonleaf(
+	struct kvm_vcpu *vcpu, struct tdp_iter *iter, bool account_nx)
+{
+	struct kvm_mmu_page *sp;
+	u64 *child_pt;
+	u64 new_spte;
+
+	WARN_ON(is_shadow_present_pte(iter->old_spte));
+	WARN_ON(is_removed_spte(iter->old_spte));
+
+	sp = alloc_tdp_mmu_page(vcpu, iter->gfn, iter->level - 1);
+	child_pt = sp->spt;
+
+	new_spte = make_nonleaf_spte(child_pt, !shadow_accessed_mask);
+
+	if (!tdp_mmu_set_spte_atomic(vcpu->kvm, iter, new_spte)) {
+		tdp_mmu_free_sp(sp);
+		return false;
+	}
+
+	tdp_mmu_link_page(vcpu->kvm, sp, account_nx);
+	trace_kvm_mmu_get_page(sp, true);
+	return true;
+}
+
  /*
   * Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing
   * page tables and SPTEs to translate the faulting guest physical address.
@@ -963,9 +988,6 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  {
  	struct kvm_mmu *mmu = vcpu->arch.mmu;
  	struct tdp_iter iter;
-	struct kvm_mmu_page *sp;
-	u64 *child_pt;
-	u64 new_spte;
  	int ret;
 
  	kvm_mmu_hugepage_adjust(vcpu, fault);
@@ -1000,6 +1022,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  		}
 
  		if (!is_shadow_present_pte(iter.old_spte)) {
+			bool account_nx;
+
  			/*
  			 * If SPTE has been frozen by another thread, just
  			 * give up and retry, avoiding unnecessary page table
@@ -1008,22 +1032,10 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  			if (is_removed_spte(iter.old_spte))
  				break;
 
-			sp = alloc_tdp_mmu_page(vcpu, iter.gfn, iter.level - 1);
-			child_pt = sp->spt;
-
-			new_spte = make_nonleaf_spte(child_pt,
-						     !shadow_accessed_mask);
-
-			if (tdp_mmu_set_spte_atomic(vcpu->kvm, &iter, new_spte)) {
-				tdp_mmu_link_page(vcpu->kvm, sp,
-						  fault->huge_page_disallowed &&
-						  fault->req_level >= iter.level);
-
-				trace_kvm_mmu_get_page(sp, true);
-			} else {
-				tdp_mmu_free_sp(sp);
+			account_nx = fault->huge_page_disallowed &&
+				fault->req_level >= iter.level;
+			if (!tdp_mmu_populate_nonleaf(vcpu, &iter, account_nx))
  				break;
-			}
  		}
  	}
 
maintainer
#293 lore raw

Re: [RFC PATCH v5 101/104] KVM: TDX: Silently ignore INIT/SIPI

In reply to [email protected]
Quoted 6 lines · On 3/4/22 20:49, [email protected] wrote:
arch/x86/kvm/lapic.c +6 -0
+		if (kvm_init_sipi_unsupported(vcpu->kvm))
+			/*
+			 * TDX doesn't support INIT.  Ignore INIT event.  In the
+			 * case of SIPI, the callback of
+			 * vcpu_deliver_sipi_vector ignores it.
+			 */

arch/x86/kvm/lapic.c int kvm_apic_accept_events(struct kvm_vcpu *vcpu) · line 2937

Quoted 10 lines
arch/x86/kvm/lapic.c +7 -2
  			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
-		else
-			vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
+		else {
+			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;
+		}

Should you check vcpu->arch.guest_state_protected instead of special-casing TDX? KVM_APIC_INIT is not valid for SEV-ES either, if I remember correctly.

Paolo

#68 lore raw

Re: [RFC PATCH v5 023/104] x86/cpu: Add helper functions to allocate/free MKTME keyid

In reply to Isaku Yamahata
Quoted 24 lines · Isaku Yamahata
Quoted 21 lines · Kai Huang
Quoted 5 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

MKTME keyid is assigned to guest TD. The memory controller encrypts guest TD memory with key id. Add helper functions to allocate/free MKTME keyid so that TDX KVM assign keyid.

Using MKTME keyid is wrong, at least not accurate I think. We should use explicitly use "TDX private KeyID", which is clearly documented in the spec:

https://software.intel.com/content/dam/develop/external/us/en/documents-tps/intel-tdx-cpu-architectural-specification.pdf

Also, description of IA32_MKTME_KEYID_PARTITIONING MSR clearly says TDX private KeyIDs span the range (NUM_MKTME_KIDS+1) through (NUM_MKTME_KIDS+NUM_TDX_PRIV_KIDS). So please just use TDX private KeyID here.

Quoted 3 lines

Also export MKTME global keyid that is used to encrypt TDX module and its memory.

Quoted 8 lines
Quoted 1 line

This needs explanation why the global keyID needs to be exported.

How about the followings?

TDX private host key id is assigned to guest TD. The memory controller encrypts guest TD memory with the assigned host key id (HIKD). Add helper functions to allocate/free TDX private host key id so that TDX KVM manage it.

HIKD -> HKID.

You may also want to use KeyID in consistent way (KeyID, keyid, key id, etc). The spec uses KeyID.

Quoted 8 lines

Also export the global TDX private host key id that is used to encrypt TDX module, its memory and some dynamic data (e.g. TDR). When VMM releasing encrypted page to reuse it, the page needs to be flushed with the used host key id. VMM needs the global TDX private host key id to flush such pages TDX module accesses with the global TDX private host key id.

Find to me.

maintainer
#115 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to Kai Huang
Quoted 13 lines · Kai Huang
Quoted 13 lines
Quoted 12 lines

arch/x86/kvm/mmu/paging_tmpl.h static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1091

Quoted 8 lines
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
-		gfn = gpte_to_gfn(gpte);
+		gfn = gpte_to_gfn(vcpu, gpte);
  		pte_access = sp->role.access;
  		pte_access &= FNAME(gpte_access)(gpte);
  		FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);

In commit message you mentioned "Don't support stolen bits for shadow EPT" (you actually mean shadow MMU I suppose), yet there's bunch of code change to shadow MMU.

Quoted 4 lines
Quoted 1 line

It's a bit ugly, but it's uglier to keep two versions of gpte_to_gfn.

gpte_to_gfn() is only used in paging_tmpl.h. Could you elaborate why we need to keep two versions of it?

You're right. Yeah, considering page table walks are not supported when private memory is available, it shouldn't be necessary to change paging_tmpl.h.

Paolo

#114 lore raw

Re: [RFC PATCH v5 033/104] KVM: x86: Add infrastructure for stolen GPA bits

In reply to Paolo Bonzini
Quoted 13 lines
Quoted 12 lines

arch/x86/kvm/mmu/paging_tmpl.h static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1091

Quoted 8 lines
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
-		gfn = gpte_to_gfn(gpte);
+		gfn = gpte_to_gfn(vcpu, gpte);
 		pte_access = sp->role.access;
 		pte_access &= FNAME(gpte_access)(gpte);
 		FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);

In commit message you mentioned "Don't support stolen bits for shadow EPT" (you actually mean shadow MMU I suppose), yet there's bunch of code change to shadow MMU.

Quoted 1 line

It's a bit ugly, but it's uglier to keep two versions of gpte_to_gfn.

gpte_to_gfn() is only used in paging_tmpl.h. Could you elaborate why we need to keep two versions of it?

Signature · 2 lines
Thanks,
-Kai
#146 lore raw

Re: [RFC PATCH v5 042/104] KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis

In reply to [email protected]
Quoted 4 lines · On Fri, 2022-03-04 at 11:48 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Define the EPT Violation #VE control bit, #VE info VMCS fields, and the suppress #VE bit for EPT entries.

It appears only the last one is introduced in this patch.

Quoted 5 lines

TDX will use a different shadow PTE entry value for MMIO from VMX. Add members to kvm_arch and track value for MMIO per-VM. By using per-VM EPT entry value for MMIO, the existing VMX logic is kept working.

Quoted 8 lines

In the case of VMX VM case, the EPT entry for MMIO is non-present PTE (present bit cleared) without backing guest physical address (on EPT violation, KVM seaching backing guest memory and it finds there is no backing guest page.) or the value to trigger EPT misconfiguration. For fast path. Once MMIO is triggered on the EPT entry, the EPT entry is updated for the future MMIO. It allows KVM to understand the memory access is for MMIO without searching backing guest pages.). And then KVM parses guest instruction to figure out address/value/width for MMIO.

What does "For fast path." meaning?

There are also grammar issues in above paragraph.

Quoted 4 lines

In the case of the guest TD, the guest memory is protected so that VMM can't parse guest instruction to trigger EPT violation.

Even VMM can parse guest instruction, it cannot trigger EPT violatoin. Only guest can trigger EPT violation.

Quoted 6 lines

Instead VMM sets
up (Shared) EPT to trigger #VE. When the guest TD issues MMIO, #VE is injected. guest VE handler converts MMIO access into MMIO hypercall to pass address/value/width for MMIO to VMM. (or directly paravirtualize MMIO into hypercall.) Then VMM can handle the MMIO hypercall without parsing guest instruction.

There are couple of grammar issues in above two paragraphs.

Quoted 9 lines

When the guest accesses GPA if "the EPT Violation #VE" control bit is set and EPT SUPPRESS VE bit in EPT entry is cleared, #VE, virtualization exception, is injected into the guest. Because the TDX guest vCPU state and memory are protected, a VMM can't emulate MMIO by the TDX guest on EPT violation by snooping vCPU state and parsing instruction to figure out MMIO address and value. Instead, PV MMIO (MMIO hypercall) is adapted. On EPT violation, CPU injects #VE to guest and the guest converts MMIO instruction into PV MMIO. Or guest directly issues MMIO hypercall.

Isn't this paragraph kinda duplicated with above paragraph?

Quoted 9 lines

The existing VMX code uses zero as an initial value for EPT entry. TDX will enable EPT-violation #VE VM-execution control and requires suppress VE bit cleared in shared EPT entry to inject #VE into the TDX guest. To keep the same behavior for VMX, suppress VE bit needs to be set. Allow to specify an initial value for EPT entry and if TDX is enabled, set initial EPT entry value to suppress VE bit set. EPT-violation #VE VM-execution control will be enabled, and For TDX shared EPT suppress VE bit will be cleared for TDX shared EPT entry.

Isn't the last paragraph talking about the same thing as you did in patch 37 "KVM: x86/mmu: Allow non-zero init value for shadow PTE"? That patch has already done the thing to set a non-zero initial PTE.

Btw, please put this patch and patch 37 together since they are handling similar thing (now there are couple of unrelated patches in the middle).

This patch talks about changing MMIO value/mask from global to per-VM tracking. Please focus on explaining the rational behind this -- i.e. unlike to legacy VMX VM (and AMD legacy VMs), TD guest requires different MMIO value/mask in order to configure MMIO EPT entry to not generate EPT misconfiguration, but instead to inject #VE by setting up a non-present SPTE which causes EPT violation but with "Suppress #VE" bit clear.

Quoted 75 lines
---
 arch/x86/include/asm/kvm_host.h |  3 +++
 arch/x86/include/asm/vmx.h      |  1 +
 arch/x86/kvm/mmu.h              |  6 ++++--
 arch/x86/kvm/mmu/mmu.c          | 19 +++++++++++------
 arch/x86/kvm/mmu/spte.c         | 38 ++++++++++++++++-----------------
 arch/x86/kvm/mmu/spte.h         |  9 ++++----
 arch/x86/kvm/mmu/tdp_mmu.c      |  6 +++---
 arch/x86/kvm/svm/svm.c          |  2 +-
 arch/x86/kvm/vmx/main.c         |  7 ++++--
 arch/x86/kvm/vmx/tdx.c          |  2 +-
 arch/x86/kvm/vmx/tdx.h          |  2 ++
 arch/x86/kvm/vmx/vmx.c          |  8 +++++++
 12 files changed, 63 insertions(+), 40 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index d33d79f2af2d..fcab2337819c 100644
@@ -1069,6 +1069,9 @@ struct kvm_arch {
 	 */
 	spinlock_t mmu_unsync_pages_lock;
 
+	u64 shadow_mmio_value;
+	u64 shadow_mmio_mask;
+
 	struct list_head assigned_dev_head;
 	struct iommu_domain *iommu_domain;
 	bool iommu_noncoherent;
arch/x86/include/asm/vmx.h +1 -0
index 0ffaa3156a4e..88d9b8cc7dde 100644
@@ -498,6 +498,7 @@ enum vmcs_field {
 #define VMX_EPT_IPAT_BIT    			(1ull << 6)
 #define VMX_EPT_ACCESS_BIT			(1ull << 8)
 #define VMX_EPT_DIRTY_BIT			(1ull << 9)
+#define VMX_EPT_SUPPRESS_VE_BIT			(1ull << 63)
 #define VMX_EPT_RWX_MASK                        (VMX_EPT_READABLE_MASK |       \
 						 VMX_EPT_WRITABLE_MASK |       \
 						 VMX_EPT_EXECUTABLE_MASK)
arch/x86/kvm/mmu.h +4 -2
index 650989c37f2e..b49841e4faaa 100644
@@ -64,8 +64,10 @@ static __always_inline u64 rsvd_bits(int s, int e)
 	return ((2ULL << (e - s)) - 1) << s;
 }
 
-void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask);
-void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only);
+void kvm_mmu_set_mmio_spte_mask(struct kvm *kvm, u64 mmio_value, u64 mmio_mask,
+				u64 access_mask);
+void kvm_mmu_set_default_mmio_spte_mask(u64 mask);
+void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only, u64 init_value);
 void kvm_mmu_set_spte_init_value(u64 init_value);
 
 void kvm_init_mmu(struct kvm_vcpu *vcpu);
arch/x86/kvm/mmu/mmu.c +1 -1
index d8c1505155b0..6e9847b1124b 100644
@@ -2336,7 +2336,7 @@ static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
 				return kvm_mmu_prepare_zap_page(kvm, child,
 								invalid_list);
 		}
-	} else if (is_mmio_spte(pte)) {
+	} else if (is_mmio_spte(kvm, pte)) {
 		mmu_spte_clear_no_track(spte);
 	}
 	return 0;

arch/x86/kvm/mmu/mmu.c static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fa · line 3074

Quoted 7 lines
arch/x86/kvm/mmu/mmu.c +3 -1
@@ -3069,9 +3069,12 @@ static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fa
 		/*
 		 * If MMIO caching is disabled, emulate immediately without
 		 * touching the shadow page tables as attempting to install an
-		 * MMIO SPTE will just be an expensive nop.
+		 * MMIO SPTE will just be an expensive nop, but excludes the
+		 * INTEL TD guest due to it also uses shadow_mmio_value = 0
+		 * to emulating MMIO access.

The comment seems is not accurate. If I read correctly, for a TD guest, shadow_mmio_value is initialized to shadow_default_mmio_mask, which isn't always
0. See changes to kvm_mmu_reset_all_pte_masks().

arch/x86/kvm/mmu/mmu.c static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fa · line 3077

Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +2 -1
 		 */
-		if (unlikely(!shadow_mmio_value)) {
+		if (unlikely(!vcpu->kvm->arch.shadow_mmio_value)
+		    && !kvm_gfn_stolen_mask(vcpu->kvm)) {

I don't like using kvm_gfn_stolen_mask() here. Similar to below comment related to is_mmio_spte().

Quoted 92 lines
arch/x86/kvm/mmu/mmu.c +7 -3
 			*ret_val = RET_PF_EMULATE;
 			return true;
 		}
@@ -3209,7 +3212,8 @@ static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 			break;
 
 		sp = sptep_to_sp(sptep);
-		if (!is_last_spte(spte, sp->role.level) || is_mmio_spte(spte))
+		if (!is_last_spte(spte, sp->role.level) ||
+			is_mmio_spte(vcpu->kvm, spte))
 			break;
 
 		/*
@@ -3892,7 +3896,7 @@ static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
 	if (WARN_ON(reserved))
 		return -EINVAL;
 
-	if (is_mmio_spte(spte)) {
+	if (is_mmio_spte(vcpu->kvm, spte)) {
 		gfn_t gfn = get_mmio_spte_gfn(spte);
 		unsigned int access = get_mmio_spte_access(spte);
 
@@ -4294,7 +4298,7 @@ static unsigned long get_cr3(struct kvm_vcpu *vcpu)
 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
 			   unsigned int access)
 {
-	if (unlikely(is_mmio_spte(*sptep))) {
+	if (unlikely(is_mmio_spte(vcpu->kvm, *sptep))) {
 		if (gfn != get_mmio_spte_gfn(*sptep)) {
 			mmu_spte_clear_no_track(sptep);
 			return true;
@@ -5791,6 +5795,9 @@ void kvm_mmu_init_vm(struct kvm *kvm)
 	kvm_page_track_register_notifier(kvm, node);
 
 	kvm->arch.tdp_max_page_level = KVM_MAX_HUGEPAGE_LEVEL;
+	kvm_mmu_set_mmio_spte_mask(kvm, shadow_default_mmio_mask,
+				   shadow_default_mmio_mask,
+				   ACC_WRITE_MASK | ACC_USER_MASK);
 }
 
 void kvm_mmu_uninit_vm(struct kvm *kvm)
arch/x86/kvm/mmu/spte.c +8 -8
index 5071e8332db2..ea83927b9231 100644
@@ -29,8 +29,7 @@ u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
 u64 __read_mostly shadow_user_mask;
 u64 __read_mostly shadow_accessed_mask;
 u64 __read_mostly shadow_dirty_mask;
-u64 __read_mostly shadow_mmio_value;
-u64 __read_mostly shadow_mmio_mask;
+u64 __read_mostly shadow_default_mmio_mask;
 u64 __read_mostly shadow_mmio_access_mask;
 u64 __read_mostly shadow_present_mask;
 u64 __read_mostly shadow_me_mask;
@@ -59,10 +58,11 @@ u64 make_mmio_spte(struct kvm_vcpu *vcpu, u64 gfn, unsigned int access)
 	u64 spte = generation_mmio_spte_mask(gen);
 	u64 gpa = gfn << PAGE_SHIFT;
 
-	WARN_ON_ONCE(!shadow_mmio_value);
+	WARN_ON_ONCE(!vcpu->kvm->arch.shadow_mmio_value &&
+		     !kvm_gfn_stolen_mask(vcpu->kvm));
 
 	access &= shadow_mmio_access_mask;
-	spte |= shadow_mmio_value | access;
+	spte |= vcpu->kvm->arch.shadow_mmio_value | access;
 	spte |= gpa | shadow_nonpresent_or_rsvd_mask;
 	spte |= (gpa & shadow_nonpresent_or_rsvd_mask)
 		<< SHADOW_NONPRESENT_OR_RSVD_MASK_LEN;
@@ -279,7 +279,8 @@ u64 mark_spte_for_access_track(u64 spte)
 	return spte;
 }
 
-void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
+void kvm_mmu_set_mmio_spte_mask(struct kvm *kvm, u64 mmio_value, u64 mmio_mask,
+				u64 access_mask)
 {
 	BUG_ON((u64)(unsigned)access_mask != access_mask);
 	WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
@@ -308,39 +309,32 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 	    WARN_ON(mmio_value && (REMOVED_SPTE & mmio_mask) == mmio_value))
 		mmio_value = 0;
 
-	shadow_mmio_value = mmio_value;
-	shadow_mmio_mask  = mmio_mask;
+	kvm->arch.shadow_mmio_value = mmio_value;
+	kvm->arch.shadow_mmio_mask = mmio_mask;
 	shadow_mmio_access_mask = access_mask;
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
 
-void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only)

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask) · line 326

Quoted 10 lines
arch/x86/kvm/mmu/spte.c +3 -1
+void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only, u64 init_value)
 {
 	shadow_user_mask	= VMX_EPT_READABLE_MASK;
 	shadow_accessed_mask	= has_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull;
 	shadow_dirty_mask	= has_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull;
 	shadow_nx_mask		= 0ull;
 	shadow_x_mask		= VMX_EPT_EXECUTABLE_MASK;
-	shadow_present_mask	= has_exec_only ? 0ull : VMX_EPT_READABLE_MASK;
+	shadow_present_mask	=
+		(has_exec_only ? 0ull : VMX_EPT_READABLE_MASK) | init_value;

This change doesn't seem make any sense. Why should "Suppress #VE" bit be set for a present PTE?

Quoted 23 lines
arch/x86/kvm/mmu/spte.c +0 -8
 	shadow_acc_track_mask	= VMX_EPT_RWX_MASK;
 	shadow_me_mask		= 0ull;
 
 	shadow_host_writable_mask = EPT_SPTE_HOST_WRITABLE;
 	shadow_mmu_writable_mask  = EPT_SPTE_MMU_WRITABLE;
-
-	/*
-	 * EPT Misconfigurations are generated if the value of bits 2:0
-	 * of an EPT paging-structure entry is 110b (write/execute).
-	 */
-	kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE,
-				   VMX_EPT_RWX_MASK, 0);
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_ept_masks);
 
 void kvm_mmu_reset_all_pte_masks(void)
 {
 	u8 low_phys_bits;
-	u64 mask;
 
 	shadow_phys_bits = kvm_get_shadow_phys_bits();
 

arch/x86/kvm/mmu/spte.c void kvm_mmu_reset_all_pte_masks(void) · line 386

Quoted 5 lines
arch/x86/kvm/mmu/spte.c +1 -1
@@ -389,9 +383,13 @@ void kvm_mmu_reset_all_pte_masks(void)
 	 * PTEs and so the reserved PA approach must be disabled.
 	 */
 	if (shadow_phys_bits < 52)
-		mask = BIT_ULL(51) | PT_PRESENT_MASK;
+		shadow_default_mmio_mask = BIT_ULL(51) | PT_PRESENT_MASK;

Hmm... Not related to this patch, but it seems there's a bug here. On a MKTME enabled system (but not TDX) with 52 physical bits, the shadow_phys_bits will be set to < 52 (depending on how many MKTME KeyIDs are configured by BIOS). In this case, bit 51 is set, but actually bit 51 isn't a reserved bit in this case. Instead, it is a MKTME KeyID bit. Therefore, above setting won't cause #PF, but will use a non-zero MKTME keyID to access the physical address.

Paolo/Sean, any comments here?

Quoted 26 lines
arch/x86/kvm/mmu/spte.c +6 -2
 	else
-		mask = 0;
+		shadow_default_mmio_mask = 0;
+}
 
-	kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
+void kvm_mmu_set_default_mmio_spte_mask(u64 mask)
+{
+	shadow_default_mmio_mask = mask;
 }
+EXPORT_SYMBOL_GPL(kvm_mmu_set_default_mmio_spte_mask);
arch/x86/kvm/mmu/spte.h +1 -2
index 8e13a35ab8c9..bde843bce878 100644
@@ -165,8 +165,7 @@ extern u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
 extern u64 __read_mostly shadow_user_mask;
 extern u64 __read_mostly shadow_accessed_mask;
 extern u64 __read_mostly shadow_dirty_mask;
-extern u64 __read_mostly shadow_mmio_value;
-extern u64 __read_mostly shadow_mmio_mask;
+extern u64 __read_mostly shadow_default_mmio_mask;
 extern u64 __read_mostly shadow_mmio_access_mask;
 extern u64 __read_mostly shadow_present_mask;
 extern u64 __read_mostly shadow_me_mask;

arch/x86/kvm/mmu/spte.h extern u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask; · line 234

Quoted 10 lines
arch/x86/kvm/mmu/spte.h +3 -3
@@ -229,10 +228,10 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
  */
 extern u8 __read_mostly shadow_phys_bits;
 
-static inline bool is_mmio_spte(u64 spte)
+static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)
 {
-	return (spte & shadow_mmio_mask) == shadow_mmio_value &&
-	       likely(shadow_mmio_value);
+	return (spte & kvm->arch.shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
+		likely(kvm->arch.shadow_mmio_value || kvm_gfn_stolen_mask(kvm));

I don't like using kvm_gfn_stolen_mask() to check whether SPTE is MMIO. kvm_gfn_stolen_mask() really doesn't imply anything regarding to setting up the value of MMIO SPTE. At least, I guess we can use some is_protected_vm() sort of things since it implies guest memory is protected therefore legacy way handling of MMIO doesn't work (i.e. you cannot parse MMIO instruction).

Quoted 97 lines
arch/x86/kvm/mmu/spte.h +0 -0
 }
 
 static inline bool is_shadow_present_pte(u64 pte)
arch/x86/kvm/mmu/tdp_mmu.c +3 -3
index bc9e3553fba2..ebd0a02620e8 100644
@@ -447,8 +447,8 @@ static void __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
 		 * impact the guest since both the former and current SPTEs
 		 * are nonpresent.
 		 */
-		if (WARN_ON(!is_mmio_spte(old_spte) &&
-			    !is_mmio_spte(new_spte) &&
+		if (WARN_ON(!is_mmio_spte(kvm, old_spte) &&
+			    !is_mmio_spte(kvm, new_spte) &&
 			    !is_removed_spte(new_spte)))
 			pr_err("Unexpected SPTE change! Nonpresent SPTEs\n"
 			       "should not be replaced with another,\n"
@@ -927,7 +927,7 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
 	}
 
 	/* If a MMIO SPTE is installed, the MMIO will need to be emulated. */
-	if (unlikely(is_mmio_spte(new_spte))) {
+	if (unlikely(is_mmio_spte(vcpu->kvm, new_spte))) {
 		trace_mark_mmio_spte(rcu_dereference(iter->sptep), iter->gfn,
 				     new_spte);
 		ret = RET_PF_EMULATE;
arch/x86/kvm/svm/svm.c +1 -1
index 778075b71dc3..c7eec23e9ebe 100644
@@ -4704,7 +4704,7 @@ static __init void svm_adjust_mmio_mask(void)
 	 */
 	mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
 
-	kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
+	kvm_mmu_set_default_mmio_spte_mask(mask);
 }
 
 static __init void svm_set_cpu_caps(void)
arch/x86/kvm/vmx/main.c +5 -2
index 51aaafe6b432..b242a9dc9e29 100644
@@ -23,9 +23,12 @@ static __init int vt_hardware_setup(void)
 
 	tdx_hardware_setup(&vt_x86_ops);
 
-	if (enable_ept)
+	if (enable_ept) {
+		const u64 init_value = enable_tdx ? VMX_EPT_SUPPRESS_VE_BIT : 0ull;
 		kvm_mmu_set_ept_masks(enable_ept_ad_bits,
-				      cpu_has_vmx_ept_execute_only());
+				      cpu_has_vmx_ept_execute_only(), init_value);
+		kvm_mmu_set_spte_init_value(init_value);
+	}
 
 	return 0;
 }
arch/x86/kvm/vmx/tdx.c +1 -1
index f86a257dd71b..c3434b33c452 100644
@@ -11,7 +11,7 @@
 #undef pr_fmt
 #define pr_fmt(fmt) "tdx: " fmt
 
-static bool __read_mostly enable_tdx = true;
+bool __read_mostly enable_tdx = true;
 module_param_named(tdx, enable_tdx, bool, 0644);
 
 #define TDX_MAX_NR_CPUID_CONFIGS					\
arch/x86/kvm/vmx/tdx.h +2 -0
index 4ce7fcab6f64..b32e068c51b4 100644
@@ -6,6 +6,7 @@
 
 #include "tdx_ops.h"
 
+extern bool __read_mostly enable_tdx;
 int tdx_module_setup(void);
 
 struct tdx_td_page {
@@ -166,6 +167,7 @@ static __always_inline u64 td_tdcs_exec_read64(struct kvm_tdx *kvm_tdx, u32 fiel
 }
 
 #else
+#define enable_tdx false
 static inline int tdx_module_setup(void) { return -ENODEV; };
 
 struct kvm_tdx;
arch/x86/kvm/vmx/vmx.c +0 -0
index 07fd892768be..00f88aa25047 100644

arch/x86/kvm/vmx/vmx.c int vmx_vm_init(struct kvm *kvm) · line 7074

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +7 -0
@@ -7065,6 +7065,14 @@ int vmx_vm_init(struct kvm *kvm)
 	if (!ple_gap)
 		kvm->arch.pause_in_guest = true;
 
+	/*
+	 * EPT Misconfigurations can be generated if the value of bits 2:0
+	 * of an EPT paging-structure entry is 110b (write/execute).
+	 */
+	if (enable_ept)
+		kvm_mmu_set_mmio_spte_mask(kvm, VMX_EPT_MISCONFIG_WX_VALUE,
+					   VMX_EPT_MISCONFIG_WX_VALUE, 0);

Should be:

	kvm_mmu_set_mmio_spte_mask(kvm, VMX_EPT_MISCONFIG_WX_VALUE,
				   	VMX_EPT_RWX_MASK, 0);
Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+
 	if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
 		switch (l1tf_mitigation) {
 		case L1TF_MITIGATION_OFF:
maintainer
#91 lore raw

Re: [RFC PATCH v5 027/104] KVM: TDX: initialize VM with TDX specific parameters

In reply to Xiaoyao Li
Quoted 6 lines · Xiaoyao Li
Quoted 4 lines

Indeed, it would be easier to use the existing cpuid data in struct kvm_vcpu, because right now there is no way to ensure that they are consistent.

Why is KVM_SET_CPUID2 not enough?  Are there any modifications done by KVM that affect the measurement?

Then we get the situation that KVM_TDX_INIT_VM must be called after 1 vcpu is created. It seems illogical that it has chance to fail the VM scope initialization after 1 vcpu is successfully created.

I see. Yeah, it makes sense to have the CPUID in KVM_TDX_INIT_VM then.

Paolo

maintainer Reviewed-by on v5 78/104
#230 lore raw

Re: [RFC PATCH v5 078/104] KVM: TDX: Implement interrupt injection

In reply to [email protected]

Please do not duplicate code, for example:

arch/x86/kvm/vmx/tdx.c static void tdx_handle_changed_private_spte( · line 1028

Quoted 8 lines · On 3/4/22 20:49, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +7 -0
+void tdx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+	pi_clear_on(&tdx->pi_desc);
+	memset(tdx->pi_desc.pir, 0, sizeof(tdx->pi_desc.pir));
+}

This is the same as vmx_apicv_post_state_restore. Please write this like:

void vt_apicv_post_state_restore(struct kvm_vcpu *vcpu)

{
	struct pi_desc *pi = vcpu_to_pi_desc(vcpu);
	pi_clear_on(pi);
	memset(pi->pir, 0, sizeof(pi->pir));
}

Otherwise,

Paolo

maintainer Reviewed-by on v5 79/104
#232 lore raw

Re: [RFC PATCH v5 079/104] KVM: TDX: Implements vcpu request_immediate_exit

In reply to [email protected]
Quoted 31 lines · On 3/4/22 20:49, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Now we are able to inject interrupts into TDX vcpu, it's ready to block TDX vcpu. Wire up kvm x86 methods for blocking/unblocking vcpu for TDX. To unblock on pending events, request immediate exit methods is also needed.

---
  arch/x86/kvm/vmx/main.c | 10 +++++++++-
  1 file changed, 9 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/main.c +8 -0
index a0bcc4dca678..404a260796e4 100644
@@ -280,6 +280,14 @@ static void vt_enable_irq_window(struct kvm_vcpu *vcpu)
  	vmx_enable_irq_window(vcpu);
  }
 
+static void vt_request_immediate_exit(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return __kvm_request_immediate_exit(vcpu);
+
+	vmx_request_immediate_exit(vcpu);
+}
+
  static int vt_mem_enc_op(struct kvm *kvm, void __user *argp)
  {
  	if (!is_td(kvm))

arch/x86/kvm/vmx/main.c struct kvm_x86_ops vt_x86_ops __initdata = { · line 416

Quoted 8 lines
arch/x86/kvm/vmx/main.c +1 -1
@@ -402,7 +410,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.check_intercept = vmx_check_intercept,
  	.handle_exit_irqoff = vmx_handle_exit_irqoff,
 
-	.request_immediate_exit = vmx_request_immediate_exit,
+	.request_immediate_exit = vt_request_immediate_exit,
 
  	.sched_in = vt_sched_in,
 
maintainer Reviewed-by on v5 81/104
#236 lore raw

Re: [RFC PATCH v5 081/104] KVM: VMX: Modify NMI and INTR handlers to take intr_info as function argument

In reply to [email protected]
Quoted 66 lines · On 3/4/22 20:49, [email protected] wrote:

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 +6 -7
index 4bd1e61b8d45..008400927144 100644
@@ -6442,28 +6442,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;
 
@@ -6482,9 +6481,9 @@ void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
  		return;

arch/x86/kvm/vmx/vmx.c void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu) · line 6489

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +2 -2
 
  	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));
  }
 
  /*
maintainer Reviewed-by on v5 80/104
#234 lore raw

Re: [RFC PATCH v5 080/104] KVM: TDX: Implement methods to inject NMI

In reply to [email protected]
Quoted 128 lines · On 3/4/22 20:49, [email protected] wrote:

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
index 404a260796e4..aa84c13f8ee1 100644
@@ -216,6 +216,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)
  {
@@ -366,14 +418,14 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.get_interrupt_shadow = vt_get_interrupt_shadow,
  	.patch_hypercall = vmx_patch_hypercall,
  	.set_irq = vt_inject_irq,
-	.set_nmi = vmx_inject_nmi,
+	.set_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
index bdc658ca9e4f..273898de9f7a 100644
@@ -763,6 +763,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 +1 -0
index c3768a20347f..31be5e8a1d5c 100644
@@ -150,6 +150,7 @@ void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu);
  void tdx_apicv_post_state_restore(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);

arch/x86/kvm/vmx/x86_ops.h static inline void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu) {} · line 187

Quoted 7 lines
arch/x86/kvm/vmx/x86_ops.h +1 -0
@@ -180,6 +181,7 @@ static inline void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu) {}
  static inline void tdx_apicv_post_state_restore(struct kvm_vcpu *vcpu) {}
  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 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; }
#90 lore raw

Re: [RFC PATCH v5 027/104] KVM: TDX: initialize VM with TDX specific parameters

In reply to Paolo Bonzini
Quoted 9 lines · Paolo Bonzini
Quoted 8 lines · Kai Huang
Quoted 5 lines

+struct kvm_tdx_init_vm {
+    __u32 max_vcpus;
+    __u32 tsc_khz;
+    __u64 attributes;
+    __u64 cpuid;

Is it better to append all CPUIDs directly into this structure, perhaps at end of this structure, to make it more consistent with TD_PARAMS?

Quoted 7 lines
Quoted 3 lines

Also, I think somewhere in commit message or comments we should explain why CPUIDs are passed here (why existing KVM_SET_CUPID2 is not sufficient).

Indeed, it would be easier to use the existing cpuid data in struct kvm_vcpu, because right now there is no way to ensure that they are consistent.

Why is KVM_SET_CPUID2 not enough?  Are there any modifications done by KVM that affect the measurement?

Then we get the situation that KVM_TDX_INIT_VM must be called after 1 vcpu is created. It seems illogical that it has chance to fail the VM scope initialization after 1 vcpu is successfully created.

Quoted 4 lines

Thanks,

Paolo

#83 lore raw

Re: [RFC PATCH v5 026/104] KVM: TDX: x86: Add vm ioctl to get TDX systemwide parameters

In reply to Paolo Bonzini
Quoted 11 lines · Paolo Bonzini
Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:

Implement a VM-scoped subcomment to get system-wide parameters.  Although this is system-wide parameters not per-VM, this subcomand is VM-scoped because
- Device model needs TDX system-wide parameters after creating KVM VM.
- This subcommands requires to initialize TDX module.  For lazy initialization of the TDX module, vm-scope ioctl is better.

Since there was agreement to install the TDX module on load, please place this ioctl on the /dev/kvm file descriptor.

At least for SEV, there were cases where the system-wide parameters are needed outside KVM, so it's better to avoid requiring a VM file descriptor.

I don't have strong preference on KVM-scope ioctl or VM-scope.

Initially, we made it KVM-scope and change it to VM-scope in this version. Yes, it returns the info from TDX module, which doesn't vary per VM. However, what if we want to return different capabilities (software controlled capabilities) per VM? Part of the TDX capabilities serves like get_supported_cpuid, making it KVM wide lacks the flexibility to return differentiated capabilities for different TDs.

Quoted 4 lines

Thanks,

Paolo

#248 lore raw

Re: [RFC PATCH v5 086/104] KVM: TDX: handle ept violation/misconfig exit

In reply to [email protected]
Quoted 19 lines · On Fri, Mar 4, 2022 at 12:23 PM <[email protected]> wrote:

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 | 40 ++++++++++++++++++++++++++++++++++++++--
 1 file changed, 38 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/tdx.c +0 -0
index 6fbe89bcfe1e..2c35dcad077e 100644

arch/x86/kvm/vmx/tdx.c void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode, · line 1084

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +1 -0
@@ -1081,6 +1081,40 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
        __vmx_deliver_posted_interrupt(vcpu, &tdx->pi_desc, vector);
 }
 
+#define TDX_SEPT_PFERR (PFERR_WRITE_MASK | PFERR_USER_MASK)

TDX_SEPT_PFERR is defined using PFERR_.* bitmask but __vmx_handle_ept_violation is accepting an EPT_VIOLATION_.* bitmask. so (PFERR_WRITE_MASK | PFERR_USER_MASK) will get interpreted as (EPT_VIOLATION_ACC_WRITE | EPT_VIOLATION_ACC_INSTR) which will get translated to (PFERR_WRITE_MASK | PFERR_FETCH_MASK). Was that the intention of this code?

Quoted 57 lines
arch/x86/kvm/vmx/tdx.c +37 -3
+
+static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)
+{
+       unsigned long exit_qual;
+
+       if (kvm_is_private_gpa(vcpu->kvm, tdexit_gpa(vcpu)))
+               exit_qual = TDX_SEPT_PFERR;
+       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;
@@ -1097,6 +1131,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 MSMI.
@@ -1378,8 +1416,6 @@ void tdx_flush_tlb(struct kvm_vcpu *vcpu)
                cpu_relax();
 }
 
-#define TDX_SEPT_PFERR (PFERR_WRITE_MASK | PFERR_USER_MASK)
-
 static int tdx_init_mem_region(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 {
        struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
--
Quoted 2 lines

2.25.1

Sagi

#220 lore raw

Re: [RFC PATCH v5 074/104] KVM: x86: Add a switch_db_regs flag to handle TDX's auto-switched behavior

In reply to Paolo Bonzini
Quoted 23 lines · Paolo Bonzini
Quoted 9 lines · On 3/4/22 20:49, [email protected] wrote:
  	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
arch/x86/kvm/vmx/tdx.c +1 -0
+	vcpu->arch.switch_db_regs = KVM_DEBUGREG_AUTO_SWITCH;
  	vcpu->arch.cr0_guest_owned_bits = -1ul;
  	vcpu->arch.cr4_guest_owned_bits = -1ul;
arch/x86/kvm/x86.c +0 -0
index 45e8a02e99bf..89d04cd64cd0 100644

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 10089

Quoted 7 lines
arch/x86/kvm/x86.c +1 -1
@@ -10084,7 +10084,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	if (vcpu->arch.guest_fpu.xfd_err)
  		wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
-	if (unlikely(vcpu->arch.switch_db_regs)) {
+	if (unlikely(vcpu->arch.switch_db_regs & ~KVM_DEBUGREG_AUTO_SWITCH)) {
  		set_debugreg(0, 7);
  		set_debugreg(vcpu->arch.eff_db[0], 0);
  		set_debugreg(vcpu->arch.eff_db[1], 1);

I'm confused. I'm probably missing something obvious, but where does KVM_DEBUGREG_AUTO_SWITCH affect the behavior of KVM? vcpu_enter_guest would still write %db0-%db3 if KVM_DEBUGREG_BP_ENABLED is set, for example.

Quoted 6 lines

Do you mean:

	if (unlikely(vcpu->arch.switch_db_regs) &&
	    !unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH)) {

?

No, you're confused there's a crucial chunk of this patch that's missing. The host restore path was originally

        if (hw_breakpoint_active() &&
            !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCHED))
                hw_breakpoint_restore();

The TDX module context switches the guest _and_ host debug registers. It restores the host DRs because it needs to write _something_ to hide guest state, so it might as well restore the host values. The above was an optmization to avoid rewriting all debug registers.

However, this patch was written before commit f85d40160691 ("KVM: X86: Disable hardware breakpoints unconditionally before kvm_x86->run()"). I suspect that when rebasing to newer KVM, the Intel folks discovered that DR7 isn't getting restored because the GUEST_DR7 in the SEAM VMCS will hold the zero'd value.

But rather than completely drop the flag, KVM can still avoid writing everything except DR7, i.e.

	if (hw_breakpoint_active()) {
		if (!(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))
			hw_breakpoint_restore();
		else
			set_debugreg(__this_cpu_read(cpu_dr7), 7);
	}

with a comment explaining that DR7 always needs to be restored because it's preemptively cleared to play nice with the non-instrumentable sections.

#157 lore raw

Re: [RFC PATCH v5 045/104] KVM: x86/tdp_mmu: make REMOVED_SPTE include shadow_initial value

In reply to [email protected]
Quoted 10 lines · On Fri, 2022-03-04 at 11:49 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDP MMU uses REMOVED_SPTE = 0x5a0ULL as special constant to indicate the intermediate value to indicate one thread is operating on it and the value should be semi-arbitrary value. For TDX (more correctly to use #VE), the value should include suppress #VE value which is shadow_init_value.

Define SHADOW_REMOVED_SPTE as shadow_init_value | REMOVED_SPTE, and replace REMOVED_SPTE with SHADOW_REMOVED_SPTE to use suppress #VE bit properly for TDX.

Like we discussed, this patch should be merged with patch "KVM: x86/mmu: Allow non-zero init value for shadow PTE".

Signature · 2 lines
Thanks,
-Kai
#155 lore raw

Re: [RFC PATCH v5 045/104] KVM: x86/tdp_mmu: make REMOVED_SPTE include shadow_initial value

In reply to Paolo Bonzini
Quoted 14 lines · Paolo Bonzini

arch/x86/kvm/mmu/spte.h extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask; · line 217

Quoted 10 lines · On 3/4/22 20:49, [email protected] wrote:
arch/x86/kvm/mmu/spte.h +7 -0
@@ -207,9 +209,17 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  /* Removed SPTEs must not be misconstrued as shadow present PTEs. */
  static_assert(!(REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
+/*
+ * See above comment around REMOVED_SPTE.  SHADOW_REMOVED_SPTE is the actual
+ * intermediate value set to the removed SPET.  When TDX is enabled, it sets
+ * the "suppress #VE" bit, otherwise it's REMOVED_SPTE.
+ */
+extern u64 __read_mostly shadow_init_value;
+#define SHADOW_REMOVED_SPTE	(shadow_init_value | REMOVED_SPTE)

Please rename the existing REMOVED_SPTE to REMOVED_SPTE_MASK, and call this simply REMOVED_SPTE. This also makes the patch smaller.

Can we name it either __REMOVE_SPTE or REMOVED_SPTE_VAL? It's most definitely not a mask, it's a full value, e.g. spte |= REMOVED_SPTE_MASK is completely wrong.

Other than that, 100% agree with avoiding churn.

#162 lore raw

Re: [RFC PATCH v5 047/104] KVM: x86/mmu: add a private pointer to struct kvm_mmu_page

In reply to [email protected]
Quoted 40 lines · On Fri, 2022-03-04 at 11:49 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a private pointer to kvm_mmu_page for private EPT.

To resolve KVM page fault on private GPA, it will allocate additional page for Secure EPT in addition to private EPT. Add memory allocator for it and topup its memory allocator before resolving KVM page fault similar to shared EPT page. Allocation of those memory will be done for TDP MMU by alloc_tdp_mmu_page(). Freeing those memory will be done for TDP MMU on behalf of kvm_tdp_mmu_zap_all() called by kvm_mmu_zap_all(). Private EPT page needs to carry one more page used for Secure EPT in addition to the private EPT page. Add private pointer to struct kvm_mmu_page for that purpose and Add helper functions to allocate/free a page for Secure EPT. Also add helper functions to check if a given kvm_mmu_page is private.

---
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/kvm/mmu/mmu.c          |  9 ++++
 arch/x86/kvm/mmu/mmu_internal.h | 84 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu/tdp_mmu.c      |  3 ++
 4 files changed, 97 insertions(+)
arch/x86/include/asm/kvm_host.h +1 -0
index fcab2337819c..0c8cc7d73371 100644
@@ -689,6 +689,7 @@ struct kvm_vcpu_arch {
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_gfn_array_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	struct kvm_mmu_memory_cache mmu_private_sp_cache;
 
 	/*
 	 * QEMU userspace and the guest each have their own FPU state.
arch/x86/kvm/mmu/mmu.c +0 -0
index 6e9847b1124b..8def8b97978f 100644

arch/x86/kvm/mmu/mmu.c static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu) · line 761

Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +1 -0
@@ -758,6 +758,13 @@ static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
 	struct kvm_mmu_memory_cache *mc = &vcpu->arch.mmu_shadow_page_cache;
 	int start, end, i, r;
 
+	if (kvm_gfn_stolen_mask(vcpu->kvm)) {

Please get rid of kvm_gfn_stolen_mask().

Quoted 9 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_private_sp_cache,
+					       PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
+	}
+
 	if (shadow_init_value)
 		start = kvm_mmu_memory_cache_nr_free_objects(mc);
 
#168 lore raw

Re: [RFC PATCH v5 048/104] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to [email protected]
Quoted 3 lines · On Fri, 2022-03-04 at 11:49 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Use private EPT to mirror Secure EPT, and On the change of the private EPT

"on the change".

Quoted 18 lines

entry, invoke kvm_x86_ops hook in __handle_changed_spte() to propagate the change to Secure EPT.

On EPT violation, determine which EPT to use, private or shared, based on faulted GPA.  When allocating an EPT page, record it (private or shared) in the page role. The private is passed down to the function as an argument as necessary. When the private EPT entry is changed, call the hook.

When zapping EPT, the EPT entry is frozen with the special EPT value that clears the present bit. After the TLB shootdown, the entry is set to the eventual value. On populating the EPT entry, atomically set the entry.

For TDX, TDX SEAMCALL to update Secure EPT in addition to direct access to the private EPT entry. For the zapping case, freeing the EPT entry works. It can call TDX SEAMCALL in addition to TLB shootdown. For populating the private EPT entry, there can be a race condition without further protection

Quoted 4 lines

vcpu 1: populating 2M private EPT entry
vcpu 2: populating 4K private EPT entry
vcpu 2: TDX SEAMCALL to update 4K secure EPT => error vcpu 1: TDX SEAMCALL to update 4M secure EPT

2M secure EPT

Quoted 7 lines

To avoid the race, the frozen EPT entry is utilized. Instead of atomic update of the private EPT entry, freeze the entry, call the hook that invokes TDX SEAMCALL, set the entry to the final value (unfreeze).

Support 4K page only at this stage. 2M page support can be done in future patches.

Btw, I'd like to see this as a patch to handle schematic of private mapping in MMU code, and put this patch close to other infrastructure patches such as "stolen GPA infrastructure" and "private_sp", so people can get a clear view on what does the schematic of "private mapping" meaning and how to handle it before jumping to TDX details.

In this patch, you have a "mirrored private page table", this is an important concept and please explain it in commit message. Only with this, your above race condition case makes sense.

Also, you mentioned you will record private or shared in page role. It seems I don't see it. Anyway, you also have SPTE_PRIVATE_PROHIBIT. It's not entirely clearly to me why you need it, or what's advantage between using page.role vs it. Please put those patches together so we can have a clear understanding on your decisions.

IMHO, in general please reorganize the MMU related patches into below way:

1) Patches to introduce schematic of private mapping, and how to handle. You can use TDX as background to explain, but IMHO please use common name such as "private page table" instead of "Secure EPT". Those patches can include:
- concept of protected VM, private/shared mapping (current "GPA stolen bits infrastructure" patch).
- shadow_nonpresent_mask to support setting "Suppress #VE" bit.
- per-VM MMIO value/mask
- 'kvm_mmu_page->private_sp'
- mirrored private page table (this patch).
- SPTE_PRIVATE_PROHIBIT (vs role.private, etc)
- Anything else?

2) After you clearly explain the schematic of private mapping, you can declare some features cannot work with private mapping, such as log-dirty, fast page fault, so that you can disable them in separate patches

3) TDX specific handling.

Order of 2) and 3) doesn't matter, of course.

And when introduce a patch, please make sure it doesn't break existing things, even logically. While I understand we want to split out independent small logic as small patches (as preparation to support main patches), please don't break anything in one patch.

My 2cents above.

Quoted 718 lines
---
 arch/x86/include/asm/kvm-x86-ops.h |   2 +
 arch/x86/include/asm/kvm_host.h    |   8 +
 arch/x86/kvm/mmu/mmu.c             |  31 +++-
 arch/x86/kvm/mmu/tdp_iter.h        |   2 +-
 arch/x86/kvm/mmu/tdp_mmu.c         | 226 +++++++++++++++++++++++------
 arch/x86/kvm/mmu/tdp_mmu.h         |  13 +-
 virt/kvm/kvm_main.c                |   1 +
 7 files changed, 232 insertions(+), 51 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index ef48dcc98cfc..7e27b73d839f 100644
@@ -91,6 +91,8 @@ KVM_X86_OP(set_tss_addr)
 KVM_X86_OP(set_identity_map_addr)
 KVM_X86_OP(get_mt_mask)
 KVM_X86_OP(load_mmu_pgd)
+KVM_X86_OP(free_private_sp)
+KVM_X86_OP(handle_changed_private_spte)
 KVM_X86_OP_NULL(has_wbinvd_exit)
 KVM_X86_OP(get_l2_tsc_offset)
 KVM_X86_OP(get_l2_tsc_multiplier)
arch/x86/include/asm/kvm_host.h +8 -0
index 0c8cc7d73371..8406f8b5ab74 100644
@@ -433,6 +433,7 @@ struct kvm_mmu {
 			 struct kvm_mmu_page *sp);
 	void (*invlpg)(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root_hpa);
 	hpa_t root_hpa;
+	hpa_t private_root_hpa;
 	gpa_t root_pgd;
 	union kvm_mmu_role mmu_role;
 	u8 root_level;
@@ -1433,6 +1434,13 @@ struct kvm_x86_ops {
 	void (*load_mmu_pgd)(struct kvm_vcpu *vcpu, hpa_t root_hpa,
 			     int root_level);
 
+	int (*free_private_sp)(struct kvm *kvm, gfn_t gfn, enum pg_level level,
+			       void *private_sp);
+	void (*handle_changed_private_spte)(
+		struct kvm *kvm, gfn_t gfn, enum pg_level level,
+		kvm_pfn_t old_pfn, bool was_present, bool was_leaf,
+		kvm_pfn_t new_pfn, bool is_present, bool is_leaf, void *sept_page);
+
 	bool (*has_wbinvd_exit)(void);
 
 	u64 (*get_l2_tsc_offset)(struct kvm_vcpu *vcpu);
arch/x86/kvm/mmu/mmu.c +29 -2
index 8def8b97978f..0ec9548ff4dd 100644
@@ -3422,6 +3422,7 @@ static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
 {
 	struct kvm_mmu *mmu = vcpu->arch.mmu;
 	u8 shadow_root_level = mmu->shadow_root_level;
+	gfn_t gfn_stolen = kvm_gfn_stolen_mask(vcpu->kvm);
 	hpa_t root;
 	unsigned i;
 	int r;
@@ -3432,7 +3433,11 @@ static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
 		goto out_unlock;
 
 	if (is_tdp_mmu_enabled(vcpu->kvm)) {
-		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
+		if (gfn_stolen && !VALID_PAGE(mmu->private_root_hpa)) {
+			root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu, true);
+			mmu->private_root_hpa = root;
+		}
+		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu, false);
 		mmu->root_hpa = root;
 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
@@ -5596,6 +5601,7 @@ static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
 	int i;
 
 	mmu->root_hpa = INVALID_PAGE;
+	mmu->private_root_hpa = INVALID_PAGE;
 	mmu->root_pgd = 0;
 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
@@ -5772,6 +5778,10 @@ static void kvm_mmu_zap_all_fast(struct kvm *kvm)
 
 	write_unlock(&kvm->mmu_lock);
 
+	/*
+	 * For now private root is never invalidate during VM is running,
+	 * so this can only happen for shared roots.
+	 */
 	if (is_tdp_mmu_enabled(kvm)) {
 		read_lock(&kvm->mmu_lock);
 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
@@ -5871,7 +5881,8 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
 	if (is_tdp_mmu_enabled(kvm)) {
 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
 			flush = kvm_tdp_mmu_zap_gfn_range(kvm, i, gfn_start,
-							  gfn_end, flush);
+							  gfn_end, flush,
+							  false);
 	}
 
 	if (flush)
@@ -5904,6 +5915,11 @@ void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
 		write_unlock(&kvm->mmu_lock);
 	}
 
+	/*
+	 * For now this can only happen for non-TD VM, because TD private
+	 * mapping doesn't support write protection.  kvm_tdp_mmu_wrprot_slot()
+	 * will give a WARN() if it hits for TD.
+	 */
 	if (is_tdp_mmu_enabled(kvm)) {
 		read_lock(&kvm->mmu_lock);
 		flush |= kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
@@ -5952,6 +5968,9 @@ static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
 		sp = sptep_to_sp(sptep);
 		pfn = spte_to_pfn(*sptep);
 
+		/* Private page dirty logging is not supported. */
+		KVM_BUG_ON(is_private_spte(sptep), kvm);
+
 		/*
 		 * We cannot do huge page mapping for indirect shadow pages,
 		 * which are found on the last rmap (level = 1) when not using
@@ -5992,6 +6011,11 @@ void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
 		write_unlock(&kvm->mmu_lock);
 	}
 
+	/*
+	 * This should only be reachable in case of log-dirty, wihch TD private
+	 * mapping doesn't support so far.  kvm_tdp_mmu_zap_collapsible_sptes()
+	 * internally gives a WARN() when it hits.
+	 */
 	if (is_tdp_mmu_enabled(kvm)) {
 		read_lock(&kvm->mmu_lock);
 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
@@ -6266,6 +6290,9 @@ int kvm_mmu_module_init(void)
 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_unload(vcpu);
+	if (is_tdp_mmu_enabled(vcpu->kvm))
+		mmu_free_root_page(vcpu->kvm, &vcpu->arch.mmu->private_root_hpa,
+				NULL);
 	free_mmu_pages(&vcpu->arch.root_mmu);
 	free_mmu_pages(&vcpu->arch.guest_mmu);
 	mmu_free_memory_caches(vcpu);
arch/x86/kvm/mmu/tdp_iter.h +1 -1
index e19cabbcb65c..ad22d5b691c5 100644
@@ -28,7 +28,7 @@ struct tdp_iter {
 	tdp_ptep_t pt_path[PT64_ROOT_MAX_LEVEL];
 	/* A pointer to the current SPTE */
 	tdp_ptep_t sptep;
-	/* The lowest GFN mapped by the current SPTE */
+	/* The lowest GFN (stolen bits included) mapped by the current SPTE */
 	gfn_t gfn;
 	/* The level of the root page given to the iterator */
 	int root_level;
arch/x86/kvm/mmu/tdp_mmu.c +183 -43
index a68f3a22836b..acba2590b51e 100644
@@ -53,6 +53,11 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
 	rcu_barrier();
 }
 
+static gfn_t tdp_iter_gfn_unalias(struct kvm *kvm, struct tdp_iter *iter)
+{
+	return kvm_gfn_unalias(kvm, iter->gfn);
+}
+
 static bool zap_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
 			  gfn_t start, gfn_t end, bool can_yield, bool flush,
 			  bool shared);
@@ -175,10 +180,13 @@ static union kvm_mmu_page_role page_role_for_level(struct kvm_vcpu *vcpu,
 }
 
 static struct kvm_mmu_page *alloc_tdp_mmu_page(struct kvm_vcpu *vcpu, gfn_t gfn,
-					       int level)
+					       int level, bool private)
 {
 	struct kvm_mmu_page *sp;
 
+	WARN_ON(level != vcpu->arch.mmu->shadow_root_level &&
+		kvm_is_private_gfn(vcpu->kvm, gfn) != private);
+	WARN_ON(level == vcpu->arch.mmu->shadow_root_level && gfn != 0);
 	sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
 	sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
@@ -186,14 +194,19 @@ static struct kvm_mmu_page *alloc_tdp_mmu_page(struct kvm_vcpu *vcpu, gfn_t gfn,
 	sp->role.word = page_role_for_level(vcpu, level).word;
 	sp->gfn = gfn;
 	sp->tdp_mmu_page = true;
-	kvm_mmu_init_private_sp(sp);
+
+	if (private)
+		kvm_mmu_alloc_private_sp(vcpu, sp);
+	else
+		kvm_mmu_init_private_sp(sp);
 
 	trace_kvm_mmu_get_page(sp, true);
 
 	return sp;
 }
 
-hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu)
+static struct kvm_mmu_page *kvm_tdp_mmu_get_vcpu_root(struct kvm_vcpu *vcpu,
+						      bool private)
 {
 	union kvm_mmu_page_role role;
 	struct kvm *kvm = vcpu->kvm;
@@ -206,11 +219,13 @@ hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu)
 	/* Check for an existing root before allocating a new one. */
 	for_each_tdp_mmu_root(kvm, root, kvm_mmu_role_as_id(role)) {
 		if (root->role.word == role.word &&
+		    is_private_sp(root) == private &&
 		    kvm_tdp_mmu_get_root(kvm, root))
 			goto out;
 	}
 
-	root = alloc_tdp_mmu_page(vcpu, 0, vcpu->arch.mmu->shadow_root_level);
+	root = alloc_tdp_mmu_page(vcpu, 0, vcpu->arch.mmu->shadow_root_level,
+			private);
 	refcount_set(&root->tdp_mmu_root_count, 1);
 
 	spin_lock(&kvm->arch.tdp_mmu_pages_lock);
@@ -218,12 +233,17 @@ hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu)
 	spin_unlock(&kvm->arch.tdp_mmu_pages_lock);
 
 out:
-	return __pa(root->spt);
+	return root;
+}
+
+hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu, bool private)
+{
+	return __pa(kvm_tdp_mmu_get_vcpu_root(vcpu, private)->spt);
 }
 
 static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
-				u64 old_spte, u64 new_spte, int level,
-				bool shared);
+				bool private_spte, u64 old_spte,
+				u64 new_spte, int level, bool shared);
 
 static void handle_changed_spte_acc_track(u64 old_spte, u64 new_spte, int level)
 {
@@ -321,6 +341,7 @@ static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
 	int level = sp->role.level;
 	gfn_t base_gfn = sp->gfn;
 	int i;
+	bool private_sp = is_private_sp(sp);
 
 	trace_kvm_mmu_prepare_zap_page(sp);
 
@@ -370,7 +391,7 @@ static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
 			 */
 			WRITE_ONCE(*sptep, SHADOW_REMOVED_SPTE);
 		}
-		handle_changed_spte(kvm, kvm_mmu_page_as_id(sp), gfn,
+		handle_changed_spte(kvm, kvm_mmu_page_as_id(sp), gfn, private_sp,
 				    old_child_spte, SHADOW_REMOVED_SPTE, level,
 				    shared);
 	}
@@ -378,6 +399,17 @@ static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
 	kvm_flush_remote_tlbs_with_address(kvm, base_gfn,
 					   KVM_PAGES_PER_HPAGE(level + 1));
 
+	if (private_sp &&
+		WARN_ON(static_call(kvm_x86_free_private_sp)(
+				kvm, sp->gfn, sp->role.level,
+				kvm_mmu_private_sp(sp)))) {
+		/*
+		 * Failed to unlink Secure EPT page and there is nothing to do
+		 * further.  Intentionally leak the page to prevent the kernel
+		 * from accessing the encrypted page.
+		 */
+		kvm_mmu_init_private_sp(sp);
+	}
 	call_rcu(&sp->rcu_head, tdp_mmu_free_sp_rcu_callback);
 }
 
@@ -386,6 +418,7 @@ static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
  * @kvm: kvm instance
  * @as_id: the address space of the paging structure the SPTE was a part of
  * @gfn: the base GFN that was mapped by the SPTE
+ * @private_spte: the SPTE is private or not
  * @old_spte: The value of the SPTE before the change
  * @new_spte: The value of the SPTE after the change
  * @level: the level of the PT the SPTE is part of in the paging structure
@@ -397,14 +430,16 @@ static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
  * This function must be called for all TDP SPTE modifications.
  */
 static void __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
-				  u64 old_spte, u64 new_spte, int level,
-				  bool shared)
+				  bool private_spte, u64 old_spte,
+				  u64 new_spte, int level, bool shared)
 {
 	bool was_present = is_shadow_present_pte(old_spte);
 	bool is_present = is_shadow_present_pte(new_spte);
 	bool was_leaf = was_present && is_last_spte(old_spte, level);
 	bool is_leaf = is_present && is_last_spte(new_spte, level);
-	bool pfn_changed = spte_to_pfn(old_spte) != spte_to_pfn(new_spte);
+	kvm_pfn_t old_pfn = spte_to_pfn(old_spte);
+	kvm_pfn_t new_pfn = spte_to_pfn(new_spte);
+	bool pfn_changed = old_pfn != new_pfn;
 
 	WARN_ON(level > PT64_ROOT_MAX_LEVEL);
 	WARN_ON(level < PG_LEVEL_4K);
@@ -468,23 +503,49 @@ static void __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
 
 	if (was_leaf && is_dirty_spte(old_spte) &&
 	    (!is_present || !is_dirty_spte(new_spte) || pfn_changed))
-		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
+		kvm_set_pfn_dirty(old_pfn);
+
+	/*
+	 * Special handling for the private mapping.  We are either
+	 * setting up new mapping at middle level page table, or leaf,
+	 * or tearing down existing mapping.
+	 */
+	if (private_spte) {
+		void *sept_page = NULL;
+
+		if (is_present && !is_leaf) {
+			struct kvm_mmu_page *sp = to_shadow_page(pfn_to_hpa(new_pfn));
+
+			sept_page = kvm_mmu_private_sp(sp);
+			WARN_ON(!sept_page);
+			WARN_ON(sp->role.level + 1 != level);
+			WARN_ON(sp->gfn != gfn);
+		}
+
+		static_call(kvm_x86_handle_changed_private_spte)(
+			kvm, gfn, level,
+			old_pfn, was_present, was_leaf,
+			new_pfn, is_present, is_leaf, sept_page);
+	}
 
 	/*
 	 * Recursively handle child PTs if the change removed a subtree from
 	 * the paging structure.
 	 */
-	if (was_present && !was_leaf && (pfn_changed || !is_present))
+	if (was_present && !was_leaf && (pfn_changed || !is_present)) {
+		WARN_ON(private_spte !=
+			is_private_spte(spte_to_child_pt(old_spte, level)));
 		handle_removed_tdp_mmu_page(kvm,
 				spte_to_child_pt(old_spte, level), shared);
+	}
 }
 
 static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
-				u64 old_spte, u64 new_spte, int level,
-				bool shared)
+				bool private_spte, u64 old_spte, u64 new_spte,
+				int level, bool shared)
 {
-	__handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, level,
-			      shared);
+	__handle_changed_spte(kvm, as_id, gfn, private_spte,
+			old_spte, new_spte, level, shared);
 	handle_changed_spte_acc_track(old_spte, new_spte, level);
 	handle_changed_spte_dirty_log(kvm, as_id, gfn, old_spte,
 				      new_spte, level);
@@ -505,6 +566,10 @@ static inline bool tdp_mmu_set_spte_atomic(struct kvm *kvm,
 					   struct tdp_iter *iter,
 					   u64 new_spte)
 {
+	bool freeze_spte = is_private_spte(iter->sptep) &&
+		!is_removed_spte(new_spte);
+	u64 tmp_spte = freeze_spte ? SHADOW_REMOVED_SPTE : new_spte;
+
 	WARN_ON_ONCE(iter->yielded);
 
 	lockdep_assert_held_read(&kvm->mmu_lock);
@@ -521,13 +586,16 @@ static inline bool tdp_mmu_set_spte_atomic(struct kvm *kvm,
 	 * does not hold the mmu_lock.
 	 */
 	if (cmpxchg64(rcu_dereference(iter->sptep), iter->old_spte,
-		      new_spte) != iter->old_spte)
+		      tmp_spte) != iter->old_spte)
 		return false;
 
-	__handle_changed_spte(kvm, iter->as_id, iter->gfn, iter->old_spte,
-			      new_spte, iter->level, true);
+	__handle_changed_spte(kvm, iter->as_id, iter->gfn, is_private_spte(iter->sptep),
+			      iter->old_spte, new_spte, iter->level, true);
 	handle_changed_spte_acc_track(iter->old_spte, new_spte, iter->level);
 
+	if (freeze_spte)
+		WRITE_ONCE(*rcu_dereference(iter->sptep), new_spte);
+
 	return true;
 }
 
@@ -603,8 +671,8 @@ static inline void __tdp_mmu_set_spte(struct kvm *kvm, struct tdp_iter *iter,
 
 	WRITE_ONCE(*rcu_dereference(iter->sptep), new_spte);
 
-	__handle_changed_spte(kvm, iter->as_id, iter->gfn, iter->old_spte,
-			      new_spte, iter->level, false);
+	__handle_changed_spte(kvm, iter->as_id, iter->gfn, is_private_spte(iter->sptep),
+			      iter->old_spte, new_spte, iter->level, false);
 	if (record_acc_track)
 		handle_changed_spte_acc_track(iter->old_spte, new_spte,
 					      iter->level);
@@ -644,9 +712,10 @@ static inline void tdp_mmu_set_spte_no_dirty_log(struct kvm *kvm,
 			continue;					\
 		else
 
-#define tdp_mmu_for_each_pte(_iter, _mmu, _start, _end)		\
-	for_each_tdp_pte(_iter, __va(_mmu->root_hpa),		\
-			 _mmu->shadow_root_level, _start, _end)
+#define tdp_mmu_for_each_pte(_iter, _mmu, _private, _start, _end)		\
+	for_each_tdp_pte(_iter,							\
+		__va((_private) ? _mmu->private_root_hpa : _mmu->root_hpa),	\
+		_mmu->shadow_root_level, _start, _end)
 
 /*
  * Yield if the MMU lock is contended or this thread needs to return control
@@ -731,6 +800,18 @@ static bool zap_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
 	 */
 	end = min(end, max_gfn_host);
 
+	/*
+	 * Extend [start, end) to include GFN shared bit when TDX is enabled,
+	 * and for shared mapping range.
+	 */
+	if (is_private_sp(root)) {
+		start = kvm_gfn_private(kvm, start);
+		end = kvm_gfn_private(kvm, end);
+	} else {
+		start = kvm_gfn_shared(kvm, start);
+		end = kvm_gfn_shared(kvm, end);
+	}
+
 	kvm_lockdep_assert_mmu_lock_held(kvm, shared);
 
 	rcu_read_lock();
@@ -783,13 +864,18 @@ static bool zap_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
  * MMU lock.
  */
 bool __kvm_tdp_mmu_zap_gfn_range(struct kvm *kvm, int as_id, gfn_t start,
-				 gfn_t end, bool can_yield, bool flush)
+				 gfn_t end, bool can_yield, bool flush,
+				 bool zap_private)
 {
 	struct kvm_mmu_page *root;
 
-	for_each_tdp_mmu_root_yield_safe(kvm, root, as_id, false)
+	for_each_tdp_mmu_root_yield_safe(kvm, root, as_id, false) {
+		/* Skip private page table if not requested */
+		if (!zap_private && is_private_sp(root))
+			continue;
 		flush = zap_gfn_range(kvm, root, start, end, can_yield, flush,
 				      false);
+	}
 
 	return flush;
 }
@@ -800,7 +886,7 @@ void kvm_tdp_mmu_zap_all(struct kvm *kvm)
 	int i;
 
 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
-		flush = kvm_tdp_mmu_zap_gfn_range(kvm, i, 0, -1ull, flush);
+		flush = kvm_tdp_mmu_zap_gfn_range(kvm, i, 0, -1ull, flush, true);
 
 	if (flush)
 		kvm_flush_remote_tlbs(kvm);
@@ -851,6 +937,13 @@ void kvm_tdp_mmu_zap_invalidated_roots(struct kvm *kvm)
 	while (root) {
 		next_root = next_invalidated_root(kvm, root);
 
+		/*
+		 * Private table is only torn down when VM is destroyed.
+		 * It is a bug to zap private table here.
+		 */
+		if (WARN_ON(is_private_sp(root)))
+			goto out;
+
 		rcu_read_unlock();
 
 		flush = zap_gfn_range(kvm, root, 0, -1ull, true, flush, true);
@@ -865,7 +958,7 @@ void kvm_tdp_mmu_zap_invalidated_roots(struct kvm *kvm)
 
 		rcu_read_lock();
 	}
-
+out:
 	rcu_read_unlock();
 
 	if (flush)
@@ -897,9 +990,16 @@ void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm)
 	struct kvm_mmu_page *root;
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
-	list_for_each_entry(root, &kvm->arch.tdp_mmu_roots, link)
+	list_for_each_entry(root, &kvm->arch.tdp_mmu_roots, link) {
+		/*
+		 * Skip private root since private page table
+		 * is only torn down when VM is destroyed.
+		 */
+		if (is_private_sp(root))
+			continue;
 		if (refcount_inc_not_zero(&root->tdp_mmu_root_count))
 			root->role.invalid = true;
+	}
 }
 
 /*
@@ -914,14 +1014,23 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
 	u64 new_spte;
 	int ret = RET_PF_FIXED;
 	bool wrprot = false;
+	unsigned long pte_access = ACC_ALL;
 
 	WARN_ON(sp->role.level != fault->goal_level);
+
+	/* TDX shared GPAs are no executable, enforce this for the SDV. */
+	if (!kvm_is_private_gfn(vcpu->kvm, iter->gfn))
+		pte_access &= ~ACC_EXEC_MASK;
+
 	if (unlikely(!fault->slot))
-		new_spte = make_mmio_spte(vcpu, iter->gfn, ACC_ALL);
+		new_spte = make_mmio_spte(vcpu,
+				tdp_iter_gfn_unalias(vcpu->kvm, iter),
+				pte_access);
 	else
-		wrprot = make_spte(vcpu, sp, fault->slot, ACC_ALL, iter->gfn,
-					 fault->pfn, iter->old_spte, fault->prefetch, true,
-					 fault->map_writable, &new_spte);
+		wrprot = make_spte(vcpu, sp, fault->slot, pte_access,
+				tdp_iter_gfn_unalias(vcpu->kvm, iter),
+				fault->pfn, iter->old_spte, fault->prefetch,
+				true, fault->map_writable, &new_spte);
 
 	if (new_spte == iter->old_spte)
 		ret = RET_PF_SPURIOUS;
@@ -959,7 +1068,8 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
 }
 
 static bool tdp_mmu_populate_nonleaf(
-	struct kvm_vcpu *vcpu, struct tdp_iter *iter, bool account_nx)
+	struct kvm_vcpu *vcpu, struct tdp_iter *iter, bool is_private,
+	bool account_nx)
 {
 	struct kvm_mmu_page *sp;
 	u64 *child_pt;
@@ -968,7 +1078,7 @@ static bool tdp_mmu_populate_nonleaf(
 	WARN_ON(is_shadow_present_pte(iter->old_spte));
 	WARN_ON(is_removed_spte(iter->old_spte));
 
-	sp = alloc_tdp_mmu_page(vcpu, iter->gfn, iter->level - 1);
+	sp = alloc_tdp_mmu_page(vcpu, iter->gfn, iter->level - 1, is_private);
 	child_pt = sp->spt;
 
 	new_spte = make_nonleaf_spte(child_pt, !shadow_accessed_mask);
@@ -991,6 +1101,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 {
 	struct kvm_mmu *mmu = vcpu->arch.mmu;
 	struct tdp_iter iter;
+	gfn_t raw_gfn;
+	bool is_private;
 	int ret;
 
 	kvm_mmu_hugepage_adjust(vcpu, fault);
@@ -999,7 +1111,17 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 
 	rcu_read_lock();
 
-	tdp_mmu_for_each_pte(iter, mmu, fault->gfn, fault->gfn + 1) {
+	raw_gfn = gpa_to_gfn(fault->addr);
+	is_private = kvm_is_private_gfn(vcpu->kvm, raw_gfn);
+
+	if (is_error_noslot_pfn(fault->pfn) || kvm_is_reserved_pfn(fault->pfn)) {
+		if (is_private) {
+			rcu_read_unlock();
+			return -EFAULT;
+		}
+	}
+
+	tdp_mmu_for_each_pte(iter, mmu, is_private, raw_gfn, raw_gfn + 1) {
 		if (fault->nx_huge_page_workaround_enabled)
 			disallowed_hugepage_adjust(fault, iter.old_spte, iter.level);
 
@@ -1015,6 +1137,12 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 		    is_large_pte(iter.old_spte)) {
 			if (!tdp_mmu_zap_spte_atomic(vcpu->kvm, &iter))
 				break;
+			/*
+			 * TODO: large page support.
+			 * Doesn't support large page for TDX now
+			 */
+			WARN_ON(is_private_spte(&iter.old_spte));
+
 
 			/*
 			 * The iter must explicitly re-read the spte here
@@ -1037,7 +1165,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 
 			account_nx = fault->huge_page_disallowed &&
 				fault->req_level >= iter.level;
-			if (!tdp_mmu_populate_nonleaf(vcpu, &iter, account_nx))
+			if (!tdp_mmu_populate_nonleaf(
+					vcpu, &iter, is_private, account_nx))
 				break;
 		}
 	}
@@ -1058,9 +1187,12 @@ bool kvm_tdp_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range,
 {
 	struct kvm_mmu_page *root;
 
-	for_each_tdp_mmu_root_yield_safe(kvm, root, range->slot->as_id, false)
+	for_each_tdp_mmu_root_yield_safe(kvm, root, range->slot->as_id, false) {
+		if (is_private_sp(root))
+			continue;
 		flush = zap_gfn_range(kvm, root, range->start, range->end,
-				      range->may_block, flush, false);
+				range->may_block, flush, false);
+	}
 
 	return flush;
 }
@@ -1513,10 +1645,14 @@ int kvm_tdp_mmu_get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes,
 	struct kvm_mmu *mmu = vcpu->arch.mmu;
 	gfn_t gfn = addr >> PAGE_SHIFT;
 	int leaf = -1;
+	bool is_private = kvm_is_private_gfn(vcpu->kvm, gfn);
 
 	*root_level = vcpu->arch.mmu->shadow_root_level;
 
-	tdp_mmu_for_each_pte(iter, mmu, gfn, gfn + 1) {
+	if (WARN_ON(is_private))
+		return leaf;
+
+	tdp_mmu_for_each_pte(iter, mmu, false, gfn, gfn + 1) {
 		leaf = iter.level;
 		sptes[leaf] = iter.old_spte;
 	}
@@ -1542,12 +1678,16 @@ u64 *kvm_tdp_mmu_fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, u64 addr,
 	struct kvm_mmu *mmu = vcpu->arch.mmu;
 	gfn_t gfn = addr >> PAGE_SHIFT;
 	tdp_ptep_t sptep = NULL;
+	bool is_private = kvm_is_private_gfn(vcpu->kvm, gfn);
 
-	tdp_mmu_for_each_pte(iter, mmu, gfn, gfn + 1) {
+	if (is_private)
+		goto out;
+
+	tdp_mmu_for_each_pte(iter, mmu, false, gfn, gfn + 1) {
 		*spte = iter.old_spte;
 		sptep = iter.sptep;
 	}
-
+out:
 	/*
 	 * Perform the rcu_dereference to get the raw spte pointer value since
 	 * we are passing it up to fast_page_fault, which is shared with the
arch/x86/kvm/mmu/tdp_mmu.h +8 -5
index 3899004a5d91..7c62f694a465 100644
@@ -5,7 +5,7 @@
 
 #include <linux/kvm_host.h>
 
-hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu);
+hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu, bool private);
 
 __must_check static inline bool kvm_tdp_mmu_get_root(struct kvm *kvm,
 						     struct kvm_mmu_page *root)
@@ -20,11 +20,14 @@ void kvm_tdp_mmu_put_root(struct kvm *kvm, struct kvm_mmu_page *root,
 			  bool shared);
 
 bool __kvm_tdp_mmu_zap_gfn_range(struct kvm *kvm, int as_id, gfn_t start,
-				 gfn_t end, bool can_yield, bool flush);
+				 gfn_t end, bool can_yield, bool flush,
+				 bool zap_private);
 static inline bool kvm_tdp_mmu_zap_gfn_range(struct kvm *kvm, int as_id,
-					     gfn_t start, gfn_t end, bool flush)
+					     gfn_t start, gfn_t end, bool flush,
+					     bool zap_private)
 {
-	return __kvm_tdp_mmu_zap_gfn_range(kvm, as_id, start, end, true, flush);
+	return __kvm_tdp_mmu_zap_gfn_range(kvm, as_id, start, end, true, flush,
+			zap_private);
 }
 static inline bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
 {
@@ -41,7 +44,7 @@ static inline bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
 	 */
 	lockdep_assert_held_write(&kvm->mmu_lock);
 	return __kvm_tdp_mmu_zap_gfn_range(kvm, kvm_mmu_page_as_id(sp),
-					   sp->gfn, end, false, false);
+					   sp->gfn, end, false, false, false);
 }
 
 void kvm_tdp_mmu_zap_all(struct kvm *kvm);
virt/kvm/kvm_main.c +1 -0
index ae3bf553f215..d4e117f5b5b9 100644
@@ -190,6 +190,7 @@ bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
 
 	return true;
 }
+EXPORT_SYMBOL_GPL(kvm_is_reserved_pfn);
 
 /*
  * Switches to specified vcpu, until a matching vcpu_put()
#69 lore raw

Re: [RFC PATCH v5 023/104] x86/cpu: Add helper functions to allocate/free MKTME keyid

In reply to Kai Huang
Quoted 5 lines
Quoted 5 lines

Also export the global TDX private host key id that is used to encrypt TDX module, its memory and some dynamic data (e.g. TDR).

Sorry I was replying too quick.

This sentence is not correct. Hardware doesn't use global KeyID to encrypt TDX module itself. In current generation of TDX, global KeyID is used to encrypt TDX memory metadata (PAMTs) and TDRs.

Quoted 9 lines
Quoted 6 lines

When VMM releasing
encrypted page to reuse it, the page needs to be flushed with the used host key id. VMM needs the global TDX private host key id to flush such pages TDX module accesses with the global TDX private host key id.

Find to me.

#84 lore raw

Re: [RFC PATCH v5 026/104] KVM: TDX: x86: Add vm ioctl to get TDX systemwide parameters

In reply to Xiaoyao Li
Quoted 15 lines · Xiaoyao Li
Quoted 8 lines · Paolo Bonzini
Quoted 6 lines · On 3/4/22 20:48, [email protected] wrote:

Implement a VM-scoped subcomment to get system-wide parameters.  Although this is system-wide parameters not per-VM, this subcomand is VM-scoped because
- Device model needs TDX system-wide parameters after creating KVM VM.
- This subcommands requires to initialize TDX module.  For lazy initialization of the TDX module, vm-scope ioctl is better.

Quoted 5 lines

Since there was agreement to install the TDX module on load, please place this ioctl on the /dev/kvm file descriptor.

At least for SEV, there were cases where the system-wide parameters are needed outside KVM, so it's better to avoid requiring a VM file descriptor.

Quoted 7 lines

I don't have strong preference on KVM-scope ioctl or VM-scope.

Initially, we made it KVM-scope and change it to VM-scope in this version. Yes, it returns the info from TDX module, which doesn't vary per VM. However, what if we want to return different capabilities (software controlled capabilities) per VM?

In this case, you don't return different capabilities, instead, you return the same capabilities but control the capabilities on per-VM basis.

Quoted 10 lines

Part of the TDX capabilities
serves like get_supported_cpuid, making it KVM wide lacks the flexibility to return differentiated capabilities for different TDs.

Quoted 4 lines

Thanks,

Paolo

#249 lore raw

Re: [RFC PATCH v5 086/104] KVM: TDX: handle ept violation/misconfig exit

In reply to Sagi Shahar
Quoted 23 lines · Sagi Shahar
Quoted 22 lines · On Fri, Mar 4, 2022 at 12:23 PM <[email protected]> wrote:

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 | 40 ++++++++++++++++++++++++++++++++++++++--
  1 file changed, 38 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/tdx.c +0 -0
index 6fbe89bcfe1e..2c35dcad077e 100644
@@ -1081,6 +1081,40 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
         __vmx_deliver_posted_interrupt(vcpu, &tdx->pi_desc, vector);
  }
 
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode, · line 1084

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+#define TDX_SEPT_PFERR (PFERR_WRITE_MASK | PFERR_USER_MASK)

TDX_SEPT_PFERR is defined using PFERR_.* bitmask but __vmx_handle_ept_violation is accepting an EPT_VIOLATION_.* bitmask. so (PFERR_WRITE_MASK | PFERR_USER_MASK) will get interpreted as (EPT_VIOLATION_ACC_WRITE | EPT_VIOLATION_ACC_INSTR) which will get translated to (PFERR_WRITE_MASK | PFERR_FETCH_MASK). Was that the intention of this code?

No. It's a mistake. We have corrected internally you can find corrected code in github repo or see it in next version.