Skip to contentSkip to conversation

TDX host kernel support

PATCH Superseded Kai Huang 11 participants 163 messages Nov 21, 2022 – Dec 8, 2022 Page 2 of 2

Subsystems (6)

v7 of 15 Superseded Latest is v15 →

lore
Share & tools
lore
author
#143 lore raw

PATCH v7 16/20 x86/virt/tdx: Configure TDX module with TDMRs and global KeyID

In reply to Kai Huang

After the TDX-usable memory regions are constructed in an array of TDMRs and the global KeyID is reserved, configure them to the TDX module using TDH.SYS.CONFIG SEAMCALL. TDH.SYS.CONFIG can only be called once and can be done on any logical cpu.

---
 arch/x86/virt/vmx/tdx/tdx.c | 37 +++++++++++++++++++++++++++++++++++++
 arch/x86/virt/vmx/tdx/tdx.h |  2 ++
 2 files changed, 39 insertions(+)
arch/x86/virt/vmx/tdx/tdx.c +37 -0
index e2cbeeb7f0dc..3a032930e58a 100644
@@ -979,6 +979,37 @@ static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num)
 	return ret;
 }
 
+static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
+			     u64 global_keyid)
+{
+	u64 *tdmr_pa_array;
+	int i, array_sz;
+	u64 ret;
+
+	/*
+	 * TDMR_INFO entries are configured to the TDX module via an
+	 * array of the physical address of each TDMR_INFO.  TDX module
+	 * requires the array itself to be 512-byte aligned.  Round up
+	 * the array size to 512-byte aligned so the buffer allocated
+	 * by kzalloc() will meet the alignment requirement.
+	 */
+	array_sz = ALIGN(tdmr_num * sizeof(u64), TDMR_INFO_PA_ARRAY_ALIGNMENT);
+	tdmr_pa_array = kzalloc(array_sz, GFP_KERNEL);
+	if (!tdmr_pa_array)
+		return -ENOMEM;
+
+	for (i = 0; i < tdmr_num; i++)
+		tdmr_pa_array[i] = __pa(tdmr_array_entry(tdmr_array, i));
+
+	ret = seamcall(TDH_SYS_CONFIG, __pa(tdmr_pa_array), tdmr_num,
+				global_keyid, 0, NULL, NULL);
+
+	/* Free the array as it is not required anymore. */
+	kfree(tdmr_pa_array);
+
+	return ret;
+}
+
 /*
  * Detect and initialize the TDX module.
  *
@@ -1062,11 +1093,17 @@ static int init_tdx_module(void)
 	 */
 	tdx_global_keyid = tdx_keyid_start;
 
+	/* Pass the TDMRs and the global KeyID to the TDX module */
+	ret = config_tdx_module(tdmr_array, tdmr_num, tdx_global_keyid);
+	if (ret)
+		goto out_free_pamts;
+
 	/*
 	 * Return -EINVAL until all steps of TDX module initialization
 	 * process are done.
 	 */
 	ret = -EINVAL;
+out_free_pamts:
 	if (ret)
 		tdmrs_free_pamt_all(tdmr_array, tdmr_num);
 	else
arch/x86/virt/vmx/tdx/tdx.h +2 -0
index a737f2b51474..c26bab2555ca 100644
@@ -19,6 +19,7 @@
 #define TDH_SYS_INIT		33
 #define TDH_SYS_LP_INIT		35
 #define TDH_SYS_LP_SHUTDOWN	44
+#define TDH_SYS_CONFIG		45
 
 struct cmr_info {
 	u64	base;
@@ -86,6 +87,7 @@ struct tdmr_reserved_area {
 } __packed;
 
 #define TDMR_INFO_ALIGNMENT	512
+#define TDMR_INFO_PA_ARRAY_ALIGNMENT	512
 
 struct tdmr_info {
 	u64 base;
Signature · 1 line
2.38.1
#144 lore raw

Re: [PATCH v7 16/20] x86/virt/tdx: Configure TDX module with TDMRs and global KeyID

Quoted 24 lines · Kai Huang

After the TDX-usable memory regions are constructed in an array of TDMRs and the global KeyID is reserved, configure them to the TDX module using TDH.SYS.CONFIG SEAMCALL. TDH.SYS.CONFIG can only be called once and can be done on any logical cpu.

---
 arch/x86/virt/vmx/tdx/tdx.c | 37 +++++++++++++++++++++++++++++++++++++
 arch/x86/virt/vmx/tdx/tdx.h |  2 ++
 2 files changed, 39 insertions(+)
arch/x86/virt/vmx/tdx/tdx.c +4 -0
index e2cbeeb7f0dc..3a032930e58a 100644
@@ -979,6 +979,37 @@ static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num)
 	return ret;
 }
 
+static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
+			     u64 global_keyid)
+{
+	u64 *tdmr_pa_array;

arch/x86/virt/vmx/tdx/tdx.c static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 995

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+	int i, array_sz;
+	u64 ret;
+
+	/*
+	 * TDMR_INFO entries are configured to the TDX module via an
+	 * array of the physical address of each TDMR_INFO.  TDX module
+	 * requires the array itself to be 512-byte aligned.  Round up
+	 * the array size to 512-byte aligned so the buffer allocated
+	 * by kzalloc() will meet the alignment requirement.
+	 */

Aagh. Return of (a different) 512-byte aligned structure.

arch/x86/virt/vmx/tdx/tdx.c static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 997

Quoted 2 lines
arch/x86/virt/vmx/tdx/tdx.c +2 -0
+	array_sz = ALIGN(tdmr_num * sizeof(u64), TDMR_INFO_PA_ARRAY_ALIGNMENT);
+	tdmr_pa_array = kzalloc(array_sz, GFP_KERNEL);

Just to be clear, all that chatter about alignment is because the *START* of the array has to be aligned. Right? I see alignment for 'array_sz', but that's not the start of the array.

tdmr_pa_array is the start of the array. Where is *THAT* aligned?

How does rounding up the size make kzalloc() magically know how to align the *START* of the allocation?

Because I'm actually questioning my own sanity at this point, I went and double-checked the docs (Documentation/core-api/memory-allocation.rst):

Quoted 3 lines

The address of a chunk allocated with kmalloc is aligned to at least ARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the alignment is also guaranteed to be at least the respective size.

Hint #1: ARCH_KMALLOC_MINALIGN is way less than 512. Hint #2: tdmr_num is not guaranteed to be a power of two. Hint #3: Comments don't actually affect the allocation

<snip>

author
#145 lore raw

Re: [PATCH v7 16/20] x86/virt/tdx: Configure TDX module with TDMRs and global KeyID

Quoted 38 lines · Dave Hansen
Quoted 24 lines · Kai Huang

After the TDX-usable memory regions are constructed in an array of TDMRs and the global KeyID is reserved, configure them to the TDX module using TDH.SYS.CONFIG SEAMCALL. TDH.SYS.CONFIG can only be called once and can be done on any logical cpu.

---
 arch/x86/virt/vmx/tdx/tdx.c | 37 +++++++++++++++++++++++++++++++++++++
 arch/x86/virt/vmx/tdx/tdx.h |  2 ++
 2 files changed, 39 insertions(+)
arch/x86/virt/vmx/tdx/tdx.c +4 -0
index e2cbeeb7f0dc..3a032930e58a 100644
@@ -979,6 +979,37 @@ static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num)
 	return ret;
 }
 
