Skip to contentSkip to conversation

KVM TDX basic feature support

PATCH Superseded [email protected] 10 participants 149 messages May 29, 2023 – Jul 17, 2023 2 messages not in the archive Page 2 of 2

Subsystems (6)
Documentation x86 KVM perf events +2 more subsystems

v14 of 19 Superseded Latest is v19 →

lore
Share & tools
lore
#8 lore raw

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to [email protected]
Quoted 166 lines · On Sun, 28 May 2023 21:18:46 -0700 [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.

---
Changes v13 -> v14:
- Use on_each_cpu(vmx_hardware_enable)

---
 arch/x86/kvm/Makefile      |  1 +
 arch/x86/kvm/vmx/main.c    | 34 ++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.c     | 63 ++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h |  8 +++++
 4 files changed, 104 insertions(+), 2 deletions(-)
 create mode 100644 arch/x86/kvm/vmx/tdx.c
arch/x86/kvm/Makefile +1 -0
index 0e894ae23cbc..4b01ab842ab7 100644
@@ -25,6 +25,7 @@ kvm-$(CONFIG_KVM_SMM)	+= smm.o
 kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
 			   vmx/hyperv.o vmx/nested.o vmx/posted_intr.o vmx/main.o
 kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o
 
 kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o \
 			   svm/sev.o svm/hyperv.o
arch/x86/kvm/vmx/main.c +32 -2
index 791ee271393d..2638b344864c 100644
@@ -6,6 +6,36 @@
 #include "nested.h"
 #include "pmu.h"
 
+static bool enable_tdx __ro_after_init;
+module_param_named(tdx, enable_tdx, bool, 0444);
+
+static int vt_hardware_enable(void)
+{
+	int ret;
+
+	ret = vmx_hardware_enable();
+	if (ret || !enable_tdx)
+		return ret;
+
+	ret = tdx_cpu_enable();
+	if (ret)
+		vmx_hardware_disable();
+	return ret;
+}
+
+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)|	       \
@@ -24,7 +54,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.hardware_unsetup = vmx_hardware_unsetup,
 
-	.hardware_enable = vmx_hardware_enable,
+	.hardware_enable = vt_hardware_enable,
 	.hardware_disable = vmx_hardware_disable,
 	.has_emulated_msr = vmx_has_emulated_msr,
 
@@ -159,7 +189,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 +49 -0
new file mode 100644
index 000000000000..965545a308ad
@@ -0,0 +1,63 @@
+// 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;
+}
+
+static void __init vmx_tdx_on(void *info)
+{
+       atomic_t *err = info;
+       int r;
+
+       r = vmx_hardware_enable();
+       if (!r)
+	       r = tdx_cpu_enable();
+       if (r)
+	       atomic_set(err, r);
+}
+
+static void __init vmx_off(void *unused)
+{
+       vmx_hardware_disable();
+}
+
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	atomic_t err = ATOMIC_INIT(0);
+	int r = 0;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+		return -EINVAL;
+	}
+
+	/* tdx_enable() in tdx_module_setup() requires cpus lock. */
+	cpus_read_lock();
+	on_each_cpu(vmx_tdx_on, &err, true);	/* TDX requires vmxon. */
+	r = atomic_read(&err);
+	if (!r)
+		r = tdx_module_setup();
+	on_each_cpu(vmx_off, NULL, true);

Out of curiosity, why VMX has to be turned off after tdx_module_setup()?

Quoted 28 lines
arch/x86/kvm/vmx/tdx.c new file +4 -0
+	cpus_read_unlock();
+
+	return r;
+}
arch/x86/kvm/vmx/x86_ops.h +8 -0
index 051b5c4b5c2f..f59e5197836a 100644
@@ -20,6 +20,8 @@ bool kvm_is_vmx_supported(void);
 int __init vmx_init(void);
 void vmx_exit(void);
 
+__init int vmx_hardware_setup(void);
+
 extern struct kvm_x86_ops vt_x86_ops __initdata;
 extern struct kvm_x86_init_ops vt_init_ops __initdata;
 
@@ -133,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 -ENOSYS; }
+#endif
+
 #endif /* __KVM_X86_VMX_X86_OPS_H */
#9 lore raw

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

Quoted 10 lines · Zhi Wang

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

Quoted 7 lines · On Sun, 28 May 2023 21:18:46 -0700 [email protected] wrote:
arch/x86/kvm/vmx/tdx.c new file +7 -0
+	/* tdx_enable() in tdx_module_setup() requires cpus lock. */
+	cpus_read_lock();
+	on_each_cpu(vmx_tdx_on, &err, true);	/* TDX requires vmxon. */
+	r = atomic_read(&err);
+	if (!r)
+		r = tdx_module_setup();
+	on_each_cpu(vmx_off, NULL, true);

Out of curiosity, why VMX has to be turned off after tdx_module_setup()?

KVM has historically enabled VMX if and only if KVM has active VMs. Whether or not it still makes sense to do dynamic enabling is debatable, but that's a discussion for another day.

#150 lore raw
In reply to Wang, Wei W
Quoted 9 lines · Wei W
Quoted 4 lines · On Monday, May 29, 2023 12:19 PM, [email protected] wrote:

The tree can be found at https://github.com/intel/tdx/tree/kvm-upstream
The corresponding qemu branch is found at
https://github.com/yamahata/qemu/tree/tdx/qemu-upm
How to run/test: It's describe at https://github.com/intel/tdx/wiki/TDX-KVM

Seems the above wiki lacks some update, e.g. tdx needs to be enabled explicitly when loading kvm_intel, example command line (e.g. private=true for memoy-backend) to launch TD with gmem.

Thanks for pointing it out. I've updated those items.

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

Re: [PATCH v14 003/113] KVM: x86/vmx: Refactor KVM VMX module init/exit functions

In reply to [email protected]
Quoted 71 lines · On Sun, 28 May 2023 21:18:45 -0700 [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.

---
 arch/x86/kvm/vmx/main.c    | 50 +++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/vmx.c     | 54 +++++---------------------------------
 arch/x86/kvm/vmx/x86_ops.h | 13 ++++++++-
 3 files changed, 68 insertions(+), 49 deletions(-)
arch/x86/kvm/vmx/main.c +25 -0
index a59559ff140e..791ee271393d 100644
@@ -165,3 +165,53 @@ 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 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();
+
+	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

arch/x86/kvm/vmx/main.c struct kvm_x86_init_ops vt_init_ops __initdata = { · line 202

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

---------------------------------

arch/x86/kvm/vmx/main.c struct kvm_x86_init_ops vt_init_ops __initdata = { · line 210

Quoted 8 lines
arch/x86/kvm/vmx/main.c +8 -0
+err_kvm_init:
+	vmx_exit();
+err_vmx_init:
+	kvm_x86_vendor_exit();
+	return r;
+}
+module_init(vt_init);
+

----------------------------------

arch/x86/kvm/vmx/main.c struct kvm_x86_init_ops vt_init_ops __initdata = { · line 215

Quoted 5 lines
arch/x86/kvm/vmx/main.c +5 -0
+static void vt_exit(void)
+{
+	kvm_exit();
+	kvm_x86_vendor_exit();
+	vmx_exit();

----------------------------------

It seems the exiting sequences above are a little bit different with each other (PS: It is not a prob introduced in this patch):

vmx_exit()
kvm_x86_vendor_exit()
....

and

...
kvm_x86_vnedor_exit()
vmx_exit()

I was wondering which one should be correct. Literally, the exiting sequence would be in reversing order of the initialization sequence.

Quoted 146 lines
arch/x86/kvm/vmx/main.c +2 -0
+}
+module_exit(vt_exit);
arch/x86/kvm/vmx/vmx.c +6 -48
index ed7bf8fc55a8..9e4def64495b 100644
@@ -554,7 +554,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;
 
@@ -590,7 +590,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;
 
@@ -614,10 +614,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) */
 
 /*
@@ -2715,7 +2711,7 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	return 0;
 }
 
-static bool kvm_is_vmx_supported(void)
+bool kvm_is_vmx_supported(void)
 {
 	int cpu = raw_smp_processor_id();
 
@@ -8381,7 +8377,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;
 
@@ -8392,32 +8388,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();
-
-	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
@@ -8427,7 +8401,7 @@ static int __init vmx_init(void)
 	 */
 	r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
 	if (r)
-		goto err_l1d_flush;
+		return r;
 
 	vmx_setup_fb_clear_ctrl();
 
@@ -8448,21 +8422,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 +12 -1
index e9ec4d259ff5..051b5c4b5c2f 100644
@@ -8,11 +8,22 @@
 
 #include "x86.h"
 
-__init int vmx_hardware_setup(void);
+#if IS_ENABLED(CONFIG_HYPERV)
+__init void hv_init_evmcs(void);
+void hv_reset_evmcs(void);
+#else /* IS_ENABLED(CONFIG_HYPERV) */
+static inline void hv_init_evmcs(void) {}
+static inline void hv_reset_evmcs(void) {}
+#endif /* IS_ENABLED(CONFIG_HYPERV) */
+
+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;
 
+__init int vmx_hardware_setup(void);
 void vmx_hardware_unsetup(void);
 int vmx_check_processor_compat(void);
 int vmx_hardware_enable(void);
#6 lore raw

Re: [PATCH v14 003/113] KVM: x86/vmx: Refactor KVM VMX module init/exit functions

In reply to a message not in the archive
Quoted 67 lines · Isaku Yamahata
Quoted 64 lines · Zhi Wang
Quoted 24 lines
(quoted diff) +24 -0
+static int __init vt_init(void)
+{
+	unsigned int vcpu_size, vcpu_align;
+	int 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();
+
+	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

Review

Quoted 10 lines
(quoted diff) +10 -0
+	 * 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;
+

---------------------------------

Review

Quoted 8 lines
(quoted diff) +8 -0
+err_kvm_init:
+	vmx_exit();
+err_vmx_init:
+	kvm_x86_vendor_exit();
+	return r;
+}
+module_init(vt_init);
+

----------------------------------

Review

Quoted 5 lines
(quoted diff) +5 -0
+static void vt_exit(void)
+{
+	kvm_exit();
+	kvm_x86_vendor_exit();
+	vmx_exit();

----------------------------------

It seems the exiting sequences above are a little bit different with each other (PS: It is not a prob introduced in this patch):

vmx_exit()
kvm_x86_vendor_exit()
....

and

...
kvm_x86_vnedor_exit()
vmx_exit()

Quoted 7 lines
Quoted 2 lines

I was wondering which one should be correct. Literally, the exiting sequence would be in reversing order of the initialization sequence.

In theory, I think kvm_x86_vendor_exit() => vmx_exit() and vmx_init() => kvm_x86_vendor_exit() should be the right order. But in practice, it doesn't matter and I didn't want to touch the order with this patch series.

Here is the patch for it. But I'd like to hold the patch after this patch series.

From 02c425cb96c252eecbeaf8e57dd6afd7576931b1 Mon Sep 17 00:00:00 2001
Message-Id: <02c425cb96c252eecbeaf8e57dd6afd7576931b1.1685566207.git.isaku.yamahata@intel.com>
From: Isaku Yamahata <[email protected]>
Date: Wed, 31 May 2023 13:36:10 -0700
Subject: [PATCH] KVM: VMX: Reorder vmx initialization with kvm vendor
initialization

To match vmx_exit cleanup.

---
 arch/x86/kvm/vmx/main.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/main.c +5 -5
index 2e4667307458..a0586da86d81 100644
@@ -1251,11 +1251,11 @@ static int __init vt_init(void)
 				   __alignof__(struct vcpu_tdx));
 	}
 
-	r = kvm_x86_vendor_init(&vt_init_ops);
+	r = vmx_init();
 	if (r)
-		return r;
+		goto err_vmx_init;
 
-	r = vmx_init();
+	r = kvm_x86_vendor_init(&vt_init_ops);
 	if (r)
 		goto err_vmx_init;
 
@@ -1270,9 +1270,9 @@ static int __init vt_init(void)
 	return 0;
 
 err_kvm_init:
-	vmx_exit();
-err_vmx_init:
 	kvm_x86_vendor_exit();
+err_vmx_init:
+	vmx_exit();
 	return r;
 }
 module_init(vt_init);
Signature · 7 lines
2.25.1




-- 
Isaku Yamahata <[email protected]>
#24 lore raw

RE: [PATCH v14 011/113] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]
Quoted 58 lines · On Monday, May 29, 2023 12:19 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.

Export __seamcall and 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. Such SEAMCALLs flush cache lines (typically by movdir64b instruction), but some don't. Those that don't clear cache lines require the VMM to flush the cache lines to avoid cache line alias.

---
 arch/x86/include/asm/tdx.h       |   4 +
 arch/x86/kvm/vmx/tdx_ops.h       | 202
+++++++++++++++++++++++++++++++
 arch/x86/virt/vmx/tdx/seamcall.S |   2 +
 arch/x86/virt/vmx/tdx/tdx.h      |   3 -
 4 files changed, 208 insertions(+), 3 deletions(-)  create mode 100644

arch/x86/kvm/vmx/tdx_ops.h

arch/x86/include/asm/tdx.h index renamed from arch/x86/include/asm/tdx.h +0 -0

112a5b9bd5cd..6c01ab572c1f 100644

