Skip to contentSkip to conversation

KVM TDX basic feature support

PATCH In review [email protected] 21 participants 695 messages Feb 26, 2024 – Jul 18, 2024 Page 2 of 6

Subsystems (8)
Documentation x86 KVM Kselftest +4 more subsystems
lore
Share & tools
lore
#581 lore raw

PATCH v19 102/130 KVM: TDX: handle EXCEPTION_NMI and EXTERNAL_INTERRUPT

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Because guest TD state is protected, exceptions in guest TDs can't be intercepted. TDX VMM doesn't need to handle exceptions. tdx_handle_exit_irqoff() handles NMI and machine check. Ignore NMI and machine check and continue guest TD execution.

For external interrupt, increment stats same to the VMX case.

---
 arch/x86/kvm/vmx/tdx.c | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
arch/x86/kvm/vmx/tdx.c +23 -0
index 0db80fa020d2..bdd74682b474 100644
@@ -918,6 +918,25 @@ void tdx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
 		vmx_handle_exception_irqoff(vcpu, tdexit_intr_info(vcpu));
 }
 
+static int tdx_handle_exception(struct kvm_vcpu *vcpu)
+{
+	u32 intr_info = tdexit_intr_info(vcpu);
+
+	if (is_nmi(intr_info) || is_machine_check(intr_info))
+		return 1;
+
+	kvm_pr_unimpl("unexpected exception 0x%x(exit_reason 0x%llx qual 0x%lx)\n",
+		intr_info,
+		to_tdx(vcpu)->exit_reason.full, tdexit_exit_qual(vcpu));
+	return -EFAULT;
+}
+
+static int tdx_handle_external_interrupt(struct kvm_vcpu *vcpu)
+{
+	++vcpu->stat.irq_exits;
+	return 1;
+}
+
 static int tdx_handle_triple_fault(struct kvm_vcpu *vcpu)
 {
 	vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
@@ -1390,6 +1409,10 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
 	WARN_ON_ONCE(fastpath != EXIT_FASTPATH_NONE);
 
 	switch (exit_reason.basic) {
+	case EXIT_REASON_EXCEPTION_NMI:
+		return tdx_handle_exception(vcpu);
+	case EXIT_REASON_EXTERNAL_INTERRUPT:
+		return tdx_handle_external_interrupt(vcpu);
 	case EXIT_REASON_EPT_VIOLATION:
 		return tdx_handle_ept_violation(vcpu);
 	case EXIT_REASON_EPT_MISCONFIG:
Signature · 1 line
2.25.1
#586 lore raw

PATCH v19 103/130 KVM: TDX: Handle EXIT_REASON_OTHER_SMI with MSMI

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

When BIOS eMCA MCE-SMI morphing is enabled, the #MC is morphed to MSMI (Machine Check System Management Interrupt). Then the SMI causes TD exit with the read reason of EXIT_REASON_OTHER_SMI with MSMI bit set in the exit qualification to KVM instead of EXIT_REASON_EXCEPTION_NMI with MC exception.

Handle EXIT_REASON_OTHER_SMI with MSMI bit set in the exit qualification as MCE(Machine Check Exception) happened during TD guest running.

---
 arch/x86/kvm/vmx/tdx.c      | 40 ++++++++++++++++++++++++++++++++++---
 arch/x86/kvm/vmx/tdx_arch.h |  2 ++
 2 files changed, 39 insertions(+), 3 deletions(-)
arch/x86/kvm/vmx/tdx.c +37 -3
index bdd74682b474..117c2315f087 100644
@@ -916,6 +916,30 @@ void tdx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
 						     tdexit_intr_info(vcpu));
 	else if (exit_reason == EXIT_REASON_EXCEPTION_NMI)
 		vmx_handle_exception_irqoff(vcpu, tdexit_intr_info(vcpu));
+	else if (unlikely(tdx->exit_reason.non_recoverable ||
+		 tdx->exit_reason.error)) {
+		/*
+		 * The only reason it gets EXIT_REASON_OTHER_SMI is there is an
+		 * #MSMI(Machine Check System Management Interrupt) with
+		 * exit_qualification bit 0 set in TD guest.
+		 * The #MSMI is delivered right after SEAMCALL returns,
+		 * and an #MC is delivered to host kernel after SMI handler
+		 * returns.
+		 *
+		 * The #MC right after SEAMCALL is fixed up and skipped in #MC
+		 * handler because it's an #MC happens in TD guest we cannot
+		 * handle it with host's context.
+		 *
+		 * Call KVM's machine check handler explicitly here.
+		 */
+		if (tdx->exit_reason.basic == EXIT_REASON_OTHER_SMI) {
+			unsigned long exit_qual;
+
+			exit_qual = tdexit_exit_qual(vcpu);
+			if (exit_qual & TD_EXIT_OTHER_SMI_IS_MSMI)
+				kvm_machine_check();
+		}
+	}
 }
 
 static int tdx_handle_exception(struct kvm_vcpu *vcpu)
@@ -1381,6 +1405,11 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
 			      exit_reason.full, exit_reason.basic,
 			      to_kvm_tdx(vcpu->kvm)->hkid,
 			      set_hkid_to_hpa(0, to_kvm_tdx(vcpu->kvm)->hkid));
+
+		/*
+		 * tdx_handle_exit_irqoff() handled EXIT_REASON_OTHER_SMI.  It
+		 * must be handled before enabling preemption because it's #MC.
+		 */
 		goto unhandled_exit;
 	}
 
@@ -1419,9 +1448,14 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
 		return tdx_handle_ept_misconfig(vcpu);
 	case EXIT_REASON_OTHER_SMI:
 		/*
-		 * If reach here, it's not a Machine Check System Management
-		 * Interrupt(MSMI).  #SMI is delivered and handled right after
-		 * SEAMRET, nothing needs to be done in KVM.
+		 * Unlike VMX, all the SMI in SEAM non-root mode (i.e. when
+		 * TD guest vcpu is running) will cause TD exit to TDX module,
+		 * then SEAMRET to KVM. Once it exits to KVM, SMI is delivered
+		 * and handled right away.
+		 *
+		 * - If it's an Machine Check System Management Interrupt
+		 *   (MSMI), it's handled above due to non_recoverable bit set.
+		 * - If it's not an MSMI, don't need to do anything here.
 		 */
 		return 1;
 	default:
arch/x86/kvm/vmx/tdx_arch.h +2 -0
index efc3c61c14ab..87ef22e9cd49 100644
@@ -42,6 +42,8 @@
 #define TDH_VP_WR			43
 #define TDH_SYS_LP_SHUTDOWN		44
 
+#define TD_EXIT_OTHER_SMI_IS_MSMI	BIT(1)
+
 /* TDX control structure (TDR/TDCS/TDVPS) field access codes */
 #define TDX_NON_ARCH			BIT_ULL(63)
 #define TDX_CLASS_SHIFT			56
Signature · 1 line
2.25.1
#591 lore raw

PATCH v19 104/130 KVM: TDX: Add a place holder for handler of TDX hypercalls (TDG.VP.VMCALL)

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

The TDX module specification defines TDG.VP.VMCALL API (TDVMCALL for short) for the guest TD to call hypercall to VMM. When the guest TD issues TDG.VP.VMCALL, the guest TD exits to VMM with a new exit reason of TDVMCALL. The arguments from the guest TD and returned values from the VMM are passed in the guest registers. The guest RCX registers indicates which registers are used. Define helper functions to access those registers as ABI.

Define the TDVMCALL exit reason, which is carved out from the VMX exit reason namespace as the TDVMCALL exit from TDX guest to TDX-SEAM is really just a VM-Exit. Add a place holder to handle TDVMCALL exit.

---
 arch/x86/include/uapi/asm/vmx.h |  4 ++-
 arch/x86/kvm/vmx/tdx.c          | 53 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h          | 13 ++++++++
 3 files changed, 69 insertions(+), 1 deletion(-)
arch/x86/include/uapi/asm/vmx.h +3 -1
index b3a30ef3efdd..f0f4a4cf84a7 100644
@@ -93,6 +93,7 @@
 #define EXIT_REASON_TPAUSE              68
 #define EXIT_REASON_BUS_LOCK            74
 #define EXIT_REASON_NOTIFY              75
+#define EXIT_REASON_TDCALL              77
 
 #define VMX_EXIT_REASONS \
 	{ EXIT_REASON_EXCEPTION_NMI,         "EXCEPTION_NMI" }, \
@@ -156,7 +157,8 @@
 	{ EXIT_REASON_UMWAIT,                "UMWAIT" }, \
 	{ EXIT_REASON_TPAUSE,                "TPAUSE" }, \
 	{ EXIT_REASON_BUS_LOCK,              "BUS_LOCK" }, \
-	{ EXIT_REASON_NOTIFY,                "NOTIFY" }
+	{ EXIT_REASON_NOTIFY,                "NOTIFY" }, \
+	{ EXIT_REASON_TDCALL,                "TDCALL" }
 
 #define VMX_EXIT_REASON_FLAGS \
 	{ VMX_EXIT_REASONS_FAILED_VMENTRY,	"FAILED_VMENTRY" }
arch/x86/kvm/vmx/tdx.c +53 -0

77 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.h +13 -0
index eaffa7384725..4399d474764f 100644
@@ -83,6 +83,19 @@ struct vcpu_tdx {
 
 	struct list_head cpu_list;
 
+	union {
+		struct {
+			union {
+				struct {
+					u16 gpr_mask;
+					u16 xmm_mask;
+				};
+				u32 regs_mask;
+			};
+			u32 reserved;
+		};
+		u64 rcx;
+	} tdvmcall;
 	union tdx_exit_reason exit_reason;
 
 	bool initialized;
Signature · 1 line
2.25.1
#594 lore raw

PATCH v19 105/130 KVM: TDX: handle KVM hypercall with TDG.VP.VMCALL

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

The TDX Guest-Host communication interface (GHCI) specification defines
the ABI for the guest TD to issue hypercall. It reserves vendor specific
arguments for VMM specific use. Use it as KVM hypercall and handle it.

---
 arch/x86/kvm/vmx/tdx.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/x86/kvm/vmx/tdx.c +33 -0
index 0be58cd428b3..c8eb47591105 100644
@@ -1008,8 +1008,41 @@ static int tdx_handle_triple_fault(struct kvm_vcpu *vcpu)
 	return 0;
 }
 
+static int tdx_emulate_vmcall(struct kvm_vcpu *vcpu)
+{
+	unsigned long nr, a0, a1, a2, a3, ret;
+
+	/*
+	 * ABI for KVM tdvmcall argument:
+	 * In Guest-Hypervisor Communication Interface(GHCI) specification,
+	 * Non-zero leaf number (R10 != 0) is defined to indicate
+	 * vendor-specific.  KVM uses this for KVM hypercall.  NOTE: KVM
+	 * hypercall number starts from one.  Zero isn't used for KVM hypercall
+	 * number.
+	 *
+	 * R10: KVM hypercall number
+	 * arguments: R11, R12, R13, R14.
+	 */
+	nr = kvm_r10_read(vcpu);
+	a0 = kvm_r11_read(vcpu);
+	a1 = kvm_r12_read(vcpu);
+	a2 = kvm_r13_read(vcpu);
+	a3 = kvm_r14_read(vcpu);
+
+	ret = __kvm_emulate_hypercall(vcpu, nr, a0, a1, a2, a3, true, 0);
+
+	tdvmcall_set_return_code(vcpu, ret);
+
+	if (nr == KVM_HC_MAP_GPA_RANGE && !ret)
+		return 0;
+	return 1;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
+	if (tdvmcall_exit_type(vcpu))
+		return tdx_emulate_vmcall(vcpu);
+
 	switch (tdvmcall_leaf(vcpu)) {
 	default:
 		break;
Signature · 1 line
2.25.1
#601 lore raw

PATCH v19 106/130 KVM: TDX: Add KVM Exit for TDX TDG.VP.VMCALL

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Some of TDG.VP.VMCALL require device model, for example, qemu, to handle them on behalf of kvm kernel module. TDVMCALL_REPORT_FATAL_ERROR, TDVMCALL_MAP_GPA, TDVMCALL_SETUP_EVENT_NOTIFY_INTERRUPT, and TDVMCALL_GET_QUOTE requires user space VMM handling.

Introduce new kvm exit, KVM_EXIT_TDX, and functions to setup it. Device model should update R10 if necessary as return value.

---
v14 -> v15:
- updated struct kvm_tdx_exit with union
- export constants for reg bitmask

---
 arch/x86/kvm/vmx/tdx.c   | 83 ++++++++++++++++++++++++++++++++++++-
 include/uapi/linux/kvm.h | 89 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 170 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/tdx.c +81 -2
index c8eb47591105..72dbe2ff9062 100644
@@ -1038,6 +1038,78 @@ static int tdx_emulate_vmcall(struct kvm_vcpu *vcpu)
 	return 1;
 }
 
+static int tdx_complete_vp_vmcall(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx_vmcall *tdx_vmcall = &vcpu->run->tdx.u.vmcall;
+	__u64 reg_mask = kvm_rcx_read(vcpu);
+
+#define COPY_REG(MASK, REG)							\
+	do {									\
+		if (reg_mask & TDX_VMCALL_REG_MASK_ ## MASK)			\
+			kvm_## REG ## _write(vcpu, tdx_vmcall->out_ ## REG);	\
+	} while (0)
+
+
+	COPY_REG(R10, r10);
+	COPY_REG(R11, r11);
+	COPY_REG(R12, r12);
+	COPY_REG(R13, r13);
+	COPY_REG(R14, r14);
+	COPY_REG(R15, r15);
+	COPY_REG(RBX, rbx);
+	COPY_REG(RDI, rdi);
+	COPY_REG(RSI, rsi);
+	COPY_REG(R8, r8);
+	COPY_REG(R9, r9);
+	COPY_REG(RDX, rdx);
+
+#undef COPY_REG
+
+	return 1;
+}
+
+static int tdx_vp_vmcall_to_user(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx_vmcall *tdx_vmcall = &vcpu->run->tdx.u.vmcall;
+	__u64 reg_mask;
+
+	vcpu->arch.complete_userspace_io = tdx_complete_vp_vmcall;
+	memset(tdx_vmcall, 0, sizeof(*tdx_vmcall));
+
+	vcpu->run->exit_reason = KVM_EXIT_TDX;
+	vcpu->run->tdx.type = KVM_EXIT_TDX_VMCALL;
+
+	reg_mask = kvm_rcx_read(vcpu);
+	tdx_vmcall->reg_mask = reg_mask;
+
+#define COPY_REG(MASK, REG)							\
+	do {									\
+		if (reg_mask & TDX_VMCALL_REG_MASK_ ## MASK) {			\
+			tdx_vmcall->in_ ## REG = kvm_ ## REG ## _read(vcpu);	\
+			tdx_vmcall->out_ ## REG = tdx_vmcall->in_ ## REG;	\
+		}								\
+	} while (0)
+
+
+	COPY_REG(R10, r10);
+	COPY_REG(R11, r11);
+	COPY_REG(R12, r12);
+	COPY_REG(R13, r13);
+	COPY_REG(R14, r14);
+	COPY_REG(R15, r15);
+	COPY_REG(RBX, rbx);
+	COPY_REG(RDI, rdi);
+	COPY_REG(RSI, rsi);
+	COPY_REG(R8, r8);
+	COPY_REG(R9, r9);
+	COPY_REG(RDX, rdx);
+
+#undef COPY_REG
+
+	/* notify userspace to handle the request */
+	return 0;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
@@ -1048,8 +1120,15 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 		break;
 	}
 
-	tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
-	return 1;
+	/*
+	 * Unknown VMCALL.  Toss the request to the user space VMM, e.g. qemu,
+	 * as it may know how to handle.
+	 *
+	 * Those VMCALLs require user space VMM:
+	 * TDVMCALL_REPORT_FATAL_ERROR, TDVMCALL_MAP_GPA,
+	 * TDVMCALL_SETUP_EVENT_NOTIFY_INTERRUPT, and TDVMCALL_GET_QUOTE.
+	 */
+	return tdx_vp_vmcall_to_user(vcpu);
 }
 
 void tdx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int pgd_level)
include/uapi/linux/kvm.h +89 -0

107 lines not on this page · raw message

Signature · 1 line
2.25.1
#605 lore raw

PATCH v19 107/130 KVM: TDX: Handle TDX PV CPUID hypercall

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Wire up TDX PV CPUID hypercall to the KVM backend function.

---
 arch/x86/kvm/vmx/tdx.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
arch/x86/kvm/vmx/tdx.c +22 -0
index 72dbe2ff9062..eb68d6c148b6 100644
@@ -1110,12 +1110,34 @@ static int tdx_vp_vmcall_to_user(struct kvm_vcpu *vcpu)
 	return 0;
 }
 
+static int tdx_emulate_cpuid(struct kvm_vcpu *vcpu)
+{
+	u32 eax, ebx, ecx, edx;
+
+	/* EAX and ECX for cpuid is stored in R12 and R13. */
+	eax = tdvmcall_a0_read(vcpu);
+	ecx = tdvmcall_a1_read(vcpu);
+
+	kvm_cpuid(vcpu, &eax, &ebx, &ecx, &edx, false);
+
+	tdvmcall_a0_write(vcpu, eax);
+	tdvmcall_a1_write(vcpu, ebx);
+	tdvmcall_a2_write(vcpu, ecx);
+	tdvmcall_a3_write(vcpu, edx);
+
+	tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+
+	return 1;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
 		return tdx_emulate_vmcall(vcpu);
 
 	switch (tdvmcall_leaf(vcpu)) {
+	case EXIT_REASON_CPUID:
+		return tdx_emulate_cpuid(vcpu);
 	default:
 		break;
 	}
Signature · 1 line
2.25.1
#606 lore raw

PATCH v19 108/130 KVM: TDX: Handle TDX PV HLT hypercall

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Wire up TDX PV HLT hypercall to the KVM backend function.

---
v19:
- move tdvps_state_non_arch_check() to this patch

v18:
- drop buggy_hlt_workaround and use TDH.VP.RD(TD_VCPU_STATE_DETAILS)

---
 arch/x86/kvm/vmx/tdx.c | 26 +++++++++++++++++++++++++-
 arch/x86/kvm/vmx/tdx.h |  4 ++++
 2 files changed, 29 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/tdx.c +25 -1
index eb68d6c148b6..a2caf2ae838c 100644
@@ -688,7 +688,18 @@ void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 
 bool tdx_protected_apic_has_interrupt(struct kvm_vcpu *vcpu)
 {
-	return pi_has_pending_interrupt(vcpu);
+	bool ret = pi_has_pending_interrupt(vcpu);
+	union tdx_vcpu_state_details details;
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+	if (ret || vcpu->arch.mp_state != KVM_MP_STATE_HALTED)
+		return true;
+
+	if (tdx->interrupt_disabled_hlt)
+		return false;
+
+	details.full = td_state_non_arch_read64(tdx, TD_VCPU_STATE_DETAILS_NON_ARCH);
+	return !!details.vmxip;
 }
 
 void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
@@ -1130,6 +1141,17 @@ static int tdx_emulate_cpuid(struct kvm_vcpu *vcpu)
 	return 1;
 }
 
+static int tdx_emulate_hlt(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+	/* See tdx_protected_apic_has_interrupt() to avoid heavy seamcall */
+	tdx->interrupt_disabled_hlt = tdvmcall_a0_read(vcpu);
+
+	tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+	return kvm_emulate_halt_noskip(vcpu);
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
@@ -1138,6 +1160,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 	switch (tdvmcall_leaf(vcpu)) {
 	case EXIT_REASON_CPUID:
 		return tdx_emulate_cpuid(vcpu);
+	case EXIT_REASON_HLT:
+		return tdx_emulate_hlt(vcpu);
 	default:
 		break;
 	}
arch/x86/kvm/vmx/tdx.h +4 -0
index 4399d474764f..11c74c34555f 100644
@@ -104,6 +104,8 @@ struct vcpu_tdx {
 	bool host_state_need_restore;
 	u64 msr_host_kernel_gs_base;
 
+	bool interrupt_disabled_hlt;
+
 	/*
 	 * Dummy to make pmu_intel not corrupt memory.
 	 * TODO: Support PMU for TDX.  Future work.
@@ -166,6 +168,7 @@ static __always_inline void tdvps_vmcs_check(u32 field, u8 bits)
 }
 
 static __always_inline void tdvps_management_check(u64 field, u8 bits) {}
+static __always_inline void tdvps_state_non_arch_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,	\
@@ -226,6 +229,7 @@ TDX_BUILD_TDVPS_ACCESSORS(32, VMCS, vmcs);
 TDX_BUILD_TDVPS_ACCESSORS(64, VMCS, vmcs);
 
 TDX_BUILD_TDVPS_ACCESSORS(8, MANAGEMENT, management);
+TDX_BUILD_TDVPS_ACCESSORS(64, STATE_NON_ARCH, state_non_arch);
 
 static __always_inline u64 td_tdcs_exec_read64(struct kvm_tdx *kvm_tdx, u32 field)
 {
Signature · 1 line
2.25.1
#612 lore raw

PATCH v19 109/130 KVM: TDX: Handle TDX PV port io hypercall

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Wire up TDX PV port IO hypercall to the KVM backend function.

---
v18:
- Fix out case to set R10 and R11 correctly when user space handled port out.

---
 arch/x86/kvm/vmx/tdx.c | 67 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
arch/x86/kvm/vmx/tdx.c +67 -0
index a2caf2ae838c..55fc6cc6c816 100644
@@ -1152,6 +1152,71 @@ static int tdx_emulate_hlt(struct kvm_vcpu *vcpu)
 	return kvm_emulate_halt_noskip(vcpu);
 }
 
+static int tdx_complete_pio_out(struct kvm_vcpu *vcpu)
+{
+	tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+	tdvmcall_set_return_val(vcpu, 0);
+	return 1;
+}
+
+static int tdx_complete_pio_in(struct kvm_vcpu *vcpu)
+{
+	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
+	unsigned long val = 0;
+	int ret;
+
+	WARN_ON_ONCE(vcpu->arch.pio.count != 1);
+
+	ret = ctxt->ops->pio_in_emulated(ctxt, vcpu->arch.pio.size,
+					 vcpu->arch.pio.port, &val, 1);
+	WARN_ON_ONCE(!ret);
+
+	tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+	tdvmcall_set_return_val(vcpu, val);
+
+	return 1;
+}
+
+static int tdx_emulate_io(struct kvm_vcpu *vcpu)
+{
+	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
+	unsigned long val = 0;
+	unsigned int port;
+	int size, ret;
+	bool write;
+
+	++vcpu->stat.io_exits;
+
+	size = tdvmcall_a0_read(vcpu);
+	write = tdvmcall_a1_read(vcpu);
+	port = tdvmcall_a2_read(vcpu);
+
+	if (size != 1 && size != 2 && size != 4) {
+		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
+		return 1;
+	}
+
+	if (write) {
+		val = tdvmcall_a3_read(vcpu);
+		ret = ctxt->ops->pio_out_emulated(ctxt, size, port, &val, 1);
+
+		/* No need for a complete_userspace_io callback. */
+		vcpu->arch.pio.count = 0;
+	} else
+		ret = ctxt->ops->pio_in_emulated(ctxt, size, port, &val, 1);
+
+	if (ret)
+		tdvmcall_set_return_val(vcpu, val);
+	else {
+		if (write)
+			vcpu->arch.complete_userspace_io = tdx_complete_pio_out;
+		else
+			vcpu->arch.complete_userspace_io = tdx_complete_pio_in;
+	}
+
+	return ret;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
@@ -1162,6 +1227,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 		return tdx_emulate_cpuid(vcpu);
 	case EXIT_REASON_HLT:
 		return tdx_emulate_hlt(vcpu);
+	case EXIT_REASON_IO_INSTRUCTION:
+		return tdx_emulate_io(vcpu);
 	default:
 		break;
 	}
Signature · 1 line
2.25.1
#617 lore raw

PATCH v19 110/130 KVM: TDX: Handle TDX PV MMIO hypercall

In reply to [email protected]

From: Sean Christopherson <[email protected]>

Export kvm_io_bus_read and kvm_mmio tracepoint and wire up TDX PV MMIO hypercall to the KVM backend functions.

kvm_io_bus_read/write() searches KVM device emulated in kernel of the given MMIO address and emulates the MMIO. As TDX PV MMIO also needs it, export kvm_io_bus_read(). kvm_io_bus_write() is already exported. TDX PV MMIO emulates some of MMIO itself. To add trace point consistently with x86 kvm, export kvm_mmio tracepoint.

---
 arch/x86/kvm/vmx/tdx.c | 114 +++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/x86.c     |   1 +
 virt/kvm/kvm_main.c    |   2 +
 3 files changed, 117 insertions(+)
arch/x86/kvm/vmx/tdx.c +114 -0
index 55fc6cc6c816..389bb95d2af0 100644
@@ -1217,6 +1217,118 @@ static int tdx_emulate_io(struct kvm_vcpu *vcpu)
 	return ret;
 }
 
+static int tdx_complete_mmio(struct kvm_vcpu *vcpu)
+{
+	unsigned long val = 0;
+	gpa_t gpa;
+	int size;
+
+	KVM_BUG_ON(vcpu->mmio_needed != 1, vcpu->kvm);
+	vcpu->mmio_needed = 0;
+
+	if (!vcpu->mmio_is_write) {
+		gpa = vcpu->mmio_fragments[0].gpa;
+		size = vcpu->mmio_fragments[0].len;
+
+		memcpy(&val, vcpu->run->mmio.data, size);
+		tdvmcall_set_return_val(vcpu, val);
+		trace_kvm_mmio(KVM_TRACE_MMIO_READ, size, gpa, &val);
+	}
+	return 1;
+}
+
+static inline int tdx_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, int size,
+				 unsigned long val)
+{
+	if (kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, gpa, size, &val) &&
+	    kvm_io_bus_write(vcpu, KVM_MMIO_BUS, gpa, size, &val))
+		return -EOPNOTSUPP;
+
+	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, size, gpa, &val);
+	return 0;
+}
+
+static inline int tdx_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, int size)
+{
+	unsigned long val;
+
+	if (kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev, gpa, size, &val) &&
+	    kvm_io_bus_read(vcpu, KVM_MMIO_BUS, gpa, size, &val))
+		return -EOPNOTSUPP;
+
+	tdvmcall_set_return_val(vcpu, val);
+	trace_kvm_mmio(KVM_TRACE_MMIO_READ, size, gpa, &val);
+	return 0;
+}
+
+static int tdx_emulate_mmio(struct kvm_vcpu *vcpu)
+{
+	struct kvm_memory_slot *slot;
+	int size, write, r;
+	unsigned long val;
+	gpa_t gpa;
+
+	KVM_BUG_ON(vcpu->mmio_needed, vcpu->kvm);
+
+	size = tdvmcall_a0_read(vcpu);
+	write = tdvmcall_a1_read(vcpu);
+	gpa = tdvmcall_a2_read(vcpu);
+	val = write ? tdvmcall_a3_read(vcpu) : 0;
+
+	if (size != 1 && size != 2 && size != 4 && size != 8)
+		goto error;
+	if (write != 0 && write != 1)
+		goto error;
+
+	/* Strip the shared bit, allow MMIO with and without it set. */
+	gpa = gpa & ~gfn_to_gpa(kvm_gfn_shared_mask(vcpu->kvm));
+
+	if (size > 8u || ((gpa + size - 1) ^ gpa) & PAGE_MASK)
+		goto error;
+
+	slot = kvm_vcpu_gfn_to_memslot(vcpu, gpa_to_gfn(gpa));
+	if (slot && !(slot->flags & KVM_MEMSLOT_INVALID))
+		goto error;
+
+	if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
+		trace_kvm_fast_mmio(gpa);
+		return 1;
+	}
+
+	if (write)
+		r = tdx_mmio_write(vcpu, gpa, size, val);
+	else
+		r = tdx_mmio_read(vcpu, gpa, size);
+	if (!r) {
+		/* Kernel completed device emulation. */
+		tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+		return 1;
+	}
+
+	/* Request the device emulation to userspace device model. */
+	vcpu->mmio_needed = 1;
+	vcpu->mmio_is_write = write;
+	vcpu->arch.complete_userspace_io = tdx_complete_mmio;
+
+	vcpu->run->mmio.phys_addr = gpa;
+	vcpu->run->mmio.len = size;
+	vcpu->run->mmio.is_write = write;
+	vcpu->run->exit_reason = KVM_EXIT_MMIO;
+
+	if (write) {
+		memcpy(vcpu->run->mmio.data, &val, size);
+	} else {
+		vcpu->mmio_fragments[0].gpa = gpa;
+		vcpu->mmio_fragments[0].len = size;
+		trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, size, gpa, NULL);
+	}
+	return 0;
+
+error:
+	tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
+	return 1;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
@@ -1229,6 +1341,8 @@ static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 		return tdx_emulate_hlt(vcpu);
 	case EXIT_REASON_IO_INSTRUCTION:
 		return tdx_emulate_io(vcpu);
+	case EXIT_REASON_EPT_VIOLATION:
+		return tdx_emulate_mmio(vcpu);
 	default:
 		break;
 	}
arch/x86/kvm/x86.c +1 -0
index 03950368d8db..d5b18cad9dcd 100644
@@ -13975,6 +13975,7 @@ EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
 
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
+EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
virt/kvm/kvm_main.c +2 -0
index e27c22449d85..bc14e1f2610c 100644
@@ -2689,6 +2689,7 @@ struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn
 
 	return NULL;
 }
+EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
 
 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
 {
@@ -5992,6 +5993,7 @@ int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
 	r = __kvm_io_bus_read(vcpu, bus, &range, val);
 	return r < 0 ? r : 0;
 }
+EXPORT_SYMBOL_GPL(kvm_io_bus_read);
 
 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
 			    int len, struct kvm_io_device *dev)
Signature · 1 line
2.25.1
#632 lore raw

PATCH v19 111/130 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 virtualize the MSRs.

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 case
Guest TD would issue TDG.VP.VMCALL<INSTRUCTION.{WRMSR,RDMSR> and VMM handles the MSR hypercall. The value set by KVM_SET_MSR_INDEX_LIST is used.

---
 arch/x86/kvm/vmx/main.c    | 44 +++++++++++++++++++++---
 arch/x86/kvm/vmx/tdx.c     | 70 ++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h |  6 ++++
 arch/x86/kvm/x86.c         |  1 -
 arch/x86/kvm/x86.h         |  2 ++
 5 files changed, 118 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/main.c +40 -4
index c9a40456d965..ed46e7e57c18 100644
@@ -247,6 +247,42 @@ 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_has_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_msr_filter_changed(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_msr_filter_changed(vcpu);
+}
+
 static void vt_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
 {
 	struct pi_desc *pi = vcpu_to_pi_desc(vcpu);
@@ -541,7 +577,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	/* TDX cpu enablement is done by tdx_hardware_setup(). */
 	.hardware_enable = vmx_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,
 	.max_vcpus = vt_max_vcpus,
@@ -563,8 +599,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,
@@ -674,7 +710,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.apic_init_signal_blocked = vmx_apic_init_signal_blocked,
 	.migrate_timers = vmx_migrate_timers,
 
-	.msr_filter_changed = vmx_msr_filter_changed,
+	.msr_filter_changed = vt_msr_filter_changed,
 	.complete_emulated_msr = kvm_complete_insn_gp,
 
 	.vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
arch/x86/kvm/vmx/tdx.c +70 -0

76 lines not on this page · raw message

arch/x86/kvm/vmx/x86_ops.h +6 -0
index a12e3bfc96dd..017a73ab34bb 100644
@@ -165,6 +165,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_has_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_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
 
@@ -214,6 +217,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_has_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_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp) { return -EOPNOTSUPP; }
 
arch/x86/kvm/x86.c +0 -1
index d5b18cad9dcd..0e1d3853eeb4 100644
@@ -90,7 +90,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 4e40c23d66ed..c87b7a777b67 100644
@@ -9,6 +9,8 @@
 #include "kvm_cache_regs.h"
 #include "kvm_emulate.h"
 
+#define KVM_MAX_MCE_BANKS 32
+
 bool __kvm_is_vm_type_supported(unsigned long type);
 
 struct kvm_caps {
Signature · 1 line
2.25.1
#641 lore raw

PATCH v19 112/130 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 c8f991b69720..4c635bfcaf7a 100644
@@ -1329,6 +1329,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, TDVMCALL_INVALID_OPERAND);
+		return 1;
+	}
+	trace_kvm_msr_read(index, data);
+
+	tdvmcall_set_return_code(vcpu, TDVMCALL_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, TDVMCALL_INVALID_OPERAND);
+		return 1;
+	}
+
+	trace_kvm_msr_write(index, data);
+	tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+	return 1;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
@@ -1343,6 +1378,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
#642 lore raw

PATCH v19 113/130 KVM: TDX: Handle MSR MTRRCap and MTRRDefType access

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Handle MTRRCap RO MSR to return all features are unsupported and handle MTRRDefType MSR to accept only E=1,FE=0,type=writeback. enable MTRR, disable Fixed range MTRRs, default memory type=writeback

TDX virtualizes that cpuid to report MTRR to guest TD and TDX enforces guest CR0.CD=0. If guest tries to set CR0.CD=1, it results in #GP. While updating MTRR requires to set CR0.CD=1 (and other cache flushing operations). It means guest TD can't update MTRR. Virtualize MTRR as all features disabled and default memory type as writeback.

---
 arch/x86/kvm/vmx/tdx.c | 99 ++++++++++++++++++++++++++++++++++--------
 1 file changed, 82 insertions(+), 17 deletions(-)
arch/x86/kvm/vmx/tdx.c +82 -17
index 4c635bfcaf7a..2bddaef495d1 100644
@@ -611,18 +611,7 @@ u8 tdx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
 	if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
 		return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
 
-	/*
-	 * TDX enforces CR0.CD = 0 and KVM MTRR emulation enforces writeback.
-	 * TODO: implement MTRR MSR emulation so that
-	 * MTRRCap: SMRR=0: SMRR interface unsupported
-	 *          WC=0: write combining unsupported
-	 *          FIX=0: Fixed range registers unsupported
-	 *          VCNT=0: number of variable range regitsers = 0
-	 * MTRRDefType: E=1, FE=0, type=writeback only. Don't allow other value.
-	 *              E=1: enable MTRR
-	 *              FE=0: disable fixed range MTRRs
-	 *              type: default memory type=writeback
-	 */
+	/* TDX enforces CR0.CD = 0 and KVM MTRR emulation enforces writeback. */
 	return MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT;
 }
 
@@ -1932,7 +1921,9 @@ bool tdx_has_emulated_msr(u32 index, bool write)
 	case MSR_IA32_UCODE_REV:
 	case MSR_IA32_ARCH_CAPABILITIES:
 	case MSR_IA32_POWER_CTL:
+	case MSR_MTRRcap:
 	case MSR_IA32_CR_PAT:
+	case MSR_MTRRdefType:
 	case MSR_IA32_TSC_DEADLINE:
 	case MSR_IA32_MISC_ENABLE:
 	case MSR_PLATFORM_INFO:
@@ -1974,16 +1965,47 @@ bool tdx_has_emulated_msr(u32 index, bool write)
 
 int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 {
-	if (tdx_has_emulated_msr(msr->index, false))
-		return kvm_get_msr_common(vcpu, msr);
-	return 1;
+	switch (msr->index) {
+	case MSR_MTRRcap:
+		/*
+		 * Override kvm_mtrr_get_msr() which hardcodes the value.
+		 * Report SMRR = 0, WC = 0, FIX = 0 VCNT = 0 to disable MTRR
+		 * effectively.
+		 */
+		msr->data = 0;
+		return 0;
+	default:
+		if (tdx_has_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_has_emulated_msr(msr->index, true))
+	switch (msr->index) {
+	case MSR_MTRRdefType:
+		/*
+		 * Allow writeback only for all memory.
+		 * Because it's reported that fixed range MTRR isn't supported
+		 * and VCNT=0, enforce MTRRDefType.FE = 0 and don't care
+		 * variable range MTRRs. Only default memory type matters.
+		 *
+		 * bit 11 E: MTRR enable/disable
+		 * bit 12 FE: Fixed-range MTRRs enable/disable
+		 * (E, FE) = (1, 1): enable MTRR and Fixed range MTRR
+		 * (E, FE) = (1, 0): enable MTRR, disable Fixed range MTRR
+		 * (E, FE) = (0, *): disable all MTRRs.  all physical memory
+		 *                   is UC
+		 */
+		if (msr->data != ((1 << 11) | MTRR_TYPE_WRBACK))
+			return 1;
 		return kvm_set_msr_common(vcpu, msr);
-	return 1;
+	default:
+		if (tdx_has_emulated_msr(msr->index, true))
+			return kvm_set_msr_common(vcpu, msr);
+		return 1;
+	}
 }
 
 static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
@@ -2704,6 +2726,45 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
 	return ret;
 }
 
+static int tdx_vcpu_init_mtrr(struct kvm_vcpu *vcpu)
+{
+	struct msr_data msr;
+	int ret;
+	int i;
+
+	/*
+	 * To avoid confusion with reporting VNCT = 0, explicitly disable
+	 * vaiale-range reisters.
+	 */
+	for (i = 0; i < KVM_NR_VAR_MTRR; i++) {
+		/* phymask */
+		msr = (struct msr_data) {
+			.host_initiated = true,
+			.index = 0x200 + 2 * i + 1,
+			.data = 0,	/* valid = 0 to disable. */
+		};
+		ret = kvm_set_msr_common(vcpu, &msr);
+		if (ret)
+			return -EINVAL;
+	}
+
+	/* Set MTRR to use writeback on reset. */
+	msr = (struct msr_data) {
+		.host_initiated = true,
+		.index = MSR_MTRRdefType,
+		/*
+		 * Set E(enable MTRR)=1, FE(enable fixed range MTRR)=0, default
+		 * type=writeback on reset to avoid UC.  Note E=0 means all
+		 * memory is UC.
+		 */
+		.data = (1 << 11) | MTRR_TYPE_WRBACK,
+	};
+	ret = kvm_set_msr_common(vcpu, &msr);
+	if (ret)
+		return -EINVAL;
+	return 0;
+}
+
 int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
 {
 	struct msr_data apic_base_msr;
@@ -2741,6 +2802,10 @@ int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
 	if (kvm_set_apic_base(vcpu, &apic_base_msr))
 		return -EINVAL;
 
+	ret = tdx_vcpu_init_mtrr(vcpu);
+	if (ret)
+		return ret;
+
 	ret = tdx_td_vcpu_init(vcpu, (u64)cmd.data);
 	if (ret)
 		return ret;
Signature · 1 line
2.25.1
#643 lore raw

PATCH v19 114/130 KVM: TDX: Handle MSR IA32_FEAT_CTL MSR and IA32_MCG_EXT_CTL

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

MCE and MCA is advertised via cpuid based on the TDX module spec. Guest kernel can access IA32_FEAT_CTL for checking if LMCE is enabled by platform and IA32_MCG_EXT_CTL to enable LMCE. Make TDX KVM handle them. Otherwise guest MSR access to them with TDG.VP.VMCALL<MSR> on VE results in GP in guest.

Because LMCE is disabled with qemu by default, "-cpu lmce=on" to qemu command line is needed to reproduce it.

---
 arch/x86/kvm/vmx/tdx.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
arch/x86/kvm/vmx/tdx.c +20 -0
index 2bddaef495d1..3481c0b6ef2c 100644
@@ -1952,6 +1952,7 @@ bool tdx_has_emulated_msr(u32 index, bool write)
 		default:
 			return true;
 		}
+	case MSR_IA32_FEAT_CTL:
 	case MSR_IA32_APICBASE:
 	case MSR_EFER:
 		return !write;
@@ -1966,6 +1967,20 @@ bool tdx_has_emulated_msr(u32 index, bool write)
 int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 {
 	switch (msr->index) {
+	case MSR_IA32_FEAT_CTL:
+		/*
+		 * MCE and MCA are advertised via cpuid. guest kernel could
+		 * check if LMCE is enabled or not.
+		 */
+		msr->data = FEAT_CTL_LOCKED;
+		if (vcpu->arch.mcg_cap & MCG_LMCE_P)
+			msr->data |= FEAT_CTL_LMCE_ENABLED;
+		return 0;
+	case MSR_IA32_MCG_EXT_CTL:
+		if (!msr->host_initiated && !(vcpu->arch.mcg_cap & MCG_LMCE_P))
+			return 1;
+		msr->data = vcpu->arch.mcg_ext_ctl;
+		return 0;
 	case MSR_MTRRcap:
 		/*
 		 * Override kvm_mtrr_get_msr() which hardcodes the value.
@@ -1984,6 +1999,11 @@ int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 {
 	switch (msr->index) {
+	case MSR_IA32_MCG_EXT_CTL:
+		if (!msr->host_initiated && !(vcpu->arch.mcg_cap & MCG_LMCE_P))
+			return 1;
+		vcpu->arch.mcg_ext_ctl = msr->data;
+		return 0;
 	case MSR_MTRRdefType:
 		/*
 		 * Allow writeback only for all memory.
Signature · 1 line
2.25.1
#644 lore raw

PATCH v19 115/130 KVM: TDX: Handle TDG.VP.VMCALL<GetTdVmCallInfo> hypercall

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Implement TDG.VP.VMCALL<GetTdVmCallInfo> hypercall. If the input value is zero, return success code and zero in output registers.

TDG.VP.VMCALL<GetTdVmCallInfo> hypercall is a subleaf of TDG.VP.VMCALL to enumerate which TDG.VP.VMCALL sub leaves are supported. This hypercall is for future enhancement of the Guest-Host-Communication Interface (GHCI) specification. The GHCI version of 344426-001US defines it to require input R12 to be zero and to return zero in output registers, R11, R12, R13, and R14 so that guest TD enumerates no enhancement.

---
v19:
- rename TDG_VP_VMCALL_GET_TD_VM_CALL_INFO => TDVMCALL_GET_TD_VM_CALL_INFO

---
 arch/x86/include/asm/shared/tdx.h |  1 +
 arch/x86/kvm/vmx/tdx.c            | 16 ++++++++++++++++
 2 files changed, 17 insertions(+)
arch/x86/include/asm/shared/tdx.h +1 -0
index 28c4a62b7dba..3e8ce567fde0 100644
@@ -22,6 +22,7 @@
 #define TDCS_NOTIFY_ENABLES		0x9100000000000010
 
 /* TDX hypercall Leaf IDs */
+#define TDVMCALL_GET_TD_VM_CALL_INFO	0x10000
 #define TDVMCALL_MAP_GPA		0x10001
 #define TDVMCALL_GET_QUOTE		0x10002
 #define TDVMCALL_REPORT_FATAL_ERROR	0x10003
arch/x86/kvm/vmx/tdx.c +16 -0
index 3481c0b6ef2c..725cb40d0814 100644
@@ -1353,6 +1353,20 @@ static int tdx_emulate_wrmsr(struct kvm_vcpu *vcpu)
 	return 1;
 }
 
+static int tdx_get_td_vm_call_info(struct kvm_vcpu *vcpu)
+{
+	if (tdvmcall_a0_read(vcpu))
+		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
+	else {
+		tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+		kvm_r11_write(vcpu, 0);
+		tdvmcall_a0_write(vcpu, 0);
+		tdvmcall_a1_write(vcpu, 0);
+		tdvmcall_a2_write(vcpu, 0);
+	}
+	return 1;
+}
+
 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
 {
 	if (tdvmcall_exit_type(vcpu))
@@ -1371,6 +1385,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 TDVMCALL_GET_TD_VM_CALL_INFO:
+		return tdx_get_td_vm_call_info(vcpu);
 	default:
 		break;
 	}
Signature · 1 line
2.25.1
#645 lore raw

PATCH v19 116/130 KVM: TDX: Silently discard SMI request

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX doesn't support system-management mode (SMM) and system-management interrupt (SMI) in guest TDs. Because guest state (vcpu state, memory state) is protected, it must go through the TDX module APIs to change guest state, injecting SMI and changing vcpu mode into SMM. The TDX module doesn't provide a way for VMM to inject SMI into guest TD and a way for VMM to switch guest vcpu mode into SMM.

We have two options in KVM when handling SMM or SMI in the guest TD or the device model (e.g. QEMU): 1) silently ignore the request or 2) return a meaningful error.

For simplicity, we implemented the option 1).

---
 arch/x86/kvm/smm.h         |  7 +++++-
 arch/x86/kvm/vmx/main.c    | 45 ++++++++++++++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.c     | 29 ++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h | 12 ++++++++++
 4 files changed, 88 insertions(+), 5 deletions(-)
arch/x86/kvm/smm.h +6 -1
index a1cf2ac5bd78..bc77902f5c18 100644
@@ -142,7 +142,12 @@ union kvm_smram {
 
 static inline int kvm_inject_smi(struct kvm_vcpu *vcpu)
 {
-	kvm_make_request(KVM_REQ_SMI, vcpu);
+	/*
+	 * If SMM isn't supported (e.g. TDX), silently discard SMI request.
+	 * Assume that SMM supported = MSR_IA32_SMBASE supported.
+	 */
+	if (static_call(kvm_x86_has_emulated_msr)(vcpu->kvm, MSR_IA32_SMBASE))
+		kvm_make_request(KVM_REQ_SMI, vcpu);
 	return 0;
 }
 
arch/x86/kvm/vmx/main.c +41 -4

57 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.c +29 -0
index 725cb40d0814..d9b36373e7d0 100644
@@ -2044,6 +2044,35 @@ int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 	}
 }
 
+#ifdef CONFIG_KVM_SMM
+int tdx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
+{
+	/* SMI isn't supported for TDX. */
+	WARN_ON_ONCE(1);
+	return false;
+}
+
+int tdx_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram)
+{
+	/* smi_allowed() is always false for TDX as above. */
+	WARN_ON_ONCE(1);
+	return 0;
+}
+
+int tdx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram)
+{
+	WARN_ON_ONCE(1);
+	return 0;
+}
+
+void tdx_enable_smi_window(struct kvm_vcpu *vcpu)
+{
+	/* SMI isn't supported for TDX.  Silently discard SMI request. */
+	WARN_ON_ONCE(1);
+	vcpu->arch.smi_pending = false;
+}
+#endif
+
 static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
 {
 	struct kvm_tdx_capabilities __user *user_caps;
arch/x86/kvm/vmx/x86_ops.h +12 -0
index 017a73ab34bb..7c63b2b48125 100644
@@ -241,4 +241,16 @@ int tdx_pre_memory_mapping(struct kvm_vcpu *vcpu,
 void tdx_post_memory_mapping(struct kvm_vcpu *vcpu, struct kvm_memory_mapping *mapping) {}
 #endif
 
+#if defined(CONFIG_INTEL_TDX_HOST) && defined(CONFIG_KVM_SMM)
+int tdx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection);
+int tdx_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram);
+int tdx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram);
+void tdx_enable_smi_window(struct kvm_vcpu *vcpu);
+#else
+static inline int tdx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection) { return false; }
+static inline int tdx_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram) { return 0; }
+static inline int tdx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram) { return 0; }
+static inline void tdx_enable_smi_window(struct kvm_vcpu *vcpu) {}
+#endif
+
 #endif /* __KVM_X86_VMX_X86_OPS_H */
Signature · 1 line
2.25.1
#653 lore raw

PATCH v19 117/130 KVM: TDX: Silently ignore INIT/SIPI

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

The TDX module API doesn't provide API for VMM to inject INIT IPI and SIPI. Instead it defines the different protocols to boot application processors. Ignore INIT and SIPI events for the TDX guest.

There are two options. 1) (silently) ignore INIT/SIPI request or 2) return error to guest TDs somehow. Given that TDX guest is paravirtualized to boot AP, the option 1 is chosen for simplicity.

---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  2 ++
 arch/x86/kvm/lapic.c               | 19 +++++++++++-------
 arch/x86/kvm/svm/svm.c             |  1 +
 arch/x86/kvm/vmx/main.c            | 32 ++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.c             |  4 ++--
 6 files changed, 48 insertions(+), 11 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index 22d93d4124c8..85c04aad6ab3 100644
@@ -149,6 +149,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_OPTIONAL(get_untagged_addr)
 KVM_X86_OP_OPTIONAL_RET0(gmem_max_level)
arch/x86/include/asm/kvm_host.h +2 -0
index bb8be091f996..2686c080820b 100644
@@ -1836,6 +1836,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
@@ -2092,6 +2093,7 @@ void kvm_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
 void kvm_set_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 8025c7f614e0..431074679e83 100644
@@ -3268,6 +3268,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;
@@ -3299,13 +3309,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 f76dd52d29ba..27546d993809 100644
@@ -5037,6 +5037,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 +30 -2
index 4f3b872cd401..84d2dc818cf7 100644
@@ -320,6 +320,14 @@ static void vt_enable_smi_window(struct kvm_vcpu *vcpu)
 }
 #endif
 
+static bool vt_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return true;
+
+	return vmx_apic_init_signal_blocked(vcpu);
+}
+
 static void vt_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
 {
 	struct pi_desc *pi = vcpu_to_pi_desc(vcpu);
@@ -348,6 +356,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)) {
@@ -744,13 +771,14 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 #endif
 
 	.check_emulate_instruction = vmx_check_emulate_instruction,
-	.apic_init_signal_blocked = vmx_apic_init_signal_blocked,
+	.apic_init_signal_blocked = vt_apic_init_signal_blocked,
 	.migrate_timers = vmx_migrate_timers,
 
 	.msr_filter_changed = vt_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,
 
 	.get_untagged_addr = vmx_get_untagged_addr,
 
arch/x86/kvm/vmx/tdx.c +2 -2
index d9b36373e7d0..4c7c83105342 100644
@@ -769,8 +769,8 @@ void tdx_vcpu_free(struct kvm_vcpu *vcpu)
 void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 {
 
-	/* Ignore INIT silently because TDX doesn't support INIT event. */
-	if (init_event)
+	/* vcpu_deliver_init method silently discards INIT event. */
+	if (KVM_BUG_ON(init_event, vcpu->kvm))
 		return;
 	if (KVM_BUG_ON(is_td_vcpu_created(to_tdx(vcpu)), vcpu->kvm))
 		return;
Signature · 1 line
2.25.1
#660 lore raw

PATCH v19 118/130 KVM: TDX: Add methods to ignore accesses to CPU state

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX protects TDX guest state from VMM. Implement access methods for TDX guest state to ignore them or return zero. Because those methods can be called by kvm ioctls to set/get cpu registers, they don't have KVM_BUG_ON except one method.

---
 arch/x86/kvm/vmx/main.c    | 289 +++++++++++++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.c     |  48 +++++-
 arch/x86/kvm/vmx/x86_ops.h |  13 ++
 3 files changed, 321 insertions(+), 29 deletions(-)
arch/x86/kvm/vmx/main.c +262 -27
index 84d2dc818cf7..9fb3f28d8259 100644
@@ -375,6 +375,200 @@ static void vt_vcpu_deliver_init(struct kvm_vcpu *vcpu)
 	kvm_vcpu_deliver_init(vcpu);
 }
 
+static void vt_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_vcpu_after_set_cpuid(vcpu);
+}
+
+static void vt_update_exception_bitmap(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_update_exception_bitmap(vcpu);
+}
+
+static u64 vt_get_segment_base(struct kvm_vcpu *vcpu, int seg)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_get_segment_base(vcpu, seg);
+
+	return vmx_get_segment_base(vcpu, seg);
+}
+
+static void vt_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var,
+			      int seg)
+{
+	if (is_td_vcpu(vcpu)) {
+		tdx_get_segment(vcpu, var, seg);
+		return;
+	}
+
+	vmx_get_segment(vcpu, var, seg);
+}
+
+static void vt_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var,
+			      int seg)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_segment(vcpu, var, seg);
+}
+
+static int vt_get_cpl(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_get_cpl(vcpu);
+
+	return vmx_get_cpl(vcpu);
+}
+
+static void vt_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
+{
+	if (is_td_vcpu(vcpu)) {
+		*db = 0;
+		*l = 0;
+		return;
+	}
+
+	vmx_get_cs_db_l_bits(vcpu, db, l);
+}
+
+static bool vt_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
+{
+	if (is_td_vcpu(vcpu))
+		return true;
+
+	return vmx_is_valid_cr0(vcpu, cr0);
+}
+
+static void vt_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_cr0(vcpu, cr0);
+}
+
+static bool vt_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
+{
+	if (is_td_vcpu(vcpu))
+		return true;
+
+	return vmx_is_valid_cr4(vcpu, cr4);
+}
+
+static void vt_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_cr4(vcpu, cr4);
+}
+
+static int vt_set_efer(struct kvm_vcpu *vcpu, u64 efer)
+{
+	if (is_td_vcpu(vcpu))
+		return 0;
+
+	return vmx_set_efer(vcpu, efer);
+}
+
+static void vt_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+{
+	if (is_td_vcpu(vcpu)) {
+		memset(dt, 0, sizeof(*dt));
+		return;
+	}
+
+	vmx_get_idt(vcpu, dt);
+}
+
+static void vt_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_idt(vcpu, dt);
+}
+
+static void vt_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+{
+	if (is_td_vcpu(vcpu)) {
+		memset(dt, 0, sizeof(*dt));
+		return;
+	}
+
+	vmx_get_gdt(vcpu, dt);
+}
+
+static void vt_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_gdt(vcpu, dt);
+}
+
+static void vt_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_dr7(vcpu, val);
+}
+
+static void vt_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
+{
+	/*
+	 * MOV-DR exiting is always cleared for TD guest, even in debug mode.
+	 * Thus KVM_DEBUGREG_WONT_EXIT can never be set and it should never
+	 * reach here for TD vcpu.
+	 */
+	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+		return;
+
+	vmx_sync_dirty_debug_regs(vcpu);
+}
+
+static void vt_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
+{
+	if (is_td_vcpu(vcpu)) {
+		tdx_cache_reg(vcpu, reg);
+		return;
+	}
+
+	vmx_cache_reg(vcpu, reg);
+}
+
+static unsigned long vt_get_rflags(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_get_rflags(vcpu);
+
+	return vmx_get_rflags(vcpu);
+}
+
+static void vt_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_rflags(vcpu, rflags);
+}
+
+static bool vt_get_if_flag(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return false;
+
+	return vmx_get_if_flag(vcpu);
+}
+
 static void vt_flush_tlb_all(struct kvm_vcpu *vcpu)
 {
 	if (is_td_vcpu(vcpu)) {
@@ -521,6 +715,14 @@ static void vt_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
 	vmx_inject_irq(vcpu, reinjected);
 }
 
+static void vt_inject_exception(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_inject_exception(vcpu);
+}
+
 static void vt_cancel_injection(struct kvm_vcpu *vcpu)
 {
 	if (is_td_vcpu(vcpu))
@@ -567,6 +769,39 @@ static void vt_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
 	vmx_get_exit_info(vcpu, reason, info1, info2, intr_info, error_code);
 }
 
+
+static void vt_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_update_cr8_intercept(vcpu, tpr, irr);
+}
+
+static void vt_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_load_eoi_exitmap(vcpu, eoi_exit_bitmap);
+}
+
+static int vt_set_tss_addr(struct kvm *kvm, unsigned int addr)
+{
+	if (is_td(kvm))
+		return 0;
+
+	return vmx_set_tss_addr(kvm, addr);
+}
+
+static int vt_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
+{
+	if (is_td(kvm))
+		return 0;
+
+	return vmx_set_identity_map_addr(kvm, ident_addr);
+}
+
 static u8 vt_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
 {
 	if (is_td_vcpu(vcpu))
@@ -661,30 +896,30 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.vcpu_load = vt_vcpu_load,
 	.vcpu_put = vt_vcpu_put,
 
-	.update_exception_bitmap = vmx_update_exception_bitmap,
+	.update_exception_bitmap = vt_update_exception_bitmap,
 	.get_msr_feature = vmx_get_msr_feature,
 	.get_msr = vt_get_msr,
 	.set_msr = vt_set_msr,
-	.get_segment_base = vmx_get_segment_base,
-	.get_segment = vmx_get_segment,
-	.set_segment = vmx_set_segment,
-	.get_cpl = vmx_get_cpl,
-	.get_cs_db_l_bits = vmx_get_cs_db_l_bits,
-	.is_valid_cr0 = vmx_is_valid_cr0,
-	.set_cr0 = vmx_set_cr0,
-	.is_valid_cr4 = vmx_is_valid_cr4,
-	.set_cr4 = vmx_set_cr4,
-	.set_efer = vmx_set_efer,
-	.get_idt = vmx_get_idt,
-	.set_idt = vmx_set_idt,
-	.get_gdt = vmx_get_gdt,
-	.set_gdt = vmx_set_gdt,
-	.set_dr7 = vmx_set_dr7,
-	.sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
-	.cache_reg = vmx_cache_reg,
-	.get_rflags = vmx_get_rflags,
-	.set_rflags = vmx_set_rflags,
-	.get_if_flag = vmx_get_if_flag,
+	.get_segment_base = vt_get_segment_base,
+	.get_segment = vt_get_segment,
+	.set_segment = vt_set_segment,
+	.get_cpl = vt_get_cpl,
+	.get_cs_db_l_bits = vt_get_cs_db_l_bits,
+	.is_valid_cr0 = vt_is_valid_cr0,
+	.set_cr0 = vt_set_cr0,
+	.is_valid_cr4 = vt_is_valid_cr4,
+	.set_cr4 = vt_set_cr4,
+	.set_efer = vt_set_efer,
+	.get_idt = vt_get_idt,
+	.set_idt = vt_set_idt,
+	.get_gdt = vt_get_gdt,
+	.set_gdt = vt_set_gdt,
+	.set_dr7 = vt_set_dr7,
+	.sync_dirty_debug_regs = vt_sync_dirty_debug_regs,
+	.cache_reg = vt_cache_reg,
+	.get_rflags = vt_get_rflags,
+	.set_rflags = vt_set_rflags,
+	.get_if_flag = vt_get_if_flag,
 
 	.flush_tlb_all = vt_flush_tlb_all,
 	.flush_tlb_current = vt_flush_tlb_current,
@@ -701,7 +936,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.patch_hypercall = vmx_patch_hypercall,
 	.inject_irq = vt_inject_irq,
 	.inject_nmi = vt_inject_nmi,
-	.inject_exception = vmx_inject_exception,
+	.inject_exception = vt_inject_exception,
 	.cancel_injection = vt_cancel_injection,
 	.interrupt_allowed = vt_interrupt_allowed,
 	.nmi_allowed = vt_nmi_allowed,
@@ -709,11 +944,11 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.set_nmi_mask = vt_set_nmi_mask,
 	.enable_nmi_window = vt_enable_nmi_window,
 	.enable_irq_window = vt_enable_irq_window,
-	.update_cr8_intercept = vmx_update_cr8_intercept,
+	.update_cr8_intercept = vt_update_cr8_intercept,
 	.set_virtual_apic_mode = vmx_set_virtual_apic_mode,
 	.set_apic_access_page_addr = vmx_set_apic_access_page_addr,
 	.refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
-	.load_eoi_exitmap = vmx_load_eoi_exitmap,
+	.load_eoi_exitmap = vt_load_eoi_exitmap,
 	.apicv_pre_state_restore = vt_apicv_pre_state_restore,
 	.required_apicv_inhibits = VMX_REQUIRED_APICV_INHIBITS,
 	.hwapic_irr_update = vmx_hwapic_irr_update,
@@ -724,13 +959,13 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
 	.protected_apic_has_interrupt = vt_protected_apic_has_interrupt,
 
-	.set_tss_addr = vmx_set_tss_addr,
-	.set_identity_map_addr = vmx_set_identity_map_addr,
+	.set_tss_addr = vt_set_tss_addr,
+	.set_identity_map_addr = vt_set_identity_map_addr,
 	.get_mt_mask = vt_get_mt_mask,
 
 	.get_exit_info = vt_get_exit_info,
 
-	.vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
+	.vcpu_after_set_cpuid = vt_vcpu_after_set_cpuid,
 
 	.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
 
arch/x86/kvm/vmx/tdx.c +46 -2

60 lines not on this page · raw message

arch/x86/kvm/vmx/x86_ops.h +13 -0
index 7c63b2b48125..727c4d418601 100644
@@ -169,6 +169,12 @@ bool tdx_has_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_get_cpl(struct kvm_vcpu *vcpu);
+void tdx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg);
+unsigned long tdx_get_rflags(struct kvm_vcpu *vcpu);
+u64 tdx_get_segment_base(struct kvm_vcpu *vcpu, int seg);
+void tdx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
+
 int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
 
 void tdx_flush_tlb(struct kvm_vcpu *vcpu);
@@ -221,6 +227,13 @@ static inline bool tdx_has_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_get_cpl(struct kvm_vcpu *vcpu) { return 0; }
+static inline void tdx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg) {}
+static inline unsigned long tdx_get_rflags(struct kvm_vcpu *vcpu) { return 0; }
+static inline u64 tdx_get_segment_base(struct kvm_vcpu *vcpu, int seg) { return 0; }
+static inline void tdx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var,
+				   int seg) {}
+
 static inline int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp) { return -EOPNOTSUPP; }
 
 static inline void tdx_flush_tlb(struct kvm_vcpu *vcpu) {}
Signature · 1 line
2.25.1
#663 lore raw

PATCH v19 119/130 KVM: TDX: Add methods to ignore guest instruction emulation

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Because TDX protects TDX guest state from VMM, instructions in guest memory cannot be emulated. Implement methods to ignore guest instruction emulator.

---
 arch/x86/kvm/vmx/main.c | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/main.c +26 -2
index 9fb3f28d8259..9aaa9bd7abf3 100644
@@ -320,6 +320,30 @@ static void vt_enable_smi_window(struct kvm_vcpu *vcpu)
 }
 #endif
 
+static int vt_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
+					void *insn, int insn_len)
+{
+	if (is_td_vcpu(vcpu))
+		return X86EMUL_RETRY_INSTR;
+
+	return vmx_check_emulate_instruction(vcpu, emul_type, insn, insn_len);
+}
+
+static int vt_check_intercept(struct kvm_vcpu *vcpu,
+				 struct x86_instruction_info *info,
+				 enum x86_intercept_stage stage,
+				 struct x86_exception *exception)
+{
+	/*
+	 * This call back is triggered by the x86 instruction emulator. TDX
+	 * doesn't allow guest memory inspection.
+	 */
+	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+		return X86EMUL_UNHANDLEABLE;
+
+	return vmx_check_intercept(vcpu, info, stage, exception);
+}
+
 static bool vt_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
 {
 	if (is_td_vcpu(vcpu))
@@ -976,7 +1000,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.load_mmu_pgd = vt_load_mmu_pgd,
 
-	.check_intercept = vmx_check_intercept,
+	.check_intercept = vt_check_intercept,
 	.handle_exit_irqoff = vt_handle_exit_irqoff,
 
 	.request_immediate_exit = vt_request_immediate_exit,
@@ -1005,7 +1029,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.enable_smi_window = vt_enable_smi_window,
 #endif
 
-	.check_emulate_instruction = vmx_check_emulate_instruction,
+	.check_emulate_instruction = vt_check_emulate_instruction,
 	.apic_init_signal_blocked = vt_apic_init_signal_blocked,
 	.migrate_timers = vmx_migrate_timers,
 
Signature · 1 line
2.25.1
#664 lore raw

PATCH v19 120/130 KVM: TDX: Add a method to ignore dirty logging

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Currently TDX KVM doesn't support tracking dirty pages (yet). Implement a method to ignore it. Because the flag for kvm memory slot to enable dirty logging isn't accepted for TDX, warn on the method is called for TDX.

---
 arch/x86/kvm/vmx/main.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/main.c +9 -1
index 9aaa9bd7abf3..991bfdecaed2 100644
@@ -834,6 +834,14 @@ static u8 vt_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
 	return vmx_get_mt_mask(vcpu, gfn, is_mmio);
 }
 
+static void vt_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+		return;
+
+	vmx_update_cpu_dirty_logging(vcpu);
+}
+
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	if (!is_td(kvm))
@@ -1008,7 +1016,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.sched_in = vt_sched_in,
 
 	.cpu_dirty_log_size = PML_ENTITY_NUM,
-	.update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
+	.update_cpu_dirty_logging = vt_update_cpu_dirty_logging,
 
 	.nested_ops = &vmx_nested_ops,
 
Signature · 1 line
2.25.1
#673 lore raw

PATCH v19 121/130 KVM: TDX: Add methods to ignore VMX preemption timer

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX doesn't support VMX preemption timer. Implement access methods for VMM to ignore VMX preemption timer.

---
 arch/x86/kvm/vmx/main.c | 25 +++++++++++++++++++++++--
 1 file changed, 23 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/main.c +23 -2
index 991bfdecaed2..ec5c0fda92e9 100644
@@ -842,6 +842,27 @@ static void vt_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
 	vmx_update_cpu_dirty_logging(vcpu);
 }
 
+#ifdef CONFIG_X86_64
+static int vt_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
+			      bool *expired)
+{
+	/* VMX-preemption timer isn't available for TDX. */
+	if (is_td_vcpu(vcpu))
+		return -EINVAL;
+
+	return vmx_set_hv_timer(vcpu, guest_deadline_tsc, expired);
+}
+
+static void vt_cancel_hv_timer(struct kvm_vcpu *vcpu)
+{
+	/* VMX-preemption timer can't be set.  See vt_set_hv_timer(). */
+	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+		return;
+
+	vmx_cancel_hv_timer(vcpu);
+}
+#endif
+
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	if (!is_td(kvm))
@@ -1024,8 +1045,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.pi_start_assignment = vmx_pi_start_assignment,
 
 #ifdef CONFIG_X86_64
-	.set_hv_timer = vmx_set_hv_timer,
-	.cancel_hv_timer = vmx_cancel_hv_timer,
+	.set_hv_timer = vt_set_hv_timer,
+	.cancel_hv_timer = vt_cancel_hv_timer,
 #endif
 
 	.setup_mce = vmx_setup_mce,
Signature · 1 line
2.25.1
#674 lore raw

PATCH v19 122/130 KVM: TDX: Add methods to ignore accesses to TSC

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX protects TDX guest TSC state from VMM. Implement access methods to ignore guest TSC.

---
 arch/x86/kvm/vmx/main.c | 44 +++++++++++++++++++++++++++++++++++++----
 1 file changed, 40 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +40 -4
index ec5c0fda92e9..9fcd71999bba 100644
@@ -834,6 +834,42 @@ static u8 vt_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
 	return vmx_get_mt_mask(vcpu, gfn, is_mmio);
 }
 
+static u64 vt_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
+{
+	/* TDX doesn't support L2 guest at the moment. */
+	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+		return 0;
+
+	return vmx_get_l2_tsc_offset(vcpu);
+}
+
+static u64 vt_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
+{
+	/* TDX doesn't support L2 guest at the moment. */
+	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+		return 0;
+
+	return vmx_get_l2_tsc_multiplier(vcpu);
+}
+
+static void vt_write_tsc_offset(struct kvm_vcpu *vcpu)
+{
+	/* In TDX, tsc offset can't be changed. */
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_write_tsc_offset(vcpu);
+}
+
+static void vt_write_tsc_multiplier(struct kvm_vcpu *vcpu)
+{
+	/* In TDX, tsc multiplier can't be changed. */
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_write_tsc_multiplier(vcpu);
+}
+
 static void vt_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
 {
 	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
@@ -1022,10 +1058,10 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
 
-	.get_l2_tsc_offset = vmx_get_l2_tsc_offset,
-	.get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
-	.write_tsc_offset = vmx_write_tsc_offset,
-	.write_tsc_multiplier = vmx_write_tsc_multiplier,
+	.get_l2_tsc_offset = vt_get_l2_tsc_offset,
+	.get_l2_tsc_multiplier = vt_get_l2_tsc_multiplier,
+	.write_tsc_offset = vt_write_tsc_offset,
+	.write_tsc_multiplier = vt_write_tsc_multiplier,
 
 	.load_mmu_pgd = vt_load_mmu_pgd,
 
Signature · 1 line
2.25.1
#675 lore raw

PATCH v19 123/130 KVM: TDX: Ignore setting up mce

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Because vmx_set_mce function is VMX specific and it cannot be used for TDX. Add vt stub to ignore setting up mce for TDX.

---
 arch/x86/kvm/vmx/main.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/main.c +9 -1
index 9fcd71999bba..7c47b02d88d8 100644
@@ -899,6 +899,14 @@ static void vt_cancel_hv_timer(struct kvm_vcpu *vcpu)
 }
 #endif
 
+static void vt_setup_mce(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_setup_mce(vcpu);
+}
+
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	if (!is_td(kvm))
@@ -1085,7 +1093,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.cancel_hv_timer = vt_cancel_hv_timer,
 #endif
 
-	.setup_mce = vmx_setup_mce,
+	.setup_mce = vt_setup_mce,
 
 #ifdef CONFIG_KVM_SMM
 	.smi_allowed = vt_smi_allowed,
Signature · 1 line
2.25.1
#676 lore raw

PATCH v19 124/130 KVM: TDX: Add a method to ignore for TDX to ignore hypercall patch

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Because guest TD memory is protected, VMM patching guest binary for hypercall instruction isn't possible. Add a method to ignore hypercall patching with a warning. Note: guest TD kernel needs to be modified to use TDG.VP.VMCALL for hypercall.

---
 arch/x86/kvm/vmx/main.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/main.c +14 -1
index 7c47b02d88d8..fae5a3668361 100644
@@ -731,6 +731,19 @@ static u32 vt_get_interrupt_shadow(struct kvm_vcpu *vcpu)
 	return vmx_get_interrupt_shadow(vcpu);
 }
 
+static void vt_patch_hypercall(struct kvm_vcpu *vcpu,
+				  unsigned char *hypercall)
+{
+	/*
+	 * Because guest memory is protected, guest can't be patched. TD kernel
+	 * is modified to use TDG.VP.VMCAL for hypercall.
+	 */
+	if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+		return;
+
+	vmx_patch_hypercall(vcpu, hypercall);
+}
+
 static void vt_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
 {
 	if (is_td_vcpu(vcpu))
@@ -1030,7 +1043,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.update_emulated_instruction = vmx_update_emulated_instruction,
 	.set_interrupt_shadow = vt_set_interrupt_shadow,
 	.get_interrupt_shadow = vt_get_interrupt_shadow,
-	.patch_hypercall = vmx_patch_hypercall,
+	.patch_hypercall = vt_patch_hypercall,
 	.inject_irq = vt_inject_irq,
 	.inject_nmi = vt_inject_nmi,
 	.inject_exception = vt_inject_exception,
Signature · 1 line
2.25.1
#677 lore raw

PATCH v19 125/130 KVM: TDX: Add methods to ignore virtual apic related operation

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX protects TDX guest APIC state from VMM. Implement access methods of TDX guest vAPIC state to ignore them or return zero.

---
 arch/x86/kvm/vmx/main.c    | 61 ++++++++++++++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.c     |  6 ++++
 arch/x86/kvm/vmx/x86_ops.h |  3 ++
 3 files changed, 64 insertions(+), 6 deletions(-)
arch/x86/kvm/vmx/main.c +55 -6
index fae5a3668361..c46c860be0f2 100644
@@ -352,6 +352,14 @@ static bool vt_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
 	return vmx_apic_init_signal_blocked(vcpu);
 }
 
+static void vt_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_set_virtual_apic_mode(vcpu);
+
+	return vmx_set_virtual_apic_mode(vcpu);
+}
+
 static void vt_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
 {
 	struct pi_desc *pi = vcpu_to_pi_desc(vcpu);
@@ -360,6 +368,31 @@ static void vt_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
 	memset(pi->pir, 0, sizeof(pi->pir));
 }
 
+static void vt_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	return vmx_hwapic_irr_update(vcpu, max_irr);
+}
+
+static void vt_hwapic_isr_update(int max_isr)
+{
+	if (is_td_vcpu(kvm_get_running_vcpu()))
+		return;
+
+	return vmx_hwapic_isr_update(max_isr);
+}
+
+static bool vt_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
+{
+	/* TDX doesn't support L2 at the moment. */
+	if (WARN_ON_ONCE(is_td_vcpu(vcpu)))
+		return false;
+
+	return vmx_guest_apic_has_interrupt(vcpu);
+}
+
 static int vt_sync_pir_to_irr(struct kvm_vcpu *vcpu)
 {
 	if (is_td_vcpu(vcpu))
@@ -815,6 +848,22 @@ static void vt_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
 	vmx_update_cr8_intercept(vcpu, tpr, irr);
 }
 
+static void vt_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return;
+
+	vmx_set_apic_access_page_addr(vcpu);
+}
+
+static void vt_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
+{
+	if (WARN_ON_ONCE(is_td_vcpu(vcpu)))
+		return;
+
+	vmx_refresh_apicv_exec_ctrl(vcpu);
+}
+
 static void vt_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
 {
 	if (is_td_vcpu(vcpu))
@@ -1055,15 +1104,15 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.enable_nmi_window = vt_enable_nmi_window,
 	.enable_irq_window = vt_enable_irq_window,
 	.update_cr8_intercept = vt_update_cr8_intercept,
-	.set_virtual_apic_mode = vmx_set_virtual_apic_mode,
-	.set_apic_access_page_addr = vmx_set_apic_access_page_addr,
-	.refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
+	.set_virtual_apic_mode = vt_set_virtual_apic_mode,
+	.set_apic_access_page_addr = vt_set_apic_access_page_addr,
+	.refresh_apicv_exec_ctrl = vt_refresh_apicv_exec_ctrl,
 	.load_eoi_exitmap = vt_load_eoi_exitmap,
 	.apicv_pre_state_restore = vt_apicv_pre_state_restore,
 	.required_apicv_inhibits = VMX_REQUIRED_APICV_INHIBITS,
-	.hwapic_irr_update = vmx_hwapic_irr_update,
-	.hwapic_isr_update = vmx_hwapic_isr_update,
-	.guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
+	.hwapic_irr_update = vt_hwapic_irr_update,
+	.hwapic_isr_update = vt_hwapic_isr_update,
+	.guest_apic_has_interrupt = vt_guest_apic_has_interrupt,
 	.sync_pir_to_irr = vt_sync_pir_to_irr,
 	.deliver_interrupt = vt_deliver_interrupt,
 	.dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
arch/x86/kvm/vmx/tdx.c +6 -0
index fc78e9ca61c1..f706c346eea4 100644
@@ -2080,6 +2080,12 @@ void tdx_enable_smi_window(struct kvm_vcpu *vcpu)
 }
 #endif
 
+void tdx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
+{
+	/* Only x2APIC mode is supported for TD. */
+	WARN_ON_ONCE(kvm_get_apic_mode(vcpu) != LAPIC_MODE_X2APIC);
+}
+
 int tdx_get_cpl(struct kvm_vcpu *vcpu)
 {
 	return 0;
arch/x86/kvm/vmx/x86_ops.h +3 -0
index 727c4d418601..c507f1513dac 100644
@@ -168,6 +168,7 @@ void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
 bool tdx_has_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);
+void tdx_set_virtual_apic_mode(struct kvm_vcpu *vcpu);
 
 int tdx_get_cpl(struct kvm_vcpu *vcpu);
 void tdx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg);
@@ -227,6 +228,8 @@ static inline bool tdx_has_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 void tdx_set_virtual_apic_mode(struct kvm_vcpu *vcpu) {}
+
 static inline int tdx_get_cpl(struct kvm_vcpu *vcpu) { return 0; }
 static inline void tdx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg) {}
 static inline unsigned long tdx_get_rflags(struct kvm_vcpu *vcpu) { return 0; }
Signature · 1 line
2.25.1
#680 lore raw

PATCH v19 126/130 KVM: TDX: Inhibit APICv for TDX guest

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX doesn't support APICV, inhibit APICv for TDX guest. Follow how SEV does it. Define a new inhibit reason for TDX, set it on TD initialization, and add the flag to kvm_x86_ops.required_apicv_inhibits.

---
 arch/x86/include/asm/kvm_host.h | 9 +++++++++
 arch/x86/kvm/vmx/main.c         | 3 ++-
 arch/x86/kvm/vmx/tdx.c          | 4 ++++
 3 files changed, 15 insertions(+), 1 deletion(-)
arch/x86/include/asm/kvm_host.h +9 -0
index 2686c080820b..920fb771246b 100644
@@ -1300,6 +1300,15 @@ enum kvm_apicv_inhibit {
 	 * mapping between logical ID and vCPU.
 	 */
 	APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED,
+
+	/*********************************************************/
+	/* INHIBITs that are relevant only to the Intel's APICv. */
+	/*********************************************************/
+
+	/*
+	 * APICv is disabled because TDX doesn't support it.
+	 */
+	APICV_INHIBIT_REASON_TDX,
 };
 
 struct kvm_arch {
arch/x86/kvm/vmx/main.c +2 -1
index c46c860be0f2..2cd404fd7176 100644
@@ -1022,7 +1022,8 @@ static void vt_post_memory_mapping(struct kvm_vcpu *vcpu,
 	 BIT(APICV_INHIBIT_REASON_BLOCKIRQ) |			\
 	 BIT(APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED) |	\
 	 BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) |		\
-	 BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED))
+	 BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED) |		\
+	 BIT(APICV_INHIBIT_REASON_TDX))
 
 struct kvm_x86_ops vt_x86_ops __initdata = {
 	.name = KBUILD_MODNAME,
arch/x86/kvm/vmx/tdx.c +4 -0
index f706c346eea4..7be1be161dc2 100644
@@ -2488,6 +2488,8 @@ static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
 		goto teardown;
 	}
 
+	kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_TDX);
+
 	return 0;
 
 	/*
@@ -2821,6 +2823,8 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
 		return -EIO;
 	}
 
+	WARN_ON_ONCE(kvm_apicv_activated(vcpu->kvm));
+	vcpu->arch.apic->apicv_active = false;
 	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
 	tdx->td_vcpu_created = true;
 	return 0;
Signature · 1 line
2.25.1
#681 lore raw

PATCH v19 127/130 Documentation/virt/kvm: Document on Trust Domain Extensions(TDX)

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Add documentation to Intel Trusted Domain Extensions(TDX) support.

---
 Documentation/virt/kvm/api.rst           |   9 +-
 Documentation/virt/kvm/x86/index.rst     |   1 +
 Documentation/virt/kvm/x86/intel-tdx.rst | 362 +++++++++++++++++++++++
 3 files changed, 371 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/virt/kvm/x86/intel-tdx.rst
Documentation/virt/kvm/api.rst +8 -1
index 667dc58f7d2f..4b70d2b43532 100644
@@ -1394,6 +1394,9 @@ the memory region are automatically reflected into the guest.  For example, an
 mmap() that affects the region will be made visible immediately.  Another
 example is madvise(MADV_DROP).
 
+For TDX guest, deleting/moving memory region loses guest memory contents.
+Read only region isn't supported.  Only as-id 0 is supported.
+
 Note: On arm64, a write generated by the page-table walker (to update
 the Access and Dirty flags, for example) never results in a
 KVM_EXIT_MMIO exit when the slot has the KVM_MEM_READONLY flag. This
@@ -4734,7 +4737,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
 
@@ -4746,6 +4749,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/x86/intel-tdx.rst.
+
 4.111 KVM_MEMORY_ENCRYPT_REG_REGION
 -----------------------------------
 
Documentation/virt/kvm/x86/index.rst +1 -0
index 9ece6b8dc817..851e99174762 100644
@@ -11,6 +11,7 @@ KVM for x86 systems
    cpuid
    errata
    hypercalls
+   intel-tdx
    mmu
    msr
    nested-vmx
Documentation/virt/kvm/x86/intel-tdx.rst new file +362 -0

362 lines not on this page · raw message

Signature · 1 line
2.25.1
#682 lore raw

PATCH v19 128/130 KVM: x86: design documentation on TDX support of x86 KVM TDP MMU

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Add a high level design document on TDX changes to TDP MMU.

---
 Documentation/virt/kvm/x86/index.rst       |   1 +
 Documentation/virt/kvm/x86/tdx-tdp-mmu.rst | 443 +++++++++++++++++++++
 2 files changed, 444 insertions(+)
 create mode 100644 Documentation/virt/kvm/x86/tdx-tdp-mmu.rst
Documentation/virt/kvm/x86/index.rst +1 -0
index 851e99174762..63a78bd41b16 100644
@@ -16,4 +16,5 @@ KVM for x86 systems
    msr
    nested-vmx
    running-nested-guests
+   tdx-tdp-mmu
    timekeeping
Documentation/virt/kvm/x86/tdx-tdp-mmu.rst new file +443 -0

443 lines not on this page · raw message

Signature · 1 line
2.25.1
#683 lore raw

PATCH v19 129/130 RFC: KVM: x86: Add x86 callback to check cpuid

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

The x86 backend should check the consistency of KVM_SET_CPUID2 because it has its constraint. Add a callback for it. The backend code will come as another patch.

---
 arch/x86/include/asm/kvm-x86-ops.h |  2 ++
 arch/x86/include/asm/kvm_host.h    |  1 +
 arch/x86/kvm/cpuid.c               | 20 ++++++++++++--------
 3 files changed, 15 insertions(+), 8 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 85c04aad6ab3..3a7140129855 100644
@@ -20,6 +20,8 @@ KVM_X86_OP(hardware_disable)
 KVM_X86_OP(hardware_unsetup)
 KVM_X86_OP_OPTIONAL_RET0(offline_cpu)
 KVM_X86_OP(has_emulated_msr)
+/* TODO: Once all backend implemented this op, remove _OPTIONAL_RET0. */
+KVM_X86_OP_OPTIONAL_RET0(vcpu_check_cpuid)
 KVM_X86_OP(vcpu_after_set_cpuid)
 KVM_X86_OP(is_vm_type_supported)
 KVM_X86_OP_OPTIONAL(max_vcpus);
arch/x86/include/asm/kvm_host.h +1 -0
index 920fb771246b..e4d40e31fc31 100644
@@ -1638,6 +1638,7 @@ struct kvm_x86_ops {
 	void (*hardware_unsetup)(void);
 	int (*offline_cpu)(void);
 	bool (*has_emulated_msr)(struct kvm *kvm, u32 index);
+	int (*vcpu_check_cpuid)(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, int nent);
 	void (*vcpu_after_set_cpuid)(struct kvm_vcpu *vcpu);
 
 	bool (*is_vm_type_supported)(unsigned long vm_type);
arch/x86/kvm/cpuid.c +12 -8
index 8cdcd6f406aa..b57006943247 100644
@@ -136,6 +136,7 @@ static int kvm_check_cpuid(struct kvm_vcpu *vcpu,
 {
 	struct kvm_cpuid_entry2 *best;
 	u64 xfeatures;
+	int r;
 
 	/*
 	 * The existing code assumes virtual address is 48-bit or 57-bit in the
@@ -155,15 +156,18 @@ static int kvm_check_cpuid(struct kvm_vcpu *vcpu,
 	 * enabling in the FPU, e.g. to expand the guest XSAVE state size.
 	 */
 	best = cpuid_entry2_find(entries, nent, 0xd, 0);
-	if (!best)
-		return 0;
-
-	xfeatures = best->eax | ((u64)best->edx << 32);
-	xfeatures &= XFEATURE_MASK_USER_DYNAMIC;
-	if (!xfeatures)
-		return 0;
+	if (best) {
+		xfeatures = best->eax | ((u64)best->edx << 32);
+		xfeatures &= XFEATURE_MASK_USER_DYNAMIC;
+		if (xfeatures) {
+			r = fpu_enable_guest_xfd_features(&vcpu->arch.guest_fpu,
+							  xfeatures);
+			if (r)
+				return r;
+		}
+	}
 
-	return fpu_enable_guest_xfd_features(&vcpu->arch.guest_fpu, xfeatures);
+	return static_call(kvm_x86_vcpu_check_cpuid)(vcpu, entries, nent);
 }
 
 /* Check whether the supplied CPUID data is equal to what is already set for the vCPU. */
Signature · 1 line
2.25.1
#684 lore raw

PATCH v19 130/130 RFC: KVM: x86, TDX: Add check for KVM_SET_CPUID2

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Implement a hook of KVM_SET_CPUID2 for additional consistency check.

Intel TDX or AMD SEV has a restriction on the value of cpuid. For example, some values must be the same between all vcpus. Check if the new values are consistent with the old values. The check is light because the cpuid consistency is very model specific and complicated. The user space VMM should set cpuid and MSRs consistently.

---
v18:
- Use TDH.SYS.RD() instead of struct tdsysinfo_struct

---
 arch/x86/kvm/vmx/main.c    | 10 ++++++
 arch/x86/kvm/vmx/tdx.c     | 66 ++++++++++++++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.h     |  7 ++++
 arch/x86/kvm/vmx/x86_ops.h |  4 +++
 4 files changed, 81 insertions(+), 6 deletions(-)
arch/x86/kvm/vmx/main.c +10 -0
index 2cd404fd7176..1a979ec644d0 100644
@@ -432,6 +432,15 @@ static void vt_vcpu_deliver_init(struct kvm_vcpu *vcpu)
 	kvm_vcpu_deliver_init(vcpu);
 }
 
+static int vt_vcpu_check_cpuid(struct kvm_vcpu *vcpu,
+			       struct kvm_cpuid_entry2 *e2, int nent)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_check_cpuid(vcpu, e2, nent);
+
+	return 0;
+}
+
 static void vt_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
 {
 	if (is_td_vcpu(vcpu))
@@ -1125,6 +1134,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.get_exit_info = vt_get_exit_info,
 
+	.vcpu_check_cpuid = vt_vcpu_check_cpuid,
 	.vcpu_after_set_cpuid = vt_vcpu_after_set_cpuid,
 
 	.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
arch/x86/kvm/vmx/tdx.c +60 -6

117 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.h +7 -0
index 11c74c34555f..af3a2b8afee8 100644
@@ -31,6 +31,13 @@ struct kvm_tdx {
 
 	u64 tsc_offset;
 
+	/*
+	 * For KVM_SET_CPUID to check consistency. Remember the one passed to
+	 * TDH.MNG_INIT
+	 */
+	int cpuid_nent;
+	struct kvm_cpuid_entry2 *cpuid;
+
 	/* For KVM_MEMORY_MAPPING */
 	struct mutex source_lock;
 	struct page *source_page;
arch/x86/kvm/vmx/x86_ops.h +4 -0
index c507f1513dac..6b067842a67f 100644
@@ -162,6 +162,8 @@ u8 tdx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio);
 
 void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
 			   int trig_mode, int vector);
+int tdx_vcpu_check_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,
+			 int nent);
 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);
@@ -221,6 +223,8 @@ static inline u8 tdx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
 
 static inline void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
 					 int trig_mode, int vector) {}
+static inline int tdx_vcpu_check_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,
+				       int nent) { return -EOPNOTSUPP; }
 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) {}
Signature · 1 line
2.25.1
#11 lore raw

Re: [PATCH v19 004/130] x86/virt/tdx: Support global metadata read for all element sizes

In reply to [email protected]
Quoted 70 lines · On 26.02.24 09:25, [email protected] wrote:

From: Kai Huang <[email protected]>

For now the kernel only reads TDMR related global metadata fields for module initialization. All these fields are 16-bits, and the kernel only supports reading 16-bits fields.

KVM will need to read a bunch of non-TDMR related metadata to create and run TDX guests. It's essential to provide a generic metadata read infrastructure which supports reading all 8/16/32/64 bits element sizes.

Extend the metadata read to support reading all these element sizes.

---
  arch/x86/virt/vmx/tdx/tdx.c | 59 +++++++++++++++++++++++++------------
  arch/x86/virt/vmx/tdx/tdx.h |  2 --
  2 files changed, 40 insertions(+), 21 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +19 -7
index eb208da4ff63..a19adc898df6 100644
@@ -271,23 +271,35 @@ static int read_sys_metadata_field(u64 field_id, u64 *data)
  	return 0;
  }
 
-static int read_sys_metadata_field16(u64 field_id,
-				     int offset,
-				     void *stbuf)
+/* Return the metadata field element size in bytes */
+static int get_metadata_field_bytes(u64 field_id)
  {
-	u16 *st_member = stbuf + offset;
+	/*
+	 * TDX supports 8/16/32/64 bits metadata field element sizes.
+	 * TDX module determines the metadata element size based on the
+	 * "element size code" encoded in the field ID (see the comment
+	 * of MD_FIELD_ID_ELE_SIZE_CODE macro for specific encodings).
+	 */
+	return 1 << MD_FIELD_ID_ELE_SIZE_CODE(field_id);
+}
+
+static int stbuf_read_sys_metadata_field(u64 field_id,
+					 int offset,
+					 int bytes,
+					 void *stbuf)
+{
+	void *st_member = stbuf + offset;
  	u64 tmp;
  	int ret;
 
-	if (WARN_ON_ONCE(MD_FIELD_ID_ELE_SIZE_CODE(field_id) !=
-			MD_FIELD_ID_ELE_SIZE_16BIT))
+	if (WARN_ON_ONCE(get_metadata_field_bytes(field_id) != bytes))
  		return -EINVAL;
 
  	ret = read_sys_metadata_field(field_id, &tmp);
  	if (ret)
  		return ret;
 
-	*st_member = tmp;
+	memcpy(st_member, &tmp, bytes);
 
  	return 0;
  }
@@ -295,11 +307,30 @@ static int read_sys_metadata_field16(u64 field_id,
  struct field_mapping {
  	u64 field_id;
  	int offset;

arch/x86/virt/vmx/tdx/tdx.c static int read_sys_metadata_field16(u64 field_id, · line 318

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -1
+	int size;
  };
 
  #define TD_SYSINFO_MAP(_field_id, _struct, _member)	\
  	{ .field_id = MD_FIELD_ID_##_field_id,		\
-	  .offset   = offsetof(_struct, _member) }
+	  .offset   = offsetof(_struct, _member),	\
+	  .size     = sizeof(typeof(((_struct *)0)->_member)) }
+
+static int read_sys_metadata(struct field_mapping *fields, int nr_fields,

The first parameter should be "const struct field_mapping *fields".

Juergen

#178 lore raw

Re: [PATCH v19 028/130] KVM: TDX: Add TDX "architectural" error codes

In reply to [email protected]

arch/x86/include/asm/shared/tdx.h line 29

Quoted 9 lines · On Mon, Feb 26, 2024 at 12:25:30AM -0800, [email protected] wrote:
arch/x86/include/asm/shared/tdx.h +0 -1
index fdfd41511b02..28c4a62b7dba 100644
@@ -26,7 +26,13 @@
 #define TDVMCALL_GET_QUOTE		0x10002
 #define TDVMCALL_REPORT_FATAL_ERROR	0x10003
 
-#define TDVMCALL_STATUS_RETRY		1

Oops, I accidentally removed this constant to break tdx guest build.

arch/x86/include/asm/shared/tdx.h +2 -0
index ef1c8e5a2944..1367a5941499 100644
@@ -28,6 +28,8 @@
 #define TDVMCALL_REPORT_FATAL_ERROR    0x10003
 #define TDVMCALL_SETUP_EVENT_NOTIFY_INTERRUPT  0x10004
 
+#define TDVMCALL_STATUS_RETRY          1
+
 /*
  * TDG.VP.VMCALL Status Codes (returned in R10)
  */
Signature · 3 lines
2.25.1
-- 
Isaku Yamahata <[email protected]>
#12 lore raw

Re: [PATCH v19 004/130] x86/virt/tdx: Support global metadata read for all element sizes

In reply to Juergen Gross
Quoted 74 lines · Juergen Gross
Quoted 73 lines · On 26.02.24 09:25, [email protected] wrote:

From: Kai Huang <[email protected]>

For now the kernel only reads TDMR related global metadata fields for module initialization. All these fields are 16-bits, and the kernel only supports reading 16-bits fields.

KVM will need to read a bunch of non-TDMR related metadata to create and run TDX guests. It's essential to provide a generic metadata read infrastructure which supports reading all 8/16/32/64 bits element sizes.

Extend the metadata read to support reading all these element sizes.

---
  arch/x86/virt/vmx/tdx/tdx.c | 59 +++++++++++++++++++++++++------------
  arch/x86/virt/vmx/tdx/tdx.h |  2 --
  2 files changed, 40 insertions(+), 21 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +20 -7
index eb208da4ff63..a19adc898df6 100644
@@ -271,23 +271,35 @@ static int read_sys_metadata_field(u64 field_id, u64 *data)
  	return 0;
  }
 
-static int read_sys_metadata_field16(u64 field_id,
-				     int offset,
-				     void *stbuf)
+/* Return the metadata field element size in bytes */
+static int get_metadata_field_bytes(u64 field_id)
  {
-	u16 *st_member = stbuf + offset;
+	/*
+	 * TDX supports 8/16/32/64 bits metadata field element sizes.
+	 * TDX module determines the metadata element size based on the
+	 * "element size code" encoded in the field ID (see the comment
+	 * of MD_FIELD_ID_ELE_SIZE_CODE macro for specific encodings).
+	 */
+	return 1 << MD_FIELD_ID_ELE_SIZE_CODE(field_id);
+}
+
+static int stbuf_read_sys_metadata_field(u64 field_id,
+					 int offset,
+					 int bytes,
+					 void *stbuf)
+{
+	void *st_member = stbuf + offset;
  	u64 tmp;
  	int ret;
 
-	if (WARN_ON_ONCE(MD_FIELD_ID_ELE_SIZE_CODE(field_id) !=
-			MD_FIELD_ID_ELE_SIZE_16BIT))
+	if (WARN_ON_ONCE(get_metadata_field_bytes(field_id) != bytes))
  		return -EINVAL;
 
  	ret = read_sys_metadata_field(field_id, &tmp);
  	if (ret)
  		return ret;
 
-	*st_member = tmp;
+	memcpy(st_member, &tmp, bytes);
 
  	return 0;
  }
@@ -295,11 +307,30 @@ static int read_sys_metadata_field16(u64 field_id,
  struct field_mapping {
  	u64 field_id;
  	int offset;
+	int size;
  };
 
Quoted 11 lines

arch/x86/virt/vmx/tdx/tdx.c static int read_sys_metadata_field16(u64 field_id, · line 318

Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -1
  #define TD_SYSINFO_MAP(_field_id, _struct, _member)	\
  	{ .field_id = MD_FIELD_ID_##_field_id,		\
-	  .offset   = offsetof(_struct, _member) }
+	  .offset   = offsetof(_struct, _member),	\
+	  .size     = sizeof(typeof(((_struct *)0)->_member)) }
+
+static int read_sys_metadata(struct field_mapping *fields, int nr_fields,

The first parameter should be "const struct field_mapping *fields".

Indeed. :-)

#535 lore raw

Re: [PATCH v19 091/130] KVM: TDX: remove use of struct vcpu_vmx from posted_interrupt.c

In reply to [email protected]
Quoted 4 lines · On 2/26/2024 4:26 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

As TDX will use posted_interrupt.c, the use of struct vcpu_vmx is a blocker. Because the members of

Extra "of"

Quoted 127 lines

struct pi_desc pi_desc and struct
list_head pi_wakeup_list are only used in posted_interrupt.c, introduce common structure, struct vcpu_pi, make vcpu_vmx and vcpu_tdx has same layout in the top of structure.

To minimize the diff size, avoid code conversion like, vmx->pi_desc => vmx->common->pi_desc. Instead add compile time check if the layout is expected.

---
  arch/x86/kvm/vmx/posted_intr.c | 41 ++++++++++++++++++++++++++--------
  arch/x86/kvm/vmx/posted_intr.h | 11 +++++++++
  arch/x86/kvm/vmx/tdx.c         |  1 +
  arch/x86/kvm/vmx/tdx.h         |  8 +++++++
  arch/x86/kvm/vmx/vmx.h         | 14 +++++++-----
  5 files changed, 60 insertions(+), 15 deletions(-)
arch/x86/kvm/vmx/posted_intr.c +32 -9
index af662312fd07..b66add9da0f3 100644
@@ -11,6 +11,7 @@
  #include "posted_intr.h"
  #include "trace.h"
  #include "vmx.h"
+#include "tdx.h"
 
  /*
   * Maintain a per-CPU list of vCPUs that need to be awakened by wakeup_handler()
@@ -31,9 +32,29 @@ static DEFINE_PER_CPU(struct list_head, wakeup_vcpus_on_cpu);
   */
  static DEFINE_PER_CPU(raw_spinlock_t, wakeup_vcpus_on_cpu_lock);
 
+/*
+ * The layout of the head of struct vcpu_vmx and struct vcpu_tdx must match with
+ * struct vcpu_pi.
+ */
+static_assert(offsetof(struct vcpu_pi, pi_desc) ==
+	      offsetof(struct vcpu_vmx, pi_desc));
+static_assert(offsetof(struct vcpu_pi, pi_wakeup_list) ==
+	      offsetof(struct vcpu_vmx, pi_wakeup_list));
+#ifdef CONFIG_INTEL_TDX_HOST
+static_assert(offsetof(struct vcpu_pi, pi_desc) ==
+	      offsetof(struct vcpu_tdx, pi_desc));
+static_assert(offsetof(struct vcpu_pi, pi_wakeup_list) ==
+	      offsetof(struct vcpu_tdx, pi_wakeup_list));
+#endif
+
+static inline struct vcpu_pi *vcpu_to_pi(struct kvm_vcpu *vcpu)
+{
+	return (struct vcpu_pi *)vcpu;
+}
+
  static inline struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
  {
-	return &(to_vmx(vcpu)->pi_desc);
+	return &vcpu_to_pi(vcpu)->pi_desc;
  }
 
  static int pi_try_set_control(struct pi_desc *pi_desc, u64 *pold, u64 new)
@@ -52,8 +73,8 @@ static int pi_try_set_control(struct pi_desc *pi_desc, u64 *pold, u64 new)
 
  void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
  {
-	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
-	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	struct vcpu_pi *vcpu_pi = vcpu_to_pi(vcpu);
+	struct pi_desc *pi_desc = &vcpu_pi->pi_desc;
  	struct pi_desc old, new;
  	unsigned long flags;
  	unsigned int dest;
@@ -90,7 +111,7 @@ void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
  	 */
  	if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR) {
  		raw_spin_lock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
-		list_del(&vmx->pi_wakeup_list);
+		list_del(&vcpu_pi->pi_wakeup_list);
  		raw_spin_unlock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
  	}
 
@@ -145,15 +166,15 @@ static bool vmx_can_use_vtd_pi(struct kvm *kvm)
   */
  static void pi_enable_wakeup_handler(struct kvm_vcpu *vcpu)
  {
-	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
-	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	struct vcpu_pi *vcpu_pi = vcpu_to_pi(vcpu);
+	struct pi_desc *pi_desc = &vcpu_pi->pi_desc;
  	struct pi_desc old, new;
  	unsigned long flags;
 
  	local_irq_save(flags);
 
  	raw_spin_lock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
-	list_add_tail(&vmx->pi_wakeup_list,
+	list_add_tail(&vcpu_pi->pi_wakeup_list,
  		      &per_cpu(wakeup_vcpus_on_cpu, vcpu->cpu));
  	raw_spin_unlock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
 
@@ -190,7 +211,8 @@ static bool vmx_needs_pi_wakeup(struct kvm_vcpu *vcpu)
  	 * notification vector is switched to the one that calls
  	 * back to the pi_wakeup_handler() function.
  	 */
-	return vmx_can_use_ipiv(vcpu) || vmx_can_use_vtd_pi(vcpu->kvm);
+	return (vmx_can_use_ipiv(vcpu) && !is_td_vcpu(vcpu)) ||
+		vmx_can_use_vtd_pi(vcpu->kvm);
  }
 
  void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
@@ -200,7 +222,8 @@ void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
  	if (!vmx_needs_pi_wakeup(vcpu))
  		return;
 
-	if (kvm_vcpu_is_blocking(vcpu) && !vmx_interrupt_blocked(vcpu))
+	if (kvm_vcpu_is_blocking(vcpu) &&
+	    (is_td_vcpu(vcpu) || !vmx_interrupt_blocked(vcpu)))
  		pi_enable_wakeup_handler(vcpu);
 
  	/*
arch/x86/kvm/vmx/posted_intr.h +0 -0
index 26992076552e..2fe8222308b2 100644
@@ -94,6 +94,17 @@ static inline bool pi_test_sn(struct pi_desc *pi_desc)
  			(unsigned long *)&pi_desc->control);
  }

arch/x86/kvm/vmx/posted_intr.h static inline bool pi_test_sn(struct pi_desc *pi_desc) · line 105

Quoted 10 lines
arch/x86/kvm/vmx/posted_intr.h +9 -0
 
+struct vcpu_pi {
+	struct kvm_vcpu	vcpu;
+
+	/* Posted interrupt descriptor */
+	struct pi_desc pi_desc;
+
+	/* Used if this vCPU is waiting for PI notification wakeup. */
+	struct list_head pi_wakeup_list;
+	/* Until here common layout betwwn vcpu_vmx and vcpu_tdx. */

s/betwwn/between

Also, in pi_wakeup_handler(), it is still using struct vcpu_vmx, but it could be vcpu_tdx.
Functionally it is OK, however, since you have added vcpu_pi, should it use vcpu_pi instead of vcpu_vmx in pi_wakeup_handler()?

Quoted 75 lines
arch/x86/kvm/vmx/posted_intr.h +2 -0
+};
+
  void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu);
  void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu);
  void pi_wakeup_handler(void);
arch/x86/kvm/vmx/tdx.c +1 -0
index a5b52aa6d153..1da58c36217c 100644
@@ -584,6 +584,7 @@ int tdx_vcpu_create(struct kvm_vcpu *vcpu)
 
  	fpstate_set_confidential(&vcpu->arch.guest_fpu);
  	vcpu->arch.apic->guest_apic_protected = true;
+	INIT_LIST_HEAD(&tdx->pi_wakeup_list);
 
  	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
 
arch/x86/kvm/vmx/tdx.h +8 -0
index 7f8c78f06508..eaffa7384725 100644
@@ -4,6 +4,7 @@
 
  #ifdef CONFIG_INTEL_TDX_HOST
 
+#include "posted_intr.h"
  #include "pmu_intel.h"
  #include "tdx_ops.h"
 
@@ -69,6 +70,13 @@ union tdx_exit_reason {
  struct vcpu_tdx {
  	struct kvm_vcpu	vcpu;
 
+	/* Posted interrupt descriptor */
+	struct pi_desc pi_desc;
+
+	/* Used if this vCPU is waiting for PI notification wakeup. */
+	struct list_head pi_wakeup_list;
+	/* Until here same layout to struct vcpu_pi. */
+
  	unsigned long tdvpr_pa;
  	unsigned long *tdvpx_pa;
  	bool td_vcpu_created;
arch/x86/kvm/vmx/vmx.h +8 -6
index 79ff54f08fee..634a9a250b95 100644
@@ -235,6 +235,14 @@ struct nested_vmx {
 
  struct vcpu_vmx {
  	struct kvm_vcpu       vcpu;
+
+	/* Posted interrupt descriptor */
+	struct pi_desc pi_desc;
+
+	/* Used if this vCPU is waiting for PI notification wakeup. */
+	struct list_head pi_wakeup_list;
+	/* Until here same layout to struct vcpu_pi. */
+
  	u8                    fail;
  	u8		      x2apic_msr_bitmap_mode;
 
@@ -304,12 +312,6 @@ struct vcpu_vmx {
 
  	union vmx_exit_reason exit_reason;
 
-	/* Posted interrupt descriptor */
-	struct pi_desc pi_desc;
-
-	/* Used if this vCPU is waiting for PI notification wakeup. */
-	struct list_head pi_wakeup_list;
-
  	/* Support for a guest hypervisor (nested VMX) */
  	struct nested_vmx nested;
 
#48 lore raw

Re: [PATCH v19 008/130] x86/tdx: Warning with 32bit build shift-count-overflow

In reply to [email protected]
Quoted 11 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

This patch fixes the following warnings.

    In file included from arch/x86/kernel/asm-offsets.c:22:
    arch/x86/include/asm/tdx.h:92:87: warning: shift count >= width of type [-Wshift-count-overflow]
    arch/x86/include/asm/tdx.h:20:21: note: expanded from macro 'TDX_ERROR'
    #define TDX_ERROR                       _BITUL(63)

                                            ^~~~~~~~~~
Quoted 3 lines

Also consistently use ULL for TDX_SEAMCALL_VMFAILINVALID.

Fixes 527a534c7326 ("x86/tdx: Provide common base for SEAMCALL and TDCALL C wrappers")

+Kirill.

This kinda fix should be sent out as a separate patch.

Quoted 11 lines
---
  arch/x86/include/asm/tdx.h | 4 ++--
  1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/include/asm/tdx.h +0 -0
index 16be3a1e4916..1e9dcdf9912b 100644
@@ -17,9 +17,9 @@
   * Bits 47:40 == 0xFF indicate Reserved status code class that never used by

arch/x86/include/asm/tdx.h line 25

Quoted 10 lines
arch/x86/include/asm/tdx.h +2 -2
   * TDX module.
   */
-#define TDX_ERROR			_BITUL(63)
+#define TDX_ERROR			_BITULL(63)
  #define TDX_SW_ERROR			(TDX_ERROR | GENMASK_ULL(47, 40))
-#define TDX_SEAMCALL_VMFAILINVALID	(TDX_SW_ERROR | _UL(0xFFFF0000))
+#define TDX_SEAMCALL_VMFAILINVALID	(TDX_SW_ERROR | _ULL(0xFFFF0000))
 
  #define TDX_SEAMCALL_GP			(TDX_SW_ERROR | X86_TRAP_GP)
  #define TDX_SEAMCALL_UD			(TDX_SW_ERROR | X86_TRAP_UD)

Both TDX guest and TDX host code depends on X86_64 in the Kconfig. This issue seems due to asm-offsets.c includes <asm/tdx.h> unconditionally.

It doesn't make sense to generate any TDX related code in asm-offsets.h so I am wondering whether it is better to just make the inclusion of <asm/tdx.h> conditionally or move it the asm-offsets_64.c?

Kirill what's your opinion?

Btw after quick try seems I cannot reproduce this (w/o this KVM TDX patchset). Isaku, could you share your .config?

#164 lore raw

Re: [PATCH v19 027/130] KVM: TDX: Define TDX architectural definitions

In reply to [email protected]
Quoted 3 lines

+ * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
+ */
+#define TDX_MAX_VCPUS (~(u16)0)

This value will be treated as -1 in tdx_vm_init(),

	"kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);"

This will lead to kvm->max_vcpus being -1 by default.
Is this by design or just an error?
If it's by design, why not set kvm->max_vcpus = -1 in tdx_vm_init() directly. If an unexpected error, may below is better?

#define TDX_MAX_VCPUS (int)((u16)(~0UL))
or
#define TDX_MAX_VCPUS 65536

#49 lore raw

Re: [PATCH v19 008/130] x86/tdx: Warning with 32bit build shift-count-overflow

In reply to Huang, Kai
Quoted 7 lines · Kai
Quoted 4 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

This patch fixes the following warnings.

Quoted 7 lines
Quoted 7 lines
    In file included from arch/x86/kernel/asm-offsets.c:22:
    arch/x86/include/asm/tdx.h:92:87: warning: shift count >= width of type [-Wshift-count-overflow]
    arch/x86/include/asm/tdx.h:20:21: note: expanded from macro 'TDX_ERROR'
    #define TDX_ERROR                       _BITUL(63)

                                            ^~~~~~~~~~

I think you trim the warning message. I don't see the actual user of the define. Define itself will not generate the warning. You need to actually use it outside of preprocessor. I don't understand who would use it in 32-bit code. Maybe fixing it this way masking other issue.

That said, I don't object the change itself. We just need to understand the context more.

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#570 lore raw

Re: [PATCH v19 101/130] KVM: TDX: handle ept violation/misconfig exit

In reply to [email protected]
Quoted 6 lines · On 2/26/2024 4:26 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

On EPT violation, call a common function, __vmx_handle_ept_violation() to trigger x86 MMU code. On EPT misconfiguration, exit to ring 3 with KVM_EXIT_UNKNOWN. because EPT misconfiguration can't happen as MMIO is trigged by TDG.VP.VMCALL. No point to set a misconfiguration value for the

s/trigged/triggered

Quoted 9 lines

fast path.

---
v14 -> v15:
- use PFERR_GUEST_ENC_MASK to tell the fault is private

duplicated SOB

Quoted 86 lines
---
 arch/x86/kvm/vmx/common.h |  3 +++
 arch/x86/kvm/vmx/tdx.c    | 49 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+)
arch/x86/kvm/vmx/common.h +3 -0
index 632af7a76d0a..027aa4175d2c 100644
@@ -87,6 +87,9 @@ static inline int __vmx_handle_ept_violation(struct kvm_vcpu *vcpu, gpa_t gpa,
 	error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
 	       PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
 
+	if (kvm_is_private_gpa(vcpu->kvm, gpa))
+		error_code |= PFERR_GUEST_ENC_MASK;
+
 	return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
 }
 
arch/x86/kvm/vmx/tdx.c +49 -0
index 2f68e6f2b53a..0db80fa020d2 100644
@@ -1285,6 +1285,51 @@ void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
 	__vmx_deliver_posted_interrupt(vcpu, &tdx->pi_desc, vector);
 }
 
+static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)
+{
+	unsigned long exit_qual;
+
+	if (kvm_is_private_gpa(vcpu->kvm, tdexit_gpa(vcpu))) {
+		/*
+		 * Always treat SEPT violations as write faults.  Ignore the
+		 * EXIT_QUALIFICATION reported by TDX-SEAM for SEPT violations.
+		 * TD private pages are always RWX in the SEPT tables,
+		 * i.e. they're always mapped writable.  Just as importantly,
+		 * treating SEPT violations as write faults is necessary to
+		 * avoid COW allocations, which will cause TDAUGPAGE failures
+		 * due to aliasing a single HPA to multiple GPAs.
+		 */
+#define TDX_SEPT_VIOLATION_EXIT_QUAL	EPT_VIOLATION_ACC_WRITE
+		exit_qual = TDX_SEPT_VIOLATION_EXIT_QUAL;
+	} else {
+		exit_qual = tdexit_exit_qual(vcpu);
+		if (exit_qual & EPT_VIOLATION_ACC_INSTR) {
+			pr_warn("kvm: TDX instr fetch to shared GPA = 0x%lx @ RIP = 0x%lx\n",
+				tdexit_gpa(vcpu), kvm_rip_read(vcpu));
+			vcpu->run->exit_reason = KVM_EXIT_EXCEPTION;
+			vcpu->run->ex.exception = PF_VECTOR;
+			vcpu->run->ex.error_code = exit_qual;
+			return 0;
+		}
+	}
+
+	trace_kvm_page_fault(vcpu, tdexit_gpa(vcpu), exit_qual);
+	return __vmx_handle_ept_violation(vcpu, tdexit_gpa(vcpu), exit_qual);
+}
+
+static int tdx_handle_ept_misconfig(struct kvm_vcpu *vcpu)
+{
+	WARN_ON_ONCE(1);
+
+	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
+	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
+	vcpu->run->internal.ndata = 2;
+	vcpu->run->internal.data[0] = EXIT_REASON_EPT_MISCONFIG;
+	vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
+
+	return 0;
+}
+
 int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
 {
 	union tdx_exit_reason exit_reason = to_tdx(vcpu)->exit_reason;
@@ -1345,6 +1390,10 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
 	WARN_ON_ONCE(fastpath != EXIT_FASTPATH_NONE);
 
 	switch (exit_reason.basic) {
+	case EXIT_REASON_EPT_VIOLATION:
+		return tdx_handle_ept_violation(vcpu);
+	case EXIT_REASON_EPT_MISCONFIG:
+		return tdx_handle_ept_misconfig(vcpu);
 	case EXIT_REASON_OTHER_SMI:
 		/*
 		 * If reach here, it's not a Machine Check System Management
#50 lore raw

Re: [PATCH v19 008/130] x86/tdx: Warning with 32bit build shift-count-overflow

In reply to Kirill A. Shutemov
Quoted 16 lines · Kirill A. Shutemov
Quoted 7 lines · Kai
Quoted 4 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

This patch fixes the following warnings.

Quoted 7 lines
Quoted 7 lines
    In file included from arch/x86/kernel/asm-offsets.c:22:
    arch/x86/include/asm/tdx.h:92:87: warning: shift count >= width of type [-Wshift-count-overflow]
    arch/x86/include/asm/tdx.h:20:21: note: expanded from macro 'TDX_ERROR'
    #define TDX_ERROR                       _BITUL(63)

                                            ^~~~~~~~~~
Quoted 7 lines

I think you trim the warning message. I don't see the actual user of the define. Define itself will not generate the warning. You need to actually use it outside of preprocessor. I don't understand who would use it in 32-bit code. Maybe fixing it this way masking other issue.

That said, I don't object the change itself. We just need to understand the context more.

v18 used it as stub function. v19 dropped it as the stub was not needed.

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

Re: [PATCH v19 027/130] KVM: TDX: Define TDX architectural definitions

In reply to Yan Zhao
Quoted 6 lines · Yan Zhao
Quoted 3 lines

+ * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
+ */
+#define TDX_MAX_VCPUS (~(u16)0)

This value will be treated as -1 in tdx_vm_init(),

	"kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);"
Quoted 8 lines

This will lead to kvm->max_vcpus being -1 by default.
Is this by design or just an error?
If it's by design, why not set kvm->max_vcpus = -1 in tdx_vm_init() directly. If an unexpected error, may below is better?

#define TDX_MAX_VCPUS (int)((u16)(~0UL))
or
#define TDX_MAX_VCPUS 65536

You're right. I'll use ((int)U16_MAX).
As TDX 1.5 introduced metadata MAX_VCPUS_PER_TD, I'll update to get the value and trim it further. Something following.

arch/x86/include/asm/kvm-x86-ops.h +0 -1
index f964d99f8701..31205f84d594 100644
@@ -23,7 +23,6 @@ KVM_X86_OP(has_emulated_msr)
 /* TODO: Once all backend implemented this op, remove _OPTIONAL_RET0. */
 KVM_X86_OP_OPTIONAL_RET0(vcpu_check_cpuid)
 KVM_X86_OP(vcpu_after_set_cpuid)
-KVM_X86_OP_OPTIONAL(max_vcpus);
 KVM_X86_OP_OPTIONAL(vm_enable_cap)
 KVM_X86_OP(vm_init)
 KVM_X86_OP_OPTIONAL(flush_shadow_all_private)
arch/x86/kvm/vmx/main.c +0 -12
index 6dd78230c9d4..deb59e94990f 100644
@@ -13,17 +13,6 @@
 static bool enable_tdx __ro_after_init;
 module_param_named(tdx, enable_tdx, bool, 0444);
 
-static int vt_max_vcpus(struct kvm *kvm)
-{
-	if (!kvm)
-		return KVM_MAX_VCPUS;
-
-	if (is_td(kvm))
-		return min(kvm->max_vcpus, TDX_MAX_VCPUS);
-
-	return kvm->max_vcpus;
-}
-
 #if IS_ENABLED(CONFIG_HYPERV) || IS_ENABLED(CONFIG_INTEL_TDX_HOST)
 static int vt_flush_remote_tlbs(struct kvm *kvm);
 static int vt_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, gfn_t nr_pages);
@@ -1130,7 +1119,6 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.hardware_disable = vt_hardware_disable,
 	.has_emulated_msr = vt_has_emulated_msr,
 
-	.max_vcpus = vt_max_vcpus,
 	.vm_size = sizeof(struct kvm_vmx),
 	.vm_enable_cap = vt_vm_enable_cap,
 	.vm_init = vt_vm_init,
arch/x86/kvm/vmx/tdx.c +7 -2
index 7cca6a33ad97..a8cfb4f214a6 100644
@@ -63,6 +63,8 @@ struct tdx_info {
 	u8 nr_tdcs_pages;
 	u8 nr_tdvpx_pages;
 
+	u16 max_vcpus_per_td;
+
 	/*
 	 * The number of WBINVD domains. 0 means that wbinvd domain is cpu
 	 * package.
@@ -100,7 +102,8 @@ int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
 		if (cap->flags || cap->args[0] == 0)
 			return -EINVAL;
 		if (cap->args[0] > KVM_MAX_VCPUS ||
-		    cap->args[0] > TDX_MAX_VCPUS)
+		    cap->args[0] > TDX_MAX_VCPUS ||
+		    cap->args[0] > tdx_info->max_vcpus_per_td)
 			return -E2BIG;
 
 		mutex_lock(&kvm->lock);
@@ -729,7 +732,8 @@ int tdx_vm_init(struct kvm *kvm)
 	 * TDX has its own limit of the number of vcpus in addition to
 	 * KVM_MAX_VCPUS.
 	 */
-	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);
+	kvm->max_vcpus = min3(kvm->max_vcpus, tdx_info->max_vcpus_per_td,
+			     TDX_MAX_VCPUS);
 
 	mutex_init(&to_kvm_tdx(kvm)->source_lock);
 	return 0;
@@ -4667,6 +4671,7 @@ static int __init tdx_module_setup(void)
 		TDX_INFO_MAP(ATTRS_FIXED1, attributes_fixed1),
 		TDX_INFO_MAP(XFAM_FIXED0, xfam_fixed0),
 		TDX_INFO_MAP(XFAM_FIXED1, xfam_fixed1),
+		TDX_INFO_MAP(MAX_VCPUS_PER_TD, max_vcpus_per_td),
 	};
 
 	ret = tdx_enable();
arch/x86/kvm/vmx/tdx_arch.h +1 -1
index b10dad8f46bb..711855be6c83 100644
@@ -144,7 +144,7 @@ struct tdx_cpuid_value {
 /*
  * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
  */
-#define TDX_MAX_VCPUS	(~(u16)0)
+#define TDX_MAX_VCPUS	((int)U16_MAX)
 
 struct td_params {
 	u64 attributes;
arch/x86/kvm/x86.c +2 -2
index d097024fd974..6822a50e1d5d 100644
@@ -4733,8 +4733,8 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 		break;
 	case KVM_CAP_MAX_VCPUS:
 		r = KVM_MAX_VCPUS;
-		if (kvm_x86_ops.max_vcpus)
-			r = static_call(kvm_x86_max_vcpus)(kvm);
+		if (kvm)
+			r = kvm->max_vcpus;
 		break;
 	case KVM_CAP_MAX_VCPU_ID:
 		r = KVM_MAX_VCPU_IDS;
Signature · 1 line
Isaku Yamahata <[email protected]>
#536 lore raw

Re: [PATCH v19 091/130] KVM: TDX: remove use of struct vcpu_vmx from posted_interrupt.c

In reply to Binbin Wu
Quoted 138 lines · Binbin Wu
Quoted 4 lines · On 2/26/2024 4:26 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

As TDX will use posted_interrupt.c, the use of struct vcpu_vmx is a blocker. Because the members of

Extra "of"

Quoted 115 lines

struct pi_desc pi_desc and struct
list_head pi_wakeup_list are only used in posted_interrupt.c, introduce common structure, struct vcpu_pi, make vcpu_vmx and vcpu_tdx has same layout in the top of structure.

To minimize the diff size, avoid code conversion like, vmx->pi_desc => vmx->common->pi_desc. Instead add compile time check if the layout is expected.

---
  arch/x86/kvm/vmx/posted_intr.c | 41 ++++++++++++++++++++++++++--------
  arch/x86/kvm/vmx/posted_intr.h | 11 +++++++++
  arch/x86/kvm/vmx/tdx.c         |  1 +
  arch/x86/kvm/vmx/tdx.h         |  8 +++++++
  arch/x86/kvm/vmx/vmx.h         | 14 +++++++-----
  5 files changed, 60 insertions(+), 15 deletions(-)
arch/x86/kvm/vmx/posted_intr.c +32 -9
index af662312fd07..b66add9da0f3 100644
@@ -11,6 +11,7 @@
  #include "posted_intr.h"
  #include "trace.h"
  #include "vmx.h"
+#include "tdx.h"
  /*
   * Maintain a per-CPU list of vCPUs that need to be awakened by wakeup_handler()
@@ -31,9 +32,29 @@ static DEFINE_PER_CPU(struct list_head, wakeup_vcpus_on_cpu);
   */
  static DEFINE_PER_CPU(raw_spinlock_t, wakeup_vcpus_on_cpu_lock);
+/*
+ * The layout of the head of struct vcpu_vmx and struct vcpu_tdx must match with
+ * struct vcpu_pi.
+ */
+static_assert(offsetof(struct vcpu_pi, pi_desc) ==
+	      offsetof(struct vcpu_vmx, pi_desc));
+static_assert(offsetof(struct vcpu_pi, pi_wakeup_list) ==
+	      offsetof(struct vcpu_vmx, pi_wakeup_list));
+#ifdef CONFIG_INTEL_TDX_HOST
+static_assert(offsetof(struct vcpu_pi, pi_desc) ==
+	      offsetof(struct vcpu_tdx, pi_desc));
+static_assert(offsetof(struct vcpu_pi, pi_wakeup_list) ==
+	      offsetof(struct vcpu_tdx, pi_wakeup_list));
+#endif
+
+static inline struct vcpu_pi *vcpu_to_pi(struct kvm_vcpu *vcpu)
+{
+	return (struct vcpu_pi *)vcpu;
+}
+
  static inline struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
  {
-	return &(to_vmx(vcpu)->pi_desc);
+	return &vcpu_to_pi(vcpu)->pi_desc;
  }
  static int pi_try_set_control(struct pi_desc *pi_desc, u64 *pold, u64 new)
@@ -52,8 +73,8 @@ static int pi_try_set_control(struct pi_desc *pi_desc, u64 *pold, u64 new)
  void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
  {
-	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
-	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	struct vcpu_pi *vcpu_pi = vcpu_to_pi(vcpu);
+	struct pi_desc *pi_desc = &vcpu_pi->pi_desc;
  	struct pi_desc old, new;
  	unsigned long flags;
  	unsigned int dest;
@@ -90,7 +111,7 @@ void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
  	 */
  	if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR) {
  		raw_spin_lock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
-		list_del(&vmx->pi_wakeup_list);
+		list_del(&vcpu_pi->pi_wakeup_list);
  		raw_spin_unlock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
  	}
@@ -145,15 +166,15 @@ static bool vmx_can_use_vtd_pi(struct kvm *kvm)
   */
  static void pi_enable_wakeup_handler(struct kvm_vcpu *vcpu)
  {
-	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
-	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	struct vcpu_pi *vcpu_pi = vcpu_to_pi(vcpu);
+	struct pi_desc *pi_desc = &vcpu_pi->pi_desc;
  	struct pi_desc old, new;
  	unsigned long flags;
  	local_irq_save(flags);
  	raw_spin_lock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
-	list_add_tail(&vmx->pi_wakeup_list,
+	list_add_tail(&vcpu_pi->pi_wakeup_list,
  		      &per_cpu(wakeup_vcpus_on_cpu, vcpu->cpu));
  	raw_spin_unlock(&per_cpu(wakeup_vcpus_on_cpu_lock, vcpu->cpu));
@@ -190,7 +211,8 @@ static bool vmx_needs_pi_wakeup(struct kvm_vcpu *vcpu)
  	 * notification vector is switched to the one that calls
  	 * back to the pi_wakeup_handler() function.
  	 */
-	return vmx_can_use_ipiv(vcpu) || vmx_can_use_vtd_pi(vcpu->kvm);
+	return (vmx_can_use_ipiv(vcpu) && !is_td_vcpu(vcpu)) ||
+		vmx_can_use_vtd_pi(vcpu->kvm);
  }
  void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
@@ -200,7 +222,8 @@ void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
  	if (!vmx_needs_pi_wakeup(vcpu))
  		return;
-	if (kvm_vcpu_is_blocking(vcpu) && !vmx_interrupt_blocked(vcpu))
+	if (kvm_vcpu_is_blocking(vcpu) &&
+	    (is_td_vcpu(vcpu) || !vmx_interrupt_blocked(vcpu)))
  		pi_enable_wakeup_handler(vcpu);
  	/*
arch/x86/kvm/vmx/posted_intr.h +0 -0
index 26992076552e..2fe8222308b2 100644
@@ -94,6 +94,17 @@ static inline bool pi_test_sn(struct pi_desc *pi_desc)
  			(unsigned long *)&pi_desc->control);

arch/x86/kvm/vmx/posted_intr.h static inline bool pi_test_sn(struct pi_desc *pi_desc) · line 104

Quoted 10 lines
arch/x86/kvm/vmx/posted_intr.h +9 -0
  }
+struct vcpu_pi {
+	struct kvm_vcpu	vcpu;
+
+	/* Posted interrupt descriptor */
+	struct pi_desc pi_desc;
+
+	/* Used if this vCPU is waiting for PI notification wakeup. */
+	struct list_head pi_wakeup_list;
+	/* Until here common layout betwwn vcpu_vmx and vcpu_tdx. */

s/betwwn/between

Quoted 5 lines

Also, in pi_wakeup_handler(), it is still using struct vcpu_vmx, but it could
be vcpu_tdx.
Functionally it is OK, however, since you have added vcpu_pi, should it use vcpu_pi instead of vcpu_vmx in pi_wakeup_handler()?

Makes sense.

arch/x86/kvm/vmx/posted_intr.c +4 -5
index b66add9da0f3..5b71aef931dc 100644
@@ -243,13 +243,13 @@ void pi_wakeup_handler(void)
        int cpu = smp_processor_id();
        struct list_head *wakeup_list = &per_cpu(wakeup_vcpus_on_cpu, cpu);
        raw_spinlock_t *spinlock = &per_cpu(wakeup_vcpus_on_cpu_lock, cpu);
-       struct vcpu_vmx *vmx;
+       struct vcpu_pi *pi;
 
        raw_spin_lock(spinlock);
-       list_for_each_entry(vmx, wakeup_list, pi_wakeup_list) {
+       list_for_each_entry(pi, wakeup_list, pi_wakeup_list) {
 
-               if (pi_test_on(&vmx->pi_desc))
-                       kvm_vcpu_wake_up(&vmx->vcpu);
+               if (pi_test_on(&pi->pi_desc))
+                       kvm_vcpu_wake_up(&pi->vcpu);
        }
 
-- 

Isaku Yamahata <[email protected]>

#51 lore raw

Re: [PATCH v19 008/130] x86/tdx: Warning with 32bit build shift-count-overflow

In reply to Isaku Yamahata
Quoted 24 lines · Isaku Yamahata
Quoted 21 lines · Kirill A. Shutemov
Quoted 7 lines · Kai
Quoted 4 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

This patch fixes the following warnings.

Quoted 7 lines
Quoted 7 lines
     In file included from arch/x86/kernel/asm-offsets.c:22:
     arch/x86/include/asm/tdx.h:92:87: warning: shift count >= width of type [-Wshift-count-overflow]
     arch/x86/include/asm/tdx.h:20:21: note: expanded from macro 'TDX_ERROR'
     #define TDX_ERROR                       _BITUL(63)

                                             ^~~~~~~~~~

I think you trim the warning message. I don't see the actual user of the define. Define itself will not generate the warning. You need to actually use it outside of preprocessor. I don't understand who would use it in 32-bit code. Maybe fixing it this way masking other issue.

Quoted 4 lines
Quoted 2 lines

That said, I don't object the change itself. We just need to understand the context more.

v18 used it as stub function. v19 dropped it as the stub was not needed.

Sorry I literally don't understand what you are talking about here.

Please just clarify (at least):

- Does this problem exist in upstream code?
- If it does, what is the root cause, and how to reproduce?

#79 lore raw

Re: [PATCH v19 016/130] KVM: x86/mmu: Introduce kvm_mmu_map_tdp_page() for use by TDX

In reply to [email protected]
Quoted 59 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Introduce a helper to directly (pun intended) fault-in a TDP page without having to go through the full page fault path. This allows TDX to get the resulting pfn and also allows the RET_PF_* enums to stay in mmu.c where they belong.

---
v19:
- Move up for KVM_MEMORY_MAPPING.
- Add goal_level for the caller to know how many pages are mapped.

v14 -> v15:
- Remove loop in kvm_mmu_map_tdp_page() and return error code based on RET_FP_xxx value to avoid potential infinite loop. The caller should loop on -EAGAIN instead now.

---
  arch/x86/kvm/mmu.h     |  3 +++
  arch/x86/kvm/mmu/mmu.c | 58 ++++++++++++++++++++++++++++++++++++++++++
  2 files changed, 61 insertions(+)
arch/x86/kvm/mmu.h +3 -0
index 60f21bb4c27b..d96c93a25b3b 100644
@@ -183,6 +183,9 @@ static inline void kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
  	__kvm_mmu_refresh_passthrough_bits(vcpu, mmu);
  }
 
+int kvm_mmu_map_tdp_page(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code,
+			 u8 max_level, u8 *goal_level);
+
  /*
   * Check if a given access (described through the I/D, W/R and U/S bits of a
   * page fault error code pfec) causes a permission fault with the given PTE
arch/x86/kvm/mmu/mmu.c +12 -0
index 61674d6b17aa..ca0c91f14063 100644
@@ -4615,6 +4615,64 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  	return direct_page_fault(vcpu, fault);
  }
 
+int kvm_mmu_map_tdp_page(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code,
+			 u8 max_level, u8 *goal_level)
+{
+	int r;
+	struct kvm_page_fault fault = (struct kvm_page_fault) {
+		.addr = gpa,
+		.error_code = error_code,
+		.exec = error_code & PFERR_FETCH_MASK,
+		.write = error_code & PFERR_WRITE_MASK,
+		.present = error_code & PFERR_PRESENT_MASK,
+		.rsvd = error_code & PFERR_RSVD_MASK,
+		.user = error_code & PFERR_USER_MASK,

arch/x86/kvm/mmu/mmu.c int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 4639

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+		.prefetch = false,
+		.is_tdp = true,
+		.is_private = error_code & PFERR_GUEST_ENC_MASK,
+		.nx_huge_page_workaround_enabled = is_nx_huge_page_enabled(vcpu->kvm),
+	};
+
+	WARN_ON_ONCE(!vcpu->arch.mmu->root_role.direct);
+	fault.slot = kvm_vcpu_gfn_to_memslot(vcpu, fault.gfn);
+
+	r = mmu_topup_memory_caches(vcpu, false);

Does it need a cache topup here?
Both kvm_tdp_mmu_page_fault() and direct_page_fault() will call mmu_topup_memory_caches() when needed.

Quoted 39 lines
arch/x86/kvm/mmu/mmu.c +36 -0
+	if (r)
+		return r;
+
+	fault.max_level = max_level;
+	fault.req_level = PG_LEVEL_4K;
+	fault.goal_level = PG_LEVEL_4K;
+
+#ifdef CONFIG_X86_64
+	if (tdp_mmu_enabled)
+		r = kvm_tdp_mmu_page_fault(vcpu, &fault);
+	else
+#endif
+		r = direct_page_fault(vcpu, &fault);
+
+	if (is_error_noslot_pfn(fault.pfn) || vcpu->kvm->vm_bugged)
+		return -EFAULT;
+
+	switch (r) {
+	case RET_PF_RETRY:
+		return -EAGAIN;
+
+	case RET_PF_FIXED:
+	case RET_PF_SPURIOUS:
+		if (goal_level)
+			*goal_level = fault.goal_level;
+		return 0;
+
+	case RET_PF_CONTINUE:
+	case RET_PF_EMULATE:
+	case RET_PF_INVALID:
+	default:
+		return -EIO;
+	}
+}
+EXPORT_SYMBOL_GPL(kvm_mmu_map_tdp_page);
+
  static void nonpaging_init_context(struct kvm_mmu *context)
  {
  	context->page_fault = nonpaging_page_fault;
#14 lore raw

Re: [PATCH v19 005/130] x86/virt/tdx: Export global metadata read infrastructure

In reply to [email protected]
Quoted 111 lines · On 26.02.2024 00:25, [email protected] wrote:

From: Kai Huang <[email protected]>

KVM will need to read a bunch of non-TDMR related metadata to create and run TDX guests. Export the metadata read infrastructure for KVM to use.

Specifically, export two helpers:

1) The helper which reads multiple metadata fields to a buffer of a structure based on the "field ID -> structure member" mapping table.

2) The low level helper which just reads a given field ID.

The two helpers cover cases when the user wants to cache a bunch of metadata fields to a certain structure and when the user just wants to query a specific metadata field on demand. They are enough for KVM to use (and also should be enough for other potential users).

---
arch/x86/include/asm/tdx.h | 22 ++++++++++++++++++++++ arch/x86/virt/vmx/tdx/tdx.c | 25 ++++++++-----------------

2 files changed, 30 insertions(+), 17 deletions(-)
arch/x86/include/asm/tdx.h +22 -0
index eba178996d84..709b9483f9e4 100644
@@ -116,6 +116,28 @@ static inline u64 sc_retry(sc_func_t func, u64 fn,
 int tdx_cpu_enable(void);
 int tdx_enable(void);
 const char *tdx_dump_mce_info(struct mce *m);
+
+struct tdx_metadata_field_mapping {
+	u64 field_id;
+	int offset;
+	int size;
+};
+
+#define TD_SYSINFO_MAP(_field_id, _struct, _member)	\
+	{ .field_id = MD_FIELD_ID_##_field_id,		\
+	  .offset   = offsetof(_struct, _member),	\
+	  .size     = sizeof(typeof(((_struct *)0)->_member)) }
+
+/*
+ * Read multiple global metadata fields to a buffer of a structure
+ * based on the "field ID -> structure member" mapping table.
+ */
+int tdx_sys_metadata_read(const struct tdx_metadata_field_mapping *fields,
+			  int nr_fields, void *stbuf);
+
+/* Read a single global metadata field */
+int tdx_sys_metadata_field_read(u64 field_id, u64 *data);
+
 #else
 static inline void tdx_init(void) { }
 static inline int tdx_cpu_enable(void) { return -ENODEV; }
arch/x86/virt/vmx/tdx/tdx.c +5 -15
index a19adc898df6..dc21310776ab 100644
@@ -251,7 +251,7 @@ static int build_tdx_memlist(struct list_head *tmb_list)
 	return ret;
 }
 
-static int read_sys_metadata_field(u64 field_id, u64 *data)
+int tdx_sys_metadata_field_read(u64 field_id, u64 *data)
 {
 	struct tdx_module_args args = {};
 	int ret;
@@ -270,6 +270,7 @@ static int read_sys_metadata_field(u64 field_id, u64 *data)
 
 	return 0;
 }
+EXPORT_SYMBOL_GPL(tdx_sys_metadata_field_read);
 
 /* Return the metadata field element size in bytes */
 static int get_metadata_field_bytes(u64 field_id)
@@ -295,7 +296,7 @@ static int stbuf_read_sys_metadata_field(u64 field_id,
 	if (WARN_ON_ONCE(get_metadata_field_bytes(field_id) != bytes))
 		return -EINVAL;
 
-	ret = read_sys_metadata_field(field_id, &tmp);
+	ret = tdx_sys_metadata_field_read(field_id, &tmp);
 	if (ret)
 		return ret;
 
@@ -304,19 +305,8 @@ static int stbuf_read_sys_metadata_field(u64 field_id,
 	return 0;
 }
 
-struct field_mapping {
-	u64 field_id;
-	int offset;
-	int size;
-};
-
-#define TD_SYSINFO_MAP(_field_id, _struct, _member)	\
-	{ .field_id = MD_FIELD_ID_##_field_id,		\
-	  .offset   = offsetof(_struct, _member),	\
-	  .size     = sizeof(typeof(((_struct *)0)->_member)) }
-
-static int read_sys_metadata(struct field_mapping *fields, int nr_fields,
-			     void *stbuf)
+int tdx_sys_metadata_read(const struct tdx_metadata_field_mapping *fields,
+			  int nr_fields, void *stbuf)
 {
 	int i, ret;
 

arch/x86/virt/vmx/tdx/tdx.c static int read_sys_metadata(struct field_mapping *fields, int nr_fields, · line 324

Quoted 4 lines
arch/x86/virt/vmx/tdx/tdx.c +1 -0
@@ -331,6 +321,7 @@ static int read_sys_metadata(struct field_mapping *fields, int nr_fields,
 
 	return 0;
 }
+EXPORT_SYMBOL_GPL(tdx_sys_metadata_read);

Hi Kai,

The two helpers can potentially be used by TD guests, as you mentioned. It's a good idea to declare it in the header asm/tdx.h.

However, the function cannot be compiled if its definition remains in the vmx/tdx/tdx.c file while disabling the CONFIG_TDX_HOST.

It would be better to move the definition to a shared location, allowing the host and guest to share the same code.

Thanks
--Sun, Yi

#15 lore raw

Re: [PATCH v19 005/130] x86/virt/tdx: Export global metadata read infrastructure

Quoted 8 lines

However, the function cannot be compiled if its definition remains in the vmx/tdx/tdx.c file while disabling the CONFIG_TDX_HOST.

It would be better to move the definition to a shared location, allowing the host and guest to share the same code.

No not in this series. Such change needs to be in your series.

Thanks,
-Kai

#52 lore raw

Re: [PATCH v19 008/130] x86/tdx: Warning with 32bit build shift-count-overflow

In reply to Huang, Kai
Quoted 30 lines · Kai
Quoted 27 lines · Isaku Yamahata
Quoted 23 lines · Kirill A. Shutemov
Quoted 7 lines · Kai
Quoted 4 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

This patch fixes the following warnings.

Quoted 7 lines
Quoted 7 lines
     In file included from arch/x86/kernel/asm-offsets.c:22:
     arch/x86/include/asm/tdx.h:92:87: warning: shift count >= width of type [-Wshift-count-overflow]
     arch/x86/include/asm/tdx.h:20:21: note: expanded from macro 'TDX_ERROR'
     #define TDX_ERROR                       _BITUL(63)

                                             ^~~~~~~~~~

I think you trim the warning message. I don't see the actual user of the define. Define itself will not generate the warning. You need to actually use it outside of preprocessor. I don't understand who would use it in 32-bit code. Maybe fixing it this way masking other issue.

That said, I don't object the change itself. We just need to understand the context more.

Quoted 7 lines
Quoted 1 line

v18 used it as stub function. v19 dropped it as the stub was not needed.

Sorry I literally don't understand what you are talking about here.

Please just clarify (at least):

- Does this problem exist in upstream code?

No.

Quoted 1 line

- If it does, what is the root cause, and how to reproduce?

v18 had a problem because it has stub function. v19 doesn't have problem because it deleted the stub function.

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

Re: [PATCH v19 016/130] KVM: x86/mmu: Introduce kvm_mmu_map_tdp_page() for use by TDX

In reply to Binbin Wu
Quoted 66 lines · Binbin Wu
Quoted 63 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Introduce a helper to directly (pun intended) fault-in a TDP page without having to go through the full page fault path. This allows TDX to get the resulting pfn and also allows the RET_PF_* enums to stay in mmu.c where they belong.

---
v19:
- Move up for KVM_MEMORY_MAPPING.
- Add goal_level for the caller to know how many pages are mapped.

v14 -> v15:
- Remove loop in kvm_mmu_map_tdp_page() and return error code based on RET_FP_xxx value to avoid potential infinite loop. The caller should loop on -EAGAIN instead now.

---
  arch/x86/kvm/mmu.h     |  3 +++
  arch/x86/kvm/mmu/mmu.c | 58 ++++++++++++++++++++++++++++++++++++++++++
  2 files changed, 61 insertions(+)
arch/x86/kvm/mmu.h +3 -0
index 60f21bb4c27b..d96c93a25b3b 100644
@@ -183,6 +183,9 @@ static inline void kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
  	__kvm_mmu_refresh_passthrough_bits(vcpu, mmu);
  }
+int kvm_mmu_map_tdp_page(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code,
+			 u8 max_level, u8 *goal_level);
+
  /*
   * Check if a given access (described through the I/D, W/R and U/S bits of a
   * page fault error code pfec) causes a permission fault with the given PTE
arch/x86/kvm/mmu/mmu.c +18 -0
index 61674d6b17aa..ca0c91f14063 100644
@@ -4615,6 +4615,64 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  	return direct_page_fault(vcpu, fault);
  }
+int kvm_mmu_map_tdp_page(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code,
+			 u8 max_level, u8 *goal_level)
+{
+	int r;
+	struct kvm_page_fault fault = (struct kvm_page_fault) {
+		.addr = gpa,
+		.error_code = error_code,
+		.exec = error_code & PFERR_FETCH_MASK,
+		.write = error_code & PFERR_WRITE_MASK,
+		.present = error_code & PFERR_PRESENT_MASK,
+		.rsvd = error_code & PFERR_RSVD_MASK,
+		.user = error_code & PFERR_USER_MASK,
+		.prefetch = false,
+		.is_tdp = true,
+		.is_private = error_code & PFERR_GUEST_ENC_MASK,
+		.nx_huge_page_workaround_enabled = is_nx_huge_page_enabled(vcpu->kvm),
+	};
+
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 4639

Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +4 -0
+	WARN_ON_ONCE(!vcpu->arch.mmu->root_role.direct);
+	fault.slot = kvm_vcpu_gfn_to_memslot(vcpu, fault.gfn);
+
+	r = mmu_topup_memory_caches(vcpu, false);

Does it need a cache topup here?
Both kvm_tdp_mmu_page_fault() and direct_page_fault() will call mmu_topup_memory_caches() when needed.

You're right. As the called function has changed, I missed to remove it.

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

Re: [PATCH v19 008/130] x86/tdx: Warning with 32bit build shift-count-overflow

In reply to Isaku Yamahata
Quoted 11 lines
Quoted 4 lines

Please just clarify (at least):

- Does this problem exist in upstream code?

No.

Quoted 1 line

- If it does, what is the root cause, and how to reproduce?

v18 had a problem because it has stub function. v19 doesn't have problem because it deleted the stub function.

What is the "stub function"??

If "v19 doesn't have problem", why do you even _need_ this patch??

I am tired of guessing, but I don't care anymore given it's not a problem in upstream code.

#75 lore raw

Re: [PATCH v19 014/130] KVM: Add KVM vcpu ioctl to pre-populate guest memory

In reply to [email protected]
Quoted 78 lines · On 2/26/24 16:25, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add new ioctl KVM_MEMORY_MAPPING in the kvm common code. It iterates on the memory range and call arch specific function. Add stub function as weak symbol.

---
v19:
- newly added

---
 include/linux/kvm_host.h |  4 +++
 include/uapi/linux/kvm.h | 10 ++++++
 virt/kvm/kvm_main.c      | 67 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 81 insertions(+)
include/linux/kvm_host.h +4 -0
index 0520cd8d03cc..eeaf4e73317c 100644
@@ -2389,4 +2389,8 @@ static inline int kvm_gmem_get_pfn(struct kvm *kvm,
 }
 #endif /* CONFIG_KVM_PRIVATE_MEM */
 
+void kvm_arch_vcpu_pre_memory_mapping(struct kvm_vcpu *vcpu);
+int kvm_arch_vcpu_memory_mapping(struct kvm_vcpu *vcpu,
+				 struct kvm_memory_mapping *mapping);
+
 #endif
include/uapi/linux/kvm.h +10 -0
index c3308536482b..5e2b28934aa9 100644
@@ -1155,6 +1155,7 @@ struct kvm_ppc_resize_hpt {
 #define KVM_CAP_MEMORY_ATTRIBUTES 233
 #define KVM_CAP_GUEST_MEMFD 234
 #define KVM_CAP_VM_TYPES 235
+#define KVM_CAP_MEMORY_MAPPING 236
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
@@ -2227,4 +2228,13 @@ struct kvm_create_guest_memfd {
 	__u64 reserved[6];
 };
 
+#define KVM_MEMORY_MAPPING	_IOWR(KVMIO, 0xd5, struct kvm_memory_mapping)
+
+struct kvm_memory_mapping {
+	__u64 base_gfn;
+	__u64 nr_pages;
+	__u64 flags;
+	__u64 source;
+};
+
 #endif /* __LINUX_KVM_H */
virt/kvm/kvm_main.c +15 -0
index 0349e1f241d1..2f0a8e28795e 100644
@@ -4409,6 +4409,62 @@ static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
 	return fd;
 }
 
+__weak void kvm_arch_vcpu_pre_memory_mapping(struct kvm_vcpu *vcpu)
+{
+}
+
+__weak int kvm_arch_vcpu_memory_mapping(struct kvm_vcpu *vcpu,
+					struct kvm_memory_mapping *mapping)
+{
+	return -EOPNOTSUPP;
+}
+
+static int kvm_vcpu_memory_mapping(struct kvm_vcpu *vcpu,
+				   struct kvm_memory_mapping *mapping)
+{
+	bool added = false;
+	int idx, r = 0;

virt/kvm/kvm_main.c static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu) · line 4436

Quoted 10 lines
virt/kvm/kvm_main.c +10 -0
+
+	/* flags isn't used yet. */
+	if (mapping->flags)
+		return -EINVAL;
+
+	/* Sanity check */
+	if (!IS_ALIGNED(mapping->source, PAGE_SIZE) ||
+	    !mapping->nr_pages ||
+	    mapping->nr_pages & GENMASK_ULL(63, 63 - PAGE_SHIFT) ||
+	    mapping->base_gfn + mapping->nr_pages <= mapping->base_gfn)

I suppose !mapping->nr_pages can be deleted as this line can cover it.

Quoted 35 lines
virt/kvm/kvm_main.c +31 -0
+		return -EINVAL;
+
+	vcpu_load(vcpu);
+	idx = srcu_read_lock(&vcpu->kvm->srcu);
+	kvm_arch_vcpu_pre_memory_mapping(vcpu);
+
+	while (mapping->nr_pages) {
+		if (signal_pending(current)) {
+			r = -ERESTARTSYS;
+			break;
+		}
+
+		if (need_resched())
+			cond_resched();
+
+		r = kvm_arch_vcpu_memory_mapping(vcpu, mapping);
+		if (r)
+			break;
+
+		added = true;
+	}
+
+	srcu_read_unlock(&vcpu->kvm->srcu, idx);
+	vcpu_put(vcpu);
+
+	if (added && mapping->nr_pages > 0)
+		r = -EAGAIN;
+
+	return r;
+}
+
 static long kvm_vcpu_ioctl(struct file *filp,
 			   unsigned int ioctl, unsigned long arg)
 {

virt/kvm/kvm_main.c static long kvm_vcpu_ioctl(struct file *filp, · line 4675

Quoted 10 lines
virt/kvm/kvm_main.c +7 -0
@@ -4610,6 +4666,17 @@ static long kvm_vcpu_ioctl(struct file *filp,
 		r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
 		break;
 	}
+	case KVM_MEMORY_MAPPING: {
+		struct kvm_memory_mapping mapping;
+
+		r = -EFAULT;
+		if (copy_from_user(&mapping, argp, sizeof(mapping)))
+			break;
+		r = kvm_vcpu_memory_mapping(vcpu, &mapping);

return value r should be checked before copy_to_user

Regards
Yin, Fengwei

Quoted 7 lines
virt/kvm/kvm_main.c +4 -0
+		if (copy_to_user(argp, &mapping, sizeof(mapping)))
+			r = -EFAULT;
+		break;
+	}
 	default:
 		r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
 	}
#73 lore raw

Re: [PATCH v19 013/130] KVM: x86: Use PFERR_GUEST_ENC_MASK to indicate fault is private

In reply to [email protected]

arch/x86/kvm/mmu/mmu.c int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 err · line 5823

Quoted 5 lines · On 2/26/24 16:25, [email protected] wrote:
arch/x86/kvm/mmu/mmu.c +5 -0
+	/*
+	 * This is racy with updating memory attributes with mmu_seq.  If we
+	 * hit a race, it would result in retrying page fault.
+	 */
+	if (vcpu->kvm->arch.vm_type == KVM_X86_SW_PROTECTED_VM &&

There are more than two times of similar check in this patchset. Maybe it's better to add a helper function to tell whether the type is KVM_X86_SW_PROTECTED_VM?

Regards
Yin, Fengwei

Quoted 3 lines
arch/x86/kvm/mmu/mmu.c +3 -0
+	    kvm_mem_is_private(vcpu->kvm, gpa_to_gfn(cr2_or_gpa)))
+		error_code |= PFERR_GUEST_ENC_MASK;
+
#485 lore raw

Re: [PATCH v19 080/130] KVM: TDX: restore host xsave state when exit from the guest TD

In reply to [email protected]
Quoted 41 lines · On 2024-02-26 at 00:26:22 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

On exiting from the guest TD, xsave state is clobbered. Restore xsave state on TD exit.

---
v19:
- Add EXPORT_SYMBOL_GPL(host_xcr0)

v15 -> v16:
- Added CET flag mask

---
 arch/x86/kvm/vmx/tdx.c | 19 +++++++++++++++++++
 arch/x86/kvm/x86.c     |  1 +
 2 files changed, 20 insertions(+)
arch/x86/kvm/vmx/tdx.c +7 -0
index 9616b1aab6ce..199226c6cf55 100644
@@ -2,6 +2,7 @@
 #include <linux/cpu.h>
 #include <linux/mmu_context.h>
 
+#include <asm/fpu/xcr.h>
 #include <asm/tdx.h>
 
 #include "capabilities.h"
@@ -534,6 +535,23 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	 */
 }
 
+static void tdx_restore_host_xsave_state(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+
+	if (static_cpu_has(X86_FEATURE_XSAVE) &&
+	    host_xcr0 != (kvm_tdx->xfam & kvm_caps.supported_xcr0))

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
+	if (static_cpu_has(X86_FEATURE_XSAVES) &&
+	    /* PT can be exposed to TD guest regardless of KVM's XSS support */
+	    host_xss != (kvm_tdx->xfam &
+			 (kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET)))
+		wrmsrl(MSR_IA32_XSS, host_xss);
+	if (static_cpu_has(X86_FEATURE_PKU) &&
+	    (kvm_tdx->xfam & XFEATURE_MASK_PKRU))
+		write_pkru(vcpu->arch.host_pkru);
+}

Maybe one minor question regarding the pkru restore. In the non-TDX version kvm_load_host_xsave_state(), it first tries to read the current setting vcpu->arch.pkru = rdpkru(); if this setting does not equal to host_pkru, it trigger the write_pkru on host. Does it mean we can also leverage that mechanism in TDX to avoid 1 pkru write(I guess pkru write is costly than a read pkru)?

thanks,
Chenyu

Reviewed-by on v19 1/130
#2 lore raw

Re: [PATCH v19 001/130] x86/virt/tdx: Rename _offset to _member for TD_SYSINFO_MAP() macro

In reply to [email protected]
Quoted 11 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Kai Huang <[email protected]>

TD_SYSINFO_MAP() macro actually takes the member of the 'struct tdx_tdmr_sysinfo' as the second argument and uses the offsetof() to calculate the offset for that member.

Rename the macro argument _offset to _member to reflect this.

Quoted 20 lines
---
  arch/x86/virt/vmx/tdx/tdx.c | 4 ++--
  1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +2 -2
index 4d6826a76f78..2aee64d2f27f 100644
@@ -297,9 +297,9 @@ struct field_mapping {
  	int offset;
  };
 
-#define TD_SYSINFO_MAP(_field_id, _offset) \
+#define TD_SYSINFO_MAP(_field_id, _member) \
  	{ .field_id = MD_FIELD_ID_##_field_id,	   \
-	  .offset   = offsetof(struct tdx_tdmr_sysinfo, _offset) }
+	  .offset   = offsetof(struct tdx_tdmr_sysinfo, _member) }
 
  /* Map TD_SYSINFO fields into 'struct tdx_tdmr_sysinfo': */
  static const struct field_mapping fields[] = {
Reviewed-by on v19 2/130
#5 lore raw

Re: [PATCH v19 002/130] x86/virt/tdx: Move TDMR metadata fields map table to local variable

In reply to [email protected]
Quoted 6 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Kai Huang <[email protected]>

The kernel reads all TDMR related global metadata fields based on a table which maps the metadata fields to the corresponding members of 'struct tdx_tdmr_sysinfo'. Currently this table is a static variable.

Quoted 6 lines

But this table is only used by the function which reads these metadata fields and becomes useless after reading is done. Change the table to function local variable.

Quoted 34 lines
---
  arch/x86/virt/vmx/tdx/tdx.c | 17 ++++++++---------
  1 file changed, 8 insertions(+), 9 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +8 -9
index 2aee64d2f27f..cdcb3332bc5d 100644
@@ -301,17 +301,16 @@ struct field_mapping {
  	{ .field_id = MD_FIELD_ID_##_field_id,	   \
  	  .offset   = offsetof(struct tdx_tdmr_sysinfo, _member) }
 
-/* Map TD_SYSINFO fields into 'struct tdx_tdmr_sysinfo': */
-static const struct field_mapping fields[] = {
-	TD_SYSINFO_MAP(MAX_TDMRS,	      max_tdmrs),
-	TD_SYSINFO_MAP(MAX_RESERVED_PER_TDMR, max_reserved_per_tdmr),
-	TD_SYSINFO_MAP(PAMT_4K_ENTRY_SIZE,    pamt_entry_size[TDX_PS_4K]),
-	TD_SYSINFO_MAP(PAMT_2M_ENTRY_SIZE,    pamt_entry_size[TDX_PS_2M]),
-	TD_SYSINFO_MAP(PAMT_1G_ENTRY_SIZE,    pamt_entry_size[TDX_PS_1G]),
-};
-
  static int get_tdx_tdmr_sysinfo(struct tdx_tdmr_sysinfo *tdmr_sysinfo)
  {
+	/* Map TD_SYSINFO fields into 'struct tdx_tdmr_sysinfo': */
+	const struct field_mapping fields[] = {
+		TD_SYSINFO_MAP(MAX_TDMRS,	      max_tdmrs),
+		TD_SYSINFO_MAP(MAX_RESERVED_PER_TDMR, max_reserved_per_tdmr),
+		TD_SYSINFO_MAP(PAMT_4K_ENTRY_SIZE,    pamt_entry_size[TDX_PS_4K]),
+		TD_SYSINFO_MAP(PAMT_2M_ENTRY_SIZE,    pamt_entry_size[TDX_PS_2M]),
+		TD_SYSINFO_MAP(PAMT_1G_ENTRY_SIZE,    pamt_entry_size[TDX_PS_1G]),
+	};
  	int ret;
  	int i;
 
Reviewed-by on v19 3/130
#9 lore raw

Re: [PATCH v19 003/130] x86/virt/tdx: Unbind global metadata read with 'struct tdx_tdmr_sysinfo'

In reply to [email protected]
Quoted 10 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Kai Huang <[email protected]>

For now the kernel only reads TDMR related global metadata fields for module initialization, and the metadata read code only works with the 'struct tdx_tdmr_sysinfo'.

KVM will need to read a bunch of non-TDMR related metadata to create and run TDX guests. It's essential to provide a generic metadata read infrastructure which is not bound to any specific structure.

Quoted 6 lines

To start providing such infrastructure, unbound the metadata read with the 'struct tdx_tdmr_sysinfo'.

Quoted 60 lines
---
  arch/x86/virt/vmx/tdx/tdx.c | 25 ++++++++++++++-----------
  1 file changed, 14 insertions(+), 11 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +14 -11
index cdcb3332bc5d..eb208da4ff63 100644
@@ -273,9 +273,9 @@ static int read_sys_metadata_field(u64 field_id, u64 *data)
 
  static int read_sys_metadata_field16(u64 field_id,
  				     int offset,
-				     struct tdx_tdmr_sysinfo *ts)
+				     void *stbuf)
  {
-	u16 *ts_member = ((void *)ts) + offset;
+	u16 *st_member = stbuf + offset;
  	u64 tmp;
  	int ret;
 
@@ -287,7 +287,7 @@ static int read_sys_metadata_field16(u64 field_id,
  	if (ret)
  		return ret;
 
-	*ts_member = tmp;
+	*st_member = tmp;
 
  	return 0;
  }
@@ -297,19 +297,22 @@ struct field_mapping {
  	int offset;
  };
 
-#define TD_SYSINFO_MAP(_field_id, _member) \
-	{ .field_id = MD_FIELD_ID_##_field_id,	   \
-	  .offset   = offsetof(struct tdx_tdmr_sysinfo, _member) }
+#define TD_SYSINFO_MAP(_field_id, _struct, _member)	\
+	{ .field_id = MD_FIELD_ID_##_field_id,		\
+	  .offset   = offsetof(_struct, _member) }
+
+#define TD_SYSINFO_MAP_TDMR_INFO(_field_id, _member)	\
+	TD_SYSINFO_MAP(_field_id, struct tdx_tdmr_sysinfo, _member)
 
  static int get_tdx_tdmr_sysinfo(struct tdx_tdmr_sysinfo *tdmr_sysinfo)
  {
  	/* Map TD_SYSINFO fields into 'struct tdx_tdmr_sysinfo': */
  	const struct field_mapping fields[] = {
-		TD_SYSINFO_MAP(MAX_TDMRS,	      max_tdmrs),
-		TD_SYSINFO_MAP(MAX_RESERVED_PER_TDMR, max_reserved_per_tdmr),
-		TD_SYSINFO_MAP(PAMT_4K_ENTRY_SIZE,    pamt_entry_size[TDX_PS_4K]),
-		TD_SYSINFO_MAP(PAMT_2M_ENTRY_SIZE,    pamt_entry_size[TDX_PS_2M]),
-		TD_SYSINFO_MAP(PAMT_1G_ENTRY_SIZE,    pamt_entry_size[TDX_PS_1G]),
+		TD_SYSINFO_MAP_TDMR_INFO(MAX_TDMRS,		max_tdmrs),
+		TD_SYSINFO_MAP_TDMR_INFO(MAX_RESERVED_PER_TDMR, max_reserved_per_tdmr),
+		TD_SYSINFO_MAP_TDMR_INFO(PAMT_4K_ENTRY_SIZE,    pamt_entry_size[TDX_PS_4K]),
+		TD_SYSINFO_MAP_TDMR_INFO(PAMT_2M_ENTRY_SIZE,    pamt_entry_size[TDX_PS_2M]),
+		TD_SYSINFO_MAP_TDMR_INFO(PAMT_1G_ENTRY_SIZE,    pamt_entry_size[TDX_PS_1G]),
  	};
  	int ret;
  	int i;
Reviewed-by on v19 5/130
#16 lore raw

Re: [PATCH v19 005/130] x86/virt/tdx: Export global metadata read infrastructure

In reply to [email protected]
Quoted 12 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Kai Huang <[email protected]>

KVM will need to read a bunch of non-TDMR related metadata to create and run TDX guests. Export the metadata read infrastructure for KVM to use.

Specifically, export two helpers:

1) The helper which reads multiple metadata fields to a buffer of a

    structure based on the "field ID -> structure member" mapping table.

2) The low level helper which just reads a given field ID.

Quoted 8 lines

The two helpers cover cases when the user wants to cache a bunch of metadata fields to a certain structure and when the user just wants to query a specific metadata field on demand. They are enough for KVM to use (and also should be enough for other potential users).

Quoted 116 lines
---
  arch/x86/include/asm/tdx.h  | 22 ++++++++++++++++++++++
  arch/x86/virt/vmx/tdx/tdx.c | 25 ++++++++-----------------
  2 files changed, 30 insertions(+), 17 deletions(-)
arch/x86/include/asm/tdx.h +22 -0
index eba178996d84..709b9483f9e4 100644
@@ -116,6 +116,28 @@ static inline u64 sc_retry(sc_func_t func, u64 fn,
  int tdx_cpu_enable(void);
  int tdx_enable(void);
  const char *tdx_dump_mce_info(struct mce *m);
+
+struct tdx_metadata_field_mapping {
+	u64 field_id;
+	int offset;
+	int size;
+};
+
+#define TD_SYSINFO_MAP(_field_id, _struct, _member)	\
+	{ .field_id = MD_FIELD_ID_##_field_id,		\
+	  .offset   = offsetof(_struct, _member),	\
+	  .size     = sizeof(typeof(((_struct *)0)->_member)) }
+
+/*
+ * Read multiple global metadata fields to a buffer of a structure
+ * based on the "field ID -> structure member" mapping table.
+ */
+int tdx_sys_metadata_read(const struct tdx_metadata_field_mapping *fields,
+			  int nr_fields, void *stbuf);
+
+/* Read a single global metadata field */
+int tdx_sys_metadata_field_read(u64 field_id, u64 *data);
+
  #else
  static inline void tdx_init(void) { }
  static inline int tdx_cpu_enable(void) { return -ENODEV; }
arch/x86/virt/vmx/tdx/tdx.c +8 -17
index a19adc898df6..dc21310776ab 100644
@@ -251,7 +251,7 @@ static int build_tdx_memlist(struct list_head *tmb_list)
  	return ret;
  }
 
-static int read_sys_metadata_field(u64 field_id, u64 *data)
+int tdx_sys_metadata_field_read(u64 field_id, u64 *data)
  {
  	struct tdx_module_args args = {};
  	int ret;
@@ -270,6 +270,7 @@ static int read_sys_metadata_field(u64 field_id, u64 *data)
 
  	return 0;
  }
+EXPORT_SYMBOL_GPL(tdx_sys_metadata_field_read);
 
  /* Return the metadata field element size in bytes */
  static int get_metadata_field_bytes(u64 field_id)
@@ -295,7 +296,7 @@ static int stbuf_read_sys_metadata_field(u64 field_id,
  	if (WARN_ON_ONCE(get_metadata_field_bytes(field_id) != bytes))
  		return -EINVAL;
 
-	ret = read_sys_metadata_field(field_id, &tmp);
+	ret = tdx_sys_metadata_field_read(field_id, &tmp);
  	if (ret)
  		return ret;
 
@@ -304,19 +305,8 @@ static int stbuf_read_sys_metadata_field(u64 field_id,
  	return 0;
  }
 
-struct field_mapping {
-	u64 field_id;
-	int offset;
-	int size;
-};
-
-#define TD_SYSINFO_MAP(_field_id, _struct, _member)	\
-	{ .field_id = MD_FIELD_ID_##_field_id,		\
-	  .offset   = offsetof(_struct, _member),	\
-	  .size     = sizeof(typeof(((_struct *)0)->_member)) }
-
-static int read_sys_metadata(struct field_mapping *fields, int nr_fields,
-			     void *stbuf)
+int tdx_sys_metadata_read(const struct tdx_metadata_field_mapping *fields,
+			  int nr_fields, void *stbuf)
  {
  	int i, ret;
 
@@ -331,6 +321,7 @@ static int read_sys_metadata(struct field_mapping *fields, int nr_fields,
 
  	return 0;
  }
+EXPORT_SYMBOL_GPL(tdx_sys_metadata_read);
 
  #define TD_SYSINFO_MAP_TDMR_INFO(_field_id, _member)	\
  	TD_SYSINFO_MAP(_field_id, struct tdx_tdmr_sysinfo, _member)
@@ -338,7 +329,7 @@ static int read_sys_metadata(struct field_mapping *fields, int nr_fields,
  static int get_tdx_tdmr_sysinfo(struct tdx_tdmr_sysinfo *tdmr_sysinfo)
  {
  	/* Map TD_SYSINFO fields into 'struct tdx_tdmr_sysinfo': */
-	const struct field_mapping fields[] = {
+	const struct tdx_metadata_field_mapping fields[] = {
  		TD_SYSINFO_MAP_TDMR_INFO(MAX_TDMRS,		max_tdmrs),
  		TD_SYSINFO_MAP_TDMR_INFO(MAX_RESERVED_PER_TDMR, max_reserved_per_tdmr),
  		TD_SYSINFO_MAP_TDMR_INFO(PAMT_4K_ENTRY_SIZE,    pamt_entry_size[TDX_PS_4K]),
@@ -347,7 +338,7 @@ static int get_tdx_tdmr_sysinfo(struct tdx_tdmr_sysinfo *tdmr_sysinfo)
  	};
 
  	/* Populate 'tdmr_sysinfo' fields using the mapping structure above: */
-	return read_sys_metadata(fields, ARRAY_SIZE(fields), tdmr_sysinfo);
+	return tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdmr_sysinfo);
  }
 
  /* Calculate the actual TDMR size */
#3 lore raw

Re: [PATCH v19 001/130] x86/virt/tdx: Rename _offset to _member for TD_SYSINFO_MAP() macro

In reply to Binbin Wu
Quoted 8 lines · Binbin Wu
Quoted 6 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Kai Huang <[email protected]>

TD_SYSINFO_MAP() macro actually takes the member of the 'struct tdx_tdmr_sysinfo' as the second argument and uses the offsetof() to calculate the offset for that member.

Quoted 9 lines
Quoted 5 lines

Rename the macro argument _offset to _member to reflect this.

Thanks for review.

I've sent out the first 5 metadata read patches as a standalone patchset separately:

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

I'll add your Reviewed-by in next version.

(for others please comment there instead, thanks!)

#486 lore raw

Re: [PATCH v19 080/130] KVM: TDX: restore host xsave state when exit from the guest TD

In reply to Chen Yu
Quoted 50 lines · Chen Yu
Quoted 49 lines · On 2024-02-26 at 00:26:22 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

On exiting from the guest TD, xsave state is clobbered. Restore xsave state on TD exit.

---
v19:
- Add EXPORT_SYMBOL_GPL(host_xcr0)

v15 -> v16:
- Added CET flag mask

---
 arch/x86/kvm/vmx/tdx.c | 19 +++++++++++++++++++
 arch/x86/kvm/x86.c     |  1 +
 2 files changed, 20 insertions(+)
arch/x86/kvm/vmx/tdx.c +15 -0
index 9616b1aab6ce..199226c6cf55 100644
@@ -2,6 +2,7 @@
 #include <linux/cpu.h>
 #include <linux/mmu_context.h>
 
+#include <asm/fpu/xcr.h>
 #include <asm/tdx.h>
 
 #include "capabilities.h"
@@ -534,6 +535,23 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	 */
 }
 
+static void tdx_restore_host_xsave_state(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+
+	if (static_cpu_has(X86_FEATURE_XSAVE) &&
+	    host_xcr0 != (kvm_tdx->xfam & kvm_caps.supported_xcr0))
+		xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
+	if (static_cpu_has(X86_FEATURE_XSAVES) &&
+	    /* PT can be exposed to TD guest regardless of KVM's XSS support */
+	    host_xss != (kvm_tdx->xfam &
+			 (kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET)))
+		wrmsrl(MSR_IA32_XSS, host_xss);
+	if (static_cpu_has(X86_FEATURE_PKU) &&
+	    (kvm_tdx->xfam & XFEATURE_MASK_PKRU))
Quoted 8 lines

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

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		write_pkru(vcpu->arch.host_pkru);
+}

Maybe one minor question regarding the pkru restore. In the non-TDX version kvm_load_host_xsave_state(), it first tries to read the current setting vcpu->arch.pkru = rdpkru(); if this setting does not equal to host_pkru, it trigger the write_pkru on host. Does it mean we can also leverage that mechanism in TDX to avoid 1 pkru write(I guess pkru write is costly than a read pkru)?

Yes, that's the intention. When we set the PKRU feature for the guest, TDX module unconditionally initialize pkru. Do you have use case that wrpkru() (without rdpkru()) is better?

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

Re: [PATCH v19 014/130] KVM: Add KVM vcpu ioctl to pre-populate guest memory

In reply to Yin Fengwei
Quoted 72 lines · Yin Fengwei
Quoted 23 lines
virt/kvm/kvm_main.c +15 -0
index 0349e1f241d1..2f0a8e28795e 100644
@@ -4409,6 +4409,62 @@ static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
 	return fd;
 }
 
+__weak void kvm_arch_vcpu_pre_memory_mapping(struct kvm_vcpu *vcpu)
+{
+}
+
+__weak int kvm_arch_vcpu_memory_mapping(struct kvm_vcpu *vcpu,
+					struct kvm_memory_mapping *mapping)
+{
+	return -EOPNOTSUPP;
+}
+
+static int kvm_vcpu_memory_mapping(struct kvm_vcpu *vcpu,
+				   struct kvm_memory_mapping *mapping)
+{
+	bool added = false;
+	int idx, r = 0;

virt/kvm/kvm_main.c static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu) · line 4436

Quoted 10 lines
virt/kvm/kvm_main.c +10 -0
+
+	/* flags isn't used yet. */
+	if (mapping->flags)
+		return -EINVAL;
+
+	/* Sanity check */
+	if (!IS_ALIGNED(mapping->source, PAGE_SIZE) ||
+	    !mapping->nr_pages ||
+	    mapping->nr_pages & GENMASK_ULL(63, 63 - PAGE_SHIFT) ||
+	    mapping->base_gfn + mapping->nr_pages <= mapping->base_gfn)

I suppose !mapping->nr_pages can be deleted as this line can cover it.

Quoted 38 lines
virt/kvm/kvm_main.c +31 -0
+		return -EINVAL;
+
+	vcpu_load(vcpu);
+	idx = srcu_read_lock(&vcpu->kvm->srcu);
+	kvm_arch_vcpu_pre_memory_mapping(vcpu);
+
+	while (mapping->nr_pages) {
+		if (signal_pending(current)) {
+			r = -ERESTARTSYS;
+			break;
+		}
+
+		if (need_resched())
+			cond_resched();
+
+		r = kvm_arch_vcpu_memory_mapping(vcpu, mapping);
+		if (r)
+			break;
+
+		added = true;
+	}
+
+	srcu_read_unlock(&vcpu->kvm->srcu, idx);
+	vcpu_put(vcpu);
+
+	if (added && mapping->nr_pages > 0)
+		r = -EAGAIN;
+
+	return r;
+}
+
 static long kvm_vcpu_ioctl(struct file *filp,
 			   unsigned int ioctl, unsigned long arg)
 {
@@ -4610,6 +4666,17 @@ static long kvm_vcpu_ioctl(struct file *filp,
 		r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
 		break;
 	}
Quoted 8 lines

virt/kvm/kvm_main.c static long kvm_vcpu_ioctl(struct file *filp, · line 4675

Quoted 7 lines
virt/kvm/kvm_main.c +7 -0
+	case KVM_MEMORY_MAPPING: {
+		struct kvm_memory_mapping mapping;
+
+		r = -EFAULT;
+		if (copy_from_user(&mapping, argp, sizeof(mapping)))
+			break;
+		r = kvm_vcpu_memory_mapping(vcpu, &mapping);

return value r should be checked before copy_to_user

That's intentional to tell the mapping is partially or fully processed regardless that error happened or not.

Quoted 13 lines

Regards
Yin, Fengwei

Quoted 7 lines
virt/kvm/kvm_main.c +4 -0
+		if (copy_to_user(argp, &mapping, sizeof(mapping)))
+			r = -EFAULT;
+		break;
+	}
 	default:
 		r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
 	}
Signature · 1 line
Isaku Yamahata <[email protected]>
#487 lore raw

Re: [PATCH v19 080/130] KVM: TDX: restore host xsave state when exit from the guest TD

In reply to Isaku Yamahata
Quoted 62 lines · Isaku Yamahata
Quoted 50 lines · Chen Yu
Quoted 49 lines · On 2024-02-26 at 00:26:22 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

On exiting from the guest TD, xsave state is clobbered. Restore xsave state on TD exit.

---
v19:
- Add EXPORT_SYMBOL_GPL(host_xcr0)

v15 -> v16:
- Added CET flag mask

---
 arch/x86/kvm/vmx/tdx.c | 19 +++++++++++++++++++
 arch/x86/kvm/x86.c     |  1 +
 2 files changed, 20 insertions(+)
arch/x86/kvm/vmx/tdx.c +15 -0
index 9616b1aab6ce..199226c6cf55 100644
@@ -2,6 +2,7 @@
 #include <linux/cpu.h>
 #include <linux/mmu_context.h>
 
+#include <asm/fpu/xcr.h>
 #include <asm/tdx.h>
 
 #include "capabilities.h"
@@ -534,6 +535,23 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	 */
 }
 
+static void tdx_restore_host_xsave_state(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+
+	if (static_cpu_has(X86_FEATURE_XSAVE) &&
+	    host_xcr0 != (kvm_tdx->xfam & kvm_caps.supported_xcr0))
+		xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
+	if (static_cpu_has(X86_FEATURE_XSAVES) &&
+	    /* PT can be exposed to TD guest regardless of KVM's XSS support */
+	    host_xss != (kvm_tdx->xfam &
+			 (kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET)))
+		wrmsrl(MSR_IA32_XSS, host_xss);
+	if (static_cpu_has(X86_FEATURE_PKU) &&
+	    (kvm_tdx->xfam & XFEATURE_MASK_PKRU))
Quoted 8 lines

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

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		write_pkru(vcpu->arch.host_pkru);
+}

Maybe one minor question regarding the pkru restore. In the non-TDX version kvm_load_host_xsave_state(), it first tries to read the current setting vcpu->arch.pkru = rdpkru(); if this setting does not equal to host_pkru, it trigger the write_pkru on host. Does it mean we can also leverage that mechanism in TDX to avoid 1 pkru write(I guess pkru write is costly than a read pkru)?

Quoted 2 lines

Yes, that's the intention. When we set the PKRU feature for the guest, TDX module unconditionally initialize pkru.

I see, thanks for the information. Please correct me if I'm wrong, and I'm not sure if wrpkru instruction would trigger the TD exit. The TDX module spec[1] mentioned PKS (protected key for supervisor pages), but does not metion PKU for user pages. PKS is controlled by MSR IA32_PKRS. The TDX module will passthrough the MSR IA32_PKRS write in TD, because TDX module clears the PKS bitmap in VMCS:
https://github.com/intel/tdx-module/blob/tdx_1.5/src/common/helpers/helpers.c#L1723
so neither write to MSR IA32_PKRS nor wrpkru triggers TD exit.

However, after a second thought, I found that after commit 72a6c08c44e4, the current code should not be a problem, because write_pkru() would first read the current pkru settings and decide whether to update to the pkru register.

Quoted 2 lines

Do you have use case that wrpkru()
(without rdpkru()) is better?

I don't have use case yet. But with/without rdpkru() in tdx_restore_host_xsave_state(), there is no much difference because write_pkru() has taken care of it if I understand correctly.

thanks,
Chenyu

Reviewed-by on v19 22/130
#95 lore raw

Re: [PATCH v19 022/130] KVM: x86/vmx: Refactor KVM VMX module init/exit functions

In reply to [email protected]
Quoted 36 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

The current module initialization flow is,
0.) Check if VMX is supported,
1.) hyper-v specific initialization,
2.) system-wide x86 specific and vendor specific initialization, 3.) Final VMX specific system-wide initialization,
4.) calculate the sizes of VMX kvm structure and VMX vcpu structure, 5.) report those sizes to the KVM common layer and KVM common
initialization

Refactor the KVM VMX module initialization function into functions with a wrapper function to separate VMX logic in vmx.c from a file, main.c, common among VMX and TDX. Introduce a wrapper function for vmx_init().

The KVM architecture common layer allocates struct kvm with reported size for architecture-specific code. The KVM VMX module defines its structure as struct vmx_kvm { struct kvm; VMX specific members;} and uses it as struct vmx kvm. Similar for vcpu structure. TDX KVM patches will define TDX specific kvm and vcpu structures.

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

---
v19:
- Eliminate the unnecessary churn with vmx_hardware_setup() by Xiaoyao

Quoted 6 lines

v18:
- Move loaded_vmcss_on_cpu initialization to vt_init() before kvm_x86_vendor_init().
- added __init to an empty stub fucntion, hv_init_evmcs().

With one minor comment. See below.

Quoted 156 lines
---
  arch/x86/kvm/vmx/main.c    | 54 ++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/vmx.c     | 60 +++++---------------------------------
  arch/x86/kvm/vmx/x86_ops.h | 14 +++++++++
  3 files changed, 75 insertions(+), 53 deletions(-)
arch/x86/kvm/vmx/main.c +54 -0
index eeb7a43b271d..18cecf12c7c8 100644
@@ -167,3 +167,57 @@ struct kvm_x86_init_ops vt_init_ops __initdata = {
  	.runtime_ops = &vt_x86_ops,
  	.pmu_ops = &intel_pmu_ops,
  };
+
+static int __init vt_init(void)
+{
+	unsigned int vcpu_size, vcpu_align;
+	int cpu, r;
+
+	if (!kvm_is_vmx_supported())
+		return -EOPNOTSUPP;
+
+	/*
+	 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
+	 * to unwind if a later step fails.
+	 */
+	hv_init_evmcs();
+
+	/* vmx_hardware_disable() accesses loaded_vmcss_on_cpu. */
+	for_each_possible_cpu(cpu)
+		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
+
+	r = kvm_x86_vendor_init(&vt_init_ops);
+	if (r)
+		return r;
+
+	r = vmx_init();
+	if (r)
+		goto err_vmx_init;
+
+	/*
+	 * Common KVM initialization _must_ come last, after this, /dev/kvm is
+	 * exposed to userspace!
+	 */
+	vcpu_size = sizeof(struct vcpu_vmx);
+	vcpu_align = __alignof__(struct vcpu_vmx);
+	r = kvm_init(vcpu_size, vcpu_align, THIS_MODULE);
+	if (r)
+		goto err_kvm_init;
+
+	return 0;
+
+err_kvm_init:
+	vmx_exit();
+err_vmx_init:
+	kvm_x86_vendor_exit();
+	return r;
+}
+module_init(vt_init);
+
+static void vt_exit(void)
+{
+	kvm_exit();
+	kvm_x86_vendor_exit();
+	vmx_exit();
+}
+module_exit(vt_exit);
arch/x86/kvm/vmx/vmx.c +6 -29
index 8af0668e4dca..2fb1cd2e28a2 100644
@@ -477,7 +477,7 @@ DEFINE_PER_CPU(struct vmcs *, current_vmcs);
   * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
   * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
   */
-static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
+DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
 
  static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
  static DEFINE_SPINLOCK(vmx_vpid_lock);
@@ -537,7 +537,7 @@ static int hv_enable_l2_tlb_flush(struct kvm_vcpu *vcpu)
  	return 0;
  }
 
-static __init void hv_init_evmcs(void)
+__init void hv_init_evmcs(void)
  {
  	int cpu;
 
@@ -573,7 +573,7 @@ static __init void hv_init_evmcs(void)
  	}
  }
 
-static void hv_reset_evmcs(void)
+void hv_reset_evmcs(void)
  {
  	struct hv_vp_assist_page *vp_ap;
 
@@ -597,10 +597,6 @@ static void hv_reset_evmcs(void)
  	vp_ap->current_nested_vmcs = 0;
  	vp_ap->enlighten_vmentry = 0;
  }
-
-#else /* IS_ENABLED(CONFIG_HYPERV) */
-static void hv_init_evmcs(void) {}
-static void hv_reset_evmcs(void) {}
  #endif /* IS_ENABLED(CONFIG_HYPERV) */
 
  /*
@@ -2743,7 +2739,7 @@ static bool __kvm_is_vmx_supported(void)
  	return true;
  }
 
-static bool kvm_is_vmx_supported(void)
+bool kvm_is_vmx_supported(void)
  {
  	bool supported;
 
@@ -8508,7 +8504,7 @@ static void vmx_cleanup_l1d_flush(void)
  	l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
  }
 
-static void __vmx_exit(void)
+void vmx_exit(void)
  {
  	allow_smaller_maxphyaddr = false;
 
@@ -8517,36 +8513,10 @@ static void __vmx_exit(void)
  	vmx_cleanup_l1d_flush();
  }
 
-static void vmx_exit(void)
-{
-	kvm_exit();
-	kvm_x86_vendor_exit();
-
-	__vmx_exit();
-}
-module_exit(vmx_exit);
-
-static int __init vmx_init(void)
+int __init vmx_init(void)
  {
  	int r, cpu;
 
-	if (!kvm_is_vmx_supported())
-		return -EOPNOTSUPP;
-
-	/*
-	 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
-	 * to unwind if a later step fails.
-	 */
-	hv_init_evmcs();
-
-	/* vmx_hardware_disable() accesses loaded_vmcss_on_cpu. */

arch/x86/kvm/vmx/vmx.c static void __vmx_exit(void) · line 8522

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +0 -7
-	for_each_possible_cpu(cpu)
-		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
-
-	r = kvm_x86_vendor_init(&vt_init_ops);
-	if (r)
-		return r;
-
  	/*
  	 * Must be called after common x86 init so enable_ept is properly set
  	 * up. Hand the parameter mitigation value in which was stored in

I am wondering whether the first sentence of above comment should be moved to vt_init()? So vt_init() has whole information about the init sequence.

Regards
Yin, Fengwei

Quoted 56 lines
arch/x86/kvm/vmx/vmx.c +1 -17
@@ -8556,7 +8526,7 @@ static int __init vmx_init(void)
  	 */
  	r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
  	if (r)
-		goto err_l1d_flush;
+		return r;
 
  	for_each_possible_cpu(cpu)
  		pi_init_cpu(cpu);
@@ -8573,21 +8543,5 @@ static int __init vmx_init(void)
  	if (!enable_ept)
  		allow_smaller_maxphyaddr = true;
 
-	/*
-	 * Common KVM initialization _must_ come last, after this, /dev/kvm is
-	 * exposed to userspace!
-	 */
-	r = kvm_init(sizeof(struct vcpu_vmx), __alignof__(struct vcpu_vmx),
-		     THIS_MODULE);
-	if (r)
-		goto err_kvm_init;
-
  	return 0;
-
-err_kvm_init:
-	__vmx_exit();
-err_l1d_flush:
-	kvm_x86_vendor_exit();
-	return r;
  }
-module_init(vmx_init);
arch/x86/kvm/vmx/x86_ops.h +14 -0
index 2f8b6c43fe0f..b936388853ab 100644
@@ -6,6 +6,20 @@
 
  #include "x86.h"
 
+#if IS_ENABLED(CONFIG_HYPERV)
+__init void hv_init_evmcs(void);
+void hv_reset_evmcs(void);
+#else /* IS_ENABLED(CONFIG_HYPERV) */
+static inline __init void hv_init_evmcs(void) {}
+static inline void hv_reset_evmcs(void) {}
+#endif /* IS_ENABLED(CONFIG_HYPERV) */
+
+DECLARE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
+
+bool kvm_is_vmx_supported(void);
+int __init vmx_init(void);
+void vmx_exit(void);
+
  extern struct kvm_x86_ops vt_x86_ops __initdata;
  extern struct kvm_x86_init_ops vt_init_ops __initdata;
 
#488 lore raw

Re: [PATCH v19 080/130] KVM: TDX: restore host xsave state when exit from the guest TD

In reply to Chen Yu
Quoted 66 lines · Chen Yu
Quoted 62 lines · Isaku Yamahata
Quoted 50 lines · Chen Yu
Quoted 49 lines · On 2024-02-26 at 00:26:22 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

On exiting from the guest TD, xsave state is clobbered. Restore xsave state on TD exit.

---
v19:
- Add EXPORT_SYMBOL_GPL(host_xcr0)

v15 -> v16:
- Added CET flag mask

---
 arch/x86/kvm/vmx/tdx.c | 19 +++++++++++++++++++
 arch/x86/kvm/x86.c     |  1 +
 2 files changed, 20 insertions(+)
arch/x86/kvm/vmx/tdx.c +15 -0
index 9616b1aab6ce..199226c6cf55 100644
@@ -2,6 +2,7 @@
 #include <linux/cpu.h>
 #include <linux/mmu_context.h>
 
+#include <asm/fpu/xcr.h>
 #include <asm/tdx.h>
 
 #include "capabilities.h"
@@ -534,6 +535,23 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	 */
 }
 
+static void tdx_restore_host_xsave_state(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+
+	if (static_cpu_has(X86_FEATURE_XSAVE) &&
+	    host_xcr0 != (kvm_tdx->xfam & kvm_caps.supported_xcr0))
+		xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
+	if (static_cpu_has(X86_FEATURE_XSAVES) &&
+	    /* PT can be exposed to TD guest regardless of KVM's XSS support */
+	    host_xss != (kvm_tdx->xfam &
+			 (kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET)))
+		wrmsrl(MSR_IA32_XSS, host_xss);
+	if (static_cpu_has(X86_FEATURE_PKU) &&
+	    (kvm_tdx->xfam & XFEATURE_MASK_PKRU))
Quoted 8 lines

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

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		write_pkru(vcpu->arch.host_pkru);
+}

Maybe one minor question regarding the pkru restore. In the non-TDX version kvm_load_host_xsave_state(), it first tries to read the current setting vcpu->arch.pkru = rdpkru(); if this setting does not equal to host_pkru, it trigger the write_pkru on host. Does it mean we can also leverage that mechanism in TDX to avoid 1 pkru write(I guess pkru write is costly than a read pkru)?

Quoted 2 lines

Yes, that's the intention. When we set the PKRU feature for the guest, TDX module unconditionally initialize pkru.

Quoted 7 lines

I see, thanks for the information. Please correct me if I'm wrong, and I'm not sure if wrpkru instruction would trigger the TD exit. The TDX module spec[1] mentioned PKS (protected key for supervisor pages), but does not metion PKU for user pages. PKS is controlled by MSR IA32_PKRS. The TDX module will passthrough the MSR IA32_PKRS write in TD, because TDX module clears the PKS bitmap in VMCS:
https://github.com/intel/tdx-module/blob/tdx_1.5/src/common/helpers/helpers.c#L1723
so neither write to MSR IA32_PKRS nor wrpkru triggers TD exit.

wrpkru instruction in TDX guest doesn't cause exit to TDX module. TDX module runs with CR4.PKE=0. The value of pkru doesn't matter to the TDX module. When exiting from TDX module to the host VMM, PKRU is initialized to zero with xrestr. So it doesn't matter.

We need to refer to NP-SEAMLDR for the register value for TDX module on SEAMCALL. It sets up the register values for TDX module on SEAMCALL.

Quoted 10 lines

However, after a second thought, I found that after commit 72a6c08c44e4, the current code should not be a problem, because write_pkru() would first read the current pkru settings and decide whether to update to the pkru register.

Quoted 2 lines

Do you have use case that wrpkru()
(without rdpkru()) is better?

I don't have use case yet. But with/without rdpkru() in tdx_restore_host_xsave_state(), there is no much difference because write_pkru() has taken care of it if I understand correctly.

The code in this hunk is TDX version of kvm_load_guest_xsave_state(). We case follow the VMX case at the moment.

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

Re: [PATCH v19 022/130] KVM: x86/vmx: Refactor KVM VMX module init/exit functions

In reply to Yin, Fengwei
Quoted 198 lines · Fengwei
Quoted 36 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

The current module initialization flow is,
0.) Check if VMX is supported,
1.) hyper-v specific initialization,
2.) system-wide x86 specific and vendor specific initialization, 3.) Final VMX specific system-wide initialization,
4.) calculate the sizes of VMX kvm structure and VMX vcpu structure, 5.) report those sizes to the KVM common layer and KVM common
initialization

Refactor the KVM VMX module initialization function into functions with a wrapper function to separate VMX logic in vmx.c from a file, main.c, common among VMX and TDX. Introduce a wrapper function for vmx_init().

The KVM architecture common layer allocates struct kvm with reported size for architecture-specific code. The KVM VMX module defines its structure as struct vmx_kvm { struct kvm; VMX specific members;} and uses it as struct vmx kvm. Similar for vcpu structure. TDX KVM patches will define TDX specific kvm and vcpu structures.

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

---
v19:
- Eliminate the unnecessary churn with vmx_hardware_setup() by Xiaoyao

Quoted 6 lines

v18:
- Move loaded_vmcss_on_cpu initialization to vt_init() before kvm_x86_vendor_init().
- added __init to an empty stub fucntion, hv_init_evmcs().

With one minor comment. See below.

Quoted 149 lines
---
  arch/x86/kvm/vmx/main.c    | 54 ++++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/vmx.c     | 60 +++++---------------------------------
  arch/x86/kvm/vmx/x86_ops.h | 14 +++++++++
  3 files changed, 75 insertions(+), 53 deletions(-)
arch/x86/kvm/vmx/main.c +54 -0
index eeb7a43b271d..18cecf12c7c8 100644
@@ -167,3 +167,57 @@ struct kvm_x86_init_ops vt_init_ops __initdata = {
  	.runtime_ops = &vt_x86_ops,
  	.pmu_ops = &intel_pmu_ops,
  };
+
+static int __init vt_init(void)
+{
+	unsigned int vcpu_size, vcpu_align;
+	int cpu, r;
+
+	if (!kvm_is_vmx_supported())
+		return -EOPNOTSUPP;
+
+	/*
+	 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
+	 * to unwind if a later step fails.
+	 */
+	hv_init_evmcs();
+
+	/* vmx_hardware_disable() accesses loaded_vmcss_on_cpu. */
+	for_each_possible_cpu(cpu)
+		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
+
+	r = kvm_x86_vendor_init(&vt_init_ops);
+	if (r)
+		return r;
+
+	r = vmx_init();
+	if (r)
+		goto err_vmx_init;
+
+	/*
+	 * Common KVM initialization _must_ come last, after this, /dev/kvm is
+	 * exposed to userspace!
+	 */
+	vcpu_size = sizeof(struct vcpu_vmx);
+	vcpu_align = __alignof__(struct vcpu_vmx);
+	r = kvm_init(vcpu_size, vcpu_align, THIS_MODULE);
+	if (r)
+		goto err_kvm_init;
+
+	return 0;
+
+err_kvm_init:
+	vmx_exit();
+err_vmx_init:
+	kvm_x86_vendor_exit();
+	return r;
+}
+module_init(vt_init);
+
+static void vt_exit(void)
+{
+	kvm_exit();
+	kvm_x86_vendor_exit();
+	vmx_exit();
+}
+module_exit(vt_exit);
arch/x86/kvm/vmx/vmx.c +6 -34
index 8af0668e4dca..2fb1cd2e28a2 100644
@@ -477,7 +477,7 @@ DEFINE_PER_CPU(struct vmcs *, current_vmcs);
   * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
   * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
   */
-static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
+DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
  static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
  static DEFINE_SPINLOCK(vmx_vpid_lock);
@@ -537,7 +537,7 @@ static int hv_enable_l2_tlb_flush(struct kvm_vcpu *vcpu)
  	return 0;
  }
-static __init void hv_init_evmcs(void)
+__init void hv_init_evmcs(void)
  {
  	int cpu;
@@ -573,7 +573,7 @@ static __init void hv_init_evmcs(void)
  	}
  }
-static void hv_reset_evmcs(void)
+void hv_reset_evmcs(void)
  {
  	struct hv_vp_assist_page *vp_ap;
@@ -597,10 +597,6 @@ static void hv_reset_evmcs(void)
  	vp_ap->current_nested_vmcs = 0;
  	vp_ap->enlighten_vmentry = 0;
  }
-
-#else /* IS_ENABLED(CONFIG_HYPERV) */
-static void hv_init_evmcs(void) {}
-static void hv_reset_evmcs(void) {}
  #endif /* IS_ENABLED(CONFIG_HYPERV) */
  /*
@@ -2743,7 +2739,7 @@ static bool __kvm_is_vmx_supported(void)
  	return true;
  }
-static bool kvm_is_vmx_supported(void)
+bool kvm_is_vmx_supported(void)
  {
  	bool supported;
@@ -8508,7 +8504,7 @@ static void vmx_cleanup_l1d_flush(void)
  	l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
  }
-static void __vmx_exit(void)
+void vmx_exit(void)
  {
  	allow_smaller_maxphyaddr = false;
@@ -8517,36 +8513,10 @@ static void __vmx_exit(void)
  	vmx_cleanup_l1d_flush();
  }
-static void vmx_exit(void)
-{
-	kvm_exit();
-	kvm_x86_vendor_exit();
-
-	__vmx_exit();
-}
-module_exit(vmx_exit);
-
-static int __init vmx_init(void)
+int __init vmx_init(void)
  {
  	int r, cpu;
-	if (!kvm_is_vmx_supported())
-		return -EOPNOTSUPP;
-
-	/*
-	 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
-	 * to unwind if a later step fails.
-	 */
-	hv_init_evmcs();
-
-	/* vmx_hardware_disable() accesses loaded_vmcss_on_cpu. */
-	for_each_possible_cpu(cpu)
-		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
-
-	r = kvm_x86_vendor_init(&vt_init_ops);
-	if (r)
Quoted 8 lines

arch/x86/kvm/vmx/vmx.c static void __vmx_exit(void) · line 8522

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +0 -2
-		return r;
-
  	/*
  	 * Must be called after common x86 init so enable_ept is properly set
  	 * up. Hand the parameter mitigation value in which was stored in

I am wondering whether the first sentence of above comment should be moved to vt_init()? So vt_init() has whole information about the init sequence.

If we do so, we should move the call of "vmx_setup_l1d_flush() to vt_init(). I hesitated to remove static of vmx_setup_l1d_flush().

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

Re: [PATCH v19 022/130] KVM: x86/vmx: Refactor KVM VMX module init/exit functions

Quoted 32 lines · Isaku Yamahata
Quoted 24 lines
Quoted 24 lines
arch/x86/kvm/vmx/vmx.c +1 -21
-
-	__vmx_exit();
-}
-module_exit(vmx_exit);
-
-static int __init vmx_init(void)
+int __init vmx_init(void)
  {
  	int r, cpu;
-	if (!kvm_is_vmx_supported())
-		return -EOPNOTSUPP;
-
-	/*
-	 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
-	 * to unwind if a later step fails.
-	 */
-	hv_init_evmcs();
-
-	/* vmx_hardware_disable() accesses loaded_vmcss_on_cpu. */
-	for_each_possible_cpu(cpu)
-		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
-
-	r = kvm_x86_vendor_init(&vt_init_ops);
-	if (r)
Quoted 8 lines

arch/x86/kvm/vmx/vmx.c static void __vmx_exit(void) · line 8522

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +0 -2
-		return r;
-
  	/*
  	 * Must be called after common x86 init so enable_ept is properly set
  	 * up. Hand the parameter mitigation value in which was stored in

I am wondering whether the first sentence of above comment should be moved to vt_init()? So vt_init() has whole information about the init sequence.

Quoted 2 lines

If we do so, we should move the call of "vmx_setup_l1d_flush() to vt_init(). I hesitated to remove static of vmx_setup_l1d_flush().

I meant this one:
"Must be called after common x86 init so enable_ept is properly set up"

Not necessary to move vmx_setup_l1d_flush().

Regards
Yin, Fengwei

Quoted 1 line
#98 lore raw

Re: [PATCH v19 022/130] KVM: x86/vmx: Refactor KVM VMX module init/exit functions

Quoted 35 lines · Yin Fengwei
Quoted 32 lines · Isaku Yamahata
Quoted 32 lines
Quoted 19 lines
arch/x86/kvm/vmx/vmx.c +1 -16
-
-	__vmx_exit();
-}
-module_exit(vmx_exit);
-
-static int __init vmx_init(void)
+int __init vmx_init(void)
  {
  	int r, cpu;
-	if (!kvm_is_vmx_supported())
-		return -EOPNOTSUPP;
-
-	/*
-	 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
-	 * to unwind if a later step fails.
-	 */
-	hv_init_evmcs();
-
-	/* vmx_hardware_disable() accesses loaded_vmcss_on_cpu. */

arch/x86/kvm/vmx/vmx.c static void __vmx_exit(void) · line 8522

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +0 -7
-	for_each_possible_cpu(cpu)
-		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
-
-	r = kvm_x86_vendor_init(&vt_init_ops);
-	if (r)
-		return r;
-
  	/*
  	 * Must be called after common x86 init so enable_ept is properly set
  	 * up. Hand the parameter mitigation value in which was stored in

I am wondering whether the first sentence of above comment should be moved to vt_init()? So vt_init() has whole information about the init sequence.

Quoted 6 lines
Quoted 2 lines

If we do so, we should move the call of "vmx_setup_l1d_flush() to vt_init(). I hesitated to remove static of vmx_setup_l1d_flush().

I meant this one:
"Must be called after common x86 init so enable_ept is properly set up"

Not necessary to move vmx_setup_l1d_flush().

Ah, you mean "only" first sentence. Ok. I'll move it.

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

Re: [PATCH v19 011/130] KVM: Add new members to struct kvm_gfn_range to operate on

In reply to [email protected]
Quoted 9 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add new members to strut kvm_gfn_range to indicate which mapping (private-vs-shared) to operate on. only_private and only_shared. Update mmu notifier, set memory attributes ioctl or KVM gmem callback to initialize them.

It was premature for set_memory_attributes ioctl to call kvm_unmap_gfn_range(). Instead, let kvm_arch_ste_memory_attributes()

"kvm_arch_ste_memory_attributes()" -> "kvm_vm_set_mem_attributes()" ?

Quoted 2 lines

handle it and add a new x86 vendor callback to react to memory attribute change. [1]

Which new x86 vendor callback?

Quoted 56 lines

- If it's from the mmu notifier, zap shared pages only
- If it's from the KVM gmem, zap private pages only
- If setting memory attributes, vendor callback checks new attributes and make decisions.
SNP would do nothing and handle it later with gmem callback TDX callback would do as follows.
When it converts pages to shared, zap private pages only. When it converts pages to private, zap shared pages only.

TDX needs to know which mapping to operate on. Shared-EPT vs. Secure-EPT. The following sequence to convert the GPA to private doesn't work for TDX because the page can already be private.

1) Update memory attributes to private in memory attributes xarray
2) Zap the GPA range irrespective of private-or-shared. Even if the page is already private, zap the entry.
3) EPT violation on the GPA
4) Populate the GPA as private
The page is zeroed, and the guest has to accept the page again.

In step 2, TDX wants to zap only shared pages and skip private ones.

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

---
Changes v18:
- rebased to kvm-next

Changes v2 -> v3:
- Drop the KVM_GFN_RANGE flags
- Updated struct kvm_gfn_range
- Change kvm_arch_set_memory_attributes() to return bool for flush
- Added set_memory_attributes x86 op for vendor backends
- Refined commit message to describe TDX care concretely

Changes v1 -> v2:
- consolidate KVM_GFN_RANGE_FLAGS_GMEM_{PUNCH_HOLE, RELEASE} into KVM_GFN_RANGE_FLAGS_GMEM.
- Update the commit message to describe TDX more. Drop SEV_SNP.

---
  include/linux/kvm_host.h |  2 ++
  virt/kvm/guest_memfd.c   |  3 +++
  virt/kvm/kvm_main.c      | 17 +++++++++++++++++
  3 files changed, 22 insertions(+)
include/linux/kvm_host.h +0 -0
index 7e7fd25b09b3..0520cd8d03cc 100644

include/linux/kvm_host.h struct kvm_gfn_range { · line 268

Quoted 5 lines
include/linux/kvm_host.h +2 -0
@@ -264,6 +264,8 @@ struct kvm_gfn_range {
  	gfn_t start;
  	gfn_t end;
  	union kvm_mmu_notifier_arg arg;
+	bool only_private;
+	bool only_shared;

IMO, an enum will be clearer than the two flags.

    enum {
        PROCESS_PRIVATE_AND_SHARED,
        PROCESS_ONLY_PRIVATE,
        PROCESS_ONLY_SHARED,
    };

Quoted 59 lines
include/linux/kvm_host.h +0 -0
  	bool may_block;
  };
  bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range);
virt/kvm/guest_memfd.c +3 -0
index 0f4e0cf4f158..3830d50b9b67 100644
@@ -64,6 +64,9 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,
  			.end = slot->base_gfn + min(pgoff + slot->npages, end) - pgoff,
  			.slot = slot,
  			.may_block = true,
+			/* guest memfd is relevant to only private mappings. */
+			.only_private = true,
+			.only_shared = false,
  		};
 
  		if (!found_memslot) {
virt/kvm/kvm_main.c +17 -0
index 10bfc88a69f7..0349e1f241d1 100644
@@ -634,6 +634,12 @@ static __always_inline kvm_mn_ret_t __kvm_handle_hva_range(struct kvm *kvm,
  			 */
  			gfn_range.arg = range->arg;
  			gfn_range.may_block = range->may_block;
+			/*
+			 * HVA-based notifications aren't relevant to private
+			 * mappings as they don't have a userspace mapping.
+			 */
+			gfn_range.only_private = false;
+			gfn_range.only_shared = true;
 
  			/*
  			 * {gfn(page) | page intersects with [hva_start, hva_end)} =
@@ -2486,6 +2492,16 @@ static __always_inline void kvm_handle_gfn_range(struct kvm *kvm,
  	gfn_range.arg = range->arg;
  	gfn_range.may_block = range->may_block;
 
+	/*
+	 * If/when KVM supports more attributes beyond private .vs shared, this
+	 * _could_ set only_{private,shared} appropriately if the entire target
+	 * range already has the desired private vs. shared state (it's unclear
+	 * if that is a net win).  For now, KVM reaches this point if and only
+	 * if the private flag is being toggled, i.e. all mappings are in play.
+	 */
+	gfn_range.only_private = false;
+	gfn_range.only_shared = false;
+
  	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
  		slots = __kvm_memslots(kvm, i);
 
@@ -2542,6 +2558,7 @@ static int kvm_vm_set_mem_attributes(struct kvm *kvm, gfn_t start, gfn_t end,
  	struct kvm_mmu_notifier_range pre_set_range = {
  		.start = start,
  		.end = end,
+		.arg.attributes = attributes,
  		.handler = kvm_pre_set_memory_attributes,
  		.on_lock = kvm_mmu_invalidate_begin,
  		.flush_on_ret = true,
#207 lore raw

Re: [PATCH v19 032/130] KVM: TDX: Add helper functions to allocate/free TDX private host key id

In reply to [email protected]
Quoted 9 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add helper functions to allocate/free TDX private host key id (HKID).

The memory controller encrypts TDX memory with the assigned TDX HKIDs.  The
global TDX HKID is to encrypt the TDX module, its memory, and some dynamic
data (TDR).

I don't see any code about the global key id.

Quoted 3 lines

The private TDX HKID is assigned to guest TD to encrypt guest
memory and the related data.  When VMM releases an encrypted page for reuse, the page needs a cache flush with the used HKID.

Not sure the cache part is pertinent to this patch. Sounds good for some other patch.

Quoted 2 lines

  VMM needs the
global TDX HKID and the private TDX HKIDs to flush encrypted pages.

I think the commit log could have a bit more about what code is added. What about adding something like this (some verbiage from Kai's setup patch):

The memory controller encrypts TDX memory with the assigned TDX HKIDs. Each TDX guest must be protected by its own unique TDX HKID.

The HW has a fixed set of these HKID keys. Out of those, some are set aside for use by for other TDX components, but most are saved for guest use. The code that does this partitioning, records the range chosen to be available for guest use in the tdx_guest_keyid_start and tdx_nr_guest_keyids variables.

Use this range of HKIDs reserved for guest use with the kernel's IDA allocator library helper to create a mini TDX HKID allocator that can be called when setting up a TD. This way it can have an exclusive HKID, as is required. This allocator will be used in future changes.

Quoted 25 lines

---
v19:
- Removed stale comment in tdx_guest_keyid_alloc() by Binbin
- Update sanity check in tdx_guest_keyid_free() by Binbin

v18:
- Moved the functions to kvm tdx from arch/x86/virt/vmx/tdx/
- Drop exporting symbols as the host tdx does.

---
 arch/x86/kvm/vmx/tdx.c | 28 ++++++++++++++++++++++++++++

 1 file changed, 28 insertions(+)
arch/x86/kvm/vmx/tdx.c +0 -0
index a7e096fd8361..cde971122c1e 100644
@@ -11,6 +11,34 @@
  #undef pr_fmt
  #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt


+/*

Quoted 8 lines

+ * Key id globally used by TDX module: TDX module maps TDR with this TDX global
+ * key id.  TDR includes key id assigned to the TD.  Then TDX module maps other
+ * TD-related pages with the assigned key id.  TDR requires this TDX global key
+ * id for cache flush unlike other TD-related pages.
+ */

The above comment is about tdx_global_keyid, which is unrelated to the patch and code.

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+/* TDX KeyID pool */
+static DEFINE_IDA(tdx_guest_keyid_pool);
+
+static int __used tdx_guest_keyid_alloc(void)
+{
+       if (WARN_ON_ONCE(!tdx_guest_keyid_start ||

!tdx_nr_guest_keyids))
+               return -EINVAL;

I think the idea of this warnings is to check if TDX failed to init? It could check X86_FEATURE_TDX_HOST_PLATFORM or enable_tdx, but that seems to be a weird thing to check in a low level function that is called in the middle of in progress setup.

Don't know, I'd probably drop this warning.

Quoted 12 lines

+
+       return ida_alloc_range(&tdx_guest_keyid_pool, tdx_guest_keyid_start,
+                              tdx_guest_keyid_start + tdx_nr_guest_keyids - 1,
+                              GFP_KERNEL);

arch/x86/kvm/vmx/tdx.c +6 -0
+}
+
+static void __used tdx_guest_keyid_free(int keyid)
+{
+       if (WARN_ON_ONCE(keyid < tdx_guest_keyid_start ||
+                        keyid > tdx_guest_keyid_start +
Quoted 2 lines

tdx_nr_guest_keyids - 1))
+               return;

This seems like a more useful warning, but still not sure it's that risky. I guess the point is to check for returning garbage. Because a double free would not be caught, but would be possible to using idr_find(). I would think if we are worried we should do the full check, but I'm not sure we can't just drop this. There are very limited callers or things that change the checked configuration (1 of each).

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+       ida_free(&tdx_guest_keyid_pool, keyid);
+}
+

 static int __init tdx_module_setup(void)
 {
        int ret;

Reviewed-by on v19 21/130
#92 lore raw

Re: [PATCH v19 021/130] KVM: x86/vmx: initialize loaded_vmcss_on_cpu in vmx_init()

In reply to [email protected]
Quoted 10 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

vmx_hardware_disable() accesses loaded_vmcss_on_cpu via hardware_disable_all(). To allow hardware_enable/disable_all() before kvm_init(), initialize it in before kvm_x86_vendor_init() in vmx_init() so that tdx module initialization, hardware_setup method, can reference the variable.

The shortlog should be this?
KVM: VMX: Initialize loaded_vmcss_on_cpu in vmx_init()

Others,

Quoted 42 lines

---
v19:
- Fix the subject to match the patch by Yuan

v18:
- Move the vmcss_on_cpu initialization from vmx_hardware_setup() to early point of vmx_init() by Binbin

---
  arch/x86/kvm/vmx/vmx.c | 9 +++++----
  1 file changed, 5 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/vmx.c +5 -4
index 434f5aaef030..8af0668e4dca 100644
@@ -8539,6 +8539,10 @@ static int __init vmx_init(void)
  	 */
  	hv_init_evmcs();
 
+	/* vmx_hardware_disable() accesses loaded_vmcss_on_cpu. */
+	for_each_possible_cpu(cpu)
+		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
+
  	r = kvm_x86_vendor_init(&vt_init_ops);
  	if (r)
  		return r;
@@ -8554,11 +8558,8 @@ static int __init vmx_init(void)
  	if (r)
  		goto err_l1d_flush;
 
-	for_each_possible_cpu(cpu) {
-		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
-
+	for_each_possible_cpu(cpu)
  		pi_init_cpu(cpu);
-	}
 
  	cpu_emergency_register_virt_callback(vmx_emergency_disable);
 
#60 lore raw

Re: [PATCH v19 011/130] KVM: Add new members to struct kvm_gfn_range to operate on

In reply to Binbin Wu
Quoted 5 lines · Binbin Wu
Quoted 2 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Quoted 8 lines
Quoted 7 lines

Add new members to strut kvm_gfn_range to indicate which mapping (private-vs-shared) to operate on. only_private and only_shared. Update mmu notifier, set memory attributes ioctl or KVM gmem callback to initialize them.

It was premature for set_memory_attributes ioctl to call kvm_unmap_gfn_range(). Instead, let kvm_arch_ste_memory_attributes()

"kvm_arch_ste_memory_attributes()" -> "kvm_vm_set_mem_attributes()" ?

Yes, will fix it.

Quoted 3 lines
Quoted 2 lines

handle it and add a new x86 vendor callback to react to memory attribute change. [1]

Which new x86 vendor callback?

Now we don't have it. Will drop this sentnse.

Quoted 13 lines

include/linux/kvm_host.h struct kvm_gfn_range { · line 268

Quoted 10 lines
include/linux/kvm_host.h +2 -0
index 7e7fd25b09b3..0520cd8d03cc 100644
@@ -264,6 +264,8 @@ struct kvm_gfn_range {
  	gfn_t start;
  	gfn_t end;
  	union kvm_mmu_notifier_arg arg;
+	bool only_private;
+	bool only_shared;

IMO, an enum will be clearer than the two flags.

Quoted 5 lines

    enum {
        PROCESS_PRIVATE_AND_SHARED,
        PROCESS_ONLY_PRIVATE,
        PROCESS_ONLY_SHARED,
    };

The code will be ugly like
"if (== PRIVATE || == PRIVATE_AND_SHARED)" or
"if (== SHARED || == PRIVATE_AND_SHARED)"

two boolean (or two flags) is less error-prone.

Thanks,

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

Re: [PATCH v19 021/130] KVM: x86/vmx: initialize loaded_vmcss_on_cpu in vmx_init()

In reply to Binbin Wu
Quoted 11 lines · Binbin Wu
Quoted 8 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

vmx_hardware_disable() accesses loaded_vmcss_on_cpu via hardware_disable_all(). To allow hardware_enable/disable_all() before kvm_init(), initialize it in before kvm_x86_vendor_init() in vmx_init() so that tdx module initialization, hardware_setup method, can reference the variable.

Quoted 5 lines
Quoted 2 lines

The shortlog should be this?
KVM: VMX: Initialize loaded_vmcss_on_cpu in vmx_init()

Yes. I also will fix the shortlog in the next patch.

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

Re: [PATCH v19 032/130] KVM: TDX: Add helper functions to allocate/free TDX private host key id

In reply to Edgecombe, Rick P
Quoted 70 lines · Rick P
Quoted 9 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add helper functions to allocate/free TDX private host key id (HKID).

The memory controller encrypts TDX memory with the assigned TDX HKIDs.  The
global TDX HKID is to encrypt the TDX module, its memory, and some dynamic
data (TDR).

I don't see any code about the global key id.

Quoted 3 lines

The private TDX HKID is assigned to guest TD to encrypt guest
memory and the related data.  When VMM releases an encrypted page for reuse, the page needs a cache flush with the used HKID.

Not sure the cache part is pertinent to this patch. Sounds good for some other patch.

Quoted 2 lines

  VMM needs the
global TDX HKID and the private TDX HKIDs to flush encrypted pages.

I think the commit log could have a bit more about what code is added. What about adding something like this (some verbiage from Kai's setup patch):

The memory controller encrypts TDX memory with the assigned TDX HKIDs. Each TDX guest must be protected by its own unique TDX HKID.

The HW has a fixed set of these HKID keys. Out of those, some are set aside for use by for other TDX components, but most are saved for guest use. The code that does this partitioning, records the range chosen to be available for guest use in the tdx_guest_keyid_start and tdx_nr_guest_keyids variables.

Use this range of HKIDs reserved for guest use with the kernel's IDA allocator library helper to create a mini TDX HKID allocator that can be called when setting up a TD. This way it can have an exclusive HKID, as is required. This allocator will be used in future changes.

Quoted 28 lines

---
v19:
- Removed stale comment in tdx_guest_keyid_alloc() by Binbin
- Update sanity check in tdx_guest_keyid_free() by Binbin

v18:
- Moved the functions to kvm tdx from arch/x86/virt/vmx/tdx/
- Drop exporting symbols as the host tdx does.

---
 arch/x86/kvm/vmx/tdx.c | 28 ++++++++++++++++++++++++++++

 1 file changed, 28 insertions(+)
arch/x86/kvm/vmx/tdx.c +0 -0
index a7e096fd8361..cde971122c1e 100644
@@ -11,6 +11,34 @@
  #undef pr_fmt
  #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt


+/*
+ * Key id globally used by TDX module: TDX module maps TDR with this TDX global
+ * key id.  TDR includes key id assigned to the TD.  Then TDX module

Quoted 8 lines
Quoted 5 lines

maps other
+ * TD-related pages with the assigned key id.  TDR requires this TDX global key
+ * id for cache flush unlike other TD-related pages.
+ */

The above comment is about tdx_global_keyid, which is unrelated to the patch and code.

Will delete this comment as it was moved into the host tdx patch series.

Quoted 30 lines
Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+/* TDX KeyID pool */
+static DEFINE_IDA(tdx_guest_keyid_pool);
+
+static int __used tdx_guest_keyid_alloc(void)
+{
+       if (WARN_ON_ONCE(!tdx_guest_keyid_start ||

!tdx_nr_guest_keyids))
+               return -EINVAL;

I think the idea of this warnings is to check if TDX failed to init? It could check X86_FEATURE_TDX_HOST_PLATFORM or enable_tdx, but that seems to be a weird thing to check in a low level function that is called in the middle of in progress setup.

Don't know, I'd probably drop this warning.

Quoted 13 lines

+
+       return ida_alloc_range(&tdx_guest_keyid_pool, tdx_guest_keyid_start,
+                              tdx_guest_keyid_start + tdx_nr_guest_keyids - 1,
+                              GFP_KERNEL);

arch/x86/kvm/vmx/tdx.c +6 -0
+}
+
+static void __used tdx_guest_keyid_free(int keyid)
+{
+       if (WARN_ON_ONCE(keyid < tdx_guest_keyid_start ||
+                        keyid > tdx_guest_keyid_start +

tdx_nr_guest_keyids - 1))

Quoted 8 lines
Quoted 1 line

+               return;

This seems like a more useful warning, but still not sure it's that risky. I guess the point is to check for returning garbage. Because a double free would not be caught, but would be possible to using idr_find(). I would think if we are worried we should do the full check, but I'm not sure we can't just drop this. There are very limited callers or things that change the checked configuration (1 of each).

The related code is stable now and I don't hit them recently. I'll drop both of them.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to [email protected]
Quoted 17 lines · On Mon, 2024-02-26 at 00:26 -0800, [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 private
page table, allocate one more page to copy the dummy page table for KVM MMU
code to directly walk.  Resolve KVM page fault with the existing code, and
do additional operations necessary for the private page table.

Quoted 6 lines

To
distinguish such cases, the existing KVM page table is called a shared page
table (i.e. not associated with private page table), and the page table
with private page table is called a private page table.

This makes it sound like the dummy page table for the private alias is also called a shared page table, but in the drawing below it looks like only the shared alias is called "shared PT".

Quoted 117 lines

  The relationship
is depicted below.

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

              KVM page fault                     |

                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
    shared PT root      dummy PT root            |    private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            dummy PT ----propagate---->   private 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.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU.  It is used to propagate PT change to the actual private PT which is used by CPU.

---
v19:
- typo in the comment in kvm_mmu_alloc_private_spt()
- drop CONFIG_KVM_MMU_PRIVATE
---
 arch/x86/include/asm/kvm_host.h |  5 +++ arch/x86/kvm/mmu/mmu.c          |  7 ++++ arch/x86/kvm/mmu/mmu_internal.h | 63 ++++++++++++++++++++++++++++++- --
 arch/x86/kvm/mmu/tdp_mmu.c      |  1 +

 4 files changed, 72 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index dcc6f7c38a83..efd3fda1c177 100644
@@ -825,6 +825,11 @@ 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.
+        */
+       struct kvm_mmu_memory_cache mmu_private_spt_cache;
        /*
         * QEMU userspace and the guest each have their own FPU state.

arch/x86/kvm/mmu/mmu.c +0 -0
index eeebbc67e42b..0d6d4506ec97 100644
@@ -685,6 +685,12 @@ 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;
+       if (kvm_gfn_shared_mask(vcpu->kvm)) {
+               r = kvm_mmu_topup_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_private_spt_cache,

+                                              PT64_ROOT_MAX_LEVEL); +               if (r)
+                       return r;
+       }
        r = kvm_mmu_topup_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_shadow_page_cache,

                                       PT64_ROOT_MAX_LEVEL); if (r)

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -704,6 +710,7 @@ static void mmu_free_memory_caches(struct
 kvm_vcpu *vcpu)

        kvm_mmu_free_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_pte_list_desc_cache);

        kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache); kvm_mmu_free_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_shadowed_info_cache);

+       kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_spt_cache); kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache); }

arch/x86/kvm/mmu/mmu_internal.h +5 -1
index e3f54701f98d..002f3f80bf3b 100644
@@ -101,7 +101,21 @@ struct kvm_mmu_page {
                 int root_count;
                 refcount_t tdp_mmu_root_count;
         };
-       unsigned int unsync_children;
+       union {
+               struct {
+                       unsigned int unsync_children;
+                       /*
+                        * Number of writes since the last time
Quoted 5 lines

traversal
+                        * visited this page. +                        */
+                       atomic_t write_flooding_count; +               };

I think the point of putting these in a union is that they only apply to shadow paging and so can't be used with TDX. I think you are putting more than the sizeof(void *) in there as there are multiple in the same category. But there seems to be a new one added, *shadowed_translation. Should it go in there too? Is the union because there wasn't room before, or just to be tidy?

I think the commit log should have more discussion of this union and maybe a comment in the struct to explain the purpose of the organization. Can you explain the reasoning now for the sake of discussion?

Quoted 67 lines

+               /*
+                * Associated private shadow page table, e.g. Secure- EPT page
+                * passed to the TDX module.
+                */
+               void *private_spt;
+       };
        union {
                struct kvm_rmap_head parent_ptes; /* rmap pointers to parent sptes */
                tdp_ptep_t ptep;

arch/x86/kvm/mmu/mmu_internal.h +0 -0
@@ -124,9 +138,6 @@ struct kvm_mmu_page {
         int clear_spte_count;
  #endif


-       /* Number of writes since the last time traversal visited this page.  */
-       atomic_t write_flooding_count;
-
 #ifdef CONFIG_X86_64
        /* Used for freeing the page asynchronously if it is a TDP MMU page. */
        struct rcu_head rcu_head;

arch/x86/kvm/mmu/mmu_internal.h +0 -0
@@ -150,6 +161,50 @@ static inline bool is_private_sp(const struct
 kvm_mmu_page *sp)
         return kvm_mmu_page_role_is_private(sp->role);
  }

arch/x86/kvm/mmu/mmu_internal.h +6 -0
+static inline void *kvm_mmu_private_spt(struct kvm_mmu_page *sp)
+{
+       return sp->private_spt;
+}
+
+static inline void kvm_mmu_init_private_spt(struct kvm_mmu_page *sp,

void *private_spt)

arch/x86/kvm/mmu/mmu_internal.h +5 -0
+{
+       sp->private_spt = private_spt;
+}
+
+static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,

struct kvm_mmu_page *sp)
+{
+       bool is_root = vcpu->arch.root_mmu.root_role.level == sp-

Quoted 1 line

role.level;

+
+       KVM_BUG_ON(!kvm_mmu_page_role_is_private(sp->role), vcpu-

Quoted 1 line

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 {
+               /*
+                * 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.
+                */
+               sp->private_spt = kvm_mmu_memory_cache_alloc(&vcpu-

Quoted 1 line

arch.mmu_private_spt_cache);

Quoted 8 lines

+               /*
+                * Because mmu_private_spt_cache is topped up before starting
+                * kvm page fault resolving, the allocation above shouldn't
+                * fail.
+                */
+               WARN_ON_ONCE(!sp->private_spt);

There is already a BUG_ON() for the allocation failure in kvm_mmu_memory_cache_alloc().

arch/x86/kvm/mmu/mmu_internal.h static inline bool is_private_sp(const struct kvm_mmu_page *sp) · line 204

Quoted 6 lines

+       }

arch/x86/kvm/mmu/mmu_internal.h +5 -0
+}
+
+static inline void kvm_mmu_free_private_spt(struct kvm_mmu_page *sp)
+{
+       if (sp->private_spt)

free_page() can accept NULL, so the above check is unneeded.

Quoted 12 lines

+               free_page((unsigned long)sp->private_spt);

arch/x86/kvm/mmu/mmu_internal.h +2 -0
+}
+

 static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
 {
        /*

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index 87233b3ceaef..d47f0daf1b03 100644
@@ -53,6 +53,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
Quoted 4 lines


 static void tdp_mmu_free_sp(struct kvm_mmu_page *sp) {
+       kvm_mmu_free_private_spt(sp);

This particular memcache zeros the allocations so it is safe to free this without regard to whether sp->private_spt has been set and that the allocation caller is not in place yet. It would be nice to add this detail in the log.

Quoted 3 lines

        free_page((unsigned long)sp->spt); kmem_cache_free(mmu_page_header_cache, sp); }

#102 lore raw

Re: [PATCH v19 023/130] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to [email protected]
Quoted 86 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX requires several initialization steps for KVM to create guest TDs. Detect CPU feature, enable VMX (TDX is based on VMX) on all online CPUs, detect the TDX module availability, initialize it and disable VMX.

To enable/disable VMX on all online CPUs, utilize vmx_hardware_enable/disable(). The method also initializes each CPU for TDX. TDX requires calling a TDX initialization function per logical processor (LP) before the LP uses TDX. When the CPU is becoming online, call the TDX LP initialization API. If it fails to initialize TDX, refuse CPU online for simplicity instead of TDX avoiding the failed LP.

There are several options on when to initialize the TDX module. A.) kernel module loading time, B.) the first guest TD creation time. A.) was chosen. With B.), a user may hit an error of the TDX initialization when trying to create the first guest TD. The machine that fails to initialize the TDX module can't boot any guest TD further. Such failure is undesirable and a surprise because the user expects that the machine can accommodate guest TD, but not. So A.) is better than B.).

Introduce a module parameter, kvm_intel.tdx, to explicitly enable TDX KVM support. It's off by default to keep the same behavior for those who don't use TDX. Implement hardware_setup method to detect TDX feature of CPU and initialize TDX module.

---
v19:
- fixed vt_hardware_enable() to use vmx_hardware_enable()
- renamed vmx_tdx_enabled => tdx_enabled
- renamed vmx_tdx_on() => tdx_on()

v18:
- Added comment in vt_hardware_enable() by Binbin.

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

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

arch/x86/kvm/Makefile +1 -0
index 274df24b647f..5b85ef84b2e9 100644
@@ -24,6 +24,7 @@ kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
 
  kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
  kvm-intel-$(CONFIG_KVM_HYPERV)	+= vmx/hyperv.o vmx/hyperv_evmcs.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o
 
  kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o \
  			   svm/sev.o
arch/x86/kvm/vmx/main.c +16 -0
index 18cecf12c7c8..18aef6e23aab 100644
@@ -6,6 +6,22 @@
  #include "nested.h"
  #include "pmu.h"
 
+static bool enable_tdx __ro_after_init;
+module_param_named(tdx, enable_tdx, bool, 0444);
+
+static __init int vt_hardware_setup(void)
+{
+	int ret;
+
+	ret = vmx_hardware_setup();
+	if (ret)
+		return ret;
+
+	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+
+	return 0;
+}
+
  #define VMX_REQUIRED_APICV_INHIBITS				\
  	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
  	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\

arch/x86/kvm/vmx/main.c struct kvm_x86_ops vt_x86_ops __initdata = { · line 41

Quoted 4 lines
arch/x86/kvm/vmx/main.c +1 -0
@@ -22,6 +38,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
  	.hardware_unsetup = vmx_hardware_unsetup,
 
+	/* TDX cpu enablement is done by tdx_hardware_setup(). */

How about if there are some LPs that are offline.
In tdx_hardware_setup(), only online LPs are initialed for TDX, right? Then when an offline LP becoming online, it doesn't have a chance to call tdx_cpu_enable()?

Quoted 117 lines
arch/x86/kvm/vmx/main.c +1 -1
  	.hardware_enable = vmx_hardware_enable,
  	.hardware_disable = vmx_hardware_disable,
  	.has_emulated_msr = vmx_has_emulated_msr,
@@ -161,7 +178,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  };
 
  struct kvm_x86_init_ops vt_init_ops __initdata = {
-	.hardware_setup = vmx_hardware_setup,
+	.hardware_setup = vt_hardware_setup,
  	.handle_intel_pt_intr = NULL,
 
  	.runtime_ops = &vt_x86_ops,
arch/x86/kvm/vmx/tdx.c new file +84 -0
new file mode 100644
index 000000000000..43c504fb4fed
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/cpu.h>
+
+#include <asm/tdx.h>
+
+#include "capabilities.h"
+#include "x86_ops.h"
+#include "x86.h"
+
+#undef pr_fmt
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+static int __init tdx_module_setup(void)
+{
+	int ret;
+
+	ret = tdx_enable();
+	if (ret) {
+		pr_info("Failed to initialize TDX module.\n");
+		return ret;
+	}
+
+	return 0;
+}
+
+struct tdx_enabled {
+	cpumask_var_t enabled;
+	atomic_t err;
+};
+
+static void __init tdx_on(void *_enable)
+{
+	struct tdx_enabled *enable = _enable;
+	int r;
+
+	r = vmx_hardware_enable();
+	if (!r) {
+		cpumask_set_cpu(smp_processor_id(), enable->enabled);
+		r = tdx_cpu_enable();
+	}
+	if (r)
+		atomic_set(&enable->err, r);
+}
+
+static void __init vmx_off(void *_enabled)
+{
+	cpumask_var_t *enabled = (cpumask_var_t *)_enabled;
+
+	if (cpumask_test_cpu(smp_processor_id(), *enabled))
+		vmx_hardware_disable();
+}
+
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	struct tdx_enabled enable = {
+		.err = ATOMIC_INIT(0),
+	};
+	int r = 0;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	if (!zalloc_cpumask_var(&enable.enabled, GFP_KERNEL)) {
+		r = -ENOMEM;
+		goto out;
+	}
+
+	/* tdx_enable() in tdx_module_setup() requires cpus lock. */
+	cpus_read_lock();
+	on_each_cpu(tdx_on, &enable, true); /* TDX requires vmxon. */
+	r = atomic_read(&enable.err);
+	if (!r)
+		r = tdx_module_setup();
+	else
+		r = -EIO;
+	on_each_cpu(vmx_off, &enable.enabled, true);
+	cpus_read_unlock();
+	free_cpumask_var(enable.enabled);
+
+out:
+	return r;
+}
arch/x86/kvm/vmx/x86_ops.h +6 -0
index b936388853ab..346289a2a01c 100644
@@ -135,4 +135,10 @@ void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu);
  #endif
  void vmx_setup_mce(struct kvm_vcpu *vcpu);
 
+#ifdef CONFIG_INTEL_TDX_HOST
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
+#else
+static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
+#endif
+
  #endif /* __KVM_X86_VMX_X86_OPS_H */
#152 lore raw

Re: [PATCH v19 024/130] KVM: TDX: Add placeholders for TDX VM/vcpu structure

In reply to [email protected]
Quoted 50 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add placeholders TDX VM/vcpu structure that overlays with VMX VM/vcpu structures. Initialize VM structure size and vcpu size/align so that x86 KVM common code knows those size irrespective of VMX or TDX. Those structures will be populated as guest creation logic develops.

Add helper functions to check if the VM is guest TD and add conversion functions between KVM VM/VCPU and TDX VM/VCPU.

---
v19:
- correctly update ops.vm_size, vcpu_size and, vcpu_align by Xiaoyao

v14 -> v15:
- use KVM_X86_TDX_VM

---
  arch/x86/kvm/vmx/main.c | 14 ++++++++++++
  arch/x86/kvm/vmx/tdx.c  |  1 +
  arch/x86/kvm/vmx/tdx.h  | 50 +++++++++++++++++++++++++++++++++++++++++
  3 files changed, 65 insertions(+)

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

arch/x86/kvm/vmx/main.c +4 -0
index 18aef6e23aab..e11edbd19e7c 100644
@@ -5,6 +5,7 @@
  #include "vmx.h"
  #include "nested.h"
  #include "pmu.h"
+#include "tdx.h"
 
  static bool enable_tdx __ro_after_init;
  module_param_named(tdx, enable_tdx, bool, 0444);
@@ -18,6 +19,9 @@ static __init int vt_hardware_setup(void)
  		return ret;
 
  	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+	if (enable_tdx)
+		vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
+					   sizeof(struct kvm_tdx));
 
  	return 0;
  }

arch/x86/kvm/vmx/main.c static int __init vt_init(void) · line 224

Quoted 6 lines
arch/x86/kvm/vmx/main.c +3 -0
@@ -215,8 +219,18 @@ static int __init vt_init(void)
  	 * Common KVM initialization _must_ come last, after this, /dev/kvm is
  	 * exposed to userspace!
  	 */
+	/*
+	 * kvm_x86_ops is updated with vt_x86_ops.  vt_x86_ops.vm_size must
+	 * be set before kvm_x86_vendor_init().

The comment is not right?
In this patch, vt_x86_ops.vm_size is set in  vt_hardware_setup(), which is called in kvm_x86_vendor_init().

Since kvm_x86_ops is updated by kvm_ops_update() with the fields of vt_x86_ops. I guess you wanted to say vt_x86_ops.vm_size must be set before kvm_ops_update()?

Quoted 80 lines
arch/x86/kvm/vmx/main.c +7 -0
+	 */
  	vcpu_size = sizeof(struct vcpu_vmx);
  	vcpu_align = __alignof__(struct vcpu_vmx);
+	if (enable_tdx) {
+		vcpu_size = max_t(unsigned int, vcpu_size,
+				  sizeof(struct vcpu_tdx));
+		vcpu_align = max_t(unsigned int, vcpu_align,
+				   __alignof__(struct vcpu_tdx));
+	}
  	r = kvm_init(vcpu_size, vcpu_align, THIS_MODULE);
  	if (r)
  		goto err_kvm_init;
arch/x86/kvm/vmx/tdx.c +1 -0
index 43c504fb4fed..14ef0ccd8f1a 100644
@@ -6,6 +6,7 @@
  #include "capabilities.h"
  #include "x86_ops.h"
  #include "x86.h"
+#include "tdx.h"
 
  #undef pr_fmt
  #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
arch/x86/kvm/vmx/tdx.h new file +50 -0
new file mode 100644
index 000000000000..473013265bd8
@@ -0,0 +1,50 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __KVM_X86_TDX_H
+#define __KVM_X86_TDX_H
+
+#ifdef CONFIG_INTEL_TDX_HOST
+struct kvm_tdx {
+	struct kvm kvm;
+	/* TDX specific members follow. */
+};
+
+struct vcpu_tdx {
+	struct kvm_vcpu	vcpu;
+	/* TDX specific members follow. */
+};
+
+static inline bool is_td(struct kvm *kvm)
+{
+	return kvm->arch.vm_type == KVM_X86_TDX_VM;
+}
+
+static inline bool is_td_vcpu(struct kvm_vcpu *vcpu)
+{
+	return is_td(vcpu->kvm);
+}
+
+static inline struct kvm_tdx *to_kvm_tdx(struct kvm *kvm)
+{
+	return container_of(kvm, struct kvm_tdx, kvm);
+}
+
+static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
+{
+	return container_of(vcpu, struct vcpu_tdx, vcpu);
+}
+#else
+struct kvm_tdx {
+	struct kvm kvm;
+};
+
+struct vcpu_tdx {
+	struct kvm_vcpu	vcpu;
+};
+
+static inline bool is_td(struct kvm *kvm) { return false; }
+static inline bool is_td_vcpu(struct kvm_vcpu *vcpu) { return false; }
+static inline struct kvm_tdx *to_kvm_tdx(struct kvm *kvm) { return NULL; }
+static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu) { return NULL; }
+#endif /* CONFIG_INTEL_TDX_HOST */
+
+#endif /* __KVM_X86_TDX_H */
#159 lore raw

Re: [PATCH v19 025/130] KVM: TDX: Make TDX VM type supported

In reply to [email protected]
Quoted 7 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

NOTE: This patch is in position of the patch series for developers to be able to test codes during the middle of the patch series although this patch series doesn't provide functional features until the all the patches of this patch series. When merging this patch series, this patch can be moved to the end.

Maybe at this point of time, you can consider to move this patch to the end?

Quoted 114 lines

As first step TDX VM support, return that TDX VM type supported to device model, e.g. qemu. The callback to create guest TD is vm_init callback for KVM_CREATE_VM.

---
  arch/x86/kvm/vmx/main.c    | 18 ++++++++++++++++--
  arch/x86/kvm/vmx/tdx.c     |  6 ++++++
  arch/x86/kvm/vmx/vmx.c     |  6 ------
  arch/x86/kvm/vmx/x86_ops.h |  3 ++-
  4 files changed, 24 insertions(+), 9 deletions(-)
arch/x86/kvm/vmx/main.c +16 -2
index e11edbd19e7c..fa19682b366c 100644
@@ -10,6 +10,12 @@
  static bool enable_tdx __ro_after_init;
  module_param_named(tdx, enable_tdx, bool, 0444);
 
+static bool vt_is_vm_type_supported(unsigned long type)
+{
+	return __kvm_is_vm_type_supported(type) ||
+		(enable_tdx && tdx_is_vm_type_supported(type));
+}
+
  static __init int vt_hardware_setup(void)
  {
  	int ret;
@@ -26,6 +32,14 @@ static __init int vt_hardware_setup(void)
  	return 0;
  }
 
+static int vt_vm_init(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return -EOPNOTSUPP;	/* Not ready to create guest TD yet. */
+
+	return vmx_vm_init(kvm);
+}
+
  #define VMX_REQUIRED_APICV_INHIBITS				\
  	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
  	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\
@@ -47,9 +61,9 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.hardware_disable = vmx_hardware_disable,
  	.has_emulated_msr = vmx_has_emulated_msr,
 
-	.is_vm_type_supported = vmx_is_vm_type_supported,
+	.is_vm_type_supported = vt_is_vm_type_supported,
  	.vm_size = sizeof(struct kvm_vmx),
-	.vm_init = vmx_vm_init,
+	.vm_init = vt_vm_init,
  	.vm_destroy = vmx_vm_destroy,
 
  	.vcpu_precreate = vmx_vcpu_precreate,
arch/x86/kvm/vmx/tdx.c +6 -0
index 14ef0ccd8f1a..a7e096fd8361 100644
@@ -24,6 +24,12 @@ static int __init tdx_module_setup(void)
  	return 0;
  }
 
+bool tdx_is_vm_type_supported(unsigned long type)
+{
+	/* enable_tdx check is done by the caller. */
+	return type == KVM_X86_TDX_VM;
+}
+
  struct tdx_enabled {
  	cpumask_var_t enabled;
  	atomic_t err;
arch/x86/kvm/vmx/vmx.c +0 -6
index 2fb1cd2e28a2..d928acc15d0f 100644
@@ -7531,12 +7531,6 @@ int vmx_vcpu_create(struct kvm_vcpu *vcpu)
  	return err;
  }
 
-bool vmx_is_vm_type_supported(unsigned long type)
-{
-	/* TODO: Check if TDX is supported. */
-	return __kvm_is_vm_type_supported(type);
-}
-
  #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
  #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
 
arch/x86/kvm/vmx/x86_ops.h +2 -1
index 346289a2a01c..f4da88a228d0 100644
@@ -28,7 +28,6 @@ void vmx_hardware_unsetup(void);
  int vmx_check_processor_compat(void);
  int vmx_hardware_enable(void);
  void vmx_hardware_disable(void);
-bool vmx_is_vm_type_supported(unsigned long type);
  int vmx_vm_init(struct kvm *kvm);
  void vmx_vm_destroy(struct kvm *kvm);
  int vmx_vcpu_precreate(struct kvm *kvm);
@@ -137,8 +136,10 @@ 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);
  #else
  static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
+static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
  #endif
 
  #endif /* __KVM_X86_VMX_X86_OPS_H */
#169 lore raw

Re: [PATCH v19 027/130] KVM: TDX: Define TDX architectural definitions

In reply to [email protected]
Quoted 136 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Define architectural definitions for KVM to issue the TDX SEAMCALLs.

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

---
v19:
- drop tdvmcall constants by Xiaoyao

v18:
- Add metadata field id

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

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

arch/x86/kvm/vmx/tdx_arch.h new file +105 -0
new file mode 100644
index 000000000000..e2c1a6f429d7
@@ -0,0 +1,265 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* architectural constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_ARCH_H
+#define __KVM_X86_TDX_ARCH_H
+
+#include <linux/types.h>
+
+/*
+ * TDX SEAMCALL API function leaves
+ */
+#define TDH_VP_ENTER			0
+#define TDH_MNG_ADDCX			1
+#define TDH_MEM_PAGE_ADD		2
+#define TDH_MEM_SEPT_ADD		3
+#define TDH_VP_ADDCX			4
+#define TDH_MEM_PAGE_RELOCATE		5
+#define TDH_MEM_PAGE_AUG		6
+#define TDH_MEM_RANGE_BLOCK		7
+#define TDH_MNG_KEY_CONFIG		8
+#define TDH_MNG_CREATE			9
+#define TDH_VP_CREATE			10
+#define TDH_MNG_RD			11
+#define TDH_MR_EXTEND			16
+#define TDH_MR_FINALIZE			17
+#define TDH_VP_FLUSH			18
+#define TDH_MNG_VPFLUSHDONE		19
+#define TDH_MNG_KEY_FREEID		20
+#define TDH_MNG_INIT			21
+#define TDH_VP_INIT			22
+#define TDH_MEM_SEPT_RD			25
+#define TDH_VP_RD			26
+#define TDH_MNG_KEY_RECLAIMID		27
+#define TDH_PHYMEM_PAGE_RECLAIM		28
+#define TDH_MEM_PAGE_REMOVE		29
+#define TDH_MEM_SEPT_REMOVE		30
+#define TDH_SYS_RD			34
+#define TDH_MEM_TRACK			38
+#define TDH_MEM_RANGE_UNBLOCK		39
+#define TDH_PHYMEM_CACHE_WB		40
+#define TDH_PHYMEM_PAGE_WBINVD		41
+#define TDH_VP_WR			43
+#define TDH_SYS_LP_SHUTDOWN		44
+
+/* TDX control structure (TDR/TDCS/TDVPS) field access codes */
+#define TDX_NON_ARCH			BIT_ULL(63)
+#define TDX_CLASS_SHIFT			56
+#define TDX_FIELD_MASK			GENMASK_ULL(31, 0)
+
+#define __BUILD_TDX_FIELD(non_arch, class, field)	\
+	(((non_arch) ? TDX_NON_ARCH : 0) |		\
+	 ((u64)(class) << TDX_CLASS_SHIFT) |		\
+	 ((u64)(field) & TDX_FIELD_MASK))
+
+#define BUILD_TDX_FIELD(class, field)			\
+	__BUILD_TDX_FIELD(false, (class), (field))
+
+#define BUILD_TDX_FIELD_NON_ARCH(class, field)		\
+	__BUILD_TDX_FIELD(true, (class), (field))
+
+
+/* Class code for TD */
+#define TD_CLASS_EXECUTION_CONTROLS	17ULL
+
+/* Class code for TDVPS */
+#define TDVPS_CLASS_VMCS		0ULL
+#define TDVPS_CLASS_GUEST_GPR		16ULL
+#define TDVPS_CLASS_OTHER_GUEST		17ULL
+#define TDVPS_CLASS_MANAGEMENT		32ULL
+
+enum tdx_tdcs_execution_control {
+	TD_TDCS_EXEC_TSC_OFFSET = 10,
+};
+
+/* @field is any of enum tdx_tdcs_execution_control */
+#define TDCS_EXEC(field)		BUILD_TDX_FIELD(TD_CLASS_EXECUTION_CONTROLS, (field))
+
+/* @field is the VMCS field encoding */
+#define TDVPS_VMCS(field)		BUILD_TDX_FIELD(TDVPS_CLASS_VMCS, (field))
+
+enum tdx_vcpu_guest_other_state {
+	TD_VCPU_STATE_DETAILS_NON_ARCH = 0x100,
+};
+
+union tdx_vcpu_state_details {
+	struct {
+		u64 vmxip	: 1;
+		u64 reserved	: 63;
+	};
+	u64 full;
+};
+
+/* @field is any of enum tdx_guest_other_state */
+#define TDVPS_STATE(field)		BUILD_TDX_FIELD(TDVPS_CLASS_OTHER_GUEST, (field))
+#define TDVPS_STATE_NON_ARCH(field)	BUILD_TDX_FIELD_NON_ARCH(TDVPS_CLASS_OTHER_GUEST, (field))
+
+/* Management class fields */
+enum tdx_vcpu_guest_management {
+	TD_VCPU_PEND_NMI = 11,
+};
+
+/* @field is any of enum tdx_vcpu_guest_management */
+#define TDVPS_MANAGEMENT(field)		BUILD_TDX_FIELD(TDVPS_CLASS_MANAGEMENT, (field))
+
+#define TDX_EXTENDMR_CHUNKSIZE		256

arch/x86/kvm/vmx/tdx_arch.h line 115

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+
+struct tdx_cpuid_value {
+	u32 eax;
+	u32 ebx;
+	u32 ecx;
+	u32 edx;
+} __packed;
+
+#define TDX_TD_ATTRIBUTE_DEBUG		BIT_ULL(0)
+#define TDX_TD_ATTR_SEPT_VE_DISABLE	BIT_ULL(28)

It's better to align the style of the naming.

Either use TDX_TD_ATTR_* or TDX_TD_ATTRIBUTE_*?

Quoted 150 lines
arch/x86/kvm/vmx/tdx_arch.h new file +150 -0
+#define TDX_TD_ATTRIBUTE_PKS		BIT_ULL(30)
+#define TDX_TD_ATTRIBUTE_KL		BIT_ULL(31)
+#define TDX_TD_ATTRIBUTE_PERFMON	BIT_ULL(63)
+
+/*
+ * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
+ */
+#define TDX_MAX_VCPUS	(~(u16)0)
+
+struct td_params {
+	u64 attributes;
+	u64 xfam;
+	u16 max_vcpus;
+	u8 reserved0[6];
+
+	u64 eptp_controls;
+	u64 exec_controls;
+	u16 tsc_frequency;
+	u8  reserved1[38];
+
+	u64 mrconfigid[6];
+	u64 mrowner[6];
+	u64 mrownerconfig[6];
+	u64 reserved2[4];
+
+	union {
+		DECLARE_FLEX_ARRAY(struct tdx_cpuid_value, cpuid_values);
+		u8 reserved3[768];
+	};
+} __packed __aligned(1024);
+
+/*
+ * Guest uses MAX_PA for GPAW when set.
+ * 0: GPA.SHARED bit is GPA[47]
+ * 1: GPA.SHARED bit is GPA[51]
+ */
+#define TDX_EXEC_CONTROL_MAX_GPAW      BIT_ULL(0)
+
+/*
+ * TDH.VP.ENTER, TDG.VP.VMCALL preserves RBP
+ * 0: RBP can be used for TDG.VP.VMCALL input. RBP is clobbered.
+ * 1: RBP can't be used for TDG.VP.VMCALL input. RBP is preserved.
+ */
+#define TDX_CONTROL_FLAG_NO_RBP_MOD	BIT_ULL(2)
+
+
+/*
+ * TDX requires the frequency to be defined in units of 25MHz, which is the
+ * frequency of the core crystal clock on TDX-capable platforms, i.e. the TDX
+ * module can only program frequencies that are multiples of 25MHz.  The
+ * frequency must be between 100mhz and 10ghz (inclusive).
+ */
+#define TDX_TSC_KHZ_TO_25MHZ(tsc_in_khz)	((tsc_in_khz) / (25 * 1000))
+#define TDX_TSC_25MHZ_TO_KHZ(tsc_in_25mhz)	((tsc_in_25mhz) * (25 * 1000))
+#define TDX_MIN_TSC_FREQUENCY_KHZ		(100 * 1000)
+#define TDX_MAX_TSC_FREQUENCY_KHZ		(10 * 1000 * 1000)
+
+union tdx_sept_entry {
+	struct {
+		u64 r		:  1;
+		u64 w		:  1;
+		u64 x		:  1;
+		u64 mt		:  3;
+		u64 ipat	:  1;
+		u64 leaf	:  1;
+		u64 a		:  1;
+		u64 d		:  1;
+		u64 xu		:  1;
+		u64 ignored0	:  1;
+		u64 pfn		: 40;
+		u64 reserved	:  5;
+		u64 vgp		:  1;
+		u64 pwa		:  1;
+		u64 ignored1	:  1;
+		u64 sss		:  1;
+		u64 spp		:  1;
+		u64 ignored2	:  1;
+		u64 sve		:  1;
+	};
+	u64 raw;
+};
+
+enum tdx_sept_entry_state {
+	TDX_SEPT_FREE = 0,
+	TDX_SEPT_BLOCKED = 1,
+	TDX_SEPT_PENDING = 2,
+	TDX_SEPT_PENDING_BLOCKED = 3,
+	TDX_SEPT_PRESENT = 4,
+};
+
+union tdx_sept_level_state {
+	struct {
+		u64 level	:  3;
+		u64 reserved0	:  5;
+		u64 state	:  8;
+		u64 reserved1	: 48;
+	};
+	u64 raw;
+};
+
+/*
+ * Global scope metadata field ID.
+ * See Table "Global Scope Metadata", TDX module 1.5 ABI spec.
+ */
+#define MD_FIELD_ID_SYS_ATTRIBUTES		0x0A00000200000000ULL
+#define MD_FIELD_ID_FEATURES0			0x0A00000300000008ULL
+#define MD_FIELD_ID_ATTRS_FIXED0		0x1900000300000000ULL
+#define MD_FIELD_ID_ATTRS_FIXED1		0x1900000300000001ULL
+#define MD_FIELD_ID_XFAM_FIXED0			0x1900000300000002ULL
+#define MD_FIELD_ID_XFAM_FIXED1			0x1900000300000003ULL
+
+#define MD_FIELD_ID_TDCS_BASE_SIZE		0x9800000100000100ULL
+#define MD_FIELD_ID_TDVPS_BASE_SIZE		0x9800000100000200ULL
+
+#define MD_FIELD_ID_NUM_CPUID_CONFIG		0x9900000100000004ULL
+#define MD_FIELD_ID_CPUID_CONFIG_LEAVES		0x9900000300000400ULL
+#define MD_FIELD_ID_CPUID_CONFIG_VALUES		0x9900000300000500ULL
+
+#define MD_FIELD_ID_FEATURES0_NO_RBP_MOD	BIT_ULL(18)
+
+#define TDX_MAX_NR_CPUID_CONFIGS       37
+
+#define TDX_MD_ELEMENT_SIZE_8BITS      0
+#define TDX_MD_ELEMENT_SIZE_16BITS     1
+#define TDX_MD_ELEMENT_SIZE_32BITS     2
+#define TDX_MD_ELEMENT_SIZE_64BITS     3
+
+union tdx_md_field_id {
+	struct {
+		u64 field                       : 24;
+		u64 reserved0                   : 8;
+		u64 element_size_code           : 2;
+		u64 last_element_in_field       : 4;
+		u64 reserved1                   : 3;
+		u64 inc_size                    : 1;
+		u64 write_mask_valid            : 1;
+		u64 context                     : 3;
+		u64 reserved2                   : 1;
+		u64 class                       : 6;
+		u64 reserved3                   : 1;
+		u64 non_arch                    : 1;
+	};
+	u64 raw;
+};
+
+#define TDX_MD_ELEMENT_SIZE_CODE(_field_id)			\
+	({ union tdx_md_field_id _fid = { .raw = (_field_id)};  \
+		_fid.element_size_code; })
+
+#endif /* __KVM_X86_TDX_ARCH_H */
#179 lore raw

Re: [PATCH v19 028/130] KVM: TDX: Add TDX "architectural" error codes

In reply to Isaku Yamahata
Quoted 11 lines · Isaku Yamahata
Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:30AM -0800, [email protected] wrote:
arch/x86/include/asm/shared/tdx.h +0 -0
index fdfd41511b02..28c4a62b7dba 100644
@@ -26,7 +26,13 @@
  #define TDVMCALL_GET_QUOTE		0x10002
  #define TDVMCALL_REPORT_FATAL_ERROR	0x10003
 
Quoted 2 lines

arch/x86/include/asm/shared/tdx.h line 29

Quoted 1 line
arch/x86/include/asm/shared/tdx.h +0 -1
-#define TDVMCALL_STATUS_RETRY		1

Oops, I accidentally removed this constant to break tdx guest build.

Is this the same as "TDVMCALL_RETRY" added in the patch? Since both tdx guest code and VMM share the same header file, maybe it needs another patch to change the code in guest or you just follow the naming style of the exist code?

Quoted 14 lines
arch/x86/include/asm/shared/tdx.h +2 -0
index ef1c8e5a2944..1367a5941499 100644
@@ -28,6 +28,8 @@
  #define TDVMCALL_REPORT_FATAL_ERROR    0x10003
  #define TDVMCALL_SETUP_EVENT_NOTIFY_INTERRUPT  0x10004
 
+#define TDVMCALL_STATUS_RETRY          1
+
  /*
   * TDG.VP.VMCALL Status Codes (returned in R10)
   */
#88 lore raw

Re: [PATCH v19 019/130] KVM: x86: Add is_vm_type_supported callback

In reply to [email protected]
Quoted 6 lines
arch/x86/kvm/x86.c +1 -1
-static bool kvm_is_vm_type_supported(unsigned long type)
+bool __kvm_is_vm_type_supported(unsigned long type)
{
	return type == KVM_X86_DEFAULT_VM ||
	       (type == KVM_X86_SW_PROTECTED_VM &&
		IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_enabled);

maybe just do:

	switch (type) {
	case KVM_X86_DEFAULT_VM:
		return true;
	case KVM_X86_SW_PROTECTED_VM:
		return IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_enabled;
	default:
		return static_call(kvm_x86_is_vm_type_supported)(type);
	}

There are two benefits
1) switch/case improves readability a little.
2) no need to expose __kvm_is_vm_type_supported()

Quoted 12 lines

}

arch/x86/kvm/x86.c +6 -0
+EXPORT_SYMBOL_GPL(__kvm_is_vm_type_supported);
 
+
+static bool kvm_is_vm_type_supported(unsigned long type)
+{
+	return static_call(kvm_x86_is_vm_type_supported)(type);
+}

int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext) {

arch/x86/kvm/x86.c int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext) · line 4796

Quoted 7 lines
arch/x86/kvm/x86.c +4 -0
@@ -4784,6 +4790,10 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 		r = BIT(KVM_X86_DEFAULT_VM);
 		if (kvm_is_vm_type_supported(KVM_X86_SW_PROTECTED_VM))
 			r |= BIT(KVM_X86_SW_PROTECTED_VM);
+		if (kvm_is_vm_type_supported(KVM_X86_TDX_VM))
+			r |= BIT(KVM_X86_TDX_VM);
+		if (kvm_is_vm_type_supported(KVM_X86_SNP_VM))
+			r |= BIT(KVM_X86_SNP_VM);

maybe use a for-loop?

#210 lore raw

Re: [PATCH v19 033/130] KVM: TDX: Add helper function to read TDX metadata in array

In reply to [email protected]
Quoted 7 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To read meta data in series, use table.
Instead of metadata_read(fid0, &data0); metadata_read(...); ... table = { {fid0, &data0}, ...}; metadata-read(tables).
TODO: Once the TDX host code introduces its framework to read TDX metadata, drop this patch and convert the code that uses this.

Do you mean the patch 1-5 included in this patch set.
I think the patch 1-5 of this patch set is doing this thing, right?

Since they are already there, I think you can use them directly in this patch set instead of introducing these temp code?

Quoted 72 lines

---
v18:
- newly added

---
  arch/x86/kvm/vmx/tdx.c | 45 ++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 45 insertions(+)
arch/x86/kvm/vmx/tdx.c +45 -0
index cde971122c1e..dce21f675155 100644
@@ -6,6 +6,7 @@
  #include "capabilities.h"
  #include "x86_ops.h"
  #include "x86.h"
+#include "tdx_arch.h"
  #include "tdx.h"
 
  #undef pr_fmt
@@ -39,6 +40,50 @@ static void __used tdx_guest_keyid_free(int keyid)
  	ida_free(&tdx_guest_keyid_pool, keyid);
  }
 
+#define TDX_MD_MAP(_fid, _ptr)			\
+	{ .fid = MD_FIELD_ID_##_fid,		\
+	  .ptr = (_ptr), }
+
+struct tdx_md_map {
+	u64 fid;
+	void *ptr;
+};
+
+static size_t tdx_md_element_size(u64 fid)
+{
+	switch (TDX_MD_ELEMENT_SIZE_CODE(fid)) {
+	case TDX_MD_ELEMENT_SIZE_8BITS:
+		return 1;
+	case TDX_MD_ELEMENT_SIZE_16BITS:
+		return 2;
+	case TDX_MD_ELEMENT_SIZE_32BITS:
+		return 4;
+	case TDX_MD_ELEMENT_SIZE_64BITS:
+		return 8;
+	default:
+		WARN_ON_ONCE(1);
+		return 0;
+	}
+}
+
+static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+{
+	struct tdx_md_map *m;
+	int ret, i;
+	u64 tmp;
+
+	for (i = 0; i < nr_maps; i++) {
+		m = &maps[i];
+		ret = tdx_sys_metadata_field_read(m->fid, &tmp);
+		if (ret)
+			return ret;
+
+		memcpy(m->ptr, &tmp, tdx_md_element_size(m->fid));
+	}
+
+	return 0;
+}
+
  static int __init tdx_module_setup(void)
  {
  	int ret;
#211 lore raw

Re: [PATCH v19 033/130] KVM: TDX: Add helper function to read TDX metadata in array

Quoted 11 lines · Binbin Wu
Quoted 7 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To read meta data in series, use table.
Instead of metadata_read(fid0, &data0); metadata_read(...); ... table = { {fid0, &data0}, ...}; metadata-read(tables).
TODO: Once the TDX host code introduces its framework to read TDX metadata, drop this patch and convert the code that uses this.

Quoted 5 lines

Do you mean the patch 1-5 included in this patch set.
I think the patch 1-5 of this patch set is doing this thing, right?

Since they are already there, I think you can use them directly in this patch set instead of introducing these temp code?

I may have some mis-understanding, but I think the TODO has been done, right?

Quoted 72 lines
Quoted 71 lines

---
v18:
- newly added
---
  arch/x86/kvm/vmx/tdx.c | 45 ++++++++++++++++++++++++++++++++++++++++++

  1 file changed, 45 insertions(+)
arch/x86/kvm/vmx/tdx.c +44 -0
index cde971122c1e..dce21f675155 100644
@@ -6,6 +6,7 @@
   #include "capabilities.h"
   #include "x86_ops.h"
   #include "x86.h"
+#include "tdx_arch.h"
   #include "tdx.h"
     #undef pr_fmt
@@ -39,6 +40,50 @@ static void __used tdx_guest_keyid_free(int keyid)
       ida_free(&tdx_guest_keyid_pool, keyid);
   }
   +#define TDX_MD_MAP(_fid, _ptr)            \
+    { .fid = MD_FIELD_ID_##_fid,        \
+      .ptr = (_ptr), }
+
+struct tdx_md_map {
+    u64 fid;
+    void *ptr;
+};
+
+static size_t tdx_md_element_size(u64 fid)
+{
+    switch (TDX_MD_ELEMENT_SIZE_CODE(fid)) {
+    case TDX_MD_ELEMENT_SIZE_8BITS:
+        return 1;
+    case TDX_MD_ELEMENT_SIZE_16BITS:
+        return 2;
+    case TDX_MD_ELEMENT_SIZE_32BITS:
+        return 4;
+    case TDX_MD_ELEMENT_SIZE_64BITS:
+        return 8;
+    default:
+        WARN_ON_ONCE(1);
+        return 0;
+    }
+}
+
+static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+{
+    struct tdx_md_map *m;
+    int ret, i;
+    u64 tmp;
+
+    for (i = 0; i < nr_maps; i++) {
+        m = &maps[i];
+        ret = tdx_sys_metadata_field_read(m->fid, &tmp);
+        if (ret)
+            return ret;
+
+        memcpy(m->ptr, &tmp, tdx_md_element_size(m->fid));
+    }
+
+    return 0;
+}
+
   static int __init tdx_module_setup(void)
   {
       int ret;
Reviewed-by on v19 34/130
#215 lore raw

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

In reply to [email protected]
Quoted 4 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX KVM needs system-wide information about the TDX module, store it in struct tdx_info.

Nit: Maybe you can add some description about hardware_unsetup()?

Quoted 201 lines

---
v19:
- Added features0
- Use tdx_sys_metadata_read()
- Fix error recovery path by Yuan

Change v18:
- Newly Added

---
  arch/x86/include/uapi/asm/kvm.h | 11 +++++
  arch/x86/kvm/vmx/main.c         |  9 +++-
  arch/x86/kvm/vmx/tdx.c          | 80 ++++++++++++++++++++++++++++++++-
  arch/x86/kvm/vmx/x86_ops.h      |  2 +
  4 files changed, 100 insertions(+), 2 deletions(-)
arch/x86/include/uapi/asm/kvm.h +11 -0
index aa7a56a47564..45b2c2304491 100644
@@ -567,4 +567,15 @@ struct kvm_pmu_event_filter {
  #define KVM_X86_TDX_VM		2
  #define KVM_X86_SNP_VM		3
 
+#define KVM_TDX_CPUID_NO_SUBLEAF	((__u32)-1)
+
+struct kvm_tdx_cpuid_config {
+	__u32 leaf;
+	__u32 sub_leaf;
+	__u32 eax;
+	__u32 ebx;
+	__u32 ecx;
+	__u32 edx;
+};
+
  #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/main.c +8 -1
index fa19682b366c..a948a6959ac7 100644
@@ -32,6 +32,13 @@ static __init int vt_hardware_setup(void)
  	return 0;
  }
 
+static void vt_hardware_unsetup(void)
+{
+	if (enable_tdx)
+		tdx_hardware_unsetup();
+	vmx_hardware_unsetup();
+}
+
  static int vt_vm_init(struct kvm *kvm)
  {
  	if (is_td(kvm))
@@ -54,7 +61,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
  	.check_processor_compatibility = vmx_check_processor_compat,
 
-	.hardware_unsetup = vmx_hardware_unsetup,
+	.hardware_unsetup = vt_hardware_unsetup,
 
  	/* TDX cpu enablement is done by tdx_hardware_setup(). */
  	.hardware_enable = vmx_hardware_enable,
arch/x86/kvm/vmx/tdx.c +79 -1
index dce21f675155..5edfb99abb89 100644
@@ -40,6 +40,21 @@ static void __used tdx_guest_keyid_free(int keyid)
  	ida_free(&tdx_guest_keyid_pool, keyid);
  }
 
+struct tdx_info {
+	u64 features0;
+	u64 attributes_fixed0;
+	u64 attributes_fixed1;
+	u64 xfam_fixed0;
+	u64 xfam_fixed1;
+
+	u16 num_cpuid_config;
+	/* This must the last member. */
+	DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+
  #define TDX_MD_MAP(_fid, _ptr)			\
  	{ .fid = MD_FIELD_ID_##_fid,		\
  	  .ptr = (_ptr), }
@@ -66,7 +81,7 @@ static size_t tdx_md_element_size(u64 fid)
  	}
  }
 
-static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
  {
  	struct tdx_md_map *m;
  	int ret, i;
@@ -84,9 +99,26 @@ static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
  	return 0;
  }
 
+#define TDX_INFO_MAP(_field_id, _member)			\
+	TD_SYSINFO_MAP(_field_id, struct tdx_info, _member)
+
  static int __init tdx_module_setup(void)
  {
+	u16 num_cpuid_config;
  	int ret;
+	u32 i;
+
+	struct tdx_md_map mds[] = {
+		TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+	};
+
+	struct tdx_metadata_field_mapping fields[] = {
+		TDX_INFO_MAP(FEATURES0, features0),
+		TDX_INFO_MAP(ATTRS_FIXED0, attributes_fixed0),
+		TDX_INFO_MAP(ATTRS_FIXED1, attributes_fixed1),
+		TDX_INFO_MAP(XFAM_FIXED0, xfam_fixed0),
+		TDX_INFO_MAP(XFAM_FIXED1, xfam_fixed1),
+	};
 
  	ret = tdx_enable();
  	if (ret) {
@@ -94,7 +126,48 @@ static int __init tdx_module_setup(void)
  		return ret;
  	}
 
+	ret = tdx_md_read(mds, ARRAY_SIZE(mds));
+	if (ret)
+		return ret;
+
+	tdx_info = kzalloc(sizeof(*tdx_info) +
+			   sizeof(*tdx_info->cpuid_configs) * num_cpuid_config,
+			   GFP_KERNEL);
+	if (!tdx_info)
+		return -ENOMEM;
+	tdx_info->num_cpuid_config = num_cpuid_config;
+
+	ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
+	if (ret)
+		goto error_out;
+
+	for (i = 0; i < num_cpuid_config; i++) {
+		struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+		u64 leaf, eax_ebx, ecx_edx;
+		struct tdx_md_map cpuids[] = {
+			TDX_MD_MAP(CPUID_CONFIG_LEAVES + i, &leaf),
+			TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2, &eax_ebx),
+			TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2 + 1, &ecx_edx),
+		};
+
+		ret = tdx_md_read(cpuids, ARRAY_SIZE(cpuids));
+		if (ret)
+			goto error_out;
+
+		c->leaf = (u32)leaf;
+		c->sub_leaf = leaf >> 32;
+		c->eax = (u32)eax_ebx;
+		c->ebx = eax_ebx >> 32;
+		c->ecx = (u32)ecx_edx;
+		c->edx = ecx_edx >> 32;
+	}
+
  	return 0;
+
+error_out:
+	/* kfree() accepts NULL. */
+	kfree(tdx_info);
+	return ret;
  }
 
  bool tdx_is_vm_type_supported(unsigned long type)
@@ -162,3 +235,8 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  out:
  	return r;
  }
+
+void tdx_hardware_unsetup(void)
+{
+	kfree(tdx_info);
+}
arch/x86/kvm/vmx/x86_ops.h +2 -0
index f4da88a228d0..e8cb4ae81cf1 100644
@@ -136,9 +136,11 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 
  #ifdef CONFIG_INTEL_TDX_HOST
  int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
+void tdx_hardware_unsetup(void);
  bool tdx_is_vm_type_supported(unsigned long type);
  #else
  static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
+static inline void tdx_hardware_unsetup(void) {}
  static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
  #endif
 
#89 lore raw

Re: [PATCH v19 019/130] KVM: x86: Add is_vm_type_supported callback

In reply to Chao Gao
Quoted 17 lines · Chao Gao
Quoted 6 lines
arch/x86/kvm/x86.c +1 -1
-static bool kvm_is_vm_type_supported(unsigned long type)
+bool __kvm_is_vm_type_supported(unsigned long type)
{
	return type == KVM_X86_DEFAULT_VM ||
	       (type == KVM_X86_SW_PROTECTED_VM &&
		IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_enabled);

maybe just do:

	switch (type) {
	case KVM_X86_DEFAULT_VM:
		return true;
	case KVM_X86_SW_PROTECTED_VM:
		return IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_enabled;
	default:
		return static_call(kvm_x86_is_vm_type_supported)(type);
	}
Quoted 3 lines

There are two benefits
1) switch/case improves readability a little.
2) no need to expose __kvm_is_vm_type_supported()

The following[1] patch will supersede this patch. Will drop this patch.

[1] https://lore.kernel.org/kvm/[email protected]/

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

Re: [PATCH v19 023/130] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Binbin Wu
Quoted 24 lines · Binbin Wu
Quoted 24 lines
arch/x86/kvm/vmx/main.c +16 -0
index 18cecf12c7c8..18aef6e23aab 100644
@@ -6,6 +6,22 @@
  #include "nested.h"
  #include "pmu.h"
+static bool enable_tdx __ro_after_init;
+module_param_named(tdx, enable_tdx, bool, 0444);
+
+static __init int vt_hardware_setup(void)
+{
+	int ret;
+
+	ret = vmx_hardware_setup();
+	if (ret)
+		return ret;
+
+	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+
+	return 0;
+}
+
  #define VMX_REQUIRED_APICV_INHIBITS				\
Quoted 8 lines

arch/x86/kvm/vmx/main.c struct kvm_x86_ops vt_x86_ops __initdata = { · line 39

Quoted 5 lines
arch/x86/kvm/vmx/main.c +1 -0
  	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
  	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\
@@ -22,6 +38,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.hardware_unsetup = vmx_hardware_unsetup,
+	/* TDX cpu enablement is done by tdx_hardware_setup(). */

How about if there are some LPs that are offline.
In tdx_hardware_setup(), only online LPs are initialed for TDX, right?

Correct.

Quoted 2 lines

Then when an offline LP becoming online, it doesn't have a chance to call tdx_cpu_enable()?

KVM registers kvm_online/offline_cpu() @ kvm_main.c as cpu hotplug callbacks. Eventually x86 kvm hardware_enable() is called on online/offline event.

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

Re: [PATCH v19 024/130] KVM: TDX: Add placeholders for TDX VM/vcpu structure

In reply to Binbin Wu
Quoted 31 lines · Binbin Wu
Quoted 20 lines
arch/x86/kvm/vmx/main.c +4 -0
index 18aef6e23aab..e11edbd19e7c 100644
@@ -5,6 +5,7 @@
  #include "vmx.h"
  #include "nested.h"
  #include "pmu.h"
+#include "tdx.h"
  static bool enable_tdx __ro_after_init;
  module_param_named(tdx, enable_tdx, bool, 0444);
@@ -18,6 +19,9 @@ static __init int vt_hardware_setup(void)
  		return ret;
  	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+	if (enable_tdx)
+		vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
+					   sizeof(struct kvm_tdx));
  	return 0;
  }

arch/x86/kvm/vmx/main.c static int __init vt_init(void) · line 224

Quoted 6 lines
arch/x86/kvm/vmx/main.c +3 -0
@@ -215,8 +219,18 @@ static int __init vt_init(void)
  	 * Common KVM initialization _must_ come last, after this, /dev/kvm is
  	 * exposed to userspace!
  	 */
+	/*
+	 * kvm_x86_ops is updated with vt_x86_ops.  vt_x86_ops.vm_size must
+	 * be set before kvm_x86_vendor_init().

The comment is not right?
In this patch, vt_x86_ops.vm_size is set in  vt_hardware_setup(), which is called in kvm_x86_vendor_init().

Quoted 3 lines

Since kvm_x86_ops is updated by kvm_ops_update() with the fields of vt_x86_ops. I guess you wanted to say vt_x86_ops.vm_size must be set before kvm_ops_update()?

Correct. Here's an updated version.

/*
* vt_hardware_setup() updates vt_x86_ops. Because kvm_ops_update()
* copies vt_x86_ops to kvm_x86_op, vt_x86_ops must be updated before
* kvm_ops_update() called by kvm_x86_vendor_init().
*/

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

Re: [PATCH v19 027/130] KVM: TDX: Define TDX architectural definitions

In reply to Binbin Wu
Quoted 5 lines · Binbin Wu

arch/x86/kvm/vmx/tdx_arch.h line 115

Quoted 2 lines
arch/x86/kvm/vmx/tdx_arch.h new file +2 -0
+#define TDX_TD_ATTRIBUTE_DEBUG		BIT_ULL(0)
+#define TDX_TD_ATTR_SEPT_VE_DISABLE	BIT_ULL(28)

It's better to align the style of the naming.

Either use TDX_TD_ATTR_* or TDX_TD_ATTRIBUTE_*?

Good point. I'll adopt TDX_TD_ATTR_* because TDX_TD_ATTR_SEPT_VE_DISABLE is already long.

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

Re: [PATCH v19 033/130] KVM: TDX: Add helper function to read TDX metadata in array

In reply to Binbin Wu
Quoted 15 lines · Binbin Wu
Quoted 12 lines · Binbin Wu
Quoted 8 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To read meta data in series, use table.
Instead of metadata_read(fid0, &data0); metadata_read(...); ... table = { {fid0, &data0}, ...}; metadata-read(tables).
TODO: Once the TDX host code introduces its framework to read TDX metadata,
drop this patch and convert the code that uses this.

Quoted 7 lines
Quoted 5 lines

Do you mean the patch 1-5 included in this patch set.
I think the patch 1-5 of this patch set is doing this thing, right?

Since they are already there, I think you can use them directly in this patch set instead of introducing these temp code?

I may have some mis-understanding, but I think the TODO has been done, right?

I meant the following patch series.
https://lore.kernel.org/kvm/[email protected]/

If (the future version of) the patch series doesn't provide a way to read one metadata with size, we need to keep this patch.

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

Re: [PATCH v19 028/130] KVM: TDX: Add TDX "architectural" error codes

In reply to Binbin Wu
Quoted 16 lines · Binbin Wu
Quoted 12 lines · Isaku Yamahata

arch/x86/include/asm/shared/tdx.h line 28

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:30AM -0800, [email protected] wrote:
arch/x86/include/asm/shared/tdx.h +0 -1
index fdfd41511b02..28c4a62b7dba 100644
@@ -26,7 +26,13 @@
  #define TDVMCALL_GET_QUOTE		0x10002
  #define TDVMCALL_REPORT_FATAL_ERROR	0x10003
-#define TDVMCALL_STATUS_RETRY		1

Oops, I accidentally removed this constant to break tdx guest build.

Quoted 4 lines

Is this the same as "TDVMCALL_RETRY" added in the patch? Since both tdx guest code and VMM share the same header file, maybe it needs another patch to change the code in guest or you just follow the naming style of the exist code?

The style in other TDX place is without STATUS. I don't want to play bike shedding. For now I'd like to leave TDVMCALL_STATUS_RETRY, not add TDVMCALL_RETRY, and keep other TDVMCALL_*.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to Edgecombe, Rick P
Quoted 25 lines · Rick P
Quoted 17 lines · On Mon, 2024-02-26 at 00:26 -0800, [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 private
page table, allocate one more page to copy the dummy page table for KVM MMU
code to directly walk.  Resolve KVM page fault with the existing code, and
do additional operations necessary for the private page table.

Quoted 6 lines

To
distinguish such cases, the existing KVM page table is called a shared page
table (i.e. not associated with private page table), and the page table
with private page table is called a private page table.

Quoted 3 lines

This makes it sound like the dummy page table for the private alias is also called a shared page table, but in the drawing below it looks like only the shared alias is called "shared PT".

How about this,
Call the existing KVM page table associated with shared GPA as shared page table. Call the KVM page table associate with private GPA as private page table.

Quoted 40 lines
Quoted 40 lines

  The relationship
is depicted below.

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

              KVM page fault                     |

                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
    shared PT root      dummy PT root            |    private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            dummy PT ----propagate---->   private 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.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU.  It is used to propagate PT change to the actual private PT which is used by CPU.

---

...snip...

Quoted 17 lines
Quoted 17 lines
arch/x86/kvm/mmu/mmu_internal.h +5 -1
index e3f54701f98d..002f3f80bf3b 100644
@@ -101,7 +101,21 @@ struct kvm_mmu_page {
                 int root_count;
                 refcount_t tdp_mmu_root_count;
         };
-       unsigned int unsync_children;
+       union {
+               struct {
+                       unsigned int unsync_children;
+                       /*
+                        * Number of writes since the last time

traversal
+                        * visited this page.

Quoted 8 lines
Quoted 3 lines

+                        */
+                       atomic_t write_flooding_count; +               };

I think the point of putting these in a union is that they only apply to shadow paging and so can't be used with TDX. I think you are putting more than the sizeof(void *) in there as there are multiple in the same category.

I'm not sure if I'm following you.
On x86_64, sizeof(unsigned int) = 4, sizeof(atomic_t) = 4, sizeof(void *) = 8. I moved write_flooding_count to have 8 bytes.

Quoted 3 lines

But there seems to be a new one added, *shadowed_translation. Should it go in there too? Is the union because there wasn't room before, or just to be tidy?

Originally TDX MMU support was implemented for legacy tdp mmu. It used shadowed_translation. It was not an option at that time. Later we switched to (new) TDP MMU. Now we have choice to which member to overlay.

Quoted 4 lines

I think the commit log should have more discussion of this union and maybe a comment in the struct to explain the purpose of the organization. Can you explain the reasoning now for the sake of discussion?

Sure. We'd like to add void * pointer to struct kvm_mmu_page. Given some members are used only for legacy KVM MMUs and not used for TDP MMU, we can save memory overhead with union. We have options.
- u64 *shadowed_translation
This was not chosen for the old implementation. Now this is option.
- pack unsync_children and write_flooding_count for 8 bytes
This patch chosen this for historical reason. Other two option is possible.
- unsync_child_bitmap
Historically it was unioned with other members. But now it's not.

I don't have strong preference for TDX support as long as we can have void *.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 28 lines · Isaku Yamahata
Quoted 25 lines · Rick P
Quoted 23 lines · On Mon, 2024-02-26 at 00:26 -0800, [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 private
page table, allocate one more page to copy the dummy page table for KVM MMU
code to directly walk.  Resolve KVM page fault with the existing code, and
do additional operations necessary for the private page table.

To
distinguish such cases, the existing KVM page table is called a shared page
table (i.e. not associated with private page table), and the page table
with private page table is called a private page table.

Quoted 7 lines
Quoted 3 lines

This makes it sound like the dummy page table for the private alias is also called a shared page table, but in the drawing below it looks like only the shared alias is called "shared PT".

How about this,
Call the existing KVM page table associated with shared GPA as shared page table. > Call the KVM page table associate with private GPA as private page table.

For the second one, are you talking about the *true* secure/private EPT page table used by hardware, or the one visible to KVM but not used by hardware?

We have 3 page tables as you mentioned:

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

If I recall correctly, we used to call the last one "mirrored (private) page table".

I lost the tracking when we changed to use "dummy page table", but it seems to me "mirrored" is better than "dummy" because the latter means it is useless but in fact it is used to propagate changes to the real private page table used by hardware.

Btw, one nit, perhaps:

"Shared PT is visible to KVM and it is used by CPU." -> "Shared PT is visible to KVM and it is used by CPU for shared mappings".

To make it more clearer it is used for "shared mappings".

But this may be unnecessary to others, so up to you.

#366 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 12 lines · Kai

We have 3 page tables as you mentioned:

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

If I recall correctly, we used to call the last one "mirrored (private)
page table".

Quoted 5 lines

I lost the tracking when we changed to use "dummy page table", but it seems to me "mirrored" is better than "dummy" because the latter means
it is useless but in fact it is used to propagate changes to the real private page table used by hardware.

Mirrored makes sense to me. So like:

Private - Table actually mapping private alias, in TDX module Shared - Shared alias table, visible in KVM
Mirror - Mirroring private, visible in KVM

Quoted 9 lines

Btw, one nit, perhaps:

"Shared PT is visible to KVM and it is used by CPU." -> "Shared PT is visible to KVM and it is used by CPU for shared mappings".

To make it more clearer it is used for "shared mappings".

But this may be unnecessary to others, so up to you.

Yep, this seems clearer.

#371 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

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

I think the point of putting these in a union is that they only apply
to shadow paging and so can't be used with TDX. I think you are putting
more than the sizeof(void *) in there as there are multiple in the same
category.

Quoted 4 lines

I'm not sure if I'm following you.
On x86_64, sizeof(unsigned int) = 4, sizeof(atomic_t) = 4, sizeof(void *) = 8.
I moved write_flooding_count to have 8 bytes.

Ah, I see. Yes you are write about it summing to 8. Ok, what do you think about putting a comment that these will always be unused with TDX?

Quoted 19 lines
Quoted 5 lines

But there seems to be a new one added, *shadowed_translation. Should it go in there too? Is the union because there wasn't room before, or just to be tidy?

Originally TDX MMU support was implemented for legacy tdp mmu.  It used
shadowed_translation.  It was not an option at that time.  Later we switched to
(new) TDP MMU.  Now we have choice to which member to overlay.

Quoted 5 lines

I think the commit log should have more discussion of this union and
maybe a comment in the struct to explain the purpose of the organization. Can you explain the reasoning now for the sake of discussion?

Quoted 7 lines

Sure.  We'd like to add void * pointer to struct kvm_mmu_page.  Given some
members are used only for legacy KVM MMUs and not used for TDP MMU, we can save
memory overhead with union.  We have options.
- u64 *shadowed_translation
  This was not chosen for the old implementation. Now this is option.

This seems a little more straighforward, but I'm on the fence if it's worth changing.

Quoted 8 lines

- pack unsync_children and write_flooding_count for 8 bytes This patch chosen this for historical reason. Other two option is possible.
- unsync_child_bitmap
  Historically it was unioned with other members. But now it's not.

I don't have strong preference for TDX support as long as we can have void *.

#213 lore raw

Re: [PATCH v19 033/130] KVM: TDX: Add helper function to read TDX metadata in array

In reply to [email protected]
Quoted 5 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To read meta data in series, use table.
Instead of metadata_read(fid0, &data0); metadata_read(...); ... table = { {fid0, &data0}, ...}; metadata-read(tables).

This explains nothing why the code introduced in patch 5 cannot be used.

Quoted 2 lines

TODO: Once the TDX host code introduces its framework to read TDX metadata, drop this patch and convert the code that uses this.

Seriously, what is this?? Please treat your patches as "official" patches.

Quoted 59 lines

---
v18:
- newly added

---
  arch/x86/kvm/vmx/tdx.c | 45 ++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 45 insertions(+)
arch/x86/kvm/vmx/tdx.c +35 -0
index cde971122c1e..dce21f675155 100644
@@ -6,6 +6,7 @@
  #include "capabilities.h"
  #include "x86_ops.h"
  #include "x86.h"
+#include "tdx_arch.h"
  #include "tdx.h"
 
  #undef pr_fmt
@@ -39,6 +40,50 @@ static void __used tdx_guest_keyid_free(int keyid)
  	ida_free(&tdx_guest_keyid_pool, keyid);
  }
 
+#define TDX_MD_MAP(_fid, _ptr)			\
+	{ .fid = MD_FIELD_ID_##_fid,		\
+	  .ptr = (_ptr), }
+
+struct tdx_md_map {
+	u64 fid;
+	void *ptr;
+};
+
+static size_t tdx_md_element_size(u64 fid)
+{
+	switch (TDX_MD_ELEMENT_SIZE_CODE(fid)) {
+	case TDX_MD_ELEMENT_SIZE_8BITS:
+		return 1;
+	case TDX_MD_ELEMENT_SIZE_16BITS:
+		return 2;
+	case TDX_MD_ELEMENT_SIZE_32BITS:
+		return 4;
+	case TDX_MD_ELEMENT_SIZE_64BITS:
+		return 8;
+	default:
+		WARN_ON_ONCE(1);
+		return 0;
+	}
+}
+
+static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+{
+	struct tdx_md_map *m;
+	int ret, i;
+	u64 tmp;
+
+	for (i = 0; i < nr_maps; i++) {
+		m = &maps[i];

arch/x86/kvm/vmx/tdx.c static void __used tdx_guest_keyid_free(int keyid) · line 86

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		ret = tdx_sys_metadata_field_read(m->fid, &tmp);
+		if (ret)
+			return ret;
+
+		memcpy(m->ptr, &tmp, tdx_md_element_size(m->fid));
+	}
+
+	return 0;
+}
+

It's just insane to have two duplicated mechanism for metadata reading.

This will only confuse people.

If there's anything missing in patch 1-5, we can enhance them.

#216 lore raw

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

In reply to [email protected]
Quoted 83 lines
arch/x86/kvm/vmx/tdx.c +57 -1
+struct tdx_info {
+	u64 features0;
+	u64 attributes_fixed0;
+	u64 attributes_fixed1;
+	u64 xfam_fixed0;
+	u64 xfam_fixed1;
+
+	u16 num_cpuid_config;
+	/* This must the last member. */
+	DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+
  #define TDX_MD_MAP(_fid, _ptr)			\
  	{ .fid = MD_FIELD_ID_##_fid,		\
  	  .ptr = (_ptr), }
@@ -66,7 +81,7 @@ static size_t tdx_md_element_size(u64 fid)
  	}
  }
 
-static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
  {
  	struct tdx_md_map *m;
  	int ret, i;
@@ -84,9 +99,26 @@ static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
  	return 0;
  }
 
+#define TDX_INFO_MAP(_field_id, _member)			\
+	TD_SYSINFO_MAP(_field_id, struct tdx_info, _member)
+
  static int __init tdx_module_setup(void)
  {
+	u16 num_cpuid_config;
  	int ret;
+	u32 i;
+
+	struct tdx_md_map mds[] = {
+		TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+	};
+
+	struct tdx_metadata_field_mapping fields[] = {
+		TDX_INFO_MAP(FEATURES0, features0),
+		TDX_INFO_MAP(ATTRS_FIXED0, attributes_fixed0),
+		TDX_INFO_MAP(ATTRS_FIXED1, attributes_fixed1),
+		TDX_INFO_MAP(XFAM_FIXED0, xfam_fixed0),
+		TDX_INFO_MAP(XFAM_FIXED1, xfam_fixed1),
+	};
 
  	ret = tdx_enable();
  	if (ret) {
@@ -94,7 +126,48 @@ static int __init tdx_module_setup(void)
  		return ret;
  	}
 
+	ret = tdx_md_read(mds, ARRAY_SIZE(mds));
+	if (ret)
+		return ret;
+
+	tdx_info = kzalloc(sizeof(*tdx_info) +
+			   sizeof(*tdx_info->cpuid_configs) * num_cpuid_config,
+			   GFP_KERNEL);
+	if (!tdx_info)
+		return -ENOMEM;
+	tdx_info->num_cpuid_config = num_cpuid_config;
+
+	ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
+	if (ret)
+		goto error_out;
+
+	for (i = 0; i < num_cpuid_config; i++) {
+		struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+		u64 leaf, eax_ebx, ecx_edx;
+		struct tdx_md_map cpuids[] = {
+			TDX_MD_MAP(CPUID_CONFIG_LEAVES + i, &leaf),
+			TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2, &eax_ebx),
+			TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2 + 1, &ecx_edx),
+		};
+

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 162

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		ret = tdx_md_read(cpuids, ARRAY_SIZE(cpuids));
+		if (ret)
+			goto error_out;
+
+		c->leaf = (u32)leaf;
+		c->sub_leaf = leaf >> 32;
+		c->eax = (u32)eax_ebx;
+		c->ebx = eax_ebx >> 32;
+		c->ecx = (u32)ecx_edx;
+		c->edx = ecx_edx >> 32;

OK I can see why you don't want to use ...

	struct tdx_metadata_field_mapping fields[] = {
		TDX_INFO_MAP(NUM_CPUID_CONFIG, num_cpuid_config),
	};

... to read num_cpuid_config first, because the memory to hold @tdx_info hasn't been allocated, because its size depends on the num_cpuid_config.

And I confess it's because the tdx_sys_metadata_field_read() that got exposed in patch ("x86/virt/tdx: Export global metadata read infrastructure") only returns 'u64' for all metadata field, and you didn't want to use something like this:

	u64 num_cpuid_config;
	
	tdx_sys_metadata_field_read(..., &num_cpuid_config);

	...

	tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

	tdx_info->num_cpuid_config = (u16)num_cpuid_config;

(I know people may don't like the assigning 'u64' to 'u16', but it seems nothing wrong to me, because the way done in (1) below effectively has the same result comparing to type case).

But there are other (better) ways to do:

1) you can introduce a helper as suggested by Xiaoyao in [*]:

	int tdx_sys_metadata_read_single(u64 field_id,
					int bytes,  void *buf)
	{
		return stbuf_read_sys_metadata_field(field_id, 0,
						bytes, buf);
	}

And do:

	tdx_sys_metadata_read_single(NUM_CPUID_CONFIG,
		sizeof(num_cpuid_config), &num_cpuid_config);

That's _much_ cleaner than the 'struct tdx_md_map', which only confuses people.

But I don't think we need to do this as mentioned above -- we just do type cast.

2) You can just preallocate enough memory. It cannot be larger than 1024B, right? You can even just allocate one page. It's just 4K, no one cares.

Then you can do:

	struct tdx_metadata_field_mapping tdx_info_fields = {
		...
		TDX_INFO_MAP(NUM_CPUID_CONFIG, num_cpuid_config),
	};

	tdx_sys_metadata_read(tdx_info_fields,
			ARRAY_SIZE(tdx_info_fields, tdx_info);

And then you read the CPUID_CONFIG array one by one using the same 'struct tdx_metadata_field_mapping' and tdx_sys_metadata_read():

	for (i = 0; i < tdx_info->num_cpuid_config; i++) {
		struct tdx_metadata_field_mapping cpuid_fields = {
			TDX_CPUID_CONFIG_MAP(CPUID_CONFIG_LEAVES + i,
						leaf),
			...
		};
		struct kvm_tdx_cpuid_config *c =
				&tdx_info->cpuid_configs[i];

		tdx_sys_metadata_read(cpuid_fields,
				ARRAY_SIZE(cpuid_fields), c);

		....
	}

So stopping having the duplicated 'struct tdx_md_map' and related staff, as they are absolutely unnecessary and only confuses people.

Btw, I am hesitated to do the change suggested by Xiaoyao in [*], as to me there's nothing wrong to do the type cast. I'll response in that thread.

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

#19 lore raw

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to [email protected]
Quoted 5 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Kai Huang <[email protected]>

KVM will need to make SEAMCALLs to create and run TDX guests. Export SEAMCALL functions for KVM to use.

Could you also list the reason that we want to expose __seamcall() directly, rather than wanting to put some higher level wrappers in the TDX host code, and export them?

For example, we can give a summary of the SEAMCALLs (e.g., how many in total, and roughly introduce them based on categories) that will be used by KVM, and clarify the reasons why we want to just export __seamcall().

E.g., we can say something like this:

TD;LR:

KVM roughly will need to use dozens of SEAMCALLs, and all these are logically related to creating and running TDX guests. It makes more sense to just export __seamcall() and let KVM maintain these VM-related wrappers rather than having the TDX host code to provide wrappers for each SEAMCALL or higher-level abstraction.

Long version:

You give a detailed explanation of SEAMCALLs that will be used by KVM, and clarify logically it's better to manage these code in KVM.

#665 lore raw

Re: [PATCH v19 120/130] KVM: TDX: Add a method to ignore dirty logging

In reply to [email protected]

arch/x86/kvm/vmx/main.c static u8 vt_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio) · line 843

Quoted 8 lines · On Mon, 2024-02-26 at 00:27 -0800, [email protected] wrote:

arch/x86/kvm/vmx/main.c +7 -0
+static void vt_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
+{
+       if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+               return;
+
+       vmx_update_cpu_dirty_logging(vcpu);
+}

Discussed this first part offline, but logging it here. Since guest_memfd cannot have dirty logging, this is essentially bugging the VM if somehow they manage anyway. But it should be blocked via the code in check_memory_region_flags().

On the subject of warnings and KVM_BUG_ON(), my feeling so far is that this series is quite aggressive about these. Is it due the complexity of the series? I think maybe we can remove some of the simple ones, but not sure if there was already some discussion on what level is appropriate.

#372 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to Edgecombe, Rick P
Quoted 9 lines · Rick P
Quoted 8 lines · Isaku Yamahata
Quoted 7 lines

I think the point of putting these in a union is that they only apply
to shadow paging and so can't be used with TDX. I think you are putting
more than the sizeof(void *) in there as there are multiple in the same
category.

Quoted 8 lines
Quoted 4 lines

I'm not sure if I'm following you.
On x86_64, sizeof(unsigned int) = 4, sizeof(atomic_t) = 4, sizeof(void *) = 8.
I moved write_flooding_count to have 8 bytes.

Ah, I see. Yes you are write about it summing to 8. Ok, what do you think about putting a comment that these will always be unused with TDX?

Ok, will add a comment. Also add some to the commit message.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to Edgecombe, Rick P
Quoted 28 lines · Rick P
Quoted 12 lines · Kai

We have 3 page tables as you mentioned:

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

If I recall correctly, we used to call the last one "mirrored (private)
page table".

Quoted 5 lines

I lost the tracking when we changed to use "dummy page table", but it seems to me "mirrored" is better than "dummy" because the latter means
it is useless but in fact it is used to propagate changes to the real private page table used by hardware.

Mirrored makes sense to me. So like:

Private - Table actually mapping private alias, in TDX module Shared - Shared alias table, visible in KVM
Mirror - Mirroring private, visible in KVM

Quoted 3 lines

Btw, one nit, perhaps:

Quoted 8 lines
Quoted 6 lines

"Shared PT is visible to KVM and it is used by CPU." -> "Shared PT is visible to KVM and it is used by CPU for shared mappings".

To make it more clearer it is used for "shared mappings".

But this may be unnecessary to others, so up to you.

Yep, this seems clearer.

Here is the updated one. Renamed dummy -> mirroed.

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

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

PT: Page table
Shared PT: visible to KVM, and the CPU uses it for shared mappings. Private PT: the CPU uses it, but it is invisible to KVM. TDX module
updates this table to map private guest pages.
Mirrored PT: It is visible to KVM, but the CPU doesn't use it. KVM uses it
to propagate PT change to the actual private PT.

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

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Huang, Kai

Dave, care to weigh in here?

Context (whether to export the generic __seamcall for KVM's use):
https://lore.kernel.org/lkml/[email protected]/

Quoted 6 lines · Kai

KVM roughly will need to use dozens of SEAMCALLs, and all these are logically related to creating and running TDX guests.  It makes more sense to just export __seamcall() and let KVM maintain these VM- related
wrappers rather than having the TDX host code to provide wrappers for each SEAMCALL or higher-level abstraction.

The helpers being discussed are these:
https://lore.kernel.org/lkml/7cfd33d896fce7b49bcf4b7179d0ded22c06b8c2.1708933498.git.isaku.yamahata@intel.com/

I guess there are three options:
1. Export the low level seamcall function
2. Export a bunch of higher level helper functions
3. Duplicate __seamcall asm in KVM

Letting modules make unrestricted seamcalls is not ideal. Preventing the compiler from inlining the small logic in the static inline helpers is not ideal. Duplicating code is not ideal. Hmm.

I want to say 2 sounds the least worst of the three. But I'm not sure. I'm not sure if x86 folks would like to police new seamcalls, or be bothered by it, either.

#21 lore raw

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

Quoted 5 lines · Rick P

I guess there are three options:
1. Export the low level seamcall function
2. Export a bunch of higher level helper functions
3. Duplicate __seamcall asm in KVM

Quoted 7 lines

Letting modules make unrestricted seamcalls is not ideal. Preventing the compiler from inlining the small logic in the static inline helpers is not ideal. Duplicating code is not ideal. Hmm.

I want to say 2 sounds the least worst of the three. But I'm not sure. I'm not sure if x86 folks would like to police new seamcalls, or be bothered by it, either.

#3 is the only objectively awful one. :)

In the end, we actually _want_ to have conversations about these things.
There are going to be considerations about what functionality should be
in KVM or the core kernel. We don't want KVM doing any calls that could affect global TDX module state, for instance.

But I'd also defer to the KVM maintainers on this. They're the ones that have to play the symbol exporting game a lot more than I ever do. If they cringe at the idea of adding 20 (or whatever) exports, then that's a lot more important than the possibility of some other silly module abusing the generic exported __seamcall.

#666 lore raw

Re: [PATCH v19 120/130] KVM: TDX: Add a method to ignore dirty logging

In reply to Edgecombe, Rick P
Quoted 14 lines · Rick P

arch/x86/kvm/vmx/main.c static u8 vt_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio) · line 843

Quoted 8 lines · On Mon, 2024-02-26 at 00:27 -0800, [email protected] wrote:

arch/x86/kvm/vmx/main.c +7 -0
+static void vt_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
+{
+       if (KVM_BUG_ON(is_td_vcpu(vcpu), vcpu->kvm))
+               return;
+
+       vmx_update_cpu_dirty_logging(vcpu);
+}

Discussed this first part offline, but logging it here. Since guest_memfd cannot have dirty logging, this is essentially bugging the VM if somehow they manage anyway. But it should be blocked via the code in check_memory_region_flags().

Will drop this patch.

Quoted 5 lines

On the subject of warnings and KVM_BUG_ON(), my feeling so far is that this series is quite aggressive about these. Is it due the complexity of the series? I think maybe we can remove some of the simple ones, but not sure if there was already some discussion on what level is appropriate.

KVM_BUG_ON() was helpful at the early stage. Because we don't hit them recently, it's okay to remove them. Will remove them.

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

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

In reply to Huang, Kai
Quoted 127 lines · Kai
Quoted 80 lines
arch/x86/kvm/vmx/tdx.c +15 -0
+struct tdx_info {
+    u64 features0;
+    u64 attributes_fixed0;
+    u64 attributes_fixed1;
+    u64 xfam_fixed0;
+    u64 xfam_fixed1;
+
+    u16 num_cpuid_config;
+    /* This must the last member. */
+    DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+

  #define TDX_MD_MAP(_fid, _ptr)            \
      { .fid = MD_FIELD_ID_##_fid,        \
        .ptr = (_ptr), }

arch/x86/kvm/vmx/tdx.c +42 -1
@@ -66,7 +81,7 @@ static size_t tdx_md_element_size(u64 fid)
       }
   }
-static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
   {
       struct tdx_md_map *m;
       int ret, i;
@@ -84,9 +99,26 @@ static int __used tdx_md_read(struct tdx_md_map 
 *maps, int nr_maps)
       return 0;
   }
+#define TDX_INFO_MAP(_field_id, _member)            \
+    TD_SYSINFO_MAP(_field_id, struct tdx_info, _member)
+
   static int __init tdx_module_setup(void)
   {
+    u16 num_cpuid_config;
       int ret;
+    u32 i;
+
+    struct tdx_md_map mds[] = {
+        TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+    };
+
+    struct tdx_metadata_field_mapping fields[] = {
+        TDX_INFO_MAP(FEATURES0, features0),
+        TDX_INFO_MAP(ATTRS_FIXED0, attributes_fixed0),
+        TDX_INFO_MAP(ATTRS_FIXED1, attributes_fixed1),
+        TDX_INFO_MAP(XFAM_FIXED0, xfam_fixed0),
+        TDX_INFO_MAP(XFAM_FIXED1, xfam_fixed1),
+    };
       ret = tdx_enable();
       if (ret) {
@@ -94,7 +126,48 @@ static int __init tdx_module_setup(void)
           return ret;
       }
+    ret = tdx_md_read(mds, ARRAY_SIZE(mds));
+    if (ret)
+        return ret;
+
+    tdx_info = kzalloc(sizeof(*tdx_info) +
+               sizeof(*tdx_info->cpuid_configs) * num_cpuid_config,
+               GFP_KERNEL);
+    if (!tdx_info)
+        return -ENOMEM;
+    tdx_info->num_cpuid_config = num_cpuid_config;
+
+    ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
+    if (ret)
+        goto error_out;
+
+    for (i = 0; i < num_cpuid_config; i++) {
+        struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+        u64 leaf, eax_ebx, ecx_edx;
+        struct tdx_md_map cpuids[] = {
+            TDX_MD_MAP(CPUID_CONFIG_LEAVES + i, &leaf),
+            TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2, &eax_ebx),
+            TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2 + 1, &ecx_edx),
+        };
+

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 161

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+        ret = tdx_md_read(cpuids, ARRAY_SIZE(cpuids));
+        if (ret)
+            goto error_out;
+
+        c->leaf = (u32)leaf;
+        c->sub_leaf = leaf >> 32;
+        c->eax = (u32)eax_ebx;
+        c->ebx = eax_ebx >> 32;
+        c->ecx = (u32)ecx_edx;
+        c->edx = ecx_edx >> 32;

OK I can see why you don't want to use ...

    struct tdx_metadata_field_mapping fields[] = { TDX_INFO_MAP(NUM_CPUID_CONFIG, num_cpuid_config), };

... to read num_cpuid_config first, because the memory to hold @tdx_info hasn't been allocated, because its size depends on the num_cpuid_config.

And I confess it's because the tdx_sys_metadata_field_read() that got exposed in patch ("x86/virt/tdx: Export global metadata read infrastructure") only returns 'u64' for all metadata field, and you didn't want to use something like this:

    u64 num_cpuid_config;

    tdx_sys_metadata_field_read(..., &num_cpuid_config);

    ...

    tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

    tdx_info->num_cpuid_config = (u16)num_cpuid_config;

(I know people may don't like the assigning 'u64' to 'u16', but it seems nothing wrong to me, because the way done in (1) below effectively has the same result comparing to type case).

But there are other (better) ways to do:

1) you can introduce a helper as suggested by Xiaoyao in [*]:

    int tdx_sys_metadata_read_single(u64 field_id, int bytes,  void *buf)
    {
        return stbuf_read_sys_metadata_field(field_id, 0, bytes, buf);
    }

Quoted 8 lines

And do:

    tdx_sys_metadata_read_single(NUM_CPUID_CONFIG, sizeof(num_cpuid_config), &num_cpuid_config);

That's _much_ cleaner than the 'struct tdx_md_map', which only confuses people.

But I don't think we need to do this as mentioned above -- we just do type cast.

type cast needs another tmp variable to hold the output of u64.

The reason I want to introduce tdx_sys_metadata_read_single() is to provide a simple and unified interface for other codes to read one metadata field, instead of letting the caller to use temporary u64 variable and handle the cast or memcpy itself.

Quoted 5 lines

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

#104 lore raw

Re: [PATCH v19 023/130] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Isaku Yamahata
Quoted 34 lines · Isaku Yamahata
Quoted 23 lines · Binbin Wu
Quoted 23 lines
arch/x86/kvm/vmx/main.c +16 -0
index 18cecf12c7c8..18aef6e23aab 100644
@@ -6,6 +6,22 @@
   #include "nested.h"
   #include "pmu.h"
+static bool enable_tdx __ro_after_init;
+module_param_named(tdx, enable_tdx, bool, 0444);
+
+static __init int vt_hardware_setup(void)
+{
+	int ret;
+
+	ret = vmx_hardware_setup();
+	if (ret)
+		return ret;
+
+	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+
+	return 0;
+}
+
Quoted 8 lines

arch/x86/kvm/vmx/main.c struct kvm_x86_ops vt_x86_ops __initdata = { · line 39

Quoted 6 lines
arch/x86/kvm/vmx/main.c +1 -0
   #define VMX_REQUIRED_APICV_INHIBITS				\
   	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
   	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\
@@ -22,6 +38,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
   	.hardware_unsetup = vmx_hardware_unsetup,
+	/* TDX cpu enablement is done by tdx_hardware_setup(). */

How about if there are some LPs that are offline.
In tdx_hardware_setup(), only online LPs are initialed for TDX, right?

Quoted 7 lines

Correct.

Quoted 2 lines

Then when an offline LP becoming online, it doesn't have a chance to call tdx_cpu_enable()?

KVM registers kvm_online/offline_cpu() @ kvm_main.c as cpu hotplug callbacks. Eventually x86 kvm hardware_enable() is called on online/offline event.

Yes, hardware_enable() will be called when online, but  hardware_enable() now is vmx_hardware_enable() right? It doens't call tdx_cpu_enable() during the online path.

#218 lore raw

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

In reply to Xiaoyao Li
Quoted 145 lines · Xiaoyao
Quoted 135 lines · Kai
Quoted 80 lines
arch/x86/kvm/vmx/tdx.c +15 -0
+struct tdx_info {
+    u64 features0;
+    u64 attributes_fixed0;
+    u64 attributes_fixed1;
+    u64 xfam_fixed0;
+    u64 xfam_fixed1;
+
+    u16 num_cpuid_config;
+    /* This must the last member. */
+    DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+

  #define TDX_MD_MAP(_fid, _ptr)            \
      { .fid = MD_FIELD_ID_##_fid,        \
        .ptr = (_ptr), }

arch/x86/kvm/vmx/tdx.c +42 -1
@@ -66,7 +81,7 @@ static size_t tdx_md_element_size(u64 fid)
       }
   }
-static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
   {
       struct tdx_md_map *m;
       int ret, i;
@@ -84,9 +99,26 @@ static int __used tdx_md_read(struct tdx_md_map 
 *maps, int nr_maps)
       return 0;
   }
+#define TDX_INFO_MAP(_field_id, _member)            \
+    TD_SYSINFO_MAP(_field_id, struct tdx_info, _member)
+
   static int __init tdx_module_setup(void)
   {
+    u16 num_cpuid_config;
       int ret;
+    u32 i;
+
+    struct tdx_md_map mds[] = {
+        TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+    };
+
+    struct tdx_metadata_field_mapping fields[] = {
+        TDX_INFO_MAP(FEATURES0, features0),
+        TDX_INFO_MAP(ATTRS_FIXED0, attributes_fixed0),
+        TDX_INFO_MAP(ATTRS_FIXED1, attributes_fixed1),
+        TDX_INFO_MAP(XFAM_FIXED0, xfam_fixed0),
+        TDX_INFO_MAP(XFAM_FIXED1, xfam_fixed1),
+    };
       ret = tdx_enable();
       if (ret) {
@@ -94,7 +126,48 @@ static int __init tdx_module_setup(void)
           return ret;
       }
+    ret = tdx_md_read(mds, ARRAY_SIZE(mds));
+    if (ret)
+        return ret;
+
+    tdx_info = kzalloc(sizeof(*tdx_info) +
+               sizeof(*tdx_info->cpuid_configs) * num_cpuid_config,
+               GFP_KERNEL);
+    if (!tdx_info)
+        return -ENOMEM;
+    tdx_info->num_cpuid_config = num_cpuid_config;
+
+    ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
+    if (ret)
+        goto error_out;
+
+    for (i = 0; i < num_cpuid_config; i++) {
+        struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+        u64 leaf, eax_ebx, ecx_edx;
+        struct tdx_md_map cpuids[] = {
+            TDX_MD_MAP(CPUID_CONFIG_LEAVES + i, &leaf),
+            TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2, &eax_ebx),
+            TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2 + 1, &ecx_edx),
+        };
+

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 161

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+        ret = tdx_md_read(cpuids, ARRAY_SIZE(cpuids));
+        if (ret)
+            goto error_out;
+
+        c->leaf = (u32)leaf;
+        c->sub_leaf = leaf >> 32;
+        c->eax = (u32)eax_ebx;
+        c->ebx = eax_ebx >> 32;
+        c->ecx = (u32)ecx_edx;
+        c->edx = ecx_edx >> 32;

OK I can see why you don't want to use ...

    struct tdx_metadata_field_mapping fields[] = { TDX_INFO_MAP(NUM_CPUID_CONFIG, num_cpuid_config), };

... to read num_cpuid_config first, because the memory to hold @tdx_info hasn't been allocated, because its size depends on the num_cpuid_config.

And I confess it's because the tdx_sys_metadata_field_read() that got exposed in patch ("x86/virt/tdx: Export global metadata read infrastructure") only returns 'u64' for all metadata field, and you didn't want to use something like this:

    u64 num_cpuid_config;

    tdx_sys_metadata_field_read(..., &num_cpuid_config);

    ...

    tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

    tdx_info->num_cpuid_config = (u16)num_cpuid_config;

(I know people may don't like the assigning 'u64' to 'u16', but it seems nothing wrong to me, because the way done in (1) below effectively has the same result comparing to type case).

But there are other (better) ways to do:

1) you can introduce a helper as suggested by Xiaoyao in [*]:

    int tdx_sys_metadata_read_single(u64 field_id, int bytes,  void *buf)
    {
        return stbuf_read_sys_metadata_field(field_id, 0, bytes, buf);
    }

And do:

Quoted 8 lines

    tdx_sys_metadata_read_single(NUM_CPUID_CONFIG, sizeof(num_cpuid_config), &num_cpuid_config);

That's _much_ cleaner than the 'struct tdx_md_map', which only confuses people.

But I don't think we need to do this as mentioned above -- we just do type cast.

Quoted 7 lines

type cast needs another tmp variable to hold the output of u64.

The reason I want to introduce tdx_sys_metadata_read_single() is to provide a simple and unified interface for other codes to read one metadata field, instead of letting the caller to use temporary u64 variable and handle the cast or memcpy itself.

You can always use u64 to hold u16 metadata field AFAICT, so it doesn't have to be temporary.

Here is what Isaku can do using the current API:

	u64 num_cpuid_config;
	

	...

	tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

	...

(you can do explicit (u16)num_cpuid_config type cast above if you want.)

With your suggestion, here is what Isaku can do:

	u16 num_cpuid_config;

	...

	tdx_sys_metadata_read_single(NUM_CPUID_CONFIG,
sizeof(num_cpuid_config),
				&num_cpuid_config);

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

	...

I don't see big difference?

One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway.

So, while I don't quite object your proposal, I don't see it being quite necessary.

I'll let other people to have a say.

#219 lore raw

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

Quoted 159 lines · Kai
Quoted 145 lines · Xiaoyao
Quoted 135 lines · Kai
Quoted 80 lines
arch/x86/kvm/vmx/tdx.c +57 -1
+struct tdx_info {
+    u64 features0;
+    u64 attributes_fixed0;
+    u64 attributes_fixed1;
+    u64 xfam_fixed0;
+    u64 xfam_fixed1;
+
+    u16 num_cpuid_config;
+    /* This must the last member. */
+    DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+
   #define TDX_MD_MAP(_fid, _ptr)            \
       { .fid = MD_FIELD_ID_##_fid,        \
         .ptr = (_ptr), }
@@ -66,7 +81,7 @@ static size_t tdx_md_element_size(u64 fid)
       }
   }
-static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
   {
       struct tdx_md_map *m;
       int ret, i;
@@ -84,9 +99,26 @@ static int __used tdx_md_read(struct tdx_md_map
 *maps, int nr_maps)
       return 0;
   }
+#define TDX_INFO_MAP(_field_id, _member)            \
+    TD_SYSINFO_MAP(_field_id, struct tdx_info, _member)
+
   static int __init tdx_module_setup(void)
   {
+    u16 num_cpuid_config;
       int ret;
+    u32 i;
+
+    struct tdx_md_map mds[] = {
+        TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+    };
+
+    struct tdx_metadata_field_mapping fields[] = {
+        TDX_INFO_MAP(FEATURES0, features0),
+        TDX_INFO_MAP(ATTRS_FIXED0, attributes_fixed0),
+        TDX_INFO_MAP(ATTRS_FIXED1, attributes_fixed1),
+        TDX_INFO_MAP(XFAM_FIXED0, xfam_fixed0),
+        TDX_INFO_MAP(XFAM_FIXED1, xfam_fixed1),
+    };
       ret = tdx_enable();
       if (ret) {
@@ -94,7 +126,48 @@ static int __init tdx_module_setup(void)
           return ret;
       }
+    ret = tdx_md_read(mds, ARRAY_SIZE(mds));
+    if (ret)
+        return ret;
+
+    tdx_info = kzalloc(sizeof(*tdx_info) +
+               sizeof(*tdx_info->cpuid_configs) * num_cpuid_config,
+               GFP_KERNEL);
+    if (!tdx_info)
+        return -ENOMEM;
+    tdx_info->num_cpuid_config = num_cpuid_config;
+
+    ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
+    if (ret)
+        goto error_out;
+
+    for (i = 0; i < num_cpuid_config; i++) {
+        struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+        u64 leaf, eax_ebx, ecx_edx;
+        struct tdx_md_map cpuids[] = {
+            TDX_MD_MAP(CPUID_CONFIG_LEAVES + i, &leaf),
+            TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2, &eax_ebx),
+            TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2 + 1, &ecx_edx),
+        };
+

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 161

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+        ret = tdx_md_read(cpuids, ARRAY_SIZE(cpuids));
+        if (ret)
+            goto error_out;
+
+        c->leaf = (u32)leaf;
+        c->sub_leaf = leaf >> 32;
+        c->eax = (u32)eax_ebx;
+        c->ebx = eax_ebx >> 32;
+        c->ecx = (u32)ecx_edx;
+        c->edx = ecx_edx >> 32;

OK I can see why you don't want to use ...

      struct tdx_metadata_field_mapping fields[] = {
          TDX_INFO_MAP(NUM_CPUID_CONFIG, num_cpuid_config),
      };

... to read num_cpuid_config first, because the memory to hold @tdx_info hasn't been allocated, because its size depends on the num_cpuid_config.

And I confess it's because the tdx_sys_metadata_field_read() that got exposed in patch ("x86/virt/tdx: Export global metadata read infrastructure") only returns 'u64' for all metadata field, and you didn't want to use something like this:

    u64 num_cpuid_config;

      tdx_sys_metadata_field_read(..., &num_cpuid_config);

    ...

      tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

      tdx_info->num_cpuid_config = (u16)num_cpuid_config;

(I know people may don't like the assigning 'u64' to 'u16', but it seems nothing wrong to me, because the way done in (1) below effectively has the same result comparing to type case).

But there are other (better) ways to do:

1) you can introduce a helper as suggested by Xiaoyao in [*]:

      int tdx_sys_metadata_read_single(u64 field_id,
                      int bytes,  void *buf)
      {
          return stbuf_read_sys_metadata_field(field_id, 0,
                          bytes, buf);
      }

And do:

Quoted 8 lines
      tdx_sys_metadata_read_single(NUM_CPUID_CONFIG,
          sizeof(num_cpuid_config), &num_cpuid_config);

That's _much_ cleaner than the 'struct tdx_md_map', which only confuses people.

But I don't think we need to do this as mentioned above -- we just do type cast.

Quoted 7 lines

type cast needs another tmp variable to hold the output of u64.

The reason I want to introduce tdx_sys_metadata_read_single() is to provide a simple and unified interface for other codes to read one metadata field, instead of letting the caller to use temporary u64 variable and handle the cast or memcpy itself.

You can always use u64 to hold u16 metadata field AFAICT, so it doesn't have to be temporary.

Here is what Isaku can do using the current API:

Quoted 10 lines
	u64 num_cpuid_config;


	...

	tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

Dosen't num_cpuid_config serve as temporary variable in some sense?

For this case, it needs to be used for calculating the size of tdx_info. So we have to have it. But it's not the common case.

E.g., if we have another non-u64 field (e.g., field_x) in tdx_info, we cannot to read it via

	tdx_sys_metadata_field_read(FIELD_X_ID, &tdx_info->field_x);

we have to use a temporary u64 variable.

Quoted 41 lines
	...

(you can do explicit (u16)num_cpuid_config type cast above if you want.)

With your suggestion, here is what Isaku can do:

	u16 num_cpuid_config;

	...

	tdx_sys_metadata_read_single(NUM_CPUID_CONFIG,
sizeof(num_cpuid_config),
				&num_cpuid_config);

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

	...

I don't see big difference?

One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway.

So, while I don't quite object your proposal, I don't see it being quite necessary.

I'll let other people to have a say.

#220 lore raw

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

Quoted 7 lines · Xiaoyao
Quoted 3 lines

Here is what Isaku can do using the current API:

  u64 num_cpuid_config;

 >

Quoted 3 lines

  ...

Quoted 7 lines
Quoted 5 lines

  tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

  tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

  tdx_info->num_cpuid_config = num_cpuid_config;

Dosen't num_cpuid_config serve as temporary variable in some sense?

You need it, regardless whether it is u64 or u16.

Quoted 10 lines

For this case, it needs to be used for calculating the size of tdx_info. So we have to have it. But it's not the common case.

E.g., if we have another non-u64 field (e.g., field_x) in tdx_info, we cannot to read it via

	tdx_sys_metadata_field_read(FIELD_X_ID, &tdx_info->field_x);

we have to use a temporary u64 variable.

Let me repeat below in my _previous_ reply:

"
One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway. "

So sorry I am not seeing a real example from you.

#221 lore raw

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

Quoted 42 lines · Kai
Quoted 7 lines · Xiaoyao
Quoted 3 lines

Here is what Isaku can do using the current API:

  u64 num_cpuid_config;

 >

Quoted 3 lines

  ...

Quoted 7 lines
Quoted 5 lines

  tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

  tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

  tdx_info->num_cpuid_config = num_cpuid_config;

Dosen't num_cpuid_config serve as temporary variable in some sense?

You need it, regardless whether it is u64 or u16.

Quoted 10 lines

For this case, it needs to be used for calculating the size of tdx_info. So we have to have it. But it's not the common case.

E.g., if we have another non-u64 field (e.g., field_x) in tdx_info, we cannot to read it via

	tdx_sys_metadata_field_read(FIELD_X_ID, &tdx_info->field_x);

we have to use a temporary u64 variable.

Let me repeat below in my _previous_ reply:

"
One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);
Quoted 3 lines

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway. "

tdx_sys_metadata_read() is too complicated for just reading one field.

Caller needs to prepare a one-item size array of "struct tdx_metadata_field_mapping" and pass the correct offset.

Quoted 2 lines

So sorry I am not seeing a real example from you.

#667 lore raw

Re: [PATCH v19 120/130] KVM: TDX: Add a method to ignore dirty logging

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

On the subject of warnings and KVM_BUG_ON(), my feeling so far is that
this series is quite aggressive about these. Is it due the complexity
of the series? I think maybe we can remove some of the simple ones, but
not sure if there was already some discussion on what level is appropriate.

Quoted 3 lines

KVM_BUG_ON() was helpful at the early stage.  Because we don't hit them
recently, it's okay to remove them.  Will remove them.

Hmm. We probably need to do it case by case.

#222 lore raw

Re: [PATCH v19 034/130] KVM: TDX: Get system-wide info about TDX module on initialization

In reply to Huang, Kai
Quoted 175 lines · Kai
Quoted 79 lines
arch/x86/kvm/vmx/tdx.c +57 -1
+struct tdx_info {
+	u64 features0;
+	u64 attributes_fixed0;
+	u64 attributes_fixed1;
+	u64 xfam_fixed0;
+	u64 xfam_fixed1;
+
+	u16 num_cpuid_config;
+	/* This must the last member. */
+	DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+
  #define TDX_MD_MAP(_fid, _ptr)			\
  	{ .fid = MD_FIELD_ID_##_fid,		\
  	  .ptr = (_ptr), }
@@ -66,7 +81,7 @@ static size_t tdx_md_element_size(u64 fid)
  	}
  }
-static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
+static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
  {
  	struct tdx_md_map *m;
  	int ret, i;
@@ -84,9 +99,26 @@ static int __used tdx_md_read(struct tdx_md_map *maps, int nr_maps)
  	return 0;
  }
+#define TDX_INFO_MAP(_field_id, _member)			\
+	TD_SYSINFO_MAP(_field_id, struct tdx_info, _member)
+
  static int __init tdx_module_setup(void)
  {
+	u16 num_cpuid_config;
  	int ret;
+	u32 i;
+
+	struct tdx_md_map mds[] = {
+		TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+	};
+
+	struct tdx_metadata_field_mapping fields[] = {
+		TDX_INFO_MAP(FEATURES0, features0),
+		TDX_INFO_MAP(ATTRS_FIXED0, attributes_fixed0),
+		TDX_INFO_MAP(ATTRS_FIXED1, attributes_fixed1),
+		TDX_INFO_MAP(XFAM_FIXED0, xfam_fixed0),
+		TDX_INFO_MAP(XFAM_FIXED1, xfam_fixed1),
+	};
  	ret = tdx_enable();
  	if (ret) {
@@ -94,7 +126,48 @@ static int __init tdx_module_setup(void)
  		return ret;
  	}
+	ret = tdx_md_read(mds, ARRAY_SIZE(mds));
+	if (ret)
+		return ret;
+
+	tdx_info = kzalloc(sizeof(*tdx_info) +
+			   sizeof(*tdx_info->cpuid_configs) * num_cpuid_config,
+			   GFP_KERNEL);
+	if (!tdx_info)
+		return -ENOMEM;
+	tdx_info->num_cpuid_config = num_cpuid_config;
+
+	ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
+	if (ret)
+		goto error_out;
+
+	for (i = 0; i < num_cpuid_config; i++) {
+		struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+		u64 leaf, eax_ebx, ecx_edx;
+		struct tdx_md_map cpuids[] = {
+			TDX_MD_MAP(CPUID_CONFIG_LEAVES + i, &leaf),
+			TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2, &eax_ebx),
+			TDX_MD_MAP(CPUID_CONFIG_VALUES + i * 2 + 1, &ecx_edx),
+		};
+

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 161

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		ret = tdx_md_read(cpuids, ARRAY_SIZE(cpuids));
+		if (ret)
+			goto error_out;
+
+		c->leaf = (u32)leaf;
+		c->sub_leaf = leaf >> 32;
+		c->eax = (u32)eax_ebx;
+		c->ebx = eax_ebx >> 32;
+		c->ecx = (u32)ecx_edx;
+		c->edx = ecx_edx >> 32;

OK I can see why you don't want to use ...

	struct tdx_metadata_field_mapping fields[] = {
		TDX_INFO_MAP(NUM_CPUID_CONFIG, num_cpuid_config),
	};

... to read num_cpuid_config first, because the memory to hold @tdx_info hasn't been allocated, because its size depends on the num_cpuid_config.

And I confess it's because the tdx_sys_metadata_field_read() that got exposed in patch ("x86/virt/tdx: Export global metadata read infrastructure") only returns 'u64' for all metadata field, and you didn't want to use something like this:

	u64 num_cpuid_config;
	
	tdx_sys_metadata_field_read(..., &num_cpuid_config);

	...

	tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

	tdx_info->num_cpuid_config = (u16)num_cpuid_config;

(I know people may don't like the assigning 'u64' to 'u16', but it seems nothing wrong to me, because the way done in (1) below effectively has the same result comparing to type case).

But there are other (better) ways to do:

1) you can introduce a helper as suggested by Xiaoyao in [*]:

	int tdx_sys_metadata_read_single(u64 field_id,
					int bytes,  void *buf)
	{
		return stbuf_read_sys_metadata_field(field_id, 0,
						bytes, buf);
	}

And do:

	tdx_sys_metadata_read_single(NUM_CPUID_CONFIG,
		sizeof(num_cpuid_config), &num_cpuid_config);

That's _much_ cleaner than the 'struct tdx_md_map', which only confuses people.

But I don't think we need to do this as mentioned above -- we just do type cast.

2) You can just preallocate enough memory. It cannot be larger than 1024B, right? You can even just allocate one page. It's just 4K, no one cares.

Then you can do:

	struct tdx_metadata_field_mapping tdx_info_fields = {
		...
		TDX_INFO_MAP(NUM_CPUID_CONFIG, num_cpuid_config),
	};

	tdx_sys_metadata_read(tdx_info_fields,
			ARRAY_SIZE(tdx_info_fields, tdx_info);

And then you read the CPUID_CONFIG array one by one using the same 'struct tdx_metadata_field_mapping' and tdx_sys_metadata_read():

	for (i = 0; i < tdx_info->num_cpuid_config; i++) {
		struct tdx_metadata_field_mapping cpuid_fields = {
			TDX_CPUID_CONFIG_MAP(CPUID_CONFIG_LEAVES + i,
						leaf),
			...
		};
		struct kvm_tdx_cpuid_config *c =
				&tdx_info->cpuid_configs[i];

		tdx_sys_metadata_read(cpuid_fields,
				ARRAY_SIZE(cpuid_fields), c);

		....
	}
Quoted 2 lines

So stopping having the duplicated 'struct tdx_md_map' and related staff, as they are absolutely unnecessary and only confuses people.

Ok, I'll rewrite the code to use tdx_sys_metadata_read() by introducng tentative struct in a function scope.

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

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Dave Hansen
Quoted 14 lines · Dave Hansen
Quoted 5 lines · Rick P

I guess there are three options:
1. Export the low level seamcall function
2. Export a bunch of higher level helper functions
3. Duplicate __seamcall asm in KVM

Quoted 7 lines

Letting modules make unrestricted seamcalls is not ideal. Preventing the compiler from inlining the small logic in the static inline helpers is not ideal. Duplicating code is not ideal. Hmm.

I want to say 2 sounds the least worst of the three. But I'm not sure. I'm not sure if x86 folks would like to police new seamcalls, or be bothered by it, either.

Quoted 6 lines

#3 is the only objectively awful one. :)

In the end, we actually _want_ to have conversations about these things.
There are going to be considerations about what functionality should be
in KVM or the core kernel. We don't want KVM doing any calls that could affect global TDX module state, for instance.

Heh, Like this one?

        static inline u64 tdh_sys_lp_shutdown(void)
        {
        	struct tdx_module_args in = {
        	};
        
        	return tdx_seamcall(TDH_SYS_LP_SHUTDOWN, &in, NULL);
        }

Which isn't actually used...

Quoted 5 lines

But I'd also defer to the KVM maintainers on this. They're the ones that have to play the symbol exporting game a lot more than I ever do. If they cringe at the idea of adding 20 (or whatever) exports, then that's a lot more important than the possibility of some other silly module abusing the generic exported __seamcall.

I don't care much about exports. What I do care about is sane code, and while the current code _looks_ pretty, it's actually quite insane.

I get why y'all put SEAMCALL in assembly subroutines; the macro shenanigans I originally wrote years ago were their own brand of crazy, and dealing with GPRs that can't be asm() constraints often results in brittle code.

But the tdx_module_args structure approach generates truly atrocious code. Yes, SEAMCALL is inherently slow, but that doesn't mean that we shouldn't at least try to generate efficient code. And it's not just efficiency that is lost, the generated code ends up being much harder to read than it ought to be.

E.g. the seemingly simple

        static inline u64 tdh_mem_page_remove(hpa_t tdr, gpa_t gpa, int level,
        				      struct tdx_module_args *out)
        {
        	struct tdx_module_args in = {
        		.rcx = gpa | level,
        		.rdx = tdr,
        	};

        	return tdx_seamcall_sept(TDH_MEM_PAGE_REMOVE, &in, out);
        }

generates the below monstrosity with gcc-13. And that's just one SEAMCALL wrapper, *every* single one generates the same mess. clang-16 is kinda sorta a little better, as it at least inlines the helpers that have single callers.

So my feedback is to not worry about the exports, and instead focus on figuring out a way to make the generated code less bloated and easier to read/debug.

Dump of assembler code for function tdh_mem_page_remove:
0x0000000000032b20 <+0>: push %r15
0x0000000000032b22 <+2>: xor %eax,%eax
0x0000000000032b24 <+4>: movabs $0x8000ff0000000006,%r15

   0x0000000000032b2e <+14>:	push   %r14
   0x0000000000032b30 <+16>:	mov    %rcx,%r14
   0x0000000000032b33 <+19>:	mov    $0xb,%ecx
   0x0000000000032b38 <+24>:	push   %r13
   0x0000000000032b3a <+26>:	movslq %edx,%r13
   0x0000000000032b3d <+29>:	push   %r12
   0x0000000000032b3f <+31>:	or     %rsi,%r13
   0x0000000000032b42 <+34>:	mov    $0x11,%r12d
   0x0000000000032b48 <+40>:	push   %rbp
   0x0000000000032b49 <+41>:	movabs $0x8000020300000000,%rbp
   0x0000000000032b53 <+51>:	push   %rbx
   0x0000000000032b54 <+52>:	sub    $0x70,%rsp
   0x0000000000032b58 <+56>:	mov    %rdi,(%rsp)
   0x0000000000032b5c <+60>:	lea    0x18(%rsp),%rdi
   0x0000000000032b61 <+65>:	rep stos %rax,%es:(%rdi)
   0x0000000000032b64 <+68>:	mov    (%rsp),%rax
   0x0000000000032b68 <+72>:	mov    %r13,(%r14)
   0x0000000000032b6b <+75>:	mov    $0xa,%ebx
   0x0000000000032b70 <+80>:	mov    %rax,0x8(%r14)
   0x0000000000032b74 <+84>:	mov    0x18(%rsp),%rax
   0x0000000000032b79 <+89>:	mov    %rax,0x10(%r14)
   0x0000000000032b7d <+93>:	mov    0x20(%rsp),%rax
   0x0000000000032b82 <+98>:	mov    %rax,0x18(%r14)
   0x0000000000032b86 <+102>:	mov    0x28(%rsp),%rax
   0x0000000000032b8b <+107>:	mov    %rax,0x20(%r14)
   0x0000000000032b8f <+111>:	mov    0x30(%rsp),%rax
   0x0000000000032b94 <+116>:	mov    %rax,0x28(%r14)
   0x0000000000032b98 <+120>:	mov    0x38(%rsp),%rax
   0x0000000000032b9d <+125>:	mov    %rax,0x30(%r14)
   0x0000000000032ba1 <+129>:	mov    0x40(%rsp),%rax
   0x0000000000032ba6 <+134>:	mov    %rax,0x38(%r14)
   0x0000000000032baa <+138>:	mov    0x48(%rsp),%rax
   0x0000000000032baf <+143>:	mov    %rax,0x40(%r14)
   0x0000000000032bb3 <+147>:	mov    0x50(%rsp),%rax
   0x0000000000032bb8 <+152>:	mov    %rax,0x48(%r14)
   0x0000000000032bbc <+156>:	mov    0x58(%rsp),%rax
   0x0000000000032bc1 <+161>:	mov    %rax,0x50(%r14)
   0x0000000000032bc5 <+165>:	mov    0x60(%rsp),%rax
   0x0000000000032bca <+170>:	mov    %rax,0x58(%r14)
   0x0000000000032bce <+174>:	mov    0x68(%rsp),%rax
   0x0000000000032bd3 <+179>:	mov    %rax,0x60(%r14)
   0x0000000000032bd7 <+183>:	mov    %r14,%rsi
   0x0000000000032bda <+186>:	mov    $0x1d,%edi
   0x0000000000032bdf <+191>:	call   0x32be4 <tdh_mem_page_remove+196>
   0x0000000000032be4 <+196>:	cmp    %rbp,%rax
   0x0000000000032be7 <+199>:	jne    0x32bfd <tdh_mem_page_remove+221>
   0x0000000000032be9 <+201>:	sub    $0x1,%ebx
   0x0000000000032bec <+204>:	jne    0x32bd7 <tdh_mem_page_remove+183>
   0x0000000000032bee <+206>:	add    $0x70,%rsp
   0x0000000000032bf2 <+210>:	pop    %rbx
   0x0000000000032bf3 <+211>:	pop    %rbp
   0x0000000000032bf4 <+212>:	pop    %r12
   0x0000000000032bf6 <+214>:	pop    %r13
   0x0000000000032bf8 <+216>:	pop    %r14
   0x0000000000032bfa <+218>:	pop    %r15
   0x0000000000032bfc <+220>:	ret
   0x0000000000032bfd <+221>:	cmp    %r15,%rax
   0x0000000000032c00 <+224>:	je     0x32c2a <tdh_mem_page_remove+266>
   0x0000000000032c02 <+226>:	movabs $0x8000020000000092,%rdx
   0x0000000000032c0c <+236>:	cmp    %rdx,%rax
   0x0000000000032c0f <+239>:	jne    0x32bee <tdh_mem_page_remove+206>
   0x0000000000032c11 <+241>:	sub    $0x1,%r12d
   0x0000000000032c15 <+245>:	jne    0x32b64 <tdh_mem_page_remove+68>
   0x0000000000032c1b <+251>:	add    $0x70,%rsp
   0x0000000000032c1f <+255>:	pop    %rbx
   0x0000000000032c20 <+256>:	pop    %rbp
   0x0000000000032c21 <+257>:	pop    %r12
   0x0000000000032c23 <+259>:	pop    %r13
   0x0000000000032c25 <+261>:	pop    %r14
   0x0000000000032c27 <+263>:	pop    %r15
   0x0000000000032c29 <+265>:	ret
   0x0000000000032c2a <+266>:	call   0x32c2f <tdh_mem_page_remove+271>
   0x0000000000032c2f <+271>:	xor    %eax,%eax
   0x0000000000032c31 <+273>:	add    $0x70,%rsp
   0x0000000000032c35 <+277>:	pop    %rbx
   0x0000000000032c36 <+278>:	pop    %rbp
   0x0000000000032c37 <+279>:	pop    %r12
   0x0000000000032c39 <+281>:	pop    %r13
   0x0000000000032c3b <+283>:	pop    %r14
   0x0000000000032c3d <+285>:	pop    %r15

0x0000000000032c3f <+287>: ret
End of assembler dump.

#471 lore raw

Re: [PATCH v19 078/130] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to [email protected]

Review

Quoted 7 lines · On Mon, Feb 26, 2024, [email protected] wrote:
(quoted diff) +7 -0
+static noinstr void tdx_vcpu_enter_exit(struct vcpu_tdx *tdx)
+{
+	struct tdx_module_args args;
+
+	/*
+	 * Avoid section mismatch with to_tdx() with KVM_VM_BUG().  The caller
+	 * should call to_tdx().

C'mon. I don't think it's unreasonable to expect that at least one of the many people working on TDX would figure out why to_vmx() is __always_inline.

Quoted 4 lines
(quoted diff) +4 -0
+	 */
+	struct kvm_vcpu *vcpu = &tdx->vcpu;
+
+	guest_state_enter_irqoff();

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+	/*
+	 * TODO: optimization:
+	 * - Eliminate copy between args and vcpu->arch.regs.
+	 * - copyin/copyout registers only if (tdx->tdvmvall.regs_mask != 0)
+	 *   which means TDG.VP.VMCALL.
+	 */
+	args = (struct tdx_module_args) {
+		.rcx = tdx->tdvpr_pa,
+#define REG(reg, REG)	.reg = vcpu->arch.regs[VCPU_REGS_ ## REG]

Organizing tdx_module_args's registers by volatile vs. non-volatile is asinine. This code should not need to exist.

Quoted 35 lines
(quoted diff) +27 -0
+	WARN_ON_ONCE(!kvm_rebooting &&
+		     (tdx->exit_reason.full & TDX_SW_ERROR) == TDX_SW_ERROR);
+
+	guest_state_exit_irqoff();
+}
+
+fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+	if (unlikely(!tdx->initialized))
+		return -EINVAL;
+	if (unlikely(vcpu->kvm->vm_bugged)) {
+		tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
+		return EXIT_FASTPATH_NONE;
+	}
+
+	trace_kvm_entry(vcpu);
+
+	tdx_vcpu_enter_exit(tdx);
+
+	vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
+	trace_kvm_exit(vcpu, KVM_ISA_VMX);
+
+	return EXIT_FASTPATH_NONE;
+}
+
 void tdx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int pgd_level)
 {
 	WARN_ON_ONCE(root_hpa & ~PAGE_MASK);
arch/x86/kvm/vmx/tdx.h +0 -0
index d822e790e3e5..81d301fbe638 100644

arch/x86/kvm/vmx/tdx.h struct kvm_tdx { · line 32

Quoted 6 lines
arch/x86/kvm/vmx/tdx.h +3 -0
@@ -27,6 +27,37 @@ struct kvm_tdx {
 	struct page *source_page;
 };
 
+union tdx_exit_reason {
+	struct {
+		/* 31:0 mirror the VMX Exit Reason format */

Then use "union vmx_exit_reason", having to maintain duplicate copies of the same union is not something I want to do.

I'm honestly not even convinced that "union tdx_exit_reason" needs to exist. I added vmx_exit_reason because we kept having bugs where KVM would fail to strip bits 31:16, and because nested VMX needs to stuff failed_vmentry, but I don't see a similar need for TDX.

I would even go so far as to say the vcpu_tdx field shouldn't be exit_reason, and instead should be "return_code" or something. E.g. if the TDX module refuses to run the vCPU, there's no VM-Enter and thus no VM-Exit (unless you count the SEAMCALL itself, har har). Ditto for #GP or #UD on the SEAMCALL (or any other reason that generates TDX_SW_ERROR).

Ugh, I'm doubling down on that suggesting. This:

	WARN_ON_ONCE(!kvm_rebooting &&
		     (tdx->vp_enter_ret & TDX_SW_ERROR) == TDX_SW_ERROR);

	if ((u16)tdx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI &&
	    is_nmi(tdexit_intr_info(vcpu))) {
		kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
		vmx_do_nmi_irqoff();
		kvm_after_interrupt(vcpu);
	}

is heinous. If there's an error that leaves bits 15:0 zero, KVM will synthesize a spurious NMI. I don't know whether or not that can happen, but it's not something that should even be possible in KVM, i.e. the exit reason should be processed if and only if KVM *knows* there was a sane VM-Exit from non-root mode.

tdx_vcpu_run() has a similar issue, though it's probably benign. If there's an error in bits 15:0 that happens to collide with EXIT_REASON_TDCALL, weird things will happen.

	if (tdx->exit_reason.basic == EXIT_REASON_TDCALL)
		tdx->tdvmcall.rcx = vcpu->arch.regs[VCPU_REGS_RCX];
	else
		tdx->tdvmcall.rcx = 0;

I vote for something like the below, with much more robust checking of vp_enter_ret before it's converted to a VMX exit reason.

static __always_inline union vmx_exit_reason tdexit_exit_reason(struct kvm_vcpu *vcpu)

{
	return (u32)vcpu->vp_enter_ret;
}
arch/x86/kvm/vmx/tdx.h +2 -32
index af3a2b8afee8..b9b40b2eaccb 100644
@@ -43,37 +43,6 @@ struct kvm_tdx {
        struct page *source_page;
 };
 
-union tdx_exit_reason {
-       struct {
-               /* 31:0 mirror the VMX Exit Reason format */
-               u64 basic               : 16;
-               u64 reserved16          : 1;
-               u64 reserved17          : 1;
-               u64 reserved18          : 1;
-               u64 reserved19          : 1;
-               u64 reserved20          : 1;
-               u64 reserved21          : 1;
-               u64 reserved22          : 1;
-               u64 reserved23          : 1;
-               u64 reserved24          : 1;
-               u64 reserved25          : 1;
-               u64 bus_lock_detected   : 1;
-               u64 enclave_mode        : 1;
-               u64 smi_pending_mtf     : 1;
-               u64 smi_from_vmx_root   : 1;
-               u64 reserved30          : 1;
-               u64 failed_vmentry      : 1;
-
-               /* 63:32 are TDX specific */
-               u64 details_l1          : 8;
-               u64 class               : 8;
-               u64 reserved61_48       : 14;
-               u64 non_recoverable     : 1;
-               u64 error               : 1;
-       };
-       u64 full;
-};
-
 struct vcpu_tdx {
        struct kvm_vcpu vcpu;
 
@@ -103,7 +72,8 @@ struct vcpu_tdx {
                };
                u64 rcx;
        } tdvmcall;
-       union tdx_exit_reason exit_reason;
+
+       u64 vp_enter_ret;
 
        bool initialized;
 
#182 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]
Quoted 12 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx_ops.h new file +12 -0
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);
+
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+		/*
+		 * SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off.
+		 * This can happen when the host gets rebooted or live
+		 * updated. In this case, the instruction execution is ignored
+		 * as KVM is shut down, so the error code is suppressed. Other
+		 * than this, the error is unexpected and the execution can't
+		 * continue as the TDX features reply on VMX to be on.
+		 */
+		kvm_spurious_fault();
+		return 0;

This is nonsensical. The reason KVM liberally uses BUG_ON(!kvm_rebooting) is because it *greatly* simpifies the overall code by obviating the need for KVM to check for errors that should never happen in practice. On, and

But KVM quite obviously needs to check the return code for all SEAMCALLs, and the SEAMCALLs are (a) wrapped in functions and (b) preserve host state, i.e. we don't need to worry about KVM consuming garbage or running with unknown hardware state because something like INVVPID or INVEPT faulted.

Oh, and the other critical aspect of all of this is that unlike VMREAD, VMWRITE, etc., SEAMCALLs almost always require a TDR or TDVPR, i.e. need a VM or vCPU. Now that we've abandoned the macro shenanigans that allowed things like tdh_mem_page_add() to be pure translators to their respective SEAMCALL, I don't see any reason to take the physical addresses of the TDR/TDVPR in the helpers.

I.e. if we do:

u64 tdh_mng_addcx(struct kvm *kvm, hpa_t addr)

then the intermediate wrapper to the SEAMCALL assembly has the vCPU or VM and thus can precisely terminate the one problematic VM.

So unless I'm missing something, I think that kvm_spurious_fault() should be persona non grata for TDX, and that KVM should instead use KVM_BUG_ON().

#562 lore raw

Re: [PATCH v19 098/130] KVM: TDX: Add a place holder to handle TDX VM exit

In reply to [email protected]
Quoted 12 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +12 -0
+int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
+{
+	union tdx_exit_reason exit_reason = to_tdx(vcpu)->exit_reason;
+
+	/* See the comment of tdh_sept_seamcall(). */
+	if (unlikely(exit_reason.full == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_SEPT)))
+		return 1;
+
+	/*
+	 * TDH.VP.ENTRY checks TD EPOCH which contend with TDH.MEM.TRACK and
+	 * vcpu TDH.VP.ENTER.
+	 */

arch/x86/kvm/vmx/tdx.c void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode, · line 1309

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	if (unlikely(exit_reason.full == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_TD_EPOCH)))
+		return 1;
+
+	if (unlikely(exit_reason.full == TDX_SEAMCALL_UD)) {
+		kvm_spurious_fault();
+		/*
+		 * In the case of reboot or kexec, loop with TDH.VP.ENTER and
+		 * TDX_SEAMCALL_UD to avoid unnecessarily activity.
+		 */
+		return 1;

No. This is unnecessarily risky. KVM_BUG_ON() and exit to userspace. The response to "SEAMCALL faulted" should never be, "well, let's try again!".

Also, what about #GP on SEAMCALL? In general, the error handling here seems lacking.

#23 lore raw

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Sean Christopherson
Quoted 2 lines · Sean Christopherson

So my feedback is to not worry about the exports, and instead focus on figuring out a way to make the generated code less bloated and easier to read/debug.

Oh, and please make it a collaborative, public effort. I don't want to hear crickets and then see v20 dropped with a completely new SEAMCALL scheme.

#26 lore raw

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Sean Christopherson
Quoted 11 lines · Sean Christopherson

Heh, Like this one?

        static inline u64 tdh_sys_lp_shutdown(void)
        {
                struct tdx_module_args in = {
                };

                return tdx_seamcall(TDH_SYS_LP_SHUTDOWN, &in, NULL); }

Which isn't actually used...

Looks like is was turned into a NOP in TDX 1.5. So will even forever be dead code. I see one other that is unused. Thanks for pointing it out.

Quoted 14 lines
Quoted 9 lines

But I'd also defer to the KVM maintainers on this.  They're the ones
that have to play the symbol exporting game a lot more than I ever do.
If they cringe at the idea of adding 20 (or whatever) exports, then that's a lot more important than the possibility of some other silly
module abusing the generic exported __seamcall.

I don't care much about exports.  What I do care about is sane code, and while
the current code _looks_ pretty, it's actually quite insane.

Quoted 5 lines

I get why y'all put SEAMCALL in assembly subroutines; the macro shenanigans I
originally wrote years ago were their own brand of crazy, and dealing with GPRs
that can't be asm() constraints often results in brittle code.

I guess it must be this, for the initiated:
https://lore.kernel.org/lkml/25f0d2c2f73c20309a1b578cc5fc15f4fd6b9a13.1605232743.git.isaku.yamahata@intel.com/

Quoted 10 lines

But the tdx_module_args structure approach generates truly atrocious code.  Yes,
SEAMCALL is inherently slow, but that doesn't mean that we shouldn't at least try
to generate efficient code.  And it's not just efficiency that is lost, the
generated code ends up being much harder to read than it ought to be.

[snip]

Quoted 6 lines

So my feedback is to not worry about the exports, and instead focus on figuring
out a way to make the generated code less bloated and easier to read/debug.

Thanks for the feedback both! It sounds like everyone is flexible on the exports. As for the generated code, oof.

Kai, I see the solution has gone through some iterations already. First the macro one linked above, then that was dropped pretty quick to something that loses the asm constraints:
https://lore.kernel.org/lkml/e777bbbe10b1ec2c37d85dcca2e175fe3bc565ec.1625186503.git.isaku.yamahata@intel.com/

Then next the struct grew here, and here:
https://lore.kernel.org/linux-mm/[email protected]/
https://lore.kernel.org/linux-mm/[email protected]/

Not sure I understand all of the constraints yet. Do you have any ideas?

#24 lore raw

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Sean Christopherson
Quoted 10 lines · Sean Christopherson
Quoted 4 lines · Sean Christopherson

So my feedback is to not worry about the exports, and instead focus on figuring
out a way to make the generated code less bloated and easier to read/debug.

Oh, and please make it a collaborative, public effort.  I don't want to hear
crickets and then see v20 dropped with a completely new SEAMCALL scheme.

And here we we're worrying that people might eventually grow tired of us adding mails to v19 and we debate every detail in public. Will do.

#28 lore raw

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Sean Christopherson
Quoted 11 lines · Sean Christopherson
        static inline u64 tdh_mem_page_remove(hpa_t tdr, gpa_t gpa, int level,
        				      struct tdx_module_args *out)
        {
        	struct tdx_module_args in = {
        		.rcx = gpa | level,
        		.rdx = tdr,
        	};

        	return tdx_seamcall_sept(TDH_MEM_PAGE_REMOVE, &in, out);
        }
Quoted 3 lines

generates the below monstrosity with gcc-13. And that's just one SEAMCALL wrapper, *every* single one generates the same mess. clang-16 is kinda sorta a little better, as it at least inlines the helpers that have single callers.

Yeah, that's really awful.

Is all the inlining making the compiler too ambitious? Why is this all inlined in the first place?

tdh_mem_page_remove() _should_ just be logically:

* initialize tdx_module_args. Move a few things into place on the stack and zero the rest.
* Put a pointer to tdx_module_args in a register
* Put TDH_MEM_PAGE_REMOVE immediate in a register
* Some register preservation, maybe
* call
* maybe some cleanup
* return

Those logical things are *NOT* easy to spot in the disassembly.

#25 lore raw

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Edgecombe, Rick P
Quoted 6 lines · Rick P Edgecombe
Quoted 5 lines · Sean Christopherson
Quoted 3 lines · Sean Christopherson

So my feedback is to not worry about the exports, and instead focus on figuring out a way to make the generated code less bloated and easier to read/debug.

Quoted 6 lines
Quoted 3 lines

Oh, and please make it a collaborative, public effort.  I don't want to hear crickets and then see v20 dropped with a completely new SEAMCALL scheme.

And here we we're worrying that people might eventually grow tired of us adding mails to v19 and we debate every detail in public. Will do.

As a general rule, I _strongly_ prefer all review to be done on-list, in public. Copy+pasting myself from another Intel series[*]

: Correct, what I object to is Intel _requiring_ a Reviewed-by before posting. :
: And while I'm certainly not going to refuse patches that have been reviewed : internally, I _strongly_ prefer reviews be on-list so that they are public and : recorded. Being able to go back and look at the history and evolution of patches : is valuable, and the discussion itself is often beneficial to non-participants, : e.g. people that are new-ish to KVM and/or aren't familiar with the feature being : enabled can often learn new things and avoid similar pitfalls of their own.

There are definitely situations where exceptions are warranted, e.g. if someone is a first-time poster and/or wants a sanity check to make sure their idea isn't completely crazy. But even then, the internal review should only be very cursory.

In addition to the history being valuable, doing reviews in public minimizes the probability of a developer being led astray, e.g. due to someone internally saying do XYZ, and then upstream reviewers telling them to do something entirely different.

As far as noise goes, look at it this way. Every time a new TDX series is posted, I get 130+ emails. Y'all can do a _lot_ of public review and discussion before you'll get anywhere near the point where it'd be noiser than spinning a new version of the series.

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

#183 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to Sean Christopherson
Quoted 41 lines · Sean Christopherson
Quoted 12 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx_ops.h new file +12 -0
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);
+
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+		/*
+		 * SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off.
+		 * This can happen when the host gets rebooted or live
+		 * updated. In this case, the instruction execution is ignored
+		 * as KVM is shut down, so the error code is suppressed. Other
+		 * than this, the error is unexpected and the execution can't
+		 * continue as the TDX features reply on VMX to be on.
+		 */
+		kvm_spurious_fault();
+		return 0;

This is nonsensical. The reason KVM liberally uses BUG_ON(!kvm_rebooting) is because it *greatly* simpifies the overall code by obviating the need for KVM to check for errors that should never happen in practice. On, and

But KVM quite obviously needs to check the return code for all SEAMCALLs, and the SEAMCALLs are (a) wrapped in functions and (b) preserve host state, i.e. we don't need to worry about KVM consuming garbage or running with unknown hardware state because something like INVVPID or INVEPT faulted.

Oh, and the other critical aspect of all of this is that unlike VMREAD, VMWRITE, etc., SEAMCALLs almost always require a TDR or TDVPR, i.e. need a VM or vCPU. Now that we've abandoned the macro shenanigans that allowed things like tdh_mem_page_add() to be pure translators to their respective SEAMCALL, I don't see any reason to take the physical addresses of the TDR/TDVPR in the helpers.

I.e. if we do:

Quoted 7 lines

u64 tdh_mng_addcx(struct kvm *kvm, hpa_t addr)

then the intermediate wrapper to the SEAMCALL assembly has the vCPU or VM and thus can precisely terminate the one problematic VM.

So unless I'm missing something, I think that kvm_spurious_fault() should be persona non grata for TDX, and that KVM should instead use KVM_BUG_ON().

Thank you for the feedback. As I don't see any issues to do so, I'll convert those wrappers to take struct kvm_tdx or struct vcpu_tdx, and eliminate kvm_spurious_fault() in favor of KVM_BUG_ON().

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

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Dave Hansen
Quoted 12 lines · Dave Hansen
Quoted 11 lines · Sean Christopherson
        static inline u64 tdh_mem_page_remove(hpa_t tdr, gpa_t gpa, int level,
        				      struct tdx_module_args *out)
        {
        	struct tdx_module_args in = {
        		.rcx = gpa | level,
        		.rdx = tdr,
        	};

        	return tdx_seamcall_sept(TDH_MEM_PAGE_REMOVE, &in, out);
        }
Quoted 7 lines
Quoted 3 lines

generates the below monstrosity with gcc-13. And that's just one SEAMCALL wrapper, *every* single one generates the same mess. clang-16 is kinda sorta a little better, as it at least inlines the helpers that have single callers.

Yeah, that's really awful.

Is all the inlining making the compiler too ambitious?

No, whether or not the wrappers are inlined doesn't change anything. gcc actually doesn't inline any of these helpers. More below.

Quoted 1 line

Why is this all inlined in the first place?

Likely because no one looked at the generated code. The C code is super simple and looks like it should be inlined.

And the very original code was macro heavy, i.e. relied on inlining to allow the compiler to precisely set only the actual registers needed for the SEAMCALL.

Quoted 4 lines

tdh_mem_page_remove() _should_ just be logically:

* initialize tdx_module_args. Move a few things into place on the stack and zero the rest.

The "zero the rest" is what generates the fugly code. The underlying problem is that the SEAMCALL assembly functions unpack _all_ registers from tdx_module_args. As a result, tdx_module_args needs to be zeroed to avoid loading registers with unitialized stack data.

E.g. before I looked at the assembly code, my initial thought to clean things up by doing:

	struct tdx_module_args in;

	in.rcx = gpa | level;
	in.rdx = tdr;

but that would make one or more sanitizers (and maybe even the compiler itself) more than a bit unhappy.

The struct is 72 bytes, which adds up to a lot of wasted effort since the majority of SEAMCALLs only use a few of the 13 registers.

FWIW, the guest side of TDX is equally gross. E.g. to do kvm_hypercall1(), which without TDX is simply

0xffffffff810eb4a2 <+82>: 48 c7 c0 8c 9a 01 00 mov $0x19a8c,%rax

   0xffffffff810eb4a9 <+89>:	8b 1c 02           	mov    (%rdx,%rax,1),%ebx
   0xffffffff810eb4ac <+92>:	b8 0b 00 00 00     	mov    $0xb,%eax
   0xffffffff810eb4b1 <+97>:	0f 01 c1           	vmcall
   0xffffffff810eb4b4 <+100>:	5b                 	pop    %rbx
   0xffffffff810eb4b5 <+101>:	5d                 	pop    %rbp

the kernel blasts the unused params

0xffffffff810ffdc1 <+97>: bf 0b 00 00 00 mov $0xb,%edi

   0xffffffff810ffdc6 <+102>:	31 d2              	xor    %edx,%edx
   0xffffffff810ffdc8 <+104>:	31 c9              	xor    %ecx,%ecx
   0xffffffff810ffdca <+106>:	45 31 c0           	xor    %r8d,%r8d
   0xffffffff810ffdcd <+109>:	5b                 	pop    %rbx
   0xffffffff810ffdce <+110>:	41 5e              	pop    %r14
   0xffffffff810ffdd0 <+112>:	e9 bb 1b f0 ff     	jmp    0xffffffff81001990 <tdx_kvm_hypercall>

then loads and zeros a ton of memory (tdx_kvm_hypercall()):

   0xffffffff81001990 <+0>:	nopl   0x0(%rax,%rax,1)
   0xffffffff81001995 <+5>:	sub    $0x70,%rsp
   0xffffffff81001999 <+9>:	mov    %gs:0x28,%rax
   0xffffffff810019a2 <+18>:	mov    %rax,0x68(%rsp)
   0xffffffff810019a7 <+23>:	mov    %edi,%eax
   0xffffffff810019a9 <+25>:	movq   $0x0,0x18(%rsp)
   0xffffffff810019b2 <+34>:	movq   $0x0,0x10(%rsp)
   0xffffffff810019bb <+43>:	movq   $0x0,0x8(%rsp)
   0xffffffff810019c4 <+52>:	movq   $0x0,(%rsp)
   0xffffffff810019cc <+60>:	mov    %rax,0x20(%rsp)
   0xffffffff810019d1 <+65>:	mov    %rsi,0x28(%rsp)
   0xffffffff810019d6 <+70>:	mov    %rdx,0x30(%rsp)
   0xffffffff810019db <+75>:	mov    %rcx,0x38(%rsp)
   0xffffffff810019e0 <+80>:	mov    %r8,0x40(%rsp)
   0xffffffff810019e5 <+85>:	movq   $0x0,0x48(%rsp)
   0xffffffff810019ee <+94>:	movq   $0x0,0x50(%rsp)
   0xffffffff810019f7 <+103>:	movq   $0x0,0x58(%rsp)
   0xffffffff81001a00 <+112>:	movq   $0x0,0x60(%rsp)
   0xffffffff81001a09 <+121>:	mov    %rsp,%rdi
   0xffffffff81001a0c <+124>:	call   0xffffffff819f0a80 <__tdx_hypercall>
   0xffffffff81001a11 <+129>:	mov    %gs:0x28,%rcx
   0xffffffff81001a1a <+138>:	cmp    0x68(%rsp),%rcx
   0xffffffff81001a1f <+143>:	jne    0xffffffff81001a26 <tdx_kvm_hypercall+150>
   0xffffffff81001a21 <+145>:	add    $0x70,%rsp

0xffffffff81001a25 <+149>: ret

and then unpacks all of that memory back into registers, and reverses that last part on the way back, (__tdcall_saved_ret()):

   0xffffffff819f0b10 <+0>:	mov    %rdi,%rax
   0xffffffff819f0b13 <+3>:	mov    (%rsi),%rcx
   0xffffffff819f0b16 <+6>:	mov    0x8(%rsi),%rdx
   0xffffffff819f0b1a <+10>:	mov    0x10(%rsi),%r8
   0xffffffff819f0b1e <+14>:	mov    0x18(%rsi),%r9
   0xffffffff819f0b22 <+18>:	mov    0x20(%rsi),%r10
   0xffffffff819f0b26 <+22>:	mov    0x28(%rsi),%r11
   0xffffffff819f0b2a <+26>:	push   %rbx
   0xffffffff819f0b2b <+27>:	push   %r12
   0xffffffff819f0b2d <+29>:	push   %r13
   0xffffffff819f0b2f <+31>:	push   %r14
   0xffffffff819f0b31 <+33>:	push   %r15
   0xffffffff819f0b33 <+35>:	mov    0x30(%rsi),%r12
   0xffffffff819f0b37 <+39>:	mov    0x38(%rsi),%r13
   0xffffffff819f0b3b <+43>:	mov    0x40(%rsi),%r14
   0xffffffff819f0b3f <+47>:	mov    0x48(%rsi),%r15
   0xffffffff819f0b43 <+51>:	mov    0x50(%rsi),%rbx
   0xffffffff819f0b47 <+55>:	push   %rsi
   0xffffffff819f0b48 <+56>:	mov    0x58(%rsi),%rdi
   0xffffffff819f0b4c <+60>:	mov    0x60(%rsi),%rsi
   0xffffffff819f0b50 <+64>:	tdcall
   0xffffffff819f0b54 <+68>:	push   %rax
   0xffffffff819f0b55 <+69>:	mov    0x8(%rsp),%rax
   0xffffffff819f0b5a <+74>:	mov    %rsi,0x60(%rax)
   0xffffffff819f0b5e <+78>:	pop    %rax
   0xffffffff819f0b5f <+79>:	pop    %rsi
   0xffffffff819f0b60 <+80>:	mov    %r12,0x30(%rsi)
   0xffffffff819f0b64 <+84>:	mov    %r13,0x38(%rsi)
   0xffffffff819f0b68 <+88>:	mov    %r14,0x40(%rsi)
   0xffffffff819f0b6c <+92>:	mov    %r15,0x48(%rsi)
   0xffffffff819f0b70 <+96>:	mov    %rbx,0x50(%rsi)
   0xffffffff819f0b74 <+100>:	mov    %rdi,0x58(%rsi)
   0xffffffff819f0b78 <+104>:	mov    %rcx,(%rsi)
   0xffffffff819f0b7b <+107>:	mov    %rdx,0x8(%rsi)
   0xffffffff819f0b7f <+111>:	mov    %r8,0x10(%rsi)
   0xffffffff819f0b83 <+115>:	mov    %r9,0x18(%rsi)
   0xffffffff819f0b87 <+119>:	mov    %r10,0x20(%rsi)
   0xffffffff819f0b8b <+123>:	mov    %r11,0x28(%rsi)
   0xffffffff819f0b8f <+127>:	xor    %ecx,%ecx
   0xffffffff819f0b91 <+129>:	xor    %edx,%edx
   0xffffffff819f0b93 <+131>:	xor    %r8d,%r8d
   0xffffffff819f0b96 <+134>:	xor    %r9d,%r9d
   0xffffffff819f0b99 <+137>:	xor    %r10d,%r10d
   0xffffffff819f0b9c <+140>:	xor    %r11d,%r11d
   0xffffffff819f0b9f <+143>:	xor    %r12d,%r12d
   0xffffffff819f0ba2 <+146>:	xor    %r13d,%r13d
   0xffffffff819f0ba5 <+149>:	xor    %r14d,%r14d
   0xffffffff819f0ba8 <+152>:	xor    %r15d,%r15d
   0xffffffff819f0bab <+155>:	xor    %ebx,%ebx
   0xffffffff819f0bad <+157>:	xor    %edi,%edi
   0xffffffff819f0baf <+159>:	pop    %r15
   0xffffffff819f0bb1 <+161>:	pop    %r14
   0xffffffff819f0bb3 <+163>:	pop    %r13
   0xffffffff819f0bb5 <+165>:	pop    %r12
   0xffffffff819f0bb7 <+167>:	pop    %rbx

0xffffffff819f0bb8 <+168>: ret

It's honestly quite amusing, because y'all took one what I see as one of the big advantages of TDX over SEV (using registers instead of shared memory), and managed to effectively turn it into a disadvantage.

Again, I completely understand the maintenance and robustness benefits, but IMO the pendulum swung a bit too far in that direction.

#472 lore raw

Re: [PATCH v19 078/130] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to Sean Christopherson
Quoted 52 lines · Sean Christopherson

arch/x86/kvm/vmx/tdx.h struct kvm_tdx { · line 32

Quoted 11 lines
arch/x86/kvm/vmx/tdx.h +3 -0
index d822e790e3e5..81d301fbe638 100644
@@ -27,6 +27,37 @@ struct kvm_tdx {
 	struct page *source_page;
 };
 
+union tdx_exit_reason {
+	struct {
+		/* 31:0 mirror the VMX Exit Reason format */

Then use "union vmx_exit_reason", having to maintain duplicate copies of the same union is not something I want to do.

I'm honestly not even convinced that "union tdx_exit_reason" needs to exist. I added vmx_exit_reason because we kept having bugs where KVM would fail to strip bits 31:16, and because nested VMX needs to stuff failed_vmentry, but I don't see a similar need for TDX.

I would even go so far as to say the vcpu_tdx field shouldn't be exit_reason, and instead should be "return_code" or something. E.g. if the TDX module refuses to run the vCPU, there's no VM-Enter and thus no VM-Exit (unless you count the SEAMCALL itself, har har). Ditto for #GP or #UD on the SEAMCALL (or any other reason that generates TDX_SW_ERROR).

Ugh, I'm doubling down on that suggesting. This:

	WARN_ON_ONCE(!kvm_rebooting &&
		     (tdx->vp_enter_ret & TDX_SW_ERROR) == TDX_SW_ERROR);

	if ((u16)tdx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI &&
	    is_nmi(tdexit_intr_info(vcpu))) {
		kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
		vmx_do_nmi_irqoff();
		kvm_after_interrupt(vcpu);
	}

is heinous. If there's an error that leaves bits 15:0 zero, KVM will synthesize a spurious NMI. I don't know whether or not that can happen, but it's not something that should even be possible in KVM, i.e. the exit reason should be processed if and only if KVM *knows* there was a sane VM-Exit from non-root mode.

tdx_vcpu_run() has a similar issue, though it's probably benign. If there's an error in bits 15:0 that happens to collide with EXIT_REASON_TDCALL, weird things will happen.

	if (tdx->exit_reason.basic == EXIT_REASON_TDCALL)
		tdx->tdvmcall.rcx = vcpu->arch.regs[VCPU_REGS_RCX];
	else
		tdx->tdvmcall.rcx = 0;
Quoted 7 lines

I vote for something like the below, with much more robust checking of vp_enter_ret before it's converted to a VMX exit reason.

static __always_inline union vmx_exit_reason tdexit_exit_reason(struct kvm_vcpu *vcpu)

{
	return (u32)vcpu->vp_enter_ret;
}

Thank you for the concrete suggestion. Let me explore what safe guard check can be done to make exit path robust.

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

Re: [PATCH v19 025/130] KVM: TDX: Make TDX VM type supported

In reply to Binbin Wu
Quoted 5 lines · Binbin Wu
Quoted 2 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Quoted 7 lines
Quoted 5 lines

NOTE: This patch is in position of the patch series for developers to be able to test codes during the middle of the patch series although this patch series doesn't provide functional features until the all the patches of this patch series. When merging this patch series, this patch can be moved to the end.

Maybe at this point of time, you can consider to move this patch to the end?

Given I don't have to do step-by-step debug recently, I think it's safe to move it.

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

Re: [PATCH v19 023/130] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Binbin Wu
Quoted 38 lines · Binbin Wu
Quoted 37 lines · Isaku Yamahata
Quoted 23 lines · Binbin Wu
Quoted 23 lines
arch/x86/kvm/vmx/main.c +16 -0
index 18cecf12c7c8..18aef6e23aab 100644
@@ -6,6 +6,22 @@
   #include "nested.h"
   #include "pmu.h"
+static bool enable_tdx __ro_after_init;
+module_param_named(tdx, enable_tdx, bool, 0444);
+
+static __init int vt_hardware_setup(void)
+{
+	int ret;
+
+	ret = vmx_hardware_setup();
+	if (ret)
+		return ret;
+
+	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+
+	return 0;
+}
+
Quoted 8 lines

arch/x86/kvm/vmx/main.c struct kvm_x86_ops vt_x86_ops __initdata = { · line 39

Quoted 6 lines
arch/x86/kvm/vmx/main.c +1 -0
   #define VMX_REQUIRED_APICV_INHIBITS				\
   	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
   	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\
@@ -22,6 +38,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
   	.hardware_unsetup = vmx_hardware_unsetup,
+	/* TDX cpu enablement is done by tdx_hardware_setup(). */

How about if there are some LPs that are offline.
In tdx_hardware_setup(), only online LPs are initialed for TDX, right?

Correct.

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Then when an offline LP becoming online, it doesn't have a chance to call tdx_cpu_enable()?

KVM registers kvm_online/offline_cpu() @ kvm_main.c as cpu hotplug callbacks. Eventually x86 kvm hardware_enable() is called on online/offline event.

Yes, hardware_enable() will be called when online, but  hardware_enable() now is vmx_hardware_enable() right? It doens't call tdx_cpu_enable() during the online path.

TDX module requires TDH.SYS.LP.INIT() on all logical processors(LPs). If we successfully initialized TDX module, we don't need further action for TDX on cpu online/offline.

If some of LPs are not online when loading kvm_intel.ko, KVM fails to initialize TDX module. TDX support is disabled. We don't bother to attempt it. Leave it to the admin of the machine.

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

Re: [PATCH v19 007/130] x86/virt/tdx: Export SEAMCALL functions

In reply to Sean Christopherson
Quoted 8 lines · Sean Christopherson
Quoted 4 lines

tdh_mem_page_remove() _should_ just be logically:

* initialize tdx_module_args. Move a few things into place on the stack and zero the rest.

The "zero the rest" is what generates the fugly code. The underlying problem is that the SEAMCALL assembly functions unpack _all_ registers from tdx_module_args. As a result, tdx_module_args needs to be zeroed to avoid loading registers with unitialized stack data.

It's the "zero the rest" and also the copy:

Review

Quoted 5 lines
(quoted diff) +5 -0
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);

Things get a wee bit nicer if you do an out-of-line mempcy() instead of the structure copy. But the really fun part is that 'out' is NULL and the compiler *SHOULD* know it. I'm not actually sure what trips it up.

In any case, I think it ends up generating code for both sides of the if/else including the entirely superfluous copy.

The two nested while loops (one for TDX_RND_NO_ENTROPY and the other for TDX_ERROR_SEPT_BUSY) also don't make for great code generation.

So, sure, the generated code here could be a better. But there's a lot more going on here than just shuffling gunk in and out of the 'struct tdx_module_args', and there's a _lot_ more work to do for one of these than for a plain old kvm_hypercall*().

It might make sense to separate out the "out" functionality into and maybe to uninline _some_ of the helper levels. But after that, there's not a lot of low hanging fruit.

#668 lore raw

Re: [PATCH v19 120/130] KVM: TDX: Add a method to ignore dirty logging

In reply to Edgecombe, Rick P
Quoted 10 lines · Rick P
Quoted 9 lines · Isaku Yamahata
Quoted 8 lines

On the subject of warnings and KVM_BUG_ON(), my feeling so far is that
this series is quite aggressive about these. Is it due the complexity
of the series? I think maybe we can remove some of the simple ones, but
not sure if there was already some discussion on what level is appropriate.

Quoted 5 lines
Quoted 3 lines

KVM_BUG_ON() was helpful at the early stage.  Because we don't hit them
recently, it's okay to remove them.  Will remove them.

Hmm. We probably need to do it case by case.

I categorize as follows. Unless otherwise, I'll update this series.

- dirty log check
As we will drop this ptach, we'll have no call site.

- KVM_BUG_ON() in main.c
We should drop them because their logic isn't complex.

- KVM_BUG_ON() in tdx.c
- The error check of the return value from SEAMCALL
We should keep it as it's unexpected error from TDX module. When we hit this, we should mark the guest bugged and prevent further operation. It's hard to deduce the reason. TDX mdoule might be broken.

- Other check
We should drop them.

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

Re: [PATCH v19 120/130] KVM: TDX: Add a method to ignore dirty logging

Quoted 7 lines · Isaku Yamahata

I categorize as follows. Unless otherwise, I'll update this series.

- dirty log check
  As we will drop this ptach, we'll have no call site.

- KVM_BUG_ON() in main.c
  We should drop them because their logic isn't complex.

What about "KVM: TDX: Add methods to ignore guest instruction emulation"? Is it cleanly blocked somehow?

Quoted 8 lines


- KVM_BUG_ON() in tdx.c
  - The error check of the return value from SEAMCALL
    We should keep it as it's unexpected error from TDX module. When we hit
    this, we should mark the guest bugged and prevent further operation.  It's
    hard to deduce the reason.  TDX mdoule might be broken.

Yes. Makes sense.

Quoted 3 lines

  - Other check
    We should drop them.

Offhand, I'm not sure what is in this category.

#474 lore raw

Re: [PATCH v19 078/130] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to [email protected]

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

Quoted 11 lines · On Mon, 2024-02-26 at 00:26 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +11 -0
+fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
+{
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+       if (unlikely(!tdx->initialized))
+               return -EINVAL;
+       if (unlikely(vcpu->kvm->vm_bugged)) {
+               tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
+               return EXIT_FASTPATH_NONE;
+       }
+

Isaku, can you elaborate on why this needs special handling? There is a check in vcpu_enter_guest() like:

	if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
		r = -EIO;
		goto out;
	}

Instead it returns a SEAM error code for something actuated by KVM. But can it even be reached because of the other check? Not sure if there is a problem, just sticks out to me and wondering whats going on.

#670 lore raw

Re: [PATCH v19 120/130] KVM: TDX: Add a method to ignore dirty logging

In reply to Edgecombe, Rick P
Quoted 10 lines · Rick P
Quoted 7 lines · Isaku Yamahata

I categorize as follows. Unless otherwise, I'll update this series.

- dirty log check
  As we will drop this ptach, we'll have no call site.

- KVM_BUG_ON() in main.c
  We should drop them because their logic isn't complex.

What about "KVM: TDX: Add methods to ignore guest instruction emulation"? Is it cleanly blocked somehow?

KVM fault handler, kvm_mmu_page_fault(), is the caller into the emulation, It should skip the emulation.

As the second guard, x86_emulate_instruction(), calls check_emulate_instruction() callback to check if the emulation can/should be done. TDX callback can return it as X86EMUL_UNHANDLEABLE. Then, the flow goes to user space as error. I'll update the vt_check_emulate_instruction().

Quoted 7 lines
Quoted 7 lines

- KVM_BUG_ON() in tdx.c
  - The error check of the return value from SEAMCALL
    We should keep it as it's unexpected error from TDX module. When we hit
    this, we should mark the guest bugged and prevent further operation.  It's
    hard to deduce the reason.  TDX mdoule might be broken.

Quoted 7 lines

Yes. Makes sense.

Quoted 3 lines

  - Other check
    We should drop them.

Offhand, I'm not sure what is in this category.

- Checking error code on TD enter/exit
I'll revise how to check error from TD enter/exit. We'll have new code. I will update wrapper function to take struct kvm_tdx or struct tdx_vcpu, and revise to remove random check. Cleanups related to kvm_rebooting, TDX_SW_ERROR, kvm_spurious_fault()

- Remaining random check for debug.
The examples are as follows. They were added for debug.

@@ -797,18 +788,14 @@ void tdx_vcpu_free(struct kvm_vcpu *vcpu)

         * list_{del,add}() on associated_tdvcpus list later.
         */
        tdx_disassociate_vp_on_cpu(vcpu);

- WARN_ON_ONCE(vcpu->cpu != -1);

/*
* This methods can be called when vcpu allocation/initialization
* failed. So it's possible that hkid, tdvpx and tdvpr are not assigned
* yet.
*/
- if (is_hkid_assigned(to_kvm_tdx(vcpu->kvm))) {
- WARN_ON_ONCE(tdx->tdvpx_pa);
- WARN_ON_ONCE(tdx->tdvpr_pa);
+ if (is_hkid_assigned(to_kvm_tdx(vcpu->kvm)))

                return;

- }

        if (tdx->tdvpx_pa) {
                for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {

@@ -831,9 +818,9 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
{

        /* vcpu_deliver_init method silently discards INIT event. */
-       if (KVM_BUG_ON(init_event, vcpu->kvm))
+       if (init_event)
                return;
-       if (KVM_BUG_ON(is_td_vcpu_created(to_tdx(vcpu)), vcpu->kvm))
+       if (is_td_vcpu_created(to_tdx(vcpu)))
                return;
 
        /*

@@ -831,9 +818,9 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
{

        /* vcpu_deliver_init method silently discards INIT event. */
-       if (KVM_BUG_ON(init_event, vcpu->kvm))
+       if (init_event)
                return;
-       if (KVM_BUG_ON(is_td_vcpu_created(to_tdx(vcpu)), vcpu->kvm))
+       if (is_td_vcpu_created(to_tdx(vcpu)))
                return;
 
        /*

@@ -831,9 +818,9 @@ void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
{

        /* vcpu_deliver_init method silently discards INIT event. */
-       if (KVM_BUG_ON(init_event, vcpu->kvm))
+       if (init_event)
                return;
-       if (KVM_BUG_ON(is_td_vcpu_created(to_tdx(vcpu)), vcpu->kvm))
+       if (is_td_vcpu_created(to_tdx(vcpu)))
                return;
 
        /*
Signature · 1 line
Isaku Yamahata <[email protected]>
#475 lore raw

Re: [PATCH v19 078/130] KVM: TDX: Implement TDX vcpu enter/exit path

In reply to Edgecombe, Rick P
Quoted 15 lines · Rick P

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

Quoted 11 lines · On Mon, 2024-02-26 at 00:26 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +11 -0
+fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
+{
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+
+       if (unlikely(!tdx->initialized))
+               return -EINVAL;
+       if (unlikely(vcpu->kvm->vm_bugged)) {
+               tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
+               return EXIT_FASTPATH_NONE;
+       }
+

Isaku, can you elaborate on why this needs special handling? There is a check in vcpu_enter_guest() like:

Quoted 8 lines
	if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
		r = -EIO;
		goto out;
	}

Instead it returns a SEAM error code for something actuated by KVM. But can it even be reached because of the other check? Not sure if there is a problem, just sticks out to me and wondering whats going on.

The original intention is to get out the inner loop. As Sean pointed it out, the current code does poor job to check error of __seamcall_saved_ret(TDH_VP_ENTER). So it fails to call KVM_BUG_ON() when it returns unexcepted error.

The right fix is to properly check an error from TDH_VP_ENTER and call KVM_BUG_ON(). Then the check you pointed out should go away.

  for // out loop
     if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
         for // inner loop
           vcpu_run()
           kvm_vcpu_exit_request(vcpu).
Signature · 1 line
Isaku Yamahata <[email protected]>
#376 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to [email protected]
Quoted 11 lines · On Mon, 2024-02-26 at 00:26 -0800, [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.)

Quoted 11 lines

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.

Is the migration case relevant to TDX?

Quoted 17 lines

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.

I get the part about only zapping leafs and not the root and mid-level PTEs. But why the MTRR, lapic page and migration part? Why should those not be zapped? Why is migration a consideration when it is not supported?

Quoted 55 lines

---
 arch/x86/kvm/mmu/mmu.c     | 61
++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c | 37 +++++++++++++++++++---- arch/x86/kvm/mmu/tdp_mmu.h |  5 ++--

 3 files changed, 92 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index 0d6d4506ec97..30c86e858ae4 100644
@@ -6339,7 +6339,7 @@ static void kvm_mmu_zap_all_fast(struct kvm
 *kvm)
          * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock

and yield.
         */
        if (tdp_mmu_enabled)
-               kvm_tdp_mmu_invalidate_all_roots(kvm);
+               kvm_tdp_mmu_invalidate_all_roots(kvm, true);
        /*
         * Notify all vcpus to reload its shadow page table and flush TLB.

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6459,7 +6459,16 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t
 gfn_start, gfn_t gfn_end)
         flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);


        if (tdp_mmu_enabled)
-               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
+               /*
+                * zap_private = false. Zap only shared pages. +                *
+                * kvm_zap_gfn_range() is used when MTRR or PAT memory
+                * type was 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.
+                */
+               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush, false);

        if (flush)
                kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6905,10 +6914,56 @@ void kvm_arch_flush_shadow_all(struct kvm
 *kvm)
         kvm_mmu_zap_all(kvm);
  }
Quoted 3 lines


+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)

What about kvm_mmu_zap_memslot_leafs() instead?

Quoted 2 lines

+{
+       bool flush = false;

It doesn't need to be initialized if it passes false directly into kvm_tdp_mmu_unmap_gfn_range(). It would make the code easier to understand.

Quoted 17 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+
+       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 (tdp_mmu_enabled) {
+               struct kvm_gfn_range range = {
+                     .slot = slot,
+                     .start = slot->base_gfn,
+                     .end = slot->base_gfn + slot->npages, +                     .may_block = true,
+

Quoted 8 lines

+                     /*
+                      * This handles both private gfn and shared gfn.
+                      * All private page should be zapped on memslot deletion.
+                      */
+                     .only_private = true,
+                     .only_shared = true,

only_private and only_shared are both true? Shouldn't they both be false? (or just unset)

Quoted 7 lines

+               };
+
+               flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush);
+       } else {
+               /* TDX supports only TDP-MMU case. */ +               WARN_ON_ONCE(1);

How about a KVM_BUG_ON() instead? If somehow this is reached, we don't want the caller thinking the pages are zapped, then enter the guest with pages mapped that have gone elsewhere.

Quoted 1 line

+               flush = true;

Why flush?

Quoted 7 lines

+       }
+       if (flush)
+               kvm_flush_remote_tlbs(kvm);

arch/x86/kvm/mmu/mmu.c +4 -0
+
+       write_unlock(&kvm->mmu_lock);
+}
+
Quoted 5 lines

 void kvm_arch_flush_shadow_memslot(struct kvm *kvm, struct kvm_memory_slot *slot) {
-       kvm_mmu_zap_all_fast(kvm);
+       if (kvm_gfn_shared_mask(kvm))

There seems to be an attempt to abstract away the existence of Secure- EPT in mmu.c, that is not fully successful. In this case the code checks kvm_gfn_shared_mask() to see if it needs to handle the zapping in a way specific needed by S-EPT. It ends up being a little confusing because the actual check is about whether there is a shared bit. It only works because only S-EPT is the only thing that has a kvm_gfn_shared_mask().

Doing something like (kvm->arch.vm_type == KVM_X86_TDX_VM) looks wrong, but is more honest about what we are getting up to here. I'm not sure though, what do you think?

Quoted 43 lines

+               /*
+                * Secure-EPT requires to release PTs from the leaf. The
+                * optimization to zap root PT first with child PT doesn't
+                * work.
+                */
+               kvm_mmu_zap_memslot(kvm, slot);
+       else
+               kvm_mmu_zap_all_fast(kvm);
 }

 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index d47f0daf1b03..e7514a807134 100644
@@ -37,7 +37,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
          * for zapping and thus puts the TDP MMU's reference to each

root, i.e.
         * ultimately frees all roots.
         */
-       kvm_tdp_mmu_invalidate_all_roots(kvm);
+       kvm_tdp_mmu_invalidate_all_roots(kvm, false); kvm_tdp_mmu_zap_invalidated_roots(kvm);
WARN_ON(atomic64_read(&kvm->arch.tdp_mmu_pages));

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -771,7 +771,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct
 kvm_mmu_page *sp)
   * operation can cause a soft lockup.
   */

 static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
-                             gfn_t start, gfn_t end, bool can_yield, bool flush)
+                             gfn_t start, gfn_t end, bool can_yield, bool flush,
+                             bool zap_private)
 {
        struct tdp_iter iter;

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -779,6 +780,10 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm,
 struct kvm_mmu_page *root,
Quoted 4 lines


        lockdep_assert_held_write(&kvm->mmu_lock);
+       WARN_ON_ONCE(zap_private && !is_private_sp(root));

All the callers have zap_private as zap_private && is_private_sp(root). What badness is it trying to uncover?

Quoted 3 lines

+       if (!zap_private && is_private_sp(root))
+               return false;
+

#61 lore raw

Re: [PATCH v19 011/130] KVM: Add new members to struct kvm_gfn_range to operate on

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

IMO, an enum will be clearer than the two flags.

    enum {
        PROCESS_PRIVATE_AND_SHARED,
        PROCESS_ONLY_PRIVATE,
        PROCESS_ONLY_SHARED,
    };

Quoted 5 lines

The code will be ugly like
"if (== PRIVATE || == PRIVATE_AND_SHARED)" or
"if (== SHARED || == PRIVATE_AND_SHARED)"

two boolean (or two flags) is less error-prone.

Yes the enum would be awkward to handle. But I also thought the way this is specified in struct kvm_gfn_range is a little strange.

It is ambiguous what it should mean if you set:
.only_private=true;
.only_shared=true;
...as happens later in the series (although it may be a mistake).

Reading the original conversation, it seems Sean suggested this specifically. But it wasn't clear to me from the discussion what the intention of the "only" semantics was. Like why not?
bool private;
bool shared;

#62 lore raw

Re: [PATCH v19 011/130] KVM: Add new members to struct kvm_gfn_range to operate on

Quoted 23 lines · Rick Edgecombe
Quoted 8 lines · Isaku Yamahata
Quoted 7 lines

IMO, an enum will be clearer than the two flags.

    enum {
        PROCESS_PRIVATE_AND_SHARED,
        PROCESS_ONLY_PRIVATE,
        PROCESS_ONLY_SHARED,
    };

Quoted 5 lines

The code will be ugly like
"if (== PRIVATE || == PRIVATE_AND_SHARED)" or
"if (== SHARED || == PRIVATE_AND_SHARED)"

two boolean (or two flags) is less error-prone.

Yes the enum would be awkward to handle. But I also thought the way this is specified in struct kvm_gfn_range is a little strange.

It is ambiguous what it should mean if you set:
 .only_private=true;
 .only_shared=true;
...as happens later in the series (although it may be a mistake).

Quoted 5 lines

Reading the original conversation, it seems Sean suggested this specifically. But it wasn't clear to me from the discussion what the intention of the "only" semantics was. Like why not?
 bool private;
 bool shared;

I see Binbin brought up this point on v18 as well:
https://lore.kernel.org/kvm/[email protected]/#t

and helpfully dug up some other discussion with Sean where he agreed the "_only" is confusing and proposed the the enum:
https://lore.kernel.org/kvm/[email protected]/

He wanted the default value (in the case the caller forgets to set them), to be to include both private and shared. I think the enum has the issues that Isaku mentioned. What about?

bool exclude_private;
bool exclude_shared;

It will become onerous if more types of aliases grow, but it clearer semantically and has the safe default behavior.

#63 lore raw

Re: [PATCH v19 011/130] KVM: Add new members to struct kvm_gfn_range to operate on

Quoted 41 lines · Rick P
Quoted 23 lines · Rick Edgecombe
Quoted 8 lines · Isaku Yamahata
Quoted 7 lines

IMO, an enum will be clearer than the two flags.

    enum {
        PROCESS_PRIVATE_AND_SHARED,
        PROCESS_ONLY_PRIVATE,
        PROCESS_ONLY_SHARED,
    };

Quoted 5 lines

The code will be ugly like
"if (== PRIVATE || == PRIVATE_AND_SHARED)" or
"if (== SHARED || == PRIVATE_AND_SHARED)"

two boolean (or two flags) is less error-prone.

Yes the enum would be awkward to handle. But I also thought the way this is specified in struct kvm_gfn_range is a little strange.

It is ambiguous what it should mean if you set:
 .only_private=true;
 .only_shared=true;
...as happens later in the series (although it may be a mistake).

Quoted 5 lines

Reading the original conversation, it seems Sean suggested this specifically. But it wasn't clear to me from the discussion what the intention of the "only" semantics was. Like why not?
 bool private;
 bool shared;

I see Binbin brought up this point on v18 as well:
https://lore.kernel.org/kvm/[email protected]/#t

and helpfully dug up some other discussion with Sean where he agreed the "_only" is confusing and proposed the the enum:
https://lore.kernel.org/kvm/[email protected]/

He wanted the default value (in the case the caller forgets to set them), to be to include both private and shared. I think the enum has the issues that Isaku mentioned. What about?

Quoted 5 lines

bool exclude_private;
bool exclude_shared;

It will become onerous if more types of aliases grow, but it clearer semantically and has the safe default behavior.

I'm fine with those names. Anyway, I'm fine with wither way, two bools or enum.

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

Re: [PATCH v19 098/130] KVM: TDX: Add a place holder to handle TDX VM exit

In reply to Sean Christopherson
Quoted 27 lines · Sean Christopherson
Quoted 12 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +12 -0
+int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
+{
+	union tdx_exit_reason exit_reason = to_tdx(vcpu)->exit_reason;
+
+	/* See the comment of tdh_sept_seamcall(). */
+	if (unlikely(exit_reason.full == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_SEPT)))
+		return 1;
+
+	/*
+	 * TDH.VP.ENTRY checks TD EPOCH which contend with TDH.MEM.TRACK and
+	 * vcpu TDH.VP.ENTER.
+	 */

arch/x86/kvm/vmx/tdx.c void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode, · line 1309

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	if (unlikely(exit_reason.full == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_TD_EPOCH)))
+		return 1;
+
+	if (unlikely(exit_reason.full == TDX_SEAMCALL_UD)) {
+		kvm_spurious_fault();
+		/*
+		 * In the case of reboot or kexec, loop with TDH.VP.ENTER and
+		 * TDX_SEAMCALL_UD to avoid unnecessarily activity.
+		 */
+		return 1;

No. This is unnecessarily risky. KVM_BUG_ON() and exit to userspace. The response to "SEAMCALL faulted" should never be, "well, let's try again!".

Quoted 2 lines

Also, what about #GP on SEAMCALL? In general, the error handling here seems lacking.

As I replied at [1], let me revise error handling in general TDX KVM code.
[1] https://lore.kernel.org/kvm/[email protected]/T/#macc431c87676995d65ddcd8de632261a2dedc525

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]
Quoted 4 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
(quoted diff) +2 -0
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level,

hpa_t page,
+                                  struct tdx_module_args *out)

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+{
+       struct tdx_module_args in = {
+               .rcx = gpa | level,
+               .rdx = tdr,
+               .r8 = page,
+       };
+
+       clflush_cache_range(__va(page), PAGE_SIZE);
+       return tdx_seamcall(TDH_MEM_SEPT_ADD, &in, out);
+}

The caller of this later in the series looks like this:

	err = tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &out);
	if (unlikely(err == TDX_ERROR_SEPT_BUSY))
		return -EAGAIN;
	if (unlikely(err == (TDX_EPT_ENTRY_STATE_INCORRECT |
TDX_OPERAND_ID_RCX))) {
		union tdx_sept_entry entry = {
			.raw = out.rcx,
		};
		union tdx_sept_level_state level_state = {
			.raw = out.rdx,
		};

		/* someone updated the entry with same value. */
		if (level_state.level == tdx_level &&
		    level_state.state == TDX_SEPT_PRESENT &&
		    !entry.leaf && entry.pfn == (hpa >> PAGE_SHIFT))
			return -EAGAIN;
	}

The helper abstracts setting the arguments into the proper registers fields passed in, but doesn't abstract pulling the result out from the register fields. Then the caller has to manually extract them in this verbose way. Why not have the helper do both?

#377 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Edgecombe, Rick P
Quoted 24 lines · Rick P
Quoted 11 lines · On Mon, 2024-02-26 at 00:26 -0800, [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.)

Quoted 11 lines

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.

Quoted 1 line

Is the migration case relevant to TDX?

We can forget about it because the page migration isn't supported yet.

Quoted 17 lines
Quoted 8 lines

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

Quoted 8 lines

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.

Quoted 4 lines

I get the part about only zapping leafs and not the root and mid-level PTEs. But why the MTRR, lapic page and migration part? Why should those not be zapped? Why is migration a consideration when it is not supported?

When we zap a page from the guest, and add it again on TDX even with the same GPA, the page is zeroed. We'd like to keep memory contents for those cases.

Ok, let me add those whys and drop migration part. Here is the updated one.

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. When we remove the private page from the guest and re-add it with the same GPA, the page is zeroed.

Regarding memory type change (mtrr virtualization and lapic page mapping change), the current implementation zaps pages, and populate the page with new memory type on the next KVM page fault. It doesn't work for TDX to have zeroed pages. Because TDX supports only WB, we ignore the request for MTRR and lapic page change to not zap private pages on unmapping for those two cases

TDX Secure-EPT requires removing the guest pages first and leaf Secure-EPT pages in order. It doesn't allow zap a Secure-EPT entry that has child pages. It doesn't work with the current TDP MMU zapping logic that zaps the root page table without touching child pages. Instead, zap only leaf SPTEs for KVM mmu that has a shared bit mask.

Quoted 53 lines
Quoted 53 lines

---
 arch/x86/kvm/mmu/mmu.c     | 61
++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c | 37 +++++++++++++++++++---- arch/x86/kvm/mmu/tdp_mmu.h |  5 ++--

 3 files changed, 92 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index 0d6d4506ec97..30c86e858ae4 100644
@@ -6339,7 +6339,7 @@ static void kvm_mmu_zap_all_fast(struct kvm
 *kvm)
          * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock

and yield.
         */
        if (tdp_mmu_enabled)
-               kvm_tdp_mmu_invalidate_all_roots(kvm);
+               kvm_tdp_mmu_invalidate_all_roots(kvm, true);
        /*
         * Notify all vcpus to reload its shadow page table and flush TLB.

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6459,7 +6459,16 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t
 gfn_start, gfn_t gfn_end)
         flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);


        if (tdp_mmu_enabled)
-               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
+               /*
+                * zap_private = false. Zap only shared pages. +                *
+                * kvm_zap_gfn_range() is used when MTRR or PAT memory
+                * type was 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.
+                */
+               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush, false);

        if (flush)
                kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6905,10 +6914,56 @@ void kvm_arch_flush_shadow_all(struct kvm
Quoted 8 lines
Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +0 -0
 *kvm)
         kvm_mmu_zap_all(kvm);
  }


+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)

What about kvm_mmu_zap_memslot_leafs() instead?

Ok.

Quoted 27 lines
Quoted 2 lines

+{
+       bool flush = false;

It doesn't need to be initialized if it passes false directly into kvm_tdp_mmu_unmap_gfn_range(). It would make the code easier to understand.

Quoted 20 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+
+       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 (tdp_mmu_enabled) {
+               struct kvm_gfn_range range = {
+                     .slot = slot,
+                     .start = slot->base_gfn,
+                     .end = slot->base_gfn + slot->npages, +                     .may_block = true,
+
+                     /*
+                      * This handles both private gfn and shared gfn.

Quoted 8 lines
Quoted 5 lines

+                      * All private page should be zapped on memslot deletion.
+                      */
+                     .only_private = true,
+                     .only_shared = true,

only_private and only_shared are both true? Shouldn't they both be false? (or just unset)

I replied at.
https://lore.kernel.org/kvm/[email protected]/

Quoted 9 lines
Quoted 8 lines

+               };
+
+               flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush);
+       } else {
+               /* TDX supports only TDP-MMU case. */ +               WARN_ON_ONCE(1);

Quoted 7 lines

How about a KVM_BUG_ON() instead? If somehow this is reached, we don't want the caller thinking the pages are zapped, then enter the guest with pages mapped that have gone elsewhere.

Quoted 1 line

+               flush = true;

Why flush?

Those are only safe guard. TDX supports only TDP MMU. Let me drop them.

Quoted 21 lines
Quoted 7 lines

+       }
+       if (flush)
+               kvm_flush_remote_tlbs(kvm);

arch/x86/kvm/mmu/mmu.c +4 -0
+
+       write_unlock(&kvm->mmu_lock);
+}
+
Quoted 5 lines

 void kvm_arch_flush_shadow_memslot(struct kvm *kvm, struct kvm_memory_slot *slot) {
-       kvm_mmu_zap_all_fast(kvm);
+       if (kvm_gfn_shared_mask(kvm))

There seems to be an attempt to abstract away the existence of Secure- EPT in mmu.c, that is not fully successful. In this case the code checks kvm_gfn_shared_mask() to see if it needs to handle the zapping in a way specific needed by S-EPT. It ends up being a little confusing because the actual check is about whether there is a shared bit. It only works because only S-EPT is the only thing that has a kvm_gfn_shared_mask().

Quoted 3 lines

Doing something like (kvm->arch.vm_type == KVM_X86_TDX_VM) looks wrong, but is more honest about what we are getting up to here. I'm not sure though, what do you think?

Right, I attempted and failed in zapping case. This is due to the restriction that the Secure-EPT pages must be removed from the leaves. the VMX case (also NPT, even SNP) heavily depends on zapping root entry as optimization.

I can think of
- add TDX check. Looks wrong
- Use kvm_gfn_shared_mask(kvm). confusing
- Give other name for this check like zap_from_leafs (or better name?) The implementation is same to kvm_gfn_shared_mask() with comment.
- Or we can add a boolean variable to struct kvm

Quoted 30 lines
Quoted 30 lines

 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index d47f0daf1b03..e7514a807134 100644
@@ -37,7 +37,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
          * for zapping and thus puts the TDP MMU's reference to each

root, i.e.
         * ultimately frees all roots.
         */
-       kvm_tdp_mmu_invalidate_all_roots(kvm);
+       kvm_tdp_mmu_invalidate_all_roots(kvm, false); kvm_tdp_mmu_zap_invalidated_roots(kvm);
WARN_ON(atomic64_read(&kvm->arch.tdp_mmu_pages));

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -771,7 +771,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct
 kvm_mmu_page *sp)
   * operation can cause a soft lockup.
   */

 static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
-                             gfn_t start, gfn_t end, bool can_yield, bool flush)
+                             gfn_t start, gfn_t end, bool can_yield, bool flush,
+                             bool zap_private)
 {
        struct tdp_iter iter;

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -779,6 +780,10 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm,
Quoted 8 lines
Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
 struct kvm_mmu_page *root,


        lockdep_assert_held_write(&kvm->mmu_lock);
+       WARN_ON_ONCE(zap_private && !is_private_sp(root));

All the callers have zap_private as zap_private && is_private_sp(root). What badness is it trying to uncover?

I added this during debug. Let me drop it.

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]
Quoted 7 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

A VMM interacts with the TDX module using a new instruction (SEAMCALL). 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 7 lines

Define C wrapper functions for SEAMCALLs for readability.

Some SEAMCALL APIs donate host pages to TDX module or guest TD, and the donated pages are encrypted. Those require the VMM to flush the cache lines to avoid cache line alias.

Not valid anymore.

[...]

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

Quoted 11 lines
arch/x86/kvm/vmx/tdx_ops.h new file +11 -0
+
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);

I think it's silly to have the @out argument in this way.

What is the main reason to still have it?

Yeah we used to have the @out in __seamcall() assembly function. The assembly code checks the @out and skips copying registers to @out when it is NULL.

But it got removed when we tried to unify the assembly for TDCALL/TDVMCALL and SEAMCALL to have a *SINGLE* assembly macro.

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

To me that means we should just accept the fact we will always have a valid @out.

But there might be some case that you _obviously_ need the @out and I missed?

Quoted 54 lines
arch/x86/kvm/vmx/tdx_ops.h new file +54 -0
+
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {
+		/*
+		 * SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off.
+		 * This can happen when the host gets rebooted or live
+		 * updated. In this case, the instruction execution is ignored
+		 * as KVM is shut down, so the error code is suppressed. Other
+		 * than this, the error is unexpected and the execution can't
+		 * continue as the TDX features reply on VMX to be on.
+		 */
+		kvm_spurious_fault();
+		return 0;
+	}
+	return ret;
+}
+
+static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
+{
+	struct tdx_module_args in = {
+		.rcx = addr,
+		.rdx = tdr,
+	};
+
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+	return tdx_seamcall(TDH_MNG_ADDCX, &in, NULL);
+}
+
+static inline u64 tdh_mem_page_add(hpa_t tdr, gpa_t gpa, hpa_t hpa, hpa_t source,
+				   struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa,
+		.rdx = tdr,
+		.r8 = hpa,
+		.r9 = source,
+	};
+
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_PAGE_ADD, &in, out);
+}
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level, hpa_t page,
+				   struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+		.r8 = page,
+	};
+
+	clflush_cache_range(__va(page), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_SEPT_ADD, &in, out);
+}
+

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+static inline u64 tdh_mem_sept_rd(hpa_t tdr, gpa_t gpa, int level,
+				  struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_SEPT_RD, &in, out);
+}

Not checked the whole series yet, but is this ever used in this series?

[...]

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx_ops.h new file +8 -0
+
+static inline u64 tdh_sys_lp_shutdown(void)
+{
+	struct tdx_module_args in = {
+	};
+
+	return tdx_seamcall(TDH_SYS_LP_SHUTDOWN, &in, NULL);
+}

As Sean already pointed out, I am sure it's/should not used in this series.

That being said, I found it's not easy to determine whether one wrapper will be used by this series or not. The other option is we introduce the wrapper(s) when they get actally used, but I can see (especially at this stage) it's also a apple vs orange question that people may have different preference.

Perhaps we can say something like below in changelog ...

"
Note, not all VM-managing related SEAMCALLs have a wrapper here, but only provide wrappers that are essential to the run the TDX guest with basic feature set. "

... so that people will at least to pay attention to this during the review?

#185 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to Edgecombe, Rick P
Quoted 37 lines · Rick P
Quoted 4 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
(quoted diff) +2 -0
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level,

hpa_t page,
+                                  struct tdx_module_args *out)

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+{
+       struct tdx_module_args in = {
+               .rcx = gpa | level,
+               .rdx = tdr,
+               .r8 = page,
+       };
+
+       clflush_cache_range(__va(page), PAGE_SIZE);
+       return tdx_seamcall(TDH_MEM_SEPT_ADD, &in, out);
+}

The caller of this later in the series looks like this:

	err = tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &out);
	if (unlikely(err == TDX_ERROR_SEPT_BUSY))
		return -EAGAIN;
	if (unlikely(err == (TDX_EPT_ENTRY_STATE_INCORRECT |
TDX_OPERAND_ID_RCX))) {
		union tdx_sept_entry entry = {
			.raw = out.rcx,
		};
		union tdx_sept_level_state level_state = {
			.raw = out.rdx,
		};

		/* someone updated the entry with same value. */
		if (level_state.level == tdx_level &&
		    level_state.state == TDX_SEPT_PRESENT &&
		    !entry.leaf && entry.pfn == (hpa >> PAGE_SHIFT))
			return -EAGAIN;
	}
Quoted 4 lines

The helper abstracts setting the arguments into the proper registers fields passed in, but doesn't abstract pulling the result out from the register fields. Then the caller has to manually extract them in this verbose way. Why not have the helper do both?

Yes. Let me update those arguments.

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 9 lines · Isaku Yamahata
Quoted 7 lines

The helper abstracts setting the arguments into the proper registers
fields passed in, but doesn't abstract pulling the result out from the
register fields. Then the caller has to manually extract them in this
verbose way. Why not have the helper do both?

Yes. Let me update those arguments.

What were you thinking exactly, like?

tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state);

And for the other helpers?

#197 lore raw

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

In reply to [email protected]
Quoted 4 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

Likely we need more information here. See below.

Quoted 10 lines

---
v19:
- dropped unnecessary include <asm/tdx.h>

v18:
- Added Reviewed-by Binbin.

The tag doesn't show in the SoB chain.

Quoted 3 lines

---

[...]

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

Quoted 7 lines
arch/x86/kvm/vmx/tdx_error.c new file +7 -0
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_args *out)
+{
+	if (!out) {
+		pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
+				   op, error_code);
+		return;
+	}

I think this is the reason you still want the @out in tdx_seamcall()?

But I am not sure either -- even if you want to have @out *here* -- why cannot you pass a NULL explicitly when you *know* the concerned SEAMCALL doesn't have a valid output?

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx_error.c new file +6 -0
+
+#define MSG	\
+	"SEAMCALL (0x%016llx) failed: 0x%016llx RCX 0x%016llx RDX 0x%016llx R8 0x%016llx R9 0x%016llx R10 0x%016llx R11 0x%016llx\n"
+	pr_err_ratelimited(MSG, op, error_code, out->rcx, out->rdx, out->r8,
+			   out->r9, out->r10, out->r11);
+}

Besides the regs that you are printing, there are more regs (R12-R15, RDI, RSI) in the structure.

It's not clear why you only print some, but not all.

AFAICT the VP.ENTER SEAMCALL can have all regs as valid output?

Anyway, that being said, you might need to put more text in changelog/comment to make this patch (at least more) reviewable.

#378 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Isaku Yamahata
Quoted 8 lines · Isaku Yamahata

When we zap a page from the guest, and add it again on TDX even with the same
GPA, the page is zeroed.  We'd like to keep memory contents for those cases.

Ok, let me add those whys and drop migration part. Here is the updated one.

Quoted 8 lines

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.  When we remove the private page from the guest
and re-add it with the same GPA, the page is zeroed.

Regarding memory type change (mtrr virtualization and lapic page mapping change), the current implementation zaps pages, and populate

                                                                     s^
Quoted 1 line

the page with new memory type on the next KVM page fault.

                               ^s
Quoted 1 line

It doesn't work for TDX to have zeroed pages.

What does this mean? Above you mention how all the pages are zeroed. Do you mean it doesn't work for TDX to zero a running guest's pages. Which would happen for the operations that would expect the pages could get faulted in again just fine.

Quoted 3 lines

Because TDX supports only WB, we
ignore the request for MTRR and lapic page change to not zap private pages on unmapping for those two cases

Hmm. I need to go back and look at this again. It's not clear from the description why it is safe for the host to not zap pages if requested to. I see why the guest wouldn't want them to be zapped.

Quoted 8 lines

TDX Secure-EPT requires removing the guest pages first and leaf Secure-EPT pages in order. It doesn't allow zap a Secure-EPT entry that has child pages.  It doesn't work with the current TDP MMU zapping logic that zaps the root page table without touching child pages.  Instead, zap only leaf SPTEs for KVM mmu that has a shared bit
mask.

Could this be better as two patches that each address a separate thing?
1. Leaf only zapping
2. Don't zap for MTRR, etc.

Quoted 24 lines
Quoted 12 lines

There seems to be an attempt to abstract away the existence of Secure-
EPT in mmu.c, that is not fully successful. In this case the code checks kvm_gfn_shared_mask() to see if it needs to handle the zapping
in a way specific needed by S-EPT. It ends up being a little confusing
because the actual check is about whether there is a shared bit. It only works because only S-EPT is the only thing that has a kvm_gfn_shared_mask().

Quoted 5 lines

Doing something like (kvm->arch.vm_type == KVM_X86_TDX_VM) looks wrong,
but is more honest about what we are getting up to here. I'm not sure
though, what do you think?

Right, I attempted and failed in zapping case.  This is due to the restriction
that the Secure-EPT pages must be removed from the leaves.  the VMX case (also
NPT, even SNP) heavily depends on zapping root entry as optimization.

Quoted 7 lines

I can think of
- add TDX check. Looks wrong
- Use kvm_gfn_shared_mask(kvm). confusing
- Give other name for this check like zap_from_leafs (or better name?)
  The implementation is same to kvm_gfn_shared_mask() with comment.
  - Or we can add a boolean variable to struct kvm

Hmm, maybe wrap it in a function like:
static inline bool kvm_can_only_zap_leafs(const struct kvm *kvm)

{
	/* A comment explaining what is going on */
	return kvm->arch.vm_type == KVM_X86_TDX_VM;
}

But KVM seems to be a bit more on the open coded side when it comes to things like this, so not sure what maintainers would prefer. My opinion is the kvm_gfn_shared_mask() check is too strange and it's worth a new helper. If that is bad, then just open coded kvm->arch.vm_type == KVM_X86_TDX_VM is the second best I think.

I feel both strongly that it should be changed, and unsure what maintainers would prefer. Hopefully one will chime in.