+static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
+			     u64 global_keyid)
+{
+	u64 *tdmr_pa_array;

arch/x86/virt/vmx/tdx/tdx.c static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 995

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+	int i, array_sz;
+	u64 ret;
+
+	/*
+	 * TDMR_INFO entries are configured to the TDX module via an
+	 * array of the physical address of each TDMR_INFO.  TDX module
+	 * requires the array itself to be 512-byte aligned.  Round up
+	 * the array size to 512-byte aligned so the buffer allocated
+	 * by kzalloc() will meet the alignment requirement.
+	 */

Aagh. Return of (a different) 512-byte aligned structure.

Quoted 6 lines

arch/x86/virt/vmx/tdx/tdx.c static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 997

Quoted 2 lines
arch/x86/virt/vmx/tdx/tdx.c +2 -0
+	array_sz = ALIGN(tdmr_num * sizeof(u64), TDMR_INFO_PA_ARRAY_ALIGNMENT);
+	tdmr_pa_array = kzalloc(array_sz, GFP_KERNEL);

Just to be clear, all that chatter about alignment is because the *START* of the array has to be aligned. Right?

Correct.

Quoted 4 lines

I see alignment for
'array_sz', but that's not the start of the array.

tdmr_pa_array is the start of the array. Where is *THAT* aligned?

The alignment is assumed to be guaranteed based on the Documentation you quoted below.

Quoted 7 lines

How does rounding up the size make kzalloc() magically know how to align the *START* of the allocation?

Because I'm actually questioning my own sanity at this point, I went and double-checked the docs (Documentation/core-api/memory-allocation.rst):

Quoted 6 lines
Quoted 3 lines

The address of a chunk allocated with kmalloc is aligned to at least ARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the alignment is also guaranteed to be at least the respective size.

Hint #1: ARCH_KMALLOC_MINALIGN is way less than 512. Hint #2: tdmr_num is not guaranteed to be a power of two.

tdmr_num * sizeof(u64) is not guaranteed.

Quoted 1 line

Hint #3: Comments don't actually affect the allocation

Sorry I don't understand the Hint #3.

Perhaps I should just allocate one page so it must be 512-byte aligned?

/*
* TDMR_INFO entries are configured to the TDX module via an array
* of physical address of each TDMR_INFO. The TDX module requires
* the array itself to be 512-byte aligned. Just allocate a page
* to use it as the array so the alignment can be guaranteed. The
* page will be freed after TDH.SYS.CONFIG anyway.
*/

#146 lore raw

Re: [PATCH v7 16/20] x86/virt/tdx: Configure TDX module with TDMRs and global KeyID

Quoted 10 lines · Kai
Quoted 6 lines · Dave Hansen

arch/x86/virt/vmx/tdx/tdx.c static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 997

Quoted 2 lines · Kai Huang
arch/x86/virt/vmx/tdx/tdx.c +2 -0
+   array_sz = ALIGN(tdmr_num * sizeof(u64), TDMR_INFO_PA_ARRAY_ALIGNMENT);
+   tdmr_pa_array = kzalloc(array_sz, GFP_KERNEL);

Just to be clear, all that chatter about alignment is because the *START* of the array has to be aligned. Right?

Correct.

Quoted 7 lines
Quoted 4 lines

I see alignment for
'array_sz', but that's not the start of the array.

tdmr_pa_array is the start of the array. Where is *THAT* aligned?

The alignment is assumed to be guaranteed based on the Documentation you quoted below.

I'm feeling kinda dense today, being Thanksgiving and all. Could you please walk me through, step-by-step how you get kzalloc() to give you an allocation where the start address is 512-byte aligned?

...

Quoted 9 lines

Perhaps I should just allocate one page so it must be 512-byte aligned?

/*
* TDMR_INFO entries are configured to the TDX module via an array
* of physical address of each TDMR_INFO. The TDX module requires
* the array itself to be 512-byte aligned. Just allocate a page
* to use it as the array so the alignment can be guaranteed. The
* page will be freed after TDH.SYS.CONFIG anyway.
*/

Kai, I just plain can't believe at this point that comments like this are still being written. I _thought_ I was very clear before that if you have a constant, say:

#define FOO_ALIGN 512

and you want to align foo, you can just do:

	foo = ALIGN(foo, FOO_ALIGN);

You don't need to mention the 512-byte alignment again. The #define is good enough.

author
#147 lore raw

Re: [PATCH v7 16/20] x86/virt/tdx: Configure TDX module with TDMRs and global KeyID

Quoted 14 lines · Dave Hansen
Quoted 13 lines · Kai
Quoted 6 lines · Dave Hansen

arch/x86/virt/vmx/tdx/tdx.c static int construct_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 997

Quoted 2 lines · Kai Huang
arch/x86/virt/vmx/tdx/tdx.c +2 -0
+   array_sz = ALIGN(tdmr_num * sizeof(u64), TDMR_INFO_PA_ARRAY_ALIGNMENT);
+   tdmr_pa_array = kzalloc(array_sz, GFP_KERNEL);

Just to be clear, all that chatter about alignment is because the *START* of the array has to be aligned. Right?

Correct.

Quoted 3 lines

I see alignment for
'array_sz', but that's not the start of the array.

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

tdmr_pa_array is the start of the array. Where is *THAT* aligned?

The alignment is assumed to be guaranteed based on the Documentation you quoted below.

I'm feeling kinda dense today, being Thanksgiving and all. Could you please walk me through, step-by-step how you get kzalloc() to give you an allocation where the start address is 512-byte aligned?

Sorry I am not good at math. I forgot although 512 is power of two, n x 512 may not be power of two.

The code works because in practice tdmr_num is never larger than 64 so tdmr_num
* sizeof(64) cannot be larger than 512.

So if want to consider array size being larger than 4K, we should use alloc_pages_exact() to allocate?

Quoted 16 lines

...

Quoted 9 lines

Perhaps I should just allocate one page so it must be 512-byte aligned?

/*
* TDMR_INFO entries are configured to the TDX module via an array
* of physical address of each TDMR_INFO. The TDX module requires
* the array itself to be 512-byte aligned. Just allocate a page
* to use it as the array so the alignment can be guaranteed. The
* page will be freed after TDH.SYS.CONFIG anyway.
*/

Kai, I just plain can't believe at this point that comments like this are still being written. I _thought_ I was very clear before that if you have a constant, say:

Quoted 10 lines

#define FOO_ALIGN 512

and you want to align foo, you can just do:

	foo = ALIGN(foo, FOO_ALIGN);

You don't need to mention the 512-byte alignment again. The #define is good enough.

My fault. I thought by changing to allocate a page we don't need to do 'foo = ALIGN(foo, FOO_ALIGN)' so I thought the comment could be useful.

Thanks for responding at Thanksgiving day.

author
#148 lore raw

PATCH v7 17/20 x86/virt/tdx: Configure global KeyID on all packages

In reply to Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel) to clear PMATs isn't needed, as the KeyID 0 doesn't support integrity check.

---

v6 -> v7:
- Improved changelong and comment to explain why MOVDIR64B isn't used when returning PAMTs back to the kernel.

---
 arch/x86/virt/vmx/tdx/tdx.c | 89 ++++++++++++++++++++++++++++++++++++-
 arch/x86/virt/vmx/tdx/tdx.h |  1 +
 2 files changed, 88 insertions(+), 2 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +87 -2
index 3a032930e58a..99d1be5941a7 100644
@@ -224,6 +224,46 @@ static void seamcall_on_each_cpu(struct seamcall_ctx *sc)
 	on_each_cpu(seamcall_smp_call_function, sc, true);
 }
 
+/*
+ * Call one SEAMCALL on one (any) cpu for each physical package in
+ * serialized way.  Return immediately in case of any error if
+ * SEAMCALL fails on any cpu.
+ *
+ * Note for serialized calls 'struct seamcall_ctx::err' doesn't have
+ * to be atomic, but for simplicity just reuse it instead of adding
+ * a new one.
+ */
+static int seamcall_on_each_package_serialized(struct seamcall_ctx *sc)
+{
+	cpumask_var_t packages;
+	int cpu, ret = 0;
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
+
+	for_each_online_cpu(cpu) {
+		if (cpumask_test_and_set_cpu(topology_physical_package_id(cpu),
+					packages))
+			continue;
+
+		ret = smp_call_function_single(cpu, seamcall_smp_call_function,
+				sc, true);
+		if (ret)
+			break;
+
+		/*
+		 * Doesn't have to use atomic_read(), but it doesn't
+		 * hurt either.
+		 */
+		ret = atomic_read(&sc->err);
+		if (ret)
+			break;
+	}
+
+	free_cpumask_var(packages);
+	return ret;
+}
+
 static int tdx_module_init_cpus(void)
 {
 	struct seamcall_ctx sc = { .fn = TDH_SYS_LP_INIT };
@@ -1010,6 +1050,22 @@ static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
 	return ret;
 }
 
+static int config_global_keyid(void)
+{
+	struct seamcall_ctx sc = { .fn = TDH_SYS_KEY_CONFIG };
+
+	/*
+	 * Configure the key of the global KeyID on all packages by
+	 * calling TDH.SYS.KEY.CONFIG on all packages in a serialized
+	 * way as it cannot run concurrently on different CPUs.
+	 *
+	 * TDH.SYS.KEY.CONFIG may fail with entropy error (which is
+	 * a recoverable error).  Assume this is exceedingly rare and
+	 * just return error if encountered instead of retrying.
+	 */
+	return seamcall_on_each_package_serialized(&sc);
+}
+
 /*
  * Detect and initialize the TDX module.
  *
@@ -1098,15 +1154,44 @@ static int init_tdx_module(void)
 	if (ret)
 		goto out_free_pamts;
 
+	/*
+	 * Hardware doesn't guarantee cache coherency across different
+	 * KeyIDs.  The kernel needs to flush PAMT's dirty cachelines
+	 * (associated with KeyID 0) before the TDX module can use the
+	 * global KeyID to access the PAMT.  Given PAMTs are potentially
+	 * large (~1/256th of system RAM), just use WBINVD on all cpus
+	 * to flush the cache.
+	 *
+	 * Follow the TDX spec to flush cache before configuring the
+	 * global KeyID on all packages.
+	 */
+	wbinvd_on_all_cpus();
+
+	/* Config the key of global KeyID on all packages */
+	ret = config_global_keyid();
+	if (ret)
+		goto out_free_pamts;
+
 	/*
 	 * Return -EINVAL until all steps of TDX module initialization
 	 * process are done.
 	 */
 	ret = -EINVAL;
 out_free_pamts:
-	if (ret)
+	if (ret) {
+		/*
+		 * Part of PAMT may already have been initialized by
+		 * TDX module.  Flush cache before returning PAMT back
+		 * to the kernel.
+		 *
+		 * Note there's no need to do MOVDIR64B (which changes
+		 * the page's associated KeyID from the old TDX private
+		 * KeyID back to KeyID 0, which is used by the kernel),
+		 * as KeyID 0 doesn't support integrity check.
+		 */
+		wbinvd_on_all_cpus();
 		tdmrs_free_pamt_all(tdmr_array, tdmr_num);
-	else
+	} else
 		pr_info("%lu pages allocated for PAMT.\n",
 				tdmrs_count_pamt_pages(tdmr_array, tdmr_num));
 out_free_tdmrs:
arch/x86/virt/vmx/tdx/tdx.h +1 -0
index c26bab2555ca..768d097412ab 100644
@@ -15,6 +15,7 @@
 /*
  * TDX module SEAMCALL leaf functions
  */
+#define TDH_SYS_KEY_CONFIG	31
 #define TDH_SYS_INFO		32
 #define TDH_SYS_INIT		33
 #define TDH_SYS_LP_INIT		35
Signature · 1 line
2.38.1
#149 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

Quoted 8 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