arch/x86/include/asm/tdx.h +0 -0
@@ -104,10 +104,14 @@ static inline long tdx_kvm_hypercall(unsigned int

nr, unsigned long p1, bool platform_tdx_enabled(void); int tdx_cpu_enable(void); int tdx_enable(void);

arch/x86/include/asm/tdx.h +2 -0
+u64 __seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+	       struct tdx_module_output *out);
 #else	/* !CONFIG_INTEL_TDX_HOST */
 static inline bool platform_tdx_enabled(void) { return false; }  static inline int

tdx_cpu_enable(void) { return -EINVAL; } static inline int tdx_enable(void) { return -EINVAL; }

arch/x86/include/asm/tdx.h +2 -0
+static inline u64 __seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			     struct tdx_module_output *out) { return

TDX_SEAMCALL_UD; };
#endif /* CONFIG_INTEL_TDX_HOST */

#endif /* !__ASSEMBLY__ */

arch/x86/kvm/vmx/tdx_ops.h new file +8 -0
new file mode 100644 index 000000000000..893cc6c25f3b
@@ -0,0 +1,202 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_OPS_H
+#define __KVM_X86_TDX_OPS_H
+
+#include <linux/compiler.h>
+

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+#include <asm/cacheflush.h>
+#include <asm/asm.h>
+#include <asm/kvm_host.h>
+
+#include "tdx_errno.h"
+#include "tdx_arch.h"
+#include "x86.h"
+
+static inline u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			       struct tdx_module_output *out) {

As discussed somewhere before, kvm_* is more common to be labelled for the generic code. Would it be better to be named tdx_seamcall here?

#25 lore raw

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

Quoted 18 lines · Wei W
Quoted 18 lines
arch/x86/kvm/vmx/tdx_ops.h new file +13 -0
new file mode 100644 index 000000000000..893cc6c25f3b
@@ -0,0 +1,202 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_OPS_H
+#define __KVM_X86_TDX_OPS_H
+
+#include <linux/compiler.h>
+
+#include <asm/cacheflush.h>
+#include <asm/asm.h>
+#include <asm/kvm_host.h>
+
+#include "tdx_errno.h"
Quoted 8 lines

arch/x86/kvm/vmx/tdx_ops.h

Quoted 5 lines
arch/x86/kvm/vmx/tdx_ops.h new file +5 -0
+#include "tdx_arch.h"
+#include "x86.h"
+
+static inline u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			       struct tdx_module_output *out) {

As discussed somewhere before, kvm_* is more common to be labelled for the generic code. Would it be better to be named tdx_seamcall here?

Ok, let's rename it to tdx_seamcall(), that's more consistent in this file.

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

Re: [PATCH v14 111/113] RFC: KVM: x86, TDX: Add check for setting CPUID

In reply to [email protected]
Quoted 10 lines · On Sun, 28 May 2023 21:20:33 -0700 [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a hook to setting CPUID for additional consistency check of KVM_SET_CPUID2.

Because intel TDX or AMD SNP has restriction on the value of cpuid. Some value can't be changed after boot. Some can be only set at the VM creation time and can't be changed later. Check if the new values are consistent with the old values.

Thanks for addressing this from the discussion. The structure looks good to me. I was thinking if the patch should be separated into two parts. One is the common part so that AMD folks can include it in their patch series. Another one is TDX callback which builds on top of the common-part patch.

Quoted 43 lines
---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  1 +
 arch/x86/kvm/cpuid.c               | 10 ++++++
 arch/x86/kvm/cpuid.h               |  2 ++
 arch/x86/kvm/vmx/main.c            | 10 ++++++
 arch/x86/kvm/vmx/tdx.c             | 57 ++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.h             |  7 ++++
 arch/x86/kvm/vmx/x86_ops.h         |  4 +++
 8 files changed, 90 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index c1a4d29cf4fa..5faa13a31f59 100644
@@ -20,6 +20,7 @@ KVM_X86_OP(hardware_disable)
 KVM_X86_OP(hardware_unsetup)
 KVM_X86_OP_OPTIONAL_RET0(offline_cpu)
 KVM_X86_OP(has_emulated_msr)
+KVM_X86_OP_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 68ddb0da31e0..4efd9770963c 100644
@@ -1588,6 +1588,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 +0 -0
index 0142a73034c4..ef7c361883d7 100644

arch/x86/kvm/cpuid.c static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, · line 421

Quoted 8 lines
arch/x86/kvm/cpuid.c +3 -0
@@ -414,6 +414,9 @@ static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,
 	}
 
 	r = kvm_check_cpuid(vcpu, e2, nent);
+	if (r)
+		return r;
+	r = static_call(kvm_x86_vcpu_check_cpuid)(vcpu, e2, nent);
 	if (r)
 		return r;

It would be nice to move the static_call into the kvm_check_cpuid() as it is part of the process of checking cpuid. It is good enough for now as kvm_check_cpuid() only has one caller. Think if more caller of kvm_check_cpuid() shows up in the future, they need to move it into kvm_check_cpuid anyway.

arch/x86/kvm/cpuid.c int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid, · line 1376

Quoted 12 lines
arch/x86/kvm/cpuid.c +7 -0
@@ -1364,6 +1367,13 @@ int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid,
 	return r;
 }
 
+struct kvm_cpuid_entry2 *__kvm_find_cpuid_entry2(
+	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index)
+{
+	return cpuid_entry2_find(entries, nent, function, index);
+}
+EXPORT_SYMBOL_GPL(__kvm_find_cpuid_entry2);
+

If evetually, we have to open kvm_cpuid2 when searching the cpuid entries, I would suggest to open it in kvm_find_cpuid_entry2() instead of introducing a new __kvm_find_cpuid_entry2(). It would be nice to let kvm_find_cpuid_entry2 () to take entreis and nent in the previou patch.

Quoted 89 lines
arch/x86/kvm/cpuid.c +0 -0
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2( struct kvm_cpuid2 *cpuid,
 						u32 function, u32 index)
 {
arch/x86/kvm/cpuid.h +2 -0
index a0e799297629..579675dcbbae 100644
@@ -13,6 +13,8 @@ void kvm_set_cpu_caps(void);
 
 void kvm_update_cpuid_runtime(struct kvm_vcpu *vcpu);
 void kvm_update_pv_runtime(struct kvm_vcpu *vcpu);
+struct kvm_cpuid_entry2 *__kvm_find_cpuid_entry2(struct kvm_cpuid_entry2 *entries,
+						 int nent, u32 function, u64 index);
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(struct kvm_cpuid2 *cpuid,
 					       u32 function, u32 index);
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry_index(struct kvm_vcpu *vcpu,
arch/x86/kvm/vmx/main.c +10 -0
index de8d8c70605b..cfc7fa87a8fe 100644
@@ -443,6 +443,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))
@@ -1087,6 +1096,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 +30 -0
index ede3b9f98243..12d6c9cacf6a 100644
@@ -491,6 +491,9 @@ void tdx_vm_free(struct kvm *kvm)
 
 	free_page((unsigned long)__va(kvm_tdx->tdr_pa));
 	kvm_tdx->tdr_pa = 0;
+
+	kfree(kvm_tdx->cpuid);
+	kvm_tdx->cpuid = NULL;
 }
 
 static int tdx_do_tdh_mng_key_config(void *param)
@@ -608,6 +611,44 @@ int tdx_vcpu_create(struct kvm_vcpu *vcpu)
 	return 0;
 }
 
+int tdx_vcpu_check_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, int nent)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	const struct tdsysinfo_struct *tdsysinfo;
+	int i;
+
+	tdsysinfo = tdx_get_sysinfo();
+	if (!tdsysinfo)
+		return -ENOTSUPP;
+
+	/*
+	 * Simple check that new cpuid is consistent with created one.
+	 * For simplicity, only trivial check.  Don't try comprehensive checks
+	 * with the cpuid virtualization table in the TDX module spec.
+	 */
+	for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
+		const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
+		u32 index = config->sub_leaf == TDX_CPUID_NO_SUBLEAF ? 0: config->sub_leaf;
+		const struct kvm_cpuid_entry2 *old =
+			__kvm_find_cpuid_entry2(kvm_tdx->cpuid, kvm_tdx->cpuid_nent,
+						config->leaf, index);
+		const struct kvm_cpuid_entry2 *new =
+			__kvm_find_cpuid_entry2(e2, nent, config->leaf, index);
+
+		if (!!old != !!new)
+			return -EINVAL;
+		if (!old && !new)

arch/x86/kvm/vmx/tdx.c int tdx_vcpu_create(struct kvm_vcpu *vcpu) · line 650

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			continue;
+
+		if ((old->eax ^ new->eax) & config->eax ||
+		    (old->ebx ^ new->ebx) & config->ebx ||
+		    (old->ecx ^ new->ecx) & config->ecx ||
+		    (old->edx ^ new->edx) & config->edx)
+			return -EINVAL;
+	}
+	return 0;
+}

Guess checkpatch.pl will complain about the length of lines above.

Quoted 48 lines
arch/x86/kvm/vmx/tdx.c +10 -2
+
 void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 {
 	struct vcpu_tdx *tdx = to_tdx(vcpu);
@@ -2003,10 +2044,12 @@ static void setup_tdparams_eptp_controls(struct kvm_cpuid2 *cpuid, struct td_par
 	}
 }
 
-static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
+static void setup_tdparams_cpuids(struct kvm *kvm,
+				  const struct tdsysinfo_struct *tdsysinfo,
 				  struct kvm_cpuid2 *cpuid,
 				  struct td_params *td_params)
 {
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
 	int i;
 
 	/*
@@ -2014,6 +2057,7 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 	 * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
 	 * It's assumed that td_params was zeroed.
 	 */
+	kvm_tdx->cpuid_nent = 0;
 	for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
 		const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
 		/* TDX_CPUID_NO_SUBLEAF in TDX CPUID_CONFIG means index = 0. */
@@ -2035,6 +2079,10 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 		value->ebx = entry->ebx & config->ebx;
 		value->ecx = entry->ecx & config->ecx;
 		value->edx = entry->edx & config->edx;
+
+		/* Remember the setting to check for KVM_SET_CPUID2. */
+		kvm_tdx->cpuid[kvm_tdx->cpuid_nent] = *entry;
+		kvm_tdx->cpuid_nent++;
 	}
 }
 
@@ -2130,7 +2178,7 @@ static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
 	td_params->tsc_frequency = TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
 
 	setup_tdparams_eptp_controls(cpuid, td_params);
-	setup_tdparams_cpuids(tdsysinfo, cpuid, td_params);
+	setup_tdparams_cpuids(kvm, tdsysinfo, cpuid, td_params);
 	ret = setup_tdparams_xfam(cpuid, td_params);
 	if (ret)
 		return ret;
@@ -2332,6 +2380,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 	if (cmd->flags)

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +5 -0
 		return -EINVAL;
 
+	kvm_tdx->cpuid = kzalloc(sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
+				 GFP_KERNEL);
+	if (!kvm_tdx->cpuid)
+		return -ENOMEM;
+
 	init_vm = kzalloc(sizeof(*init_vm) +
 			  sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
 			  GFP_KERNEL);

kfree(kvm_tdx->cpuid) is required in the error handling path of tdx_td_init().

Quoted 40 lines
arch/x86/kvm/vmx/tdx.h +7 -0
index ff35cd8409d9..846700a9c698 100644
@@ -32,6 +32,13 @@ struct kvm_tdx {
 	atomic_t tdh_mem_track;
 
 	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;
 };
 
 union tdx_exit_reason {
arch/x86/kvm/vmx/x86_ops.h +4 -0
index b339be6b5300..e2f44f754609 100644
@@ -163,6 +163,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);
@@ -211,6 +213,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) {}
#141 lore raw

Re: [PATCH v14 111/113] RFC: KVM: x86, TDX: Add check for setting CPUID

Quoted 14 lines · Zhi Wang
Quoted 10 lines · On Sun, 28 May 2023 21:20:33 -0700 [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a hook to setting CPUID for additional consistency check of KVM_SET_CPUID2.

Because intel TDX or AMD SNP has restriction on the value of cpuid. Some value can't be changed after boot. Some can be only set at the VM creation time and can't be changed later. Check if the new values are consistent with the old values.

Quoted 4 lines

Thanks for addressing this from the discussion. The structure looks good to me. I was thinking if the patch should be separated into two parts. One is the common part so that AMD folks can include it in their patch series. Another one is TDX callback which builds on top of the common-part patch.

OK.

Quoted 63 lines
Quoted 43 lines
---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  1 +
 arch/x86/kvm/cpuid.c               | 10 ++++++
 arch/x86/kvm/cpuid.h               |  2 ++
 arch/x86/kvm/vmx/main.c            | 10 ++++++
 arch/x86/kvm/vmx/tdx.c             | 57 ++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.h             |  7 ++++
 arch/x86/kvm/vmx/x86_ops.h         |  4 +++
 8 files changed, 90 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index c1a4d29cf4fa..5faa13a31f59 100644
@@ -20,6 +20,7 @@ KVM_X86_OP(hardware_disable)
 KVM_X86_OP(hardware_unsetup)
 KVM_X86_OP_OPTIONAL_RET0(offline_cpu)
 KVM_X86_OP(has_emulated_msr)
+KVM_X86_OP_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 68ddb0da31e0..4efd9770963c 100644
@@ -1588,6 +1588,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 +0 -0
index 0142a73034c4..ef7c361883d7 100644

arch/x86/kvm/cpuid.c static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, · line 421

Quoted 8 lines
arch/x86/kvm/cpuid.c +3 -0
@@ -414,6 +414,9 @@ static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,
 	}
 
 	r = kvm_check_cpuid(vcpu, e2, nent);
