Skip to contentSkip to conversation

KVM TDX basic feature support

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

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

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

In reply to Chao Gao
Quoted 26 lines · Chao
Quoted 20 lines · Kai
Quoted 12 lines
Quoted 11 lines
Quoted 5 lines

The important thing is that they're handled by _one_ entity. What we have today is probably the worst setup; VMXON is handled by KVM, but TDX.SYS.LP.INIT is handled by core kernel (sort of).

I cannot argue against this :-)

But from this point of view, I cannot see difference between tdx_enable() and tdx_cpu_enable(), because they both in core-kernel while depend on KVM to handle VMXON.

Quoted 7 lines

My comments were made under the assumption that the code was NOT buggy, i.e. if KVM did NOT need to call tdx_cpu_enable() independent of tdx_enable().

That said, I do think it makes to have tdx_enable() call an private/inner version, e.g. __tdx_cpu_enable(), and then have KVM call a public version. Alternatively, the kernel could register yet another cpuhp hook that runs after KVM's, i.e. does TDX.SYS.LP.INIT after KVM has done VMXON (if TDX has been enabled).

Quoted 4 lines

We will need to handle tdx_cpu_online() in "some cpuhp callback" anyway, no matter whether tdx_enable() calls __tdx_cpu_enable() internally or not, because now tdx_enable() can be done on a subset of cpus that the platform has.

Quoted 4 lines

Can you confirm this is allowed again? it seems like this code indicates the opposite:

https://github.com/intel/tdx-module/blob/tdx_1.5/src/vmm_dispatcher/api_calls/tdh_sys_config.c#L768C1-L775C6

This feature requires ucode/P-SEAMLDR and TDX module change, and cannot be supported for some *early* generations. I think they haven't added such code to the opensource TDX module code yet.

I can ask TDX module people's plan if it is a concern.

In reality, this shouldn't be a problem because the current code kinda works with both cases:

1) If this feature is not supported (i.e., old platform and/or old module), and if user tries to enable TDX when there's offline cpu, then tdx_enable() will fail when it does TDH.SYS.CONFIG, and we can use the error code to pinpoint the root cause.

2) Otherwise, it just works.

Quoted 8 lines
Quoted 8 lines

For the latter (after the "Alternatively" above), by "the kernel" do you mean the core-kernel but not KVM?

E.g., you mean to register a cpuhp book _inside_ tdx_enable() after TDX is initialized successfully?

Quoted 7 lines
Quoted 2 lines

That would have problem like when KVM is not present (e.g., KVM is unloaded after it enables TDX), the cpuhp book won't work at all.

Is "the cpuhp hook doesn't work if KVM is not loaded" a real problem?

The CPU about to online won't run any TDX code. So, it should be ok to skip tdx_cpu_enable().

It _can_ work if we only consider KVM, because for KVM we can always guarantee:

1) VMXON + tdx_cpu_enable() have been done for all online cpus before it calls tdx_enable().
2) VMXON + tdx_cpu_enable() have been done in cpuhp for any new CPU before it goes online.

Btw, this reminds me why I didn't want to do tdx_cpu_enable() inside tdx_enable():

tdx_enable() will need to _always_ call tdx_cpu_enable() for all online cpus regardless of whether the module has been initialized successfully in the previous calls.

I believed this is kinda silly, i.e., why not just letting the caller to do tdx_cpu_enable() for all online cpus before tdx_enable().

However, back to the TDX-specific core-kernel cpuhp hook, in the long term, I believe the TDX cpuhp hook should be put _BEFORE_ all in-kernel TDX-users' cpuhp hooks, because logically TDX users should depend on TDX core-kernel code, but not the opposite.

That is, my long term vision is we can have a simple rule:

The core-kernel TDX code always guarantees online CPUs are TDX-capable. All TDX users don't need to consider tdx_cpu_enable() ever. They just need to call tdx_enable() to bring TDX to work.

So for now, given we depend on KVM for VMXON anyway, I don't see any reason the core-kernel should register any TDX cpuhp. Having to "skip tdx_cpu_enable() when VMX isn't enabled" is kinda hacky anyway.

#147 lore raw

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

In reply to Sean Christopherson
Quoted 19 lines
Quoted 6 lines

So I think we have consensus to go with the approach that shows in your second diff -- that is to always enable virtualization during module loading for all other ARCHs other than x86, for which we only always enables virtualization during module loading for TDX.

Assuming the other arch maintainers are ok with that approach. If waiting until a VM is created is desirable for other architectures, then we'll need to figure out a plan b. E.g. KVM arm64 doesn't support being built as a module, so enabling hardware during initialization would mean virtualization is enabled for any kernel that is built with CONFIG_KVM=y.

Actually, duh. There's absolutely no reason to force other architectures to choose when to enable virtualization. As evidenced by the massaging to have x86 keep enabling virtualization on-demand for !TDX, the cleanups don't come from enabling virtualization during module load, they come from registering cpuup and syscore ops when virtualization is enabled.

Quoted 8 lines

I.e. we can keep kvm_usage_count in common code, and just do exactly what I proposed for kvm_x86_enable_virtualization().

I have patches to do this, and initial testing suggests they aren't wildly broken. I'll post them soon-ish, assuming nothing pops up in testing. They are clean enough that they can land in advance of TDX, e.g. in kvm-coco-queue even before other architectures verify I didn't break them.

Hi Sean,

Just want to check with you what is your plan on this?

Please feel free to let me know if there's anything that I can help. Thanks.

#148 lore raw

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

Quoted 26 lines · Kai Huang
Quoted 17 lines
Quoted 4 lines

So I think we have consensus to go with the approach that shows in your second diff -- that is to always enable virtualization during module loading for all other ARCHs other than x86, for which we only always enables virtualization during module loading for TDX.

Assuming the other arch maintainers are ok with that approach. If waiting until a VM is created is desirable for other architectures, then we'll need to figure out a plan b. E.g. KVM arm64 doesn't support being built as a module, so enabling hardware during initialization would mean virtualization is enabled for any kernel that is built with CONFIG_KVM=y.

Actually, duh. There's absolutely no reason to force other architectures to choose when to enable virtualization. As evidenced by the massaging to have x86 keep enabling virtualization on-demand for !TDX, the cleanups don't come from enabling virtualization during module load, they come from registering cpuup and syscore ops when virtualization is enabled.

Quoted 8 lines

I.e. we can keep kvm_usage_count in common code, and just do exactly what I proposed for kvm_x86_enable_virtualization().

I have patches to do this, and initial testing suggests they aren't wildly broken. I'll post them soon-ish, assuming nothing pops up in testing. They are clean enough that they can land in advance of TDX, e.g. in kvm-coco-queue even before other architectures verify I didn't break them.

Quoted 5 lines

Hi Sean,

Just want to check with you what is your plan on this?

Please feel free to let me know if there's anything that I can help.

Ah shoot, I posted patches[*] but managed to forget to Cc any of the TDX folks. Sorry :-/

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

#149 lore raw

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

Quoted 29 lines · Sean Christopherson
Quoted 28 lines · Kai Huang
Quoted 17 lines
Quoted 4 lines

So I think we have consensus to go with the approach that shows in your second diff -- that is to always enable virtualization during module loading for all other ARCHs other than x86, for which we only always enables virtualization during module loading for TDX.

Assuming the other arch maintainers are ok with that approach. If waiting until a VM is created is desirable for other architectures, then we'll need to figure out a plan b. E.g. KVM arm64 doesn't support being built as a module, so enabling hardware during initialization would mean virtualization is enabled for any kernel that is built with CONFIG_KVM=y.

Actually, duh. There's absolutely no reason to force other architectures to choose when to enable virtualization. As evidenced by the massaging to have x86 keep enabling virtualization on-demand for !TDX, the cleanups don't come from enabling virtualization during module load, they come from registering cpuup and syscore ops when virtualization is enabled.

Quoted 8 lines

I.e. we can keep kvm_usage_count in common code, and just do exactly what I proposed for kvm_x86_enable_virtualization().

I have patches to do this, and initial testing suggests they aren't wildly broken. I'll post them soon-ish, assuming nothing pops up in testing. They are clean enough that they can land in advance of TDX, e.g. in kvm-coco-queue even before other architectures verify I didn't break them.

Hi Sean,

Quoted 8 lines
Quoted 3 lines

Just want to check with you what is your plan on this?

Please feel free to let me know if there's anything that I can help.

Ah shoot, I posted patches[*] but managed to forget to Cc any of the TDX folks. Sorry :-/

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

Oh I missed that :-( Thanks for the info!

#150 lore raw

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

In reply to [email protected]
Quoted 42 lines · Isaku
arch/x86/kvm/vmx/tdx.c new file +42 -0
+struct tdx_enabled {
+	cpumask_var_t enabled;
+	atomic_t err;
+};
+
+static void __init tdx_on(void *_enable)
+{
+	struct tdx_enabled *enable = _enable;
+	int r;
+
+	r = vmx_hardware_enable();
+	if (!r) {
+		cpumask_set_cpu(smp_processor_id(), enable->enabled);
+		r = tdx_cpu_enable();
+	}
+	if (r)
+		atomic_set(&enable->err, r);
+}
+
+static void __init vmx_off(void *_enabled)
+{
+	cpumask_var_t *enabled = (cpumask_var_t *)_enabled;
+
+	if (cpumask_test_cpu(smp_processor_id(), *enabled))
+		vmx_hardware_disable();
+}
+
+int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
+{
+	struct tdx_enabled enable = {
+		.err = ATOMIC_INIT(0),
+	};
+	int r = 0;
+
+	if (!enable_ept) {
+		pr_warn("Cannot enable TDX with EPT disabled\n");
+		return -EINVAL;
+	}
+
+	if (!zalloc_cpumask_var(&enable.enabled, GFP_KERNEL)) {
+		r = -ENOMEM;
+		goto out;

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

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

I was thinking why do we need to convert to -EIO.

Convert error code to -EIO unconditionally would cause the original error code being lost. Although given tdx_on() is called on all online cpus in parallel, the @enable.err could be imprecise anyway, the explicit conversion seems not quite reasonable to be done _here_.

I think it would be more reasonable to explicitly set the error code to -EIO in tdx_on(), where we _exactly_ know what went wrong and can still possibly do something before losing the error code.

E.g., we can dump the error code to the user, but looks both vmx_hardware_enable() and tdx_cpu_enable() will do so already so we can safely lose the error code there.

We can perhaps add a comment to point this out before losing the error code if that's better:

/*
* Both vmx_hardware_enable() and tdx_cpu_enable() print error
* message when they fail. Just convert the error code to -EIO
* when multiple cpu fault the @err cannot be used to precisely
* record the error code for them anyway.
*/

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c new file +7 -0
+	on_each_cpu(vmx_off, &enable.enabled, true);
+	cpus_read_unlock();
+	free_cpumask_var(enable.enabled);
+
+out:
+	return r;
+}
#151 lore raw

PATCH v19 24/130 KVM: TDX: Add placeholders for TDX VM/vcpu structure

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

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

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

v14 -> v15:
- use KVM_X86_TDX_VM

---
 arch/x86/kvm/vmx/main.c | 14 ++++++++++++
 arch/x86/kvm/vmx/tdx.c  |  1 +
 arch/x86/kvm/vmx/tdx.h  | 50 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 65 insertions(+)
 create mode 100644 arch/x86/kvm/vmx/tdx.h
arch/x86/kvm/vmx/main.c +14 -0
index 18aef6e23aab..e11edbd19e7c 100644
@@ -5,6 +5,7 @@
 #include "vmx.h"
 #include "nested.h"
 #include "pmu.h"
+#include "tdx.h"
 
 static bool enable_tdx __ro_after_init;
 module_param_named(tdx, enable_tdx, bool, 0444);
@@ -18,6 +19,9 @@ static __init int vt_hardware_setup(void)
 		return ret;
 
 	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+	if (enable_tdx)
+		vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
+					   sizeof(struct kvm_tdx));
 
 	return 0;
 }
@@ -215,8 +219,18 @@ static int __init vt_init(void)
 	 * Common KVM initialization _must_ come last, after this, /dev/kvm is
 	 * exposed to userspace!
 	 */
+	/*
+	 * kvm_x86_ops is updated with vt_x86_ops.  vt_x86_ops.vm_size must
+	 * be set before kvm_x86_vendor_init().
+	 */
 	vcpu_size = sizeof(struct vcpu_vmx);
 	vcpu_align = __alignof__(struct vcpu_vmx);
+	if (enable_tdx) {
+		vcpu_size = max_t(unsigned int, vcpu_size,
+				  sizeof(struct vcpu_tdx));
+		vcpu_align = max_t(unsigned int, vcpu_align,
+				   __alignof__(struct vcpu_tdx));
+	}
 	r = kvm_init(vcpu_size, vcpu_align, THIS_MODULE);
 	if (r)
 		goto err_kvm_init;
arch/x86/kvm/vmx/tdx.c +1 -0
index 43c504fb4fed..14ef0ccd8f1a 100644
@@ -6,6 +6,7 @@
 #include "capabilities.h"
 #include "x86_ops.h"
 #include "x86.h"
+#include "tdx.h"
 
 #undef pr_fmt
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
arch/x86/kvm/vmx/tdx.h new file +50 -0

50 lines not on this page · raw message

Signature · 1 line
2.25.1
#152 lore raw

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

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

From: Isaku Yamahata <[email protected]>

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

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

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

v14 -> v15:
- use KVM_X86_TDX_VM

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

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

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

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

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

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

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

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

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

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

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

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

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

Quoted 3 lines

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

Correct. Here's an updated version.

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

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

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

In reply to [email protected]
Quoted 9 lines · Isaku

From: Isaku Yamahata <[email protected]>

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

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

The changelog is essentially only saying "doing what" w/o "why".

Please at least explain why you invented the 'struct kvm_tdx' and 'struct vcpu_tdx', and why they are invented in this way.

E.g., can we extend 'struct kvm_vmx' for TDX?

struct kvm_tdx {
	struct kvm_vmx vmx;
	...
};
Quoted 31 lines

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

v14 -> v15:
- use KVM_X86_TDX_VM

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

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

arch/x86/kvm/vmx/main.c +1 -0
index 18aef6e23aab..e11edbd19e7c 100644
@@ -5,6 +5,7 @@
  #include "vmx.h"
  #include "nested.h"
  #include "pmu.h"
+#include "tdx.h"
 
  static bool enable_tdx __ro_after_init;
  module_param_named(tdx, enable_tdx, bool, 0444);

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

Quoted 7 lines
arch/x86/kvm/vmx/main.c +3 -0
@@ -18,6 +19,9 @@ static __init int vt_hardware_setup(void)
  		return ret;
 
  	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+	if (enable_tdx)
+		vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
+					   sizeof(struct kvm_tdx));
 

Now I see why you included 'struct kvm_x86_ops' as function parameter.

Please move it to this patch.

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

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

Quoted 10 lines
arch/x86/kvm/vmx/main.c +8 -0
+	 * be set before kvm_x86_vendor_init().
+	 */
  	vcpu_size = sizeof(struct vcpu_vmx);
  	vcpu_align = __alignof__(struct vcpu_vmx);
+	if (enable_tdx) {
+		vcpu_size = max_t(unsigned int, vcpu_size,
+				  sizeof(struct vcpu_tdx));
+		vcpu_align = max_t(unsigned int, vcpu_align,
+				   __alignof__(struct vcpu_tdx));
+	}

Since you are updating vm_size in vt_hardware_setup(), I am wondering whether we can do similar thing for vcpu_size and vcpu_align.

That is, we put them both to 'struct kvm_x86_ops', and you update them in vt_hardware_setup().

kvm_init() can then just access them directly in this way both 'vcpu_size' and 'vcpu_align' function parameters can be removed.

Quoted 3 lines
arch/x86/kvm/vmx/main.c +0 -0
  	r = kvm_init(vcpu_size, vcpu_align, THIS_MODULE);
  	if (r)
  		goto err_kvm_init;
#155 lore raw

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

Quoted 18 lines · Kai
Quoted 9 lines · Isaku

From: Isaku Yamahata <[email protected]>

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

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

The changelog is essentially only saying "doing what" w/o "why".

Please at least explain why you invented the 'struct kvm_tdx' and 'struct vcpu_tdx', and why they are invented in this way.

Quoted 6 lines

E.g., can we extend 'struct kvm_vmx' for TDX?

struct kvm_tdx {
	struct kvm_vmx vmx;
	...
};

Here is the updated version.

KVM: TDX: Add placeholders for TDX VM/vcpu structure

Add placeholders TDX VM/vCPU structure, overlaying with the existing VMX VM/vCPU structures. Initialize VM structure size and vCPU size/align so that x86 KVM-common code knows those sizes irrespective of VMX or TDX. Those structures will be populated as guest creation logic develops.

TDX requires its data structure for guest and vcpu. For VMX, we already have struct kvm_vmx and struct vcpu_vmx. Two options to add TDX-specific members.

1. Append TDX-specific members to kvm_vmx and vcpu_vmx. Use the same struct for both VMX and TDX.
2. Define TDX-specific data struct and overlay.

Choose option two because it has less memory overhead and what member is needed is clearer

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

Quoted 37 lines
Quoted 29 lines

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

v14 -> v15:
- use KVM_X86_TDX_VM

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

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

arch/x86/kvm/vmx/main.c +1 -0
index 18aef6e23aab..e11edbd19e7c 100644
@@ -5,6 +5,7 @@
  #include "vmx.h"
  #include "nested.h"
  #include "pmu.h"
+#include "tdx.h"
  static bool enable_tdx __ro_after_init;
  module_param_named(tdx, enable_tdx, bool, 0444);

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

Quoted 5 lines
arch/x86/kvm/vmx/main.c +3 -0
@@ -18,6 +19,9 @@ static __init int vt_hardware_setup(void)
  		return ret;
  	enable_tdx = enable_tdx && !tdx_hardware_setup(&vt_x86_ops);
+	if (enable_tdx)
+		vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
+					   sizeof(struct kvm_tdx));

Now I see why you included 'struct kvm_x86_ops' as function parameter.

Quoted 1 line

Please move it to this patch.

Sure.

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

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

Quoted 10 lines
arch/x86/kvm/vmx/main.c +8 -0
+	 * be set before kvm_x86_vendor_init().
+	 */
  	vcpu_size = sizeof(struct vcpu_vmx);
  	vcpu_align = __alignof__(struct vcpu_vmx);
+	if (enable_tdx) {
+		vcpu_size = max_t(unsigned int, vcpu_size,
+				  sizeof(struct vcpu_tdx));
+		vcpu_align = max_t(unsigned int, vcpu_align,
+				   __alignof__(struct vcpu_tdx));
+	}

Since you are updating vm_size in vt_hardware_setup(), I am wondering whether we can do similar thing for vcpu_size and vcpu_align.

Quoted 5 lines

That is, we put them both to 'struct kvm_x86_ops', and you update them in vt_hardware_setup().

kvm_init() can then just access them directly in this way both 'vcpu_size' and 'vcpu_align' function parameters can be removed.

Hmm, now I noticed the vm_size can be moved here. We have

vcpu_size = sizeof(struct vcpu_vmx);

 	vcpu_align = __alignof__(struct vcpu_vmx);
	if (enable_tdx) {
		vcpu_size = max_t(unsigned int, vcpu_size,
				  sizeof(struct vcpu_tdx));
		vcpu_align = max_t(unsigned int, vcpu_align,
				   __alignof__(struct vcpu_tdx));
                vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
                                          sizeof(struct kvm_tdx));
	}

We can add vcpu_size, vcpu_align to struct kvm_x86_ops. If we do so, we have to touch svm code unnecessarily.

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

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

Quoted 6 lines

Here is the updated version.

KVM: TDX: Add placeholders for TDX VM/vcpu structure

Add placeholders TDX VM/vCPU structure, overlaying with the existing

^ structures

"TDX VM/vCPU structure" -> "TDX VM/vCPU structures".

And I don't quite understand what does "overlaying" mean here.

Quoted 6 lines

VMX VM/vCPU structures. Initialize VM structure size and vCPU size/align so that x86 KVM-common code knows those sizes irrespective of VMX or TDX. Those structures will be populated as guest creation logic develops.

TDX requires its data structure for guest and vcpu. For VMX, we

I don't think TDX "requires" anything here. Introducing separate structures are software implementation, but not requirement by TDX.

Quoted 7 lines

already have struct kvm_vmx and struct vcpu_vmx. Two options to add TDX-specific members.

1. Append TDX-specific members to kvm_vmx and vcpu_vmx. Use the same struct for both VMX and TDX.
2. Define TDX-specific data struct and overlay.

Quoted 5 lines

Choose option two because it has less memory overhead and what member is needed is clearer

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

FYI:

Add TDX's own VM and vCPU structures as placeholder to manage and run TDX guests.

TDX protects guest VMs from malicious host. Unlike VMX guests, TDX guests are crypto-protected. KVM cannot access TDX guests' memory and vCPU states directly. Instead, TDX requires KVM to use a set of architecture-defined firmware APIs (a.k.a TDX module SEAMCALLs) to manage and run TDX guests.

In fact, the way to manage and run TDX guests and normal VMX guests are quite different. Because of that, the current structures ('struct kvm_vmx' and 'struct vcpu_vmx') to manage VMX guests are not quite suitable for TDX guests. E.g., the majority of the members of 'struct vcpu_vmx' don't apply to TDX guests.

Introduce TDX's own VM and vCPU structures ('struct kvm_tdx' and 'struct vcpu_tdx' respectively) for KVM to manage and run TDX guests. And instead of building TDX's VM and vCPU structures based on VMX's, build them directly based on 'struct kvm'.

As a result, TDX and VMX will have different VM size and vCPU size/alignment. Adjust the 'vt_x86_ops.vm_size' and the 'vcpu_size' and 'vcpu_align' to the maximum value of TDX guest and VMX guest during module initialization time so that KVM can always allocate enough memory for both TDX guests and VMX guests.

[...]

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

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

Quoted 10 lines
arch/x86/kvm/vmx/main.c +8 -0
+	 * be set before kvm_x86_vendor_init().
+	 */
  	vcpu_size = sizeof(struct vcpu_vmx);
  	vcpu_align = __alignof__(struct vcpu_vmx);
+	if (enable_tdx) {
+		vcpu_size = max_t(unsigned int, vcpu_size,
+				  sizeof(struct vcpu_tdx));
+		vcpu_align = max_t(unsigned int, vcpu_align,
+				   __alignof__(struct vcpu_tdx));
+	}

Since you are updating vm_size in vt_hardware_setup(), I am wondering whether we can do similar thing for vcpu_size and vcpu_align.

Quoted 5 lines

That is, we put them both to 'struct kvm_x86_ops', and you update them in vt_hardware_setup().

kvm_init() can then just access them directly in this way both 'vcpu_size' and 'vcpu_align' function parameters can be removed.

Hmm, now I noticed the vm_size can be moved here. We have

arch/x86/kvm/vmx/main.c +0 -0
 	vcpu_size = sizeof(struct vcpu_vmx);
 	vcpu_align = __alignof__(struct vcpu_vmx);
	if (enable_tdx) {
		vcpu_size = max_t(unsigned int, vcpu_size,
				  sizeof(struct vcpu_tdx));
		vcpu_align = max_t(unsigned int, vcpu_align,
				   __alignof__(struct vcpu_tdx));
                vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
                                          sizeof(struct kvm_tdx));
	}
Quoted 2 lines

We can add vcpu_size, vcpu_align to struct kvm_x86_ops. If we do so, we have to touch svm code unnecessarily.

Not only SVM, but also other architectures, because you are going to remove two function parameters from kvm_init().

That reminds me that other ARCHs may not use 'kvm_x86_ops'-similar thing, so to make thing simple I am fine with your above approach.

#157 lore raw

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

In reply to Isaku Yamahata
Quoted 12 lines · Isaku Yamahata

Hmm, now I noticed the vm_size can be moved here.  We have

  vcpu_size = sizeof(struct vcpu_vmx);

 	vcpu_align = __alignof__(struct vcpu_vmx);
	if (enable_tdx) {
		vcpu_size = max_t(unsigned int, vcpu_size,
				  sizeof(struct vcpu_tdx));
		vcpu_align = max_t(unsigned int, vcpu_align,
				   __alignof__(struct vcpu_tdx));
                vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size,
                                          sizeof(struct kvm_tdx));
	}

Hmm.. After reading again, I don't think we can?

In your comments that was replied to Binbin:

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

You said update to vt_x86_ops.vm_size must be done in vt_hardware_setup().

But I think we should move the above comment to the vt_hardware_setup() where vm_size is truly updated.

/*
* TDX and VMX have different VM structure. If TDX is enabled,
* update vt_x86_ops.vm_size to the maximum value of the two
* before it is copied to kvm_x86_ops in kvm_update_ops() to make
* sure KVM always allocates enough memory for the VM structure. */

Here the purpose to calculate vcpu_size/vcpu_align is just to pass them to kvm_init(). If needed, we can add a comment to describe "what this code does":

/*
* TDX and VMX have different vCPU structure. Calculate the
* maximum size/align so that kvm_init() can use the larger
* values to create the vCPU kmem_cache.
*/

#158 lore raw

PATCH v19 25/130 KVM: TDX: Make TDX VM type supported

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

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

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

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

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

From: Isaku Yamahata <[email protected]>

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

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

Quoted 114 lines

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

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

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

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

From: Isaku Yamahata <[email protected]>

Quoted 7 lines
Quoted 5 lines

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

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

Given I don't have to do step-by-step debug recently, I think it's safe to move it.

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

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

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

From: Isaku Yamahata <[email protected]>

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

Quoted 4 lines
Quoted 1 line

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

Given I don't have to do step-by-step debug recently, I think it's safe to move it.

Even if you have to, I don't think it's a valid reason for "official" patches.

I agree we should move this to the end after all build blocks of running TDX guest is ready.

#162 lore raw

PATCH v19 26/130 The start of TDX KVM patch series: TDX architectural definitions

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

This empty commit is to mark the start of patch series of TDX architectural definitions.

---
 Documentation/virt/kvm/index.rst              |  2 ++
 .../virt/kvm/intel-tdx-layer-status.rst       | 29 +++++++++++++++++++
 2 files changed, 31 insertions(+)
 create mode 100644 Documentation/virt/kvm/intel-tdx-layer-status.rst
Documentation/virt/kvm/index.rst +2 -0
index ad13ec55ddfe..ccff56dca2b1 100644
@@ -19,3 +19,5 @@ KVM
    vcpu-requests
    halt-polling
    review-checklist
+
+   intel-tdx-layer-status
Documentation/virt/kvm/intel-tdx-layer-status.rst new file +29 -0
new file mode 100644
index 000000000000..f11ea701dc19
@@ -0,0 +1,29 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===================================
+Intel Trust Dodmain Extensions(TDX)
+===================================
+
+Layer status
+============
+What qemu can do
+----------------
+- TDX VM TYPE is exposed to Qemu.
+- Qemu can try to create VM of TDX VM type and then fails.
+
+Patch Layer status
+------------------
+  Patch layer                          Status
+
+* TDX, VMX coexistence:                 Applied
+* TDX architectural definitions:        Applying
+* TD VM creation/destruction:           Not yet
+* TD vcpu creation/destruction:         Not yet
+* TDX EPT violation:                    Not yet
+* TD finalization:                      Not yet
+* TD vcpu enter/exit:                   Not yet
+* TD vcpu interrupts/exit/hypercall:    Not yet
+
+* KVM MMU GPA shared bits:              Not yet
+* KVM TDP refactoring for TDX:          Not yet
+* KVM TDP MMU hooks:                    Not yet
Signature · 1 line
2.25.1
#163 lore raw

PATCH v19 27/130 KVM: TDX: Define TDX architectural definitions

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Define architectural definitions for KVM to issue the TDX SEAMCALLs.

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

---
v19:
- drop tdvmcall constants by Xiaoyao

v18:
- Add metadata field id

---
 arch/x86/kvm/vmx/tdx_arch.h | 265 ++++++++++++++++++++++++++++++++++++
 1 file changed, 265 insertions(+)
 create mode 100644 arch/x86/kvm/vmx/tdx_arch.h
arch/x86/kvm/vmx/tdx_arch.h new file +265 -0
new file mode 100644
index 000000000000..e2c1a6f429d7
@@ -0,0 +1,265 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* architectural constants/data definitions for TDX SEAMCALLs */
+
+#ifndef __KVM_X86_TDX_ARCH_H
+#define __KVM_X86_TDX_ARCH_H
+
+#include <linux/types.h>
+
+/*
+ * TDX SEAMCALL API function leaves
+ */
+#define TDH_VP_ENTER			0
+#define TDH_MNG_ADDCX			1
+#define TDH_MEM_PAGE_ADD		2
+#define TDH_MEM_SEPT_ADD		3
+#define TDH_VP_ADDCX			4
+#define TDH_MEM_PAGE_RELOCATE		5
+#define TDH_MEM_PAGE_AUG		6
+#define TDH_MEM_RANGE_BLOCK		7
+#define TDH_MNG_KEY_CONFIG		8
+#define TDH_MNG_CREATE			9
+#define TDH_VP_CREATE			10
+#define TDH_MNG_RD			11
+#define TDH_MR_EXTEND			16
+#define TDH_MR_FINALIZE			17
+#define TDH_VP_FLUSH			18
+#define TDH_MNG_VPFLUSHDONE		19
+#define TDH_MNG_KEY_FREEID		20
+#define TDH_MNG_INIT			21
+#define TDH_VP_INIT			22
+#define TDH_MEM_SEPT_RD			25
+#define TDH_VP_RD			26
+#define TDH_MNG_KEY_RECLAIMID		27
+#define TDH_PHYMEM_PAGE_RECLAIM		28
+#define TDH_MEM_PAGE_REMOVE		29
+#define TDH_MEM_SEPT_REMOVE		30
+#define TDH_SYS_RD			34
+#define TDH_MEM_TRACK			38
+#define TDH_MEM_RANGE_UNBLOCK		39
+#define TDH_PHYMEM_CACHE_WB		40
+#define TDH_PHYMEM_PAGE_WBINVD		41
+#define TDH_VP_WR			43
+#define TDH_SYS_LP_SHUTDOWN		44
+
+/* TDX control structure (TDR/TDCS/TDVPS) field access codes */
+#define TDX_NON_ARCH			BIT_ULL(63)
+#define TDX_CLASS_SHIFT			56
+#define TDX_FIELD_MASK			GENMASK_ULL(31, 0)
+
+#define __BUILD_TDX_FIELD(non_arch, class, field)	\
+	(((non_arch) ? TDX_NON_ARCH : 0) |		\
+	 ((u64)(class) << TDX_CLASS_SHIFT) |		\
+	 ((u64)(field) & TDX_FIELD_MASK))
+
+#define BUILD_TDX_FIELD(class, field)			\
+	__BUILD_TDX_FIELD(false, (class), (field))
+
+#define BUILD_TDX_FIELD_NON_ARCH(class, field)		\
+	__BUILD_TDX_FIELD(true, (class), (field))
+
+
+/* Class code for TD */
+#define TD_CLASS_EXECUTION_CONTROLS	17ULL
+
+/* Class code for TDVPS */
+#define TDVPS_CLASS_VMCS		0ULL
+#define TDVPS_CLASS_GUEST_GPR		16ULL
+#define TDVPS_CLASS_OTHER_GUEST		17ULL
+#define TDVPS_CLASS_MANAGEMENT		32ULL
+
+enum tdx_tdcs_execution_control {
+	TD_TDCS_EXEC_TSC_OFFSET = 10,
+};
+
+/* @field is any of enum tdx_tdcs_execution_control */
+#define TDCS_EXEC(field)		BUILD_TDX_FIELD(TD_CLASS_EXECUTION_CONTROLS, (field))
+
+/* @field is the VMCS field encoding */
+#define TDVPS_VMCS(field)		BUILD_TDX_FIELD(TDVPS_CLASS_VMCS, (field))
+
+enum tdx_vcpu_guest_other_state {
+	TD_VCPU_STATE_DETAILS_NON_ARCH = 0x100,
+};
+
+union tdx_vcpu_state_details {
+	struct {
+		u64 vmxip	: 1;
+		u64 reserved	: 63;
+	};
+	u64 full;
+};
+
+/* @field is any of enum tdx_guest_other_state */
+#define TDVPS_STATE(field)		BUILD_TDX_FIELD(TDVPS_CLASS_OTHER_GUEST, (field))
+#define TDVPS_STATE_NON_ARCH(field)	BUILD_TDX_FIELD_NON_ARCH(TDVPS_CLASS_OTHER_GUEST, (field))
+
+/* Management class fields */
+enum tdx_vcpu_guest_management {
+	TD_VCPU_PEND_NMI = 11,
+};
+
+/* @field is any of enum tdx_vcpu_guest_management */
+#define TDVPS_MANAGEMENT(field)		BUILD_TDX_FIELD(TDVPS_CLASS_MANAGEMENT, (field))
+
+#define TDX_EXTENDMR_CHUNKSIZE		256
+
+struct tdx_cpuid_value {
+	u32 eax;
+	u32 ebx;
+	u32 ecx;
+	u32 edx;
+} __packed;
+
+#define TDX_TD_ATTRIBUTE_DEBUG		BIT_ULL(0)
+#define TDX_TD_ATTR_SEPT_VE_DISABLE	BIT_ULL(28)
+#define TDX_TD_ATTRIBUTE_PKS		BIT_ULL(30)
+#define TDX_TD_ATTRIBUTE_KL		BIT_ULL(31)
+#define TDX_TD_ATTRIBUTE_PERFMON	BIT_ULL(63)
+
+/*
+ * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
+ */
+#define TDX_MAX_VCPUS	(~(u16)0)
+
+struct td_params {
+	u64 attributes;
+	u64 xfam;
+	u16 max_vcpus;
+	u8 reserved0[6];
+
+	u64 eptp_controls;
+	u64 exec_controls;
+	u16 tsc_frequency;
+	u8  reserved1[38];
+
+	u64 mrconfigid[6];
+	u64 mrowner[6];
+	u64 mrownerconfig[6];
+	u64 reserved2[4];
+
+	union {
+		DECLARE_FLEX_ARRAY(struct tdx_cpuid_value, cpuid_values);
+		u8 reserved3[768];
+	};
+} __packed __aligned(1024);
+
+/*
+ * Guest uses MAX_PA for GPAW when set.
+ * 0: GPA.SHARED bit is GPA[47]
+ * 1: GPA.SHARED bit is GPA[51]
+ */
+#define TDX_EXEC_CONTROL_MAX_GPAW      BIT_ULL(0)
+
+/*
+ * TDH.VP.ENTER, TDG.VP.VMCALL preserves RBP
+ * 0: RBP can be used for TDG.VP.VMCALL input. RBP is clobbered.
+ * 1: RBP can't be used for TDG.VP.VMCALL input. RBP is preserved.
+ */
+#define TDX_CONTROL_FLAG_NO_RBP_MOD	BIT_ULL(2)
+
+
+/*
+ * TDX requires the frequency to be defined in units of 25MHz, which is the
+ * frequency of the core crystal clock on TDX-capable platforms, i.e. the TDX
+ * module can only program frequencies that are multiples of 25MHz.  The
+ * frequency must be between 100mhz and 10ghz (inclusive).
+ */
+#define TDX_TSC_KHZ_TO_25MHZ(tsc_in_khz)	((tsc_in_khz) / (25 * 1000))
+#define TDX_TSC_25MHZ_TO_KHZ(tsc_in_25mhz)	((tsc_in_25mhz) * (25 * 1000))
+#define TDX_MIN_TSC_FREQUENCY_KHZ		(100 * 1000)
+#define TDX_MAX_TSC_FREQUENCY_KHZ		(10 * 1000 * 1000)
+
+union tdx_sept_entry {
+	struct {
+		u64 r		:  1;
+		u64 w		:  1;
+		u64 x		:  1;
+		u64 mt		:  3;
+		u64 ipat	:  1;
+		u64 leaf	:  1;
+		u64 a		:  1;
+		u64 d		:  1;
+		u64 xu		:  1;
+		u64 ignored0	:  1;
+		u64 pfn		: 40;
+		u64 reserved	:  5;
+		u64 vgp		:  1;
+		u64 pwa		:  1;
+		u64 ignored1	:  1;
+		u64 sss		:  1;
+		u64 spp		:  1;
+		u64 ignored2	:  1;
+		u64 sve		:  1;
+	};
+	u64 raw;
+};
+
+enum tdx_sept_entry_state {
+	TDX_SEPT_FREE = 0,
+	TDX_SEPT_BLOCKED = 1,
+	TDX_SEPT_PENDING = 2,
+	TDX_SEPT_PENDING_BLOCKED = 3,
+	TDX_SEPT_PRESENT = 4,
+};
+
+union tdx_sept_level_state {
+	struct {
+		u64 level	:  3;
+		u64 reserved0	:  5;
+		u64 state	:  8;
+		u64 reserved1	: 48;
+	};
+	u64 raw;
+};
+
+/*
+ * Global scope metadata field ID.
+ * See Table "Global Scope Metadata", TDX module 1.5 ABI spec.
+ */
+#define MD_FIELD_ID_SYS_ATTRIBUTES		0x0A00000200000000ULL
+#define MD_FIELD_ID_FEATURES0			0x0A00000300000008ULL
+#define MD_FIELD_ID_ATTRS_FIXED0		0x1900000300000000ULL
+#define MD_FIELD_ID_ATTRS_FIXED1		0x1900000300000001ULL
+#define MD_FIELD_ID_XFAM_FIXED0			0x1900000300000002ULL
+#define MD_FIELD_ID_XFAM_FIXED1			0x1900000300000003ULL
+
+#define MD_FIELD_ID_TDCS_BASE_SIZE		0x9800000100000100ULL
+#define MD_FIELD_ID_TDVPS_BASE_SIZE		0x9800000100000200ULL
+
+#define MD_FIELD_ID_NUM_CPUID_CONFIG		0x9900000100000004ULL
+#define MD_FIELD_ID_CPUID_CONFIG_LEAVES		0x9900000300000400ULL
+#define MD_FIELD_ID_CPUID_CONFIG_VALUES		0x9900000300000500ULL
+
+#define MD_FIELD_ID_FEATURES0_NO_RBP_MOD	BIT_ULL(18)
+
+#define TDX_MAX_NR_CPUID_CONFIGS       37
+
+#define TDX_MD_ELEMENT_SIZE_8BITS      0
+#define TDX_MD_ELEMENT_SIZE_16BITS     1
+#define TDX_MD_ELEMENT_SIZE_32BITS     2
+#define TDX_MD_ELEMENT_SIZE_64BITS     3
+
+union tdx_md_field_id {
+	struct {
+		u64 field                       : 24;
+		u64 reserved0                   : 8;
+		u64 element_size_code           : 2;
+		u64 last_element_in_field       : 4;
+		u64 reserved1                   : 3;
+		u64 inc_size                    : 1;
+		u64 write_mask_valid            : 1;
+		u64 context                     : 3;
+		u64 reserved2                   : 1;
+		u64 class                       : 6;
+		u64 reserved3                   : 1;
+		u64 non_arch                    : 1;
+	};
+	u64 raw;
+};
+
+#define TDX_MD_ELEMENT_SIZE_CODE(_field_id)			\
+	({ union tdx_md_field_id _fid = { .raw = (_field_id)};  \
+		_fid.element_size_code; })
+
+#endif /* __KVM_X86_TDX_ARCH_H */
Signature · 1 line
2.25.1
#164 lore raw

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