This has the same problems as SYS.LP.INIT. It's basically snake oil in some TDX configurations.

This really only needs to be done when the TDX module has memory mappings on a socket for which it needs to use the "global KeyID". If there's no PAMT on a socket, there are probably no allocations there to speak of and no *technical* reason to call TDH.SYS.KEY.CONFIG on that socket. At least none I can see.

So, let's check up on this requirement as well. This could also turn out to be a real pain if all the CPUs on a socket are offline.

Quoted 5 lines

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

I think it's probably worth an aside here about why TDX security isn't dependent on this step. I *think* it boils down to the memory integrity protections. If the caches aren't flushed, a dirty KeyID-0 cacheline could be written back to RAM. The TDX module would come along later and read the cacheline using KeyID-whatever, get an integrity mismatch, machine check, and then everyone would be sad.

Everyone is sad, but TDX security remains intact because memory integrity saved us.

Is it memory integrity or the TD bit, actually?

Quoted 2 lines

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

<sigh>

Quoted 6 lines

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel) to clear PMATs isn't needed, as the KeyID 0 doesn't support integrity check.

I hope this is covered in the code well.

Quoted 29 lines
arch/x86/virt/vmx/tdx/tdx.c +21 -0
index 3a032930e58a..99d1be5941a7 100644
@@ -224,6 +224,46 @@ static void seamcall_on_each_cpu(struct seamcall_ctx *sc)
 	on_each_cpu(seamcall_smp_call_function, sc, true);
 }
 
+/*
+ * Call one SEAMCALL on one (any) cpu for each physical package in
+ * serialized way.  Return immediately in case of any error if
+ * SEAMCALL fails on any cpu.
+ *
+ * Note for serialized calls 'struct seamcall_ctx::err' doesn't have
+ * to be atomic, but for simplicity just reuse it instead of adding
+ * a new one.
+ */
+static int seamcall_on_each_package_serialized(struct seamcall_ctx *sc)
+{
+	cpumask_var_t packages;
+	int cpu, ret = 0;
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
+
+	for_each_online_cpu(cpu) {
+		if (cpumask_test_and_set_cpu(topology_physical_package_id(cpu),
+					packages))
+			continue;

arch/x86/virt/vmx/tdx/tdx.c static void seamcall_on_each_cpu(struct seamcall_ctx *sc) · line 257

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+
+		ret = smp_call_function_single(cpu, seamcall_smp_call_function,
+				sc, true);
+		if (ret)
+			break;
+
+		/*
+		 * Doesn't have to use atomic_read(), but it doesn't
+		 * hurt either.
+		 */

I don't think you need to cover this twice. Just do it in one comment.

Quoted 57 lines
arch/x86/virt/vmx/tdx/tdx.c +43 -0
+		ret = atomic_read(&sc->err);
+		if (ret)
+			break;
+	}
+
+	free_cpumask_var(packages);
+	return ret;
+}
+
 static int tdx_module_init_cpus(void)
 {
 	struct seamcall_ctx sc = { .fn = TDH_SYS_LP_INIT };
@@ -1010,6 +1050,22 @@ static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
 	return ret;
 }
 
+static int config_global_keyid(void)
+{
+	struct seamcall_ctx sc = { .fn = TDH_SYS_KEY_CONFIG };
+
+	/*
+	 * Configure the key of the global KeyID on all packages by
+	 * calling TDH.SYS.KEY.CONFIG on all packages in a serialized
+	 * way as it cannot run concurrently on different CPUs.
+	 *
+	 * TDH.SYS.KEY.CONFIG may fail with entropy error (which is
+	 * a recoverable error).  Assume this is exceedingly rare and
+	 * just return error if encountered instead of retrying.
+	 */
+	return seamcall_on_each_package_serialized(&sc);
+}
+
 /*
  * Detect and initialize the TDX module.
  *
@@ -1098,15 +1154,44 @@ static int init_tdx_module(void)
 	if (ret)
 		goto out_free_pamts;
 
+	/*
+	 * Hardware doesn't guarantee cache coherency across different
+	 * KeyIDs.  The kernel needs to flush PAMT's dirty cachelines
+	 * (associated with KeyID 0) before the TDX module can use the
+	 * global KeyID to access the PAMT.  Given PAMTs are potentially
+	 * large (~1/256th of system RAM), just use WBINVD on all cpus
+	 * to flush the cache.
+	 *
+	 * Follow the TDX spec to flush cache before configuring the
+	 * global KeyID on all packages.
+	 */
+	wbinvd_on_all_cpus();
+
+	/* Config the key of global KeyID on all packages */
+	ret = config_global_keyid();
+	if (ret)
+		goto out_free_pamts;
+

arch/x86/virt/vmx/tdx/tdx.c static int init_tdx_module(void) · line 1183

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -1
 	/*
 	 * Return -EINVAL until all steps of TDX module initialization
 	 * process are done.
 	 */
 	ret = -EINVAL;
 out_free_pamts:
-	if (ret)
+	if (ret) {
+		/*
+		 * Part of PAMT may already have been initialized by

s/initialized/written/

arch/x86/virt/vmx/tdx/tdx.c static int init_tdx_module(void) · line 1191

Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +8 -0
+		 * TDX module.  Flush cache before returning PAMT back
+		 * to the kernel.
+		 *
+		 * Note there's no need to do MOVDIR64B (which changes
+		 * the page's associated KeyID from the old TDX private
+		 * KeyID back to KeyID 0, which is used by the kernel),
+		 * as KeyID 0 doesn't support integrity check.
+		 */

MOVDIR64B is the tiniest of implementation details and also not the only way to initialize memory integrity metadata.

Just keep this high level:

* No need to worry about memory integrity checks here.
* KeyID 0 has integrity checking disabled.

Quoted 19 lines
arch/x86/virt/vmx/tdx/tdx.c +2 -1
+		wbinvd_on_all_cpus();
 		tdmrs_free_pamt_all(tdmr_array, tdmr_num);
-	else
+	} else
 		pr_info("%lu pages allocated for PAMT.\n",
 				tdmrs_count_pamt_pages(tdmr_array, tdmr_num));
 out_free_tdmrs:
arch/x86/virt/vmx/tdx/tdx.h +1 -0
index c26bab2555ca..768d097412ab 100644
@@ -15,6 +15,7 @@
 /*
  * TDX module SEAMCALL leaf functions
  */
+#define TDH_SYS_KEY_CONFIG	31
 #define TDH_SYS_INFO		32
 #define TDH_SYS_INIT		33
 #define TDH_SYS_LP_INIT		35
author
#150 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

Quoted 10 lines · Dave Hansen
Quoted 10 lines · Kai Huang
Quoted 8 lines
Quoted 8 lines

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Quoted 6 lines
Quoted 6 lines

This has the same problems as SYS.LP.INIT. It's basically snake oil in some TDX configurations.

This really only needs to be done when the TDX module has memory mappings on a socket for which it needs to use the "global KeyID".

I think so.

Quoted 4 lines
Quoted 4 lines

If
there's no PAMT on a socket, there are probably no allocations there to speak of and no *technical* reason to call TDH.SYS.KEY.CONFIG on that socket. At least none I can see.

Right PAMT is the main user. Besides PAMT, each TDX guest has a "Trust Domain Root" (TDR) page, and this TDR page is also encrypted using the global KeyID.

Quoted 3 lines
Quoted 3 lines

So, let's check up on this requirement as well. This could also turn out to be a real pain if all the CPUs on a socket are offline.

Yes I'll also check.

Quoted 14 lines
Quoted 14 lines
Quoted 6 lines
Quoted 6 lines

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

I think it's probably worth an aside here about why TDX security isn't dependent on this step. I *think* it boils down to the memory integrity protections. If the caches aren't flushed, a dirty KeyID-0 cacheline could be written back to RAM. The TDX module would come along later and read the cacheline using KeyID-whatever, get an integrity mismatch, machine check, and then everyone would be sad.

Quoted 4 lines
Quoted 4 lines

Everyone is sad, but TDX security remains intact because memory integrity saved us.

Is it memory integrity or the TD bit, actually?

For this case, I think memory integrity.

The TD bit is mainly used to prevent host kernel from being able to read the integrity checksum (MAC) of TD memory, which could result in potential blute- force attack on the MAC.

Specifically, there's such attack that: the host kernel can establish a shared (non-TDX private) KeyID mapping, and repeatedly use different keys via that mapping to speculatively read TDX guest memory. W/o the TD bit, the hardware always performs the integrity check and thus there's possibility that the host eventually can find a key which matches the integrity check.

To prevent such case, the TD bit is added. Hardware will check the TD bit match first, and only perform integrity check _after_ TD bit match. So in above case, host kernel speculatively read TDX memory via shared KeyID mapping will always get a TD bit mismatch, thus won't be able to achieve above attack.

Quoted 50 lines
Quoted 50 lines
Quoted 2 lines
Quoted 2 lines

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

<sigh>

Quoted 6 lines
Quoted 6 lines

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel) to clear PMATs isn't needed, as the KeyID 0 doesn't support integrity check.

I hope this is covered in the code well.

Quoted 36 lines
Quoted 36 lines
arch/x86/virt/vmx/tdx/tdx.c +0 -0
index 3a032930e58a..99d1be5941a7 100644
@@ -224,6 +224,46 @@ static void seamcall_on_each_cpu(struct
 seamcall_ctx *sc)
  	on_each_cpu(seamcall_smp_call_function, sc, true);
  }