+	if (r)
+		return r;
+	r = static_call(kvm_x86_vcpu_check_cpuid)(vcpu, e2, nent);
 	if (r)
 		return r;

It would be nice to move the static_call into the kvm_check_cpuid() as it is part of the process of checking cpuid. It is good enough for now as kvm_check_cpuid() only has one caller. Think if more caller of kvm_check_cpuid() shows up in the future, they need to move it into kvm_check_cpuid anyway.

Quoted 5 lines
arch/x86/kvm/cpuid.c +0 -0
@@ -1364,6 +1367,13 @@ int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid,
 	return r;
 }
 
Quoted 12 lines

arch/x86/kvm/cpuid.c int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid, · line 1376

Quoted 7 lines
arch/x86/kvm/cpuid.c +7 -0
+struct kvm_cpuid_entry2 *__kvm_find_cpuid_entry2(
+	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index)
+{
+	return cpuid_entry2_find(entries, nent, function, index);
+}
+EXPORT_SYMBOL_GPL(__kvm_find_cpuid_entry2);
+

If evetually, we have to open kvm_cpuid2 when searching the cpuid entries, I would suggest to open it in kvm_find_cpuid_entry2() instead of introducing a new __kvm_find_cpuid_entry2(). It would be nice to let kvm_find_cpuid_entry2 () to take entreis and nent in the previou patch.

Makes sense. Consolidated kvm_find_cpuid_entry2(
struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index).

Quoted 3 lines
Quoted 3 lines
arch/x86/kvm/cpuid.c +0 -0
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2( struct kvm_cpuid2 *cpuid,
 						u32 function, u32 index)
 {

... snip...

Quoted 31 lines
Quoted 31 lines
arch/x86/kvm/cpuid.c +31 -0
+int tdx_vcpu_check_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, int nent)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	const struct tdsysinfo_struct *tdsysinfo;
+	int i;
+
+	tdsysinfo = tdx_get_sysinfo();
+	if (!tdsysinfo)
+		return -ENOTSUPP;
+
+	/*
+	 * Simple check that new cpuid is consistent with created one.
+	 * For simplicity, only trivial check.  Don't try comprehensive checks
+	 * with the cpuid virtualization table in the TDX module spec.
+	 */
+	for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
+		const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
+		u32 index = config->sub_leaf == TDX_CPUID_NO_SUBLEAF ? 0: config->sub_leaf;
+		const struct kvm_cpuid_entry2 *old =
+			__kvm_find_cpuid_entry2(kvm_tdx->cpuid, kvm_tdx->cpuid_nent,
+						config->leaf, index);
+		const struct kvm_cpuid_entry2 *new =
+			__kvm_find_cpuid_entry2(e2, nent, config->leaf, index);
+
+		if (!!old != !!new)
+			return -EINVAL;
+		if (!old && !new)
+			continue;
+
+		if ((old->eax ^ new->eax) & config->eax ||
+		    (old->ebx ^ new->ebx) & config->ebx ||
Quoted 8 lines

arch/x86/kvm/cpuid.c

Quoted 6 lines
arch/x86/kvm/cpuid.c +6 -0
+		    (old->ecx ^ new->ecx) & config->ecx ||
+		    (old->edx ^ new->edx) & config->edx)
+			return -EINVAL;
+	}
+	return 0;
+}

Guess checkpatch.pl will complain about the length of lines above.

By default, the line is 100 chars. Not 80.

Quoted 50 lines
Quoted 50 lines
arch/x86/kvm/cpuid.c +10 -2
+
 void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 {
 	struct vcpu_tdx *tdx = to_tdx(vcpu);
@@ -2003,10 +2044,12 @@ static void setup_tdparams_eptp_controls(struct kvm_cpuid2 *cpuid, struct td_par
 	}
 }
 
-static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
+static void setup_tdparams_cpuids(struct kvm *kvm,
+				  const struct tdsysinfo_struct *tdsysinfo,
 				  struct kvm_cpuid2 *cpuid,
 				  struct td_params *td_params)
 {
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
 	int i;
 
 	/*
@@ -2014,6 +2057,7 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 	 * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
 	 * It's assumed that td_params was zeroed.
 	 */
+	kvm_tdx->cpuid_nent = 0;
 	for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
 		const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
 		/* TDX_CPUID_NO_SUBLEAF in TDX CPUID_CONFIG means index = 0. */
@@ -2035,6 +2079,10 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 		value->ebx = entry->ebx & config->ebx;
 		value->ecx = entry->ecx & config->ecx;
 		value->edx = entry->edx & config->edx;
+
+		/* Remember the setting to check for KVM_SET_CPUID2. */
+		kvm_tdx->cpuid[kvm_tdx->cpuid_nent] = *entry;
+		kvm_tdx->cpuid_nent++;
 	}
 }
 
@@ -2130,7 +2178,7 @@ static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
 	td_params->tsc_frequency = TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
 
 	setup_tdparams_eptp_controls(cpuid, td_params);
-	setup_tdparams_cpuids(tdsysinfo, cpuid, td_params);
+	setup_tdparams_cpuids(kvm, tdsysinfo, cpuid, td_params);
 	ret = setup_tdparams_xfam(cpuid, td_params);
 	if (ret)
 		return ret;
@@ -2332,6 +2380,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 	if (cmd->flags)
 		return -EINVAL;
 
Quoted 10 lines

arch/x86/kvm/cpuid.c static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 2390

Quoted 8 lines
arch/x86/kvm/cpuid.c +5 -0
+	kvm_tdx->cpuid = kzalloc(sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
+				 GFP_KERNEL);
+	if (!kvm_tdx->cpuid)
+		return -ENOMEM;
+
 	init_vm = kzalloc(sizeof(*init_vm) +
 			  sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
 			  GFP_KERNEL);

kfree(kvm_tdx->cpuid) is required in the error handling path of tdx_td_init().

No need. tdx_vm_free() frees it. Not here.

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

Re: [PATCH v14 111/113] RFC: KVM: x86, TDX: Add check for setting CPUID

Quoted 149 lines · On Sat, 3 Jun 2023 11:02:35 -0700 Isaku Yamahata <[email protected]>…
Quoted 14 lines · Zhi Wang
Quoted 10 lines · On Sun, 28 May 2023 21:20:33 -0700 [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a hook to setting CPUID for additional consistency check of KVM_SET_CPUID2.

Because intel TDX or AMD SNP has restriction on the value of cpuid. Some value can't be changed after boot. Some can be only set at the VM creation time and can't be changed later. Check if the new values are consistent with the old values.

Quoted 4 lines

Thanks for addressing this from the discussion. The structure looks good to me. I was thinking if the patch should be separated into two parts. One is the common part so that AMD folks can include it in their patch series. Another one is TDX callback which builds on top of the common-part patch.

OK.

Quoted 63 lines
Quoted 43 lines
---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  1 +
 arch/x86/kvm/cpuid.c               | 10 ++++++
 arch/x86/kvm/cpuid.h               |  2 ++
 arch/x86/kvm/vmx/main.c            | 10 ++++++
 arch/x86/kvm/vmx/tdx.c             | 57 ++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.h             |  7 ++++
 arch/x86/kvm/vmx/x86_ops.h         |  4 +++
 8 files changed, 90 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index c1a4d29cf4fa..5faa13a31f59 100644
@@ -20,6 +20,7 @@ KVM_X86_OP(hardware_disable)
 KVM_X86_OP(hardware_unsetup)
 KVM_X86_OP_OPTIONAL_RET0(offline_cpu)
 KVM_X86_OP(has_emulated_msr)
+KVM_X86_OP_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 68ddb0da31e0..4efd9770963c 100644
@@ -1588,6 +1588,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 +0 -0
index 0142a73034c4..ef7c361883d7 100644

arch/x86/kvm/cpuid.c static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, · line 421

Quoted 8 lines
arch/x86/kvm/cpuid.c +3 -0
@@ -414,6 +414,9 @@ static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,
 	}
 
 	r = kvm_check_cpuid(vcpu, e2, nent);
+	if (r)
+		return r;
+	r = static_call(kvm_x86_vcpu_check_cpuid)(vcpu, e2, nent);
 	if (r)
 		return r;

It would be nice to move the static_call into the kvm_check_cpuid() as it is part of the process of checking cpuid. It is good enough for now as kvm_check_cpuid() only has one caller. Think if more caller of kvm_check_cpuid() shows up in the future, they need to move it into kvm_check_cpuid anyway.

Quoted 5 lines
arch/x86/kvm/cpuid.c +0 -0
@@ -1364,6 +1367,13 @@ int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid,
 	return r;
 }
 
Quoted 12 lines

arch/x86/kvm/cpuid.c int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid, · line 1376

Quoted 7 lines
arch/x86/kvm/cpuid.c +7 -0
+struct kvm_cpuid_entry2 *__kvm_find_cpuid_entry2(
+	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index)
+{
+	return cpuid_entry2_find(entries, nent, function, index);
+}
+EXPORT_SYMBOL_GPL(__kvm_find_cpuid_entry2);
+

If evetually, we have to open kvm_cpuid2 when searching the cpuid entries, I would suggest to open it in kvm_find_cpuid_entry2() instead of introducing a new __kvm_find_cpuid_entry2(). It would be nice to let kvm_find_cpuid_entry2 () to take entreis and nent in the previou patch.

Makes sense. Consolidated kvm_find_cpuid_entry2(
struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index).

Quoted 3 lines
Quoted 3 lines
arch/x86/kvm/cpuid.c +0 -0
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2( struct kvm_cpuid2 *cpuid,
 						u32 function, u32 index)
 {

... snip...

Quoted 31 lines
Quoted 31 lines
arch/x86/kvm/cpuid.c +31 -0
+int tdx_vcpu_check_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, int nent)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	const struct tdsysinfo_struct *tdsysinfo;
+	int i;
+
+	tdsysinfo = tdx_get_sysinfo();
+	if (!tdsysinfo)
+		return -ENOTSUPP;
+
+	/*
+	 * Simple check that new cpuid is consistent with created one.
+	 * For simplicity, only trivial check.  Don't try comprehensive checks
+	 * with the cpuid virtualization table in the TDX module spec.
+	 */
+	for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
+		const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
+		u32 index = config->sub_leaf == TDX_CPUID_NO_SUBLEAF ? 0: config->sub_leaf;
+		const struct kvm_cpuid_entry2 *old =
+			__kvm_find_cpuid_entry2(kvm_tdx->cpuid, kvm_tdx->cpuid_nent,
+						config->leaf, index);
+		const struct kvm_cpuid_entry2 *new =
+			__kvm_find_cpuid_entry2(e2, nent, config->leaf, index);
+
+		if (!!old != !!new)
+			return -EINVAL;
+		if (!old && !new)
+			continue;
+
+		if ((old->eax ^ new->eax) & config->eax ||
+		    (old->ebx ^ new->ebx) & config->ebx ||
Quoted 8 lines

arch/x86/kvm/cpuid.c

Quoted 6 lines
arch/x86/kvm/cpuid.c +6 -0
+		    (old->ecx ^ new->ecx) & config->ecx ||
+		    (old->edx ^ new->edx) & config->edx)
+			return -EINVAL;
+	}
+	return 0;
+}

Guess checkpatch.pl will complain about the length of lines above.

Quoted 2 lines

By default, the line is 100 chars. Not 80.

The reason I raised this up is because: It seems there are two different rules going on in this patch. One seems respecting the 80-columns limitation. E.g.

struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2( struct kvm_cpuid2 *cpuid,
u32 function, u32 index)

While this one respects a 100-columns rule different than others.

int tdx_vcpu_check_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, int nent)

Note that 80-columns rules are still in the kernel coding style guide[1].

It would be better to follow it.

[1] https://docs.kernel.org/process/coding-style.html

Quoted 63 lines
Quoted 51 lines
Quoted 51 lines
arch/x86/kvm/cpuid.c +10 -2
+
 void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 {
 	struct vcpu_tdx *tdx = to_tdx(vcpu);
@@ -2003,10 +2044,12 @@ static void setup_tdparams_eptp_controls(struct kvm_cpuid2 *cpuid, struct td_par
 	}
 }
 
-static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
+static void setup_tdparams_cpuids(struct kvm *kvm,
+				  const struct tdsysinfo_struct *tdsysinfo,
 				  struct kvm_cpuid2 *cpuid,
 				  struct td_params *td_params)
 {
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
 	int i;
 
 	/*
@@ -2014,6 +2057,7 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 	 * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
 	 * It's assumed that td_params was zeroed.
 	 */
+	kvm_tdx->cpuid_nent = 0;
 	for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
 		const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
 		/* TDX_CPUID_NO_SUBLEAF in TDX CPUID_CONFIG means index = 0. */
@@ -2035,6 +2079,10 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 		value->ebx = entry->ebx & config->ebx;
 		value->ecx = entry->ecx & config->ecx;
 		value->edx = entry->edx & config->edx;
+
+		/* Remember the setting to check for KVM_SET_CPUID2. */
+		kvm_tdx->cpuid[kvm_tdx->cpuid_nent] = *entry;
+		kvm_tdx->cpuid_nent++;
 	}
 }
 