Quoted 3 lines

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

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

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

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

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

#165 lore raw

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

Quoted 6 lines · Yan Zhao
Quoted 3 lines

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

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

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

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

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

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

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

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

Quoted 22 lines · Isaku Yamahata
Quoted 6 lines · Yan Zhao
Quoted 3 lines

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

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

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

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

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

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

[...]

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	u16 max_vcpus_per_td;
+

[...]

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +2 -1
-	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);
+	kvm->max_vcpus = min3(kvm->max_vcpus, tdx_info->max_vcpus_per_td,
+			     TDX_MAX_VCPUS);

[...]

arch/x86/kvm/vmx/tdx_arch.h struct tdx_cpuid_value { · line 147

Quoted 2 lines
arch/x86/kvm/vmx/tdx_arch.h +1 -1
-#define TDX_MAX_VCPUS	(~(u16)0)
+#define TDX_MAX_VCPUS	((int)U16_MAX)

Why do you even need TDX_MAX_VCPUS, given it cannot exceed U16_MAX and you will have the 'u16 max_vcpus_per_td' anyway?

IIUC, in KVM_ENABLE_CAP(KVM_CAP_MAX_VCPUS), we can overwrite the kvm->max_vcpus to the 'max_vcpus' provided by the userspace, and make sure it doesn't exceed tdx_info->max_vcpus_per_td.

Anything I am missing?

#167 lore raw

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

Quoted 45 lines · Kai
Quoted 22 lines · Isaku Yamahata
Quoted 6 lines · Yan Zhao
Quoted 3 lines

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

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

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

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

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

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

[...]

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	u16 max_vcpus_per_td;
+

[...]

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +2 -1
-	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);
+	kvm->max_vcpus = min3(kvm->max_vcpus, tdx_info->max_vcpus_per_td,
+			     TDX_MAX_VCPUS);

[...]

arch/x86/kvm/vmx/tdx_arch.h struct tdx_cpuid_value { · line 147

Quoted 2 lines
arch/x86/kvm/vmx/tdx_arch.h +1 -1
-#define TDX_MAX_VCPUS	(~(u16)0)
+#define TDX_MAX_VCPUS	((int)U16_MAX)

Why do you even need TDX_MAX_VCPUS, given it cannot exceed U16_MAX and you will have the 'u16 max_vcpus_per_td' anyway?

Quoted 5 lines

IIUC, in KVM_ENABLE_CAP(KVM_CAP_MAX_VCPUS), we can overwrite the kvm->max_vcpus to the 'max_vcpus' provided by the userspace, and make sure it doesn't exceed tdx_info->max_vcpus_per_td.

Anything I am missing?

With the latest TDX 1.5 module, we don't need TDX_MAX_VCPUS.

The metadata MD_FIELD_ID_MAX_VCPUS_PER_TD was introduced at the middle version of TDX 1.5. (I don't remember the exact version.), the logic was something like as follows. Now if we fail to read the metadata, disable TDX.

read metadata MD_FIELD_ID_MAX_VCPUS_PER_TD; if success
tdx_info->max_vcpu_per_td = the value read metadata
else
tdx_info->max_vcpu_per_td = TDX_MAX_VCPUS;

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

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

Quoted 60 lines · Isaku
Quoted 45 lines · Kai
Quoted 22 lines · Isaku Yamahata
Quoted 6 lines · Yan Zhao
Quoted 3 lines

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

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

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

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

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

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

[...]

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	u16 max_vcpus_per_td;
+

[...]

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +2 -1
-	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);
+	kvm->max_vcpus = min3(kvm->max_vcpus, tdx_info->max_vcpus_per_td,
+			     TDX_MAX_VCPUS);

[...]

arch/x86/kvm/vmx/tdx_arch.h struct tdx_cpuid_value { · line 147

Quoted 2 lines
arch/x86/kvm/vmx/tdx_arch.h +1 -1
-#define TDX_MAX_VCPUS	(~(u16)0)
+#define TDX_MAX_VCPUS	((int)U16_MAX)

Why do you even need TDX_MAX_VCPUS, given it cannot exceed U16_MAX and you will have the 'u16 max_vcpus_per_td' anyway?

Quoted 5 lines

IIUC, in KVM_ENABLE_CAP(KVM_CAP_MAX_VCPUS), we can overwrite the kvm->max_vcpus to the 'max_vcpus' provided by the userspace, and make sure it doesn't exceed tdx_info->max_vcpus_per_td.

Anything I am missing?

With the latest TDX 1.5 module, we don't need TDX_MAX_VCPUS.

The metadata MD_FIELD_ID_MAX_VCPUS_PER_TD was introduced at the middle version of TDX 1.5. (I don't remember the exact version.), the logic was something like as follows. Now if we fail to read the metadata, disable TDX.

Quoted 6 lines

read metadata MD_FIELD_ID_MAX_VCPUS_PER_TD; if success
tdx_info->max_vcpu_per_td = the value read metadata
else
tdx_info->max_vcpu_per_td = TDX_MAX_VCPUS;

OK. But even the SEAMCALL can fail, we can just use U16_MAX directly when it fails given we can see clearly the type of max_vcpu_per_td is 'u16'.

if success

	tdx_info->max_vcpu_per_td = the value read metadata
else
	tdx_info->max_vcpu_per_td = U16_MAX;

So I don't see why TDX_MAX_VCPUS is needed (especially in tdx_arch.h as it is not an architectural value but just some value chosen for our convenience).

#169 lore raw

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

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

From: Isaku Yamahata <[email protected]>

Define architectural definitions for KVM to issue the TDX SEAMCALLs.

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

---
v19:
- drop tdvmcall constants by Xiaoyao

v18:
- Add metadata field id

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

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

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

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

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

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

Either use TDX_TD_ATTR_* or TDX_TD_ATTRIBUTE_*?

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

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

Quoted 5 lines · Binbin Wu

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

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

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

Either use TDX_TD_ATTR_* or TDX_TD_ATTRIBUTE_*?

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

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

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

In reply to [email protected]

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +9 -0
+/*
+ * TDX SEAMCALL API function leaves
+ */
+#define TDH_VP_ENTER			0
+#define TDH_MNG_ADDCX			1
+#define TDH_MEM_PAGE_ADD		2
+#define TDH_MEM_SEPT_ADD		3
+#define TDH_VP_ADDCX			4
+#define TDH_MEM_PAGE_RELOCATE		5

I don't think the "RELOCATE" is needed in this patchset?

Quoted 16 lines
arch/x86/kvm/vmx/tdx_arch.h new file +16 -0
+#define TDH_MEM_PAGE_AUG		6
+#define TDH_MEM_RANGE_BLOCK		7
+#define TDH_MNG_KEY_CONFIG		8
+#define TDH_MNG_CREATE			9
+#define TDH_VP_CREATE			10
+#define TDH_MNG_RD			11
+#define TDH_MR_EXTEND			16
+#define TDH_MR_FINALIZE			17
+#define TDH_VP_FLUSH			18
+#define TDH_MNG_VPFLUSHDONE		19
+#define TDH_MNG_KEY_FREEID		20
+#define TDH_MNG_INIT			21
+#define TDH_VP_INIT			22
+#define TDH_MEM_SEPT_RD			25
+#define TDH_VP_RD			26
+#define TDH_MNG_KEY_RECLAIMID		27

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+#define TDH_PHYMEM_PAGE_RECLAIM		28
+#define TDH_MEM_PAGE_REMOVE		29
+#define TDH_MEM_SEPT_REMOVE		30
+#define TDH_SYS_RD			34
+#define TDH_MEM_TRACK			38
+#define TDH_MEM_RANGE_UNBLOCK		39
+#define TDH_PHYMEM_CACHE_WB		40
+#define TDH_PHYMEM_PAGE_WBINVD		41
+#define TDH_VP_WR			43
+#define TDH_SYS_LP_SHUTDOWN		44

And LP_SHUTDOWN is certainly not needed.

Could you check whether there are others that are not needed?

Perhaps we should just include macros that got used, but anyway.

[...]

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx_arch.h new file +4 -0
+
+/*
+ * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
+ */

Why is this comment applied to TDX_MAX_VCPUS?

Quoted 1 line

+#define TDX_MAX_VCPUS (~(u16)0)

And is (~(16)0) an architectural value defined by TDX spec, or just SW value that you just put here for convenience?

I mean, is it possible that different version of TDX module have different implementation of MAX_CPU, e.g., module 1.0 only supports X but module 1.5 increases to Y where Y > X?

Anyway, looks you can safely move this to the patch to enable CAP_MAX_CPU?

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+
+struct td_params {
+	u64 attributes;
+	u64 xfam;
+	u16 max_vcpus;
+	u8 reserved0[6];
+
+	u64 eptp_controls;
+	u64 exec_controls;
+	u16 tsc_frequency;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+	u8  reserved1[38];
+
+	u64 mrconfigid[6];
+	u64 mrowner[6];
+	u64 mrownerconfig[6];
+	u64 reserved2[4];
+
+	union {
+		DECLARE_FLEX_ARRAY(struct tdx_cpuid_value, cpuid_values);
+		u8 reserved3[768];

I am not sure you need the 'reseved3[768]', unless you need to make sieof(struct td_params) return 1024?

Quoted 2 lines
(quoted diff) +2 -0
+	};
+} __packed __aligned(1024); > +

[...]

Quoted 13 lines
arch/x86/kvm/vmx/tdx_arch.h new file +13 -0
+
+#define TDX_MD_ELEMENT_SIZE_8BITS      0
+#define TDX_MD_ELEMENT_SIZE_16BITS     1
+#define TDX_MD_ELEMENT_SIZE_32BITS     2
+#define TDX_MD_ELEMENT_SIZE_64BITS     3
+
+union tdx_md_field_id {
+	struct {
+		u64 field                       : 24;
+		u64 reserved0                   : 8;
+		u64 element_size_code           : 2;
+		u64 last_element_in_field       : 4;
+		u64 reserved1                   : 3;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+		u64 inc_size                    : 1;
+		u64 write_mask_valid            : 1;
+		u64 context                     : 3;
+		u64 reserved2                   : 1;
+		u64 class                       : 6;
+		u64 reserved3                   : 1;
+		u64 non_arch                    : 1;
+	};
+	u64 raw;
+};

Could you clarify why we need such detailed definition? For metadata element size you can use simple '&' and '<<' to get the result.

Quoted 6 lines
arch/x86/kvm/vmx/tdx_arch.h new file +6 -0
+
+#define TDX_MD_ELEMENT_SIZE_CODE(_field_id)			\
+	({ union tdx_md_field_id _fid = { .raw = (_field_id)};  \
+		_fid.element_size_code; })
+
+#endif /* __KVM_X86_TDX_ARCH_H */
#172 lore raw

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

Quoted 42 lines · Kai

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +9 -0
+/*
+ * TDX SEAMCALL API function leaves
+ */
+#define TDH_VP_ENTER			0
+#define TDH_MNG_ADDCX			1
+#define TDH_MEM_PAGE_ADD		2
+#define TDH_MEM_SEPT_ADD		3
+#define TDH_VP_ADDCX			4
+#define TDH_MEM_PAGE_RELOCATE		5

I don't think the "RELOCATE" is needed in this patchset?

Quoted 16 lines
arch/x86/kvm/vmx/tdx_arch.h new file +16 -0
+#define TDH_MEM_PAGE_AUG		6
+#define TDH_MEM_RANGE_BLOCK		7
+#define TDH_MNG_KEY_CONFIG		8
+#define TDH_MNG_CREATE			9
+#define TDH_VP_CREATE			10
+#define TDH_MNG_RD			11
+#define TDH_MR_EXTEND			16
+#define TDH_MR_FINALIZE			17
+#define TDH_VP_FLUSH			18
+#define TDH_MNG_VPFLUSHDONE		19
+#define TDH_MNG_KEY_FREEID		20
+#define TDH_MNG_INIT			21
+#define TDH_VP_INIT			22
+#define TDH_MEM_SEPT_RD			25
+#define TDH_VP_RD			26
+#define TDH_MNG_KEY_RECLAIMID		27

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+#define TDH_PHYMEM_PAGE_RECLAIM		28
+#define TDH_MEM_PAGE_REMOVE		29
+#define TDH_MEM_SEPT_REMOVE		30
+#define TDH_SYS_RD			34
+#define TDH_MEM_TRACK			38
+#define TDH_MEM_RANGE_UNBLOCK		39
+#define TDH_PHYMEM_CACHE_WB		40
+#define TDH_PHYMEM_PAGE_WBINVD		41
+#define TDH_VP_WR			43
+#define TDH_SYS_LP_SHUTDOWN		44

And LP_SHUTDOWN is certainly not needed.

Quoted 3 lines

Could you check whether there are others that are not needed?

Perhaps we should just include macros that got used, but anyway.

Ok, let's break this patch into other patches that uses the constants first.

Quoted 6 lines
Quoted 3 lines

+/*
+ * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
+ */

Why is this comment applied to TDX_MAX_VCPUS?

Quoted 8 lines
Quoted 1 line

+#define TDX_MAX_VCPUS (~(u16)0)

And is (~(16)0) an architectural value defined by TDX spec, or just SW value that you just put here for convenience?

I mean, is it possible that different version of TDX module have different implementation of MAX_CPU, e.g., module 1.0 only supports X but module 1.5 increases to Y where Y > X?

This is architectural because it the field width is 16 bits. Each version of TDX module may have their own limitation with metadata, MAX_VCPUS_PER_TD.

Quoted 1 line

Anyway, looks you can safely move this to the patch to enable CAP_MAX_CPU?

Yes.

Quoted 15 lines
Quoted 15 lines
arch/x86/kvm/vmx/tdx_arch.h new file +15 -0
+
+struct td_params {
+	u64 attributes;
+	u64 xfam;
+	u16 max_vcpus;
+	u8 reserved0[6];
+
+	u64 eptp_controls;
+	u64 exec_controls;
+	u16 tsc_frequency;
+	u8  reserved1[38];
+
+	u64 mrconfigid[6];
+	u64 mrowner[6];
+	u64 mrownerconfig[6];
Quoted 8 lines

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

Quoted 5 lines
arch/x86/kvm/vmx/tdx_arch.h new file +5 -0
+	u64 reserved2[4];
+
+	union {
+		DECLARE_FLEX_ARRAY(struct tdx_cpuid_value, cpuid_values);
+		u8 reserved3[768];

I am not sure you need the 'reseved3[768]', unless you need to make sieof(struct td_params) return 1024?

I'm trying to make it 1024 because the spec defines the struct size is 1024. Maybe I can add BUILD_BUG_ON(sizeof(struct td_params) != 1024);

Quoted 17 lines
Quoted 17 lines
arch/x86/kvm/vmx/tdx_arch.h new file +17 -0
+#define TDX_MD_ELEMENT_SIZE_8BITS      0
+#define TDX_MD_ELEMENT_SIZE_16BITS     1
+#define TDX_MD_ELEMENT_SIZE_32BITS     2
+#define TDX_MD_ELEMENT_SIZE_64BITS     3
+
+union tdx_md_field_id {
+	struct {
+		u64 field                       : 24;
+		u64 reserved0                   : 8;
+		u64 element_size_code           : 2;
+		u64 last_element_in_field       : 4;
+		u64 reserved1                   : 3;
+		u64 inc_size                    : 1;
+		u64 write_mask_valid            : 1;
+		u64 context                     : 3;
+		u64 reserved2                   : 1;
+		u64 class                       : 6;
Quoted 8 lines

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

Quoted 5 lines
arch/x86/kvm/vmx/tdx_arch.h new file +5 -0
+		u64 reserved3                   : 1;
+		u64 non_arch                    : 1;
+	};
+	u64 raw;
+};

Could you clarify why we need such detailed definition? For metadata element size you can use simple '&' and '<<' to get the result.

Now your TDX host patch has the definition in arch/x86/include/asm/tdx.h, I'll eliminate this one here and use your definition.

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

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

In reply to [email protected]
Quoted 135 lines · On Mon, Feb 26, 2024 at 12:25:29AM -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Define architectural definitions for KVM to issue the TDX SEAMCALLs.

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

---
v19:
- drop tdvmcall constants by Xiaoyao

v18:
- Add metadata field id

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

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

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

This series doesn't really touch off-TD things, so you can remove this.

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

2.25.1

#174 lore raw

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

Quoted 140 lines · Yuan Yao
Quoted 139 lines · On Mon, Feb 26, 2024 at 12:25:29AM -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Define architectural definitions for KVM to issue the TDX SEAMCALLs.

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

---
v19:
- drop tdvmcall constants by Xiaoyao

v18:
- Add metadata field id

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

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx_arch.h new file +6 -0
+	u32 ebx;
+	u32 ecx;
+	u32 edx;
+} __packed;
+
+#define TDX_TD_ATTRIBUTE_DEBUG		BIT_ULL(0)

This series doesn't really touch off-TD things, so you can remove this.

Yes. I'll clean up to delete unused ones including this.

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

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

In reply to [email protected]

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

Quoted 7 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx_arch.h new file +7 -0
+union tdx_vcpu_state_details {
+	struct {
+		u64 vmxip	: 1;
+		u64 reserved	: 63;
+	};
+	u64 full;
+};

No unions please. KVM uses unions in a few places where they are the lesser of all evils, but in general, unions are frowned upon. Bitfields in particular are strongly discourage, as they are a nightmare to read/review and tend to generate bad code.

E.g. for this one, something like (names aren't great)

static inline bool tdx_has_pending_virtual_interrupt(struct kvm_vcpu *vcpu)

{
	return <get "non arch field"> & TDX_VCPU_STATE_VMXIP;
}
Quoted 11 lines
arch/x86/kvm/vmx/tdx_arch.h new file +11 -0
+union tdx_sept_entry {
+	struct {
+		u64 r		:  1;
+		u64 w		:  1;
+		u64 x		:  1;
+		u64 mt		:  3;
+		u64 ipat	:  1;
+		u64 leaf	:  1;
+		u64 a		:  1;
+		u64 d		:  1;
+		u64 xu		:  1;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+		u64 ignored0	:  1;
+		u64 pfn		: 40;
+		u64 reserved	:  5;
+		u64 vgp		:  1;
+		u64 pwa		:  1;
+		u64 ignored1	:  1;
+		u64 sss		:  1;
+		u64 spp		:  1;
+		u64 ignored2	:  1;
+		u64 sve		:  1;

Yeah, NAK to these unions. They are crappy duplicates of existing definitions, e.g. it took me a few seconds to realize SVE is SUPPRESS_VE, which is far too long.

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+	};
+	u64 raw;
+};
+enum tdx_sept_entry_state {
+	TDX_SEPT_FREE = 0,
+	TDX_SEPT_BLOCKED = 1,
+	TDX_SEPT_PENDING = 2,
+	TDX_SEPT_PENDING_BLOCKED = 3,
+	TDX_SEPT_PRESENT = 4,
+};

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+
+union tdx_sept_level_state {
+	struct {
+		u64 level	:  3;
+		u64 reserved0	:  5;
+		u64 state	:  8;
+		u64 reserved1	: 48;
+	};
+	u64 raw;
+};

Similar thing here. Depending on what happens with the SEAMCALL argument mess, the code can look somethign like:

static u8 tdx_get_sept_level(struct tdx_module_args *out)

{
	return out->rdx & TDX_SEPT_LEVEL_MASK;
}

static u8 tdx_get_sept_state(struct tdx_module_args *out)

{
	return (out->rdx & TDX_SEPT_STATE_MASK) >> TDX_SEPT_STATE_SHIFT;
}
Quoted 11 lines
arch/x86/kvm/vmx/tdx_arch.h new file +11 -0
+union tdx_md_field_id {
+	struct {
+		u64 field                       : 24;
+		u64 reserved0                   : 8;
+		u64 element_size_code           : 2;
+		u64 last_element_in_field       : 4;
+		u64 reserved1                   : 3;
+		u64 inc_size                    : 1;
+		u64 write_mask_valid            : 1;
+		u64 context                     : 3;
+		u64 reserved2                   : 1;

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_arch.h new file +10 -0
+		u64 class                       : 6;
+		u64 reserved3                   : 1;
+		u64 non_arch                    : 1;
+	};
+	u64 raw;
+};
+
+#define TDX_MD_ELEMENT_SIZE_CODE(_field_id)			\
+	({ union tdx_md_field_id _fid = { .raw = (_field_id)};  \
+		_fid.element_size_code; })

Yeah, no thanks. MASK + SHIFT will do just fine.

#176 lore raw

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

Quoted 14 lines · Sean Christopherson

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

Quoted 7 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx_arch.h new file +7 -0
+union tdx_vcpu_state_details {
+	struct {
+		u64 vmxip	: 1;
+		u64 reserved	: 63;
+	};
+	u64 full;
+};

No unions please. KVM uses unions in a few places where they are the lesser of all evils, but in general, unions are frowned upon. Bitfields in particular are strongly discourage, as they are a nightmare to read/review and tend to generate bad code.

Quoted 6 lines

E.g. for this one, something like (names aren't great)

static inline bool tdx_has_pending_virtual_interrupt(struct kvm_vcpu *vcpu)

{
	return <get "non arch field"> & TDX_VCPU_STATE_VMXIP;
}

Sure, let me replace them with mask and shift.

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

PATCH v19 28/130 KVM: TDX: Add TDX "architectural" error codes

In reply to [email protected]

From: Sean Christopherson <[email protected]>

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

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

---
v19:
- Drop TDX_EPT_WALK_FAILED, TDX_EPT_ENTRY_NOT_FREE
- Rename TDG_VP_VMCALL_ => TDVMCALL_ to match the existing code
- Move TDVMCALL error codes to shared/tdx.h
- Added TDX_OPERAND_ID_TDR

---
 arch/x86/include/asm/shared/tdx.h |  8 +++++++-
 arch/x86/kvm/vmx/tdx_errno.h      | 34 +++++++++++++++++++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100644 arch/x86/kvm/vmx/tdx_errno.h
arch/x86/include/asm/shared/tdx.h +7 -1
index fdfd41511b02..28c4a62b7dba 100644
@@ -26,7 +26,13 @@
 #define TDVMCALL_GET_QUOTE		0x10002
 #define TDVMCALL_REPORT_FATAL_ERROR	0x10003
 
-#define TDVMCALL_STATUS_RETRY		1
+/*
+ * TDG.VP.VMCALL Status Codes (returned in R10)
+ */
+#define TDVMCALL_SUCCESS		0x0000000000000000ULL
+#define TDVMCALL_RETRY			0x0000000000000001ULL
+#define TDVMCALL_INVALID_OPERAND	0x8000000000000000ULL
+#define TDVMCALL_TDREPORT_FAILED	0x8000000000000001ULL
 
 /*
  * Bitmasks of exposed registers (with VMM).
arch/x86/kvm/vmx/tdx_errno.h new file +34 -0
new file mode 100644
index 000000000000..5366bf476d2c
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* architectural status code for SEAMCALL */
+
+#ifndef __KVM_X86_TDX_ERRNO_H
+#define __KVM_X86_TDX_ERRNO_H
+
+#define TDX_SEAMCALL_STATUS_MASK		0xFFFFFFFF00000000ULL
+
+/*
+ * TDX SEAMCALL Status Codes (returned in RAX)
+ */
+#define TDX_NON_RECOVERABLE_VCPU		0x4000000100000000ULL
+#define TDX_INTERRUPTED_RESUMABLE		0x8000000300000000ULL
+#define TDX_OPERAND_INVALID			0xC000010000000000ULL
+#define TDX_OPERAND_BUSY			0x8000020000000000ULL
+#define TDX_PREVIOUS_TLB_EPOCH_BUSY		0x8000020100000000ULL
+#define TDX_VCPU_NOT_ASSOCIATED			0x8000070200000000ULL
+#define TDX_KEY_GENERATION_FAILED		0x8000080000000000ULL
+#define TDX_KEY_STATE_INCORRECT			0xC000081100000000ULL
+#define TDX_KEY_CONFIGURED			0x0000081500000000ULL
+#define TDX_NO_HKID_READY_TO_WBCACHE		0x0000082100000000ULL
+#define TDX_FLUSHVP_NOT_DONE			0x8000082400000000ULL
+#define TDX_EPT_ENTRY_STATE_INCORRECT		0xC0000B0D00000000ULL
+
+/*
+ * TDX module operand ID, appears in 31:0 part of error code as
+ * detail information
+ */
+#define TDX_OPERAND_ID_RCX			0x01
+#define TDX_OPERAND_ID_TDR			0x80
+#define TDX_OPERAND_ID_SEPT			0x92
+#define TDX_OPERAND_ID_TD_EPOCH			0xa9
+
+#endif /* __KVM_X86_TDX_ERRNO_H */
Signature · 1 line
2.25.1
#178 lore raw

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

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

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

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

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

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

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

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

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

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

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

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

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

Quoted 16 lines · Binbin Wu
Quoted 12 lines · Isaku Yamahata

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

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

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

Quoted 4 lines

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

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

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

PATCH v19 29/130 KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]

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.

Define C wrapper functions for SEAMCALLs for readability.

Some SEAMCALL APIs donate host pages to TDX module or guest TD, and the donated pages are encrypted. Those require the VMM to flush the cache lines to avoid cache line alias.

---
Changes
v19:
- Update the commit message to match the patch by Yuan
- Use seamcall() and seamcall_ret() by paolo

v18:
- removed stub functions for __seamcall{,_ret}()
- Added Reviewed-by Binbin
- Make tdx_seamcall() use struct tdx_module_args instead of taking each inputs.

v15 -> v16:
- use struct tdx_module_args instead of struct tdx_module_output
- Add tdh_mem_sept_rd() for SEPT_VE_DISABLE=1.

---
 arch/x86/kvm/vmx/tdx_ops.h | 360 +++++++++++++++++++++++++++++++++++++
 1 file changed, 360 insertions(+)
 create mode 100644 arch/x86/kvm/vmx/tdx_ops.h
arch/x86/kvm/vmx/tdx_ops.h new file +360 -0
new file mode 100644
index 000000000000..c5bb165b260e
@@ -0,0 +1,360 @@
+/* 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 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);
+
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {
+		/*
+		 * SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off.
+		 * This can happen when the host gets rebooted or live
+		 * updated. In this case, the instruction execution is ignored
+		 * as KVM is shut down, so the error code is suppressed. Other
+		 * than this, the error is unexpected and the execution can't
+		 * continue as the TDX features reply on VMX to be on.
+		 */
+		kvm_spurious_fault();
+		return 0;
+	}
+	return ret;
+}
+
+static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
+{
+	struct tdx_module_args in = {
+		.rcx = addr,
+		.rdx = tdr,
+	};
+
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+	return tdx_seamcall(TDH_MNG_ADDCX, &in, NULL);
+}
+
+static inline u64 tdh_mem_page_add(hpa_t tdr, gpa_t gpa, hpa_t hpa, hpa_t source,
+				   struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa,
+		.rdx = tdr,
+		.r8 = hpa,
+		.r9 = source,
+	};
+
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_PAGE_ADD, &in, out);
+}
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level, hpa_t page,
+				   struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+		.r8 = page,
+	};
+
+	clflush_cache_range(__va(page), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_SEPT_ADD, &in, out);
+}
+
+static inline u64 tdh_mem_sept_rd(hpa_t tdr, gpa_t gpa, int level,
+				  struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_SEPT_RD, &in, out);
+}
+
+static inline u64 tdh_mem_sept_remove(hpa_t tdr, gpa_t gpa, int level,
+				      struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_SEPT_REMOVE, &in, out);
+}
+
+static inline u64 tdh_vp_addcx(hpa_t tdvpr, hpa_t addr)
+{
+	struct tdx_module_args in = {
+		.rcx = addr,
+		.rdx = tdvpr,
+	};
+
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+	return tdx_seamcall(TDH_VP_ADDCX, &in, NULL);
+}
+
+static inline u64 tdh_mem_page_relocate(hpa_t tdr, gpa_t gpa, hpa_t hpa,
+					struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa,
+		.rdx = tdr,
+		.r8 = hpa,
+	};
+
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_PAGE_RELOCATE, &in, out);
+}
+
+static inline u64 tdh_mem_page_aug(hpa_t tdr, gpa_t gpa, hpa_t hpa,
+				   struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa,
+		.rdx = tdr,
+		.r8 = hpa,
+	};
+
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_PAGE_AUG, &in, out);
+}
+
+static inline u64 tdh_mem_range_block(hpa_t tdr, gpa_t gpa, int level,
+				      struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_RANGE_BLOCK, &in, out);
+}
+
+static inline u64 tdh_mng_key_config(hpa_t tdr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MNG_KEY_CONFIG, &in, NULL);
+}
+
+static inline u64 tdh_mng_create(hpa_t tdr, int hkid)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+		.rdx = hkid,
+	};
+
+	clflush_cache_range(__va(tdr), PAGE_SIZE);
+	return tdx_seamcall(TDH_MNG_CREATE, &in, NULL);
+}
+
+static inline u64 tdh_vp_create(hpa_t tdr, hpa_t tdvpr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdvpr,
+		.rdx = tdr,
+	};
+
+	clflush_cache_range(__va(tdvpr), PAGE_SIZE);
+	return tdx_seamcall(TDH_VP_CREATE, &in, NULL);
+}
+
+static inline u64 tdh_mng_rd(hpa_t tdr, u64 field, struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+		.rdx = field,
+	};
+
+	return tdx_seamcall(TDH_MNG_RD, &in, out);
+}
+
+static inline u64 tdh_mr_extend(hpa_t tdr, gpa_t gpa,
+				struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MR_EXTEND, &in, out);
+}
+
+static inline u64 tdh_mr_finalize(hpa_t tdr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MR_FINALIZE, &in, NULL);
+}
+
+static inline u64 tdh_vp_flush(hpa_t tdvpr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdvpr,
+	};
+
+	return tdx_seamcall(TDH_VP_FLUSH, &in, NULL);
+}
+
+static inline u64 tdh_mng_vpflushdone(hpa_t tdr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MNG_VPFLUSHDONE, &in, NULL);
+}
+
+static inline u64 tdh_mng_key_freeid(hpa_t tdr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MNG_KEY_FREEID, &in, NULL);
+}
+
+static inline u64 tdh_mng_init(hpa_t tdr, hpa_t td_params,
+			       struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+		.rdx = td_params,
+	};
+
+	return tdx_seamcall(TDH_MNG_INIT, &in, out);
+}
+
+static inline u64 tdh_vp_init(hpa_t tdvpr, u64 rcx)
+{
+	struct tdx_module_args in = {
+		.rcx = tdvpr,
+		.rdx = rcx,
+	};
+
+	return tdx_seamcall(TDH_VP_INIT, &in, NULL);
+}
+
+static inline u64 tdh_vp_rd(hpa_t tdvpr, u64 field,
+			    struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = tdvpr,
+		.rdx = field,
+	};
+
+	return tdx_seamcall(TDH_VP_RD, &in, out);
+}
+
+static inline u64 tdh_mng_key_reclaimid(hpa_t tdr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MNG_KEY_RECLAIMID, &in, NULL);
+}
+
+static inline u64 tdh_phymem_page_reclaim(hpa_t page,
+					  struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = page,
+	};
+
+	return tdx_seamcall(TDH_PHYMEM_PAGE_RECLAIM, &in, out);
+}
+
+static inline u64 tdh_mem_page_remove(hpa_t tdr, gpa_t gpa, int level,
+				      struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_PAGE_REMOVE, &in, out);
+}
+
+static inline u64 tdh_sys_lp_shutdown(void)
+{
+	struct tdx_module_args in = {
+	};
+
+	return tdx_seamcall(TDH_SYS_LP_SHUTDOWN, &in, NULL);
+}
+
+static inline u64 tdh_mem_track(hpa_t tdr)
+{
+	struct tdx_module_args in = {
+		.rcx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_TRACK, &in, NULL);
+}
+
+static inline u64 tdh_mem_range_unblock(hpa_t tdr, gpa_t gpa, int level,
+					struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_RANGE_UNBLOCK, &in, out);
+}
+
+static inline u64 tdh_phymem_cache_wb(bool resume)
+{
+	struct tdx_module_args in = {
+		.rcx = resume ? 1 : 0,
+	};
+
+	return tdx_seamcall(TDH_PHYMEM_CACHE_WB, &in, NULL);
+}
+
+static inline u64 tdh_phymem_page_wbinvd(hpa_t page)
+{
+	struct tdx_module_args in = {
+		.rcx = page,
+	};
+
+	return tdx_seamcall(TDH_PHYMEM_PAGE_WBINVD, &in, NULL);
+}
+
+static inline u64 tdh_vp_wr(hpa_t tdvpr, u64 field, u64 val, u64 mask,
+			    struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = tdvpr,
+		.rdx = field,
+		.r8 = val,
+		.r9 = mask,
+	};
+
+	return tdx_seamcall(TDH_VP_WR, &in, out);
+}
+
+#endif /* __KVM_X86_TDX_OPS_H */
Signature · 1 line
2.25.1
#182 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 12 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx_ops.h new file +12 -0
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);
+
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+		/*
+		 * SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off.
+		 * This can happen when the host gets rebooted or live
+		 * updated. In this case, the instruction execution is ignored
+		 * as KVM is shut down, so the error code is suppressed. Other
+		 * than this, the error is unexpected and the execution can't
+		 * continue as the TDX features reply on VMX to be on.
+		 */
+		kvm_spurious_fault();
+		return 0;

This is nonsensical. The reason KVM liberally uses BUG_ON(!kvm_rebooting) is because it *greatly* simpifies the overall code by obviating the need for KVM to check for errors that should never happen in practice. On, and

But KVM quite obviously needs to check the return code for all SEAMCALLs, and the SEAMCALLs are (a) wrapped in functions and (b) preserve host state, i.e. we don't need to worry about KVM consuming garbage or running with unknown hardware state because something like INVVPID or INVEPT faulted.

Oh, and the other critical aspect of all of this is that unlike VMREAD, VMWRITE, etc., SEAMCALLs almost always require a TDR or TDVPR, i.e. need a VM or vCPU. Now that we've abandoned the macro shenanigans that allowed things like tdh_mem_page_add() to be pure translators to their respective SEAMCALL, I don't see any reason to take the physical addresses of the TDR/TDVPR in the helpers.