arch/x86/virt/vmx/tdx/tdx.c +19 -0
+/*
+ * Call one SEAMCALL on one (any) cpu for each physical package in
+ * serialized way.  Return immediately in case of any error if
+ * SEAMCALL fails on any cpu.
+ *
+ * Note for serialized calls 'struct seamcall_ctx::err' doesn't have
+ * to be atomic, but for simplicity just reuse it instead of adding
+ * a new one.
+ */
+static int seamcall_on_each_package_serialized(struct seamcall_ctx *sc)
+{
+	cpumask_var_t packages;
+	int cpu, ret = 0;
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
+
+	for_each_online_cpu(cpu) {
+		if

(cpumask_test_and_set_cpu(topology_physical_package_id(cpu),

arch/x86/virt/vmx/tdx/tdx.c +4 -0
+					packages))
+			continue;
+
+		ret = smp_call_function_single(cpu,

seamcall_smp_call_function,

arch/x86/virt/vmx/tdx/tdx.c +2 -0
+				sc, true);
+		if (ret)
Quoted 8 lines
Quoted 8 lines
Quoted 6 lines

arch/x86/virt/vmx/tdx/tdx.c static void seamcall_on_each_cpu(struct seamcall_ctx *sc) · line 257

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+			break;
+
+		/*
+		 * Doesn't have to use atomic_read(), but it doesn't
+		 * hurt either.
+		 */

I don't think you need to cover this twice. Just do it in one comment.

Right. I'll remove. I'll be more careful next time to avoid such pattern.

Quoted 62 lines
Quoted 62 lines
Quoted 62 lines
Quoted 62 lines
arch/x86/virt/vmx/tdx/tdx.c +43 -0
+		ret = atomic_read(&sc->err);
+		if (ret)
+			break;
+	}
+
+	free_cpumask_var(packages);
+	return ret;
+}
+
 static int tdx_module_init_cpus(void)
 {
 	struct seamcall_ctx sc = { .fn = TDH_SYS_LP_INIT };
@@ -1010,6 +1050,22 @@ static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
 	return ret;
 }
 
+static int config_global_keyid(void)
+{
+	struct seamcall_ctx sc = { .fn = TDH_SYS_KEY_CONFIG };
+
+	/*
+	 * Configure the key of the global KeyID on all packages by
+	 * calling TDH.SYS.KEY.CONFIG on all packages in a serialized
+	 * way as it cannot run concurrently on different CPUs.
+	 *
+	 * TDH.SYS.KEY.CONFIG may fail with entropy error (which is
+	 * a recoverable error).  Assume this is exceedingly rare and
+	 * just return error if encountered instead of retrying.
+	 */
+	return seamcall_on_each_package_serialized(&sc);
+}
+
 /*
  * Detect and initialize the TDX module.
  *
@@ -1098,15 +1154,44 @@ static int init_tdx_module(void)
 	if (ret)
 		goto out_free_pamts;
 
+	/*
+	 * Hardware doesn't guarantee cache coherency across different
+	 * KeyIDs.  The kernel needs to flush PAMT's dirty cachelines
+	 * (associated with KeyID 0) before the TDX module can use the
+	 * global KeyID to access the PAMT.  Given PAMTs are potentially
+	 * large (~1/256th of system RAM), just use WBINVD on all cpus
+	 * to flush the cache.
+	 *
+	 * Follow the TDX spec to flush cache before configuring the
+	 * global KeyID on all packages.
+	 */
+	wbinvd_on_all_cpus();
+
+	/* Config the key of global KeyID on all packages */
+	ret = config_global_keyid();
+	if (ret)
+		goto out_free_pamts;
+
 	/*
 	 * Return -EINVAL until all steps of TDX module initialization
 	 * process are done.
 	 */
Quoted 8 lines
Quoted 8 lines
Quoted 6 lines

arch/x86/virt/vmx/tdx/tdx.c static int init_tdx_module(void) · line 1183

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -1
 	ret = -EINVAL;
 out_free_pamts:
-	if (ret)
+	if (ret) {
+		/*
+		 * Part of PAMT may already have been initialized by

s/initialized/written/

Will do.

Quoted 13 lines
Quoted 13 lines
Quoted 9 lines

arch/x86/virt/vmx/tdx/tdx.c static int init_tdx_module(void) · line 1191

Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +8 -0
+		 * TDX module.  Flush cache before returning PAMT back
+		 * to the kernel.
+		 *
+		 * Note there's no need to do MOVDIR64B (which changes
+		 * the page's associated KeyID from the old TDX private
+		 * KeyID back to KeyID 0, which is used by the kernel),
+		 * as KeyID 0 doesn't support integrity check.
+		 */

MOVDIR64B is the tiniest of implementation details and also not the only way to initialize memory integrity metadata.

Quoted 4 lines
Quoted 4 lines

Just keep this high level:

* No need to worry about memory integrity checks here.
* KeyID 0 has integrity checking disabled.

Will do. Thanks.

author
#151 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

Quoted 14 lines · Kai
Quoted 14 lines
Quoted 14 lines
Quoted 6 lines
Quoted 6 lines

Intel hardware doesn't guarantee cache coherency across different KeyIDs.  The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the
PAMT.  Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

I think it's probably worth an aside here about why TDX security isn't dependent on this step.  I *think* it boils down to the memory integrity protections.  If the caches aren't flushed, a dirty KeyID-0 cacheline could be written back to RAM.  The TDX module would come along later and read the cacheline using KeyID-whatever, get an integrity mismatch, machine check, and then everyone would be sad.

Quoted 6 lines
Quoted 4 lines
Quoted 4 lines

Everyone is sad, but TDX security remains intact because memory integrity saved us.

Is it memory integrity or the TD bit, actually?

For this case, I think memory integrity.

Sorry thinking again, I was wrong. It should be the TD bit, since TD bit check happens before integrity check.

So the follow is:

1) Dirty KeyID-0 cacheline written back to RAM, which clears the TD bit.
2) TDX module reads PAMT using TDX private KeyId causes TD mismatch, which in this case, results in poison.
3) Further consume of poisoned data results in #MC.

Quoted 17 lines

The TD bit is mainly used to prevent host kernel from being able to read the integrity checksum (MAC) of TD memory, which could result in potential blute- force attack on the MAC.

Specifically, there's such attack that: the host kernel can establish a shared (non-TDX private) KeyID mapping, and repeatedly use different keys via that mapping to speculatively read TDX guest memory. W/o the TD bit, the hardware always performs the integrity check and thus there's possibility that the host eventually can find a key which matches the integrity check.

To prevent such case, the TD bit is added. Hardware will check the TD bit match
first, and only perform integrity check _after_ TD bit match. So in above case,
host kernel speculatively read TDX memory via shared KeyID mapping will always get a TD bit mismatch, thus won't be able to achieve above attack.

#152 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Kai Huang
Quoted 15 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Quoted 8 lines

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

Quoted 2 lines

to clear
PMATs isn't needed, as the KeyID 0 doesn't support integrity check.

For integrity check, is KeyID 0 special or it just has the same behavior as non-zero shared KeyID (if any)?

By saying "KeyID 0 doesn't support integrity check", is it because of  the implementation of this patch set or hardware behavior?

According to Architecure Specification 1.0 of TDX Module (344425-004US), shared KeyID could also enable integrity check.

Quoted 147 lines

---

v6 -> v7:
- Improved changelong and comment to explain why MOVDIR64B isn't used when returning PAMTs back to the kernel.

---
  arch/x86/virt/vmx/tdx/tdx.c | 89 ++++++++++++++++++++++++++++++++++++-
  arch/x86/virt/vmx/tdx/tdx.h |  1 +
  2 files changed, 88 insertions(+), 2 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +87 -2
index 3a032930e58a..99d1be5941a7 100644
@@ -224,6 +224,46 @@ static void seamcall_on_each_cpu(struct seamcall_ctx *sc)
  	on_each_cpu(seamcall_smp_call_function, sc, true);
  }
 
+/*
+ * Call one SEAMCALL on one (any) cpu for each physical package in
+ * serialized way.  Return immediately in case of any error if
+ * SEAMCALL fails on any cpu.
+ *
+ * Note for serialized calls 'struct seamcall_ctx::err' doesn't have
+ * to be atomic, but for simplicity just reuse it instead of adding
+ * a new one.
+ */
+static int seamcall_on_each_package_serialized(struct seamcall_ctx *sc)
+{
+	cpumask_var_t packages;
+	int cpu, ret = 0;
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
+
+	for_each_online_cpu(cpu) {
+		if (cpumask_test_and_set_cpu(topology_physical_package_id(cpu),
+					packages))
+			continue;
+
+		ret = smp_call_function_single(cpu, seamcall_smp_call_function,
+				sc, true);
+		if (ret)
+			break;
+
+		/*
+		 * Doesn't have to use atomic_read(), but it doesn't
+		 * hurt either.
+		 */
+		ret = atomic_read(&sc->err);
+		if (ret)
+			break;
+	}
+
+	free_cpumask_var(packages);
+	return ret;
+}
+
  static int tdx_module_init_cpus(void)
  {
  	struct seamcall_ctx sc = { .fn = TDH_SYS_LP_INIT };
@@ -1010,6 +1050,22 @@ static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
  	return ret;
  }
 