@@ -2130,7 +2178,7 @@ static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
 	td_params->tsc_frequency = TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
 
 	setup_tdparams_eptp_controls(cpuid, td_params);
-	setup_tdparams_cpuids(tdsysinfo, cpuid, td_params);
+	setup_tdparams_cpuids(kvm, tdsysinfo, cpuid, td_params);
 	ret = setup_tdparams_xfam(cpuid, td_params);
 	if (ret)
 		return ret;
@@ -2332,6 +2380,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 	if (cmd->flags)
 		return -EINVAL;
 
Quoted 10 lines

arch/x86/kvm/cpuid.c static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 2390

Quoted 8 lines
arch/x86/kvm/cpuid.c +5 -0
+	kvm_tdx->cpuid = kzalloc(sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
+				 GFP_KERNEL);
+	if (!kvm_tdx->cpuid)
+		return -ENOMEM;
+
 	init_vm = kzalloc(sizeof(*init_vm) +
 			  sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
 			  GFP_KERNEL);

kfree(kvm_tdx->cpuid) is required in the error handling path of tdx_td_init().

Quoted 1 line

No need. tdx_vm_free() frees it. Not here.

From a perspective of correctness, Yes. But there seems different kinds of strategies of function error handling path going on in this patch series. Taking __tdx_td_init() as an example, tdx_vm_free() is immediately called in its error handling path. But, the error handling below the allocation of cpuid will be deferred to the late VM teardown path in this patch. I am confused of the strategy of common error handling path, what is the preferred error handling strategy? Deferring or immediate handling?

Second, it is not graceful to defer the error handling to the teardown path all the time even they seem work: 1) Readability. It looks like a problematic error handling at a first glance. 2) Error handling path and teardown path are for different purposes. Separating the concerns brings clearer code organization and better maintainability. 3) Testability, thinking about an error injection test for tdx_td_init(). Un-freed kvm_tdx->cpuid will look like a memory leaking in this case and needs to be noted as "free is in another function". It just makes the case more complicated.

Third, I believe a static code scanner will complain about it.

#26 lore raw

RE: [PATCH v14 011/113] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]
Quoted 78 lines · On Monday, May 29, 2023 12:19 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.

Export __seamcall and 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. Such SEAMCALLs flush cache lines (typically by movdir64b instruction), but some don't. Those that don't clear cache lines require the VMM to flush the cache lines to avoid cache line alias.

---
 arch/x86/include/asm/tdx.h       |   4 +
 arch/x86/kvm/vmx/tdx_ops.h       | 202
+++++++++++++++++++++++++++++++
 arch/x86/virt/vmx/tdx/seamcall.S |   2 +
 arch/x86/virt/vmx/tdx/tdx.h      |   3 -
 4 files changed, 208 insertions(+), 3 deletions(-)  create mode 100644

arch/x86/kvm/vmx/tdx_ops.h

arch/x86/include/asm/tdx.h index renamed from arch/x86/include/asm/tdx.h +0 -0

112a5b9bd5cd..6c01ab572c1f 100644

arch/x86/include/asm/tdx.h +0 -0
@@ -104,10 +104,14 @@ static inline long tdx_kvm_hypercall(unsigned int

nr, unsigned long p1, bool platform_tdx_enabled(void); int tdx_cpu_enable(void); int tdx_enable(void);

arch/x86/include/asm/tdx.h +2 -0
+u64 __seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+	       struct tdx_module_output *out);
 #else	/* !CONFIG_INTEL_TDX_HOST */
 static inline bool platform_tdx_enabled(void) { return false; }  static inline int

tdx_cpu_enable(void) { return -EINVAL; } static inline int tdx_enable(void) { return -EINVAL; }

arch/x86/include/asm/tdx.h +2 -0
+static inline u64 __seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			     struct tdx_module_output *out) { return

TDX_SEAMCALL_UD; };
#endif /* CONFIG_INTEL_TDX_HOST */

#endif /* !__ASSEMBLY__ */

arch/x86/kvm/vmx/tdx_ops.h new file +24 -0
new file mode 100644 index 000000000000..893cc6c25f3b
@@ -0,0 +1,202 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_OPS_H
+#define __KVM_X86_TDX_OPS_H
+
+#include <linux/compiler.h>
+
+#include <asm/cacheflush.h>
+#include <asm/asm.h>
+#include <asm/kvm_host.h>
+
+#include "tdx_errno.h"
+#include "tdx_arch.h"
+#include "x86.h"
+
+static inline u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			       struct tdx_module_output *out) {
+	u64 ret;
+
+	ret = __seamcall(op, rcx, rdx, r8, r9, out);
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {
+		/*
+		 * TDX requires VMXON or #UD.  In the case of reboot or

kexec,

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+		 * VMX is made off (VMXOFF) by kvm reboot notifier,
+		 * kvm_reboot(), while TDs are still running.  The callers

check

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

Quoted 2 lines
arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+		 * the returned error and complain.  Suppress it by returning 0.
+		 */

Curious how do the callers check the returned error when " Suppress it by returning 0" here.

Quoted 5 lines
arch/x86/kvm/vmx/tdx_ops.h new file +5 -0
+		kvm_spurious_fault();
+		return 0;
+	}
+	return ret;
+}
#143 lore raw

Re: [PATCH v14 111/113] RFC: KVM: x86, TDX: Add check for setting CPUID

In reply to Zhi Wang
Quoted 82 lines · Zhi Wang
Quoted 62 lines
Quoted 50 lines
Quoted 50 lines
(quoted diff) +10 -2
+
 void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 {
 	struct vcpu_tdx *tdx = to_tdx(vcpu);
@@ -2003,10 +2044,12 @@ static void setup_tdparams_eptp_controls(struct kvm_cpuid2 *cpuid, struct td_par
 	}
 }
 
-static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
+static void setup_tdparams_cpuids(struct kvm *kvm,
+				  const struct tdsysinfo_struct *tdsysinfo,
 				  struct kvm_cpuid2 *cpuid,
 				  struct td_params *td_params)
 {
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
 	int i;
 
 	/*
@@ -2014,6 +2057,7 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 	 * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
 	 * It's assumed that td_params was zeroed.
 	 */
+	kvm_tdx->cpuid_nent = 0;
 	for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
 		const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
 		/* TDX_CPUID_NO_SUBLEAF in TDX CPUID_CONFIG means index = 0. */
@@ -2035,6 +2079,10 @@ static void setup_tdparams_cpuids(const struct tdsysinfo_struct *tdsysinfo,
 		value->ebx = entry->ebx & config->ebx;
 		value->ecx = entry->ecx & config->ecx;
 		value->edx = entry->edx & config->edx;
+
+		/* Remember the setting to check for KVM_SET_CPUID2. */
+		kvm_tdx->cpuid[kvm_tdx->cpuid_nent] = *entry;
+		kvm_tdx->cpuid_nent++;
 	}
 }
 
@@ -2130,7 +2178,7 @@ static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
 	td_params->tsc_frequency = TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
 
 	setup_tdparams_eptp_controls(cpuid, td_params);
-	setup_tdparams_cpuids(tdsysinfo, cpuid, td_params);
+	setup_tdparams_cpuids(kvm, tdsysinfo, cpuid, td_params);
 	ret = setup_tdparams_xfam(cpuid, td_params);
 	if (ret)
 		return ret;
@@ -2332,6 +2380,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 	if (cmd->flags)
 		return -EINVAL;
 
Quoted 10 lines

Review static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd) · line 2390

Quoted 8 lines
(quoted diff) +5 -0
+	kvm_tdx->cpuid = kzalloc(sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
+				 GFP_KERNEL);
+	if (!kvm_tdx->cpuid)
+		return -ENOMEM;
+
 	init_vm = kzalloc(sizeof(*init_vm) +
 			  sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
 			  GFP_KERNEL);

kfree(kvm_tdx->cpuid) is required in the error handling path of tdx_td_init().

Quoted 1 line

No need. tdx_vm_free() frees it. Not here.

From a perspective of correctness, Yes. But there seems different kinds of strategies of function error handling path going on in this patch series. Taking __tdx_td_init() as an example, tdx_vm_free() is immediately called in its error handling path. But, the error handling below the allocation of cpuid will be deferred to the late VM teardown path in this patch. I am confused of the strategy of common error handling path, what is the preferred error handling strategy? Deferring or immediate handling?

Second, it is not graceful to defer the error handling to the teardown path all the time even they seem work: 1) Readability. It looks like a problematic error handling at a first glance. 2) Error handling path and teardown path are for different purposes. Separating the concerns brings clearer code organization and better maintainability. 3) Testability, thinking about an error injection test for tdx_td_init(). Un-freed kvm_tdx->cpuid will look like a memory leaking in this case and needs to be noted as "free is in another function". It just makes the case more complicated.

Quoted 1 line

Third, I believe a static code scanner will complain about it.

I noticed that it results in memory leak when KVM_TDX_INIT_VM after KVM_TDX_INIT_VM error. So I come up with the following to fix it with immediate handling.

arch/x86/kvm/vmx/tdx.c +14 -4
index d392262d8605..55cf07a72332 100644
@@ -3549,16 +3549,21 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
        if (cmd->flags)
                return -EINVAL;
 
+       WARN_ON_ONCE(kvm_tdx->cpuid);
        kvm_tdx->cpuid = kzalloc(sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
                                 GFP_KERNEL);
-       if (!kvm_tdx->cpuid)
-               return -ENOMEM;
+       if (!kvm_tdx->cpuid) {
+               ret = -ENOMEM;
+               goto out;
+       }
 
        init_vm = kzalloc(sizeof(*init_vm) +
                          sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
                          GFP_KERNEL);
-       if (!init_vm)
-               return -ENOMEM;
+       if (!init_vm) {
+               ret = -ENOMEM;
+               goto out;
+       }
        if (copy_from_user(init_vm, (void __user *)cmd->data, sizeof(*init_vm))) {
                ret = -EFAULT;
                goto out;
@@ -3604,6 +3609,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 
 out:
        /* kfree() accepts NULL. */
+       if (ret) {
+               kfree(kvm_tdx->cpuid);
+               kvm_tdx->cpuid = NULL;
+               kvm_tdx->cpuid_nent = 0;
+       }
        kfree(init_vm);
        kfree(td_params);
        return ret;
Signature · 1 line
Isaku Yamahata <[email protected]>
#10 lore raw

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to [email protected]
Quoted 28 lines · Isaku
arch/x86/kvm/vmx/tdx.c new file +28 -0
+static void __init vmx_tdx_on(void *info)
+{
+       atomic_t *err = info;
+       int r;
+
+       r = vmx_hardware_enable();
+       if (!r)
+	       r = tdx_cpu_enable();
+       if (r)
+	       atomic_set(err, r);
+}
+
+static void __init vmx_off(void *unused)
+{
+       vmx_hardware_disable();
+}
+
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	atomic_t err = ATOMIC_INIT(0);
+	int r = 0;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	/* tdx_enable() in tdx_module_setup() requires cpus lock. */

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c new file +10 -0
+	cpus_read_lock();
+	on_each_cpu(vmx_tdx_on, &err, true);	/* TDX requires vmxon. */
+	r = atomic_read(&err);
+	if (!r)
+		r = tdx_module_setup();
+	on_each_cpu(vmx_off, NULL, true);
+	cpus_read_unlock();
+
+	return r;
+}

As we discussed in v13, this code doesn't track which CPUs have run vmx_hardware_enable() successfully. Thus if ...

	on_each_cpu(vmx_tdx_on, &err, true);	/* TDX requires vmxon. */

... fails on some cpu due to whatever reason, in ...

	on_each_cpu(vmx_off, NULL, true);

... vmx_hardware_disable() will fail to do VMXOFF for those cpus that haven't done VMXON successfully yet, resulting in BUG_ON(!kvm_rebooting) being triggered in kvm_spurious_fault().

We need a per-cpu flag to track whether cpu has done VMXON successfully.

#52 lore raw

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

In reply to [email protected]
Quoted 49 lines · On Sun, May 28, 2023 at 09:19:13PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware uses the bit 63 as NX for present SPTE and ignored for non-present SPTE; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

---
 arch/x86/kvm/mmu/mmu.c         | 20 +++++++++++++++-----
 arch/x86/kvm/mmu/paging_tmpl.h |  2 +-
 arch/x86/kvm/mmu/spte.h        |  2 ++
 arch/x86/kvm/mmu/tdp_mmu.c     | 14 +++++++-------
 4 files changed, 25 insertions(+), 13 deletions(-)
arch/x86/kvm/mmu/mmu.c +3 -3
index dc2b9a2f717c..1b6fd4434e96 100644
@@ -576,9 +576,9 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
 
 	if (!is_shadow_present_pte(old_spte) ||
 	    !spte_has_volatile_bits(old_spte))
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
 	else
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
 
 	if (!is_shadow_present_pte(old_spte))
 		return old_spte;
@@ -612,7 +612,7 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
  */
 static void mmu_spte_clear_no_track(u64 *sptep)
 {
-	__update_clear_spte_fast(sptep, 0ull);
+	__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
 }
 
 static u64 mmu_spte_get_lockless(u64 *sptep)