I.e. if we do:

u64 tdh_mng_addcx(struct kvm *kvm, hpa_t addr)

then the intermediate wrapper to the SEAMCALL assembly has the vCPU or VM and thus can precisely terminate the one problematic VM.

So unless I'm missing something, I think that kvm_spurious_fault() should be persona non grata for TDX, and that KVM should instead use KVM_BUG_ON().

#183 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 41 lines · Sean Christopherson
Quoted 12 lines · On Mon, Feb 26, 2024, [email protected] wrote:
arch/x86/kvm/vmx/tdx_ops.h new file +12 -0
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);
+
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+		/*
+		 * SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off.
+		 * This can happen when the host gets rebooted or live
+		 * updated. In this case, the instruction execution is ignored
+		 * as KVM is shut down, so the error code is suppressed. Other
+		 * than this, the error is unexpected and the execution can't
+		 * continue as the TDX features reply on VMX to be on.
+		 */
+		kvm_spurious_fault();
+		return 0;

This is nonsensical. The reason KVM liberally uses BUG_ON(!kvm_rebooting) is because it *greatly* simpifies the overall code by obviating the need for KVM to check for errors that should never happen in practice. On, and

But KVM quite obviously needs to check the return code for all SEAMCALLs, and the SEAMCALLs are (a) wrapped in functions and (b) preserve host state, i.e. we don't need to worry about KVM consuming garbage or running with unknown hardware state because something like INVVPID or INVEPT faulted.

Oh, and the other critical aspect of all of this is that unlike VMREAD, VMWRITE, etc., SEAMCALLs almost always require a TDR or TDVPR, i.e. need a VM or vCPU. Now that we've abandoned the macro shenanigans that allowed things like tdh_mem_page_add() to be pure translators to their respective SEAMCALL, I don't see any reason to take the physical addresses of the TDR/TDVPR in the helpers.

I.e. if we do:

Quoted 7 lines

u64 tdh_mng_addcx(struct kvm *kvm, hpa_t addr)

then the intermediate wrapper to the SEAMCALL assembly has the vCPU or VM and thus can precisely terminate the one problematic VM.

So unless I'm missing something, I think that kvm_spurious_fault() should be persona non grata for TDX, and that KVM should instead use KVM_BUG_ON().

Thank you for the feedback. As I don't see any issues to do so, I'll convert those wrappers to take struct kvm_tdx or struct vcpu_tdx, and eliminate kvm_spurious_fault() in favor of KVM_BUG_ON().

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]
Quoted 4 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
(quoted diff) +2 -0
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level,

hpa_t page,
+                                  struct tdx_module_args *out)

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+{
+       struct tdx_module_args in = {
+               .rcx = gpa | level,
+               .rdx = tdr,
+               .r8 = page,
+       };
+
+       clflush_cache_range(__va(page), PAGE_SIZE);
+       return tdx_seamcall(TDH_MEM_SEPT_ADD, &in, out);
+}

The caller of this later in the series looks like this:

	err = tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &out);
	if (unlikely(err == TDX_ERROR_SEPT_BUSY))
		return -EAGAIN;
	if (unlikely(err == (TDX_EPT_ENTRY_STATE_INCORRECT |
TDX_OPERAND_ID_RCX))) {
		union tdx_sept_entry entry = {
			.raw = out.rcx,
		};
		union tdx_sept_level_state level_state = {
			.raw = out.rdx,
		};

		/* someone updated the entry with same value. */
		if (level_state.level == tdx_level &&
		    level_state.state == TDX_SEPT_PRESENT &&
		    !entry.leaf && entry.pfn == (hpa >> PAGE_SHIFT))
			return -EAGAIN;
	}

The helper abstracts setting the arguments into the proper registers fields passed in, but doesn't abstract pulling the result out from the register fields. Then the caller has to manually extract them in this verbose way. Why not have the helper do both?

#185 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 37 lines · Rick P
Quoted 4 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
(quoted diff) +2 -0
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level,

hpa_t page,
+                                  struct tdx_module_args *out)

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+{
+       struct tdx_module_args in = {
+               .rcx = gpa | level,
+               .rdx = tdr,
+               .r8 = page,
+       };
+
+       clflush_cache_range(__va(page), PAGE_SIZE);
+       return tdx_seamcall(TDH_MEM_SEPT_ADD, &in, out);
+}

The caller of this later in the series looks like this:

	err = tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &out);
	if (unlikely(err == TDX_ERROR_SEPT_BUSY))
		return -EAGAIN;
	if (unlikely(err == (TDX_EPT_ENTRY_STATE_INCORRECT |
TDX_OPERAND_ID_RCX))) {
		union tdx_sept_entry entry = {
			.raw = out.rcx,
		};
		union tdx_sept_level_state level_state = {
			.raw = out.rdx,
		};

		/* someone updated the entry with same value. */
		if (level_state.level == tdx_level &&
		    level_state.state == TDX_SEPT_PRESENT &&
		    !entry.leaf && entry.pfn == (hpa >> PAGE_SHIFT))
			return -EAGAIN;
	}
Quoted 4 lines

The helper abstracts setting the arguments into the proper registers fields passed in, but doesn't abstract pulling the result out from the register fields. Then the caller has to manually extract them in this verbose way. Why not have the helper do both?

Yes. Let me update those arguments.

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 9 lines · Isaku Yamahata
Quoted 7 lines

The helper abstracts setting the arguments into the proper registers
fields passed in, but doesn't abstract pulling the result out from the
register fields. Then the caller has to manually extract them in this
verbose way. Why not have the helper do both?

Yes. Let me update those arguments.

What were you thinking exactly, like?

tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state);

And for the other helpers?

#187 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 9 lines · Rick P
Quoted 8 lines · Isaku Yamahata
Quoted 7 lines

The helper abstracts setting the arguments into the proper registers
fields passed in, but doesn't abstract pulling the result out from the
register fields. Then the caller has to manually extract them in this
verbose way. Why not have the helper do both?

Quoted 7 lines
Quoted 1 line

Yes. Let me update those arguments.

What were you thinking exactly, like?

tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state);

And for the other helpers?

I have the following four helpers. Other helpers will have no out argument.

tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state); tdh_mem_page_aug(kvm_tdx, gpa, hpa, &entry, &level_state); tdh_mem_page_remove(kvm_tdx, gpa, tdx_level, &entry, &level_state); tdh_mem_range_block(kvm_tdx, gpa, tdx_level, &entry, &level_state);

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 18 lines · Isaku Yamahata
Quoted 15 lines · Rick P
Quoted 9 lines · Isaku Yamahata
Quoted 7 lines

The helper abstracts setting the arguments into the proper registers
fields passed in, but doesn't abstract pulling the result out from the
register fields. Then the caller has to manually extract them in this
verbose way. Why not have the helper do both?

Yes. Let me update those arguments.

What were you thinking exactly, like?

tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state);

Quoted 8 lines
Quoted 1 line

And for the other helpers?

I have the following four helpers. Other helpers will have no out argument.

tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state); tdh_mem_page_aug(kvm_tdx, gpa, hpa, &entry, &level_state); tdh_mem_page_remove(kvm_tdx, gpa, tdx_level, &entry, &level_state); tdh_mem_range_block(kvm_tdx, gpa, tdx_level, &entry, &level_state);

By updating the code, I found that tdh_mem_range_block() doesn't need out variables. and tdh_vp_rd() needs output. tdh_mem_range_block() doesn't need the out.

u64 tdh_vp_rd(struct vcpu_tdx *tdx, u64 field, u64 *value)

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

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

From: Isaku Yamahata <[email protected]>

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

Quoted 7 lines

Define C wrapper functions for SEAMCALLs for readability.

Some SEAMCALL APIs donate host pages to TDX module or guest TD, and the donated pages are encrypted. Those require the VMM to flush the cache lines to avoid cache line alias.

Not valid anymore.

[...]

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

Quoted 11 lines
arch/x86/kvm/vmx/tdx_ops.h new file +11 -0
+
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);

I think it's silly to have the @out argument in this way.

What is the main reason to still have it?

Yeah we used to have the @out in __seamcall() assembly function. The assembly code checks the @out and skips copying registers to @out when it is NULL.

But it got removed when we tried to unify the assembly for TDCALL/TDVMCALL and SEAMCALL to have a *SINGLE* assembly macro.

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

To me that means we should just accept the fact we will always have a valid @out.

But there might be some case that you _obviously_ need the @out and I missed?

Quoted 54 lines
arch/x86/kvm/vmx/tdx_ops.h new file +54 -0
+
+	if (unlikely(ret == TDX_SEAMCALL_UD)) {
+		/*
+		 * SEAMCALLs fail with TDX_SEAMCALL_UD returned when VMX is off.
+		 * This can happen when the host gets rebooted or live
+		 * updated. In this case, the instruction execution is ignored
+		 * as KVM is shut down, so the error code is suppressed. Other
+		 * than this, the error is unexpected and the execution can't
+		 * continue as the TDX features reply on VMX to be on.
+		 */
+		kvm_spurious_fault();
+		return 0;
+	}
+	return ret;
+}
+
+static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
+{
+	struct tdx_module_args in = {
+		.rcx = addr,
+		.rdx = tdr,
+	};
+
+	clflush_cache_range(__va(addr), PAGE_SIZE);
+	return tdx_seamcall(TDH_MNG_ADDCX, &in, NULL);
+}
+
+static inline u64 tdh_mem_page_add(hpa_t tdr, gpa_t gpa, hpa_t hpa, hpa_t source,
+				   struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa,
+		.rdx = tdr,
+		.r8 = hpa,
+		.r9 = source,
+	};
+
+	clflush_cache_range(__va(hpa), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_PAGE_ADD, &in, out);
+}
+
+static inline u64 tdh_mem_sept_add(hpa_t tdr, gpa_t gpa, int level, hpa_t page,
+				   struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+		.r8 = page,
+	};
+
+	clflush_cache_range(__va(page), PAGE_SIZE);
+	return tdx_seamcall(TDH_MEM_SEPT_ADD, &in, out);
+}
+

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+static inline u64 tdh_mem_sept_rd(hpa_t tdr, gpa_t gpa, int level,
+				  struct tdx_module_args *out)
+{
+	struct tdx_module_args in = {
+		.rcx = gpa | level,
+		.rdx = tdr,
+	};
+
+	return tdx_seamcall(TDH_MEM_SEPT_RD, &in, out);
+}

Not checked the whole series yet, but is this ever used in this series?

[...]

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx_ops.h new file +8 -0
+
+static inline u64 tdh_sys_lp_shutdown(void)
+{
+	struct tdx_module_args in = {
+	};
+
+	return tdx_seamcall(TDH_SYS_LP_SHUTDOWN, &in, NULL);
+}

As Sean already pointed out, I am sure it's/should not used in this series.

That being said, I found it's not easy to determine whether one wrapper will be used by this series or not. The other option is we introduce the wrapper(s) when they get actally used, but I can see (especially at this stage) it's also a apple vs orange question that people may have different preference.

Perhaps we can say something like below in changelog ...

"
Note, not all VM-managing related SEAMCALLs have a wrapper here, but only provide wrappers that are essential to the run the TDX guest with basic feature set. "

... so that people will at least to pay attention to this during the review?

#190 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 22 lines · Kai

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);

I think it's silly to have the @out argument in this way.

What is the main reason to still have it?

Yeah we used to have the @out in __seamcall() assembly function. The assembly code checks the @out and skips copying registers to @out when it is NULL.

But it got removed when we tried to unify the assembly for TDCALL/TDVMCALL and SEAMCALL to have a *SINGLE* assembly macro.

Quoted 7 lines

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

To me that means we should just accept the fact we will always have a valid @out.

But there might be some case that you _obviously_ need the @out and I missed?

As I replied at [1], those four wrappers need to return values. The first three on error, the last one on success.

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

  tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state);
  tdh_mem_page_aug(kvm_tdx, gpa, hpa, &entry, &level_state);
  tdh_mem_page_remove(kvm_tdx, gpa, tdx_level, &entry, &level_state);
  u64 tdh_vp_rd(struct vcpu_tdx *tdx, u64 field, u64 *value)

We can delete out from other wrappers.
Because only TDH.MNG.CREATE() and TDH.MNG.ADDCX() can return TDX_RND_NO_ENTROPY, we can use __seamcall(). The TDX spec doesn't guarantee such error code convention. It's very unlikely, though.

Quoted 18 lines

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

Quoted 7 lines
arch/x86/kvm/vmx/tdx_ops.h new file +7 -0
+static inline u64 tdh_sys_lp_shutdown(void)
+{
+	struct tdx_module_args in = {
+	};
+
+	return tdx_seamcall(TDH_SYS_LP_SHUTDOWN, &in, NULL);
+}

As Sean already pointed out, I am sure it's/should not used in this series.

That being said, I found it's not easy to determine whether one wrapper will be used by this series or not. The other option is we introduce the wrapper(s) when they get actally used, but I can see (especially at this stage) it's also a apple vs orange question that people may have different preference.

Perhaps we can say something like below in changelog ...

Quoted 7 lines

"
Note, not all VM-managing related SEAMCALLs have a wrapper here, but only provide wrappers that are essential to the run the TDX guest with basic feature set.
"

... so that people will at least to pay attention to this during the review?

Makes sense. We can split this patch into other patches that first use the wrappers.

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 36 lines · Isaku Yamahata
Quoted 22 lines · Kai

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);

I think it's silly to have the @out argument in this way.

What is the main reason to still have it?

Yeah we used to have the @out in __seamcall() assembly function. The assembly code checks the @out and skips copying registers to @out when it is NULL.

But it got removed when we tried to unify the assembly for TDCALL/TDVMCALL and SEAMCALL to have a *SINGLE* assembly macro.

Quoted 7 lines

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

To me that means we should just accept the fact we will always have a valid @out.

But there might be some case that you _obviously_ need the @out and I missed?

As I replied at [1], those four wrappers need to return values. The first three on error, the last one on success.

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

   tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state);
   tdh_mem_page_aug(kvm_tdx, gpa, hpa, &entry, &level_state);
   tdh_mem_page_remove(kvm_tdx, gpa, tdx_level, &entry, &level_state);
   u64 tdh_vp_rd(struct vcpu_tdx *tdx, u64 field, u64 *value)

We can delete out from other wrappers.

Ah, OK. I got you don't want to invent separate wrappers for each seamcall() variants like:

- tdx_seamcall(u64 fn, struct tdx_module_args *args);
- tdx_seamcall_ret(u64 fn, struct tdx_module_args *args);
- tdx_seamcall_saved_ret(u64 fn, struct tdx_module_args *args);

To be honest I found they were kinda annoying myself during the "unify TDCALL/SEAMCALL and TDVMCALL assembly" patchset.

But life is hard...

And given (it seems) we are going to remove kvm_spurious_fault(), I think the tdx_seamcall() variants are just very simple wrapper of plain seamcall() variants.

So how about we have some macros:

static inline bool is_seamcall_err_kernel_defined(u64 err)

{
	return err & TDX_SW_ERROR;
}
#define TDX_KVM_SEAMCALL(_kvm, _seamcall_func, _fn, _args)	\
	({				\
		u64 _ret = _seamcall_func(_fn, _args);
		KVM_BUG_ON(_kvm, is_seamcall_err_kernel_defined(_ret));
		_ret;
	})

#define tdx_kvm_seamcall(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall, _fn, _args)

#define tdx_kvm_seamcall_ret(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall_ret, _fn, _args)

#define tdx_kvm_seamcall_saved_ret(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall_saved_ret, _fn, _args)

This is consistent with what we have in TDX host code, and this handles NO_ENTROPY error internally.

Or, maybe we can just use the seamcall_ret() for ALL SEAMCALLs, except using seamcall_saved_ret() for TDH.VP.ENTER.

u64 tdx_kvm_seamcall(sruct kvm*kvm, u64 fn,
struct tdx_module_args *args)

{
	u64 ret = seamcall_ret(fn, args);

	KVM_BUG_ON(kvm, is_seamcall_err_kernel_defined(ret);

	return ret;
}

IIUC this at least should give us a single tdx_kvm_seamcall() API for majority (99%) code sites?

And obviously I'd like other people to weigh in too.

Quoted 2 lines

Because only TDH.MNG.CREATE() and TDH.MNG.ADDCX() can return TDX_RND_NO_ENTROPY, > we can use __seamcall(). The TDX spec doesn't guarantee such error code convention. It's very unlikely, though.

I don't quite follow the "convention" part. Can you elaborate?

NO_ENTROPY is already handled in seamcall() variants. Can we just use them directly?

Quoted 26 lines
Quoted 26 lines

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

Quoted 9 lines
arch/x86/kvm/vmx/tdx_ops.h new file +7 -0
+static inline u64 tdh_sys_lp_shutdown(void)
+{
+	struct tdx_module_args in = {
+	};
+
+	return tdx_seamcall(TDH_SYS_LP_SHUTDOWN, &in, NULL);
+}

As Sean already pointed out, I am sure it's/should not used in this series.

That being said, I found it's not easy to determine whether one wrapper will be used by this series or not. The other option is we introduce the wrapper(s) when they get actally used, but I can see (especially at this stage) it's also a apple vs orange question that people may have different preference.

Perhaps we can say something like below in changelog ...

"
Note, not all VM-managing related SEAMCALLs have a wrapper here, but only provide wrappers that are essential to the run the TDX guest with basic feature set.
"

Quoted 4 lines
Quoted 1 line

... so that people will at least to pay attention to this during the review?

Makes sense. We can split this patch into other patches that first use the wrappers.

Obviously I didn't want to make you do dramatic patchset reorganization, so it's up to you.

#192 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 71 lines · Kai
Quoted 36 lines · Isaku Yamahata
Quoted 22 lines · Kai

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx_ops.h new file +10 -0
+static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
+			       struct tdx_module_args *out)
+{
+	u64 ret;
+
+	if (out) {
+		*out = *in;
+		ret = seamcall_ret(op, out);
+	} else
+		ret = seamcall(op, in);

I think it's silly to have the @out argument in this way.

What is the main reason to still have it?

Yeah we used to have the @out in __seamcall() assembly function. The assembly code checks the @out and skips copying registers to @out when it is NULL.

But it got removed when we tried to unify the assembly for TDCALL/TDVMCALL and SEAMCALL to have a *SINGLE* assembly macro.

Quoted 7 lines

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

To me that means we should just accept the fact we will always have a valid @out.

But there might be some case that you _obviously_ need the @out and I missed?

As I replied at [1], those four wrappers need to return values. The first three on error, the last one on success.

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

   tdh_mem_sept_add(kvm_tdx, gpa, tdx_level, hpa, &entry, &level_state);
   tdh_mem_page_aug(kvm_tdx, gpa, hpa, &entry, &level_state);
   tdh_mem_page_remove(kvm_tdx, gpa, tdx_level, &entry, &level_state);
   u64 tdh_vp_rd(struct vcpu_tdx *tdx, u64 field, u64 *value)

We can delete out from other wrappers.

Ah, OK. I got you don't want to invent separate wrappers for each seamcall() variants like:

- tdx_seamcall(u64 fn, struct tdx_module_args *args);
- tdx_seamcall_ret(u64 fn, struct tdx_module_args *args);
- tdx_seamcall_saved_ret(u64 fn, struct tdx_module_args *args);

To be honest I found they were kinda annoying myself during the "unify TDCALL/SEAMCALL and TDVMCALL assembly" patchset.

But life is hard...

And given (it seems) we are going to remove kvm_spurious_fault(), I think the tdx_seamcall() variants are just very simple wrapper of plain seamcall() variants.

So how about we have some macros:

static inline bool is_seamcall_err_kernel_defined(u64 err)

{
	return err & TDX_SW_ERROR;
}
Quoted 6 lines
#define TDX_KVM_SEAMCALL(_kvm, _seamcall_func, _fn, _args)	\
	({				\
		u64 _ret = _seamcall_func(_fn, _args);
		KVM_BUG_ON(_kvm, is_seamcall_err_kernel_defined(_ret));
		_ret;
	})

As we can move out KVM_BUG_ON() to the call site, we can simply have seamcall() or seamcall_ret().
The call site has to check error. whether it is TDX_SW_ERROR or not. And if it hit the unexpected error, it will mark the guest bugged.

Quoted 25 lines

#define tdx_kvm_seamcall(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall, _fn, _args)

#define tdx_kvm_seamcall_ret(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall_ret, _fn, _args)

#define tdx_kvm_seamcall_saved_ret(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall_saved_ret, _fn, _args)

This is consistent with what we have in TDX host code, and this handles NO_ENTROPY error internally.

Or, maybe we can just use the seamcall_ret() for ALL SEAMCALLs, except using seamcall_saved_ret() for TDH.VP.ENTER.

u64 tdx_kvm_seamcall(sruct kvm*kvm, u64 fn,
struct tdx_module_args *args)

{
	u64 ret = seamcall_ret(fn, args);

	KVM_BUG_ON(kvm, is_seamcall_err_kernel_defined(ret);

	return ret;
}
Quoted 2 lines

IIUC this at least should give us a single tdx_kvm_seamcall() API for majority (99%) code sites?

We can eleiminate tdx_kvm_seamcall() and use seamcall() or seamcall_ret() directly.

Quoted 9 lines

And obviously I'd like other people to weigh in too.

Quoted 2 lines

Because only TDH.MNG.CREATE() and TDH.MNG.ADDCX() can return TDX_RND_NO_ENTROPY, > we can use __seamcall(). The TDX spec doesn't guarantee such error code convention. It's very unlikely, though.

I don't quite follow the "convention" part. Can you elaborate?

NO_ENTROPY is already handled in seamcall() variants. Can we just use them directly?

I intended for bad code generation. If the loop on NO_ENTRY error harms the code generation, we might be able to use __seamcall() or __seamcall_ret() instead of seamcall(), seamcall_ret().

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 15 lines
Quoted 8 lines

So how about we have some macros:

static inline bool is_seamcall_err_kernel_defined(u64 err)

{
	return err & TDX_SW_ERROR;
}
Quoted 6 lines
#define TDX_KVM_SEAMCALL(_kvm, _seamcall_func, _fn, _args)	\
	({				\
		u64 _ret = _seamcall_func(_fn, _args);
		KVM_BUG_ON(_kvm, is_seamcall_err_kernel_defined(_ret));
		_ret;
	})
Quoted 4 lines

As we can move out KVM_BUG_ON() to the call site, we can simply have seamcall() or seamcall_ret().
The call site has to check error. whether it is TDX_SW_ERROR or not. And if it hit the unexpected error, it will mark the guest bugged.

How many call sites are we talking about?

I think handling KVM_BUG_ON() in macro should be able to eliminate bunch of individual KVM_BUG_ON()s in these call sites?

Quoted 15 lines
Quoted 15 lines

#define tdx_kvm_seamcall(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall, _fn, _args)

#define tdx_kvm_seamcall_ret(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall_ret, _fn, _args)

#define tdx_kvm_seamcall_saved_ret(_kvm, _fn, _args) \
TDX_KVM_SEAMCALL(_kvm, seamcall_saved_ret, _fn, _args)

This is consistent with what we have in TDX host code, and this handles NO_ENTROPY error internally.

[...]

Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

Because only TDH.MNG.CREATE() and TDH.MNG.ADDCX() can return TDX_RND_NO_ENTROPY, > we can use __seamcall(). The TDX spec doesn't guarantee such error code convention. It's very unlikely, though.

Quoted 8 lines
Quoted 4 lines

I don't quite follow the "convention" part. Can you elaborate?

NO_ENTROPY is already handled in seamcall() variants. Can we just use them directly?

I intended for bad code generation. If the loop on NO_ENTRY error harms the code generation, we might be able to use __seamcall() or __seamcall_ret() instead of seamcall(), seamcall_ret().

This doesn't make sense to me.

Firstly, you have to *prove* the loop generates worse code.

Secondly, if it does generate worse code, and we care about it, we should fix it in the host seamcall() code. No?

#194 lore raw

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

Quoted 20 lines · Kai
Quoted 15 lines
Quoted 8 lines

So how about we have some macros:

static inline bool is_seamcall_err_kernel_defined(u64 err)

{
	return err & TDX_SW_ERROR;
}
Quoted 6 lines
#define TDX_KVM_SEAMCALL(_kvm, _seamcall_func, _fn, _args)	\
	({				\
		u64 _ret = _seamcall_func(_fn, _args);
		KVM_BUG_ON(_kvm, is_seamcall_err_kernel_defined(_ret));
		_ret;
	})
Quoted 4 lines

As we can move out KVM_BUG_ON() to the call site, we can simply have seamcall() or seamcall_ret().
The call site has to check error. whether it is TDX_SW_ERROR or not. And if it hit the unexpected error, it will mark the guest bugged.

Quoted 4 lines

How many call sites are we talking about?

I think handling KVM_BUG_ON() in macro should be able to eliminate bunch of individual KVM_BUG_ON()s in these call sites?

16: custom error check is needed
6: always error

So I'd like to consistently have error check in KVM code, not in macro or wrapper.

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

Re: [PATCH v19 029/130] KVM: TDX: Add C wrapper functions for SEAMCALLs to the TDX module

In reply to [email protected]

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

Quoted 5 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx_ops.h new file +5 -0
+#include <linux/compiler.h>
+
+#include <asm/cacheflush.h>
+#include <asm/asm.h>
+#include <asm/kvm_host.h>

None of above are needed to build this file, except the <asm/cacheflush.h>.

I am removing them.

I am also adding <asm/tdx.h> because this file uses 'struct tdx_module_args'. And <asm/page.h> for __va().

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

Quoted 3 lines
arch/x86/kvm/vmx/tdx_ops.h new file +3 -0
+
+#include "tdx_errno.h"
+#include "tdx_arch.h"

I am moving them to "tdx.h", and make "tdx.h" to include this "tdx_ops.h" as well, and declare the C file should never include "tdx_ops.h" directly:

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

#196 lore raw

PATCH v19 30/130 KVM: TDX: Add helper functions to print TDX SEAMCALL error

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

---
v19:
- dropped unnecessary include <asm/tdx.h>

v18:
- Added Reviewed-by Binbin.

---
 arch/x86/kvm/Makefile        |  2 +-
 arch/x86/kvm/vmx/tdx_error.c | 21 +++++++++++++++++++++
 arch/x86/kvm/vmx/tdx_ops.h   |  4 ++++
 3 files changed, 26 insertions(+), 1 deletion(-)
 create mode 100644 arch/x86/kvm/vmx/tdx_error.c
arch/x86/kvm/Makefile +1 -1
index 5b85ef84b2e9..44b0594da877 100644
@@ -24,7 +24,7 @@ kvm-intel-y		+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \
 
 kvm-intel-$(CONFIG_X86_SGX_KVM)	+= vmx/sgx.o
 kvm-intel-$(CONFIG_KVM_HYPERV)	+= vmx/hyperv.o vmx/hyperv_evmcs.o
-kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o
+kvm-intel-$(CONFIG_INTEL_TDX_HOST)	+= vmx/tdx.o vmx/tdx_error.o
 
 kvm-amd-y		+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o \
 			   svm/sev.o
arch/x86/kvm/vmx/tdx_error.c new file +21 -0
new file mode 100644
index 000000000000..42fcabe1f6c7
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* functions to record TDX SEAMCALL error */
+
+#include <linux/kernel.h>
+#include <linux/bug.h>
+
+#include "tdx_ops.h"
+
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_args *out)
+{
+	if (!out) {
+		pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
+				   op, error_code);
+		return;
+	}
+
+#define MSG	\
+	"SEAMCALL (0x%016llx) failed: 0x%016llx RCX 0x%016llx RDX 0x%016llx R8 0x%016llx R9 0x%016llx R10 0x%016llx R11 0x%016llx\n"
+	pr_err_ratelimited(MSG, op, error_code, out->rcx, out->rdx, out->r8,
+			   out->r9, out->r10, out->r11);
+}
arch/x86/kvm/vmx/tdx_ops.h +4 -0
index c5bb165b260e..d80212b1daf3 100644
@@ -40,6 +40,10 @@ static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
 	return ret;
 }
 
+#ifdef CONFIG_INTEL_TDX_HOST
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_args *out);
+#endif
+
 static inline u64 tdh_mng_addcx(hpa_t tdr, hpa_t addr)
 {
 	struct tdx_module_args in = {
Signature · 1 line
2.25.1
#197 lore raw

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

Quoted 4 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

Likely we need more information here. See below.

Quoted 10 lines

---
v19:
- dropped unnecessary include <asm/tdx.h>

v18:
- Added Reviewed-by Binbin.

The tag doesn't show in the SoB chain.

Quoted 3 lines

---

[...]

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

Quoted 7 lines
arch/x86/kvm/vmx/tdx_error.c new file +7 -0
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_args *out)
+{
+	if (!out) {
+		pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
+				   op, error_code);
+		return;
+	}

I think this is the reason you still want the @out in tdx_seamcall()?

But I am not sure either -- even if you want to have @out *here* -- why cannot you pass a NULL explicitly when you *know* the concerned SEAMCALL doesn't have a valid output?

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx_error.c new file +6 -0
+
+#define MSG	\
+	"SEAMCALL (0x%016llx) failed: 0x%016llx RCX 0x%016llx RDX 0x%016llx R8 0x%016llx R9 0x%016llx R10 0x%016llx R11 0x%016llx\n"
+	pr_err_ratelimited(MSG, op, error_code, out->rcx, out->rdx, out->r8,
+			   out->r9, out->r10, out->r11);
+}

Besides the regs that you are printing, there are more regs (R12-R15, RDI, RSI) in the structure.

It's not clear why you only print some, but not all.

AFAICT the VP.ENTER SEAMCALL can have all regs as valid output?

Anyway, that being said, you might need to put more text in changelog/comment to make this patch (at least more) reviewable.

#198 lore raw

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

Quoted 53 lines · Kai
Quoted 4 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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

Likely we need more information here. See below.

Quoted 10 lines

---
v19:
- dropped unnecessary include <asm/tdx.h>

v18:
- Added Reviewed-by Binbin.

The tag doesn't show in the SoB chain.

Quoted 3 lines

---

[...]

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

Quoted 7 lines
arch/x86/kvm/vmx/tdx_error.c new file +7 -0
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_args *out)
+{
+	if (!out) {
+		pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
+				   op, error_code);
+		return;
+	}

I think this is the reason you still want the @out in tdx_seamcall()?

But I am not sure either -- even if you want to have @out *here* -- why cannot you pass a NULL explicitly when you *know* the concerned SEAMCALL doesn't have a valid output?

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx_error.c new file +6 -0
+
+#define MSG	\
+	"SEAMCALL (0x%016llx) failed: 0x%016llx RCX 0x%016llx RDX 0x%016llx R8 0x%016llx R9 0x%016llx R10 0x%016llx R11 0x%016llx\n"
+	pr_err_ratelimited(MSG, op, error_code, out->rcx, out->rdx, out->r8,
+			   out->r9, out->r10, out->r11);
+}

Besides the regs that you are printing, there are more regs (R12-R15, RDI, RSI) in the structure.

Quoted 3 lines

It's not clear why you only print some, but not all.

AFAICT the VP.ENTER SEAMCALL can have all regs as valid output?

Only those are used for SEAMCALLs except TDH.VP.ENTER. TDH.VP.ENTER is an exception.

As discussed at [1], out can be eliminated. We will have only limited output. If we go for that route, we'll have the two following functions. Does it make sense?

void pr_tdx_error(u64 op, u64 error_code)

{
        pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
                           op, error_code);
}

void pr_tdx_sept_error(u64 op, u64 error_code, const union tdx_sept_entry *entry,
const union tdx_sept_level_state *level_state)
{

#define MSG \
        "SEAMCALL (0x%016llx) failed: 0x%016llx entry 0x%016llx level_state 0x%016llx\n"
        pr_err_ratelimited(MSG, op, error_code, entry->raw, level_state->raw);
}

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

Quoted 4 lines

Anyway, that being said, you might need to put more text in changelog/comment to make this patch (at least more) reviewable.

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

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

Quoted 8 lines

Does it make sense?

void pr_tdx_error(u64 op, u64 error_code)

{
         pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
                            op, error_code);
}

Should we also have a _ret version?

void pr_seamcall_err(u64 op, u64 err)

{
	/* A comment to explain why using the _ratelimited() version? */
	pr_err_ratelimited(...);
}

void pr_seamcall_err_ret(u64 op, u64 err, struct tdx_module_args *arg)

{
	pr_err_seamcall(op, err);
	
	pr_err_ratelimited(...);
}

(Hmm... if you look at the tdx.c in TDX host, there's similar code there, and again, it was a little bit annoying when I did that..)

Again, if we just use seamcall_ret() for ALL SEAMCALLs except VP.ENTER, we can simply have one..

Quoted 8 lines

void pr_tdx_sept_error(u64 op, u64 error_code, const union tdx_sept_entry *entry,
const union tdx_sept_level_state *level_state)
{

#define MSG \
         "SEAMCALL (0x%016llx) failed: 0x%016llx entry 0x%016llx level_state 0x%016llx\n"
         pr_err_ratelimited(MSG, op, error_code, entry->raw, level_state->raw);
}

A higher-level wrapper to print SEPT error is fine to me, but do it in a separate patch.

#200 lore raw

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

Quoted 8 lines · Kai
Quoted 7 lines

Does it make sense?

void pr_tdx_error(u64 op, u64 error_code)

{
         pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
                            op, error_code);
}
Quoted 5 lines

Should we also have a _ret version?

void pr_seamcall_err(u64 op, u64 err)

{
	/* A comment to explain why using the _ratelimited() version? */

Because KVM can hit successive seamcall erorrs e.g. during desutructing TD, (it's unintentional sometimes), ratelimited version is preferred as safe guard. For example, SEAMCALL on all or some LPs (TDH_MNG_KEY_FREEID) can fail at the same time. And the number of LPs can be hundreds.

Quoted 10 lines
	pr_err_ratelimited(...);
}

void pr_seamcall_err_ret(u64 op, u64 err, struct tdx_module_args *arg)

{
	pr_err_seamcall(op, err);
	
	pr_err_ratelimited(...);
}
Quoted 5 lines

(Hmm... if you look at the tdx.c in TDX host, there's similar code there, and again, it was a little bit annoying when I did that..)

Again, if we just use seamcall_ret() for ALL SEAMCALLs except VP.ENTER, we can simply have one..

What about this?

void pr_seamcall_err_ret(u64 op, u64 err, struct tdx_module_args *arg)

{
        pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
                           op, error_code);
        if (arg)	
        	pr_err_ratelimited(...);
}
Quoted 10 lines
Quoted 7 lines

void pr_tdx_sept_error(u64 op, u64 error_code, const union tdx_sept_entry *entry,
const union tdx_sept_level_state *level_state)
{

#define MSG \
         "SEAMCALL (0x%016llx) failed: 0x%016llx entry 0x%016llx level_state 0x%016llx\n"
         pr_err_ratelimited(MSG, op, error_code, entry->raw, level_state->raw);
}

A higher-level wrapper to print SEPT error is fine to me, but do it in a separate patch.

Ok, Let's postpone custom version.

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

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

Quoted 13 lines · Isaku Yamahata
Quoted 10 lines · Kai
Quoted 7 lines

Does it make sense?

void pr_tdx_error(u64 op, u64 error_code)

{
         pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
                            op, error_code);
}

Should we also have a _ret version?

Quoted 8 lines
Quoted 3 lines

void pr_seamcall_err(u64 op, u64 err)

{
	/* A comment to explain why using the _ratelimited() version? */

Because KVM can hit successive seamcall erorrs e.g. during desutructing TD, (it's unintentional sometimes), ratelimited version is preferred as safe guard. For example, SEAMCALL on all or some LPs (TDH_MNG_KEY_FREEID) can fail at the same time. And the number of LPs can be hundreds.

I mean you certainly have a reason to use _ratelimited() version. My point is you at least explain it in a comment.

Quoted 20 lines
Quoted 12 lines

	pr_err_ratelimited(...);
}

void pr_seamcall_err_ret(u64 op, u64 err, struct tdx_module_args *arg)

{
	pr_err_seamcall(op, err);
	
	pr_err_ratelimited(...);
}
Quoted 5 lines

(Hmm... if you look at the tdx.c in TDX host, there's similar code there, and again, it was a little bit annoying when I did that..)

Again, if we just use seamcall_ret() for ALL SEAMCALLs except VP.ENTER, we can simply have one..

What about this?

Quoted 8 lines

void pr_seamcall_err_ret(u64 op, u64 err, struct tdx_module_args *arg)

{
        pr_err_ratelimited("SEAMCALL (0x%016llx) failed: 0x%016llx\n",
                           op, error_code);
        if (arg)	
        	pr_err_ratelimited(...);
}

Fine to me.

Or call pr_seamcall_err() instead. I don't care too much.

#202 lore raw

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

In reply to [email protected]

arch/x86/kvm/vmx/tdx_ops.h static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in, · line 46

Quoted 10 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx_ops.h +0 -0
@@ -40,6 +40,10 @@ static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
  	return ret;
  }

arch/x86/kvm/vmx/tdx_ops.h +4 -0
+#ifdef CONFIG_INTEL_TDX_HOST
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_args *out);
+#endif
+

