Skip to contentSkip to conversation

KVM TDX basic feature support

PATCH Superseded [email protected] 17 participants 228 messages Oct 30, 2022 – Jan 18, 2023 Page 2 of 3

Subsystems (7)
Documentation x86 KVM perf events +3 more subsystems

v10 of 19 Superseded Latest is v19 →

lore
Share & tools
lore
#198 lore raw

PATCH v10 98/108 KVM: TDX: Implement callbacks for MSR operations for TDX

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Implements set_msr/get_msr/has_emulated_msr methods for TDX to handle hypercall from guest TD for paravirtualized rdmsr and wrmsr. The TDX module virtualizes MSRs. For some MSRs, it injects #VE to the guest TD upon RDMSR or WRMSR. The exact list of such MSRs are defined in the spec.

Upon #VE, the guest TD may execute hypercalls, TDG.VP.VMCALL<INSTRUCTION.RDMSR> and TDG.VP.VMCALL<INSTRUCTION.WRMSR>, which are defined in GHCI (Guest-Host Communication Interface) so that the host VMM (e.g. KVM) can virtualizes the MSRs.

---
 arch/x86/kvm/vmx/main.c    | 34 ++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.c     | 63 ++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h |  6 ++++
 arch/x86/kvm/x86.c         |  1 -
 arch/x86/kvm/x86.h         |  2 ++
 5 files changed, 102 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +31 -3
index 74c561e3eb46..3a8a4fdf1ce7 100644
@@ -195,6 +195,34 @@ static void vt_handle_exit_irqoff(struct kvm_vcpu *vcpu)
 	vmx_handle_exit_irqoff(vcpu);
 }
 
+static int vt_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
+{
+	if (unlikely(is_td_vcpu(vcpu)))
+		return tdx_set_msr(vcpu, msr_info);
+
+	return vmx_set_msr(vcpu, msr_info);
+}
+
+/*
+ * The kvm parameter can be NULL (module initialization, or invocation before
+ * VM creation). Be sure to check the kvm parameter before using it.
+ */
+static bool vt_has_emulated_msr(struct kvm *kvm, u32 index)
+{
+	if (kvm && is_td(kvm))
+		return tdx_is_emulated_msr(index, true);
+
+	return vmx_has_emulated_msr(kvm, index);
+}
+
+static int vt_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
+{
+	if (unlikely(is_td_vcpu(vcpu)))
+		return tdx_get_msr(vcpu, msr_info);
+
+	return vmx_get_msr(vcpu, msr_info);
+}
+
 static void vt_apicv_post_state_restore(struct kvm_vcpu *vcpu)
 {
 	struct pi_desc *pi = vcpu_to_pi_desc(vcpu);
@@ -431,7 +459,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.hardware_enable = vt_hardware_enable,
 	.hardware_disable = vt_hardware_disable,
-	.has_emulated_msr = vmx_has_emulated_msr,
+	.has_emulated_msr = vt_has_emulated_msr,
 
 	.is_vm_type_supported = vt_is_vm_type_supported,
 	.vm_size = sizeof(struct kvm_vmx),
@@ -451,8 +479,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.update_exception_bitmap = vmx_update_exception_bitmap,
 	.get_msr_feature = vmx_get_msr_feature,
-	.get_msr = vmx_get_msr,
-	.set_msr = vmx_set_msr,
+	.get_msr = vt_get_msr,
+	.set_msr = vt_set_msr,
 	.get_segment_base = vmx_get_segment_base,
 	.get_segment = vmx_get_segment,
 	.set_segment = vmx_set_segment,
arch/x86/kvm/vmx/tdx.c +63 -0

69 lines not on this page · raw message

arch/x86/kvm/vmx/x86_ops.h +6 -0
index d02619f64b6e..8b9399b154f3 100644
@@ -162,6 +162,9 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
 void tdx_inject_nmi(struct kvm_vcpu *vcpu);
 void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
 		u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code);
+bool tdx_is_emulated_msr(u32 index, bool write);
+int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr);
+int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr);
 
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
@@ -200,6 +203,9 @@ static inline void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mo
 static inline void tdx_inject_nmi(struct kvm_vcpu *vcpu) {}
 static inline void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason, u64 *info1,
 				     u64 *info2, u32 *intr_info, u32 *error_code) {}
+static inline bool tdx_is_emulated_msr(u32 index, bool write) { return false; }
+static inline int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr) { return 1; }
+static inline int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr) { return 1; }
 
 static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOPNOTSUPP; }
 static inline int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp) { return -EOPNOTSUPP; }
arch/x86/kvm/x86.c +0 -1
index 2eacc4929d5d..5304b27f2566 100644
@@ -85,7 +85,6 @@
 #include "trace.h"
 
 #define MAX_IO_MSRS 256
-#define KVM_MAX_MCE_BANKS 32
 
 struct kvm_caps kvm_caps __read_mostly = {
 	.supported_mce_cap = MCG_CTL_P | MCG_SER_P,
arch/x86/kvm/x86.h +2 -0
index 829d3134c1eb..1d77c39821ae 100644
@@ -8,6 +8,8 @@
 #include "kvm_cache_regs.h"
 #include "kvm_emulate.h"
 
+#define KVM_MAX_MCE_BANKS 32
+
 struct kvm_caps {
 	/* control of guest tsc rate supported? */
 	bool has_tsc_control;
Signature · 1 line
2.25.1
#205 lore raw

PATCH v10 99/108 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Wire up TDX PV rdmsr/wrmsr hypercall to the KVM backend function.

---
 arch/x86/kvm/vmx/tdx.c | 39 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)
arch/x86/kvm/vmx/tdx.c +39 -0
index b820475ce0ab..e3062c245e70 100644
@@ -1033,6 +1033,41 @@ static int tdx_emulate_mmio(struct kvm_vcpu *vcpu)
 	return 1;
 }
 
+static int tdx_emulate_rdmsr(struct kvm_vcpu *vcpu)
+{
+	u32 index = tdvmcall_a0_read(vcpu);
+	u64 data;
+
+	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ) ||
+	    kvm_get_msr(vcpu, index, &data)) {
+		trace_kvm_msr_read_ex(index);
+		tdvmcall_set_return_code(vcpu, TDG_VP_VMCALL_INVALID_OPERAND);
+		return 1;
+	}
+	trace_kvm_msr_read(index, data);
+
+	tdvmcall_set_return_code(vcpu, TDG_VP_VMCALL_SUCCESS);
+	tdvmcall_set_return_val(vcpu, data);
+	return 1;
+}
+
+static int tdx_emulate_wrmsr(struct kvm_vcpu *vcpu)
+{
+	u32 index = tdvmcall_a0_read(vcpu);
+	u64 data = tdvmcall_a1_read(vcpu);
+
+	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE) ||
+	    kvm_set_msr(vcpu, index, data)) {
+		trace_kvm_msr_write_ex(index, data);
+		tdvmcall_set_return_code(vcpu, TDG_VP_VMCALL_INVALID_OPERAND);
+		return 1;
+	}
+
+	trace_kvm_msr_write(index, data);
+	tdvmcall_set_return_code(vcpu, TDG_VP_VMCALL_SUCCESS);
+	return 1;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
@@ -1047,6 +1082,10 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 		return tdx_emulate_io(vcpu);
 	case EXIT_REASON_EPT_VIOLATION:
 		return tdx_emulate_mmio(vcpu);
+	case EXIT_REASON_MSR_READ:
+		return tdx_emulate_rdmsr(vcpu);
+	case EXIT_REASON_MSR_WRITE:
+		return tdx_emulate_wrmsr(vcpu);
 	default:
 		break;
 	}
Signature · 1 line
2.25.1
#224 lore raw

Re: [PATCH v10 107/108] KVM: x86: design documentation on TDX support of x86 KVM TDP MMU

In reply to [email protected]

Review

Quoted 8 lines · On Sat, Oct 29, 2022 at 11:23:48PM -0700, [email protected] wrote:
(quoted diff) +8 -0
+During TDX non-root operation (i.e. guest TD), memory accesses can be qualified
+as either shared or private, based on the value of a new SHARED bit in the Guest
+Physical Address (GPA).  The CPU translates shared GPAs using the usual VMX EPT
+(Extended Page Table) or "Shared EPT" (in this document), which resides in the
+host VMM memory.  The Shared EPT is directly managed by the host VMM - the same
+as with the current VMX.  Since guest TDs usually require I/O, and the data
+exchange needs to be done via shared memory, thus KVM needs to use the current
+EPT functionality even for TDs.

Strip the last "thus", so it becomes "... via shared memory, KVM needs to use ..."

Quoted 21 lines
(quoted diff) +21 -0
+The following depicts the relationship.
+::
+
+                    KVM                             |       TDX module
+                     |                              |           |
+        -------------+----------                    |           |
+        |                      |                    |           |
+        V                      V                    |           |
+     shared GPA           private GPA               |           |
+  CPU shared EPT pointer  KVM private EPT pointer   |  CPU secure EPT pointer
+        |                      |                    |           |
+        |                      |                    |           |
+        V                      V                    |           V
+  shared EPT                private EPT<-------mirror----->Secure EPT
+        |                      |                    |           |
+        |                      \--------------------+------\    |
+        |                                           |      |    |
+        V                                           |      V    V
+  shared guest page                                 |    private guest page
+                                                    |
+                                                    |

Review

Quoted 10 lines
(quoted diff) +10 -0
+                              non-encrypted memory  |    encrypted memory
+                                                    |
+
+shared EPT: CPU and KVM walk with shared GPA
+            Maintained by the existing code
+private EPT: KVM walks with private GPA
+             Maintained by the twisted existing code
+secure EPT: CPU walks with private GPA.
+            Maintained by TDX module with TDX SEAMCALLs via hooks
+

What about this legend below?

---- >8 ----

Documentation/virt/kvm/tdx-tdp-mmu.rst +8 -6
index 2d91c94e6d8fd7..9ddbf44725f212 100644
@@ -236,12 +236,14 @@ The following depicts the relationship.
                               non-encrypted memory  |    encrypted memory
                                                     |
 
-shared EPT: CPU and KVM walk with shared GPA
-            Maintained by the existing code
-private EPT: KVM walks with private GPA
-             Maintained by the twisted existing code
-secure EPT: CPU walks with private GPA.
-            Maintained by TDX module with TDX SEAMCALLs via hooks
+Where:
+
+  * shared EPT: CPU and KVM walk with shared GPA (maintained by the existing
+    code)
+  * private EPT: KVM walks with private GPA (maintained by the twisted existing
+    code)
+  * secure EPT: CPU walks with private GPA (maintained by TDX module with TDX
+    SEAMCALLs via hooks).
 
 
 Tracking private EPT page

Review

Quoted 12 lines
(quoted diff) +12 -0
+Concurrent zapping
+------------------
+1. read lock
+2. freeze the EPT entry (atomically set the value to REMOVED_SPTE)
+   If other vcpu froze the entry, restart page fault.
+3. TLB shootdown
+
+   * send IPI to remote vcpus
+   * TLB flush (local and remote)
+
+   For each entry update, TLB shootdown is needed because of the
+   concurrency.

Concurrency issues?

Also, as I have iterated several times before, you need to add the documentation to KVM table of contents (index):

---- >8 ----

Documentation/virt/kvm/index.rst +1 -0
index cdb8b43ce7970a..ff2db9ab428d3c 100644
@@ -20,3 +20,4 @@ KVM
    review-checklist
 
    intel-tdx
+   tdx-tdp-mmu

Thanks.

Signature · 1 line
An old man doll... just what I always wanted! - Clara
#19 lore raw

Re: [PATCH v10 010/108] KVM: TDX: Add TDX "architectural" error codes

In reply to [email protected]
Quoted 31 lines · On 2022/10/30 14:22, [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.

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.

---
  arch/x86/kvm/vmx/tdx_errno.h | 38 ++++++++++++++++++++++++++++++++++++
  1 file changed, 38 insertions(+)

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

arch/x86/kvm/vmx/tdx_errno.h new file +5 -0
new file mode 100644
index 000000000000..ce246ba62454
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* architectural status code for SEAMCALL */
+
+#ifndef __KVM_X86_TDX_ERRNO_H
+#define __KVM_X86_TDX_ERRNO_H

arch/x86/kvm/vmx/tdx_errno.h line 15

Quoted 10 lines
arch/x86/kvm/vmx/tdx_errno.h new file +10 -0
+
+#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_OPERAND_BUSY                        0x8000020000000000ULL

one minor format issue, spaces are used  instread of tabs this line.

Quoted 23 lines
arch/x86/kvm/vmx/tdx_errno.h new file +23 -0
+#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
+
+/*
+ * TDG.VP.VMCALL Status Codes (returned in R10)
+ */
+#define TDG_VP_VMCALL_SUCCESS			0x0000000000000000ULL
+#define TDG_VP_VMCALL_RETRY			0x0000000000000001ULL
+#define TDG_VP_VMCALL_INVALID_OPERAND		0x8000000000000000ULL
+#define TDG_VP_VMCALL_TDREPORT_FAILED		0x8000000000000001ULL
+
+/*
+ * TDX module operand ID, appears in 31:0 part of error code as
+ * detail information
+ */
+#define TDX_OPERAND_ID_RCX			0x01
+#define TDX_OPERAND_ID_SEPT			0x92
+
+#endif /* __KVM_X86_TDX_ERRNO_H */
#27 lore raw

Re: [PATCH v10 014/108] KVM: TDX: Stub in tdx.h with structs, accessors, and VMCS helpers

In reply to [email protected]
Quoted 133 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Stub in kvm_tdx, vcpu_tdx, and their various accessors. TDX defines SEAMCALL APIs to access TDX control structures corresponding to the VMX VMCS. Introduce helper accessors to hide its SEAMCALL ABI details.

---
  arch/x86/kvm/vmx/tdx.h | 118 ++++++++++++++++++++++++++++++++++++++++-
  1 file changed, 116 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/tdx.h +98 -2
index 473013265bd8..98999bf3f188 100644
@@ -3,14 +3,27 @@
  #define __KVM_X86_TDX_H
 
  #ifdef CONFIG_INTEL_TDX_HOST
+
+#include "tdx_ops.h"
+
+struct tdx_td_page {
+	unsigned long va;
+	hpa_t pa;
+	bool added;
+};
+
  struct kvm_tdx {
  	struct kvm kvm;
-	/* TDX specific members follow. */
+
+	struct tdx_td_page tdr;
+	struct tdx_td_page *tdcs;
  };
 
  struct vcpu_tdx {
  	struct kvm_vcpu	vcpu;
-	/* TDX specific members follow. */
+
+	struct tdx_td_page tdvpr;
+	struct tdx_td_page *tdvpx;
  };
 
  static inline bool is_td(struct kvm *kvm)
@@ -32,6 +45,107 @@ static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
  {
  	return container_of(vcpu, struct vcpu_tdx, vcpu);
  }
+
+static __always_inline void tdvps_vmcs_check(u32 field, u8 bits)
+{
+#define VMCS_ENC_ACCESS_TYPE_MASK	0x1UL
+#define VMCS_ENC_ACCESS_TYPE_FULL	0x0UL
+#define VMCS_ENC_ACCESS_TYPE_HIGH	0x1UL
+#define VMCS_ENC_ACCESS_TYPE(field)	((field) & VMCS_ENC_ACCESS_TYPE_MASK)
+
+	/* TDX is 64bit only.  HIGH field isn't supported. */
+	BUILD_BUG_ON_MSG(__builtin_constant_p(field) &&
+			 VMCS_ENC_ACCESS_TYPE(field) == VMCS_ENC_ACCESS_TYPE_HIGH,
+			 "Read/Write to TD VMCS *_HIGH fields not supported");
+
+	BUILD_BUG_ON(bits != 16 && bits != 32 && bits != 64);
+
+#define VMCS_ENC_WIDTH_MASK	GENMASK(14, 13)
+#define VMCS_ENC_WIDTH_16BIT	(0UL << 13)
+#define VMCS_ENC_WIDTH_64BIT	(1UL << 13)
+#define VMCS_ENC_WIDTH_32BIT	(2UL << 13)
+#define VMCS_ENC_WIDTH_NATURAL	(3UL << 13)
+#define VMCS_ENC_WIDTH(field)	((field) & VMCS_ENC_WIDTH_MASK)
+
+	/* TDX is 64bit only.  i.e. natural width = 64bit. */
+	BUILD_BUG_ON_MSG(bits != 64 && __builtin_constant_p(field) &&
+			 (VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_64BIT ||
+			  VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_NATURAL),
+			 "Invalid TD VMCS access for 64-bit field");
+	BUILD_BUG_ON_MSG(bits != 32 && __builtin_constant_p(field) &&
+			 VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_32BIT,
+			 "Invalid TD VMCS access for 32-bit field");
+	BUILD_BUG_ON_MSG(bits != 16 && __builtin_constant_p(field) &&
+			 VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_16BIT,
+			 "Invalid TD VMCS access for 16-bit field");
+}
+
+static __always_inline void tdvps_state_non_arch_check(u64 field, u8 bits) {}
+static __always_inline void tdvps_management_check(u64 field, u8 bits) {}
+
+#define TDX_BUILD_TDVPS_ACCESSORS(bits, uclass, lclass)				\
+static __always_inline u##bits td_##lclass##_read##bits(struct vcpu_tdx *tdx,	\
+							u32 field)		\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_rd(tdx->tdvpr.pa, TDVPS_##uclass(field), &out);		\
+	if (unlikely(err)) {							\
+		pr_err("TDH_VP_RD["#uclass".0x%x] failed: 0x%llx\n",		\
+		       field, err);						\
+		return 0;							\
+	}									\
+	return (u##bits)out.r8;							\
+}										\
+static __always_inline void td_##lclass##_write##bits(struct vcpu_tdx *tdx,	\
+						      u32 field, u##bits val)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), val,		\
+		      GENMASK_ULL(bits - 1, 0), &out);				\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] = 0x%llx failed: 0x%llx\n",	\
+		       field, (u64)val, err);					\
+}										\
+static __always_inline void td_##lclass##_setbit##bits(struct vcpu_tdx *tdx,	\
+						       u32 field, u64 bit)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), bit, bit,		\
+			&out);							\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] |= 0x%llx failed: 0x%llx\n",	\
+		       field, bit, err);					\
+}										\
+static __always_inline void td_##lclass##_clearbit##bits(struct vcpu_tdx *tdx,	\
+							 u32 field, u64 bit)	\
+{										\

arch/x86/kvm/vmx/tdx.h static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu) · line 140

Quoted 10 lines
arch/x86/kvm/vmx/tdx.h +10 -0
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), 0, bit,		\
+			&out);							\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] &= ~0x%llx failed: 0x%llx\n",	\
+		       field, bit,  err);					\
+}

For the set of accessors, although there will be kernel errer message when tdh_vp_{rd,wr} fails, the caller doesn't know these function calls succeed or not. Won't this cause any unexpected behavior?

Quoted 11 lines
arch/x86/kvm/vmx/tdx.h +8 -0
+
+TDX_BUILD_TDVPS_ACCESSORS(16, VMCS, vmcs);
+TDX_BUILD_TDVPS_ACCESSORS(32, VMCS, vmcs);
+TDX_BUILD_TDVPS_ACCESSORS(64, VMCS, vmcs);
+
+TDX_BUILD_TDVPS_ACCESSORS(64, STATE_NON_ARCH, state_non_arch);
+TDX_BUILD_TDVPS_ACCESSORS(8, MANAGEMENT, management);
+
  #else
  struct kvm_tdx {
  	struct kvm kvm;
#145 lore raw

Re: [PATCH v10 060/108] KVM: Add functions to set GFN to private or shared

In reply to [email protected]
Quoted 98 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX KVM support needs to track whether GFN is private or shared. Introduce functions to set whether GFN is private or shared and pre-allocate memory for xarray.

---
  include/linux/kvm_host.h | 11 ++++++
  virt/kvm/kvm_main.c      | 74 ++++++++++++++++++++++++++++++++++++++++
  2 files changed, 85 insertions(+)
include/linux/kvm_host.h +11 -0
index a0b64308d240..fac07886ab39 100644
@@ -2307,9 +2307,20 @@ static inline void kvm_account_pgtable_pages(void *virt, int nr)
  #define KVM_MEM_ATTR_PRIVATE	0x0002
 
  #ifdef __KVM_HAVE_ARCH_UPDATE_MEM_ATTR
+/* memory attr on [start, end) */
+int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end);
+int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end);
  void kvm_arch_update_mem_attr(struct kvm *kvm, struct kvm_memory_slot *slot,
  			      unsigned int attr, gfn_t start, gfn_t end);
  #else
+static inline int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	return -EOPNOTSUPP;
+}
+static inline int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end)
+{
+	return -EOPNOTSUPP;
+}
  static inline void kvm_arch_update_mem_attr(struct kvm *kvm,
  					    struct kvm_memory_slot *slot,
  					    unsigned int attr,
virt/kvm/kvm_main.c +52 -0
index 9f82b03a8118..f0e77b65939b 100644
@@ -1121,6 +1121,80 @@ static inline void kvm_restrictedmem_unregister(struct kvm_memory_slot *slot)
  					  &slot->notifier);
  }
 
+/*
+ * Reserve memory for [start, end) so that the next set oepration won't fail
+ * with -ENOMEM.
+ */
+int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	int r = 0;
+	gfn_t gfn;
+
+	xa_lock(&kvm->mem_attr_array);
+	for (gfn = start; gfn < end; gfn++) {
+		r = __xa_insert(&kvm->mem_attr_array, gfn, NULL, GFP_KERNEL_ACCOUNT);
+		if (r == -EBUSY)
+			r = 0;
+		if (r)
+			break;
+	}
+	xa_unlock(&kvm->mem_attr_array);
+
+	return r;
+}
+EXPORT_SYMBOL_GPL(kvm_vm_reserve_mem_attr);
+
+/* Set memory attr for [start, end) */
+int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end)
+{
+	void *entry;
+	gfn_t gfn;
+	int r;
+	int i;
+
+	/* By default, the entry is private. */
+	switch (attr) {
+	case KVM_MEM_ATTR_PRIVATE:
+		entry = NULL;
+		break;
+	case KVM_MEM_ATTR_SHARED:
+		entry = xa_mk_value(KVM_MEM_ATTR_SHARED);
+		break;
+	default:
+		WARN_ON_ONCE(1);
+		return -EINVAL;
+	}
+
+	WARN_ON_ONCE(start >= end);
+	for (gfn = start; gfn < end; gfn++) {
+		r = xa_err(xa_store(&kvm->mem_attr_array, gfn, entry,
+				    GFP_KERNEL_ACCOUNT));
+		if (r)
+			break;
+	}
+	if (start >= gfn)

virt/kvm/kvm_main.c static inline void kvm_restrictedmem_unregister(struct kvm_memory_slot *slot) · line 1185

Quoted 10 lines
virt/kvm/kvm_main.c +10 -0
+		return r;
+
+	end = gfn;
+	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
+		struct kvm_memslot_iter iter;
+		struct kvm_memory_slot *slot;
+		struct kvm_memslots *slots;
+
+		slots = __kvm_memslots(kvm, i);
+		kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {

slot needs to be set as

			slot = iter.slot;
Quoted 15 lines
virt/kvm/kvm_main.c +12 -0
+			gfn_t s = max(start, slot->base_gfn);
+			gfn_t e = min(end, slot->base_gfn + slot->npages);
+
+			WARN_ON_ONCE(s >= e);
+			kvm_arch_update_mem_attr(kvm, slot, attr, s, e);
+		}
+	}
+
+	return r;
+}
+EXPORT_SYMBOL_GPL(kvm_vm_set_mem_attr);
+
  #else /* !CONFIG_HAVE_KVM_RESTRICTED_MEM */
 
  static inline void kvm_restrictedmem_register(struct kvm_memory_slot *slot)
#46 lore raw

Re: [PATCH v10 017/108] KVM: TDX: Refuse to unplug the last cpu on the package

In reply to [email protected]
Quoted 155 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

In order to reclaim TDX host key id, (i.e. when deleting guest TD), needs to call TDH.PHYMEM.PAGE.WBINVD on all packages. If we have used TDX host key id, refuse to offline the last online cpu.

---
  arch/x86/include/asm/kvm-x86-ops.h |  1 +
  arch/x86/include/asm/kvm_host.h    |  1 +
  arch/x86/kvm/vmx/main.c            |  1 +
  arch/x86/kvm/vmx/tdx.c             | 40 +++++++++++++++++++++++++++++-
  arch/x86/kvm/vmx/x86_ops.h         |  2 ++
  arch/x86/kvm/x86.c                 | 27 ++++++++++++--------
  6 files changed, 61 insertions(+), 11 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index 3a29a6b31ee8..0ceb8e58a6c0 100644
@@ -17,6 +17,7 @@ BUILD_BUG_ON(1)
  KVM_X86_OP(hardware_enable)
  KVM_X86_OP(hardware_disable)
  KVM_X86_OP(hardware_unsetup)
+KVM_X86_OP_OPTIONAL_RET0(offline_cpu)
  KVM_X86_OP(has_emulated_msr)
  KVM_X86_OP(vcpu_after_set_cpuid)
  KVM_X86_OP(is_vm_type_supported)
arch/x86/include/asm/kvm_host.h +1 -0
index 2870155ce6fb..50b39d0071ff 100644
@@ -1466,6 +1466,7 @@ struct kvm_x86_ops {
  	int (*hardware_enable)(void);
  	void (*hardware_disable)(void);
  	void (*hardware_unsetup)(void);
+	int (*offline_cpu)(void);
  	bool (*has_emulated_msr)(struct kvm *kvm, u32 index);
  	void (*vcpu_after_set_cpuid)(struct kvm_vcpu *vcpu);
 
arch/x86/kvm/vmx/main.c +1 -0
index d01a946a18cf..0918d1e6d2f3 100644
@@ -67,6 +67,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.name = "kvm_intel",
 
  	.hardware_unsetup = vt_hardware_unsetup,
+	.offline_cpu = tdx_offline_cpu,
  	.check_processor_compatibility = vmx_check_processor_compatibility,
 
  	.hardware_enable = vmx_hardware_enable,
arch/x86/kvm/vmx/tdx.c +39 -1
index ec88dde0d300..64229c3b3c5a 100644
@@ -42,6 +42,7 @@ static struct tdx_capabilities tdx_caps;
   */
  static DEFINE_MUTEX(tdx_lock);
  static struct mutex *tdx_mng_key_config_lock;
+static atomic_t nr_configured_hkid;
 
  static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
  {
@@ -222,7 +223,8 @@ void tdx_mmu_release_hkid(struct kvm *kvm)
  		pr_err("tdh_mng_key_freeid failed. HKID %d is leaked.\n",
  			kvm_tdx->hkid);
  		return;
-	}
+	} else
+		atomic_dec(&nr_configured_hkid);
 
  free_hkid:
  	tdx_hkid_free(kvm_tdx);
@@ -371,6 +373,8 @@ int tdx_vm_init(struct kvm *kvm)
  		if (ret)
  			break;
  	}
+	if (!ret)
+		atomic_inc(&nr_configured_hkid);
  	cpus_read_unlock();
  	free_cpumask_var(packages);
  	if (ret)
@@ -514,3 +518,37 @@ void tdx_hardware_unsetup(void)
  	/* kfree accepts NULL. */
  	kfree(tdx_mng_key_config_lock);
  }
+
+int tdx_offline_cpu(void)
+{
+	int curr_cpu = smp_processor_id();
+	cpumask_var_t packages;
+	int ret = 0;
+	int i;
+
+	if (!atomic_read(&nr_configured_hkid))
+		return 0;
+
+	/*
+	 * To reclaim hkid, need to call TDH.PHYMEM.PAGE.WBINVD on all packages.
+	 * If this is the last online cpu on the package, refuse offline.
+	 */
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
+
+	for_each_online_cpu(i) {
+		if (i != curr_cpu)
+			cpumask_set_cpu(topology_physical_package_id(i), packages);
+	}
+	if (!cpumask_test_cpu(topology_physical_package_id(curr_cpu), packages))
+		ret = -EBUSY;
+	free_cpumask_var(packages);
+	if (ret)
+		/*
+		 * Because it's hard for human operator to understand the
+		 * reason, warn it.
+		 */
+		pr_warn("TDX requires all packages to have an online CPU.  "
+			"Delete all TDs in order to offline all CPUs of a package.\n");
+	return ret;
+}
arch/x86/kvm/vmx/x86_ops.h +2 -0
index 95da978c9aa9..b2cb5786830a 100644
@@ -134,6 +134,7 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
  int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
  bool tdx_is_vm_type_supported(unsigned long type);
  void tdx_hardware_unsetup(void);
+int tdx_offline_cpu(void);
 
  int tdx_vm_init(struct kvm *kvm);
  void tdx_mmu_release_hkid(struct kvm *kvm);
@@ -142,6 +143,7 @@ void tdx_vm_free(struct kvm *kvm);
  static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return 0; }
  static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
  static inline void tdx_hardware_unsetup(void) {}
+static inline int tdx_offline_cpu(void) { return 0; }
 
  static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
  static inline void tdx_mmu_release_hkid(struct kvm *kvm) {}
arch/x86/kvm/x86.c +0 -6
index 4b22196cb12c..25c30c8c2d9b 100644
@@ -12337,16 +12337,23 @@ int kvm_arch_online_cpu(unsigned int cpu, int usage_count)
 
  int kvm_arch_offline_cpu(unsigned int cpu, int usage_count)
  {
-	if (usage_count) {
-		/*
-		 * arch callback kvm_arch_hardware_disable() assumes that
-		 * preemption is disabled for historical reason.  Disable
-		 * preemption until all arch callbacks are fixed.
-		 */

arch/x86/kvm/x86.c int kvm_arch_online_cpu(unsigned int cpu, int usage_count) · line 12345

Quoted 10 lines
arch/x86/kvm/x86.c +6 -4
-		preempt_disable();
-		hardware_disable(NULL);
-		preempt_enable();
-	}
+	int ret;
+
+	if (!usage_count)
+		return 0;
+
+	ret = static_call(kvm_x86_offline_cpu)();

Use static_call_cond instead?
Seems the new interface for x86 is only implemented for Intel.

Quoted 14 lines
arch/x86/kvm/x86.c +11 -0
+	if (ret)
+		return ret;
+
+	/*
+	 * arch callback kvm_arch_hardware_disable() assumes that preemption is
+	 * disabled for historical reason.  Disable preemption until all arch
+	 * callbacks are fixed.
+	 */
+	preempt_disable();
+	hardware_disable(NULL);
+	preempt_enable();
  	return 0;
  }
 
#20 lore raw

Re: [PATCH v10 010/108] KVM: TDX: Add TDX "architectural" error codes

In reply to Binbin Wu
Quoted 37 lines · Binbin Wu
Quoted 35 lines · On 2022/10/30 14:22, [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.

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.

---
  arch/x86/kvm/vmx/tdx_errno.h | 38 ++++++++++++++++++++++++++++++++++++
  1 file changed, 38 insertions(+)

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

arch/x86/kvm/vmx/tdx_errno.h new file +9 -0
new file mode 100644
index 000000000000..ce246ba62454
@@ -0,0 +1,38 @@
+/* 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
+
+/*
Quoted 8 lines

arch/x86/kvm/vmx/tdx_errno.h line 15

Quoted 6 lines
arch/x86/kvm/vmx/tdx_errno.h new file +6 -0
+ * TDX SEAMCALL Status Codes (returned in RAX)
+ */
+#define TDX_SUCCESS				0x0000000000000000ULL
+#define TDX_NON_RECOVERABLE_VCPU		0x4000000100000000ULL
+#define TDX_INTERRUPTED_RESUMABLE		0x8000000300000000ULL
+#define TDX_OPERAND_BUSY                        0x8000020000000000ULL

one minor format issue, spaces are used  instread of tabs this line.

Thanks, fixed it locally. It will be include in the next respin.

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

Re: [PATCH v10 014/108] KVM: TDX: Stub in tdx.h with structs, accessors, and VMCS helpers

In reply to Binbin Wu
Quoted 140 lines · Binbin Wu
Quoted 138 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Stub in kvm_tdx, vcpu_tdx, and their various accessors. TDX defines SEAMCALL APIs to access TDX control structures corresponding to the VMX VMCS. Introduce helper accessors to hide its SEAMCALL ABI details.

---
  arch/x86/kvm/vmx/tdx.h | 118 ++++++++++++++++++++++++++++++++++++++++-
  1 file changed, 116 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/tdx.h +106 -2
index 473013265bd8..98999bf3f188 100644
@@ -3,14 +3,27 @@
  #define __KVM_X86_TDX_H
  #ifdef CONFIG_INTEL_TDX_HOST
+
+#include "tdx_ops.h"
+
+struct tdx_td_page {
+	unsigned long va;
+	hpa_t pa;
+	bool added;
+};
+
  struct kvm_tdx {
  	struct kvm kvm;
-	/* TDX specific members follow. */
+
+	struct tdx_td_page tdr;
+	struct tdx_td_page *tdcs;
  };
  struct vcpu_tdx {
  	struct kvm_vcpu	vcpu;
-	/* TDX specific members follow. */
+
+	struct tdx_td_page tdvpr;
+	struct tdx_td_page *tdvpx;
  };
  static inline bool is_td(struct kvm *kvm)
@@ -32,6 +45,107 @@ static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
  {
  	return container_of(vcpu, struct vcpu_tdx, vcpu);
  }
+
+static __always_inline void tdvps_vmcs_check(u32 field, u8 bits)
+{
+#define VMCS_ENC_ACCESS_TYPE_MASK	0x1UL
+#define VMCS_ENC_ACCESS_TYPE_FULL	0x0UL
+#define VMCS_ENC_ACCESS_TYPE_HIGH	0x1UL
+#define VMCS_ENC_ACCESS_TYPE(field)	((field) & VMCS_ENC_ACCESS_TYPE_MASK)
+
+	/* TDX is 64bit only.  HIGH field isn't supported. */
+	BUILD_BUG_ON_MSG(__builtin_constant_p(field) &&
+			 VMCS_ENC_ACCESS_TYPE(field) == VMCS_ENC_ACCESS_TYPE_HIGH,
+			 "Read/Write to TD VMCS *_HIGH fields not supported");
+
+	BUILD_BUG_ON(bits != 16 && bits != 32 && bits != 64);
+
+#define VMCS_ENC_WIDTH_MASK	GENMASK(14, 13)
+#define VMCS_ENC_WIDTH_16BIT	(0UL << 13)
+#define VMCS_ENC_WIDTH_64BIT	(1UL << 13)
+#define VMCS_ENC_WIDTH_32BIT	(2UL << 13)
+#define VMCS_ENC_WIDTH_NATURAL	(3UL << 13)
+#define VMCS_ENC_WIDTH(field)	((field) & VMCS_ENC_WIDTH_MASK)
+
+	/* TDX is 64bit only.  i.e. natural width = 64bit. */
+	BUILD_BUG_ON_MSG(bits != 64 && __builtin_constant_p(field) &&
+			 (VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_64BIT ||
+			  VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_NATURAL),
+			 "Invalid TD VMCS access for 64-bit field");
+	BUILD_BUG_ON_MSG(bits != 32 && __builtin_constant_p(field) &&
+			 VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_32BIT,
+			 "Invalid TD VMCS access for 32-bit field");
+	BUILD_BUG_ON_MSG(bits != 16 && __builtin_constant_p(field) &&
+			 VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_16BIT,
+			 "Invalid TD VMCS access for 16-bit field");
+}
+
+static __always_inline void tdvps_state_non_arch_check(u64 field, u8 bits) {}
+static __always_inline void tdvps_management_check(u64 field, u8 bits) {}
+
+#define TDX_BUILD_TDVPS_ACCESSORS(bits, uclass, lclass)				\
+static __always_inline u##bits td_##lclass##_read##bits(struct vcpu_tdx *tdx,	\
+							u32 field)		\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_rd(tdx->tdvpr.pa, TDVPS_##uclass(field), &out);		\
+	if (unlikely(err)) {							\
+		pr_err("TDH_VP_RD["#uclass".0x%x] failed: 0x%llx\n",		\
+		       field, err);						\
+		return 0;							\
+	}									\
+	return (u##bits)out.r8;							\
+}										\
+static __always_inline void td_##lclass##_write##bits(struct vcpu_tdx *tdx,	\
+						      u32 field, u##bits val)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), val,		\
+		      GENMASK_ULL(bits - 1, 0), &out);				\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] = 0x%llx failed: 0x%llx\n",	\
+		       field, (u64)val, err);					\
+}										\
+static __always_inline void td_##lclass##_setbit##bits(struct vcpu_tdx *tdx,	\
+						       u32 field, u64 bit)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), bit, bit,		\
+			&out);							\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] |= 0x%llx failed: 0x%llx\n",	\
+		       field, bit, err);					\
+}										\
+static __always_inline void td_##lclass##_clearbit##bits(struct vcpu_tdx *tdx,	\
+							 u32 field, u64 bit)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), 0, bit,		\
+			&out);							\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] &= ~0x%llx failed: 0x%llx\n",	\
Quoted 8 lines

arch/x86/kvm/vmx/tdx.h static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu) · line 140

Quoted 2 lines
arch/x86/kvm/vmx/tdx.h +2 -0
+		       field, bit,  err);					\
+}

For the set of accessors, although there will be kernel errer message when tdh_vp_{rd,wr} fails,
the caller doesn't know these function calls succeed or not. Won't this cause any unexpected
behavior?

Oh right. Basically tdh_vp_{rd, wr} should fail as long as parameters are correct. So I'll add KVM_BUG_ON(). TDX module takes shared lock on TDVPR, TDR and TDCS. It should fails with TDX_OPERAND_BUSY on run time. (At least with TDX module 1.0)

Thanks,

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

Re: [PATCH v10 017/108] KVM: TDX: Refuse to unplug the last cpu on the package

In reply to Binbin Wu
Quoted 18 lines · Binbin Wu
Quoted 18 lines
arch/x86/kvm/x86.c +1 -10
index 4b22196cb12c..25c30c8c2d9b 100644
@@ -12337,16 +12337,23 @@ int kvm_arch_online_cpu(unsigned int cpu, int usage_count)
  int kvm_arch_offline_cpu(unsigned int cpu, int usage_count)
  {
-	if (usage_count) {
-		/*
-		 * arch callback kvm_arch_hardware_disable() assumes that
-		 * preemption is disabled for historical reason.  Disable
-		 * preemption until all arch callbacks are fixed.
-		 */
-		preempt_disable();
-		hardware_disable(NULL);
-		preempt_enable();
-	}
+	int ret;
Quoted 8 lines

arch/x86/kvm/x86.c int kvm_arch_online_cpu(unsigned int cpu, int usage_count) · line 12345

Quoted 5 lines
arch/x86/kvm/x86.c +5 -0
+
+	if (!usage_count)
+		return 0;
+
+	ret = static_call(kvm_x86_offline_cpu)();

Use static_call_cond instead?
Seems the new interface for x86 is only implemented for Intel.

Not needed because KVM_X86_OP_OPTIONAL_RET0(offline_cpu) is used.

Please remember

#define KVM_X86_OP_OPTIONAL_RET0(func) \
        static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
                                           (void *)__static_call_return0);

Thanks,

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

Re: [PATCH v10 060/108] KVM: Add functions to set GFN to private or shared

In reply to Xiaoyao Li
Quoted 110 lines · Xiaoyao Li
Quoted 96 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX KVM support needs to track whether GFN is private or shared. Introduce functions to set whether GFN is private or shared and pre-allocate memory for xarray.

---
  include/linux/kvm_host.h | 11 ++++++
  virt/kvm/kvm_main.c      | 74 ++++++++++++++++++++++++++++++++++++++++
  2 files changed, 85 insertions(+)
include/linux/kvm_host.h +11 -0
index a0b64308d240..fac07886ab39 100644
@@ -2307,9 +2307,20 @@ static inline void kvm_account_pgtable_pages(void *virt, int nr)
  #define KVM_MEM_ATTR_PRIVATE	0x0002
  #ifdef __KVM_HAVE_ARCH_UPDATE_MEM_ATTR
+/* memory attr on [start, end) */
+int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end);
+int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end);
  void kvm_arch_update_mem_attr(struct kvm *kvm, struct kvm_memory_slot *slot,
  			      unsigned int attr, gfn_t start, gfn_t end);
  #else
+static inline int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	return -EOPNOTSUPP;
+}
+static inline int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end)
+{
+	return -EOPNOTSUPP;
+}
  static inline void kvm_arch_update_mem_attr(struct kvm *kvm,
  					    struct kvm_memory_slot *slot,
  					    unsigned int attr,
virt/kvm/kvm_main.c +52 -0
index 9f82b03a8118..f0e77b65939b 100644
@@ -1121,6 +1121,80 @@ static inline void kvm_restrictedmem_unregister(struct kvm_memory_slot *slot)
  					  &slot->notifier);
  }
+/*
+ * Reserve memory for [start, end) so that the next set oepration won't fail
+ * with -ENOMEM.
+ */
+int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	int r = 0;
+	gfn_t gfn;
+
+	xa_lock(&kvm->mem_attr_array);
+	for (gfn = start; gfn < end; gfn++) {
+		r = __xa_insert(&kvm->mem_attr_array, gfn, NULL, GFP_KERNEL_ACCOUNT);
+		if (r == -EBUSY)
+			r = 0;
+		if (r)
+			break;
+	}
+	xa_unlock(&kvm->mem_attr_array);
+
+	return r;
+}
+EXPORT_SYMBOL_GPL(kvm_vm_reserve_mem_attr);
+
+/* Set memory attr for [start, end) */
+int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end)
+{
+	void *entry;
+	gfn_t gfn;
+	int r;
+	int i;
+
+	/* By default, the entry is private. */
+	switch (attr) {
+	case KVM_MEM_ATTR_PRIVATE:
+		entry = NULL;
+		break;
+	case KVM_MEM_ATTR_SHARED:
+		entry = xa_mk_value(KVM_MEM_ATTR_SHARED);
+		break;
+	default:
+		WARN_ON_ONCE(1);
+		return -EINVAL;
+	}
+
+	WARN_ON_ONCE(start >= end);
+	for (gfn = start; gfn < end; gfn++) {
+		r = xa_err(xa_store(&kvm->mem_attr_array, gfn, entry,
+				    GFP_KERNEL_ACCOUNT));
+		if (r)
+			break;
+	}
+	if (start >= gfn)

virt/kvm/kvm_main.c static inline void kvm_restrictedmem_unregister(struct kvm_memory_slot *slot) · line 1184

Quoted 10 lines
virt/kvm/kvm_main.c +10 -0
+		return r;
+
+	end = gfn;
+	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
+		struct kvm_memslot_iter iter;
+		struct kvm_memory_slot *slot;
+		struct kvm_memslots *slots;
+
+		slots = __kvm_memslots(kvm, i);
+		kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {

slot needs to be set as

Quoted 2 lines
			slot = iter.slot;

Thanks, will fix it.

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

Re: [PATCH v10 031/108] KVM: x86/mmu: Replace hardcoded value 0 for the initial value for SPTE

In reply to [email protected]
Quoted 47 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The TDX support will need the "suppress #VE" bit (bit 63) set as the initial value for SPTE. To reduce code change size, introduce a new macro SHADOW_NONPRESENT_VALUE for the initial value for the shadow page table entry (SPTE) and replace hard-coded value 0 for it. Initialize shadow page tables with their value.

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware doesn't use this bit; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

---
  arch/x86/kvm/mmu/mmu.c     | 50 +++++++++++++++++++++++++++++++++-----
  arch/x86/kvm/mmu/spte.h    |  2 ++
  arch/x86/kvm/mmu/tdp_mmu.c | 15 ++++++------
  3 files changed, 54 insertions(+), 13 deletions(-)
arch/x86/kvm/mmu/mmu.c +3 -3
index 10017a9f26ee..e7e11f51f8b4 100644
@@ -538,9 +538,9 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
 
  	if (!is_shadow_present_pte(old_spte) ||
  	    !spte_has_volatile_bits(old_spte))
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
  	else
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
 
  	if (!is_shadow_present_pte(old_spte))
  		return old_spte;
@@ -574,7 +574,7 @@ static u64 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_NONPRESENT_VALUE);
  }
 
  static u64 mmu_spte_get_lockless(u64 *sptep)

arch/x86/kvm/mmu/mmu.c static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu) · line 644

Quoted 3 lines
arch/x86/kvm/mmu/mmu.c +0 -0
@@ -642,6 +642,39 @@ static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
  	}
  }
 

Why the changes in mmu_spte_clear_track_bits and mmu_spte_clear_no_track are not handled differently for X86_64 and non X86_64 as the shadow page init below? It seems the two functions are the common code.

Quoted 128 lines
arch/x86/kvm/mmu/mmu.c +41 -3
+#ifdef CONFIG_X86_64
+static inline void kvm_init_shadow_page(void *page)
+{
+	memset64(page, SHADOW_NONPRESENT_VALUE, 4096 / 8);
+}
+
+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;
+
+	start = kvm_mmu_memory_cache_nr_free_objects(mc);
+	r = kvm_mmu_topup_memory_cache(mc, PT64_ROOT_MAX_LEVEL);
+
+	/*
+	 * Note, topup may have allocated objects even if it failed to allocate
+	 * the minimum number of objects required to make forward progress _at
+	 * this time_.  Initialize newly allocated objects even on failure, as
+	 * userspace can free memory and rerun the vCPU in response to -ENOMEM.
+	 */
+	end = kvm_mmu_memory_cache_nr_free_objects(mc);
+	for (i = start; i < end; i++)
+		kvm_init_shadow_page(mc->objects[i]);
+	return r;
+}
+#else
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
+					  PT64_ROOT_MAX_LEVEL);
+}
+#endif /* CONFIG_X86_64 */
+
  static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
  {
  	int r;
@@ -651,8 +684,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) {
@@ -5870,7 +5902,13 @@ 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;
+	/*
+	 * When X86_64, initial SEPT entries are initialized with
+	 * SHADOW_NONPRESENT_VALUE.  Otherwise zeroed.  See
+	 * mmu_topup_shadow_page_cache().
+	 */
+	if (!IS_ENABLED(CONFIG_X86_64))
+		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.h +2 -0
index 7670c13ce251..42ecaa75da15 100644
@@ -148,6 +148,8 @@ static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11);
 
  #define MMIO_SPTE_GEN_MASK		GENMASK_ULL(MMIO_SPTE_GEN_LOW_BITS + MMIO_SPTE_GEN_HIGH_BITS - 1, 0)
 
+#define SHADOW_NONPRESENT_VALUE	0ULL
+
  extern u64 __read_mostly shadow_host_writable_mask;
  extern u64 __read_mostly shadow_mmu_writable_mask;
  extern u64 __read_mostly shadow_nx_mask;
arch/x86/kvm/mmu/tdp_mmu.c +8 -7
index eab765442d0b..38bc4c2f0f1f 100644
@@ -694,7 +694,7 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
  	 * here since the SPTE is going from non-present to non-present.  Use
  	 * the raw write helper to avoid an unnecessary check on volatile bits.
  	 */
-	__kvm_tdp_mmu_write_spte(iter->sptep, 0);
+	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
 
  	return 0;
  }
@@ -871,8 +871,8 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, struct kvm_mmu_page *root,
  			continue;
 
  		if (!shared)
-			tdp_mmu_set_spte(kvm, &iter, 0);
-		else if (tdp_mmu_set_spte_atomic(kvm, &iter, 0))
+			tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+		else if (tdp_mmu_set_spte_atomic(kvm, &iter, SHADOW_NONPRESENT_VALUE))
  			goto retry;
  	}
  }
@@ -928,8 +928,9 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
  	if (WARN_ON_ONCE(!is_shadow_present_pte(old_spte)))
  		return false;
 
-	__tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte, 0,
-			   sp->gfn, sp->role.level + 1, true, true);
+	__tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
+			   SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1,
+			   true, true);
 
  	return true;
  }
@@ -963,7 +964,7 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
  		    !is_last_spte(iter.old_spte, iter.level))
  			continue;
 
-		tdp_mmu_set_spte(kvm, &iter, 0);
+		tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
  		flush = true;
  	}
 
@@ -1328,7 +1329,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_NONPRESENT_VALUE);
 
  	if (!pte_write(range->pte)) {
  		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
#69 lore raw

Re: [PATCH v10 031/108] KVM: x86/mmu: Replace hardcoded value 0 for the initial value for SPTE

Quoted 47 lines · Binbin Wu
Quoted 45 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The TDX support will need the "suppress #VE" bit (bit 63) set as the initial value for SPTE.  To reduce code change size, introduce a new macro SHADOW_NONPRESENT_VALUE for the initial value for the shadow page table entry (SPTE) and replace hard-coded value 0 for it.  Initialize shadow page tables with their value.

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware doesn't use this bit; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

---
  arch/x86/kvm/mmu/mmu.c     | 50 +++++++++++++++++++++++++++++++++----- arch/x86/kvm/mmu/spte.h    |  2 ++ arch/x86/kvm/mmu/tdp_mmu.c | 15 ++++++------

  3 files changed, 54 insertions(+), 13 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index 10017a9f26ee..e7e11f51f8b4 100644
@@ -538,9 +538,9 @@ static u64 mmu_spte_clear_track_bits(struct kvm 
 *kvm, u64 *sptep)

        if (!is_shadow_present_pte(old_spte) || !spte_has_volatile_bits(old_spte))
-        __update_clear_spte_fast(sptep, 0ull);
+        __update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE); else
-        old_spte = __update_clear_spte_slow(sptep, 0ull); +        old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
        if (!is_shadow_present_pte(old_spte))
          return old_spte;

arch/x86/kvm/mmu/mmu.c +1 -1
@@ -574,7 +574,7 @@ static u64 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_NONPRESENT_VALUE);
   }
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c static void walk_shadow_page_lockless_end(struct · line 644

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +0 -0
     static u64 mmu_spte_get_lockless(u64 *sptep)
@@ -642,6 +642,39 @@ static void walk_shadow_page_lockless_end(struct 
 kvm_vcpu *vcpu)
       }
   }

Why the changes in mmu_spte_clear_track_bits and mmu_spte_clear_no_track are not handled differently for X86_64 and non X86_64 as the shadow page init below? It seems the two functions are the common code.

I see there are different definitions of SHADOW_NONPRESENT_VALUE for X86_64 and  non X86_64 in the following patch. So got the answer now. : )

Quoted 132 lines
Quoted 132 lines
arch/x86/kvm/mmu/mmu.c +16 -0
+#ifdef CONFIG_X86_64
+static inline void kvm_init_shadow_page(void *page)
+{
+    memset64(page, SHADOW_NONPRESENT_VALUE, 4096 / 8);
+}
+
+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;
+
+    start = kvm_mmu_memory_cache_nr_free_objects(mc);
+    r = kvm_mmu_topup_memory_cache(mc, PT64_ROOT_MAX_LEVEL);
+
+    /*
+     * Note, topup may have allocated objects even if it failed to 

allocate
+     * the minimum number of objects required to make forward progress _at
+     * this time_.  Initialize newly allocated objects even on failure, as
+     * userspace can free memory and rerun the vCPU in response to

arch/x86/kvm/mmu/mmu.c +10 -1
-ENOMEM.
+     */
+    end = kvm_mmu_memory_cache_nr_free_objects(mc);
+    for (i = start; i < end; i++)
+        kvm_init_shadow_page(mc->objects[i]);
+    return r;
+}
+#else
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+    return 

kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache, +                      PT64_ROOT_MAX_LEVEL);

arch/x86/kvm/mmu/mmu.c +3 -0
+}
+#endif /* CONFIG_X86_64 */
+

  static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect) {
      int r;

arch/x86/kvm/mmu/mmu.c +1 -2
@@ -651,8 +684,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 +7 -0
@@ -5870,7 +5902,13 @@ 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;
+    /*
+     * When X86_64, initial SEPT entries are initialized with
+     * SHADOW_NONPRESENT_VALUE.  Otherwise zeroed.  See
+     * mmu_topup_shadow_page_cache().
+     */
+    if (!IS_ENABLED(CONFIG_X86_64))
+        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.h +0 -0
index 7670c13ce251..42ecaa75da15 100644
@@ -148,6 +148,8 @@ static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && 
 MMIO_SPTE_GEN_HIGH_BITS == 11);
     #define MMIO_SPTE_GEN_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_BITS + MMIO_SPTE_GEN_HIGH_BITS - 1, 0)

  +#define SHADOW_NONPRESENT_VALUE    0ULL
+
  extern u64 __read_mostly shadow_host_writable_mask; extern u64 __read_mostly shadow_mmu_writable_mask; extern u64 __read_mostly shadow_nx_mask;

arch/x86/kvm/mmu/tdp_mmu.c +3 -3
index eab765442d0b..38bc4c2f0f1f 100644
@@ -694,7 +694,7 @@ static inline int tdp_mmu_zap_spte_atomic(struct 
 kvm *kvm,
        * here since the SPTE is going from non-present to non-present.  Use
        * the raw write helper to avoid an unnecessary check on volatile bits.
        */
-    __kvm_tdp_mmu_write_spte(iter->sptep, 0);
+    __kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
         return 0;
   }
@@ -871,8 +871,8 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, 
 struct kvm_mmu_page *root,
               continue;
             if (!shared)
-            tdp_mmu_set_spte(kvm, &iter, 0);
-        else if (tdp_mmu_set_spte_atomic(kvm, &iter, 0))
+            tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+        else if (tdp_mmu_set_spte_atomic(kvm, &iter, 
 SHADOW_NONPRESENT_VALUE))
               goto retry;
       }

  }

arch/x86/kvm/mmu/tdp_mmu.c +4 -1
@@ -928,8 +928,9 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct 
 kvm_mmu_page *sp)
       if (WARN_ON_ONCE(!is_shadow_present_pte(old_spte)))
           return false;
   -    __tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte, 0,
-               sp->gfn, sp->role.level + 1, true, true);
+    __tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
+               SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1,
+               true, true);
         return true;
   }
@@ -963,7 +964,7 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, 
 struct kvm_mmu_page *root,
               !is_last_spte(iter.old_spte, iter.level))
               continue;
   -        tdp_mmu_set_spte(kvm, &iter, 0);
+        tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
           flush = true;
       }

  @@ -1328,7 +1329,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_NONPRESENT_VALUE);
        if (!pte_write(range->pte)) {
          new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,

#97 lore raw

Re: [PATCH v10 039/108] KVM: VMX: Introduce test mode related to EPT violation VE

In reply to [email protected]
Quoted 97 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

---
  arch/x86/include/asm/vmx.h | 12 +++++++
  arch/x86/kvm/vmx/vmcs.h    |  5 +++
  arch/x86/kvm/vmx/vmx.c     | 69 +++++++++++++++++++++++++++++++++++++-
  arch/x86/kvm/vmx/vmx.h     |  6 +++-
  4 files changed, 90 insertions(+), 2 deletions(-)
arch/x86/include/asm/vmx.h +12 -0
index cdbf12c1a83c..752d53652007 100644
@@ -68,6 +68,7 @@
  #define SECONDARY_EXEC_ENCLS_EXITING		VMCS_CONTROL_BIT(ENCLS_EXITING)
  #define SECONDARY_EXEC_RDSEED_EXITING		VMCS_CONTROL_BIT(RDSEED_EXITING)
  #define SECONDARY_EXEC_ENABLE_PML               VMCS_CONTROL_BIT(PAGE_MOD_LOGGING)
+#define SECONDARY_EXEC_EPT_VIOLATION_VE		VMCS_CONTROL_BIT(EPT_VIOLATION_VE)
  #define SECONDARY_EXEC_PT_CONCEAL_VMX		VMCS_CONTROL_BIT(PT_CONCEAL_VMX)
  #define SECONDARY_EXEC_XSAVES			VMCS_CONTROL_BIT(XSAVES)
  #define SECONDARY_EXEC_MODE_BASED_EPT_EXEC	VMCS_CONTROL_BIT(MODE_BASED_EPT_EXEC)
@@ -223,6 +224,8 @@ enum vmcs_field {
  	VMREAD_BITMAP_HIGH              = 0x00002027,
  	VMWRITE_BITMAP                  = 0x00002028,
  	VMWRITE_BITMAP_HIGH             = 0x00002029,
+	VE_INFORMATION_ADDRESS		= 0x0000202A,
+	VE_INFORMATION_ADDRESS_HIGH	= 0x0000202B,
  	XSS_EXIT_BITMAP                 = 0x0000202C,
  	XSS_EXIT_BITMAP_HIGH            = 0x0000202D,
  	ENCLS_EXITING_BITMAP		= 0x0000202E,
@@ -628,4 +631,13 @@ enum vmx_l1d_flush_state {
 
  extern enum vmx_l1d_flush_state l1tf_vmx_mitigation;
 
+struct vmx_ve_information {
+	u32 exit_reason;
+	u32 delivery;
+	u64 exit_qualification;
+	u64 guest_linear_address;
+	u64 guest_physical_address;
+	u16 eptp_index;
+};
+
  #endif
arch/x86/kvm/vmx/vmcs.h +5 -0
index ac290a44a693..9277676057a7 100644
@@ -140,6 +140,11 @@ static inline bool is_nm_fault(u32 intr_info)
  	return is_exception_n(intr_info, NM_VECTOR);
  }
 
+static inline bool is_ve_fault(u32 intr_info)
+{
+	return is_exception_n(intr_info, VE_VECTOR);
+}
+
  /* Undocumented: icebp/int1 */
  static inline bool is_icebp(u32 intr_info)
  {
arch/x86/kvm/vmx/vmx.c +10 -0
index f890191e8580..dd3fde9d3c32 100644
@@ -126,6 +126,9 @@ module_param(error_on_inconsistent_vmcs_config, bool, 0444);
  static bool __read_mostly dump_invalid_vmcs = 0;
  module_param(dump_invalid_vmcs, bool, 0644);
 
+static bool __read_mostly ept_violation_ve_test;
+module_param(ept_violation_ve_test, bool, 0444);
+
  #define MSR_BITMAP_MODE_X2APIC		1
  #define MSR_BITMAP_MODE_X2APIC_APICV	2
 
@@ -783,6 +786,13 @@ void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
 
  	eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
  	     (1u << DB_VECTOR) | (1u << AC_VECTOR);
+	/*
+	 * #VE isn't used for VMX, but for TDX.  To test against unexpected
+	 * change related to #VE for VMX, intercept unexpected #VE and warn on
+	 * it.
+	 */
+	if (ept_violation_ve_test)
+		eb |= 1u << VE_VECTOR;
  	/*
  	 * Guest access to VMware backdoor ports could legitimately
  	 * trigger #GP because of TSS I/O permission bitmap.

arch/x86/kvm/vmx/vmx.c static int setup_vmcs_config(struct vmcs_config *vmcs_conf, · line 2658

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -2644,6 +2654,9 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
  					&_cpu_based_2nd_exec_control))
  			return -EIO;
  	}
+	if (!ept_violation_ve_test)
+		_cpu_based_exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE;

should be _cpu_based_2nd_exec_control

Quoted 127 lines
arch/x86/kvm/vmx/vmx.c +56 -1
+
  #ifndef CONFIG_X86_64
  	if (!(_cpu_based_2nd_exec_control &
  				SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
@@ -2668,6 +2681,7 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
  			return -EIO;
 
  		vmx_cap->ept = 0;
+		_cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE;
  	}
  	if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
  	    vmx_cap->vpid) {
@@ -4510,6 +4524,7 @@ static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
  		exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
  	if (!enable_ept) {
  		exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
+		exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE;
  		enable_unrestricted_guest = 0;
  	}
  	if (!enable_unrestricted_guest)
@@ -4637,8 +4652,40 @@ static void init_vmcs(struct vcpu_vmx *vmx)
 
  	exec_controls_set(vmx, vmx_exec_control(vmx));
 
-	if (cpu_has_secondary_exec_ctrls())
+	if (cpu_has_secondary_exec_ctrls()) {
  		secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
+		if (secondary_exec_controls_get(vmx) &
+		    SECONDARY_EXEC_EPT_VIOLATION_VE) {
+			if (!vmx->ve_info) {
+				/* ve_info must be page aligned. */
+				struct page *page;
+
+				BUILD_BUG_ON(sizeof(*vmx->ve_info) > PAGE_SIZE);
+				page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+				if (page)
+					vmx->ve_info = page_to_virt(page);
+			}
+			if (vmx->ve_info) {
+				/*
+				 * Allow #VE delivery. CPU sets this field to
+				 * 0xFFFFFFFF on #VE delivery.  Another #VE can
+				 * occur only if software clears the field.
+				 */
+				vmx->ve_info->delivery = 0;
+				vmcs_write64(VE_INFORMATION_ADDRESS,
+					     __pa(vmx->ve_info));
+			} else {
+				/*
+				 * Because SECONDARY_EXEC_EPT_VIOLATION_VE is
+				 * used only when ept_violation_ve_test is true,
+				 * it's okay to go with the bit disabled.
+				 */
+				pr_err("Failed to allocate ve_info. disabling EPT_VIOLATION_VE.\n");
+				secondary_exec_controls_clearbit(vmx,
+								 SECONDARY_EXEC_EPT_VIOLATION_VE);
+			}
+		}
+	}
 
  	if (cpu_has_tertiary_exec_ctrls())
  		tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
@@ -5118,6 +5165,12 @@ static int handle_exception_nmi(struct kvm_vcpu *vcpu)
  	if (is_invalid_opcode(intr_info))
  		return handle_ud(vcpu);
 
+	/*
+	 * #VE isn't supposed to happen.  Although vcpu can send
+	 */
+	if (KVM_BUG_ON(is_ve_fault(intr_info), vcpu->kvm))
+		return -EIO;
+
  	error_code = 0;
  	if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
  		error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
@@ -6306,6 +6359,18 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
  	if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
  		pr_err("Virtual processor ID = 0x%04x\n",
  		       vmcs_read16(VIRTUAL_PROCESSOR_ID));
+	if (secondary_exec_control & SECONDARY_EXEC_EPT_VIOLATION_VE) {
+		struct vmx_ve_information *ve_info;
+
+		pr_err("VE info address = 0x%016llx\n",
+		       vmcs_read64(VE_INFORMATION_ADDRESS));
+		ve_info = __va(vmcs_read64(VE_INFORMATION_ADDRESS));
+		pr_err("ve_info: 0x%08x 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%04x\n",
+		       ve_info->exit_reason, ve_info->delivery,
+		       ve_info->exit_qualification,
+		       ve_info->guest_linear_address,
+		       ve_info->guest_physical_address, ve_info->eptp_index);
+	}
  }
 
  /*
@@ -7302,6 +7367,8 @@ void vmx_vcpu_free(struct kvm_vcpu *vcpu)
  	free_vpid(vmx->vpid);
  	nested_vmx_free_vcpu(vcpu);
  	free_loaded_vmcs(vmx->loaded_vmcs);
+	if (vmx->ve_info)
+		free_page((unsigned long)vmx->ve_info);
  }
 
  int vmx_vcpu_create(struct kvm_vcpu *vcpu)
arch/x86/kvm/vmx/vmx.h +5 -1
index d49d0ace9fb8..1813caeb24d8 100644
@@ -359,6 +359,9 @@ struct vcpu_vmx {
  		DECLARE_BITMAP(read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
  		DECLARE_BITMAP(write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
  	} shadow_msr_intercept;
+
+	/* ve_info must be page aligned. */
+	struct vmx_ve_information *ve_info;
  };
 
  struct kvm_vmx {
@@ -570,7 +573,8 @@ static inline u8 vmx_get_rvi(void)
  	 SECONDARY_EXEC_ENABLE_VMFUNC |					\
  	 SECONDARY_EXEC_BUS_LOCK_DETECTION |				\
  	 SECONDARY_EXEC_NOTIFY_VM_EXITING |				\
-	 SECONDARY_EXEC_ENCLS_EXITING)
+	 SECONDARY_EXEC_ENCLS_EXITING |					\
+	 SECONDARY_EXEC_EPT_VIOLATION_VE)
 
  #define KVM_REQUIRED_VMX_TERTIARY_VM_EXEC_CONTROL 0
  #define KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL			\
#98 lore raw

Re: [PATCH v10 039/108] KVM: VMX: Introduce test mode related to EPT violation VE

Quoted 92 lines · Binbin Wu
Quoted 90 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

---
  arch/x86/include/asm/vmx.h | 12 +++++++
  arch/x86/kvm/vmx/vmcs.h    |  5 +++
  arch/x86/kvm/vmx/vmx.c     | 69 +++++++++++++++++++++++++++++++++++++-
  arch/x86/kvm/vmx/vmx.h     |  6 +++-
  4 files changed, 90 insertions(+), 2 deletions(-)
arch/x86/include/asm/vmx.h +12 -0
index cdbf12c1a83c..752d53652007 100644
@@ -68,6 +68,7 @@
  #define SECONDARY_EXEC_ENCLS_EXITING		VMCS_CONTROL_BIT(ENCLS_EXITING)
  #define SECONDARY_EXEC_RDSEED_EXITING		VMCS_CONTROL_BIT(RDSEED_EXITING)
  #define SECONDARY_EXEC_ENABLE_PML               VMCS_CONTROL_BIT(PAGE_MOD_LOGGING)
+#define SECONDARY_EXEC_EPT_VIOLATION_VE		VMCS_CONTROL_BIT(EPT_VIOLATION_VE)
  #define SECONDARY_EXEC_PT_CONCEAL_VMX		VMCS_CONTROL_BIT(PT_CONCEAL_VMX)
  #define SECONDARY_EXEC_XSAVES			VMCS_CONTROL_BIT(XSAVES)
  #define SECONDARY_EXEC_MODE_BASED_EPT_EXEC	VMCS_CONTROL_BIT(MODE_BASED_EPT_EXEC)
@@ -223,6 +224,8 @@ enum vmcs_field {
  	VMREAD_BITMAP_HIGH              = 0x00002027,
  	VMWRITE_BITMAP                  = 0x00002028,
  	VMWRITE_BITMAP_HIGH             = 0x00002029,
+	VE_INFORMATION_ADDRESS		= 0x0000202A,
+	VE_INFORMATION_ADDRESS_HIGH	= 0x0000202B,
  	XSS_EXIT_BITMAP                 = 0x0000202C,
  	XSS_EXIT_BITMAP_HIGH            = 0x0000202D,
  	ENCLS_EXITING_BITMAP		= 0x0000202E,
@@ -628,4 +631,13 @@ enum vmx_l1d_flush_state {
  extern enum vmx_l1d_flush_state l1tf_vmx_mitigation;
+struct vmx_ve_information {
+	u32 exit_reason;
+	u32 delivery;
+	u64 exit_qualification;
+	u64 guest_linear_address;
+	u64 guest_physical_address;
+	u16 eptp_index;
+};
+
  #endif
arch/x86/kvm/vmx/vmcs.h +5 -0
index ac290a44a693..9277676057a7 100644
@@ -140,6 +140,11 @@ static inline bool is_nm_fault(u32 intr_info)
  	return is_exception_n(intr_info, NM_VECTOR);
  }
+static inline bool is_ve_fault(u32 intr_info)
+{
+	return is_exception_n(intr_info, VE_VECTOR);
+}
+
  /* Undocumented: icebp/int1 */
  static inline bool is_icebp(u32 intr_info)
  {
arch/x86/kvm/vmx/vmx.c +10 -0
index f890191e8580..dd3fde9d3c32 100644
@@ -126,6 +126,9 @@ module_param(error_on_inconsistent_vmcs_config, bool, 0444);
  static bool __read_mostly dump_invalid_vmcs = 0;
  module_param(dump_invalid_vmcs, bool, 0644);
+static bool __read_mostly ept_violation_ve_test;
+module_param(ept_violation_ve_test, bool, 0444);
+
  #define MSR_BITMAP_MODE_X2APIC		1
  #define MSR_BITMAP_MODE_X2APIC_APICV	2
@@ -783,6 +786,13 @@ void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
  	eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
  	     (1u << DB_VECTOR) | (1u << AC_VECTOR);
+	/*
+	 * #VE isn't used for VMX, but for TDX.  To test against unexpected
+	 * change related to #VE for VMX, intercept unexpected #VE and warn on
+	 * it.
+	 */
+	if (ept_violation_ve_test)
+		eb |= 1u << VE_VECTOR;
  	/*
  	 * Guest access to VMware backdoor ports could legitimately
  	 * trigger #GP because of TSS I/O permission bitmap.
Quoted 8 lines

arch/x86/kvm/vmx/vmx.c static int setup_vmcs_config(struct vmcs_config *vmcs_conf, · line 2658

Quoted 6 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -2644,6 +2654,9 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
  					&_cpu_based_2nd_exec_control))
  			return -EIO;
  	}
+	if (!ept_violation_ve_test)
+		_cpu_based_exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE;

should be _cpu_based_2nd_exec_control

Oops, thanks.

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

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to [email protected]
Quoted 12 lines
arch/x86/kvm/vmx/tdx.c new file +11 -0
+
+#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;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+	u64 attrs_fixed1;
+	u64 xfam_fixed0;
+	u64 xfam_fixed1;
+
+	u32 nr_cpuid_configs;
+	struct tdx_cpuid_config cpuid_configs[TDX_MAX_NR_CPUID_CONFIGS];
+};
+
+/* Capabilities of KVM + the TDX module. */
+static struct tdx_capabilities tdx_caps;

I think you can introduce this tdx_capabilities in another patch.

As claimed this patch can just focus on initializing the TDX module. Whether you need this tdx_capabilities or tdx_sysinfo is enough can be done in the patch when they are really needed. It makes review easier otherwise people won't be able to tell why tdx_capabilities is needed here.

Quoted 29 lines
arch/x86/kvm/vmx/tdx.c new file +29 -0
+
+static int __init 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_enable();
+	if (ret) {
+		pr_info("Failed to initialize TDX module.\n");
+		return ret;
+	}
+
+	tdsysinfo = tdx_get_sysinfo();
+	if (tdsysinfo->num_cpuid_config > 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,

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+		.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;
+
+	pr_info("kvm: TDX is supported. x86 phys bits %d\n",
+		boot_cpu_data.x86_phys_bits);

What''s the benefit of print out x86_phys_bits? Looks a little bit weird here.

TDX host code will print out TDX private KeyID range. I think that is useful enough?

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c new file +6 -0
+
+	return 0;
+}
+
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+	int r;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	/* MOVDIR64B instruction is needed. */
+	if (!static_cpu_has(X86_FEATURE_MOVDIR64B)) {
+		pr_warn("Cannot enable TDX with MOVDIR64B supported ");
					   ^
					   without

Review

Quoted 2 lines
(quoted diff) +2 -0
+		return -ENODEV;
+	}

I think you should explain why MOVDIR64B is required, otherwise this just comes out of blue.

Btw, is this absolutely required? TDX also supports Li-mode, which doesn't have integrity check. So theoretically with Li-mode, normal zeroing is also OK but doesn't need to use MOVDIR64B.

That being said, do we have a way to tell whether TDX works in Ci or Li mode?

#31 lore raw

Re: [PATCH v10 015/108] x86/cpu: Add helper functions to allocate/free TDX private host key id

In reply to [email protected]
Quoted 4 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX private host key id is assigned to guest TD. The memory controller encrypts guest TD memory with the assigned TDX private host key id (HIKD).

								     ^
								     HKID.

And since you already mentioned in the first sentence, you can put (HKID) part there. And I think you can just use HKID in the rest places to save some typing as this is the purpose of using (HKID) I suppose.

[...]

Quoted 11 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+/* 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,

arch/x86/virt/vmx/tdx/tdx.c static void __init clear_tdx(void) · line 136

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+			       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;

Double check of keyid == 0.

I think you can just use:

	if (keyid <= tdx_keyid_start)
		return;

And/or add a WARN() as it's a bug if above happens.

Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+
+	ida_free(&tdx_keyid_pool, keyid);
+}
+EXPORT_SYMBOL_GPL(tdx_keyid_free);
+
 static void __init tdx_memory_destroy(void)
 {
 	while (!list_empty(&tdx_memlist)) {
#70 lore raw

Re: [PATCH v10 031/108] KVM: x86/mmu: Replace hardcoded value 0 for the initial value for SPTE

In reply to [email protected]
Quoted 4 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware doesn't use this bit; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

Hi Isaku,

"AMD hardware doesn't use this bit" is wrong:

https://lore.kernel.org/lkml/[email protected]/T/#m5ed59404da43677e99ac51dd1360dc22b964bcbb

#122 lore raw

Re: [PATCH v10 049/108] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to [email protected]
Quoted 6 lines · On 2022/10/30 14:22, [email protected] wrote:

From: Isaku Yamahata<[email protected]>

Allocate protected page table for private page table, and add hooks to operate on protected page table. This patch adds allocation/free of protected page tables and hooks. When calling hooks to update SPTE entry, freeze the entry, call hooks and unfree

unfreeze

Quoted 7 lines

the entry to allow concurrent
updates on page tables. Which is the advantage of TDP MMU. As kvm_gfn_shared_mask() returns false always, those hooks aren't called yet with this patch.

When the faulting GPA is private, the KVM fault is called private. When resolving private KVM,

private KVM fault?

Quoted 84 lines

allocate protected page table and call hooks to
operate on protected page table. On the change of the private PTE entry, invoke kvm_x86_ops hook in __handle_changed_spte() to propagate the change to protected page table. The following depicts the relationship.

   private KVM page fault   |
       |                    |
       V                    |
  private GPA               |     CPU protected EPTP
       |                    |           |
       V                    |           V
  private PT root           |     protected PT root
       |                    |           |
       V                    |           V

private PT --hook to propagate-->protected PT
| | |
\--------------------+------\ |
| | |
| V V
| private guest page
|
|
non-encrypted memory | encrypted memory
|
PT: page table

The existing KVM TDP MMU code uses atomic update of SPTE. On populating the EPT entry, atomically set the entry. However, it requires TLB shootdown to zap SPTE. To address it, the entry is frozen with the special SPTE value that clears the present bit. After the TLB shootdown, the entry is set to the eventual value (unfreeze).

For protected page table, hooks are called to update protected page table in addition to direct access to the private SPTE. For the zapping case, it works to freeze the SPTE. It can call hooks in addition to TLB shootdown. For populating the private SPTE entry, there can be a race condition without further protection

vcpu 1: populating 2M private SPTE
vcpu 2: populating 4K private SPTE
vcpu 2: TDX SEAMCALL to update 4K protected SPTE => error vcpu 1: TDX SEAMCALL to update 2M protected SPTE

To avoid the race, the frozen SPTE is utilized. Instead of atomic update of the private entry, freeze the entry, call the hook that update protected SPTE, set the entry to the final value.

Support 4K page only at this stage. 2M page support can be done in future patches.

---
  arch/x86/include/asm/kvm-x86-ops.h |   5 +
  arch/x86/include/asm/kvm_host.h    |  11 ++
  arch/x86/kvm/mmu/mmu.c             |  15 +-
  arch/x86/kvm/mmu/mmu_internal.h    |  32 ++++
  arch/x86/kvm/mmu/tdp_iter.h        |   2 +-
  arch/x86/kvm/mmu/tdp_mmu.c         | 244 +++++++++++++++++++++++++----
  arch/x86/kvm/mmu/tdp_mmu.h         |   2 +-
  virt/kvm/kvm_main.c                |   1 +
  8 files changed, 280 insertions(+), 32 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +5 -0
index f28c9fd72ac4..1b01dc2098b0 100644
@@ -94,6 +94,11 @@ KVM_X86_OP_OPTIONAL_RET0(set_tss_addr)
  KVM_X86_OP_OPTIONAL_RET0(set_identity_map_addr)
  KVM_X86_OP_OPTIONAL_RET0(get_mt_mask)
  KVM_X86_OP(load_mmu_pgd)
+KVM_X86_OP_OPTIONAL(link_private_spt)
+KVM_X86_OP_OPTIONAL(free_private_spt)
+KVM_X86_OP_OPTIONAL(set_private_spte)
+KVM_X86_OP_OPTIONAL(remove_private_spte)
+KVM_X86_OP_OPTIONAL(zap_private_spte)
  KVM_X86_OP(has_wbinvd_exit)
  KVM_X86_OP(get_l2_tsc_offset)
  KVM_X86_OP(get_l2_tsc_multiplier)
@@ -509,9 +524,81 @@ static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared)
  		WARN_ON_ONCE(ret);
  	}

arch/x86/include/asm/kvm-x86-ops.h static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared) · line 535

Quoted 10 lines
arch/x86/include/asm/kvm-x86-ops.h +9 -0
 
+	if (is_private_sp(sp) &&
+	    WARN_ON(static_call(kvm_x86_free_private_spt)(kvm, sp->gfn, sp->role.level,
+							  kvm_mmu_private_spt(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_spt(sp, NULL);

Do you think is it better to add some statistics for the intentinal leakage?

Quoted 6 lines
arch/x86/include/asm/kvm-x86-ops.h +2 -0
+	}
+
  	call_rcu(&sp->rcu_head, tdp_mmu_free_sp_rcu_callback);
  }
 
 pu, until a matching vcpu_put()
#7 lore raw

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Huang, Kai
Quoted 11 lines · Kai

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

Quoted 11 lines
arch/x86/kvm/vmx/tdx.c new file +11 -0
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	int r;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	/* MOVDIR64B instruction is needed. */
+	if (!static_cpu_has(X86_FEATURE_MOVDIR64B)) {

Nit unrelated to Kai's comments: use boot_cpu_has(), not static_cpu_has(). This is run-once code that's not a hot path so there's zero reason to trigger patching.

Quoted 17 lines

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

Quoted 1 line
arch/x86/kvm/vmx/tdx.c new file +1 -0
+		pr_warn("Cannot enable TDX with MOVDIR64B supported ");
					   ^
					   without

Review

Quoted 2 lines
(quoted diff) +2 -0
+		return -ENODEV;
+	}

I think you should explain why MOVDIR64B is required, otherwise this just comes out of blue.

Btw, is this absolutely required? TDX also supports Li-mode, which doesn't have integrity check. So theoretically with Li-mode, normal zeroing is also OK but doesn't need to use MOVDIR64B.

That being said, do we have a way to tell whether TDX works in Ci or Li mode?

#76 lore raw

Re: [PATCH v10 033/108] KVM: x86/mmu: Allow non-zero value for non-present SPTE and removed SPTE

In reply to [email protected]
Quoted 6 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

For TD guest, the current way to emulate MMIO doesn't work any more, as KVM is not able to access the private memory of TD guest and do the emulation. Instead, TD guest expects to receive #VE when it accesses the MMIO and then it can explicitly makes hypercall to KVM to get the expected information.

		    ^
		    make
Quoted 11 lines

To achieve this, the TDX module always enables "EPT-violation #VE" in the VMCS control. And accordingly, KVM needs to configure the MMIO spte to trigger EPT violation (instead of misconfiguration) and at the same time, also clear the "suppress #VE" bit so the TD guest can get the #VE instead of causing actual EPT violation to KVM.

In order for KVM to be able to have chance to set up the correct SPTE for MMIO for TD guest, the default non-present SPTE must have the "suppress guest accesses the MMIO.

The above sentence is broken.

Quoted 38 lines

Also, when TD guest accesses the actual shared
memory, it should continue to trigger EPT violation to the KVM instead of receiving the #VE (the TDX module guarantees KVM will receive EPT violation for private memory access). This means for the shared memory, the SPTE also must have the "suppress #VE" bit set for the non-present SPTE.

Add "suppress VE" bit (bit 63) to SHADOW_NONPRESENT_VALUE and REMOVED_SPTE. Unconditionally set the "suppress #VE" bit (which is bit 63) for both AMD and Intel as: 1) AMD hardware doesn't use this bit when present bit is off;
2) for normal VMX guest, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

---
 arch/x86/include/asm/vmx.h |  1 +
 arch/x86/kvm/mmu/spte.c    |  4 +++-
 arch/x86/kvm/mmu/spte.h    | 22 +++++++++++++++++++++-
 arch/x86/kvm/mmu/tdp_mmu.c |  8 ++++++++
 4 files changed, 33 insertions(+), 2 deletions(-)
arch/x86/include/asm/vmx.h +1 -0
index 498dc600bd5c..cdbf12c1a83c 100644
@@ -511,6 +511,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/spte.c +0 -0
index 2e08b2a45361..0b97a045c5f0 100644

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only) · line 424

Quoted 7 lines
arch/x86/kvm/mmu/spte.c +3 -1
@@ -419,7 +419,9 @@ void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only)
 	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;
+	/* VMX_EPT_SUPPRESS_VE_BIT is needed for W or X violation. */
+	shadow_present_mask	=
+		(has_exec_only ? 0ull : VMX_EPT_READABLE_MASK) | VMX_EPT_SUPPRESS_VE_BIT;

I think this chunk can be in a separate patch since it doesn't handle fault from non-present to present, which is claimed by the patch title and changelog.

Or I think you need to describe handling W or X fault part in the changelog.

arch/x86/kvm/mmu/spte.h static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11); · line 152

Quoted 13 lines
arch/x86/kvm/mmu/spte.c +0 -0
 	/*
 	 * EPT overrides the host MTRRs, and so KVM must program the desired
 	 * memtype directly into the SPTEs.  Note, this mask is just the mask
arch/x86/kvm/mmu/spte.h +2 -0
index 42ecaa75da15..7e0f79e8f45b 100644
@@ -148,7 +148,22 @@ static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11);
 
 #define MMIO_SPTE_GEN_MASK		GENMASK_ULL(MMIO_SPTE_GEN_LOW_BITS + MMIO_SPTE_GEN_HIGH_BITS - 1, 0)
 
+/*
+ * non-present SPTE value for both VMX and SVM for TDP MMU.
      ^
      Non-present

arch/x86/kvm/mmu/spte.h static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11); · line 157

Quoted 5 lines
arch/x86/kvm/mmu/spte.h +5 -0
+ * For SVM NPT, for non-present spte (bit 0 = 0), other bits are ignored.
+ * For VMX EPT, bit 63 is ignored if #VE is disabled. (EPT_VIOLATION_VE=0)
+ *              bit 63 is #VE suppress if #VE is enabled. (EPT_VIOLATION_VE=1)
+ * For TDX:
+ *   Secure-EPT: TDX module sets EPT_VIOLATION_VE for Secure-EPT

"EPT-violation #VE" is a VMCS control, so it applies to both Secure-EPT and shared-EPT. Looks "for Secure-EPT" is a little bit confusing.

arch/x86/kvm/mmu/spte.h static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11); · line 158

Quoted 1 line
arch/x86/kvm/mmu/spte.h +1 -0
+ *   private EPT: "suppress #VE" bit is ignored.  CPU doesn't walk it.

Looks "private EPT" just comes out of blue. I am not sure whether you need to mention it here.

Quoted 12 lines
arch/x86/kvm/mmu/spte.h +7 -0
+ *   conventional EPT: "suppress #VE" bit must be set to get EPT violation
+ */
+#ifdef CONFIG_X86_64
+#define SHADOW_NONPRESENT_VALUE	BIT_ULL(63)
+static_assert(!(SHADOW_NONPRESENT_VALUE & SPTE_MMU_PRESENT_MASK));
+#else
 #define SHADOW_NONPRESENT_VALUE	0ULL
+#endif
 
 extern u64 __read_mostly shadow_host_writable_mask;
 extern u64 __read_mostly shadow_mmu_writable_mask;

arch/x86/kvm/mmu/spte.h extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask; · line 211

Quoted 8 lines
arch/x86/kvm/mmu/spte.h +5 -0
@@ -189,13 +204,18 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  * non-present intermediate value. Other threads which encounter this value
  * should not modify the SPTE.
  *
+ * For X86_64 case, SHADOW_NONPRESENT_VALUE, "suppress #VE" bit, is set because
+ * "EPT violation #VE" in the secondary VM execution control may be enabled.
+ * Because TDX module sets "EPT violation #VE" for TD, "suppress #VE" bit for
+ * the conventional EPT needs to be set.
+ *

This comment looks duplicated with the above one. Not sure whether needed.

Quoted 20 lines
arch/x86/kvm/mmu/spte.h +1 -1
  * 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
  * vulnerability.  Use only low bits to avoid 64-bit immediates.
  *
  * Only used by the TDP MMU.
  */
-#define REMOVED_SPTE	0x5a0ULL
+#define REMOVED_SPTE	(SHADOW_NONPRESENT_VALUE | 0x5a0ULL)
 
 /* Removed SPTEs must not be misconstrued as shadow present PTEs. */
 static_assert(!(REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
arch/x86/kvm/mmu/tdp_mmu.c +1 -0
index 38bc4c2f0f1f..1eee9c159958 100644
@@ -693,6 +693,14 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
 	 * overwrite the special removed SPTE value. No bookkeeping is needed
 	 * here since the SPTE is going from non-present to non-present.  Use
 	 * the raw write helper to avoid an unnecessary check on volatile bits.
+	 *

arch/x86/kvm/mmu/tdp_mmu.c static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm, · line 706

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -0
+	 * Set non-present value to SHADOW_NONPRESENT_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_NONPRESENT_VALUE (which sets "suppress #VE" bit) so it
+	 * can be set when EPT table entries are zapped.
 	 */
 	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
 

Ditto.

#73 lore raw

Re: [PATCH v10 032/108] KVM: x86/mmu: Make sync_page not use hard-coded 0 as the initial SPTE value

In reply to [email protected]
Quoted 16 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

FNAME(sync_page) in arch/x86/kvm/mmu/paging_tmpl.h assumes that the initial shadow page table entry (SPTE) is zero. Remove the assumption by using SHADOW_NONPRESENT_VALUE that will be updated from 0 to non-zero value.

---
 arch/x86/kvm/mmu/paging_tmpl.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/paging_tmpl.h +0 -0
index 5ab5f94dcb6f..6db3f2b5563a 100644

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

Quoted 9 lines
arch/x86/kvm/mmu/paging_tmpl.h +2 -1
@@ -1036,7 +1036,8 @@ static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 		gpa_t pte_gpa;
 		gfn_t gfn;
 
-		if (!sp->spt[i])
+		/* spt[i] has initial value of shadow page table allocation */
+		if (sp->spt[i] == SHADOW_NONPRESENT_VALUE)
 			continue;
 
 		pte_gpa = first_pte_gpa + i * sizeof(pt_element_t);

I think this patch can be merged to previous one? Looks there's no good reason to keep it as standalone.

#79 lore raw

Re: [PATCH v10 034/108] KVM: x86/mmu: Add Suppress VE bit to shadow_mmio_{value, mask}

In reply to [email protected]
Quoted 6 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Because TDX will need shadow_mmio_mask to be VMX_SUPPRESS_VE | RWX shadow_mmio_value to be 0, make VMX EPT case use same value for TDX shadow_mmio_mask.

TDX need to use different mmio_mask/value doesn't mean they need to be changed for VMX guest. I think the true purpose here is to still be able to use a global shadow_mmio_mask for both TDX and VMX guests. So please explicitly call out.

Quoted 3 lines

For VMX, VMX_SUPPRESS_VE doesn't matter, it doesn't
affect VMX logic to add the bit to shadow_mmio_{value, mask}. Note that shadow_mmio_value will be per-VM value.

Not sure why the last sentence matters.

Quoted 11 lines
---
 arch/x86/kvm/mmu/spte.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/kvm/mmu/spte.c +0 -0
index 0b97a045c5f0..5d5c06d4fd89 100644

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only) · line 440

Quoted 6 lines
arch/x86/kvm/mmu/spte.c +1 -2
@@ -437,8 +437,8 @@ void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only)
 	 * 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);
+	kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE | VMX_EPT_SUPPRESS_VE_BIT,

Is "suppress #VE" bit required for mmio_value for VMX guest? Why adding it?

Quoted 4 lines
arch/x86/kvm/mmu/spte.c +1 -0
+				   VMX_EPT_RWX_MASK | VMX_EPT_SUPPRESS_VE_BIT, 0);
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_ept_masks);
 
#83 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

In reply to [email protected]
Quoted 8 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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 instead of global variables. By using the per-VM EPT entry value for MMIO, the existing VMX logic is kept working. To untangle the logic to initialize shadow_mmio_access_mask, introduce a separate setter function.

It's weird to mention "shadow_mmio_access_mask" here (and this doesn't stand anymore anyway as we have changed to only make mmio_value per-vm). Just say something like "introduce a setter function to set mmio_value for the given guest so that TDX guest can override later".

Also, seems it's worth to mention the same mmio_mask is used for both TDX guest and VMX guest so we can still use global shadow_mmio_mask.

[...]

arch/x86/kvm/mmu/spte.c u64 mark_spte_for_access_track(u64 spte) · line 356

Quoted 5 lines

void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask) {

arch/x86/kvm/mmu/spte.c +1 -0
 	BUG_ON((u64)(unsigned)access_mask != access_mask);
+
 	WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);

Looks unnecessary change.

#93 lore raw

Re: [PATCH v10 036/108] KVM: TDX: Enable mmio spte caching always for TDX

In reply to [email protected]
Quoted 32 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX needs to set shared spte for MMIO GFN to !SUPPRES_VE_BIT | !RWX so that guest TD can get #VE and then issue TDG.VP.VMCALL<MMIO>. Enable mmio caching always for TDX irrelevant the module parameter enable_mmio_caching.

---
 arch/x86/kvm/mmu/mmu.c     | 3 ++-
 arch/x86/kvm/mmu/spte.h    | 2 +-
 arch/x86/kvm/mmu/tdp_mmu.c | 7 +++++++
 3 files changed, 10 insertions(+), 2 deletions(-)
arch/x86/kvm/mmu/mmu.c +2 -1
index 0d3fa29ccccc..9098f77cdaa4 100644
@@ -3229,7 +3229,8 @@ static int handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fau
 		 * and only if L1's MAXPHYADDR is inaccurate with respect to
 		 * the hardware's).
 		 */
-		if (unlikely(!enable_mmio_caching) ||
+		if (unlikely(!enable_mmio_caching &&
+			     !kvm_gfn_shared_mask(vcpu->kvm)) ||
 		    unlikely(fault->gfn > kvm_mmu_max_gfn()))
 			return RET_PF_EMULATE;
 	}
arch/x86/kvm/mmu/spte.h +0 -0
index 82f0d5c08b77..fecfdcb5f321 100644

arch/x86/kvm/mmu/spte.h extern u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask; · line 248

Quoted 6 lines
arch/x86/kvm/mmu/spte.h +1 -1
@@ -244,7 +244,7 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
 static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)
 {
 	return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
-	       likely(enable_mmio_caching);
+	       likely(enable_mmio_caching || kvm_gfn_shared_mask(kvm));
 }

Sean suggested we can change to treat "mmio_value == 0" also as MMIO caching being enabled:

https://lore.kernel.org/lkml/[email protected]/

Quoted 7 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 +0 -0
index e07f14351d14..3325633b1cb5 100644

arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, · line 1884

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -0
@@ -1875,6 +1875,13 @@ int kvm_tdp_mmu_get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes,
 
 	*root_level = vcpu->arch.mmu->root_role.level;
 
+	/*
+	 * mmio page fault isn't supported for protected guest because
+	 * instructions in protected guest memory can't be parsed by VMM.
+	 */
+	if (WARN_ON_ONCE(kvm_gfn_shared_mask(vcpu->kvm)))
+		return leaf;
+

It's weird to put this here.

I think the logic is, for TDX guest (or similar protected guests), handle_mmio_page_fault() should not be reached at all. So I think we can just add a WARN() against kvm_gfn_shared_mask(), or is_tdx_vm() at the very beginning of handle_mmio_page_fault()?

Quoted 3 lines
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
 	tdp_mmu_for_each_pte(iter, mmu, gfn, gfn + 1) {
 		leaf = iter.level;
 		sptes[leaf] = iter.old_spte;
#147 lore raw

Re: [PATCH v10 060/108] KVM: Add functions to set GFN to private or shared

In reply to [email protected]
Quoted 100 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX KVM support needs to track whether GFN is private or shared. Introduce functions to set whether GFN is private or shared and pre-allocate memory for xarray.

---
  include/linux/kvm_host.h | 11 ++++++
  virt/kvm/kvm_main.c      | 74 ++++++++++++++++++++++++++++++++++++++++
  2 files changed, 85 insertions(+)
include/linux/kvm_host.h +11 -0
index a0b64308d240..fac07886ab39 100644
@@ -2307,9 +2307,20 @@ static inline void kvm_account_pgtable_pages(void *virt, int nr)
  #define KVM_MEM_ATTR_PRIVATE	0x0002
 
  #ifdef __KVM_HAVE_ARCH_UPDATE_MEM_ATTR
+/* memory attr on [start, end) */
+int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end);
+int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end);
  void kvm_arch_update_mem_attr(struct kvm *kvm, struct kvm_memory_slot *slot,
  			      unsigned int attr, gfn_t start, gfn_t end);
  #else
+static inline int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	return -EOPNOTSUPP;
+}
+static inline int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end)
+{
+	return -EOPNOTSUPP;
+}
  static inline void kvm_arch_update_mem_attr(struct kvm *kvm,
  					    struct kvm_memory_slot *slot,
  					    unsigned int attr,
virt/kvm/kvm_main.c +54 -0
index 9f82b03a8118..f0e77b65939b 100644
@@ -1121,6 +1121,80 @@ static inline void kvm_restrictedmem_unregister(struct kvm_memory_slot *slot)
  					  &slot->notifier);
  }
 
+/*
+ * Reserve memory for [start, end) so that the next set oepration won't fail
+ * with -ENOMEM.
+ */
+int kvm_vm_reserve_mem_attr(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	int r = 0;
+	gfn_t gfn;
+
+	xa_lock(&kvm->mem_attr_array);
+	for (gfn = start; gfn < end; gfn++) {
+		r = __xa_insert(&kvm->mem_attr_array, gfn, NULL, GFP_KERNEL_ACCOUNT);
+		if (r == -EBUSY)
+			r = 0;
+		if (r)
+			break;
+	}
+	xa_unlock(&kvm->mem_attr_array);
+
+	return r;
+}
+EXPORT_SYMBOL_GPL(kvm_vm_reserve_mem_attr);
+
+/* Set memory attr for [start, end) */
+int kvm_vm_set_mem_attr(struct kvm *kvm, int attr, gfn_t start, gfn_t end)
+{
+	void *entry;
+	gfn_t gfn;
+	int r;
+	int i;
+
+	/* By default, the entry is private. */
+	switch (attr) {
+	case KVM_MEM_ATTR_PRIVATE:
+		entry = NULL;
+		break;
+	case KVM_MEM_ATTR_SHARED:
+		entry = xa_mk_value(KVM_MEM_ATTR_SHARED);
+		break;
+	default:
+		WARN_ON_ONCE(1);
+		return -EINVAL;
+	}
+
+	WARN_ON_ONCE(start >= end);
+	for (gfn = start; gfn < end; gfn++) {
+		r = xa_err(xa_store(&kvm->mem_attr_array, gfn, entry,
+				    GFP_KERNEL_ACCOUNT));
+		if (r)
+			break;
+	}
+	if (start >= gfn)
+		return r;
+

virt/kvm/kvm_main.c static inline void kvm_restrictedmem_unregister(struct kvm_memory_slot *slot) · line 1187

Quoted 10 lines
virt/kvm/kvm_main.c +10 -0
+	end = gfn;
+	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
+		struct kvm_memslot_iter iter;
+		struct kvm_memory_slot *slot;
+		struct kvm_memslots *slots;
+
+		slots = __kvm_memslots(kvm, i);
+		kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
+			gfn_t s = max(start, slot->base_gfn);
+			gfn_t e = min(end, slot->base_gfn + slot->npages);

slot is not inited.

Quoted 13 lines
virt/kvm/kvm_main.c +10 -0
+
+			WARN_ON_ONCE(s >= e);
+			kvm_arch_update_mem_attr(kvm, slot, attr, s, e);
+		}
+	}
+
+	return r;
+}
+EXPORT_SYMBOL_GPL(kvm_vm_set_mem_attr);
+
  #else /* !CONFIG_HAVE_KVM_RESTRICTED_MEM */
 
  static inline void kvm_restrictedmem_register(struct kvm_memory_slot *slot)
#150 lore raw

Re: [PATCH v10 062/108] KVM: x86/tdp_mmu: implement MapGPA hypercall for TDX

In reply to [email protected]
Quoted 62 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The TDX Guest-Hypervisor communication interface(GHCI) specification defines MapGPA hypercall for guest TD to request the host VMM to map given GPA range as private or shared.

It means the guest TD uses the GPA as shared (or private). The GPA won't be used as private (or shared). VMM should enforce GPA usage. VMM doesn't have to map the GPA on the hypercall request.

- Zap the aliased region.
If shared (or private) GPA is requested, zap private (or shared) GPA (modulo shared bit).
- Record the request GPA is shared (or private) by kvm.mem_attr_array.
- Don't map GPA. The GPA is mapped on the next EPT violation.

---
  arch/x86/kvm/mmu.h         |  5 ++++
  arch/x86/kvm/mmu/mmu.c     | 60 ++++++++++++++++++++++++++++++++++++++
  arch/x86/kvm/mmu/tdp_mmu.c | 35 ++++++++++++++++++++++
  arch/x86/kvm/mmu/tdp_mmu.h |  3 ++
  4 files changed, 103 insertions(+)
arch/x86/kvm/mmu.h +5 -0
index e2a0dfbee56d..e1641fa5a862 100644
@@ -219,6 +219,11 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
 
  int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu);
 
+int __kvm_mmu_map_gpa(struct kvm *kvm, gfn_t *startp, gfn_t end,
+		      bool map_private);
+int kvm_mmu_map_gpa(struct kvm_vcpu *vcpu, gfn_t *startp, gfn_t end,
+		    bool map_private);
+
  int kvm_mmu_post_init_vm(struct kvm *kvm);
  void kvm_mmu_pre_destroy_vm(struct kvm *kvm);
 
arch/x86/kvm/mmu/mmu.c +14 -0
index 168c84c99de3..37b378bf60df 100644
@@ -6778,6 +6778,66 @@ void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
  	}
  }
 
+int __kvm_mmu_map_gpa(struct kvm *kvm, gfn_t *startp, gfn_t end,
+		      bool map_private)
+{
+	gfn_t start = *startp;
+	int attr;
+	int ret;
+
+	if (!kvm_gfn_shared_mask(kvm))
+		return -EOPNOTSUPP;
+
+	attr = map_private ? KVM_MEM_ATTR_PRIVATE : KVM_MEM_ATTR_SHARED;
+	start = start & ~kvm_gfn_shared_mask(kvm);
+	end = end & ~kvm_gfn_shared_mask(kvm);
+

arch/x86/kvm/mmu/mmu.c void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen) · line 6804

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	/*
+	 * To make the following kvm_vm_set_mem_attr() success within spinlock
+	 * without memory allocation.
+	 */
+	ret = kvm_vm_reserve_mem_attr(kvm, start, end);
+	if (ret)
+		return ret;
+
+	write_lock(&kvm->mmu_lock);
+	if (is_tdp_mmu_enabled(kvm)) {

How about moving the condition test to the beginning of the function to make the code simpler?

Quoted 90 lines
arch/x86/kvm/mmu/mmu.c +36 -0
+		gfn_t s = start;
+
+		ret = kvm_tdp_mmu_map_gpa(kvm, &s, end, map_private);
+		if (!ret) {
+			KVM_BUG_ON(kvm_vm_set_mem_attr(kvm, attr, start, end), kvm);
+		} else if (ret == -EAGAIN) {
+			KVM_BUG_ON(kvm_vm_set_mem_attr(kvm, attr, start, s), kvm);
+			start = s;
+		}
+	} else {
+		ret = -EOPNOTSUPP;
+	}
+	write_unlock(&kvm->mmu_lock);
+
+	if (ret == -EAGAIN) {
+		if (map_private)
+			*startp = kvm_gfn_private(kvm, start);
+		else
+			*startp = kvm_gfn_shared(kvm, start);
+	}
+	return ret;
+}
+EXPORT_SYMBOL_GPL(__kvm_mmu_map_gpa);
+
+int kvm_mmu_map_gpa(struct kvm_vcpu *vcpu, gfn_t *startp, gfn_t end,
+		    bool map_private)
+{
+	struct kvm_mmu *mmu = vcpu->arch.mmu;
+
+	if (!VALID_PAGE(mmu->root.hpa) || !VALID_PAGE(mmu->private_root_hpa))
+		return -EINVAL;
+
+	return __kvm_mmu_map_gpa(vcpu->kvm, startp, end, map_private);
+}
+EXPORT_SYMBOL_GPL(kvm_mmu_map_gpa);
+
  static unsigned long
  mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  {
arch/x86/kvm/mmu/tdp_mmu.c +35 -0
index 4b207ce83ffe..d3bab382ceaa 100644
@@ -2156,6 +2156,41 @@ bool kvm_tdp_mmu_write_protect_gfn(struct kvm *kvm,
  	return spte_set;
  }
 
+int kvm_tdp_mmu_map_gpa(struct kvm *kvm,
+			gfn_t *startp, gfn_t end, bool map_private)
+{
+	struct kvm_mmu_page *root;
+	gfn_t start = *startp;
+	bool flush = false;
+	int i;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+	KVM_BUG_ON(start & kvm_gfn_shared_mask(kvm), kvm);
+	KVM_BUG_ON(end & kvm_gfn_shared_mask(kvm), kvm);
+
+	kvm_mmu_invalidate_begin(kvm, start, end);
+	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
+		for_each_tdp_mmu_root_yield_safe(kvm, root, i) {
+			if (is_private_sp(root) == map_private)
+				continue;
+
+			/*
+			 * TODO: If necessary, return to the caller with -EAGAIN
+			 * instead of yield-and-resume within
+			 * tdp_mmu_zap_leafs().
+			 */
+			flush = tdp_mmu_zap_leafs(kvm, root, start, end,
+						  /*can_yield=*/true, flush,
+						  /*zap_private=*/is_private_sp(root));
+		}
+	}
+	if (flush)
+		kvm_flush_remote_tlbs_with_address(kvm, start, end - start);
+	kvm_mmu_invalidate_end(kvm, start, end);
+
+	return 0;
+}
+
  /*
   * Return the level of the lowest level SPTE added to sptes.
   * That SPTE may be non-present.
arch/x86/kvm/mmu/tdp_mmu.h +0 -0
index 695175c921a5..cb13bc1c3679 100644

arch/x86/kvm/mmu/tdp_mmu.h void kvm_tdp_mmu_try_split_huge_pages(struct kvm *kvm, · line 55

Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.h +2 -0
@@ -51,6 +51,9 @@ void kvm_tdp_mmu_try_split_huge_pages(struct kvm *kvm,
  				      gfn_t start, gfn_t end,
  				      int target_level, bool shared);
 
+int kvm_tdp_mmu_map_gpa(struct kvm *kvm,
+			gfn_t *startp, gfn_t end, bool map_private);

Sugguest to add some description about the function to avoid confusion, since the function name is quite generic but the usage is highly related to TDX.

Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.h +1 -0
+
  static inline void kvm_tdp_mmu_walk_lockless_begin(void)
  {
  	rcu_read_lock();
#34 lore raw

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to [email protected]
Quoted 9 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:
Quoted 9 lines

From: Sean Christopherson <[email protected]>

As the first step to create TDX guest, create/destroy VM struct. Assign TDX private 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.

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

				 ^
				 HKID

It's better to use consistent words throughout patch/series I guess.

Quoted 6 lines
Quoted 6 lines

flush_shadow_all_private callback before tearing down private page tables for it.

Add a second kvm_x86_ops hook in kvm_arch_destroy_vm() 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.

Perhaps explicitly call out the hook is vm_free() and why the existing vm_destroy() hook cannot meet TDX's purpose, so that people can understand easily why you need vm_free().

[...]

Quoted 4 lines

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
+{
+	tdx_keyid_free(kvm_tdx->hkid);
+	kvm_tdx->hkid = -1;

Why -1? Can it be set to 0, which is the initial value when kvm_tdx is allocated anyway?

Quoted 12 lines
Quoted 12 lines
arch/x86/kvm/vmx/tdx.c +12 -0
+}
+
+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;
+
Quoted 8 lines

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+	/*
+	 * Zeroing the page is only necessary for systems with MKTME-i:
+	 * 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.
+	 *
+	 * The cache line could be poisoned (even without MKTME-i), clear the
+	 * poison bit.

Does this happen only when there's potential kernel bug?

Quoted 73 lines
Quoted 73 lines
arch/x86/kvm/vmx/tdx.c +73 -0
+	 */
+	for (i = 0; i < PAGE_SIZE; i += 64)
+		movdir64b((void *)(page + i), zero_page);
+	/*
+	 * MOVDIR64B store uses WC buffer.  Prevent following memory reads
+	 * from seeing potentially poisoned cache.
+	 */
+	__mb();
+}
+
+static int tdx_reclaim_page(unsigned long va, hpa_t pa, bool do_wb, u16 hkid)
+{
+	struct tdx_module_output out;
+	u64 err;
+
+	do {
+		err = tdh_phymem_page_reclaim(pa, &out);
+		/*
+		 * TDH.PHYMEM.PAGE.RECLAIM is allowed only when TD is shutdown.
+		 * state.  i.e. destructing TD.
+		 * TDH.PHYMEM.PAGE.RECLAIM  requires TDR and target page.
+		 * Because we're destructing TD, it's rare to contend with TDR.
+		 */
+	} while (err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_RCX));
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
+		return -EIO;
+	}
+
+	if (do_wb) {
+		/*
+		 * Only TDR page gets into this path.  No contention is expected
+		 * because the last page of TD.
+		 */
+		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_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 inline 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) {
+		/*
+		 * TDCX are being reclaimed.  TDX module maps TDCX with HKID
+		 * assigned to the TD.  Here the cache associated to the TD
+		 * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+		 * cache doesn't need to be flushed again.
+		 */
+		if (tdx_reclaim_page(page->va, page->pa, false, 0))
+			return;
+
Quoted 8 lines

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+		page->added = false;
+	}
+	if (page->va) {
+		free_page(page->va);
+		page->va = 0;
+	}
+}
+

I am wondering why this 'struct tdx_td_page' is needed?

It appears the page->pa is used by SEAMCALLs and page->va is used by tdx_clear_page() as MOVDIR64B needs a virtual address.

But since GFP_KERNEL_ACCOUNT is used in memory allocation, so you can actually just get the pa and va from the page easily (using page_to_phys() and __va()). Also it's 64-bit kernel so you don't even need to consider HIGHMEM.

Also, it seems page->added can be replaced with simply checking whether page is NULL, correct?

Btw, I think the introduce of 'struct tdx_td_page' and the new 'struct tdx_td_page tdr' to 'struct kvm_tdx' should come together with this patch, but not in the previous patch "KVM: TDX: Stub in tdx.h with structs, accessors, and VMCS helpers". This makes the code review easier.

The "accessors" can be introduced in later patch when they are needed -- it doesn't seem any of them is used in this patch?

#29 lore raw

Re: [PATCH v10 014/108] KVM: TDX: Stub in tdx.h with structs, accessors, and VMCS helpers

In reply to [email protected]
Quoted 34 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Stub in kvm_tdx, vcpu_tdx, and their various accessors. TDX defines SEAMCALL APIs to access TDX control structures corresponding to the VMX VMCS. Introduce helper accessors to hide its SEAMCALL ABI details.

---
 arch/x86/kvm/vmx/tdx.h | 118 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 116 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/tdx.h +11 -1
index 473013265bd8..98999bf3f188 100644
@@ -3,14 +3,27 @@
 #define __KVM_X86_TDX_H
 
 #ifdef CONFIG_INTEL_TDX_HOST
+
+#include "tdx_ops.h"
+
+struct tdx_td_page {
+	unsigned long va;
+	hpa_t pa;
+	bool added;
+};
+
 struct kvm_tdx {
 	struct kvm kvm;
-	/* TDX specific members follow. */
+
+	struct tdx_td_page tdr;

arch/x86/kvm/vmx/tdx.h line 27

Quoted 10 lines
arch/x86/kvm/vmx/tdx.h +4 -1
+	struct tdx_td_page *tdcs;
 };
 
 struct vcpu_tdx {
 	struct kvm_vcpu	vcpu;
-	/* TDX specific members follow. */
+
+	struct tdx_td_page tdvpr;
+	struct tdx_td_page *tdvpx;
 };

As replied to the patch "KVM: TDX: create/destroy VM structure", I think it's better to introduce this part together with that patch to make reviewer easier.

If I am not seeing mistakenly, the "accessors" below are not used in that patch, so they can be done in a later patch when needed.

Quoted 108 lines
arch/x86/kvm/vmx/tdx.h +101 -0
 static inline bool is_td(struct kvm *kvm)
@@ -32,6 +45,107 @@ static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
 {
 	return container_of(vcpu, struct vcpu_tdx, vcpu);
 }
+
+static __always_inline void tdvps_vmcs_check(u32 field, u8 bits)
+{
+#define VMCS_ENC_ACCESS_TYPE_MASK	0x1UL
+#define VMCS_ENC_ACCESS_TYPE_FULL	0x0UL
+#define VMCS_ENC_ACCESS_TYPE_HIGH	0x1UL
+#define VMCS_ENC_ACCESS_TYPE(field)	((field) & VMCS_ENC_ACCESS_TYPE_MASK)
+
+	/* TDX is 64bit only.  HIGH field isn't supported. */
+	BUILD_BUG_ON_MSG(__builtin_constant_p(field) &&
+			 VMCS_ENC_ACCESS_TYPE(field) == VMCS_ENC_ACCESS_TYPE_HIGH,
+			 "Read/Write to TD VMCS *_HIGH fields not supported");
+
+	BUILD_BUG_ON(bits != 16 && bits != 32 && bits != 64);
+
+#define VMCS_ENC_WIDTH_MASK	GENMASK(14, 13)
+#define VMCS_ENC_WIDTH_16BIT	(0UL << 13)
+#define VMCS_ENC_WIDTH_64BIT	(1UL << 13)
+#define VMCS_ENC_WIDTH_32BIT	(2UL << 13)
+#define VMCS_ENC_WIDTH_NATURAL	(3UL << 13)
+#define VMCS_ENC_WIDTH(field)	((field) & VMCS_ENC_WIDTH_MASK)
+
+	/* TDX is 64bit only.  i.e. natural width = 64bit. */
+	BUILD_BUG_ON_MSG(bits != 64 && __builtin_constant_p(field) &&
+			 (VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_64BIT ||
+			  VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_NATURAL),
+			 "Invalid TD VMCS access for 64-bit field");
+	BUILD_BUG_ON_MSG(bits != 32 && __builtin_constant_p(field) &&
+			 VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_32BIT,
+			 "Invalid TD VMCS access for 32-bit field");
+	BUILD_BUG_ON_MSG(bits != 16 && __builtin_constant_p(field) &&
+			 VMCS_ENC_WIDTH(field) == VMCS_ENC_WIDTH_16BIT,
+			 "Invalid TD VMCS access for 16-bit field");
+}
+
+static __always_inline void tdvps_state_non_arch_check(u64 field, u8 bits) {}
+static __always_inline void tdvps_management_check(u64 field, u8 bits) {}
+
+#define TDX_BUILD_TDVPS_ACCESSORS(bits, uclass, lclass)				\
+static __always_inline u##bits td_##lclass##_read##bits(struct vcpu_tdx *tdx,	\
+							u32 field)		\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_rd(tdx->tdvpr.pa, TDVPS_##uclass(field), &out);		\
+	if (unlikely(err)) {							\
+		pr_err("TDH_VP_RD["#uclass".0x%x] failed: 0x%llx\n",		\
+		       field, err);						\
+		return 0;							\
+	}									\
+	return (u##bits)out.r8;							\
+}										\
+static __always_inline void td_##lclass##_write##bits(struct vcpu_tdx *tdx,	\
+						      u32 field, u##bits val)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), val,		\
+		      GENMASK_ULL(bits - 1, 0), &out);				\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] = 0x%llx failed: 0x%llx\n",	\
+		       field, (u64)val, err);					\
+}										\
+static __always_inline void td_##lclass##_setbit##bits(struct vcpu_tdx *tdx,	\
+						       u32 field, u64 bit)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), bit, bit,		\
+			&out);							\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] |= 0x%llx failed: 0x%llx\n",	\
+		       field, bit, err);					\
+}										\
+static __always_inline void td_##lclass##_clearbit##bits(struct vcpu_tdx *tdx,	\
+							 u32 field, u64 bit)	\
+{										\
+	struct tdx_module_output out;						\
+	u64 err;								\
+										\
+	tdvps_##lclass##_check(field, bits);					\
+	err = tdh_vp_wr(tdx->tdvpr.pa, TDVPS_##uclass(field), 0, bit,		\
+			&out);							\
+	if (unlikely(err))							\
+		pr_err("TDH_VP_WR["#uclass".0x%x] &= ~0x%llx failed: 0x%llx\n",	\
+		       field, bit,  err);					\
+}
+
+TDX_BUILD_TDVPS_ACCESSORS(16, VMCS, vmcs);
+TDX_BUILD_TDVPS_ACCESSORS(32, VMCS, vmcs);
+TDX_BUILD_TDVPS_ACCESSORS(64, VMCS, vmcs);
+
+TDX_BUILD_TDVPS_ACCESSORS(64, STATE_NON_ARCH, state_non_arch);
+TDX_BUILD_TDVPS_ACCESSORS(8, MANAGEMENT, management);
+
 
#59 lore raw

Re: [PATCH v10 024/108] KVM: TDX: allocate/free TDX vcpu structure

In reply to [email protected]
Quoted 192 lines · On Sat, Oct 29, 2022 at 11:22:25PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The next step of TDX guest creation is to create vcpu. Allocate TDX vcpu structures, initialize it. Allocate pages of TDX vcpu for the TDX module.

In the case of the conventional case, cpuid is empty at the initialization. and cpuid is configured after the vcpu initialization. Because TDX supports only X2APIC mode, cpuid is forcibly initialized to support X2APIC on the vcpu initialization.

---
 arch/x86/kvm/vmx/main.c    |  40 +++++++++--
 arch/x86/kvm/vmx/tdx.c     | 138 +++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h |   8 +++
 3 files changed, 182 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +36 -4
index b4e4c6c677f6..c125b2e3e8b4 100644
@@ -63,6 +63,38 @@ static void vt_vm_free(struct kvm *kvm)
 		return tdx_vm_free(kvm);
 }
 
+static int vt_vcpu_precreate(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return 0;
+
+	return vmx_vcpu_precreate(kvm);
+}
+
+static int vt_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_create(vcpu);
+
+	return vmx_vcpu_create(vcpu);
+}
+
+static void vt_vcpu_free(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_free(vcpu);
+
+	return vmx_vcpu_free(vcpu);
+}
+
+static void vt_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_reset(vcpu, init_event);
+
+	return vmx_vcpu_reset(vcpu, init_event);
+}
+
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	if (!is_td(kvm))
@@ -89,10 +121,10 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.vm_destroy = vt_vm_destroy,
 	.vm_free = vt_vm_free,
 
-	.vcpu_precreate = vmx_vcpu_precreate,
-	.vcpu_create = vmx_vcpu_create,
-	.vcpu_free = vmx_vcpu_free,
-	.vcpu_reset = vmx_vcpu_reset,
+	.vcpu_precreate = vt_vcpu_precreate,
+	.vcpu_create = vt_vcpu_create,
+	.vcpu_free = vt_vcpu_free,
+	.vcpu_reset = vt_vcpu_reset,
 
 	.prepare_switch_to_guest = vmx_prepare_switch_to_guest,
 	.vcpu_load = vmx_vcpu_load,
arch/x86/kvm/vmx/tdx.c +102 -0
index 54045e0576e7..0625c354b341 100644
@@ -49,6 +49,11 @@ static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
 	return pa | ((hpa_t)hkid << boot_cpu_data.x86_phys_bits);
 }
 
+static inline bool is_td_vcpu_created(struct vcpu_tdx *tdx)
+{
+	return tdx->tdvpr.added;
+}
+
 static inline bool is_td_created(struct kvm_tdx *kvm_tdx)
 {
 	return kvm_tdx->tdr.added;
@@ -296,6 +301,139 @@ int tdx_vm_init(struct kvm *kvm)
 	return 0;
 }
 
+int tdx_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	int ret, i;
+
+	/* TDX only supports x2APIC, which requires an in-kernel local APIC. */
+	if (!vcpu->arch.apic)
+		return -EINVAL;
+
+	fpstate_set_confidential(&vcpu->arch.guest_fpu);
+
+	ret = tdx_alloc_td_page(&tdx->tdvpr);
+	if (ret)
+		return ret;
+
+	tdx->tdvpx = kcalloc(tdx_caps.tdvpx_nr_pages, sizeof(*tdx->tdvpx),
+			GFP_KERNEL_ACCOUNT);
+	if (!tdx->tdvpx) {
+		ret = -ENOMEM;
+		goto free_tdvpr;
+	}
+	for (i = 0; i < tdx_caps.tdvpx_nr_pages; i++) {
+		ret = tdx_alloc_td_page(&tdx->tdvpx[i]);
+		if (ret)
+			goto free_tdvpx;
+	}
+
+	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
+
+	vcpu->arch.cr0_guest_owned_bits = -1ul;
+	vcpu->arch.cr4_guest_owned_bits = -1ul;
+
+	vcpu->arch.tsc_offset = to_kvm_tdx(vcpu->kvm)->tsc_offset;
+	vcpu->arch.l1_tsc_offset = vcpu->arch.tsc_offset;
+	vcpu->arch.guest_state_protected =
+		!(to_kvm_tdx(vcpu->kvm)->attributes & TDX_TD_ATTRIBUTE_DEBUG);
+
+	return 0;
+
+free_tdvpx:
+	/* @i points at the TDVPX page that failed allocation. */
+	for (--i; i >= 0; i--)
+		free_page(tdx->tdvpx[i].va);
+	kfree(tdx->tdvpx);
+	tdx->tdvpx = NULL;
+free_tdvpr:
+	free_page(tdx->tdvpr.va);
+
+	return ret;
+}
+
+void tdx_vcpu_free(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	int i;
+
+	/* Can't reclaim or free pages if teardown failed. */
+	if (is_hkid_assigned(to_kvm_tdx(vcpu->kvm)))
+		return;
+
+	if (tdx->tdvpx) {
+		for (i = 0; i < tdx_caps.tdvpx_nr_pages; i++)
+			tdx_reclaim_td_page(&tdx->tdvpx[i]);
+		kfree(tdx->tdvpx);
+		tdx->tdvpx = NULL;
+	}
+	tdx_reclaim_td_page(&tdx->tdvpr);
+}
+
+void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	struct msr_data apic_base_msr;
+	u64 err;
+	int i;
+
+	/* TDX doesn't support INIT event. */
+	if (WARN_ON_ONCE(init_event))
+		goto td_bugged;
+	if (WARN_ON_ONCE(is_td_vcpu_created(tdx)))
+		goto td_bugged;
+
+	err = tdh_vp_create(kvm_tdx->tdr.pa, tdx->tdvpr.pa);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_VP_CREATE, err, NULL);
+		goto td_bugged;
+	}
+	tdx_mark_td_page_added(&tdx->tdvpr);
+
+	for (i = 0; i < tdx_caps.tdvpx_nr_pages; i++) {
+		err = tdh_vp_addcx(tdx->tdvpr.pa, tdx->tdvpx[i].pa);
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_VP_ADDCX, err, NULL);
+			goto td_bugged;
+		}
+		tdx_mark_td_page_added(&tdx->tdvpx[i]);

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	}
+
+	if (!vcpu->arch.cpuid_entries) {
+		/*
+		 * On cpu creation, cpuid entry is blank.  Forcibly enable
+		 * X2APIC feature to allow X2APIC.
+		 */
+		struct kvm_cpuid_entry2 *e;
+
+		e = kvmalloc_array(1, sizeof(*e), GFP_KERNEL_ACCOUNT);

NULL checking is necessary for kvmalloc_array.

Quoted 58 lines
arch/x86/kvm/vmx/tdx.c +26 -0
+		*e  = (struct kvm_cpuid_entry2) {
+			.function = 1,	/* Features for X2APIC */
+			.index = 0,
+			.eax = 0,
+			.ebx = 0,
+			.ecx = 1ULL << 21,	/* X2APIC */
+			.edx = 0,
+		};
+		vcpu->arch.cpuid_entries = e;
+		vcpu->arch.cpuid_nent = 1;
+	}
+	apic_base_msr.data = APIC_DEFAULT_PHYS_BASE | LAPIC_MODE_X2APIC;
+	if (kvm_vcpu_is_reset_bsp(vcpu))
+		apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
+	apic_base_msr.host_initiated = true;
+	if (WARN_ON_ONCE(kvm_set_apic_base(vcpu, &apic_base_msr)))
+		goto td_bugged;
+
+	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+
+	return;
+
+td_bugged:
+	vcpu->kvm->vm_bugged = true;
+}
+
 int tdx_dev_ioctl(void __user *argp)
 {
 	struct kvm_tdx_capabilities __user *user_caps;
arch/x86/kvm/vmx/x86_ops.h +8 -1
index 93ffe2deb8e8..f6841c3dd12d 100644
@@ -141,6 +141,10 @@ int tdx_vm_init(struct kvm *kvm);
 void tdx_mmu_release_hkid(struct kvm *kvm);
 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);
+
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return 0; }
@@ -154,6 +158,10 @@ static inline void tdx_mmu_release_hkid(struct kvm *kvm) {}
 static inline void tdx_flush_shadow_all_private(struct kvm *kvm) {}
 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 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOPNOTSUPP; }
 #endif
 
--

2.25.1

#164 lore raw

Re: [PATCH v10 071/108] KVM: x86: Allow to update cached values in kvm_user_return_msrs w/o wrmsr

In reply to [email protected]
Quoted 68 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Chao Gao <[email protected]>

Several MSRs are constant and only used in userspace(ring 3). But VMs may have different values. KVM uses kvm_set_user_return_msr() to switch to guest's values and leverages user return notifier to restore them when the kernel is to return to userspace. To eliminate unnecessary wrmsr, KVM also caches the value it wrote to an MSR last time.

TDX module unconditionally resets some of these MSRs to architectural INIT state on TD exit. It makes the cached values in kvm_user_return_msrs are inconsistent with values in hardware. This inconsistency needs to be fixed. Otherwise, it may mislead kvm_on_user_return() to skip restoring some MSRs to the host's values. kvm_set_user_return_msr() can help correct this case, but it is not optimal as it always does a wrmsr. So, introduce a variation of kvm_set_user_return_msr() to update cached values and skip that wrmsr.

---
  arch/x86/include/asm/kvm_host.h |  1 +
  arch/x86/kvm/x86.c              | 26 +++++++++++++++++++++-----
  2 files changed, 22 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -0
index b225cdfac4bc..fdb00d96e954 100644
@@ -2082,6 +2082,7 @@ int kvm_add_user_return_msr(u32 msr);
  int kvm_find_user_return_msr(u32 msr);
  void kvm_user_return_msr_init_cpu(void);
  int kvm_set_user_return_msr(unsigned index, u64 val, u64 mask);
+void kvm_user_return_update_cache(unsigned int index, u64 val);
 
  static inline bool kvm_is_supported_user_return_msr(u32 msr)
  {
arch/x86/kvm/x86.c +10 -5
index 65541bfebb37..4d4b71c4cdb1 100644
@@ -440,6 +440,15 @@ void kvm_user_return_msr_init_cpu(void)
  }
  EXPORT_SYMBOL_GPL(kvm_user_return_msr_init_cpu);
 
+static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
+{
+	if (!msrs->registered) {
+		msrs->urn.on_user_return = kvm_on_user_return;
+		user_return_notifier_register(&msrs->urn);
+		msrs->registered = true;
+	}
+}
+
  int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
  {
  	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
@@ -455,15 +464,22 @@ int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
  		return 1;
 
  	msrs->values[slot].curr = value;
-	if (!msrs->registered) {
-		msrs->urn.on_user_return = kvm_on_user_return;
-		user_return_notifier_register(&msrs->urn);
-		msrs->registered = true;
-	}
+	kvm_user_return_register_notifier(msrs);
  	return 0;

arch/x86/kvm/x86.c int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask) · line 478

Quoted 10 lines
arch/x86/kvm/x86.c +7 -0
  }
  EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
 
+/* Update the cache, "curr", and register the notifier */
+void kvm_user_return_update_cache(unsigned int slot, u64 value)
+{
+	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
+
+	WARN_ON_ONCE(!msrs->initialized);
+	msrs->values[slot].curr = value;

If the value is the same as the cached one, can it just skip notifier registration?

Quoted 7 lines
arch/x86/kvm/x86.c +4 -0
+	kvm_user_return_register_notifier(msrs);
+}
+EXPORT_SYMBOL_GPL(kvm_user_return_update_cache);
+
  static void drop_user_return_notifiers(void)
  {
  	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
#167 lore raw

Re: [PATCH v10 072/108] KVM: TDX: restore user ret MSRs

In reply to [email protected]
Quoted 56 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Several user ret MSRs are clobbered on TD exit. Restore those values on TD exit and before returning to ring 3.

---
  arch/x86/kvm/vmx/tdx.c | 43 ++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 43 insertions(+)
arch/x86/kvm/vmx/tdx.c +23 -0
index 3ec465cbaeef..f35ccf2b502d 100644
@@ -456,6 +456,28 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  	vcpu->kvm->vm_bugged = true;
  }
 
+struct tdx_uret_msr {
+	u32 msr;
+	unsigned int slot;
+	u64 defval;
+};
+
+static struct tdx_uret_msr tdx_uret_msrs[] = {
+	{.msr = MSR_SYSCALL_MASK,},
+	{.msr = MSR_STAR,},
+	{.msr = MSR_LSTAR,},
+	{.msr = MSR_TSC_AUX,},
+};
+
+static void tdx_user_return_update_cache(void)
+{
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(tdx_uret_msrs); i++)
+		kvm_user_return_update_cache(tdx_uret_msrs[i].slot,
+					     tdx_uret_msrs[i].defval);
+}
+
  static void tdx_restore_host_xsave_state(struct kvm_vcpu *vcpu)
  {
  	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
@@ -495,6 +517,7 @@ fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
 
  	tdx_vcpu_enter_exit(vcpu, tdx);
 
+	tdx_user_return_update_cache();
  	tdx_restore_host_xsave_state(vcpu);
  	tdx->host_state_need_restore = true;
 
@@ -1558,6 +1581,26 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  		return -ENODEV;
  	}
 

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	for (i = 0; i < ARRAY_SIZE(tdx_uret_msrs); i++) {
+		/*
+		 * Here it checks if MSRs (tdx_uret_msrs) can be saved/restored
+		 * before returning to user space.
+		 *
+		 * this_cpu_ptr(user_return_msrs)->registered isn't checked
+		 * because the registration is done at vcpu runtime by
+		 * kvm_set_user_return_msr().
+		 * Here is setting up cpu feature before running vcpu,
+		 * registered is alreays

typo, already or always?

Quoted 14 lines
arch/x86/kvm/vmx/tdx.c +10 -0
  false.
+		 */
+		tdx_uret_msrs[i].slot = kvm_find_user_return_msr(tdx_uret_msrs[i].msr);
+		if (tdx_uret_msrs[i].slot == -1) {
+			/* If any MSR isn't supported, it is a KVM bug */
+			pr_err("MSR %x isn't included by kvm_find_user_return_msr\n",
+				tdx_uret_msrs[i].msr);
+			return -EIO;
+		}
+	}
+
  	max_pkgs = topology_max_packages();
  	tdx_mng_key_config_lock = kcalloc(max_pkgs, sizeof(*tdx_mng_key_config_lock),

GFP_KERNEL);

#8 lore raw

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Huang, Kai
Quoted 25 lines · Kai
Quoted 12 lines
arch/x86/kvm/vmx/tdx.c new file +11 -0
+
+#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;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+	u64 attrs_fixed1;
+	u64 xfam_fixed0;
+	u64 xfam_fixed1;
+
+	u32 nr_cpuid_configs;
+	struct tdx_cpuid_config cpuid_configs[TDX_MAX_NR_CPUID_CONFIGS];
+};
+
+/* Capabilities of KVM + the TDX module. */
+static struct tdx_capabilities tdx_caps;

I think you can introduce this tdx_capabilities in another patch.

Quoted 4 lines

As claimed this patch can just focus on initializing the TDX module. Whether you need this tdx_capabilities or tdx_sysinfo is enough can be done in the patch when they are really needed. It makes review easier otherwise people won't be able to tell why tdx_capabilities is needed here.

Ok, the previous patch ("x86/virt/tdx: Add a helper function to return system wide info about TDX module ") and this part will be moved right before the first use of tdx_caps. "KVM: TDX: create/destroy VM structure"

Quoted 42 lines
Quoted 29 lines
arch/x86/kvm/vmx/tdx.c new file +29 -0
+
+static int __init 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_enable();
+	if (ret) {
+		pr_info("Failed to initialize TDX module.\n");
+		return ret;
+	}
+
+	tdsysinfo = tdx_get_sysinfo();
+	if (tdsysinfo->num_cpuid_config > 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,

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+		.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;
+
+	pr_info("kvm: TDX is supported. x86 phys bits %d\n",
+		boot_cpu_data.x86_phys_bits);

What''s the benefit of print out x86_phys_bits? Looks a little bit weird here.

Quoted 2 lines

TDX host code will print out TDX private KeyID range. I think that is useful enough?

Ok, please make TDX host code print it. I will remove key id rane.

Quoted 24 lines
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c new file +6 -0
+
+	return 0;
+}
+
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+	int r;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	/* MOVDIR64B instruction is needed. */
+	if (!static_cpu_has(X86_FEATURE_MOVDIR64B)) {
+		pr_warn("Cannot enable TDX with MOVDIR64B supported ");
					   ^
					   without

Review

Quoted 2 lines
(quoted diff) +2 -0
+		return -ENODEV;
+	}

I think you should explain why MOVDIR64B is required, otherwise this just comes out of blue.

Quoted 5 lines

Btw, is this absolutely required? TDX also supports Li-mode, which doesn't have integrity check. So theoretically with Li-mode, normal zeroing is also OK but doesn't need to use MOVDIR64B.

That being said, do we have a way to tell whether TDX works in Ci or Li mode?

As long as I don't know. When clearing page, we can use if (featuremovdir64b) movdir64b else memset(0).

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

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to [email protected]
Quoted 374 lines · On Sat, Oct 29, 2022 at 11:24 PM <[email protected]> wrote:

From: Sean Christopherson <[email protected]>

As the first step to create TDX guest, create/destroy VM struct. Assign TDX private 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.

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 flush_shadow_all_private callback before tearing down private page tables for it.

Add a second kvm_x86_ops hook in kvm_arch_destroy_vm() 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/include/asm/kvm-x86-ops.h |   2 +
 arch/x86/include/asm/kvm_host.h    |   2 +
 arch/x86/kvm/vmx/main.c            |  34 ++-
 arch/x86/kvm/vmx/tdx.c             | 411 +++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h             |   2 +
 arch/x86/kvm/vmx/x86_ops.h         |  11 +
 arch/x86/kvm/x86.c                 |   8 +
 7 files changed, 467 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 8a5c5ae70bc5..3a29a6b31ee8 100644
@@ -21,7 +21,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_OPTIONAL(flush_shadow_all_private)
 KVM_X86_OP_OPTIONAL(vm_destroy)
+KVM_X86_OP_OPTIONAL(vm_free)
 KVM_X86_OP_OPTIONAL_RET0(vcpu_precreate)
 KVM_X86_OP(vcpu_create)
 KVM_X86_OP(vcpu_free)
arch/x86/include/asm/kvm_host.h +2 -0
index 2a41a93a80f3..2870155ce6fb 100644
@@ -1472,7 +1472,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 (*flush_shadow_all_private)(struct kvm *kvm);
        void (*vm_destroy)(struct kvm *kvm);
+       void (*vm_free)(struct kvm *kvm);
 
        /* Create, but do not attach this VCPU */
        int (*vcpu_precreate)(struct kvm *kvm);
arch/x86/kvm/vmx/main.c +31 -3
index 0900ff2f2390..d01a946a18cf 100644
@@ -29,18 +29,44 @@ 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)
 {
        if (is_td(kvm))
-               return -EOPNOTSUPP;     /* Not ready to create guest TD yet. */
+               return tdx_vm_init(kvm);
 
        return vmx_vm_init(kvm);
 }
 
+static void vt_flush_shadow_all_private(struct kvm *kvm)
+{
+       if (is_td(kvm))
+               return tdx_mmu_release_hkid(kvm);
+}
+
+static void vt_vm_destroy(struct kvm *kvm)
+{
+       if (is_td(kvm))
+               return;
+
+       vmx_vm_destroy(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",
 
-       .hardware_unsetup = vmx_hardware_unsetup,
+       .hardware_unsetup = vt_hardware_unsetup,
        .check_processor_compatibility = vmx_check_processor_compatibility,
 
        .hardware_enable = vmx_hardware_enable,
@@ -50,7 +76,9 @@ 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,
-       .vm_destroy = vmx_vm_destroy,
+       .flush_shadow_all_private = vt_flush_shadow_all_private,
+       .vm_destroy = vt_vm_destroy,
+       .vm_free = vt_vm_free,
 
        .vcpu_precreate = vmx_vcpu_precreate,
        .vcpu_create = vmx_vcpu_create,
arch/x86/kvm/vmx/tdx.c +245 -0
index 530e72f85762..ec88dde0d300 100644
@@ -32,6 +32,401 @@ struct tdx_capabilities {
 /* Capabilities of KVM + the TDX module. */
 static struct tdx_capabilities tdx_caps;
 
+/*
+ * Some TDX SEAMCALLs (TDH.MNG.CREATE, TDH.PHYMEM.CACHE.WB,
+ * TDH.MNG.KEY.RECLAIMID, TDH.MNG.KEY.FREEID etc) tries to acquire a global lock
+ * internally in TDX module.  If failed, TDX_OPERAND_BUSY is returned without
+ * spinning or waiting due to a constraint on execution time.  It's caller's
+ * responsibility to avoid race (or retry on TDX_OPERAND_BUSY).  Use this mutex
+ * to avoid race in TDX module because the kernel knows better about scheduling.
+ */
+static DEFINE_MUTEX(tdx_lock);
+static struct mutex *tdx_mng_key_config_lock;
+
+static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
+{
+       return pa | ((hpa_t)hkid << boot_cpu_data.x86_phys_bits);
+}
+
+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:
+        * 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.
+        *
+        * The cache line could be poisoned (even without MKTME-i), clear the
+        * poison bit.
+        */
+       for (i = 0; i < PAGE_SIZE; i += 64)
+               movdir64b((void *)(page + i), zero_page);
+       /*
+        * MOVDIR64B store uses WC buffer.  Prevent following memory reads
+        * from seeing potentially poisoned cache.
+        */
+       __mb();
+}
+
+static int tdx_reclaim_page(unsigned long va, hpa_t pa, bool do_wb, u16 hkid)
+{
+       struct tdx_module_output out;
+       u64 err;
+
+       do {
+               err = tdh_phymem_page_reclaim(pa, &out);
+               /*
+                * TDH.PHYMEM.PAGE.RECLAIM is allowed only when TD is shutdown.
+                * state.  i.e. destructing TD.
+                * TDH.PHYMEM.PAGE.RECLAIM  requires TDR and target page.
+                * Because we're destructing TD, it's rare to contend with TDR.
+                */
+       } while (err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_RCX));
+       if (WARN_ON_ONCE(err)) {
+               pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
+               return -EIO;
+       }
+
+       if (do_wb) {
+               /*
+                * Only TDR page gets into this path.  No contention is expected
+                * because the last page of TD.
+                */
+               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_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 inline 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) {
+               /*
+                * TDCX are being reclaimed.  TDX module maps TDCX with HKID
+                * assigned to the TD.  Here the cache associated to the TD
+                * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+                * cache doesn't need to be flushed again.
+                */
+               if (tdx_reclaim_page(page->va, page->pa, false, 0))
+                       return;
+
+               page->added = false;
+       }
+       if (page->va) {
+               free_page(page->va);
+               page->va = 0;
+       }
+}
+
+static int tdx_do_tdh_phymem_cache_wb(void *param)
+{
+       u64 err = 0;
+
+       do {
+               err = tdh_phymem_cache_wb(!!err);
+       } while (err == TDX_INTERRUPTED_RESUMABLE);
+
+       /* 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_release_hkid(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;
+
+       cpumask_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+       cpus_read_lock();
+       for_each_online_cpu(i) {
+               if (cpumask_allocated &&
+                       cpumask_test_and_set_cpu(topology_physical_package_id(i),
+                                               packages))
+                       continue;
+
+               /*
+                * We can destroy multiple the guest TDs simultaneously.
+                * Prevent tdh_phymem_cache_wb from returning TDX_BUSY by
+                * serialization.
+                */
+               mutex_lock(&tdx_lock);
+               ret = smp_call_on_cpu(i, tdx_do_tdh_phymem_cache_wb, NULL, 1);
+               mutex_unlock(&tdx_lock);
+               if (ret)
+                       break;
+       }
+       cpus_read_unlock();
+       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);
+               pr_err("tdh_mng_key_freeid failed. HKID %d is leaked.\n",
+                       kvm_tdx->hkid);
+               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;
+
+       if (kvm_tdx->tdcs) {
+               for (i = 0; i < tdx_caps.tdcs_nr_pages; i++)
+                       tdx_reclaim_td_page(&kvm_tdx->tdcs[i]);
+               kfree(kvm_tdx->tdcs);
+       }
+
+       /*
+        * TDX module maps TDR with TDX global HKID.  TDX module may access TDR
+        * while operating on TD (Especially reclaiming TDCS).  Cache flush with
+        * TDX global HKID is needed.
+        */
+       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;
+       u64 err;
+
+       do {
+               err = tdh_mng_key_config(*tdr_p);
+
+               /*
+                * If it failed to generate a random key, retry it because this
+                * is typically caused by an entropy error of the CPU's random
+                * number generator.
+                */
+       } while (err == TDX_KEY_GENERATION_FAILED);
+
+       if (WARN_ON_ONCE(err)) {
+               pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
+               return -EIO;
+       }
+
+       return 0;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -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;
+
+       ret = tdx_keyid_alloc();

Can we skip the hkid allocation at such an early stage? This makes intra-host migration more complicated as the hkid of the destination VM is already allocated before we have a chance to migrate the state from the source VM.

I remember you had an internal version that already did that in
https://github.com/intel/tdx/blob/552dd80c48f67ca01bcdd10667e0c11efd375177/arch/x86/kvm/vmx/tdx.c#L508

Quoted 244 lines
arch/x86/kvm/vmx/tdx.c +156 -0
+       if (ret < 0)
+               return ret;
+       kvm_tdx->hkid = ret;
+
+       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 | __GFP_ZERO);
+       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;
+       }
+
+       if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+               ret = -ENOMEM;
+               goto free_tdcs;
+       }
+       cpus_read_lock();
+       /*
+        * Need at least one CPU of the package to be online in order to
+        * program all packages for host key id.  Check it.
+        */
+       for_each_present_cpu(i)
+               cpumask_set_cpu(topology_physical_package_id(i), packages);
+       for_each_online_cpu(i)
+               cpumask_clear_cpu(topology_physical_package_id(i), packages);
+       if (!cpumask_empty(packages)) {
+               ret = -EIO;
+               /*
+                * Because it's hard for human operator to figure out the
+                * reason, warn it.
+                */
+               pr_warn("All packages need to have online CPU to create TD. Online CPU and retry.\n");
+               goto free_packages;
+       }
+
+       /*
+        * Acquire global lock to avoid TDX_OPERAND_BUSY:
+        * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+        * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+        * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+        * caller to handle the contention.  This is because of time limitation
+        * usable inside the TDX module and OS/VMM knows better about process
+        * scheduling.
+        *
+        * APIs to acquire the lock of KOT:
+        * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+        * TDH.PHYMEM.CACHE.WB.
+        */
+       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_packages;
+       }
+       tdx_mark_td_page_added(&kvm_tdx->tdr);
+
+       for_each_online_cpu(i) {
+               int pkg = topology_physical_package_id(i);
+
+               if (cpumask_test_and_set_cpu(pkg, packages))
+                       continue;
+
+               /*
+                * Program the memory controller in the package with an
+                * encryption key associated to a TDX private host key id
+                * assigned to this TDR.  Concurrent operations on same memory
+                * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+                * mutex.
+                */
+               mutex_lock(&tdx_mng_key_config_lock[pkg]);
+               ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+                                     &kvm_tdx->tdr.pa, true);
+               mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+               if (ret)
+                       break;
+       }
+       cpus_read_unlock();
+       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_release_hkid(kvm);
+       tdx_vm_free(kvm);
+       return ret;
+
+free_packages:
+       cpus_read_unlock();
+       free_cpumask_var(packages);
+free_tdcs:
+       for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+               if (!kvm_tdx->tdcs[i].va)
+                       continue;
+               free_page(kvm_tdx->tdcs[i].va);
+       }
+       kfree(kvm_tdx->tdcs);
+       kvm_tdx->tdcs = NULL;
+free_tdr:
+       if (kvm_tdx->tdr.va) {
+               free_page(kvm_tdx->tdr.va);
+               kvm_tdx->tdr.added = false;
+               kvm_tdx->tdr.va = 0;
+               kvm_tdx->tdr.pa = 0;
+       }
+free_hkid:
+       if (kvm_tdx->hkid != -1)
+               tdx_hkid_free(kvm_tdx);
+       return ret;
+}
+
 static int __init tdx_module_setup(void)
 {
        const struct tdsysinfo_struct *tdsysinfo;
@@ -82,6 +477,8 @@ bool tdx_is_vm_type_supported(unsigned long type)
 
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 {
+       int max_pkgs;
+       int i;
        int r;
 
        if (!enable_ept) {
@@ -95,6 +492,14 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
                return -ENODEV;
        }
 
+       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]);
+
        /* TDX requires VMX. */
        r = vmxon_all();
        if (!r)
@@ -103,3 +508,9 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 
        return r;
 }
+
+void tdx_hardware_unsetup(void)
+{
+       /* kfree accepts NULL. */
+       kfree(tdx_mng_key_config_lock);
+}
arch/x86/kvm/vmx/tdx.h +2 -0
index 98999bf3f188..938314635b47 100644
@@ -17,6 +17,8 @@ struct kvm_tdx {
 
        struct tdx_td_page tdr;
        struct tdx_td_page *tdcs;
+
+       int hkid;
 };
 
 struct vcpu_tdx {
arch/x86/kvm/vmx/x86_ops.h +11 -0
index ac1688b0b0e3..95da978c9aa9 100644
@@ -133,9 +133,20 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 #ifdef CONFIG_INTEL_TDX_HOST
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 bool tdx_is_vm_type_supported(unsigned long type);
+void tdx_hardware_unsetup(void);
+
+int tdx_vm_init(struct kvm *kvm);
+void tdx_mmu_release_hkid(struct kvm *kvm);
+void tdx_vm_free(struct kvm *kvm);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return 0; }
 static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
+static inline void tdx_hardware_unsetup(void) {}
+
+static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
+static inline void tdx_mmu_release_hkid(struct kvm *kvm) {}
+static inline void tdx_flush_shadow_all_private(struct kvm *kvm) {}
+static inline void tdx_vm_free(struct kvm *kvm) {}
 #endif
 
 #endif /* __KVM_X86_VMX_X86_OPS_H */
arch/x86/kvm/x86.c +8 -1
index 91053fdc4512..4b22196cb12c 100644
@@ -12702,6 +12702,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)
@@ -13012,6 +13013,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_flush_shadow_all_private() for this.
+        */
+       static_call_cond(kvm_x86_flush_shadow_all_private)(kvm);
        kvm_mmu_zap_all(kvm);
 }
 
--

2.25.1

#9 lore raw

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Isaku Yamahata
Quoted 26 lines · Isaku Yamahata
Quoted 18 lines
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c new file +5 -0
+struct tdx_capabilities {
+	u8 tdcs_nr_pages;
+	u8 tdvpx_nr_pages;
+
+	u64 attrs_fixed0;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+	u64 attrs_fixed1;
+	u64 xfam_fixed0;
+	u64 xfam_fixed1;
+
+	u32 nr_cpuid_configs;
+	struct tdx_cpuid_config cpuid_configs[TDX_MAX_NR_CPUID_CONFIGS];
+};
+
+/* Capabilities of KVM + the TDX module. */
+static struct tdx_capabilities tdx_caps;

I think you can introduce this tdx_capabilities in another patch.

Quoted 7 lines

As claimed this patch can just focus on initializing the TDX module. Whether
you need this tdx_capabilities or tdx_sysinfo is enough can be done in the patch
when they are really needed.  It makes review easier otherwise people won't be
able to tell why tdx_capabilities is needed here.

Quoted 4 lines

Ok, the previous patch ("x86/virt/tdx: Add a helper function to return system wide info about TDX module ") and this part will be moved right before the
first use of tdx_caps. "KVM: TDX: create/destroy VM structure"

I think it's OK to put all host dependency patches at the beginning of the series, but just move 'tdx_capabilities' to the patch where it is needed.

#173 lore raw

Re: [PATCH v10 076/108] KVM: TDX: handle vcpu migration over logical processor

In reply to [email protected]
Quoted 3 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

For vcpu migration, in the case of VMX, VCMS

typo, VMCS

Quoted 29 lines

is flushed on the source pcpu,
and load it on the target pcpu. There are corresponding TDX SEAMCALL APIs, call them on vcpu migration. The logic is mostly same as VMX except the TDX SEAMCALLs are used.

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    |  43 +++++++++++--
  arch/x86/kvm/vmx/tdx.c     | 121 +++++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/tdx.h     |   2 +
  arch/x86/kvm/vmx/x86_ops.h |   6 ++
  4 files changed, 168 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/tdx.c +8 -0
@@ -176,6 +214,41 @@ static void tdx_reclaim_td_page(struct tdx_td_page *page)
  	}
  }
 
+static void tdx_flush_vp(void *arg)
+{
+	struct kvm_vcpu *vcpu = arg;
+	u64 err;
+
+	lockdep_assert_irqs_disabled();
+
+	/* Task migration can race with CPU offlining. */

arch/x86/kvm/vmx/tdx.c static void tdx_reclaim_td_page(struct tdx_td_page *page) · line 234

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	if (vcpu->cpu != raw_smp_processor_id())
+		return;
+
+	/*
+	 * No need to do TDH_VP_FLUSH if the vCPU hasn't been initialized.  The
+	 * list tracking still needs to be updated so that it's correct if/when
+	 * the vCPU does get initialized.
+	 */
+	if (is_td_vcpu_created(to_tdx(vcpu))) {
+		err = tdh_vp_flush(to_tdx(vcpu)->tdvpr.pa);

Need to retry here if tdh.vp.flush fails due to tdx operand busy?

If such failure occurs, the next vp enter will fail after the vCPU migrated to another LP, how is it hanlded?

Quoted 147 lines
arch/x86/kvm/vmx/tdx.c +65 -0
+		if (unlikely(err && err != TDX_VCPU_NOT_ASSOCIATED)) {
+			if (WARN_ON_ONCE(err))
+				pr_tdx_error(TDH_VP_FLUSH, err, NULL);
+		}
+	}
+
+	tdx_disassociate_vp(vcpu);
+}
+
+static void tdx_flush_vp_on_cpu(struct kvm_vcpu *vcpu)
+{
+	if (unlikely(vcpu->cpu == -1))
+		return;
+
+	smp_call_function_single(vcpu->cpu, tdx_flush_vp, vcpu, 1);
+}
+
  static int tdx_do_tdh_phymem_cache_wb(void *param)
  {
  	u64 err = 0;
@@ -200,6 +273,8 @@ void tdx_mmu_release_hkid(struct kvm *kvm)
  	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
  	cpumask_var_t packages;
  	bool cpumask_allocated;
+	struct kvm_vcpu *vcpu;
+	unsigned long j;
  	u64 err;
  	int ret;
  	int i;
@@ -210,6 +285,19 @@ void tdx_mmu_release_hkid(struct kvm *kvm)
  	if (!is_td_created(kvm_tdx))
  		goto free_hkid;
 
+	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);
+	mutex_unlock(&tdx_lock);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_VPFLUSHDONE, err, NULL);
+		pr_err("tdh_mng_vpflushdone failed. HKID %d is leaked.\n",
+			kvm_tdx->hkid);
+		return;
+	}
+
  	cpumask_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
  	cpus_read_lock();
  	for_each_online_cpu(i) {
@@ -355,6 +443,26 @@ int tdx_vcpu_create(struct kvm_vcpu *vcpu)
  	return 0;
  }
 
+void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
+{
+	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)
  {
  	struct vcpu_tdx *tdx = to_tdx(vcpu);
@@ -405,6 +513,19 @@ void tdx_vcpu_free(struct kvm_vcpu *vcpu)
  		tdx->tdvpx = NULL;
  	}
  	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_ONCE(vcpu->cpu != -1);
  }
 
  void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
arch/x86/kvm/vmx/tdx.h +2 -0
index e5f973b2d752..c02073102a5f 100644
@@ -68,6 +68,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 vcpu_initialized;
arch/x86/kvm/vmx/x86_ops.h +6 -0
index a4e50c5a4bf5..d4fcb6b29ffe 100644
@@ -138,6 +138,8 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
  bool tdx_is_vm_type_supported(unsigned long type);
  void tdx_hardware_unsetup(void);
  int tdx_offline_cpu(void);
+void tdx_hardware_enable(void);
+void tdx_hardware_disable(void);
  int tdx_dev_ioctl(void __user *argp);
 
  int tdx_vm_init(struct kvm *kvm);
@@ -150,6 +152,7 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
  fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu);
  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);
 
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
  int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
@@ -162,6 +165,8 @@ static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return 0; }
  static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
  static inline void tdx_hardware_unsetup(void) {}
  static inline int tdx_offline_cpu(void) { return 0; }
+static inline void tdx_hardware_enable(void) {}
+static inline void tdx_hardware_disable(void) {}
  static inline int tdx_dev_ioctl(void __user *argp) { return -EOPNOTSUPP; };
 
  static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
@@ -175,6 +180,7 @@ 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 void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu) {}
  static inline void tdx_vcpu_put(struct kvm_vcpu *vcpu) {}
+static inline void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu) {}
 
  static inline 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; }
#10 lore raw

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Isaku Yamahata
Quoted 11 lines · Isaku Yamahata
Quoted 8 lines

I think you should explain why MOVDIR64B is required, otherwise this just comes out of blue.

Btw, is this absolutely required? TDX also supports Li-mode, which doesn't have integrity check. So theoretically with Li-mode, normal zeroing is also OK but doesn't need to use MOVDIR64B.

That being said, do we have a way to tell whether TDX works in Ci or Li mode?

As long as I don't know. When clearing page, we can use if (featuremovdir64b) movdir64b else memset(0).

-- sorry for resending the same email, for some reason my previous email was not in plain text mode--
As far as I know, Li mode and Ci mode both are working very similarly and require movdir64b to clear any poison bit previously set. Why would movdir64b is not supported in a tdx capable cpu?

Quoted 2 lines

--
Isaku Yamahata <[email protected]>

#124 lore raw

Re: [PATCH v10 049/108] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to [email protected]
Quoted 365 lines · On 10/30/2022 2:22 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Allocate protected page table for private page table, and add hooks to operate on protected page table. This patch adds allocation/free of protected page tables and hooks. When calling hooks to update SPTE entry, freeze the entry, call hooks and unfree the entry to allow concurrent updates on page tables. Which is the advantage of TDP MMU. As kvm_gfn_shared_mask() returns false always, those hooks aren't called yet with this patch.

When the faulting GPA is private, the KVM fault is called private. When resolving private KVM, allocate protected page table and call hooks to operate on protected page table. On the change of the private PTE entry, invoke kvm_x86_ops hook in __handle_changed_spte() to propagate the change to protected page table. The following depicts the relationship.

   private KVM page fault   |
       |                    |
       V                    |
  private GPA               |     CPU protected EPTP
       |                    |           |
       V                    |           V
  private PT root           |     protected PT root
       |                    |           |
       V                    |           V

private PT --hook to propagate-->protected PT
| | |
\--------------------+------\ |
| | |
| V V
| private guest page
|
|
non-encrypted memory | encrypted memory
|
PT: page table

The existing KVM TDP MMU code uses atomic update of SPTE. On populating the EPT entry, atomically set the entry. However, it requires TLB shootdown to zap SPTE. To address it, the entry is frozen with the special SPTE value that clears the present bit. After the TLB shootdown, the entry is set to the eventual value (unfreeze).

For protected page table, hooks are called to update protected page table in addition to direct access to the private SPTE. For the zapping case, it works to freeze the SPTE. It can call hooks in addition to TLB shootdown. For populating the private SPTE entry, there can be a race condition without further protection

vcpu 1: populating 2M private SPTE
vcpu 2: populating 4K private SPTE
vcpu 2: TDX SEAMCALL to update 4K protected SPTE => error vcpu 1: TDX SEAMCALL to update 2M protected SPTE

To avoid the race, the frozen SPTE is utilized. Instead of atomic update of the private entry, freeze the entry, call the hook that update protected SPTE, set the entry to the final value.

Support 4K page only at this stage. 2M page support can be done in future patches.

---
  arch/x86/include/asm/kvm-x86-ops.h |   5 +
  arch/x86/include/asm/kvm_host.h    |  11 ++
  arch/x86/kvm/mmu/mmu.c             |  15 +-
  arch/x86/kvm/mmu/mmu_internal.h    |  32 ++++
  arch/x86/kvm/mmu/tdp_iter.h        |   2 +-
  arch/x86/kvm/mmu/tdp_mmu.c         | 244 +++++++++++++++++++++++++----
  arch/x86/kvm/mmu/tdp_mmu.h         |   2 +-
  virt/kvm/kvm_main.c                |   1 +
  8 files changed, 280 insertions(+), 32 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +5 -0
index f28c9fd72ac4..1b01dc2098b0 100644
@@ -94,6 +94,11 @@ KVM_X86_OP_OPTIONAL_RET0(set_tss_addr)
  KVM_X86_OP_OPTIONAL_RET0(set_identity_map_addr)
  KVM_X86_OP_OPTIONAL_RET0(get_mt_mask)
  KVM_X86_OP(load_mmu_pgd)
+KVM_X86_OP_OPTIONAL(link_private_spt)
+KVM_X86_OP_OPTIONAL(free_private_spt)
+KVM_X86_OP_OPTIONAL(set_private_spte)
+KVM_X86_OP_OPTIONAL(remove_private_spte)
+KVM_X86_OP_OPTIONAL(zap_private_spte)
  KVM_X86_OP(has_wbinvd_exit)
  KVM_X86_OP(get_l2_tsc_offset)
  KVM_X86_OP(get_l2_tsc_multiplier)
arch/x86/include/asm/kvm_host.h +11 -0
index 381df2c8136d..5f9634c130d0 100644
@@ -467,6 +467,7 @@ struct kvm_mmu {
  			 struct kvm_mmu_page *sp);
  	void (*invlpg)(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root_hpa);
  	struct kvm_mmu_root_info root;
+	hpa_t private_root_hpa;
  	union kvm_cpu_role cpu_role;
  	union kvm_mmu_page_role root_role;
 
@@ -1613,6 +1614,16 @@ struct kvm_x86_ops {
  	void (*load_mmu_pgd)(struct kvm_vcpu *vcpu, hpa_t root_hpa,
  			     int root_level);
 
+	int (*link_private_spt)(struct kvm *kvm, gfn_t gfn, enum pg_level level,
+				void *private_spt);
+	int (*free_private_spt)(struct kvm *kvm, gfn_t gfn, enum pg_level level,
+				void *private_spt);
+	int (*set_private_spte)(struct kvm *kvm, gfn_t gfn, enum pg_level level,
+				 kvm_pfn_t pfn);
+	int (*remove_private_spte)(struct kvm *kvm, gfn_t gfn, enum pg_level level,
+				    kvm_pfn_t pfn);
+	int (*zap_private_spte)(struct kvm *kvm, gfn_t gfn, enum pg_level level);
+
  	bool (*has_wbinvd_exit)(void);
 
  	u64 (*get_l2_tsc_offset)(struct kvm_vcpu *vcpu);
arch/x86/kvm/mmu/mmu.c +12 -3
index 0237e143299c..02e7b5cf3231 100644
@@ -3646,7 +3646,12 @@ 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 (kvm_gfn_shared_mask(vcpu->kvm) &&
+		    !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);
@@ -4357,7 +4362,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 = gpa_to_gfn(fault->addr) & ~kvm_gfn_shared_mask(vcpu->kvm);
  	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
 
  	if (page_fault_handle_page_track(vcpu, fault))
@@ -5893,6 +5898,7 @@ static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
 
  	mmu->root.hpa = INVALID_PAGE;
  	mmu->root.pgd = 0;
+	mmu->private_root_hpa = INVALID_PAGE;
  	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
 
@@ -6116,7 +6122,7 @@ static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
  		};
 
  		/*
-		 * this handles both private gfn and shared gfn.
+		 * This handles both private gfn and shared gfn.
  		 * All private page should be zapped on memslot deletion.
  		 */
  		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush, true);
@@ -6919,6 +6925,9 @@ int kvm_mmu_vendor_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/mmu_internal.h +32 -0
index 4c013124534b..508e8402c07a 100644
@@ -6,6 +6,8 @@
  #include <linux/kvm_host.h>
  #include <asm/kvm_host.h>
 
+#include "mmu.h"
+
  #undef MMU_DEBUG
 
  #ifdef MMU_DEBUG
@@ -209,11 +211,29 @@ static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,
  	}
  }
 
+static inline int kvm_alloc_private_spt_for_split(struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	gfp &= ~__GFP_ZERO;
+	sp->private_spt = (void *)__get_free_page(gfp);
+	if (!sp->private_spt)
+		return -ENOMEM;
+	return 0;
+}
+
  static inline void kvm_mmu_free_private_spt(struct kvm_mmu_page *sp)
  {
  	if (sp->private_spt)
  		free_page((unsigned long)sp->private_spt);
  }
+
+static inline gfn_t kvm_gfn_for_root(struct kvm *kvm, struct kvm_mmu_page *root,
+				     gfn_t gfn)
+{
+	if (is_private_sp(root))
+		return kvm_gfn_private(kvm, gfn);
+	else
+		return kvm_gfn_shared(kvm, gfn);
+}
  #else
  static inline void *kvm_mmu_private_spt(struct kvm_mmu_page *sp)
  {
@@ -230,9 +250,20 @@ static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,
  {
  }
 
+static inline int kvm_alloc_private_spt_for_split(struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	return -ENOMEM;
+}
+
  static inline void kvm_mmu_free_private_spt(struct kvm_mmu_page *sp)
  {
  }
+
+static inline gfn_t kvm_gfn_for_root(struct kvm *kvm, struct kvm_mmu_page *root,
+				     gfn_t gfn)
+{
+	return gfn;
+}
  #endif
 
  static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
@@ -367,6 +398,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(vcpu->kvm),
+		.is_private = kvm_is_private_gpa(vcpu->kvm, cr2_or_gpa),
 
  		.max_level = vcpu->kvm->arch.tdp_max_page_level,
  		.req_level = PG_LEVEL_4K,
arch/x86/kvm/mmu/tdp_iter.h +1 -1
index 9e56a5b1024c..eab62baf8549 100644
@@ -71,7 +71,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 (shared 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 +46 -4
index bdb50c26849f..0e053b96444a 100644
@@ -285,6 +285,9 @@ static struct kvm_mmu_page *tdp_mmu_alloc_sp(struct kvm_vcpu *vcpu,
  	sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
  	sp->role = role;
 
+	if (kvm_mmu_page_role_is_private(role))
+		kvm_mmu_alloc_private_spt(vcpu, NULL, sp);
+
  	return sp;
  }
 
@@ -305,7 +308,8 @@ static void tdp_mmu_init_sp(struct kvm_mmu_page *sp, tdp_ptep_t sptep,
  	trace_kvm_mmu_get_page(sp, true);
  }
 
-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 = vcpu->arch.mmu->root_role;
  	struct kvm *kvm = vcpu->kvm;
@@ -317,6 +321,8 @@ hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu)
  	 * Check for an existing root before allocating a new one.  Note, the
  	 * role check prevents consuming an invalid root.
  	 */
+	if (private)
+		kvm_mmu_page_role_set_private(&role);
  	for_each_tdp_mmu_root(kvm, root, kvm_mmu_role_as_id(role)) {
  		if (root->role.word == role.word &&
  		    kvm_tdp_mmu_get_root(root))
@@ -333,11 +339,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 int __must_check handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
-					    u64 old_spte, u64 new_spte, int level,
+					    u64 old_spte, u64 new_spte,
+					    union kvm_mmu_page_role role,
  					    bool shared);
 
  static void handle_changed_spte_acc_track(u64 old_spte, u64 new_spte, int level)
@@ -364,6 +376,8 @@ static void handle_changed_spte_dirty_log(struct kvm *kvm, int as_id, gfn_t gfn,
 
  	if ((!is_writable_pte(old_spte) || pfn_changed) &&
  	    is_writable_pte(new_spte)) {
+		/* For memory slot operations, use GFN without aliasing */
+		gfn = gfn & ~kvm_gfn_shared_mask(kvm);
  		slot = __gfn_to_memslot(__kvm_memslots(kvm, as_id), gfn);
  		mark_page_dirty_in_slot(kvm, slot, gfn);
  	}
@@ -500,7 +514,8 @@ static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared)
  							  REMOVED_SPTE, level);
  		}
  		ret = handle_changed_spte(kvm, kvm_mmu_page_as_id(sp), gfn,
-					  old_spte, REMOVED_SPTE, level, shared);
+					  old_spte, REMOVED_SPTE, sp->role,
+					  shared);
  		/*
  		 * We are removing page tables.  Because in TDX case we don't
  		 * zap private page tables except tearing down VM.  It means
@@ -509,9 +524,81 @@ static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared)
  		WARN_ON_ONCE(ret);
  	}
 
+	if (is_private_sp(sp) &&
+	    WARN_ON(static_call(kvm_x86_free_private_spt)(kvm, sp->gfn, sp->role.level,
+							  kvm_mmu_private_spt(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_spt(sp, NULL);
+	}
+
  	call_rcu(&sp->rcu_head, tdp_mmu_free_sp_rcu_callback);
  }
 
+static void *get_private_spt(gfn_t gfn, u64 new_spte, int level)
+{
+	if (is_shadow_present_pte(new_spte) && !is_last_spte(new_spte, level)) {
+		struct kvm_mmu_page *sp = to_shadow_page(pfn_to_hpa(spte_to_pfn(new_spte)));
+		void *private_spt = kvm_mmu_private_spt(sp);
+
+		WARN_ON_ONCE(!private_spt);
+		WARN_ON_ONCE(sp->role.level + 1 != level);
+		WARN_ON_ONCE(sp->gfn != gfn);
+		return private_spt;
+	}
+
+	return NULL;
+}
+
+static int __must_check handle_changed_private_spte(struct kvm *kvm, gfn_t gfn,

arch/x86/kvm/mmu/tdp_mmu.c static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared) · line 566

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10 -0
+						    u64 old_spte, u64 new_spte,
+						    int level)
+{
+	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);
+	kvm_pfn_t old_pfn = spte_to_pfn(old_spte);
+	kvm_pfn_t new_pfn = spte_to_pfn(new_spte);
+	int ret;

int ret = 0;

Quoted 22 lines
arch/x86/kvm/mmu/tdp_mmu.c +22 -0
+
+	lockdep_assert_held(&kvm->mmu_lock);
+	if (is_present) {
+		/* TDP MMU doesn't change present -> present */
+		KVM_BUG_ON(was_present, kvm);
+
+		/*
+		 * Use different call to either set up middle level
+		 * private page table, or leaf.
+		 */
+		if (is_leaf)
+			ret = static_call(kvm_x86_set_private_spte)(kvm, gfn, level, new_pfn);
+		else {
+			void *private_spt = get_private_spt(gfn, new_spte, level);
+
+			KVM_BUG_ON(!private_spt, kvm);
+			ret = static_call(kvm_x86_link_private_spt)(kvm, gfn, level, private_spt);
+		}
+	} else if (was_leaf) {
+		/* non-present -> non-present doesn't make sense. */
+		KVM_BUG_ON(!was_present, kvm);
+		/*

arch/x86/kvm/mmu/tdp_mmu.c static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared) · line 598

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10 -0
+		 * Zap private leaf SPTE.  Zapping private table is done
+		 * below in handle_removed_tdp_mmu_page().
+		 */
+		lockdep_assert_held_write(&kvm->mmu_lock);
+		ret = static_call(kvm_x86_zap_private_spte)(kvm, gfn, level);
+		if (!ret) {
+			ret = static_call(kvm_x86_remove_private_spte)(kvm, gfn, level, old_pfn);
+			WARN_ON_ONCE(ret);
+		}
+	}

Otherwise, "ret" may be returned without initialization. Then it will trigger the WARN_ON_ONCE(ret) after handle_changed_spte() in patch 48.

Quoted 331 lines
arch/x86/kvm/mmu/tdp_mmu.c +129 -23
+	return ret;
+}
+
  /**
   * __handle_changed_spte - handle bookkeeping associated with an SPTE change
   * @kvm: kvm instance
@@ -519,7 +606,7 @@ static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared)
   * @gfn: the base GFN that was mapped by the SPTE
   * @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
+ * @role: the role of the PT the SPTE is part of in the paging structure
   * @shared: This operation may not be running under the exclusive use of
   *	    the MMU lock and the operation must synchronize with other
   *	    threads that might be modifying SPTEs.
@@ -528,14 +615,18 @@ static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared)
   * This function must be called for all TDP SPTE modifications.
   */
  static int __must_check __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
-					      u64 old_spte, u64 new_spte, int level,
-					      bool shared)
+					      u64 old_spte, u64 new_spte,
+					      union kvm_mmu_page_role role, bool shared)
  {
+	bool is_private = kvm_mmu_page_role_is_private(role);
+	int level = role.level;
  	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);
@@ -602,7 +693,7 @@ static int __must_check __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t
 
  	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);
 
  	/*
  	 * Recursively handle child PTs if the change removed a subtree from
@@ -611,26 +702,42 @@ static int __must_check __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t
  	 * pages are kernel allocations and should never be migrated.
  	 */
  	if (was_present && !was_leaf &&
-	    (is_leaf || !is_present || WARN_ON_ONCE(pfn_changed)))
+	    (is_leaf || !is_present || WARN_ON_ONCE(pfn_changed))) {
+		KVM_BUG_ON(is_private != is_private_sptep(spte_to_child_pt(old_spte, level)),
+			   kvm);
  		handle_removed_pt(kvm, spte_to_child_pt(old_spte, level), shared);
+	}
 
+	/*
+	 * 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.
+	 *
+	 * This is after handling lower page table by above
+	 * handle_remove_tdp_mmu_page().  Secure-EPT requires to remove
+	 * Secure-EPT tables after removing children.
+	 */
+	if (is_private &&
+	    /* Ignore change of software only bits. e.g. host_writable */
+	    (was_leaf != is_leaf || was_present != is_present || pfn_changed))
+		return handle_changed_private_spte(kvm, gfn, old_spte, new_spte, role.level);
  	return 0;
  }
 
  static int __must_check handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
-					    u64 old_spte, u64 new_spte, int level,
+					    u64 old_spte, u64 new_spte,
+					    union kvm_mmu_page_role role,
  					    bool shared)
  {
  	int ret;
 
-	ret = __handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, level,
-				    shared);
+	ret = __handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, role, shared);
  	if (ret)
  		return ret;
 
-	handle_changed_spte_acc_track(old_spte, new_spte, level);
+	handle_changed_spte_acc_track(old_spte, new_spte, role.level);
  	handle_changed_spte_dirty_log(kvm, as_id, gfn, old_spte,
-				      new_spte, level);
+				      new_spte, role.level);
  	return 0;
  }
 
@@ -656,6 +763,24 @@ static inline int __must_check tdp_mmu_set_spte_atomic(struct kvm *kvm,
  						       struct tdp_iter *iter,
  						       u64 new_spte)
  {
+	/*
+	 * For conventional page table, the update flow is
+	 * - update STPE with atomic operation
+	 * - handle changed SPTE. __handle_changed_spte()
+	 * NOTE: __handle_changed_spte() (and functions) must be safe against
+	 * concurrent update.  It is an exception to zap SPTE.  See
+	 * tdp_mmu_zap_spte_atomic().
+	 *
+	 * For private page table, callbacks are needed to propagate SPTE
+	 * change into the protected page table.  In order to atomically update
+	 * both the SPTE and the protected page tables with callbacks, utilize
+	 * freezing SPTE.
+	 * - Freeze the SPTE. Set entry to REMOVED_SPTE.
+	 * - Trigger callbacks for protected page tables. __handle_changed_spte()
+	 * - Unfreeze the SPTE.  Set the entry to new_spte.
+	 */
+	bool freeze_spte = is_private_sptep(iter->sptep) && !is_removed_spte(new_spte);
+	u64 tmp_spte = freeze_spte ? REMOVED_SPTE : new_spte;
  	u64 *sptep = rcu_dereference(iter->sptep);
  	int ret;
 
@@ -673,14 +798,24 @@ static inline int __must_check tdp_mmu_set_spte_atomic(struct kvm *kvm,
  	 * Note, fast_pf_fix_direct_spte() can also modify TDP MMU SPTEs and
  	 * does not hold the mmu_lock.
  	 */
-	if (!try_cmpxchg64(sptep, &iter->old_spte, new_spte))
+	if (!try_cmpxchg64(sptep, &iter->old_spte, tmp_spte))
  		return -EBUSY;
 
  	ret = __handle_changed_spte(kvm, iter->as_id, iter->gfn, iter->old_spte,
-				    new_spte, iter->level, true);
+				    new_spte, sptep_to_sp(sptep)->role, true);
  	if (!ret)
  		handle_changed_spte_acc_track(iter->old_spte, new_spte, iter->level);
 
+	if (ret) {
+		/*
+		 * !freeze_spte means this fault isn't private.  No call to
+		 * operation on Secure EPT.
+		 */
+		WARN_ON_ONCE(!freeze_spte);
+		__kvm_tdp_mmu_write_spte(sptep, iter->old_spte);
+	} else if (freeze_spte)
+		__kvm_tdp_mmu_write_spte(sptep, new_spte);
+
  	return ret;
  }
 
@@ -750,6 +885,7 @@ static u64 __tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep,
  			      u64 old_spte, u64 new_spte, gfn_t gfn, int level,
  			      bool record_acc_track, bool record_dirty_log)
  {
+	union kvm_mmu_page_role role;
  	int ret;
 
  	lockdep_assert_held_write(&kvm->mmu_lock);
@@ -765,7 +901,9 @@ static u64 __tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep,
 
  	old_spte = kvm_tdp_mmu_write_spte(sptep, old_spte, new_spte, level);
 
-	ret = __handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, level, false);
+	role = sptep_to_sp(sptep)->role;
+	role.level = level;
+	ret = __handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, role, false);
  	/* Because write spin lock is held, no race.  It should success. */
  	WARN_ON_ONCE(ret);
 
@@ -819,8 +957,11 @@ 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, to_shadow_page(_mmu->root.hpa), _start, _end)
+#define tdp_mmu_for_each_pte(_iter, _mmu, _private, _start, _end)	\
+	for_each_tdp_pte(_iter,						\
+		 to_shadow_page((_private) ? _mmu->private_root_hpa :	\
+				_mmu->root.hpa),			\
+		_start, _end)
 
  /*
   * Yield if the MMU lock is contended or this thread needs to return control
@@ -983,6 +1124,14 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
  	if (!zap_private && is_private_sp(root))
  		return false;
 
+	/*
+	 * start and end doesn't have GFN shared bit.  This function zaps
+	 * a region including alias.  Adjust shared bit of [start, end) if the
+	 * root is shared.
+	 */
+	start = kvm_gfn_for_root(kvm, root, start);
+	end = kvm_gfn_for_root(kvm, root, end);
+
  	rcu_read_lock();
 
  	for_each_tdp_pte_min_level(iter, root, PG_LEVEL_4K, start, end) {
@@ -1111,10 +1260,19 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
  	WARN_ON(sp->role.level != fault->goal_level);
  	if (unlikely(!fault->slot))
  		new_spte = make_mmio_spte(vcpu, iter->gfn, ACC_ALL);
-	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);
+	else {
+		unsigned long pte_access = ACC_ALL;
+		gfn_t gfn_unalias = iter->gfn & ~kvm_gfn_shared_mask(vcpu->kvm);
+
+		/* TDX shared GPAs are no executable, enforce this for the SDV. */
+		if (kvm_gfn_shared_mask(vcpu->kvm) && !fault->is_private)
+			pte_access &= ~ACC_EXEC_MASK;
+
+		wrprot = make_spte(vcpu, sp, fault->slot, pte_access,
+				   gfn_unalias, fault->pfn, iter->old_spte,
+				   fault->prefetch, true, fault->map_writable,
+				   &new_spte);
+	}
 
  	if (new_spte == iter->old_spte)
  		ret = RET_PF_SPURIOUS;
@@ -1214,6 +1372,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 = fault->is_private;
  	int ret;
 
  	kvm_mmu_hugepage_adjust(vcpu, fault);
@@ -1222,7 +1382,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);
+
+	if (is_error_noslot_pfn(fault->pfn) ||
+	    !kvm_pfn_to_refcounted_page(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);
 
@@ -1238,6 +1408,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
+			 */
+			KVM_BUG_ON(is_private_sptep(iter.sptep), vcpu->kvm);
+
 
  			/*
  			 * The iter must explicitly re-read the spte here
@@ -1480,6 +1656,12 @@ static struct kvm_mmu_page *__tdp_mmu_alloc_sp_for_split(gfp_t gfp, union kvm_mm
 
  	sp->role = role;
  	sp->spt = (void *)__get_free_page(gfp);
+	if (kvm_mmu_page_role_is_private(role)) {
+		if (kvm_alloc_private_spt_for_split(sp, gfp)) {
+			free_page((unsigned long)sp->spt);
+			sp->spt = NULL;
+		}
+	}
  	if (!sp->spt) {
  		kmem_cache_free(mmu_page_header_cache, sp);
  		return NULL;
@@ -1495,6 +1677,11 @@ static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split(struct kvm *kvm,
  	union kvm_mmu_page_role role = tdp_iter_child_role(iter);
  	struct kvm_mmu_page *sp;
 
+	KVM_BUG_ON(kvm_mmu_page_role_is_private(role) !=
+		   is_private_sptep(iter->sptep), kvm);
+	/* TODO: Large page isn't supported for private SPTE yet. */
+	KVM_BUG_ON(kvm_mmu_page_role_is_private(role), kvm);
+
  	/*
  	 * Since we are allocating while under the MMU lock we have to be
  	 * careful about GFP flags. Use GFP_NOWAIT to avoid blocking on direct
@@ -1929,7 +2116,7 @@ int kvm_tdp_mmu_get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes,
  	if (WARN_ON_ONCE(kvm_gfn_shared_mask(vcpu->kvm)))
  		return leaf;
 
-	tdp_mmu_for_each_pte(iter, mmu, gfn, gfn + 1) {
+	tdp_mmu_for_each_pte(iter, mmu, false, gfn, gfn + 1) {
  		leaf = iter.level;
  		sptes[leaf] = iter.old_spte;
  	}
@@ -1956,7 +2143,10 @@ u64 *kvm_tdp_mmu_fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, u64 addr,
  	gfn_t gfn = addr >> PAGE_SHIFT;
  	tdp_ptep_t sptep = NULL;
 
-	tdp_mmu_for_each_pte(iter, mmu, gfn, gfn + 1) {
+	/* fast page fault for private GPA isn't supported. */
+	WARN_ON_ONCE(kvm_is_private_gpa(vcpu->kvm, addr));
+
+	tdp_mmu_for_each_pte(iter, mmu, false, gfn, gfn + 1) {
  		*spte = iter.old_spte;
  		sptep = iter.sptep;
  	}
arch/x86/kvm/mmu/tdp_mmu.h +1 -1
index c98c7df449a8..695175c921a5 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_mmu_page *root)
  {
virt/kvm/kvm_main.c +1 -0
index dda2f2ec4faa..8c996f40b544 100644
@@ -211,6 +211,7 @@ struct page *kvm_pfn_to_refcounted_page(kvm_pfn_t pfn)
 
  	return NULL;
  }
+EXPORT_SYMBOL_GPL(kvm_pfn_to_refcounted_page);
 
  /*
   * Switches to specified vcpu, until a matching vcpu_put()
#176 lore raw

Re: [PATCH v10 077/108] KVM: x86: Add a switch_db_regs flag to handle TDX's auto-switched behavior

In reply to [email protected]
Quoted 75 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a flag, KVM_DEBUGREG_AUTO_SWITCHED_GUEST, to skip saving/restoring DRs irrespective of any other flags. TDX-SEAM unconditionally saves and restores guest DRs and reset to architectural INIT state on TD exit. So, KVM needs to save host DRs before TD enter without restoring guest DRs and restore host DRs after TD exit.

Opportunistically convert the KVM_DEBUGREG_* definitions to use BIT().

---
  arch/x86/include/asm/kvm_host.h |  9 +++++++--
  arch/x86/kvm/vmx/tdx.c          |  1 +
  arch/x86/kvm/x86.c              | 11 ++++++++---
  3 files changed, 16 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm_host.h +7 -2
index fdb00d96e954..082e94f78c66 100644
@@ -583,8 +583,13 @@ struct kvm_pmu {
  struct kvm_pmu_ops;
 
  enum {
-	KVM_DEBUGREG_BP_ENABLED = 1,
-	KVM_DEBUGREG_WONT_EXIT = 2,
+	KVM_DEBUGREG_BP_ENABLED		= BIT(0),
+	KVM_DEBUGREG_WONT_EXIT		= BIT(1),
+	/*
+	 * Guest debug registers are saved/restored by hardware on exit from
+	 * or enter guest. KVM needn't switch them.
+	 */
+	KVM_DEBUGREG_AUTO_SWITCH	= BIT(2),
  };
 
  struct kvm_mtrr_range {
arch/x86/kvm/vmx/tdx.c +1 -0
index fc4de83a2df8..57767ef3353b 100644
@@ -429,6 +429,7 @@ int tdx_vcpu_create(struct kvm_vcpu *vcpu)
 
  	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
 
+	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 +2 -1
index 4d4b71c4cdb1..ad7b227b68dd 100644
@@ -10779,7 +10779,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);
@@ -10822,6 +10822,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);

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 10842

Quoted 10 lines
arch/x86/kvm/x86.c +5 -2
@@ -10834,8 +10835,12 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	 * care about the messed up debug address registers. But if
  	 * we have some of them active, restore the old state.
  	 */
-	if (hw_breakpoint_active())
-		hw_breakpoint_restore();
+	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);

Why only restore dr7 when TD exit?

According to the commit message, dr0~dr3 are also reset to architectural INIT value on TD exit.

Quoted 4 lines
arch/x86/kvm/x86.c +1 -0
+	}
 
  	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
  	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
#52 lore raw

Re: [PATCH v10 021/108] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]
Quoted 355 lines · On 10/30/2022 2:22 PM, [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.

This subcommand is called before creating vcpu and KVM_SET_CPUID2, i.e. cpuids configurations aren't available yet. So CPUIDs configuration values needs to be passed in struct kvm_init_vm. It's device model responsibility to make this cpuid config for KVM_TDX_INIT_VM and KVM_SET_CPUID2.

---
 arch/x86/include/asm/tdx.h            |   3 +
 arch/x86/include/uapi/asm/kvm.h       |  31 +++
 arch/x86/kvm/vmx/tdx.c                | 296 ++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.h                |  22 ++
 tools/arch/x86/include/uapi/asm/kvm.h |  33 +++
 5 files changed, 347 insertions(+), 38 deletions(-)
arch/x86/include/asm/tdx.h +3 -0
index cd304d323d33..05ac4bfc8f8a 100644
@@ -131,6 +131,9 @@ static inline long tdx_kvm_hypercall(unsigned int nr, unsigned long p1,
 #endif /* CONFIG_INTEL_TDX_GUEST && CONFIG_KVM_GUEST */
 
 #ifdef CONFIG_INTEL_TDX_HOST
+
+/* -1 indicates CPUID leaf with no sub-leaves. */
+#define TDX_CPUID_NO_SUBLEAF	((u32)-1)
 struct tdx_cpuid_config {
 	u32	leaf;
 	u32	sub_leaf;
arch/x86/include/uapi/asm/kvm.h +31 -0
index 2ad9666e02a5..26661879c031 100644
@@ -538,6 +538,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,
 };
@@ -583,4 +584,34 @@ struct kvm_tdx_capabilities {
 	struct kvm_tdx_cpuid_config cpuid_configs[0];
 };
 
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha348 digest */
+	union {
+		/*
+		 * KVM_TDX_INIT_VM is called before vcpu creation, thus before
+		 * KVM_SET_CPUID2.  CPUID configurations needs to be passed.
+		 *
+		 * This configuration supersedes KVM_SET_CPUID{,2}.
+		 * The user space VMM, e.g. qemu, should make them consistent
+		 * with this values.
+		 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(256)
+		 * = 8KB.
+		 */
+		struct {
+			struct kvm_cpuid2 cpuid;
+			/* 8KB with KVM_MAX_CPUID_ENTRIES. */
+			struct kvm_cpuid_entry2 entries[];
+		};
+		/*
+		 * For future extensibility.
+		 * The size(struct kvm_tdx_init_vm) = 16KB.
+		 * This should be enough given sizeof(TD_PARAMS) = 1024
+		 */
+		__u64 reserved[2029];
+	};
+};
+
 #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/tdx.c +217 -17
index d77709a6da51..54045e0576e7 100644
@@ -284,6 +284,205 @@ static int tdx_do_tdh_mng_key_config(void *param)
 int tdx_vm_init(struct kvm *kvm)
 {
 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+
+	kvm_tdx->hkid = -1;
+
+	/*
+	 * This function initializes only KVM software construct.  It doesn't
+	 * initialize TDX stuff, e.g. TDCS, TDR, TDCX, HKID etc.
+	 * It is handled by KVM_TDX_INIT_VM, __tdx_td_init().
+	 */
+
+	return 0;
+}
+
+int tdx_dev_ioctl(void __user *argp)
+{
+	struct kvm_tdx_capabilities __user *user_caps;
+	struct kvm_tdx_capabilities caps;
+	struct kvm_tdx_cmd cmd;
+
+	BUILD_BUG_ON(sizeof(struct kvm_tdx_cpuid_config) !=
+		     sizeof(struct tdx_cpuid_config));
+
+	if (copy_from_user(&cmd, argp, sizeof(cmd)))
+		return -EFAULT;
+	if (cmd.flags || cmd.error || cmd.unused)
+		return -EINVAL;
+	/*
+	 * Currently only KVM_TDX_CAPABILITIES is defined for system-scoped
+	 * mem_enc_ioctl().
+	 */
+	if (cmd.id != KVM_TDX_CAPABILITIES)
+		return -EINVAL;
+
+	user_caps = (void __user *)cmd.data;
+	if (copy_from_user(&caps, user_caps, sizeof(caps)))
+		return -EFAULT;
+
+	if (caps.nr_cpuid_configs < tdx_caps.nr_cpuid_configs)
+		return -E2BIG;
+
+	caps = (struct kvm_tdx_capabilities) {
+		.attrs_fixed0 = tdx_caps.attrs_fixed0,
+		.attrs_fixed1 = tdx_caps.attrs_fixed1,
+		.xfam_fixed0 = tdx_caps.xfam_fixed0,
+		.xfam_fixed1 = tdx_caps.xfam_fixed1,
+		.nr_cpuid_configs = tdx_caps.nr_cpuid_configs,
+		.padding = 0,
+	};
+
+	if (copy_to_user(user_caps, &caps, sizeof(caps)))
+		return -EFAULT;
+	if (copy_to_user(user_caps->cpuid_configs, &tdx_caps.cpuid_configs,
+			 tdx_caps.nr_cpuid_configs *
+			 sizeof(struct tdx_cpuid_config)))
+		return -EFAULT;
+
+	return 0;
+}
+
+/*
+ * cpuid entry lookup in TDX cpuid config way.
+ * The difference is how to specify index(subleaves).
+ * Specify index to TDX_CPUID_NO_SUBLEAF for CPUID leaf with no-subleaves.
+ */
+static const struct kvm_cpuid_entry2 *tdx_find_cpuid_entry(const struct kvm_cpuid2 *cpuid,
+							   u32 function, u32 index)
+{
+	int i;
+
+	/* In TDX CPU CONFIG, TDX_CPUID_NO_SUBLEAF means index = 0. */
+	if (index == TDX_CPUID_NO_SUBLEAF)
+		index = 0;
+
+	for (i = 0; i < cpuid->nent; i++) {
+		const struct kvm_cpuid_entry2 *e = &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)
+{
+	const struct kvm_cpuid2 *cpuid = &init_vm->cpuid;
+	const struct kvm_cpuid_entry2 *entry;
+	u64 guest_supported_xcr0;
+	u64 guest_supported_xss;
+	int max_pa;
+	int i;
+
+	if (kvm->created_vcpus)
+		return -EBUSY;
+	td_params->max_vcpus = kvm->max_vcpus;
+	td_params->attributes = init_vm->attributes;
+	if (td_params->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+		/*
+		 * TODO: save/restore PMU related registers around TDENTER.
+		 * Once it's done, remove this guard.
+		 */
+		pr_warn("TD doesn't support perfmon yet. KVM needs to save/restore "
+			"host perf registers properly.\n");
+		return -EOPNOTSUPP;
+	}
+
+	for (i = 0; i < tdx_caps.nr_cpuid_configs; i++) {
+		const struct tdx_cpuid_config *config = &tdx_caps.cpuid_configs[i];
+		const struct kvm_cpuid_entry2 *entry =
+			tdx_find_cpuid_entry(cpuid, config->leaf, config->sub_leaf);
+		struct tdx_cpuid_value *value = &td_params->cpuid_values[i];
+
+		if (!entry)
+			continue;
+
+		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(cpuid, 0x80000008, 0);
+	if (entry)
+		max_pa = entry->eax & 0xff;
+
+	td_params->eptp_controls = VMX_EPTP_MT_WB;
+	/*
+	 * No CPU supports 4-level && max_pa > 48.
+	 * "5-level paging and 5-level EPT" section 4.1 4-level EPT
+	 * "4-level EPT is limited to translating 48-bit guest-physical
+	 *  addresses."
+	 * cpu_has_vmx_ept_5levels() check is just in case.
+	 */
+	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;
+	}
+
+	/* Setup td_params.xfam */
+	entry = tdx_find_cpuid_entry(cpuid, 0xd, 0);
+	if (entry)
+		guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+	else
+		guest_supported_xcr0 = 0;
+	guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+	entry = tdx_find_cpuid_entry(cpuid, 0xd, 1);
+	if (entry)
+		guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+	else
+		guest_supported_xss = 0;
+	/* PT can be exposed to TD guest regardless of KVM's XSS support */
+	guest_supported_xss &= (kvm_caps.supported_xss | XFEATURE_MASK_PT);
+
+	td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+	if (td_params->xfam & XFEATURE_MASK_LBR) {
+		/*
+		 * TODO: once KVM supports LBR(save/restore LBR related
+		 * registers around TDENTER), remove this guard.
+		 */
+		pr_warn("TD doesn't support LBR yet. KVM needs to save/restore "
+			"IA32_LBR_DEPTH properly.\n");
+		return -EOPNOTSUPP;
+	}
+
+	if (td_params->xfam & XFEATURE_MASK_XTILE) {
+		/*
+		 * TODO: once KVM supports AMX(save/restore AMX related
+		 * registers around TDENTER), remove this guard.
+		 */
+		pr_warn("TD doesn't support AMX yet. KVM needs to save/restore "
+			"IA32_XFD, IA32_XFD_ERR properly.\n");
+		return -EOPNOTSUPP;
+	}
+
+	td_params->tsc_frequency =
+		TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
+
+#define MEMCPY_SAME_SIZE(dst, src)				\
+	do {							\
+		BUILD_BUG_ON(sizeof(dst) != sizeof(src));	\
+		memcpy((dst), (src), sizeof(dst));		\
+	} while (0)
+
+	MEMCPY_SAME_SIZE(td_params->mrconfigid, init_vm->mrconfigid);
+	MEMCPY_SAME_SIZE(td_params->mrowner, init_vm->mrowner);
+	MEMCPY_SAME_SIZE(td_params->mrownerconfig, init_vm->mrownerconfig);
+
+	return 0;
+}
+
+static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	struct tdx_module_output out;
 	cpumask_var_t packages;
 	int ret, i;
 	u64 err;
@@ -390,10 +589,13 @@ int tdx_vm_init(struct kvm *kvm)
 		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.
-	 */
+	err = tdh_mng_init(kvm_tdx->tdr.pa, __pa(td_params), &out);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_INIT, err, &out);
+		ret = -EIO;
+		goto teardown;
+	}
+
 	return 0;
 
 	/*
@@ -431,50 +633,65 @@ int tdx_vm_init(struct kvm *kvm)
 	return ret;
 }
 
-int tdx_dev_ioctl(void __user *argp)
+static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 {
-	struct kvm_tdx_capabilities __user *user_caps;
-	struct kvm_tdx_capabilities caps;
-	struct kvm_tdx_cmd cmd;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	struct kvm_tdx_init_vm *init_vm = NULL;
+	struct td_params *td_params = NULL;
+	void *entries_end;
+	int ret;
 
-	BUILD_BUG_ON(sizeof(struct kvm_tdx_cpuid_config) !=
-		     sizeof(struct tdx_cpuid_config));
+	BUILD_BUG_ON(sizeof(*init_vm) != 16 * 1024);
+	BUILD_BUG_ON((sizeof(*init_vm) - offsetof(typeof(*init_vm), entries)) /
+		     sizeof(init_vm->entries[0]) < KVM_MAX_CPUID_ENTRIES);
+	BUILD_BUG_ON(sizeof(struct td_params) != 1024);
 
-	if (copy_from_user(&cmd, argp, sizeof(cmd)))
-		return -EFAULT;
-	if (cmd.flags || cmd.error || cmd.unused)
+	if (is_td_initialized(kvm))
 		return -EINVAL;
-	/*
-	 * Currently only KVM_TDX_CAPABILITIES is defined for system-scoped
-	 * mem_enc_ioctl().
-	 */

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +4 -4
-	if (cmd.id != KVM_TDX_CAPABILITIES)
+
+	if (cmd->flags)
 		return -EINVAL;
 
-	user_caps = (void __user *)cmd.data;
-	if (copy_from_user(&caps, user_caps, sizeof(caps)))
-		return -EFAULT;
+	init_vm = kzalloc(sizeof(*init_vm), GFP_KERNEL);
+	if (copy_from_user(init_vm, (void __user *)cmd->data, sizeof(*init_vm))) {

Pointer 'init_vm' returned from call to function 'kzalloc' may be NULL and will be dereferenced at this line.

Maybe a NULL-check here is needed?

Quoted 165 lines
arch/x86/kvm/vmx/tdx.c +37 -17
+		ret = -EFAULT;
+		goto out;
+	}
 
-	if (caps.nr_cpuid_configs < tdx_caps.nr_cpuid_configs)
-		return -E2BIG;
+	ret = -EINVAL;
+	if (init_vm->cpuid.padding)
+		goto out;
+	/* init_vm->entries shouldn't overrun. */
+	entries_end = init_vm->entries + init_vm->cpuid.nent;
+	if (entries_end > (void *)(init_vm + 1))
+		goto out;
+	/* Unused part must be zero. */
+	if (memchr_inv(entries_end, 0, (void *)(init_vm + 1) - entries_end))
+		goto out;
 
-	caps = (struct kvm_tdx_capabilities) {
-		.attrs_fixed0 = tdx_caps.attrs_fixed0,
-		.attrs_fixed1 = tdx_caps.attrs_fixed1,
-		.xfam_fixed0 = tdx_caps.xfam_fixed0,
-		.xfam_fixed1 = tdx_caps.xfam_fixed1,
-		.nr_cpuid_configs = tdx_caps.nr_cpuid_configs,
-		.padding = 0,
-	};
+	td_params = kzalloc(sizeof(struct td_params), GFP_KERNEL);
+	if (!td_params) {
+		ret = -ENOMEM;
+		goto out;
+	}
 
-	if (copy_to_user(user_caps, &caps, sizeof(caps)))
-		return -EFAULT;
-	if (copy_to_user(user_caps->cpuid_configs, &tdx_caps.cpuid_configs,
-			 tdx_caps.nr_cpuid_configs *
-			 sizeof(struct tdx_cpuid_config)))
-		return -EFAULT;
+	ret = setup_tdparams(kvm, td_params, init_vm);
+	if (ret)
+		goto out;
 
-	return 0;
+	ret = __tdx_td_init(kvm, td_params);
+	if (ret)
+		goto out;
+
+	kvm_tdx->tsc_offset = td_tdcs_exec_read64(kvm_tdx, TD_TDCS_EXEC_TSC_OFFSET);
+	kvm_tdx->attributes = td_params->attributes;
+	kvm_tdx->xfam = td_params->xfam;
+
+out:
+	/* kfree() accepts NULL. */
+	kfree(init_vm);
+	kfree(td_params);
+	return ret;
 }
 
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
@@ -490,6 +707,9 @@ int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
 	mutex_lock(&kvm->lock);
 
 	switch (tdx_cmd.id) {
+	case KVM_TDX_INIT_VM:
+		r = tdx_td_init(kvm, &tdx_cmd);
+		break;
 	default:
 		r = -EINVAL;
 		goto out;
arch/x86/kvm/vmx/tdx.h +22 -0
index 938314635b47..ff0ea9cad347 100644
@@ -18,7 +18,11 @@ struct kvm_tdx {
 	struct tdx_td_page tdr;
 	struct tdx_td_page *tdcs;
 
+	u64 attributes;
+	u64 xfam;
 	int hkid;
+
+	u64 tsc_offset;
 };
 
 struct vcpu_tdx {
@@ -48,6 +52,11 @@ static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
 	return container_of(vcpu, struct vcpu_tdx, vcpu);
 }
 
+static inline bool is_td_initialized(struct kvm *kvm)
+{
+	return to_kvm_tdx(kvm)->hkid > 0;
+}
+
 static __always_inline void tdvps_vmcs_check(u32 field, u8 bits)
 {
 #define VMCS_ENC_ACCESS_TYPE_MASK	0x1UL
@@ -148,6 +157,19 @@ TDX_BUILD_TDVPS_ACCESSORS(64, VMCS, vmcs);
 TDX_BUILD_TDVPS_ACCESSORS(64, STATE_NON_ARCH, state_non_arch);
 TDX_BUILD_TDVPS_ACCESSORS(8, MANAGEMENT, management);
 
+static __always_inline u64 td_tdcs_exec_read64(struct kvm_tdx *kvm_tdx, u32 field)
+{
+	struct tdx_module_output out;
+	u64 err;
+
+	err = tdh_mng_rd(kvm_tdx->tdr.pa, TDCS_EXEC(field), &out);
+	if (unlikely(err)) {
+		pr_err("TDH_MNG_RD[EXEC.0x%x] failed: 0x%llx\n", field, err);
+		return 0;
+	}
+	return out.r8;
+}
+
 #else
 struct kvm_tdx {
 	struct kvm kvm;
tools/arch/x86/include/uapi/asm/kvm.h +33 -0
index 2ad9666e02a5..531a0033e530 100644
@@ -538,6 +538,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,
 };
@@ -583,4 +584,36 @@ struct kvm_tdx_capabilities {
 	struct kvm_tdx_cpuid_config cpuid_configs[0];
 };
 
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u32 max_vcpus;
+	__u32 padding;
+	__u64 mrconfigid[6];    /* sha384 digest */
+	__u64 mrowner[6];       /* sha384 digest */
+	__u64 mrownerconfig[6]; /* sha348 digest */
+	union {
+		/*
+		 * KVM_TDX_INIT_VM is called before vcpu creation, thus before
+		 * KVM_SET_CPUID2.  CPUID configurations needs to be passed.
+		 *
+		 * This configuration supersedes KVM_SET_CPUID{,2}.
+		 * The user space VMM, e.g. qemu, should make them consistent
+		 * with this values.
+		 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(256)
+		 * = 8KB.
+		 */
+		struct {
+			struct kvm_cpuid2 cpuid;
+			/* 8KB with KVM_MAX_CPUID_ENTRIES. */
+			struct kvm_cpuid_entry2 entries[];
+		};
+		/*
+		 * For future extensibility.
+		 * The size(struct kvm_tdx_init_vm) = 16KB.
+		 * This should be enough given sizeof(TD_PARAMS) = 1024
+		 */
+		__u64 reserved[2028];
+	};
+};
+
 #endif /* _ASM_X86_KVM_H */
#101 lore raw

Re: [PATCH v10 041/108] KVM: x86/tdp_mmu: refactor kvm_tdp_mmu_map()

In reply to [email protected]
Quoted 5 lines · On Sat, 2022-10-29 at 23:22 -0700, [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.

Is this patch still valid/needed since you have changed to use XArray to store whether GFN is private or shared?

Quoted 58 lines
---
 arch/x86/kvm/mmu/tdp_mmu.c | 26 +++++++++++++++++++-------
 1 file changed, 19 insertions(+), 7 deletions(-)
arch/x86/kvm/mmu/tdp_mmu.c +19 -7
index 3325633b1cb5..11b0ec8aebe2 100644
@@ -1157,6 +1157,24 @@ static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter,
 	return 0;
 }
 
+static int tdp_mmu_populate_nonleaf(struct kvm_vcpu *vcpu, struct tdp_iter *iter,
+				    bool account_nx)
+{
+	struct kvm_mmu_page *sp;
+	int ret;
+
+	KVM_BUG_ON(is_shadow_present_pte(iter->old_spte), vcpu->kvm);
+	KVM_BUG_ON(is_removed_spte(iter->old_spte), vcpu->kvm);
+
+	sp = tdp_mmu_alloc_sp(vcpu);
+	tdp_mmu_init_child_sp(sp, iter);
+
+	ret = tdp_mmu_link_sp(vcpu->kvm, iter, sp, account_nx, true);
+	if (ret)
+		tdp_mmu_free_sp(sp);
+	return ret;
+}
+
 /*
  * Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing
  * page tables and SPTEs to translate the faulting guest physical address.
@@ -1165,7 +1183,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;
 	int ret;
 
 	kvm_mmu_hugepage_adjust(vcpu, fault);
@@ -1211,13 +1228,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 			if (is_removed_spte(iter.old_spte))
 				break;
 
-			sp = tdp_mmu_alloc_sp(vcpu);
-			tdp_mmu_init_child_sp(sp, &iter);
-
-			if (tdp_mmu_link_sp(vcpu->kvm, &iter, sp, account_nx, true)) {
-				tdp_mmu_free_sp(sp);
+			if (tdp_mmu_populate_nonleaf(vcpu, &iter, account_nx))
 				break;
-			}
 		}
 	}
 
#107 lore raw

Re: [PATCH v10 045/108] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to [email protected]
Quoted 60 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

For private GPA, CPU refers a private page table whose contents are encrypted. The dedicated APIs to operate on it (e.g. updating/reading its PTE entry) are used and their cost is expensive.

When KVM resolves KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost to directly walk protected (encrypted) page table, allocate one more page to copy the protected page table for KVM MMU code to directly walk. Resolve KVM page fault with the existing code, and do additional operations necessary for the protected page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e. not associated with protected page table), and the page table with protected page table is called a private page table. The relationship is depicted below.

Add a private pointer to struct kvm_mmu_page for protected page table and add helper functions to allocate/initialize/free a protected page table page.

              KVM page fault                     |
                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
    shared PT root      private PT root          |    protected PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            private PT ----propagate----> protected PT
        |                      |                 |           |
        |                      \-----------------+------\    |
        |                                        |      |    |
        V                                        |      V    V
  shared guest page                              |    private guest page
                                                 |
                           non-encrypted memory  |    encrypted memory
                                                 |

PT: page table
- Shared PT is visible to KVM and it is used by CPU.
- Protected PT is used by CPU but it is invisible to KVM.
- Private PT is visible to KVM but not used by CPU. It is used to propagate PT change to the actual protected PT which is used by CPU.

---
 arch/x86/include/asm/kvm_host.h |  7 +++
 arch/x86/kvm/mmu/mmu.c          |  8 +++
 arch/x86/kvm/mmu/mmu_internal.h | 90 +++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c      |  1 +
 4 files changed, 102 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index ee01add57a6b..381df2c8136d 100644

arch/x86/include/asm/kvm_host.h struct kvm_vcpu_arch { · line 762

Quoted 9 lines
arch/x86/include/asm/kvm_host.h +6 -0
@@ -754,6 +754,13 @@ struct kvm_vcpu_arch {
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_shadowed_info_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	/*
+	 * This cache is to allocate private page table. E.g.  Secure-EPT used
+	 * by the TDX module.  Because the TDX module doesn't trust VMM and
+	 * initializes the pages itself, KVM doesn't initialize them.  Allocate
+	 * pages with garbage and give them to the TDX module.
+	 */

Perhaps put "Because ..." part to kvm_mmu_create() so people can see why there's no initialization for mmu_private_spte_cache?

arch/x86/include/asm/kvm_host.h struct kvm_vcpu_arch { · line 763

Quoted 1 line
arch/x86/include/asm/kvm_host.h +1 -0
+	struct kvm_mmu_memory_cache mmu_private_spt_cache;

Nit:

In changelog you mentioned the page table used by CPU is actually "protected PT". IIUC the sp->private_spt you allocated from this cache is the one that is actually used by CPU. So looks there's some inconsistency here.

[...]

arch/x86/include/asm/kvm_host.h struct kvm_vcpu_arch {

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +4 -0
+
+static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,
+					     struct kvm_mmu_memory_cache *private_spt_cache,
+					     struct kvm_mmu_page *sp)

This function is very weird in the context of this patch. _Only_ a new vcpu- scope 'mmu_private_spte_cache' is added in this patch, but here you allow caller to pass an additional argument of private_spt_cache. So there must be another cache which is not introduced in this patch?

arch/x86/include/asm/kvm_host.h

Quoted 5 lines
arch/x86/include/asm/kvm_host.h +5 -0
+{
+	/*
+	 * vcpu == NULL means non-root SPT:
+	 * vcpu == NULL is used to split a large SPT into smaller SPT.  Root SPT
+	 * is not a large SPT.

I am guessing this "vcpu == NULL" case is for "Eager Splitting"?

If so, why not adding a global MMU cache for private_spt allocation, and make vcpu->arch.mmu_private_spt_cache point to the global cache? In this case, in the context where you only have 'kvm', you can use the global cache directly. And in the context where you have a 'vcpu', you just use vcpu's cache.

Quoted 24 lines
arch/x86/include/asm/kvm_host.h +24 -0
+	 */
+	bool is_root = vcpu &&
+		vcpu->arch.root_mmu.root_role.level == sp->role.level;
+
+	if (vcpu)
+		private_spt_cache = &vcpu->arch.mmu_private_spt_cache;
+	KVM_BUG_ON(!kvm_mmu_page_role_is_private(sp->role), vcpu->kvm);
+	if (is_root)
+		/*
+		 * Because TDX module assigns root Secure-EPT page and set it to
+		 * Secure-EPTP when TD vcpu is created, secure page table for
+		 * root isn't needed.
+		 */
+		sp->private_spt = NULL;
+	else {
+		sp->private_spt = kvm_mmu_memory_cache_alloc(private_spt_cache);
+		/*
+		 * Because mmu_private_spt_cache is topped up before staring kvm
+		 * page fault resolving, the allocation above shouldn't fail.
+		 */
+		WARN_ON_ONCE(!sp->private_spt);
+	}
+}
+
#108 lore raw

Re: [PATCH v10 045/108] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 21 lines · Kai

Review

Quoted 5 lines
arch/x86/kvm/mmu/mmu_internal.h +3 -0
+
+static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,
+					     struct kvm_mmu_memory_cache

*private_spt_cache,

(quoted diff) +1 -0
+					     struct kvm_mmu_page *sp)

This function is very weird in the context of this patch.  _Only_ a new vcpu- scope 'mmu_private_spte_cache' is added in this patch, but here you allow caller
to pass an additional argument of private_spt_cache.  So there must be another cache which is not introduced in this patch?

arch/x86/kvm/mmu/mmu_internal.h static inline bool is_private_sptep(u64 *sptep) · line 187

Quoted 6 lines
arch/x86/kvm/mmu/mmu_internal.h +4 -0
+{
+	/*
+	 * vcpu == NULL means non-root SPT:
+	 * vcpu == NULL is used to split a large SPT into smaller SPT. 

Root SPT

arch/x86/kvm/mmu/mmu_internal.h +1 -0
+	 * is not a large SPT.

I am guessing this "vcpu == NULL" case is for "Eager Splitting"?

Quoted 4 lines

If so, why not adding a global MMU cache for private_spt allocation, and make vcpu->arch.mmu_private_spt_cache point to the global cache?  In this case, in the context where you only have 'kvm', you can use the global cache directly. And in the context where you have a 'vcpu', you just use vcpu's cache.

So I went through all MMU related patches in this series, but I cannot find a place where this function is called with 'vcpu == NULL' and a valid cache is passed in, if I am reading correctly.

Also checked that "Eager Splitting" uses a kvm-scope cache for legacy MMU, but just uses __get_free_page() for TDP MMU. And in later patch "KVM: x86/tdp_mmu:
Support TDX private mapping for TDP MMU", __get_free_page() is also used to allocate the private_spt (which is consistent with existing eager splitting code).

So IIUC only legacy MMU code will call this function with 'vcpu == NULL' and a valid cache. In this case, please remove the 'private_spt_cache' argument for now, and make the function always allocate from the vcpu-

Quoted 1 line

arch.mmu_private_spt_cache.

You can add the additional argument when TDX gets legacy MMU support.

Also, I think you need to move eager splitting support part (whether that handling is correct is another story) from the later patch to this patch. Otherwise this patch is not complete.

Quoted 30 lines

Quoted 29 lines
arch/x86/kvm/mmu/mmu_internal.h +10 -0
+	 */
+	bool is_root = vcpu &&
+		vcpu->arch.root_mmu.root_role.level == sp->role.level;
+
+	if (vcpu)
+		private_spt_cache = &vcpu->arch.mmu_private_spt_cache;
+	KVM_BUG_ON(!kvm_mmu_page_role_is_private(sp->role), vcpu->kvm);
+	if (is_root)
+		/*
+		 * Because TDX module assigns root Secure-EPT page and set

it to

(quoted diff) +1 -0
+		 * Secure-EPTP when TD vcpu is created, secure page table

for

arch/x86/kvm/mmu/mmu_internal.h +5 -0
+		 * root isn't needed.
+		 */
+		sp->private_spt = NULL;
+	else {
+		sp->private_spt =

kvm_mmu_memory_cache_alloc(private_spt_cache);

(quoted diff) +2 -0
+		/*
+		 * Because mmu_private_spt_cache is topped up before

staring kvm

(quoted diff) +1 -0
+		 * page fault resolving, the allocation above shouldn't

fail.

arch/x86/kvm/mmu/mmu_internal.h +5 -0
+		 */
+		WARN_ON_ONCE(!sp->private_spt);
+	}
+}
+
#126 lore raw

Re: [PATCH v10 049/108] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to [email protected]
Quoted 12 lines
arch/x86/kvm/mmu/mmu_internal.h +9 -0
+static inline int kvm_alloc_private_spt_for_split(struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	gfp &= ~__GFP_ZERO;
+	sp->private_spt = (void *)__get_free_page(gfp);
+	if (!sp->private_spt)
+		return -ENOMEM;
+	return 0;
+}
+

[...]

arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1417

Quoted 11 lines
arch/x86/kvm/mmu/tdp_mmu.c +6 -0
@@ -1238,6 +1408,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
+			 */
+			KVM_BUG_ON(is_private_sptep(iter.sptep), vcpu->kvm);
+
 

So large page is not supported for private page, ...

arch/x86/kvm/mmu/tdp_mmu.c static struct kvm_mmu_page *__tdp_mmu_alloc_sp_for_split(gfp_t gfp, union kvm_mm · line 1664

Quoted 12 lines
arch/x86/kvm/mmu/tdp_mmu.c +6 -0
 			/*
 			 * The iter must explicitly re-read the spte here
@@ -1480,6 +1656,12 @@ static struct kvm_mmu_page *__tdp_mmu_alloc_sp_for_split(gfp_t gfp, union kvm_mm
 
 	sp->role = role;
 	sp->spt = (void *)__get_free_page(gfp);
+	if (kvm_mmu_page_role_is_private(role)) {
+		if (kvm_alloc_private_spt_for_split(sp, gfp)) {
+			free_page((unsigned long)sp->spt);
+			sp->spt = NULL;
+		}
+	}

... then I don't think eager splitting could happen for private mapping?

If so, should we just KVM_BUG_ON() if role is private?

#11 lore raw

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Erdem Aktas
Quoted 10 lines · Erdem Aktas
Quoted 9 lines · Isaku Yamahata
Quoted 8 lines

I think you should explain why MOVDIR64B is required, otherwise this just comes out of blue.

Btw, is this absolutely required? TDX also supports Li-mode, which doesn't have integrity check. So theoretically with Li-mode, normal zeroing is also OK but doesn't need to use MOVDIR64B.

That being said, do we have a way to tell whether TDX works in Ci or Li mode?

Quoted 8 lines
Quoted 2 lines

As long as I don't know. When clearing page, we can use if (featuremovdir64b) movdir64b else memset(0).

-- sorry for resending the same email, for some reason my previous email was not in plain text mode--
As far as I know, Li mode and Ci mode both are working very similarly and require movdir64b to clear any poison bit previously set. Why would movdir64b is not supported in a tdx capable cpu?

In practice, movdir64b can be safely assumed to be supported, I think. Strictly it's not guaranteed by SDM.
There are two options.

1. Assume modir64b. If it's not supported, KVM refuses to enable TDX.
+ Don't care CI-mode or Li-mode
- not strictly conforming to SDM. In practice, it won't matter.
2. Don't assume movdir64b. If movdir64b not supported, use memset(0).
+ strictly conforming to SDM
- needs to care Ci-mode or Li-mode.

So I'll choose option 1.

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

Re: [PATCH v10 015/108] x86/cpu: Add helper functions to allocate/free TDX private host key id

In reply to Huang, Kai
Quoted 38 lines · Kai
Quoted 4 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX private host key id is assigned to guest TD. The memory controller encrypts guest TD memory with the assigned TDX private host key id (HIKD).

								     ^
								     HKID.

And since you already mentioned in the first sentence, you can put (HKID) part there. And I think you can just use HKID in the rest places to save some typing as this is the purpose of using (HKID) I suppose.

[...]

Quoted 11 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+/* 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,

arch/x86/virt/vmx/tdx/tdx.c static void __init clear_tdx(void) · line 136

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+			       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;

Double check of keyid == 0.

Quoted 6 lines

I think you can just use:

	if (keyid <= tdx_keyid_start)
		return;

And/or add a WARN() as it's a bug if above happens.

Ok. Will fix it with WARN().

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

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to Huang, Kai
Quoted 10 lines · Kai
Quoted 6 lines
Quoted 6 lines

flush_shadow_all_private callback before tearing down private page tables for it.

Add a second kvm_x86_ops hook in kvm_arch_destroy_vm() 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.

Perhaps explicitly call out the hook is vm_free() and why the existing vm_destroy() hook cannot meet TDX's purpose, so that people can understand easily why you need vm_free().

Sure, will update the commit message.

Quoted 7 lines
Quoted 4 lines

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
+{
+	tdx_keyid_free(kvm_tdx->hkid);
+	kvm_tdx->hkid = -1;

Why -1? Can it be set to 0, which is the initial value when kvm_tdx is allocated anyway?

0 works. I'll replace it with 0.

Quoted 14 lines
Quoted 14 lines
Quoted 14 lines
arch/x86/kvm/vmx/tdx.c +14 -0
+}
+
+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:
Quoted 8 lines
Quoted 6 lines

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	 * 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.
+	 *
+	 * The cache line could be poisoned (even without MKTME-i), clear the
+	 * poison bit.

Does this happen only when there's potential kernel bug?

That's right.

Quoted 40 lines
Quoted 28 lines
Quoted 28 lines
arch/x86/kvm/vmx/tdx.c +28 -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 inline 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) {
+		/*
+		 * TDCX are being reclaimed.  TDX module maps TDCX with HKID
+		 * assigned to the TD.  Here the cache associated to the TD
+		 * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+		 * cache doesn't need to be flushed again.
+		 */
+		if (tdx_reclaim_page(page->va, page->pa, false, 0))
+			return;
+
Quoted 8 lines

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+		page->added = false;
+	}
+	if (page->va) {
+		free_page(page->va);
+		page->va = 0;
+	}
+}
+

I am wondering why this 'struct tdx_td_page' is needed?

Quoted 6 lines

It appears the page->pa is used by SEAMCALLs and page->va is used by tdx_clear_page() as MOVDIR64B needs a virtual address.

But since GFP_KERNEL_ACCOUNT is used in memory allocation, so you can actually just get the pa and va from the page easily (using page_to_phys() and __va()). Also it's 64-bit kernel so you don't even need to consider HIGHMEM.

Yes, page->va member can be dropped. Will drop it.

Quoted 2 lines

Also, it seems page->added can be replaced with simply checking whether page is NULL, correct?

No. It's subtle. Anyway let me check it.

Quoted 7 lines

Btw, I think the introduce of 'struct tdx_td_page' and the new 'struct tdx_td_page tdr' to 'struct kvm_tdx' should come together with this patch, but not in the previous patch "KVM: TDX: Stub in tdx.h with structs, accessors, and VMCS helpers". This makes the code review easier.

The "accessors" can be introduced in later patch when they are needed -- it doesn't seem any of them is used in this patch?

Ok, will move it to that patch.

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

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to Sagi Shahar
Quoted 14 lines · Sagi Shahar

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -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;
+
+       ret = tdx_keyid_alloc();

Can we skip the hkid allocation at such an early stage? This makes intra-host migration more complicated as the hkid of the destination VM is already allocated before we have a chance to migrate the state from the source VM.

Quoted 2 lines

I remember you had an internal version that already did that in
https://github.com/intel/tdx/blob/552dd80c48f67ca01bcdd10667e0c11efd375177/arch/x86/kvm/vmx/tdx.c#L508

With the patch of "KVM: TDX: initialize VM with TDX specific parameters", the allocation code is split out into its own code with KVM_TDX_INIT_VM. I think that's what you want.

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

Re: [PATCH v10 021/108] KVM: TDX: initialize VM with TDX specific parameters

In reply to Wang, Lei
Quoted 46 lines · Lei
Quoted 32 lines
arch/x86/kvm/vmx/tdx.c +11 -13
@@ -431,50 +633,65 @@ int tdx_vm_init(struct kvm *kvm)
 	return ret;
 }
 
-int tdx_dev_ioctl(void __user *argp)
+static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 {
-	struct kvm_tdx_capabilities __user *user_caps;
-	struct kvm_tdx_capabilities caps;
-	struct kvm_tdx_cmd cmd;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	struct kvm_tdx_init_vm *init_vm = NULL;
+	struct td_params *td_params = NULL;
+	void *entries_end;
+	int ret;
 
-	BUILD_BUG_ON(sizeof(struct kvm_tdx_cpuid_config) !=
-		     sizeof(struct tdx_cpuid_config));
+	BUILD_BUG_ON(sizeof(*init_vm) != 16 * 1024);
+	BUILD_BUG_ON((sizeof(*init_vm) - offsetof(typeof(*init_vm), entries)) /
+		     sizeof(init_vm->entries[0]) < KVM_MAX_CPUID_ENTRIES);
+	BUILD_BUG_ON(sizeof(struct td_params) != 1024);
 
-	if (copy_from_user(&cmd, argp, sizeof(cmd)))
-		return -EFAULT;
-	if (cmd.flags || cmd.error || cmd.unused)
+	if (is_td_initialized(kvm))
 		return -EINVAL;
-	/*
-	 * Currently only KVM_TDX_CAPABILITIES is defined for system-scoped
-	 * mem_enc_ioctl().
-	 */

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +4 -4
-	if (cmd.id != KVM_TDX_CAPABILITIES)
+
+	if (cmd->flags)
 		return -EINVAL;
 
-	user_caps = (void __user *)cmd.data;
-	if (copy_from_user(&caps, user_caps, sizeof(caps)))
-		return -EFAULT;
+	init_vm = kzalloc(sizeof(*init_vm), GFP_KERNEL);
+	if (copy_from_user(init_vm, (void __user *)cmd->data, sizeof(*init_vm))) {

Pointer 'init_vm' returned from call to function 'kzalloc' may be NULL and will be dereferenced at this line.

Quoted 1 line

Maybe a NULL-check here is needed?

Yes, thank you for catching it.

Thanks,

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

Re: [PATCH v10 031/108] KVM: x86/mmu: Replace hardcoded value 0 for the initial value for SPTE

In reply to Huang, Kai
Quoted 11 lines · Kai
Quoted 4 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware doesn't use this bit; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

Hi Isaku,

"AMD hardware doesn't use this bit" is wrong:

https://lore.kernel.org/lkml/[email protected]/T/#m5ed59404da43677e99ac51dd1360dc22b964bcbb

Oops. I'll update the commit message.

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

Re: [PATCH v10 032/108] KVM: x86/mmu: Make sync_page not use hard-coded 0 as the initial SPTE value

In reply to Huang, Kai
Quoted 25 lines · Kai
Quoted 24 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

FNAME(sync_page) in arch/x86/kvm/mmu/paging_tmpl.h assumes that the initial shadow page table entry (SPTE) is zero. Remove the assumption by using SHADOW_NONPRESENT_VALUE that will be updated from 0 to non-zero value.

---
 arch/x86/kvm/mmu/paging_tmpl.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/paging_tmpl.h +2 -1
index 5ab5f94dcb6f..6db3f2b5563a 100644
@@ -1036,7 +1036,8 @@ static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 		gpa_t pte_gpa;
 		gfn_t gfn;
 
-		if (!sp->spt[i])
+		/* spt[i] has initial value of shadow page table allocation */
+		if (sp->spt[i] == SHADOW_NONPRESENT_VALUE)
 			continue;
 
Quoted 4 lines

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

Quoted 1 line
arch/x86/kvm/mmu/paging_tmpl.h +0 -0
 		pte_gpa = first_pte_gpa + i * sizeof(pt_element_t);

I think this patch can be merged to previous one? Looks there's no good reason to keep it as standalone.

Yes, will squash it.

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

Re: [PATCH v10 033/108] KVM: x86/mmu: Allow non-zero value for non-present SPTE and removed SPTE

In reply to Huang, Kai
Quoted 16 lines · Kai

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only) · line 424

Quoted 12 lines
arch/x86/kvm/mmu/spte.c +3 -1
index 2e08b2a45361..0b97a045c5f0 100644
@@ -419,7 +419,9 @@ void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only)
 	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;
+	/* VMX_EPT_SUPPRESS_VE_BIT is needed for W or X violation. */
+	shadow_present_mask	=
+		(has_exec_only ? 0ull : VMX_EPT_READABLE_MASK) | VMX_EPT_SUPPRESS_VE_BIT;

I think this chunk can be in a separate patch since it doesn't handle fault from non-present to present, which is claimed by the patch title and changelog.

Quoted 1 line

Or I think you need to describe handling W or X fault part in the changelog.

Ok, let me try to split that hunk.

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

Re: [PATCH v10 034/108] KVM: x86/mmu: Add Suppress VE bit to shadow_mmio_{value, mask}

In reply to Huang, Kai
Quoted 8 lines · Kai
Quoted 6 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Because TDX will need shadow_mmio_mask to be VMX_SUPPRESS_VE | RWX shadow_mmio_value to be 0, make VMX EPT case use same value for TDX shadow_mmio_mask.

Quoted 4 lines

TDX need to use different mmio_mask/value doesn't mean they need to be changed for VMX guest. I think the true purpose here is to still be able to use a global shadow_mmio_mask for both TDX and VMX guests. So please explicitly call out.

That's right. With this change, per-VM shadow_mmio_{value, mask} can be avoided. The common value can be used for both VMX and TDX.

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

Re: [PATCH v10 041/108] KVM: x86/tdp_mmu: refactor kvm_tdp_mmu_map()

In reply to Huang, Kai
Quoted 9 lines · Kai
Quoted 5 lines · On Sat, 2022-10-29 at 23:22 -0700, [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.

Is this patch still valid/needed since you have changed to use XArray to store whether GFN is private or shared?

Because tdp_mmu_populate_nonleaf() won't be touched any more, this patch doesn't have any benefit. Will drop it.

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

Re: [PATCH v10 045/108] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to Huang, Kai
Quoted 40 lines · Kai
Quoted 21 lines · Kai

Review

Quoted 5 lines
arch/x86/kvm/mmu/mmu_internal.h +3 -0
+
+static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,
+					     struct kvm_mmu_memory_cache

*private_spt_cache,

(quoted diff) +1 -0
+					     struct kvm_mmu_page *sp)

This function is very weird in the context of this patch.  _Only_ a new vcpu- scope 'mmu_private_spte_cache' is added in this patch, but here you allow caller
to pass an additional argument of private_spt_cache.  So there must be another cache which is not introduced in this patch?

arch/x86/kvm/mmu/mmu_internal.h static inline bool is_private_sptep(u64 *sptep) · line 187

Quoted 6 lines
arch/x86/kvm/mmu/mmu_internal.h +4 -0
+{
+	/*
+	 * vcpu == NULL means non-root SPT:
+	 * vcpu == NULL is used to split a large SPT into smaller SPT. 

Root SPT

arch/x86/kvm/mmu/mmu_internal.h +1 -0
+	 * is not a large SPT.

I am guessing this "vcpu == NULL" case is for "Eager Splitting"?

Quoted 4 lines

If so, why not adding a global MMU cache for private_spt allocation, and make vcpu->arch.mmu_private_spt_cache point to the global cache?  In this case, in the context where you only have 'kvm', you can use the global cache directly. And in the context where you have a 'vcpu', you just use vcpu's cache.

So I went through all MMU related patches in this series, but I cannot find a place where this function is called with 'vcpu == NULL' and a valid cache is passed in, if I am reading correctly.

Also checked that "Eager Splitting" uses a kvm-scope cache for legacy MMU, but just uses __get_free_page() for TDP MMU. And in later patch "KVM: x86/tdp_mmu:
Support TDX private mapping for TDP MMU", __get_free_page() is also used to allocate the private_spt (which is consistent with existing eager splitting code).

So IIUC only legacy MMU code will call this function with 'vcpu == NULL' and a valid cache. In this case, please remove the 'private_spt_cache' argument for now, and make the function always allocate from the vcpu-

Quoted 7 lines
Quoted 1 line

arch.mmu_private_spt_cache.

You can add the additional argument when TDX gets legacy MMU support.

Also, I think you need to move eager splitting support part (whether that handling is correct is another story) from the later patch to this patch. Otherwise this patch is not complete.

Yes, you're right. Somehow legacy mmu part is crept in. I'll remove those from this patch series.

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

Re: [PATCH v10 049/108] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to Chenyi Qiang
Quoted 41 lines · Chenyi Qiang

arch/x86/kvm/mmu/tdp_mmu.c static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared) · line 566

Quoted 11 lines
arch/x86/kvm/mmu/tdp_mmu.c +11 -0
+static int __must_check handle_changed_private_spte(struct kvm *kvm, gfn_t gfn,
+						    u64 old_spte, u64 new_spte,
+						    int level)
+{
+	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);
+	kvm_pfn_t old_pfn = spte_to_pfn(old_spte);
+	kvm_pfn_t new_pfn = spte_to_pfn(new_spte);
+	int ret;

int ret = 0;

Quoted 27 lines
arch/x86/kvm/mmu/tdp_mmu.c +27 -0
+
+	lockdep_assert_held(&kvm->mmu_lock);
+	if (is_present) {
+		/* TDP MMU doesn't change present -> present */
+		KVM_BUG_ON(was_present, kvm);
+
+		/*
+		 * Use different call to either set up middle level
+		 * private page table, or leaf.
+		 */
+		if (is_leaf)
+			ret = static_call(kvm_x86_set_private_spte)(kvm, gfn, level, new_pfn);
+		else {
+			void *private_spt = get_private_spt(gfn, new_spte, level);
+
+			KVM_BUG_ON(!private_spt, kvm);
+			ret = static_call(kvm_x86_link_private_spt)(kvm, gfn, level, private_spt);
+		}
+	} else if (was_leaf) {
+		/* non-present -> non-present doesn't make sense. */
+		KVM_BUG_ON(!was_present, kvm);
+		/*
+		 * Zap private leaf SPTE.  Zapping private table is done
+		 * below in handle_removed_tdp_mmu_page().
+		 */
+		lockdep_assert_held_write(&kvm->mmu_lock);
+		ret = static_call(kvm_x86_zap_private_spte)(kvm, gfn, level);
Quoted 8 lines

arch/x86/kvm/mmu/tdp_mmu.c static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared) · line 598

Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.c +5 -0
+		if (!ret) {
+			ret = static_call(kvm_x86_remove_private_spte)(kvm, gfn, level, old_pfn);
+			WARN_ON_ONCE(ret);
+		}
+	}

Otherwise, "ret" may be returned without initialization. Then it will trigger the WARN_ON_ONCE(ret) after handle_changed_spte() in patch 48.

Thanks for catching it. Compiler didn't complain it. Maybe W=1 is needed.

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

Re: [PATCH v10 049/108] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to Huang, Kai
Quoted 43 lines · Kai
Quoted 12 lines
arch/x86/kvm/mmu/mmu_internal.h +9 -0
+static inline int kvm_alloc_private_spt_for_split(struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	gfp &= ~__GFP_ZERO;
+	sp->private_spt = (void *)__get_free_page(gfp);
+	if (!sp->private_spt)
+		return -ENOMEM;
+	return 0;
+}
+

[...]

arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1417

Quoted 11 lines
arch/x86/kvm/mmu/tdp_mmu.c +6 -0
@@ -1238,6 +1408,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
+			 */
+			KVM_BUG_ON(is_private_sptep(iter.sptep), vcpu->kvm);
+
 

So large page is not supported for private page, ...

arch/x86/kvm/mmu/tdp_mmu.c static struct kvm_mmu_page *__tdp_mmu_alloc_sp_for_split(gfp_t gfp, union kvm_mm · line 1664

Quoted 12 lines
arch/x86/kvm/mmu/tdp_mmu.c +6 -0
 			/*
 			 * The iter must explicitly re-read the spte here
@@ -1480,6 +1656,12 @@ static struct kvm_mmu_page *__tdp_mmu_alloc_sp_for_split(gfp_t gfp, union kvm_mm
 
 	sp->role = role;
 	sp->spt = (void *)__get_free_page(gfp);
+	if (kvm_mmu_page_role_is_private(role)) {
+		if (kvm_alloc_private_spt_for_split(sp, gfp)) {
+			free_page((unsigned long)sp->spt);
+			sp->spt = NULL;
+		}
+	}

... then I don't think eager splitting could happen for private mapping?

Quoted 1 line

If so, should we just KVM_BUG_ON() if role is private?

Right, will remove this part from this patch series and move it to large page support series.

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

Re: [PATCH v10 049/108] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to Binbin Wu
Quoted 17 lines · Binbin Wu
Quoted 17 lines
arch/x86/include/asm/kvm-x86-ops.h +5 -0
index f28c9fd72ac4..1b01dc2098b0 100644
@@ -94,6 +94,11 @@ KVM_X86_OP_OPTIONAL_RET0(set_tss_addr)
  KVM_X86_OP_OPTIONAL_RET0(set_identity_map_addr)
  KVM_X86_OP_OPTIONAL_RET0(get_mt_mask)
  KVM_X86_OP(load_mmu_pgd)
+KVM_X86_OP_OPTIONAL(link_private_spt)
+KVM_X86_OP_OPTIONAL(free_private_spt)
+KVM_X86_OP_OPTIONAL(set_private_spte)
+KVM_X86_OP_OPTIONAL(remove_private_spte)
+KVM_X86_OP_OPTIONAL(zap_private_spte)
  KVM_X86_OP(has_wbinvd_exit)
  KVM_X86_OP(get_l2_tsc_offset)
  KVM_X86_OP(get_l2_tsc_multiplier)
Quoted 14 lines

arch/x86/include/asm/kvm-x86-ops.h static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared) · line 534

Quoted 12 lines
arch/x86/include/asm/kvm-x86-ops.h +9 -0
@@ -509,9 +524,81 @@ static void handle_removed_pt(struct kvm *kvm, tdp_ptep_t pt, bool shared)
  		WARN_ON_ONCE(ret);
  	}
+	if (is_private_sp(sp) &&
+	    WARN_ON(static_call(kvm_x86_free_private_spt)(kvm, sp->gfn, sp->role.level,
+							  kvm_mmu_private_spt(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_spt(sp, NULL);

Do you think is it better to add some statistics for the intentinal leakage?

No because this error case happens only when race condition bug(TDX_OPERAND_BUSY) or TDX module was shutdown due to bug or attack. They are (should be) rare.

The race condition bug should be fixed. It's covered by WARN_ON(). In the case of TDX module shutdown, the current TDX KVM implementation checks unexpected error and mark it bugged, KVM_BUG_ON(), in vmx/tdx.c. So adding statistic counter doesn't help. It's another story to harden the code against TDX module shutdown.

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

Re: [PATCH v10 071/108] KVM: x86: Allow to update cached values in kvm_user_return_msrs w/o wrmsr

In reply to Binbin Wu
Quoted 33 lines · Binbin Wu
Quoted 33 lines
arch/x86/kvm/x86.c +12 -5
index 65541bfebb37..4d4b71c4cdb1 100644
@@ -440,6 +440,15 @@ void kvm_user_return_msr_init_cpu(void)
  }
  EXPORT_SYMBOL_GPL(kvm_user_return_msr_init_cpu);
+static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
+{
+	if (!msrs->registered) {
+		msrs->urn.on_user_return = kvm_on_user_return;
+		user_return_notifier_register(&msrs->urn);
+		msrs->registered = true;
+	}
+}
+
  int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
  {
  	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
@@ -455,15 +464,22 @@ int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
  		return 1;
  	msrs->values[slot].curr = value;
-	if (!msrs->registered) {
-		msrs->urn.on_user_return = kvm_on_user_return;
-		user_return_notifier_register(&msrs->urn);
-		msrs->registered = true;
-	}
+	kvm_user_return_register_notifier(msrs);
  	return 0;
  }
  EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
+/* Update the cache, "curr", and register the notifier */
+void kvm_user_return_update_cache(unsigned int slot, u64 value)
Quoted 8 lines

arch/x86/kvm/x86.c int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask) · line 478

Quoted 5 lines
arch/x86/kvm/x86.c +5 -0
+{
+	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
+
+	WARN_ON_ONCE(!msrs->initialized);
+	msrs->values[slot].curr = value;

If the value is the same as the cached one, can it just skip notifier registration?

We know tha the the user of the function (in the next patch) passes the different value, the initial reset value in the return of TDH.VP.ENTER. So such check isn't added.

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

Re: [PATCH v10 072/108] KVM: TDX: restore user ret MSRs

In reply to Binbin Wu
Quoted 57 lines · Binbin Wu
Quoted 55 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Several user ret MSRs are clobbered on TD exit. Restore those values on TD exit and before returning to ring 3.

---
  arch/x86/kvm/vmx/tdx.c | 43 ++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 43 insertions(+)
arch/x86/kvm/vmx/tdx.c +27 -0
index 3ec465cbaeef..f35ccf2b502d 100644
@@ -456,6 +456,28 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  	vcpu->kvm->vm_bugged = true;
  }
+struct tdx_uret_msr {
+	u32 msr;
+	unsigned int slot;
+	u64 defval;
+};
+
+static struct tdx_uret_msr tdx_uret_msrs[] = {
+	{.msr = MSR_SYSCALL_MASK,},
+	{.msr = MSR_STAR,},
+	{.msr = MSR_LSTAR,},
+	{.msr = MSR_TSC_AUX,},
+};
+
+static void tdx_user_return_update_cache(void)
+{
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(tdx_uret_msrs); i++)
+		kvm_user_return_update_cache(tdx_uret_msrs[i].slot,
+					     tdx_uret_msrs[i].defval);
+}
+
  static void tdx_restore_host_xsave_state(struct kvm_vcpu *vcpu)
  {
  	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
@@ -495,6 +517,7 @@ fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
  	tdx_vcpu_enter_exit(vcpu, tdx);
+	tdx_user_return_update_cache();
  	tdx_restore_host_xsave_state(vcpu);
  	tdx->host_state_need_restore = true;
@@ -1558,6 +1581,26 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  		return -ENODEV;
  	}
+	for (i = 0; i < ARRAY_SIZE(tdx_uret_msrs); i++) {
+		/*
+		 * Here it checks if MSRs (tdx_uret_msrs) can be saved/restored
+		 * before returning to user space.
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+		 *
+		 * this_cpu_ptr(user_return_msrs)->registered isn't checked
+		 * because the registration is done at vcpu runtime by
+		 * kvm_set_user_return_msr().
+		 * Here is setting up cpu feature before running vcpu,
+		 * registered is alreays

typo, already or always?

already. Thanks.

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

Re: [PATCH v10 076/108] KVM: TDX: handle vcpu migration over logical processor

In reply to Binbin Wu
Quoted 50 lines · Binbin Wu
Quoted 3 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

For vcpu migration, in the case of VMX, VCMS

typo, VMCS

Quoted 28 lines

is flushed on the source pcpu,
and load it on the target pcpu. There are corresponding TDX SEAMCALL APIs, call them on vcpu migration. The logic is mostly same as VMX except the TDX SEAMCALLs are used.

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    |  43 +++++++++++--
  arch/x86/kvm/vmx/tdx.c     | 121 +++++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/tdx.h     |   2 +
  arch/x86/kvm/vmx/x86_ops.h |   6 ++
  4 files changed, 168 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/tdx.c +8 -0
@@ -176,6 +214,41 @@ static void tdx_reclaim_td_page(struct tdx_td_page *page)
  	}
  }
+static void tdx_flush_vp(void *arg)
+{
+	struct kvm_vcpu *vcpu = arg;
+	u64 err;
+
+	lockdep_assert_irqs_disabled();
+
+	/* Task migration can race with CPU offlining. */

arch/x86/kvm/vmx/tdx.c static void tdx_reclaim_td_page(struct tdx_td_page *page) · line 233

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	if (vcpu->cpu != raw_smp_processor_id())
+		return;
+
+	/*
+	 * No need to do TDH_VP_FLUSH if the vCPU hasn't been initialized.  The
+	 * list tracking still needs to be updated so that it's correct if/when
+	 * the vCPU does get initialized.
+	 */
+	if (is_td_vcpu_created(to_tdx(vcpu))) {
+		err = tdh_vp_flush(to_tdx(vcpu)->tdvpr.pa);

Need to retry here if tdh.vp.flush fails due to tdx operand busy?

Quoted 2 lines

If such failure occurs, the next vp enter will fail after the vCPU migrated to another LP, how is it hanlded?

No need to retry. TDX Resources needed for TDH.VP.FLUSH are, TDVPR as exclusive, TDR as shared, and TDCS as shared.

This vp flush function is called when destructing vcpu/TD or vcpu migration. No other thread uses TDVPR in those cases.

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

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to Isaku Yamahata
Quoted 18 lines · Isaku Yamahata
Quoted 14 lines · Sagi Shahar

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -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;
+
+       ret = tdx_keyid_alloc();

Can we skip the hkid allocation at such an early stage? This makes intra-host migration more complicated as the hkid of the destination VM is already allocated before we have a chance to migrate the state from the source VM.

Quoted 6 lines
Quoted 2 lines

I remember you had an internal version that already did that in
https://github.com/intel/tdx/blob/552dd80c48f67ca01bcdd10667e0c11efd375177/arch/x86/kvm/vmx/tdx.c#L508

With the patch of "KVM: TDX: initialize VM with TDX specific parameters", the allocation code is split out into its own code with KVM_TDX_INIT_VM. I think that's what you want.

Right, I missed that. Thanks.

Quoted 2 lines

--
Isaku Yamahata <[email protected]>

#138 lore raw

Re: [PATCH v10 056/108] KVM: TDX: don't request KVM_REQ_APIC_PAGE_RELOAD

In reply to [email protected]
Quoted 26 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX doesn't need APIC page depending on vapic and its callback is WARN_ON_ONCE(is_tdx). To avoid unnecessary overhead and WARN_ON_ONCE(), skip requesting KVM_REQ_APIC_PAGE_RELOAD when TD.

  WARNING: arch/x86/kvm/vmx/main.c:696 vt_set_apic_access_page_addr+0x3c/0x50 [kvm_intel]
  RIP: 0010:vt_set_apic_access_page_addr+0x3c/0x50 [kvm_intel]
  Call Trace:
   vcpu_enter_guest+0x145d/0x24d0 [kvm]
   kvm_arch_vcpu_ioctl_run+0x25d/0xcc0 [kvm]
   kvm_vcpu_ioctl+0x414/0xa30 [kvm]
   __x64_sys_ioctl+0xc0/0x100
   do_syscall_64+0x39/0xc0
   entry_SYSCALL_64_after_hwframe+0x44/0xae
---
 arch/x86/kvm/x86.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
arch/x86/kvm/x86.c +0 -0
index 3868605462ed..5dadd0f9a10e 100644

arch/x86/kvm/x86.c void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm, · line 10495

Quoted 10 lines
arch/x86/kvm/x86.c +3 -1
@@ -10487,7 +10487,9 @@ void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
 	 * Update it when it becomes invalid.
 	 */
 	apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
-	if (start <= apic_address && apic_address < end)
+	/* TDX doesn't need APIC page. */
+	if (kvm->arch.vm_type != KVM_X86_TDX_VM &&
+	    start <= apic_address && apic_address < end)
 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
 }
 

In patch "[PATCH v10 105/108] KVM: TDX: Add methods to ignore accesses to CPU state", you have:

+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);
+}

If you drop the WARN_ON_ONCE() above, you can just drop this patch.

For this particular case, I don't find it is quite necessary to change the common x86 code as done in this patch. In fact, SVM doesn't have a set_apic_access_page_addr() callback which is consistent with just return if VM is TD in vt_set_apic_access_page_addr().

Also, I don't particularly like the idea of having a lot of "is_td(kvm)" in the common x86 code as if similar technology happens in the future, you will need to have another "is_td_similar_vm(kvm)" thing.

If modifying common x86 code is necessary, then it would make more sense to introduce some common flag, and make TD guest set that flag.

Btw, this patch just comes out of blue from the middle of a bunch of MMU patches. Shouldn't it be moved to "patches which handles interrupt related staff"?

Btw2, by saying above, does it make sense to split patch "[PATCH v10 105/108]
KVM: TDX: Add methods to ignore accesses to CPU state" based on category such as MMU/interrupt, etc? Particularly, in that patch, some callbacks have WARN() or KVM_BUG_ON() against TD guest, but some don't. The logic behind those decisions highly depend on previous patches. To me, it makes more sense to just move logic related things together.

#216 lore raw

Re: [PATCH v10 105/108] KVM: TDX: Add methods to ignore accesses to CPU state

In reply to [email protected]
Quoted 4 lines · On Sat, 2022-10-29 at 23:23 -0700, [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.

IMHO this patch isn't reviewable -- too many things mixed together. And the logic of whether to use WARN()/KVM_BUG_ON() against TD is hard to tell as they depends on common x86 code logic. The relative parts (i.e. interrupt related parts) should be put together as separate patches to make the whole thing reviewable.

Hi Sean, do you have any comments?

#84 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

In reply to [email protected]
Quoted 109 lines · On Sat, Oct 29, 2022 at 11:22:36PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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 instead of global variables. By using the per-VM EPT entry value for MMIO, the existing VMX logic is kept working. To untangle the logic to initialize shadow_mmio_access_mask, introduce a separate setter function.

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/mmu.h              |  1 +
 arch/x86/kvm/mmu/mmu.c          |  7 ++++---
 arch/x86/kvm/mmu/spte.c         | 11 +++++++++--
 arch/x86/kvm/mmu/spte.h         |  4 ++--
 arch/x86/kvm/mmu/tdp_mmu.c      |  6 +++---
 6 files changed, 21 insertions(+), 10 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index 3374ec0d6d90..a1c801ca61d3 100644
@@ -1171,6 +1171,8 @@ struct kvm_arch {
 	 */
 	spinlock_t mmu_unsync_pages_lock;
 
+	u64 shadow_mmio_value;
+
 	struct list_head assigned_dev_head;
 	struct iommu_domain *iommu_domain;
 	bool iommu_noncoherent;
arch/x86/kvm/mmu.h +1 -0
index a45f7a96b821..50d240d52697 100644
@@ -101,6 +101,7 @@ static inline u8 kvm_get_shadow_phys_bits(void)
 }
 
 void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask);
+void kvm_mmu_set_mmio_spte_value(struct kvm *kvm, u64 mmio_value);
 void kvm_mmu_set_me_spte_mask(u64 me_value, u64 me_mask);
 void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only);
 
arch/x86/kvm/mmu/mmu.c +4 -3
index e7e11f51f8b4..0d3fa29ccccc 100644
@@ -2421,7 +2421,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;
@@ -4081,7 +4081,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);
 
@@ -4578,7 +4578,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;
@@ -6061,6 +6061,7 @@ int kvm_mmu_init_vm(struct kvm *kvm)
 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
 	int r;
 
+	kvm->arch.shadow_mmio_value = shadow_mmio_value;
 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
 	INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
arch/x86/kvm/mmu/spte.c +3 -2
index 5d5c06d4fd89..8f468ee2b985 100644
@@ -74,10 +74,10 @@ 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);
 
 	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;
@@ -352,6 +352,7 @@ u64 mark_spte_for_access_track(u64 spte)
 void kvm_mmu_set_mmio_spte_mask(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);
 
 	/*

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask) · line 408

Quoted 7 lines
arch/x86/kvm/mmu/spte.c +4 -0
@@ -401,6 +402,12 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
 
+void kvm_mmu_set_mmio_spte_value(struct kvm *kvm, u64 mmio_value)
+{
+	kvm->arch.shadow_mmio_value = mmio_value;
+}

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

Quoted 10 lines
arch/x86/kvm/mmu/spte.c +2 -0
+EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_value);
+
 void kvm_mmu_set_me_spte_mask(u64 me_value, u64 me_mask)
 {
 	/* shadow_me_value must be a subset of shadow_me_mask */
arch/x86/kvm/mmu/spte.h +0 -0
index 7e0f79e8f45b..82f0d5c08b77 100644

arch/x86/kvm/mmu/spte.h static inline int spte_index(u64 *sptep) · line 247

Quoted 9 lines
arch/x86/kvm/mmu/spte.h +2 -2
@@ -241,9 +241,9 @@ static inline int spte_index(u64 *sptep)
  */
 extern u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
 
-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 &&
+	return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
 	       likely(enable_mmio_caching);

As above, also turn enable_mmio_caching to be per-vm ?

Quoted 29 lines
arch/x86/kvm/mmu/spte.h +0 -0
 }
 
arch/x86/kvm/mmu/tdp_mmu.c +3 -3
index 1eee9c159958..e07f14351d14 100644
@@ -580,8 +580,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"
@@ -1105,7 +1105,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))) {
 		vcpu->stat.pf_mmio_spte_created++;
 		trace_mark_mmio_spte(rcu_dereference(iter->sptep), iter->gfn,
 				     new_spte);
Signature · 1 line
2.25.1
#115 lore raw

Re: [PATCH v10 047/108] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to [email protected]
Quoted 39 lines

From: Sean Christopherson <[email protected]>

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense for private memory. Also currently, page migration isn't supported for TDX yet. (TDX architecturally supports page migration. it's KVM and kernel implementation issue.)

Regarding memory type change (mtrr virtualization and lapic page mapping change), pages are zapped by kvm_zap_gfn_range(). On the next KVM page fault, the SPTE entry with a new memory type for the page is populated. Regarding page migration, pages are zapped by the mmu notifier. On the next KVM page fault, the new migrated page is populated. Don't zap private pages on unmapping for those two cases.

When deleting/moving a KVM memory slot, zap private pages. Typically tearing down VM. Don't invalidate private page tables. i.e. zap only leaf SPTEs for KVM mmu that has a shared bit mask. The existing kvm_tdp_mmu_invalidate_all_roots() depends on role.invalid with read-lock of mmu_lock so that other vcpu can operate on KVM mmu concurrently. It marks the root page table invalid and zaps SPTEs of the root page tables. The TDX module doesn't allow to unlink a protected root page table from the hardware and then allocate a new one for it. i.e. replacing a protected root page table. Instead, zap only leaf SPTEs for KVM mmu with a shared bit mask set.

---
  arch/x86/kvm/mmu/mmu.c     | 85 ++++++++++++++++++++++++++++++++++++--
  arch/x86/kvm/mmu/tdp_mmu.c | 24 ++++++++---
  arch/x86/kvm/mmu/tdp_mmu.h |  5 ++-
  3 files changed, 103 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index faf69774c7ce..0237e143299c 100644

arch/x86/kvm/mmu/mmu.c bool kvm_unmap_gfn_range(struct kvm *kvm, struct · line 1582

Quoted 8 lines
arch/x86/kvm/mmu/mmu.c +2 -2
@@ -1577,8 +1577,38 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct  
 kvm_gfn_range *range)
  	if (kvm_memslots_have_rmaps(kvm))
  		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
 
-	if (is_tdp_mmu_enabled(kvm))
-		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
+	if (is_tdp_mmu_enabled(kvm)) {
+		bool zap_private;

We should initialize zap_private to true, otherwise zap_private is uninitialized in call

kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush, zap_private)

if the condition

    if (kvm_slot_can_be_private(range->slot)) {

evaluates to false.

Quoted 33 lines
arch/x86/kvm/mmu/mmu.c +30 -0
+
+		if (kvm_slot_can_be_private(range->slot)) {
+			if (range->flags & KVM_GFN_RANGE_FLAGS_RESTRICTED_MEM)
+				/*
+				 * For private slot, the callback is triggered
+				 * via falloc.  Mode can be allocation or punch
+				 * hole.  Because the private-shared conversion
+				 * is done via
+				 * KVM_MEMORY_ENCRYPT_REG/UNREG_REGION, we can
+				 * ignore the request from restrictedmem.
+				 */
+				return flush;
+			else if (range->flags & KVM_GFN_RANGE_FLAGS_SET_MEM_ATTR) {
+				if (range->attr == KVM_MEM_ATTR_SHARED)
+					zap_private = true;
+				else {
+					WARN_ON_ONCE(range->attr != KVM_MEM_ATTR_PRIVATE);
+					zap_private = false;
+				}
+			} else
+				/*
+				 * kvm_unmap_gfn_range() is called via mmu
+				 * notifier.  For now page migration for private
+				 * page isn't supported yet, don't zap private
+				 * pages.
+				 */
+				zap_private = false;
+		}
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush, zap_private);
+	}
 
  	return flush;
  }
#22 lore raw

Re: [PATCH v10 011/108] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]
Quoted 9 lines · On Sat, 29 Oct 2022 23:22:12 -0700 [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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 3 lines

Export __seamcall and define C wrapper functions for SEAMCALLs for readability. Some SEAMCALL APIs donates pages to TDX module or guest TD. The pages are encrypted with TDX private host key id set in high

It seems a little bit confusing here.

I guess you are talking about the host pages donated to TDX module will be encrypted with TDX module global key id, which is used to encrypted the pages only used by TDX module. For pages donated to the TD guest, the pages are encrypted with TD guest prviate key id?

It might be better that you can talk about the actual reaason instead of the key id stuff. For example Some SEMCALL APIs will zap or write the pages donated by VMM via MOVDIR64B, which requires the VMM to flush the cachelines.

Quoted 1 line

bits of physical address. If any modified cache lines may exit for

typo exit->exist

Quoted 239 lines

these pages, flush them to memory by clflush_cache_range().

---
 arch/x86/include/asm/tdx.h       |   2 +
 arch/x86/kvm/vmx/tdx_ops.h       | 185
+++++++++++++++++++++++++++++++ arch/x86/virt/vmx/tdx/seamcall.S |
2 + 3 files changed, 189 insertions(+)
 create mode 100644 arch/x86/kvm/vmx/tdx_ops.h
arch/x86/include/asm/tdx.h +2 -0
index 5cff7ed5b11e..ba2e4c69fb9f 100644
@@ -186,6 +186,8 @@ struct tdsysinfo_struct {
 const struct tdsysinfo_struct *tdx_get_sysinfo(void);
 bool platform_tdx_enabled(void);
 int tdx_enable(void);
+u64 __seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+	       struct tdx_module_output *out);
 #else	/* !CONFIG_INTEL_TDX_HOST */
 struct tdsysinfo_struct;
 static inline const struct tdsysinfo_struct *tdx_get_sysinfo(void) {

return NULL; } diff --git a/arch/x86/kvm/vmx/tdx_ops.h b/arch/x86/kvm/vmx/tdx_ops.h new file mode 100644 index 000000000000..85adbf49c277

arch/x86/kvm/vmx/tdx_ops.h new file +24 -0
@@ -0,0 +1,185 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_OPS_H
+#define __KVM_X86_TDX_OPS_H
+
+#include <linux/compiler.h>
+
+#include <asm/cacheflush.h>
+#include <asm/asm.h>
+#include <asm/kvm_host.h>
+
+#include "tdx_errno.h"
+#include "tdx_arch.h"
+
+#ifdef CONFIG_INTEL_TDX_HOST
+
+static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
+{
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+	return __seamcall(TDH_MNG_ADDCX, addr, tdr, 0, 0, NULL);
+}
+
+static inline u64 tdh_mem_page_add(hpa_t tdr, gpa_t gpa, hpa_t hpa,

hpa_t source,

arch/x86/kvm/vmx/tdx_ops.h new file +4 -0
+				   struct tdx_module_output *out)
+{
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return __seamcall(TDH_MEM_PAGE_ADD, gpa, tdr, hpa, source,

out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level,

hpa_t page,

arch/x86/kvm/vmx/tdx_ops.h new file +4 -0
+				   struct tdx_module_output *out)
+{
+	clflush_cache_range(__va(page), PAGE_SIZE);
+	return __seamcall(TDH_MEM_SEPT_ADD, gpa | level, tdr, page,

0, out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+
+static inline u64 tdh_mem_sept_remove(hpa_t tdr, gpa_t gpa, int

level,

arch/x86/kvm/vmx/tdx_ops.h new file +3 -0
+				      struct tdx_module_output *out)
+{
+	return __seamcall(TDH_MEM_SEPT_REMOVE, gpa | level, tdr, 0,

0, out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +8 -0
+
+static inline u64 tdh_vp_addcx(hpa_t tdvpr, hpa_t addr)
+{
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+	return __seamcall(TDH_VP_ADDCX, addr, tdvpr, 0, 0, NULL);
+}
+
+static inline u64 tdh_mem_page_relocate(hpa_t tdr, gpa_t gpa, hpa_t

hpa,

arch/x86/kvm/vmx/tdx_ops.h new file +1 -0
+					struct tdx_module_output

*out) +{

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return __seamcall(TDH_MEM_PAGE_RELOCATE, gpa, tdr, hpa, 0,

out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +9 -0
+
+static inline u64 tdh_mem_page_aug(hpa_t tdr, gpa_t gpa, hpa_t hpa,
+				   struct tdx_module_output *out)
+{
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return __seamcall(TDH_MEM_PAGE_AUG, gpa, tdr, hpa, 0, out);
+}
+
+static inline u64 tdh_mem_range_block(hpa_t tdr, gpa_t gpa, int

level,

arch/x86/kvm/vmx/tdx_ops.h new file +3 -0
+				      struct tdx_module_output *out)
+{
+	return __seamcall(TDH_MEM_RANGE_BLOCK, gpa | level, tdr, 0,

0, out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +19 -0
+
+static inline u64 tdh_mng_key_config(hpa_t tdr)
+{
+	return __seamcall(TDH_MNG_KEY_CONFIG, tdr, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_mng_create(hpa_t tdr, int hkid)
+{
+	clflush_cache_range(__va(tdr), PAGE_SIZE);
+	return __seamcall(TDH_MNG_CREATE, tdr, hkid, 0, 0, NULL);
+}
+
+static inline u64 tdh_vp_create(hpa_t tdr, hpa_t tdvpr)
+{
+	clflush_cache_range(__va(tdvpr), PAGE_SIZE);
+	return __seamcall(TDH_VP_CREATE, tdvpr, tdr, 0, 0, NULL);
+}
+
+static inline u64 tdh_mng_rd(hpa_t tdr, u64 field, struct

tdx_module_output *out) +{

arch/x86/kvm/vmx/tdx_ops.h new file +53 -0
+	return __seamcall(TDH_MNG_RD, tdr, field, 0, 0, out);
+}
+
+static inline u64 tdh_mr_extend(hpa_t tdr, gpa_t gpa,
+				struct tdx_module_output *out)
+{
+	return __seamcall(TDH_MR_EXTEND, gpa, tdr, 0, 0, out);
+}
+
+static inline u64 tdh_mr_finalize(hpa_t tdr)
+{
+	return __seamcall(TDH_MR_FINALIZE, tdr, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_vp_flush(hpa_t tdvpr)
+{
+	return __seamcall(TDH_VP_FLUSH, tdvpr, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_mng_vpflushdone(hpa_t tdr)
+{
+	return __seamcall(TDH_MNG_VPFLUSHDONE, tdr, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_mng_key_freeid(hpa_t tdr)
+{
+	return __seamcall(TDH_MNG_KEY_FREEID, tdr, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_mng_init(hpa_t tdr, hpa_t td_params,
+			       struct tdx_module_output *out)
+{
+	return __seamcall(TDH_MNG_INIT, tdr, td_params, 0, 0, out);
+}
+
+static inline u64 tdh_vp_init(hpa_t tdvpr, u64 rcx)
+{
+	return __seamcall(TDH_VP_INIT, tdvpr, rcx, 0, 0, NULL);
+}
+
+static inline u64 tdh_vp_rd(hpa_t tdvpr, u64 field,
+			    struct tdx_module_output *out)
+{
+	return __seamcall(TDH_VP_RD, tdvpr, field, 0, 0, out);
+}
+
+static inline u64 tdh_mng_key_reclaimid(hpa_t tdr)
+{
+	return __seamcall(TDH_MNG_KEY_RECLAIMID, tdr, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_phymem_page_reclaim(hpa_t page,
+					  struct tdx_module_output

*out) +{

arch/x86/kvm/vmx/tdx_ops.h new file +1 -0
+	return __seamcall(TDH_PHYMEM_PAGE_RECLAIM, page, 0, 0, 0,

out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+
+static inline u64 tdh_mem_page_remove(hpa_t tdr, gpa_t gpa, int

level,

arch/x86/kvm/vmx/tdx_ops.h new file +3 -0
+				      struct tdx_module_output *out)
+{
+	return __seamcall(TDH_MEM_PAGE_REMOVE, gpa | level, tdr, 0,

0, out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +12 -0
+
+static inline u64 tdh_sys_lp_shutdown(void)
+{
+	return __seamcall(TDH_SYS_LP_SHUTDOWN, 0, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_mem_track(hpa_t tdr)
+{
+	return __seamcall(TDH_MEM_TRACK, tdr, 0, 0, 0, NULL);
+}
+
+static inline u64 tdh_mem_range_unblock(hpa_t tdr, gpa_t gpa, int

level,

arch/x86/kvm/vmx/tdx_ops.h new file +1 -0
+					struct tdx_module_output

*out) +{

arch/x86/kvm/vmx/tdx_ops.h new file +1 -0
+	return __seamcall(TDH_MEM_RANGE_UNBLOCK, gpa | level, tdr,

0, 0, out); +}

arch/x86/kvm/vmx/tdx_ops.h new file +4 -0
+
+static inline u64 tdh_phymem_cache_wb(bool resume)
+{
+	return __seamcall(TDH_PHYMEM_CACHE_WB, resume ? 1 : 0, 0, 0,

0, NULL); +}

arch/x86/kvm/vmx/tdx_ops.h new file +4 -0
+
+static inline u64 tdh_phymem_page_wbinvd(hpa_t page)
+{
+	return __seamcall(TDH_PHYMEM_PAGE_WBINVD, page, 0, 0, 0,

NULL); +}

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+
+static inline u64 tdh_vp_wr(hpa_t tdvpr, u64 field, u64 val, u64

mask,

arch/x86/kvm/vmx/tdx_ops.h new file +7 -0
+			    struct tdx_module_output *out)
+{
+	return __seamcall(TDH_VP_WR, tdvpr, field, val, mask, out);
+}
+#endif /* CONFIG_INTEL_TDX_HOST */
+
+#endif /* __KVM_X86_TDX_OPS_H */
(quoted diff) +0 -0

b/arch/x86/virt/vmx/tdx/seamcall.S index f81be6b9c133..b90a7fe05494 100644 --- a/arch/x86/virt/vmx/tdx/seamcall.S
+++ b/arch/x86/virt/vmx/tdx/seamcall.S

arch/x86/virt/vmx/tdx/seamcall.S +2 -0
@@ -1,5 +1,6 @@
 /* SPDX-License-Identifier: GPL-2.0 */
 #include <linux/linkage.h>
+#include <asm/export.h>
 #include <asm/frame.h>
 
 #include "tdxcall.S"
@@ -50,3 +51,4 @@ SYM_FUNC_START(__seamcall)
 	FRAME_END
 	RET
 SYM_FUNC_END(__seamcall)
+EXPORT_SYMBOL_GPL(__seamcall)
#39 lore raw

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to [email protected]
Quoted 184 lines · On Sat, 29 Oct 2022 23:22:17 -0700 [email protected] wrote:

From: Sean Christopherson <[email protected]>

As the first step to create TDX guest, create/destroy VM struct. Assign TDX private 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.

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 flush_shadow_all_private callback before tearing down private page tables for it.

Add a second kvm_x86_ops hook in kvm_arch_destroy_vm() 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/include/asm/kvm-x86-ops.h |   2 +
 arch/x86/include/asm/kvm_host.h    |   2 +
 arch/x86/kvm/vmx/main.c            |  34 ++-
 arch/x86/kvm/vmx/tdx.c             | 411
+++++++++++++++++++++++++++++ arch/x86/kvm/vmx/tdx.h             |
2 + arch/x86/kvm/vmx/x86_ops.h         |  11 +
 arch/x86/kvm/x86.c                 |   8 +
 7 files changed, 467 insertions(+), 3 deletions(-)
(quoted diff) +0 -0

b/arch/x86/include/asm/kvm-x86-ops.h index 8a5c5ae70bc5..3a29a6b31ee8 100644 --- a/arch/x86/include/asm/kvm-x86-ops.h
+++ b/arch/x86/include/asm/kvm-x86-ops.h

arch/x86/include/asm/kvm-x86-ops.h +2 -0
@@ -21,7 +21,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_OPTIONAL(flush_shadow_all_private)
 KVM_X86_OP_OPTIONAL(vm_destroy)
+KVM_X86_OP_OPTIONAL(vm_free)
 KVM_X86_OP_OPTIONAL_RET0(vcpu_precreate)
 KVM_X86_OP(vcpu_create)
 KVM_X86_OP(vcpu_free)
(quoted diff) +0 -0

b/arch/x86/include/asm/kvm_host.h index 2a41a93a80f3..2870155ce6fb 100644 --- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h

arch/x86/include/asm/kvm_host.h +2 -0
@@ -1472,7 +1472,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 (*flush_shadow_all_private)(struct kvm *kvm);
 	void (*vm_destroy)(struct kvm *kvm);
+	void (*vm_free)(struct kvm *kvm);
 
 	/* Create, but do not attach this VCPU */
 	int (*vcpu_precreate)(struct kvm *kvm);
arch/x86/kvm/vmx/main.c +6 -1
index 0900ff2f2390..d01a946a18cf 100644
@@ -29,18 +29,44 @@ 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)
 {
 	if (is_td(kvm))
-		return -EOPNOTSUPP;	/* Not ready to create

guest TD yet. */

arch/x86/kvm/vmx/main.c +22 -1
+		return tdx_vm_init(kvm);
 
 	return vmx_vm_init(kvm);
 }
 
+static void vt_flush_shadow_all_private(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_mmu_release_hkid(kvm);
+}
+
+static void vt_vm_destroy(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return;
+
+	vmx_vm_destroy(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",
 
-	.hardware_unsetup = vmx_hardware_unsetup,
+	.hardware_unsetup = vt_hardware_unsetup,
 	.check_processor_compatibility =

vmx_check_processor_compatibility,

arch/x86/kvm/vmx/main.c +3 -1
 	.hardware_enable = vmx_hardware_enable,
@@ -50,7 +76,9 @@ 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,
-	.vm_destroy = vmx_vm_destroy,
+	.flush_shadow_all_private = vt_flush_shadow_all_private,
+	.vm_destroy = vt_vm_destroy,
+	.vm_free = vt_vm_free,
 
 	.vcpu_precreate = vmx_vcpu_precreate,
 	.vcpu_create = vmx_vcpu_create,
arch/x86/kvm/vmx/tdx.c +3 -0
index 530e72f85762..ec88dde0d300 100644
@@ -32,6 +32,401 @@ struct tdx_capabilities {
 /* Capabilities of KVM + the TDX module. */
 static struct tdx_capabilities tdx_caps;
 
+/*
+ * Some TDX SEAMCALLs (TDH.MNG.CREATE, TDH.PHYMEM.CACHE.WB,
+ * TDH.MNG.KEY.RECLAIMID, TDH.MNG.KEY.FREEID etc) tries to acquire a

global lock
+ * internally in TDX module. If failed, TDX_OPERAND_BUSY is returned without
+ * spinning or waiting due to a constraint on execution time. It's caller's
+ * responsibility to avoid race (or retry on TDX_OPERAND_BUSY). Use this mutex
+ * to avoid race in TDX module because the kernel knows better about scheduling.
+ */

arch/x86/kvm/vmx/tdx.c +27 -0
+static DEFINE_MUTEX(tdx_lock);
+static struct mutex *tdx_mng_key_config_lock;
+
+static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
+{
+	return pa | ((hpa_t)hkid << boot_cpu_data.x86_phys_bits);
+}
+
+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)));

arch/x86/kvm/vmx/tdx.c +4 -0
+	unsigned long i;
+
+	/*
+	 * Zeroing the page is only necessary for systems with

MKTME-i:

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * when re-assign one page from old keyid to a new keyid,

MOVDIR64B is

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * required to clear/write the page with new keyid to

prevent integrity

arch/x86/kvm/vmx/tdx.c +3 -0
+	 * error when read on the page with new keyid.
+	 *
+	 * The cache line could be poisoned (even without MKTME-i),

clear the

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	 * poison bit.
+	 */
+	for (i = 0; i < PAGE_SIZE; i += 64)
+		movdir64b((void *)(page + i), zero_page);

In patch 11, the clflush is used on the movdir64b target. Should we also use the clflush here?

I suppose the clflush is to prevent the unexpected cacheline writeback after the movdir64b.

Quoted 34 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	/*
+	 * MOVDIR64B store uses WC buffer.  Prevent following memory

reads

arch/x86/kvm/vmx/tdx.c +6 -0
+	 * from seeing potentially poisoned cache.
+	 */
+	__mb();
+}
+
+static int tdx_reclaim_page(unsigned long va, hpa_t pa, bool do_wb,

u16 hkid) +{

arch/x86/kvm/vmx/tdx.c +7 -0
+	struct tdx_module_output out;
+	u64 err;
+
+	do {
+		err = tdh_phymem_page_reclaim(pa, &out);
+		/*
+		 * TDH.PHYMEM.PAGE.RECLAIM is allowed only when TD

is shutdown.

arch/x86/kvm/vmx/tdx.c +2 -0
+		 * state.  i.e. destructing TD.
+		 * TDH.PHYMEM.PAGE.RECLAIM  requires TDR and target

page.

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * Because we're destructing TD, it's rare to

contend with TDR.

arch/x86/kvm/vmx/tdx.c +10 -0
+		 */
+	} while (err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_RCX));
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
+		return -EIO;
+	}
+
+	if (do_wb) {
+		/*
+		 * Only TDR page gets into this path.  No contention

is expected

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

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+		 * because the last page of TD.

because of

Quoted 459 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		 */
+		err = tdh_phymem_page_wbinvd(set_hkid_to_hpa(pa,

hkid));

arch/x86/kvm/vmx/tdx.c +2 -0
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err,

NULL);

arch/x86/kvm/vmx/tdx.c +29 -0
+			return -EIO;
+		}
+	}
+
+	tdx_clear_page(va);
+	return 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 inline 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) {
+		/*
+		 * TDCX are being reclaimed.  TDX module maps TDCX

with HKID

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * assigned to the TD.  Here the cache associated to

the TD

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * was already flushed by TDH.PHYMEM.CACHE.WB before

here, So

arch/x86/kvm/vmx/tdx.c +48 -0
+		 * cache doesn't need to be flushed again.
+		 */
+		if (tdx_reclaim_page(page->va, page->pa, false, 0))
+			return;
+
+		page->added = false;
+	}
+	if (page->va) {
+		free_page(page->va);
+		page->va = 0;
+	}
+}
+
+static int tdx_do_tdh_phymem_cache_wb(void *param)
+{
+	u64 err = 0;
+
+	do {
+		err = tdh_phymem_cache_wb(!!err);
+	} while (err == TDX_INTERRUPTED_RESUMABLE);
+
+	/* 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_release_hkid(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;
+
+	cpumask_allocated = zalloc_cpumask_var(&packages,

GFP_KERNEL);

arch/x86/kvm/vmx/tdx.c +4 -0
+	cpus_read_lock();
+	for_each_online_cpu(i) {
+		if (cpumask_allocated &&
+

cpumask_test_and_set_cpu(topology_physical_package_id(i),

arch/x86/kvm/vmx/tdx.c +5 -0
+						packages))
+			continue;
+
+		/*
+		 * We can destroy multiple the guest TDs

simultaneously.

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * Prevent tdh_phymem_cache_wb from returning

TDX_BUSY by

arch/x86/kvm/vmx/tdx.c +4 -0
+		 * serialization.
+		 */
+		mutex_lock(&tdx_lock);
+		ret = smp_call_on_cpu(i, tdx_do_tdh_phymem_cache_wb,

NULL, 1);

arch/x86/kvm/vmx/tdx.c +13 -0
+		mutex_unlock(&tdx_lock);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	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);
+		pr_err("tdh_mng_key_freeid failed. HKID %d is

leaked.\n",

arch/x86/kvm/vmx/tdx.c +25 -0
+			kvm_tdx->hkid);
+		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;
+
+	if (kvm_tdx->tdcs) {
+		for (i = 0; i < tdx_caps.tdcs_nr_pages; i++)
+			tdx_reclaim_td_page(&kvm_tdx->tdcs[i]);
+		kfree(kvm_tdx->tdcs);
+	}
+
+	/*
+	 * TDX module maps TDR with TDX global HKID.  TDX module may

access TDR

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * while operating on TD (Especially reclaiming TDCS).

Cache flush with

arch/x86/kvm/vmx/tdx.c +4 -0
+	 * TDX global HKID is needed.
+	 */
+	if (kvm_tdx->tdr.added &&
+		tdx_reclaim_page(kvm_tdx->tdr.va, kvm_tdx->tdr.pa,

true,

arch/x86/kvm/vmx/tdx.c +16 -0
+				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;
+	u64 err;
+
+	do {
+		err = tdh_mng_key_config(*tdr_p);
+
+		/*
+		 * If it failed to generate a random key, retry it

because this

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * is typically caused by an entropy error of the

CPU's random

arch/x86/kvm/vmx/tdx.c +29 -0
+		 * number generator.
+		 */
+	} while (err == TDX_KEY_GENERATION_FAILED);
+
+	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;
+
+	ret = tdx_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;
+
+	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),

arch/x86/kvm/vmx/tdx.c +16 -0
+				GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	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;
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in

order to

arch/x86/kvm/vmx/tdx.c +4 -0
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i),

packages);

arch/x86/kvm/vmx/tdx.c +2 -0
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i),

packages);

arch/x86/kvm/vmx/tdx.c +4 -0
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure

out the

arch/x86/kvm/vmx/tdx.c +3 -0
+		 * reason, warn it.
+		 */
+		pr_warn("All packages need to have online CPU to

create TD. Online CPU and retry.\n");

arch/x86/kvm/vmx/tdx.c +6 -0
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key

Owner

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * Table (KOT) to track the assigned TDX private HKID.  It

doesn't spin

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead,

and let the

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * caller to handle the contention.  This is because of time

limitation

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * usable inside the TDX module and OS/VMM knows better

about process

arch/x86/kvm/vmx/tdx.c +4 -0
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE,

and

arch/x86/kvm/vmx/tdx.c +20 -0
+	 * TDH.PHYMEM.CACHE.WB.
+	 */
+	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_packages;
+	}
+	tdx_mark_td_page_added(&kvm_tdx->tdr);
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with

an

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * encryption key associated to a TDX private host

key id

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * assigned to this TDR.  Concurrent operations on

same memory

arch/x86/kvm/vmx/tdx.c +1 -0
+		 * controller results in TDX_OPERAND_BUSY.  Avoid

this race by

arch/x86/kvm/vmx/tdx.c +16 -0
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr.pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	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);

arch/x86/kvm/vmx/tdx.c +10 -0
+		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

arch/x86/kvm/vmx/tdx.c +6 -0
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially

initialized TD

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * varies based on where in the initialization flow failure

occurred.

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * Simply use the full teardown and destroy, which naturally

play nice

arch/x86/kvm/vmx/tdx.c +41 -0
+	 * with partial initialization.
+	 */
+teardown:
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		if (!kvm_tdx->tdcs[i].va)
+			continue;
+		free_page(kvm_tdx->tdcs[i].va);
+	}
+	kfree(kvm_tdx->tdcs);
+	kvm_tdx->tdcs = NULL;
+free_tdr:
+	if (kvm_tdx->tdr.va) {
+		free_page(kvm_tdx->tdr.va);
+		kvm_tdx->tdr.added = false;
+		kvm_tdx->tdr.va = 0;
+		kvm_tdx->tdr.pa = 0;
+	}
+free_hkid:
+	if (kvm_tdx->hkid != -1)
+		tdx_hkid_free(kvm_tdx);
+	return ret;
+}
+
 static int __init tdx_module_setup(void)
 {
 	const struct tdsysinfo_struct *tdsysinfo;
@@ -82,6 +477,8 @@ bool tdx_is_vm_type_supported(unsigned long type)
 
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 {
+	int max_pkgs;
+	int i;
 	int r;
 
 	if (!enable_ept) {
@@ -95,6 +492,14 @@ int __init tdx_hardware_setup(struct kvm_x86_ops
 *x86_ops) return -ENODEV;
 	}
 
+	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]);
+
 	/* TDX requires VMX. */
 	r = vmxon_all();
arch/x86/kvm/vmx/tdx.c +6 -0
 	if (!r)
@@ -103,3 +508,9 @@ int __init tdx_hardware_setup(struct kvm_x86_ops
 *x86_ops) 
 	return r;
 }
+
+void tdx_hardware_unsetup(void)
+{
+	/* kfree accepts NULL. */
+	kfree(tdx_mng_key_config_lock);
+}
arch/x86/kvm/vmx/tdx.h +2 -0
index 98999bf3f188..938314635b47 100644
@@ -17,6 +17,8 @@ struct kvm_tdx {
 
 	struct tdx_td_page tdr;
 	struct tdx_td_page *tdcs;
+
+	int hkid;
 };
 
 struct vcpu_tdx {
arch/x86/kvm/vmx/x86_ops.h +5 -0
index ac1688b0b0e3..95da978c9aa9 100644
@@ -133,9 +133,20 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 #ifdef CONFIG_INTEL_TDX_HOST
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 bool tdx_is_vm_type_supported(unsigned long type);
+void tdx_hardware_unsetup(void);
+
+int tdx_vm_init(struct kvm *kvm);
+void tdx_mmu_release_hkid(struct kvm *kvm);
+void tdx_vm_free(struct kvm *kvm);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) {

return 0; } static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; } +static inline void tdx_hardware_unsetup(void) {} +
+static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; } +static inline void tdx_mmu_release_hkid(struct kvm *kvm) {}

arch/x86/kvm/vmx/x86_ops.h +2 -0
+static inline void tdx_flush_shadow_all_private(struct kvm *kvm) {}
+static inline void tdx_vm_free(struct kvm *kvm) {}
 #endif
 
 #endif /* __KVM_X86_VMX_X86_OPS_H */
arch/x86/kvm/x86.c +3 -0
index 91053fdc4512..4b22196cb12c 100644
@@ -12702,6 +12702,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)
@@ -13012,6 +13013,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

arch/x86/kvm/x86.c +1 -0
+	 * tearing down private page tables, TDX requires some TD

resources to

arch/x86/kvm/x86.c +1 -0
+	 * be destroyed (i.e. keyID must have been reclaimed, etc).

Invoke

arch/x86/kvm/x86.c +3 -0
+	 * kvm_x86_flush_shadow_all_private() for this.
+	 */
+	static_call_cond(kvm_x86_flush_shadow_all_private)(kvm);
 	kvm_mmu_zap_all(kvm);
 }
#199 lore raw

Re: [PATCH v10 098/108] KVM: TDX: Implement callbacks for MSR operations for TDX

In reply to [email protected]
Quoted 6 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Implements set_msr/get_msr/has_emulated_msr methods for TDX to handle hypercall from guest TD for paravirtualized rdmsr and wrmsr. The TDX module virtualizes MSRs. For some MSRs, it injects #VE to the guest TD upon RDMSR or WRMSR. The exact list of such MSRs are defined in the spec.

How does KVM handle the case that the userland wants to get the TD MSR list?

KVM_GET_MSR_INDEX_LIST will return the global KVM MSR list, which is different from the TD version.

Quoted 5 lines

Upon #VE, the guest TD may execute hypercalls, TDG.VP.VMCALL<INSTRUCTION.RDMSR> and TDG.VP.VMCALL<INSTRUCTION.WRMSR>, which are defined in GHCI (Guest-Host Communication Interface) so that the host VMM (e.g. KVM) can virtualizes

can virtualize

Quoted 194 lines

the MSRs.

---
  arch/x86/kvm/vmx/main.c    | 34 ++++++++++++++++++--
  arch/x86/kvm/vmx/tdx.c     | 63 ++++++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/x86_ops.h |  6 ++++
  arch/x86/kvm/x86.c         |  1 -
  arch/x86/kvm/x86.h         |  2 ++
  5 files changed, 102 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +31 -3
index 74c561e3eb46..3a8a4fdf1ce7 100644
@@ -195,6 +195,34 @@ static void vt_handle_exit_irqoff(struct kvm_vcpu *vcpu)
  	vmx_handle_exit_irqoff(vcpu);
  }
 
+static int vt_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
+{
+	if (unlikely(is_td_vcpu(vcpu)))
+		return tdx_set_msr(vcpu, msr_info);
+
+	return vmx_set_msr(vcpu, msr_info);
+}
+
+/*
+ * The kvm parameter can be NULL (module initialization, or invocation before
+ * VM creation). Be sure to check the kvm parameter before using it.
+ */
+static bool vt_has_emulated_msr(struct kvm *kvm, u32 index)
+{
+	if (kvm && is_td(kvm))
+		return tdx_is_emulated_msr(index, true);
+
+	return vmx_has_emulated_msr(kvm, index);
+}
+
+static int vt_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
+{
+	if (unlikely(is_td_vcpu(vcpu)))
+		return tdx_get_msr(vcpu, msr_info);
+
+	return vmx_get_msr(vcpu, msr_info);
+}
+
  static void vt_apicv_post_state_restore(struct kvm_vcpu *vcpu)
  {
  	struct pi_desc *pi = vcpu_to_pi_desc(vcpu);
@@ -431,7 +459,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
  	.hardware_enable = vt_hardware_enable,
  	.hardware_disable = vt_hardware_disable,
-	.has_emulated_msr = vmx_has_emulated_msr,
+	.has_emulated_msr = vt_has_emulated_msr,
 
  	.is_vm_type_supported = vt_is_vm_type_supported,
  	.vm_size = sizeof(struct kvm_vmx),
@@ -451,8 +479,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
  	.update_exception_bitmap = vmx_update_exception_bitmap,
  	.get_msr_feature = vmx_get_msr_feature,
-	.get_msr = vmx_get_msr,
-	.set_msr = vmx_set_msr,
+	.get_msr = vt_get_msr,
+	.set_msr = vt_set_msr,
  	.get_segment_base = vmx_get_segment_base,
  	.get_segment = vmx_get_segment,
  	.set_segment = vmx_set_segment,
arch/x86/kvm/vmx/tdx.c +63 -0
index 50e9352464a9..b820475ce0ab 100644
@@ -1489,6 +1489,69 @@ void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
  	*error_code = 0;
  }
 
+bool tdx_is_emulated_msr(u32 index, bool write)
+{
+	switch (index) {
+	case MSR_IA32_UCODE_REV:
+	case MSR_IA32_ARCH_CAPABILITIES:
+	case MSR_IA32_POWER_CTL:
+	case MSR_MTRRcap:
+	case 0x200 ... 0x26f:
+		/* IA32_MTRR_PHYS{BASE, MASK}, IA32_MTRR_FIX*_* */
+	case MSR_IA32_CR_PAT:
+	case MSR_MTRRdefType:
+	case MSR_IA32_TSC_DEADLINE:
+	case MSR_IA32_MISC_ENABLE:
+	case MSR_KVM_STEAL_TIME:
+	case MSR_KVM_POLL_CONTROL:
+	case MSR_PLATFORM_INFO:
+	case MSR_MISC_FEATURES_ENABLES:
+	case MSR_IA32_MCG_CAP:
+	case MSR_IA32_MCG_STATUS:
+	case MSR_IA32_MCG_CTL:
+	case MSR_IA32_MCG_EXT_CTL:
+	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
+	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
+		/* MSR_IA32_MCx_{CTL, STATUS, ADDR, MISC, CTL2} */
+		return true;
+	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
+		/*
+		 * x2APIC registers that are virtualized by the CPU can't be
+		 * emulated, KVM doesn't have access to the virtual APIC page.
+		 */
+		switch (index) {
+		case X2APIC_MSR(APIC_TASKPRI):
+		case X2APIC_MSR(APIC_PROCPRI):
+		case X2APIC_MSR(APIC_EOI):
+		case X2APIC_MSR(APIC_ISR) ... X2APIC_MSR(APIC_ISR + APIC_ISR_NR):
+		case X2APIC_MSR(APIC_TMR) ... X2APIC_MSR(APIC_TMR + APIC_ISR_NR):
+		case X2APIC_MSR(APIC_IRR) ... X2APIC_MSR(APIC_IRR + APIC_ISR_NR):
+			return false;
+		default:
+			return true;
+		}
+	case MSR_IA32_APICBASE:
+	case MSR_EFER:
+		return !write;
+	default:
+		return false;
+	}
+}
+
+int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
+{
+	if (tdx_is_emulated_msr(msr->index, false))
+		return kvm_get_msr_common(vcpu, msr);
+	return 1;
+}
+
+int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
+{
+	if (tdx_is_emulated_msr(msr->index, true))
+		return kvm_set_msr_common(vcpu, msr);
+	return 1;
+}
+
  int tdx_dev_ioctl(void __user *argp)
  {
  	struct kvm_tdx_capabilities __user *user_caps;
arch/x86/kvm/vmx/x86_ops.h +6 -0
index d02619f64b6e..8b9399b154f3 100644
@@ -162,6 +162,9 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
  void tdx_inject_nmi(struct kvm_vcpu *vcpu);
  void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
  		u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code);
+bool tdx_is_emulated_msr(u32 index, bool write);
+int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr);
+int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr);
 
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
  int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
@@ -200,6 +203,9 @@ static inline void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mo
  static inline void tdx_inject_nmi(struct kvm_vcpu *vcpu) {}
  static inline void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason, u64 *info1,
  				     u64 *info2, u32 *intr_info, u32 *error_code) {}
+static inline bool tdx_is_emulated_msr(u32 index, bool write) { return false; }
+static inline int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr) { return 1; }
+static inline int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr) { return 1; }
 
  static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOPNOTSUPP; }
  static inline int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp) { return -EOPNOTSUPP; }
arch/x86/kvm/x86.c +0 -1
index 2eacc4929d5d..5304b27f2566 100644
@@ -85,7 +85,6 @@
  #include "trace.h"
 
  #define MAX_IO_MSRS 256
-#define KVM_MAX_MCE_BANKS 32
 
  struct kvm_caps kvm_caps __read_mostly = {
  	.supported_mce_cap = MCG_CTL_P | MCG_SER_P,
arch/x86/kvm/x86.h +2 -0
index 829d3134c1eb..1d77c39821ae 100644
@@ -8,6 +8,8 @@
  #include "kvm_cache_regs.h"
  #include "kvm_emulate.h"
 
+#define KVM_MAX_MCE_BANKS 32
+
  struct kvm_caps {
  	/* control of guest tsc rate supported? */
  	bool has_tsc_control;
#207 lore raw

Re: [PATCH v10 100/108] KVM: TDX: Handle TDX PV report fatal error hypercall

In reply to [email protected]
Quoted 16 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Wire up TDX PV report fatal error hypercall to KVM_SYSTEM_EVENT_CRASH KVM exit event.

---
  arch/x86/kvm/vmx/tdx.c   | 20 ++++++++++++++++++++
  include/uapi/linux/kvm.h |  1 +
  2 files changed, 21 insertions(+)
arch/x86/kvm/vmx/tdx.c +0 -0
index e3062c245e70..16f168f4f21a 100644

arch/x86/kvm/vmx/tdx.c static int tdx_emulate_wrmsr(struct kvm_vcpu *vcpu) · line 1075

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +5 -0
@@ -1068,6 +1068,24 @@ static int tdx_emulate_wrmsr(struct kvm_vcpu *vcpu)
  	return 1;
  }
 
+static int tdx_report_fatal_error(struct kvm_vcpu *vcpu)
+{
+	/*
+	 * Exit to userspace device model for teardown.
+	 * Because guest TD is already panicing

panicking

Quoted 1 line

, returning an error to guerst

typo, guest

Quoted 38 lines

TD

arch/x86/kvm/vmx/tdx.c +15 -0
+	 * doesn't make sense.  No argument check is done.
+	 */
+
+	vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
+	vcpu->run->system_event.type = KVM_SYSTEM_EVENT_TDX;
+	vcpu->run->system_event.ndata = 3;
+	vcpu->run->system_event.data[0] = TDG_VP_VMCALL_REPORT_FATAL_ERROR;
+	vcpu->run->system_event.data[1] = tdvmcall_a0_read(vcpu);
+	vcpu->run->system_event.data[2] = tdvmcall_a1_read(vcpu);
+
+	return 0;
+}
+
  static int handle_tdvmcall(struct kvm_vcpu *vcpu)
  {
  	if (tdvmcall_exit_type(vcpu))
@@ -1086,6 +1104,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)
  		return tdx_emulate_rdmsr(vcpu);
  	case EXIT_REASON_MSR_WRITE:
  		return tdx_emulate_wrmsr(vcpu);
+	case TDG_VP_VMCALL_REPORT_FATAL_ERROR:
+		return tdx_report_fatal_error(vcpu);
  	default:
  		break;
  	}
include/uapi/linux/kvm.h +1 -0
index 49386e4de8b8..504a8f73284b 100644
@@ -478,6 +478,7 @@ struct kvm_run {
  #define KVM_SYSTEM_EVENT_WAKEUP         4
  #define KVM_SYSTEM_EVENT_SUSPEND        5
  #define KVM_SYSTEM_EVENT_SEV_TERM       6
+#define KVM_SYSTEM_EVENT_TDX            7
  			__u32 type;
  			__u32 ndata;
  			union {
#212 lore raw

Re: [PATCH v10 104/108] KVM: TDX: Silently ignore INIT/SIPI

In reply to [email protected]
Quoted 117 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The TDX module API doesn't provide API for VMM to inject INIT IPI and SIPI. Instead it defines the different protocols to boot application processors. Ignore INIT and SIPI events for the TDX guest.

There are two options. 1) (silently) ignore INIT/SIPI request or 2) return error to guest TDs somehow. Given that TDX guest is paravirtualized to boot AP, the option 1 is chosen for simplicity.

---
  arch/x86/include/asm/kvm-x86-ops.h |  1 +
  arch/x86/include/asm/kvm_host.h    |  2 ++
  arch/x86/kvm/lapic.c               | 19 ++++++++++++-------
  arch/x86/kvm/svm/svm.c             |  1 +
  arch/x86/kvm/vmx/main.c            | 22 +++++++++++++++++++++-
  5 files changed, 37 insertions(+), 8 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index 17c3828d42a3..4e9b96480716 100644
@@ -140,6 +140,7 @@ KVM_X86_OP_OPTIONAL(migrate_timers)
  KVM_X86_OP(msr_filter_changed)
  KVM_X86_OP(complete_emulated_msr)
  KVM_X86_OP(vcpu_deliver_sipi_vector)
+KVM_X86_OP(vcpu_deliver_init)
  KVM_X86_OP_OPTIONAL_RET0(vcpu_get_apicv_inhibit_reasons);
  KVM_X86_OP(check_processor_compatibility)
 
arch/x86/include/asm/kvm_host.h +2 -0
index 094fff5414e1..df67ca7b23d3 100644
@@ -1706,6 +1706,7 @@ struct kvm_x86_ops {
  	int (*complete_emulated_msr)(struct kvm_vcpu *vcpu, int err);
 
  	void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu, u8 vector);
+	void (*vcpu_deliver_init)(struct kvm_vcpu *vcpu);
 
  	/*
  	 * Returns vCPU specific APICv inhibit reasons
@@ -1914,6 +1915,7 @@ int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu);
  void kvm_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
  int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector, int seg);
  void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);
+void kvm_vcpu_deliver_init(struct kvm_vcpu *vcpu);
 
  int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
  		    int reason, bool has_error_code, u32 error_code);
arch/x86/kvm/lapic.c +12 -7
index 7a1d612bd138..7393d858ed72 100644
@@ -3035,6 +3035,16 @@ int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
  	return 0;
  }
 
+void kvm_vcpu_deliver_init(struct kvm_vcpu *vcpu)
+{
+	kvm_vcpu_reset(vcpu, true);
+	if (kvm_vcpu_is_bsp(vcpu))
+		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+	else
+		vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
+}
+EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_init);
+
  int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
  {
  	struct kvm_lapic *apic = vcpu->arch.apic;
@@ -3066,13 +3076,8 @@ int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
  		return 0;
  	}
 
-	if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
-		kvm_vcpu_reset(vcpu, true);
-		if (kvm_vcpu_is_bsp(apic->vcpu))
-			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
-		else
-			vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
-	}
+	if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events))
+		static_call(kvm_x86_vcpu_deliver_init)(vcpu);
  	if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
  		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
  			/* evaluate pending_events before reading the vector */
arch/x86/kvm/svm/svm.c +1 -0
index 2bcf2e1a5271..5d56b0f1f595 100644
@@ -4857,6 +4857,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
  	.complete_emulated_msr = svm_complete_emulated_msr,
 
  	.vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
+	.vcpu_deliver_init = kvm_vcpu_deliver_init,
  	.vcpu_get_apicv_inhibit_reasons = avic_vcpu_get_apicv_inhibit_reasons,
  };
 
arch/x86/kvm/vmx/main.c +9 -0
index 4acba8d8cb27..d776d5d169d0 100644
@@ -286,6 +286,25 @@ static void vt_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
  	vmx_deliver_interrupt(apic, delivery_mode, trig_mode, vector);
  }
 
+static void vt_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	kvm_vcpu_deliver_sipi_vector(vcpu, vector);
+}
+
+static void vt_vcpu_deliver_init(struct kvm_vcpu *vcpu)

arch/x86/kvm/vmx/main.c static void vt_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode, · line 307

Quoted 10 lines
arch/x86/kvm/vmx/main.c +10 -0
+{
+	if (is_td_vcpu(vcpu)) {
+		/* TDX doesn't support INIT.  Ignore INIT event */
+		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+		return;
+	}
+
+	kvm_vcpu_deliver_init(vcpu);
+}
+

Is it better to add WARN_ON_ONCE in the above two functions for TD case?

Quoted 13 lines
arch/x86/kvm/vmx/main.c +2 -1
  static void vt_flush_tlb_all(struct kvm_vcpu *vcpu)
  {
  	if (is_td_vcpu(vcpu))
@@ -627,7 +646,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.msr_filter_changed = vmx_msr_filter_changed,
  	.complete_emulated_msr = kvm_complete_insn_gp,
 
-	.vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
+	.vcpu_deliver_sipi_vector = vt_vcpu_deliver_sipi_vector,
+	.vcpu_deliver_init = vt_vcpu_deliver_init,
 
  	.dev_mem_enc_ioctl = tdx_dev_ioctl,
  	.mem_enc_ioctl = vt_mem_enc_ioctl,
#85 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

In reply to Yan Zhao
Quoted 2 lines · Yan Zhao

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

If I recall correctly, Sean said we can disable TDX guests if mmio_caching is disabled (we also will need to change to allow enable_mmio_caching to still be true when mmio_value is 0).

SEV_ES has similar logic:

void __init sev_hardware_setup(void)
{

	...

        /*
         * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
         * instruction stream, i.e. can't emulate in response to a #NPF and
         * instead relies on #NPF(RSVD) being reflected into the guest as #VC
         * (the guest can then do a #VMGEXIT to request MMIO emulation).
         */
        if (!enable_mmio_caching)
                goto out;
#86 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

Quoted 13 lines · Kai
Quoted 2 lines · Yan Zhao

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

If I recall correctly, Sean said we can disable TDX guests if mmio_caching is disabled (we also will need to change to allow enable_mmio_caching to still be true when mmio_value is 0).

SEV_ES has similar logic:

void __init sev_hardware_setup(void)
{

Quoted 11 lines
	...

        /*
         * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
         * instruction stream, i.e. can't emulate in response to a #NPF and
         * instead relies on #NPF(RSVD) being reflected into the guest as #VC
         * (the guest can then do a #VMGEXIT to request MMIO emulation).
         */
        if (!enable_mmio_caching)
                goto out;

Would enabling mmio caching in per-VM basis be better?

#87 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

Quoted 26 lines · Yan Zhao
Quoted 13 lines · Kai
Quoted 2 lines · Yan Zhao

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

If I recall correctly, Sean said we can disable TDX guests if mmio_caching is disabled (we also will need to change to allow enable_mmio_caching to still be true when mmio_value is 0).

SEV_ES has similar logic:

void __init sev_hardware_setup(void)
{

Quoted 11 lines
	...

        /*
         * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
         * instruction stream, i.e. can't emulate in response to a #NPF and
         * instead relies on #NPF(RSVD) being reflected into the guest as #VC
         * (the guest can then do a #VMGEXIT to request MMIO emulation).
         */
        if (!enable_mmio_caching)
                goto out;
Quoted 2 lines

Would enabling mmio caching in per-VM basis be better?

We need Paolo/Sean to decide.

The thing is TDX guests always require mmio_caching being enabled. For VMX guests, normally we will always enable mmio_caching too. So I think per-VM basis mmio_caching is not that useful.

#88 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

Quoted 27 lines · Kai
Quoted 26 lines · Yan Zhao
Quoted 24 lines · Kai
Quoted 2 lines · Yan Zhao

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

If I recall correctly, Sean said we can disable TDX guests if mmio_caching is disabled (we also will need to change to allow enable_mmio_caching to still be true when mmio_value is 0).

SEV_ES has similar logic:

void __init sev_hardware_setup(void)
{

	...

        /*
         * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
         * instruction stream, i.e. can't emulate in response to a #NPF and
         * instead relies on #NPF(RSVD) being reflected into the guest as #VC
         * (the guest can then do a #VMGEXIT to request MMIO emulation).
         */
        if (!enable_mmio_caching)
                goto out;
Quoted 8 lines
Quoted 2 lines

Would enabling mmio caching in per-VM basis be better?

We need Paolo/Sean to decide.

The thing is TDX guests always require mmio_caching being enabled. For VMX guests, normally we will always enable mmio_caching too. So I think per-VM basis mmio_caching is not that useful.

With per-VM basis enabling, I think we can get rid of the kvm_gfn_shared_mask(kvm) in below code and also in handle_abnormal_pfn()

static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)

{
        return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
               likely(enable_mmio_caching || kvm_gfn_shared_mask(kvm));
}

Thanks
Yan

#89 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

Quoted 36 lines · Yan Zhao
Quoted 27 lines · Kai
Quoted 26 lines · Yan Zhao
Quoted 24 lines · Kai
Quoted 2 lines · Yan Zhao

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

If I recall correctly, Sean said we can disable TDX guests if mmio_caching is disabled (we also will need to change to allow enable_mmio_caching to still be true when mmio_value is 0).

SEV_ES has similar logic:

void __init sev_hardware_setup(void)
{

	...

        /*
         * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
         * instruction stream, i.e. can't emulate in response to a #NPF and
         * instead relies on #NPF(RSVD) being reflected into the guest as #VC
         * (the guest can then do a #VMGEXIT to request MMIO emulation).
         */
        if (!enable_mmio_caching)
                goto out;
Quoted 8 lines
Quoted 2 lines

Would enabling mmio caching in per-VM basis be better?

We need Paolo/Sean to decide.

The thing is TDX guests always require mmio_caching being enabled. For VMX guests, normally we will always enable mmio_caching too. So I think per-VM basis mmio_caching is not that useful.

Quoted 9 lines

With per-VM basis enabling, I think we can get rid of the kvm_gfn_shared_mask(kvm) in below code and also in handle_abnormal_pfn()

static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)

{
        return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
               likely(enable_mmio_caching || kvm_gfn_shared_mask(kvm));
}

It needs to go anyway regardless per-VM mmio_caching or not, as explained we need to change to allow enable_mmio_caching to be true even mmio_value is 0.

#90 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

Quoted 47 lines · Kai
Quoted 36 lines · Yan Zhao
Quoted 27 lines · Kai
Quoted 26 lines · Yan Zhao
Quoted 24 lines · Kai
Quoted 2 lines · Yan Zhao

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

If I recall correctly, Sean said we can disable TDX guests if mmio_caching is disabled (we also will need to change to allow enable_mmio_caching to still be true when mmio_value is 0).

SEV_ES has similar logic:

void __init sev_hardware_setup(void)
{

	...

        /*
         * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
         * instruction stream, i.e. can't emulate in response to a #NPF and
         * instead relies on #NPF(RSVD) being reflected into the guest as #VC
         * (the guest can then do a #VMGEXIT to request MMIO emulation).
         */
        if (!enable_mmio_caching)
                goto out;
Quoted 8 lines
Quoted 2 lines

Would enabling mmio caching in per-VM basis be better?

We need Paolo/Sean to decide.

The thing is TDX guests always require mmio_caching being enabled. For VMX guests, normally we will always enable mmio_caching too. So I think per-VM basis mmio_caching is not that useful.

Quoted 9 lines

With per-VM basis enabling, I think we can get rid of the kvm_gfn_shared_mask(kvm) in below code and also in handle_abnormal_pfn()

static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)

{
        return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
               likely(enable_mmio_caching || kvm_gfn_shared_mask(kvm));
}
Quoted 2 lines

It needs to go anyway regardless per-VM mmio_caching or not, as explained we need to change to allow enable_mmio_caching to be true even mmio_value is 0.

Or it's better to check enable_mmio_caching is true in kvm_mmu_set_mmio_spte_value() as below.

void kvm_mmu_set_mmio_spte_value(struct kvm *kvm, u64 mmio_value)

{
        WARN_ON(!enable_mmio_caching);
        kvm->arch.shadow_mmio_value = mmio_value;
}
#221 lore raw

Re: [PATCH v10 106/108] Documentation/virt/kvm: Document on Trust Domain Extensions(TDX)

In reply to [email protected]
Quoted 280 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add documentation to Intel Trusted Domain Extensions(TDX) support.

---
  Documentation/virt/kvm/api.rst       |   9 +-
  Documentation/virt/kvm/index.rst     |   2 +
  Documentation/virt/kvm/intel-tdx.rst | 345 +++++++++++++++++++++++++++
  3 files changed, 355 insertions(+), 1 deletion(-)

create mode 100644 Documentation/virt/kvm/intel-tdx.rst

Documentation/virt/kvm/api.rst +8 -1
index b6f08e8a8320..3d819b2ceb78 100644
@@ -1426,6 +1426,9 @@ It is recommended to use this API instead of the KVM_SET_MEMORY_REGION ioctl.
  The KVM_SET_MEMORY_REGION does not allow fine grained control over memory
  allocation and is deprecated.
 
+For TDX guest, deleting/moving memory region loses guest memory contents.
+Read only region isn't supported.  Only as-id 0 is supported.
+
 
  4.36 KVM_SET_TSS_ADDR
  ---------------------
@@ -4714,7 +4717,7 @@ H_GET_CPU_CHARACTERISTICS hypercall.
 
  :Capability: basic
  :Architectures: x86
-:Type: vm
+:Type: vm ioctl, vcpu ioctl
  :Parameters: an opaque platform specific structure (in/out)
  :Returns: 0 on success; -1 on error
 
@@ -4726,6 +4729,10 @@ Currently, this ioctl is used for issuing Secure Encrypted Virtualization
  (SEV) commands on AMD Processors. The SEV commands are defined in
  Documentation/virt/kvm/x86/amd-memory-encryption.rst.
 
+Currently, this ioctl is used for issuing Trusted Domain Extensions
+(TDX) commands on Intel Processors. The TDX commands are defined in
+Documentation/virt/kvm/intel-tdx.rst.
+
  4.111 KVM_MEMORY_ENCRYPT_REG_REGION
  -----------------------------------
 
Documentation/virt/kvm/index.rst +2 -0
index e0a2c74e1043..cdb8b43ce797 100644
@@ -18,3 +18,5 @@ KVM
     locking
     vcpu-requests
     review-checklist
+
+   intel-tdx
Documentation/virt/kvm/intel-tdx.rst new file +218 -0
new file mode 100644
index 000000000000..6999b0f4f6c2
@@ -0,0 +1,345 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===================================
+Intel Trust Domain Extensions (TDX)
+===================================
+
+Overview
+========
+TDX stands for Trust Domain Extensions which isolates VMs from
+the virtual-machine manager (VMM)/hypervisor and any other software on
+the platform. For details, see the specifications [1]_, whitepaper [2]_,
+architectural extensions specification [3]_, module documentation [4]_,
+loader interface specification [5]_, guest-hypervisor communication
+interface [6]_, virtual firmware design guide [7]_, and other resources
+([8]_, [9]_, [10]_, [11]_, and [12]_).
+
+
+API description
+===============
+
+KVM_MEMORY_ENCRYPT_OP
+---------------------
+:Type: vm ioctl, vcpu ioctl
+
+For TDX operations, KVM_MEMORY_ENCRYPT_OP is re-purposed to be generic
+ioctl with TDX specific sub ioctl command.
+
+::
+
+  /* Trust Domain eXtension sub-ioctl() commands. */
+  enum kvm_tdx_cmd_id {
+          KVM_TDX_CAPABILITIES = 0,
+          KVM_TDX_INIT_VM,
+          KVM_TDX_INIT_VCPU,
+          KVM_TDX_INIT_MEM_REGION,
+          KVM_TDX_FINALIZE_VM,
+
+          KVM_TDX_CMD_NR_MAX,
+  };
+
+  struct kvm_tdx_cmd {
+        /* enum kvm_tdx_cmd_id */
+        __u32 id;
+        /* flags for sub-commend. If sub-command doesn't use this, set zero. */
+        __u32 flags;
+        /*
+         * data for each sub-command. An immediate or a pointer to the actual
+         * data in process virtual address.  If sub-command doesn't use it,
+         * set zero.
+         */
+        __u64 data;
+        /*
+         * Auxiliary error code.  The sub-command may return TDX SEAMCALL
+         * status code in addition to -Exxx.
+         * Defined for consistency with struct kvm_sev_cmd.
+         */
+        __u64 error;
+        /* Reserved: Defined for consistency with struct kvm_sev_cmd. */
+        __u64 unused;
+  };
+
+KVM_TDX_CAPABILITIES
+--------------------
+:Type: vm ioctl
+
+Subset of TDSYSINFO_STRCUCT retrieved by TDH.SYS.INFO TDX SEAM call will be
+returned. Which describes about Intel TDX module.
+
+- id: KVM_TDX_CAPABILITIES
+- flags: must be 0
+- data: pointer to struct kvm_tdx_capabilities
+- error: must be 0
+- unused: must be 0
+
+::
+
+  struct kvm_tdx_cpuid_config {
+          __u32 leaf;
+          __u32 sub_leaf;
+          __u32 eax;
+          __u32 ebx;
+          __u32 ecx;
+          __u32 edx;
+  };
+
+  struct kvm_tdx_capabilities {
+          __u64 attrs_fixed0;
+          __u64 attrs_fixed1;
+          __u64 xfam_fixed0;
+          __u64 xfam_fixed1;
+
+          __u32 nr_cpuid_configs;
+          struct kvm_tdx_cpuid_config cpuid_configs[0];
+  };
+
+
+KVM_TDX_INIT_VM
+---------------
+:Type: vm ioctl
+
+Does additional VM initialization specific to TDX which corresponds to
+TDH.MNG.INIT TDX SEAM call.
+
+- id: KVM_TDX_INIT_VM
+- flags: must be 0
+- data: pointer to struct kvm_tdx_init_vm
+- error: must be 0
+- unused: must be 0
+
+::
+
+  struct kvm_tdx_init_vm {
+          __u32 max_vcpus;
+          __u32 reserved;
+          __u64 attributes;
+          __u64 cpuid;  /* pointer to struct kvm_cpuid2 */
+          __u64 mrconfigid[6];          /* sha384 digest */
+          __u64 mrowner[6];             /* sha384 digest */
+          __u64 mrownerconfig[6];       /* sha348 digest */
+          __u64 reserved[43];           /* must be zero for future extensibility */
+  };
+
+
+KVM_TDX_INIT_VCPU
+-----------------
+:Type: vcpu ioctl
+
+Does additional VCPU initialization specific to TDX which corresponds to
+TDH.VP.INIT TDX SEAM call.
+
+- id: KVM_TDX_INIT_VCPU
+- flags: must be 0
+- data: initial value of the guest TD VCPU RCX
+- error: must be 0
+- unused: must be 0
+
+KVM_TDX_INIT_MEM_REGION
+-----------------------
+:Type: vm ioctl
+
+Encrypt a memory continuous region which corresponding to TDH.MEM.PAGE.ADD
+TDX SEAM call.
+If KVM_TDX_MEASURE_MEMORY_REGION flag is specified, it also extends measurement
+which corresponds to TDH.MR.EXTEND TDX SEAM call.
+
+- id: KVM_TDX_INIT_VCPU
+- flags: flags
+            currently only KVM_TDX_MEASURE_MEMORY_REGION is defined
+- data: pointer to struct kvm_tdx_init_mem_region
+- error: must be 0
+- unused: must be 0
+
+::
+
+  #define KVM_TDX_MEASURE_MEMORY_REGION   (1UL << 0)
+
+  struct kvm_tdx_init_mem_region {
+          __u64 source_addr;
+          __u64 gpa;
+          __u64 nr_pages;
+  };
+
+
+KVM_TDX_FINALIZE_VM
+-------------------
+:Type: vm ioctl
+
+Complete measurement of the initial TD contents and mark it ready to run
+which corresponds to TDH.MR.FINALIZE
+
+- id: KVM_TDX_FINALIZE_VM
+- flags: must be 0
+- data: must be 0
+- error: must be 0
+- unused: must be 0
+
+KVM TDX creation flow
+=====================
+In addition to KVM normal flow, new TDX ioctls need to be called.  The control flow
+looks like as follows.
+
+#. system wide capability check
+
+   * KVM_CAP_VM_TYPES: check if VM type is supported and if TDX_VM_TYPE is
+     supported.
+
+#. creating VM
+
+   * KVM_CREATE_VM
+   * KVM_TDX_CAPABILITIES: query if TDX is supported on the platform.
+   * KVM_TDX_INIT_VM: pass TDX specific VM parameters.
+
+#. creating VCPU
+
+   * KVM_CREATE_VCPU
+   * KVM_TDX_INIT_VCPU: pass TDX specific VCPU parameters.
+
+#. initializing guest memory
+
+   * allocate guest memory and initialize page same to normal KVM case
+     In TDX case, parse and load TDVF into guest memory in addition.
+   * KVM_TDX_INIT_MEM_REGION to add and measure guest pages.
+     If the pages has contents above, those pages need to be added.
+     Otherwise the contents will be lost and guest sees zero pages.
+   * KVM_TDX_FINALIAZE_VM: Finalize VM and measurement
+     This must be after KVM_TDX_INIT_MEM_REGION.
+
+#. run vcpu
+
+Design discussion
+=================
+
+Coexistence of normal(VMX) VM and TD VM
+---------------------------------------
+It's required to allow both legacy(normal VMX) VMs and new TD VMs to
+coexist. Otherwise the benefits of VM flexibility would be eliminated.
+The main issue for it is that the logic of kvm_x86_ops callbacks for
+TDX is different from VMX. On the other hand, the variable,

Documentation/virt/kvm/intel-tdx.rst line 228

Quoted 10 lines
Documentation/virt/kvm/intel-tdx.rst new file +10 -0
+kvm_x86_ops, is global single variable. Not per-VM, not per-vcpu.
+
+Several points to be considered:
+
+  * No or minimal overhead when TDX is disabled(CONFIG_INTEL_TDX_HOST=n).
+  * Avoid overhead of indirect call via function pointers.
+  * Contain the changes under arch/x86/kvm/vmx directory and share logic
+    with VMX for maintenance.
+    Even though the ways to operation on VM (VMX instruction vs TDX
+    SEAM call) is

are

Quoted 1 line

different, the basic idea remains same.

remains the same

Quoted 58 lines

So, many

Documentation/virt/kvm/intel-tdx.rst new file +57 -0
+    logic can be shared.
+  * Future maintenance
+    The huge change of kvm_x86_ops in (near) future isn't expected.
+    a centralized file is acceptable.
+
+- Wrapping kvm x86_ops: The current choice
+
+  Introduce dedicated file for arch/x86/kvm/vmx/main.c (the name,
+  main.c, is just chosen to show main entry points for callbacks.) and
+  wrapper functions around all the callbacks with
+  "if (is-tdx) tdx-callback() else vmx-callback()".
+
+  Pros:
+
+  - No major change in common x86 KVM code. The change is (mostly)
+    contained under arch/x86/kvm/vmx/.
+  - When TDX is disabled(CONFIG_INTEL_TDX_HOST=n), the overhead is
+    optimized out.
+  - Micro optimization by avoiding function pointer.
+
+  Cons:
+
+  - Many boiler plates in arch/x86/kvm/vmx/main.c.
+
+KVM MMU Changes
+---------------
+KVM MMU needs to be enhanced to handle Secure/Shared-EPT. The
+high-level execution flow is mostly same to normal EPT case.
+EPT violation/misconfiguration -> invoke TDP fault handler ->
+resolve TDP fault -> resume execution. (or emulate MMIO)
+The difference is, that S-EPT is operated(read/write) via TDX SEAM
+call which is expensive instead of direct read/write EPT entry.
+One bit of GPA (51 or 47 bit) is repurposed so that it means shared
+with host(if set to 1) or private to TD(if cleared to 0).
+
+- The current implementation
+
+  * Reuse the existing MMU code with minimal update.  Because the
+    execution flow is mostly same. But additional operation, TDX call
+    for S-EPT, is needed. So add hooks for it to kvm_x86_ops.
+  * For performance, minimize TDX SEAM call to operate on S-EPT. When
+    getting corresponding S-EPT pages/entry from faulting GPA, don't
+    use TDX SEAM call to read S-EPT entry. Instead create shadow copy
+    in host memory.
+    Repurpose the existing kvm_mmu_page as shadow copy of S-EPT and
+    associate S-EPT to it.
+  * Treats share bit as attributes. mask/unmask the bit where
+    necessary to keep the existing traversing code works.
+    Introduce kvm.arch.gfn_shared_mask and use "if (gfn_share_mask)"
+    for special case.
+
+    * 0 : for non-TDX case
+    * 51 or 47 bit set for TDX case.
+
+  Pros:
+
+  - Large code reuse with minimal new hooks.

Documentation/virt/kvm/intel-tdx.rst

Quoted 10 lines
Documentation/virt/kvm/intel-tdx.rst new file +10 -0
+  - Execution path is same.
+
+  Cons:
+
+  - Complicates the existing code.
+  - Repurpose kvm_mmu_page as shadow of Secure-EPT can be confusing.
+
+New KVM API, ioctl (sub)command, to manage TD VMs
+-------------------------------------------------
+Additional KVM API

API -> APIs

Documentation/virt/kvm/intel-tdx.rst

Quoted 6 lines

are needed to control TD VMs. The operations on TD

Documentation/virt/kvm/intel-tdx.rst new file +5 -0
+VMs are specific to TDX.
+
+- Piggyback and repurpose KVM_MEMORY_ENCRYPT_OP
+
+  Although not all operation isn't memory encryption,

How to understand it?

Quoted 46 lines

repupose to get

Documentation/virt/kvm/intel-tdx.rst new file +45 -0
+  TDX specific ioctls.
+
+  Pros:
+
+  - No major change in common x86 KVM code.
+
+  Cons:
+
+  - The operations aren't actually memory encryption, but operations
+    on TD VMs.
+
+References
+==========
+
+.. [1] TDX specification
+   https://software.intel.com/content/www/us/en/develop/articles/intel-trust-domain-extensions.html
+.. [2] Intel Trust Domain Extensions (Intel TDX)
+   https://software.intel.com/content/dam/develop/external/us/en/documents/tdx-whitepaper-final9-17.pdf
+.. [3] Intel CPU Architectural Extensions Specification
+   https://software.intel.com/content/dam/develop/external/us/en/documents/intel-tdx-cpu-architectural-specification.pdf
+.. [4] Intel TDX Module 1.0 EAS
+   https://software.intel.com/content/dam/develop/external/us/en/documents/intel-tdx-module-1eas.pdf
+.. [5] Intel TDX Loader Interface Specification
+   https://software.intel.com/content/dam/develop/external/us/en/documents/intel-tdx-seamldr-interface-specification.pdf
+.. [6] Intel TDX Guest-Hypervisor Communication Interface
+   https://software.intel.com/content/dam/develop/external/us/en/documents/intel-tdx-guest-hypervisor-communication-interface.pdf
+.. [7] Intel TDX Virtual Firmware Design Guide
+   https://software.intel.com/content/dam/develop/external/us/en/documents/tdx-virtual-firmware-design-guide-rev-1.
+.. [8] intel public github
+
+   * kvm TDX branch: https://github.com/intel/tdx/tree/kvm
+   * TDX guest branch: https://github.com/intel/tdx/tree/guest
+
+.. [9] tdvf
+    https://github.com/tianocore/edk2-staging/tree/TDVF
+.. [10] KVM forum 2020: Intel Virtualization Technology Extensions to
+     Enable Hardware Isolated VMs
+     https://osseu2020.sched.com/event/eDzm/intel-virtualization-technology-extensions-to-enable-hardware-isolated-vms-sean-christopherson-intel
+.. [11] Linux Security Summit EU 2020:
+     Architectural Extensions for Hardware Virtual Machine Isolation
+     to Advance Confidential Computing in Public Clouds - Ravi Sahita
+     & Jun Nakajima, Intel Corporation
+     https://osseu2020.sched.com/event/eDOx/architectural-extensions-for-hardware-virtual-machine-isolation-to-advance-confidential-computing-in-public-clouds-ravi-sahita-jun-nakajima-intel-corporation
+.. [12] [RFCv2,00/16] KVM protected memory extension
+     https://lkml.org/lkml/2020/10/20/66
#91 lore raw

Re: [PATCH v10 035/108] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

In reply to Yan Zhao
Quoted 48 lines · Yan Zhao
Quoted 47 lines · Kai
Quoted 45 lines · Yan Zhao
Quoted 27 lines · Kai
Quoted 26 lines · Yan Zhao
Quoted 24 lines · Kai
Quoted 2 lines · Yan Zhao

Also make enable_mmio_caching to be a per-VM value?
As if the shadow_mmio_value is 0, mmio_caching needs to be disabled.

If I recall correctly, Sean said we can disable TDX guests if mmio_caching is disabled (we also will need to change to allow enable_mmio_caching to still be true when mmio_value is 0).

SEV_ES has similar logic:

void __init sev_hardware_setup(void)
{

	...

        /*
         * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
         * instruction stream, i.e. can't emulate in response to a #NPF and
         * instead relies on #NPF(RSVD) being reflected into the guest as #VC
         * (the guest can then do a #VMGEXIT to request MMIO emulation).
         */
        if (!enable_mmio_caching)
                goto out;
Quoted 8 lines
Quoted 2 lines

Would enabling mmio caching in per-VM basis be better?

We need Paolo/Sean to decide.

The thing is TDX guests always require mmio_caching being enabled. For VMX guests, normally we will always enable mmio_caching too. So I think per-VM basis mmio_caching is not that useful.

With per-VM basis enabling, I think we can get rid of the kvm_gfn_shared_mask(kvm) in below code and also in handle_abnormal_pfn()

static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)

{
        return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
               likely(enable_mmio_caching || kvm_gfn_shared_mask(kvm));
}
Quoted 2 lines
Quoted 2 lines

It needs to go anyway regardless per-VM mmio_caching or not, as explained we need to change to allow enable_mmio_caching to be true even mmio_value is 0.

Yes, the kvm_gfn_shared_mask() in is_mmio_spte() should not exist.

Quoted 7 lines

Or it's better to check enable_mmio_caching is true in kvm_mmu_set_mmio_spte_value() as below.

void kvm_mmu_set_mmio_spte_value(struct kvm *kvm, u64 mmio_value)

{
        WARN_ON(!enable_mmio_caching);
        kvm->arch.shadow_mmio_value = mmio_value;

Eh, if you're going to bother with that assert, capture the more subtle aspects as well, e.g. that EPT is enabled and that shadow_mmio_mask has been set to the expected value. I would also ditch the helper and just open code this in TDX code, I doubt there's a use case outside of TDX+VMX coexistence.

#81 lore raw

Re: [PATCH v10 034/108] KVM: x86/mmu: Add Suppress VE bit to shadow_mmio_{value, mask}

In reply to Isaku Yamahata
Quoted 11 lines · Isaku Yamahata
Quoted 8 lines · Kai
Quoted 6 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Because TDX will need shadow_mmio_mask to be VMX_SUPPRESS_VE | RWX shadow_mmio_value to be 0, make VMX EPT case use same value for TDX shadow_mmio_mask.

Quoted 7 lines
Quoted 4 lines

TDX need to use different mmio_mask/value doesn't mean they need to be changed for VMX guest. I think the true purpose here is to still be able to use a global shadow_mmio_mask for both TDX and VMX guests. So please explicitly call out.

That's right. With this change, per-VM shadow_mmio_{value, mask} can be avoided. The common value can be used for both VMX and TDX.

No, the mask can be global, but the value needs to be per-VM. VMX needs to generate an EPT misconfig, but TDX needs to generate an EPT violation to get the automagic #VE reflection.

#131 lore raw

RE: [PATCH v10 052/108] KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs

In reply to [email protected]
Quoted 127 lines · Isaku

From: Isaku Yamahata <[email protected]>

Some KVM MMU operations (dirty page logging, page migration, aging page) aren't supported for private GFNs (yet) with the first generation of TDX. Silently return on unsupported TDX KVM MMU operations.

---
 arch/x86/kvm/mmu/mmu.c     |  3 ++
 arch/x86/kvm/mmu/tdp_mmu.c | 73
+++++++++++++++++++++++++++++++++++---
 arch/x86/kvm/x86.c         |  3 ++
 3 files changed, 74 insertions(+), 5 deletions(-)
arch/x86/kvm/mmu/mmu.c index renamed from arch/x86/kvm/mmu/mmu.c +0 -0

02e7b5cf3231..efc3b3f2dd12 100644

arch/x86/kvm/mmu/mmu.c +3 -0
@@ -6588,6 +6588,9 @@ static bool kvm_mmu_zap_collapsible_spte(struct
 kvm *kvm,
 	for_each_rmap_spte(rmap_head, &iter, sptep) {
 		sp = sptep_to_sp(sptep);
 
+		/* Private page dirty logging is not supported yet. */
+		KVM_BUG_ON(is_private_sptep(sptep), kvm);
+
 		/*
 		 * We cannot do huge page mapping for indirect shadow pages,

* which are found on the last rmap (level = 1) when not using diff --git
a/arch/x86/kvm/mmu/tdp_mmu.c b/arch/x86/kvm/mmu/tdp_mmu.c index 0e053b96444a..4b207ce83ffe 100644

arch/x86/kvm/mmu/tdp_mmu.c +2 -1
@@ -1469,7 +1469,8 @@ typedef bool (*tdp_handler_t)(struct kvm *kvm,
 struct tdp_iter *iter,
 
 static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm,
 						   struct kvm_gfn_range *range,
-						   tdp_handler_t handler)
+						   tdp_handler_t handler,
+						   bool only_shared)
 {
 	struct kvm_mmu_page *root;
arch/x86/kvm/mmu/tdp_mmu.c +15 -1
 	struct tdp_iter iter;
@@ -1480,9 +1481,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) {
+		gfn_t start;
+		gfn_t end;
+
+		if (only_shared && is_private_sp(root))
+			continue;
+
 		rcu_read_lock();
 
-		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.
+		 */
+		start = kvm_gfn_for_root(kvm, root, range->start);
+		end = kvm_gfn_for_root(kvm, root, range->end);
+
+		tdp_root_for_each_leaf_pte(iter, root, start, end)
 			ret |= handler(kvm, &iter, range);
 
arch/x86/kvm/mmu/tdp_mmu.c +6 -1
 		rcu_read_unlock();
@@ -1526,7 +1541,12 @@ static bool age_gfn_range(struct kvm *kvm, struct
 tdp_iter *iter,
 
 bool kvm_tdp_mmu_age_gfn_range(struct kvm *kvm, struct kvm_gfn_range
 *range)  {
-	return kvm_tdp_mmu_handle_gfn(kvm, range, age_gfn_range);
+	/*
+	 * 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.
+	 */
+	return kvm_tdp_mmu_handle_gfn(kvm, range, age_gfn_range, true);
 }
 

static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter, @@ -1537,7
+1557,8 @@ static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter,

bool kvm_tdp_mmu_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range
*range) {

arch/x86/kvm/mmu/tdp_mmu.c +3 -1
-	return kvm_tdp_mmu_handle_gfn(kvm, range, test_age_gfn);
+	/* The first TDX generation doesn't support A bit. */
+	return kvm_tdp_mmu_handle_gfn(kvm, range, test_age_gfn, true);
 }
 
 static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter, @@ -1582,8
+1603,11 @@ bool kvm_tdp_mmu_set_spte_gfn(struct kvm *kvm, struct

kvm_gfn_range *range)

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
 	 * No need to handle the remote TLB flush under RCU protection, the
 	 * target SPTE _must_ be a leaf SPTE, i.e. cannot result in freeing a
 	 * shadow page.  See the WARN on pfn_changed in

__handle_changed_spte().

arch/x86/kvm/mmu/tdp_mmu.c +13 -1
+	 *
+	 * .change_pte() callback should not happen for private page, because
+	 * for now TDX private pages are pinned during VM's life time.
 	 */
-	return kvm_tdp_mmu_handle_gfn(kvm, range, set_spte_gfn);
+	return kvm_tdp_mmu_handle_gfn(kvm, range, set_spte_gfn, true);
 }
 
 /*
@@ -1637,6 +1661,14 @@ bool kvm_tdp_mmu_wrprot_slot(struct kvm *kvm,
 
 	lockdep_assert_held_read(&kvm->mmu_lock);
 
+	/*
+	 * Because first TDX generation doesn't support write protecting private
+	 * mappings and kvm_arch_dirty_log_supported(kvm) = false, it's a bug
+	 * to reach here for guest TD.
+	 */
+	if (WARN_ON_ONCE(!kvm_arch_dirty_log_supported(kvm)))
+		return false;
+
 	for_each_valid_tdp_mmu_root_yield_safe(kvm, root, slot->as_id, true)
 		spte_set |= wrprot_gfn_range(kvm, root, slot->base_gfn,
 			     slot->base_gfn + slot->npages, min_level); @@ -1902,6
+1934,14 @@ bool kvm_tdp_mmu_clear_dirty_slot(struct kvm *kvm,
 

arch/x86/kvm/mmu/tdp_mmu.c bool kvm_tdp_mmu_wrprot_slot(struct kvm *kvm,

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +8 -0
 	lockdep_assert_held_read(&kvm->mmu_lock);
 
+	/*
+	 * 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_ONCE(!kvm_arch_dirty_log_supported(kvm)))
+		return false;
+

It might not be a good choice to intercept everywhere in kvm_mmu just as tdx doesn't support it. I'm thinking maybe we could do the check in tdx.c, which is much simpler. For example:

@@ -2592,6 +2605,12 @@ static void tdx_handle_changed_private_spte(struct kvm *kvm,

        lockdep_assert_held(&kvm->mmu_lock);

        if (change->new.is_present) {

+ /* Only flags change. This isn't supported currently. */
+ KVM_BUG_ON(change->old.is_present, kvm);

Then we can have kvm_arch_dirty_log_supported completely removed.

#151 lore raw

PATCH v10 62/108 KVM: x86/tdp_mmu: implement MapGPA hypercall for TDX

In reply to Binbin Wu
Quoted 19 lines
arch/x86/kvm/mmu/mmu.c +19 -0
+int __kvm_mmu_map_gpa(struct kvm *kvm, gfn_t *startp, gfn_t end,
+		      bool map_private)
+{
+	gfn_t start = *startp;
+	int attr;
+	int ret;
+
+	if (!kvm_gfn_shared_mask(kvm))
+		return -EOPNOTSUPP;
+
+	attr = map_private ? KVM_MEM_ATTR_PRIVATE : KVM_MEM_ATTR_SHARED;
+	start = start & ~kvm_gfn_shared_mask(kvm);
+	end = end & ~kvm_gfn_shared_mask(kvm);
+
+	/*
+	 * To make the following kvm_vm_set_mem_attr() success within spinlock
+	 * without memory allocation.
+	 */
+	ret = kvm_vm_reserve_mem_attr(kvm, start, end);

arch/x86/kvm/mmu/mmu.c void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen) · line 6809

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	if (ret)
+		return ret;
+
+	write_lock(&kvm-> mmu_lock);
+	if (is_tdp_mmu_enabled(kvm)) {
+		gfn_t s = start;
+
+		ret = kvm_tdp_mmu_map_gpa(kvm, &s, end, map_private);
+		if (!ret) {
+			KVM_BUG_ON(kvm_vm_set_mem_attr(kvm, attr, start, end), kvm);

This will result in no exits to userspace during memory conversion requests from guests. And as a result, userspace will not be able to explicitly back/unback shared/private memory during conversions leading to double allocation of memory.

Is this an intended behavior for memory conversion with TDX VMs as per earlier discussion?

Quoted 11 lines
arch/x86/kvm/mmu/mmu.c +11 -0
+		} else if (ret == -EAGAIN) {
+			KVM_BUG_ON(kvm_vm_set_mem_attr(kvm, attr, start, s), kvm);
+			start = s;
+		}
+	} else {
+		ret = -EOPNOTSUPP;
+	}
+	write_unlock(&kvm-> mmu_lock);
+
+	if (ret == -EAGAIN) {
+		if (map_private)
#41 lore raw

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to [email protected]

In tdx_vm_init, it is possible to have a double-reclaim, which eventually causes a host crash. I have a selftest that reliably reproduces this, and I believe the problem is that withiin tdx_vm_free(), we don't reset kvm->tdcs = NULL and kvm->tdr.added to false.

Quoted 115 lines
(quoted diff) +46 -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;
+
+	ret = tdx_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;
+
+	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 | __GFP_ZERO);
+	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;
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in order to
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i), packages);
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i), packages);
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure out the
+		 * reason, warn it.
+		 */
+		pr_warn("All packages need to have online CPU to create TD. Online CPU  

and retry.\n");

(quoted diff) +63 -0
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+	 * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+	 * caller to handle the contention.  This is because of time limitation
+	 * usable inside the TDX module and OS/VMM knows better about process
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+	 * TDH.PHYMEM.CACHE.WB.
+	 */
+	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_packages;
+	}
+	tdx_mark_td_page_added(&kvm_tdx->tdr);
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr.pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	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

(quoted diff) +4 -0
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+

Review

Quoted 10 lines
(quoted diff) +10 -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_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;

If there is some error that causes an exit through teardown, tdx_vm_free() will be called, which causes the resources to be freed. However, tdx_vm_free() is called a second time when the selftest (or qemu) exits, which causes a second reclaim to be performed.

Quoted 14 lines
(quoted diff) +14 -0
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		if (!kvm_tdx->tdcs[i].va)
+			continue;
+		free_page(kvm_tdx->tdcs[i].va);
+	}
+	kfree(kvm_tdx->tdcs);
+	kvm_tdx->tdcs = NULL;
+free_tdr:
+	if (kvm_tdx->tdr.va) {

Review

Quoted 10 lines
(quoted diff) +10 -0
+		free_page(kvm_tdx->tdr.va);
+		kvm_tdx->tdr.added = false;
+		kvm_tdx->tdr.va = 0;
+		kvm_tdx->tdr.pa = 0;
+	}
+free_hkid:
+	if (kvm_tdx->hkid != -1)
+		tdx_hkid_free(kvm_tdx);
+	return ret;
+}

The second reclaim is performed because kvm_tdx->tdcs is still set, and kvm_tdx->tdr.added is still set, so the second two if blocks in tdx_vm_free() are executed.

Quoted 17 lines
(quoted diff) +17 -0
+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;
+
+	if (kvm_tdx->tdcs) {
+		for (i = 0; i < tdx_caps.tdcs_nr_pages; i++)
+			tdx_reclaim_td_page(&kvm_tdx->tdcs[i]);
+		kfree(kvm_tdx->tdcs);
+	}
+
+	/*
+	 * TDX module maps TDR with TDX global HKID.  TDX module may access TDR

Review

Quoted 10 lines
(quoted diff) +10 -0
+	 * while operating on TD (Especially reclaiming TDCS).  Cache flush with
+	 * TDX global HKID is needed.
+	 */
+	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);
+}

Here's the fix that stopped the crash I was observing

arch/x86/kvm/vmx/tdx.c +4 -0
index 2e7916fb72a7..41d1ff1510c3 100644
@@ -405,6 +405,7 @@ void tdx_vm_free(struct kvm *kvm)
                for (i = 0; i < tdx_caps.tdcs_nr_pages; i++)
                        tdx_reclaim_td_page(&kvm_tdx->tdcs[i]);
                kfree(kvm_tdx->tdcs);
+               kvm_tdx->tdcs = NULL;
        }
 
        /*
@@ -418,6 +419,9 @@ void tdx_vm_free(struct kvm *kvm)
                return;
 
        free_page(kvm_tdx->tdr.va);
+       kvm_tdx->tdr.added = false;
+       kvm_tdx->tdr.va = 0;
+       kvm_tdx->tdr.pa = 0;
 }
 
 static int tdx_do_tdh_mng_key_config(void *param)
#111 lore raw

Re: [PATCH v10 046/108] KVM: Add flags to struct kvm_gfn_range

In reply to [email protected]
Quoted 8 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

kvm_unmap_gfn_range() needs to know the reason of the callback for TDX. mmu notifier, set memattr ioctl or restrictedmem notifier. Based on the reason, TDX changes the behavior. For mmu notifier, it's the operation on shared memory slot to zap shared PTE. For set memattr, private<->shared conversion, zap the original PTE. For restrictedmem, it's a hint that TDX can ignore.

Could you elaborate why restricted memfd notifier can be ignored? IIUC if userspace punch a hole, the pages within the hole will be de-allocated. So why can such notifier be ignored?

Btw, I think this patch should be just merged to the patch which consumes those flags (checked it is next patch). It's easier to review when putting them together.

Quoted 16 lines
---
 include/linux/kvm_host.h | 8 +++++++-
 virt/kvm/kvm_main.c      | 5 ++++-
 2 files changed, 11 insertions(+), 2 deletions(-)
include/linux/kvm_host.h +1 -0
index 839d98d56632..b658803ea2c7 100644
@@ -247,12 +247,18 @@ int kvm_async_pf_wakeup_all(struct kvm_vcpu *vcpu);
 
 
 #if defined(KVM_ARCH_WANT_MMU_NOTIFIER) || defined(CONFIG_HAVE_KVM_RESTRICTED_MEM)
+#define KVM_GFN_RANGE_FLAGS_RESTRICTED_MEM	BIT(0)

include/linux/kvm_host.h int kvm_async_pf_wakeup_all(struct kvm_vcpu *vcpu); · line 259

Quoted 10 lines
include/linux/kvm_host.h +5 -1
+#define KVM_GFN_RANGE_FLAGS_SET_MEM_ATTR	BIT(1)
 struct kvm_gfn_range {
 	struct kvm_memory_slot *slot;
 	gfn_t start;
 	gfn_t end;
-	pte_t pte;
+	union {
+		pte_t pte;
+		int attr;
+	};

attribute is u64 in Chao's series.

Quoted 3 lines
include/linux/kvm_host.h +1 -0
 	bool may_block;
+	unsigned int flags;
 };
#116 lore raw

Re: [PATCH v10 047/108] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to [email protected]
Quoted 42 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense for private memory. Also currently, page migration isn't supported for TDX yet. (TDX architecturally supports page migration. it's KVM and kernel implementation issue.)

Regarding memory type change (mtrr virtualization and lapic page mapping change), pages are zapped by kvm_zap_gfn_range(). On the next KVM page fault, the SPTE entry with a new memory type for the page is populated. Regarding page migration, pages are zapped by the mmu notifier. On the next KVM page fault, the new migrated page is populated. Don't zap private pages on unmapping for those two cases.

When deleting/moving a KVM memory slot, zap private pages. Typically tearing down VM. Don't invalidate private page tables. i.e. zap only leaf SPTEs for KVM mmu that has a shared bit mask. The existing kvm_tdp_mmu_invalidate_all_roots() depends on role.invalid with read-lock of mmu_lock so that other vcpu can operate on KVM mmu concurrently. It marks the root page table invalid and zaps SPTEs of the root page tables. The TDX module doesn't allow to unlink a protected root page table from the hardware and then allocate a new one for it. i.e. replacing a protected root page table. Instead, zap only leaf SPTEs for KVM mmu with a shared bit mask set.

---
 arch/x86/kvm/mmu/mmu.c     | 85 ++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c | 24 ++++++++---
 arch/x86/kvm/mmu/tdp_mmu.h |  5 ++-
 3 files changed, 103 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index faf69774c7ce..0237e143299c 100644
@@ -1577,8 +1577,38 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 	if (kvm_memslots_have_rmaps(kvm))
 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
 

arch/x86/kvm/mmu/mmu.c bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) · line 1587

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +8 -2
-	if (is_tdp_mmu_enabled(kvm))
-		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
+	if (is_tdp_mmu_enabled(kvm)) {
+		bool zap_private;
+
+		if (kvm_slot_can_be_private(range->slot)) {
+			if (range->flags & KVM_GFN_RANGE_FLAGS_RESTRICTED_MEM)
+				/*
+				 * For private slot, the callback is triggered
+				 * via falloc.  Mode can be allocation or punch
				       ^
				       fallocate(), please?

arch/x86/kvm/mmu/mmu.c bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) · line 1593

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+				 * hole.  Because the private-shared conversion
+				 * is done via
+				 * KVM_MEMORY_ENCRYPT_REG/UNREG_REGION, we can
+				 * ignore the request from restrictedmem.
+				 */
+				return flush;

Sorry why "private-shared conversion is done via KVM_MEMORY_ENCRYPT_REG" results in "we can ignore the requres from restrictedmem"?

If we punch a hole, the pages are de-allocated, correct?

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+			else if (range->flags & KVM_GFN_RANGE_FLAGS_SET_MEM_ATTR) {
+				if (range->attr == KVM_MEM_ATTR_SHARED)
+					zap_private = true;
+				else {
+					WARN_ON_ONCE(range->attr != KVM_MEM_ATTR_PRIVATE);

arch/x86/kvm/mmu/mmu.c bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) · line 1608

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+					zap_private = false;
+				}
+			} else
+				/*
+				 * kvm_unmap_gfn_range() is called via mmu
+				 * notifier.  For now page migration for private
+				 * page isn't supported yet, don't zap private
+				 * pages.
+				 */
+				zap_private = false;

Page migration is not the only reason that KVM will receive the MMU notifer -- just say something like "for now all private pages are pinned during VM's life time".

Quoted 44 lines
arch/x86/kvm/mmu/mmu.c +37 -0
+		}
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush, zap_private);
+	}
 
 	return flush;
 }
@@ -6066,11 +6096,48 @@ static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
 }
 
+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
+{
+	bool flush = false;
+
+	write_lock(&kvm->mmu_lock);
+
+	/*
+	 * Zapping non-leaf SPTEs, a.k.a. not-last SPTEs, isn't required, worst
+	 * case scenario we'll have unused shadow pages lying around until they
+	 * are recycled due to age or when the VM is destroyed.
+	 */
+	if (is_tdp_mmu_enabled(kvm)) {
+		struct kvm_gfn_range range = {
+		      .slot = slot,
+		      .start = slot->base_gfn,
+		      .end = slot->base_gfn + slot->npages,
+		      .may_block = false,
+		};
+
+		/*
+		 * this handles both private gfn and shared gfn.
+		 * All private page should be zapped on memslot deletion.
+		 */
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush, true);
+	} else {
+		flush = slot_handle_level(kvm, slot, __kvm_zap_rmap, PG_LEVEL_4K,
+					  KVM_MAX_HUGEPAGE_LEVEL, true);
+	}
+	if (flush)
+		kvm_flush_remote_tlbs(kvm);
+
+	write_unlock(&kvm->mmu_lock);
+}
+

arch/x86/kvm/mmu/mmu.c static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm) · line 6141

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +4 -1
 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
 			struct kvm_memory_slot *slot,
 			struct kvm_page_track_notifier_node *node)
 {
-	kvm_mmu_zap_all_fast(kvm);
+	if (kvm_gfn_shared_mask(kvm))
+		kvm_mmu_zap_memslot(kvm, slot);
+	else
+		kvm_mmu_zap_all_fast(kvm);
 }

A comment would be nice here.

arch/x86/kvm/mmu/mmu.c void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end) · line 6246

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +4 -0
 int kvm_mmu_init_vm(struct kvm *kvm)
@@ -6173,8 +6240,18 @@ 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++)
+			/*
+			 * zap_private = true. Zap both private/shared pages.
+			 *
+			 * kvm_zap_gfn_range() is used when PAT memory type was

Is it PAT or MTRR, or both (thus just memory type)?

arch/x86/kvm/mmu/mmu.c void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end) · line 6251

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+			 * changed.  Later on the next kvm page fault, populate
+			 * it with updated spte entry.
+			 * Because only WB is supported for private pages, don't
+			 * care of private pages.
+			 */

Then why bother zapping private? If I read correctly, the changelog says "don't zap private"?

arch/x86/kvm/mmu/mmu.c void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end) · line 6256

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +2 -1
 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
-						      gfn_end, true, flush);
+						      gfn_end, true, flush,
+						      true);
 	}
 

Btw, as you mentioned in the changelog, private memory always has WB memory type, thus cannot be virtualized. Is it better to modify update_mtrr() to just return early if the gfn range is purely private?

IMHO the handling of MTRR/PAT virtualization for TDX guest deserves dedicated patch(es) to put them together so it's easier to review. Now the relevant parts spread in multiple independent patches (MSR handling, vt_get_mt_mask(), etc).

#201 lore raw

Re: [PATCH v10 098/108] KVM: TDX: Implement callbacks for MSR operations for TDX

In reply to [email protected]
Quoted 5 lines · On Sat, 2022-10-29 at 23:23 -0700, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +5 -0
+bool tdx_is_emulated_msr(u32 index, bool write)
+{
+	switch (index) {
+	case MSR_IA32_UCODE_REV:
+	case MSR_IA32_ARCH_CAPABILITIES:

arch/x86/kvm/vmx/tdx.c void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason, · line 1506

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	case MSR_IA32_POWER_CTL:
+	case MSR_MTRRcap:
+	case 0x200 ... 0x26f:
+		/* IA32_MTRR_PHYS{BASE, MASK}, IA32_MTRR_FIX*_* */
+	case MSR_IA32_CR_PAT:
+	case MSR_MTRRdefType:
+	case MSR_IA32_TSC_DEADLINE:
+	case MSR_IA32_MISC_ENABLE:
+	case MSR_KVM_STEAL_TIME:
+	case MSR_KVM_POLL_CONTROL:

To me putting KVM para-virt MSRs and hardware MSRs together isn't good idea. You can introduce separate helpers for them.

Quoted 33 lines
arch/x86/kvm/vmx/tdx.c +33 -0
+	case MSR_PLATFORM_INFO:
+	case MSR_MISC_FEATURES_ENABLES:
+	case MSR_IA32_MCG_CAP:
+	case MSR_IA32_MCG_STATUS:
+	case MSR_IA32_MCG_CTL:
+	case MSR_IA32_MCG_EXT_CTL:
+	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
+	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
+		/* MSR_IA32_MCx_{CTL, STATUS, ADDR, MISC, CTL2} */
+		return true;
+	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
+		/*
+		 * x2APIC registers that are virtualized by the CPU can't be
+		 * emulated, KVM doesn't have access to the virtual APIC page.
+		 */
+		switch (index) {
+		case X2APIC_MSR(APIC_TASKPRI):
+		case X2APIC_MSR(APIC_PROCPRI):
+		case X2APIC_MSR(APIC_EOI):
+		case X2APIC_MSR(APIC_ISR) ... X2APIC_MSR(APIC_ISR + APIC_ISR_NR):
+		case X2APIC_MSR(APIC_TMR) ... X2APIC_MSR(APIC_TMR + APIC_ISR_NR):
+		case X2APIC_MSR(APIC_IRR) ... X2APIC_MSR(APIC_IRR + APIC_ISR_NR):
+			return false;
+		default:
+			return true;
+		}
+	case MSR_IA32_APICBASE:
+	case MSR_EFER:
+		return !write;
+	default:
+		return false;
+	}
+}
#217 lore raw

Re: [PATCH v10 105/108] KVM: TDX: Add methods to ignore accesses to CPU state

In reply to [email protected]

arch/x86/kvm/vmx/main.c static void vt_request_immediate_exit(struct kvm_vcpu *vcpu) · line 791

Quoted 10 lines · On Sat, 2022-10-29 at 23:23 -0700, [email protected] wrote:
arch/x86/kvm/vmx/main.c +10 -0
+static u8 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);
+}

So you are returning WB for _ALL_ guest memory, including shared. Wouldn't this break MTRR handling for shared memory? For instance, IIUC we can still support assigning a device to a TDX guest while the VT-d doesn't support coherent memory, in which case guest's MTRR/PAT are honored. I think this should also apply to TDX guest's shared memory?

#23 lore raw

Re: [PATCH v10 011/108] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to Zhi Wang
Quoted 16 lines · Zhi Wang
Quoted 9 lines · On Sat, 29 Oct 2022 23:22:12 -0700 [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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 3 lines

Export __seamcall and define C wrapper functions for SEAMCALLs for readability. Some SEAMCALL APIs donates pages to TDX module or guest TD. The pages are encrypted with TDX private host key id set in high

Quoted 6 lines

It seems a little bit confusing here.

I guess you are talking about the host pages donated to TDX module will be encrypted with TDX module global key id, which is used to encrypted the pages only used by TDX module. For pages donated to the TD guest, the pages are encrypted with TD guest prviate key id?

Basically yes. Only TDR is encrypted with the global key id.

Quoted 4 lines

It might be better that you can talk about the actual reaason instead of the key id stuff. For example Some SEMCALL APIs will zap or write the pages donated by VMM via MOVDIR64B, which requires the VMM to flush the cachelines.

How about the followings?

Some SEAMCALL APIs donates host pages to TDX module or guest TD and the donated pages are encrypted. Some of such SEAMCALLs flush cache lines (typically by movdir64b instruction), some don't. Those that doesn't clear cache lines require the VMM to flush the cache lines to avoid cache line alias.

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

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to Zhi Wang
Quoted 195 lines · Zhi Wang
Quoted 184 lines · On Sat, 29 Oct 2022 23:22:17 -0700 [email protected] wrote:

From: Sean Christopherson <[email protected]>

As the first step to create TDX guest, create/destroy VM struct. Assign TDX private 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.

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 flush_shadow_all_private callback before tearing down private page tables for it.

Add a second kvm_x86_ops hook in kvm_arch_destroy_vm() 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/include/asm/kvm-x86-ops.h |   2 +
 arch/x86/include/asm/kvm_host.h    |   2 +
 arch/x86/kvm/vmx/main.c            |  34 ++-
 arch/x86/kvm/vmx/tdx.c             | 411
+++++++++++++++++++++++++++++ arch/x86/kvm/vmx/tdx.h             |
2 + arch/x86/kvm/vmx/x86_ops.h         |  11 +
 arch/x86/kvm/x86.c                 |   8 +
 7 files changed, 467 insertions(+), 3 deletions(-)
(quoted diff) +0 -0

b/arch/x86/include/asm/kvm-x86-ops.h index 8a5c5ae70bc5..3a29a6b31ee8 100644 --- a/arch/x86/include/asm/kvm-x86-ops.h
+++ b/arch/x86/include/asm/kvm-x86-ops.h

arch/x86/include/asm/kvm-x86-ops.h +2 -0
@@ -21,7 +21,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_OPTIONAL(flush_shadow_all_private)
 KVM_X86_OP_OPTIONAL(vm_destroy)
+KVM_X86_OP_OPTIONAL(vm_free)
 KVM_X86_OP_OPTIONAL_RET0(vcpu_precreate)
 KVM_X86_OP(vcpu_create)
 KVM_X86_OP(vcpu_free)
(quoted diff) +0 -0

b/arch/x86/include/asm/kvm_host.h index 2a41a93a80f3..2870155ce6fb 100644 --- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h

arch/x86/include/asm/kvm_host.h +2 -0
@@ -1472,7 +1472,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 (*flush_shadow_all_private)(struct kvm *kvm);
 	void (*vm_destroy)(struct kvm *kvm);
+	void (*vm_free)(struct kvm *kvm);
 
 	/* Create, but do not attach this VCPU */
 	int (*vcpu_precreate)(struct kvm *kvm);
arch/x86/kvm/vmx/main.c +6 -1
index 0900ff2f2390..d01a946a18cf 100644
@@ -29,18 +29,44 @@ 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)
 {
 	if (is_td(kvm))
-		return -EOPNOTSUPP;	/* Not ready to create

guest TD yet. */

arch/x86/kvm/vmx/main.c +22 -1
+		return tdx_vm_init(kvm);
 
 	return vmx_vm_init(kvm);
 }
 
+static void vt_flush_shadow_all_private(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_mmu_release_hkid(kvm);
+}
+
+static void vt_vm_destroy(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return;
+
+	vmx_vm_destroy(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",
 
-	.hardware_unsetup = vmx_hardware_unsetup,
+	.hardware_unsetup = vt_hardware_unsetup,
 	.check_processor_compatibility =

vmx_check_processor_compatibility,

arch/x86/kvm/vmx/main.c +3 -1
 	.hardware_enable = vmx_hardware_enable,
@@ -50,7 +76,9 @@ 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,
-	.vm_destroy = vmx_vm_destroy,
+	.flush_shadow_all_private = vt_flush_shadow_all_private,
+	.vm_destroy = vt_vm_destroy,
+	.vm_free = vt_vm_free,
 
 	.vcpu_precreate = vmx_vcpu_precreate,
 	.vcpu_create = vmx_vcpu_create,
arch/x86/kvm/vmx/tdx.c +3 -0
index 530e72f85762..ec88dde0d300 100644
@@ -32,6 +32,401 @@ struct tdx_capabilities {
 /* Capabilities of KVM + the TDX module. */
 static struct tdx_capabilities tdx_caps;
 
+/*
+ * Some TDX SEAMCALLs (TDH.MNG.CREATE, TDH.PHYMEM.CACHE.WB,
+ * TDH.MNG.KEY.RECLAIMID, TDH.MNG.KEY.FREEID etc) tries to acquire a

global lock
+ * internally in TDX module. If failed, TDX_OPERAND_BUSY is returned without
+ * spinning or waiting due to a constraint on execution time. It's caller's
+ * responsibility to avoid race (or retry on TDX_OPERAND_BUSY). Use this mutex
+ * to avoid race in TDX module because the kernel knows better about scheduling.
+ */

arch/x86/kvm/vmx/tdx.c +27 -0
+static DEFINE_MUTEX(tdx_lock);
+static struct mutex *tdx_mng_key_config_lock;
+
+static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
+{
+	return pa | ((hpa_t)hkid << boot_cpu_data.x86_phys_bits);
+}
+
+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)));

arch/x86/kvm/vmx/tdx.c +4 -0
+	unsigned long i;
+
+	/*
+	 * Zeroing the page is only necessary for systems with

MKTME-i:

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * when re-assign one page from old keyid to a new keyid,

MOVDIR64B is

arch/x86/kvm/vmx/tdx.c +1 -0
+	 * required to clear/write the page with new keyid to

prevent integrity

arch/x86/kvm/vmx/tdx.c +3 -0
+	 * error when read on the page with new keyid.
+	 *
+	 * The cache line could be poisoned (even without MKTME-i),

clear the

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	 * poison bit.
+	 */
+	for (i = 0; i < PAGE_SIZE; i += 64)
+		movdir64b((void *)(page + i), zero_page);

In patch 11, the clflush is used on the movdir64b target. Should we also use the clflush here?

Quoted 2 lines

I suppose the clflush is to prevent the unexpected cacheline writeback after the movdir64b.

No, clflush doesn't work. The cache with HKID set needs to be flushed and (potential) poison needs to be cleared. In host OS/VMM, clflush flushes on cache with HKID=0 (or HKID of MKTME). clflush doesn't clear poison.

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

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to Ackerley Tng
Quoted 6 lines · Ackerley Tng

In tdx_vm_init, it is possible to have a double-reclaim, which eventually causes a host crash. I have a selftest that reliably reproduces this, and I believe the problem is that withiin tdx_vm_free(), we don't reset kvm->tdcs = NULL and kvm->tdr.added to false.

Thanks for the fix. Did you use error injection to trigger the error path?

Thanks,

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

Re: [PATCH v10 024/108] KVM: TDX: allocate/free TDX vcpu structure

In reply to Yuan Yao
Quoted 197 lines · Yuan Yao
Quoted 196 lines · On Sat, Oct 29, 2022 at 11:22:25PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The next step of TDX guest creation is to create vcpu. Allocate TDX vcpu structures, initialize it. Allocate pages of TDX vcpu for the TDX module.

In the case of the conventional case, cpuid is empty at the initialization. and cpuid is configured after the vcpu initialization. Because TDX supports only X2APIC mode, cpuid is forcibly initialized to support X2APIC on the vcpu initialization.

---
 arch/x86/kvm/vmx/main.c    |  40 +++++++++--
 arch/x86/kvm/vmx/tdx.c     | 138 +++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h |   8 +++
 3 files changed, 182 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +36 -4
index b4e4c6c677f6..c125b2e3e8b4 100644
@@ -63,6 +63,38 @@ static void vt_vm_free(struct kvm *kvm)
 		return tdx_vm_free(kvm);
 }
 
+static int vt_vcpu_precreate(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return 0;
+
+	return vmx_vcpu_precreate(kvm);
+}
+
+static int vt_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_create(vcpu);
+
+	return vmx_vcpu_create(vcpu);
+}
+
+static void vt_vcpu_free(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_free(vcpu);
+
+	return vmx_vcpu_free(vcpu);
+}
+
+static void vt_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_reset(vcpu, init_event);
+
+	return vmx_vcpu_reset(vcpu, init_event);
+}
+
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	if (!is_td(kvm))
@@ -89,10 +121,10 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.vm_destroy = vt_vm_destroy,
 	.vm_free = vt_vm_free,
 
-	.vcpu_precreate = vmx_vcpu_precreate,
-	.vcpu_create = vmx_vcpu_create,
-	.vcpu_free = vmx_vcpu_free,
-	.vcpu_reset = vmx_vcpu_reset,
+	.vcpu_precreate = vt_vcpu_precreate,
+	.vcpu_create = vt_vcpu_create,
+	.vcpu_free = vt_vcpu_free,
+	.vcpu_reset = vt_vcpu_reset,
 
 	.prepare_switch_to_guest = vmx_prepare_switch_to_guest,
 	.vcpu_load = vmx_vcpu_load,
arch/x86/kvm/vmx/tdx.c +106 -0
index 54045e0576e7..0625c354b341 100644
@@ -49,6 +49,11 @@ static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
 	return pa | ((hpa_t)hkid << boot_cpu_data.x86_phys_bits);
 }
 
+static inline bool is_td_vcpu_created(struct vcpu_tdx *tdx)
+{
+	return tdx->tdvpr.added;
+}
+
 static inline bool is_td_created(struct kvm_tdx *kvm_tdx)
 {
 	return kvm_tdx->tdr.added;
@@ -296,6 +301,139 @@ int tdx_vm_init(struct kvm *kvm)
 	return 0;
 }
 
+int tdx_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	int ret, i;
+
+	/* TDX only supports x2APIC, which requires an in-kernel local APIC. */
+	if (!vcpu->arch.apic)
+		return -EINVAL;
+
+	fpstate_set_confidential(&vcpu->arch.guest_fpu);
+
+	ret = tdx_alloc_td_page(&tdx->tdvpr);
+	if (ret)
+		return ret;
+
+	tdx->tdvpx = kcalloc(tdx_caps.tdvpx_nr_pages, sizeof(*tdx->tdvpx),
+			GFP_KERNEL_ACCOUNT);
+	if (!tdx->tdvpx) {
+		ret = -ENOMEM;
+		goto free_tdvpr;
+	}
+	for (i = 0; i < tdx_caps.tdvpx_nr_pages; i++) {
+		ret = tdx_alloc_td_page(&tdx->tdvpx[i]);
+		if (ret)
+			goto free_tdvpx;
+	}
+
+	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
+
+	vcpu->arch.cr0_guest_owned_bits = -1ul;
+	vcpu->arch.cr4_guest_owned_bits = -1ul;
+
+	vcpu->arch.tsc_offset = to_kvm_tdx(vcpu->kvm)->tsc_offset;
+	vcpu->arch.l1_tsc_offset = vcpu->arch.tsc_offset;
+	vcpu->arch.guest_state_protected =
+		!(to_kvm_tdx(vcpu->kvm)->attributes & TDX_TD_ATTRIBUTE_DEBUG);
+
+	return 0;
+
+free_tdvpx:
+	/* @i points at the TDVPX page that failed allocation. */
+	for (--i; i >= 0; i--)
+		free_page(tdx->tdvpx[i].va);
+	kfree(tdx->tdvpx);
+	tdx->tdvpx = NULL;
+free_tdvpr:
+	free_page(tdx->tdvpr.va);
+
+	return ret;
+}
+
+void tdx_vcpu_free(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	int i;
+
+	/* Can't reclaim or free pages if teardown failed. */
+	if (is_hkid_assigned(to_kvm_tdx(vcpu->kvm)))
+		return;
+
+	if (tdx->tdvpx) {
+		for (i = 0; i < tdx_caps.tdvpx_nr_pages; i++)
+			tdx_reclaim_td_page(&tdx->tdvpx[i]);
+		kfree(tdx->tdvpx);
+		tdx->tdvpx = NULL;
+	}
+	tdx_reclaim_td_page(&tdx->tdvpr);
+}
+
+void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	struct msr_data apic_base_msr;
+	u64 err;
+	int i;
+
+	/* TDX doesn't support INIT event. */
+	if (WARN_ON_ONCE(init_event))
+		goto td_bugged;
+	if (WARN_ON_ONCE(is_td_vcpu_created(tdx)))
+		goto td_bugged;
+
+	err = tdh_vp_create(kvm_tdx->tdr.pa, tdx->tdvpr.pa);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_VP_CREATE, err, NULL);
+		goto td_bugged;
+	}
+	tdx_mark_td_page_added(&tdx->tdvpr);
+
+	for (i = 0; i < tdx_caps.tdvpx_nr_pages; i++) {
+		err = tdh_vp_addcx(tdx->tdvpr.pa, tdx->tdvpx[i].pa);
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_VP_ADDCX, err, NULL);
+			goto td_bugged;
+		}
+		tdx_mark_td_page_added(&tdx->tdvpx[i]);
+	}
+
+	if (!vcpu->arch.cpuid_entries) {
+		/*
Quoted 8 lines

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+		 * On cpu creation, cpuid entry is blank.  Forcibly enable
+		 * X2APIC feature to allow X2APIC.
+		 */
+		struct kvm_cpuid_entry2 *e;
+
+		e = kvmalloc_array(1, sizeof(*e), GFP_KERNEL_ACCOUNT);

NULL checking is necessary for kvmalloc_array.

Fixed. Because vcpu_reset() function doesn't return error, this logic is moved to tdx_vcpu_create().

Thanks,

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

Re: [PATCH v10 046/108] KVM: Add flags to struct kvm_gfn_range

In reply to Huang, Kai
Quoted 10 lines · Kai
Quoted 8 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

kvm_unmap_gfn_range() needs to know the reason of the callback for TDX. mmu notifier, set memattr ioctl or restrictedmem notifier. Based on the reason, TDX changes the behavior. For mmu notifier, it's the operation on shared memory slot to zap shared PTE. For set memattr, private<->shared conversion, zap the original PTE. For restrictedmem, it's a hint that TDX can ignore.

Quoted 3 lines

Could you elaborate why restricted memfd notifier can be ignored? IIUC if userspace punch a hole, the pages within the hole will be de-allocated. So why can such notifier be ignored?

Because set-memory-attribute ioctl is expected to follow the callback from restrictedmem. So set memory attributes can do de-allocation. I wanted to avoid zapping twice.

With v9 UPM, the restrictedmem callback was triggered for both allocation and punch-hole.
With v10 UPM, the callback is triggered only for punch-hole. With v10 callback semantics, probably this can be cleaned up slightly.

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

Re: [PATCH v10 046/108] KVM: Add flags to struct kvm_gfn_range

Quoted 13 lines · Isaku Yamahata
Quoted 10 lines · Kai
Quoted 8 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

kvm_unmap_gfn_range() needs to know the reason of the callback for TDX. mmu notifier, set memattr ioctl or restrictedmem notifier. Based on the reason, TDX changes the behavior. For mmu notifier, it's the operation on shared memory slot to zap shared PTE. For set memattr, private<->shared conversion, zap the original PTE. For restrictedmem, it's a hint that TDX can ignore.

Quoted 7 lines
Quoted 3 lines

Could you elaborate why restricted memfd notifier can be ignored? IIUC if userspace punch a hole, the pages within the hole will be de-allocated. So why can such notifier be ignored?

Because set-memory-attribute ioctl is expected to follow the callback from restrictedmem. So set memory attributes can do de-allocation. I wanted to avoid zapping twice.

Even this is true, the punch hole can be done alone w/o being followed by set_memory_attribute(), correct? Your explanation doesn't seem to be reasonable?

At least, you need to explain the semantics of how to use "punch hole" and set_memory_attributes() clearly in the changelog. Otherwise it's hard for people to review.

#117 lore raw

Re: [PATCH v10 047/108] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Huang, Kai
Quoted 66 lines · Kai
Quoted 42 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense for private memory. Also currently, page migration isn't supported for TDX yet. (TDX architecturally supports page migration. it's KVM and kernel implementation issue.)

Regarding memory type change (mtrr virtualization and lapic page mapping change), pages are zapped by kvm_zap_gfn_range(). On the next KVM page fault, the SPTE entry with a new memory type for the page is populated. Regarding page migration, pages are zapped by the mmu notifier. On the next KVM page fault, the new migrated page is populated. Don't zap private pages on unmapping for those two cases.

When deleting/moving a KVM memory slot, zap private pages. Typically tearing down VM. Don't invalidate private page tables. i.e. zap only leaf SPTEs for KVM mmu that has a shared bit mask. The existing kvm_tdp_mmu_invalidate_all_roots() depends on role.invalid with read-lock of mmu_lock so that other vcpu can operate on KVM mmu concurrently. It marks the root page table invalid and zaps SPTEs of the root page tables. The TDX module doesn't allow to unlink a protected root page table from the hardware and then allocate a new one for it. i.e. replacing a protected root page table. Instead, zap only leaf SPTEs for KVM mmu with a shared bit mask set.

---
 arch/x86/kvm/mmu/mmu.c     | 85 ++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c | 24 ++++++++---
 arch/x86/kvm/mmu/tdp_mmu.h |  5 ++-
 3 files changed, 103 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index faf69774c7ce..0237e143299c 100644
@@ -1577,8 +1577,38 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 	if (kvm_memslots_have_rmaps(kvm))
 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
 

arch/x86/kvm/mmu/mmu.c bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) · line 1587

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +8 -2
-	if (is_tdp_mmu_enabled(kvm))
-		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
+	if (is_tdp_mmu_enabled(kvm)) {
+		bool zap_private;
+
+		if (kvm_slot_can_be_private(range->slot)) {
+			if (range->flags & KVM_GFN_RANGE_FLAGS_RESTRICTED_MEM)
+				/*
+				 * For private slot, the callback is triggered
+				 * via falloc.  Mode can be allocation or punch
				       ^
				       fallocate(), please?

arch/x86/kvm/mmu/mmu.c bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) · line 1593

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+				 * hole.  Because the private-shared conversion
+				 * is done via
+				 * KVM_MEMORY_ENCRYPT_REG/UNREG_REGION, we can
+				 * ignore the request from restrictedmem.
+				 */
+				return flush;

Sorry why "private-shared conversion is done via KVM_MEMORY_ENCRYPT_REG" results in "we can ignore the requres from restrictedmem"?

Quoted 1 line

If we punch a hole, the pages are de-allocated, correct?

With v10 UPM, we can have zap_private = true always.

With v9 UPM, the callback is triggered both for allocation and punch-hole without any further argument. With v10 UPM, the callback is triggered only for punching hole.

Quoted 12 lines
Quoted 12 lines
arch/x86/kvm/mmu/mmu.c +11 -0
+			else if (range->flags & KVM_GFN_RANGE_FLAGS_SET_MEM_ATTR) {
+				if (range->attr == KVM_MEM_ATTR_SHARED)
+					zap_private = true;
+				else {
+					WARN_ON_ONCE(range->attr != KVM_MEM_ATTR_PRIVATE);
+					zap_private = false;
+				}
+			} else
+				/*
+				 * kvm_unmap_gfn_range() is called via mmu
+				 * notifier.  For now page migration for private
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) · line 1608

Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +4 -0
+				 * page isn't supported yet, don't zap private
+				 * pages.
+				 */
+				zap_private = false;

Page migration is not the only reason that KVM will receive the MMU notifer -- just say something like "for now all private pages are pinned during VM's life time".

Will update the comment.

Quoted 50 lines
Quoted 50 lines
arch/x86/kvm/mmu/mmu.c +37 -0
+		}
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush, zap_private);
+	}
 
 	return flush;
 }
@@ -6066,11 +6096,48 @@ static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
 }
 
+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
+{
+	bool flush = false;
+
+	write_lock(&kvm->mmu_lock);
+
+	/*
+	 * Zapping non-leaf SPTEs, a.k.a. not-last SPTEs, isn't required, worst
+	 * case scenario we'll have unused shadow pages lying around until they
+	 * are recycled due to age or when the VM is destroyed.
+	 */
+	if (is_tdp_mmu_enabled(kvm)) {
+		struct kvm_gfn_range range = {
+		      .slot = slot,
+		      .start = slot->base_gfn,
+		      .end = slot->base_gfn + slot->npages,
+		      .may_block = false,
+		};
+
+		/*
+		 * this handles both private gfn and shared gfn.
+		 * All private page should be zapped on memslot deletion.
+		 */
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush, true);
+	} else {
+		flush = slot_handle_level(kvm, slot, __kvm_zap_rmap, PG_LEVEL_4K,
+					  KVM_MAX_HUGEPAGE_LEVEL, true);
+	}
+	if (flush)
+		kvm_flush_remote_tlbs(kvm);
+
+	write_unlock(&kvm->mmu_lock);
+}
+
 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
 			struct kvm_memory_slot *slot,
 			struct kvm_page_track_notifier_node *node)
 {
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm) · line 6141

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +4 -1
-	kvm_mmu_zap_all_fast(kvm);
+	if (kvm_gfn_shared_mask(kvm))
+		kvm_mmu_zap_memslot(kvm, slot);
+	else
+		kvm_mmu_zap_all_fast(kvm);
 }

A comment would be nice here.

Will add a comment.

Quoted 4 lines
Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +0 -0
 int kvm_mmu_init_vm(struct kvm *kvm)
@@ -6173,8 +6240,18 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
 
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end) · line 6246

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +4 -0
 	if (is_tdp_mmu_enabled(kvm)) {
 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
+			/*
+			 * zap_private = true. Zap both private/shared pages.
+			 *
+			 * kvm_zap_gfn_range() is used when PAT memory type was

Is it PAT or MTRR, or both (thus just memory type)?

Both. Will update the comment.

Quoted 9 lines

arch/x86/kvm/mmu/mmu.c void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end) · line 6251

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+			 * changed.  Later on the next kvm page fault, populate
+			 * it with updated spte entry.
+			 * Because only WB is supported for private pages, don't
+			 * care of private pages.
+			 */

Then why bother zapping private? If I read correctly, the changelog says "don't zap private"?

Right. Will fix.

Quoted 10 lines

arch/x86/kvm/mmu/mmu.c void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end) · line 6256

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +2 -1
 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
-						      gfn_end, true, flush);
+						      gfn_end, true, flush,
+						      true);
 	}
 

Btw, as you mentioned in the changelog, private memory always has WB memory type, thus cannot be virtualized. Is it better to modify update_mtrr() to just return early if the gfn range is purely private?

MTRR support in cpuid is fixed to 1, PAT in cpuid is native. MTRR and PAT are supported on shared pages.

Quoted 3 lines

IMHO the handling of MTRR/PAT virtualization for TDX guest deserves dedicated patch(es) to put them together so it's easier to review. Now the relevant parts spread in multiple independent patches (MSR handling, vt_get_mt_mask(), etc).

Ok, let me check it.

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

Re: [PATCH v10 047/108] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 8 lines · Isaku Yamahata
Quoted 4 lines

Btw, as you mentioned in the changelog, private memory always has WB memory type, thus cannot be virtualized.  Is it better to modify update_mtrr() to just
return early if the gfn range is purely private?

MTRR support in cpuid is fixed to 1, PAT in cpuid is native. MTRR and PAT are supported on shared pages.

But none of those are mentioned in the changelog or whatever. They are hidden in the spec or in the later patches far away.

ALso, the handling of "load/save IA32_PAT" in VMEXIT/VMENTRY VMCS control is different between TDX module and KVM. None of those are mentioned.

All those make the patch review so hard.

Quoted 9 lines
Quoted 7 lines

IMHO the handling of MTRR/PAT virtualization for TDX guest deserves dedicated
patch(es) to put them together so it's easier to review.  Now the relevant parts
spread in multiple independent patches (MSR handling, vt_get_mt_mask(), etc).

Ok, let me check it.

Yes. IMHO you should put all relevant parts together and make a clear changelog to justify the patch(es).

#132 lore raw

Re: [PATCH v10 052/108] KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs

In reply to Wang, Wei W
Quoted 150 lines · Wei W
Quoted 127 lines · Isaku

From: Isaku Yamahata <[email protected]>

Some KVM MMU operations (dirty page logging, page migration, aging page) aren't supported for private GFNs (yet) with the first generation of TDX. Silently return on unsupported TDX KVM MMU operations.

---
 arch/x86/kvm/mmu/mmu.c     |  3 ++
 arch/x86/kvm/mmu/tdp_mmu.c | 73
+++++++++++++++++++++++++++++++++++---
 arch/x86/kvm/x86.c         |  3 ++
 3 files changed, 74 insertions(+), 5 deletions(-)
arch/x86/kvm/mmu/mmu.c index renamed from arch/x86/kvm/mmu/mmu.c +0 -0

02e7b5cf3231..efc3b3f2dd12 100644

arch/x86/kvm/mmu/mmu.c +3 -0
@@ -6588,6 +6588,9 @@ static bool kvm_mmu_zap_collapsible_spte(struct
 kvm *kvm,
 	for_each_rmap_spte(rmap_head, &iter, sptep) {
 		sp = sptep_to_sp(sptep);
 
+		/* Private page dirty logging is not supported yet. */
+		KVM_BUG_ON(is_private_sptep(sptep), kvm);
+
 		/*
 		 * We cannot do huge page mapping for indirect shadow pages,

* which are found on the last rmap (level = 1) when not using diff --git
a/arch/x86/kvm/mmu/tdp_mmu.c b/arch/x86/kvm/mmu/tdp_mmu.c index 0e053b96444a..4b207ce83ffe 100644

arch/x86/kvm/mmu/tdp_mmu.c +2 -1
@@ -1469,7 +1469,8 @@ typedef bool (*tdp_handler_t)(struct kvm *kvm,
 struct tdp_iter *iter,
 
 static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm,
 						   struct kvm_gfn_range *range,
-						   tdp_handler_t handler)
+						   tdp_handler_t handler,
+						   bool only_shared)
 {
 	struct kvm_mmu_page *root;
arch/x86/kvm/mmu/tdp_mmu.c +15 -1
 	struct tdp_iter iter;
@@ -1480,9 +1481,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) {
+		gfn_t start;
+		gfn_t end;
+
+		if (only_shared && is_private_sp(root))
+			continue;
+
 		rcu_read_lock();
 
-		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.
+		 */
+		start = kvm_gfn_for_root(kvm, root, range->start);
+		end = kvm_gfn_for_root(kvm, root, range->end);
+
+		tdp_root_for_each_leaf_pte(iter, root, start, end)
 			ret |= handler(kvm, &iter, range);
 
arch/x86/kvm/mmu/tdp_mmu.c +6 -1
 		rcu_read_unlock();
@@ -1526,7 +1541,12 @@ static bool age_gfn_range(struct kvm *kvm, struct
 tdp_iter *iter,
 
 bool kvm_tdp_mmu_age_gfn_range(struct kvm *kvm, struct kvm_gfn_range
 *range)  {
-	return kvm_tdp_mmu_handle_gfn(kvm, range, age_gfn_range);
+	/*
+	 * 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.
+	 */
+	return kvm_tdp_mmu_handle_gfn(kvm, range, age_gfn_range, true);
 }
 

static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter, @@ -1537,7
+1557,8 @@ static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter,

bool kvm_tdp_mmu_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range
*range) {

arch/x86/kvm/mmu/tdp_mmu.c +3 -1
-	return kvm_tdp_mmu_handle_gfn(kvm, range, test_age_gfn);
+	/* The first TDX generation doesn't support A bit. */
+	return kvm_tdp_mmu_handle_gfn(kvm, range, test_age_gfn, true);
 }
 
 static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter, @@ -1582,8
+1603,11 @@ bool kvm_tdp_mmu_set_spte_gfn(struct kvm *kvm, struct

kvm_gfn_range *range)

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
 	 * No need to handle the remote TLB flush under RCU protection, the
 	 * target SPTE _must_ be a leaf SPTE, i.e. cannot result in freeing a
 	 * shadow page.  See the WARN on pfn_changed in

__handle_changed_spte().

arch/x86/kvm/mmu/tdp_mmu.c +13 -1
+	 *
+	 * .change_pte() callback should not happen for private page, because
+	 * for now TDX private pages are pinned during VM's life time.
 	 */
-	return kvm_tdp_mmu_handle_gfn(kvm, range, set_spte_gfn);
+	return kvm_tdp_mmu_handle_gfn(kvm, range, set_spte_gfn, true);
 }
 
 /*
@@ -1637,6 +1661,14 @@ bool kvm_tdp_mmu_wrprot_slot(struct kvm *kvm,
 
 	lockdep_assert_held_read(&kvm->mmu_lock);
 
+	/*
+	 * Because first TDX generation doesn't support write protecting private
+	 * mappings and kvm_arch_dirty_log_supported(kvm) = false, it's a bug
+	 * to reach here for guest TD.
+	 */
+	if (WARN_ON_ONCE(!kvm_arch_dirty_log_supported(kvm)))
+		return false;
+
 	for_each_valid_tdp_mmu_root_yield_safe(kvm, root, slot->as_id, true)
 		spte_set |= wrprot_gfn_range(kvm, root, slot->base_gfn,
 			     slot->base_gfn + slot->npages, min_level); @@ -1902,6
+1934,14 @@ bool kvm_tdp_mmu_clear_dirty_slot(struct kvm *kvm,
 

arch/x86/kvm/mmu/tdp_mmu.c bool kvm_tdp_mmu_wrprot_slot(struct kvm *kvm,

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +8 -0
 	lockdep_assert_held_read(&kvm->mmu_lock);
 
+	/*
+	 * 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_ONCE(!kvm_arch_dirty_log_supported(kvm)))
+		return false;
+

It might not be a good choice to intercept everywhere in kvm_mmu just as tdx doesn't support it. I'm thinking maybe we could do the check in tdx.c, which is much simpler. For example:

(quoted diff) +2 -0
@@ -2592,6 +2605,12 @@ static void tdx_handle_changed_private_spte(struct kvm *kvm,
        lockdep_assert_held(&kvm->mmu_lock);
 
        if (change->new.is_present) {
+               /* Only flags change. This isn't supported currently. */
+               KVM_BUG_ON(change->old.is_present, kvm);
 
Quoted 1 line

Then we can have kvm_arch_dirty_log_supported completely removed.

Do you mean WARN_ON_ONCE()? If so, they can be removed from this patches because the code should be blocked by "if (!kvm_arch_dirty_log_supported(kvm))" at the caller.

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

Re: [PATCH v10 047/108] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Isaku Yamahata
Quoted 6 lines · Isaku Yamahata
Quoted 5 lines

Sorry why "private-shared conversion is done via KVM_MEMORY_ENCRYPT_REG" results
in "we can ignore the requres from restrictedmem"?

If we punch a hole, the pages are de-allocated, correct?

Quoted 7 lines

With v10 UPM, we can have zap_private = true always.

With v9 UPM, the callback is triggered both for allocation and punch-hole without
any further argument.  With v10 UPM, the callback is triggered only for punching
hole.

I honestly don't quite understand "why v9 UPM the callback is triggered for allocation" (assuming the "callback" here you mean the invaidate notifier). Removing it seems to be right.

But, this is not the point. The point is you need to be clear about how to use "punch hole" and/or set_memory_attributes().

Now my assumption is "punch hole" can be done alone w/o set_memory_attributes(). For instance, perhaps a (I guess valid) case is hot-removal of memory from TDX guest, where you don't need to set_memory_attributes().

However it does seem that set_memory_attributes(shared) should (or must) be done after "punch hole". And we need to document that clearly.

So it seems a more reasonable way is:

1) in "punch hole", you zap everything.
2) in set_memory_attribute() from private -> shared, you try to zap all private pages anyway (it should be very quick if "punch hole" has been done), and you can pr_warn_once() (or WARN()) if you found any private page still exists.

Did I miss anything?

But I am not sure about set_memory_attribute() from shared -> private. Should we do fallocate() before that?

#139 lore raw

Re: [PATCH v10 056/108] KVM: TDX: don't request KVM_REQ_APIC_PAGE_RELOAD

In reply to Huang, Kai
Quoted 49 lines · Kai
Quoted 26 lines · On Sat, 2022-10-29 at 23:22 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX doesn't need APIC page depending on vapic and its callback is WARN_ON_ONCE(is_tdx). To avoid unnecessary overhead and WARN_ON_ONCE(), skip requesting KVM_REQ_APIC_PAGE_RELOAD when TD.

  WARNING: arch/x86/kvm/vmx/main.c:696 vt_set_apic_access_page_addr+0x3c/0x50 [kvm_intel]
  RIP: 0010:vt_set_apic_access_page_addr+0x3c/0x50 [kvm_intel]
  Call Trace:
   vcpu_enter_guest+0x145d/0x24d0 [kvm]
   kvm_arch_vcpu_ioctl_run+0x25d/0xcc0 [kvm]
   kvm_vcpu_ioctl+0x414/0xa30 [kvm]
   __x64_sys_ioctl+0xc0/0x100
   do_syscall_64+0x39/0xc0
   entry_SYSCALL_64_after_hwframe+0x44/0xae
---
 arch/x86/kvm/x86.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
arch/x86/kvm/x86.c +0 -0
index 3868605462ed..5dadd0f9a10e 100644

arch/x86/kvm/x86.c void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm, · line 10495

Quoted 10 lines
arch/x86/kvm/x86.c +3 -1
@@ -10487,7 +10487,9 @@ void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
 	 * Update it when it becomes invalid.
 	 */
 	apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
-	if (start <= apic_address && apic_address < end)
+	/* TDX doesn't need APIC page. */
+	if (kvm->arch.vm_type != KVM_X86_TDX_VM &&
+	    start <= apic_address && apic_address < end)
 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
 }
 

In patch "[PATCH v10 105/108] KVM: TDX: Add methods to ignore accesses to CPU state", you have:

(quoted diff) +7 -0
+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);
+}
Quoted 7 lines

If you drop the WARN_ON_ONCE() above, you can just drop this patch.

For this particular case, I don't find it is quite necessary to change the common x86 code as done in this patch. In fact, SVM doesn't have a set_apic_access_page_addr() callback which is consistent with just return if VM is TD in vt_set_apic_access_page_addr().

Oh, yes. I will drop this patch with removing WARN_ON_ONCE().

Quoted 3 lines

Also, I don't particularly like the idea of having a lot of "is_td(kvm)" in the common x86 code as if similar technology happens in the future, you will need to have another "is_td_similar_vm(kvm)" thing.

Currently KVM_CAP_VM_TYPES has such check in x86 kvm common code.

Quoted 7 lines

If modifying common x86 code is necessary, then it would make more sense to introduce some common flag, and make TD guest set that flag.

Btw, this patch just comes out of blue from the middle of a bunch of MMU patches. Shouldn't it be moved to "patches which handles interrupt related staff"?

Quoted 6 lines

Btw2, by saying above, does it make sense to split patch "[PATCH v10 105/108]
KVM: TDX: Add methods to ignore accesses to CPU state" based on category such as MMU/interrupt, etc? Particularly, in that patch, some callbacks have WARN() or KVM_BUG_ON() against TD guest, but some don't. The logic behind those decisions highly depend on previous patches. To me, it makes more sense to just move logic related things together.

Ok, I'll split it up to cpu states/KVM MMU/interrupt parts.

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

Re: [PATCH v10 062/108] KVM: x86/tdp_mmu: implement MapGPA hypercall for TDX

In reply to Binbin Wu
Quoted 65 lines · Binbin Wu
Quoted 63 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The TDX Guest-Hypervisor communication interface(GHCI) specification defines MapGPA hypercall for guest TD to request the host VMM to map given GPA range as private or shared.

It means the guest TD uses the GPA as shared (or private). The GPA won't be used as private (or shared). VMM should enforce GPA usage. VMM doesn't have to map the GPA on the hypercall request.

- Zap the aliased region.
If shared (or private) GPA is requested, zap private (or shared) GPA (modulo shared bit).
- Record the request GPA is shared (or private) by kvm.mem_attr_array.
- Don't map GPA. The GPA is mapped on the next EPT violation.

---
  arch/x86/kvm/mmu.h         |  5 ++++
  arch/x86/kvm/mmu/mmu.c     | 60 ++++++++++++++++++++++++++++++++++++++
  arch/x86/kvm/mmu/tdp_mmu.c | 35 ++++++++++++++++++++++
  arch/x86/kvm/mmu/tdp_mmu.h |  3 ++
  4 files changed, 103 insertions(+)
arch/x86/kvm/mmu.h +5 -0
index e2a0dfbee56d..e1641fa5a862 100644
@@ -219,6 +219,11 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
  int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu);
+int __kvm_mmu_map_gpa(struct kvm *kvm, gfn_t *startp, gfn_t end,
+		      bool map_private);
+int kvm_mmu_map_gpa(struct kvm_vcpu *vcpu, gfn_t *startp, gfn_t end,
+		    bool map_private);
+
  int kvm_mmu_post_init_vm(struct kvm *kvm);
  void kvm_mmu_pre_destroy_vm(struct kvm *kvm);
arch/x86/kvm/mmu/mmu.c +19 -0
index 168c84c99de3..37b378bf60df 100644
@@ -6778,6 +6778,66 @@ void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
  	}
  }
+int __kvm_mmu_map_gpa(struct kvm *kvm, gfn_t *startp, gfn_t end,
+		      bool map_private)
+{
+	gfn_t start = *startp;
+	int attr;
+	int ret;
+
+	if (!kvm_gfn_shared_mask(kvm))
+		return -EOPNOTSUPP;
+
+	attr = map_private ? KVM_MEM_ATTR_PRIVATE : KVM_MEM_ATTR_SHARED;
+	start = start & ~kvm_gfn_shared_mask(kvm);
+	end = end & ~kvm_gfn_shared_mask(kvm);
+
+	/*
+	 * To make the following kvm_vm_set_mem_attr() success within spinlock
+	 * without memory allocation.
+	 */
+	ret = kvm_vm_reserve_mem_attr(kvm, start, end);
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen) · line 6804

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+	if (ret)
+		return ret;
+
+	write_lock(&kvm->mmu_lock);
+	if (is_tdp_mmu_enabled(kvm)) {

How about moving the condition test to the beginning of the function to make the code simpler?

Ok.

Quoted 89 lines
Quoted 89 lines
arch/x86/kvm/mmu/mmu.c +36 -0
+		gfn_t s = start;
+
+		ret = kvm_tdp_mmu_map_gpa(kvm, &s, end, map_private);
+		if (!ret) {
+			KVM_BUG_ON(kvm_vm_set_mem_attr(kvm, attr, start, end), kvm);
+		} else if (ret == -EAGAIN) {
+			KVM_BUG_ON(kvm_vm_set_mem_attr(kvm, attr, start, s), kvm);
+			start = s;
+		}
+	} else {
+		ret = -EOPNOTSUPP;
+	}
+	write_unlock(&kvm->mmu_lock);
+
+	if (ret == -EAGAIN) {
+		if (map_private)
+			*startp = kvm_gfn_private(kvm, start);
+		else
+			*startp = kvm_gfn_shared(kvm, start);
+	}
+	return ret;
+}
+EXPORT_SYMBOL_GPL(__kvm_mmu_map_gpa);
+
+int kvm_mmu_map_gpa(struct kvm_vcpu *vcpu, gfn_t *startp, gfn_t end,
+		    bool map_private)
+{
+	struct kvm_mmu *mmu = vcpu->arch.mmu;
+
+	if (!VALID_PAGE(mmu->root.hpa) || !VALID_PAGE(mmu->private_root_hpa))
+		return -EINVAL;
+
+	return __kvm_mmu_map_gpa(vcpu->kvm, startp, end, map_private);
+}
+EXPORT_SYMBOL_GPL(kvm_mmu_map_gpa);
+
  static unsigned long
  mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  {
arch/x86/kvm/mmu/tdp_mmu.c +35 -0
index 4b207ce83ffe..d3bab382ceaa 100644
@@ -2156,6 +2156,41 @@ bool kvm_tdp_mmu_write_protect_gfn(struct kvm *kvm,
  	return spte_set;
  }
+int kvm_tdp_mmu_map_gpa(struct kvm *kvm,
+			gfn_t *startp, gfn_t end, bool map_private)
+{
+	struct kvm_mmu_page *root;
+	gfn_t start = *startp;
+	bool flush = false;
+	int i;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+	KVM_BUG_ON(start & kvm_gfn_shared_mask(kvm), kvm);
+	KVM_BUG_ON(end & kvm_gfn_shared_mask(kvm), kvm);
+
+	kvm_mmu_invalidate_begin(kvm, start, end);
+	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
+		for_each_tdp_mmu_root_yield_safe(kvm, root, i) {
+			if (is_private_sp(root) == map_private)
+				continue;
+
+			/*
+			 * TODO: If necessary, return to the caller with -EAGAIN
+			 * instead of yield-and-resume within
+			 * tdp_mmu_zap_leafs().
+			 */
+			flush = tdp_mmu_zap_leafs(kvm, root, start, end,
+						  /*can_yield=*/true, flush,
+						  /*zap_private=*/is_private_sp(root));
+		}
+	}
+	if (flush)
+		kvm_flush_remote_tlbs_with_address(kvm, start, end - start);
+	kvm_mmu_invalidate_end(kvm, start, end);
+
+	return 0;
+}
+
  /*
   * Return the level of the lowest level SPTE added to sptes.
   * That SPTE may be non-present.
arch/x86/kvm/mmu/tdp_mmu.h +0 -0
index 695175c921a5..cb13bc1c3679 100644
@@ -51,6 +51,9 @@ void kvm_tdp_mmu_try_split_huge_pages(struct kvm *kvm,
Quoted 8 lines

arch/x86/kvm/mmu/tdp_mmu.h void kvm_tdp_mmu_try_split_huge_pages(struct kvm *kvm, · line 55

Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.h +2 -0
  				      gfn_t start, gfn_t end,
  				      int target_level, bool shared);
+int kvm_tdp_mmu_map_gpa(struct kvm *kvm,
+			gfn_t *startp, gfn_t end, bool map_private);

Sugguest to add some description about the function to avoid confusion, since the function name is quite generic but the usage is highly related to TDX.

Agreed that the name is too generic. Will rename it to kvm_tdp_mmu_map_private().

I can think of convert_private(), convert_gpa(), or any other suggestion?

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

Re: [PATCH v10 062/108] KVM: x86/tdp_mmu: implement MapGPA hypercall for TDX

In reply to Vishal Annapurve
Quoted 34 lines · Vishal Annapurve
Quoted 19 lines
arch/x86/kvm/mmu/mmu.c +19 -0
+int __kvm_mmu_map_gpa(struct kvm *kvm, gfn_t *startp, gfn_t end,
+		      bool map_private)
+{
+	gfn_t start = *startp;
+	int attr;
+	int ret;
+
+	if (!kvm_gfn_shared_mask(kvm))
+		return -EOPNOTSUPP;
+
+	attr = map_private ? KVM_MEM_ATTR_PRIVATE : KVM_MEM_ATTR_SHARED;
+	start = start & ~kvm_gfn_shared_mask(kvm);
+	end = end & ~kvm_gfn_shared_mask(kvm);
+
+	/*
+	 * To make the following kvm_vm_set_mem_attr() success within spinlock
+	 * without memory allocation.
+	 */
+	ret = kvm_vm_reserve_mem_attr(kvm, start, end);

arch/x86/kvm/mmu/mmu.c void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen) · line 6809

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	if (ret)
+		return ret;
+
+	write_lock(&kvm-> mmu_lock);
+	if (is_tdp_mmu_enabled(kvm)) {
+		gfn_t s = start;
+
+		ret = kvm_tdp_mmu_map_gpa(kvm, &s, end, map_private);
+		if (!ret) {
+			KVM_BUG_ON(kvm_vm_set_mem_attr(kvm, attr, start, end), kvm);

This will result in no exits to userspace during memory conversion requests from guests. And as a result, userspace will not be able to explicitly back/unback shared/private memory during conversions leading to double allocation of memory.

Quoted 2 lines

Is this an intended behavior for memory conversion with TDX VMs as per earlier discussion?

It was because UPM ioctl interface was not stable yet. With v10, it seems mostly stable, I'll change the patch of "[PATCH v10 101/108] KVM: TDX: Handle TDX PV map_gpa hypercall" to exit to user space.

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

Re: [PATCH v10 056/108] KVM: TDX: don't request KVM_REQ_APIC_PAGE_RELOAD

In reply to Isaku Yamahata
Quoted 11 lines · Isaku Yamahata
Quoted 10 lines

Btw2, by saying above, does it make sense to split patch "[PATCH v10 105/108]
KVM: TDX: Add methods to ignore accesses to CPU state" based on category such as
MMU/interrupt, etc?  Particularly, in that patch, some callbacks have WARN() or
KVM_BUG_ON() against TD guest, but some don't.  The logic behind those decisions
highly depend on previous patches.  To me, it makes more sense to just move logic related things together.

Quoted 1 line

Ok, I'll split it up to cpu states/KVM MMU/interrupt parts.

If I recall correctly, originally (long time ago before starting to upstream), what we did was we have a patch to make all kvm_x86_ops callback KVM_BUG_ON() for TDX guest, then we fix those KVM_BUG_ON() in later patches in separate patches.

We don't need to do the exact same way, but this also seems reasonable to me. For instance, at the beginning we can mark KVM_BUG_ON() for all callbacks which reads/writes CPU states (which is reasonable anyway), and in later patches we remove the KVM_BUG_ON() if needed when handling specific logic.

Simply my 2cents above. Just for your reference. My real comment is we should put relevant parts together so it's easy to review.

#177 lore raw

Re: [PATCH v10 077/108] KVM: x86: Add a switch_db_regs flag to handle TDX's auto-switched behavior

In reply to Binbin Wu
Quoted 84 lines · Binbin Wu
Quoted 69 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a flag, KVM_DEBUGREG_AUTO_SWITCHED_GUEST, to skip saving/restoring DRs irrespective of any other flags. TDX-SEAM unconditionally saves and restores guest DRs and reset to architectural INIT state on TD exit. So, KVM needs to save host DRs before TD enter without restoring guest DRs and restore host DRs after TD exit.

Opportunistically convert the KVM_DEBUGREG_* definitions to use BIT().

---
  arch/x86/include/asm/kvm_host.h |  9 +++++++--
  arch/x86/kvm/vmx/tdx.c          |  1 +
  arch/x86/kvm/x86.c              | 11 ++++++++---
  3 files changed, 16 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm_host.h +7 -2
index fdb00d96e954..082e94f78c66 100644
@@ -583,8 +583,13 @@ struct kvm_pmu {
  struct kvm_pmu_ops;
  enum {
-	KVM_DEBUGREG_BP_ENABLED = 1,
-	KVM_DEBUGREG_WONT_EXIT = 2,
+	KVM_DEBUGREG_BP_ENABLED		= BIT(0),
+	KVM_DEBUGREG_WONT_EXIT		= BIT(1),
+	/*
+	 * Guest debug registers are saved/restored by hardware on exit from
+	 * or enter guest. KVM needn't switch them.
+	 */
+	KVM_DEBUGREG_AUTO_SWITCH	= BIT(2),
  };
  struct kvm_mtrr_range {
arch/x86/kvm/vmx/tdx.c +1 -0
index fc4de83a2df8..57767ef3353b 100644
@@ -429,6 +429,7 @@ int tdx_vcpu_create(struct kvm_vcpu *vcpu)
  	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
+	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 +2 -1
index 4d4b71c4cdb1..ad7b227b68dd 100644
@@ -10779,7 +10779,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);
@@ -10822,6 +10822,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);

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 10842

Quoted 10 lines
arch/x86/kvm/x86.c +5 -2
@@ -10834,8 +10835,12 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	 * care about the messed up debug address registers. But if
  	 * we have some of them active, restore the old state.
  	 */
-	if (hw_breakpoint_active())
-		hw_breakpoint_restore();
+	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);

Why only restore dr7 when TD exit?

Quoted 2 lines

According to the commit message, dr0~dr3 are also reset to architectural INIT value on TD exit.

Probably you're referring to the old version of the spec. context switched: DR0-3, DR6, IA32_DS_AREA
reset on TD exit: RFLAGS, IA32_DEBUGCTL, DR7

I'll add a comment.

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

Re: [PATCH v10 098/108] KVM: TDX: Implement callbacks for MSR operations for TDX

In reply to Binbin Wu
Quoted 9 lines · Binbin Wu
Quoted 6 lines · On 10/30/2022 2:23 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Implements set_msr/get_msr/has_emulated_msr methods for TDX to handle hypercall from guest TD for paravirtualized rdmsr and wrmsr. The TDX module virtualizes MSRs. For some MSRs, it injects #VE to the guest TD upon RDMSR or WRMSR. The exact list of such MSRs are defined in the spec.

Quoted 4 lines

How does KVM handle the case that the userland wants to get the TD MSR list?

KVM_GET_MSR_INDEX_LIST will return the global KVM MSR list, which is different from the TD version.

Do you mean user space VMM (e.g. qemu) by "the userland"?
There are three classes of MSRs virtualization.
- non-configurable: TDX module directly virtualizes it. VMM can't configure. the value set by KVM_SET_MSR_INDEX_LIST is ignored.
- configurable: TDX module directly virtualizes it. VMM can configure at the VM creation time.
the value set by KVM_SET_MSR_INDEX_LIST is used.
- #VE
VMM handles the MSR hypercall by guest TD issues. The value set by KVM_SET_MSR_INDEX_LIST is used.

Quoted 5 lines
Quoted 4 lines

Upon #VE, the guest TD may execute hypercalls, TDG.VP.VMCALL<INSTRUCTION.RDMSR> and TDG.VP.VMCALL<INSTRUCTION.WRMSR>, which are defined in GHCI (Guest-Host Communication Interface) so that the host VMM (e.g. KVM) can virtualizes

can virtualize

Yes, will fix.

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

Re: [PATCH v10 098/108] KVM: TDX: Implement callbacks for MSR operations for TDX

In reply to Huang, Kai
Quoted 11 lines · Kai
Quoted 10 lines · On Sat, 2022-10-29 at 23:23 -0700, [email protected] wrote:
(quoted diff) +10 -0
+bool tdx_is_emulated_msr(u32 index, bool write)
+{
+	switch (index) {
+	case MSR_IA32_UCODE_REV:
+	case MSR_IA32_ARCH_CAPABILITIES:
+	case MSR_IA32_POWER_CTL:
+	case MSR_MTRRcap:
+	case 0x200 ... 0x26f:
+		/* IA32_MTRR_PHYS{BASE, MASK}, IA32_MTRR_FIX*_* */
+	case MSR_IA32_CR_PAT:
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+	case MSR_MTRRdefType:
+	case MSR_IA32_TSC_DEADLINE:
+	case MSR_IA32_MISC_ENABLE:
+	case MSR_KVM_STEAL_TIME:
+	case MSR_KVM_POLL_CONTROL:

To me putting KVM para-virt MSRs and hardware MSRs together isn't good idea. You can introduce separate helpers for them.

Makes sense. updated as follows.

arch/x86/kvm/vmx/tdx.c +14 -2
index ee8d395af849..b4132167e2bb 100644
@@ -1606,6 +1606,17 @@ void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
        *error_code = 0;
 }
 
+static bool tdx_is_emulated_kvm_msr(u32 index, bool write)
+{
+       switch (index) {
+       case MSR_KVM_STEAL_TIME:
+       case MSR_KVM_POLL_CONTROL:
+               return true;
+       default:
+               return false;
+       }
+}
+
 bool tdx_is_emulated_msr(u32 index, bool write)
 {
        switch (index) {
@@ -1619,8 +1630,6 @@ bool tdx_is_emulated_msr(u32 index, bool write)
        case MSR_MTRRdefType:
        case MSR_IA32_TSC_DEADLINE:
        case MSR_IA32_MISC_ENABLE:
-       case MSR_KVM_STEAL_TIME:
-       case MSR_KVM_POLL_CONTROL:
        case MSR_PLATFORM_INFO:
        case MSR_MISC_FEATURES_ENABLES:
        case MSR_IA32_MCG_CAP:
@@ -1650,6 +1659,9 @@ bool tdx_is_emulated_msr(u32 index, bool write)
        case MSR_IA32_APICBASE:
        case MSR_EFER:
                return !write;
+       case 0x4b564d00 ... 0x4b564dff:
+               /* KVM custom MSRs */
+               return tdx_is_emulated_kvm_msr(index, write);
        default:
                return false;
        }
Signature · 1 line
Isaku Yamahata <[email protected]>
#213 lore raw

Re: [PATCH v10 104/108] KVM: TDX: Silently ignore INIT/SIPI

In reply to Binbin Wu
Quoted 20 lines · Binbin Wu
Quoted 20 lines
arch/x86/kvm/vmx/main.c +13 -0
index 4acba8d8cb27..d776d5d169d0 100644
@@ -286,6 +286,25 @@ static void vt_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
  	vmx_deliver_interrupt(apic, delivery_mode, trig_mode, vector);
  }
+static void vt_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	kvm_vcpu_deliver_sipi_vector(vcpu, vector);
+}
+
+static void vt_vcpu_deliver_init(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu)) {
+		/* TDX doesn't support INIT.  Ignore INIT event */
+		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
Quoted 8 lines

arch/x86/kvm/vmx/main.c static void vt_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode, · line 307

Quoted 6 lines
arch/x86/kvm/vmx/main.c +6 -0
+		return;
+	}
+
+	kvm_vcpu_deliver_init(vcpu);
+}
+

Is it better to add WARN_ON_ONCE in the above two functions for TD case?

No because KVM_SET_VCPU_EVENTS ioctl can trigger those callback.

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

Re: [PATCH v10 106/108] Documentation/virt/kvm: Document on Trust Domain Extensions(TDX)

In reply to Binbin Wu
Quoted 4 lines · Binbin Wu

Documentation/virt/kvm/intel-tdx.rst

Quoted 3 lines
Documentation/virt/kvm/intel-tdx.rst new file +3 -0
+New KVM API, ioctl (sub)command, to manage TD VMs
+-------------------------------------------------
+Additional KVM API

API -> APIs

Quoted 11 lines

Documentation/virt/kvm/intel-tdx.rst

Quoted 6 lines

are needed to control TD VMs. The operations on TD

Documentation/virt/kvm/intel-tdx.rst new file +5 -0
+VMs are specific to TDX.
+
+- Piggyback and repurpose KVM_MEMORY_ENCRYPT_OP
+
+  Although not all operation isn't memory encryption,

How to understand it?

Quoted 1 line

repupose to get

How about the followings?

New KVM API, ioctl (sub)command, to manage TD VMs
-------------------------------------------------
Additional KVM APIs are needed to control TD VMs. The operations on TD VMs are specific to TDX.

- Piggyback and repurpose KVM_MEMORY_ENCRYPT_OP

Although operations for TD VMs aren't necessarily related to memory encryption, define sub operations of KVM_MEMORY_ENCRYPT_OP for TDX specific ioctls.

Pros:

- No major change in common x86 KVM code.
- Follows the SEV case.

Cons:

- The sub operations of KVM_MEMORY_ENCRYPT_OP aren't necessarily memory encryption, but operations on TD VMs.

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

Re: [PATCH v10 105/108] KVM: TDX: Add methods to ignore accesses to CPU state

In reply to Huang, Kai
Quoted 17 lines · Kai

Review

Quoted 10 lines · On Sat, 2022-10-29 at 23:23 -0700, [email protected] wrote:
(quoted diff) +10 -0
+static u8 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);
+}

So you are returning WB for _ALL_ guest memory, including shared. Wouldn't this break MTRR handling for shared memory? For instance, IIUC we can still support assigning a device to a TDX guest while the VT-d doesn't support coherent memory, in which case guest's MTRR/PAT are honored. I think this should also apply to TDX guest's shared memory?

You're right. So here is the updated change.

arch/x86/kvm/vmx/main.c +2 -5
@@ -798,11 +798,8 @@ static int vt_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
 
 static u8 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;
-       }
+       if (is_td_vcpu(vcpu))
+               return tdx_get_mt_mask(vcpu, gfn, is_mmio);
 
        return vmx_get_mt_mask(vcpu, gfn, is_mmio);
 }
arch/x86/kvm/vmx/tdx.c +24 -0
index ac47b20e4e91..f1842eb32d6c 100644
@@ -568,7 +568,31 @@ int tdx_vm_init(struct kvm *kvm)
        return 0;
 }
 
+u8 tdx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
+{
+       if (is_mmio)
+               return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
+
+       if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
+               return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
+
+       /* Guest CR0 is unknown.  Assume CR0.CD = 0. */
+
+       /* TDX private GPA is always WB. */
+       if (gfn & kvm_gfn_shared_mask(vcpu->kvm))
+               return  MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT;
+
+       /*
+        * Because the definition of MTRR MSR is unaware of shared-bit,
+        * clear shared-bit.
+        */
+       gfn = kvm_gfn_private(vcpu->kvm, gfn);
+       return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
+}
+
 int tdx_vcpu_create(struct kvm_vcpu *vcpu)
+
+
 {
        struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
        struct vcpu_tdx *tdx = to_tdx(vcpu);
arch/x86/kvm/vmx/x86_ops.h +1 -0
index 96f5546194d4..38fb888e1be9 100644
@@ -168,6 +168,7 @@ int tdx_handle_exit(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);
+u8 tdx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio);
 void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
                u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code);
 bool tdx_is_emulated_msr(u32 index, bool write);
Signature · 1 line
Isaku Yamahata <[email protected]>
#214 lore raw

Re: [PATCH v10 104/108] KVM: TDX: Silently ignore INIT/SIPI

In reply to [email protected]
Quoted 12 lines · On Sat, Oct 29, 2022, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The TDX module API doesn't provide API for VMM to inject INIT IPI and SIPI. Instead it defines the different protocols to boot application processors. Ignore INIT and SIPI events for the TDX guest.

There are two options. 1) (silently) ignore INIT/SIPI request or 2) return error to guest TDs somehow. Given that TDX guest is paravirtualized to boot AP, the option 1 is chosen for simplicity.

---

...

Quoted 31 lines
arch/x86/kvm/vmx/main.c +19 -0
index 4acba8d8cb27..d776d5d169d0 100644
@@ -286,6 +286,25 @@ static void vt_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
 	vmx_deliver_interrupt(apic, delivery_mode, trig_mode, vector);
 }
 
+static void vt_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	kvm_vcpu_deliver_sipi_vector(vcpu, vector);
+}
+
+static void vt_vcpu_deliver_init(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu)) {
+		/* TDX doesn't support INIT.  Ignore INIT event */
+		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+		return;
+	}
+
+	kvm_vcpu_deliver_init(vcpu);
+}
+
 static void vt_flush_tlb_all(struct kvm_vcpu *vcpu)
 {
 	if (is_td_vcpu(vcpu))

arch/x86/kvm/vmx/main.c struct kvm_x86_ops vt_x86_ops __initdata = { · line 650

Quoted 6 lines
arch/x86/kvm/vmx/main.c +2 -1
@@ -627,7 +646,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.msr_filter_changed = vmx_msr_filter_changed,
 	.complete_emulated_msr = kvm_complete_insn_gp,
 
-	.vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
+	.vcpu_deliver_sipi_vector = vt_vcpu_deliver_sipi_vector,
+	.vcpu_deliver_init = vt_vcpu_deliver_init,

A simpler, and arguably more correct, appraoch would be to hook .apic_init_signal_blocked() and have that return true for TDX. Waiting until delivery means the vCPU will get spurious wake events, e.g. KVM will wake the vCPU to service the INIT, but then ignore the INIT. Of course, sending the bogus INIT/SIPI in the first place is a guest bug.

That would also prevent userspace from putting the vCPU into INIT/SIPI via KVM_SET_MP_STATE.

Ideally, KVM would never mark INIT or SIPI pending in the first place, though I'm not sure that's worth the effort.

#219 lore raw

Re: [PATCH v10 105/108] KVM: TDX: Add methods to ignore accesses to CPU state

In reply to Isaku Yamahata
Quoted 45 lines · Isaku Yamahata
Quoted 17 lines · Kai

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

Quoted 10 lines · On Sat, 2022-10-29 at 23:23 -0700, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +10 -0
+static u8 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);
+}

So you are returning WB for _ALL_ guest memory, including shared. Wouldn't this break MTRR handling for shared memory? For instance, IIUC we can still support assigning a device to a TDX guest while the VT-d doesn't support coherent memory, in which case guest's MTRR/PAT are honored. I think this should also apply to TDX guest's shared memory?

You're right. So here is the updated change.

arch/x86/kvm/vmx/main.c +2 -5
@@ -798,11 +798,8 @@ static int vt_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
 
 static u8 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;
-       }
+       if (is_td_vcpu(vcpu))
+               return tdx_get_mt_mask(vcpu, gfn, is_mmio);
 
        return vmx_get_mt_mask(vcpu, gfn, is_mmio);
 }
arch/x86/kvm/vmx/tdx.c +0 -0
index ac47b20e4e91..f1842eb32d6c 100644
@@ -568,7 +568,31 @@ int tdx_vm_init(struct kvm *kvm)
        return 0;
 }

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +9 -0
 
+u8 tdx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
+{
+       if (is_mmio)
+               return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
+
+       if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
+               return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
+
+       /* Guest CR0 is unknown.  Assume CR0.CD = 0. */

This comment is horrible. You need to explain why guest CR0.CD is irrelevant here.

And the fact is for TDX guest, TDX module tells us the CR0.CD is always 0.

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+       /* TDX private GPA is always WB. */
+       if (gfn & kvm_gfn_shared_mask(vcpu->kvm))
+               return  MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT;

Dose the 'gfn' still have the shared bit set? I don't think so?

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+
+       /*
+        * Because the definition of MTRR MSR is unaware of shared-bit,
+        * clear shared-bit.
+        */
+       gfn = kvm_gfn_private(vcpu->kvm, gfn);
+       return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
+}

Overall, I think a better logic should be: 1) for private page, return WB (and WARN_ON(is_mmio)), although this doesn't matter anyway as the SPTE won't be used by CPU anyway. 2) Then for shared pages, we try to copy vmx_get_mt_mask() logic, or use vmx_get_mt_mask() directly.

But since how KVM and TDX module virtualize MTRR/PAT is different, thus for now I am not sure whether just using vmx_get_mt_mask() can work. For example, IIUC for TDX guest KVM cannot know guest's PAT, but for VMX guest KVM traps MTRR/PAT so it can know guest's memory type.

For now I am not even sure whether we can/should support device assignment w/o VT-d snooping capability as for TDX guest KVM cannot know guest's PAT? Perhaps we should just make sure this won't happen so we can always returns WB for shared memory too for TDX guest.

#133 lore raw

RE: [PATCH v10 052/108] KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs

In reply to Isaku Yamahata
Quoted 21 lines · Isaku

Review static void

Quoted 14 lines

arch/x86/kvm/mmu/tdp_mmu.c bool kvm_tdp_mmu_clear_dirty_slot(struct kvm *kvm, · line 1944

Quoted 8 lines
arch/x86/kvm/mmu/tdp_mmu.c +8 -0
+	/*
+	 * 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_ONCE(!kvm_arch_dirty_log_supported(kvm)))
+		return false;
+

It might not be a good choice to intercept everywhere in kvm_mmu just as tdx doesn't support it. I'm thinking maybe we could do the check in tdx.c, which is much simpler. For example:

(quoted diff) +0 -0
@@ -2592,6 +2605,12 @@ static void

tdx_handle_changed_private_spte(struct kvm *kvm,

Quoted 6 lines
(quoted diff) +2 -0
        lockdep_assert_held(&kvm->mmu_lock);
 
        if (change->new.is_present) {
+               /* Only flags change. This isn't supported currently. */
+               KVM_BUG_ON(change->old.is_present, kvm);
 
Quoted 6 lines
Quoted 1 line

Then we can have kvm_arch_dirty_log_supported completely removed.

Do you mean WARN_ON_ONCE()? If so, they can be removed from this patches because the code should be blocked by "if (!kvm_arch_dirty_log_supported(kvm))" at the caller.

As you also mentioned in the comment "It is a bug to reach here", we could keep using KVM_BUG_ON. The suggestion is that we don't need to add such checks in all the callers as it is more complicated (and error-prone) to consider all of them. Why not let callers run into tdx_handle_changed_private_spte to do the check (at this only place)? From what I understand, we don’t support an spte change with flags update only for this version. This would be much simpler.

#226 lore raw
In reply to [email protected]
Quoted 12 lines · On 10/30/2022 2:22 PM, [email protected] wrote:

** Detecting the TDX module readiness.
TDX host patch series implements the detection of the TDX module availability and its initialization so that KVM can use it. Also it manages Host KeyID (HKID) assigned to guest TD.
The assumed APIs the TDX host patch series provides are
- int seamrr_enabled()
Check if required cpu feature (SEAM mode) is available. This only check CPU feature availability. At this point, the TDX module may not be ready for KVM to use.
- int init_tdx(void);
Initialization of TDX module so that the TDX module is ready for KVM to use.
- const struct tdsysinfo_struct *tdx_get_sysinfo(void);

Quoted 8 lines

Return the system wide information about the TDX module. NULL if the TDX isn't initialized.
- u32 tdx_get_global_keyid(void);
Return global key id that is used for the TDX module itself.
- int tdx_keyid_alloc(void);
Allocate HKID for guest TD.
- void tdx_keyid_free(int keyid);
Free HKID for guest TD.

tdx_enable() is introduced by TDX host patch series and used in patch 5, should it be added to this list too?

#43 lore raw

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to Isaku Yamahata

Happy to help!

Nope it wasn't any special technique, I was working on the selftests and made a mistake configuring the TD while initializing it.

While setting up struct kvm_tdx_init_vm, I did not copy the entire struct kvm_cpuid2.

This reliably reproduces the crash:

--------

// SPDX-License-Identifier: GPL-2.0-only

#include "kvm_util_base.h"
#include <processor.h>

static int tdx_ioctl(int fd, int ioctl_no, uint32_t flags, void *data)

{
	struct kvm_tdx_cmd tdx_cmd;

	memset(&tdx_cmd, 0x0, sizeof(tdx_cmd));
	tdx_cmd.id = ioctl_no;
	tdx_cmd.flags = flags;
	tdx_cmd.data = (uint64_t)data;
	return ioctl(fd, KVM_MEMORY_ENCRYPT_OP, &tdx_cmd);
}

#define XFEATURE_LBR 15
#define XFEATURE_XTILECFG 17
#define XFEATURE_XTILEDATA 18
#define XFEATURE_CET_U 11
#define XFEATURE_CET_S 12

#define XFEATURE_MASK_LBR (1 << XFEATURE_LBR)
#define XFEATURE_MASK_CET_U (1 << XFEATURE_CET_U)
#define XFEATURE_MASK_CET_S (1 << XFEATURE_CET_S)
#define XFEATURE_MASK_CET (XFEATURE_MASK_CET_U | XFEATURE_MASK_CET_S)
#define XFEATURE_MASK_XTILECFG (1 << XFEATURE_XTILECFG)
#define XFEATURE_MASK_XTILEDATA (1 << XFEATURE_XTILEDATA)
#define XFEATURE_MASK_XTILE (XFEATURE_MASK_XTILECFG | XFEATURE_MASK_XTILEDATA)

static void apply_tdx_restrictions(struct kvm_cpuid2 *cpuid_data)

{
	for (int i = 0; i < 100; i++) {
		struct kvm_cpuid_entry2 *e = &cpuid_data->entries[i];

		if (e->function == 0xd && e->index == 0) {
			/*
			 * TDX module requires both XTILE_{CFG, DATA} to be set.
			 * Both bits are required for AMX to be functional.
			 */
			if ((e->eax & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE) {
				e->eax &= ~XFEATURE_MASK_XTILE;
			}
		}

		if (e->function == 0xd && e->index == 1) {
			/*
			 * TDX doesn't support LBR yet.
			 * Disable bits from the XCR0 register.
			 */
			e->ecx &= ~XFEATURE_MASK_LBR;

			/*
			 * TDX modules requires both CET_{U, S} to be set even
			 * if only one is supported.
			 */
			if (e->ecx & XFEATURE_MASK_CET)
				e->ecx |= XFEATURE_MASK_CET;
		}
	}
}

void initialize_td_bad(struct kvm_vm *vm)

{
	const struct kvm_cpuid2 *cpuid;
	int rc;

	/* No guest VMM controlled cpuid information yet. */
	struct kvm_tdx_init_vm init_vm;

	rc = kvm_check_cap(KVM_CAP_X2APIC_API);
	TEST_ASSERT(rc, "TDX: KVM_CAP_X2APIC_API is not supported!");
	rc = kvm_check_cap(KVM_CAP_SPLIT_IRQCHIP);
	TEST_ASSERT(rc, "TDX: KVM_CAP_SPLIT_IRQCHIP is not supported!");

	vm_enable_cap(vm, KVM_CAP_X2APIC_API,
		      KVM_X2APIC_API_USE_32BIT_IDS |
			      KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK);
	vm_enable_cap(vm, KVM_CAP_SPLIT_IRQCHIP, 24);

	/* Allocate and setup memory for the td guest. */
	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, 0, 0, 1, 0);

	cpuid = kvm_get_supported_cpuid();
	apply_tdx_restrictions((struct kvm_cpuid2 *) cpuid);

	memset(&init_vm, 0, sizeof(init_vm));
	init_vm.attributes = 0;

	/*
	 * Should have been kvm_cpuid2_size(cpuid->nent) instead of
	 * sizeof(*cpuid)
	 */
	memcpy(&init_vm.cpuid, cpuid, sizeof(*cpuid));

	rc = tdx_ioctl(vm->fd, KVM_TDX_INIT_VM, 0, &init_vm);
	TEST_ASSERT(rc == 0, "KVM_TDX_INIT_VM failed: %d %d", rc, errno);
}

static int crash(void)

{
	struct kvm_vm *vm;

	/* Create a TD VM with no memory.*/
	vm = ____vm_create(VM_MODE_DEFAULT, 0, KVM_X86_TDX_VM);

	/* Allocate TD guest memory and initialize the TD.*/
	initialize_td_bad(vm);

	return 0;
}

int main(int argc, char **argv)

{
	/* Disable stdout buffering */
	setbuf(stdout, NULL);

	return crash();
}
#44 lore raw

Re: [PATCH v10 016/108] KVM: TDX: create/destroy VM structure

In reply to [email protected]

On 10/30/2022 2:22 PM, [email protected] wrote:> +static void vt_hardware_unsetup(void)

Quoted 9 lines
arch/x86/kvm/vmx/main.c +5 -1
+{
+	tdx_hardware_unsetup();
+	vmx_hardware_unsetup();
+}
+
 static int vt_vm_init(struct kvm *kvm)
 {
 	if (is_td(kvm))
-		return -EOPNOTSUPP;	/* Not ready to create guest TD yet. */

arch/x86/kvm/vmx/main.c static __init int vt_hardware_setup(void) · line 50

Quoted 10 lines
arch/x86/kvm/vmx/main.c +6 -0
+		return tdx_vm_init(kvm);
 
 	return vmx_vm_init(kvm);
 }
 
+static void vt_flush_shadow_all_private(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_mmu_release_hkid(kvm);
+}

nit: there is no need to use the "return" keyword.

Quoted 4 lines
arch/x86/kvm/vmx/main.c +4 -0
+
+static void vt_vm_destroy(struct kvm *kvm)
+{
+	if (is_td(kvm))

arch/x86/kvm/vmx/main.c static __init int vt_hardware_setup(void) · line 64

Quoted 10 lines
arch/x86/kvm/vmx/main.c +10 -0
+		return;
+
+	vmx_vm_destroy(kvm);
+}
+
+static void vt_vm_free(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return tdx_vm_free(kvm);
+}

ditto.

#54 lore raw

Re: [PATCH v10 021/108] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]
Quoted 19 lines · On 10/30/2022 2:22 PM, [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.

Quoted 3 lines

This subcommand is called before creating vcpu and KVM_SET_CPUID2, i.e. cpuids configurations aren't available yet. So CPUIDs configuration values needs to be passed in struct kvm_init_vm. It's device model responsibility

I suppose this should be kvm_tdx_init_vm.

Quoted 128 lines

to make this cpuid config for KVM_TDX_INIT_VM and KVM_SET_CPUID2.

---
 arch/x86/include/asm/tdx.h            |   3 +
 arch/x86/include/uapi/asm/kvm.h       |  31 +++
 arch/x86/kvm/vmx/tdx.c                | 296 ++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.h                |  22 ++
 tools/arch/x86/include/uapi/asm/kvm.h |  33 +++
 5 files changed, 347 insertions(+), 38 deletions(-)
arch/x86/include/asm/tdx.h +3 -0
index cd304d323d33..05ac4bfc8f8a 100644
@@ -131,6 +131,9 @@ static inline long tdx_kvm_hypercall(unsigned int nr, unsigned long p1,
 #endif /* CONFIG_INTEL_TDX_GUEST && CONFIG_KVM_GUEST */
 
 #ifdef CONFIG_INTEL_TDX_HOST
+
+/* -1 indicates CPUID leaf with no sub-leaves. */
+#define TDX_CPUID_NO_SUBLEAF	((u32)-1)
 struct tdx_cpuid_config {
 	u32	leaf;
 	u32	sub_leaf;
arch/x86/include/uapi/asm/kvm.h +31 -0
index 2ad9666e02a5..26661879c031 100644
@@ -538,6 +538,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,
 };
@@ -583,4 +584,34 @@ struct kvm_tdx_capabilities {
 	struct kvm_tdx_cpuid_config cpuid_configs[0];
 };
 
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha348 digest */
+	union {
+		/*
+		 * KVM_TDX_INIT_VM is called before vcpu creation, thus before
+		 * KVM_SET_CPUID2.  CPUID configurations needs to be passed.
+		 *
+		 * This configuration supersedes KVM_SET_CPUID{,2}.
+		 * The user space VMM, e.g. qemu, should make them consistent
+		 * with this values.
+		 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(256)
+		 * = 8KB.
+		 */
+		struct {
+			struct kvm_cpuid2 cpuid;
+			/* 8KB with KVM_MAX_CPUID_ENTRIES. */
+			struct kvm_cpuid_entry2 entries[];
+		};
+		/*
+		 * For future extensibility.
+		 * The size(struct kvm_tdx_init_vm) = 16KB.
+		 * This should be enough given sizeof(TD_PARAMS) = 1024
+		 */
+		__u64 reserved[2029];
+	};
+};
+
 #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/tdx.c +47 -0
index d77709a6da51..54045e0576e7 100644
@@ -284,6 +284,205 @@ static int tdx_do_tdh_mng_key_config(void *param)
 int tdx_vm_init(struct kvm *kvm)
 {
 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+
+	kvm_tdx->hkid = -1;
+
+	/*
+	 * This function initializes only KVM software construct.  It doesn't
+	 * initialize TDX stuff, e.g. TDCS, TDR, TDCX, HKID etc.
+	 * It is handled by KVM_TDX_INIT_VM, __tdx_td_init().
+	 */
+
+	return 0;
+}
+
+int tdx_dev_ioctl(void __user *argp)
+{
+	struct kvm_tdx_capabilities __user *user_caps;
+	struct kvm_tdx_capabilities caps;
+	struct kvm_tdx_cmd cmd;
+
+	BUILD_BUG_ON(sizeof(struct kvm_tdx_cpuid_config) !=
+		     sizeof(struct tdx_cpuid_config));
+
+	if (copy_from_user(&cmd, argp, sizeof(cmd)))
+		return -EFAULT;
+	if (cmd.flags || cmd.error || cmd.unused)
+		return -EINVAL;
+	/*
+	 * Currently only KVM_TDX_CAPABILITIES is defined for system-scoped
+	 * mem_enc_ioctl().
+	 */
+	if (cmd.id != KVM_TDX_CAPABILITIES)
+		return -EINVAL;
+
+	user_caps = (void __user *)cmd.data;
+	if (copy_from_user(&caps, user_caps, sizeof(caps)))
+		return -EFAULT;
+
+	if (caps.nr_cpuid_configs < tdx_caps.nr_cpuid_configs)
+		return -E2BIG;
+
+	caps = (struct kvm_tdx_capabilities) {
+		.attrs_fixed0 = tdx_caps.attrs_fixed0,
+		.attrs_fixed1 = tdx_caps.attrs_fixed1,
+		.xfam_fixed0 = tdx_caps.xfam_fixed0,
+		.xfam_fixed1 = tdx_caps.xfam_fixed1,
+		.nr_cpuid_configs = tdx_caps.nr_cpuid_configs,
+		.padding = 0,
+	};

arch/x86/kvm/vmx/tdx.c static int tdx_do_tdh_mng_key_config(void *param) · line 343

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+	if (copy_to_user(user_caps, &caps, sizeof(caps)))
+		return -EFAULT;
+	if (copy_to_user(user_caps->cpuid_configs, &tdx_caps.cpuid_configs,
+			 tdx_caps.nr_cpuid_configs *
+			 sizeof(struct tdx_cpuid_config)))
+		return -EFAULT;
+
+	return 0;
+}

tdx_dev_ioctl() is introduced in previous patch with the same code added here, which means this is just a place change and it will confuse reviewers. Is it neccesary to do so?

Quoted 18 lines
arch/x86/kvm/vmx/tdx.c +18 -0
+
+/*
+ * cpuid entry lookup in TDX cpuid config way.
+ * The difference is how to specify index(subleaves).
+ * Specify index to TDX_CPUID_NO_SUBLEAF for CPUID leaf with no-subleaves.
+ */
+static const struct kvm_cpuid_entry2 *tdx_find_cpuid_entry(const struct kvm_cpuid2 *cpuid,
+							   u32 function, u32 index)
+{
+	int i;
+
+	/* In TDX CPU CONFIG, TDX_CPUID_NO_SUBLEAF means index = 0. */
+	if (index == TDX_CPUID_NO_SUBLEAF)
+		index = 0;
+
+	for (i = 0; i < cpuid->nent; i++) {
+		const struct kvm_cpuid_entry2 *e = &cpuid->entries[i];
+

arch/x86/kvm/vmx/tdx.c static int tdx_do_tdh_mng_key_config(void *param) · line 371

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		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)

Indentation is broken here, please fix it.

Quoted 262 lines
arch/x86/kvm/vmx/tdx.c +173 -38
+{
+	const struct kvm_cpuid2 *cpuid = &init_vm->cpuid;
+	const struct kvm_cpuid_entry2 *entry;
+	u64 guest_supported_xcr0;
+	u64 guest_supported_xss;
+	int max_pa;
+	int i;
+
+	if (kvm->created_vcpus)
+		return -EBUSY;
+	td_params->max_vcpus = kvm->max_vcpus;
+	td_params->attributes = init_vm->attributes;
+	if (td_params->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+		/*
+		 * TODO: save/restore PMU related registers around TDENTER.
+		 * Once it's done, remove this guard.
+		 */
+		pr_warn("TD doesn't support perfmon yet. KVM needs to save/restore "
+			"host perf registers properly.\n");
+		return -EOPNOTSUPP;
+	}
+
+	for (i = 0; i < tdx_caps.nr_cpuid_configs; i++) {
+		const struct tdx_cpuid_config *config = &tdx_caps.cpuid_configs[i];
+		const struct kvm_cpuid_entry2 *entry =
+			tdx_find_cpuid_entry(cpuid, config->leaf, config->sub_leaf);
+		struct tdx_cpuid_value *value = &td_params->cpuid_values[i];
+
+		if (!entry)
+			continue;
+
+		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(cpuid, 0x80000008, 0);
+	if (entry)
+		max_pa = entry->eax & 0xff;
+
+	td_params->eptp_controls = VMX_EPTP_MT_WB;
+	/*
+	 * No CPU supports 4-level && max_pa > 48.
+	 * "5-level paging and 5-level EPT" section 4.1 4-level EPT
+	 * "4-level EPT is limited to translating 48-bit guest-physical
+	 *  addresses."
+	 * cpu_has_vmx_ept_5levels() check is just in case.
+	 */
+	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;
+	}
+
+	/* Setup td_params.xfam */
+	entry = tdx_find_cpuid_entry(cpuid, 0xd, 0);
+	if (entry)
+		guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+	else
+		guest_supported_xcr0 = 0;
+	guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+	entry = tdx_find_cpuid_entry(cpuid, 0xd, 1);
+	if (entry)
+		guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+	else
+		guest_supported_xss = 0;
+	/* PT can be exposed to TD guest regardless of KVM's XSS support */
+	guest_supported_xss &= (kvm_caps.supported_xss | XFEATURE_MASK_PT);
+
+	td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+	if (td_params->xfam & XFEATURE_MASK_LBR) {
+		/*
+		 * TODO: once KVM supports LBR(save/restore LBR related
+		 * registers around TDENTER), remove this guard.
+		 */
+		pr_warn("TD doesn't support LBR yet. KVM needs to save/restore "
+			"IA32_LBR_DEPTH properly.\n");
+		return -EOPNOTSUPP;
+	}
+
+	if (td_params->xfam & XFEATURE_MASK_XTILE) {
+		/*
+		 * TODO: once KVM supports AMX(save/restore AMX related
+		 * registers around TDENTER), remove this guard.
+		 */
+		pr_warn("TD doesn't support AMX yet. KVM needs to save/restore "
+			"IA32_XFD, IA32_XFD_ERR properly.\n");
+		return -EOPNOTSUPP;
+	}
+
+	td_params->tsc_frequency =
+		TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
+
+#define MEMCPY_SAME_SIZE(dst, src)				\
+	do {							\
+		BUILD_BUG_ON(sizeof(dst) != sizeof(src));	\
+		memcpy((dst), (src), sizeof(dst));		\
+	} while (0)
+
+	MEMCPY_SAME_SIZE(td_params->mrconfigid, init_vm->mrconfigid);
+	MEMCPY_SAME_SIZE(td_params->mrowner, init_vm->mrowner);
+	MEMCPY_SAME_SIZE(td_params->mrownerconfig, init_vm->mrownerconfig);
+
+	return 0;
+}
+
+static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	struct tdx_module_output out;
 	cpumask_var_t packages;
 	int ret, i;
 	u64 err;
@@ -390,10 +589,13 @@ int tdx_vm_init(struct kvm *kvm)
 		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.
-	 */
+	err = tdh_mng_init(kvm_tdx->tdr.pa, __pa(td_params), &out);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_INIT, err, &out);
+		ret = -EIO;
+		goto teardown;
+	}
+
 	return 0;
 
 	/*
@@ -431,50 +633,65 @@ int tdx_vm_init(struct kvm *kvm)
 	return ret;
 }
 
-int tdx_dev_ioctl(void __user *argp)
+static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 {
-	struct kvm_tdx_capabilities __user *user_caps;
-	struct kvm_tdx_capabilities caps;
-	struct kvm_tdx_cmd cmd;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	struct kvm_tdx_init_vm *init_vm = NULL;
+	struct td_params *td_params = NULL;
+	void *entries_end;
+	int ret;
 
-	BUILD_BUG_ON(sizeof(struct kvm_tdx_cpuid_config) !=
-		     sizeof(struct tdx_cpuid_config));
+	BUILD_BUG_ON(sizeof(*init_vm) != 16 * 1024);
+	BUILD_BUG_ON((sizeof(*init_vm) - offsetof(typeof(*init_vm), entries)) /
+		     sizeof(init_vm->entries[0]) < KVM_MAX_CPUID_ENTRIES);
+	BUILD_BUG_ON(sizeof(struct td_params) != 1024);
 
-	if (copy_from_user(&cmd, argp, sizeof(cmd)))
-		return -EFAULT;
-	if (cmd.flags || cmd.error || cmd.unused)
+	if (is_td_initialized(kvm))
 		return -EINVAL;
-	/*
-	 * Currently only KVM_TDX_CAPABILITIES is defined for system-scoped
-	 * mem_enc_ioctl().
-	 */
-	if (cmd.id != KVM_TDX_CAPABILITIES)
+
+	if (cmd->flags)
 		return -EINVAL;
 
-	user_caps = (void __user *)cmd.data;
-	if (copy_from_user(&caps, user_caps, sizeof(caps)))
-		return -EFAULT;
+	init_vm = kzalloc(sizeof(*init_vm), GFP_KERNEL);
+	if (copy_from_user(init_vm, (void __user *)cmd->data, sizeof(*init_vm))) {
+		ret = -EFAULT;
+		goto out;
+	}
 
-	if (caps.nr_cpuid_configs < tdx_caps.nr_cpuid_configs)
-		return -E2BIG;
+	ret = -EINVAL;
+	if (init_vm->cpuid.padding)
+		goto out;
+	/* init_vm->entries shouldn't overrun. */
+	entries_end = init_vm->entries + init_vm->cpuid.nent;
+	if (entries_end > (void *)(init_vm + 1))
+		goto out;
+	/* Unused part must be zero. */
+	if (memchr_inv(entries_end, 0, (void *)(init_vm + 1) - entries_end))
+		goto out;
 
-	caps = (struct kvm_tdx_capabilities) {
-		.attrs_fixed0 = tdx_caps.attrs_fixed0,
-		.attrs_fixed1 = tdx_caps.attrs_fixed1,
-		.xfam_fixed0 = tdx_caps.xfam_fixed0,
-		.xfam_fixed1 = tdx_caps.xfam_fixed1,
-		.nr_cpuid_configs = tdx_caps.nr_cpuid_configs,
-		.padding = 0,
-	};
+	td_params = kzalloc(sizeof(struct td_params), GFP_KERNEL);
+	if (!td_params) {
+		ret = -ENOMEM;
+		goto out;
+	}
 
-	if (copy_to_user(user_caps, &caps, sizeof(caps)))
-		return -EFAULT;
-	if (copy_to_user(user_caps->cpuid_configs, &tdx_caps.cpuid_configs,
-			 tdx_caps.nr_cpuid_configs *
-			 sizeof(struct tdx_cpuid_config)))
-		return -EFAULT;
+	ret = setup_tdparams(kvm, td_params, init_vm);
+	if (ret)
+		goto out;
 
-	return 0;
+	ret = __tdx_td_init(kvm, td_params);
+	if (ret)
+		goto out;
+
+	kvm_tdx->tsc_offset = td_tdcs_exec_read64(kvm_tdx, TD_TDCS_EXEC_TSC_OFFSET);
+	kvm_tdx->attributes = td_params->attributes;
+	kvm_tdx->xfam = td_params->xfam;
+
+out:
+	/* kfree() accepts NULL. */
+	kfree(init_vm);
+	kfree(td_params);
+	return ret;
 }
 
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
@@ -490,6 +707,9 @@ int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
 	mutex_lock(&kvm->lock);
 
 	switch (tdx_cmd.id) {
+	case KVM_TDX_INIT_VM:
+		r = tdx_td_init(kvm, &tdx_cmd);
+		break;
 	default:
 		r = -EINVAL;
 		goto out;
arch/x86/kvm/vmx/tdx.h +4 -0
index 938314635b47..ff0ea9cad347 100644
@@ -18,7 +18,11 @@ struct kvm_tdx {
 	struct tdx_td_page tdr;
 	struct tdx_td_page *tdcs;
 
+	u64 attributes;
+	u64 xfam;
 	int hkid;
+
+	u64 tsc_offset;
 };
 
 struct vcpu_tdx {

arch/x86/kvm/vmx/tdx.h static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu) · line 58

Quoted 7 lines
arch/x86/kvm/vmx/tdx.h +4 -0
@@ -48,6 +52,11 @@ static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
 	return container_of(vcpu, struct vcpu_tdx, vcpu);
 }
 
+static inline bool is_td_initialized(struct kvm *kvm)
+{
+	return to_kvm_tdx(kvm)->hkid > 0;
+}

There is a similar function, is_hkid_assigned(), which is previously defined. Do you think redefining a new function here will bring code redundency?

Quoted 73 lines
arch/x86/kvm/vmx/tdx.h +14 -0
+
 static __always_inline void tdvps_vmcs_check(u32 field, u8 bits)
 {
 #define VMCS_ENC_ACCESS_TYPE_MASK	0x1UL
@@ -148,6 +157,19 @@ TDX_BUILD_TDVPS_ACCESSORS(64, VMCS, vmcs);
 TDX_BUILD_TDVPS_ACCESSORS(64, STATE_NON_ARCH, state_non_arch);
 TDX_BUILD_TDVPS_ACCESSORS(8, MANAGEMENT, management);
 
+static __always_inline u64 td_tdcs_exec_read64(struct kvm_tdx *kvm_tdx, u32 field)
+{
+	struct tdx_module_output out;
+	u64 err;
+
+	err = tdh_mng_rd(kvm_tdx->tdr.pa, TDCS_EXEC(field), &out);
+	if (unlikely(err)) {
+		pr_err("TDH_MNG_RD[EXEC.0x%x] failed: 0x%llx\n", field, err);
+		return 0;
+	}
+	return out.r8;
+}
+
 #else
 struct kvm_tdx {
 	struct kvm kvm;
tools/arch/x86/include/uapi/asm/kvm.h +33 -0
index 2ad9666e02a5..531a0033e530 100644
@@ -538,6 +538,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,
 };
@@ -583,4 +584,36 @@ struct kvm_tdx_capabilities {
 	struct kvm_tdx_cpuid_config cpuid_configs[0];
 };
 
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u32 max_vcpus;
+	__u32 padding;
+	__u64 mrconfigid[6];    /* sha384 digest */
+	__u64 mrowner[6];       /* sha384 digest */
+	__u64 mrownerconfig[6]; /* sha348 digest */
+	union {
+		/*
+		 * KVM_TDX_INIT_VM is called before vcpu creation, thus before
+		 * KVM_SET_CPUID2.  CPUID configurations needs to be passed.
+		 *
+		 * This configuration supersedes KVM_SET_CPUID{,2}.
+		 * The user space VMM, e.g. qemu, should make them consistent
+		 * with this values.
+		 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(256)
+		 * = 8KB.
+		 */
+		struct {
+			struct kvm_cpuid2 cpuid;
+			/* 8KB with KVM_MAX_CPUID_ENTRIES. */
+			struct kvm_cpuid_entry2 entries[];
+		};
+		/*
+		 * For future extensibility.
+		 * The size(struct kvm_tdx_init_vm) = 16KB.
+		 * This should be enough given sizeof(TD_PARAMS) = 1024
+		 */
+		__u64 reserved[2028];
+	};
+};
+
 #endif /* _ASM_X86_KVM_H */
#203 lore raw

Re: [PATCH v10 098/108] KVM: TDX: Implement callbacks for MSR operations for TDX

In reply to [email protected]

I believe we should also have a handler for .msr_filter_changed.

Without an .msr_filter_changed handler, a host crash can occur if we first set up a vcpu for the TD, and then set an MSR filter.

If we first set up a vcpu for the TD, and then set an MSR filter, upon vcpu_enter_guest, the .msr_filter_changed handler (currently vmx_msr_filter_changed()) will be invoked. to_vmx(vcpu) interprets the containing struct of struct kvm_vcpu to be a struct vcpu_vmx instead of a struct vcpu_tdx.

In my case, I was working on a selftest and the missing handler caused a NULL dereference in vmx_disable_intercept_for_msr() because vmx->vmcs01.msr_bitmap is NULL.

#12 lore raw

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to [email protected]
Quoted 13 lines · On Sat, Oct 29, 2022 at 11:24 PM <[email protected]> wrote:

From: Isaku Yamahata <[email protected]>

arch/x86/kvm/vmx/tdx.c new file +10 -0
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+       int r;
+
+       if (!enable_ept) {
+               pr_warn("Cannot enable TDX with EPT disabled\n");
+               return -EINVAL;
+       }
+
+       /* MOVDIR64B instruction is needed. */

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+       if (!static_cpu_has(X86_FEATURE_MOVDIR64B)) {
+               pr_warn("Cannot enable TDX with MOVDIR64B supported ");
+               return -ENODEV;
+       }
+
+       /* TDX requires VMX. */
+       r = vmxon_all();
+       if (!r)
+               r = tdx_module_setup();
+       vmxoff_all();

if few CPUs have VMX enabled, this will disable VMX in all of them. Depending on what enabled VMX on those CPUs, would this not cause kernel crashes/problems?

#13 lore raw

Re: [PATCH v10 005/108] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

Quoted 20 lines · Erdem Aktas
Quoted 19 lines · On Sat, Oct 29, 2022 at 11:24 PM <[email protected]> wrote:

From: Isaku Yamahata <[email protected]>

arch/x86/kvm/vmx/tdx.c new file +16 -0
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+       int r;
+
+       if (!enable_ept) {
+               pr_warn("Cannot enable TDX with EPT disabled\n");
+               return -EINVAL;
+       }
+
+       /* MOVDIR64B instruction is needed. */
+       if (!static_cpu_has(X86_FEATURE_MOVDIR64B)) {
+               pr_warn("Cannot enable TDX with MOVDIR64B supported ");
+               return -ENODEV;
+       }
+
+       /* TDX requires VMX. */
Quoted 8 lines

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c new file +4 -0
+       r = vmxon_all();
+       if (!r)
+               r = tdx_module_setup();
+       vmxoff_all();

if few CPUs have VMX enabled, this will disable VMX in all of them. Depending on what enabled VMX on those CPUs, would this not cause kernel crashes/problems?

Are you seeing any issues? or is this a question in theory?

In theory, you're right. In practice, unless we have other kernel components that uses VMX, we don't have to worry. In fact, only KVM in the kernel tree uses VMX.

The flow is as follows,
- VMX is off on all CPUs on start up.
NOTE: VMX is disabled on kexec or reboot.
- On loading kvm_intel.ko (or kernel boot if builtin), this function is called. vmxon/off_all()
- VMX is enabled on all online CPUs when creating the first guest.
- VMX is disabled on all online CPUs when destroying the last guest.
- VMX is disabled on offlining CPU

Thanks,

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

Re: [PATCH v10 021/108] KVM: TDX: initialize VM with TDX specific parameters

In reply to Wang, Lei
Quoted 160 lines · Lei
Quoted 19 lines · On 10/30/2022 2:22 PM, [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.

Quoted 3 lines

This subcommand is called before creating vcpu and KVM_SET_CPUID2, i.e. cpuids configurations aren't available yet. So CPUIDs configuration values needs to be passed in struct kvm_init_vm. It's device model responsibility

I suppose this should be kvm_tdx_init_vm.

Quoted 134 lines

to make this cpuid config for KVM_TDX_INIT_VM and KVM_SET_CPUID2.

---
 arch/x86/include/asm/tdx.h            |   3 +
 arch/x86/include/uapi/asm/kvm.h       |  31 +++
 arch/x86/kvm/vmx/tdx.c                | 296 ++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.h                |  22 ++
 tools/arch/x86/include/uapi/asm/kvm.h |  33 +++
 5 files changed, 347 insertions(+), 38 deletions(-)
arch/x86/include/asm/tdx.h +3 -0
index cd304d323d33..05ac4bfc8f8a 100644
@@ -131,6 +131,9 @@ static inline long tdx_kvm_hypercall(unsigned int nr, unsigned long p1,
 #endif /* CONFIG_INTEL_TDX_GUEST && CONFIG_KVM_GUEST */
 
 #ifdef CONFIG_INTEL_TDX_HOST
+
+/* -1 indicates CPUID leaf with no sub-leaves. */
+#define TDX_CPUID_NO_SUBLEAF	((u32)-1)
 struct tdx_cpuid_config {
 	u32	leaf;
 	u32	sub_leaf;
arch/x86/include/uapi/asm/kvm.h +31 -0
index 2ad9666e02a5..26661879c031 100644
@@ -538,6 +538,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,
 };
@@ -583,4 +584,34 @@ struct kvm_tdx_capabilities {
 	struct kvm_tdx_cpuid_config cpuid_configs[0];
 };
 
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha348 digest */
+	union {
+		/*
+		 * KVM_TDX_INIT_VM is called before vcpu creation, thus before
+		 * KVM_SET_CPUID2.  CPUID configurations needs to be passed.
+		 *
+		 * This configuration supersedes KVM_SET_CPUID{,2}.
+		 * The user space VMM, e.g. qemu, should make them consistent
+		 * with this values.
+		 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(256)
+		 * = 8KB.
+		 */
+		struct {
+			struct kvm_cpuid2 cpuid;
+			/* 8KB with KVM_MAX_CPUID_ENTRIES. */
+			struct kvm_cpuid_entry2 entries[];
+		};
+		/*
+		 * For future extensibility.
+		 * The size(struct kvm_tdx_init_vm) = 16KB.
+		 * This should be enough given sizeof(TD_PARAMS) = 1024
+		 */
+		__u64 reserved[2029];
+	};
+};
+
 #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/tdx.c +53 -0
index d77709a6da51..54045e0576e7 100644
@@ -284,6 +284,205 @@ static int tdx_do_tdh_mng_key_config(void *param)
 int tdx_vm_init(struct kvm *kvm)
 {
 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+
+	kvm_tdx->hkid = -1;
+
+	/*
+	 * This function initializes only KVM software construct.  It doesn't
+	 * initialize TDX stuff, e.g. TDCS, TDR, TDCX, HKID etc.
+	 * It is handled by KVM_TDX_INIT_VM, __tdx_td_init().
+	 */
+
+	return 0;
+}
+
+int tdx_dev_ioctl(void __user *argp)
+{
+	struct kvm_tdx_capabilities __user *user_caps;
+	struct kvm_tdx_capabilities caps;
+	struct kvm_tdx_cmd cmd;
+
+	BUILD_BUG_ON(sizeof(struct kvm_tdx_cpuid_config) !=
+		     sizeof(struct tdx_cpuid_config));
+
+	if (copy_from_user(&cmd, argp, sizeof(cmd)))
+		return -EFAULT;
+	if (cmd.flags || cmd.error || cmd.unused)
+		return -EINVAL;
+	/*
+	 * Currently only KVM_TDX_CAPABILITIES is defined for system-scoped
+	 * mem_enc_ioctl().
+	 */
+	if (cmd.id != KVM_TDX_CAPABILITIES)
+		return -EINVAL;
+
+	user_caps = (void __user *)cmd.data;
+	if (copy_from_user(&caps, user_caps, sizeof(caps)))
+		return -EFAULT;
+
+	if (caps.nr_cpuid_configs < tdx_caps.nr_cpuid_configs)
+		return -E2BIG;
+
+	caps = (struct kvm_tdx_capabilities) {
+		.attrs_fixed0 = tdx_caps.attrs_fixed0,
+		.attrs_fixed1 = tdx_caps.attrs_fixed1,
+		.xfam_fixed0 = tdx_caps.xfam_fixed0,
+		.xfam_fixed1 = tdx_caps.xfam_fixed1,
+		.nr_cpuid_configs = tdx_caps.nr_cpuid_configs,
+		.padding = 0,
+	};
+
+	if (copy_to_user(user_caps, &caps, sizeof(caps)))
+		return -EFAULT;
+	if (copy_to_user(user_caps->cpuid_configs, &tdx_caps.cpuid_configs,
+			 tdx_caps.nr_cpuid_configs *
+			 sizeof(struct tdx_cpuid_config)))
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_do_tdh_mng_key_config(void *param) · line 343

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+		return -EFAULT;
+
+	return 0;
+}

tdx_dev_ioctl() is introduced in previous patch with the same code added here, which means this is just a place change and it will confuse reviewers. Is it neccesary to do so?

Right. Somehow diff was also confused. I'll try to twist the previous patch to introduce __tdx_td_init() with the previous patch.

...

Quoted 7 lines

arch/x86/kvm/vmx/tdx.c static int tdx_do_tdh_mng_key_config(void *param) · line 347

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+static inline bool is_td_initialized(struct kvm *kvm)
+{
+	return to_kvm_tdx(kvm)->hkid > 0;
+}

There is a similar function, is_hkid_assigned(), which is previously defined. Do you think redefining a new function here will bring code redundency?

I'll drop this function and replace it with is_hkid_assigned().

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

Re: [PATCH v10 098/108] KVM: TDX: Implement callbacks for MSR operations for TDX

In reply to Ackerley Tng
Quoted 12 lines · Ackerley Tng

I believe we should also have a handler for .msr_filter_changed.

Without an .msr_filter_changed handler, a host crash can occur if we first set up a vcpu for the TD, and then set an MSR filter.

If we first set up a vcpu for the TD, and then set an MSR filter, upon vcpu_enter_guest, the .msr_filter_changed handler (currently vmx_msr_filter_changed()) will be invoked. to_vmx(vcpu) interprets the containing struct of struct kvm_vcpu to be a struct vcpu_vmx instead of a struct vcpu_tdx.

Quoted 3 lines

In my case, I was working on a selftest and the missing handler caused a NULL dereference in vmx_disable_intercept_for_msr() because vmx->vmcs01.msr_bitmap is NULL.

Nice catch. I'll fix it.

Signature · 1 line
Isaku Yamahata <[email protected]>