arch/x86/kvm/mmu/mmu.c static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1973

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +2 -1
@@ -1969,7 +1969,8 @@ static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 
 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
 {
-	if (!sp->spt[i])
+	/* sp->spt[i] has initial value of shadow page table allocation */
+	if (sp->spt[i] != SHADOW_NONPRESENT_VALUE)

This should be "sp->spt[i] == SHADOW_NONPRESENT_VALUE" ? Looks all present spt[i] are skipped without sync for shadow paging.

Quoted 103 lines
arch/x86/kvm/mmu/mmu.c +10 -1
 		return 0;
 
 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
@@ -6120,7 +6121,16 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
 
-	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
+	/*
+	 * When X86_64, initial SEPT entries are initialized with
+	 * SHADOW_NONPRESENT_VALUE.  Otherwise zeroed.  See
+	 * mmu_memory_cache_alloc_obj().
+	 */
+	if (IS_ENABLED(CONFIG_X86_64))
+		vcpu->arch.mmu_shadow_page_cache.init_value =
+			SHADOW_NONPRESENT_VALUE;
+	if (!vcpu->arch.mmu_shadow_page_cache.init_value)
+		vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
 
 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
index 0662e0278e70..ef8124bd2f11 100644
@@ -892,7 +892,7 @@ static int FNAME(sync_spte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int
 	gpa_t pte_gpa;
 	gfn_t gfn;
 
-	if (WARN_ON_ONCE(!sp->spt[i]))
+	if (WARN_ON_ONCE(sp->spt[i] == SHADOW_NONPRESENT_VALUE))
 		return 0;
 
 	first_pte_gpa = FNAME(get_level1_sp_gpa)(sp);
arch/x86/kvm/mmu/spte.h +2 -0
index 1279db2eab44..a99eb7d4ae5d 100644
@@ -148,6 +148,8 @@ static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11);
 
 #define MMIO_SPTE_GEN_MASK		GENMASK_ULL(MMIO_SPTE_GEN_LOW_BITS + MMIO_SPTE_GEN_HIGH_BITS - 1, 0)
 
+#define SHADOW_NONPRESENT_VALUE	0ULL
+
 extern u64 __read_mostly shadow_host_writable_mask;
 extern u64 __read_mostly shadow_mmu_writable_mask;
 extern u64 __read_mostly shadow_nx_mask;
arch/x86/kvm/mmu/tdp_mmu.c +7 -8
index 3000ef6d79ea..ddd995885dd3 100644
@@ -627,7 +627,7 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
 	 * here since the SPTE is going from non-present to non-present.  Use
 	 * the raw write helper to avoid an unnecessary check on volatile bits.
 	 */
-	__kvm_tdp_mmu_write_spte(iter->sptep, 0);
+	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
 
 	return 0;
 }
@@ -764,8 +764,8 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, struct kvm_mmu_page *root,
 			continue;
 
 		if (!shared)
-			tdp_mmu_iter_set_spte(kvm, &iter, 0);
-		else if (tdp_mmu_set_spte_atomic(kvm, &iter, 0))
+			tdp_mmu_iter_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+		else if (tdp_mmu_set_spte_atomic(kvm, &iter, SHADOW_NONPRESENT_VALUE))
 			goto retry;
 	}
 }
@@ -821,8 +821,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
 	if (WARN_ON_ONCE(!is_shadow_present_pte(old_spte)))
 		return false;
 
-	tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte, 0,
-			 sp->gfn, sp->role.level + 1);
+	tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
+			 SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1);
 
 	return true;
 }
@@ -856,7 +856,7 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 		    !is_last_spte(iter.old_spte, iter.level))
 			continue;
 
-		tdp_mmu_iter_set_spte(kvm, &iter, 0);
+		tdp_mmu_iter_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
 		flush = true;
 	}
 
@@ -1250,7 +1250,7 @@ static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
 	 * invariant that the PFN of a present * leaf SPTE can never change.
 	 * See handle_changed_spte().
 	 */
-	tdp_mmu_iter_set_spte(kvm, iter, 0);
+	tdp_mmu_iter_set_spte(kvm, iter, SHADOW_NONPRESENT_VALUE);
 
 	if (!pte_write(range->pte)) {
 		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
--

2.25.1

#54 lore raw

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

In reply to [email protected]
Quoted 49 lines · On 5/29/2023 12:19 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware uses the bit 63 as NX for present SPTE and ignored for non-present SPTE; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

---
  arch/x86/kvm/mmu/mmu.c         | 20 +++++++++++++++-----
  arch/x86/kvm/mmu/paging_tmpl.h |  2 +-
  arch/x86/kvm/mmu/spte.h        |  2 ++
  arch/x86/kvm/mmu/tdp_mmu.c     | 14 +++++++-------
  4 files changed, 25 insertions(+), 13 deletions(-)
arch/x86/kvm/mmu/mmu.c +3 -3
index dc2b9a2f717c..1b6fd4434e96 100644
@@ -576,9 +576,9 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
 
  	if (!is_shadow_present_pte(old_spte) ||
  	    !spte_has_volatile_bits(old_spte))
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
  	else
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
 
  	if (!is_shadow_present_pte(old_spte))
  		return old_spte;
@@ -612,7 +612,7 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
   */
  static void mmu_spte_clear_no_track(u64 *sptep)
  {
-	__update_clear_spte_fast(sptep, 0ull);
+	__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
  }
 
  static u64 mmu_spte_get_lockless(u64 *sptep)

arch/x86/kvm/mmu/mmu.c static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1973

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +2 -1
@@ -1969,7 +1969,8 @@ static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 
  static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
  {
-	if (!sp->spt[i])
+	/* sp->spt[i] has initial value of shadow page table allocation */
+	if (sp->spt[i] != SHADOW_NONPRESENT_VALUE)

this condition should be "sp->spt[i] == SHADOW_NONPRESENT_VALUE"?

I found this cause the bug of  "guest launch failure with EPT disable".

Quoted 100 lines
arch/x86/kvm/mmu/mmu.c +10 -1
  		return 0;
 
  	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
@@ -6120,7 +6121,16 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
  	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
  	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
 
-	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
+	/*
+	 * When X86_64, initial SEPT entries are initialized with
+	 * SHADOW_NONPRESENT_VALUE.  Otherwise zeroed.  See
+	 * mmu_memory_cache_alloc_obj().
+	 */
+	if (IS_ENABLED(CONFIG_X86_64))
+		vcpu->arch.mmu_shadow_page_cache.init_value =
+			SHADOW_NONPRESENT_VALUE;
+	if (!vcpu->arch.mmu_shadow_page_cache.init_value)
+		vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
 
  	vcpu->arch.mmu = &vcpu->arch.root_mmu;
  	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
index 0662e0278e70..ef8124bd2f11 100644
@@ -892,7 +892,7 @@ static int FNAME(sync_spte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int
  	gpa_t pte_gpa;
  	gfn_t gfn;
 
-	if (WARN_ON_ONCE(!sp->spt[i]))
+	if (WARN_ON_ONCE(sp->spt[i] == SHADOW_NONPRESENT_VALUE))
  		return 0;
 
  	first_pte_gpa = FNAME(get_level1_sp_gpa)(sp);
arch/x86/kvm/mmu/spte.h +2 -0
index 1279db2eab44..a99eb7d4ae5d 100644
@@ -148,6 +148,8 @@ static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11);
 
  #define MMIO_SPTE_GEN_MASK		GENMASK_ULL(MMIO_SPTE_GEN_LOW_BITS + MMIO_SPTE_GEN_HIGH_BITS - 1, 0)
 
+#define SHADOW_NONPRESENT_VALUE	0ULL
+
  extern u64 __read_mostly shadow_host_writable_mask;
  extern u64 __read_mostly shadow_mmu_writable_mask;
  extern u64 __read_mostly shadow_nx_mask;
arch/x86/kvm/mmu/tdp_mmu.c +7 -7
index 3000ef6d79ea..ddd995885dd3 100644
@@ -627,7 +627,7 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
  	 * here since the SPTE is going from non-present to non-present.  Use
  	 * the raw write helper to avoid an unnecessary check on volatile bits.
  	 */
-	__kvm_tdp_mmu_write_spte(iter->sptep, 0);
+	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
 
  	return 0;
  }
@@ -764,8 +764,8 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, struct kvm_mmu_page *root,
  			continue;
 
  		if (!shared)
-			tdp_mmu_iter_set_spte(kvm, &iter, 0);
-		else if (tdp_mmu_set_spte_atomic(kvm, &iter, 0))
+			tdp_mmu_iter_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+		else if (tdp_mmu_set_spte_atomic(kvm, &iter, SHADOW_NONPRESENT_VALUE))
  			goto retry;
  	}
  }
@@ -821,8 +821,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
  	if (WARN_ON_ONCE(!is_shadow_present_pte(old_spte)))
  		return false;
 
-	tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte, 0,
-			 sp->gfn, sp->role.level + 1);
+	tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
+			 SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1);
 
  	return true;
  }
@@ -856,7 +856,7 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
  		    !is_last_spte(iter.old_spte, iter.level))
  			continue;
 
-		tdp_mmu_iter_set_spte(kvm, &iter, 0);
+		tdp_mmu_iter_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
  		flush = true;
  	}
 
@@ -1250,7 +1250,7 @@ static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
  	 * invariant that the PFN of a present * leaf SPTE can never change.
  	 * See handle_changed_spte().
  	 */
-	tdp_mmu_iter_set_spte(kvm, iter, 0);
+	tdp_mmu_iter_set_spte(kvm, iter, SHADOW_NONPRESENT_VALUE);
 
  	if (!pte_write(range->pte)) {
  		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
#53 lore raw

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

In reply to Yuan Yao
Quoted 51 lines · Yuan Yao
Quoted 50 lines · On Sun, May 28, 2023 at 09:19:13PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware uses the bit 63 as NX for present SPTE and ignored for non-present SPTE; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

---
 arch/x86/kvm/mmu/mmu.c         | 20 +++++++++++++++-----
 arch/x86/kvm/mmu/paging_tmpl.h |  2 +-
 arch/x86/kvm/mmu/spte.h        |  2 ++
 arch/x86/kvm/mmu/tdp_mmu.c     | 14 +++++++-------
 4 files changed, 25 insertions(+), 13 deletions(-)
arch/x86/kvm/mmu/mmu.c +3 -3
index dc2b9a2f717c..1b6fd4434e96 100644
@@ -576,9 +576,9 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
 
 	if (!is_shadow_present_pte(old_spte) ||
 	    !spte_has_volatile_bits(old_spte))
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
 	else
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
 
 	if (!is_shadow_present_pte(old_spte))
 		return old_spte;
@@ -612,7 +612,7 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
  */
 static void mmu_spte_clear_no_track(u64 *sptep)
 {
-	__update_clear_spte_fast(sptep, 0ull);
+	__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
 }
 
 static u64 mmu_spte_get_lockless(u64 *sptep)
@@ -1969,7 +1969,8 @@ static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) · line 1973

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +2 -1
 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
 {
-	if (!sp->spt[i])
+	/* sp->spt[i] has initial value of shadow page table allocation */
+	if (sp->spt[i] != SHADOW_NONPRESENT_VALUE)

This should be "sp->spt[i] == SHADOW_NONPRESENT_VALUE" ? Looks all present spt[i] are skipped without sync for shadow paging.

Oop, you're right. Will fix it.

Thanks,

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

Re: [PATCH v14 111/113] RFC: KVM: x86, TDX: Add check for setting CPUID

In reply to [email protected]
Quoted 9 lines · On Sun, 2023-05-28 at 21:20 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a hook to setting CPUID for additional consistency check of KVM_SET_CPUID2.

Because intel TDX or AMD SNP has restriction on the value of cpuid. Some value can't be changed after boot. Some can be only set at the VM creation time and can't be changed later. Check if the new values are consistent with the old values.

You might want to use some grammar tool to check against the changelog.

Also, personally I think it's better to briefly mention why we choose this design but not another (e.g., why we just don't make KVM remember all CPUIDs in TDH.MNG.INIT and simply ignores/rejects further KVM_SET_CPUID2). It would be helpful for the reviewer, or some git blamer in the future.

And why this patch is placed at the very bottom of this series? This logic should belong to TD creation part which should be at a relative earlier position in this series.

[...]