Why this needs to be inside the CONFIG_INTEL_TDX_HOST while other tdh_xxx() don't?

I suppose all tdh_xxx() together with this pr_tdx_error() should only be called tdx.c, which is only built when CONFIG_INTEL_TDX_HOST is true?

In fact, tdx_seamcall() directly calls seamcall() and seamcall_ret(), which are only present when CONFIG_INTEL_TDX_HOST is on.

So things are really confused here. I do believe we should just remove this CONFIG_INTEL_TDX_HOST around pr_tdx_error() so all functions in "tdx_ops.h" should only be used in tdx.c.

#203 lore raw

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

Quoted 18 lines · Kai

arch/x86/kvm/vmx/tdx_ops.h static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in, · line 46

Quoted 10 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx_ops.h +0 -0
@@ -40,6 +40,10 @@ static inline u64 tdx_seamcall(u64 op, struct tdx_module_args *in,
  	return ret;
  }

arch/x86/kvm/vmx/tdx_ops.h +4 -0
+#ifdef CONFIG_INTEL_TDX_HOST
+void pr_tdx_error(u64 op, u64 error_code, const struct tdx_module_args *out);
+#endif
+

Why this needs to be inside the CONFIG_INTEL_TDX_HOST while other tdh_xxx() don't?

I suppose all tdh_xxx() together with this pr_tdx_error() should only be called tdx.c, which is only built when CONFIG_INTEL_TDX_HOST is true?

Quoted 6 lines

In fact, tdx_seamcall() directly calls seamcall() and seamcall_ret(), which are only present when CONFIG_INTEL_TDX_HOST is on.

So things are really confused here. I do believe we should just remove this CONFIG_INTEL_TDX_HOST around pr_tdx_error() so all functions in "tdx_ops.h" should only be used in tdx.c.

You're right, please go clean them up.

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

Re: [PATCH v19 030/130] KVM: TDX: Add helper functions to print TDX SEAMCALL error

In reply to [email protected]

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

Quoted 9 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx_error.c new file +6 -0
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* functions to record TDX SEAMCALL error */
+
+#include <linux/kernel.h>
+#include <linux/bug.h>
+

I don't see why the above two are needed, especially the giant <linux/kernel.h>.

<linux/printk.h> should be sufficient for the current patch.

#205 lore raw

PATCH v19 31/130 The start of TDX KVM patch series: TD VM creation/destruction

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

This empty commit is to mark the start of patch series of TD VM creation/destruction.

---
 Documentation/virt/kvm/intel-tdx-layer-status.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
Documentation/virt/kvm/intel-tdx-layer-status.rst +2 -2
index f11ea701dc19..098150da6ea2 100644
@@ -16,8 +16,8 @@ Patch Layer status
   Patch layer                          Status
 
 * TDX, VMX coexistence:                 Applied
-* TDX architectural definitions:        Applying
-* TD VM creation/destruction:           Not yet
+* TDX architectural definitions:        Applied
+* TD VM creation/destruction:           Applying
 * TD vcpu creation/destruction:         Not yet
 * TDX EPT violation:                    Not yet
 * TD finalization:                      Not yet
Signature · 1 line
2.25.1
#206 lore raw

PATCH v19 32/130 KVM: TDX: Add helper functions to allocate/free TDX private host key id

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

The memory controller encrypts TDX memory with the assigned TDX HKIDs. The global TDX HKID is to encrypt the TDX module, its memory, and some dynamic data (TDR). The private TDX HKID is assigned to guest TD to encrypt guest memory and the related data. When VMM releases an encrypted page for reuse, the page needs a cache flush with the used HKID. VMM needs the global TDX HKID and the private TDX HKIDs to flush encrypted pages.

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

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

---
 arch/x86/kvm/vmx/tdx.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