+static int config_global_keyid(void)
+{
+	struct seamcall_ctx sc = { .fn = TDH_SYS_KEY_CONFIG };
+
+	/*
+	 * Configure the key of the global KeyID on all packages by
+	 * calling TDH.SYS.KEY.CONFIG on all packages in a serialized
+	 * way as it cannot run concurrently on different CPUs.
+	 *
+	 * TDH.SYS.KEY.CONFIG may fail with entropy error (which is
+	 * a recoverable error).  Assume this is exceedingly rare and
+	 * just return error if encountered instead of retrying.
+	 */
+	return seamcall_on_each_package_serialized(&sc);
+}
+
  /*
   * Detect and initialize the TDX module.
   *
@@ -1098,15 +1154,44 @@ static int init_tdx_module(void)
  	if (ret)
  		goto out_free_pamts;
 
+	/*
+	 * Hardware doesn't guarantee cache coherency across different
+	 * KeyIDs.  The kernel needs to flush PAMT's dirty cachelines
+	 * (associated with KeyID 0) before the TDX module can use the
+	 * global KeyID to access the PAMT.  Given PAMTs are potentially
+	 * large (~1/256th of system RAM), just use WBINVD on all cpus
+	 * to flush the cache.
+	 *
+	 * Follow the TDX spec to flush cache before configuring the
+	 * global KeyID on all packages.
+	 */
+	wbinvd_on_all_cpus();
+
+	/* Config the key of global KeyID on all packages */
+	ret = config_global_keyid();
+	if (ret)
+		goto out_free_pamts;
+
  	/*
  	 * Return -EINVAL until all steps of TDX module initialization
  	 * process are done.
  	 */
  	ret = -EINVAL;
  out_free_pamts:
-	if (ret)
+	if (ret) {
+		/*
+		 * Part of PAMT may already have been initialized by
+		 * TDX module.  Flush cache before returning PAMT back
+		 * to the kernel.
+		 *
+		 * Note there's no need to do MOVDIR64B (which changes
+		 * the page's associated KeyID from the old TDX private
+		 * KeyID back to KeyID 0, which is used by the kernel),
+		 * as KeyID 0 doesn't support integrity check.
+		 */
+		wbinvd_on_all_cpus();
  		tdmrs_free_pamt_all(tdmr_array, tdmr_num);
-	else
+	} else
  		pr_info("%lu pages allocated for PAMT.\n",
  				tdmrs_count_pamt_pages(tdmr_array, tdmr_num));
  out_free_tdmrs:
arch/x86/virt/vmx/tdx/tdx.h +1 -0
index c26bab2555ca..768d097412ab 100644
@@ -15,6 +15,7 @@
  /*
   * TDX module SEAMCALL leaf functions
   */
+#define TDH_SYS_KEY_CONFIG	31
  #define TDH_SYS_INFO		32
  #define TDH_SYS_INIT		33
  #define TDH_SYS_LP_INIT		35
author
#153 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

Quoted 19 lines · Binbin Wu
Quoted 18 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Quoted 8 lines
Quoted 5 lines

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

Quoted 7 lines
Quoted 4 lines

to clear
PMATs isn't needed, as the KeyID 0 doesn't support integrity check.

For integrity check, is KeyID 0 special or it just has the same behavior as non-zero shared KeyID (if any)?

KeyID 0 is TME KeyID. It is special. Hardware treats the KeyID 0 differently.

Quoted 3 lines

By saying "KeyID 0 doesn't support integrity check", is it because of the implementation of this patch set or hardware behavior?

It's hardware behaviour.

Quoted 4 lines

According to Architecure Specification 1.0 of TDX Module (344425-004US), shared KeyID could also enable integrity check.

KeyID 0 is different from non-0 MKTME shared KeyID. For example, you cannot do PCONFIG on KeyID 0.

#154 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

Quoted 26 lines · Kai
Quoted 25 lines · Binbin Wu
Quoted 23 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

Quoted 6 lines
Quoted 2 lines

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

MOVDIR64B KeyID for the cache line, not the page. Integrity tracked on per-cacheline basis.

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

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Huang, Kai
Quoted 26 lines · Kai
Quoted 25 lines · Binbin Wu
Quoted 23 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

Quoted 6 lines
Quoted 2 lines

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

Just delete it from the changelog. It's a distraction. I'm not even sure it's *necessary* to do any memory content conversion after the TDX module has written gunk.