arch/x86/kvm/vmx/tdx.h struct kvm_tdx { · line 41

Quoted 11 lines
arch/x86/kvm/vmx/tdx.h +7 -0
@@ -32,6 +32,13 @@ struct kvm_tdx {
 	atomic_t tdh_mem_track;
 
 	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;

Since these CPUIDs may only be part of the vcpu's CPUIDs, you may want a more specific name, for instance, consistent_cpuid?

Also if you want this be common to AMD, then perhaps the comment should be improved too to be more generic.

#11 lore raw

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Huang, Kai
Quoted 47 lines · Kai
Quoted 28 lines · Isaku
(quoted diff) +28 -0
+static void __init vmx_tdx_on(void *info)
+{
+       atomic_t *err = info;
+       int r;
+
+       r = vmx_hardware_enable();
+       if (!r)
+	       r = tdx_cpu_enable();
+       if (r)
+	       atomic_set(err, r);
+}
+
+static void __init vmx_off(void *unused)
+{
+       vmx_hardware_disable();
+}
+
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	atomic_t err = ATOMIC_INIT(0);
+	int r = 0;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	/* tdx_enable() in tdx_module_setup() requires cpus lock. */

Review

Quoted 10 lines
(quoted diff) +10 -0
+	cpus_read_lock();
+	on_each_cpu(vmx_tdx_on, &err, true);	/* TDX requires vmxon. */
+	r = atomic_read(&err);
+	if (!r)
+		r = tdx_module_setup();
+	on_each_cpu(vmx_off, NULL, true);
+	cpus_read_unlock();
+
+	return r;
+}

As we discussed in v13, this code doesn't track which CPUs have run vmx_hardware_enable() successfully. Thus if ...

	on_each_cpu(vmx_tdx_on, &err, true);	/* TDX requires vmxon. */

... fails on some cpu due to whatever reason, in ...

Quoted 7 lines
	on_each_cpu(vmx_off, NULL, true);

... vmx_hardware_disable() will fail to do VMXOFF for those cpus that haven't done VMXON successfully yet, resulting in BUG_ON(!kvm_rebooting) being triggered in kvm_spurious_fault().

We need a per-cpu flag to track whether cpu has done VMXON successfully.

Thanks for pointing it out. The following is the fix.

arch/x86/kvm/vmx/tdx.c +30 -9
index 8a1d0755d275..b0d3f646afb1 100644
@@ -4499,26 +4499,39 @@ u64 tdx_non_arch_field_switch(u64 field)
 	}
 }
 
-static void __init vmx_tdx_on(void *info)
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t *err;
+};
+
+static void __init vmx_tdx_on(void *_vmx_tdx_on)
 {
-	atomic_t *err = info;
+	struct vmx_tdx_enabled *vmx_tdx = _vmx_tdx_on;
 	int r;
 
 	r = vmx_hardware_enable();
-	if (!r)
+	if (!r) {
+		cpumask_set_cpu(smp_processor_id(), vmx_tdx->vmx_enabled);
 		r = tdx_cpu_enable();
+	}
 	if (r)
-		atomic_set(err, r);
+		atomic_set(vmx_tdx->err, r);
 }
 
-static void __init vmx_off(void *unused)
+static void __init vmx_off(void *_vmx_enabled)
 {
-	vmx_hardware_disable();
+	cpumask_var_t vmx_enabled = *(cpumask_var_t *)_vmx_enabled;
+
+	if (cpumask_test_cpu(smp_processor_id(), vmx_enabled))
+		vmx_hardware_disable();
 }
 
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 {
 	atomic_t err = ATOMIC_INIT(0);
+	struct vmx_tdx_enabled vmx_tdx = {
+		.err = &err,
+	};
 	int max_pkgs;
 	int r = 0;
 	int i;
@@ -4582,6 +4595,11 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 	for (i = 0; i < max_pkgs; i++)
 		mutex_init(&tdx_mng_key_config_lock[i]);
 
+	if (!zalloc_cpumask_var(&vmx_tdx.vmx_enabled, GFP_KERNEL)) {
+		r = -ENOMEM;
+		goto out;
+	}
+
 	/* tdx_enable() in tdx_module_setup() requires cpus lock. */
 	cpus_read_lock();
 	/*
@@ -4592,12 +4610,15 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 	 */
 	if (!cpumask_equal(cpu_online_mask, cpu_present_mask))
 		pr_warn("The old TDX module requires all present CPUs to be online to initialize.\n");
-	on_each_cpu(vmx_tdx_on, &err, true);	/* TDX requires vmxon. */
-	r = atomic_read(&err);
+	on_each_cpu(vmx_tdx_on, &vmx_tdx, true);	/* TDX requires vmxon. */
+	r = atomic_read(vmx_tdx.err);
 	if (!r)
 		r = tdx_module_setup();
-	on_each_cpu(vmx_off, NULL, true);
+	else
+		r = -EIO;
+	on_each_cpu(vmx_off, vmx_tdx.vmx_enabled, true);
 	cpus_read_unlock();
+	free_cpumask_var(vmx_tdx.vmx_enabled);
 	if (r)
 		goto out;
 
Signature · 1 line
Isaku Yamahata <[email protected]>
#27 lore raw

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

In reply to Wang, Wei W
Quoted 30 lines · Wei W
Quoted 30 lines
arch/x86/kvm/vmx/tdx_ops.h new file +24 -0
new file mode 100644 index 000000000000..893cc6c25f3b
@@ -0,0 +1,202 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_OPS_H
+#define __KVM_X86_TDX_OPS_H
+
+#include <linux/compiler.h>
+
+#include <asm/cacheflush.h>
+#include <asm/asm.h>
+#include <asm/kvm_host.h>
+
+#include "tdx_errno.h"
+#include "tdx_arch.h"
+#include "x86.h"
+
+static inline u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			       struct tdx_module_output *out) {
+	u64 ret;
+
+	ret = __seamcall(op, rcx, rdx, r8, r9, out);
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {
+		/*
+		 * TDX requires VMXON or #UD.  In the case of reboot or

kexec,

Quoted 8 lines

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

Quoted 5 lines
arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+		 * VMX is made off (VMXOFF) by kvm reboot notifier,
+		 * kvm_reboot(), while TDs are still running.  The callers

check

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+		 * the returned error and complain.  Suppress it by returning 0.
+		 */

Curious how do the callers check the returned error when " Suppress it by returning 0" here.

It doesn't make sense for the caller to check the error and warn when kvm_rebooting = true.
Let's make it "return kvm_rebooting ? 0 : ret;" instread of "return 0;". Does it make sense?

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

RE: [PATCH v14 011/113] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 20 lines · Isaku Yamahata
Quoted 9 lines · Wei W
Quoted 9 lines
arch/x86/kvm/vmx/tdx_ops.h new file +8 -0
+static inline u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			       struct tdx_module_output *out) {
+	u64 ret;
+
+	ret = __seamcall(op, rcx, rdx, r8, r9, out);
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {
+		/*
+		 * TDX requires VMXON or #UD.  In the case of reboot or

kexec,

Quoted 8 lines

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

Quoted 5 lines
(quoted diff) +2 -0
+		 * VMX is made off (VMXOFF) by kvm reboot notifier,
+		 * kvm_reboot(), while TDs are still running.  The callers

check

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+		 * the returned error and complain.  Suppress it by returning 0.
+		 */

Curious how do the callers check the returned error when " Suppress it by returning 0" here.

Quoted 4 lines

It doesn't make sense for the caller to check the error and warn when kvm_rebooting = true.
Let's make it "return kvm_rebooting ? 0 : ret;" instread of "return 0;". Does it make sense?

Seems no need. The comments look confusing, and not aligned to what the code achieves. From what I read:
- if kvm_rebooting=true there: return 0 to caller and no error or warning happens
- if kvm_rebooting=false there: crash the system via kvm_spurious_fault. In this non-rebooting case, I think the callers don’t get a chance to read the returned value and complain.

Another thing is, have you double-checked that invocation of seamcalls indeed returns TDX_SEAMCALL_UD when VMX=off?

#80 lore raw

Re: [PATCH v14 055/113] KVM: TDX: TDP MMU TDX support

In reply to a message not in the archive
Quoted 46 lines · On Sun, May 28, 2023 at 9:21 PM <[email protected]> wrote:

From: Isaku Yamahata <[email protected]>

arch/x86/kvm/vmx/tdx.c +43 -0
+static int tdx_sept_drop_private_spte(struct kvm *kvm, gfn_t gfn,
+                                      enum pg_level level, kvm_pfn_t pfn)
+{
+       int tdx_level = pg_level_to_tdx_sept_level(level);
+       struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+       struct tdx_module_output out;
+       gpa_t gpa = gfn_to_gpa(gfn);
+       hpa_t hpa = pfn_to_hpa(pfn);
+       hpa_t hpa_with_hkid;
+       u64 err;
+
+       /* TODO: handle large pages. */
+       if (KVM_BUG_ON(level != PG_LEVEL_4K, kvm))
+               return -EINVAL;
+
+       if (unlikely(!is_hkid_assigned(kvm_tdx))) {
+               /*
+                * The HKID assigned to this TD was already freed and cache
+                * was already flushed. We don't have to flush again.
+                */
+               err = tdx_reclaim_page(hpa, false, 0);
+               if (KVM_BUG_ON(err, kvm))
+                       return -EIO;
+               tdx_unpin(kvm, pfn);
+               return 0;
+       }
+
+       do {
+               /*
+                * When zapping private page, write lock is held. So no race
+                * condition with other vcpu sept operation.  Race only with
+                * TDH.VP.ENTER.
+                */
+               err = tdh_mem_page_remove(kvm_tdx->tdr_pa, gpa, tdx_level, &out);
+       } while (unlikely(err == TDX_ERROR_SEPT_BUSY));
+       if (KVM_BUG_ON(err, kvm)) {
+               pr_tdx_error(TDH_MEM_PAGE_REMOVE, err, &out);
+               return -EIO;
+       }
+
+       hpa_with_hkid = set_hkid_to_hpa(hpa, (u16)kvm_tdx->hkid);
+       do {
+               /*

arch/x86/kvm/vmx/tdx.c void tdx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int pgd_level) · line 527

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+                * TDX_OPERAND_BUSY can happen on locking PAMT entry.  Because
+                * this page was removed above, other thread shouldn't be
+                * repeatedly operating on this page.  Just retry loop.
+                */
+               err = tdh_phymem_page_wbinvd(hpa_with_hkid);
+       } while (unlikely(err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_RCX)));
+       if (KVM_BUG_ON(err, kvm)) {
+               pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err, NULL);
+               return -EIO;
+       }

It seems like when the TD is destroyed, all the TD private pages are removed with tdx_reclaim_page which also clears the page with movdir64b instruction. But when the page is removed while the TD is alive (in this case), the page content is never cleared with movdir64b which causes any poisoned cache line to be consumed by the host resulting in #MC exceptions in the host context.

We should clear the page before returning it back to the free pool by calling tdx_clear_page((unsigned long)__va(hpa)) here.

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+       tdx_unpin(kvm, pfn);
+       return 0;
+}
+
#29 lore raw

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

In reply to Wang, Wei W
Quoted 26 lines · Wei W
Quoted 20 lines · Isaku Yamahata
Quoted 9 lines · Wei W
Quoted 9 lines
arch/x86/kvm/vmx/tdx_ops.h new file +8 -0
+static inline u64 kvm_seamcall(u64 op, u64 rcx, u64 rdx, u64 r8, u64 r9,
+			       struct tdx_module_output *out) {
+	u64 ret;
+
+	ret = __seamcall(op, rcx, rdx, r8, r9, out);
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {
+		/*
+		 * TDX requires VMXON or #UD.  In the case of reboot or

kexec,

Quoted 8 lines

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

Quoted 5 lines
(quoted diff) +2 -0
+		 * VMX is made off (VMXOFF) by kvm reboot notifier,
+		 * kvm_reboot(), while TDs are still running.  The callers

check

arch/x86/kvm/vmx/tdx_ops.h new file +2 -0
+		 * the returned error and complain.  Suppress it by returning 0.
+		 */

Curious how do the callers check the returned error when " Suppress it by returning 0" here.

Quoted 4 lines

It doesn't make sense for the caller to check the error and warn when kvm_rebooting = true.
Let's make it "return kvm_rebooting ? 0 : ret;" instread of "return 0;". Does it make sense?

Quoted 6 lines

Seems no need. The comments look confusing, and not aligned to what the code achieves. From what I read:
- if kvm_rebooting=true there: return 0 to caller and no error or warning happens
- if kvm_rebooting=false there: crash the system via kvm_spurious_fault. In this non-rebooting case, I think the callers don’t get a chance to read the returned value and complain.

How about this comment?

	if (unlikely(ret == TDX_SEAMCALL_UD)) {
		/*
		 * TDX requires VMXON or #UD.  In the case of reboot or kexec,
		 * kvm shutdown notifier, kvm_shutdown(), makes VMX off (VMXOFF)
		 * while TDs can be still running to invoke SEAMCALL.  It
		 * results in superfluous errors or warnings.
		 * If rebooting, return 0 to suppress superfluous messages.
		 * If not rebooting, panic by kvm_spurious_fault().
		 */
		kvm_spurious_fault();
		return 0;
	}
Quoted 2 lines

Another thing is, have you double-checked that invocation of seamcalls indeed returns TDX_SEAMCALL_UD when VMX=off?

I observed it several times during testing tdx module initialization. Here is the example I dug out from my debug logs.

tdx: SEAMCALL failed: CPU 162 is not in VMX operation.
tdx: TDX module initialization failed (-22)
kvm_intel: Failed to initialize TDX module.

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

Re: [PATCH v14 055/113] KVM: TDX: TDP MMU TDX support

In reply to Erdem Aktas
Quoted 66 lines · Erdem Aktas
Quoted 46 lines · On Sun, May 28, 2023 at 9:21 PM <[email protected]> wrote:

From: Isaku Yamahata <[email protected]>

arch/x86/kvm/vmx/tdx.c +43 -0
+static int tdx_sept_drop_private_spte(struct kvm *kvm, gfn_t gfn,
+                                      enum pg_level level, kvm_pfn_t pfn)
+{
+       int tdx_level = pg_level_to_tdx_sept_level(level);
+       struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+       struct tdx_module_output out;
+       gpa_t gpa = gfn_to_gpa(gfn);
+       hpa_t hpa = pfn_to_hpa(pfn);
+       hpa_t hpa_with_hkid;
+       u64 err;
+
+       /* TODO: handle large pages. */
+       if (KVM_BUG_ON(level != PG_LEVEL_4K, kvm))
+               return -EINVAL;
+
+       if (unlikely(!is_hkid_assigned(kvm_tdx))) {
+               /*
+                * The HKID assigned to this TD was already freed and cache
+                * was already flushed. We don't have to flush again.
+                */
+               err = tdx_reclaim_page(hpa, false, 0);
+               if (KVM_BUG_ON(err, kvm))
+                       return -EIO;
+               tdx_unpin(kvm, pfn);
+               return 0;
+       }
+
+       do {
+               /*
+                * When zapping private page, write lock is held. So no race
+                * condition with other vcpu sept operation.  Race only with
+                * TDH.VP.ENTER.
+                */
+               err = tdh_mem_page_remove(kvm_tdx->tdr_pa, gpa, tdx_level, &out);
+       } while (unlikely(err == TDX_ERROR_SEPT_BUSY));
+       if (KVM_BUG_ON(err, kvm)) {
+               pr_tdx_error(TDH_MEM_PAGE_REMOVE, err, &out);
+               return -EIO;
+       }
+
+       hpa_with_hkid = set_hkid_to_hpa(hpa, (u16)kvm_tdx->hkid);
+       do {
+               /*

arch/x86/kvm/vmx/tdx.c void tdx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int pgd_level) · line 527

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+                * TDX_OPERAND_BUSY can happen on locking PAMT entry.  Because
+                * this page was removed above, other thread shouldn't be
+                * repeatedly operating on this page.  Just retry loop.
+                */
+               err = tdh_phymem_page_wbinvd(hpa_with_hkid);
+       } while (unlikely(err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_RCX)));
+       if (KVM_BUG_ON(err, kvm)) {
+               pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err, NULL);
+               return -EIO;
+       }

It seems like when the TD is destroyed, all the TD private pages are removed with tdx_reclaim_page which also clears the page with movdir64b instruction. But when the page is removed while the TD is alive (in this case), the page content is never cleared with movdir64b which causes any poisoned cache line to be consumed by the host resulting in #MC exceptions in the host context.

Quoted 2 lines

We should clear the page before returning it back to the free pool by calling tdx_clear_page((unsigned long)__va(hpa)) here.

Thank you for catching it up. I'll fix tdx_sept_drop_private_spte(), tdx_sept_free_private_spt() (and tdx_sept_merge_private_spt() for large page support). We should clear the page for Not only guest memory, but also secure-ept.

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

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Isaku Yamahata
Quoted 10 lines · Isaku Yamahata

Thanks for pointing it out. The following is the fix.

arch/x86/kvm/vmx/tdx.c +0 -0
index 8a1d0755d275..b0d3f646afb1 100644
@@ -4499,26 +4499,39 @@ u64 tdx_non_arch_field_switch(u64 field)
  	}
  }