arch/x86/kvm/vmx/tdx.c +28 -0
index a7e096fd8361..cde971122c1e 100644
@@ -11,6 +11,34 @@
 #undef pr_fmt
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 
+/*
+ * Key id globally used by TDX module: TDX module maps TDR with this TDX global
+ * key id.  TDR includes key id assigned to the TD.  Then TDX module maps other
+ * TD-related pages with the assigned key id.  TDR requires this TDX global key
+ * id for cache flush unlike other TD-related pages.
+ */
+/* TDX KeyID pool */
+static DEFINE_IDA(tdx_guest_keyid_pool);
+
+static int __used tdx_guest_keyid_alloc(void)
+{
+	if (WARN_ON_ONCE(!tdx_guest_keyid_start || !tdx_nr_guest_keyids))
+		return -EINVAL;
+
+	return ida_alloc_range(&tdx_guest_keyid_pool, tdx_guest_keyid_start,
+			       tdx_guest_keyid_start + tdx_nr_guest_keyids - 1,
+			       GFP_KERNEL);
+}
+
+static void __used tdx_guest_keyid_free(int keyid)
+{
+	if (WARN_ON_ONCE(keyid < tdx_guest_keyid_start ||
+			 keyid > tdx_guest_keyid_start + tdx_nr_guest_keyids - 1))
+		return;
+
+	ida_free(&tdx_guest_keyid_pool, keyid);
+}
+
 static int __init tdx_module_setup(void)
 {
 	int ret;
Signature · 1 line
2.25.1
#207 lore raw

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

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

From: Isaku Yamahata <[email protected]>

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

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

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

Quoted 3 lines

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

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

Quoted 2 lines

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

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

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

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

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

Quoted 25 lines

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

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

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

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


+/*

Quoted 8 lines

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

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

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

!tdx_nr_guest_keyids))
+               return -EINVAL;

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

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

Quoted 12 lines

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

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

tdx_nr_guest_keyids - 1))
+               return;

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

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

 static int __init tdx_module_setup(void)
 {
        int ret;

#208 lore raw

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

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

From: Isaku Yamahata <[email protected]>

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

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

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

Quoted 3 lines

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

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

Quoted 2 lines

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

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

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

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

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

Quoted 28 lines

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

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

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

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


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

Quoted 8 lines
Quoted 5 lines

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

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

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

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

!tdx_nr_guest_keyids))
+               return -EINVAL;

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

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

Quoted 13 lines

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

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

tdx_nr_guest_keyids - 1))

Quoted 8 lines
Quoted 1 line

+               return;

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

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

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

PATCH v19 33/130 KVM: TDX: Add helper function to read TDX metadata in array

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

---
v18:
- newly added

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

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

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

From: Isaku Yamahata <[email protected]>

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

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

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

Quoted 72 lines

---
v18:
- newly added

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

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

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

From: Isaku Yamahata <[email protected]>

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

Quoted 5 lines

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

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

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

Quoted 72 lines
Quoted 71 lines

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

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

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

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

From: Isaku Yamahata <[email protected]>

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

Quoted 7 lines
Quoted 5 lines

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

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

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

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

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

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

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

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

From: Isaku Yamahata <[email protected]>

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

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

Quoted 2 lines

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

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

Quoted 59 lines

---
v18:
- newly added

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

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

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

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

This will only confuse people.

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

#214 lore raw

PATCH v19 34/130 KVM: TDX: Get system-wide info about TDX module on initialization

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

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

Change v18:
- Newly Added

---
 arch/x86/include/uapi/asm/kvm.h | 11 +++++
 arch/x86/kvm/vmx/main.c         |  9 +++-
 arch/x86/kvm/vmx/tdx.c          | 80 ++++++++++++++++++++++++++++++++-
 arch/x86/kvm/vmx/x86_ops.h      |  2 +
 4 files changed, 100 insertions(+), 2 deletions(-)
arch/x86/include/uapi/asm/kvm.h +11 -0
index aa7a56a47564..45b2c2304491 100644
@@ -567,4 +567,15 @@ struct kvm_pmu_event_filter {
 #define KVM_X86_TDX_VM		2
 #define KVM_X86_SNP_VM		3
 
+#define KVM_TDX_CPUID_NO_SUBLEAF	((__u32)-1)
+
+struct kvm_tdx_cpuid_config {
+	__u32 leaf;
+	__u32 sub_leaf;
+	__u32 eax;
+	__u32 ebx;
+	__u32 ecx;
+	__u32 edx;
+};
+
 #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/main.c +8 -1
index fa19682b366c..a948a6959ac7 100644
@@ -32,6 +32,13 @@ static __init int vt_hardware_setup(void)
 	return 0;
 }
 
+static void vt_hardware_unsetup(void)
+{
+	if (enable_tdx)
+		tdx_hardware_unsetup();
+	vmx_hardware_unsetup();
+}
+
 static int vt_vm_init(struct kvm *kvm)
 {
 	if (is_td(kvm))
@@ -54,7 +61,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 
 	.check_processor_compatibility = vmx_check_processor_compat,
 
-	.hardware_unsetup = vmx_hardware_unsetup,
+	.hardware_unsetup = vt_hardware_unsetup,
 
 	/* TDX cpu enablement is done by tdx_hardware_setup(). */
 	.hardware_enable = vmx_hardware_enable,
arch/x86/kvm/vmx/tdx.c +79 -1

111 lines not on this page · raw message

arch/x86/kvm/vmx/x86_ops.h +2 -0
index f4da88a228d0..e8cb4ae81cf1 100644
@@ -136,9 +136,11 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 
 #ifdef CONFIG_INTEL_TDX_HOST
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
+void tdx_hardware_unsetup(void);
 bool tdx_is_vm_type_supported(unsigned long type);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
+static inline void tdx_hardware_unsetup(void) {}
 static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
 #endif
 
Signature · 1 line
2.25.1
Reviewed-by on v19 34/130
#215 lore raw

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

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

From: Isaku Yamahata <[email protected]>

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

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

Quoted 201 lines

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

Change v18:
- Newly Added

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

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

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

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

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

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

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

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

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

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

	...

	tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

	tdx_info->num_cpuid_config = (u16)num_cpuid_config;

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

But there are other (better) ways to do:

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

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

And do:

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

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

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

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

Then you can do:

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

	tdx_sys_metadata_read(tdx_info_fields,
			ARRAY_SIZE(tdx_info_fields, tdx_info);

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

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

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

		....
	}

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

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

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

#217 lore raw

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

Quoted 127 lines · Kai
Quoted 80 lines
arch/x86/kvm/vmx/tdx.c +15 -0
+struct tdx_info {
+    u64 features0;
+    u64 attributes_fixed0;
+    u64 attributes_fixed1;
+    u64 xfam_fixed0;
+    u64 xfam_fixed1;
+
+    u16 num_cpuid_config;
+    /* This must the last member. */
+    DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+

  #define TDX_MD_MAP(_fid, _ptr)            \
      { .fid = MD_FIELD_ID_##_fid,        \
        .ptr = (_ptr), }

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

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

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

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

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

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

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

    u64 num_cpuid_config;

    tdx_sys_metadata_field_read(..., &num_cpuid_config);

    ...

    tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

    tdx_info->num_cpuid_config = (u16)num_cpuid_config;

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

But there are other (better) ways to do:

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

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

Quoted 8 lines

And do:

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

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

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

type cast needs another tmp variable to hold the output of u64.

The reason I want to introduce tdx_sys_metadata_read_single() is to provide a simple and unified interface for other codes to read one metadata field, instead of letting the caller to use temporary u64 variable and handle the cast or memcpy itself.

Quoted 5 lines

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

#218 lore raw

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

Quoted 145 lines · Xiaoyao
Quoted 135 lines · Kai
Quoted 80 lines
arch/x86/kvm/vmx/tdx.c +15 -0
+struct tdx_info {
+    u64 features0;
+    u64 attributes_fixed0;
+    u64 attributes_fixed1;
+    u64 xfam_fixed0;
+    u64 xfam_fixed1;
+
+    u16 num_cpuid_config;
+    /* This must the last member. */
+    DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
+};
+
+/* Info about the TDX module. */
+static struct tdx_info *tdx_info;
+

  #define TDX_MD_MAP(_fid, _ptr)            \
      { .fid = MD_FIELD_ID_##_fid,        \
        .ptr = (_ptr), }

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

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

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

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

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

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

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

    u64 num_cpuid_config;

    tdx_sys_metadata_field_read(..., &num_cpuid_config);

    ...

    tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

    tdx_info->num_cpuid_config = (u16)num_cpuid_config;

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

But there are other (better) ways to do:

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

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

And do:

Quoted 8 lines

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

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

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

Quoted 7 lines

type cast needs another tmp variable to hold the output of u64.

The reason I want to introduce tdx_sys_metadata_read_single() is to provide a simple and unified interface for other codes to read one metadata field, instead of letting the caller to use temporary u64 variable and handle the cast or memcpy itself.

You can always use u64 to hold u16 metadata field AFAICT, so it doesn't have to be temporary.

Here is what Isaku can do using the current API:

	u64 num_cpuid_config;
	

	...

	tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

	...

(you can do explicit (u16)num_cpuid_config type cast above if you want.)

With your suggestion, here is what Isaku can do:

	u16 num_cpuid_config;

	...

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

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

	...

I don't see big difference?

One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway.

So, while I don't quite object your proposal, I don't see it being quite necessary.

I'll let other people to have a say.

#219 lore raw

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

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

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

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

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

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

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

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

    u64 num_cpuid_config;

      tdx_sys_metadata_field_read(..., &num_cpuid_config);

    ...

      tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

      tdx_info->num_cpuid_config = (u16)num_cpuid_config;

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

But there are other (better) ways to do:

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

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

And do:

Quoted 8 lines
      tdx_sys_metadata_read_single(NUM_CPUID_CONFIG,
          sizeof(num_cpuid_config), &num_cpuid_config);

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

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

Quoted 7 lines

type cast needs another tmp variable to hold the output of u64.

The reason I want to introduce tdx_sys_metadata_read_single() is to provide a simple and unified interface for other codes to read one metadata field, instead of letting the caller to use temporary u64 variable and handle the cast or memcpy itself.

You can always use u64 to hold u16 metadata field AFAICT, so it doesn't have to be temporary.

Here is what Isaku can do using the current API:

Quoted 10 lines
	u64 num_cpuid_config;


	...

	tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

Dosen't num_cpuid_config serve as temporary variable in some sense?

For this case, it needs to be used for calculating the size of tdx_info. So we have to have it. But it's not the common case.

E.g., if we have another non-u64 field (e.g., field_x) in tdx_info, we cannot to read it via

	tdx_sys_metadata_field_read(FIELD_X_ID, &tdx_info->field_x);

we have to use a temporary u64 variable.

Quoted 41 lines
	...

(you can do explicit (u16)num_cpuid_config type cast above if you want.)

With your suggestion, here is what Isaku can do:

	u16 num_cpuid_config;

	...

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

	tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

	tdx_info->num_cpuid_config = num_cpuid_config;

	...

I don't see big difference?

One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway.

So, while I don't quite object your proposal, I don't see it being quite necessary.

I'll let other people to have a say.

#220 lore raw

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

Quoted 7 lines · Xiaoyao
Quoted 3 lines

Here is what Isaku can do using the current API:

  u64 num_cpuid_config;

 >

Quoted 3 lines

  ...

Quoted 7 lines
Quoted 5 lines

  tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

  tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

  tdx_info->num_cpuid_config = num_cpuid_config;

Dosen't num_cpuid_config serve as temporary variable in some sense?

You need it, regardless whether it is u64 or u16.

Quoted 10 lines

For this case, it needs to be used for calculating the size of tdx_info. So we have to have it. But it's not the common case.

E.g., if we have another non-u64 field (e.g., field_x) in tdx_info, we cannot to read it via

	tdx_sys_metadata_field_read(FIELD_X_ID, &tdx_info->field_x);

we have to use a temporary u64 variable.

Let me repeat below in my _previous_ reply:

"
One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway. "

So sorry I am not seeing a real example from you.

#221 lore raw

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

Quoted 42 lines · Kai
Quoted 7 lines · Xiaoyao
Quoted 3 lines

Here is what Isaku can do using the current API:

  u64 num_cpuid_config;

 >

Quoted 3 lines

  ...

Quoted 7 lines
Quoted 5 lines

  tdx_sys_metadata_field_read(NUM_CPUID_CONFIG, &num_cpuid_config);

  tdx_info = kzalloc(calculate_tdx_info_size(num_cpuid_config), ...);

  tdx_info->num_cpuid_config = num_cpuid_config;

Dosen't num_cpuid_config serve as temporary variable in some sense?

You need it, regardless whether it is u64 or u16.

Quoted 10 lines

For this case, it needs to be used for calculating the size of tdx_info. So we have to have it. But it's not the common case.

E.g., if we have another non-u64 field (e.g., field_x) in tdx_info, we cannot to read it via

	tdx_sys_metadata_field_read(FIELD_X_ID, &tdx_info->field_x);

we have to use a temporary u64 variable.

Let me repeat below in my _previous_ reply:

"
One example that the current tdx_sys_metadata_field_read() doesn't quite fit is you have something like this:

	struct {
		u16 whatever;
		...
	} st;

	tdx_sys_metadata_field_read(FIELD_ID_WHATEVER, &st.whatever);
Quoted 3 lines

But for this use case you are not supposed to use tdx_sys_metadata_field_read(), but use tdx_sys_metadata_read() which has a mapping provided anyway. "

tdx_sys_metadata_read() is too complicated for just reading one field.

Caller needs to prepare a one-item size array of "struct tdx_metadata_field_mapping" and pass the correct offset.

Quoted 2 lines

So sorry I am not seeing a real example from you.

#222 lore raw

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

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

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

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

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

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

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

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

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

	...

	tdx_info->num_cpuid_config = num_cpuid_config;

Or you can explicitly cast:

	tdx_info->num_cpuid_config = (u16)num_cpuid_config;

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

But there are other (better) ways to do:

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

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

And do:

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

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

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

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

Then you can do:

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

	tdx_sys_metadata_read(tdx_info_fields,
			ARRAY_SIZE(tdx_info_fields, tdx_info);

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

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

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

		....
	}
Quoted 2 lines

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

Ok, I'll rewrite the code to use tdx_sys_metadata_read() by introducng tentative struct in a function scope.

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

PATCH v19 35/130 KVM: TDX: Add place holder for TDX VM specific mem_enc_op ioctl

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

TDX requires VM-scoped TDX-specific operations for device model, for example, qemu. Getting system-wide parameters, TDX-specific VM initialization.

Add a place holder function for TDX specific VM-scoped ioctl as mem_enc_op. TDX specific sub-commands will be added to retrieve/pass TDX specific parameters. Make mem_enc_ioctl non-optional as it's always filled.

---
v15:
- change struct kvm_tdx_cmd to drop unused member.

---
 arch/x86/include/asm/kvm-x86-ops.h |  2 +-
 arch/x86/include/uapi/asm/kvm.h    | 26 ++++++++++++++++++++++++++
 arch/x86/kvm/vmx/main.c            | 10 ++++++++++
 arch/x86/kvm/vmx/tdx.c             | 26 ++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h         |  4 ++++
 arch/x86/kvm/x86.c                 |  4 ----
 6 files changed, 67 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -1
index 8be71a5c5c87..00b371d9a1ca 100644
@@ -123,7 +123,7 @@ KVM_X86_OP(enter_smm)
 KVM_X86_OP(leave_smm)
 KVM_X86_OP(enable_smi_window)
 #endif
-KVM_X86_OP_OPTIONAL(mem_enc_ioctl)
+KVM_X86_OP(mem_enc_ioctl)
 KVM_X86_OP_OPTIONAL(mem_enc_register_region)
 KVM_X86_OP_OPTIONAL(mem_enc_unregister_region)
 KVM_X86_OP_OPTIONAL(vm_copy_enc_context_from)
arch/x86/include/uapi/asm/kvm.h +26 -0
index 45b2c2304491..9ea46d143bef 100644
@@ -567,6 +567,32 @@ struct kvm_pmu_event_filter {
 #define KVM_X86_TDX_VM		2
 #define KVM_X86_SNP_VM		3
 
+/* Trust Domain eXtension sub-ioctl() commands. */
+enum kvm_tdx_cmd_id {
+	KVM_TDX_CAPABILITIES = 0,
+
+	KVM_TDX_CMD_NR_MAX,
+};
+
+struct kvm_tdx_cmd {
+	/* enum kvm_tdx_cmd_id */
+	__u32 id;
+	/* flags for sub-commend. If sub-command doesn't use this, set zero. */
+	__u32 flags;
+	/*
+	 * data for each sub-command. An immediate or a pointer to the actual
+	 * data in process virtual address.  If sub-command doesn't use it,
+	 * set zero.
+	 */
+	__u64 data;
+	/*
+	 * Auxiliary error code.  The sub-command may return TDX SEAMCALL
+	 * status code in addition to -Exxx.
+	 * Defined for consistency with struct kvm_sev_cmd.
+	 */
+	__u64 error;
+};
+
 #define KVM_TDX_CPUID_NO_SUBLEAF	((__u32)-1)
 
 struct kvm_tdx_cpuid_config {
arch/x86/kvm/vmx/main.c +10 -0
index a948a6959ac7..082e82ce6580 100644
@@ -47,6 +47,14 @@ static int vt_vm_init(struct kvm *kvm)
 	return vmx_vm_init(kvm);
 }
 
+static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
+{
+	if (!is_td(kvm))
+		return -ENOTTY;
+
+	return tdx_vm_ioctl(kvm, argp);
+}
+
 #define VMX_REQUIRED_APICV_INHIBITS				\
 	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
 	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\
@@ -200,6 +208,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
 
 	.get_untagged_addr = vmx_get_untagged_addr,
+
+	.mem_enc_ioctl = vt_mem_enc_ioctl,
 };
 
 struct kvm_x86_init_ops vt_init_ops __initdata = {
arch/x86/kvm/vmx/tdx.c +26 -0
index 5edfb99abb89..07a3f0f75f87 100644
@@ -55,6 +55,32 @@ struct tdx_info {
 /* Info about the TDX module. */
 static struct tdx_info *tdx_info;
 
+int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
+{
+	struct kvm_tdx_cmd tdx_cmd;
+	int r;
+
+	if (copy_from_user(&tdx_cmd, argp, sizeof(struct kvm_tdx_cmd)))
+		return -EFAULT;
+	if (tdx_cmd.error)
+		return -EINVAL;
+
+	mutex_lock(&kvm->lock);
+
+	switch (tdx_cmd.id) {
+	default:
+		r = -EINVAL;
+		goto out;
+	}
+
+	if (copy_to_user(argp, &tdx_cmd, sizeof(struct kvm_tdx_cmd)))
+		r = -EFAULT;
+
+out:
+	mutex_unlock(&kvm->lock);
+	return r;
+}
+
 #define TDX_MD_MAP(_fid, _ptr)			\
 	{ .fid = MD_FIELD_ID_##_fid,		\
 	  .ptr = (_ptr), }
arch/x86/kvm/vmx/x86_ops.h +4 -0
index e8cb4ae81cf1..f6c57ad44f80 100644
@@ -138,10 +138,14 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 void tdx_hardware_unsetup(void);
 bool tdx_is_vm_type_supported(unsigned long type);
+
+int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
 static inline void tdx_hardware_unsetup(void) {}
 static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
+
+static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOPNOTSUPP; }
 #endif
 
 #endif /* __KVM_X86_VMX_X86_OPS_H */
arch/x86/kvm/x86.c +0 -4
index 442b356e4939..c459a5e9e520 100644
@@ -7247,10 +7247,6 @@ int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
 		goto out;
 	}
 	case KVM_MEMORY_ENCRYPT_OP: {
-		r = -ENOTTY;
-		if (!kvm_x86_ops.mem_enc_ioctl)
-			goto out;
-
 		r = static_call(kvm_x86_mem_enc_ioctl)(kvm, argp);
 		break;
 	}
Signature · 1 line
2.25.1
#224 lore raw

Re: [PATCH v19 035/130] KVM: TDX: Add place holder for TDX VM specific mem_enc_op ioctl

Quoted 9 lines · Isaku

From: Isaku Yamahata <[email protected]>

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

Quoted 3 lines

TDX requires VM-scoped TDX-specific operations for device model, for example, qemu. Getting system-wide parameters, TDX-specific VM initialization.

-EPARSE for the second sentence (or it is not a valid sentence at all).

Quoted 53 lines

Add a place holder function for TDX specific VM-scoped ioctl as mem_enc_op. TDX specific sub-commands will be added to retrieve/pass TDX specific parameters. Make mem_enc_ioctl non-optional as it's always filled.

---
v15:
- change struct kvm_tdx_cmd to drop unused member.

---
  arch/x86/include/asm/kvm-x86-ops.h |  2 +-
  arch/x86/include/uapi/asm/kvm.h    | 26 ++++++++++++++++++++++++++
  arch/x86/kvm/vmx/main.c            | 10 ++++++++++
  arch/x86/kvm/vmx/tdx.c             | 26 ++++++++++++++++++++++++++
  arch/x86/kvm/vmx/x86_ops.h         |  4 ++++
  arch/x86/kvm/x86.c                 |  4 ----
  6 files changed, 67 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -1
index 8be71a5c5c87..00b371d9a1ca 100644
@@ -123,7 +123,7 @@ KVM_X86_OP(enter_smm)
  KVM_X86_OP(leave_smm)
  KVM_X86_OP(enable_smi_window)
  #endif
-KVM_X86_OP_OPTIONAL(mem_enc_ioctl)
+KVM_X86_OP(mem_enc_ioctl)
  KVM_X86_OP_OPTIONAL(mem_enc_register_region)
  KVM_X86_OP_OPTIONAL(mem_enc_unregister_region)
  KVM_X86_OP_OPTIONAL(vm_copy_enc_context_from)
arch/x86/include/uapi/asm/kvm.h +14 -0
index 45b2c2304491..9ea46d143bef 100644
@@ -567,6 +567,32 @@ struct kvm_pmu_event_filter {
  #define KVM_X86_TDX_VM		2
  #define KVM_X86_SNP_VM		3
 
+/* Trust Domain eXtension sub-ioctl() commands. */
+enum kvm_tdx_cmd_id {
+	KVM_TDX_CAPABILITIES = 0,
+
+	KVM_TDX_CMD_NR_MAX,
+};
+
+struct kvm_tdx_cmd {
+	/* enum kvm_tdx_cmd_id */
+	__u32 id;
+	/* flags for sub-commend. If sub-command doesn't use this, set zero. */
+	__u32 flags;
+	/*
+	 * data for each sub-command. An immediate or a pointer to the actual

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

Quoted 10 lines
arch/x86/include/uapi/asm/kvm.h +10 -0
+	 * data in process virtual address.  If sub-command doesn't use it,
+	 * set zero.
+	 */
+	__u64 data;
+	/*
+	 * Auxiliary error code.  The sub-command may return TDX SEAMCALL
+	 * status code in addition to -Exxx.
+	 * Defined for consistency with struct kvm_sev_cmd.
+	 */
+	__u64 error;

If the 'error' is for SEAMCALL error, should we rename it to 'hw_error' or 'fw_error' or something similar? I think 'error' is too generic.

Quoted 38 lines
arch/x86/include/uapi/asm/kvm.h +2 -0
+};
+
  #define KVM_TDX_CPUID_NO_SUBLEAF	((__u32)-1)
 
  struct kvm_tdx_cpuid_config {
arch/x86/kvm/vmx/main.c +10 -0
index a948a6959ac7..082e82ce6580 100644
@@ -47,6 +47,14 @@ static int vt_vm_init(struct kvm *kvm)
  	return vmx_vm_init(kvm);
  }
 
+static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
+{
+	if (!is_td(kvm))
+		return -ENOTTY;
+
+	return tdx_vm_ioctl(kvm, argp);
+}
+
  #define VMX_REQUIRED_APICV_INHIBITS				\
  	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
  	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\
@@ -200,6 +208,8 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
 
  	.get_untagged_addr = vmx_get_untagged_addr,
+
+	.mem_enc_ioctl = vt_mem_enc_ioctl,
  };
 
  struct kvm_x86_init_ops vt_init_ops __initdata = {
arch/x86/kvm/vmx/tdx.c +0 -0
index 5edfb99abb89..07a3f0f75f87 100644

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 64

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +7 -0
@@ -55,6 +55,32 @@ struct tdx_info {
  /* Info about the TDX module. */
  static struct tdx_info *tdx_info;
 
+int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
+{
+	struct kvm_tdx_cmd tdx_cmd;
+	int r;
+
+	if (copy_from_user(&tdx_cmd, argp, sizeof(struct kvm_tdx_cmd)))
+		return -EFAULT;

Add an empty line.

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 66

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	if (tdx_cmd.error)
+		return -EINVAL;

Add a comment?

	/*
	 * Userspace should never set @error, which is used to fill
	 * hardware-defined error by the kernel.
	 */

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 72

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	mutex_lock(&kvm->lock);
+
+	switch (tdx_cmd.id) {
+	default:
+		r = -EINVAL;

I am not sure whether you should return -ENOTTY to be consistent with the previous vt_mem_enc_ioctl() where a TDX-specific IOCTL is issued for non-TDX guest.

Here I think the invalid @id means the sub-command isn't valid.

Quoted 11 lines
arch/x86/kvm/vmx/tdx.c +11 -0
+		goto out;
+	}
+
+	if (copy_to_user(argp, &tdx_cmd, sizeof(struct kvm_tdx_cmd)))
+		r = -EFAULT;
+
+out:
+	mutex_unlock(&kvm->lock);
+	return r;
+}
+
#225 lore raw

Re: [PATCH v19 035/130] KVM: TDX: Add place holder for TDX VM specific mem_enc_op ioctl

Quoted 26 lines · Kai
Quoted 26 lines
arch/x86/include/uapi/asm/kvm.h +19 -0
index 45b2c2304491..9ea46d143bef 100644
@@ -567,6 +567,32 @@ struct kvm_pmu_event_filter {
  #define KVM_X86_TDX_VM		2
  #define KVM_X86_SNP_VM		3
+/* Trust Domain eXtension sub-ioctl() commands. */
+enum kvm_tdx_cmd_id {
+	KVM_TDX_CAPABILITIES = 0,
+
+	KVM_TDX_CMD_NR_MAX,
+};
+
+struct kvm_tdx_cmd {
+	/* enum kvm_tdx_cmd_id */
+	__u32 id;
+	/* flags for sub-commend. If sub-command doesn't use this, set zero. */
+	__u32 flags;
+	/*
+	 * data for each sub-command. An immediate or a pointer to the actual
+	 * data in process virtual address.  If sub-command doesn't use it,
+	 * set zero.
+	 */
+	__u64 data;
+	/*
Quoted 8 lines

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

Quoted 5 lines
arch/x86/include/uapi/asm/kvm.h +5 -0
+	 * Auxiliary error code.  The sub-command may return TDX SEAMCALL
+	 * status code in addition to -Exxx.
+	 * Defined for consistency with struct kvm_sev_cmd.
+	 */
+	__u64 error;

If the 'error' is for SEAMCALL error, should we rename it to 'hw_error' or 'fw_error' or something similar? I think 'error' is too generic.

Ok, will rename it to hw_error.

Quoted 22 lines
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +0 -0
index 5edfb99abb89..07a3f0f75f87 100644

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 63

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +7 -0
@@ -55,6 +55,32 @@ struct tdx_info {
  /* Info about the TDX module. */
  static struct tdx_info *tdx_info;
+int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
+{
+	struct kvm_tdx_cmd tdx_cmd;
+	int r;
+
+	if (copy_from_user(&tdx_cmd, argp, sizeof(struct kvm_tdx_cmd)))
+		return -EFAULT;

Add an empty line.

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 66

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	if (tdx_cmd.error)
+		return -EINVAL;

Add a comment?

Quoted 4 lines
	/*
	 * Userspace should never set @error, which is used to fill
	 * hardware-defined error by the kernel.
	 */

Sure.

Quoted 11 lines

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 72

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	mutex_lock(&kvm->lock);
+
+	switch (tdx_cmd.id) {
+	default:
+		r = -EINVAL;

I am not sure whether you should return -ENOTTY to be consistent with the previous vt_mem_enc_ioctl() where a TDX-specific IOCTL is issued for non-TDX guest.

Quoted 1 line

Here I think the invalid @id means the sub-command isn't valid.

vt_vcpu_mem_enc_ioctl() checks non-TDX case and returns -ENOTTY. We know that the guest is TD.

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

Re: [PATCH v19 035/130] KVM: TDX: Add place holder for TDX VM specific mem_enc_op ioctl

Quoted 12 lines
Quoted 12 lines

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 72

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	mutex_lock(&kvm->lock);
+
+	switch (tdx_cmd.id) {
+	default:
+		r = -EINVAL;

I am not sure whether you should return -ENOTTY to be consistent with the previous vt_mem_enc_ioctl() where a TDX-specific IOCTL is issued for non-TDX guest.

Quoted 4 lines
Quoted 1 line

Here I think the invalid @id means the sub-command isn't valid.

vt_vcpu_mem_enc_ioctl() checks non-TDX case and returns -ENOTTY. We know that the guest is TD.

But the command is not supported, right?

I roughly recall I saw somewhere that in such case we should return -ENOTTY, but I cannot find the link now.

But I found this old link uses -ENOTTY:

https://lwn.net/Articles/58719/

So, just fyi.

#227 lore raw

Re: [PATCH v19 035/130] KVM: TDX: Add place holder for TDX VM specific mem_enc_op ioctl

Quoted 5 lines · Kai
Quoted 2 lines

vt_vcpu_mem_enc_ioctl() checks non-TDX case and returns -ENOTTY.  We know that the guest is TD.

But the command is not supported, right?

Quoted 8 lines

I roughly recall I saw somewhere that in such case we should return -ENOTTY, but I cannot find the link now.

But I found this old link uses -ENOTTY:

https://lwn.net/Articles/58719/

So, just fyi.

The AMD version of this returns -EINVAL when the subcommand is not implemented. I don't think the TDX side should need to necessarily match that. Is the case of concern when in a future where there are more subcommands that are only supported when some other mode is enabled?

The man page says:
ENOTTY The specified request does not apply to the kind of object
that the file descriptor fd references.

If a future command does not apply for the TDX mode, then an upgraded kernel could start returning ENOTTY instead of EINVAL. Hmm. We could always have the option of making KVM_MEMORY_ENCRYPT_OP_FOO for some future mode foo if there were compatibility issues, so I don't think we would be stuck either way.

After thinking about it, I'd make a weak vote to leave it. No strong opinion though.

#228 lore raw

PATCH v19 36/130 KVM: TDX: x86: Add ioctl to get TDX systemwide parameters

In reply to [email protected]

From: Sean Christopherson <[email protected]>

Implement an ioctl to get system-wide parameters for TDX. Although the function is systemwide, vm scoped mem_enc ioctl works for userspace VMM like qemu and device scoped version is not define, re-use vm scoped mem_enc.

---
v18:
- drop the use of tdhsysinfo_struct and TDH.SYS.INFO, use TDH.SYS.RD(). For that, dynamically allocate/free tdx_info.
- drop the change of tools/arch/x86/include/uapi/asm/kvm.h.

v14 -> v15:
- ABI change: added supported_gpaw and reserved area.

---
 arch/x86/include/uapi/asm/kvm.h | 17 ++++++++++
 arch/x86/kvm/vmx/tdx.c          | 56 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h          |  3 ++
 3 files changed, 76 insertions(+)
arch/x86/include/uapi/asm/kvm.h +17 -0
index 9ea46d143bef..e28189c81691 100644
@@ -604,4 +604,21 @@ struct kvm_tdx_cpuid_config {
 	__u32 edx;
 };
 
+/* supported_gpaw */
+#define TDX_CAP_GPAW_48	(1 << 0)
+#define TDX_CAP_GPAW_52	(1 << 1)
+
+struct kvm_tdx_capabilities {
+	__u64 attrs_fixed0;
+	__u64 attrs_fixed1;
+	__u64 xfam_fixed0;
+	__u64 xfam_fixed1;
+	__u32 supported_gpaw;
+	__u32 padding;
+	__u64 reserved[251];
+
+	__u32 nr_cpuid_configs;
+	struct kvm_tdx_cpuid_config cpuid_configs[];
+};
+
 #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/tdx.c +56 -0

74 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.h +3 -0
index 473013265bd8..22c0b57f69ca 100644
@@ -3,6 +3,9 @@
 #define __KVM_X86_TDX_H
 
 #ifdef CONFIG_INTEL_TDX_HOST
+
+#include "tdx_ops.h"
+
 struct kvm_tdx {
 	struct kvm kvm;
 	/* TDX specific members follow. */
Signature · 1 line
2.25.1
#229 lore raw

Re: [PATCH v19 036/130] KVM: TDX: x86: Add ioctl to get TDX systemwide parameters

Quoted 6 lines · Isaku

From: Sean Christopherson <[email protected]>

Implement an ioctl to get system-wide parameters for TDX. Although the function is systemwide, vm scoped mem_enc ioctl works for userspace VMM like qemu and device scoped version is not define, re-use vm scoped mem_enc.

-EPARSE for the part starting from "and device scoped ...".

Grammar check please.

Quoted 34 lines

---
v18:
- drop the use of tdhsysinfo_struct and TDH.SYS.INFO, use TDH.SYS.RD(). For that, dynamically allocate/free tdx_info.
- drop the change of tools/arch/x86/include/uapi/asm/kvm.h.

v14 -> v15:
- ABI change: added supported_gpaw and reserved area.

---
  arch/x86/include/uapi/asm/kvm.h | 17 ++++++++++
  arch/x86/kvm/vmx/tdx.c          | 56 +++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/tdx.h          |  3 ++
  3 files changed, 76 insertions(+)
arch/x86/include/uapi/asm/kvm.h +7 -0
index 9ea46d143bef..e28189c81691 100644
@@ -604,4 +604,21 @@ struct kvm_tdx_cpuid_config {
  	__u32 edx;
  };
 
+/* supported_gpaw */
+#define TDX_CAP_GPAW_48	(1 << 0)
+#define TDX_CAP_GPAW_52	(1 << 1)
+
+struct kvm_tdx_capabilities {
+	__u64 attrs_fixed0;
+	__u64 attrs_fixed1;

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_cpuid_config { · line 623

Quoted 10 lines
arch/x86/include/uapi/asm/kvm.h +10 -0
+	__u64 xfam_fixed0;
+	__u64 xfam_fixed1;
+	__u32 supported_gpaw;
+	__u32 padding;
+	__u64 reserved[251];
+
+	__u32 nr_cpuid_configs;
+	struct kvm_tdx_cpuid_config cpuid_configs[];
+};
+

I think you should use __DECLARE_FLEX_ARRAY().

It's already used in existing KVM UAPI header:

struct kvm_nested_state {
	...
        union {
                __DECLARE_FLEX_ARRAY(struct kvm_vmx_nested_state_data,
					 vmx);
                __DECLARE_FLEX_ARRAY(struct kvm_svm_nested_state_data,
					 svm);
        } data;
}
Quoted 15 lines
arch/x86/include/uapi/asm/kvm.h +0 -0
  #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/vmx/tdx.c +1 -0
index 07a3f0f75f87..816ccdb4bc41 100644
@@ -6,6 +6,7 @@
  #include "capabilities.h"
  #include "x86_ops.h"
  #include "x86.h"
+#include "mmu.h"
  #include "tdx_arch.h"
  #include "tdx.h"
 
@@ -55,6 +56,58 @@ struct tdx_info {
  /* Info about the TDX module. */

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 66

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +8 -0
  static struct tdx_info *tdx_info;
 
+static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
+{
+	struct kvm_tdx_capabilities __user *user_caps;
+	struct kvm_tdx_capabilities *caps = NULL;
+	int ret = 0;
+
+	if (cmd->flags)
+		return -EINVAL;

Add a comment?

	/* flags is reserved for future use */
Quoted 22 lines
arch/x86/kvm/vmx/tdx.c +22 -0
+
+	caps = kmalloc(sizeof(*caps), GFP_KERNEL);
+	if (!caps)
+		return -ENOMEM;
+
+	user_caps = (void __user *)cmd->data;
+	if (copy_from_user(caps, user_caps, sizeof(*caps))) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+	if (caps->nr_cpuid_configs < tdx_info->num_cpuid_config) {
+		ret = -E2BIG;
+		goto out;
+	}
+
+	*caps = (struct kvm_tdx_capabilities) {
+		.attrs_fixed0 = tdx_info->attributes_fixed0,
+		.attrs_fixed1 = tdx_info->attributes_fixed1,
+		.xfam_fixed0 = tdx_info->xfam_fixed0,
+		.xfam_fixed1 = tdx_info->xfam_fixed1,
+		.supported_gpaw = TDX_CAP_GPAW_48 |

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 98

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		((kvm_get_shadow_phys_bits() >= 52 &&
+		  cpu_has_vmx_ept_5levels()) ? TDX_CAP_GPAW_52 : 0),
+		.nr_cpuid_configs = tdx_info->num_cpuid_config,
+		.padding = 0,
+	};
+
+	if (copy_to_user(user_caps, caps, sizeof(*caps))) {
+		ret = -EFAULT;
+		goto out;
+	}

Add an empty line.

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 103

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	if (copy_to_user(user_caps->cpuid_configs, &tdx_info->cpuid_configs,
+			 tdx_info->num_cpuid_config *
+			 sizeof(tdx_info->cpuid_configs[0]))) {
+		ret = -EFAULT;
+	}

I think the '{ }' is needed here.

Quoted 25 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+out:
+	/* kfree() accepts NULL. */
+	kfree(caps);
+	return ret;
+}
+
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
  {
  	struct kvm_tdx_cmd tdx_cmd;
@@ -68,6 +121,9 @@ int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
  	mutex_lock(&kvm->lock);
 
  	switch (tdx_cmd.id) {
+	case KVM_TDX_CAPABILITIES:
+		r = tdx_get_capabilities(&tdx_cmd);
+		break;
  	default:
  		r = -EINVAL;
  		goto out;
arch/x86/kvm/vmx/tdx.h +0 -0
index 473013265bd8..22c0b57f69ca 100644

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

Quoted 6 lines
arch/x86/kvm/vmx/tdx.h +3 -0
@@ -3,6 +3,9 @@
  #define __KVM_X86_TDX_H
 
  #ifdef CONFIG_INTEL_TDX_HOST
+
+#include "tdx_ops.h"
+

It appears "tdx_ops.h" is used for making SEAMCALLs.

I don't see this patch uses any SEAMCALL so I am wondering whether this chunk is needed here?

Quoted 3 lines
arch/x86/kvm/vmx/tdx.h +0 -0
  struct kvm_tdx {
  	struct kvm kvm;
  	/* TDX specific members follow. */
#230 lore raw

Re: [PATCH v19 036/130] KVM: TDX: x86: Add ioctl to get TDX systemwide parameters

Quoted 29 lines · Kai
Quoted 14 lines
arch/x86/include/uapi/asm/kvm.h +7 -0
index 9ea46d143bef..e28189c81691 100644
@@ -604,4 +604,21 @@ struct kvm_tdx_cpuid_config {
  	__u32 edx;
  };
+/* supported_gpaw */
+#define TDX_CAP_GPAW_48	(1 << 0)
+#define TDX_CAP_GPAW_52	(1 << 1)
+
+struct kvm_tdx_capabilities {
+	__u64 attrs_fixed0;
+	__u64 attrs_fixed1;

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_cpuid_config { · line 622

Quoted 10 lines
arch/x86/include/uapi/asm/kvm.h +10 -0
+	__u64 xfam_fixed0;
+	__u64 xfam_fixed1;
+	__u32 supported_gpaw;
+	__u32 padding;
+	__u64 reserved[251];
+
+	__u32 nr_cpuid_configs;
+	struct kvm_tdx_cpuid_config cpuid_configs[];
+};
+

I think you should use __DECLARE_FLEX_ARRAY().

It's already used in existing KVM UAPI header:

Quoted 9 lines
struct kvm_nested_state {
	...
        union {
                __DECLARE_FLEX_ARRAY(struct kvm_vmx_nested_state_data,
					 vmx);
                __DECLARE_FLEX_ARRAY(struct kvm_svm_nested_state_data,
					 svm);
        } data;
}

Yes, will use it.

Quoted 7 lines

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_cpuid_config {

Quoted 5 lines
arch/x86/include/uapi/asm/kvm.h +5 -0
+	if (copy_to_user(user_caps->cpuid_configs, &tdx_info->cpuid_configs,
+			 tdx_info->num_cpuid_config *
+			 sizeof(tdx_info->cpuid_configs[0]))) {
+		ret = -EFAULT;
+	}

I think the '{ }' is needed here.

Unnecessary? Will remove braces.

Quoted 32 lines
Quoted 24 lines
arch/x86/include/uapi/asm/kvm.h +10 -0
+
+out:
+	/* kfree() accepts NULL. */
+	kfree(caps);
+	return ret;
+}
+
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
  {
  	struct kvm_tdx_cmd tdx_cmd;
@@ -68,6 +121,9 @@ int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
  	mutex_lock(&kvm->lock);
  	switch (tdx_cmd.id) {
+	case KVM_TDX_CAPABILITIES:
+		r = tdx_get_capabilities(&tdx_cmd);
+		break;
  	default:
  		r = -EINVAL;
  		goto out;
arch/x86/kvm/vmx/tdx.h +0 -0
index 473013265bd8..22c0b57f69ca 100644

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

Quoted 5 lines
arch/x86/kvm/vmx/tdx.h +3 -0
@@ -3,6 +3,9 @@
  #define __KVM_X86_TDX_H
  #ifdef CONFIG_INTEL_TDX_HOST
+
+#include "tdx_ops.h"
+

It appears "tdx_ops.h" is used for making SEAMCALLs.

Quoted 2 lines

I don't see this patch uses any SEAMCALL so I am wondering whether this chunk is needed here?

Will remove it to move it to an appropriate patch

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

Re: [PATCH v19 036/130] KVM: TDX: x86: Add ioctl to get TDX systemwide parameters

Quoted 7 lines · Isaku
Quoted 6 lines

arch/x86/kvm/vmx/tdx.c struct tdx_info { · line 103

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	if (copy_to_user(user_caps->cpuid_configs, &tdx_info->cpuid_configs,
+			 tdx_info->num_cpuid_config *
+			 sizeof(tdx_info->cpuid_configs[0]))) {
+		ret = -EFAULT;
+	}

I think the '{ }' is needed here.

Unnecessary? Will remove braces.

Right. Sorry I didn't finish the 'isn't'.

#232 lore raw

Re: [PATCH v19 036/130] KVM: TDX: x86: Add ioctl to get TDX systemwide parameters

In reply to [email protected]
Quoted 9 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.h +0 -0
@@ -3,6 +3,9 @@
  #define __KVM_X86_TDX_H


 #ifdef CONFIG_INTEL_TDX_HOST

arch/x86/kvm/vmx/tdx.h +3 -0
+
+#include "tdx_ops.h"
+
Quoted 3 lines

 struct kvm_tdx {
  struct kvm kvm;
  /* TDX specific members follow. */

I am consistently hitting build error for the middle patches in our internal tree, mostly because of this madness of header file inclusion.

I found the above inclusion of "tdx_ops.h" in "tdx.h" just out of blue.

We have

- "tdx_arch.h"
- "tdx_errno.h"
- "tdx_ops.h"
- "tdx.h"

The first two can be included by the "tdx.h", so that we can have a rule for C files to just include "tdx.h", i.e., the C files should never need to include the first two explicitly.

The "tdx_ops.h" is a little bit confusing. I _think_ the purpose of it is to only contain SEAMCALL wrappers. But I am not sure whether it can be included by any C file directly.

Based on above code change, I _think_ the intention is to also embed it to "tdx.h", so the C files should just include "tdx.h".

But based on Sean's comments, the SEAMCALL wrappers will be changed to take 'struct kvm_tdx *' and 'struct vcpu_tdx *', so they need the declaration of those structures which are in "tdx.h".

I think we can just make a rule that, "tdx_ops.h" should never be directly included by any C file, instead, we include "tdx_ops.h" into "tdx.h" somewhere after declaration of 'struct kvm_tdx' and 'struct vcpu_tdx'.

And such inclusion should happen when the "tdx_ops.h" is introduced.

Am I missing anything?

#233 lore raw

PATCH v19 37/130 KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX has its own limitation on the maximum number of vcpus that the guest can accommodate. Allow x86 kvm backend to implement its own KVM_ENABLE_CAP handler and implement TDX backend for KVM_CAP_MAX_VCPUS. user space VMM, e.g. qemu, can specify its value instead of KVM_MAX_VCPUS.

When creating TD (TDH.MNG.INIT), the maximum number of vcpu needs to be specified as struct td_params_struct. and the value is a part of measurement. The user space has to specify the value somehow. There are two options for it.
option 1. API (Set KVM_CAP_MAX_VCPU) to specify the value (this patch) option 2. Add max_vcpu as a parameter to initialize the guest.

          (TDG.MNG.INIT)

The flow will be create VM (KVM_CREATE_VM), create VCPUs (KVM_CREATE_VCPU), initialize TDX part of VM and, initialize TDX part of vcpu. Because the creation of vcpu is independent from TDX VM initialization, Choose the option 1.
The work flow will be, KVM_CREATE_VM, set KVM_CAP_MAX_VCPU and, KVM_CREATE_VCPU.

---
v18:
- use TDX instead of "x86, tdx" in subject
- use min(max_vcpu, TDX_MAX_VCPU) instead of
min3(max_vcpu, KVM_MAX_VCPU, TDX_MAX_VCPU)
- make "if (KVM_MAX_VCPU) and if (TDX_MAX_VCPU)" into one if statement

---
 arch/x86/include/asm/kvm-x86-ops.h |  2 ++
 arch/x86/include/asm/kvm_host.h    |  2 ++
 arch/x86/kvm/vmx/main.c            | 22 ++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.c             | 29 +++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h         |  5 +++++
 arch/x86/kvm/x86.c                 |  4 ++++
 6 files changed, 64 insertions(+)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 00b371d9a1ca..1b0dacc6b6c0 100644
@@ -21,6 +21,8 @@ KVM_X86_OP(hardware_unsetup)
 KVM_X86_OP(has_emulated_msr)
 KVM_X86_OP(vcpu_after_set_cpuid)
 KVM_X86_OP(is_vm_type_supported)
+KVM_X86_OP_OPTIONAL(max_vcpus);
+KVM_X86_OP_OPTIONAL(vm_enable_cap)
 KVM_X86_OP(vm_init)
 KVM_X86_OP_OPTIONAL(vm_destroy)
 KVM_X86_OP_OPTIONAL_RET0(vcpu_precreate)
arch/x86/include/asm/kvm_host.h +2 -0
index 37cda8aa07b6..cf8eb46b3a20 100644
@@ -1604,7 +1604,9 @@ struct kvm_x86_ops {
 	void (*vcpu_after_set_cpuid)(struct kvm_vcpu *vcpu);
 
 	bool (*is_vm_type_supported)(unsigned long vm_type);
+	int (*max_vcpus)(struct kvm *kvm);
 	unsigned int vm_size;
+	int (*vm_enable_cap)(struct kvm *kvm, struct kvm_enable_cap *cap);
 	int (*vm_init)(struct kvm *kvm);
 	void (*vm_destroy)(struct kvm *kvm);
 
arch/x86/kvm/vmx/main.c +22 -0
index 082e82ce6580..e8a1a7533eea 100644
@@ -6,6 +6,7 @@
 #include "nested.h"
 #include "pmu.h"
 #include "tdx.h"
+#include "tdx_arch.h"
 
 static bool enable_tdx __ro_after_init;
 module_param_named(tdx, enable_tdx, bool, 0444);
@@ -16,6 +17,17 @@ static bool vt_is_vm_type_supported(unsigned long type)
 		(enable_tdx && tdx_is_vm_type_supported(type));
 }
 
+static int vt_max_vcpus(struct kvm *kvm)
+{
+	if (!kvm)
+		return KVM_MAX_VCPUS;
+
+	if (is_td(kvm))
+		return min(kvm->max_vcpus, TDX_MAX_VCPUS);
+
+	return kvm->max_vcpus;
+}
+
 static __init int vt_hardware_setup(void)
 {
 	int ret;
@@ -39,6 +51,14 @@ static void vt_hardware_unsetup(void)
 	vmx_hardware_unsetup();
 }
 
+static int vt_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
+{
+	if (is_td(kvm))
+		return tdx_vm_enable_cap(kvm, cap);
+
+	return -EINVAL;
+}
+
 static int vt_vm_init(struct kvm *kvm)
 {
 	if (is_td(kvm))
@@ -77,7 +97,9 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.has_emulated_msr = vmx_has_emulated_msr,
 
 	.is_vm_type_supported = vt_is_vm_type_supported,
+	.max_vcpus = vt_max_vcpus,
 	.vm_size = sizeof(struct kvm_vmx),
+	.vm_enable_cap = vt_vm_enable_cap,
 	.vm_init = vt_vm_init,
 	.vm_destroy = vmx_vm_destroy,
 
arch/x86/kvm/vmx/tdx.c +29 -0
index 816ccdb4bc41..ee015f3ce2c9 100644
@@ -56,6 +56,35 @@ struct tdx_info {
 /* Info about the TDX module. */
 static struct tdx_info *tdx_info;
 
+int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
+{
+	int r;
+
+	switch (cap->cap) {
+	case KVM_CAP_MAX_VCPUS: {
+		if (cap->flags || cap->args[0] == 0)
+			return -EINVAL;
+		if (cap->args[0] > KVM_MAX_VCPUS ||
+		    cap->args[0] > TDX_MAX_VCPUS)
+			return -E2BIG;
+
+		mutex_lock(&kvm->lock);
+		if (kvm->created_vcpus)
+			r = -EBUSY;
+		else {
+			kvm->max_vcpus = cap->args[0];
+			r = 0;
+		}
+		mutex_unlock(&kvm->lock);
+		break;
+	}
+	default:
+		r = -EINVAL;
+		break;
+	}
+	return r;
+}
+
 static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
 {
 	struct kvm_tdx_capabilities __user *user_caps;
arch/x86/kvm/vmx/x86_ops.h +5 -0
index f6c57ad44f80..0031a8d61589 100644
@@ -139,12 +139,17 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 void tdx_hardware_unsetup(void);
 bool tdx_is_vm_type_supported(unsigned long type);
 
+int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap);
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
 static inline void tdx_hardware_unsetup(void) {}
 static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
 
+static inline int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
+{
+	return -EINVAL;
+};
 static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOPNOTSUPP; }
 #endif
 
arch/x86/kvm/x86.c +4 -0
index c459a5e9e520..3f16e9450d2f 100644
@@ -4726,6 +4726,8 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 		break;
 	case KVM_CAP_MAX_VCPUS:
 		r = KVM_MAX_VCPUS;
+		if (kvm_x86_ops.max_vcpus)
+			r = static_call(kvm_x86_max_vcpus)(kvm);
 		break;
 	case KVM_CAP_MAX_VCPU_ID:
 		r = KVM_MAX_VCPU_IDS;
@@ -6709,6 +6711,8 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
 		break;
 	default:
 		r = -EINVAL;
+		if (kvm_x86_ops.vm_enable_cap)
+			r = static_call(kvm_x86_vm_enable_cap)(kvm, cap);
 		break;
 	}
 	return r;
Signature · 1 line
2.25.1
#234 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 4 lines · Isaku

From: Isaku Yamahata <[email protected]>

TDX has its own limitation on the maximum number of vcpus that the guest can accommodate.

"limitation" -> "control".

"the guest" -> "a guest".

Allow x86 kvm backend to implement its own KVM_ENABLE_CAP

Quoted 1 line

handler and implement TDX backend for KVM_CAP_MAX_VCPUS.

I am not sure we normally say "x86 KVM backend". Just say "Allow KVM x86 ...".

user space VMM,

Quoted 1 line

e.g. qemu, can specify its value instead of KVM_MAX_VCPUS.

Grammar check.

Quoted 3 lines

When creating TD (TDH.MNG.INIT), the maximum number of vcpu needs to be specified as struct td_params_struct.

'struct td_params_struct'??

Anyway, I don't think you need to mention such details.

and the value is a part of

Quoted 1 line

measurement. The user space has to specify the value somehow.

"and" -> "And" (grammar check please).

And add an empty line to start below as a new paragraph.

There are

Quoted 4 lines

two options for it.
option 1. API (Set KVM_CAP_MAX_VCPU) to specify the value (this patch) option 2. Add max_vcpu as a parameter to initialize the guest.

           (TDG.MNG.INIT)

First of all, it seems to me that the two are not conflicting.

Based on the uapi/kvm.h:

  #define KVM_CAP_MAX_VCPUS 66       /* returns max vcpus per vm */

Currently KVM x86 doesn't allow to configure MAX_VCPU on VM-basis, but always reports KVM_MAX_VCPUS for _ALL_ VMs. I.e., it doesn't support userspace to explicitly enable KVM_CAP_MAX_VCPUS for a given VM.

Now, if we allow the userspace to configure the MAX_VCPU for TDX guest (this could be a separate discussion in fact) due to attestation whatever, we need to support allowing userspace to configure MAX_VCPUS on VM-basis.

Therefore, option 1 isn't really an option to me, but is the thing that we _SHOULD_ do to support TDX.

So this pach should really just add "per-VM max vcpus" support for TDX, starting from:

	struct kvm_tdx {	/* or 'struct kvm_arch' ?? */
		...
		int max_vcpus;
	}

And in TDH.MNG.INIT, we need to manually check the MAX_VCPU specified in TD_PARAMS structure to make sure it matches to the record that we specified via KVM_CAP_MAX_VCPUS.

So how about:

"
TDX has its own mechanism to control the maximum number of VCPUs that the TDX guest can use. When creating a TDX guest, the maximum number of vcpus needs to be passed to the TDX module as part of the measurement of the guest.

Because the value is part of the measurement, thus part of attestation, it better to allow the userspace to be able to configure it. E.g. the users may want to precisely control the maximum number of vcpus their precious VMs can use.

The actual control itself must be done via the TDH.MNG.INIT SEAMCALL itself, where the number of maximum cpus is an input to the TDX module, but KVM needs to support the "per-VM number of maximum vcpus" and reflect that in the KVM_CAP_MAX_VCPUS.

Currently, the KVM x86 always reports KVM_MAX_VCPUS for all VMs but doesn't allow to enable KVM_CAP_MAX_VCPUS to configure the number of maximum vcpus on VM-basis.

Add "per-VM maximum vcpus" to KVM x86/TDX to accommodate TDX's needs.

The userspace-configured value then can be verified when KVM is actually creating the TDX guest. "

#235 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 1 line · Kai

So how about:

Thanks for it. I'll update the commit message with some minor fixes.

Quoted 7 lines

"
TDX has its own mechanism to control the maximum number of VCPUs that the TDX guest can use. When creating a TDX guest, the maximum number of vcpus needs to be passed to the TDX module as part of the measurement of the guest.

Because the value is part of the measurement, thus part of attestation, it

                                                                           ^'s
Quoted 1 line

better to allow the userspace to be able to configure it. E.g. the users

the userspace to configure it ^,

Quoted 6 lines

may want to precisely control the maximum number of vcpus their precious VMs can use.

The actual control itself must be done via the TDH.MNG.INIT SEAMCALL itself, where the number of maximum cpus is an input to the TDX module, but KVM needs to support the "per-VM number of maximum vcpus" and reflect that in

per-VM maximum number of vcpus

Quoted 4 lines

the KVM_CAP_MAX_VCPUS.

Currently, the KVM x86 always reports KVM_MAX_VCPUS for all VMs but doesn't allow to enable KVM_CAP_MAX_VCPUS to configure the number of maximum vcpus

maximum number of vcpus

Quoted 5 lines

on VM-basis.

Add "per-VM maximum vcpus" to KVM x86/TDX to accommodate TDX's needs.

The userspace-configured value then can be verified when KVM is actually

used

Quoted 2 lines

creating the TDX guest.
"

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

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 27 lines · Isaku Yamahata
Quoted 1 line · Kai

So how about:

Thanks for it. I'll update the commit message with some minor fixes.

Quoted 7 lines

"
TDX has its own mechanism to control the maximum number of VCPUs that the TDX guest can use. When creating a TDX guest, the maximum number of vcpus needs to be passed to the TDX module as part of the measurement of the guest.

Because the value is part of the measurement, thus part of attestation, it

                                                                            ^'s
Quoted 1 line

better to allow the userspace to be able to configure it. E.g. the users

the userspace to configure it ^,

Quoted 6 lines

may want to precisely control the maximum number of vcpus their precious VMs can use.

The actual control itself must be done via the TDH.MNG.INIT SEAMCALL itself, where the number of maximum cpus is an input to the TDX module, but KVM needs to support the "per-VM number of maximum vcpus" and reflect that in

per-VM maximum number of vcpus

Quoted 4 lines

the KVM_CAP_MAX_VCPUS.

Currently, the KVM x86 always reports KVM_MAX_VCPUS for all VMs but doesn't allow to enable KVM_CAP_MAX_VCPUS to configure the number of maximum vcpus

Quoted 7 lines

maximum number of vcpus

Quoted 5 lines

on VM-basis.

Add "per-VM maximum vcpus" to KVM x86/TDX to accommodate TDX's needs.

The userspace-configured value then can be verified when KVM is actually

used

Here, "verified", I think Kai wanted to emphasize that the value of max_vcpus passed in via KVM_TDX_INIT_VM should be checked against the value configured via KVM_CAP_MAX_VCPUS?

Maybe "verified and used" ?

Quoted 3 lines
Quoted 2 lines

creating the TDX guest.
"

#237 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 36 lines · Binbin Wu
Quoted 33 lines · Isaku Yamahata
Quoted 1 line · Kai

So how about:

Thanks for it. I'll update the commit message with some minor fixes.

Quoted 7 lines

"
TDX has its own mechanism to control the maximum number of VCPUs that the TDX guest can use. When creating a TDX guest, the maximum number of vcpus needs to be passed to the TDX module as part of the measurement of the guest.

Because the value is part of the measurement, thus part of attestation, it

                                                                            ^'s
Quoted 1 line

better to allow the userspace to be able to configure it. E.g. the users

the userspace to configure it ^,

Quoted 6 lines

may want to precisely control the maximum number of vcpus their precious VMs can use.

The actual control itself must be done via the TDH.MNG.INIT SEAMCALL itself, where the number of maximum cpus is an input to the TDX module, but KVM needs to support the "per-VM number of maximum vcpus" and reflect that in

per-VM maximum number of vcpus

Quoted 4 lines

the KVM_CAP_MAX_VCPUS.

Currently, the KVM x86 always reports KVM_MAX_VCPUS for all VMs but doesn't allow to enable KVM_CAP_MAX_VCPUS to configure the number of maximum vcpus

maximum number of vcpus

Quoted 5 lines

on VM-basis.

Add "per-VM maximum vcpus" to KVM x86/TDX to accommodate TDX's needs.

The userspace-configured value then can be verified when KVM is actually

Quoted 8 lines
Quoted 1 line

used

Here, "verified", I think Kai wanted to emphasize that the value of max_vcpus passed in via
KVM_TDX_INIT_VM should be checked against the value configured via KVM_CAP_MAX_VCPUS?

Maybe "verified and used" ?

Ok. I don't have strong opinion here.

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

RE: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 7 lines
Quoted 5 lines

Here, "verified", I think Kai wanted to emphasize that the value of max_vcpus passed in via KVM_TDX_INIT_VM should be checked against the value configured via KVM_CAP_MAX_VCPUS?

Maybe "verified and used" ?

Ok. I don't have strong opinion here.

It depends on how you implement that patch.

If we don't pass 'max_vcpus' in that patch, there's nothing to verify really.

#239 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

In reply to Isaku Yamahata
Quoted 12 lines
Quoted 3 lines

Currently, the KVM x86 always reports KVM_MAX_VCPUS for all VMs but doesn't allow to enable KVM_CAP_MAX_VCPUS to configure the number of maximum vcpus

maximum number of vcpus

Quoted 5 lines

on VM-basis.

Add "per-VM maximum vcpus" to KVM x86/TDX to accommodate TDX's needs.

The userspace-configured value then can be verified when KVM is actually

used

Quoted 2 lines

creating the TDX guest.
"

I think we still have two options regarding to how 'max_vcpus' is handled in ioctl() to do TDH.MNG.INIT:

1) Just use the 'max_vcpus' done in KVM_ENABLE_CAP(KVM_CAP_MAX_VCPUS),
2) Still pass the 'max_vcpus' as input, but KVM verifies it against the value that is saved in KVM_ENABLE_CAP(KVM_CAP_MAX_VCPUS).

2) seems unnecessary, so I don't have objection to use 1). But it seems we could still mention it in the changelog in that patch?

#240 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 16 lines · Kai
Quoted 12 lines
Quoted 3 lines

Currently, the KVM x86 always reports KVM_MAX_VCPUS for all VMs but doesn't allow to enable KVM_CAP_MAX_VCPUS to configure the number of maximum vcpus

maximum number of vcpus

Quoted 5 lines

on VM-basis.

Add "per-VM maximum vcpus" to KVM x86/TDX to accommodate TDX's needs.

The userspace-configured value then can be verified when KVM is actually

used

Quoted 2 lines

creating the TDX guest.
"

I think we still have two options regarding to how 'max_vcpus' is handled in ioctl() to do TDH.MNG.INIT:

Quoted 6 lines

1) Just use the 'max_vcpus' done in KVM_ENABLE_CAP(KVM_CAP_MAX_VCPUS),
2) Still pass the 'max_vcpus' as input, but KVM verifies it against the value that is saved in KVM_ENABLE_CAP(KVM_CAP_MAX_VCPUS).

2) seems unnecessary, so I don't have objection to use 1). But it seems we could still mention it in the changelog in that patch?

Sure, let me update the commit log.

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

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

In reply to [email protected]
Quoted 7 lines · On Mon, Feb 26, 2024, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX has its own limitation on the maximum number of vcpus that the guest can accommodate. Allow x86 kvm backend to implement its own KVM_ENABLE_CAP handler and implement TDX backend for KVM_CAP_MAX_VCPUS. user space VMM, e.g. qemu, can specify its value instead of KVM_MAX_VCPUS.

Quoted 5 lines

When creating TD (TDH.MNG.INIT), the maximum number of vcpu needs to be specified as struct td_params_struct. and the value is a part of measurement. The user space has to specify the value somehow. There are two options for it.
option 1. API (Set KVM_CAP_MAX_VCPU) to specify the value (this patch)

When I suggested adding a capability[*], the intent was for the capability to be generic, not buried in TDX code. I can't think of any reason why this can't be supported for all VMs on all architectures. The only wrinkle is that it'll require a separate capability since userspace needs to be able to detect that KVM supports restricting the number of vCPUs, but that'll still be _less_ code.

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

Review

Quoted 9 lines
(quoted diff) +9 -0
+static int vt_max_vcpus(struct kvm *kvm)
+{
+	if (!kvm)
+		return KVM_MAX_VCPUS;
+
+	if (is_td(kvm))
+		return min(kvm->max_vcpus, TDX_MAX_VCPUS);
+
+	return kvm->max_vcpus;

This is _completely_ orthogonal to allowing userspace to restrict the maximum number of vCPUs. And unless I'm missing something, it's also ridiculous and unnecessary at this time. KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

  #define TDX_MAX_VCPUS  (~(u16)0)

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

So rather than add a bunch of pointless plumbing, just throw in

arch/x86/kvm/vmx/tdx.c +3 -0
index 137d08da43c3..018d5b9eb93d 100644
@@ -2488,6 +2488,9 @@ static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
                return -EOPNOTSUPP;
        }
 
+       BUILD_BUG_ON(CONFIG_KVM_MAX_NR_VCPUS <
+                    sizeof(td_params->max_vcpus) * BITS_PER_BYTE);
+
        td_params->max_vcpus = kvm->max_vcpus;
        td_params->attributes = init_vm->attributes;
        /* td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD; */
#242 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 22 lines · Sean Christopherson
Quoted 7 lines · On Mon, Feb 26, 2024, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX has its own limitation on the maximum number of vcpus that the guest can accommodate. Allow x86 kvm backend to implement its own KVM_ENABLE_CAP handler and implement TDX backend for KVM_CAP_MAX_VCPUS. user space VMM, e.g. qemu, can specify its value instead of KVM_MAX_VCPUS.

Quoted 5 lines

When creating TD (TDH.MNG.INIT), the maximum number of vcpu needs to be specified as struct td_params_struct. and the value is a part of measurement. The user space has to specify the value somehow. There are two options for it.
option 1. API (Set KVM_CAP_MAX_VCPU) to specify the value (this patch)

When I suggested adding a capability[*], the intent was for the capability to be generic, not buried in TDX code. I can't think of any reason why this can't be supported for all VMs on all architectures. The only wrinkle is that it'll require a separate capability since userspace needs to be able to detect that KVM supports restricting the number of vCPUs, but that'll still be _less_ code.

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

Quoted 13 lines

Review

Quoted 9 lines
(quoted diff) +9 -0
+static int vt_max_vcpus(struct kvm *kvm)
+{
+	if (!kvm)
+		return KVM_MAX_VCPUS;
+
+	if (is_td(kvm))
+		return min(kvm->max_vcpus, TDX_MAX_VCPUS);
+
+	return kvm->max_vcpus;

This is _completely_ orthogonal to allowing userspace to restrict the maximum number of vCPUs. And unless I'm missing something, it's also ridiculous and unnecessary at this time.

Right it's not necessary. I think it can be reported as:

        case KVM_CAP_MAX_VCPUS:
                r = KVM_MAX_VCPUS;
+               if (kvm)
+                       r = kvm->max_vcpus;
                break;
Quoted 13 lines

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

Quoted 6 lines
   #define TDX_MAX_VCPUS  (~(u16)0)

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

Quoted 9 lines

So rather than add a bunch of pointless plumbing, just throw in

arch/x86/kvm/vmx/tdx.c +0 -0
index 137d08da43c3..018d5b9eb93d 100644

arch/x86/kvm/vmx/tdx.c static int setup_tdparams(struct kvm *kvm, struct td_params *td_params, · line 2496

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +3 -0
@@ -2488,6 +2488,9 @@ static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
                 return -EOPNOTSUPP;
         }
 
+       BUILD_BUG_ON(CONFIG_KVM_MAX_NR_VCPUS <
+                    sizeof(td_params->max_vcpus) * BITS_PER_BYTE);
+
         td_params->max_vcpus = kvm->max_vcpus;
         td_params->attributes = init_vm->attributes;
         /* td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD; */

Yeah the above could be helpful, but might not be necessary.

So the logic of updated patch is:

1) During module loading time, we grab the maximum vCPUs that the TDX module can support:

	/kvm_vm_ioctl_enable_cap
	 * TDX module may not support MD_FIELD_ID_MAX_VCPUS_PER_TD
	 * depending on its version.
	 */
	tdx_info->max_vcpus_per_td = U16_MAX;
	if (!tdx_sys_metadata_field_read(MD_FIELD_ID_MAX_VCPUS_PER_TD,
					&tmp))
	        tdx_info->max_vcpus_per_td = (u16)tmp;

2) When TDX guest is created, the userspace needs to call IOCTL(KVM_ENABLE_CAP) to configure the maximum vCPUs of the guest. A new kvm_x86_ops::vm_enable_cap() is added because TDX has it's own limitation (metadata field) as mentioned above.

@@ -6827,6 +6829,8 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,

        }
        default:
                r = -EINVAL;

+ if (kvm_x86_ops.vm_enable_cap)
+ r = static_call(kvm_x86_vm_enable_cap)(kvm,
+ cap);

And we only allow the kvm->max_vcpus to be updated if it's a TDX guest in the vt_vm_enable_cap(). The reason is we want to avoid unnecessary change for normal VMX guests.

And the new kvm->max_vcpus cannot exceed the KVM_MAX_VCPUS and the tdx_info->max_vcpus_per_td:

+ case KVM_CAP_MAX_VCPUS: {
+ if (cap->flags || cap->args[0] == 0)
+ return -EINVAL;
+ if (cap->args[0] > KVM_MAX_VCPUS ||
+ cap->args[0] > tdx_info->max_vcpus_per_td)
+ return -E2BIG;
+
+ mutex_lock(&kvm->lock);
+ if (kvm->created_vcpus)
+ r = -EBUSY;
+ else {
+ kvm->max_vcpus = cap->args[0];
+ r = 0;

+               }
+               mutex_unlock(&kvm->lock);
+               break;

+ }

3) We just report kvm->max_vcpus when the userspace wants to check the KVM_CAP_MAX_VCPUS as shown in the beginning of my reply.

Does this make sense to you?

I am also pasting the new updated patch for your review (there are line wrapper issues unfortunately due to the simple copy/paste):

From 797e439634d106f744517c97c5ea7887e494fc44 Mon Sep 17 00:00:00 2001
From: Isaku Yamahata <[email protected]>
Date: Thu, 16 Feb 2023 17:03:40 -0800
Subject: [PATCH] KVM: TDX: Allow userspace to configure maximum vCPUs for TDX guests

TDX has its own mechanism to control the maximum number of vCPUs that the TDX guest can use. When creating a TDX guest, the maximum number of vCPUs of the guest needs to be passed to the TDX module as part of the measurement of the guest. Depending on TDX module's version, it may also report the maximum vCPUs it can support for all TDX guests.

Because the maximum number of vCPUs is part of the measurement, thus part of attestation, it's better to allow the userspace to be able to configure it. E.g. the users may want to precisely control the maximum number of vCPUs their precious VMs can use.

The actual control itself must be done via the TDH.MNG.INIT SEAMCALL, where the number of maximum cpus is part of the input to the TDX module, but KVM needs to support the "per-VM maximum number of vCPUs" and reflect that in the KVM_CAP_MAX_VCPUS.

Currently, the KVM x86 always reports KVM_MAX_VCPUS for all VMs but doesn't allow to enable KVM_CAP_MAX_VCPUS to configure the number of maximum vCPUs on VM-basis.

Add "per-VM maximum number of vCPUs" to KVM x86/TDX to accommodate TDX's needs.

Specifically, use KVM's existing KVM_ENABLE_CAP IOCTL() to allow the userspace to configure the maximum vCPUs by making KVM x86 support enabling the KVM_CAP_MAX_VCPUS cap on VM-basis.

For that, add a new 'kvm_x86_ops::vm_enable_cap()' callback and call it from kvm_vm_ioctl_enable_cap() as a placeholder to handle the KVM_CAP_MAX_VCPUS for TDX guests (and other KVM_CAP_xx for TDX and/or other VMs if needed in the future).

Implement the callback for TDX guest to check whether the maximum vCPUs passed from usrspace can be supported by TDX, and if it can, override Accordingly, in the KVM_CHECK_EXTENSION IOCTL(), change to return the 'struct kvm::max_vcpus' for a given VM for the KVM_CAP_MAX_VCPUS.

---
v20:
- Drop max_vcpu ops to use kvm.max_vcpus
- Remove TDX_MAX_VCPUS (Kai)
- Use type cast (u16) instead of calling memcpy() when reading the 'max_vcpus_per_td' (Kai)
- Improve change log and change patch title from "KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific" (Kai)

---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  1 +
 arch/x86/kvm/vmx/main.c            | 10 ++++++++
 arch/x86/kvm/vmx/tdx.c             | 40 ++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h         |  5 ++++
 arch/x86/kvm/x86.c                 |  4 +++
 6 files changed, 61 insertions(+)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index bcb8302561f2..022b9eace3a5 100644
@@ -20,6 +20,7 @@ KVM_X86_OP(hardware_disable)
 KVM_X86_OP(hardware_unsetup)
 KVM_X86_OP(has_emulated_msr)
 KVM_X86_OP(vcpu_after_set_cpuid)
+KVM_X86_OP_OPTIONAL(vm_enable_cap)
 KVM_X86_OP(vm_init)
 KVM_X86_OP_OPTIONAL(vm_destroy)
 KVM_X86_OP_OPTIONAL_RET0(vcpu_precreate)
arch/x86/include/asm/kvm_host.h +1 -0
index c461c2e57fcb..1d10e3d29533 100644
@@ -1639,6 +1639,7 @@ struct kvm_x86_ops {
        void (*vcpu_after_set_cpuid)(struct kvm_vcpu *vcpu);
 
        unsigned int vm_size;
+       int (*vm_enable_cap)(struct kvm *kvm, struct kvm_enable_cap *cap);
        int (*vm_init)(struct kvm *kvm);
        void (*vm_destroy)(struct kvm *kvm);
 
arch/x86/kvm/vmx/main.c +9 -0
index 8e4aa8d15aec..686ca6348993 100644
@@ -6,6 +6,7 @@
 #include "nested.h"
 #include "pmu.h"
 #include "tdx.h"
+#include "tdx_arch.h"
 
 static bool enable_tdx __ro_after_init;
 module_param_named(tdx, enable_tdx, bool, 0444);
@@ -33,6 +34,14 @@ static void vt_hardware_unsetup(void)
        vmx_hardware_unsetup();
 }
 
+static int vt_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
+{
+       if (is_td(kvm))
+               return tdx_vm_enable_cap(kvm, cap);
+
+       return -EINVAL;
+}
+
 
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
        if (!is_td(kvm))

@@ -63,6 +72,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
.has_emulated_msr = vmx_has_emulated_msr,

.vm_size = sizeof(struct kvm_vmx),
+ .vm_enable_cap = vt_vm_enable_cap,
.vm_init = vmx_vm_init,
.vm_destroy = vmx_vm_destroy,

arch/x86/kvm/vmx/tdx.c +40 -0
index c7d849582d44..cdfc95904d6c 100644
@@ -34,6 +34,8 @@ struct tdx_info {
        u64 xfam_fixed0;
        u64 xfam_fixed1;
 
+       u16 max_vcpus_per_td;
+
        u16 num_cpuid_config;
        /* This must the last member. */
        DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
@@ -42,6 +44,35 @@ struct tdx_info {
 /* Info about the TDX module. */
 static struct tdx_info *tdx_info;
 
+int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
+{
+       int r;
+
+       switch (cap->cap) {
+       case KVM_CAP_MAX_VCPUS: {
+               if (cap->flags || cap->args[0] == 0)
+                       return -EINVAL;
+               if (cap->args[0] > KVM_MAX_VCPUS ||
+                   cap->args[0] > tdx_info->max_vcpus_per_td)
+                       return -E2BIG;
+
+               mutex_lock(&kvm->lock);
+               if (kvm->created_vcpus)
+                       r = -EBUSY;
+               else {
+                       kvm->max_vcpus = cap->args[0];
+                       r = 0;
+               }
+               mutex_unlock(&kvm->lock);
+               break;
+       }
+       default:
+               r = -EINVAL;
+               break;
+       }
+       return r;
+}
+
 static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
 {
        struct kvm_tdx_capabilities __user *user_caps;
@@ -129,6 +160,7 @@ static int __init tdx_module_setup(void)
                u16 num_cpuid_config;
                /* More member will come. */
        } st;
+       u64 tmp;
        int ret;
        u32 i;
 
@@ -167,6 +199,14 @@ static int __init tdx_module_setup(void)
                return -ENOMEM;
        tdx_info->num_cpuid_config = st.num_cpuid_config;
 
+       /*
+        * TDX module may not support MD_FIELD_ID_MAX_VCPUS_PER_TD depending
+        * on its version.
+        */
+       tdx_info->max_vcpus_per_td = U16_MAX;
+       if (!tdx_sys_metadata_field_read(MD_FIELD_ID_MAX_VCPUS_PER_TD, &tmp))
+               tdx_info->max_vcpus_per_td = (u16)tmp;
+
        ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
        ret = tdx_sys_metadata_read(fields, ARRAY_SIZE(fields), tdx_info);
        if (ret)
                goto error_out;
arch/x86/kvm/vmx/x86_ops.h +1 -0
index 9bc287a7efac..7c768e360bc6 100644
@@ -139,11 +139,16 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 void tdx_hardware_unsetup(void);
 
+int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap);
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { 

return -EOPNOTSUPP; }
static inline void tdx_hardware_unsetup(void) {}

+static inline int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) +{
+ return -EINVAL;
+};
static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) {
return -EOPNOTSUPP; }
#endif

arch/x86/kvm/x86.c +4 -0
index ee8288a46d30..97ed4fe25964 100644
@@ -4776,6 +4776,8 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
                break;
        case KVM_CAP_MAX_VCPUS:
                r = KVM_MAX_VCPUS;
+               if (kvm)
+                       r = kvm->max_vcpus;
                break;
        case KVM_CAP_MAX_VCPU_ID:
                r = KVM_MAX_VCPU_IDS;
@@ -6827,6 +6829,8 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
        }
        default:
                r = -EINVAL;
+               if (kvm_x86_ops.vm_enable_cap)
+                       r = static_call(kvm_x86_vm_enable_cap)(kvm, cap);
                break;
        }
        return r;

--
2.34.1

#243 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 6 lines

Implement the callback for TDX guest to check whether the maximum vCPUs passed from usrspace can be supported by TDX, and if it can, override Accordingly, in the KVM_CHECK_EXTENSION IOCTL(), change to return the 'struct kvm::max_vcpus' for a given VM for the KVM_CAP_MAX_VCPUS.

Sorry some error during copy/paste. The above should be:

Implement the callback for TDX guest to check whether the maximum vCPUs passed from usrspace can be supported by TDX, and if it can, override the 'struct kvm::max_vcpus'. Leave VMX guests and all AMD guests unsupported to avoid any side-effect for those VMs.

Accordingly, in the KVM_CHECK_EXTENSION IOCTL(), change to return the 'struct kvm::max_vcpus' for a given VM for the KVM_CAP_MAX_VCPUS.

#244 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

In reply to Huang, Kai
Quoted 16 lines · Kai Huang
Quoted 15 lines · Sean Christopherson

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

   #define TDX_MAX_VCPUS  (~(u16)0)
Quoted 8 lines
Quoted 4 lines

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

My quick glance at the 1.5 source shows that the limit is still effectively 0xffff, so again, who cares? Assert on 0xffff compile time, and on the reported max at runtime and simply refuse to use a TDX module that has dropped the minimum below 0xffff.

Quoted 3 lines

And we only allow the kvm->max_vcpus to be updated if it's a TDX guest in the vt_vm_enable_cap(). The reason is we want to avoid unnecessary change for normal VMX guests.

That's a frankly ridiculous reason to bury code in TDX. Nothing is _forcing_ userspace to set KVM_CAP_MAX_VCPUS, i.e. there won't be any change to VMX VMs unless userspace _wants_ there to be a change.

#245 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 22 lines · Sean Christopherson
Quoted 21 lines · Kai Huang
Quoted 19 lines · Sean Christopherson

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

    #define TDX_MAX_VCPUS  (~(u16)0)

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Quoted 8 lines
Quoted 3 lines

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

My quick glance at the 1.5 source shows that the limit is still effectively 0xffff, so again, who cares? Assert on 0xffff compile time, and on the reported max at runtime and simply refuse to use a TDX module that has dropped the minimum below 0xffff.

I need to double check why this metadata field was added. My concern is in future module versions they may just low down the value.

But another way to handle is we can adjust code when that truly happens? Might not be ideal for stable kernel situation, though?

Quoted 8 lines
Quoted 4 lines

And we only allow the kvm->max_vcpus to be updated if it's a TDX guest in the vt_vm_enable_cap(). The reason is we want to avoid unnecessary change for normal VMX guests.

That's a frankly ridiculous reason to bury code in TDX. Nothing is _forcing_ userspace to set KVM_CAP_MAX_VCPUS, i.e. there won't be any change to VMX VMs unless userspace _wants_ there to be a change.

Right. Anyway allowing userspace to set KVM_CAP_MAX_VCPUS for non-TDX guests shouldn't have any issue.

The main reason to bury code in TDX is it needs to additionally check tdx_info->max_vcpus_per_td. We can just do in common code if we avoid that TDX specific check.

#246 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 29 lines · Kai
Quoted 26 lines · Sean Christopherson
Quoted 24 lines · Kai Huang
Quoted 13 lines · Sean Christopherson

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

Quoted 6 lines
    #define TDX_MAX_VCPUS  (~(u16)0)

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

Quoted 7 lines
Quoted 4 lines

My quick glance at the 1.5 source shows that the limit is still effectively 0xffff, so again, who cares? Assert on 0xffff compile time, and on the reported max at runtime and simply refuse to use a TDX module that has dropped the minimum below 0xffff.

I need to double check why this metadata field was added. My concern is in future module versions they may just low down the value.

TD partitioning would reduce it much.

Quoted 11 lines

But another way to handle is we can adjust code when that truly happens? Might not be ideal for stable kernel situation, though?

Quoted 7 lines
Quoted 3 lines

And we only allow the kvm->max_vcpus to be updated if it's a TDX guest in the vt_vm_enable_cap(). The reason is we want to avoid unnecessary change for normal VMX guests.

That's a frankly ridiculous reason to bury code in TDX. Nothing is _forcing_ userspace to set KVM_CAP_MAX_VCPUS, i.e. there won't be any change to VMX VMs unless userspace _wants_ there to be a change.

Quoted 6 lines

Right. Anyway allowing userspace to set KVM_CAP_MAX_VCPUS for non-TDX guests shouldn't have any issue.

The main reason to bury code in TDX is it needs to additionally check tdx_info->max_vcpus_per_td. We can just do in common code if we avoid that TDX specific check.

So we can make it arch-independent.

When creating VM, we can set kvm->max_vcpu = tdx_info->max_vcpus_per_td by tdx_vm_init(). The check can be common like
"if (new max_vcpu > kvm->max_vcpu) error".

Or we can add kvm->hard_max_vcpu or something, arch-common code can have "if (kvm->hard_max_vcpu && new max_vcpu > kvm->hard_max_vcpu) error".

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

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 33 lines · Isaku Yamahata
Quoted 32 lines · Kai Huang
Quoted 30 lines · Sean Christopherson
Quoted 16 lines · Kai Huang
Quoted 15 lines · Sean Christopherson

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

    #define TDX_MAX_VCPUS  (~(u16)0)
Quoted 8 lines
Quoted 4 lines

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

My quick glance at the 1.5 source shows that the limit is still effectively 0xffff, so again, who cares? Assert on 0xffff compile time, and on the reported max at runtime and simply refuse to use a TDX module that has dropped the minimum below 0xffff.

Quoted 4 lines
Quoted 2 lines

I need to double check why this metadata field was added. My concern is in future module versions they may just low down the value.

TD partitioning would reduce it much.

That's still not a reason to plumb in what is effectively dead code. Either partitioning is opt-in, at which I suspect KVM will need yet more uAPI to express the limitations to userspace, or the TDX-module is potentially breaking existing use cases.

#248 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 37 lines · Sean Christopherson
Quoted 36 lines · Isaku Yamahata
Quoted 34 lines · Kai Huang
Quoted 22 lines · Sean Christopherson
Quoted 21 lines · Kai Huang
Quoted 19 lines · Sean Christopherson

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

     #define TDX_MAX_VCPUS  (~(u16)0)

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Quoted 8 lines
Quoted 3 lines

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

My quick glance at the 1.5 source shows that the limit is still effectively 0xffff, so again, who cares? Assert on 0xffff compile time, and on the reported max at runtime and simply refuse to use a TDX module that has dropped the minimum below 0xffff.

I need to double check why this metadata field was added. My concern is in future module versions they may just low down the value.

Quoted 6 lines
Quoted 1 line

TD partitioning would reduce it much.

That's still not a reason to plumb in what is effectively dead code. Either partitioning is opt-in, at which I suspect KVM will need yet more uAPI to express the limitations to userspace, or the TDX-module is potentially breaking existing use cases.

The 'max_vcpus_per_td' global metadata fields is static for the TDX module. If the module supports the TD partitioning, it just reports some smaller value regardless whether we opt-in TDX partitioning or not.

I think the point is this 'max_vcpus_per_td' is TDX architectural thing and kernel should not make any assumption of the value of it. The architectural behaviour is:

If the module has this 'max_vcpus_per_td', software should read and use it; Otherwise software should treat it as U16_MAX.

Thus I don't think we will need a new uAPI (TDX specific presumably) just for TD partitioning. And this doesn't break existing use cases.

In fact, this doesn't prevent us from making the KVM_CAP_MAX_VCPUS code generic, e.g., we can do below:

1) In tdx_vm_init() (called via KVM_VM_CREATE -> vt_vm_init()), we do:

	kvm->max_vcpus = min(kvm->max_vcpus,
				tdx_info->max_vcpus_per_td);

2) In kvm_vm_ioctl_enable_cap_generic(), we add support to handle KVM_CAP_MAX_VCPUS to have the generic code to do:

	if (new_max_vcpus > kvm->max_vcpus)
		return -EINVAL;

	kvm->max_vcpus = new_max_vcpus;

However this means we only allow "lowing down" the kvm->max_vcpus in the kvm_vm_ioctl_enable_cap_generic(KVM_CAP_MAX_VCPUS), but I think this is acceptable?

If it is a concern, alternatively, we can add a new 'kvm->hard_max_vcpus' (or whatever makes sense), and set it in kvm_create_vm() right after kvm_arch_init_vm():

	r = kvm_arch_init_vm(kvm, type);
        if (r)
                goto out_err_no_arch_destroy_vm;

	kvm->hard_max_vcpus = kvm->max_vcpus;

So it always contains "the max_vcpus limited by the ARCH hardware/firmware etc".

And in kvm_vm_ioctl_enable_cap_generic(), we check against kvm->hard_max_vcpus instead to get rid of the limitation of only allowing lowing down the kvm->max_vcpus.

But I don't think this is necessary at this stage.

#249 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 47 lines · Kai Huang
Quoted 37 lines · Sean Christopherson
Quoted 36 lines · Isaku Yamahata
Quoted 34 lines · Kai Huang
Quoted 22 lines · Sean Christopherson
Quoted 21 lines · Kai Huang
Quoted 19 lines · Sean Christopherson

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

     #define TDX_MAX_VCPUS  (~(u16)0)

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Quoted 8 lines
Quoted 3 lines

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

My quick glance at the 1.5 source shows that the limit is still effectively 0xffff, so again, who cares? Assert on 0xffff compile time, and on the reported max at runtime and simply refuse to use a TDX module that has dropped the minimum below 0xffff.

I need to double check why this metadata field was added. My concern is in future module versions they may just low down the value.

Quoted 6 lines
Quoted 1 line

TD partitioning would reduce it much.

That's still not a reason to plumb in what is effectively dead code. Either partitioning is opt-in, at which I suspect KVM will need yet more uAPI to express the limitations to userspace, or the TDX-module is potentially breaking existing use cases.

Quoted 6 lines

The 'max_vcpus_per_td' global metadata fields is static for the TDX module. If the module supports the TD partitioning, it just reports some smaller value regardless whether we opt-in TDX partitioning or not.

I think the point is this 'max_vcpus_per_td' is TDX architectural thing and kernel should not make any assumption of the value of it.

It's not an assumption, it's a requirement. And KVM already places requirements on "hardware", e.g. kvm-intel.ko will refuse to load if the CPU doesn't support a bare mimimum VMX feature set. Refusing to enable TDX because max_vcpus_per_td is unexpectedly low isn't fundamentally different than refusing to enable VMX because IRQ window exiting is unsupported.

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

#250 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 52 lines · Sean Christopherson
Quoted 51 lines · Kai Huang
Quoted 37 lines · Sean Christopherson
Quoted 36 lines · Isaku Yamahata
Quoted 34 lines · Kai Huang
Quoted 22 lines · Sean Christopherson
Quoted 21 lines · Kai Huang
Quoted 19 lines · Sean Christopherson

KVM x86 limits KVM_MAX_VCPUS to 4096:

config KVM_MAX_NR_VCPUS
int "Maximum number of vCPUs per KVM guest" depends on KVM
range 1024 4096
default 4096 if MAXSMP
default 1024
help

whereas the limitation from TDX is apprarently simply due to TD_PARAMS taking a 16-bit unsigned value:

     #define TDX_MAX_VCPUS  (~(u16)0)

i.e. it will likely be _years_ before TDX's limitation matters, if it ever does. And _if_ it becomes a problem, we don't necessarily need to have a different _runtime_ limit for TDX, e.g. TDX support could be conditioned on KVM_MAX_NR_VCPUS being <= 64k.

Quoted 8 lines
Quoted 3 lines

Actually later versions of TDX module (starting from 1.5 AFAICT), the module has a metadata field to report the maximum vCPUs that the module can support for all TDX guests.

My quick glance at the 1.5 source shows that the limit is still effectively 0xffff, so again, who cares? Assert on 0xffff compile time, and on the reported max at runtime and simply refuse to use a TDX module that has dropped the minimum below 0xffff.

I need to double check why this metadata field was added. My concern is in future module versions they may just low down the value.

Quoted 6 lines
Quoted 1 line

TD partitioning would reduce it much.

That's still not a reason to plumb in what is effectively dead code. Either partitioning is opt-in, at which I suspect KVM will need yet more uAPI to express the limitations to userspace, or the TDX-module is potentially breaking existing use cases.

The 'max_vcpus_per_td' global metadata fields is static for the TDX module. If the module supports the TD partitioning, it just reports some smaller value regardless whether we opt-in TDX partitioning or not.

Quoted 8 lines
Quoted 2 lines

I think the point is this 'max_vcpus_per_td' is TDX architectural thing and kernel should not make any assumption of the value of it.

It's not an assumption, it's a requirement. And KVM already places requirements on "hardware", e.g. kvm-intel.ko will refuse to load if the CPU doesn't support a bare mimimum VMX feature set. Refusing to enable TDX because max_vcpus_per_td is unexpectedly low isn't fundamentally different than refusing to enable VMX because IRQ window exiting is unsupported.

OK. I have no argument against this.

But I am not sure why we need to have such requirement. See below.

Quoted 4 lines

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

I am afraid we already have a legitimate case: TD partitioning. Isaku told me the 'max_vcpus_per_td' is lowed to 512 for the modules with TD partitioning supported. And again this is static, i.e., doesn't require TD partitioning to be opt-in to low to 512.

So AFAICT this isn't a theoretical thing now.

Also, I want to say I was wrong about "MAX_VCPUS" in the TD_PARAMS is part of attestation. It is not. TDREPORT dosen't include the "MAX_VCPUS", and it is not involved in the calculation of the measurement of the guest.

Given "MAX_VCPUS" is not part of attestation, I think there's no need to allow user to change kvm->max_vcpus by enabling KVM_ENABLE_CAP ioctl() for KVM_CAP_MAX_VCPUS.

So we could just once for all adjust kvm->max_vcpus for TDX in the tdx_vm_init() for TDX guest:

	kvm->max_vcpus = min(kvm->max_vcpus, tdx_info->max_vcpus_per_td);

AFAICT no other change is needed.

And in KVM_TDX_VM_INIT (where TDH.MNG.INIT is done) we can just use kvm-

Quoted 1 line

max_vcpus to fill the "MAX_VCPUS" in TD_PARAMS.

#251 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 9 lines · Kai Huang
Quoted 3 lines · Sean Christopherson

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

I am afraid we already have a legitimate case: TD partitioning. Isaku told me the 'max_vcpus_per_td' is lowed to 512 for the modules with TD partitioning supported. And again this is static, i.e., doesn't require TD partitioning to be opt-in to low to 512.

So what's Intel's plan for use cases that creates TDs with >512 vCPUs?

Quoted 9 lines

So AFAICT this isn't a theoretical thing now.

Also, I want to say I was wrong about "MAX_VCPUS" in the TD_PARAMS is part of attestation. It is not. TDREPORT dosen't include the "MAX_VCPUS", and it is not involved in the calculation of the measurement of the guest.

Given "MAX_VCPUS" is not part of attestation, I think there's no need to allow user to change kvm->max_vcpus by enabling KVM_ENABLE_CAP ioctl() for KVM_CAP_MAX_VCPUS.

Sure, but KVM would still need to advertise the reduced value for KVM_CAP_MAX_VCPUS when queried via KVM_CHECK_EXTENSION. And userspace needs to be conditioned to do a VM-scoped check, not a system-scoped check.

Quoted 9 lines

So we could just once for all adjust kvm->max_vcpus for TDX in the tdx_vm_init() for TDX guest:

	kvm->max_vcpus = min(kvm->max_vcpus, tdx_info->max_vcpus_per_td);

AFAICT no other change is needed.

And in KVM_TDX_VM_INIT (where TDH.MNG.INIT is done) we can just use kvm-

Quoted 1 line

max_vcpus to fill the "MAX_VCPUS" in TD_PARAMS.

#252 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Kai Huang
Quoted 3 lines · Sean Christopherson

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

Quoted 6 lines
Quoted 4 lines

I am afraid we already have a legitimate case: TD partitioning. Isaku told me the 'max_vcpus_per_td' is lowed to 512 for the modules with TD partitioning supported. And again this is static, i.e., doesn't require TD partitioning to be opt-in to low to 512.

So what's Intel's plan for use cases that creates TDs with >512 vCPUs?

I don't think we have such use cases. Let me double check with TDX module guys.

Quoted 7 lines
Quoted 7 lines

So AFAICT this isn't a theoretical thing now.

Also, I want to say I was wrong about "MAX_VCPUS" in the TD_PARAMS is part of attestation. It is not. TDREPORT dosen't include the "MAX_VCPUS", and it is not involved in the calculation of the measurement of the guest.

Quoted 7 lines
Quoted 3 lines

Given "MAX_VCPUS" is not part of attestation, I think there's no need to allow user to change kvm->max_vcpus by enabling KVM_ENABLE_CAP ioctl() for KVM_CAP_MAX_VCPUS.

Sure, but KVM would still need to advertise the reduced value for KVM_CAP_MAX_VCPUS when queried via KVM_CHECK_EXTENSION. And userspace needs to be conditioned to do a VM-scoped check, not a system-scoped check.

Oh yes.

#253 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

In reply to Sean Christopherson
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Kai Huang
Quoted 3 lines · Sean Christopherson

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

Quoted 6 lines
Quoted 4 lines

I am afraid we already have a legitimate case: TD partitioning. Isaku told me the 'max_vcpus_per_td' is lowed to 512 for the modules with TD partitioning supported. And again this is static, i.e., doesn't require TD partitioning to be opt-in to low to 512.

So what's Intel's plan for use cases that creates TDs with >512 vCPUs?

I checked with TDX module guys. Turns out the 'max_vcpus_per_td' wasn't introduced because of TD partitioning, and they are not actually related.

They introduced this to support "topology virtualization", which requires a table to record the X2APIC IDs for all vcpus for each TD. In practice, given a TDX module, the 'max_vcpus_per_td', a.k.a, the X2APIC ID table size reflects the physical logical cpus that *ALL* platforms that the module supports can possibly have.

The reason of this design is TDX guys don't believe there's sense in supporting the case where the 'max_vcpus' for one single TD needs to exceed the physical logical cpus.

So in short:

- The "max_vcpus_per_td" can be different depending on module versions. In practice it reflects the maximum physical logical cpus that all the platforms (that the module supports) can possibly have.

- Before CSPs deploy/migrate TD on a TDX machine, they must be aware of the "max_vcpus_per_td" the module supports, and only deploy/migrate TD to it when it can support.

- For TDX 1.5.xx modules, the value is 576 (the previous number 512 isn't correct); For TDX 2.0.xx modules, the value is larger (>1000). For future module versions, it could have a smaller number, depending on what platforms that module needs to support. Also, if TDX ever gets supported on client platforms, we can image the number could be much smaller due to the "vcpus per td no need to exceed physical logical cpus".

We may ask them to support the case where 'max_vcpus' for single TD exceeds the physical logical cpus, or at least not to low down the value any further for future modules (> 2.0.xx modules). We may also ask them to give promise to not low the number to below some certain value for any future modules. But I am not sure there's any concrete reason to do so?

What's your thinking?

#254 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 44 lines · Kai
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Kai Huang
Quoted 3 lines · Sean Christopherson

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

Quoted 6 lines
Quoted 4 lines

I am afraid we already have a legitimate case: TD partitioning. Isaku told me the 'max_vcpus_per_td' is lowed to 512 for the modules with TD partitioning supported. And again this is static, i.e., doesn't require TD partitioning to be opt-in to low to 512.

So what's Intel's plan for use cases that creates TDs with >512 vCPUs?

I checked with TDX module guys. Turns out the 'max_vcpus_per_td' wasn't introduced because of TD partitioning, and they are not actually related.

They introduced this to support "topology virtualization", which requires a table to record the X2APIC IDs for all vcpus for each TD. In practice, given a TDX module, the 'max_vcpus_per_td', a.k.a, the X2APIC ID table size reflects the physical logical cpus that *ALL* platforms that the module supports can possibly have.

The reason of this design is TDX guys don't believe there's sense in supporting the case where the 'max_vcpus' for one single TD needs to exceed the physical logical cpus.

So in short:

- The "max_vcpus_per_td" can be different depending on module versions. In practice it reflects the maximum physical logical cpus that all the platforms (that the module supports) can possibly have.

- Before CSPs deploy/migrate TD on a TDX machine, they must be aware of the "max_vcpus_per_td" the module supports, and only deploy/migrate TD to it when it can support.

- For TDX 1.5.xx modules, the value is 576 (the previous number 512 isn't correct); For TDX 2.0.xx modules, the value is larger (>1000). For future module versions, it could have a smaller number, depending on what platforms that module needs to support. Also, if TDX ever gets supported on client platforms, we can image the number could be much smaller due to the "vcpus per td no need to exceed physical logical cpus".

Quoted 8 lines

We may ask them to support the case where 'max_vcpus' for single TD exceeds the physical logical cpus, or at least not to low down the value any further for future modules (> 2.0.xx modules). We may also ask them to give promise to not low the number to below some certain value for any future modules. But I am not sure there's any concrete reason to do so?

What's your thinking?

Hi Sean,

Sorry to ping, but do you have any comments on this?

Is there anything we should make TDX module guys do?

#255 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 45 lines · Kai Huang
Quoted 44 lines · Kai
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Kai Huang
Quoted 3 lines · Sean Christopherson

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

Quoted 6 lines
Quoted 4 lines

I am afraid we already have a legitimate case: TD partitioning. Isaku told me the 'max_vcpus_per_td' is lowed to 512 for the modules with TD partitioning supported. And again this is static, i.e., doesn't require TD partitioning to be opt-in to low to 512.

So what's Intel's plan for use cases that creates TDs with >512 vCPUs?

I checked with TDX module guys. Turns out the 'max_vcpus_per_td' wasn't introduced because of TD partitioning, and they are not actually related.

They introduced this to support "topology virtualization", which requires a table to record the X2APIC IDs for all vcpus for each TD. In practice, given a TDX module, the 'max_vcpus_per_td', a.k.a, the X2APIC ID table size reflects the physical logical cpus that *ALL* platforms that the module supports can possibly have.

The reason of this design is TDX guys don't believe there's sense in supporting the case where the 'max_vcpus' for one single TD needs to exceed the physical logical cpus.

So in short:

- The "max_vcpus_per_td" can be different depending on module versions. In practice it reflects the maximum physical logical cpus that all the platforms (that the module supports) can possibly have.

- Before CSPs deploy/migrate TD on a TDX machine, they must be aware of the "max_vcpus_per_td" the module supports, and only deploy/migrate TD to it when it can support.

- For TDX 1.5.xx modules, the value is 576 (the previous number 512 isn't correct); For TDX 2.0.xx modules, the value is larger (>1000). For future module versions, it could have a smaller number, depending on what platforms that module needs to support. Also, if TDX ever gets supported on client platforms, we can image the number could be much smaller due to the "vcpus per td no need to exceed physical logical cpus".

Quoted 7 lines
Quoted 7 lines

We may ask them to support the case where 'max_vcpus' for single TD exceeds the physical logical cpus, or at least not to low down the value any further for future modules (> 2.0.xx modules). We may also ask them to give promise to not low the number to below some certain value for any future modules. But I am not sure there's any concrete reason to do so?

What's your thinking?

It's a reasonable restriction, e.g. KVM_CAP_NR_VCPUS is already capped at number of online CPUs, although userspace is obviously allowed to create oversubscribed VMs.

I think the sane thing to do is document that TDX VMs are restricted to the number of logical CPUs in the system, have KVM_CAP_MAX_VCPUS enumerate exactly that, and then sanity check that max_vcpus_per_td is greater than or equal to what KVM reports for KVM_CAP_MAX_VCPUS.

Stating that the maximum number of vCPUs depends on the whims TDX module doesn't provide a predictable ABI for KVM, i.e. I don't want to simply forward TDX's max_vcpus_per_td to userspace.

#256 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 58 lines · Sean Christopherson
Quoted 45 lines · Kai Huang
Quoted 44 lines · Kai
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Kai Huang
Quoted 3 lines · Sean Christopherson

In the unlikely event there is a legitimate reason for max_vcpus_per_td being less than KVM's minimum, then we can update KVM's minimum as needed. But AFAICT, that's purely theoretical at this point, i.e. this is all much ado about nothing.

Quoted 6 lines
Quoted 4 lines

I am afraid we already have a legitimate case: TD partitioning. Isaku told me the 'max_vcpus_per_td' is lowed to 512 for the modules with TD partitioning supported. And again this is static, i.e., doesn't require TD partitioning to be opt-in to low to 512.

So what's Intel's plan for use cases that creates TDs with >512 vCPUs?

I checked with TDX module guys. Turns out the 'max_vcpus_per_td' wasn't introduced because of TD partitioning, and they are not actually related.

They introduced this to support "topology virtualization", which requires a table to record the X2APIC IDs for all vcpus for each TD. In practice, given a TDX module, the 'max_vcpus_per_td', a.k.a, the X2APIC ID table size reflects the physical logical cpus that *ALL* platforms that the module supports can possibly have.

The reason of this design is TDX guys don't believe there's sense in supporting the case where the 'max_vcpus' for one single TD needs to exceed the physical logical cpus.

So in short:

- The "max_vcpus_per_td" can be different depending on module versions. In practice it reflects the maximum physical logical cpus that all the platforms (that the module supports) can possibly have.

- Before CSPs deploy/migrate TD on a TDX machine, they must be aware of the "max_vcpus_per_td" the module supports, and only deploy/migrate TD to it when it can support.

- For TDX 1.5.xx modules, the value is 576 (the previous number 512 isn't correct); For TDX 2.0.xx modules, the value is larger (>1000). For future module versions, it could have a smaller number, depending on what platforms that module needs to support. Also, if TDX ever gets supported on client platforms, we can image the number could be much smaller due to the "vcpus per td no need to exceed physical logical cpus".

Quoted 7 lines
Quoted 7 lines

We may ask them to support the case where 'max_vcpus' for single TD exceeds the physical logical cpus, or at least not to low down the value any further for future modules (> 2.0.xx modules). We may also ask them to give promise to not low the number to below some certain value for any future modules. But I am not sure there's any concrete reason to do so?

What's your thinking?

It's a reasonable restriction, e.g. KVM_CAP_NR_VCPUS is already capped at number of online CPUs, although userspace is obviously allowed to create oversubscribed VMs.

Quoted 7 lines

I think the sane thing to do is document that TDX VMs are restricted to the number of logical CPUs in the system, have KVM_CAP_MAX_VCPUS enumerate exactly that, and then sanity check that max_vcpus_per_td is greater than or equal to what KVM reports for KVM_CAP_MAX_VCPUS. >
Stating that the maximum number of vCPUs depends on the whims TDX module doesn't provide a predictable ABI for KVM, i.e. I don't want to simply forward TDX's max_vcpus_per_td to userspace.

This sounds good to me. I think it should be also OK for client too, if TDX ever gets supported for client.

IIUC we can consult the @nr_cpu_ids or num_possible_cpus() to get the "number of logical CPUs in the system". And we can reject to use the TDX module if 'max_vcpus_per_td' turns to be smaller.

I think the relevant question is is whether we should still report "number of logical CPUs in the system" via KVM_CAP_MAX_VCPUS? Because if doing so, this still means the userspace will need to check KVM_CAP_MAX_VCPUS vm extention on per-vm basis.

And if it does, then from userspace's perspective, it actually doesn't matter whether underneath the per-vm KVM_CAP_MAX_VCPUS is limited by TDX or the system cpus (also see below).

The userspace cannot tell the difference anyway. It just needs to change to query KVM_CAP_MAX_VCPUS to per-vm basis.

Or, we could limit this to TDX guest ONLY:

The KVM_CAP_MAX_VCPUS is still global. However for TDX specifically, the userspace should use other way to query the number of LPs the system supports (I assume there should be existing ABI for this?).

But looks this isn't something nice?

#257 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 18 lines · Kai Huang
Quoted 9 lines · Sean Christopherson
Quoted 3 lines · Kai Huang
Quoted 3 lines

- The "max_vcpus_per_td" can be different depending on module versions. In practice it reflects the maximum physical logical cpus that all the platforms (that the module supports) can possibly have.

It's a reasonable restriction, e.g. KVM_CAP_NR_VCPUS is already capped at number of online CPUs, although userspace is obviously allowed to create oversubscribed VMs.

Quoted 7 lines

I think the sane thing to do is document that TDX VMs are restricted to the number of logical CPUs in the system, have KVM_CAP_MAX_VCPUS enumerate exactly that, and then sanity check that max_vcpus_per_td is greater than or equal to what KVM reports for KVM_CAP_MAX_VCPUS. >
Stating that the maximum number of vCPUs depends on the whims TDX module doesn't provide a predictable ABI for KVM, i.e. I don't want to simply forward TDX's max_vcpus_per_td to userspace.

Quoted 6 lines

This sounds good to me. I think it should be also OK for client too, if TDX ever gets supported for client.

IIUC we can consult the @nr_cpu_ids or num_possible_cpus() to get the "number of logical CPUs in the system". And we can reject to use the TDX module if 'max_vcpus_per_td' turns to be smaller.

I assume TDX is incompatible with actual physical CPU hotplug? If so, we can and should use num_present_cpus(). If loading the TDX module completely disables onlining CPUs, then we can use num_online_cpus().

Quoted 4 lines

I think the relevant question is is whether we should still report "number of logical CPUs in the system" via KVM_CAP_MAX_VCPUS? Because if doing so, this still means the userspace will need to check KVM_CAP_MAX_VCPUS vm extention on per-vm basis.

Yes.

Quoted 3 lines

And if it does, then from userspace's perspective, it actually doesn't matter whether underneath the per-vm KVM_CAP_MAX_VCPUS is limited by TDX or the system cpus (also see below).

It matters because I don't want KVM's ABI to be tied to the whims of the TDX module. Today, there's no limitations on the max number of vCPUs. Tomorrow, it's limited by the number of pCPUs. Three days from now, I don't want to find out that the TDX module is limiting the number of vCPUs based on some other new criteria.

Quoted 10 lines

The userspace cannot tell the difference anyway. It just needs to change to query KVM_CAP_MAX_VCPUS to per-vm basis.

Or, we could limit this to TDX guest ONLY:

The KVM_CAP_MAX_VCPUS is still global. However for TDX specifically, the userspace should use other way to query the number of LPs the system supports (I assume there should be existing ABI for this?).

But looks this isn't something nice?

What's wrong with querying KVM_CAP_MAX_VCPUS on the VM file descriptor?

#258 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 19 lines · Sean Christopherson
Quoted 18 lines · Kai Huang
Quoted 16 lines · Sean Christopherson
Quoted 3 lines · Kai Huang
Quoted 3 lines

- The "max_vcpus_per_td" can be different depending on module versions. In practice it reflects the maximum physical logical cpus that all the platforms (that the module supports) can possibly have.

It's a reasonable restriction, e.g. KVM_CAP_NR_VCPUS is already capped at number of online CPUs, although userspace is obviously allowed to create oversubscribed VMs.

I think the sane thing to do is document that TDX VMs are restricted to the number of logical CPUs in the system, have KVM_CAP_MAX_VCPUS enumerate exactly that, and then sanity check that max_vcpus_per_td is greater than or equal to what KVM reports for KVM_CAP_MAX_VCPUS. >
Stating that the maximum number of vCPUs depends on the whims TDX module doesn't provide a predictable ABI for KVM, i.e. I don't want to simply forward TDX's max_vcpus_per_td to userspace.

Quoted 9 lines
Quoted 6 lines

This sounds good to me. I think it should be also OK for client too, if TDX ever gets supported for client.

IIUC we can consult the @nr_cpu_ids or num_possible_cpus() to get the "number of logical CPUs in the system". And we can reject to use the TDX module if 'max_vcpus_per_td' turns to be smaller.

I assume TDX is incompatible with actual physical CPU hotplug?

Correct.

Quoted 3 lines

If so, we can and
should use num_present_cpus().

On TDX platform num_present_cpus() and num_possible_cpus() should be just identical, because TDX requires BIOS to mark all all physical LPs the platform as enabled, and TDX doesn't support physical CPU hotplug.

Using num_present_cpus() w/o holding CPU hotplug lock is a little bit annoying from code's perspective, but it's OK to me. We can add a comment saying TDX doesn't support physical CPU hotplug.

Quoted 10 lines

If loading the TDX module completely disables
onlining CPUs, then we can use num_online_cpus().

Quoted 4 lines

I think the relevant question is is whether we should still report "number of logical CPUs in the system" via KVM_CAP_MAX_VCPUS? Because if doing so, this still means the userspace will need to check KVM_CAP_MAX_VCPUS vm extention on per-vm basis.

Yes.

Quoted 8 lines
Quoted 3 lines

And if it does, then from userspace's perspective, it actually doesn't matter whether underneath the per-vm KVM_CAP_MAX_VCPUS is limited by TDX or the system cpus (also see below).

It matters because I don't want KVM's ABI to be tied to the whims of the TDX module. Today, there's no limitations on the max number of vCPUs. Tomorrow, it's limited by the number of pCPUs. Three days from now, I don't want to find out that the TDX module is limiting the number of vCPUs based on some other new criteria.

Yeah understood.

Quoted 6 lines
Quoted 6 lines

The userspace cannot tell the difference anyway. It just needs to change to query KVM_CAP_MAX_VCPUS to per-vm basis.

Or, we could limit this to TDX guest ONLY:

Quoted 7 lines
Quoted 5 lines

The KVM_CAP_MAX_VCPUS is still global. However for TDX specifically, the userspace should use other way to query the number of LPs the system supports (I assume there should be existing ABI for this?).

But looks this isn't something nice?

What's wrong with querying KVM_CAP_MAX_VCPUS on the VM file descriptor?

Nothing wrong.

I just wanted to point out if we require userspace to do so, from userspace's perspective it cannot tell how the number is limited underneath by KVM.

Will go with this route. Thanks!

#259 lore raw

Re: [PATCH v19 037/130] KVM: TDX: Make KVM_CAP_MAX_VCPUS backend specific

Quoted 36 lines · Kai
Quoted 19 lines · Sean Christopherson
Quoted 18 lines · Kai Huang
Quoted 16 lines · Sean Christopherson
Quoted 3 lines · Kai Huang
Quoted 3 lines

- The "max_vcpus_per_td" can be different depending on module versions. In practice it reflects the maximum physical logical cpus that all the platforms (that the module supports) can possibly have.

It's a reasonable restriction, e.g. KVM_CAP_NR_VCPUS is already capped at number of online CPUs, although userspace is obviously allowed to create oversubscribed VMs.

I think the sane thing to do is document that TDX VMs are restricted to the number of logical CPUs in the system, have KVM_CAP_MAX_VCPUS enumerate exactly that, and then sanity check that max_vcpus_per_td is greater than or equal to what KVM reports for KVM_CAP_MAX_VCPUS. >
Stating that the maximum number of vCPUs depends on the whims TDX module doesn't provide a predictable ABI for KVM, i.e. I don't want to simply forward TDX's max_vcpus_per_td to userspace.

Quoted 9 lines
Quoted 6 lines

This sounds good to me. I think it should be also OK for client too, if TDX ever gets supported for client.

IIUC we can consult the @nr_cpu_ids or num_possible_cpus() to get the "number of logical CPUs in the system". And we can reject to use the TDX module if 'max_vcpus_per_td' turns to be smaller.

I assume TDX is incompatible with actual physical CPU hotplug?

Correct.

Quoted 3 lines

If so, we can and
should use num_present_cpus().

Quoted 10 lines

On TDX platform num_present_cpus() and num_possible_cpus() should be just identical, because TDX requires BIOS to mark all all physical LPs the platform as enabled, and TDX doesn't support physical CPU hotplug.

Using num_present_cpus() w/o holding CPU hotplug lock is a little bit annoying from code's perspective, but it's OK to me. We can add a comment saying TDX doesn't support physical CPU hotplug.

Quoted 2 lines

If loading the TDX module completely disables
onlining CPUs, then we can use num_online_cpus().

Missed this one.

No loading/initializing TDX module doesn't disable onlining CPUs. TDX module can be initialized on a subset of physical logical CPUs. Also, after module initialization, logical CPU can be put to offline and then brought back to online again.

#260 lore raw

PATCH v19 38/130 KVM: TDX: create/destroy VM structure

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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

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

Add vm_free() of kvm_x86_ops hook at the end of kvm_arch_destroy_vm() because some per-VM TDX resources, e.g. TDR, need to be freed after other TDX resources, e.g. HKID, were freed.

---
v19:
- fix check error code of TDH.PHYMEM.PAGE.RECLAIM. RCX and TDR.

v18:
- Use TDH.SYS.RD() instead of struct tdsysinfo_struct.
- Rename tdx_reclaim_td_page() to tdx_reclaim_control_page()
- return -EAGAIN on TDX_RND_NO_ENTROPY of TDH.MNG.CREATE(), TDH.MNG.ADDCX()
- fix comment to remove extra the.
- use true instead of 1 for boolean.
- remove an extra white line.

v16:
- Simplified tdx_reclaim_page()
- Reorganize the locking of tdx_release_hkid(), and use smp_call_mask() instead of smp_call_on_cpu() to hold spinlock to race with invalidation on releasing guest memfd

---
 arch/x86/include/asm/kvm-x86-ops.h |   2 +
 arch/x86/include/asm/kvm_host.h    |   2 +
 arch/x86/kvm/Kconfig               |   3 +-
 arch/x86/kvm/mmu/mmu.c             |   7 +
 arch/x86/kvm/vmx/main.c            |  26 +-
 arch/x86/kvm/vmx/tdx.c             | 475 ++++++++++++++++++++++++++++-
 arch/x86/kvm/vmx/tdx.h             |   6 +-
 arch/x86/kvm/vmx/x86_ops.h         |   6 +
 arch/x86/kvm/x86.c                 |   1 +
 9 files changed, 520 insertions(+), 8 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 1b0dacc6b6c0..97f0a681e02c 100644
@@ -24,7 +24,9 @@ KVM_X86_OP(is_vm_type_supported)
 KVM_X86_OP_OPTIONAL(max_vcpus);
 KVM_X86_OP_OPTIONAL(vm_enable_cap)
 KVM_X86_OP(vm_init)
+KVM_X86_OP_OPTIONAL(flush_shadow_all_private)
 KVM_X86_OP_OPTIONAL(vm_destroy)
+KVM_X86_OP_OPTIONAL(vm_free)
 KVM_X86_OP_OPTIONAL_RET0(vcpu_precreate)
 KVM_X86_OP(vcpu_create)
 KVM_X86_OP(vcpu_free)
arch/x86/include/asm/kvm_host.h +2 -0
index cf8eb46b3a20..6dedb5cb71ef 100644
@@ -1608,7 +1608,9 @@ struct kvm_x86_ops {
 	unsigned int vm_size;
 	int (*vm_enable_cap)(struct kvm *kvm, struct kvm_enable_cap *cap);
 	int (*vm_init)(struct kvm *kvm);
+	void (*flush_shadow_all_private)(struct kvm *kvm);
 	void (*vm_destroy)(struct kvm *kvm);
+	void (*vm_free)(struct kvm *kvm);
 
 	/* Create, but do not attach this VCPU */
 	int (*vcpu_precreate)(struct kvm *kvm);
arch/x86/kvm/Kconfig +2 -1
index 87e3da7b0439..bc077d6f4b43 100644
@@ -76,7 +76,6 @@ config KVM_WERROR
 
 config KVM_SW_PROTECTED_VM
 	bool "Enable support for KVM software-protected VMs"
-	depends on EXPERT
 	depends on KVM && X86_64
 	select KVM_GENERIC_PRIVATE_MEM
 	help
@@ -89,6 +88,8 @@ config KVM_SW_PROTECTED_VM
 config KVM_INTEL
 	tristate "KVM for Intel (and compatible) processors support"
 	depends on KVM && IA32_FEAT_CTL
+	select KVM_SW_PROTECTED_VM if INTEL_TDX_HOST
+	select KVM_GENERIC_MEMORY_ATTRIBUTES if INTEL_TDX_HOST
 	help
 	  Provides support for KVM on processors equipped with Intel's VT
 	  extensions, a.k.a. Virtual Machine Extensions (VMX).
arch/x86/kvm/mmu/mmu.c +7 -0
index c45252ed2ffd..2becc86c71b2 100644
@@ -6866,6 +6866,13 @@ static void kvm_mmu_zap_all(struct kvm *kvm)
 
 void kvm_arch_flush_shadow_all(struct kvm *kvm)
 {
+	/*
+	 * kvm_mmu_zap_all() zaps both private and shared page tables.  Before
+	 * tearing down private page tables, TDX requires some TD resources to
+	 * be destroyed (i.e. keyID must have been reclaimed, etc).  Invoke
+	 * kvm_x86_flush_shadow_all_private() for this.
+	 */
+	static_call_cond(kvm_x86_flush_shadow_all_private)(kvm);
 	kvm_mmu_zap_all(kvm);
 }
 
arch/x86/kvm/vmx/main.c +24 -2
index e8a1a7533eea..437c6d5e802e 100644
@@ -62,11 +62,31 @@ static int vt_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
 static int vt_vm_init(struct kvm *kvm)
 {
 	if (is_td(kvm))
-		return -EOPNOTSUPP;	/* Not ready to create guest TD yet. */
+		return tdx_vm_init(kvm);
 
 	return vmx_vm_init(kvm);
 }
 
+static void vt_flush_shadow_all_private(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		tdx_mmu_release_hkid(kvm);
+}
+
+static void vt_vm_destroy(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return;
+
+	vmx_vm_destroy(kvm);
+}
+
+static void vt_vm_free(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		tdx_vm_free(kvm);
+}
+
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	if (!is_td(kvm))
@@ -101,7 +121,9 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.vm_size = sizeof(struct kvm_vmx),
 	.vm_enable_cap = vt_vm_enable_cap,
 	.vm_init = vt_vm_init,
-	.vm_destroy = vmx_vm_destroy,
+	.flush_shadow_all_private = vt_flush_shadow_all_private,
+	.vm_destroy = vt_vm_destroy,
+	.vm_free = vt_vm_free,
 
 	.vcpu_precreate = vmx_vcpu_precreate,
 	.vcpu_create = vmx_vcpu_create,
arch/x86/kvm/vmx/tdx.c +471 -4

548 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.h +5 -1
index 22c0b57f69ca..ae117f864cfb 100644
@@ -8,7 +8,11 @@
 
 struct kvm_tdx {
 	struct kvm kvm;
-	/* TDX specific members follow. */
+
+	unsigned long tdr_pa;
+	unsigned long *tdcs_pa;
+
+	int hkid;
 };
 
 struct vcpu_tdx {
arch/x86/kvm/vmx/x86_ops.h +6 -0
index 0031a8d61589..7f123ffe4d42 100644
@@ -140,6 +140,9 @@ void tdx_hardware_unsetup(void);
 bool tdx_is_vm_type_supported(unsigned long type);
 
 int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap);
+int tdx_vm_init(struct kvm *kvm);
+void tdx_mmu_release_hkid(struct kvm *kvm);
+void tdx_vm_free(struct kvm *kvm);
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
@@ -150,6 +153,9 @@ static inline int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
 {
 	return -EINVAL;
 };
+static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
+static inline void tdx_mmu_release_hkid(struct kvm *kvm) {}
+static inline void tdx_vm_free(struct kvm *kvm) {}
 static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOPNOTSUPP; }
 #endif
 
arch/x86/kvm/x86.c +1 -0
index 3f16e9450d2f..1f01c7f91652 100644
@@ -12743,6 +12743,7 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_page_track_cleanup(kvm);
 	kvm_xen_destroy_vm(kvm);
 	kvm_hv_destroy_vm(kvm);
+	static_call_cond(kvm_x86_vm_free)(kvm);
 }
 
 static void memslot_rmap_free(struct kvm_memory_slot *slot)
Signature · 1 line
2.25.1
#261 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

arch/x86/kvm/Kconfig config KVM_SW_PROTECTED_VM · line 91

Quoted 11 lines

config KVM_SW_PROTECTED_VM
bool "Enable support for KVM software-protected VMs"

arch/x86/kvm/Kconfig +0 -1
-	depends on EXPERT
	depends on KVM && X86_64
	select KVM_GENERIC_PRIVATE_MEM
	help
(quoted diff) +0 -0
@@ -89,6 +88,8 @@ config KVM_SW_PROTECTED_VM

config KVM_INTEL

	tristate "KVM for Intel (and compatible) processors support"
	depends on KVM && IA32_FEAT_CTL
arch/x86/kvm/Kconfig +1 -0
+	select KVM_SW_PROTECTED_VM if INTEL_TDX_HOST

why does INTEL_TDX_HOST select KVM_SW_PROTECTED_VM?

Quoted 8 lines
arch/x86/kvm/Kconfig +1 -0
+	select KVM_GENERIC_MEMORY_ATTRIBUTES if INTEL_TDX_HOST

help
.vcpu_precreate = vmx_vcpu_precreate,
.vcpu_create = vmx_vcpu_create,

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

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +2 -1
@@ -5,10 +5,11 @@
 
 #include "capabilities.h"
 #include "x86_ops.h"
-#include "x86.h"
 #include "mmu.h"
 #include "tdx_arch.h"
 #include "tdx.h"
+#include "tdx_ops.h"
+#include "x86.h"

any reason to reorder x86.h?

Quoted 54 lines
arch/x86/kvm/vmx/tdx.c +54 -0
+static void tdx_do_tdh_phymem_cache_wb(void *unused)
+{
+	u64 err = 0;
+
+	do {
+		err = tdh_phymem_cache_wb(!!err);
+	} while (err == TDX_INTERRUPTED_RESUMABLE);
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;
+	if (WARN_ON_ONCE(err))
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+}
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}
+
+	packages_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+	targets_allocated = zalloc_cpumask_var(&targets, GFP_KERNEL);
+	cpus_read_lock();
+
+	/*
+	 * We can destroy multiple guest TDs simultaneously.  Prevent
+	 * tdh_phymem_cache_wb from returning TDX_BUSY by serialization.
+	 */
+	mutex_lock(&tdx_lock);
+
+	/*
+	 * Go through multiple TDX HKID state transitions with three SEAMCALLs
+	 * to make TDH.PHYMEM.PAGE.RECLAIM() usable.  Make the transition atomic
+	 * to other functions to operate private pages and Secure-EPT pages.
+	 *
+	 * Avoid race for kvm_gmem_release() to call kvm_mmu_unmap_gfn_range().
+	 * This function is called via mmu notifier, mmu_release().
+	 * kvm_gmem_release() is called via fput() on process exit.
+	 */
+	write_lock(&kvm->mmu_lock);
+
+	for_each_online_cpu(i) {
+		if (packages_allocated &&

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 266

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		    cpumask_test_and_set_cpu(topology_physical_package_id(i),
+					     packages))
+			continue;
+		if (targets_allocated)
+			cpumask_set_cpu(i, targets);
+	}
+	if (targets_allocated)
+		on_each_cpu_mask(targets, tdx_do_tdh_phymem_cache_wb, NULL, true);
+	else
+		on_each_cpu(tdx_do_tdh_phymem_cache_wb, NULL, true);

This tries flush cache on all CPUs when we run out of memory. I am not sure if it is the best solution. A simple solution is just use two global bitmaps.

And current logic isn't optimal. e.g., if packages_allocated is true while targets_allocated is false, then we will fill in the packages bitmap but don't use it at all.

That said, I prefer to optimize the rare case in a separate patch. We can just use two global bitmaps or let the flush fail here just as you are doing below on seamcall failure.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 277

Quoted 11 lines
arch/x86/kvm/vmx/tdx.c +11 -0
+	/*
+	 * In the case of error in tdx_do_tdh_phymem_cache_wb(), the following
+	 * tdh_mng_key_freeid() will fail.
+	 */
+	err = tdh_mng_key_freeid(kvm_tdx->tdr_pa);
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_FREEID, err, NULL);
+		pr_err("tdh_mng_key_freeid() failed. HKID %d is leaked.\n",
+		       kvm_tdx->hkid);
+	} else
+		tdx_hkid_free(kvm_tdx);

curly brackets are missing.

Quoted 95 lines
arch/x86/kvm/vmx/tdx.c +94 -0
+
+	write_unlock(&kvm->mmu_lock);
+	mutex_unlock(&tdx_lock);
+	cpus_read_unlock();
+	free_cpumask_var(targets);
+	free_cpumask_var(packages);
+}
+
 
+static int __tdx_td_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	unsigned long *tdcs_pa = NULL;
+	unsigned long tdr_pa = 0;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	ret = tdx_guest_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;
+
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		goto free_hkid;
+	tdr_pa = __pa(va);
+
+	tdcs_pa = kcalloc(tdx_info->nr_tdcs_pages, sizeof(*kvm_tdx->tdcs_pa),
+			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	if (!tdcs_pa)
+		goto free_tdr;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va)
+			goto free_tdcs;
+		tdcs_pa[i] = __pa(va);
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in order to
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i), packages);
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i), packages);
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure out the
+		 * reason, warn it.
+		 */
+#define MSG_ALLPKG	"All packages need to have online CPU to create TD. Online CPU and retry.\n"
+		pr_warn_ratelimited(MSG_ALLPKG);
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+	 * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+	 * caller to handle the contention.  This is because of time limitation
+	 * usable inside the TDX module and OS/VMM knows better about process
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+	 * TDH.PHYMEM.CACHE.WB.
+	 */
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(tdr_pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);
+	if (err == TDX_RND_NO_ENTROPY) {
+		ret = -EAGAIN;
+		goto free_packages;
+	}
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_packages;
+	}
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 514

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Quoted 60 lines
arch/x86/kvm/vmx/tdx.c +60 -0
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr_pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+	if (ret) {
+		i = 0;
+		goto teardown;
+	}
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.
+	 */
+teardown:
+	for (; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i]) {
+			free_page((unsigned long)__va(tdcs_pa[i]));
+			tdcs_pa[i] = 0;
+		}
+	}
+	if (!kvm_tdx->tdcs_pa)
+		kfree(tdcs_pa);
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i])
+			free_page((unsigned long)__va(tdcs_pa[i]));

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 584

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	}
+	kfree(tdcs_pa);
+	kvm_tdx->tdcs_pa = NULL;
+
+free_tdr:
+	if (tdr_pa)
+		free_page((unsigned long)__va(tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+free_hkid:
+	if (is_hkid_assigned(kvm_tdx))

IIUC, this is always true because you just return if keyid allocation fails.

	>+	ret = tdx_guest_keyid_alloc();
	>+	if (ret < 0)
	>+		return ret;
	>+	kvm_tdx->hkid = ret;
	>+
	>+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
	>+	if (!va)
	>+		goto free_hkid;
Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+		tdx_hkid_free(kvm_tdx);
+	return ret;
+}
#262 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 5 lines · Chao Gao
Quoted 5 lines

config KVM_SW_PROTECTED_VM
bool "Enable support for KVM software-protected VMs"

arch/x86/kvm/Kconfig +0 -1
-	depends on EXPERT
	depends on KVM && X86_64
	select KVM_GENERIC_PRIVATE_MEM
Quoted 8 lines

arch/x86/kvm/Kconfig config KVM_SW_PROTECTED_VM · line 91

Quoted 6 lines

help

(quoted diff) +0 -0
@@ -89,6 +88,8 @@ config KVM_SW_PROTECTED_VM

config KVM_INTEL

	tristate "KVM for Intel (and compatible) processors support"
	depends on KVM && IA32_FEAT_CTL
arch/x86/kvm/Kconfig +1 -0
+	select KVM_SW_PROTECTED_VM if INTEL_TDX_HOST

why does INTEL_TDX_HOST select KVM_SW_PROTECTED_VM?

I wanted KVM_GENERIC_PRIVATE_MEM. Ah, we should do

select KKVM_GENERIC_PRIVATE_MEM if INTEL_TDX_HOST

Quoted 9 lines
Quoted 9 lines
arch/x86/kvm/Kconfig +1 -0
+	select KVM_GENERIC_MEMORY_ATTRIBUTES if INTEL_TDX_HOST

help
.vcpu_precreate = vmx_vcpu_precreate,
.vcpu_create = vmx_vcpu_create,

arch/x86/kvm/vmx/tdx.c +0 -0
@@ -5,10 +5,11 @@
 
Quoted 10 lines

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +2 -1
 #include "capabilities.h"
 #include "x86_ops.h"
-#include "x86.h"
 #include "mmu.h"
 #include "tdx_arch.h"
 #include "tdx.h"
+#include "tdx_ops.h"
+#include "x86.h"

any reason to reorder x86.h?

No, I think it's accidental during rebase.
Will fix.

Quoted 68 lines
Quoted 54 lines
arch/x86/kvm/vmx/tdx.c +54 -0
+static void tdx_do_tdh_phymem_cache_wb(void *unused)
+{
+	u64 err = 0;
+
+	do {
+		err = tdh_phymem_cache_wb(!!err);
+	} while (err == TDX_INTERRUPTED_RESUMABLE);
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;
+	if (WARN_ON_ONCE(err))
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+}
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}
+
+	packages_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+	targets_allocated = zalloc_cpumask_var(&targets, GFP_KERNEL);
+	cpus_read_lock();
+
+	/*
+	 * We can destroy multiple guest TDs simultaneously.  Prevent
+	 * tdh_phymem_cache_wb from returning TDX_BUSY by serialization.
+	 */
+	mutex_lock(&tdx_lock);
+
+	/*
+	 * Go through multiple TDX HKID state transitions with three SEAMCALLs
+	 * to make TDH.PHYMEM.PAGE.RECLAIM() usable.  Make the transition atomic
+	 * to other functions to operate private pages and Secure-EPT pages.
+	 *
+	 * Avoid race for kvm_gmem_release() to call kvm_mmu_unmap_gfn_range().
+	 * This function is called via mmu notifier, mmu_release().
+	 * kvm_gmem_release() is called via fput() on process exit.
+	 */
+	write_lock(&kvm->mmu_lock);
+
+	for_each_online_cpu(i) {
+		if (packages_allocated &&

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 266

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		    cpumask_test_and_set_cpu(topology_physical_package_id(i),
+					     packages))
+			continue;
+		if (targets_allocated)
+			cpumask_set_cpu(i, targets);
+	}
+	if (targets_allocated)
+		on_each_cpu_mask(targets, tdx_do_tdh_phymem_cache_wb, NULL, true);
+	else
+		on_each_cpu(tdx_do_tdh_phymem_cache_wb, NULL, true);

