TDX host kernel support
Subsystems (7)
v14 cover TDX host kernel support
Hi all,
For people who concern this patchset, sorry for sending out late. And to save people's time, I didn't include the full coverletter here this time. For detailed information please refer to previous v13's coverletter[1].
This version mainly adds a new patch to handle TDX vs S3/hibernation interaction. In short, TDX cannot survive when platform goes to S3 and deeper states. TDX gets completely reset upon this, and both TDX guests and TDX module are destroyed. Please refer to the new patch (21).
Other changes from v13 -> v14:
- Addressed comments received in v13 (Rick/Nikolay/Dave).
- SEAMCALL patches, skeleton patch, kexec patch
- Some minor updates based on internal discussion.
- Added received Reviewed-by tags (thanks!).
- Updated the documentation patch to reflect new changes.
Please see each individual patch for specific change history.
Hi Dave,
In this version all patches (except the documentation one) now have at least Kirill's Reviewed-by tag. Could you help to take a look?
And again, thanks everyone for reviewing and helping on this series.
[1]: v13 https://lore.kernel.org/lkml/[email protected]/T/
Kai Huang (23):
x86/virt/tdx: Detect TDX during kernel boot
x86/tdx: Define TDX supported page sizes as macros x86/virt/tdx: Make INTEL_TDX_HOST depend on X86_X2APIC x86/cpu: Detect TDX partial write machine check erratum x86/virt/tdx: Handle SEAMCALL no entropy error in common code x86/virt/tdx: Add SEAMCALL error printing for module initialization x86/virt/tdx: Add skeleton to enable TDX on demand x86/virt/tdx: Get information about TDX module and TDX-capable memory x86/virt/tdx: Use all system memory when initializing TDX module as
TDX memory
x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX
memory regions
x86/virt/tdx: Fill out TDMRs to cover all TDX memory regions x86/virt/tdx: Allocate and set up PAMTs for TDMRs x86/virt/tdx: Designate reserved areas for all TDMRs x86/virt/tdx: Configure TDX module with the TDMRs and global KeyID x86/virt/tdx: Configure global KeyID on all packages x86/virt/tdx: Initialize all TDMRs
x86/kexec: Flush cache of TDX private memory
x86/virt/tdx: Keep TDMRs when module initialization is successful x86/virt/tdx: Improve readability of module initialization error
handling
x86/kexec(): Reset TDX private memory on platforms with TDX erratum x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states x86/mce: Improve error log of kernel space TDX #MC due to erratum Documentation/x86: Add documentation for TDX host support
Documentation/arch/x86/tdx.rst | 217 +++- arch/x86/Kconfig | 3 + arch/x86/coco/tdx/tdx-shared.c | 6 +- arch/x86/include/asm/cpufeatures.h | 1 + arch/x86/include/asm/msr-index.h | 3 + arch/x86/include/asm/shared/tdx.h | 6 + arch/x86/include/asm/tdx.h | 39 + arch/x86/kernel/cpu/intel.c | 17 + arch/x86/kernel/cpu/mce/core.c | 33 + arch/x86/kernel/machine_kexec_64.c | 16 + arch/x86/kernel/process.c | 8 +- arch/x86/kernel/reboot.c | 15 + arch/x86/kernel/setup.c | 2 + arch/x86/virt/vmx/tdx/Makefile | 2 +- arch/x86/virt/vmx/tdx/tdx.c | 1587 ++++++++++++++++++++++++++++ arch/x86/virt/vmx/tdx/tdx.h | 145 +++ 16 files changed, 2084 insertions(+), 16 deletions(-) create mode 100644 arch/x86/virt/vmx/tdx/tdx.c create mode 100644 arch/x86/virt/vmx/tdx/tdx.h
base-commit: 9ee4318c157b9802589b746cc340bae3142d984c
Signature · 1 line
2.41.0
PATCH v14 1/23 x86/virt/tdx: Detect TDX during kernel boot
Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. A CPU-attested software module called 'the TDX module' runs inside a new isolated memory range as a trusted hypervisor to manage and run protected VMs.
Pre-TDX Intel hardware has support for a memory encryption architecture called MKTME. The memory encryption hardware underpinning MKTME is also used for Intel TDX. TDX ends up "stealing" some of the physical address space from the MKTME architecture for crypto-protection to VMs. The BIOS is responsible for partitioning the "KeyID" space between legacy MKTME and TDX. The KeyIDs reserved for TDX are called 'TDX private KeyIDs' or 'TDX KeyIDs' for short.
During machine boot, TDX microcode verifies that the BIOS programmed TDX private KeyIDs consistently and correctly programmed across all CPU packages. The MSRs are locked in this state after verification. This is why MSR_IA32_MKTME_KEYID_PARTITIONING gets used for TDX enumeration:
it indicates not just that the hardware supports TDX, but that all the boot-time security checks passed.
The TDX module is expected to be loaded by the BIOS when it enables TDX, but the kernel needs to properly initialize it before it can be used to create and run any TDX guests. The TDX module will be initialized by the KVM subsystem when KVM wants to use TDX.
Add a new early_initcall(tdx_init) to detect the TDX by detecting TDX private KeyIDs. Also add a function to report whether TDX is enabled by the BIOS. Similar to AMD SME, kexec() will use it to determine whether cache flush is needed.
The TDX module itself requires one TDX KeyID as the 'TDX global KeyID' to protect its metadata. Each TDX guest also needs a TDX KeyID for its own protection. Just use the first TDX KeyID as the global KeyID and leave the rest for TDX guests. If no TDX KeyID is left for TDX guests, disable TDX as initializing the TDX module alone is useless.
---
v13 -> v14:
- "tdx:" -> "virt/tdx:" (internal)
- Add Dave's tag
--- arch/x86/include/asm/msr-index.h | 3 ++ arch/x86/include/asm/tdx.h | 4 ++ arch/x86/virt/vmx/tdx/Makefile | 2 +- arch/x86/virt/vmx/tdx/tdx.c | 90 ++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 arch/x86/virt/vmx/tdx/tdx.c
arch/x86/include/asm/msr-index.h +3 -0
@@ -535,6 +535,9 @@#define MSR_RELOAD_PMC0 0x000014c1#define MSR_RELOAD_FIXED_CTR0 0x00001309 +/* KeyID partitioning between MKTME and TDX */ +#define MSR_IA32_MKTME_KEYID_PARTITIONING 0x00000087 +/* * AMD64 MSRs. Not complete. See the architecture manual for a more * complete list.
arch/x86/include/asm/tdx.h +4 -0
@@ -81,6 +81,10 @@ static inline long tdx_kvm_hypercall(unsigned int nr, unsigned long p1,u64 __seamcall (u64 fn,struct tdx_module_args *args);u64 __seamcall_ret (u64 fn,struct tdx_module_args *args);u64 __seamcall_saved_ret (u64 fn,struct tdx_module_args *args); + +bool platform_tdx_enabled (void ); +#else +static inline bool platform_tdx_enabled (void ) {return false; }#endif /* CONFIG_INTEL_TDX_HOST */ #endif /* !__ASSEMBLY__ */
arch/x86/virt/vmx/tdx/Makefile +1 -1
@@ -1,2 +1,2 @@ # SPDX-License-Identifier: GPL-2.0-only -obj-y += seamcall.o +obj-y += seamcall.o tdx.o
arch/x86/virt/vmx/tdx/tdx.c new file +90 -0
90 lines not on this page · raw message
Signature · 1 line
2.41.0
Re: [PATCH v14 01/23] x86/virt/tdx: Detect TDX during kernel boot
Quoted 36 lines · Kai Huang
Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. A CPU-attested software module called 'the TDX module' runs inside a new isolated memory range as a trusted hypervisor to manage and run protected VMs.
Pre-TDX Intel hardware has support for a memory encryption architecture called MKTME. The memory encryption hardware underpinning MKTME is also used for Intel TDX. TDX ends up "stealing" some of the physical address space from the MKTME architecture for crypto-protection to VMs. The BIOS is responsible for partitioning the "KeyID" space between legacy MKTME and TDX. The KeyIDs reserved for TDX are called 'TDX private KeyIDs' or 'TDX KeyIDs' for short.
During machine boot, TDX microcode verifies that the BIOS programmed TDX private KeyIDs consistently and correctly programmed across all CPU packages. The MSRs are locked in this state after verification. This is why
MSR_IA32_MKTME_KEYID_PARTITIONINGgets used for TDX enumeration:
it indicates not just that the hardware supports TDX, but that all the boot-time security checks passed.The TDX module is expected to be loaded by the BIOS when it enables TDX, but the kernel needs to properly initialize it before it can be used to create and run any TDX guests. The TDX module will be initialized by the KVM subsystem when KVM wants to use TDX.
Add a new
early_initcall(tdx_init)to detect the TDX by detecting TDX private KeyIDs. Also add a function to report whether TDX is enabled by the BIOS. Similar to AMD SME,kexec()will use it to determine whether cache flush is needed.The TDX module itself requires one TDX KeyID as the 'TDX global KeyID' to protect its metadata. Each TDX guest also needs a TDX KeyID for its own protection. Just use the first TDX KeyID as the global KeyID and leave the rest for TDX guests. If no TDX KeyID is left for TDX guests, disable TDX as initializing the TDX module alone is useless.
Quoted 6 lines
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>Reviewed-by Isaku Yamahata <[email protected]>Reviewed-by David Hildenbrand <[email protected]>Reviewed-by Dave Hansen <[email protected]>---
Looks good to me.
Quoted 146 lines
v13 -> v14:
- "tdx:" -> "virt/tdx:" (internal)
- Add Dave's tag--- arch/x86/include/asm/msr-index.h | 3 ++ arch/x86/include/asm/tdx.h | 4 ++ arch/x86/virt/vmx/tdx/Makefile | 2 +- arch/x86/virt/vmx/tdx/tdx.c | 90 ++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 arch/x86/virt/vmx/tdx/tdx.carch/x86/include/asm/msr-index.h +3
-0@@ -535,6 +535,9 @@#define MSR_RELOAD_PMC0 0x000014c1#define MSR_RELOAD_FIXED_CTR0 0x00001309 +/* KeyID partitioning between MKTME and TDX */ +#define MSR_IA32_MKTME_KEYID_PARTITIONING 0x00000087 +/* * AMD64 MSRs. Not complete. See the architecture manual for a more * complete list. arch/x86/include/asm/tdx.h +4
-0@@ -81,6 +81,10 @@ static inline long tdx_kvm_hypercall(unsigned int nr, unsigned long p1,u64 __seamcall (u64 fn,struct tdx_module_args *args);u64 __seamcall_ret (u64 fn,struct tdx_module_args *args);u64 __seamcall_saved_ret (u64 fn,struct tdx_module_args *args); + +bool platform_tdx_enabled (void ); +#else +static inline bool platform_tdx_enabled (void ) {return false; }#endif /* CONFIG_INTEL_TDX_HOST */ #endif /* !__ASSEMBLY__ */ arch/x86/virt/vmx/tdx/Makefile +1
-1@@ -1,2 +1,2 @@ # SPDX-License-Identifier: GPL-2.0-only -obj-y += seamcall.o +obj-y += seamcall.o tdx.oarch/x86/virt/vmx/tdx/tdx.c new file +90
-0@@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Copyright(c) 2023 Intel Corporation. +* +* Intel Trusted Domain Extensions (TDX) support +*/ + +#define pr_fmt (fmt) "virt/tdx: " fmt + +#include <linux/types.h> +#include <linux/cache.h> +#include <linux/init.h> +#include <linux/errno.h> +#include <linux/printk.h> +#include <asm/msr-index.h> +#include <asm/msr.h> +#include <asm/tdx.h> + +static u32 tdx_global_keyid__ro_after_init ; +static u32 tdx_guest_keyid_start__ro_after_init ; +static u32 tdx_nr_guest_keyids__ro_after_init ; + +static int __init record_keyid_partitioning (u32 *tdx_keyid_start, +u32 *nr_tdx_keyids) +{ +u32 _nr_mktme_keyids, _tdx_keyid_start, _nr_tdx_keyids; +int ret; + +/* +* IA32_MKTME_KEYID_PARTIONING: +* Bit [31:0]: Number of MKTME KeyIDs. +* Bit [63:32]: Number of TDX private KeyIDs. +*/ + ret =rdmsr_safe (MSR_IA32_MKTME_KEYID_PARTITIONING , &_nr_mktme_keyids, + &_nr_tdx_keyids); +if (ret) +return -ENODEV ; + +if (!_nr_tdx_keyids) +return -ENODEV ; + +/* TDX KeyIDs start after the last MKTME KeyID. */ + _tdx_keyid_start = _nr_mktme_keyids +1 ; + + *tdx_keyid_start = _tdx_keyid_start; + *nr_tdx_keyids = _nr_tdx_keyids; + +return 0 ; +} + +static int __init tdx_init (void ) +{ +u32 tdx_keyid_start, nr_tdx_keyids; +int err; + + err =record_keyid_partitioning (&tdx_keyid_start, &nr_tdx_keyids); +if (err) +return err; + +pr_info ("BIOS enabled: private KeyID range [%u, %u)\n" , + tdx_keyid_start, tdx_keyid_start + nr_tdx_keyids); + +/* +* The TDX module itself requires one 'global KeyID' to protect +* its metadata. If there's only one TDX KeyID, there won't be +* any left for TDX guests thus there's no point to enable TDX +* at all. +*/ +if (nr_tdx_keyids <2 ) { +pr_err ("initialization failed: too few private KeyIDs available.\n" ); +return -ENODEV ; + } + +/* +* Just use the first TDX KeyID as the 'global KeyID' and +* leave the rest for TDX guests. +*/ + tdx_global_keyid = tdx_keyid_start; + tdx_guest_keyid_start = tdx_keyid_start +1 ; + tdx_nr_guest_keyids = nr_tdx_keyids -1 ; + +return 0 ; +} +early_initcall (tdx_init); + +/* Return whether the BIOS has enabled TDX */ +bool platform_tdx_enabled (void ) +{ +return !!tdx_global_keyid; +}
Signature · 2 lines
Sathyanarayanan Kuppuswamy Linux Kernel Developer
PATCH v14 2/23 x86/tdx: Define TDX supported page sizes as macros
In reply to Kai HuangTDX supports 4K, 2M and 1G page sizes. The corresponding values are defined by the TDX module spec and used as TDX module ABI. Currently, they are used in try_accept_one() when the TDX guest tries to accept a page. However currently try_accept_one() uses hard-coded magic values.
Define TDX supported page sizes as macros and get rid of the hard-coded values in try_accept_one(). TDX host support will need to use them too.
--- arch/x86/coco/tdx/tdx-shared.c | 6 +++--- arch/x86/include/asm/shared/tdx.h | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-)
arch/x86/coco/tdx/tdx-shared.c +3 -3
@@ -22,13 +22,13 @@ static unsigned long try_accept_one(phys_addr_t start, unsigned long len,*/ switch (pg_level) {case PG_LEVEL_4K : - page_size =0 ; + page_size =TDX_PS_4K ;break ;case PG_LEVEL_2M : - page_size =1 ; + page_size =TDX_PS_2M ;break ;case PG_LEVEL_1G : - page_size =2 ; + page_size =TDX_PS_1G ;break ;default :return 0 ;
arch/x86/include/asm/shared/tdx.h +5 -0
@@ -54,6 +54,11 @@ (TDX_RDX |TDX_RBX |TDX_RSI |TDX_RDI |TDX_R8 |TDX_R9 | \TDX_R10 |TDX_R11 |TDX_R12 |TDX_R13 |TDX_R14 |TDX_R15 ) +/* TDX supported page sizes from the TDX module ABI. */ +#define TDX_PS_4K 0 +#define TDX_PS_2M 1 +#define TDX_PS_1G 2 +#ifndef __ASSEMBLY__#include <linux/compiler_attributes.h>
Signature · 1 line
2.41.0
PATCH v14 3/23 x86/virt/tdx: Make INTEL_TDX_HOST depend on X86_X2APIC
In reply to Kai HuangTDX capable platforms are locked to X2APIC mode and cannot fall back to the legacy xAPIC mode when TDX is enabled by the BIOS. TDX host support requires x2APIC. Make INTEL_TDX_HOST depend on X86_X2APIC.
--- arch/x86/Kconfig | 1 + 1 file changed, 1 insertion(+)
arch/x86/Kconfig +1 -0
@@ -1944,6 +1944,7 @@ config INTEL_TDX_HOST depends on CPU_SUP_INTEL depends on X86_64 depends on KVM_INTEL + depends on X86_X2APIC help Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. This option enables necessary TDX
Signature · 1 line
2.41.0
PATCH v14 4/23 x86/cpu: Detect TDX partial write machine check erratum
In reply to Kai HuangTDX memory has integrity and confidentiality protections. Violations of this integrity protection are supposed to only affect TDX operations and are never supposed to affect the host kernel itself. In other words, the host kernel should never, itself, see machine checks induced by the TDX integrity hardware.
Alas, the first few generations of TDX hardware have an erratum. A partial write to a TDX private memory cacheline will silently "poison" the line. Subsequent reads will consume the poison and generate a machine check. According to the TDX hardware spec, neither of these things should have happened.
Virtually all kernel memory accesses operations happen in full cachelines. In practice, writing a "byte" of memory usually reads a 64 byte cacheline of memory, modifies it, then writes the whole line back. Those operations do not trigger this problem.
This problem is triggered by "partial" writes where a write transaction of less than cacheline lands at the memory controller. The CPU does these via non-temporal write instructions (like MOVNTI), or through UC/WC memory mappings. The issue can also be triggered away from the CPU by devices doing partial writes via DMA.
With this erratum, there are additional things need to be done. To prepare for those changes, add a CPU bug bit to indicate this erratum. Note this bug reflects the hardware thus it is detected regardless of whether the kernel is built with TDX support or not.
---
v13 -> v14:
- Use "To prepare for ___, add ___" in changelog (Dave)
- Added Dave's tag.
v12 -> v13:
- Added David's tag.
v11 -> v12:
- Added Kirill's tag
- Changed to detect the erratum in early_init_intel() (Kirill)
v10 -> v11:
- New patch
--- arch/x86/include/asm/cpufeatures.h | 1 + arch/x86/kernel/cpu/intel.c | 17 +++++++++++++++++ 2 files changed, 18 insertions(+)
arch/x86/include/asm/cpufeatures.h +1 -0
@@ -494,6 +494,7 @@#define X86_BUG_EIBRS_PBRSB X86_BUG(28)/* EIBRS is vulnerable to Post Barrier RSB Predictions */ #define X86_BUG_SMT_RSB X86_BUG(29)/* CPU is vulnerable to Cross-Thread Return Address Predictions */ #define X86_BUG_GDS X86_BUG(30)/* CPU is affected by Gather Data Sampling */ +#define X86_BUG_TDX_PW_MCE X86_BUG(31)/* CPU may incur #MC if non-TD software does partial write to TDX private memory */ /* BUG word 2 */ #define X86_BUG_SRSO X86_BUG(1*32 + 0)/* AMD SRSO bug */
arch/x86/kernel/cpu/intel.c +17 -0
@@ -184,6 +184,21 @@ static bool bad_spectre_microcode(struct cpuinfo_x86 *c)return false; } +static void check_tdx_erratum (struct cpuinfo_x86 *c) +{ +/* +* These CPUs have an erratum. A partial write from non-TD +* software (e.g. via MOVNTI variants or UC/WC mapping) to TDX +* private memory poisons that memory, and a subsequent read of +* that memory triggers #MC. +*/ +switch (c->x86_model) { +case INTEL_FAM6_SAPPHIRERAPIDS_X : +case INTEL_FAM6_EMERALDRAPIDS_X : +setup_force_cpu_bug (X86_BUG_TDX_PW_MCE ); + } +} +static void early_init_intel (struct cpuinfo_x86 *c) {u64 misc_enable;
@@ -335,6 +350,8 @@ static void early_init_intel(struct cpuinfo_x86 *c)*/ if (detect_extended_topology_early (c) <0 )detect_ht_early (c); + +check_tdx_erratum (c); }static void bsp_init_intel (struct cpuinfo_x86 *c)
Signature · 1 line
2.41.0
PATCH v14 5/23 x86/virt/tdx: Handle SEAMCALL no entropy error in common code
In reply to Kai HuangSome SEAMCALLs use the RDRAND hardware and can fail for the same reasons as RDRAND. Use the kernel RDRAND retry logic for them.
There are three __seamcall*() variants. Do the SEAMCALL retry in common code and add a wrapper for each of them.
---
v13 -> v14:
- Use real function sc_retry() instead of using macros. (Dave)
- Added Kirill's tag.
v12 -> v13:
- New implementation due to TDCALL assembly series.
--- arch/x86/include/asm/tdx.h | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+)
arch/x86/include/asm/tdx.h +26 -0
@@ -24,6 +24,11 @@#define TDX_SEAMCALL_GP (TDX_SW_ERROR | X86_TRAP_GP)#define TDX_SEAMCALL_UD (TDX_SW_ERROR | X86_TRAP_UD) +/* +* TDX module SEAMCALL leaf function error codes +*/ +#define TDX_RND_NO_ENTROPY 0x8000020300000000ULL +#ifndef __ASSEMBLY__/*
@@ -82,6 +87,27 @@ u64 __seamcall(u64 fn, struct tdx_module_args *args);u64 __seamcall_ret (u64 fn,struct tdx_module_args *args);u64 __seamcall_saved_ret (u64 fn,struct tdx_module_args *args); +#include <asm/archrandom.h> + +typedef u64 (*sc_func_t )(u64 fn,struct tdx_module_args *args); + +static inline u64 sc_retry (sc_func_t func,u64 fn, +struct tdx_module_args *args) +{ +int retry =RDRAND_RETRY_LOOPS ; +u64 ret; + +do { + ret =func (fn, args); + }while (ret ==TDX_RND_NO_ENTROPY && --retry); + +return ret; +} + +#define seamcall (_fn, _args) sc_retry(__seamcall, (_fn), (_args)) +#define seamcall_ret (_fn, _args) sc_retry(__seamcall_ret, (_fn), (_args)) +#define seamcall_saved_ret (_fn, _args) sc_retry(__seamcall_saved_ret, (_fn), (_args)) +bool platform_tdx_enabled (void );#else static inline bool platform_tdx_enabled (void ) {return false; }
Signature · 1 line
2.41.0
Re: [PATCH v14 05/23] x86/virt/tdx: Handle SEAMCALL no entropy error in common code
Quoted 10 lines · Kai Huang
Some SEAMCALLs use the RDRAND hardware and can fail for the same reasons as RDRAND. Use the kernel RDRAND retry logic for them.
There are three __seamcall*() variants. Do the SEAMCALL retry in common code and add a wrapper for each of them.
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>---
Quoted 7 lines
v13 -> v14:
- Use real functionsc_retry()instead of using macros. (Dave)
- Added Kirill's tag.v12 -> v13:
- New implementation due to TDCALL assembly series.
---
Quoted 47 lines
arch/x86/include/asm/tdx.h | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+)arch/x86/include/asm/tdx.h +26
-0@@ -24,6 +24,11 @@#define TDX_SEAMCALL_GP (TDX_SW_ERROR | X86_TRAP_GP)#define TDX_SEAMCALL_UD (TDX_SW_ERROR | X86_TRAP_UD) +/* +* TDX module SEAMCALL leaf function error codes +*/ +#define TDX_RND_NO_ENTROPY 0x8000020300000000ULL +#ifndef __ASSEMBLY__/* @@ -82,6 +87,27 @@ u64 __seamcall(u64 fn, struct tdx_module_args *args);u64 __seamcall_ret (u64 fn,struct tdx_module_args *args);u64 __seamcall_saved_ret (u64 fn,struct tdx_module_args *args); +#include <asm/archrandom.h> + +typedef u64 (*sc_func_t )(u64 fn,struct tdx_module_args *args); + +static inline u64 sc_retry (sc_func_t func,u64 fn, +struct tdx_module_args *args) +{ +int retry =RDRAND_RETRY_LOOPS ; +u64 ret; + +do { + ret =func (fn, args); + }while (ret ==TDX_RND_NO_ENTROPY && --retry); + +return ret; +} + +#define seamcall (_fn, _args) sc_retry(__seamcall, (_fn), (_args)) +#define seamcall_ret (_fn, _args) sc_retry(__seamcall_ret, (_fn), (_args)) +#define seamcall_saved_ret (_fn, _args) sc_retry(__seamcall_saved_ret, (_fn), (_args)) +bool platform_tdx_enabled (void );#else static inline bool platform_tdx_enabled (void ) {return false; }
Signature · 2 lines
Sathyanarayanan Kuppuswamy Linux Kernel Developer
PATCH v14 6/23 x86/virt/tdx: Add SEAMCALL error printing for module initialization
In reply to Kai HuangThe SEAMCALLs involved during the TDX module initialization are not expected to fail. In fact, they are not expected to return any non-zero code (except the "running out of entropy error", which can be handled internally already).
Add yet another set of SEAMCALL wrappers, which treats all non-zero return code as error, to support printing SEAMCALL error upon failure for module initialization. Note the TDX module initialization doesn't use the _saved_ret() variant thus no wrapper is added for it.
SEAMCALL assembly can also return kernel-defined error codes for three special cases: 1) TDX isn't enabled by the BIOS; 2) TDX module isn't loaded; 3) CPU isn't in VMX operation. Whether they can legally happen depends on the caller, so leave to the caller to print error message when desired.
Also convert the SEAMCALL error codes to the kernel error codes in the new wrappers so that each SEAMCALL caller doesn't have to repeat the conversion.
---
v13 -> v14:
- Use real functions to replace macros. (Dave)
- Moved printing error message for special error code to the caller (internal)
- Added Kirill's tag
v12 -> v13:
- New implementation due to TDCALL assembly series.
--- arch/x86/include/asm/tdx.h | 1 + arch/x86/virt/vmx/tdx/tdx.c | 52 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+)
arch/x86/include/asm/tdx.h +1 -0
@@ -27,6 +27,7 @@/* * TDX module SEAMCALL leaf function error codes */ +#define TDX_SUCCESS 0ULL#define TDX_RND_NO_ENTROPY 0x8000020300000000ULL#ifndef __ASSEMBLY__
arch/x86/virt/vmx/tdx/tdx.c +52 -0
58 lines not on this page · raw message
Signature · 1 line
2.41.0
Re: [PATCH v14 06/23] x86/virt/tdx: Add SEAMCALL error printing for module initialization
Quoted 55 lines · Kai Huang
The SEAMCALLs involved during the TDX module initialization are not expected to fail. In fact, they are not expected to return any non-zero code (except the "running out of entropy error", which can be handled internally already).
Add yet another set of SEAMCALL wrappers, which treats all non-zero return code as error, to support printing SEAMCALL error upon failure for module initialization. Note the TDX module initialization doesn't use the
_saved_ret()variant thus no wrapper is added for it.SEAMCALL assembly can also return kernel-defined error codes for three special cases: 1) TDX isn't enabled by the BIOS; 2) TDX module isn't loaded; 3) CPU isn't in VMX operation. Whether they can legally happen depends on the caller, so leave to the caller to print error message when desired.
Also convert the SEAMCALL error codes to the kernel error codes in the new wrappers so that each SEAMCALL caller doesn't have to repeat the conversion.
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>---
v13 -> v14:
- Use real functions to replace macros. (Dave)
- Moved printing error message for special error code to the caller (internal)
- Added Kirill's tagv12 -> v13:
- New implementation due to TDCALL assembly series.--- arch/x86/include/asm/tdx.h | 1 + arch/x86/virt/vmx/tdx/tdx.c | 52 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+)arch/x86/include/asm/tdx.h +1
-0@@ -27,6 +27,7 @@/* * TDX module SEAMCALL leaf function error codes */ +#define TDX_SUCCESS 0ULL#define TDX_RND_NO_ENTROPY 0x8000020300000000ULL#ifndef __ASSEMBLY__arch/x86/virt/vmx/tdx/tdx.c +0
-0
arch/x86/virt/vmx/tdx/tdx.c static u32 tdx_global_keyid __ro_after_init; · line 29
Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +7
-0@@ -20,6 +20,58 @@ static u32 tdx_global_keyid __ro_after_init;static u32 tdx_guest_keyid_start__ro_after_init ;static u32 tdx_nr_guest_keyids__ro_after_init ; +typedef void (*sc_err_func_t )(u64 fn,u64 err,struct tdx_module_args *args); + +static inline void seamcall_err (u64 fn,u64 err,struct tdx_module_args *args) +{ +pr_err ("SEAMCALL (0x%llx) failed: 0x%llx\n" , fn, err); +} +
Why pass args here?
Quoted 48 lines
arch/x86/virt/vmx/tdx/tdx.c +45
-0+static inline void seamcall_err_ret (u64 fn,u64 err, +struct tdx_module_args *args) +{ +seamcall_err (fn, err, args); +pr_err ("RCX 0x%llx RDX 0x%llx R8 0x%llx R9 0x%llx R10 0x%llx R11 0x%llx\n" , + args->rcx, args->rdx, args->r8, args->r9, + args->r10, args->r11); +} + +static inline void seamcall_err_saved_ret (u64 fn,u64 err, +struct tdx_module_args *args) +{ +seamcall_err_ret (fn, err, args); +pr_err ("RBX 0x%llx RDI 0x%llx RSI 0x%llx R12 0x%llx R13 0x%llx R14 0x%llx R15 0x%llx\n" , + args->rbx, args->rdi, args->rsi, args->r12, + args->r13, args->r14, args->r15); +} + +static inline int sc_retry_prerr (sc_func_t func,sc_err_func_t err_func, +u64 fn,struct tdx_module_args *args) +{ +u64 sret =sc_retry (func, fn, args); + +if (sret ==TDX_SUCCESS ) +return 0 ; + +if (sret ==TDX_SEAMCALL_VMFAILINVALID ) +return -ENODEV ; + +if (sret ==TDX_SEAMCALL_GP ) +return -EOPNOTSUPP ; + +if (sret ==TDX_SEAMCALL_UD ) +return -EACCES ; + +err_func (fn, sret, args); +return -EIO ; +} + +#define seamcall_prerr (__fn, __args) \ + sc_retry_prerr(__seamcall, seamcall_err, (__fn), (__args)) + +#define seamcall_prerr_ret (__fn, __args) \ + sc_retry_prerr(__seamcall_ret, seamcall_err_ret, (__fn), (__args)) +static int __init record_keyid_partitioning (u32 *tdx_keyid_start,u32 *nr_tdx_keyids) {
Signature · 2 lines
Sathyanarayanan Kuppuswamy Linux Kernel Developer
Re: [PATCH v14 06/23] x86/virt/tdx: Add SEAMCALL error printing for module initialization
Quoted 11 lines
arch/x86/virt/vmx/tdx/tdx.c static u32 tdx_global_keyid __ro_after_init; · line 29
Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +7
-0+typedef void (*sc_err_func_t )(u64 fn,u64 err,struct tdx_module_args *args); + +static inline void seamcall_err (u64 fn,u64 err,struct tdx_module_args *args) +{ +pr_err ("SEAMCALL (0x%llx) failed: 0x%llx\n" , fn, err); +} +Why pass args here?
It needs to be sc_err_func_t so that it can be used by the common code sc_retry_prerr() below.
Quoted 50 lines
Quoted 49 lines
arch/x86/virt/vmx/tdx/tdx.c +45
-0+static inline void seamcall_err_ret (u64 fn,u64 err, +struct tdx_module_args *args) +{ +seamcall_err (fn, err, args); +pr_err ("RCX 0x%llx RDX 0x%llx R8 0x%llx R9 0x%llx R10 0x%llx R11 0x%llx\n" , + args->rcx, args->rdx, args->r8, args->r9, + args->r10, args->r11); +} + +static inline void seamcall_err_saved_ret (u64 fn,u64 err, +struct tdx_module_args *args) +{ +seamcall_err_ret (fn, err, args); +pr_err ("RBX 0x%llx RDI 0x%llx RSI 0x%llx R12 0x%llx R13 0x%llx R14 0x%llx R15 0x%llx\n" , + args->rbx, args->rdi, args->rsi, args->r12, + args->r13, args->r14, args->r15); +} + +static inline int sc_retry_prerr (sc_func_t func,sc_err_func_t err_func, +u64 fn,struct tdx_module_args *args) +{ +u64 sret =sc_retry (func, fn, args); + +if (sret ==TDX_SUCCESS ) +return 0 ; + +if (sret ==TDX_SEAMCALL_VMFAILINVALID ) +return -ENODEV ; + +if (sret ==TDX_SEAMCALL_GP ) +return -EOPNOTSUPP ; + +if (sret ==TDX_SEAMCALL_UD ) +return -EACCES ; + +err_func (fn, sret, args); +return -EIO ; +} + +#define seamcall_prerr (__fn, __args) \ + sc_retry_prerr(__seamcall, seamcall_err, (__fn), (__args)) + +#define seamcall_prerr_ret (__fn, __args) \ + sc_retry_prerr(__seamcall_ret, seamcall_err_ret, (__fn), (__args)) +static int __init record_keyid_partitioning (u32 *tdx_keyid_start,u32 *nr_tdx_keyids) {
Re: [PATCH v14 06/23] x86/virt/tdx: Add SEAMCALL error printing for module initialization
In reply to Kai HuangQuoted 66 lines · Kai Huang
The SEAMCALLs involved during the TDX module initialization are not expected to fail. In fact, they are not expected to return any non-zero code (except the "running out of entropy error", which can be handled internally already).
Add yet another set of SEAMCALL wrappers, which treats all non-zero return code as error, to support printing SEAMCALL error upon failure for module initialization. Note the TDX module initialization doesn't use the
_saved_ret()variant thus no wrapper is added for it.SEAMCALL assembly can also return kernel-defined error codes for three special cases: 1) TDX isn't enabled by the BIOS; 2) TDX module isn't loaded; 3) CPU isn't in VMX operation. Whether they can legally happen depends on the caller, so leave to the caller to print error message when desired.
Also convert the SEAMCALL error codes to the kernel error codes in the new wrappers so that each SEAMCALL caller doesn't have to repeat the conversion.
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>---
v13 -> v14:
- Use real functions to replace macros. (Dave)
- Moved printing error message for special error code to the caller (internal)
- Added Kirill's tagv12 -> v13:
- New implementation due to TDCALL assembly series.--- arch/x86/include/asm/tdx.h | 1 + arch/x86/virt/vmx/tdx/tdx.c | 52 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+)arch/x86/include/asm/tdx.h +1
-0@@ -27,6 +27,7 @@/* * TDX module SEAMCALL leaf function error codes */ +#define TDX_SUCCESS 0ULL#define TDX_RND_NO_ENTROPY 0x8000020300000000ULL#ifndef __ASSEMBLY__arch/x86/virt/vmx/tdx/tdx.c +8
-0@@ -20,6 +20,58 @@ static u32 tdx_global_keyid __ro_after_init;static u32 tdx_guest_keyid_start__ro_after_init ;static u32 tdx_nr_guest_keyids__ro_after_init ; +typedef void (*sc_err_func_t )(u64 fn,u64 err,struct tdx_module_args *args); + +static inline void seamcall_err (u64 fn,u64 err,struct tdx_module_args *args) +{ +pr_err ("SEAMCALL (0x%llx) failed: 0x%llx\n" , fn, err); +} + +static inline void seamcall_err_ret(u64 fn, u64 err,
arch/x86/virt/vmx/tdx/tdx.c static u32 tdx_global_keyid __ro_after_init; · line 40
Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10
-0+ struct tdx_module_args *args) +{ +seamcall_err (fn, err, args); +pr_err ("RCX 0x%llx RDX 0x%llx R8 0x%llx R9 0x%llx R10 0x%llx R11 0x%llx\n" , + args->rcx, args->rdx, args->r8, args->r9, + args->r10, args->r11); +} + +static inline void seamcall_err_saved_ret (u64 fn,u64 err, +struct tdx_module_args *args)
This function remains unused throughout the whole series, remove it and add it later when it's actually going to be useful.
<snip>
Re: [PATCH v14 06/23] x86/virt/tdx: Add SEAMCALL error printing for module initialization
Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c static u32 tdx_global_keyid __ro_after_init; · line 40
Quoted 4 lines
arch/x86/virt/vmx/tdx/tdx.c +3
-0+ +static inline void seamcall_err_saved_ret (u64 fn,u64 err, +struct tdx_module_args *args)This function remains unused throughout the whole series, remove it and add it later when it's actually going to be useful.
<snip>
OK fine to me. Thanks.
Re: [PATCH v14 06/23] x86/virt/tdx: Add SEAMCALL error printing for module initialization
In reply to Kai HuangQuoted 30 lines · Kai Huang
The SEAMCALLs involved during the TDX module initialization are not expected to fail. In fact, they are not expected to return any non-zero code (except the "running out of entropy error", which can be handled internally already).
Add yet another set of SEAMCALL wrappers, which treats all non-zero return code as error, to support printing SEAMCALL error upon failure for module initialization. Note the TDX module initialization doesn't use the
_saved_ret()variant thus no wrapper is added for it.SEAMCALL assembly can also return kernel-defined error codes for three special cases: 1) TDX isn't enabled by the BIOS; 2) TDX module isn't loaded; 3) CPU isn't in VMX operation. Whether they can legally happen depends on the caller, so leave to the caller to print error message when desired.
Also convert the SEAMCALL error codes to the kernel error codes in the new wrappers so that each SEAMCALL caller doesn't have to repeat the conversion.
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>---
v13 -> v14:
- Use real functions to replace macros. (Dave)
- Moved printing error message for special error code to the caller (internal)
- Added Kirill's tag
Quoted 4 lines
v12 -> v13:
- New implementation due to TDCALL assembly series.---
Signature · 2 lines
Sathyanarayanan Kuppuswamy Linux Kernel Developer
PATCH v14 7/23 x86/virt/tdx: Add skeleton to enable TDX on demand
In reply to Kai HuangTo enable TDX the kernel needs to initialize TDX from two perspectives:
1) Do a set of SEAMCALLs to initialize the TDX module to make it ready to create and run TDX guests; 2) Do the per-cpu initialization SEAMCALL on one logical cpu before the kernel wants to make any other SEAMCALLs on that cpu (including those involved during module initialization and running TDX guests).
The TDX module can be initialized only once in its lifetime. Instead of always initializing it at boot time, this implementation chooses an "on demand" approach to initialize TDX until there is a real need (e.g when requested by KVM). This approach has below pros:
1) It avoids consuming the memory that must be allocated by kernel and given to the TDX module as metadata (~1/256th of the TDX-usable memory), and also saves the CPU cycles of initializing the TDX module (and the metadata) when TDX is not used at all.
2) The TDX module design allows it to be updated while the system is running. The update procedure shares quite a few steps with this "on demand" initialization mechanism. The hope is that much of "on demand" mechanism can be shared with a future "update" mechanism. A boot-time TDX module implementation would not be able to share much code with the update mechanism.
3) Making SEAMCALL requires VMX to be enabled. Currently, only the KVM code mucks with VMX enabling. If the TDX module were to be initialized separately from KVM (like at boot), the boot code would need to be taught how to muck with VMX enabling and KVM would need to be taught how to cope with that. Making KVM itself responsible for TDX initialization lets the rest of the kernel stay blissfully unaware of VMX.
Similar to module initialization, also make the per-cpu initialization "on demand" as it also depends on VMX being enabled.
Add two functions, tdx_enable() and tdx_cpu_enable(), to enable the TDX module and enable TDX on local cpu respectively. For now tdx_enable() is a placeholder. The TODO list will be pared down as functionality is added.
Export both tdx_cpu_enable() and tdx_enable() for KVM use.
In tdx_enable() use a state machine protected by mutex to make sure the initialization will only be done once, as tdx_enable() can be called multiple times (i.e. KVM module can be reloaded) and may be called concurrently by other kernel components in the future.
The per-cpu initialization on each cpu can only be done once during the module's life time. Use a per-cpu variable to track its status to make sure it is only done once in tdx_cpu_enable().
Also, a SEAMCALL to do TDX module global initialization must be done once on any logical cpu before any per-cpu initialization SEAMCALL. Do it inside tdx_cpu_enable() too (if hasn't been done).
tdx_enable() can potentially invoke SEAMCALLs on any online cpus. The per-cpu initialization must be done before those SEAMCALLs are invoked on some cpu. To keep things simple, in tdx_cpu_enable(), always do the per-cpu initialization regardless of whether the TDX module has been initialized or not. And in tdx_enable(), don't call tdx_cpu_enable() but assume the caller has disabled CPU hotplug, done VMXON and tdx_cpu_enable() on all online cpus before calling tdx_enable().
---
v13 -> v14:
- Use lockdep_assert_irqs_off() in try_init_model_global() (Nikolay), but still keep the comment (Kirill).
- Add code to print "module not loaded" in the first SEAMCALL.
- If SYS.INIT fails, stop calling LP.INIT in other tdx_cpu_enable()s.
- Added Kirill's tag
v12 -> v13:
- Made tdx_cpu_enable() always be called with IRQ disabled via IPI funciton call (Peter, Kirill).
v11 -> v12:
- Simplified TDX module global init and lp init status tracking (David).
- Added comment around try_init_module_global() for using raw_spin_lock() (Dave).
- Added one sentence to changelog to explain why to expose tdx_enable() and tdx_cpu_enable() (Dave).
- Simplifed comments around tdx_enable() and tdx_cpu_enable() to use lockdep_assert_*() instead. (Dave)
- Removed redundent "TDX" in error message (Dave).
v10 -> v11:
- Return -NODEV instead of -EINVAL when CONFIG_INTEL_TDX_HOST is off.
- Return the actual error code for tdx_enable() instead of -EINVAL.
- Added Isaku's Reviewed-by.
v9 -> v10:
- Merged the patch to handle per-cpu initialization to this patch to tell the story better.
- Changed how to handle the per-cpu initialization to only provide a tdx_cpu_enable() function to let the user of TDX to do it when the user wants to run TDX code on a certain cpu.
- Changed tdx_enable() to not call cpus_read_lock() explicitly, but call lockdep_assert_cpus_held() to assume the caller has done that.
- Improved comments around tdx_enable() and tdx_cpu_enable().
- Improved changelog to tell the story better accordingly.
v8 -> v9:
- Removed detailed TODO list in the changelog (Dave).
- Added back steps to do module global initialization and per-cpu initialization in the TODO list comment.
- Moved the 'enum tdx_module_status_t' from tdx.c to local tdx.h
v7 -> v8:
- Refined changelog (Dave).
- Removed "all BIOS-enabled cpus" related code (Peter/Thomas/Dave).
- Add a "TODO list" comment in init_tdx_module() to list all steps of initializing the TDX Module to tell the story (Dave).
- Made tdx_enable() unverisally return -EINVAL, and removed nonsense comments (Dave).
- Simplified __tdx_enable() to only handle success or failure.
- TDX_MODULE_SHUTDOWN -> TDX_MODULE_ERROR
- Removed TDX_MODULE_NONE (not loaded) as it is not necessary.
- Improved comments (Dave).
- Pointed out 'tdx_module_status' is software thing (Dave).
...
--- arch/x86/include/asm/tdx.h | 4 + arch/x86/virt/vmx/tdx/tdx.c | 167 ++++++++++++++++++++++++++++++++++++ arch/x86/virt/vmx/tdx/tdx.h | 30 +++++++ 3 files changed, 201 insertions(+) create mode 100644 arch/x86/virt/vmx/tdx/tdx.h
arch/x86/include/asm/tdx.h +4 -0
@@ -110,8 +110,12 @@ static inline u64 sc_retry(sc_func_t func, u64 fn,#define seamcall_saved_ret (_fn, _args) sc_retry(__seamcall_saved_ret, (_fn), (_args))bool platform_tdx_enabled (void ); +int tdx_cpu_enable (void ); +int tdx_enable (void );#else static inline bool platform_tdx_enabled (void ) {return false; } +static inline int tdx_cpu_enable (void ) {return -ENODEV ; } +static inline int tdx_enable (void ) {return -ENODEV ; }#endif /* CONFIG_INTEL_TDX_HOST */ #endif /* !__ASSEMBLY__ */
arch/x86/virt/vmx/tdx/tdx.c +167 -0
187 lines not on this page · raw message
arch/x86/virt/vmx/tdx/tdx.h new file +30 -0
@@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _X86_VIRT_TDX_H +#define _X86_VIRT_TDX_H + +/* +* This file contains both macros and data structures defined by the TDX +* architecture and Linux defined software data structures and functions. +* The two should not be mixed together for better readability. The +* architectural definitions come first. +*/ + +/* +* TDX module SEAMCALL leaf functions +*/ +#define TDH_SYS_INIT 33 +#define TDH_SYS_LP_INIT 35 + +/* +* Do not put any hardware-defined TDX structure representations below +* this comment! +*/ + +/* Kernel defined TDX module status during module initialization. */ +enum tdx_module_status_t { +TDX_MODULE_UNINITIALIZED , +TDX_MODULE_INITIALIZED , +TDX_MODULE_ERROR +}; + +#endif
Signature · 1 line
2.41.0
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 192 lines · Kai Huang
To enable TDX the kernel needs to initialize TDX from two perspectives:
1) Do a set of SEAMCALLs to initialize the TDX module to make it ready to create and run TDX guests; 2) Do the per-cpu initialization SEAMCALL on one logical cpu before the kernel wants to make any other SEAMCALLs on that cpu (including those involved during module initialization and running TDX guests).The TDX module can be initialized only once in its lifetime. Instead of always initializing it at boot time, this implementation chooses an "on demand" approach to initialize TDX until there is a real need (e.g when requested by KVM). This approach has below pros:
1) It avoids consuming the memory that must be allocated by kernel and given to the TDX module as metadata (~1/256th of the TDX-usable memory), and also saves the CPU cycles of initializing the TDX module (and the metadata) when TDX is not used at all.
2) The TDX module design allows it to be updated while the system is running. The update procedure shares quite a few steps with this "on demand" initialization mechanism. The hope is that much of "on demand" mechanism can be shared with a future "update" mechanism. A boot-time TDX module implementation would not be able to share much code with the update mechanism.
3) Making SEAMCALL requires VMX to be enabled. Currently, only the KVM code mucks with VMX enabling. If the TDX module were to be initialized separately from KVM (like at boot), the boot code would need to be taught how to muck with VMX enabling and KVM would need to be taught how to cope with that. Making KVM itself responsible for TDX initialization lets the rest of the kernel stay blissfully unaware of VMX.
Similar to module initialization, also make the per-cpu initialization "on demand" as it also depends on VMX being enabled.
Add two functions,
tdx_enable()andtdx_cpu_enable(), to enable the TDX module and enable TDX on local cpu respectively. For nowtdx_enable()is a placeholder. The TODO list will be pared down as functionality is added.Export both
tdx_cpu_enable()andtdx_enable()for KVM use.In
tdx_enable()use a state machine protected by mutex to make sure the initialization will only be done once, astdx_enable()can be called multiple times (i.e. KVM module can be reloaded) and may be called concurrently by other kernel components in the future.The per-cpu initialization on each cpu can only be done once during the module's life time. Use a per-cpu variable to track its status to make sure it is only done once in
tdx_cpu_enable().Also, a SEAMCALL to do TDX module global initialization must be done once on any logical cpu before any per-cpu initialization SEAMCALL. Do it inside
tdx_cpu_enable()too (if hasn't been done).
tdx_enable()can potentially invoke SEAMCALLs on any online cpus. The per-cpu initialization must be done before those SEAMCALLs are invoked on some cpu. To keep things simple, intdx_cpu_enable(), always do the per-cpu initialization regardless of whether the TDX module has been initialized or not. And intdx_enable(), don't calltdx_cpu_enable()but assume the caller has disabled CPU hotplug, done VMXON andtdx_cpu_enable()on all online cpus before callingtdx_enable().Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>---
v13 -> v14:
- Uselockdep_assert_irqs_off()intry_init_model_global()(Nikolay), but still keep the comment (Kirill).
- Add code to print "module not loaded" in the first SEAMCALL.
- If SYS.INIT fails, stop calling LP.INIT in other tdx_cpu_enable()s.
- Added Kirill's tagv12 -> v13:
- Madetdx_cpu_enable()always be called with IRQ disabled via IPI funciton call (Peter, Kirill).v11 -> v12:
- Simplified TDX module global init and lp init status tracking (David).
- Added comment aroundtry_init_module_global()for usingraw_spin_lock()(Dave).
- Added one sentence to changelog to explain why to exposetdx_enable()andtdx_cpu_enable()(Dave).
- Simplifed comments aroundtdx_enable()andtdx_cpu_enable()to use lockdep_assert_*() instead. (Dave)
- Removed redundent "TDX" in error message (Dave).v10 -> v11:
- Return -NODEV instead of-EINVALwhenCONFIG_INTEL_TDX_HOSTis off.
- Return the actual error code fortdx_enable()instead of-EINVAL.
- Added Isaku's Reviewed-by.v9 -> v10:
- Merged the patch to handle per-cpu initialization to this patch to tell the story better.
- Changed how to handle the per-cpu initialization to only provide atdx_cpu_enable()function to let the user of TDX to do it when the user wants to run TDX code on a certain cpu.
- Changedtdx_enable()to not callcpus_read_lock()explicitly, but calllockdep_assert_cpus_held()to assume the caller has done that.
- Improved comments aroundtdx_enable()andtdx_cpu_enable().
- Improved changelog to tell the story better accordingly.v8 -> v9:
- Removed detailed TODO list in the changelog (Dave).
- Added back steps to do module global initialization and per-cpu initialization in the TODO list comment.
- Moved the 'enumtdx_module_status_t' fromtdx.cto localtdx.hv7 -> v8:
- Refined changelog (Dave).
- Removed "all BIOS-enabled cpus" related code (Peter/Thomas/Dave).
- Add a "TODO list" comment ininit_tdx_module()to list all steps of initializing the TDX Module to tell the story (Dave).
- Madetdx_enable()unverisally return-EINVAL, and removed nonsense comments (Dave).
- Simplified__tdx_enable()to only handle success or failure.
-TDX_MODULE_SHUTDOWN->TDX_MODULE_ERROR
- RemovedTDX_MODULE_NONE(not loaded) as it is not necessary.
- Improved comments (Dave).
- Pointed out 'tdx_module_status' is software thing (Dave)....
--- arch/x86/include/asm/tdx.h | 4 + arch/x86/virt/vmx/tdx/tdx.c | 167 ++++++++++++++++++++++++++++++++++++ arch/x86/virt/vmx/tdx/tdx.h | 30 +++++++ 3 files changed, 201 insertions(+) create mode 100644 arch/x86/virt/vmx/tdx/tdx.harch/x86/include/asm/tdx.h +4
-0@@ -110,8 +110,12 @@ static inline u64 sc_retry(sc_func_t func, u64 fn,#define seamcall_saved_ret (_fn, _args) sc_retry(__seamcall_saved_ret, (_fn), (_args))bool platform_tdx_enabled (void ); +int tdx_cpu_enable (void ); +int tdx_enable (void );#else static inline bool platform_tdx_enabled (void ) {return false; } +static inline int tdx_cpu_enable (void ) {return -ENODEV ; } +static inline int tdx_enable (void ) {return -ENODEV ; }#endif /* CONFIG_INTEL_TDX_HOST */ #endif /* !__ASSEMBLY__ */ arch/x86/virt/vmx/tdx/tdx.c +21
-0@@ -12,14 +12,24 @@#include <linux/init.h> #include <linux/errno.h> #include <linux/printk.h> +#include <linux/cpu.h> +#include <linux/spinlock.h> +#include <linux/percpu-defs.h> +#include <linux/mutex.h> #include <asm/msr-index.h> #include <asm/msr.h> #include <asm/tdx.h> +#include "tdx.h" static u32 tdx_global_keyid__ro_after_init ;static u32 tdx_guest_keyid_start__ro_after_init ;static u32 tdx_nr_guest_keyids__ro_after_init ; +static DEFINE_PER_CPU(bool, tdx_lp_initialized); + +static enum tdx_module_status_t tdx_module_status; +static DEFINE_MUTEX (tdx_module_lock); +typedef void (*sc_err_func_t )(u64 fn,u64 err,struct tdx_module_args *args);static inline void seamcall_err (u64 fn,u64 err,struct tdx_module_args *args)@@ -72,6 +82,163 @@ static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func,#define seamcall_prerr_ret (__fn, __args) \ sc_retry_prerr(__seamcall_ret, seamcall_err_ret, (__fn), (__args)) +/* +* Do the module global initialization once and return its result. +* It can be done on any cpu. It's always called with interrupts +* disabled. +*/ +static int try_init_module_global (void ) +{ +struct tdx_module_args args = {}; +static DEFINE_RAW_SPINLOCK (sysinit_lock); +static bool sysinit_done; +static int sysinit_ret;
arch/x86/virt/vmx/tdx/tdx.c static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func, · line 105
Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10
-0+ +lockdep_assert_irqs_disabled (); + +raw_spin_lock (&sysinit_lock); + +if (sysinit_done) + goto out; + +/* RCX is module attributes and all bits are reserved */ + args.rcx =0 ;
Isn't args.rcx already initialized to 0, why explixitly set it?
Quoted 40 lines
arch/x86/virt/vmx/tdx/tdx.c +40
-0+ sysinit_ret =seamcall_prerr (TDH_SYS_INIT , &args); + +/* +* The first SEAMCALL also detects the TDX module, thus +* it can fail due to the TDX module is not loaded. +* Dump message to let the user know. +*/ +if (sysinit_ret == -ENODEV ) +pr_err ("module not loaded\n" ); + + sysinit_done = true; +out: +raw_spin_unlock (&sysinit_lock); +return sysinit_ret; +} + +/** +* tdx_cpu_enable - Enable TDX on local cpu +* +* Do one-time TDX module per-cpu initialization SEAMCALL (and TDX module +* global initialization SEAMCALL if not done) on local cpu to make this +* cpu be ready to run any other SEAMCALLs. +* +* Always call this function via IPI function calls. +* +* Return 0 on success, otherwise errors. +*/ +int tdx_cpu_enable (void ) +{ +struct tdx_module_args args = {}; +int ret; + +if (!platform_tdx_enabled ()) +return -ENODEV ; + +lockdep_assert_irqs_disabled (); + +if (__this_cpu_read (tdx_lp_initialized)) +return 0 ; +
arch/x86/virt/vmx/tdx/tdx.c static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func, · line 155
Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10
-0+/* +* The TDX module global initialization is the very first step +* to enable TDX. Need to do it first (if hasn't been done) +* before the per-cpu initialization. +*/ + ret =try_init_module_global (); +if (ret) +return ret; + + ret =seamcall_prerr (TDH_SYS_LP_INIT , &args);
If you have more usage of zero intialized args variant, do you want to add a helper for it?
Quoted 125 lines
arch/x86/virt/vmx/tdx/tdx.c +86
-0+if (ret) +return ret; + +__this_cpu_write (tdx_lp_initialized, true); + +return 0 ; +} +EXPORT_SYMBOL_GPL (tdx_cpu_enable); + +static int init_tdx_module (void ) +{ +/* +* TODO: +* +* - Get TDX module information and TDX-capable memory regions. +* - Build the list of TDX-usable memory regions. +* - Construct a list of "TD Memory Regions" (TDMRs) to cover +* all TDX-usable memory regions. +* - Configure the TDMRs and the global KeyID to the TDX module. +* - Configure the global KeyID on all packages. +* - Initialize all TDMRs. +* +* Return error before all steps are done. +*/ +return -EINVAL ; +} + +static int __tdx_enable (void ) +{ +int ret; + + ret =init_tdx_module (); +if (ret) { +pr_err ("module initialization failed (%d)\n" , ret); + tdx_module_status =TDX_MODULE_ERROR ; +return ret; + } + +pr_info ("module initialized\n" ); + tdx_module_status =TDX_MODULE_INITIALIZED ; + +return 0 ; +} + +/** +* tdx_enable - Enable TDX module to make it ready to run TDX guests +* +* This function assumes the caller has: 1) held read lock of CPU hotplug +* lock to prevent any new cpu from becoming online; 2) done both VMXON +* and tdx_cpu_enable() on all online cpus. +* +* This function can be called in parallel by multiple callers. +* +* Return 0 if TDX is enabled successfully, otherwise error. +*/ +int tdx_enable (void ) +{ +int ret; + +if (!platform_tdx_enabled ()) +return -ENODEV ; + +lockdep_assert_cpus_held (); + +mutex_lock (&tdx_module_lock); + +switch (tdx_module_status) { +case TDX_MODULE_UNINITIALIZED : + ret =__tdx_enable (); +break ; +case TDX_MODULE_INITIALIZED : +/* Already initialized, great, tell the caller. */ + ret =0 ; +break ; +default : +/* Failed to initialize in the previous attempts */ + ret = -EINVAL ; +break ; + } + +mutex_unlock (&tdx_module_lock); + +return ret; +} +EXPORT_SYMBOL_GPL (tdx_enable); +static int __init record_keyid_partitioning (u32 *tdx_keyid_start,u32 *nr_tdx_keyids) {arch/x86/virt/vmx/tdx/tdx.h new file +30
-0@@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _X86_VIRT_TDX_H +#define _X86_VIRT_TDX_H + +/* +* This file contains both macros and data structures defined by the TDX +* architecture and Linux defined software data structures and functions. +* The two should not be mixed together for better readability. The +* architectural definitions come first. +*/ + +/* +* TDX module SEAMCALL leaf functions +*/ +#define TDH_SYS_INIT 33 +#define TDH_SYS_LP_INIT 35 + +/* +* Do not put any hardware-defined TDX structure representations below +* this comment! +*/ + +/* Kernel defined TDX module status during module initialization. */ +enum tdx_module_status_t { +TDX_MODULE_UNINITIALIZED , +TDX_MODULE_INITIALIZED , +TDX_MODULE_ERROR +}; + +#endif
Signature · 2 lines
Sathyanarayanan Kuppuswamy Linux Kernel Developer
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 16 lines
Quoted 16 lines
arch/x86/virt/vmx/tdx/tdx.c +15
-0+/* +* Do the module global initialization once and return its result. +* It can be done on any cpu. It's always called with interrupts +* disabled. +*/ +static int try_init_module_global (void ) +{ +struct tdx_module_args args = {}; +static DEFINE_RAW_SPINLOCK (sysinit_lock); +static bool sysinit_done; +static int sysinit_ret; + +lockdep_assert_irqs_disabled (); + +raw_spin_lock (&sysinit_lock);
Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func, · line 105
Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6
-0+ +if (sysinit_done) + goto out; + +/* RCX is module attributes and all bits are reserved */ + args.rcx =0 ;Isn't args.rcx already initialized to 0, why explixitly set it?
The purpose was to indicate SYS.INIT takes RCX as input, but OK I agree it's unnecessary.
I found the existing upstream TDX code uses this pattern (please see tdx_parse_info(), hv_tdx_hypercall() and try_accept_one()):
struct tdx_module_args args = {};
args.xx = xx;
args.yy = yy;
...So I followed in this series.
But I think explicit zeroing the structure isn't needed, so I think I'll just remove the explicit initialization in the @args declaration in all SEAMCALLs which use this pattern in this series:
struct tdx_module_args args; /* RCX is module attributes and all bits are reserved */ args.rcx = 0;
Or just explicitly init RCX in the declaration:
struct tdx_module_args args = {
.rcx = 0; /* Module attributes. All bits reserved. */
};
// other variable declarationsBut it seems many people don't like tail comment.
Hi Kirill/Dave,
Do you have any preference?
Quoted 1 line
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 1 line · Kai
Hi Kirill/Dave, Do you have any preference?
I'm fine with the explicit initialization. The compiler might even zap it for you so it basically becomes documentation.
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 5 lines · Dave Hansen
Quoted 1 line · Kai
Hi Kirill/Dave, Do you have any preference?
I'm fine with the explicit initialization. The compiler might even zap it for you so it basically becomes documentation.
So I think I'll keep the current code in this patch. Thanks Dave!
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
In reply to Kai Huang<snip>
Quoted 54 lines
--- arch/x86/include/asm/tdx.h | 4 + arch/x86/virt/vmx/tdx/tdx.c | 167 ++++++++++++++++++++++++++++++++++++ arch/x86/virt/vmx/tdx/tdx.h | 30 +++++++ 3 files changed, 201 insertions(+)create mode 100644
arch/x86/virt/vmx/tdx/tdx.harch/x86/include/asm/tdx.h +4
-0@@ -110,8 +110,12 @@ static inline u64 sc_retry(sc_func_t func, u64 fn,#define seamcall_saved_ret (_fn, _args) sc_retry(__seamcall_saved_ret, (_fn), (_args))bool platform_tdx_enabled (void ); +int tdx_cpu_enable (void ); +int tdx_enable (void );#else static inline bool platform_tdx_enabled (void ) {return false; } +static inline int tdx_cpu_enable (void ) {return -ENODEV ; } +static inline int tdx_enable (void ) {return -ENODEV ; }#endif /* CONFIG_INTEL_TDX_HOST */ #endif /* !__ASSEMBLY__ */ arch/x86/virt/vmx/tdx/tdx.c +10
-0@@ -12,14 +12,24 @@#include <linux/init.h> #include <linux/errno.h> #include <linux/printk.h> +#include <linux/cpu.h> +#include <linux/spinlock.h> +#include <linux/percpu-defs.h> +#include <linux/mutex.h> #include <asm/msr-index.h> #include <asm/msr.h> #include <asm/tdx.h> +#include "tdx.h" static u32 tdx_global_keyid__ro_after_init ;static u32 tdx_guest_keyid_start__ro_after_init ;static u32 tdx_nr_guest_keyids__ro_after_init ; +static DEFINE_PER_CPU(bool, tdx_lp_initialized); + +static enum tdx_module_status_t tdx_module_status; +static DEFINE_MUTEX (tdx_module_lock); +typedef void (*sc_err_func_t )(u64 fn,u64 err,struct tdx_module_args *args);static inline void seamcall_err (u64 fn,u64 err,struct tdx_module_args *args)
arch/x86/virt/vmx/tdx/tdx.c static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func, · line 91
Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +7
-0@@ -72,6 +82,163 @@ static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func,#define seamcall_prerr_ret (__fn, __args) \ sc_retry_prerr(__seamcall_ret, seamcall_err_ret, (__fn), (__args)) +/* +* Do the module global initialization once and return its result. +* It can be done on any cpu. It's always called with interrupts +* disabled. +*/ +static int try_init_module_global (void ) +{
Any particular reason why this function is not called from the tdx module's tdx_init? It's global and must be called once when the module is initialised. Subsequently kvm which is supposed to call tdx_cpu_enable() must be sequenced _after_ tdx which shouldn't be that hard, no? This will eliminate the spinlock as well.
<snip>
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 15 lines
arch/x86/virt/vmx/tdx/tdx.c static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func, · line 91
Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +7
-0+/* +* Do the module global initialization once and return its result. +* It can be done on any cpu. It's always called with interrupts +* disabled. +*/ +static int try_init_module_global (void ) +{Any particular reason why this function is not called from the tdx module's tdx_init? It's global and must be called once when the module is initialised. Subsequently kvm which is supposed to call
tdx_cpu_enable()must be sequenced _after_ tdx which shouldn't be that hard, no? This will eliminate the spinlock as well.
Do you mean early_initcall(tdx_init)?
Because it requires VMXON being done to do SEAMCALL. For now only KVM does VMXON.
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 16 lines · Kai
Quoted 15 lines
arch/x86/virt/vmx/tdx/tdx.c static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func, · line 91
Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +7
-0+/* +* Do the module global initialization once and return its result. +* It can be done on any cpu. It's always called with interrupts +* disabled. +*/ +static int try_init_module_global (void ) +{Any particular reason why this function is not called from the tdx module's tdx_init? It's global and must be called once when the module is initialised. Subsequently kvm which is supposed to call
tdx_cpu_enable()must be sequenced _after_ tdx which shouldn't be that hard, no? This will eliminate the spinlock as well.
Quoted 5 lines
Do you mean
early_initcall(tdx_init)?Because it requires VMXON being done to do SEAMCALL. For now only KVM does VMXON.
Right, then would it not make more sense too have this code as part of the KVM bringup of TDX. In fact by keeping the 2 series separate you might be adding complexity. What is the initial motivation to keep those patches out of the KVM tdx host series support?
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 20 lines · Nikolay Borisov
Quoted 18 lines · Kai
Quoted 15 lines
arch/x86/virt/vmx/tdx/tdx.c static inline int sc_retry_prerr(sc_func_t func, sc_err_func_t err_func, · line 91
Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +7
-0+/* +* Do the module global initialization once and return its result. +* It can be done on any cpu. It's always called with interrupts +* disabled. +*/ +static int try_init_module_global (void ) +{Any particular reason why this function is not called from the tdx module's tdx_init? It's global and must be called once when the module is initialised. Subsequently kvm which is supposed to call
tdx_cpu_enable()must be sequenced _after_ tdx which shouldn't be that hard, no? This will eliminate the spinlock as well.Do you mean
early_initcall(tdx_init)?
Quoted 8 lines
Quoted 3 lines
Because it requires VMXON being done to do SEAMCALL. For now only KVM does VMXON.
Right, then would it not make more sense too have this code as part of the KVM bringup of TDX. In fact by keeping the 2 series separate you might be adding complexity. What is the initial motivation to keep those patches out of the KVM tdx host series support?
A simple answer is, for now only KVM uses this series, but later other kernel components such as IOMMU will need to use this series too, so the core-kernel is the right place to fit.
Another practical reason is, although for now KVM is the only user, but the effect of enabling TDX module is system wide, because once TDX module is initialized, it stays there no matter KVM is still present or not (KVM can enable TDX and then unloaded permanently).
For instance, kexec() and #MC handler needs additional handling when TDX gets enabled. If we completely maintain this series in KVM, then after KVM is unloaded we will lose some essential information to do these system-wide things.
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
In reply to Kai HuangQuoted 62 lines · Kai Huang
To enable TDX the kernel needs to initialize TDX from two perspectives:
1) Do a set of SEAMCALLs to initialize the TDX module to make it ready to create and run TDX guests; 2) Do the per-cpu initialization SEAMCALL on one logical cpu before the kernel wants to make any other SEAMCALLs on that cpu (including those involved during module initialization and running TDX guests).The TDX module can be initialized only once in its lifetime. Instead of always initializing it at boot time, this implementation chooses an "on demand" approach to initialize TDX until there is a real need (e.g when requested by KVM). This approach has below pros:
1) It avoids consuming the memory that must be allocated by kernel and given to the TDX module as metadata (~1/256th of the TDX-usable memory), and also saves the CPU cycles of initializing the TDX module (and the metadata) when TDX is not used at all.
2) The TDX module design allows it to be updated while the system is running. The update procedure shares quite a few steps with this "on demand" initialization mechanism. The hope is that much of "on demand" mechanism can be shared with a future "update" mechanism. A boot-time TDX module implementation would not be able to share much code with the update mechanism.
3) Making SEAMCALL requires VMX to be enabled. Currently, only the KVM code mucks with VMX enabling. If the TDX module were to be initialized separately from KVM (like at boot), the boot code would need to be taught how to muck with VMX enabling and KVM would need to be taught how to cope with that. Making KVM itself responsible for TDX initialization lets the rest of the kernel stay blissfully unaware of VMX.
Similar to module initialization, also make the per-cpu initialization "on demand" as it also depends on VMX being enabled.
Add two functions,
tdx_enable()andtdx_cpu_enable(), to enable the TDX module and enable TDX on local cpu respectively. For nowtdx_enable()is a placeholder. The TODO list will be pared down as functionality is added.Export both
tdx_cpu_enable()andtdx_enable()for KVM use.In
tdx_enable()use a state machine protected by mutex to make sure the initialization will only be done once, astdx_enable()can be called multiple times (i.e. KVM module can be reloaded) and may be called concurrently by other kernel components in the future.The per-cpu initialization on each cpu can only be done once during the module's life time. Use a per-cpu variable to track its status to make sure it is only done once in
tdx_cpu_enable().Also, a SEAMCALL to do TDX module global initialization must be done once on any logical cpu before any per-cpu initialization SEAMCALL. Do it inside
tdx_cpu_enable()too (if hasn't been done).
tdx_enable()can potentially invoke SEAMCALLs on any online cpus. The per-cpu initialization must be done before those SEAMCALLs are invoked on some cpu. To keep things simple, intdx_cpu_enable(), always do the per-cpu initialization regardless of whether the TDX module has been initialized or not. And intdx_enable(), don't calltdx_cpu_enable()but assume the caller has disabled CPU hotplug, done VMXON andtdx_cpu_enable()on all online cpus before callingtdx_enable().
Quoted 2 lines
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>
With the latest explanation from Kai :
Re: [PATCH v14 07/23] x86/virt/tdx: Add skeleton to enable TDX on demand
Quoted 64 lines · Nikolay Borisov
Quoted 62 lines · Kai Huang
To enable TDX the kernel needs to initialize TDX from two perspectives:
1) Do a set of SEAMCALLs to initialize the TDX module to make it ready to create and run TDX guests; 2) Do the per-cpu initialization SEAMCALL on one logical cpu before the kernel wants to make any other SEAMCALLs on that cpu (including those involved during module initialization and running TDX guests).The TDX module can be initialized only once in its lifetime. Instead of always initializing it at boot time, this implementation chooses an "on demand" approach to initialize TDX until there is a real need (e.g when requested by KVM). This approach has below pros:
1) It avoids consuming the memory that must be allocated by kernel and given to the TDX module as metadata (~1/256th of the TDX-usable memory), and also saves the CPU cycles of initializing the TDX module (and the metadata) when TDX is not used at all.
2) The TDX module design allows it to be updated while the system is running. The update procedure shares quite a few steps with this "on demand" initialization mechanism. The hope is that much of "on demand" mechanism can be shared with a future "update" mechanism. A boot-time TDX module implementation would not be able to share much code with the update mechanism.
3) Making SEAMCALL requires VMX to be enabled. Currently, only the KVM code mucks with VMX enabling. If the TDX module were to be initialized separately from KVM (like at boot), the boot code would need to be taught how to muck with VMX enabling and KVM would need to be taught how to cope with that. Making KVM itself responsible for TDX initialization lets the rest of the kernel stay blissfully unaware of VMX.
Similar to module initialization, also make the per-cpu initialization "on demand" as it also depends on VMX being enabled.
Add two functions,
tdx_enable()andtdx_cpu_enable(), to enable the TDX module and enable TDX on local cpu respectively. For nowtdx_enable()is a placeholder. The TODO list will be pared down as functionality is added.Export both
tdx_cpu_enable()andtdx_enable()for KVM use.In
tdx_enable()use a state machine protected by mutex to make sure the initialization will only be done once, astdx_enable()can be called multiple times (i.e. KVM module can be reloaded) and may be called concurrently by other kernel components in the future.The per-cpu initialization on each cpu can only be done once during the module's life time. Use a per-cpu variable to track its status to make sure it is only done once in
tdx_cpu_enable().Also, a SEAMCALL to do TDX module global initialization must be done once on any logical cpu before any per-cpu initialization SEAMCALL. Do it inside
tdx_cpu_enable()too (if hasn't been done).
tdx_enable()can potentially invoke SEAMCALLs on any online cpus. The per-cpu initialization must be done before those SEAMCALLs are invoked on some cpu. To keep things simple, intdx_cpu_enable(), always do the per-cpu initialization regardless of whether the TDX module has been initialized or not. And intdx_enable(), don't calltdx_cpu_enable()but assume the caller has disabled CPU hotplug, done VMXON andtdx_cpu_enable()on all online cpus before callingtdx_enable().
Quoted 7 lines
Quoted 2 lines
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>With the latest explanation from Kai :
Reviewed-by Nikolay Borisov <[email protected]>
Thanks!
PATCH v14 8/23 x86/virt/tdx: Get information about TDX module and TDX-capable memory
In reply to Kai HuangStart to transit out the "multi-steps" to initialize the TDX module.
TDX provides increased levels of memory confidentiality and integrity. This requires special hardware support for features like memory encryption and storage of memory integrity checksums. Not all memory satisfies these requirements.
As a result, TDX introduced the concept of a "Convertible Memory Region" (CMR). During boot, the firmware builds a list of all of the memory ranges which can provide the TDX security guarantees.
CMRs tell the kernel which memory is TDX compatible. The kernel takes CMRs (plus a little more metadata) and constructs "TD Memory Regions" (TDMRs). TDMRs let the kernel grant TDX protections to some or all of the CMR areas.
The TDX module also reports necessary information to let the kernel build TDMRs and run TDX guests in structure 'tdsysinfo_struct'. The list of CMRs, along with the TDX module information, is available to the kernel by querying the TDX module.
As a preparation to construct TDMRs, get the TDX module information and the list of CMRs. Print out CMRs to help user to decode which memory regions are TDX convertible.
The 'tdsysinfo_struct' is fairly large (1024 bytes) and contains a lot of info about the TDX module. Fully define the entire structure, but only use the fields necessary to build the TDMRs and pr_info() some basics about the module. The rest of the fields will get used by KVM.
---
v13 -> v14:
- Added Kirill's tag.
v12 -> v13:
- Allocate TDSYSINFO and CMR array separately. (Kirill)
- Added comment around TDH.SYS.INFO. (Peter)
v11 -> v12:
- Changed to use dynamic allocation for TDSYSINFO_STRUCT and CMR array (Kirill).
- Keep SEAMCALL leaf macro definitions in order (Kirill)
- Removed is_cmr_empty() but open code directly (David)
- 'atribute' -> 'attribute' (David)
v10 -> v11:
- No change.
v9 -> v10:
- Added back "start to transit out..." as now per-cpu init has been moved out from tdx_enable().
v8 -> v9:
- Removed "start to trransit out ..." part in changelog since this patch is no longer the first step anymore.
- Changed to declare 'tdsysinfo' and 'cmr_array' as local static, and changed changelog accordingly (Dave).
- Improved changelog to explain why to declare 'tdsysinfo_struct' in full but only use a few members of them (Dave).
v7 -> v8: (Dave)
- Improved changelog to tell this is the first patch to transit out the "multi-steps" init_tdx_module().
- Removed all CMR check/trim code but to depend on later SEAMCALL.
- Variable 'vertical alignment' in print TDX module information.
- Added DECLARE_PADDED_STRUCT() for padded structure.
- Made tdx_sysinfo and tdx_cmr_array[] to be function local variable (and rename them accordingly), and added -Wframe-larger-than=4096 flag to silence the build warning.
...
--- arch/x86/virt/vmx/tdx/tdx.c | 94 ++++++++++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 64 +++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 2 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +92 -2
@@ -16,8 +16,11 @@#include <linux/spinlock.h> #include <linux/percpu-defs.h> #include <linux/mutex.h> +#include <linux/slab.h> +#include <linux/math.h> #include <asm/msr-index.h> #include <asm/msr.h> +#include <asm/page.h> #include <asm/tdx.h> #include "tdx.h"
@@ -162,12 +165,91 @@ int tdx_cpu_enable(void) }EXPORT_SYMBOL_GPL (tdx_cpu_enable); +static void print_cmrs (struct cmr_info *cmr_array,int nr_cmrs) +{ +int i; + +for (i =0 ; i < nr_cmrs; i++) { +struct cmr_info *cmr = &cmr_array[i]; + +/* +* The array of CMRs reported via TDH.SYS.INFO can +* contain tail empty CMRs. Don't print them. +*/ +if (!cmr->size) +break ; + +pr_info ("CMR: [0x%llx, 0x%llx)\n" , cmr->base, + cmr->base + cmr->size); + } +} + +static int get_tdx_sysinfo (struct tdsysinfo_struct *tdsysinfo, +struct cmr_info *cmr_array) +{ +struct tdx_module_args args = {}; +int ret; + +/* +* TDH.SYS.INFO writes the TDSYSINFO_STRUCT and the CMR array +* to the buffers provided by the kernel (via RCX and R8 +* respectively). The buffer size of the TDSYSINFO_STRUCT +* (via RDX) and the maximum entries of the CMR array (via R9) +* passed to this SEAMCALL must be at least the size of +* TDSYSINFO_STRUCT and MAX_CMRS respectively. +* +* Upon a successful return, R9 contains the actual entries +* written to the CMR array. +*/ + args.rcx =__pa (tdsysinfo); + args.rdx =TDSYSINFO_STRUCT_SIZE ; + args.r8 =__pa (cmr_array); + args.r9 =MAX_CMRS ; + ret =seamcall_prerr_ret (TDH_SYS_INFO , &args); +if (ret) +return ret; + +pr_info ("TDX module: attributes 0x%x, vendor_id 0x%x, major_version %u, minor_version %u, build_date %u, build_num %u" , + tdsysinfo->attributes, tdsysinfo->vendor_id, + tdsysinfo->major_version, tdsysinfo->minor_version, + tdsysinfo->build_date, tdsysinfo->build_num); + +print_cmrs (cmr_array, args.r9); + +return 0 ; +} +static int init_tdx_module (void ) { +struct tdsysinfo_struct *tdsysinfo; +struct cmr_info *cmr_array; +int tdsysinfo_size; +int cmr_array_size; +int ret; + + tdsysinfo_size =round_up (TDSYSINFO_STRUCT_SIZE , +TDSYSINFO_STRUCT_ALIGNMENT ); + tdsysinfo =kzalloc (tdsysinfo_size,GFP_KERNEL ); +if (!tdsysinfo) +return -ENOMEM ; + + cmr_array_size =sizeof (struct cmr_info ) *MAX_CMRS ; + cmr_array_size =round_up (cmr_array_size,CMR_INFO_ARRAY_ALIGNMENT ); + cmr_array =kzalloc (cmr_array_size,GFP_KERNEL ); +if (!cmr_array) { +kfree (tdsysinfo); +return -ENOMEM ; + } + + +/* Get the TDSYSINFO_STRUCT and CMRs from the TDX module. */ + ret =get_tdx_sysinfo (tdsysinfo, cmr_array); +if (ret) + goto out; +/* * TODO: * -* - Get TDX module information and TDX-capable memory regions. * - Build the list of TDX-usable memory regions. * - Construct a list of "TD Memory Regions" (TDMRs) to cover * all TDX-usable memory regions.
@@ -177,7 +259,15 @@ static int init_tdx_module(void)* * Return error before all steps are done. */ -return -EINVAL ; + ret = -EINVAL ; +out: +/* +* For now both @sysinfo and @cmr_array are only used during +* module initialization, so always free them. +*/ +kfree (tdsysinfo); +kfree (cmr_array); +return ret; }static int __tdx_enable (void )
arch/x86/virt/vmx/tdx/tdx.h +64 -0
79 lines not on this page · raw message
Signature · 1 line
2.41.0
PATCH v14 9/23 x86/virt/tdx: Use all system memory when initializing TDX module as TDX memory
In reply to Kai HuangAs a step of initializing the TDX module, the kernel needs to tell the TDX module which memory regions can be used by the TDX module as TDX guest memory.
TDX reports a list of "Convertible Memory Region" (CMR) to tell the kernel which memory is TDX compatible. The kernel needs to build a list of memory regions (out of CMRs) as "TDX-usable" memory and pass them to the TDX module. Once this is done, those "TDX-usable" memory regions are fixed during module's lifetime.
To keep things simple, assume that all TDX-protected memory will come from the page allocator. Make sure all pages in the page allocator *are* TDX-usable memory.
As TDX-usable memory is a fixed configuration, take a snapshot of the memory configuration from memblocks at the time of module initialization (memblocks are modified on memory hotplug). This snapshot is used to enable TDX support for *this* memory configuration only. Use a memory hotplug notifier to ensure that no other RAM can be added outside of this configuration.
This approach requires all memblock memory regions at the time of module initialization to be TDX convertible memory to work, otherwise module initialization will fail in a later SEAMCALL when passing those regions to the module. This approach works when all boot-time "system RAM" is TDX convertible memory, and no non-TDX-convertible memory is hot-added to the core-mm before module initialization.
For instance, on the first generation of TDX machines, both CXL memory and NVDIMM are not TDX convertible memory. Using kmem driver to hot-add any CXL memory or NVDIMM to the core-mm before module initialization will result in failure to initialize the module. The SEAMCALL error code will be available in the dmesg to help user to understand the failure.
---
v13 -> v14:
- No change
v12 -> v13:
- Avoided using " ? : " in tdx_memory_notifier(). (Peter)
v11 -> v12:
- Added tags from Dave/Kirill.
v10 -> v11:
- Added Isaku's Reviewed-by.
v9 -> v10:
- Moved empty @tdx_memlist check out of is_tdx_memory() to make the logic better.
- Added Ying's Reviewed-by.
v8 -> v9:
- Replace "The initial support ..." with timeless sentence in both changelog and comments(Dave).
- Fix run-on sentence in changelog, and senstence to explain why to stash off memblock (Dave).
- Tried to improve why to choose this approach and how it work in changelog based on Dave's suggestion.
- Many other comments enhancement (Dave).
v7 -> v8:
- Trimed down changelog (Dave).
- Changed to use PHYS_PFN() and PFN_PHYS() throughout this series (Ying).
- Moved memory hotplug handling from add_arch_memory() to memory_notifier (Dan/David).
- Removed 'nid' from 'struct tdx_memblock' to later patch (Dave).
- {build|free}_tdx_memory() -> {build|}free_tdx_memlist() (Dave).
- Removed pfn_covered_by_cmr() check as no code to trim CMRs now.
- Improve the comment around first 1MB (Dave).
- Added a comment around reserve_real_mode() to point out TDX code relies on first 1MB being reserved (Ying).
- Added comment to explain why the new online memory range cannot cross multiple TDX memory blocks (Dave).
- Improved other comments (Dave).
--- arch/x86/Kconfig | 1 + arch/x86/kernel/setup.c | 2 + arch/x86/virt/vmx/tdx/tdx.c | 162 +++++++++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 6 ++ 4 files changed, 170 insertions(+), 1 deletion(-)
arch/x86/Kconfig +1 -0
@@ -1945,6 +1945,7 @@ config INTEL_TDX_HOST depends on X86_64 depends on KVM_INTEL depends on X86_X2APIC + select ARCH_KEEP_MEMBLOCK help Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. This option enables necessary TDX
arch/x86/kernel/setup.c +2 -0
@@ -1162,6 +1162,8 @@ void __init setup_arch(char **cmdline_p)* * Moreover, on machines with SandyBridge graphics or in setups that use * crashkernel the entire 1M is reserved anyway. +* +* Note the host kernel TDX also requires the first 1MB being reserved. */ x86_platform.realmode_reserve ();
arch/x86/virt/vmx/tdx/tdx.c +161 -1
207 lines not on this page · raw message
arch/x86/virt/vmx/tdx/tdx.h +6 -0
@@ -91,4 +91,10 @@ enum tdx_module_status_t {TDX_MODULE_ERROR }; +struct tdx_memblock { +struct list_head list; +unsigned long start_pfn; +unsigned long end_pfn; +}; +#endif
Signature · 1 line
2.41.0
PATCH v14 10/23 x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions
In reply to Kai HuangAfter the kernel selects all TDX-usable memory regions, the kernel needs to pass those regions to the TDX module via data structure "TD Memory Region" (TDMR).
Add a placeholder to construct a list of TDMRs (in multiple steps) to cover all TDX-usable memory regions.
=== Long Version ===
TDX provides increased levels of memory confidentiality and integrity. This requires special hardware support for features like memory encryption and storage of memory integrity checksums. Not all memory satisfies these requirements.
As a result, TDX introduced the concept of a "Convertible Memory Region" (CMR). During boot, the firmware builds a list of all of the memory ranges which can provide the TDX security guarantees. The list of these ranges is available to the kernel by querying the TDX module.
The TDX architecture needs additional metadata to record things like which TD guest "owns" a given page of memory. This metadata essentially serves as the 'struct page' for the TDX module. The space for this metadata is not reserved by the hardware up front and must be allocated by the kernel and given to the TDX module.
Since this metadata consumes space, the VMM can choose whether or not to allocate it for a given area of convertible memory. If it chooses not to, the memory cannot receive TDX protections and can not be used by TDX guests as private memory.
For every memory region that the VMM wants to use as TDX memory, it sets up a "TD Memory Region" (TDMR). Each TDMR represents a physically contiguous convertible range and must also have its own physically contiguous metadata table, referred to as a Physical Address Metadata Table (PAMT), to track status for each page in the TDMR range.
Unlike a CMR, each TDMR requires 1G granularity and alignment. To support physical RAM areas that don't meet those strict requirements, each TDMR permits a number of internal "reserved areas" which can be placed over memory holes. If PAMT metadata is placed within a TDMR it must be covered by one of these reserved areas.
Let's summarize the concepts:
CMR - Firmware-enumerated physical ranges that support TDX. CMRs are
4K aligned.
TDMR - Physical address range which is chosen by the kernel to support
TDX. 1G granularity and alignment required. Each TDMR has reserved areas where TDX memory holes and overlapping PAMTs can be represented.
PAMT - Physically contiguous TDX metadata. One table for each page size
per TDMR. Roughly 1/256th of TDMR in size. 256G TDMR = ~1G PAMT.
As one step of initializing the TDX module, the kernel configures TDX-usable memory regions by passing a list of TDMRs to the TDX module.
Constructing the list of TDMRs consists below steps:
1) Fill out TDMRs to cover all memory regions that the TDX module will use for TD memory.
2) Allocate and set up PAMT for each TDMR.
3) Designate reserved areas for each TDMR.
Add a placeholder to construct TDMRs to do the above steps. To keep things simple, just allocate enough space to hold maximum number of TDMRs up front. Always free the buffer of TDMRs since they are only used during module initialization.
---
v13 -> v14:
- No change.
v12 -> v13:
- No change.
v11 -> v12:
- Added tags from Dave/Kirill.
v10 -> v11:
- Changed to keep TDMRs after module initialization to deal with TDX erratum in future patches.
v9 -> v10:
- Changed the TDMR list from static variable back to local variable as now TDX module isn't disabled when tdx_cpu_enable() fails.
v8 -> v9:
- Changes around 'struct tdmr_info_list' (Dave):
- Moved the declaration from tdx.c to tdx.h.
- Renamed 'first_tdmr' to 'tdmrs'.
- 'nr_tdmrs' -> 'nr_consumed_tdmrs'.
- Changed 'tdmrs' to 'void *'.
- Improved comments for all structure members.
- Added a missing empty line in alloc_tdmr_list() (Dave).
v7 -> v8:
- Improved changelog to tell this is one step of "TODO list" in init_tdx_module().
- Other changelog improvement suggested by Dave (with "Create TDMRs" to "Fill out TDMRs" to align with the code).
- Added a "TODO list" comment to lay out the steps to construct TDMRs, following the same idea of "TODO list" in tdx_module_init().
- Introduced 'struct tdmr_info_list' (Dave)
- Further added additional members (tdmr_sz/max_tdmrs/nr_tdmrs) to simplify getting TDMR by given index, and reduce passing arguments around functions.
- Added alloc_tdmr_list()/free_tdmr_list() accordingly, which internally uses tdmr_size_single() (Dave).
- tdmr_num -> nr_tdmrs (Dave).
v6 -> v7:
- Improved commit message to explain 'int' overflow cannot happen in cal_tdmr_size() and alloc_tdmr_array(). -- Andy/Dave.
...
--- arch/x86/virt/vmx/tdx/tdx.c | 97 ++++++++++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 32 ++++++++++++ 2 files changed, 127 insertions(+), 2 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +95 -2
@@ -24,6 +24,7 @@#include <linux/minmax.h> #include <linux/sizes.h> #include <linux/pfn.h> +#include <linux/align.h> #include <asm/msr-index.h> #include <asm/msr.h> #include <asm/page.h>
@@ -301,9 +302,84 @@ static int build_tdx_memlist(struct list_head *tmb_list)return ret; } +/* Calculate the actual TDMR size */ +static int tdmr_size_single (u16 max_reserved_per_tdmr) +{ +int tdmr_sz; + +/* +* The actual size of TDMR depends on the maximum +* number of reserved areas. +*/ + tdmr_sz =sizeof (struct tdmr_info ); + tdmr_sz +=sizeof (struct tdmr_reserved_area ) * max_reserved_per_tdmr; + +return ALIGN (tdmr_sz,TDMR_INFO_ALIGNMENT ); +} + +static int alloc_tdmr_list (struct tdmr_info_list *tdmr_list, +struct tdsysinfo_struct *sysinfo) +{ +size_t tdmr_sz, tdmr_array_sz; +void *tdmr_array; + + tdmr_sz =tdmr_size_single (sysinfo->max_reserved_per_tdmr); + tdmr_array_sz = tdmr_sz * sysinfo->max_tdmrs; + +/* +* To keep things simple, allocate all TDMRs together. +* The buffer needs to be physically contiguous to make +* sure each TDMR is physically contiguous. +*/ + tdmr_array =alloc_pages_exact (tdmr_array_sz, +GFP_KERNEL | __GFP_ZERO); +if (!tdmr_array) +return -ENOMEM ; + + tdmr_list->tdmrs = tdmr_array; + +/* +* Keep the size of TDMR to find the target TDMR +* at a given index in the TDMR list. +*/ + tdmr_list->tdmr_sz = tdmr_sz; + tdmr_list->max_tdmrs = sysinfo->max_tdmrs; + tdmr_list->nr_consumed_tdmrs =0 ; + +return 0 ; +} + +static void free_tdmr_list (struct tdmr_info_list *tdmr_list) +{ +free_pages_exact (tdmr_list->tdmrs, + tdmr_list->max_tdmrs * tdmr_list->tdmr_sz); +} + +/* +* Construct a list of TDMRs on the preallocated space in @tdmr_list +* to cover all TDX memory regions in @tmb_list based on the TDX module +* information in @sysinfo. +*/ +static int construct_tdmrs (struct list_head *tmb_list, +struct tdmr_info_list *tdmr_list, +struct tdsysinfo_struct *sysinfo) +{ +/* +* TODO: +* +* - Fill out TDMRs to cover all TDX memory regions. +* - Allocate and set up PAMTs for each TDMR. +* - Designate reserved areas for each TDMR. +* +* Return -EINVAL until constructing TDMRs is done +*/ +return -EINVAL ; +} +static int init_tdx_module (void ) {struct tdsysinfo_struct *tdsysinfo; +struct tdmr_info_list tdmr_list;struct cmr_info *cmr_array;int tdsysinfo_size;int cmr_array_size;
@@ -345,11 +421,19 @@ static int init_tdx_module(void)if (ret) goto out_put_tdxmem; +/* Allocate enough space for constructing TDMRs */ + ret =alloc_tdmr_list (&tdmr_list, tdsysinfo); +if (ret) + goto out_free_tdxmem; + +/* Cover all TDX-usable memory regions in TDMRs */ + ret =construct_tdmrs (&tdx_memlist, &tdmr_list, tdsysinfo); +if (ret) + goto out_free_tdmrs; +/* * TODO: * -* - Construct a list of "TD Memory Regions" (TDMRs) to cover -* all TDX-usable memory regions. * - Configure the TDMRs and the global KeyID to the TDX module. * - Configure the global KeyID on all packages. * - Initialize all TDMRs.
@@ -357,6 +441,15 @@ static int init_tdx_module(void)* Return error before all steps are done. */ ret = -EINVAL ; +out_free_tdmrs: +/* +* Always free the buffer of TDMRs as they are only used during +* module initialization. +*/ +free_tdmr_list (&tdmr_list); +out_free_tdxmem: +if (ret) +free_tdx_memlist (&tdx_memlist); out_put_tdxmem:/* * @tdx_memlist is written here and read at memory hotplug time.
arch/x86/virt/vmx/tdx/tdx.h +32 -0
@@ -79,6 +79,29 @@ struct tdsysinfo_struct { DECLARE_FLEX_ARRAY(struct cpuid_config, cpuid_configs); } __packed; +struct tdmr_reserved_area { +u64 offset; +u64 size; +} __packed; + +#define TDMR_INFO_ALIGNMENT 512 + +struct tdmr_info { +u64 base; +u64 size; +u64 pamt_1g_base; +u64 pamt_1g_size; +u64 pamt_2m_base; +u64 pamt_2m_size; +u64 pamt_4k_base; +u64 pamt_4k_size; +/* +* Actual number of reserved areas depends on +* 'struct tdsysinfo_struct'::max_reserved_per_tdmr. +*/ + DECLARE_FLEX_ARRAY(struct tdmr_reserved_area, reserved_areas); +} __packed__aligned(TDMR_INFO_ALIGNMENT) ; +/* * Do not put any hardware-defined TDX structure representations below * this comment!
@@ -97,4 +120,13 @@ struct tdx_memblock { unsigned long end_pfn; }; +struct tdmr_info_list { +void *tdmrs;/* Flexible array to hold 'tdmr_info's */ +int nr_consumed_tdmrs;/* How many 'tdmr_info's are in use */ + +/* Metadata for finding target 'tdmr_info' and freeing @tdmrs */ +int tdmr_sz;/* Size of one 'tdmr_info' */ +int max_tdmrs;/* How many 'tdmr_info's are allocated */ +}; +#endif
Signature · 1 line
2.41.0
PATCH v14 11/23 x86/virt/tdx: Fill out TDMRs to cover all TDX memory regions
In reply to Kai HuangStart to transit out the "multi-steps" to construct a list of "TD Memory Regions" (TDMRs) to cover all TDX-usable memory regions.
The kernel configures TDX-usable memory regions by passing a list of TDMRs "TD Memory Regions" (TDMRs) to the TDX module. Each TDMR contains the information of the base/size of a memory region, the base/size of the associated Physical Address Metadata Table (PAMT) and a list of reserved areas in the region.
Do the first step to fill out a number of TDMRs to cover all TDX memory regions. To keep it simple, always try to use one TDMR for each memory region. As the first step only set up the base/size for each TDMR.
Each TDMR must be 1G aligned and the size must be in 1G granularity. This implies that one TDMR could cover multiple memory regions. If a memory region spans the 1GB boundary and the former part is already covered by the previous TDMR, just use a new TDMR for the remaining part.
TDX only supports a limited number of TDMRs. Disable TDX if all TDMRs are consumed but there is more memory region to cover.
There are fancier things that could be done like trying to merge adjacent TDMRs. This would allow more pathological memory layouts to be supported. But, current systems are not even close to exhausting the existing TDMR resources in practice. For now, keep it simple.
---
v13 -> v14:
- No change
v12 -> v13:
- Added Yuan's tag.
v11 -> v12:
- Improved comments around looping over TDX memblock to create TDMRs. (Dave).
- Added code to pr_warn() when consumed TDMRs reaching maximum TDMRs (Dave).
- BIT_ULL(30) -> SZ_1G (Kirill)
- Removed unused TDMR_PFN_ALIGNMENT (Sathy)
- Added tags from Kirill/Sathy
v10 -> v11:
- No update
v9 -> v10:
- No change.
v8 -> v9:
- Added the last paragraph in the changelog (Dave).
- Removed unnecessary type cast in tdmr_entry() (Dave).
--- arch/x86/virt/vmx/tdx/tdx.c | 103 +++++++++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 3 ++ 2 files changed, 105 insertions(+), 1 deletion(-)
arch/x86/virt/vmx/tdx/tdx.c +102 -1
@@ -355,6 +355,102 @@ static void free_tdmr_list(struct tdmr_info_list *tdmr_list) tdmr_list->max_tdmrs * tdmr_list->tdmr_sz); } +/* Get the TDMR from the list at the given index. */ +static struct tdmr_info *tdmr_entry (struct tdmr_info_list *tdmr_list, +int idx) +{ +int tdmr_info_offset = tdmr_list->tdmr_sz * idx; + +return (void *)tdmr_list->tdmrs + tdmr_info_offset; +} + +#define TDMR_ALIGNMENT SZ_1G +#define TDMR_ALIGN_DOWN (_addr) ALIGN_DOWN((_addr), TDMR_ALIGNMENT) +#define TDMR_ALIGN_UP (_addr) ALIGN((_addr), TDMR_ALIGNMENT) + +static inline u64 tdmr_end (struct tdmr_info *tdmr) +{ +return tdmr->base + tdmr->size; +} + +/* +* Take the memory referenced in @tmb_list and populate the +* preallocated @tdmr_list, following all the special alignment +* and size rules for TDMR. +*/ +static int fill_out_tdmrs (struct list_head *tmb_list, +struct tdmr_info_list *tdmr_list) +{ +struct tdx_memblock *tmb; +int tdmr_idx =0 ; + +/* +* Loop over TDX memory regions and fill out TDMRs to cover them. +* To keep it simple, always try to use one TDMR to cover one +* memory region. +* +* In practice TDX supports at least 64 TDMRs. A 2-socket system +* typically only consumes less than 10 of those. This code is +* dumb and simple and may use more TMDRs than is strictly +* required. +*/ +list_for_each_entry (tmb, tmb_list, list) { +struct tdmr_info *tdmr =tdmr_entry (tdmr_list, tdmr_idx); +u64 start, end; + + start =TDMR_ALIGN_DOWN (PFN_PHYS (tmb->start_pfn)); + end =TDMR_ALIGN_UP (PFN_PHYS (tmb->end_pfn)); + +/* +* A valid size indicates the current TDMR has already +* been filled out to cover the previous memory region(s). +*/ +if (tdmr->size) { +/* +* Loop to the next if the current memory region +* has already been fully covered. +*/ +if (end <=tdmr_end (tdmr)) +continue ; + +/* Otherwise, skip the already covered part. */ +if (start <tdmr_end (tdmr)) + start =tdmr_end (tdmr); + +/* +* Create a new TDMR to cover the current memory +* region, or the remaining part of it. +*/ + tdmr_idx++; +if (tdmr_idx >= tdmr_list->max_tdmrs) { +pr_warn ("initialization failed: TDMRs exhausted.\n" ); +return -ENOSPC ; + } + + tdmr =tdmr_entry (tdmr_list, tdmr_idx); + } + + tdmr->base = start; + tdmr->size = end - start; + } + +/* @tdmr_idx is always the index of the last valid TDMR. */ + tdmr_list->nr_consumed_tdmrs = tdmr_idx +1 ; + +/* +* Warn early that kernel is about to run out of TDMRs. +* +* This is an indication that TDMR allocation has to be +* reworked to be smarter to not run into an issue. +*/ +if (tdmr_list->max_tdmrs - tdmr_list->nr_consumed_tdmrs <TDMR_NR_WARN ) +pr_warn ("consumed TDMRs reaching limit: %d used out of %d\n" , + tdmr_list->nr_consumed_tdmrs, + tdmr_list->max_tdmrs); + +return 0 ; +} +/* * Construct a list of TDMRs on the preallocated space in @tdmr_list * to cover all TDX memory regions in @tmb_list based on the TDX module
@@ -364,10 +460,15 @@ static int construct_tdmrs(struct list_head *tmb_list,struct tdmr_info_list *tdmr_list, struct tdsysinfo_struct *sysinfo) { + int ret; + + ret =fill_out_tdmrs (tmb_list, tdmr_list); +if (ret) +return ret; +/* * TODO: * -* - Fill out TDMRs to cover all TDX memory regions. * - Allocate and set up PAMTs for each TDMR. * - Designate reserved areas for each TDMR. *
arch/x86/virt/vmx/tdx/tdx.h +3 -0
@@ -120,6 +120,9 @@ struct tdx_memblock {unsigned long end_pfn; }; +/* Warn if kernel has less than TDMR_NR_WARN TDMRs after allocation */ +#define TDMR_NR_WARN 4 +struct tdmr_info_list {void *tdmrs;/* Flexible array to hold 'tdmr_info's */ int nr_consumed_tdmrs;/* How many 'tdmr_info's are in use */
Signature · 1 line
2.41.0
PATCH v14 12/23 x86/virt/tdx: Allocate and set up PAMTs for TDMRs
In reply to Kai HuangThe TDX module uses additional metadata to record things like which guest "owns" a given page of memory. This metadata, referred as Physical Address Metadata Table (PAMT), essentially serves as the 'struct page' for the TDX module. PAMTs are not reserved by hardware up front. They must be allocated by the kernel and then given to the TDX module during module initialization.
TDX supports 3 page sizes: 4K, 2M, and 1G. Each "TD Memory Region" (TDMR) has 3 PAMTs to track the 3 supported page sizes. Each PAMT must be a physically contiguous area from a Convertible Memory Region (CMR). However, the PAMTs which track pages in one TDMR do not need to reside within that TDMR but can be anywhere in CMRs. If one PAMT overlaps with any TDMR, the overlapping part must be reported as a reserved area in that particular TDMR.
Use alloc_contig_pages() since PAMT must be a physically contiguous area and it may be potentially large (~1/256th of the size of the given TDMR). The downside is alloc_contig_pages() may fail at runtime. One (bad) mitigation is to launch a TDX guest early during system boot to get those PAMTs allocated at early time, but the only way to fix is to add a boot option to allocate or reserve PAMTs during kernel boot.
It is imperfect but will be improved on later.
TDX only supports a limited number of reserved areas per TDMR to cover both PAMTs and memory holes within the given TDMR. If many PAMTs are allocated within a single TDMR, the reserved areas may not be sufficient to cover all of them.
Adopt the following policies when allocating PAMTs for a given TDMR:
- Allocate three PAMTs of the TDMR in one contiguous chunk to minimize the total number of reserved areas consumed for PAMTs.
- Try to first allocate PAMT from the local node of the TDMR for better NUMA locality.
Also dump out how many pages are allocated for PAMTs when the TDX module is initialized successfully. This helps answer the eternal "where did all my memory go?" questions.
---
v13 -> v14:
- No change
v12 -> v13:
- Added Kirill and Yuan's tag.
- Removed unintended space. (Yuan)
v11 -> v12:
- Moved TDX_PS_NUM from tdx.c to <asm/tdx.h> (Kirill)
- "<= TDX_PS_1G" -> "< TDX_PS_NUM" (Kirill)
- Changed tdmr_get_pamt() to return base and size instead of base_pfn and npages and related code directly (Dave).
- Simplified PAMT kb counting. (Dave)
- tdmrs_count_pamt_pages() -> tdmr_count_pamt_kb() (Kirill/Dave)
v10 -> v11:
- No update
v9 -> v10:
- Removed code change in disable_tdx_module() as it doesn't exist anymore.
v8 -> v9:
- Added TDX_PS_NR macro instead of open-coding (Dave).
- Better alignment of 'pamt_entry_size' in tdmr_set_up_pamt() (Dave).
- Changed to print out PAMTs in "KBs" instead of "pages" (Dave).
- Added Dave's Reviewed-by.
v7 -> v8: (Dave)
- Changelog:
- Added a sentence to state PAMT allocation will be improved.
- Others suggested by Dave.
- Moved 'nid' of 'struct tdx_memblock' to this patch.
- Improved comments around tdmr_get_nid().
- WARN_ON_ONCE() -> pr_warn() in tdmr_get_nid().
- Other changes due to 'struct tdmr_info_list'.
v6 -> v7:
- Changes due to using macros instead of 'enum' for TDX supported page sizes.
v5 -> v6:
- Rebase due to using 'tdx_memblock' instead of memblock.
- 'int pamt_entry_nr' -> 'unsigned long nr_pamt_entries' (Dave/Sagis).
- Improved comment around tdmr_get_nid() (Dave).
- Improved comment in tdmr_set_up_pamt() around breaking the PAMT into PAMTs for 4K/2M/1G (Dave).
- tdmrs_get_pamt_pages() -> tdmrs_count_pamt_pages() (Dave).
--- arch/x86/Kconfig | 1 + arch/x86/include/asm/shared/tdx.h | 1 + arch/x86/virt/vmx/tdx/tdx.c | 215 +++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 1 + 4 files changed, 213 insertions(+), 5 deletions(-)
arch/x86/Kconfig +1 -0
@@ -1946,6 +1946,7 @@ config INTEL_TDX_HOST depends on KVM_INTEL depends on X86_X2APIC select ARCH_KEEP_MEMBLOCK + depends on CONTIG_ALLOC help Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. This option enables necessary TDX
arch/x86/include/asm/shared/tdx.h +1 -0
@@ -58,6 +58,7 @@#define TDX_PS_4K 0#define TDX_PS_2M 1#define TDX_PS_1G 2 +#define TDX_PS_NR (TDX_PS_1G + 1)#ifndef __ASSEMBLY__
arch/x86/virt/vmx/tdx/tdx.c +210 -5
261 lines not on this page · raw message
arch/x86/virt/vmx/tdx/tdx.h +1 -0
@@ -118,6 +118,7 @@ struct tdx_memblock {struct list_head list;unsigned long start_pfn;unsigned long end_pfn; +int nid; };/* Warn if kernel has less than TDMR_NR_WARN TDMRs after allocation */
Signature · 1 line
2.41.0
Re: [PATCH v14 12/23] x86/virt/tdx: Allocate and set up PAMTs for TDMRs
On 17.10.23 г. 13:14 ч., Kai Huang wrote:
<snip>
Quoted 23 lines
arch/x86/Kconfig | 1 + arch/x86/include/asm/shared/tdx.h | 1 + arch/x86/virt/vmx/tdx/tdx.c | 215 +++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 1 + 4 files changed, 213 insertions(+), 5 deletions(-)arch/x86/Kconfig +1
-0@@ -1946,6 +1946,7 @@ config INTEL_TDX_HOST depends on KVM_INTEL depends on X86_X2APIC select ARCH_KEEP_MEMBLOCK + depends on CONTIG_ALLOC help Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. This option enables necessary TDXarch/x86/include/asm/shared/tdx.h +0
-0
arch/x86/include/asm/shared/tdx.h line 61
Quoted 4 lines
arch/x86/include/asm/shared/tdx.h +1
-0@@ -58,6 +58,7 @@#define TDX_PS_4K 0#define TDX_PS_2M 1#define TDX_PS_1G 2 +#define TDX_PS_NR (TDX_PS_1G + 1)
nit: I'd prefer if you those defines are turned into an enum and subsequently this enum type can be used in the definition of tdmr_get_pamt_sz(). However, at this point I consider this a bikeshedding and you can do that iff you are going to respin the series due to other feedback as well.
<snip>
Re: [PATCH v14 12/23] x86/virt/tdx: Allocate and set up PAMTs for TDMRs
Quoted 39 lines · Nikolay Borisov
On 17.10.23 г. 13:14 ч., Kai Huang wrote:
<snip>
Quoted 23 lines
arch/x86/Kconfig | 1 + arch/x86/include/asm/shared/tdx.h | 1 + arch/x86/virt/vmx/tdx/tdx.c | 215 +++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 1 + 4 files changed, 213 insertions(+), 5 deletions(-)arch/x86/Kconfig +1
-0@@ -1946,6 +1946,7 @@ config INTEL_TDX_HOST depends on KVM_INTEL depends on X86_X2APIC select ARCH_KEEP_MEMBLOCK + depends on CONTIG_ALLOC help Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. This option enables necessary TDXarch/x86/include/asm/shared/tdx.h +0
-0arch/x86/include/asm/shared/tdx.h line 61
Quoted 4 lines
arch/x86/include/asm/shared/tdx.h +1
-0@@ -58,6 +58,7 @@#define TDX_PS_4K 0#define TDX_PS_2M 1#define TDX_PS_1G 2 +#define TDX_PS_NR (TDX_PS_1G + 1)nit: I'd prefer if you those defines are turned into an enum and subsequently this enum type can be used in the definition of
tdmr_get_pamt_sz(). However, at this point I consider this a bikeshedding and you can do that iff you are going to respin the series due to other feedback as well.
Quoted 1 line
<snip>
Thanks for comments. But to be honest I don't get why enum is better, and I would like to leave this to future work if really needed. Please note these TDX_PS_xx are also used by TDX guest code (see patch 2).
Re: [PATCH v14 12/23] x86/virt/tdx: Allocate and set up PAMTs for TDMRs
Quoted 40 lines · Kai
Quoted 39 lines · Nikolay Borisov
On 17.10.23 г. 13:14 ч., Kai Huang wrote:
<snip>
Quoted 23 lines
arch/x86/Kconfig | 1 + arch/x86/include/asm/shared/tdx.h | 1 + arch/x86/virt/vmx/tdx/tdx.c | 215 +++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 1 + 4 files changed, 213 insertions(+), 5 deletions(-)arch/x86/Kconfig +1
-0@@ -1946,6 +1946,7 @@ config INTEL_TDX_HOST depends on KVM_INTEL depends on X86_X2APIC select ARCH_KEEP_MEMBLOCK + depends on CONTIG_ALLOC help Intel Trust Domain Extensions (TDX) protects guest VMs from malicious host and certain physical attacks. This option enables necessary TDXarch/x86/include/asm/shared/tdx.h +0
-0arch/x86/include/asm/shared/tdx.h line 61
Quoted 4 lines
arch/x86/include/asm/shared/tdx.h +1
-0@@ -58,6 +58,7 @@#define TDX_PS_4K 0#define TDX_PS_2M 1#define TDX_PS_1G 2 +#define TDX_PS_NR (TDX_PS_1G + 1)nit: I'd prefer if you those defines are turned into an enum and subsequently this enum type can be used in the definition of
tdmr_get_pamt_sz(). However, at this point I consider this a bikeshedding and you can do that iff you are going to respin the series due to other feedback as well.
Quoted 5 lines
Quoted 1 line
<snip>
Thanks for comments. But to be honest I don't get why enum is better, and I would like to leave this to future work if really needed. Please note these
TDX_PS_xxare also used by TDX guest code (see patch 2).
The reason being self-documenting code. In particular when looking at the signature of tdmr_get_pamt_sz if the 2nd argument was enum tdx_ps_size or some such it would be immediately evident what this parameter is all about. Right now it's just a plain int which can be anything. Indeed, this is mostly cosmetic so hence it's minor.
PATCH v14 13/23 x86/virt/tdx: Designate reserved areas for all TDMRs
In reply to Kai HuangAs the last step of constructing TDMRs, populate reserved areas for all TDMRs. For each TDMR, put all memory holes within this TDMR to the reserved areas. And for all PAMTs which overlap with this TDMR, put all the overlapping parts to reserved areas too.
---
v13 -> v14:
- No change
v12 -> v13:
- Added Yuan's tag.
v11 -> v12:
- Code change due to tdmr_get_pamt() change from returning pfn/npages to base/size
- Added Kirill's tag
v10 -> v11:
- No update
v9 -> v10:
- No change.
v8 -> v9:
- Added comment around 'tdmr_add_rsvd_area()' to point out it doesn't do optimization to save reserved areas. (Dave).
v7 -> v8: (Dave)
- "set_up" -> "populate" in function name change (Dave).
- Improved comment suggested by Dave.
- Other changes due to 'struct tdmr_info_list'.
--- arch/x86/virt/vmx/tdx/tdx.c | 217 ++++++++++++++++++++++++++++++++++-- 1 file changed, 209 insertions(+), 8 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +209 -8
@@ -25,6 +25,7 @@#include <linux/sizes.h> #include <linux/pfn.h> #include <linux/align.h> +#include <linux/sort.h> #include <asm/msr-index.h> #include <asm/msr.h> #include <asm/page.h>
@@ -648,6 +649,207 @@ static unsigned long tdmrs_count_pamt_kb(struct tdmr_info_list *tdmr_list)return pamt_size /1024 ; } +static int tdmr_add_rsvd_area (struct tdmr_info *tdmr,int *p_idx,u64 addr, +u64 size,u16 max_reserved_per_tdmr) +{ +struct tdmr_reserved_area *rsvd_areas = tdmr->reserved_areas; +int idx = *p_idx; + +/* Reserved area must be 4K aligned in offset and size */ +if (WARN_ON (addr & ~PAGE_MASK || size & ~PAGE_MASK )) +return -EINVAL ; + +if (idx >= max_reserved_per_tdmr) { +pr_warn ("initialization failed: TDMR [0x%llx, 0x%llx): reserved areas exhausted.\n" , + tdmr->base,tdmr_end (tdmr)); +return -ENOSPC ; + } + +/* +* Consume one reserved area per call. Make no effort to +* optimize or reduce the number of reserved areas which are +* consumed by contiguous reserved areas, for instance. +*/ + rsvd_areas[idx].offset = addr - tdmr->base; + rsvd_areas[idx].size = size; + + *p_idx = idx +1 ; + +return 0 ; +} + +/* +* Go through @tmb_list to find holes between memory areas. If any of +* those holes fall within @tdmr, set up a TDMR reserved area to cover +* the hole. +*/ +static int tdmr_populate_rsvd_holes (struct list_head *tmb_list, +struct tdmr_info *tdmr, +int *rsvd_idx, +u16 max_reserved_per_tdmr) +{ +struct tdx_memblock *tmb; +u64 prev_end; +int ret; + +/* +* Start looking for reserved blocks at the +* beginning of the TDMR. +*/ + prev_end = tdmr->base; +list_for_each_entry (tmb, tmb_list, list) { +u64 start, end; + + start =PFN_PHYS (tmb->start_pfn); + end =PFN_PHYS (tmb->end_pfn); + +/* Break if this region is after the TDMR */ +if (start >=tdmr_end (tdmr)) +break ; + +/* Exclude regions before this TDMR */ +if (end < tdmr->base) +continue ; + +/* +* Skip over memory areas that +* have already been dealt with. +*/ +if (start <= prev_end) { + prev_end = end; +continue ; + } + +/* Add the hole before this region */ + ret =tdmr_add_rsvd_area (tdmr, rsvd_idx, prev_end, + start - prev_end, + max_reserved_per_tdmr); +if (ret) +return ret; + + prev_end = end; + } + +/* Add the hole after the last region if it exists. */ +if (prev_end <tdmr_end (tdmr)) { + ret =tdmr_add_rsvd_area (tdmr, rsvd_idx, prev_end, +tdmr_end (tdmr) - prev_end, + max_reserved_per_tdmr); +if (ret) +return ret; + } + +return 0 ; +} + +/* +* Go through @tdmr_list to find all PAMTs. If any of those PAMTs +* overlaps with @tdmr, set up a TDMR reserved area to cover the +* overlapping part. +*/ +static int tdmr_populate_rsvd_pamts (struct tdmr_info_list *tdmr_list, +struct tdmr_info *tdmr, +int *rsvd_idx, +u16 max_reserved_per_tdmr) +{ +int i, ret; + +for (i =0 ; i < tdmr_list->nr_consumed_tdmrs; i++) { +struct tdmr_info *tmp =tdmr_entry (tdmr_list, i); +unsigned long pamt_base, pamt_size, pamt_end; + +tdmr_get_pamt (tmp, &pamt_base, &pamt_size); +/* Each TDMR must already have PAMT allocated */ +WARN_ON_ONCE (!pamt_size || !pamt_base); + + pamt_end = pamt_base + pamt_size; +/* Skip PAMTs outside of the given TDMR */ +if ((pamt_end <= tdmr->base) || + (pamt_base >=tdmr_end (tdmr))) +continue ; + +/* Only mark the part within the TDMR as reserved */ +if (pamt_base < tdmr->base) + pamt_base = tdmr->base; +if (pamt_end >tdmr_end (tdmr)) + pamt_end =tdmr_end (tdmr); + + ret =tdmr_add_rsvd_area (tdmr, rsvd_idx, pamt_base, + pamt_end - pamt_base, + max_reserved_per_tdmr); +if (ret) +return ret; + } + +return 0 ; +} + +/* Compare function called by sort() for TDMR reserved areas */ +static int rsvd_area_cmp_func (const void *a,const void *b) +{ +struct tdmr_reserved_area *r1 = (struct tdmr_reserved_area *)a; +struct tdmr_reserved_area *r2 = (struct tdmr_reserved_area *)b; + +if (r1->offset + r1->size <= r2->offset) +return -1 ; +if (r1->offset >= r2->offset + r2->size) +return 1 ; + +/* Reserved areas cannot overlap. The caller must guarantee. */ +WARN_ON_ONCE (1 ); +return -1 ; +} + +/* +* Populate reserved areas for the given @tdmr, including memory holes +* (via @tmb_list) and PAMTs (via @tdmr_list). +*/ +static int tdmr_populate_rsvd_areas (struct tdmr_info *tdmr, +struct list_head *tmb_list, +struct tdmr_info_list *tdmr_list, +u16 max_reserved_per_tdmr) +{ +int ret, rsvd_idx =0 ; + + ret =tdmr_populate_rsvd_holes (tmb_list, tdmr, &rsvd_idx, + max_reserved_per_tdmr); +if (ret) +return ret; + + ret =tdmr_populate_rsvd_pamts (tdmr_list, tdmr, &rsvd_idx, + max_reserved_per_tdmr); +if (ret) +return ret; + +/* TDX requires reserved areas listed in address ascending order */ +sort (tdmr->reserved_areas, rsvd_idx,sizeof (struct tdmr_reserved_area ), + rsvd_area_cmp_func,NULL ); + +return 0 ; +} + +/* +* Populate reserved areas for all TDMRs in @tdmr_list, including memory +* holes (via @tmb_list) and PAMTs. +*/ +static int tdmrs_populate_rsvd_areas_all (struct tdmr_info_list *tdmr_list, +struct list_head *tmb_list, +u16 max_reserved_per_tdmr) +{ +int i; + +for (i =0 ; i < tdmr_list->nr_consumed_tdmrs; i++) { +int ret; + + ret =tdmr_populate_rsvd_areas (tdmr_entry (tdmr_list, i), + tmb_list, tdmr_list, max_reserved_per_tdmr); +if (ret) +return ret; + } + +return 0 ; +} +/* * Construct a list of TDMRs on the preallocated space in @tdmr_list * to cover all TDX memory regions in @tmb_list based on the TDX module
@@ -667,14 +869,13 @@ static int construct_tdmrs(struct list_head *tmb_list, sysinfo->pamt_entry_size);if (ret)return ret; -/* -* TODO: -* -* - Designate reserved areas for each TDMR. -* -* Return -EINVAL until constructing TDMRs is done -*/ -return -EINVAL ; + + ret =tdmrs_populate_rsvd_areas_all (tdmr_list, tmb_list, + sysinfo->max_reserved_per_tdmr); +if (ret) +tdmrs_free_pamt_all (tdmr_list); + +return ret; }static int init_tdx_module (void )
Signature · 1 line
2.41.0
PATCH v14 14/23 x86/virt/tdx: Configure TDX module with the TDMRs and global KeyID
In reply to Kai HuangThe TDX module uses a private KeyID as the "global KeyID" for mapping things like the PAMT and other TDX metadata. This KeyID has already been reserved when detecting TDX during the kernel early boot.
After the list of "TD Memory Regions" (TDMRs) has been constructed to cover all TDX-usable memory regions, the next step is to pass them to the TDX module together with the global KeyID.
---
v13 -> v14:
- No change
v12 -> v13:
- Added Yuan's tag.
v11 -> v12:
- Added Kirill's tag
v10 -> v11:
- No update
v9 -> v10:
- Code change due to change static 'tdx_tdmr_list' to local 'tdmr_list'.
v8 -> v9:
- Improved changlog to explain why initializing TDMRs can take long time (Dave).
- Improved comments around 'next-to-initialize' address (Dave).
v7 -> v8: (Dave)
- Changelog:
- explicitly call out this is the last step of TDX module initialization.
- Trimed down changelog by removing SEAMCALL name and details.
- Removed/trimmed down unnecessary comments.
- Other changes due to 'struct tdmr_info_list'.
v6 -> v7:
- Removed need_resched() check. -- Andi.
--- arch/x86/virt/vmx/tdx/tdx.c | 43 ++++++++++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 2 ++ 2 files changed, 44 insertions(+), 1 deletion(-)
arch/x86/virt/vmx/tdx/tdx.c +42 -1
@@ -26,6 +26,7 @@#include <linux/pfn.h> #include <linux/align.h> #include <linux/sort.h> +#include <linux/log2.h> #include <asm/msr-index.h> #include <asm/msr.h> #include <asm/page.h>
@@ -878,6 +879,41 @@ static int construct_tdmrs(struct list_head *tmb_list,return ret; } +static int config_tdx_module (struct tdmr_info_list *tdmr_list,u64 global_keyid) +{ +struct tdx_module_args args = {}; +u64 *tdmr_pa_array; +size_t array_sz; +int i, ret; + +/* +* TDMRs are passed to the TDX module via an array of physical +* addresses of each TDMR. The array itself also has certain +* alignment requirement. +*/ + array_sz = tdmr_list->nr_consumed_tdmrs *sizeof (u64); + array_sz =roundup_pow_of_two (array_sz); +if (array_sz <TDMR_INFO_PA_ARRAY_ALIGNMENT ) + array_sz =TDMR_INFO_PA_ARRAY_ALIGNMENT ; + + tdmr_pa_array =kzalloc (array_sz,GFP_KERNEL ); +if (!tdmr_pa_array) +return -ENOMEM ; + +for (i =0 ; i < tdmr_list->nr_consumed_tdmrs; i++) + tdmr_pa_array[i] =__pa (tdmr_entry (tdmr_list, i)); + + args.rcx =__pa (tdmr_pa_array); + args.rdx = tdmr_list->nr_consumed_tdmrs; + args.r8 = global_keyid; + ret =seamcall_prerr (TDH_SYS_CONFIG , &args); + +/* Free the array as it is not required anymore. */ +kfree (tdmr_pa_array); + +return ret; +} +static int init_tdx_module (void ) {struct tdsysinfo_struct *tdsysinfo;
@@ -933,16 +969,21 @@ static int init_tdx_module(void)if (ret) goto out_free_tdmrs; +/* Pass the TDMRs and the global KeyID to the TDX module */ + ret =config_tdx_module (&tdmr_list, tdx_global_keyid); +if (ret) + goto out_free_pamts; +/* * TODO: * -* - Configure the TDMRs and the global KeyID to the TDX module. * - Configure the global KeyID on all packages. * - Initialize all TDMRs. * * Return error before all steps are done. */ ret = -EINVAL ; +out_free_pamts:if (ret)tdmrs_free_pamt_all (&tdmr_list);else
arch/x86/virt/vmx/tdx/tdx.h +2 -0
@@ -19,6 +19,7 @@#define TDH_SYS_INFO 32#define TDH_SYS_INIT 33#define TDH_SYS_LP_INIT 35 +#define TDH_SYS_CONFIG 45struct cmr_info {u64 base;
@@ -85,6 +86,7 @@ struct tdmr_reserved_area { } __packed;#define TDMR_INFO_ALIGNMENT 512 +#define TDMR_INFO_PA_ARRAY_ALIGNMENT 512struct tdmr_info {u64 base;
Signature · 1 line
2.41.0
PATCH v14 15/23 x86/virt/tdx: Configure global KeyID on all packages
In reply to Kai HuangAfter the list of TDMRs and the global KeyID are configured to the TDX module, the kernel needs to configure the key of the global KeyID on all packages using TDH.SYS.KEY.CONFIG.
This SEAMCALL cannot run parallel on different cpus. Loop all online cpus and use smp_call_on_cpu() to call this SEAMCALL on the first cpu of each package.
To keep things simple, this implementation takes no affirmative steps to online cpus to make sure there's at least one cpu for each package. The callers (aka. KVM) can ensure success by ensuring sufficient CPUs are online for this to succeed.
Intel hardware doesn't guarantee cache coherency across different KeyIDs. The PAMTs are transitioning from being used by the kernel mapping (KeyId 0) to the TDX module's "global KeyID" mapping.
This means that the kernel must flush any dirty KeyID-0 PAMT cachelines before the TDX module uses the global KeyID to access the PAMTs. Otherwise, if those dirty cachelines were written back, they would corrupt the TDX module's metadata. Aside: This corruption would be detected by the memory integrity hardware on the next read of the memory with the global KeyID. The result would likely be fatal to the system but would not impact TDX security.
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.
If TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write the PAMTs. Therefore, use WBINVD to flush cache before returning the PAMTs back to the kernel. Also convert all PAMTs back to normal by using MOVDIR64B as suggested by the TDX module spec, although on the platform without the "partial write machine check" erratum it's OK to leave PAMTs as is.
---
v13 -> v14:
- No change
v12 -> v13:
- Added Yuan's tag.
v11 -> v12:
- Added Kirill's tag
- Improved changelog (Nikolay)
v10 -> v11:
- Convert PAMTs back to normal when module initialization fails.
- Fixed an error in changelog
v9 -> v10:
- Changed to use 'smp_call_on_cpu()' directly to do key configuration.
v8 -> v9:
- Improved changelog (Dave).
- Improved comments to explain the function to configure global KeyID "takes no affirmative action to online any cpu". (Dave).
- Improved other comments suggested by Dave.
v7 -> v8: (Dave)
- Changelog changes:
- Point out this is the step of "multi-steps" of init_tdx_module().
- Removed MOVDIR64B part.
- Other changes due to removing TDH.SYS.SHUTDOWN and TDH.SYS.LP.INIT.
- Changed to loop over online cpus and use smp_call_function_single() directly as the patch to shut down TDX module has been removed.
- Removed MOVDIR64B part in comment.
--- arch/x86/virt/vmx/tdx/tdx.c | 130 +++++++++++++++++++++++++++++++++++- arch/x86/virt/vmx/tdx/tdx.h | 1 + 2 files changed, 129 insertions(+), 2 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +128 -2
@@ -30,6 +30,7 @@#include <asm/msr-index.h> #include <asm/msr.h> #include <asm/page.h> +#include <asm/special_insns.h> #include <asm/tdx.h> #include "tdx.h"
@@ -591,7 +592,8 @@ static void tdmr_get_pamt(struct tdmr_info *tdmr, unsigned long *pamt_base, *pamt_size = pamt_sz; } -static void tdmr_free_pamt (struct tdmr_info *tdmr) +static void tdmr_do_pamt_func (struct tdmr_info *tdmr, +void (*pamt_func)(unsigned long base,unsigned long size)) {unsigned long pamt_base, pamt_size;
@@ -604,9 +606,19 @@ static void tdmr_free_pamt(struct tdmr_info *tdmr)if (WARN_ON_ONCE (!pamt_base))return ; + (*pamt_func)(pamt_base, pamt_size); +} + +static void free_pamt (unsigned long pamt_base,unsigned long pamt_size) +{free_contig_range (pamt_base >>PAGE_SHIFT , pamt_size >>PAGE_SHIFT ); } +static void tdmr_free_pamt (struct tdmr_info *tdmr) +{ +tdmr_do_pamt_func (tdmr, free_pamt); +} +static void tdmrs_free_pamt_all (struct tdmr_info_list *tdmr_list) {int i;
@@ -635,6 +647,41 @@ static int tdmrs_set_up_pamt_all(struct tdmr_info_list *tdmr_list,return ret; } +/* +* Convert TDX private pages back to normal by using MOVDIR64B to +* clear these pages. Note this function doesn't flush cache of +* these TDX private pages. The caller should make sure of that. +*/ +static void reset_tdx_pages (unsigned long base,unsigned long size) +{ +const void *zero_page = (const void *)page_address (ZERO_PAGE (0 )); +unsigned long phys, end; + + end = base + size; +for (phys = base; phys < end; phys +=64 ) +movdir64b (__va (phys), zero_page); + +/* +* MOVDIR64B uses WC protocol. Use memory barrier to +* make sure any later user of these pages sees the +* updated data. +*/ +mb (); +} + +static void tdmr_reset_pamt (struct tdmr_info *tdmr) +{ +tdmr_do_pamt_func (tdmr, reset_tdx_pages); +} + +static void tdmrs_reset_pamt_all (struct tdmr_info_list *tdmr_list) +{ +int i; + +for (i =0 ; i < tdmr_list->nr_consumed_tdmrs; i++) +tdmr_reset_pamt (tdmr_entry (tdmr_list, i)); +} +static unsigned long tdmrs_count_pamt_kb (struct tdmr_info_list *tdmr_list) {unsigned long pamt_size =0 ;
@@ -914,6 +961,50 @@ static int config_tdx_module(struct tdmr_info_list *tdmr_list, u64 global_keyid)return ret; } +static int do_global_key_config (void *data) +{ +struct tdx_module_args args = {}; + +return seamcall_prerr (TDH_SYS_KEY_CONFIG , &args); +} + +/* +* Attempt to configure the global KeyID on all physical packages. +* +* This requires running code on at least one CPU in each package. If a +* package has no online CPUs, that code will not run and TDX module +* initialization (TDMR initialization) will fail. +* +* This code takes no affirmative steps to online CPUs. Callers (aka. +* KVM) can ensure success by ensuring sufficient CPUs are online for +* this to succeed. +*/ +static int config_global_keyid (void ) +{ +cpumask_var_t packages; +int cpu, ret = -EINVAL ; + +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 ; + +/* +* TDH.SYS.KEY.CONFIG cannot run concurrently on +* different cpus, so just do it one by one. +*/ + ret =smp_call_on_cpu (cpu, do_global_key_config,NULL , true); +if (ret) +break ; + } + +free_cpumask_var (packages); +return ret; +} +static int init_tdx_module (void ) {struct tdsysinfo_struct *tdsysinfo;
@@ -974,15 +1065,47 @@ 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. +*/ +wbinvd_on_all_cpus (); + +/* Config the key of global KeyID on all packages */ + ret =config_global_keyid (); +if (ret) + goto out_reset_pamts; +/* * TODO: * -* - Configure the global KeyID on all packages. * - Initialize all TDMRs. * * Return error before all steps are done. */ ret = -EINVAL ; +out_reset_pamts: +if (ret) { +/* +* Part of PAMTs may already have been initialized by the +* TDX module. Flush cache before returning PAMTs back +* to the kernel. +*/ +wbinvd_on_all_cpus (); +/* +* According to the TDX hardware spec, if the platform +* doesn't have the "partial write machine check" +* erratum, any kernel read/write will never cause #MC +* in kernel space, thus it's OK to not convert PAMTs +* back to normal. But do the conversion anyway here +* as suggested by the TDX spec. +*/ +tdmrs_reset_pamt_all (&tdmr_list); + } out_free_pamts:if (ret)tdmrs_free_pamt_all (&tdmr_list);
@@ -1038,6 +1161,9 @@ static int __tdx_enable(void)* lock to prevent any new cpu from becoming online; 2) done both VMXON * and tdx_cpu_enable() on all online cpus. * +* This function requires there's at least one online cpu for each CPU +* package to succeed. +* * This function can be called in parallel by multiple callers. * * Return 0 if TDX is enabled successfully, otherwise error.
arch/x86/virt/vmx/tdx/tdx.h +1 -0
@@ -16,6 +16,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.41.0
PATCH v14 16/23 x86/virt/tdx: Initialize all TDMRs
In reply to Kai HuangAfter the global KeyID has been configured on all packages, initialize all TDMRs to make all TDX-usable memory regions that are passed to the TDX module become usable.
This is the last step of initializing the TDX module.
Initializing TDMRs can be time consuming on large memory systems as it involves initializing all metadata entries for all pages that can be used by TDX guests. Initializing different TDMRs can be parallelized. For now to keep it simple, just initialize all TDMRs one by one. It can be enhanced in the future.
---
v13 -> v14:
- No change
v12 -> v13:
- Added Yuan's tag.
v11 -> v12:
- Added Kirill's tag
v10 -> v11:
- No update
v9 -> v10:
- Code change due to change static 'tdx_tdmr_list' to local 'tdmr_list'.
v8 -> v9:
- Improved changlog to explain why initializing TDMRs can take long time (Dave).
- Improved comments around 'next-to-initialize' address (Dave).
v7 -> v8: (Dave)
- Changelog:
- explicitly call out this is the last step of TDX module initialization.
- Trimed down changelog by removing SEAMCALL name and details.
- Removed/trimmed down unnecessary comments.
- Other changes due to 'struct tdmr_info_list'.
v6 -> v7:
- Removed need_resched() check. -- Andi.
--- arch/x86/virt/vmx/tdx/tdx.c | 60 ++++++++++++++++++++++++++++++++----- arch/x86/virt/vmx/tdx/tdx.h | 1 + 2 files changed, 53 insertions(+), 8 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +52 -8
@@ -1005,6 +1005,56 @@ static int config_global_keyid(void)return ret; } +static int init_tdmr (struct tdmr_info *tdmr) +{ +u64 next; + +/* +* 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. +*/ +do { +struct tdx_module_args args = { + .rcx = tdmr->base, + }; +int ret; + + ret =seamcall_prerr_ret (TDH_SYS_TDMR_INIT , &args); +if (ret) +return ret; +/* +* RDX contains 'next-to-initialize' address if +* TDH.SYS.TDMR.INIT did not fully complete and +* should be retried. +*/ + next = args.rdx; +cond_resched (); +/* Keep making SEAMCALLs until the TDMR is done */ + }while (next < tdmr->base + tdmr->size); + +return 0 ; +} + +static int init_tdmrs (struct tdmr_info_list *tdmr_list) +{ +int i; + +/* +* This operation is costly. It can be parallelized, +* but keep it simple for now. +*/ +for (i =0 ; i < tdmr_list->nr_consumed_tdmrs; i++) { +int ret; + + ret =init_tdmr (tdmr_entry (tdmr_list, i)); +if (ret) +return ret; + } + +return 0 ; +} +static int init_tdx_module (void ) {struct tdsysinfo_struct *tdsysinfo;
@@ -1080,14 +1130,8 @@ static int init_tdx_module(void)if (ret) goto out_reset_pamts; -/* -* TODO: -* -* - Initialize all TDMRs. -* -* Return error before all steps are done. -*/ - ret = -EINVAL ; +/* Initialize TDMRs to complete the TDX module initialization */ + ret =init_tdmrs (&tdmr_list); out_reset_pamts:if (ret) {/*
arch/x86/virt/vmx/tdx/tdx.h +1 -0
@@ -20,6 +20,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_CONFIG 45struct cmr_info {
Signature · 1 line
2.41.0
PATCH v14 17/23 x86/kexec: Flush cache of TDX private memory
In reply to Kai HuangThere 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; 2) There might be dirty cachelines associated with TDX private pages.
The first problem doesn't matter on the platforms w/o the "partial write machine check" erratum. KeyID 0 doesn't have integrity check. If the new kernel wants to use any non-zero KeyID, it needs to convert the memory to that KeyID and such conversion would work from any KeyID.
However the old kernel needs to guarantee there's no dirty cacheline left behind before booting to the new kernel to avoid silent corruption from later cacheline writeback (Intel hardware doesn't guarantee cache coherency across different KeyIDs).
There are two things that the old kernel needs to do to achieve that:
1) Stop accessing TDX private memory mappings:
a. Stop making TDX module SEAMCALLs (TDX global KeyID); b. Stop TDX guests from running (per-guest TDX KeyID).
2) Flush any cachelines from previous TDX private KeyID writes.
For 2), use wbinvd() to flush cache in stop_this_cpu(), following SME support. And in this way 1) happens for free as there's no TDX activity between wbinvd() and the native_halt().
Flushing cache in stop_this_cpu() only flushes cache on remote cpus. On the rebooting cpu which does kexec(), unlike SME which does the cache flush in relocate_kernel(), flush the cache right after stopping remote cpus in machine_shutdown().
There are two reasons to do so: 1) For TDX there's no need to defer cache flush to relocate_kernel() because all TDX activities have been stopped. 2) On the platforms with the above erratum the kernel must convert all TDX private pages back to normal before booting to the new kernel in kexec(), and flushing cache early allows the kernel to convert memory early rather than having to muck with the relocate_kernel() assembly.
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 the BIOS instead to flush cache.
---
v13 -> v14:
- No change
--- arch/x86/kernel/process.c | 8 +++++++- arch/x86/kernel/reboot.c | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-)
arch/x86/kernel/process.c +7 -1
@@ -830,8 +830,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. +* +* The TDX module or guests might have left dirty cachelines +* behind. Flush them to avoid corruption from later writeback. +* Note that this flushes on all systems where TDX is possible, +* but does not actually check that TDX was in use. */ -if (c->extended_cpuid_level >=0x8000001f && (cpuid_eax (0x8000001f ) &BIT (0 ))) +if ((c->extended_cpuid_level >=0x8000001f && (cpuid_eax (0x8000001f ) &BIT (0 ))) + ||platform_tdx_enabled ())native_wbinvd ();/*
arch/x86/kernel/reboot.c +15 -0
@@ -31,6 +31,7 @@#include <asm/realmode.h> #include <asm/x86_init.h> #include <asm/efi.h> +#include <asm/tdx.h> /* * Power off function, if any
@@ -741,6 +742,20 @@ void native_machine_shutdown(void)local_irq_disable ();stop_other_cpus ();#endif +/* +* stop_other_cpus() has flushed all dirty cachelines of TDX +* private memory on remote cpus. Unlike SME, which does the +* cache flush on _this_ cpu in the relocate_kernel(), flush +* the cache for _this_ cpu here. This is because on the +* platforms with "partial write machine check" erratum the +* kernel needs to convert all TDX private pages back to normal +* before booting to the new kernel in kexec(), and the cache +* flush must be done before that. If the kernel took SME's way, +* it would have to muck with the relocate_kernel() assembly to +* do memory conversion. +*/ +if (platform_tdx_enabled ()) +native_wbinvd ();lapic_shutdown ();restore_boot_irq_mode ();
Signature · 1 line
2.41.0
PATCH v14 18/23 x86/virt/tdx: Keep TDMRs when module initialization is successful
In reply to Kai HuangOn the platforms with the "partial write machine check" erratum, the kexec() needs to convert all TDX private pages back to normal before booting to the new kernel. Otherwise, the new kernel may get unexpected machine check.
There's no existing infrastructure to track TDX private pages. Keep TDMRs when module initialization is successful so that they can be used to find PAMTs.
---
v13 -> v14:
- "Change to keep" -> "Keep" (Kirill)
- Add Kirill/Rick's tags
v12 -> v13:
- Split "improve error handling" part out as a separate patch.
v11 -> v12 (new patch):
- Defer keeping TDMRs logic to this patch for better review
- Improved error handling logic (Nikolay/Kirill in patch 15)
--- arch/x86/virt/vmx/tdx/tdx.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +11 -13
@@ -46,6 +46,8 @@ static DEFINE_MUTEX(tdx_module_lock);/* All TDX-usable memory regions. Protected by mem_hotplug_lock. */ static LIST_HEAD (tdx_memlist); +static struct tdmr_info_list tdx_tdmr_list; +typedef void (*sc_err_func_t )(u64 fn,u64 err,struct tdx_module_args *args);static inline void seamcall_err (u64 fn,u64 err,struct tdx_module_args *args)
@@ -1058,7 +1060,6 @@ static int init_tdmrs(struct tdmr_info_list *tdmr_list)static int init_tdx_module (void ) {struct tdsysinfo_struct *tdsysinfo; -struct tdmr_info_list tdmr_list;struct cmr_info *cmr_array;int tdsysinfo_size;int cmr_array_size;
@@ -1101,17 +1102,17 @@ static int init_tdx_module(void) goto out_put_tdxmem;/* Allocate enough space for constructing TDMRs */ - ret =alloc_tdmr_list (&tdmr_list, tdsysinfo); + ret =alloc_tdmr_list (&tdx_tdmr_list, tdsysinfo);if (ret) goto out_free_tdxmem;/* Cover all TDX-usable memory regions in TDMRs */ - ret =construct_tdmrs (&tdx_memlist, &tdmr_list, tdsysinfo); + ret =construct_tdmrs (&tdx_memlist, &tdx_tdmr_list, tdsysinfo);if (ret) goto out_free_tdmrs;/* Pass the TDMRs and the global KeyID to the TDX module */ - ret =config_tdx_module (&tdmr_list, tdx_global_keyid); + ret =config_tdx_module (&tdx_tdmr_list, tdx_global_keyid);if (ret) goto out_free_pamts;
@@ -1131,7 +1132,7 @@ static int init_tdx_module(void) goto out_reset_pamts;/* Initialize TDMRs to complete the TDX module initialization */ - ret =init_tdmrs (&tdmr_list); + ret =init_tdmrs (&tdx_tdmr_list); out_reset_pamts:if (ret) {/*
@@ -1148,20 +1149,17 @@ static int init_tdx_module(void)* back to normal. But do the conversion anyway here * as suggested by the TDX spec. */ -tdmrs_reset_pamt_all (&tdmr_list); +tdmrs_reset_pamt_all (&tdx_tdmr_list); } out_free_pamts:if (ret) -tdmrs_free_pamt_all (&tdmr_list); +tdmrs_free_pamt_all (&tdx_tdmr_list);else pr_info ("%lu KBs allocated for PAMT\n" , -tdmrs_count_pamt_kb (&tdmr_list)); +tdmrs_count_pamt_kb (&tdx_tdmr_list)); out_free_tdmrs: -/* -* Always free the buffer of TDMRs as they are only used during -* module initialization. -*/ -free_tdmr_list (&tdmr_list); +if (ret) +free_tdmr_list (&tdx_tdmr_list); out_free_tdxmem:if (ret)free_tdx_memlist (&tdx_memlist);
Signature · 1 line
2.41.0
PATCH v14 19/23 x86/virt/tdx: Improve readability of module initialization error handling
In reply to Kai HuangWith keeping TDMRs upon successful TDX module initialization, now only put_online_mems() and freeing the buffers of the TDSYSINFO_STRUCT and the CMR array still need to be done even when module initialization is successful. On the other hand, all other four "out_*" labels before them explicitly check the return value and only clean up when module initialization fails.
This isn't ideal. Make all other four "out_*" labels only reachable when module initialization fails to improve the readability of error handling. Rename them from "out_*" to "err_*" to reflect the fact.
---
v13 -> v14:
- Fix spell typo (Rick)
- Add Kirill/Rick's tags
v12 -> v13:
- New patch to improve error handling. (Kirill, Nikolay)
--- arch/x86/virt/vmx/tdx/tdx.c | 67 +++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 33 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +34 -33
@@ -1104,17 +1104,17 @@ static int init_tdx_module(void)/* Allocate enough space for constructing TDMRs */ ret =alloc_tdmr_list (&tdx_tdmr_list, tdsysinfo);if (ret) - goto out_free_tdxmem; + goto err_free_tdxmem;/* Cover all TDX-usable memory regions in TDMRs */ ret =construct_tdmrs (&tdx_memlist, &tdx_tdmr_list, tdsysinfo);if (ret) - goto out_free_tdmrs; + goto err_free_tdmrs;/* Pass the TDMRs and the global KeyID to the TDX module */ ret =config_tdx_module (&tdx_tdmr_list, tdx_global_keyid);if (ret) - goto out_free_pamts; + goto err_free_pamts;/* * Hardware doesn't guarantee cache coherency across different
@@ -1129,40 +1129,16 @@ static int init_tdx_module(void)/* Config the key of global KeyID on all packages */ ret =config_global_keyid ();if (ret) - goto out_reset_pamts; + goto err_reset_pamts;/* Initialize TDMRs to complete the TDX module initialization */ ret =init_tdmrs (&tdx_tdmr_list); -out_reset_pamts: -if (ret) { -/* -* Part of PAMTs may already have been initialized by the -* TDX module. Flush cache before returning PAMTs back -* to the kernel. -*/ -wbinvd_on_all_cpus (); -/* -* According to the TDX hardware spec, if the platform -* doesn't have the "partial write machine check" -* erratum, any kernel read/write will never cause #MC -* in kernel space, thus it's OK to not convert PAMTs -* back to normal. But do the conversion anyway here -* as suggested by the TDX spec. -*/ -tdmrs_reset_pamt_all (&tdx_tdmr_list); - } -out_free_pamts:if (ret) -tdmrs_free_pamt_all (&tdx_tdmr_list); -else -pr_info ("%lu KBs allocated for PAMT\n" , -tdmrs_count_pamt_kb (&tdx_tdmr_list)); -out_free_tdmrs: -if (ret) -free_tdmr_list (&tdx_tdmr_list); -out_free_tdxmem: -if (ret) -free_tdx_memlist (&tdx_memlist); + goto err_reset_pamts; + +pr_info ("%lu KBs allocated for PAMT\n" , +tdmrs_count_pamt_kb (&tdx_tdmr_list)); + out_put_tdxmem:/* * @tdx_memlist is written here and read at memory hotplug time.
@@ -1177,6 +1153,31 @@ static int init_tdx_module(void)kfree (tdsysinfo);kfree (cmr_array);return ret; + +err_reset_pamts: +/* +* Part of PAMTs may already have been initialized by the +* TDX module. Flush cache before returning PAMTs back +* to the kernel. +*/ +wbinvd_on_all_cpus (); +/* +* According to the TDX hardware spec, if the platform +* doesn't have the "partial write machine check" +* erratum, any kernel read/write will never cause #MC +* in kernel space, thus it's OK to not convert PAMTs +* back to normal. But do the conversion anyway here +* as suggested by the TDX spec. +*/ +tdmrs_reset_pamt_all (&tdx_tdmr_list); +err_free_pamts: +tdmrs_free_pamt_all (&tdx_tdmr_list); +err_free_tdmrs: +free_tdmr_list (&tdx_tdmr_list); +err_free_tdxmem: +free_tdx_memlist (&tdx_memlist); +/* Do things irrelevant to module initialization result */ + goto out_put_tdxmem; }static int __tdx_enable (void )
Signature · 1 line
2.41.0
PATCH v14 20/23 x86/kexec(): Reset TDX private memory on platforms with TDX erratum
In reply to Kai HuangThe first few generations of TDX hardware have an erratum. A partial write to a TDX private memory cacheline will silently "poison" the line. Subsequent reads will consume the poison and generate a machine check. According to the TDX hardware spec, neither of these things should have happened.
== Background ==
Virtually all kernel memory accesses operations happen in full cachelines. In practice, writing a "byte" of memory usually reads a 64 byte cacheline of memory, modifies it, then writes the whole line back. Those operations do not trigger this problem.
This problem is triggered by "partial" writes where a write transaction of less than cacheline lands at the memory controller. The CPU does these via non-temporal write instructions (like MOVNTI), or through UC/WC memory mappings. The issue can also be triggered away from the CPU by devices doing partial writes via DMA.
== Problem ==
A fast warm reset doesn't reset TDX private memory. Kexec() can also boot into the new kernel directly. Thus if the old kernel has enabled TDX on the platform with this erratum, the new kernel may get unexpected machine check.
Note that w/o this erratum any kernel read/write on TDX private memory should never cause machine check, thus it's OK for the old kernel to leave TDX private pages as is.
== Solution ==
In short, with this erratum, the kernel needs to explicitly convert all TDX private pages back to normal to give the new kernel a clean slate after kexec(). The BIOS is also expected to disable fast warm reset as a workaround to this erratum, thus this implementation doesn't try to reset TDX private memory for the reboot case in the kernel but depend on the BIOS to enable the workaround.
Convert TDX private pages back to normal after all remote cpus has been stopped and cache flush has been done on all cpus, when no more TDX activity can happen further. Do it in machine_kexec() to avoid the additional overhead to the normal reboot/shutdown as the kernel depends on the BIOS to disable fast warm reset for the reboot case.
For now TDX private memory can only be PAMT pages. It would be ideal to cover all types of TDX private memory here, but there are practical problems to do so:
1) There's no existing infrastructure to track TDX private pages;
2) It's not feasible to query the TDX module about page type because VMX has already been stopped when KVM receives the reboot notifier, plus the result from the TDX module may not be accurate (e.g., the remote CPU could be stopped right before MOVDIR64B).
One temporary solution is to blindly convert all memory pages, but it's problematic to do so too, because not all pages are mapped as writable in the direct mapping. It can be done by switching to the identical mapping created for kexec() or a new page table, but the complexity looks overkill.
Therefore, rather than doing something dramatic, only reset PAMT pages here. Other kernel components which use TDX need to do the conversion on their own by intercepting the rebooting/shutdown notifier (KVM already does that).
Note kexec() can happen at anytime, including when TDX module is being initialized. Register TDX reboot notifier callback to stop further TDX module initialization. If there's any ongoing module initialization, wait until it finishes. This makes sure the TDX module status is stable after the reboot notifier callback, and the later kexec() code can read module status to decide whether PAMTs are stable and available.
Also stop further TDX module initialization in case of machine shutdown and halt, but not limited to kexec(), as there's no reason to do so in these cases too.
---
v13 -> v14:
- Skip resetting TDX private memory when preserve_context is true (Rick)
- Use reboot notifier to stop TDX module initialization at early time of kexec() to make module status stable, to avoid using a new variable and memory barrier (which is tricky to review).
- Added Kirill's tag
v12 -> v13:
- Improve comments to explain why barrier is needed and ignore WBINVD. (Dave)
- Improve comments to document memory ordering. (Nikolay)
- Made comments/changelog slightly more concise.
v11 -> v12:
- Changed comment/changelog to say kernel doesn't try to handle fast warm reset but depends on BIOS to enable workaround (Kirill)
- Added a new tdx_may_has_private_mem to indicate system may have TDX private memory and PAMTs/TDMRs are stable to access. (Dave).
- Use atomic_t for tdx_may_has_private_mem for build-in memory barrier (Dave)
- Changed calling x86_platform.memory_shutdown() to calling tdx_reset_memory() directly from machine_kexec() to avoid overhead to normal reboot case.
v10 -> v11:
- New patch
--- arch/x86/include/asm/tdx.h | 2 + arch/x86/kernel/machine_kexec_64.c | 16 ++++++ arch/x86/virt/vmx/tdx/tdx.c | 92 ++++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+)
arch/x86/include/asm/tdx.h +2 -0
@@ -112,10 +112,12 @@ static inline u64 sc_retry(sc_func_t func, u64 fn,bool platform_tdx_enabled (void );int tdx_cpu_enable (void );int tdx_enable (void ); +void tdx_reset_memory (void );#else static inline bool platform_tdx_enabled (void ) {return false; }static inline int tdx_cpu_enable (void ) {return -ENODEV ; }static inline int tdx_enable (void ) {return -ENODEV ; } +static inline void tdx_reset_memory (void ) { }#endif /* CONFIG_INTEL_TDX_HOST */ #endif /* !__ASSEMBLY__ */
arch/x86/kernel/machine_kexec_64.c +16 -0
@@ -28,6 +28,7 @@#include <asm/setup.h> #include <asm/set_memory.h> #include <asm/cpu.h> +#include <asm/tdx.h> #ifdef CONFIG_ACPI /*
@@ -301,9 +302,24 @@ void machine_kexec(struct kimage *image)void *control_page;int save_ftrace_enabled; +/* +* For platforms with TDX "partial write machine check" erratum, +* all TDX private pages need to be converted back to normal +* before booting to the new kernel, otherwise the new kernel +* may get unexpected machine check. +* +* But skip this when preserve_context is on. The second kernel +* shouldn't write to the first kernel's memory anyway. Skipping +* this also avoids killing TDX in the first kernel, which would +* require more complicated handling. +*/ #ifdef CONFIG_KEXEC_JUMP if (image->preserve_context)save_processor_state (); +else +tdx_reset_memory (); +#else +tdx_reset_memory ();#endif save_ftrace_enabled =__ftrace_enabled_save ();
arch/x86/virt/vmx/tdx/tdx.c +92 -0
128 lines not on this page · raw message
Signature · 1 line
2.41.0
PATCH v14 21/23 x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
In reply to Kai HuangTDX cannot survive from S3 and deeper states. The hardware resets and disables TDX completely when platform goes to S3 and deeper. Both TDX guests and the TDX module get destroyed permanently.
The kernel uses S3 to support suspend-to-ram, and S4 or deeper states to support hibernation. The kernel also maintains TDX states to track whether it has been initialized and its metadata resource, etc. After resuming from S3 or hibernation, these TDX states won't be correct anymore.
Theoretically, the kernel can do more complicated things like resetting TDX internal states and TDX module metadata before going to S3 or deeper, and re-initialize TDX module after resuming, etc, but there is no way to save/restore TDX guests for now.
Until TDX supports full save and restore of TDX guests, there is no big value to handle TDX module in suspend and hibernation alone. To make things simple, just choose to make TDX mutually exclusive with S3 and hibernation.
Note the TDX module is initialized at runtime. To avoid having to deal with the fuss of determining TDX state at runtime, just choose TDX vs S3 and hibernation at kernel early boot. It's a bad user experience if the choice of TDX and S3/hibernation is done at runtime anyway, i.e., the user can experience being able to do S3/hibernation but later becoming unable to due to TDX being enabled.
Disable TDX in kernel early boot when hibernation is available, and give a message telling the user to disable hibernation via kernel command line in order to use TDX. Currently there's no mechanism exposed by the hibernation code to allow other kernel code to disable hibernation once for all.
Disable ACPI S3 by setting acpi_suspend_lowlevel function pointer to NULL when TDX is enabled by the BIOS. This avoids having to modify the ACPI code to disable ACPI S3 in other ways.
Also give a message telling the user to disable TDX in the BIOS in order to use ACPI S3. A new kernel command line can be added in the future if there's a need to let user disable TDX host via kernel command line.
---
v13 -> v14:
- New patch
--- arch/x86/virt/vmx/tdx/tdx.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)
arch/x86/virt/vmx/tdx/tdx.c +23 -0
@@ -28,10 +28,12 @@#include <linux/sort.h> #include <linux/log2.h> #include <linux/reboot.h> +#include <linux/suspend.h> #include <asm/msr-index.h> #include <asm/msr.h> #include <asm/page.h> #include <asm/special_insns.h> +#include <asm/acpi.h> #include <asm/tdx.h> #include "tdx.h"
@@ -1427,6 +1429,22 @@ static int __init tdx_init(void)return -ENODEV ; } +#define HIBERNATION_MSG \ + "Disable TDX due to hibernation is available. Use 'nohibernate' command line to disable hibernation." +/* +* Note hibernation_available() can vary when it is called at +* runtime as it checks secretmem_active() and cxl_mem_active() +* which can both vary at runtime. But here at early_init() they +* both cannot return true, thus when hibernation_available() +* returns false here, hibernation is disabled by either +* 'nohibernate' or LOCKDOWN_HIBERNATION security lockdown, +* which are both permanent. +*/ +if (hibernation_available ()) { +pr_err ("initialization failed: %s\n" ,HIBERNATION_MSG ); +return -ENODEV ; + } + err =register_memory_notifier (&tdx_memory_nb);if (err) { pr_err("initialization failed: register_memory_notifier() failed (%d)\n",
@@ -1442,6 +1460,11 @@ static int __init tdx_init(void)return -ENODEV ; } +#ifdef CONFIG_ACPI +pr_info ("Disable ACPI S3 suspend. Turn off TDX in the BIOS to use ACPI S3.\n" ); + acpi_suspend_lowlevel =NULL ; +#endif +/* * Just use the first TDX KeyID as the 'global KeyID' and * leave the rest for TDX guests.
Signature · 1 line
2.41.0
Rafael J. Wysocki
maintainerRe: [PATCH v14 21/23] x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
Quoted 71 lines · Kai Huang
TDX cannot survive from S3 and deeper states. The hardware resets and disables TDX completely when platform goes to S3 and deeper. Both TDX guests and the TDX module get destroyed permanently.
The kernel uses S3 to support suspend-to-ram, and S4 or deeper states to support hibernation. The kernel also maintains TDX states to track whether it has been initialized and its metadata resource, etc. After resuming from S3 or hibernation, these TDX states won't be correct anymore.
Theoretically, the kernel can do more complicated things like resetting TDX internal states and TDX module metadata before going to S3 or deeper, and re-initialize TDX module after resuming, etc, but there is no way to save/restore TDX guests for now.
Until TDX supports full save and restore of TDX guests, there is no big value to handle TDX module in suspend and hibernation alone. To make things simple, just choose to make TDX mutually exclusive with S3 and hibernation.
Note the TDX module is initialized at runtime. To avoid having to deal with the fuss of determining TDX state at runtime, just choose TDX vs S3 and hibernation at kernel early boot. It's a bad user experience if the choice of TDX and S3/hibernation is done at runtime anyway, i.e., the user can experience being able to do S3/hibernation but later becoming unable to due to TDX being enabled.
Disable TDX in kernel early boot when hibernation is available, and give a message telling the user to disable hibernation via kernel command line in order to use TDX. Currently there's no mechanism exposed by the hibernation code to allow other kernel code to disable hibernation once for all.
Disable ACPI S3 by setting
acpi_suspend_lowlevelfunction pointer to NULL when TDX is enabled by the BIOS. This avoids having to modify the ACPI code to disable ACPI S3 in other ways.Also give a message telling the user to disable TDX in the BIOS in order to use ACPI S3. A new kernel command line can be added in the future if there's a need to let user disable TDX host via kernel command line.
Signed-off-by Kai Huang <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>---
v13 -> v14:
- New patch--- arch/x86/virt/vmx/tdx/tdx.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)arch/x86/virt/vmx/tdx/tdx.c +2
-0@@ -28,10 +28,12 @@#include <linux/sort.h> #include <linux/log2.h> #include <linux/reboot.h> +#include <linux/suspend.h> #include <asm/msr-index.h> #include <asm/msr.h> #include <asm/page.h> #include <asm/special_insns.h> +#include <asm/acpi.h> #include <asm/tdx.h> #include "tdx.h"
arch/x86/virt/vmx/tdx/tdx.c static int __init tdx_init(void) · line 1433
Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +2
-0@@ -1427,6 +1429,22 @@ static int __init tdx_init(void)return -ENODEV ; } +#define HIBERNATION_MSG \ + "Disable TDX due to hibernation is available. Use 'nohibernate' command line to disable hibernation."
I'm not sure if this new symbol is really necessary.
The message could be as simple as "Initialization failed: Hibernation support is enabled" (assuming a properly defined pr_fmt()), because that carries enough information about the reason for the failure IMO.
How to address it can be documented elsewhere.
arch/x86/virt/vmx/tdx/tdx.c static int __init tdx_init(void) · line 1442
Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +9
-0+/* +* Note hibernation_available() can vary when it is called at +* runtime as it checks secretmem_active() and cxl_mem_active() +* which can both vary at runtime. But here at early_init() they +* both cannot return true, thus when hibernation_available() +* returns false here, hibernation is disabled by either +* 'nohibernate' or LOCKDOWN_HIBERNATION security lockdown, +* which are both permanent. +*/
IIUC, the role of the comment is to document the fact that it is OK to use hiberation_available() here, because it cannot return "false" intermittently at this point, so I would just say "At this point, hibernation_available() indicates whether or not hibernation support has been permanently disabled", without going into all of the details (which are irrelevant IMO and may change in the future).
Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +5
-0+if (hibernation_available ()) { +pr_err ("initialization failed: %s\n" ,HIBERNATION_MSG ); +return -ENODEV ; + } + err =register_memory_notifier (&tdx_memory_nb);if (err) { pr_err("initialization failed: register_memory_notifier() failed (%d)\n",
arch/x86/virt/vmx/tdx/tdx.c static int __init tdx_init(void) · line 1466
Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +4
-0@@ -1442,6 +1460,11 @@ static int __init tdx_init(void)return -ENODEV ; } +#ifdef CONFIG_ACPI +pr_info ("Disable ACPI S3 suspend. Turn off TDX in the BIOS to use ACPI S3.\n" ); + acpi_suspend_lowlevel =NULL ; +#endif
It would be somewhat nicer to have a helper for setting this pointer.
Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +1
-1+/* * Just use the first TDX KeyID as the 'global KeyID' and * leave the rest for TDX guests. --
Re: [PATCH v14 21/23] x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
Hi Rafael,
Thanks for feedback!
Quoted 9 lines
Review static int __init tdx_init(void) · line 1433
Quoted 9 lines
(quoted diff) +2
-0@@ -1427,6 +1429,22 @@ static int __init tdx_init(void) return -ENODEV; } +#define HIBERNATION_MSG \ + "Disable TDX due to hibernation is available. Use 'nohibernate'
command line to disable hibernation."
Quoted 8 lines
I'm not sure if this new symbol is really necessary.
The message could be as simple as "Initialization failed: Hibernation support is enabled" (assuming a properly defined
pr_fmt()), because that carries enough information about the reason for the failure IMO.How to address it can be documented elsewhere.
The last patch of this series is the documentation patch to add TDX host. We can add a sentence to suggest the user to use 'nohibernate' kernel command line when one sees TDX gets disabled because of hibernation being available.
But isn't better to just provide such information together in the dmesg so the user can immediately know how to resolve this issue?
If user only sees "... failed: Hibernation support is enabled", then the user will need additional knowledge to know where to look for the solution first, and only after that, the user can know how to resolve this.
Quoted 11 lines
Review static int __init tdx_init(void) · line 1442
Quoted 10 lines
(quoted diff) +9
-0+ /* + * Note hibernation_available() can vary when it is called at + * runtime as it checks secretmem_active() and cxl_mem_active() + * which can both vary at runtime. But here at early_init() they + * both cannot return true, thus when hibernation_available() + * returns false here, hibernation is disabled by either + * 'nohibernate' or LOCKDOWN_HIBERNATION security lockdown, + * which are both permanent. + */
Quoted 6 lines
IIUC, the role of the comment is to document the fact that it is OK to use
hiberation_available()here, because it cannot return "false" intermittently at this point, so I would just say "At this point,hibernation_available()indicates whether or not hibernation support has been permanently disabled", without going into all of the details (which are irrelevant IMO and may change in the future).
Agreed. Will do. Thanks.
Quoted 9 lines
Review static int __init tdx_init(void) · line 1450
Quoted 9 lines
(quoted diff) +5
-0+ if (hibernation_available()) { + pr_err("initialization failed: %s\n", HIBERNATION_MSG); + return -ENODEV; + } + err = register_memory_notifier(&tdx_memory_nb); if (err) { pr_err("initialization failed: register_memory_notifier()
failed (%d)\n",
Quoted 6 lines
Review static int __init tdx_init(void) · line 1464
Quoted 6 lines
(quoted diff) +2
-0@@ -1442,6 +1460,11 @@ static int __init tdx_init(void) return -ENODEV; } +#ifdef CONFIG_ACPI + pr_info("Disable ACPI S3 suspend. Turn off TDX in the BIOS to use
ACPI S3.\n");
Quoted 5 lines
Review static int __init tdx_init(void) · line 1466
Quoted 2 lines
(quoted diff) +2
-0+ acpi_suspend_lowlevel = NULL; +#endifIt would be somewhat nicer to have a helper for setting this pointer.
OK. Currently Xen PV dom0 also overrides the acpi_suspend_lowlevel.
Do you want the helper introduced now together with this series, or it is acceptable to have a patch later after TDX gets merged to add a helper and change both Xen and TDX code to use the helper?
Anyway, I suppose you mean we provide a helper in the ACPI code, and call that helper here in TDX code.
Just in case you want the helper now, then I think it's better to have two patches to do below ?
1) A patch to introduce the helper, and change the Xen code to use it.
2) The current TDX patch here, but change to use the new helper to set the acpi_suspend_lowlevel
I made the incremental diff to cover above based on this patch (see below, compile tested only). And the TDX part change will be split out as mentioned above.
Do you have any comments?
arch/x86/include/asm/acpi.h +4 -2
@@ -60,8 +60,10 @@ static inline void acpi_disable_pci(void)acpi_noirq_set (); } -/* Low-level suspend routine. */ -extern int (*acpi_suspend_lowlevel)(void ); +typedef int (*acpi_suspend_lowlevel_t )(void ); + +/* Set up low-level suspend routine. */ +void acpi_set_suspend_lowlevel (acpi_suspend_lowlevel_t func);/* Physical address to resume after wakeup */ unsigned long acpi_get_wakeup_address (void );
arch/x86/kernel/acpi/boot.c +8 -2
@@ -779,11 +779,17 @@ int (*__acpi_register_gsi)(struct device *dev, u32 gsi,void (*__acpi_unregister_gsi)(u32 gsi) =NULL ;#ifdef CONFIG_ACPI_SLEEP -int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel; +static int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel;#else -int (*acpi_suspend_lowlevel)(void ); +static int (*acpi_suspend_lowlevel)(void );#endif +/* To override the default acpi_suspend_lowlevel */ +void acpi_set_suspend_lowlevel (acpi_suspend_lowlevel_t func) +{ + acpi_suspend_lowlevel = func; +} +/* * success: return IRQ number (>=0) * failure: return < 0
arch/x86/virt/vmx/tdx/tdx.c +0 -0
@@ -1565,7 +1565,7 @@ static int __init tdx_init(void)#ifdef CONFIG_ACPI pr_info("Disable ACPI S3 suspend. Turn off TDX in the BIOS to use ACPI
S3.\n");
- acpi_suspend_lowlevel = NULL;
+ acpi_set_suspend_lowlevel(NULL);
#endif
/*
include/xen/acpi.h +1 -1
@@ -64,7 +64,7 @@ static inline void xen_acpi_sleep_register(void)acpi_os_set_prepare_extended_sleep ( &xen_acpi_notify_hypervisor_extended_sleep); - acpi_suspend_lowlevel = xen_acpi_suspend_lowlevel; + acpi_set_suspend_lowlevel(xen_acpi_suspend_lowlevel); } }#else
Quoted 1 line
Rafael J. Wysocki
maintainerRe: [PATCH v14 21/23] x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
Quoted 27 lines · Kai
Hi Rafael,
Thanks for feedback!Quoted 9 lines
Review static int __init tdx_init(void) · line 1433
Quoted 9 lines
(quoted diff) +2
-0@@ -1427,6 +1429,22 @@ static int __init tdx_init(void) return -ENODEV; } +#define HIBERNATION_MSG \ + "Disable TDX due to hibernation is available. Use 'nohibernate'command line to disable hibernation."
Quoted 8 lines
I'm not sure if this new symbol is really necessary.
The message could be as simple as "Initialization failed: Hibernation support is enabled" (assuming a properly defined
pr_fmt()), because that carries enough information about the reason for the failure IMO.How to address it can be documented elsewhere.
The last patch of this series is the documentation patch to add TDX host. We can add a sentence to suggest the user to use 'nohibernate' kernel command line when one sees TDX gets disabled because of hibernation being available.
Quoted 6 lines
But isn't better to just provide such information together in the dmesg so the user can immediately know how to resolve this issue?
If user only sees "... failed: Hibernation support is enabled", then the user will need additional knowledge to know where to look for the solution first, and only after that, the user can know how to resolve this.
I would expect anyone interested in a given feature to get familiar with its documentation in the first place. If they neglect to do that and then find this message, it is absolutely fair to expect them to go and look into the documentation after all.
Quoted 45 lines
Quoted 11 lines
Review static int __init tdx_init(void) · line 1442
Quoted 10 lines
(quoted diff) +9
-0+ /* + * Note hibernation_available() can vary when it is called at + * runtime as it checks secretmem_active() and cxl_mem_active() + * which can both vary at runtime. But here at early_init() they + * both cannot return true, thus when hibernation_available() + * returns false here, hibernation is disabled by either + * 'nohibernate' or LOCKDOWN_HIBERNATION security lockdown, + * which are both permanent. + */Quoted 6 lines
IIUC, the role of the comment is to document the fact that it is OK to use
hiberation_available()here, because it cannot return "false" intermittently at this point, so I would just say "At this point,hibernation_available()indicates whether or not hibernation support has been permanently disabled", without going into all of the details (which are irrelevant IMO and may change in the future).Agreed. Will do. Thanks.
Quoted 9 lines
Review static int __init tdx_init(void) · line 1450
Quoted 9 lines
(quoted diff) +5
-0+ if (hibernation_available()) { + pr_err("initialization failed: %s\n", HIBERNATION_MSG); + return -ENODEV; + } + err = register_memory_notifier(&tdx_memory_nb); if (err) { pr_err("initialization failed: register_memory_notifier()failed (%d)\n",
Quoted 6 lines
Review static int __init tdx_init(void) · line 1464
Quoted 6 lines
(quoted diff) +2
-0@@ -1442,6 +1460,11 @@ static int __init tdx_init(void) return -ENODEV; } +#ifdef CONFIG_ACPI + pr_info("Disable ACPI S3 suspend. Turn off TDX in the BIOS to useACPI S3.\n");
Quoted 5 lines
Review static int __init tdx_init(void) · line 1466
Quoted 2 lines
(quoted diff) +2
-0+ acpi_suspend_lowlevel = NULL; +#endifIt would be somewhat nicer to have a helper for setting this pointer.
Quoted 8 lines
OK. Currently Xen PV dom0 also overrides the
acpi_suspend_lowlevel.Do you want the helper introduced now together with this series, or it is acceptable to have a patch later after TDX gets merged to add a helper and change both Xen and TDX code to use the helper?
Anyway, I suppose you mean we provide a helper in the ACPI code, and call that helper here in TDX code.
Yes, I do.
Quoted 6 lines
Just in case you want the helper now, then I think it's better to have two patches to do below ?
1) A patch to introduce the helper, and change the Xen code to use it.
2) The current TDX patch here, but change to use the new helper to set theacpi_suspend_lowlevel
Yes, this makes sense to me.
Quoted 11 lines
I made the incremental diff to cover above based on this patch (see below, compile tested only). And the TDX part change will be split out as mentioned above.
Do you have any comments?
arch/x86/include/asm/acpi.h +0
-0
arch/x86/include/asm/acpi.h static inline void acpi_disable_pci(void) · line 66
Quoted 9 lines
arch/x86/include/asm/acpi.h +4
-2@@ -60,8 +60,10 @@ static inline void acpi_disable_pci(void)acpi_noirq_set (); } -/* Low-level suspend routine. */ -extern int (*acpi_suspend_lowlevel)(void ); +typedef int (*acpi_suspend_lowlevel_t )(void ); + +/* Set up low-level suspend routine. */ +void acpi_set_suspend_lowlevel (acpi_suspend_lowlevel_t func);
I'm not sure about the typededf, but I have no strong opinion against it either.
Quoted 8 lines
arch/x86/include/asm/acpi.h +0
-0/* Physical address to resume after wakeup */ unsigned long acpi_get_wakeup_address (void );arch/x86/kernel/acpi/boot.c +0
-0
arch/x86/kernel/acpi/boot.c int (*__acpi_register_gsi)(struct device *dev, u32 gsi, · line 784
Quoted 8 lines
arch/x86/kernel/acpi/boot.c +2
-2@@ -779,11 +779,17 @@ int (*__acpi_register_gsi)(struct device *dev, u32 gsi,void (*__acpi_unregister_gsi)(u32 gsi) =NULL ;#ifdef CONFIG_ACPI_SLEEP -int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel; +static int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel;#else -int (*acpi_suspend_lowlevel)(void ); +static int (*acpi_suspend_lowlevel)(void );
For the sake of consistency, either use the typedef here, or don't use it at all.
Quoted 30 lines
arch/x86/kernel/acpi/boot.c +6
-0#endif +/* To override the default acpi_suspend_lowlevel */ +void acpi_set_suspend_lowlevel (acpi_suspend_lowlevel_t func) +{ + acpi_suspend_lowlevel = func; +} +/* * success: return IRQ number (>=0) * failure: return < 0 arch/x86/virt/vmx/tdx/tdx.c +1
-1@@ -1565,7 +1565,7 @@ static int __init tdx_init(void)#ifdef CONFIG_ACPI pr_info("Disable ACPI S3 suspend. Turn off TDX in the BIOS to use ACPI S3.\n"); - acpi_suspend_lowlevel =NULL ; +acpi_set_suspend_lowlevel (NULL );#endif /*include/xen/acpi.h +0
-0
include/xen/acpi.h static inline void xen_acpi_sleep_register(void) · line 70
Quoted 8 lines
include/xen/acpi.h +1
-1@@ -64,7 +64,7 @@ static inline void xen_acpi_sleep_register(void)acpi_os_set_prepare_extended_sleep ( &xen_acpi_notify_hypervisor_extended_sleep); - acpi_suspend_lowlevel = xen_acpi_suspend_lowlevel; + acpi_set_suspend_lowlevel(xen_acpi_suspend_lowlevel); } }#else
Otherwise LGTM.
Re: [PATCH v14 21/23] x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
Quoted 31 lines · Rafael J. Wysocki
Quoted 30 lines · Kai
Hi Rafael,
Thanks for feedback!Quoted 9 lines
Review static int __init tdx_init(void) · line 1433
Quoted 9 lines
(quoted diff) +2
-0@@ -1427,6 +1429,22 @@ static int __init tdx_init(void) return -ENODEV; } +#define HIBERNATION_MSG \ + "Disable TDX due to hibernation is available. Use 'nohibernate'command line to disable hibernation."
Quoted 8 lines
I'm not sure if this new symbol is really necessary.
The message could be as simple as "Initialization failed: Hibernation support is enabled" (assuming a properly defined
pr_fmt()), because that carries enough information about the reason for the failure IMO.How to address it can be documented elsewhere.
The last patch of this series is the documentation patch to add TDX host. We can add a sentence to suggest the user to use 'nohibernate' kernel command line when one sees TDX gets disabled because of hibernation being available.
But isn't better to just provide such information together in the dmesg so the user can immediately know how to resolve this issue?
Quoted 8 lines
Quoted 3 lines
If user only sees "... failed: Hibernation support is enabled", then the user will need additional knowledge to know where to look for the solution first, and only after that, the user can know how to resolve this.
I would expect anyone interested in a given feature to get familiar with its documentation in the first place. If they neglect to do that and then find this message, it is absolutely fair to expect them to go and look into the documentation after all.
OK. I'll remove HIBERNATION_MSG and just print the message suggested by you.
And in the documentation patch, add one sentence to tell user when this happens, add 'nohibernate' to resolve.
[...]
Quoted 20 lines
arch/x86/include/asm/acpi.h static inline void acpi_disable_pci(void) · line 66
Quoted 7 lines
arch/x86/include/asm/acpi.h +4
-2-/* Low-level suspend routine. */ -extern int (*acpi_suspend_lowlevel)(void ); +typedef int (*acpi_suspend_lowlevel_t )(void ); + +/* Set up low-level suspend routine. */ +void acpi_set_suspend_lowlevel (acpi_suspend_lowlevel_t func);I'm not sure about the typededf, but I have no strong opinion against it either.
Quoted 10 lines
/* Physical address to resume after wakeup */
unsigned longacpi_get_wakeup_address(void);arch/x86/kernel/acpi/boot.c +0
-0@@ -779,11 +779,17 @@ int (*__acpi_register_gsi)(struct device *dev, u32 gsi,void (*__acpi_unregister_gsi)(u32 gsi) =NULL ;
Quoted 9 lines
arch/x86/kernel/acpi/boot.c int (*__acpi_register_gsi)(struct device *dev, u32 gsi, · line 784
Quoted 6 lines
arch/x86/kernel/acpi/boot.c +2
-2#ifdef CONFIG_ACPI_SLEEP -int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel; +static int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel;#else -int (*acpi_suspend_lowlevel)(void ); +static int (*acpi_suspend_lowlevel)(void );For the sake of consistency, either use the typedef here, or don't use it at all.
Ah right.
Since you don't prefer the typedef, I'll abandon it:
E.g,:
void acpi_set_suspend_lowlevel(int (*suspend_lowlevel)(void))
{
acpi_suspend_lowlevel = suspend_lowlevel;
}Let me know whether this looks good to you?
[...]
Quoted 2 lines
Otherwise LGTM.
Thanks. I'll split the helper patch out and include it to the next version of this series.
Rafael J. Wysocki
maintainerRe: [PATCH v14 21/23] x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
Quoted 84 lines · Kai
Quoted 31 lines · Rafael J. Wysocki
Quoted 30 lines · Kai
Hi Rafael,
Thanks for feedback!Quoted 9 lines
Review static int __init tdx_init(void) · line 1433
Quoted 9 lines
(quoted diff) +2
-0@@ -1427,6 +1429,22 @@ static int __init tdx_init(void) return -ENODEV; } +#define HIBERNATION_MSG \ + "Disable TDX due to hibernation is available. Use 'nohibernate'command line to disable hibernation."
Quoted 8 lines
I'm not sure if this new symbol is really necessary.
The message could be as simple as "Initialization failed: Hibernation support is enabled" (assuming a properly defined
pr_fmt()), because that carries enough information about the reason for the failure IMO.How to address it can be documented elsewhere.
The last patch of this series is the documentation patch to add TDX host. We can add a sentence to suggest the user to use 'nohibernate' kernel command line when one sees TDX gets disabled because of hibernation being available.
But isn't better to just provide such information together in the dmesg so the user can immediately know how to resolve this issue?
Quoted 8 lines
Quoted 3 lines
If user only sees "... failed: Hibernation support is enabled", then the user will need additional knowledge to know where to look for the solution first, and only after that, the user can know how to resolve this.
I would expect anyone interested in a given feature to get familiar with its documentation in the first place. If they neglect to do that and then find this message, it is absolutely fair to expect them to go and look into the documentation after all.
OK. I'll remove
HIBERNATION_MSGand just print the message suggested by you.And in the documentation patch, add one sentence to tell user when this happens, add 'nohibernate' to resolve.
[...]
Quoted 20 lines
arch/x86/include/asm/acpi.h static inline void acpi_disable_pci(void) · line 66
Quoted 7 lines
arch/x86/include/asm/acpi.h +4
-2-/* Low-level suspend routine. */ -extern int (*acpi_suspend_lowlevel)(void ); +typedef int (*acpi_suspend_lowlevel_t )(void ); + +/* Set up low-level suspend routine. */ +void acpi_set_suspend_lowlevel (acpi_suspend_lowlevel_t func);I'm not sure about the typededf, but I have no strong opinion against it either.
Quoted 10 lines
/* Physical address to resume after wakeup */
unsigned longacpi_get_wakeup_address(void);arch/x86/kernel/acpi/boot.c +0
-0@@ -779,11 +779,17 @@ int (*__acpi_register_gsi)(struct device *dev, u32 gsi,void (*__acpi_unregister_gsi)(u32 gsi) =NULL ;Quoted 9 lines
arch/x86/kernel/acpi/boot.c int (*__acpi_register_gsi)(struct device *dev, u32 gsi, · line 784
Quoted 6 lines
arch/x86/kernel/acpi/boot.c +2
-2#ifdef CONFIG_ACPI_SLEEP -int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel; +static int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel;#else -int (*acpi_suspend_lowlevel)(void ); +static int (*acpi_suspend_lowlevel)(void );For the sake of consistency, either use the typedef here, or don't use it at all.
Ah right.
Since you don't prefer the typedef, I'll abandon it:
Quoted 8 lines
E.g,:
void
acpi_set_suspend_lowlevel(int (*suspend_lowlevel)(void)){ acpi_suspend_lowlevel = suspend_lowlevel; }Let me know whether this looks good to you?
Yes, this is fine with me.
Quoted 8 lines
[...]
Quoted 2 lines
Otherwise LGTM.
Thanks. I'll split the helper patch out and include it to the next version of this series.
Re: [PATCH v14 21/23] x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
Quoted 37 lines
Quoted 37 lines
Quoted 21 lines
Review
Quoted 8 lines
(quoted diff) +4
-2-/* Low-level suspend routine. */ -extern int (*acpi_suspend_lowlevel)(void); +typedef int (*acpi_suspend_lowlevel_t)(void); + +/* Set up low-level suspend routine. */ +void acpi_set_suspend_lowlevel(acpi_suspend_lowlevel_t func);I'm not sure about the typededf, but I have no strong opinion against it either.
Quoted 10 lines
/* Physical address to resume after wakeup */
unsigned longacpi_get_wakeup_address(void);arch/x86/kernel/acpi/boot.c +0
-0@@ -779,11 +779,17 @@ int (*__acpi_register_gsi)(struct device *dev, u32 gsi,void (*__acpi_unregister_gsi)(u32 gsi) =NULL ;Quoted 9 lines
arch/x86/kernel/acpi/boot.c int (*__acpi_register_gsi)(struct device *dev, u32 gsi, · line 784
Quoted 6 lines
arch/x86/kernel/acpi/boot.c +2
-2#ifdef CONFIG_ACPI_SLEEP -int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel; +static int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel;#else -int (*acpi_suspend_lowlevel)(void ); +static int (*acpi_suspend_lowlevel)(void );For the sake of consistency, either use the typedef here, or don't use it at all.
Ah right.
Since you don't prefer the typedef, I'll abandon it:
E.g,:
Quoted 9 lines
Quoted 6 lines
void
acpi_set_suspend_lowlevel(int (*suspend_lowlevel)(void)){ acpi_suspend_lowlevel = suspend_lowlevel; }Let me know whether this looks good to you?
Yes, this is fine with me.
Hi Rafael,
Sorry for the back and forth on this.
With the patch which provides the helper, LKP reported build error:
drivers/acpi/sleep.c: In function 'acpi_suspend_enter':
Quoted 1 line
Quoted 1 line
drivers/acpi/sleep.c:600:22: error: 'acpi_suspend_lowlevel' undeclared (first
use in this function); did you mean 'acpi_set_suspend_lowlevel'?
600 | if (!acpi_suspend_lowlevel)
| ^~~~~~~~~~~~~~~~~~~~~
| acpi_set_suspend_lowlevelTurns out I disabled both suspend/hibernation in my own kernel build test, sigh.
The common ACPI sleep code requires the ARCH to declare 'acpi_suspend_lowlevel' in <asm/acpi.h>, and define it somewhere in the ARCH code too.
So sadly I cannot remove the acpi_suspend_lowlevel variable declaration in <asm/acpi.h>. And the ending patch would have both below in <asm/acpi.h>:
/* Low-level suspend routine. */ extern int (*acpi_suspend_lowlevel)(void);
+/* To override @acpi_suspend_lowlevel at early boot */ +void acpi_set_suspend_lowlevel(int (*suspend_lowlevel)(void)); +
Thus I am not sure whether it still a good idea to have the helper?
Any comments? Thanks!
Below is the full patch that I end up for your reference:
From 9372e0278e2a14419d08e8df36e474dc72d93784 Mon Sep 17 00:00:00 2001
From: Kai Huang <[email protected]>
Date: Thu, 19 Oct 2023 14:37:19 +1300
Subject: [PATCH] x86/acpi: Add a helper to override ACPI lowlevel suspend
function
ACPI S3 suspend code requires a valid 'acpi_suspend_lowlevel' function pointer to work. Each ARCH needs to set the acpi_suspend_lowlevel to its own implementation to make ACPI S3 suspend work on that ARCH. X86 implements a default function for that, and Xen PV dom0 overrides it with its own version during early kernel boot.
Intel Trusted Domain Extensions (TDX) doesn't play nice with ACPI S3. ACPI S3 suspend will gets disabled during kernel early boot if TDX is enabled.
Add a helper function to override the acpi_suspend_lowlevel at kernel early boot, so that the callers don't manipulate the function pointer directly. Change the Xen code to use the helper. It will be used by TDX code to disable ACPI S3 suspend too.
No functional change is intended.
--- arch/x86/include/asm/acpi.h | 3 +++ arch/x86/kernel/acpi/boot.c | 9 +++++++-- include/xen/acpi.h | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-)
arch/x86/include/asm/acpi.h +3 -0
@@ -63,6 +63,9 @@ static inline void acpi_disable_pci(void)/* Low-level suspend routine. */ extern int (*acpi_suspend_lowlevel)(void ); +/* To override @acpi_suspend_lowlevel at early boot */ +void acpi_set_suspend_lowlevel (int (*suspend_lowlevel)(void )); +/* Physical address to resume after wakeup */ unsigned long acpi_get_wakeup_address (void );
arch/x86/kernel/acpi/boot.c +7 -2
@@ -779,11 +779,16 @@ int (*__acpi_register_gsi)(struct device *dev, u32 gsi,void (*__acpi_unregister_gsi)(u32 gsi) =NULL ;#ifdef CONFIG_ACPI_SLEEP -int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel; +static int (*acpi_suspend_lowlevel)(void ) = x86_acpi_suspend_lowlevel;#else -int (*acpi_suspend_lowlevel)(void ); +static int (*acpi_suspend_lowlevel)(void );#endif +void __init acpi_set_suspend_lowlevel (int (*suspend_lowlevel)(void )) +{ + acpi_suspend_lowlevel = suspend_lowlevel; +} +/* * success: return IRQ number (>=0) * failure: return < 0
include/xen/acpi.h +1 -1
@@ -64,7 +64,7 @@ static inline void xen_acpi_sleep_register(void)acpi_os_set_prepare_extended_sleep ( &xen_acpi_notify_hypervisor_extended_sleep); - acpi_suspend_lowlevel = xen_acpi_suspend_lowlevel; + acpi_set_suspend_lowlevel(xen_acpi_suspend_lowlevel); } }#else
Signature · 1 line
2.41.0
Re: [PATCH v14 21/23] x86/virt/tdx: Handle TDX interaction with ACPI S3 and deeper states
Quoted 22 lines
Hi Rafael,
Sorry for the back and forth on this.
With the patch which provides the helper, LKP reported build error:
drivers/acpi/sleep.c: In function '
acpi_suspend_enter':Quoted 1 line
Quoted 1 line
drivers/acpi/sleep.c:600:22: error: 'acpi_suspend_lowlevel' undeclared (firstuse in this function); did you mean '
acpi_set_suspend_lowlevel'?
600 | if (!acpi_suspend_lowlevel)| ^~~~~~~~~~~~~~~~~~~~~ | acpi_set_suspend_lowlevelTurns out I disabled both suspend/hibernation in my own kernel build test, sigh.
The common ACPI sleep code requires the ARCH to declare '
acpi_suspend_lowlevel' in <asm/acpi.h>, and define it somewhere in the ARCH code too.So sadly I cannot remove the
acpi_suspend_lowlevelvariable declaration in <asm/acpi.h>. And the ending patch would have both below in <asm/acpi.h>:
Quoted 9 lines
/* Low-level suspend routine. */
extern int (*acpi_suspend_lowlevel)(void);+/* To override @acpi_suspend_lowlevel at early boot */ +void
acpi_set_suspend_lowlevel(int (*suspend_lowlevel)(void)); +Thus I am not sure whether it still a good idea to have the helper?
Hi Rafael,
Could you help to take a look whether you still want the helper?
Ans sorry in previous reply I pasted an old/wrong patch, please ignore. Below is the patch that can build successfully.
x86/acpi: Add a helper to override ACPI lowlevel suspend function
ACPI S3 suspend code requires a valid 'acpi_suspend_lowlevel' function pointer to work. Each ARCH needs to set the acpi_suspend_lowlevel to its own implementation to make ACPI S3 suspend work on that ARCH. X86 implements a default function for that, and Xen PV dom0 overrides it with its own version during early kernel boot.
Intel Trusted Domain Extensions (TDX) doesn't play nice with ACPI S3. ACPI S3 suspend will gets disabled during kernel early boot if TDX is enabled.
Add a helper function to override the acpi_suspend_lowlevel at kernel early boot, so that the callers don't manipulate the function pointer directly. Change the Xen code to use the helper. It will be used by TDX code to disable ACPI S3 suspend too.
No functional change is intended.
--- arch/x86/include/asm/acpi.h | 3 +++ arch/x86/kernel/acpi/boot.c | 5 +++++ include/xen/acpi.h | 2 +- 3 files changed, 9 insertions(+), 1 deletion(-)
arch/x86/include/asm/acpi.h +3 -0
@@ -63,6 +63,9 @@ static inline void acpi_disable_pci(void)/* Low-level suspend routine. */ extern int (*acpi_suspend_lowlevel)(void ); +/* To override @acpi_suspend_lowlevel at early boot */ +void acpi_set_suspend_lowlevel (int (*suspend_lowlevel)(void )); +/* Physical address to resume after wakeup */ unsigned long acpi_get_wakeup_address (void );
arch/x86/kernel/acpi/boot.c +0 -0
@@ -784,6 +784,11 @@ int (*acpi_suspend_lowlevel)(void) =
x86_acpi_suspend_lowlevel;
int (*acpi_suspend_lowlevel)(void);
#endif
+void __init acpi_set_suspend_lowlevel(int (*suspend_lowlevel)(void)) +{
+ acpi_suspend_lowlevel = suspend_lowlevel;
+}
+
/*
* success: return IRQ number (>=0)
* failure: return < 0
include/xen/acpi.h +1 -1
@@ -64,7 +64,7 @@ static inline void xen_acpi_sleep_register(void)acpi_os_set_prepare_extended_sleep ( &xen_acpi_notify_hypervisor_extended_sleep); - acpi_suspend_lowlevel = xen_acpi_suspend_lowlevel; + acpi_set_suspend_lowlevel(xen_acpi_suspend_lowlevel); } }#else
Signature · 1 line
2.41.0
PATCH v14 22/23 x86/mce: Improve error log of kernel space TDX #MC due to erratum
In reply to Kai HuangThe first few generations of TDX hardware have an erratum. Triggering it in Linux requires some kind of kernel bug involving relatively exotic memory writes to TDX private memory and will manifest via spurious-looking machine checks when reading the affected memory.
== Background ==
Virtually all kernel memory accesses operations happen in full cachelines. In practice, writing a "byte" of memory usually reads a 64 byte cacheline of memory, modifies it, then writes the whole line back. Those operations do not trigger this problem.
This problem is triggered by "partial" writes where a write transaction of less than cacheline lands at the memory controller. The CPU does these via non-temporal write instructions (like MOVNTI), or through UC/WC memory mappings. The issue can also be triggered away from the CPU by devices doing partial writes via DMA.
== Problem ==
A partial write to a TDX private memory cacheline will silently "poison" the line. Subsequent reads will consume the poison and generate a machine check. According to the TDX hardware spec, neither of these things should have happened.
To add insult to injury, the Linux machine code will present these as a literal "Hardware error" when they were, in fact, a software-triggered issue.
== Solution ==
In the end, this issue is hard to trigger. Rather than do something rash (and incomplete) like unmap TDX private memory from the direct map, improve the machine check handler.
Currently, the #MC handler doesn't distinguish whether the memory is TDX private memory or not but just dump, for instance, below message:
[...] mce: [Hardware Error]: CPU 147: Machine Check Exception: f Bank 1: bd80000000100134 [...] mce: [Hardware Error]: RIP 10:<ffffffffadb69870> {__tlb_remove_page_size+0x10/0xa0}
...
[...] mce: [Hardware Error]: Run the above through 'mcelog --ascii'
[...] mce: [Hardware Error]: Machine check: Data load in unrecoverable area of kernel [...] Kernel panic - not syncing: Fatal local machine check
Which says "Hardware Error" and "Data load in unrecoverable area of kernel".
Ideally, it's better for the log to say "software bug around TDX private memory" instead of "Hardware Error". But in reality the real hardware memory error can happen, and sadly such software-triggered #MC cannot be distinguished from the real hardware error. Also, the error message is used by userspace tool 'mcelog' to parse, so changing the output may break userspace.
So keep the "Hardware Error". The "Data load in unrecoverable area of kernel" is also helpful, so keep it too.
Instead of modifying above error log, improve the error log by printing additional TDX related message to make the log like:
...
[...] mce: [Hardware Error]: Machine check: Data load in unrecoverable area of kernel [...] mce: [Hardware Error]: Machine Check: TDX private memory error. Possible kernel bug.
Adding this additional message requires determination of whether the memory page is TDX private memory. There is no existing infrastructure to do that. Add an interface to query the TDX module to fill this gap.
== Impact ==
This issue requires some kind of kernel bug to trigger.
TDX private memory should never be mapped UC/WC. A partial write originating from these mappings would require *two* bugs, first mapping the wrong page, then writing the wrong memory. It would also be detectable using traditional memory corruption techniques like DEBUG_PAGEALLOC.
MOVNTI (and friends) could cause this issue with something like a simple buffer overrun or use-after-free on the direct map. It should also be detectable with normal debug techniques.
The one place where this might get nasty would be if the CPU read data then wrote back the same data. That would trigger this problem but would not, for instance, set off mechanisms like slab redzoning because it doesn't actually corrupt data.
With an IOMMU at least, the DMA exposure is similar to the UC/WC issue. TDX private memory would first need to be incorrectly mapped into the I/O space and then a later DMA to that mapping would actually cause the poisoning event.
---
v13 -> v14:
- No change
v12 -> v13:
- Added Kirill and Yuan's tag.
v11 -> v12:
- Simplified #MC message (Dave/Kirill)
- Slightly improved some comments.
v10 -> v11:
- New patch
--- arch/x86/include/asm/tdx.h | 2 + arch/x86/kernel/cpu/mce/core.c | 33 +++++++++++ arch/x86/virt/vmx/tdx/tdx.c | 103 +++++++++++++++++++++++++++++++++ arch/x86/virt/vmx/tdx/tdx.h | 5 ++ 4 files changed, 143 insertions(+)
arch/x86/include/asm/tdx.h +2 -0
@@ -113,11 +113,13 @@ bool platform_tdx_enabled(void);int tdx_cpu_enable (void );int tdx_enable (void );void tdx_reset_memory (void ); +bool tdx_is_private_mem (unsigned long phys);#else static inline bool platform_tdx_enabled (void ) {return false; }static inline int tdx_cpu_enable (void ) {return -ENODEV ; }static inline int tdx_enable (void ) {return -ENODEV ; }static inline void tdx_reset_memory (void ) { } +static inline bool tdx_is_private_mem (unsigned long phys) {return false; }#endif /* CONFIG_INTEL_TDX_HOST */ #endif /* !__ASSEMBLY__ */
arch/x86/kernel/cpu/mce/core.c +33 -0
@@ -52,6 +52,7 @@#include <asm/mce.h> #include <asm/msr.h> #include <asm/reboot.h> +#include <asm/tdx.h> #include "internal.h"
@@ -228,11 +229,34 @@ static void wait_for_panic(void)panic ("Panicing machine check CPU died" ); } +static const char *mce_memory_info (struct mce *m) +{ +if (!m || !mce_is_memory_error (m) || !mce_usable_address (m)) +return NULL ; + +/* +* Certain initial generations of TDX-capable CPUs have an +* erratum. A kernel non-temporal partial write to TDX private +* memory poisons that memory, and a subsequent read of that +* memory triggers #MC. +* +* However such #MC caused by software cannot be distinguished +* from the real hardware #MC. Just print additional message +* to show such #MC may be result of the CPU erratum. +*/ +if (!boot_cpu_has_bug (X86_BUG_TDX_PW_MCE )) +return NULL ; + +return !tdx_is_private_mem (m->addr) ?NULL : +"TDX private memory error. Possible kernel bug." ; +} + static noinstr void mce_panic(const char *msg, struct mce *final, char *exp) {struct llist_node *pending;struct mce_evt_llist *l;int apei_err =0 ; +const char *memmsg;/* * Allow instrumentation around external facilities usage. Not that it
@@ -283,6 +307,15 @@ static noinstr void mce_panic(const char *msg, struct mce *final, char *exp) }if (exp)pr_emerg (HW_ERR "Machine check: %s\n" , exp); +/* +* Confidential computing platforms such as TDX platforms +* may occur MCE due to incorrect access to confidential +* memory. Print additional information for such error. +*/ + memmsg =mce_memory_info (final); +if (memmsg) +pr_emerg (HW_ERR "Machine check: %s\n" , memmsg); +if (!fake_panic) {if (panic_timeout ==0 ) panic_timeout = mca_cfg.panic_timeout;
arch/x86/virt/vmx/tdx/tdx.c +103 -0
109 lines not on this page · raw message
arch/x86/virt/vmx/tdx/tdx.h +5 -0
@@ -16,6 +16,7 @@/* * TDX module SEAMCALL leaf functions */ +#define TDH_PHYMEM_PAGE_RDMD 24#define TDH_SYS_KEY_CONFIG 31#define TDH_SYS_INFO 32#define TDH_SYS_INIT 33
@@ -23,6 +24,10 @@#define TDH_SYS_TDMR_INIT 36#define TDH_SYS_CONFIG 45 +/* TDX page types */ +#define PT_NDA 0x0 +#define PT_RSVD 0x1 +struct cmr_info {u64 base;u64 size;
Signature · 1 line
2.41.0
PATCH v14 23/23 Documentation/x86: Add documentation for TDX host support
In reply to Kai HuangAdd 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.
---
- Added new sections for "Erratum" and "TDX vs S3/hibernation"
--- Documentation/arch/x86/tdx.rst | 217 +++++++++++++++++++++++++++++++-- 1 file changed, 206 insertions(+), 11 deletions(-)
Documentation/arch/x86/tdx.rst +206 -11
@@ -10,6 +10,201 @@ 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:: + + [..] virt/tdx: BIOS enabled: private KeyID range: [16, 64) + +TDX module initialization +--------------------------------------- + +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. + +If the TDX module isn't loaded, the SEAMCALL instruction fails with a +special error. In this case the kernel fails the module initialization +and reports the module isn't loaded:: + + [..] virt/tdx: module not loaded + +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. + +Besides initializing the TDX module, a per-cpu initialization SEAMCALL +must be done on one cpu before any other SEAMCALLs can be made on that +cpu. + +The kernel provides two functions, tdx_enable() and tdx_cpu_enable() to +allow the user of TDX to enable the TDX module and enable TDX on local +cpu. + +Making SEAMCALL requires the CPU already being in VMX operation (VMXON +has been done). For now both tdx_enable() and tdx_cpu_enable() don't +handle VMXON internally, but depends on the caller to guarantee that. + +To enable TDX, the caller of TDX should: 1) hold read lock of CPU hotplug +lock; 2) do VMXON and tdx_enable_cpu() on all online cpus successfully; +3) call tdx_enable(). For example:: + + cpus_read_lock(); + on_each_cpu(vmxon_and_tdx_cpu_enable()); + ret = tdx_enable(); + cpus_read_unlock(); + if (ret) + goto no_tdx; + // TDX is ready to use + +And the caller of TDX must guarantee the tdx_cpu_enable() has been +successfully done on any cpu before it wants to run any other SEAMCALL. +A typical usage is do both VMXON and tdx_cpu_enable() in CPU hotplug +online callback, and refuse to online if tdx_cpu_enable() fails. + +User can consult dmesg to see whether the TDX module has been initialized. + +If the TDX module is initialized successfully, dmesg shows something +like below:: + + [..] virt/tdx: TDX module: attributes 0x0, vendor_id 0x8086, major_version 1, minor_version 0, build_date 20211209, build_num 160 + [..] virt/tdx: 262668 KBs allocated for PAMT + [..] virt/tdx: module initialized + +If the TDX module failed to initialize, dmesg also shows it failed to +initialize:: + + [..] virt/tdx: module initialization failed ... + +TDX Interaction to Other Kernel Components +------------------------------------------ + +TDX Memory Policy +~~~~~~~~~~~~~~~~~ + +TDX reports a list of "Convertible Memory Region" (CMR) to tell the +kernel which memory is TDX compatible. The kernel needs to build a list +of memory regions (out of CMRs) as "TDX-usable" memory and pass those +regions to the TDX module. Once this is done, those "TDX-usable" memory +regions are fixed during module's lifetime. + +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 in the meantime, refuses to online any non-TDX-memory +in the memory hotplug. + +Physical Memory Hotplug +~~~~~~~~~~~~~~~~~~~~~~~ + +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 module requires the per-cpu initialization SEAMCALL (TDH.SYS.LP.INIT) +must be done on one cpu before any other SEAMCALLs can be made on that +cpu, including those involved during the module initialization. + +The kernel provides tdx_cpu_enable() to let the user of TDX to do it when +the user wants to use a new cpu for TDX task. + +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; 2) There might be dirty cachelines associated +with TDX private pages. + +The first problem doesn't matter. KeyID 0 doesn't have integrity check. +Even the new kernel wants use any non-zero KeyID, it needs to convert +the memory to that KeyID and such conversion would work from any KeyID. + +However the old kernel needs to guarantee there's no dirty cacheline +left behind before booting to the new kernel to avoid silent corruption +from later cacheline writeback (Intel hardware doesn't guarantee cache +coherency across different KeyIDs). + +Similar to AMD SME, the kernel just uses wbinvd() to flush cache before +booting to the new kernel. + +Erratum +~~~~~~~ + +The first few generations of TDX hardware have an erratum. A partial +write to a TDX private memory cacheline will silently "poison" the +line. Subsequent reads will consume the poison and generate a machine +check. + +A partial write is a memory write where a write transaction of less than +cacheline lands at the memory controller. The CPU does these via +non-temporal write instructions (like MOVNTI), or through UC/WC memory +mappings. Devices can also do partial writes via DMA. + +Theoretically, a kernel bug could do partial write to TDX private memory +and trigger unexpected machine check. What's more, the machine check +code will present these as "Hardware error" when they were, in fact, a +software-triggered issue. But in the end, this issue is hard to trigger. + +If the platform has such erratum, the kernel does additional things: +1) resetting TDX private pages using MOVDIR64B in kexec before booting to +the new kernel; 2) Printing additional message in machine check handler +to tell user the machine check may be caused by kernel bug on TDX private +memory. + +Interaction vs S3 and deeper states +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +TDX cannot survive from S3 and deeper states. The hardware resets and +disables TDX completely when platform goes to S3 and deeper. Both TDX +guests and the TDX module get destroyed permanently. + +The kernel uses S3 for suspend-to-ram, and use S4 and deeper states for +hibernation. Currently, for simplicity, the kernel chooses to make TDX +mutually exclusive with S3 and hibernation. + +For most cases, the user needs to add 'nohibernation' kernel command line +in order to use TDX. S3 is disabled during kernel early boot if TDX is +detected. The user needs to turn off TDX in the BIOS in order to use S3. + +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 +215,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 +225,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 +236,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 +247,7 @@ Instruction-based #GP - RDMSR*,WRMSR* RDMSR/WRMSR Behavior --------------------- +~~~~~~~~~~~~~~~~~~~~ MSR access behavior falls into three categories:
@@ -73,7 +268,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 +288,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 +302,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 +322,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 +340,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 +362,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 +384,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.41.0