arch/x86/kvm/vmx/tdx.c u64 tdx_non_arch_field_switch(u64 field) · line 4506

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +5 -1
-static void __init vmx_tdx_on(void *info)
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t *err;
+};
+

Sorry for late reply.

I think you just need to mimic hardware_enable_all() -- using a per-cpu variable. In this way you can get rid of this structure.

But again, we have listed a couple of options in the v13 discussion [1]:

1) Call kvm_ops_update() twice before and after hardware_setup() in order to use hardware_enable_all() directly.

2) Expose kvm_x86_ops as symbol so VMX can set hardware_{enable|disable}() callback before hardware_setup() in order to use hardware_enable_all().

3) Implement VMX's own hardware_enable_all() logic as shown in this patch.

4) ???

I think it would be better if Sean can provide some comments here, but until he does, we can keep using option 3) (this patch).

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

#145 lore raw

Re: [PATCH v14 111/113] RFC: KVM: x86, TDX: Add check for setting CPUID

In reply to Huang, Kai
Quoted 19 lines · Kai
Quoted 9 lines · On Sun, 2023-05-28 at 21:20 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a hook to setting CPUID for additional consistency check of KVM_SET_CPUID2.

Because intel TDX or AMD SNP has restriction on the value of cpuid. Some value can't be changed after boot. Some can be only set at the VM creation time and can't be changed later. Check if the new values are consistent with the old values.

You might want to use some grammar tool to check against the changelog.

Also, personally I think it's better to briefly mention why we choose this design but not another (e.g., why we just don't make KVM remember all CPUIDs in TDH.MNG.INIT and simply ignores/rejects further KVM_SET_CPUID2). It would be helpful for the reviewer, or some git blamer in the future.

Quoted 3 lines

And why this patch is placed at the very bottom of this series? This logic should belong to TD creation part which should be at a relative earlier position in this series.

Because this is nice-to-have, not necessary for this patch series to work.

Quoted 15 lines

arch/x86/kvm/vmx/tdx.h struct kvm_tdx { · line 41

Quoted 11 lines
arch/x86/kvm/vmx/tdx.h +7 -0
@@ -32,6 +32,13 @@ struct kvm_tdx {
 	atomic_t tdh_mem_track;
 
 	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;

Since these CPUIDs may only be part of the vcpu's CPUIDs, you may want a more specific name, for instance, consistent_cpuid?

Quoted 2 lines

Also if you want this be common to AMD, then perhaps the comment should be improved too to be more generic.

Because I don't see apparent constraint on cpuid for SEV case in the spec, I doubt they want it. Please correct me if I'm wrong.

Given tdx_vcpu_check_cpuid() doesn't do much meaningful check, let's postpone this patch for now.

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

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Huang, Kai
Quoted 33 lines · Kai
Quoted 10 lines · Isaku Yamahata

Thanks for pointing it out. The following is the fix.

arch/x86/kvm/vmx/tdx.c +0 -0
index 8a1d0755d275..b0d3f646afb1 100644
@@ -4499,26 +4499,39 @@ u64 tdx_non_arch_field_switch(u64 field)
  	}
  }

arch/x86/kvm/vmx/tdx.c

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +5 -1
-static void __init vmx_tdx_on(void *info)
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t *err;
+};
+

Sorry for late reply.

I think you just need to mimic hardware_enable_all() -- using a per-cpu variable. In this way you can get rid of this structure.

But again, we have listed a couple of options in the v13 discussion [1]:

1) Call kvm_ops_update() twice before and after hardware_setup() in order to use hardware_enable_all() directly.

2) Expose kvm_x86_ops as symbol so VMX can set hardware_{enable|disable}() callback before hardware_setup() in order to use hardware_enable_all().

3) Implement VMX's own hardware_enable_all() logic as shown in this patch.

Quoted 7 lines

4) ???

I think it would be better if Sean can provide some comments here, but until he does, we can keep using option 3) (this patch).

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

Ok, makes sense. Here is the updated version with the fix for the error you pointed out. Introduce cpu bitmap to track which cpu enable VMX(VMXON) successfully. Disable VMX off only for cpu with bit set.

From 01dbb58b50e3119da9c3d639a10eb5d0029ee944 Mon Sep 17 00:00:00 2001
Message-Id: <01dbb58b50e3119da9c3d639a10eb5d0029ee944.1686677692.git.isaku.yamahata@intel.com>
From: Isaku Yamahata <[email protected]>
Date: Tue, 22 Feb 2022 14:44:15 -0800
Subject: [PATCH] KVM: TDX: Initialize the TDX module when loading the KVM
intel kernel module

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.

---
 arch/x86/kvm/Makefile      |  1 +
 arch/x86/kvm/vmx/main.c    | 34 ++++++++++++++-
 arch/x86/kvm/vmx/tdx.c     | 84 ++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h |  8 ++++
 4 files changed, 125 insertions(+), 2 deletions(-)
 create mode 100644 arch/x86/kvm/vmx/tdx.c
arch/x86/kvm/Makefile +1 -0
index 0e894ae23cbc..4b01ab842ab7 100644
@@ -25,6 +25,7 @@ kvm-$(CONFIG_KVM_SMM)	+= smm.o
 kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
 			   vmx/hyperv.o vmx/nested.o vmx/posted_intr.o vmx/main.o
 kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o
 
 kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o \
 			   svm/sev.o svm/hyperv.o
arch/x86/kvm/vmx/main.c +32 -2
index bbeb32d40b8b..af037d1367e7 100644
@@ -6,6 +6,36 @@
 #include "nested.h"
 #include "pmu.h"
 
+static bool enable_tdx __ro_after_init;
+module_param_named(tdx, enable_tdx, bool, 0444);
+
+static int vt_hardware_enable(void)
+{
+	int ret;
+
+	ret = vmx_hardware_enable();
+	if (ret || !enable_tdx)
+		return ret;
+
+	ret = tdx_cpu_enable();
+	if (ret)
+		vmx_hardware_disable();
+	return ret;
+}
+
+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) |			\
@@ -22,7 +52,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.hardware_unsetup = vmx_hardware_unsetup,
 
-	.hardware_enable = vmx_hardware_enable,
+	.hardware_enable = vt_hardware_enable,
 	.hardware_disable = vmx_hardware_disable,
 	.has_emulated_msr = vmx_has_emulated_msr,
 
@@ -157,7 +187,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

84 lines not on this page · raw message

arch/x86/kvm/vmx/x86_ops.h +8 -0
index 051b5c4b5c2f..a30683c6d822 100644
@@ -20,6 +20,8 @@ bool kvm_is_vmx_supported(void);
 int __init vmx_init(void);
 void vmx_exit(void);
 
+__init int vmx_hardware_setup(void);
+
 extern struct kvm_x86_ops vt_x86_ops __initdata;
 extern struct kvm_x86_init_ops vt_init_ops __initdata;
 
@@ -133,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 */
Signature · 6 lines
2.25.1



-- 
Isaku Yamahata <[email protected]>
#14 lore raw

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

Quoted 49 lines · Isaku Yamahata
Quoted 33 lines · Kai
Quoted 10 lines · Isaku Yamahata

Thanks for pointing it out. The following is the fix.

arch/x86/kvm/vmx/tdx.c +0 -0
index 8a1d0755d275..b0d3f646afb1 100644
@@ -4499,26 +4499,39 @@ u64 tdx_non_arch_field_switch(u64 field)
  	}
  }

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +5 -1
-static void __init vmx_tdx_on(void *info)
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t *err;
+};
+

Sorry for late reply.

I think you just need to mimic hardware_enable_all() -- using a per-cpu variable. In this way you can get rid of this structure.

But again, we have listed a couple of options in the v13 discussion [1]:

1) Call kvm_ops_update() twice before and after hardware_setup() in order to use hardware_enable_all() directly.

2) Expose kvm_x86_ops as symbol so VMX can set hardware_{enable|disable}() callback before hardware_setup() in order to use hardware_enable_all().

3) Implement VMX's own hardware_enable_all() logic as shown in this patch.

Quoted 7 lines

4) ???

I think it would be better if Sean can provide some comments here, but until he does, we can keep using option 3) (this patch).

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

Ok, makes sense. Here is the updated version with the fix for the error you pointed out. Introduce cpu bitmap to track which cpu enable VMX(VMXON) successfully. Disable VMX off only for cpu with bit set.

[...]

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

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c new file +5 -0
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t err;
+};
+

Again (and again), why not just mimic hardware_enable_all() to use a per-cpu variable instead of a cpumask, so that you can get rid of this structure?

#146 lore raw

Re: [PATCH v14 111/113] RFC: KVM: x86, TDX: Add check for setting CPUID

In reply to Isaku Yamahata
Quoted 22 lines · Isaku Yamahata
Quoted 18 lines · Kai
Quoted 9 lines · On Sun, 2023-05-28 at 21:20 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Add a hook to setting CPUID for additional consistency check of KVM_SET_CPUID2.

Because intel TDX or AMD SNP has restriction on the value of cpuid. Some value can't be changed after boot. Some can be only set at the VM creation time and can't be changed later. Check if the new values are consistent with the old values.

You might want to use some grammar tool to check against the changelog.

Also, personally I think it's better to briefly mention why we choose this design but not another (e.g., why we just don't make KVM remember all CPUIDs in TDH.MNG.INIT and simply ignores/rejects further KVM_SET_CPUID2). It would be helpful for the reviewer, or some git blamer in the future.

Quoted 5 lines
Quoted 3 lines

And why this patch is placed at the very bottom of this series? This logic should belong to TD creation part which should be at a relative earlier position in this series.

Because this is nice-to-have, not necessary for this patch series to work.

Is it? I thought Sean suggested we should to this.

I think you should just include it to this series and place it in a proper position (or even merge it to some other patch).

#30 lore raw

RE: [PATCH v14 011/113] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to Isaku Yamahata
Quoted 3 lines · Isaku Yamahata