This tries flush cache on all CPUs when we run out of memory. I am not sure if it is the best solution. A simple solution is just use two global bitmaps.

Quoted 7 lines

And current logic isn't optimal. e.g., if packages_allocated is true while targets_allocated is false, then we will fill in the packages bitmap but don't use it at all.

That said, I prefer to optimize the rare case in a separate patch. We can just use two global bitmaps or let the flush fail here just as you are doing below on seamcall failure.

Makes sense. We can allocate cpumasks on hardware_setup/unsetup() and update them on hardware_enable/disable().

...

Quoted 94 lines
Quoted 94 lines
arch/x86/kvm/vmx/tdx.c +94 -0
+static int __tdx_td_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	unsigned long *tdcs_pa = NULL;
+	unsigned long tdr_pa = 0;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	ret = tdx_guest_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;
+
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		goto free_hkid;
+	tdr_pa = __pa(va);
+
+	tdcs_pa = kcalloc(tdx_info->nr_tdcs_pages, sizeof(*kvm_tdx->tdcs_pa),
+			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	if (!tdcs_pa)
+		goto free_tdr;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va)
+			goto free_tdcs;
+		tdcs_pa[i] = __pa(va);
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in order to
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i), packages);
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i), packages);
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure out the
+		 * reason, warn it.
+		 */
+#define MSG_ALLPKG	"All packages need to have online CPU to create TD. Online CPU and retry.\n"
+		pr_warn_ratelimited(MSG_ALLPKG);
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+	 * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+	 * caller to handle the contention.  This is because of time limitation
+	 * usable inside the TDX module and OS/VMM knows better about process
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+	 * TDH.PHYMEM.CACHE.WB.
+	 */
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(tdr_pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);
+	if (err == TDX_RND_NO_ENTROPY) {
+		ret = -EAGAIN;
+		goto free_packages;
+	}
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_packages;
+	}
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Makes sense. Will drop the lock.