There won't be any integrity issues because integrity errors don't do anything for KeyID-0 (no #MC).

I _think_ the reads of the page using KeyID-0 will see abort page semantics. That's *FINE*.

author
#156 lore raw

RE: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

Quoted 40 lines · Kai
Quoted 20 lines · Binbin Wu
Quoted 19 lines · Kai Huang
Quoted 18 lines

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Quoted 8 lines
Quoted 8 lines
Quoted 6 lines

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

It seems not accurate to say MOVDIR64B changes the page's associated

KeyID.

Quoted 5 lines
Quoted 1 line

It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

Just delete it from the changelog. It's a distraction. I'm not even sure it's *necessary* to do any memory content conversion after the TDX module has written gunk.

Quoted 5 lines

There won't be any integrity issues because integrity errors don't do anything for KeyID-0 (no #MC).

I _think_ the reads of the page using KeyID-0 will see abort page semantics. That's *FINE*.

I'll remove this from the changelog. Thanks!

#157 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Kai Huang
Quoted 3 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

I want to circle back to this because it potentially has the same class of issue that TDH.SYS.LP.INIT had. So, here's some more background followed by the key question: is TDH.SYS.KEY.CONFIG too strict? Should we explore relaxing it?

Here's the very long-winded way of asking the same thing:

This key is used to protect TDX module memory which is too large to fit into the limited range-register-protected (SMRR) areas that most of the module uses. Right now, that metadata includes the Physical Address Metadata Tables (PAMT) and "TD Root" (TDR) pages. Using this "global KeyID" provides stronger isolation and integrity protection for these structures than is provided by KeyID-0.

The "global KeyID" only strictly needs to be programmed into a memory controllers if a PAMT or TDR page is allocated in memory attached to that controller. However, the TDX module currently requires that TDH.SYS.KEY.CONFIG be executed on one processor in each package. This is true even if there is no TDX Memory Region (TDMR) attached to that package.

This was likely done for simplicity in the TDX module. It currently has no NUMA awareness (or even trusted NUMA metadata) and no ability to correlate processor packages with the memory attached to their memory controllers.

The TDH.SYS.KEY.CONFIG design is actually pretty similar to Kirill's MKTME implementation[1]. Basically blast the KeyID configuration out to one processor in each package, regardless of whether the KeyID will ever get used on that package.

While this requirement from the TDX module is _slightly_ too strict, I'm not quite as worried about it as I was about the *super* strict TDH.SYS.LP.INIT requirements. It's a lot harder and more rare to have an entire package of CPUs unavailable versus a single logical CPU. There is, for instance, no side-channel mitigation that disables an entire package worth of CPUs. I'm not even sure if we allow an entire package worth of NOHZ_FULL-indisposed processors.

I'm happy to go run the same drill for TDH.SYS.KEY.CONFIG that we did for TDH.SYS.LP.INIT. Basically, can we relax the too-strict restrictions? But, I'm not sure anyone will ever reap a practical benefit from it. I'm tempted to just leave it as-is.

Does anyone feel differently?

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

author
#158 lore raw

PATCH v7 18/20 x86/virt/tdx: Initialize all TDMRs

In reply to Kai Huang

Initialize TDMRs via TDH.SYS.TDMR.INIT as the last step to complete the TDX initialization.

All TDMRs need to be initialized using TDH.SYS.TDMR.INIT SEAMCALL before the memory pages can be used by the TDX module. The time to initialize TDMR is proportional to the size of the TDMR because TDH.SYS.TDMR.INIT internally initializes the PAMT entries using the global KeyID.

To avoid long latency caused in one SEAMCALL, TDH.SYS.TDMR.INIT only initializes an (implementation-specific) subset of PAMT entries of one TDMR in one invocation. The caller needs to call TDH.SYS.TDMR.INIT iteratively until all PAMT entries of the given TDMR are initialized.

TDH.SYS.TDMR.INITs can run concurrently on multiple CPUs as long as they are initializing different TDMRs. To keep it simple, just initialize all TDMRs one by one. On a 2-socket machine with 2.2G CPUs and 64GB memory, each TDH.SYS.TDMR.INIT roughly takes couple of microseconds on average, and it takes roughly dozens of milliseconds to complete the initialization of all TDMRs while system is idle.

---

v6 -> v7:
- Removed need_resched() check. -- Andi.

---
 arch/x86/virt/vmx/tdx/tdx.c | 69 ++++++++++++++++++++++++++++++++++---
 arch/x86/virt/vmx/tdx/tdx.h |  1 +
 2 files changed, 65 insertions(+), 5 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +64 -5
index 99d1be5941a7..9bcdb30b7a80 100644
@@ -1066,6 +1066,65 @@ static int config_global_keyid(void)
 	return seamcall_on_each_package_serialized(&sc);
 }
 
+/* Initialize one TDMR */
+static int init_tdmr(struct tdmr_info *tdmr)
+{
+	u64 next;
+
+	/*
+	 * Initializing PAMT entries might be time-consuming (in
+	 * proportion to the size of the requested TDMR).  To avoid long
+	 * latency in one SEAMCALL, TDH.SYS.TDMR.INIT only initializes
+	 * an (implementation-defined) subset of PAMT entries in one
+	 * invocation.
+	 *
+	 * Call TDH.SYS.TDMR.INIT iteratively until all PAMT entries
+	 * of the requested TDMR are initialized (if next-to-initialize
+	 * address matches the end address of the TDMR).
+	 */
+	do {
+		struct tdx_module_output out;
+		int ret;
+
+		ret = seamcall(TDH_SYS_TDMR_INIT, tdmr->base, 0, 0, 0, NULL,
+				&out);
+		if (ret)
+			return ret;
+		/*
+		 * RDX contains 'next-to-initialize' address if
+		 * TDH.SYS.TDMR.INT succeeded.
+		 */
+		next = out.rdx;
+		/* Allow scheduling when needed */
+		cond_resched();
+	} while (next < tdmr->base + tdmr->size);
+
+	return 0;
+}
+
+/* Initialize all TDMRs */
+static int init_tdmrs(struct tdmr_info *tdmr_array, int tdmr_num)
+{
+	int i;
+
+	/*
+	 * Initialize TDMRs one-by-one for simplicity, though the TDX
+	 * architecture does allow different TDMRs to be initialized in
+	 * parallel on multiple CPUs.  Parallel initialization could
+	 * be added later when the time spent in the serialized scheme
+	 * becomes a real concern.
+	 */
+	for (i = 0; i < tdmr_num; i++) {
+		int ret;
+
+		ret = init_tdmr(tdmr_array_entry(tdmr_array, i));
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
 /*
  * Detect and initialize the TDX module.
  *
@@ -1172,11 +1231,11 @@ static int init_tdx_module(void)
 	if (ret)
 		goto out_free_pamts;
 
-	/*
-	 * Return -EINVAL until all steps of TDX module initialization
-	 * process are done.
-	 */
-	ret = -EINVAL;
+	/* Initialize TDMRs to complete the TDX module initialization */
+	ret = init_tdmrs(tdmr_array, tdmr_num);
+	if (ret)
+		goto out_free_pamts;
+
 out_free_pamts:
 	if (ret) {
 		/*
arch/x86/virt/vmx/tdx/tdx.h +1 -0
index 768d097412ab..891691b1ea50 100644
@@ -19,6 +19,7 @@
 #define TDH_SYS_INFO		32
 #define TDH_SYS_INIT		33
 #define TDH_SYS_LP_INIT		35
+#define TDH_SYS_TDMR_INIT	36
 #define TDH_SYS_LP_SHUTDOWN	44
 #define TDH_SYS_CONFIG		45
 
Signature · 1 line
2.38.1
#159 lore raw

Re: [PATCH v7 18/20] x86/virt/tdx: Initialize all TDMRs

Quoted 13 lines · Kai Huang

Initialize TDMRs via TDH.SYS.TDMR.INIT as the last step to complete the TDX initialization.

All TDMRs need to be initialized using TDH.SYS.TDMR.INIT SEAMCALL before the memory pages can be used by the TDX module. The time to initialize TDMR is proportional to the size of the TDMR because TDH.SYS.TDMR.INIT internally initializes the PAMT entries using the global KeyID.

To avoid long latency caused in one SEAMCALL, TDH.SYS.TDMR.INIT only initializes an (implementation-specific) subset of PAMT entries of one TDMR in one invocation. The caller needs to call TDH.SYS.TDMR.INIT iteratively until all PAMT entries of the given TDMR are initialized.

Quoted 6 lines

TDH.SYS.TDMR.INITs can run concurrently on multiple CPUs as long as they are initializing different TDMRs. To keep it simple, just initialize all TDMRs one by one. On a 2-socket machine with 2.2G CPUs and 64GB memory, each TDH.SYS.TDMR.INIT roughly takes couple of microseconds on average, and it takes roughly dozens of milliseconds to complete the initialization of all TDMRs while system is idle.

Any chance you could say TDH.SYS.TDMR.INIT a few more times in there? ;)

Seriously, please try to trim that down. If you talk about the implementation in detail in the code comments, don't cover it in detail in the changelog too.

Also, this is a momentous patch, right? It's the last piece. Maybe worth calling that out.

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1069

Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +1 -0
index 99d1be5941a7..9bcdb30b7a80 100644
@@ -1066,6 +1066,65 @@ static int config_global_keyid(void)
 	return seamcall_on_each_package_serialized(&sc);
 }
 
+/* Initialize one TDMR */

Does this comment add value? Even if it does, it is better than naming the dang function init_one_tdmr()?

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+static int init_tdmr(struct tdmr_info *tdmr)
+{
+	u64 next;
+
+	/*

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1084

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+	 * Initializing PAMT entries might be time-consuming (in
+	 * proportion to the size of the requested TDMR).  To avoid long
+	 * latency in one SEAMCALL, TDH.SYS.TDMR.INIT only initializes
+	 * an (implementation-defined) subset of PAMT entries in one
+	 * invocation.
+	 *
+	 * Call TDH.SYS.TDMR.INIT iteratively until all PAMT entries
+	 * of the requested TDMR are initialized (if next-to-initialize
+	 * address matches the end address of the TDMR).
+	 */

The PAMT discussion here is, IMNHO silly. If this were about initializing PAMT's then it should be renamed init_pamts() and the SEAMCALL should be called PAMT_INIT or soemthing. It's not, and the ABI is built around the TDMR and *its* addresses.

Let's chop this comment down:

/*
* Initializing a TDMR can be time consuming. To avoid long
* SEAMCALLs, the TDX module may only initialize a part of the
* TDMR in each call.
*/

Talk about the looping logic in the loop.

Quoted 4 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -0
+	do {
+		struct tdx_module_output out;
+		int ret;
+

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1098

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+		ret = seamcall(TDH_SYS_TDMR_INIT, tdmr->base, 0, 0, 0, NULL,
+				&out);
+		if (ret)
+			return ret;
+		/*
+		 * RDX contains 'next-to-initialize' address if
+		 * TDH.SYS.TDMR.INT succeeded.
+		 */
+		next = out.rdx;
+		/* Allow scheduling when needed */

That comment is a wee bit superfluous, don't you think?

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1099

Quoted 1 line
arch/x86/virt/vmx/tdx/tdx.c +1 -0
+		cond_resched();
		/* Keep making SEAMCALLs until the TDMR is done */

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1105

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+	} while (next < tdmr->base + tdmr->size);
+
+	return 0;
+}
+
+/* Initialize all TDMRs */

Does this comment add value?

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1116

Quoted 11 lines
arch/x86/virt/vmx/tdx/tdx.c +11 -0
+static int init_tdmrs(struct tdmr_info *tdmr_array, int tdmr_num)
+{
+	int i;
+
+	/*
+	 * Initialize TDMRs one-by-one for simplicity, though the TDX
+	 * architecture does allow different TDMRs to be initialized in
+	 * parallel on multiple CPUs.  Parallel initialization could
+	 * be added later when the time spent in the serialized scheme
+	 * becomes a real concern.
+	 */

Trim down the comment:

	/*
	 * This operation is costly.  It can be parallelized,
	 * but keep it simple for now.
	 */
Quoted 43 lines
arch/x86/virt/vmx/tdx/tdx.c +16 -5
+	for (i = 0; i < tdmr_num; i++) {
+		int ret;
+
+		ret = init_tdmr(tdmr_array_entry(tdmr_array, i));
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
 /*
  * Detect and initialize the TDX module.
  *
@@ -1172,11 +1231,11 @@ static int init_tdx_module(void)
 	if (ret)
 		goto out_free_pamts;
 
-	/*
-	 * Return -EINVAL until all steps of TDX module initialization
-	 * process are done.
-	 */
-	ret = -EINVAL;
+	/* Initialize TDMRs to complete the TDX module initialization */
+	ret = init_tdmrs(tdmr_array, tdmr_num);
+	if (ret)
+		goto out_free_pamts;
+
 out_free_pamts:
 	if (ret) {
 		/*
arch/x86/virt/vmx/tdx/tdx.h +1 -0
index 768d097412ab..891691b1ea50 100644
@@ -19,6 +19,7 @@
 #define TDH_SYS_INFO		32
 #define TDH_SYS_INIT		33
 #define TDH_SYS_LP_INIT		35
+#define TDH_SYS_TDMR_INIT	36
 #define TDH_SYS_LP_SHUTDOWN	44
 #define TDH_SYS_CONFIG		45
 
author
#160 lore raw

Re: [PATCH v7 18/20] x86/virt/tdx: Initialize all TDMRs

Quoted 14 lines · Dave Hansen
Quoted 13 lines · Kai Huang

Initialize TDMRs via TDH.SYS.TDMR.INIT as the last step to complete the TDX initialization.

All TDMRs need to be initialized using TDH.SYS.TDMR.INIT SEAMCALL before the memory pages can be used by the TDX module. The time to initialize TDMR is proportional to the size of the TDMR because TDH.SYS.TDMR.INIT internally initializes the PAMT entries using the global KeyID.

To avoid long latency caused in one SEAMCALL, TDH.SYS.TDMR.INIT only initializes an (implementation-specific) subset of PAMT entries of one TDMR in one invocation. The caller needs to call TDH.SYS.TDMR.INIT iteratively until all PAMT entries of the given TDMR are initialized.

Quoted 8 lines
Quoted 6 lines

TDH.SYS.TDMR.INITs can run concurrently on multiple CPUs as long as they are initializing different TDMRs. To keep it simple, just initialize all TDMRs one by one. On a 2-socket machine with 2.2G CPUs and 64GB memory, each TDH.SYS.TDMR.INIT roughly takes couple of microseconds on average, and it takes roughly dozens of milliseconds to complete the initialization of all TDMRs while system is idle.

Any chance you could say TDH.SYS.TDMR.INIT a few more times in there? ;)

I am a bad changelog writer.

Quoted 4 lines

Seriously, please try to trim that down. If you talk about the implementation in detail in the code comments, don't cover it in detail in the changelog too.

Yes will use this tip to trim down. Thanks for the tip.

Quoted 3 lines

Also, this is a momentous patch, right? It's the last piece. Maybe worth calling that out.

Yes this is the last step of initializing the TDX module. It is sort of mentioned in the first sentence of this changelong:

Initialize TDMRs via TDH.SYS.TDMR.INIT as the last step to complete the TDX initialization.

But perhaps it can be more explicitly.

Quoted 9 lines
Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +0 -0
index 99d1be5941a7..9bcdb30b7a80 100644
@@ -1066,6 +1066,65 @@ static int config_global_keyid(void)
 	return seamcall_on_each_package_serialized(&sc);
 }
 
Quoted 4 lines

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1069

Quoted 1 line
arch/x86/virt/vmx/tdx/tdx.c +1 -0
+/* Initialize one TDMR */

Does this comment add value? Even if it does, it is better than naming the dang function init_one_tdmr()?

Sorry will try best to avoid such type of comments in the future.

Quoted 13 lines
Quoted 13 lines
arch/x86/virt/vmx/tdx/tdx.c +12 -0
+static int init_tdmr(struct tdmr_info *tdmr)
+{
+	u64 next;
+
+	/*
+	 * Initializing PAMT entries might be time-consuming (in
+	 * proportion to the size of the requested TDMR).  To avoid long
+	 * latency in one SEAMCALL, TDH.SYS.TDMR.INIT only initializes
+	 * an (implementation-defined) subset of PAMT entries in one
+	 * invocation.
+	 *
+	 * Call TDH.SYS.TDMR.INIT iteratively until all PAMT entries
Quoted 8 lines

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1084

Quoted 3 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -0
+	 * of the requested TDMR are initialized (if next-to-initialize
+	 * address matches the end address of the TDMR).
+	 */

The PAMT discussion here is, IMNHO silly. If this were about initializing PAMT's then it should be renamed init_pamts() and the SEAMCALL should be called PAMT_INIT or soemthing. It's not, and the ABI is built around the TDMR and *its* addresses.

Agreed.

Quoted 10 lines

Let's chop this comment down:

/*
* Initializing a TDMR can be time consuming. To avoid long
* SEAMCALLs, the TDX module may only initialize a part of the
* TDMR in each call.
*/

Talk about the looping logic in the loop.

Agreed. Thanks.

Quoted 17 lines
Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -0
+	do {
+		struct tdx_module_output out;
+		int ret;
+

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1098

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+		ret = seamcall(TDH_SYS_TDMR_INIT, tdmr->base, 0, 0, 0, NULL,
+				&out);
+		if (ret)
+			return ret;
+		/*
+		 * RDX contains 'next-to-initialize' address if
+		 * TDH.SYS.TDMR.INT succeeded.
+		 */
+		next = out.rdx;
+		/* Allow scheduling when needed */

That comment is a wee bit superfluous, don't you think?

Indeed.

Quoted 5 lines

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1099

Quoted 2 lines
arch/x86/virt/vmx/tdx/tdx.c +1 -0
+		cond_resched();
		/* Keep making SEAMCALLs until the TDMR is done */
Quoted 8 lines

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1105

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+	} while (next < tdmr->base + tdmr->size);
+
+	return 0;
+}
+
+/* Initialize all TDMRs */

Does this comment add value?

No. Will remove.

Quoted 15 lines

arch/x86/virt/vmx/tdx/tdx.c static int config_global_keyid(void) · line 1116

Quoted 12 lines
arch/x86/virt/vmx/tdx/tdx.c +11 -0
+static int init_tdmrs(struct tdmr_info *tdmr_array, int tdmr_num)
+{
+	int i;
+
+	/*
+	 * Initialize TDMRs one-by-one for simplicity, though the TDX
+	 * architecture does allow different TDMRs to be initialized in
+	 * parallel on multiple CPUs.  Parallel initialization could
+	 * be added later when the time spent in the serialized scheme
+	 * becomes a real concern.
+	 */

Trim down the comment:

Quoted 4 lines
	/*
	 * This operation is costly.  It can be parallelized,
	 * but keep it simple for now.
	 */

Thanks.

[...]

author
#161 lore raw

PATCH v7 19/20 x86/virt/tdx: Flush cache in kexec() when TDX is enabled

In reply to Kai Huang

There are two problems in terms of using kexec() to boot to a new kernel when the old kernel has enabled TDX: 1) Part of the memory pages are still TDX private pages (i.e. metadata used by the TDX module, and any TDX guest memory if kexec() happens when there's any TDX guest alive).
2) There might be dirty cachelines associated with TDX private pages.

Because the hardware doesn't guarantee cache coherency among different KeyIDs, the old kernel needs to flush cache (of those TDX private pages) before booting to the new kernel. Also, reading TDX private page using any shared non-TDX KeyID with integrity-check enabled can trigger #MC. Therefore ideally, the kernel should convert all TDX private pages back to normal before booting to the new kernel.

However, this implementation doesn't convert TDX private pages back to normal in kexec() because of below considerations:

1) The kernel doesn't have existing infrastructure to track which pages are TDX private pages.
2) The number of TDX private pages can be large, and converting all of them (cache flush + using MOVDIR64B to clear the page) in kexec() can be time consuming.
3) The new kernel will almost only use KeyID 0 to access memory. KeyID 0 doesn't support integrity-check, so it's OK.
4) The kernel doesn't (and may never) support MKTME. If any 3rd party kernel ever supports MKTME, it should do MOVDIR64B to clear the page with the new MKTME KeyID (just like TDX does) before using it.

Therefore, this implementation just flushes cache to make sure there are no stale dirty cachelines associated with any TDX private KeyIDs before booting to the new kernel, otherwise they may silently corrupt the new kernel.

Following SME support, use wbinvd() to flush cache in stop_this_cpu(). Theoretically, cache flush is only needed when the TDX module has been initialized. However initializing the TDX module is done on demand at runtime, and it takes a mutex to read the module status. Just check whether TDX is enabled by BIOS instead to flush cache.

Also, the current TDX module doesn't play nicely with kexec(). The TDX module can only be initialized once during its lifetime, and there is no ABI to reset the module to give a new clean slate to the new kernel. Therefore ideally, if the TDX module is ever initialized, it's better to shut it down. The new kernel won't be able to use TDX anyway (as it needs to go through the TDX module initialization process which will fail immediately at the first step).

However, shutting down the TDX module requires all CPUs being in VMX operation, but there's no such guarantee as kexec() can happen at any time (i.e. when KVM is not even loaded). So just do nothing but leave leave the TDX module open.

---

v6 -> v7:
- Improved changelog to explain why don't convert TDX private pages back to normal.

---
 arch/x86/kernel/process.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
arch/x86/kernel/process.c +7 -1
index c21b7347a26d..0cc84977dc62 100644
@@ -765,8 +765,14 @@ void __noreturn stop_this_cpu(void *dummy)
 	 *
 	 * Test the CPUID bit directly because the machine might've cleared
 	 * X86_FEATURE_SME due to cmdline options.
+	 *
+	 * Similar to SME, if the TDX module is ever initialized, the
+	 * cachelines associated with any TDX private KeyID must be flushed
+	 * before transiting to the new kernel.  The TDX module is initialized
+	 * on demand, and it takes the mutex to read its status.  Just check
+	 * whether TDX is enabled by BIOS instead to flush cache.
 	 */
-	if (cpuid_eax(0x8000001f) & BIT(0))
+	if (cpuid_eax(0x8000001f) & BIT(0) || platform_tdx_enabled())
 		native_wbinvd();
 	for (;;) {
 		/*
Signature · 1 line
2.38.1
author
#162 lore raw

PATCH v7 20/20 Documentation/x86: Add documentation for TDX host support

In reply to Kai Huang

Add documentation for TDX host kernel support. There is already one file Documentation/x86/tdx.rst containing documentation for TDX guest internals. Also reuse it for TDX host kernel support.

Introduce a new level menu "TDX Guest Support" and move existing materials under it, and add a new menu for TDX host kernel support.

---

v6 -> v7:
- Changed "TDX Memory Policy" and "Kexec()" sections.

---
 Documentation/x86/tdx.rst | 181 +++++++++++++++++++++++++++++++++++---
 1 file changed, 170 insertions(+), 11 deletions(-)
Documentation/x86/tdx.rst +170 -11
index dc8d9fd2c3f7..35092e7c60f7 100644
@@ -10,6 +10,165 @@ encrypting the guest memory. In TDX, a special module running in a special
 mode sits between the host and the guest and manages the guest/host
 separation.
 
+TDX Host Kernel Support
+=======================
+
+TDX introduces a new CPU mode called Secure Arbitration Mode (SEAM) and
+a new isolated range pointed by the SEAM Ranger Register (SEAMRR).  A
+CPU-attested software module called 'the TDX module' runs inside the new
+isolated range to provide the functionalities to manage and run protected
+VMs.
+
+TDX also leverages Intel Multi-Key Total Memory Encryption (MKTME) to
+provide crypto-protection to the VMs.  TDX reserves part of MKTME KeyIDs
+as TDX private KeyIDs, which are only accessible within the SEAM mode.
+BIOS is responsible for partitioning legacy MKTME KeyIDs and TDX KeyIDs.
+
+Before the TDX module can be used to create and run protected VMs, it
+must be loaded into the isolated range and properly initialized.  The TDX
+architecture doesn't require the BIOS to load the TDX module, but the
+kernel assumes it is loaded by the BIOS.
+
+TDX boot-time detection
+-----------------------
+
+The kernel detects TDX by detecting TDX private KeyIDs during kernel
+boot.  Below dmesg shows when TDX is enabled by BIOS::
+
+  [..] tdx: TDX enabled by BIOS. TDX private KeyID range: [16, 64).
+
+TDX module detection and initialization
+---------------------------------------
+
+There is no CPUID or MSR to detect the TDX module.  The kernel detects it
+by initializing it.
+
+The kernel talks to the TDX module via the new SEAMCALL instruction.  The
+TDX module implements SEAMCALL leaf functions to allow the kernel to
+initialize it.
+
+Initializing the TDX module consumes roughly ~1/256th system RAM size to
+use it as 'metadata' for the TDX memory.  It also takes additional CPU
+time to initialize those metadata along with the TDX module itself.  Both
+are not trivial.  The kernel initializes the TDX module at runtime on
+demand.  The caller to call tdx_enable() to initialize the TDX module::
+
+        ret = tdx_enable();
+        if (ret)
+                goto no_tdx;
+        // TDX is ready to use
+
+Initializing the TDX module requires all logical CPUs being online.
+tdx_enable() internally temporarily disables CPU hotplug to prevent any
+CPU from going offline, but the caller still needs to guarantee all
+present CPUs are online before calling tdx_enable().
+
+Also, tdx_enable() requires all CPUs are already in VMX operation
+(requirement of making SEAMCALL).  Currently, tdx_enable() doesn't handle
+VMXON internally, but depends on the caller to guarantee that.  So far
+KVM is the only user of TDX and KVM already handles VMXON.
+
+User can consult dmesg to see the presence of the TDX module, and whether
+it has been initialized.
+
+If the TDX module is not loaded, dmesg shows below::
+
+  [..] tdx: TDX module is not loaded.
+
+If the TDX module is initialized successfully, dmesg shows something
+like below::
+
+  [..] tdx: TDX module: attributes 0x0, vendor_id 0x8086, major_version 1, minor_version 0, build_date 20211209, build_num 160
+  [..] tdx: 65667 pages allocated for PAMT.
+  [..] tdx: TDX module initialized.
+
+If the TDX module failed to initialize, dmesg shows below::
+
+  [..] tdx: Failed to initialize TDX module. Shut it down.
+
+TDX Interaction to Other Kernel Components
+------------------------------------------
+
+TDX Memory Policy
+~~~~~~~~~~~~~~~~~
+
+TDX reports a list of "Convertible Memory Region" (CMR) to indicate all
+memory regions that can possibly be used by the TDX module, but they are
+not automatically usable to the TDX module.  As a step of initializing
+the TDX module, the kernel needs to choose a list of memory regions (out
+from convertible memory regions) that the TDX module can use and pass
+those regions to the TDX module.  Once this is done, those "TDX-usable"
+memory regions are fixed during module's lifetime.  No more TDX-usable
+memory can be added to the TDX module after that.
+
+To keep things simple, currently the kernel simply guarantees all pages
+in the page allocator are TDX memory.  Specifically, the kernel uses all
+system memory in the core-mm at the time of initializing the TDX module
+as TDX memory, and at the meantime, refuses to add any non-TDX-memory in
+the memory hotplug.
+
+This can be enhanced in the future, i.e. by allowing adding non-TDX
+memory to a separate NUMA node.  In this case, the "TDX-capable" nodes
+and the "non-TDX-capable" nodes can co-exist, but the kernel/userspace
+needs to guarantee memory pages for TDX guests are always allocated from
+the "TDX-capable" nodes.
+
+Note TDX assumes convertible memory is always physically present during
+machine's runtime.  A non-buggy BIOS should never support hot-removal of
+any convertible memory.  This implementation doesn't handle ACPI memory
+removal but depends on the BIOS to behave correctly.
+
+CPU Hotplug
+~~~~~~~~~~~
+
+TDX doesn't support physical (ACPI) CPU hotplug.  During machine boot,
+TDX verifies all boot-time present logical CPUs are TDX compatible before
+enabling TDX.  A non-buggy BIOS should never support hot-add/removal of
+physical CPU.  Currently the kernel doesn't handle physical CPU hotplug,
+but depends on the BIOS to behave correctly.
+
+Note TDX works with CPU logical online/offline, thus the kernel still
+allows to offline logical CPU and online it again.
+
+Kexec()
+~~~~~~~
+
+There are two problems in terms of using kexec() to boot to a new kernel
+when the old kernel has enabled TDX: 1) Part of the memory pages are
+still TDX private pages (i.e. metadata used by the TDX module, and any
+TDX guest memory if kexec() is executed when there's live TDX guests).
+2) There might be dirty cachelines associated with TDX private pages.
+
+Because the hardware doesn't guarantee cache coherency among different
+KeyIDs, the old kernel needs to flush cache (of TDX private pages)
+before booting to the new kernel.  Also, the kernel doesn't convert all
+TDX private pages back to normal because of below considerations:
+
+1) The kernel doesn't have existing infrastructure to track which pages
+   are TDX private page.
+2) The number of TDX private pages can be large, and converting all of
+   them (cache flush + using MOVDIR64B to clear the page) can be time
+   consuming.
+3) The new kernel will almost only use KeyID 0 to access memory.  KeyID
+   0 doesn't support integrity-check, so it's OK.
+4) The kernel doesn't (and may never) support MKTME.  If any 3rd party
+   kernel ever supports MKTME, it should do MOVDIR64B to clear the page
+   with the new MKTME KeyID (just like TDX does) before using it.
+
+The current TDX module architecture doesn't play nicely with kexec().
+The TDX module can only be initialized once during its lifetime, and
+there is no SEAMCALL to reset the module to give a new clean slate to
+the new kernel.  Therefore, ideally, if the module is ever initialized,
+it's better to shut down the module.  The new kernel won't be able to
+use TDX anyway (as it needs to go through the TDX module initialization
+process which will fail immediately at the first step).
+
+However, there's no guarantee CPU is in VMX operation during kexec(), so
+it's impractical to shut down the module.  Currently, the kernel just
+leaves the module in open state.
+
+TDX Guest Support
+=================
 Since the host cannot directly access guest registers or memory, much
 normal functionality of a hypervisor must be moved into the guest. This is
 implemented using a Virtualization Exception (#VE) that is handled by the
@@ -20,7 +179,7 @@ TDX includes new hypercall-like mechanisms for communicating from the
 guest to the hypervisor or the TDX module.
 
 New TDX Exceptions
-==================
+------------------
 
 TDX guests behave differently from bare-metal and traditional VMX guests.
 In TDX guests, otherwise normal instructions or memory accesses can cause
@@ -30,7 +189,7 @@ Instructions marked with an '*' conditionally cause exceptions.  The
 details for these instructions are discussed below.
 
 Instruction-based #VE
----------------------
+~~~~~~~~~~~~~~~~~~~~~
 
 - Port I/O (INS, OUTS, IN, OUT)
 - HLT
@@ -41,7 +200,7 @@ Instruction-based #VE
 - CPUID*
 
 Instruction-based #GP
----------------------
+~~~~~~~~~~~~~~~~~~~~~
 
 - All VMX instructions: INVEPT, INVVPID, VMCLEAR, VMFUNC, VMLAUNCH,
   VMPTRLD, VMPTRST, VMREAD, VMRESUME, VMWRITE, VMXOFF, VMXON
@@ -52,7 +211,7 @@ Instruction-based #GP
 - RDMSR*,WRMSR*
 
 RDMSR/WRMSR Behavior
---------------------
+~~~~~~~~~~~~~~~~~~~~
 
 MSR access behavior falls into three categories:
 
@@ -73,7 +232,7 @@ trapping and handling in the TDX module.  Other than possibly being slow,
 these MSRs appear to function just as they would on bare metal.
 
 CPUID Behavior
---------------
+~~~~~~~~~~~~~~
 
 For some CPUID leaves and sub-leaves, the virtualized bit fields of CPUID
 return values (in guest EAX/EBX/ECX/EDX) are configurable by the
@@ -93,7 +252,7 @@ not know how to handle. The guest kernel may ask the hypervisor for the
 value with a hypercall.
 
 #VE on Memory Accesses
-======================
+----------------------
 
 There are essentially two classes of TDX memory: private and shared.
 Private memory receives full TDX protections.  Its content is protected
@@ -107,7 +266,7 @@ entries.  This helps ensure that a guest does not place sensitive
 information in shared memory, exposing it to the untrusted hypervisor.
 
 #VE on Shared Memory
---------------------
+~~~~~~~~~~~~~~~~~~~~
 
 Access to shared mappings can cause a #VE.  The hypervisor ultimately
 controls whether a shared memory access causes a #VE, so the guest must be
@@ -127,7 +286,7 @@ be careful not to access device MMIO regions unless it is also prepared to
 handle a #VE.
 
 #VE on Private Pages
---------------------
+~~~~~~~~~~~~~~~~~~~~
 
 An access to private mappings can also cause a #VE.  Since all kernel
 memory is also private memory, the kernel might theoretically need to
@@ -145,7 +304,7 @@ The hypervisor is permitted to unilaterally move accepted pages to a
 to handle the exception.
 
 Linux #VE handler
-=================
+-----------------
 
 Just like page faults or #GP's, #VE exceptions can be either handled or be
 fatal.  Typically, an unhandled userspace #VE results in a SIGSEGV.
@@ -167,7 +326,7 @@ While the block is in place, any #VE is elevated to a double fault (#DF)
 which is not recoverable.
 
 MMIO handling
-=============
+-------------
 
 In non-TDX VMs, MMIO is usually implemented by giving a guest access to a
 mapping which will cause a VMEXIT on access, and then the hypervisor
@@ -189,7 +348,7 @@ MMIO access via other means (like structure overlays) may result in an
 oops.
 
 Shared Memory Conversions
-=========================
+-------------------------
 
 All TDX guest memory starts out as private at boot.  This memory can not
 be accessed by the hypervisor.  However, some kernel users like device
Signature · 1 line
2.38.1