How about this comment?

	if (unlikely(ret == TDX_SEAMCALL_UD)) {

Where is the TDX_SEAMCALL_UD error code documented in the spec? I failed to find it.

Quoted 2 lines
		/*
		 * TDX requires VMXON or #UD.  

TDX requires #UD? Seems a bit ambiguous.

Quoted 9 lines

In the case of reboot or kexec,
* kvm shutdown notifier, kvm_shutdown(), makes VMX off
(VMXOFF)
* while TDs can be still running to invoke SEAMCALL. It
* results in superfluous errors or warnings.
* If rebooting, return 0 to suppress superfluous messages.
* If not rebooting, panic by kvm_spurious_fault(). */
kvm_spurious_fault();

I would put it this way:
SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off. This can happen when host gets rebooted or live updated. In this case, the instruction execution is actually 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.

#15 lore raw

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Huang, Kai
Quoted 52 lines · Kai
Quoted 49 lines · Isaku Yamahata
Quoted 33 lines · Kai
Quoted 10 lines · Isaku Yamahata

Thanks for pointing it out. The following is the fix.

arch/x86/kvm/vmx/tdx.c +0 -0
index 8a1d0755d275..b0d3f646afb1 100644
@@ -4499,26 +4499,39 @@ u64 tdx_non_arch_field_switch(u64 field)
  	}
  }

arch/x86/kvm/vmx/tdx.c

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +5 -1
-static void __init vmx_tdx_on(void *info)
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t *err;
+};
+

Sorry for late reply.

I think you just need to mimic hardware_enable_all() -- using a per-cpu variable. In this way you can get rid of this structure.

But again, we have listed a couple of options in the v13 discussion [1]:

1) Call kvm_ops_update() twice before and after hardware_setup() in order to use hardware_enable_all() directly.

2) Expose kvm_x86_ops as symbol so VMX can set hardware_{enable|disable}() callback before hardware_setup() in order to use hardware_enable_all().

3) Implement VMX's own hardware_enable_all() logic as shown in this patch.

Quoted 7 lines

4) ???

I think it would be better if Sean can provide some comments here, but until he does, we can keep using option 3) (this patch).

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

Ok, makes sense. Here is the updated version with the fix for the error you pointed out. Introduce cpu bitmap to track which cpu enable VMX(VMXON) successfully. Disable VMX off only for cpu with bit set.

[...]

Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t err;
+};
+

Again (and again), why not just mimic hardware_enable_all() to use a per-cpu variable instead of a cpumask, so that you can get rid of this structure?

Do you mean __hardware_enable_nolock() uses per-cpu variable? Because hardware setup is one shot on the initialization, we don't want to allocate the variable statically. Anyway the following is a patch to use per-cpu variable with dynamic allocation. Which version do you prefer?

arch/x86/kvm/vmx/tdx.c +24 -21
index 95be6b2fba83..40a3c9c01ac6 100644
@@ -4511,38 +4511,34 @@ u64 tdx_non_arch_field_switch(u64 field)
 }
 
 struct vmx_tdx_enabled {
-	cpumask_var_t vmx_enabled;
-	atomic_t err;
+	bool vmx_enabled;
+	int err;
 };
 
 static void __init vmx_tdx_on(void *_vmx_tdx)
 {
-	struct vmx_tdx_enabled *vmx_tdx = _vmx_tdx;
-	int r;
+	struct vmx_tdx_enabled *vmx_tdx = this_cpu_ptr(_vmx_tdx);
 
-	r = vmx_hardware_enable();
-	if (!r) {
-		cpumask_set_cpu(smp_processor_id(), vmx_tdx->vmx_enabled);
-		r = tdx_cpu_enable();
+	vmx_tdx->err = vmx_hardware_enable();
+	if (!vmx_tdx->err) {
+		vmx_tdx->vmx_enabled = true;
+		vmx_tdx->err = tdx_cpu_enable();
 	}
-	if (r)
-		atomic_set(&vmx_tdx->err, r);
 }
 
-static void __init vmx_off(void *_vmx_enabled)
+static void __init vmx_off(void *_vmx_tdx)
 {
-	cpumask_var_t *vmx_enabled = (cpumask_var_t *)_vmx_enabled;
+	struct vmx_tdx_enabled *vmx_tdx = this_cpu_ptr(_vmx_tdx);
 
-	if (cpumask_test_cpu(smp_processor_id(), *vmx_enabled))
+	if (vmx_tdx->vmx_enabled)
 		vmx_hardware_disable();
 }
 
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 {
-	struct vmx_tdx_enabled vmx_tdx = {
-		.err = ATOMIC_INIT(0),
-	};
+	struct vmx_tdx_enabled __percpu *vmx_tdx_enabled;
 	int max_pkgs;
+	int cpu;
 	int r = 0;
 	int i;
 
@@ -4603,7 +4599,8 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 	for (i = 0; i < max_pkgs; i++)
 		mutex_init(&tdx_mng_key_config_lock[i]);
 
-	if (!zalloc_cpumask_var(&vmx_tdx.vmx_enabled, GFP_KERNEL)) {
+	vmx_tdx_enabled = alloc_percpu_gfp(struct vmx_tdx_enabled, GFP_KERNEL | __GFP_ZERO);
+	if (!vmx_tdx_enabled) {
 		r = -ENOMEM;
 		goto out;
 	}
@@ -4618,15 +4615,21 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
 	 */
 	if (!cpumask_equal(cpu_online_mask, cpu_present_mask))
 		pr_warn("The old TDX module requires all present CPUs to be online to initialize.\n");
-	on_each_cpu(vmx_tdx_on, &vmx_tdx, true);	/* TDX requires vmxon. */
-	r = atomic_read(&vmx_tdx.err);
+	on_each_cpu(vmx_tdx_on, vmx_tdx_enabled, true);	/* TDX requires vmxon. */
+	for_each_present_cpu(cpu) {
+		struct vmx_tdx_enabled *vmx_tdx = per_cpu_ptr(vmx_tdx_enabled, cpu);
+		if (vmx_tdx->err) {
+			r = vmx_tdx->err;
+			break;
+		}
+	}
 	if (!r)
 		r = tdx_module_setup();
 	else
 		r = -EIO;
-	on_each_cpu(vmx_off, &vmx_tdx.vmx_enabled, true);
+	on_each_cpu(vmx_off, vmx_tdx_enabled, true);
 	cpus_read_unlock();
-	free_cpumask_var(vmx_tdx.vmx_enabled);
+	free_percpu(vmx_tdx_enabled);
 	if (r)
 		goto out;
 
Signature · 7 lines
2.25.1




-- 
Isaku Yamahata <[email protected]>
#31 lore raw

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

In reply to Wang, Wei W
Quoted 7 lines · Wei W
Quoted 3 lines · Isaku Yamahata

How about this comment?

	if (unlikely(ret == TDX_SEAMCALL_UD)) {

Where is the TDX_SEAMCALL_UD error code documented in the spec? I failed to find it.

This is not a part of the spec, but a convention of __seamcall(). Please refer to
https://lore.kernel.org/all/ec640452a4385d61bec97f8b761ed1ff38898504.1685887183.git.kai.huang@intel.com/

Quoted 10 lines
Quoted 9 lines

In the case of reboot or kexec,
* kvm shutdown notifier, kvm_shutdown(), makes VMX off
(VMXOFF)
* while TDs can be still running to invoke SEAMCALL. It
* results in superfluous errors or warnings.
* If rebooting, return 0 to suppress superfluous messages.
* If not rebooting, panic by kvm_spurious_fault(). */
kvm_spurious_fault();

Quoted 7 lines

I would put it this way:
SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off. This can happen when host gets rebooted or live updated. In this case, the instruction execution is actually 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.

Thanks for it. I made minor fix to it.

	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;
	}
Signature · 1 line
Isaku Yamahata <[email protected]>
#16 lore raw

Re: [PATCH v14 004/113] KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

In reply to Isaku Yamahata
Quoted 64 lines · Isaku Yamahata
Quoted 52 lines · Kai
Quoted 49 lines · Isaku Yamahata
Quoted 33 lines · Kai
Quoted 10 lines · Isaku Yamahata

Thanks for pointing it out. The following is the fix.

arch/x86/kvm/vmx/tdx.c +0 -0
index 8a1d0755d275..b0d3f646afb1 100644
@@ -4499,26 +4499,39 @@ u64 tdx_non_arch_field_switch(u64 field)
  	}
  }

arch/x86/kvm/vmx/tdx.c

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +5 -1
-static void __init vmx_tdx_on(void *info)
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t *err;
+};
+

Sorry for late reply.

I think you just need to mimic hardware_enable_all() -- using a per-cpu variable. In this way you can get rid of this structure.

But again, we have listed a couple of options in the v13 discussion [1]:

1) Call kvm_ops_update() twice before and after hardware_setup() in order to use hardware_enable_all() directly.

2) Expose kvm_x86_ops as symbol so VMX can set hardware_{enable|disable}() callback before hardware_setup() in order to use hardware_enable_all().

3) Implement VMX's own hardware_enable_all() logic as shown in this patch.

Quoted 7 lines

4) ???

I think it would be better if Sean can provide some comments here, but until he does, we can keep using option 3) (this patch).

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

Ok, makes sense. Here is the updated version with the fix for the error you pointed out. Introduce cpu bitmap to track which cpu enable VMX(VMXON) successfully. Disable VMX off only for cpu with bit set.

[...]

Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+struct vmx_tdx_enabled {
+	cpumask_var_t vmx_enabled;
+	atomic_t err;
+};
+

Again (and again), why not just mimic hardware_enable_all() to use a per-cpu variable instead of a cpumask, so that you can get rid of this structure?

Quoted 1 line

Do you mean __hardware_enable_nolock() uses per-cpu variable?

Yes.

Quoted 3 lines

Because hardware setup is one shot on the initialization, we don't want to allocate the variable statically. Anyway the following is a patch to use per-cpu variable with dynamic allocation. Which version do you prefer?

This looks over-complicated. My preference is to mimic __hardware_enable_nolock() to avoid the 'struct vmx_tdx_enabled'.  But if you care about the variable being statically, then looks your current cpumask_var_t looks cleaner to me

Anyway, since you have mentioned the reason, and I understand your concern now, I will leave this to you.

#99 lore raw

Re: [PATCH v14 072/113] KVM: TDX: handle vcpu migration over logical processor

In reply to [email protected]
Quoted 20 lines · On 5/29/2023 12:19 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

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

---
 arch/x86/kvm/vmx/main.c    |  32 ++++++-
 arch/x86/kvm/vmx/tdx.c     | 168 +++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h     |   2 +
 arch/x86/kvm/vmx/x86_ops.h |   4 +
 4 files changed, 203 insertions(+), 3 deletions(-)
arch/x86/kvm/vmx/main.c +0 -0
index 17fb1515e56a..29ebd171dbe3 100644

...

Quoted 4 lines
arch/x86/kvm/vmx/main.c +0 -0
@@ -455,6 +606,19 @@ void tdx_vcpu_free(struct kvm_vcpu *vcpu)
 		return;
 	}
 

arch/x86/kvm/vmx/main.c void tdx_vcpu_free(struct kvm_vcpu *vcpu) · line 618

Quoted 10 lines
arch/x86/kvm/vmx/main.c +10 -0
+	/*
+	 * kvm_free_vcpus()
+	 *   -> kvm_unload_vcpu_mmu()
+	 *
+	 * does vcpu_load() for every vcpu after they already disassociated
+	 * from the per cpu list when tdx_vm_teardown(). So we need to
+	 * disassociate them again, otherwise the freed vcpu data will be
+	 * accessed when do list_{del,add}() on associated_tdvcpus list
+	 * later.
+	 */

Nit: kvm_free_vcpus() and tdx_vm_teardown() are typos? I don't find these functions.

Quoted 6 lines
arch/x86/kvm/vmx/main.c +3 -0
+	tdx_disassociate_vp_on_cpu(vcpu);
+	WARN_ON_ONCE(vcpu->cpu != -1);
+
 	if (tdx->tdvpx_pa) {
 		for (i = 0; i < tdx_info.nr_tdvpx_pages; i++) {
 			if (tdx->tdvpx_pa[i])
#100 lore raw

Re: [PATCH v14 072/113] KVM: TDX: handle vcpu migration over logical processor

Quoted 28 lines · Qian
Quoted 20 lines · On 5/29/2023 12:19 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

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

---
 arch/x86/kvm/vmx/main.c    |  32 ++++++-
 arch/x86/kvm/vmx/tdx.c     | 168 +++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h     |   2 +
 arch/x86/kvm/vmx/x86_ops.h |   4 +
 4 files changed, 203 insertions(+), 3 deletions(-)
arch/x86/kvm/vmx/main.c +0 -0
index 17fb1515e56a..29ebd171dbe3 100644

...

Quoted 4 lines
arch/x86/kvm/vmx/main.c +0 -0
@@ -455,6 +606,19 @@ void tdx_vcpu_free(struct kvm_vcpu *vcpu)
 		return;
 	}
 
Quoted 12 lines

arch/x86/kvm/vmx/main.c void tdx_vcpu_free(struct kvm_vcpu *vcpu) · line 618

Quoted 10 lines
arch/x86/kvm/vmx/main.c +10 -0
+	/*
+	 * kvm_free_vcpus()
+	 *   -> kvm_unload_vcpu_mmu()
+	 *
+	 * does vcpu_load() for every vcpu after they already disassociated
+	 * from the per cpu list when tdx_vm_teardown(). So we need to
+	 * disassociate them again, otherwise the freed vcpu data will be
+	 * accessed when do list_{del,add}() on associated_tdvcpus list
+	 * later.
+	 */

Nit: kvm_free_vcpus() and tdx_vm_teardown() are typos? I don't find these functions.

kvm_free_vcpus() => kvm_destroy_vcpus()
tdx_vm_teardown() => tdx_mmu_release_hkid()

Will fix the comment.

Signature · 1 line
Isaku Yamahata <[email protected]>