Quoted 65 lines
Quoted 65 lines
arch/x86/kvm/vmx/tdx.c +65 -0
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr_pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+	if (ret) {
+		i = 0;
+		goto teardown;
+	}
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.
+	 */
+teardown:
+	for (; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i]) {
+			free_page((unsigned long)__va(tdcs_pa[i]));
+			tdcs_pa[i] = 0;
+		}
+	}
+	if (!kvm_tdx->tdcs_pa)
+		kfree(tdcs_pa);
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i])
+			free_page((unsigned long)__va(tdcs_pa[i]));
+	}
+	kfree(tdcs_pa);
+	kvm_tdx->tdcs_pa = NULL;
+
+free_tdr:
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 584

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	if (tdr_pa)
+		free_page((unsigned long)__va(tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+free_hkid:
+	if (is_hkid_assigned(kvm_tdx))

IIUC, this is always true because you just return if keyid allocation fails.

You're right. Will fix

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 231 lines · Isaku Yamahata
Quoted 5 lines · Chao Gao
Quoted 5 lines

config KVM_SW_PROTECTED_VM
bool "Enable support for KVM software-protected VMs"

arch/x86/kvm/Kconfig +0 -1
-	depends on EXPERT
	depends on KVM && X86_64
	select KVM_GENERIC_PRIVATE_MEM
Quoted 8 lines

arch/x86/kvm/Kconfig config KVM_SW_PROTECTED_VM · line 91

Quoted 6 lines

help

(quoted diff) +0 -0
@@ -89,6 +88,8 @@ config KVM_SW_PROTECTED_VM

config KVM_INTEL

	tristate "KVM for Intel (and compatible) processors support"
	depends on KVM && IA32_FEAT_CTL
arch/x86/kvm/Kconfig +1 -0
+	select KVM_SW_PROTECTED_VM if INTEL_TDX_HOST

why does INTEL_TDX_HOST select KVM_SW_PROTECTED_VM?

I wanted KVM_GENERIC_PRIVATE_MEM. Ah, we should do

select KKVM_GENERIC_PRIVATE_MEM if INTEL_TDX_HOST

Quoted 9 lines
Quoted 9 lines
arch/x86/kvm/Kconfig +1 -0
+	select KVM_GENERIC_MEMORY_ATTRIBUTES if INTEL_TDX_HOST

help
.vcpu_precreate = vmx_vcpu_precreate,
.vcpu_create = vmx_vcpu_create,

arch/x86/kvm/vmx/tdx.c +0 -0
@@ -5,10 +5,11 @@
 
Quoted 10 lines

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +2 -1
 #include "capabilities.h"
 #include "x86_ops.h"
-#include "x86.h"
 #include "mmu.h"
 #include "tdx_arch.h"
 #include "tdx.h"
+#include "tdx_ops.h"
+#include "x86.h"

any reason to reorder x86.h?

No, I think it's accidental during rebase.
Will fix.

Quoted 68 lines
Quoted 54 lines
arch/x86/kvm/vmx/tdx.c +54 -0
+static void tdx_do_tdh_phymem_cache_wb(void *unused)
+{
+	u64 err = 0;
+
+	do {
+		err = tdh_phymem_cache_wb(!!err);
+	} while (err == TDX_INTERRUPTED_RESUMABLE);
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;
+	if (WARN_ON_ONCE(err))
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+}
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}
+
+	packages_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+	targets_allocated = zalloc_cpumask_var(&targets, GFP_KERNEL);
+	cpus_read_lock();
+
+	/*
+	 * We can destroy multiple guest TDs simultaneously.  Prevent
+	 * tdh_phymem_cache_wb from returning TDX_BUSY by serialization.
+	 */
+	mutex_lock(&tdx_lock);
+
+	/*
+	 * Go through multiple TDX HKID state transitions with three SEAMCALLs
+	 * to make TDH.PHYMEM.PAGE.RECLAIM() usable.  Make the transition atomic
+	 * to other functions to operate private pages and Secure-EPT pages.
+	 *
+	 * Avoid race for kvm_gmem_release() to call kvm_mmu_unmap_gfn_range().
+	 * This function is called via mmu notifier, mmu_release().
+	 * kvm_gmem_release() is called via fput() on process exit.
+	 */
+	write_lock(&kvm->mmu_lock);
+
+	for_each_online_cpu(i) {
+		if (packages_allocated &&

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 266

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		    cpumask_test_and_set_cpu(topology_physical_package_id(i),
+					     packages))
+			continue;
+		if (targets_allocated)
+			cpumask_set_cpu(i, targets);
+	}
+	if (targets_allocated)
+		on_each_cpu_mask(targets, tdx_do_tdh_phymem_cache_wb, NULL, true);
+	else
+		on_each_cpu(tdx_do_tdh_phymem_cache_wb, NULL, true);

This tries flush cache on all CPUs when we run out of memory. I am not sure if it is the best solution. A simple solution is just use two global bitmaps.

Quoted 7 lines

And current logic isn't optimal. e.g., if packages_allocated is true while targets_allocated is false, then we will fill in the packages bitmap but don't use it at all.

That said, I prefer to optimize the rare case in a separate patch. We can just use two global bitmaps or let the flush fail here just as you are doing below on seamcall failure.

Makes sense. We can allocate cpumasks on hardware_setup/unsetup() and update them on hardware_enable/disable().

...

Quoted 94 lines
Quoted 94 lines
arch/x86/kvm/vmx/tdx.c +94 -0
+static int __tdx_td_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	unsigned long *tdcs_pa = NULL;
+	unsigned long tdr_pa = 0;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	ret = tdx_guest_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;
+
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		goto free_hkid;
+	tdr_pa = __pa(va);
+
+	tdcs_pa = kcalloc(tdx_info->nr_tdcs_pages, sizeof(*kvm_tdx->tdcs_pa),
+			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	if (!tdcs_pa)
+		goto free_tdr;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va)
+			goto free_tdcs;
+		tdcs_pa[i] = __pa(va);
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in order to
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i), packages);
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i), packages);
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure out the
+		 * reason, warn it.
+		 */
+#define MSG_ALLPKG	"All packages need to have online CPU to create TD. Online CPU and retry.\n"
+		pr_warn_ratelimited(MSG_ALLPKG);
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+	 * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+	 * caller to handle the contention.  This is because of time limitation
+	 * usable inside the TDX module and OS/VMM knows better about process
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+	 * TDH.PHYMEM.CACHE.WB.
+	 */
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(tdr_pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);
+	if (err == TDX_RND_NO_ENTROPY) {
+		ret = -EAGAIN;
+		goto free_packages;
+	}
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_packages;
+	}
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Quoted 1 line

Makes sense. Will drop the lock.

Not get the point, the variable "packages" on stack, and it's possible that "i" is same for 2 threads which are trying to create td. Anything I missed ?

Quoted 80 lines
Quoted 67 lines
Quoted 67 lines
arch/x86/kvm/vmx/tdx.c +65 -0
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr_pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+	if (ret) {
+		i = 0;
+		goto teardown;
+	}
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.
+	 */
+teardown:
+	for (; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i]) {
+			free_page((unsigned long)__va(tdcs_pa[i]));
+			tdcs_pa[i] = 0;
+		}
+	}
+	if (!kvm_tdx->tdcs_pa)
+		kfree(tdcs_pa);
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i])
+			free_page((unsigned long)__va(tdcs_pa[i]));
+	}
+	kfree(tdcs_pa);
+	kvm_tdx->tdcs_pa = NULL;
+
+free_tdr:
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 584

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	if (tdr_pa)
+		free_page((unsigned long)__va(tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+free_hkid:
+	if (is_hkid_assigned(kvm_tdx))

IIUC, this is always true because you just return if keyid allocation fails.

You're right. Will fix
--
Isaku Yamahata <[email protected]>

#264 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 3 lines · Yuan Yao
Quoted 2 lines · Isaku Yamahata

On Wed, Mar 20, 2024 at 01:12:01PM +0800,
Chao Gao <[email protected]> wrote:

...

Quoted 103 lines
Quoted 103 lines
Quoted 102 lines
Quoted 86 lines
arch/x86/kvm/vmx/tdx.c +86 -0
+static int __tdx_td_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	unsigned long *tdcs_pa = NULL;
+	unsigned long tdr_pa = 0;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	ret = tdx_guest_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;
+
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		goto free_hkid;
+	tdr_pa = __pa(va);
+
+	tdcs_pa = kcalloc(tdx_info->nr_tdcs_pages, sizeof(*kvm_tdx->tdcs_pa),
+			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	if (!tdcs_pa)
+		goto free_tdr;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va)
+			goto free_tdcs;
+		tdcs_pa[i] = __pa(va);
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in order to
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i), packages);
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i), packages);
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure out the
+		 * reason, warn it.
+		 */
+#define MSG_ALLPKG	"All packages need to have online CPU to create TD. Online CPU and retry.\n"
+		pr_warn_ratelimited(MSG_ALLPKG);
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+	 * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+	 * caller to handle the contention.  This is because of time limitation
+	 * usable inside the TDX module and OS/VMM knows better about process
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+	 * TDH.PHYMEM.CACHE.WB.
+	 */
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(tdr_pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);
+	if (err == TDX_RND_NO_ENTROPY) {
+		ret = -EAGAIN;
+		goto free_packages;
+	}
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_packages;
+	}
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 514

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Quoted 5 lines
Quoted 1 line

Makes sense. Will drop the lock.

Not get the point, the variable "packages" on stack, and it's possible that "i" is same for 2 threads which are trying to create td. Anything I missed ?

Got the point after synced with chao.
in case of using for_each_online_cpu() it's safe to remove the mutex_lock(&tdx_mng_key_config_lock[pkg]), since every thread will select only 1 cpu for each sockets in same order, and requests submited to same cpu by smp_call_on_cpu() are ordered on the target cpu. That means removing the lock works for using for_each_online_cpu() but does NOT work for randomly pick up a cpu per socket.

Maybe it's just my issue that doesn't realize what's going on here, but I think it still worth to give comment here for why it works/does not work.

Quoted 82 lines
Quoted 81 lines
Quoted 68 lines
Quoted 68 lines
arch/x86/kvm/vmx/tdx.c +65 -0
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr_pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+	if (ret) {
+		i = 0;
+		goto teardown;
+	}
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.
+	 */
+teardown:
+	for (; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i]) {
+			free_page((unsigned long)__va(tdcs_pa[i]));
+			tdcs_pa[i] = 0;
+		}
+	}
+	if (!kvm_tdx->tdcs_pa)
+		kfree(tdcs_pa);
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i])
+			free_page((unsigned long)__va(tdcs_pa[i]));
+	}
+	kfree(tdcs_pa);
+	kvm_tdx->tdcs_pa = NULL;
+
+free_tdr:
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 584

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	if (tdr_pa)
+		free_page((unsigned long)__va(tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+free_hkid:
+	if (is_hkid_assigned(kvm_tdx))

IIUC, this is always true because you just return if keyid allocation fails.

You're right. Will fix
--
Isaku Yamahata <[email protected]>

#265 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 114 lines · Yuan Yao
Quoted 3 lines · Yuan Yao
Quoted 2 lines · Isaku Yamahata

On Wed, Mar 20, 2024 at 01:12:01PM +0800,
Chao Gao <[email protected]> wrote:

...

Quoted 103 lines
Quoted 103 lines
Quoted 102 lines
Quoted 86 lines
arch/x86/kvm/vmx/tdx.c +86 -0
+static int __tdx_td_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	unsigned long *tdcs_pa = NULL;
+	unsigned long tdr_pa = 0;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	ret = tdx_guest_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;
+
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		goto free_hkid;
+	tdr_pa = __pa(va);
+
+	tdcs_pa = kcalloc(tdx_info->nr_tdcs_pages, sizeof(*kvm_tdx->tdcs_pa),
+			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	if (!tdcs_pa)
+		goto free_tdr;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va)
+			goto free_tdcs;
+		tdcs_pa[i] = __pa(va);
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in order to
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i), packages);
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i), packages);
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure out the
+		 * reason, warn it.
+		 */
+#define MSG_ALLPKG	"All packages need to have online CPU to create TD. Online CPU and retry.\n"
+		pr_warn_ratelimited(MSG_ALLPKG);
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+	 * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+	 * caller to handle the contention.  This is because of time limitation
+	 * usable inside the TDX module and OS/VMM knows better about process
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+	 * TDH.PHYMEM.CACHE.WB.
+	 */
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(tdr_pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);
+	if (err == TDX_RND_NO_ENTROPY) {
+		ret = -EAGAIN;
+		goto free_packages;
+	}
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_packages;
+	}
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 514

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Quoted 5 lines
Quoted 1 line

Makes sense. Will drop the lock.

Not get the point, the variable "packages" on stack, and it's possible that "i" is same for 2 threads which are trying to create td. Anything I missed ?

Quoted 8 lines

Got the point after synced with chao.
in case of using for_each_online_cpu() it's safe to remove the mutex_lock(&tdx_mng_key_config_lock[pkg]), since every thread will select only 1 cpu for each sockets in same order, and requests submited to same cpu by smp_call_on_cpu() are ordered on the target cpu. That means removing the lock works for using for_each_online_cpu() but does NOT work for randomly pick up a cpu per socket.

Maybe it's just my issue that doesn't realize what's going on here, but I think it still worth to give comment here for why it works/does not work.

It's deserves comment. Will add it.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to Isaku Yamahata
Quoted 6 lines · Isaku Yamahata
Quoted 3 lines · Chao Gao

arch/x86/kvm/Kconfig config KVM_WERROR · line 79

Quoted 3 lines

config KVM_SW_PROTECTED_VM
bool "Enable support for KVM software-protected VMs"

arch/x86/kvm/Kconfig +0 -1
-	depends on EXPERT

This change is not needed, right?
Since you intended to use KVM_GENERIC_PRIVATE_MEM, not KVM_SW_PROTECTED_VM.

Quoted 19 lines
Quoted 9 lines

arch/x86/kvm/Kconfig config KVM_SW_PROTECTED_VM · line 91

Quoted 8 lines
	depends on KVM && X86_64
	select KVM_GENERIC_PRIVATE_MEM
	help
(quoted diff) +0 -0
@@ -89,6 +88,8 @@ config KVM_SW_PROTECTED_VM

config KVM_INTEL

	tristate "KVM for Intel (and compatible) processors support"
	depends on KVM && IA32_FEAT_CTL
arch/x86/kvm/Kconfig +1 -0
+	select KVM_SW_PROTECTED_VM if INTEL_TDX_HOST

why does INTEL_TDX_HOST select KVM_SW_PROTECTED_VM?

I wanted KVM_GENERIC_PRIVATE_MEM. Ah, we should do

select KKVM_GENERIC_PRIVATE_MEM if INTEL_TDX_HOST

Quoted 5 lines
Quoted 4 lines
arch/x86/kvm/Kconfig +1 -0
+	select KVM_GENERIC_MEMORY_ATTRIBUTES if INTEL_TDX_HOST

help
.vcpu_precreate = vmx_vcpu_precreate,
.vcpu_create = vmx_vcpu_create,

[...]

#267 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 6 lines · Binbin Wu
Quoted 3 lines · Isaku Yamahata

On Wed, Mar 20, 2024 at 01:12:01PM +0800,
Chao Gao <[email protected]> wrote:

Quoted 6 lines
Quoted 3 lines
Quoted 3 lines

Review

Quoted 3 lines

config KVM_SW_PROTECTED_VM
bool "Enable support for KVM software-protected VMs"

(quoted diff) +0 -1
-	depends on EXPERT

This change is not needed, right?
Since you intended to use KVM_GENERIC_PRIVATE_MEM, not KVM_SW_PROTECTED_VM.

Right. The fix will be something as follows.

arch/x86/kvm/Kconfig +2 -1
index f2bc78ceaa9a..e912b128bddb 100644
@@ -77,6 +77,7 @@ config KVM_WERROR
 
 config KVM_SW_PROTECTED_VM
        bool "Enable support for KVM software-protected VMs"
+       depends on EXPERT
        depends on KVM && X86_64
        select KVM_GENERIC_PRIVATE_MEM
        help
@@ -90,7 +91,7 @@ config KVM_SW_PROTECTED_VM
 config KVM_INTEL
        tristate "KVM for Intel (and compatible) processors support"
        depends on KVM && IA32_FEAT_CTL
-       select KVM_SW_PROTECTED_VM if INTEL_TDX_HOST
+       select KVM_GENERIC_PRIVATE_MEM if INTEL_TDX_HOST
        select KVM_GENERIC_MEMORY_ATTRIBUTES if INTEL_TDX_HOST
        help
          Provides support for KVM on processors equipped with Intel's VT
Signature · 3 lines
2.43.2
-- 
Isaku Yamahata <[email protected]>
#268 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to Isaku Yamahata
Quoted 20 lines · Isaku
Quoted 12 lines
Quoted 12 lines
arch/x86/kvm/vmx/tdx.c +12 -0
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 514

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Quoted 1 line

Makes sense. Will drop the lock.

Hmm.. Skipping in cpumask_test_and_set_cpu() would result in the second TDH.MNG.KEY.CONFIG not being done for the second VM. No?

#269 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 23 lines · Kai
Quoted 20 lines · Isaku
Quoted 20 lines
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 514

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Quoted 4 lines
Quoted 1 line

Makes sense. Will drop the lock.

Hmm.. Skipping in cpumask_test_and_set_cpu() would result in the second TDH.MNG.KEY.CONFIG not being done for the second VM. No?

No. Because @packages isn't shared between VMs.

#270 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 24 lines · Chao Gao
Quoted 23 lines · Kai
Quoted 20 lines · Isaku
Quoted 20 lines
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+
+		if (cpumask_test_and_set_cpu(pkg, packages))

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 514

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);

the lock is superfluous to me. with cpu lock held, even if multiple CPUs try to create TDs, the same set of CPUs (the first online CPU of each package) will be selected to configure the key because of the cpumask_test_and_set_cpu() above. it means, we never have two CPUs in the same socket trying to program the key, i.e., no concurrent calls.

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Makes sense. Will drop the lock.

Hmm.. Skipping in cpumask_test_and_set_cpu() would result in the second TDH.MNG.KEY.CONFIG not being done for the second VM. No?

No. Because @packages isn't shared between VMs.

I see. Thanks.

#271 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

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

From: Isaku Yamahata <[email protected]>

As the first step to create TDX guest, create/destroy VM struct. Assign TDX private Host Key ID (HKID) to the TDX guest for memory encryption and

Here we are at patch 38, and I don't think you still need to fully spell "Host KeyID (HKID)" anymore.

Just say: Assign one TDX private KeyID ...

Quoted 2 lines

allocate extra pages for the TDX guest. On destruction, free allocated pages, and HKID.

Could we put more information here?

For instance, here should be a wonderful place to explain what are TDR, TDCS, etc??

And briefly describe the sequence of creating the TD?

Roughly checking the code, you have implemented many things including MNG.KEY.CONFIG staff. It's worth to add some text here to give reviewer a rough idea what's going on here.

Quoted 8 lines

Before tearing down private page tables, TDX requires some resources of the guest TD to be destroyed (i.e. HKID must have been reclaimed, etc). Add mmu notifier release callback before tearing down private page tables for it. >
Add vm_free() of kvm_x86_ops hook at the end of kvm_arch_destroy_vm() because some per-VM TDX resources, e.g. TDR, need to be freed after other TDX resources, e.g. HKID, were freed.

I think we should split the "adding callbacks' part out, given you have ...

	9 files changed, 520 insertions(+), 8 deletions(-)

... in this patch.

IMHO, >500 LOC change normally means there are too many things in this patch, thus hard to review, and we should split.

I think perhaps we can split this big patch to smaller pieces based on the steps, like we did for the init_tdx_module() function in the TDX host patchset??

(But I would like to hear from others too.)

Quoted 4 lines

Sean's tag doesn't make sense anymore.

Quoted 2 lines

[...]

Quoted 26 lines
arch/x86/kvm/mmu/mmu.c +7 -0
index c45252ed2ffd..2becc86c71b2 100644
@@ -6866,6 +6866,13 @@ static void kvm_mmu_zap_all(struct kvm *kvm)
 
  void kvm_arch_flush_shadow_all(struct kvm *kvm)
  {
+	/*
+	 * kvm_mmu_zap_all() zaps both private and shared page tables.  Before
+	 * tearing down private page tables, TDX requires some TD resources to
+	 * be destroyed (i.e. keyID must have been reclaimed, etc).  Invoke
+	 * kvm_x86_flush_shadow_all_private() for this.
+	 */
+	static_call_cond(kvm_x86_flush_shadow_all_private)(kvm);
  	kvm_mmu_zap_all(kvm);
  }
 
arch/x86/kvm/vmx/main.c +0 -0
index e8a1a7533eea..437c6d5e802e 100644
@@ -62,11 +62,31 @@ static int vt_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
  static int vt_vm_init(struct kvm *kvm)
  {
  	if (is_td(kvm))

arch/x86/kvm/vmx/main.c static int vt_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 73

Quoted 10 lines
arch/x86/kvm/vmx/main.c +5 -1
-		return -EOPNOTSUPP;	/* Not ready to create guest TD yet. */
+		return tdx_vm_init(kvm);
 
  	return vmx_vm_init(kvm);
  }
 
+static void vt_flush_shadow_all_private(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		tdx_mmu_release_hkid(kvm);

Add a comment to explain please.

arch/x86/kvm/vmx/main.c static int vt_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 79

Quoted 6 lines
arch/x86/kvm/vmx/main.c +6 -0
+}
+
+static void vt_vm_destroy(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return;

Please add a comment to explain why we don't do anything here, but have to delay to vt_vm_free().

Quoted 69 lines
arch/x86/kvm/vmx/main.c +12 -1
+
+	vmx_vm_destroy(kvm);
+}
+
+static void vt_vm_free(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		tdx_vm_free(kvm);
+} > +
  static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
  {
  	if (!is_td(kvm))
@@ -101,7 +121,9 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
  	.vm_size = sizeof(struct kvm_vmx),
  	.vm_enable_cap = vt_vm_enable_cap,
  	.vm_init = vt_vm_init,
-	.vm_destroy = vmx_vm_destroy,
+	.flush_shadow_all_private = vt_flush_shadow_all_private,
+	.vm_destroy = vt_vm_destroy,
+	.vm_free = vt_vm_free,
 
  	.vcpu_precreate = vmx_vcpu_precreate,
  	.vcpu_create = vmx_vcpu_create,
arch/x86/kvm/vmx/tdx.c +6 -3
index ee015f3ce2c9..1cf2b15da257 100644
@@ -5,10 +5,11 @@
 
  #include "capabilities.h"
  #include "x86_ops.h"
-#include "x86.h"
  #include "mmu.h"
  #include "tdx_arch.h"
  #include "tdx.h"
+#include "tdx_ops.h"
+#include "x86.h"
 
  #undef pr_fmt
  #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
@@ -22,7 +23,7 @@
  /* TDX KeyID pool */
  static DEFINE_IDA(tdx_guest_keyid_pool);
 
-static int __used tdx_guest_keyid_alloc(void)
+static int tdx_guest_keyid_alloc(void)
  {
  	if (WARN_ON_ONCE(!tdx_guest_keyid_start || !tdx_nr_guest_keyids))
  		return -EINVAL;
@@ -32,7 +33,7 @@ static int __used tdx_guest_keyid_alloc(void)
  			       GFP_KERNEL);
  }
 
-static void __used tdx_guest_keyid_free(int keyid)
+static void tdx_guest_keyid_free(int keyid)
  {
  	if (WARN_ON_ONCE(keyid < tdx_guest_keyid_start ||
  			 keyid > tdx_guest_keyid_start + tdx_nr_guest_keyids - 1))
@@ -48,6 +49,8 @@ struct tdx_info {
  	u64 xfam_fixed0;
  	u64 xfam_fixed1;
 
+	u8 nr_tdcs_pages;
+
  	u16 num_cpuid_config;
  	/* This must the last member. */
  	DECLARE_FLEX_ARRAY(struct kvm_tdx_cpuid_config, cpuid_configs);
@@ -85,6 +88,282 @@ int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
  	return r;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 98

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +8 -0
  }
 
+/*
+ * Some TDX SEAMCALLs (TDH.MNG.CREATE, TDH.PHYMEM.CACHE.WB,
+ * TDH.MNG.KEY.RECLAIMID, TDH.MNG.KEY.FREEID etc) tries to acquire a global lock
+ * internally in TDX module.  If failed, TDX_OPERAND_BUSY is returned without
+ * spinning or waiting due to a constraint on execution time.  It's caller's
+ * responsibility to avoid race (or retry on TDX_OPERAND_BUSY).  Use this mutex
+ * to avoid race in TDX module because the kernel knows better about scheduling.
+ */

/*
* Some SEAMCALLs acquire TDX module globlly. They fail with
* TDX_OPERAND_BUSY if fail to acquire. Use a global mutex to
* serialize these SEAMCALLs.
*/

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+static DEFINE_MUTEX(tdx_lock);
+static struct mutex *tdx_mng_key_config_lock;
+
+static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
+{
+	return pa | ((hpa_t)hkid << boot_cpu_data.x86_phys_bits);
+}
+
+static inline bool is_td_created(struct kvm_tdx *kvm_tdx)
+{
+	return kvm_tdx->tdr_pa;
+}
+

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 121

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
+{
+	tdx_guest_keyid_free(kvm_tdx->hkid);
+	kvm_tdx->hkid = -1;
+}
+
+static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)
+{
+	return kvm_tdx->hkid > 0;
+}

Hmm...

"Allocating a TDX private KeyID" seems to be one step of creating the TDX guest. Perhaps we should split this patch based on the steps of creating TD.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+
+static void tdx_clear_page(unsigned long page_pa)
+{
+	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
+	void *page = __va(page_pa);
+	unsigned long i;
+
+	/*
+	 * When re-assign one page from old keyid to a new keyid, MOVDIR64B is
+	 * required to clear/write the page with new keyid to prevent integrity
+	 * error when read on the page with new keyid.
+	 *
+	 * clflush doesn't flush cache with HKID set.  

I don't understand this "clflush".

(Firstly, I think it's better to use TDX private KeyID or TDX KeyID instead of HKID, which can be MKTME KeyID really.)

How is "clflush doesn't flush cache with HKID set" relevant here??

What you really want is "all caches associated with the given page must have been flushed before tdx_clear_page()".

You can add as a function comment for tdx_clear_page(), but certainly not here.

The cache line could be

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 135

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+	 * poisoned (even without MKTME-i), clear the poison bit. > +	 */

Is below better?

	/*
	 * The page could have been poisoned.  MOVDIR64B also clears
	 * the poison bit so the kernel can safely use the page again.
	 */
Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+	for (i = 0; i < PAGE_SIZE; i += 64)
+		movdir64b(page + i, zero_page);
+	/*
+	 * MOVDIR64B store uses WC buffer.  Prevent following memory reads
+	 * from seeing potentially poisoned cache.
+	 */
+	__mb();
+}
+

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 155

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+static int __tdx_reclaim_page(hpa_t pa)
+{
+	struct tdx_module_args out;
+	u64 err;
+
+	do {
+		err = tdh_phymem_page_reclaim(pa, &out);
+		/*
+		 * TDH.PHYMEM.PAGE.RECLAIM is allowed only when TD is shutdown.
+		 * state.  i.e. destructing TD.

Does this mean __tdx_reclaim_page() can only be used when destroying the TD?

Pleas add this to the function comment of __tdx_reclaim_page().

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 158

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+		 * TDH.PHYMEM.PAGE.RECLAIM requires TDR and target page.
+		 * Because we're destructing TD, it's rare to contend with TDR.
+		 */

It's rare to contend, so what?

If you want to justify the loop, and the "unlikely()" used in the loop, then put this part right before the 'do { } while ()' loop, where your intention applies, and explicitly call out.

And in general I think it's better to add a 'cond_resched()' for such loop because SEAMCALL is time-costy. If your comment is intended for not adding 'cond_resched()', please also call out.

Quoted 31 lines
arch/x86/kvm/vmx/tdx.c +31 -0
+	} while (unlikely(err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_RCX) ||
+			  err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_TDR)));
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+static int tdx_reclaim_page(hpa_t pa)
+{
+	int r;
+
+	r = __tdx_reclaim_page(pa);
+	if (!r)
+		tdx_clear_page(pa);
+	return r;
+}
+
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID
+	 * assigned to the TD.  Here the cache associated to the TD
+	 * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+	 * cache doesn't need to be flushed again.
+	 */
+	if (tdx_reclaim_page(td_page_pa))

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 199

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		/*
+		 * Leak the page on failure:
+		 * tdx_reclaim_page() returns an error if and only if there's an
+		 * unexpected, fatal error, e.g. a SEAMCALL with bad params,
+		 * incorrect concurrency in KVM, a TDX Module bug, etc.
+		 * Retrying at a later point is highly unlikely to be
+		 * successful.
+		 * No log here as tdx_reclaim_page() already did.
+		 */
+		return;

Use empty lines to make text more breathable between paragraphs.

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	free_page((unsigned long)__va(td_page_pa));
+}
+
+static void tdx_do_tdh_phymem_cache_wb(void *unused)

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 213

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+{
+	u64 err = 0;
+
+	do {
+		err = tdh_phymem_cache_wb(!!err);
+	} while (err == TDX_INTERRUPTED_RESUMABLE);
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;

Empty line.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 216

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	if (WARN_ON_ONCE(err))
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+}

[snip]

I am stopping here, because I need to take a break.

Again I think we should split this patch, there are just too many things to review here.

#272 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 19 lines · Kai

Roughly checking the code, you have implemented many things including MNG.KEY.CONFIG staff. It's worth to add some text here to give reviewer a rough idea what's going on here.

Quoted 8 lines

Before tearing down private page tables, TDX requires some resources of the guest TD to be destroyed (i.e. HKID must have been reclaimed, etc). Add mmu notifier release callback before tearing down private page tables for it. >
Add vm_free() of kvm_x86_ops hook at the end of kvm_arch_destroy_vm() because some per-VM TDX resources, e.g. TDR, need to be freed after other TDX resources, e.g. HKID, were freed.

I think we should split the "adding callbacks' part out, given you have ...

	9 files changed, 520 insertions(+), 8 deletions(-)

... in this patch.

Quoted 8 lines

IMHO, >500 LOC change normally means there are too many things in this patch, thus hard to review, and we should split.

I think perhaps we can split this big patch to smaller pieces based on the steps, like we did for the init_tdx_module() function in the TDX host patchset??

(But I would like to hear from others too.)

Ok, how about those steps
- tdr allocation/free
- allocate+configure/release HKID
- phyemme cache wb
- tdcs allocation/free
- clearing page

520/5 = 104. Want more steps?

Quoted 10 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 216

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	if (WARN_ON_ONCE(err))
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+}

[snip]

I am stopping here, because I need to take a break.

Again I think we should split this patch, there are just too many things to review here.

Thank you so much for the review. Let me try to break this patch.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

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

From: Isaku Yamahata <[email protected]>

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

Before tearing down private page tables, TDX requires some resources of the guest TD to be destroyed (i.e. HKID must have been reclaimed, etc). Add mmu notifier release callback

It seems not accurate to say "Add mmu notifier release callback", since the interface has already been there. This patch extends the cache flush function, i.e, kvm_flush_shadow_all() to do TDX specific thing.

Quoted 43 lines

before tearing down private page tables for
it.

Add vm_free() of kvm_x86_ops hook at the end of kvm_arch_destroy_vm() because some per-VM TDX resources, e.g. TDR, need to be freed after other TDX resources, e.g. HKID, were freed.

---
v19:
- fix check error code of TDH.PHYMEM.PAGE.RECLAIM. RCX and TDR.

v18:
- Use TDH.SYS.RD() instead of struct tdsysinfo_struct.
- Rename tdx_reclaim_td_page() to tdx_reclaim_control_page()
- return -EAGAIN on TDX_RND_NO_ENTROPY of TDH.MNG.CREATE(), TDH.MNG.ADDCX()
- fix comment to remove extra the.
- use true instead of 1 for boolean.
- remove an extra white line.

v16:
- Simplified tdx_reclaim_page()
- Reorganize the locking of tdx_release_hkid(), and use smp_call_mask() instead of smp_call_on_cpu() to hold spinlock to race with invalidation on releasing guest memfd

---
  arch/x86/include/asm/kvm-x86-ops.h |   2 +
  arch/x86/include/asm/kvm_host.h    |   2 +
  arch/x86/kvm/Kconfig               |   3 +-
  arch/x86/kvm/mmu/mmu.c             |   7 +
  arch/x86/kvm/vmx/main.c            |  26 +-
  arch/x86/kvm/vmx/tdx.c             | 475 ++++++++++++++++++++++++++++-
  arch/x86/kvm/vmx/tdx.h             |   6 +-
  arch/x86/kvm/vmx/x86_ops.h         |   6 +
  arch/x86/kvm/x86.c                 |   1 +
  9 files changed, 520 insertions(+), 8 deletions(-)

[...]

Quoted 12 lines
arch/x86/kvm/vmx/tdx.c +12 -0
+
+static void tdx_clear_page(unsigned long page_pa)
+{
+	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
+	void *page = __va(page_pa);
+	unsigned long i;
+
+	/*
+	 * When re-assign one page from old keyid to a new keyid, MOVDIR64B is
+	 * required to clear/write the page with new keyid to prevent integrity
+	 * error when read on the page with new keyid.
+	 *

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 143

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	 * clflush doesn't flush cache with HKID set.  The cache line could be
+	 * poisoned (even without MKTME-i), clear the poison bit.
+	 */
+	for (i = 0; i < PAGE_SIZE; i += 64)
+		movdir64b(page + i, zero_page);
+	/*
+	 * MOVDIR64B store uses WC buffer.  Prevent following memory reads
+	 * from seeing potentially poisoned cache.
+	 */
+	__mb();

Is __wmb() sufficient for this case?

Quoted 2 lines
(quoted diff) +2 -0
+}
+

[...]

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 340

Quoted 12 lines
arch/x86/kvm/vmx/tdx.c +12 -0
+
+static int tdx_do_tdh_mng_key_config(void *param)
+{
+	hpa_t *tdr_p = param;
+	u64 err;
+
+	do {
+		err = tdh_mng_key_config(*tdr_p);
+
+		/*
+		 * If it failed to generate a random key, retry it because this
+		 * is typically caused by an entropy error of the CPU's random

Here you say "typically", is there other cause and is it safe to loop on retry?

Quoted 12 lines
arch/x86/kvm/vmx/tdx.c +12 -0
+		 * number generator.
+		 */
+	} while (err == TDX_KEY_GENERATION_FAILED);
+
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}
+

[...]

#274 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 15 lines · Binbin Wu
Quoted 15 lines
arch/x86/kvm/vmx/tdx.c +15 -0
+static void tdx_clear_page(unsigned long page_pa)
+{
+	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
+	void *page = __va(page_pa);
+	unsigned long i;
+
+	/*
+	 * When re-assign one page from old keyid to a new keyid, MOVDIR64B is
+	 * required to clear/write the page with new keyid to prevent integrity
+	 * error when read on the page with new keyid.
+	 *
+	 * clflush doesn't flush cache with HKID set.  The cache line could be
+	 * poisoned (even without MKTME-i), clear the poison bit.
+	 */
+	for (i = 0; i < PAGE_SIZE; i += 64)
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 143

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+		movdir64b(page + i, zero_page);
+	/*
+	 * MOVDIR64B store uses WC buffer.  Prevent following memory reads
+	 * from seeing potentially poisoned cache.
+	 */
+	__mb();

Is __wmb() sufficient for this case?

I don't think so because sfence is for other store. Here we care other load.

Quoted 7 lines
Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+
+static int tdx_do_tdh_mng_key_config(void *param)
+{
+	hpa_t *tdr_p = param;
+	u64 err;
+
+	do {
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 340

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+		err = tdh_mng_key_config(*tdr_p);
+
+		/*
+		 * If it failed to generate a random key, retry it because this
+		 * is typically caused by an entropy error of the CPU's random

Here you say "typically", is there other cause and is it safe to loop on retry?

No as long as I know. the TDX module returns KEY_GENERATION_FAILED only when rdrnd (or equivalent) failed. But I don't know the future.

Let's delete "tyepically" because it seems confusing.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to [email protected]

... continue the previous review ...

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 181

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);

From the name 'td_page_pa' we cannot tell whether it is a control page, but this function is only intended for control page AFAICT, so perhaps a more specific name.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 184

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID

"are" -> "is".

Are you sure it is TDCX, but not TDCS?

AFAICT TDCX is the control structure for 'vcpu', but here you are handling the control structure for the VM.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 188

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	 * assigned to the TD.  Here the cache associated to the TD
+	 * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+	 * cache doesn't need to be flushed again.
+	 */

How about put this part as the comment for this function?

/*
* Reclaim <name of control page> page(s) which are crypto-protected
* by TDX guest's private KeyID. Assume the cache associated with the
* TDX private KeyID has been flushed.
*/

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 197

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+	if (tdx_reclaim_page(td_page_pa))
+		/*
+		 * Leak the page on failure:
+		 * tdx_reclaim_page() returns an error if and only if there's an
+		 * unexpected, fatal error, e.g. a SEAMCALL with bad params,
+		 * incorrect concurrency in KVM, a TDX Module bug, etc.
+		 * Retrying at a later point is highly unlikely to be
+		 * successful.
+		 * No log here as tdx_reclaim_page() already did.

IMHO can be simplified to below, and nothing else matters.

	/*
	 * Leak the page if the kernel failed to reclaim the page.
	 * The krenel cannot use it safely anymore.
	 */

And you can put this comment above the 'if (tdx_reclaim_page())' statement.

Review

Quoted 2 lines
(quoted diff) +2 -0
+		 */
+		return;

Empty line.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 203

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	free_page((unsigned long)__va(td_page_pa));
+}
+
+static void tdx_do_tdh_phymem_cache_wb(void *unused)

Better to make the name explicit that it is a smp_func, and you don't need the "tdx_" prefix for all the 'static' functions here:

static void smp_func_do_phymem_cache_wb(void *unused)

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 208

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+{
+	u64 err = 0;
+
+	do {
+		err = tdh_phymem_cache_wb(!!err);
		bool resume = !!err;

		err = tdh_phymem_cache_wb(resume);

So that we don't need to jump to the tdh_phymem_cache_wb() to see what does !!err mean.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 209

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+	} while (err == TDX_INTERRUPTED_RESUMABLE);

Add a comment before the do {} while():

/*
* TDH.PHYMEM.CACHE.WB flushes caches associated with _ANY_
* TDX private KeyID on the package (or logical cpu?) where
* it is called on. The TDX module may not finish the cache
* flush but return TDX_INTERRUPTED_RESUMEABLE instead. The
* kernel should retry it until it returns success w/o
* rescheduling.
*/

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 213

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;

Empty line.

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+	if (WARN_ON_ONCE(err))
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+}
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 232

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}

I lost tracking what does "td_created()" mean.

I guess it means: KeyID has been allocated to the TDX guest, but not yet programmed/configured.

Perhaps add a comment to remind the reviewer?

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 241

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+
+	packages_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+	targets_allocated = zalloc_cpumask_var(&targets, GFP_KERNEL);
+	cpus_read_lock();
+
+	/*
+	 * We can destroy multiple guest TDs simultaneously.  Prevent
+	 * tdh_phymem_cache_wb from returning TDX_BUSY by serialization.
+	 */

IMHO it's better to remind people that TDH.PHYMEM.CACHE.WB tries to grab the global TDX module lock:

/*
* TDH.PHYMEM.CACHE.WB tries to acquire the TDX module global
* lock and can fail with TDX_OPERAND_BUSY when it fails to
* grab. Multiple TDX guests can be destroyed simultaneously.
* Take the mutex to prevent it from getting error. */

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	mutex_lock(&tdx_lock);
+
+	/*
+	 * Go through multiple TDX HKID state transitions with three SEAMCALLs
+	 * to make TDH.PHYMEM.PAGE.RECLAIM() usable. 

What is "TDX HKID state transitions"? Not mentioned before, so needs explanation _if_ you want to say this.

And what are the three "SEAMCALLs"? Where are they? The only _two_ SEAMCALLs that I can see here are: TDH.PHYMEM.CACHE.WB and TDH.MNG.KEY.FREEID.

Make the transition atomic

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 247

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+	 * to other functions to operate private pages and Secure-EPT pages.

What's the consequence to "other functions" if we don't make it atomic here?

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 253

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	 *
+	 * Avoid race for kvm_gmem_release() to call kvm_mmu_unmap_gfn_range().
+	 * This function is called via mmu notifier, mmu_release().
+	 * kvm_gmem_release() is called via fput() on process exit.
+	 */
+	write_lock(&kvm->mmu_lock);

I don't fully get the race here, but it seems strange that this function is called via mmu notifier.

IIUC, this function is "supposedly" only be called when we tear down the VM, so I don't know why there's such race.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 266

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+
+	for_each_online_cpu(i) {
+		if (packages_allocated &&
+		    cpumask_test_and_set_cpu(topology_physical_package_id(i),
+					     packages))
+			continue;
+		if (targets_allocated)
+			cpumask_set_cpu(i, targets);
+	}
+	if (targets_allocated)
+		on_each_cpu_mask(targets, tdx_do_tdh_phymem_cache_wb, NULL, true);
+	else
+		on_each_cpu(tdx_do_tdh_phymem_cache_wb, NULL, true);

I don't understand the logic here -- no comments whatever.

But I am 99% sure the logic here could be simplified.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 272

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	/*
+	 * In the case of error in tdx_do_tdh_phymem_cache_wb(), the following
+	 * tdh_mng_key_freeid() will fail.
+	 */
+	err = tdh_mng_key_freeid(kvm_tdx->tdr_pa);
+	if (WARN_ON_ONCE(err)) {

I see KVM_BUG_ON() is normally used for SEAMCALL error. Why this uses WARN_ON_ONCE() here?

Quoted 21 lines
arch/x86/kvm/vmx/tdx.c +21 -0
+		pr_tdx_error(TDH_MNG_KEY_FREEID, err, NULL);
+		pr_err("tdh_mng_key_freeid() failed. HKID %d is leaked.\n",
+		       kvm_tdx->hkid);
+	} else
+		tdx_hkid_free(kvm_tdx);
+
+	write_unlock(&kvm->mmu_lock);
+	mutex_unlock(&tdx_lock);
+	cpus_read_unlock();
+	free_cpumask_var(targets);
+	free_cpumask_var(packages);
+}
+
+void tdx_vm_free(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	u64 err;
+	int i;
+
+	/*
+	 * tdx_mmu_release_hkid() failed to reclaim HKID.  Something went wrong

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 303

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	 * heavily with TDX module.  Give up freeing TD pages.  As the function
+	 * already warned, don't warn it again.
+	 */
+	if (is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (kvm_tdx->tdcs_pa) {
+		for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+			if (kvm_tdx->tdcs_pa[i])
+				tdx_reclaim_control_page(kvm_tdx->tdcs_pa[i]);

AFAICT, here tdcs_pa[i] cannot be NULL, right? How about:

			if (!WARN_ON_ONCE(!kvm_tdx->tdcs_pa[i]))
				continue;
			
			tdx_reclaim_control_page(...);

which at least saves you some indent.

Btw, does it make sense to stop if any tdx_reclaim_control_page() fails?

It's OK to continue, but perhaps worth to add a comment to point out:

/*
* Continue to reclaim other control pages and
* TDR page, even failed to reclaim one control
* page. Do the best to reclaim these TDX
* private pages.
*/
tdx_reclaim_control_page();

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 317

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+		}
+		kfree(kvm_tdx->tdcs_pa);
+		kvm_tdx->tdcs_pa = NULL;
+	}
+
+	if (!kvm_tdx->tdr_pa)
+		return;
+	if (__tdx_reclaim_page(kvm_tdx->tdr_pa))
+		return;
+	/*
+	 * TDX module maps TDR with TDX global HKID.  TDX module may access TDR
+	 * while operating on TD (Especially reclaiming TDCS).  Cache flush with > +	 * TDX global HKID is needed.
+	 */

"Especially reclaiming TDCS" -> "especially when it is reclaiming TDCS".

Use imperative mode to describe your change:

Use the SEAMCALL to ask the TDX module to flush the cache of it using the global KeyID.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 320

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	err = tdh_phymem_page_wbinvd(set_hkid_to_hpa(kvm_tdx->tdr_pa,
+						     tdx_global_keyid));
+	if (WARN_ON_ONCE(err)) {

Again, KVM_BUG_ON()?

Should't matter, though.

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+		pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err, NULL);
+		return;
+	}
+	tdx_clear_page(kvm_tdx->tdr_pa);
+
+	free_page((unsigned long)__va(kvm_tdx->tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+}
+
+static int tdx_do_tdh_mng_key_config(void *param)
+{
+	hpa_t *tdr_p = param;
+	u64 err;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 343

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+	do {
+		err = tdh_mng_key_config(*tdr_p);
+
+		/*
+		 * If it failed to generate a random key, retry it because this
+		 * is typically caused by an entropy error of the CPU's random
+		 * number generator.
+		 */
+	} while (err == TDX_KEY_GENERATION_FAILED);

If you want to handle TDX_KEY_GENERTION_FAILED, it's better to have a retry limit similar to the TDX host code does.

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+	if (WARN_ON_ONCE(err)) {

KVM_BUG_ON()?

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+		pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 361

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+static int __tdx_td_init(struct kvm *kvm);
+
+int tdx_vm_init(struct kvm *kvm)
+{
+	/*
+	 * TDX has its own limit of the number of vcpus in addition to
+	 * KVM_MAX_VCPUS.
+	 */
+	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);

I believe this should be part of the patch that handles KVM_CAP_MAX_VCPUS.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 366

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+
+	/* Place holder for TDX specific logic. */
+	return __tdx_td_init(kvm);
+}
+

... to be continued ...