x86/cpufeatures: Add X86_FEATURE_RMPOPT feature flag
Subsystems (6)
A message that is not in the archive (sent off-list or not yet received): [email protected]
Ashish Kalra
maintainerPATCH v9 1/6 x86/cpufeatures: Add X86_FEATURE_RMPOPT feature flag
From: Ashish Kalra <[email protected]>
Add a flag indicating whether RMPOPT instruction is supported.
RMPOPT is a new instruction that reduces the performance overhead of RMP checks for the hypervisor and non-SNP guests by allowing those checks to be skipped when 1-GB memory regions are known to contain no SEV-SNP guest memory.
For more information on the RMPOPT instruction, see the AMD64 RMPOPT technical documentation.
--- arch/x86/include/asm/cpufeatures.h | 2 +- arch/x86/kernel/cpu/scattered.c | 1 + tools/arch/x86/include/asm/cpufeatures.h | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-)
arch/x86/include/asm/cpufeatures.h +1 -1
@@ -76,7 +76,7 @@#define X86_FEATURE_K8 ( 3*32+ 4)/* Opteron, Athlon64 */ #define X86_FEATURE_ZEN5 ( 3*32+ 5)/* CPU based on Zen5 microarchitecture */ #define X86_FEATURE_ZEN6 ( 3*32+ 6)/* CPU based on Zen6 microarchitecture */ -/* Free ( 3*32+ 7) */ +#define X86_FEATURE_RMPOPT ( 3*32+ 7)/* Support for AMD RMPOPT instruction */ #define X86_FEATURE_CONSTANT_TSC ( 3*32+ 8)/* "constant_tsc" TSC ticks at a constant rate */ #define X86_FEATURE_UP ( 3*32+ 9)/* "up" SMP kernel running on UP */ #define X86_FEATURE_ART ( 3*32+10)/* "art" Always running timer (ART) */
arch/x86/kernel/cpu/scattered.c +1 -0
@@ -67,6 +67,7 @@ static const struct cpuid_bit cpuid_bits[] = { { X86_FEATURE_PERFMON_V2, CPUID_EAX, 0, 0x80000022, 0 }, { X86_FEATURE_AMD_LBR_V2, CPUID_EAX, 1, 0x80000022, 0 }, { X86_FEATURE_AMD_LBR_PMC_FREEZE, CPUID_EAX, 2, 0x80000022, 0 }, + { X86_FEATURE_RMPOPT, CPUID_EDX, 0, 0x80000025, 0 }, { X86_FEATURE_AMD_HTR_CORES, CPUID_EAX, 30, 0x80000026, 0 }, { 0, 0, 0, 0, 0 } };
tools/arch/x86/include/asm/cpufeatures.h +1 -1
@@ -76,7 +76,7 @@#define X86_FEATURE_K8 ( 3*32+ 4)/* Opteron, Athlon64 */ #define X86_FEATURE_ZEN5 ( 3*32+ 5)/* CPU based on Zen5 microarchitecture */ #define X86_FEATURE_ZEN6 ( 3*32+ 6)/* CPU based on Zen6 microarchitecture */ -/* Free ( 3*32+ 7) */ +#define X86_FEATURE_RMPOPT ( 3*32+ 7)/* Support for AMD RMPOPT instruction */ #define X86_FEATURE_CONSTANT_TSC ( 3*32+ 8)/* "constant_tsc" TSC ticks at a constant rate */ #define X86_FEATURE_UP ( 3*32+ 9)/* "up" SMP kernel running on UP */ #define X86_FEATURE_ART ( 3*32+10)/* "art" Always running timer (ART) */
Signature · 1 line
2.43.0
Ashish Kalra
maintainerPATCH v9 2/6 x86/sev: Initialize RMPOPT configuration MSRs
In reply to a message not in the archiveFrom: Ashish Kalra <[email protected]>
The new RMPOPT instruction helps manage per-CPU RMP optimization structures inside the CPU. It takes a 1GB-aligned physical address and either returns the status of the optimizations or tries to enable the optimizations.
Per-CPU RMPOPT tables support at most 2 TB of addressable memory for RMP optimizations.
Initialize the per-CPU RMPOPT table base to the starting physical address. This enables RMP optimization for up to 2 TB of system RAM on all CPUs.
Additionally, add support to setup and enable RMPOPT once SNP is enabled and initialized.
--- arch/x86/coco/core.c | 2 + arch/x86/include/asm/msr-index.h | 3 ++ arch/x86/include/asm/sev.h | 4 ++ arch/x86/virt/svm/sev.c | 70 ++++++++++++++++++++++++++++++++ drivers/crypto/ccp/sev-dev.c | 3 ++ 5 files changed, 82 insertions(+)
arch/x86/coco/core.c +2 -0
@@ -16,6 +16,7 @@#include <asm/archrandom.h> #include <asm/coco.h> #include <asm/processor.h> +#include <asm/sev.h> enum cc_vendor cc_vendor__ro_after_init =CC_VENDOR_NONE ;SYM_PIC_ALIAS (cc_vendor);
@@ -172,6 +173,7 @@ static void amd_cc_platform_clear(enum cc_attr attr)switch (attr) {case CC_ATTR_HOST_SEV_SNP : cc_flags.host_sev_snp =0 ; +snp_clear_rmpopt_capable ();break ;default :break ;
arch/x86/include/asm/msr-index.h +3 -0
@@ -761,6 +761,9 @@#define MSR_AMD64_SEG_RMP_ENABLED_BIT 0#define MSR_AMD64_SEG_RMP_ENABLED BIT_ULL(MSR_AMD64_SEG_RMP_ENABLED_BIT)#define MSR_AMD64_RMP_SEGMENT_SHIFT (x) (((x) & GENMASK_ULL(13, 8)) >> 8) +#define MSR_AMD64_RMPOPT_BASE 0xc0010139 +#define MSR_AMD64_RMPOPT_ENABLE_BIT 0 +#define MSR_AMD64_RMPOPT_ENABLE BIT_ULL(MSR_AMD64_RMPOPT_ENABLE_BIT)#define MSR_SVSM_CAA 0xc001f000
arch/x86/include/asm/sev.h +4 -0
@@ -662,6 +662,8 @@ static inline void snp_leak_pages(u64 pfn, unsigned int pages) __snp_leak_pages(pfn, pages, true); }int snp_prepare (void ); +void snp_setup_rmpopt (void ); +void snp_clear_rmpopt_capable (void );void snp_shutdown (void );#else static inline bool snp_probe_rmptable_info (void ) {return false; }
@@ -680,6 +682,8 @@ static inline void snp_leak_pages(u64 pfn, unsigned int npages) {}static inline void kdump_sev_callback (void ) { }static inline void snp_fixup_e820_tables (void ) {}static inline int snp_prepare (void ) {return -ENODEV ; } +static inline void snp_setup_rmpopt (void ) {} +static inline void snp_clear_rmpopt_capable (void ) {}static inline void snp_shutdown (void ) {}#endif
arch/x86/virt/svm/sev.c +70 -0
99 lines not on this page · raw message
drivers/crypto/ccp/sev-dev.c +3 -0
@@ -1478,6 +1478,9 @@ static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid) }snp_hv_fixed_pages_state_update (sev,HV_FIXED ); + +snp_setup_rmpopt (); + sev->snp_initialized = true;dev_dbg (sev->dev,"SEV-SNP firmware initialized, SEV-TIO is %s\n" , data.tio_en ?"enabled" :"disabled" );
Signature · 1 line
2.43.0
Ashish Kalra
maintainerPATCH v9 3/6 x86/sev: Disable CPU hotplug while SNP is active
In reply to a message not in the archiveFrom: Ashish Kalra <[email protected]>
While SNP is active, every memory write is checked against the RMP to protect the integrity of SEV-SNP guest memory. By the SNP architecture these checks cannot be disabled on a subset of CPUs: they are gated per-core by SYSCFG[SNP_EN], which the SEV firmware requires to be set on every present CPU before SNP initialization. A CPU that does not have SNP_EN set and was not initialized via SNP_INIT performs no RMP checks at all, so there is no valid configuration with SNP active and any CPU exempt from RMP checks.
The firmware determines which CPUs are present from the processor and the BIOS/UEFI configuration (e.g. SMT disabled in the BIOS) and enumerates them at SNP init; it is not aware of the OS bringing CPUs online or offline afterwards. A CPU brought online after SNP init was not enumerated at SNP_INIT and does not have SNP_EN set, so writes from it are not RMP-checked and could corrupt SEV-SNP guest memory, and there is no way to keep work off such a CPU once it is online. OS CPU hotplug can thus diverge from the firmware's expectations and break SNP. Disable CPU hotplug while SNP is active.
Use cpu_hotplug_disable() at SNP init and cpu_hotplug_enable() only on the full x86_snp_shutdown path; the legacy SNP_SHUTDOWN_EX path leaves SNP active and must keep hotplug disabled. A flag in built-in SNP code keeps the disable balanced across the teardown paths, re-init and kexec, and survives a ccp module reload.
This also keeps the CPU set stable for the asynchronous RMPOPT scan added later in this series, and ensures cpus_read_lock() in the scan is uncontended.
--- arch/x86/include/asm/sev.h | 2 ++ arch/x86/virt/svm/sev.c | 30 ++++++++++++++++++++++++++++++ drivers/crypto/ccp/sev-dev.c | 3 +++ 3 files changed, 35 insertions(+)
arch/x86/include/asm/sev.h +2 -0
@@ -664,6 +664,7 @@ static inline void snp_leak_pages(u64 pfn, unsigned int pages)int snp_prepare (void );void snp_setup_rmpopt (void );void snp_clear_rmpopt_capable (void ); +void snp_disable_cpu_hotplug (void );void snp_shutdown (void );#else static inline bool snp_probe_rmptable_info (void ) {return false; }
@@ -684,6 +685,7 @@ static inline void snp_fixup_e820_tables(void) {}static inline int snp_prepare (void ) {return -ENODEV ; }static inline void snp_setup_rmpopt (void ) {}static inline void snp_clear_rmpopt_capable (void ) {} +static inline void snp_disable_cpu_hotplug (void ) {}static inline void snp_shutdown (void ) {}#endif
arch/x86/virt/svm/sev.c +30 -0
@@ -133,6 +133,9 @@ static DEFINE_SPINLOCK(snp_leaked_pages_list_lock);static unsigned long snp_nr_leaked_pages; +/* Set while SNP has CPU hotplug disabled (kernel-lifetime; survives ccp reload). */ +static bool snp_cpu_hotplug_disabled; +#undef pr_fmt#define pr_fmt (fmt) "SEV-SNP: " fmt
@@ -577,6 +580,22 @@ static void rmpopt_cleanup(void) rmpopt_pa_start =0 ; } +/* +* Disable CPU hotplug while SNP is active. Applied once per SNP-active +* window and balanced by cpu_hotplug_enable() in snp_shutdown(). +* The legacy SNP_SHUTDOWN_EX path leaves SNP enabled without re-enabling +* hotplug, so a re-init while SNP is still active must not stack the +* disable count. +*/ +void snp_disable_cpu_hotplug (void ) +{ +if (!snp_cpu_hotplug_disabled) { +cpu_hotplug_disable (); + snp_cpu_hotplug_disabled = true; + } +} +EXPORT_SYMBOL_FOR_MODULES (snp_disable_cpu_hotplug,"ccp" ); +void snp_shutdown (void ) {u64 syscfg;
@@ -587,6 +606,17 @@ void snp_shutdown(void)rmpopt_cleanup (); +/* +* Re-enable CPU hotplug now that SNP is fully shut down. Done here +* (x86_snp_shutdown path) only -- the legacy path leaves SNP active +* and must keep hotplug disabled. After rmpopt_cleanup() so the +* per-core RMPOPT_BASE MSRs are cleared with hotplug still disabled. +*/ +if (snp_cpu_hotplug_disabled) { +cpu_hotplug_enable (); + snp_cpu_hotplug_disabled = false; + } +clear_rmp ();on_each_cpu (mfd_reconfigure,NULL ,1 ); }
drivers/crypto/ccp/sev-dev.c +3 -0
@@ -1479,6 +1479,9 @@ static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid)snp_hv_fixed_pages_state_update (sev,HV_FIXED ); +/* Disable CPU hotplug while SNP is active (see snp_disable_cpu_hotplug). */ +snp_disable_cpu_hotplug (); +snp_setup_rmpopt (); sev->snp_initialized = true;
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] CPU hotplug is disabled too late in the SEV-SNP initialization sequence, leaving a race condition…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] CPU hotplug is disabled too late in the SEV-SNP initialization sequence, leaving a race condition that could lead to SEV-SNP guest memory corruption. --
commit 3de14e7df8d9891da860d77abb4bcd8843de6e48
Author: Ashish Kalra <[email protected]>
x86/sev: Disable CPU hotplug while SNP is active
This commit disables CPU hotplug while SEV-SNP is active to prevent CPUs brought online after SNP initialization from bypassing RMP checks. This ensures the hardware checks are consistently enforced across all active cores to protect guest memory integrity.
Quoted 4 lines
drivers/crypto/ccp/sev-dev.c +0
-0
[ ... ]
drivers/crypto/ccp/sev-dev.c static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid) · line 1483
Quoted 7 lines
drivers/crypto/ccp/sev-dev.c +3
-0@@ -1478,6 +1478,9 @@ static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid)snp_hv_fixed_pages_state_update (sev,HV_FIXED ); +/* Disable CPU hotplug while SNP is active (see snp_disable_cpu_hotplug). */ +snp_disable_cpu_hotplug (); +
[Severity: High]
Is there a race condition between snp_prepare() and snp_disable_cpu_hotplug()?
Earlier in __sev_snp_init_locked(), snp_prepare() is called which sets SNP_EN on all online CPUs. If a CPU is offlined and re-onlined before we reach snp_disable_cpu_hotplug(), could it lose its SNP_EN bit and bypass RMP checks?
Also, if the intermediate firmware commands like SEV_CMD_SNP_INIT_EX or SEV_CMD_SNP_DF_FLUSH fail and return early:
rc = __sev_do_cmd_locked(SEV_CMD_SNP_DF_FLUSH, NULL, error);
if (rc) {
dev_err(sev->dev, "SEV-SNP: SNP_DF_FLUSH failed rc %d, error %#x\n",
rc, *error);
return rc;
}snp_disable_cpu_hotplug() will never be called. Does this leave the system permanently vulnerable to hotplugging CPUs without SNP_EN if snp_prepare() has already executed?
Quoted 3 lines
drivers/crypto/ccp/sev-dev.c +0
-0snp_setup_rmpopt (); sev->snp_initialized = true;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
In reply to Ashish KalraHello Ashish,
Quoted 11 lines · Ashish Kalra
From: Ashish Kalra <[email protected]>
While SNP is active, every memory write is checked against the RMP to protect the integrity of SEV-SNP guest memory. By the SNP architecture these checks cannot be disabled on a subset of CPUs: they are gated per-core by SYSCFG[SNP_EN], which the SEV firmware requires to be set on every present CPU before SNP initialization. A CPU that does not have
SNP_ENset and was not initialized viaSNP_INITperforms no RMP checks at all, so there is no valid configuration with SNP active and any CPU exempt from RMP checks.
Quoted 8 lines
The firmware determines which CPUs are present from the processor and the BIOS/UEFI configuration (e.g. SMT disabled in the BIOS) and enumerates them at SNP init; it is not aware of the OS bringing CPUs online or offline afterwards. A CPU brought online after SNP init was not enumerated at
SNP_INITand does not haveSNP_ENset, so writes from it are not RMP-checked and could corrupt SEV-SNP guest memory, and there is no way to keep work off such a CPU once it is online. OS CPU hotplug can thus diverge from the firmware's expectations and break SNP.
If this is true ...
[..snip..]
drivers/crypto/ccp/sev-dev.c static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid) · line 1483
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +2
-0@@ -1479,6 +1479,9 @@ static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid)snp_hv_fixed_pages_state_update (sev,HV_FIXED ); +/* Disable CPU hotplug while SNP is active (see snp_disable_cpu_hotplug). */ +snp_disable_cpu_hotplug ();
... then this should be done at snp_prepare() before on_each_cpu(snp_enable) right?
If not, then any CPU hotplug between the cpus_read_unlock() there and the snp_disable_cpu_hotplug() here will not have the SNP_EN set.
Isn't that a concern?
Also, this patch can probably go first since the FW assumptions on hotplug exists independent of RMPOPT bits.
Quoted 4 lines
drivers/crypto/ccp/sev-dev.c +1
-0+snp_setup_rmpopt (); sev->snp_initialized = true;
Signature · 2 lines
Thanks and Regards, Prateek
Kalra, Ashish
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Hello Prateek,
Quoted 41 lines · K Prateek Nayak
Hello Ashish,
Quoted 11 lines · Ashish Kalra
From: Ashish Kalra <[email protected]>
While SNP is active, every memory write is checked against the RMP to protect the integrity of SEV-SNP guest memory. By the SNP architecture these checks cannot be disabled on a subset of CPUs: they are gated per-core by SYSCFG[SNP_EN], which the SEV firmware requires to be set on every present CPU before SNP initialization. A CPU that does not have
SNP_ENset and was not initialized viaSNP_INITperforms no RMP checks at all, so there is no valid configuration with SNP active and any CPU exempt from RMP checks.Quoted 8 lines
The firmware determines which CPUs are present from the processor and the BIOS/UEFI configuration (e.g. SMT disabled in the BIOS) and enumerates them at SNP init; it is not aware of the OS bringing CPUs online or offline afterwards. A CPU brought online after SNP init was not enumerated at
SNP_INITand does not haveSNP_ENset, so writes from it are not RMP-checked and could corrupt SEV-SNP guest memory, and there is no way to keep work off such a CPU once it is online. OS CPU hotplug can thus diverge from the firmware's expectations and break SNP.If this is true ...
[..snip..]
drivers/crypto/ccp/sev-dev.c static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid) · line 1483
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +2
-0@@ -1479,6 +1479,9 @@ static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid)snp_hv_fixed_pages_state_update (sev,HV_FIXED ); +/* Disable CPU hotplug while SNP is active (see snp_disable_cpu_hotplug). */ +snp_disable_cpu_hotplug ();... then this should be done at
snp_prepare()beforeon_each_cpu(snp_enable)right?
Quoted 4 lines
If not, then any CPU hotplug between the
cpus_read_unlock()there and thesnp_disable_cpu_hotplug()here will not have theSNP_ENset.Isn't that a concern?
yes — it's a concern, and i agree the disable belongs in snp_prepare() before SNP_EN is programmed.
snp_enable runs via on_each_cpu() over the set that is online at snp_prepare() time, and SNP_INIT_EX runs right after. With the disable where it is now (after SNP_INIT_EX/DF_FLUSH), there's a window starting at snp_prepare()'s cpus_read_unlock() in which a CPU can come online that never had snp_enable run on it, i.e. with SNP_EN clear. .
So hotplug needs to be frozen before SNP_EN is programmed, so the online set that gets SNP_EN cannot change underneath us.
I'll move the disable into snp_prepare(), before cpus_read_lock() rather than just before on_each_cpu(snp_enable):cpu_hotplug_disable() takes cpu_add_remove_lock, which nests above cpu_hotplug_lock, so calling it under cpus_read_lock() would invert the order, causing deadlock.
On the failure paths where SNP does not end up active, i.e., SNP_INIT_EX/DF_FLUSH error, then I'll re-enable hotplug so a failed init doesn't leave it permanently disabled; the success path continues to re-enable only on the full shutdown path.
Will fix in v10.
Thanks,
Ashish
Quoted 9 lines
Also, this patch can probably go first since the FW assumptions on hotplug exists independent of RMPOPT bits.
Quoted 4 lines
drivers/crypto/ccp/sev-dev.c +1
-0+snp_setup_rmpopt (); sev->snp_initialized = true;
Tom Lendacky
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
In reply to K Prateek NayakQuoted 19 lines · K Prateek Nayak
Hello Ashish,
Quoted 16 lines · Ashish Kalra
From: Ashish Kalra <[email protected]>
While SNP is active, every memory write is checked against the RMP to protect the integrity of SEV-SNP guest memory. By the SNP architecture these checks cannot be disabled on a subset of CPUs: they are gated per-core by SYSCFG[SNP_EN], which the SEV firmware requires to be set on every present CPU before SNP initialization. A CPU that does not have
SNP_ENset and was not initialized viaSNP_INITperforms no RMP checks at all, so there is no valid configuration with SNP active and any CPU exempt from RMP checks.The firmware determines which CPUs are present from the processor and the BIOS/UEFI configuration (e.g. SMT disabled in the BIOS) and enumerates them at SNP init; it is not aware of the OS bringing CPUs online or offline afterwards. A CPU brought online after SNP init was not enumerated at
SNP_INITand does not haveSNP_ENset, so writes from it are
SNP_INIT will fail if not all of the CPUs have SnpEn set. So if the CPU was offline and didn't have SnpEn set, SNP_INIT will fail and so you can't have SNP guest memory.
Thanks,
Tom
Quoted 35 lines
Quoted 3 lines
not RMP-checked and could corrupt SEV-SNP guest memory, and there is no way to keep work off such a CPU once it is online. OS CPU hotplug can thus diverge from the firmware's expectations and break SNP.
If this is true ...
[..snip..]
drivers/crypto/ccp/sev-dev.c static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid) · line 1483
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +2
-0@@ -1479,6 +1479,9 @@ static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid)snp_hv_fixed_pages_state_update (sev,HV_FIXED ); +/* Disable CPU hotplug while SNP is active (see snp_disable_cpu_hotplug). */ +snp_disable_cpu_hotplug ();... then this should be done at
snp_prepare()beforeon_each_cpu(snp_enable)right?If not, then any CPU hotplug between the
cpus_read_unlock()there and thesnp_disable_cpu_hotplug()here will not have theSNP_ENset.Isn't that a concern?
Also, this patch can probably go first since the FW assumptions on hotplug exists independent of RMPOPT bits.
Quoted 4 lines
drivers/crypto/ccp/sev-dev.c +1
-0+snp_setup_rmpopt (); sev->snp_initialized = true;
Borislav Petkov
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
In reply to Ashish Kalraarch/x86/virt/svm/sev.c static DEFINE_SPINLOCK(snp_leaked_pages_list_lock); · line 137
Quoted 2 lines · Ashish Kalra
arch/x86/virt/svm/sev.c +2
-0+/* Set while SNP has CPU hotplug disabled (kernel-lifetime; survives ccp reload). */ +static bool snp_cpu_hotplug_disabled;
Do you really need this?
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteKalra, Ashish
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Hello Boris,
Quoted 6 lines · Borislav Petkov
arch/x86/virt/svm/sev.c static DEFINE_SPINLOCK(snp_leaked_pages_list_lock); · line 137
Quoted 2 lines · Ashish Kalra
arch/x86/virt/svm/sev.c +2
-0+/* Set while SNP has CPU hotplug disabled (kernel-lifetime; survives ccp reload). */ +static bool snp_cpu_hotplug_disabled;Do you really need this?
Yes.
cpu_hotplug_disable()/cpu_hotplug_enable() are refcounted (cpu_hotplug_disabled++/--, with a WARN on underflow), so they have to be balanced. This flag collapses them to exactly one outstanding disable per SNP-active window, because the disable and enable sites are not reached a symmetric number of times:
- On firmware without SNP_X86_SHUTDOWN_SUPPORTED, __sev_snp_shutdown_locked() does not call snp_shutdown() (it's gated on data.x86_snp_shutdown), so SNP stays enabled in hardware — SNP_EN stays set and hotplug stays disabled — while sev->snp_initialized is cleared. Re-init after that is routine, the SNP ioctls self-bracket init and shutdown (e.g. SNP_COMMIT, SNP_SET_CONFIG, SNP_VLEK_LOAD):
if (!sev->snp_initialized)
snp_move_to_init_state(...); /* -> __sev_snp_init_locked -> snp_prepare() */
... SNP_CMD ...
if (shutdown_required)
__sev_snp_shutdown_locked(...); - So whenever SNP isn't already initialized (psp_init_on_probe off, or after a prior legacy shutdown), every such ioctl does init -> command -> legacy shutdown. Each init reaches snp_prepare() with SNP_EN already set, and the disable now sits at the top of snp_prepare(), so it fires on every cycle. Without this flag that keeps bumping cpu_hotplug_disabled while the legacy shutdown never re-enables — hotplug ends up stuck disabled. This flag makes all but the first disable a no-op.
- Also, importantly, kvm-amd module reload on legacy firmware is the same pattern:
unload leaves SNP_EN set, reload re-inits.)
- On the enable side it avoids an unbalanced cpu_hotplug_enable() when the teardown/failure paths run without an outstanding disable (e.g. shutdown of a never-fully-initialized SNP).
So it's not redundant with cpu_hotplug_disabled — it tracks whether the outstanding disable belongs to this SNP-active window in this kernel, which keeps the single disable/enable balanced across the asymmetric legacy-vs-full SNP teardown paths and re-init.
Thanks,
Ashish
Re: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Hello Ashish,
Quoted 34 lines · Ashish
Hello Boris,
Quoted 6 lines · Borislav Petkov
arch/x86/virt/svm/sev.c static DEFINE_SPINLOCK(snp_leaked_pages_list_lock); · line 137
Quoted 2 lines · Ashish Kalra
arch/x86/virt/svm/sev.c +2
-0+/* Set while SNP has CPU hotplug disabled (kernel-lifetime; survives ccp reload). */ +static bool snp_cpu_hotplug_disabled;Do you really need this?
Yes.
cpu_hotplug_disable()/cpu_hotplug_enable() are refcounted (cpu_hotplug_disabled++/--, with a WARN on underflow), so they have to be balanced. This flag collapses them to exactly one outstanding disable per SNP-active window, because the disable and enable sites are not reached a symmetric number of times:
Quoted 1 line
- On firmware without
SNP_X86_SHUTDOWN_SUPPORTED,__sev_snp_shutdown_locked()does notcall
snp_shutdown()(it's gated on data.x86_snp_shutdown), so SNP stays enabled in hardware —SNP_ENstays set and hotplug stays disabled — whilesev->snp_initializedis cleared. Re-init after that is routine, the SNP ioctls self-bracket init and shutdown (e.g.SNP_COMMIT,SNP_SET_CONFIG,SNP_VLEK_LOAD):if (!sev->snp_initialized)
snp_move_to_init_state(...); /* -> __sev_snp_init_locked -> snp_prepare() */ ... SNP_CMD ... if (shutdown_required) __sev_snp_shutdown_locked(...);- So whenever SNP isn't already initialized (
psp_init_on_probeoff, or after a prior legacy shutdown), every such ioctl does init -> command -> legacy shutdown. Each init reachessnp_prepare()withSNP_ENalready set, and the disable now sits at the top ofsnp_prepare(), so it fires on every cycle. Without this flag that keeps bumpingcpu_hotplug_disabledwhile the legacy shutdown never re-enables — hotplug ends up stuck disabled. This flag makes all but the first disable a no-op.
Quoted 2 lines
- Also, importantly, kvm-amd module reload on legacy firmware is the same pattern:
unload leavesSNP_ENset, reload re-inits.)
Looking at snp_prepare(), we have an early-bailout for
rdmsrq(MSR_AMD64_SYSCFG, val);
if (val & MSR_AMD64_SYSCFG_SNP_EN)
return;Does executing SHUTDOWN command lead to the firmware clearing SNP_EN in SYSCFG on all CPUS?
If SNP_EN remains set (and Linux can't clear it since it is "Write-1-only" bit), then a subsequent snp_prepare() will skip setting SYSCFG if it sees SNP_EN on local CPU.
It can so happen that we enable hotlpug at shutdown, CPUs come online without setting SNP_EN in SYSCFG, subsequent snp_prepare() runs on a CPU where SNP_EN is still set and skips configuring it for the CPUs that don't have it set, and we'll be in a pickle still.
The comment above that bailout saying "this can happen in case of kexec boot" makes me believe that SNP_EN remains set until a full system reset.
The only safe way to do this is to ensure all possible CPUs are online during snp_prepare() and do snp_enable() regardless of whether local CPU has SNP_EN or not.
Am I missing something?
Quoted 7 lines
- On the enable side it avoids an unbalanced
cpu_hotplug_enable()when the teardown/failure paths run without an outstanding disable (e.g. shutdown of a never-fully-initialized SNP).So it's not redundant with
cpu_hotplug_disabled— it tracks whether the outstanding disable belongs to this SNP-active window in this kernel, which keeps the single disable/enable balanced across the asymmetric legacy-vs-full SNP teardown paths and re-init.
Signature · 2 lines
Thanks and Regards, Prateek
Kalra, Ashish
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Quoted 40 lines · K Prateek Nayak
Hello Ashish,
Quoted 34 lines · Ashish
Hello Boris,
Quoted 6 lines · Borislav Petkov
arch/x86/virt/svm/sev.c static DEFINE_SPINLOCK(snp_leaked_pages_list_lock); · line 137
Quoted 2 lines · Ashish Kalra
arch/x86/virt/svm/sev.c +2
-0+/* Set while SNP has CPU hotplug disabled (kernel-lifetime; survives ccp reload). */ +static bool snp_cpu_hotplug_disabled;Do you really need this?
Yes.
cpu_hotplug_disable()/cpu_hotplug_enable() are refcounted (cpu_hotplug_disabled++/--, with a WARN on underflow), so they have to be balanced. This flag collapses them to exactly one outstanding disable per SNP-active window, because the disable and enable sites are not reached a symmetric number of times:
Quoted 1 line
- On firmware without
SNP_X86_SHUTDOWN_SUPPORTED,__sev_snp_shutdown_locked()does notcall
snp_shutdown()(it's gated on data.x86_snp_shutdown), so SNP stays enabled in hardware —SNP_ENstays set and hotplug stays disabled — whilesev->snp_initializedis cleared. Re-init after that is routine, the SNP ioctls self-bracket init and shutdown (e.g.SNP_COMMIT,SNP_SET_CONFIG,SNP_VLEK_LOAD):if (!sev->snp_initialized)
snp_move_to_init_state(...); /* -> __sev_snp_init_locked -> snp_prepare() */ ... SNP_CMD ... if (shutdown_required) __sev_snp_shutdown_locked(...);- So whenever SNP isn't already initialized (
psp_init_on_probeoff, or after a prior legacy shutdown), every such ioctl does init -> command -> legacy shutdown. Each init reachessnp_prepare()withSNP_ENalready set, and the disable now sits at the top ofsnp_prepare(), so it fires on every cycle. Without this flag that keeps bumpingcpu_hotplug_disabledwhile the legacy shutdown never re-enables — hotplug ends up stuck disabled. This flag makes all but the first disable a no-op.Quoted 2 lines
- Also, importantly, kvm-amd module reload on legacy firmware is the same pattern:
unload leavesSNP_ENset, reload re-inits.)
Quoted 8 lines
Looking at
snp_prepare(), we have an early-bailout forrdmsrq(MSR_AMD64_SYSCFG, val); if (val & MSR_AMD64_SYSCFG_SNP_EN) return;Does executing SHUTDOWN command lead to the firmware clearing
SNP_ENin SYSCFG on all CPUS?
Yes, in case of X86_SNP_SHUTDOWN (available if firmware supports X86SnpShutdown feature) SNP is disabled on all cores by clearing SYSCFG[SNPEn] bit.
If X86_SNP_SHUTDOWN is set to 1, the firmware clears the SYSCFG[SNPEn] bit in each core.
But, in case of legacy SNP shutdown, SNP_EN bit is not cleared and so SNP remains enabled.
Quoted 14 lines
If
SNP_ENremains set (and Linux can't clear it since it is "Write-1-only" bit), then a subsequentsnp_prepare()will skip setting SYSCFG if it seesSNP_ENon local CPU.It can so happen that we enable hotlpug at shutdown, CPUs come online without setting
SNP_ENin SYSCFG, subsequentsnp_prepare()runs on a CPU whereSNP_ENis still set and skips configuring it for the CPUs that don't have it set, and we'll be in a pickle still.The comment above that bailout saying "this can happen in case of kexec boot" makes me believe that
SNP_ENremains set until a full system reset.
Quoted 6 lines
The only safe way to do this is to ensure all possible CPUs are online during
snp_prepare()and dosnp_enable()regardless of whether local CPU hasSNP_ENor not.Am I missing something?
The piece that makes the early bailout safe is the disable this patch adds:
hotplug is disabled while SNP is active, so the online set can't change under an active SNP. snp_prepare() already requires online == present, so at a successful init every present CPU gets SNP_EN, and because hotplug is then disabled none can leave or rejoin without it. So whenever the bailout is hit with SNP active, every online CPU already has SNP_EN:
- kexec: SNP_EN is already set on all CPUs by the previous kernel.
- re-init while SNP is still active (e.g. after a legacy SNP_SHUTDOWN that leaves SNP_EN set): hotplug was disabled the whole time, so the online set is unchanged and all of them still have SNP_EN.
The only way a CPU can be online without SNP_EN is when SNP is not active -- i.e. after an SNP_INIT failure, where this patch re-enables hotplug. That is deliberately the same as the behavior before this support existed (hotplug was never disabled then), and it is benign: SNP_EN only gates RMP checks, the RMP itself is initialized by SNP_INIT, so on a failed init the RMP is all-zeroes -- every entry is in the default HV-owned state, no page is assigned, no check ever blocks and snp_initialized stays false, so no SNP guest can be created.
Nothing is enforced and nothing is protected.
So I've kept snp_prepare()'s existing bailout / snp_enable() behavior unchanged; what this patch adds is disabling hotplug while SNP is active, which is what actually closes the window (a CPU coming online without SNP_EN while SNP is live). That window -- and the SNP_EN-stays-set-on-failure situation -- already exist in today's code, this patch constrains the dangerous (active) case and otherwise matches current behavior.
(On the v9 placement specifically: I'm moving the disable into snp_prepare() ahead of SNP_EN in the next version; in v9 it sits after SNP_INIT, which leaves the window you originally pointed out.)
Thanks,
Ashish
Quoted 7 lines
Quoted 7 lines
- On the enable side it avoids an unbalanced
cpu_hotplug_enable()when the teardown/failure paths run without an outstanding disable (e.g. shutdown of a never-fully-initialized SNP).So it's not redundant with
cpu_hotplug_disabled— it tracks whether the outstanding disable belongs to this SNP-active window in this kernel, which keeps the single disable/enable balanced across the asymmetric legacy-vs-full SNP teardown paths and re-init.
Re: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Hello Ashish,
Quoted 9 lines · Ashish
Quoted 8 lines
Looking at
snp_prepare(), we have an early-bailout forrdmsrq(MSR_AMD64_SYSCFG, val); if (val & MSR_AMD64_SYSCFG_SNP_EN) return;Does executing SHUTDOWN command lead to the firmware clearing
SNP_ENin SYSCFG on all CPUS?
Quoted 6 lines
Yes, in case of
X86_SNP_SHUTDOWN(available if firmware supports X86SnpShutdown feature) SNP is disabled on all cores by clearing SYSCFG[SNPEn] bit.If
X86_SNP_SHUTDOWNis set to 1, the firmware clears the SYSCFG[SNPEn] bit in each core.But, in case of legacy SNP shutdown,
SNP_ENbit is not cleared and so SNP remains enabled.
Ah! That was the bit I was missing. Thanks a ton for clarifying.
Quoted 19 lines
Quoted 19 lines
If
SNP_ENremains set (and Linux can't clear it since it is "Write-1-only" bit), then a subsequentsnp_prepare()will skip setting SYSCFG if it seesSNP_ENon local CPU.It can so happen that we enable hotlpug at shutdown, CPUs come online without setting
SNP_ENin SYSCFG, subsequentsnp_prepare()runs on a CPU whereSNP_ENis still set and skips configuring it for the CPUs that don't have it set, and we'll be in a pickle still.The comment above that bailout saying "this can happen in case of kexec boot" makes me believe that
SNP_ENremains set until a full system reset.The only safe way to do this is to ensure all possible CPUs are online during
snp_prepare()and dosnp_enable()regardless of whether local CPU hasSNP_ENor not.
Quoted 7 lines
Quoted 2 lines
Am I missing something?
The piece that makes the early bailout safe is the disable this patch adds:
hotplug is disabled while SNP is active, so the online set can't change under an active SNP.snp_prepare()already requires online == present, so at a successful init every present CPU getsSNP_EN,
How is this enforced? AFAICT, on_each_cpu(snp_enable) will only covers the online CPUs and there could be CPUs that have been offlined before that right?
Quoted 5 lines
and because hotplug is then disabled none
can leave or rejoin without it. So whenever the bailout is hit with SNP active, every online CPU already hasSNP_EN:- kexec:
SNP_ENis already set on all CPUs by the previous kernel.
There is a catch here: you can have offline CPUs during the previous boot (say you have maxcpus=8 in your cmdline), and then you kexec with a different kernel / cmdline that brings online a bunch more CPUs.
SNP_EN will only be set for a subset of then with the legacy SNP_INIT and if snp_prepare() runs on those legacy CPUs, you still skip setting it for the ones that don't have SNP_EN set.
Is that case covered somehow or is it a non-issue?
Quoted 13 lines
- re-init while SNP is still active (e.g. after a legacy
SNP_SHUTDOWNthat leavesSNP_ENset): hotplug was disabled the whole time, so the online set is unchanged and all of them still haveSNP_EN.The only way a CPU can be online without
SNP_ENis when SNP is not active -- i.e. after anSNP_INITfailure, where this patch re-enables hotplug. That is deliberately the same as the behavior before this support existed (hotplug was never disabled then), and it is benign:SNP_ENonly gates RMP checks, the RMP itself is initialized bySNP_INIT, so on a failed init the RMP is all-zeroes -- every entry is in the default HV-owned state, no page is assigned, no check ever blocks andsnp_initializedstays false, so no SNP guest can be created.
Nothing is enforced and nothing is protected.
Quoted 6 lines
So I've kept snp_prepare()'s existing bailout /
snp_enable()behavior unchanged; what this patch adds is disabling hotplug while SNP is active, which is what actually closes the window (a CPU coming online withoutSNP_ENwhile SNP is live). That window -- and the SNP_EN-stays-set-on-failure situation -- already exist in today's code, this patch constrains the dangerous (active) case and otherwise matches current behavior.
Ack! Just that one small bit up above bothers me but other than that, doing it in snp_prepare() should be good.
This is all new to me so thanks a ton for answering my queries.
Quoted 4 lines
(On the v9 placement specifically: I'm moving the disable into
snp_prepare()ahead ofSNP_ENin the next version; in v9 it sits afterSNP_INIT, which leaves the window you originally pointed out.)
Signature · 2 lines
Thanks and Regards, Prateek
Kalra, Ashish
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Hello Prateek,
Quoted 43 lines · K Prateek Nayak
Hello Ashish,
Quoted 9 lines · Ashish
Quoted 8 lines
Looking at
snp_prepare(), we have an early-bailout forrdmsrq(MSR_AMD64_SYSCFG, val); if (val & MSR_AMD64_SYSCFG_SNP_EN) return;Does executing SHUTDOWN command lead to the firmware clearing
SNP_ENin SYSCFG on all CPUS?Quoted 6 lines
Yes, in case of
X86_SNP_SHUTDOWN(available if firmware supports X86SnpShutdown feature) SNP is disabled on all cores by clearing SYSCFG[SNPEn] bit.If
X86_SNP_SHUTDOWNis set to 1, the firmware clears the SYSCFG[SNPEn] bit in each core.But, in case of legacy SNP shutdown,
SNP_ENbit is not cleared and so SNP remains enabled.Ah! That was the bit I was missing. Thanks a ton for clarifying.
Quoted 22 lines
Quoted 21 lines
If
SNP_ENremains set (and Linux can't clear it since it is "Write-1-only" bit), then a subsequentsnp_prepare()will skip setting SYSCFG if it seesSNP_ENon local CPU.It can so happen that we enable hotlpug at shutdown, CPUs come online without setting
SNP_ENin SYSCFG, subsequentsnp_prepare()runs on a CPU whereSNP_ENis still set and skips configuring it for the CPUs that don't have it set, and we'll be in a pickle still.The comment above that bailout saying "this can happen in case of kexec boot" makes me believe that
SNP_ENremains set until a full system reset.The only safe way to do this is to ensure all possible CPUs are online during
snp_prepare()and dosnp_enable()regardless of whether local CPU hasSNP_ENor not.Am I missing something?
Quoted 8 lines
Quoted 4 lines
The piece that makes the early bailout safe is the disable this patch adds:
hotplug is disabled while SNP is active, so the online set can't change under an active SNP.snp_prepare()already requires online == present, so at a successful init every present CPU getsSNP_EN,How is this enforced? AFAICT,
on_each_cpu(snp_enable)will only covers the online CPUs and there could be CPUs that have been offlined before that right
Right that on_each_cpu() only covers online CPUs -- but snp_prepare() refuses to proceed unless online == present.
if (!cpumask_equal(cpu_online_mask, cpu_present_mask)) {
ret = -EOPNOTSUPP;
pr_warn("SNP init failed: not all CPUs online. ...");
goto unlock;
}The check right before on_each_cpu(snp_enable) returns -EOPNOTSUPP if any present CPU is offline, so SNP init simply fails in that case -- there is no successful init that leaves a CPU without SNP_EN. The check and on_each_cpu(snp_enable) both run under cpus_read_lock(), so the online set can't change between the two, at a successful snp_prepare(), online == present and every present CPU has SNP_EN. After that this patch disables hotplug, so the set stays == present.
(That online == present requirement is existing snp_prepare() behavior, not something this patch adds.)
And cpu_hotplug_disable() comes right before cpus_read_lock() as it must not be called while holding cpus_read_lock(), something like this:
rdmsrq(MSR_AMD64_SYSCFG, val);
if (val & MSR_AMD64_SYSCFG_SNP_EN)
return 0; /* bailout: re-init/kexec, SNP_EN already set */
clear_rmp();
cpu_hotplug_disable(); /* <-- here: after bailout, before cpus_read_lock */
cpus_read_lock();
if (!cpumask_equal(cpu_online_mask, cpu_present_mask)) {
ret = -EOPNOTSUPP;
...
goto unlock; /* will re-enable below */
}
on_each_cpu(mfd_reconfigure, ...);
on_each_cpu(snp_enable, ...);
...
unlock:
cpus_read_unlock();
if (ret)
cpu_hotplug_enable(); /* undo: failed before SNP_EN was set */
return ret;Quoted 11 lines
Quoted 6 lines
and because hotplug is then disabled none
can leave or rejoin without it. So whenever the bailout is hit with SNP active, every online CPU already hasSNP_EN:- kexec:
SNP_ENis already set on all CPUs by the previous kernel.There is a catch here: you can have offline CPUs during the previous boot (say you have maxcpus=8 in your cmdline), and then you kexec with a different kernel / cmdline that brings online a bunch more CPUs.
Quoted 6 lines
SNP_ENwill only be set for a subset of then with the legacySNP_INITand ifsnp_prepare()runs on those legacy CPUs, you still skip setting it for the ones that don't haveSNP_ENset.Is that case covered somehow or is it a non-issue?
It's a non-issue, for two independent reasons.
First, kexec with SNP active currently requires a full SNP shutdown before the kexec. SNP_SHUTDOWN_EX (and the IOMMU SNP shutdown it performs) fail if there are any active SNP guests or assigned ASIDs, so a working kexec has to terminate all SNP guests and run a full shutdown first (via systemctl kexec). On firmware that supports X86_SNP_SHUTDOWN, that full shutdown clears SNP_EN on all CPUs, so the kexec target boots with SNP_EN clear and runs a complete, fresh snp_prepare() -- where online == present is enforced, so every present CPU gets SNP_EN. There is no inherited partial-SNP_EN state.
Second, even independent of kexec, this kernel's snp_prepare() never sets SNP_EN on a subset: on_each_cpu(snp_enable) runs only after the cpumask_equal(cpu_online_mask, cpu_present_mask) check passes, so it's all (every present CPU) or nothing (snp_prepare() returns -EOPNOTSUPP and SNP_EN is never set). With maxcpus=8 on a larger system, online != present, so SNP simply does not initialize -- it cannot leave SNP_EN set on only those 8 cores. A successful init therefore implies every present CPU has SNP_EN, and the present mask is the same physical hardware across kexec.
So producing a partial SNP_EN set would require a source kernel that both sets SNP_EN partially (i.e. doesn't enforce online == present) and skips the full shutdown before kexec -- neither of which applies here. I think it's a non-issue in practice.
Quoted 20 lines
Quoted 13 lines
- re-init while SNP is still active (e.g. after a legacy
SNP_SHUTDOWNthat leavesSNP_ENset): hotplug was disabled the whole time, so the online set is unchanged and all of them still haveSNP_EN.The only way a CPU can be online without
SNP_ENis when SNP is not active -- i.e. after anSNP_INITfailure, where this patch re-enables hotplug. That is deliberately the same as the behavior before this support existed (hotplug was never disabled then), and it is benign:SNP_ENonly gates RMP checks, the RMP itself is initialized bySNP_INIT, so on a failed init the RMP is all-zeroes -- every entry is in the default HV-owned state, no page is assigned, no check ever blocks andsnp_initializedstays false, so no SNP guest can be created.
Nothing is enforced and nothing is protected.Quoted 6 lines
So I've kept snp_prepare()'s existing bailout /
snp_enable()behavior unchanged; what this patch adds is disabling hotplug while SNP is active, which is what actually closes the window (a CPU coming online withoutSNP_ENwhile SNP is live). That window -- and the SNP_EN-stays-set-on-failure situation -- already exist in today's code, this patch constrains the dangerous (active) case and otherwise matches current behavior.
Quoted 5 lines
Ack! Just that one small bit up above bothers me but other than that, doing it in
snp_prepare()should be good.This is all new to me so thanks a ton for answering my queries.
Thanks,
Ashish
Quoted 4 lines
Quoted 4 lines
(On the v9 placement specifically: I'm moving the disable into
snp_prepare()ahead ofSNP_ENin the next version; in v9 it sits afterSNP_INIT, which leaves the window you originally pointed out.)
Borislav Petkov
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
In reply to Kalra, AshishQuoted 1 line · Ashish
Hello Boris,
Hello Ashish,
lemme try to make sense of your AI reply...
Quoted 4 lines
cpu_hotplug_disable()/cpu_hotplug_enable() are refcounted (cpu_hotplug_disabled++/--, with a WARN on underflow), so they have to be balanced. This flag collapses them to exactly one outstanding disable per SNP-active window, because the disable and enable sites are not reached a symmetric number of times:
Well, why aren't they?
Why isn't a simple design where on SNP init hotplug is disabled - *exactly* one call to cpu_hotplug_disable() and on SNP shutdown hotplug is reenabled again - also exactly one call.
I know why...
Quoted 1 line
- On firmware without
SNP_X86_SHUTDOWN_SUPPORTED,__sev_snp_shutdown_locked()does not
This function is one convoluted mess which does gazillion things. If I were maintaining that code, I would impose a mandatory cleanup phase before new features are added. But I probably said that already before...
And because a lot of code from your set goes into areas I maintain, I would suggest you take the time and do that cleanup. Before that code goes completely off the rails. And I'm willing to offer you review bandwidth and other help I can with doing this right.
Quoted 4 lines
call
snp_shutdown()(it's gated on data.x86_snp_shutdown), so SNP stays enabled in hardware —SNP_ENstays set and hotplug stays disabled — whilesev->snp_initializedis cleared. Re-init after that is routine, the SNP ioctls self-bracket init and shutdown (e.g.SNP_COMMIT,SNP_SET_CONFIG,SNP_VLEK_LOAD):
That init and teardown flow should be simplified:
You have multiple things which you need to do at different times
- per-CPU init
- global init
- per-CPU teardown
- global teardown
CPU hotplug toggling belongs to the global category. Instead of piling more stuff onto that __sev_snp_shutdown_locked() function, you should take some time to clean it up, analyze what goes where and then simplify that flow.
So let's clean stuff up first, please, analyze the flow and determine what goes where and then do it. Not bolt more stuff on what is already wobbly.
Thx.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteKalra, Ashish
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Hello Boris,
Quoted 12 lines · Borislav Petkov
Quoted 1 line · Ashish
Hello Boris,
Hello Ashish,
lemme try to make sense of your AI reply...
Quoted 4 lines
cpu_hotplug_disable()/cpu_hotplug_enable() are refcounted (cpu_hotplug_disabled++/--, with a WARN on underflow), so they have to be balanced. This flag collapses them to exactly one outstanding disable per SNP-active window, because the disable and enable sites are not reached a symmetric number of times:
Quoted 8 lines
Well, why aren't they?
Why isn't a simple design where on SNP init hotplug is disabled - *exactly* one call to
cpu_hotplug_disable()and on SNP shutdown hotplug is reenabled again - also exactly one call.I know why...
It can be that simple, and flag-free, by following the SNP_EN state:
- cpu_hotplug_disable() when SNP_EN is programmed: in snp_prepare(), before snp_enable().
- cpu_hotplug_enable() when SNP_EN is cleared: in snp_shutdown(), after the firmware clears it on X86_SNP_SHUTDOWN.
SNP_EN is set only by snp_enable() in snp_prepare() (gated by online == present), and only the firmware clears it. So:
- snp_prepare() programs SNP_EN and disables hotplug on the same path; if it's called again while SNP_EN is already set (re-init), it bails before the disable.
- snp_shutdown() runs only on the X86_SNP_SHUTDOWN path, after SNP_EN has been cleared, and enables hotplug. A legacy shutdown leaves SNP_EN set and does not call snp_shutdown(), so hotplug correctly stays disabled.
We also have to re-enable cpu hotplug on the init failure paths (snp_prepare()'s online != present check, and the SNP_INIT_EX / DF_FLUSH failures in __sev_snp_init_locked()), so a failed init leaves hotplug enabled, as it was before this support.
The only extra case is a kexec target that boots with SNP_EN already set (legacy firmware -- on X86_SNP_SHUTDOWN firmware the full shutdown required before kexec clears SNP_EN, so the target re-inits normally). There snp_prepare() bails, so I do the disable once at boot in snp_rmptable_init() when SNP_EN is already set. That and the snp_prepare() disable can't both run -- SNP_EN is either already set at boot, or it gets programmed by snp_prepare().
No (extra) flag needed.
Thanks,
Ashish
Borislav Petkov
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Quoted 1 line · Ashish
It can be that simple, and flag-free, by following the
SNP_ENstate:
Maybe. But that doesn't mean that you should not clean things up first where needed. But I'll do a proper review once the dust from patchsets flying around settles.
Quoted 4 lines
We also have to re-enable cpu hotplug on the init failure paths (snp_prepare()'s online != present check, and the
SNP_INIT_EX/DF_FLUSHfailures in__sev_snp_init_locked()), so a failed init leaves hotplug enabled, as it was before this support.
You could also block hotplug for the time being by grabbing cpus_read_lock(). And only when you know you are all clear to disable hotplug, then you can do that in the end and drop the hotplug lock.
Quoted 6 lines
The only extra case is a kexec target that boots with
SNP_ENalready set (legacy firmware -- onX86_SNP_SHUTDOWNfirmware the full shutdown required before kexec clearsSNP_EN, so the target re-inits normally). Theresnp_prepare()bails, so I do the disable once at boot insnp_rmptable_init()whenSNP_ENis already set. That and thesnp_prepare()disable can't both run --SNP_ENis either already set at boot, or it gets programmed bysnp_prepare().
Ok.
Thx.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Hello Boris,
Quoted 3 lines · Borislav Petkov
You could also block hotplug for the time being by grabbing
cpus_read_lock(). And only when you know you are all clear to disable hotplug, then you can do that in the end and drop the hotplug lock.
This is bad idea because it'll stall the tasks trying to do a hotplug until the last SNP VM exits. Instead of simply getting an -EBUSY, the users will start seeing a hung task splats in dmesg.
Also, since the last VM has to re-enable hotplug, you'll need a up_read_non_owner() variant for cpus_read_unlock() to unlock the rwsem from a different thread compared to the one that locks.
I think cpu_hotplug_disable() is the correct way to go forward but if you are not a fan of the global "snp_cpu_hotplug_disabled" flag, maybe it can be turned into an indicator like "snp_initialized" in "struct sev_device". Thoughts?
Signature · 2 lines
Thanks and Regards, Prateek
Kalra, Ashish
maintainerRe: [PATCH v9 3/6] x86/sev: Disable CPU hotplug while SNP is active
Quoted 11 lines · K Prateek Nayak
Hello Boris,
Quoted 3 lines · Borislav Petkov
You could also block hotplug for the time being by grabbing
cpus_read_lock(). And only when you know you are all clear to disable hotplug, then you can do that in the end and drop the hotplug lock.This is bad idea because it'll stall the tasks trying to do a hotplug until the last SNP VM exits. Instead of simply getting an
-EBUSY, the users will start seeing a hung task splats in dmesg.
Quoted 9 lines
Also, since the last VM has to re-enable hotplug, you'll need a
up_read_non_owner()variant forcpus_read_unlock()to unlock the rwsem from a different thread compared to the one that locks.I think
cpu_hotplug_disable()is the correct way to go forward but if you are not a fan of the global "snp_cpu_hotplug_disabled" flag, maybe it can be turned into an indicator like "snp_initialized" in "structsev_device". Thoughts?
As i mentioned in my previous reply, i have already removed the global "snp_cpu_hotplug_disabled", the new implementation is flag-free, and does hotplug disable/enable by following the SNP_EN state.
Thanks,
Ashish
Ashish Kalra
maintainerPATCH v9 4/6 x86/sev: Add support to perform RMP optimizations asynchronously
In reply to a message not in the archiveFrom: Ashish Kalra <[email protected]>
When SEV-SNP is enabled, all writes to memory are checked to ensure integrity of SNP guest memory. This imposes performance overhead on the whole system.
RMPOPT is a new instruction that minimizes the performance overhead of RMP checks on the hypervisor and on non-SNP guests by allowing RMP checks to be skipped for 1GB regions of memory that are known not to contain any SEV-SNP guest memory.
Add support for performing RMP optimizations asynchronously using a dedicated workqueue.
Enable RMPOPT optimizations for up to 2TB of system RAM starting from the lowest physical memory address aligned down to a 1GB boundary at RMP initialization time. RMP checks can initially be skipped for 1GB memory ranges that do not contain SEV-SNP guest memory (excluding preassigned pages such as the RMP table and firmware pages). As SNP guests are launched, RMPUPDATE will disable the corresponding RMPOPT optimizations.
--- arch/x86/virt/svm/sev.c | 165 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 162 insertions(+), 3 deletions(-)
arch/x86/virt/svm/sev.c +162 -3
@@ -19,6 +19,7 @@#include <linux/iommu.h> #include <linux/amd-iommu.h> #include <linux/nospec.h> +#include <linux/workqueue.h> #include <asm/sev.h> #include <asm/processor.h>
@@ -125,9 +126,20 @@ static void *rmp_bookkeeping __ro_after_init;static u64 probed_rmp_base, probed_rmp_size;static cpumask_var_t rmpopt_cpumask; -static phys_addr_t rmpopt_pa_start; +static phys_addr_t rmpopt_pa_start, rmpopt_pa_end;static bool rmpopt_capable; +enum rmpopt_function { +RMPOPT_FUNC_VERIFY_AND_REPORT_STATUS , +RMPOPT_FUNC_REPORT_STATUS +}; + +#define RMPOPT_WORK_TIMEOUT 10000 + +static struct workqueue_struct *rmpopt_wq; +static struct delayed_work rmpopt_delayed_work; +static DEFINE_MUTEX (rmpopt_wq_mutex); +static LIST_HEAD (snp_leaked_pages_list);static DEFINE_SPINLOCK (snp_leaked_pages_list_lock);
@@ -571,13 +583,22 @@ static void rmpopt_cleanup(void) {int cpu; +guard (mutex)(&rmpopt_wq_mutex); + +if (!rmpopt_wq) +return ; + +cancel_delayed_work_sync (&rmpopt_delayed_work); +destroy_workqueue (rmpopt_wq); +scoped_guard (cpus_read_lock) {for_each_cpu (cpu, rmpopt_cpumask)wrmsrq_on_cpu (cpu,MSR_AMD64_RMPOPT_BASE ,0 ); }free_cpumask_var (rmpopt_cpumask); - rmpopt_pa_start =0 ; + rmpopt_pa_start = rmpopt_pa_end =0 ; + rmpopt_wq =NULL ; }/*
@@ -627,6 +648,101 @@ void snp_clear_rmpopt_capable(void) rmpopt_capable = false; } +/* +* RMPOPT: F2 0F 01 FC +* Input: RAX = system physical address (1GB aligned) +* RCX = operation type +* Output: CF set if the range was optimized +*/ +static inline bool __rmpopt (u64 pa_start,u64 op_type) +{ +bool optimized; + + asmvolatile (".byte 0xf2, 0x0f, 0x01, 0xfc" + :"=@ccc" (optimized) + :"a" (pa_start),"c" (op_type) + :"memory" ,"cc" ); + +return optimized; +} + +static void rmpopt (u64 pa) +{ +u64 pa_start =ALIGN_DOWN (pa,SZ_1G ); +u64 op_type =RMPOPT_FUNC_VERIFY_AND_REPORT_STATUS ; + +__rmpopt (pa_start, op_type); +} + +/* +* 'val' is a system physical address. +*/ +static void rmpopt_smp (void *val) +{ +rmpopt ((u64 )val); +} + +/* +* RMPOPT optimizations skip RMP checks at 1GB granularity if this +* range of memory does not contain any SNP guest memory. +*/ +static void rmpopt_work_handler (struct work_struct *work) +{ +cpumask_var_t follower_mask; +phys_addr_t pa; +int this_cpu; + +pr_info ("Attempt RMP optimizations on physical address range @1GB alignment [0x%016llx - 0x%016llx]\n" , + rmpopt_pa_start, rmpopt_pa_end); + +if (!alloc_cpumask_var (&follower_mask,GFP_KERNEL )) +return ; + +/* +* RMPOPT scans the RMP table, stores the result of the scan in the +* reserved processor memory. The RMP scan is the most expensive +* part. If a second RMPOPT occurs, it can skip the expensive scan +* if they can see a cached result in the reserved processor memory. +* +* Do RMPOPT on one CPU alone. Then, follow that up with RMPOPT +* on every other primary thread. Followers are "designed to" +* skip the scan if they see the "cached" scan results. +* +* Pin the worker to the current CPU for the leader loop so that +* this_cpu remains valid and the RMPOPT instruction executes on +* the correct CPU. Use migrate_disable() rather than get_cpu() to +* prevent migration while still allowing preemption. +*/ +migrate_disable (); + this_cpu =smp_processor_id (); + +cpumask_andnot (follower_mask, rmpopt_cpumask, +topology_sibling_cpumask (this_cpu)); + +for (pa = rmpopt_pa_start; pa < rmpopt_pa_end; pa +=SZ_1G ) { +rmpopt (pa); +cond_resched (); + } +migrate_enable (); + +/* +* Followers: run RMPOPT on remaining cores. CPUs cannot go offline +* while SNP is active, so the follower set stays valid across the +* scan and cpus_read_lock() is uncontended. +*/ +scoped_guard (cpus_read_lock) { +for (pa = rmpopt_pa_start; pa < rmpopt_pa_end; pa +=SZ_1G ) { +on_each_cpu_mask (follower_mask, rmpopt_smp, + (void *)pa, true); + +/* Give a chance for other threads to run */ +cond_resched (); + } + } + +free_cpumask_var (follower_mask); +} +void snp_setup_rmpopt (void ) {u64 rmpopt_base;
@@ -635,14 +751,42 @@ void snp_setup_rmpopt(void)if (!cpu_feature_enabled (X86_FEATURE_RMPOPT ) || !rmpopt_capable)return ; +guard (mutex)(&rmpopt_wq_mutex); + +/* +* Guard against re-initialization. When SNP_SHUTDOWN_EX is issued +* with x86_snp_shutdown=0, snp_shutdown() is not called and +* rmpopt_cleanup() is skipped, but snp_initialized is still cleared. +* A subsequent __sev_snp_init_locked() would call snp_setup_rmpopt() +* again, leaking the existing workqueue, delayed work, and cpumask +* state. +*/ +if (rmpopt_wq) +return ; + +/* +* Create an RMPOPT-specific workqueue to avoid scheduling +* RMPOPT workitem on the global system workqueue. +*/ + rmpopt_wq =alloc_workqueue ("rmpopt_wq" ,WQ_UNBOUND ,1 ); +if (!rmpopt_wq) { +pr_err ("Failed to allocate RMPOPT workqueue\n" ); +return ; + } + +INIT_DELAYED_WORK (&rmpopt_delayed_work, rmpopt_work_handler); +if (!zalloc_cpumask_var (&rmpopt_cpumask,GFP_KERNEL )) {pr_err ("Failed to allocate RMPOPT cpumask\n" ); +destroy_workqueue (rmpopt_wq); + rmpopt_wq =NULL ;return ; }/* * The RMPOPT_BASE MSR is per-core, so only one thread per core needs -* to set up the RMPOPT_BASE MSR. +* to set up the RMPOPT_BASE MSR. Likewise, only one thread per core +* needs to issue the RMPOPT instruction. * * Note: only online primary threads are included. If a core's * primary thread is offline, that core is not covered. CPU hotplug
@@ -665,6 +809,21 @@ void snp_setup_rmpopt(void)for_each_cpu (cpu, rmpopt_cpumask)wrmsrq_on_cpu (cpu,MSR_AMD64_RMPOPT_BASE , rmpopt_base); } + + rmpopt_pa_end =ALIGN (PFN_PHYS (max_pfn),SZ_1G ); + +/* Limit memory scanning to 2TB of RAM */ +if ((rmpopt_pa_end - rmpopt_pa_start) >SZ_2T ) { +pr_info ("RMPOPT coverage limited to 2TB; memory above 0x%llx not optimized\n" , + rmpopt_pa_start +SZ_2T ); + rmpopt_pa_end = rmpopt_pa_start +SZ_2T ; + } + +/* +* Once all per-CPU RMPOPT tables have been configured, enable RMPOPT +* optimizations on all physical memory. +*/ +queue_delayed_work (rmpopt_wq, &rmpopt_delayed_work,0 ); }EXPORT_SYMBOL_FOR_MODULES (snp_setup_rmpopt,"ccp" );
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v9 4/6] x86/sev: Add support to perform RMP optimizations asynchronously
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The RMP optimization work handler fails silently if allocating the follower cpumask fails…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The RMP optimization work handler fails silently if allocating the follower cpumask fails, permanently dropping the optimization. --
commit aff4fb20feaba36704d56dc8d40be21819095e40
Author: Ashish Kalra <[email protected]>
x86/sev: Add support to perform RMP optimizations asynchronously
This commit introduces support for performing RMP (Reverse Map Table) optimizations asynchronously via a dedicated workqueue. It enables skipping RMP checks for 1GB memory regions known not to contain SEV-SNP guest memory to minimize performance overhead.
Quoted 4 lines
arch/x86/virt/svm/sev.c +0
-0
[ ... ]
Quoted 10 lines
arch/x86/virt/svm/sev.c +6
-0@@ -627,6 +648,101 @@ void snp_clear_rmpopt_capable(void) rmpopt_capable = false; } +/* +* RMPOPT: F2 0F 01 FC +* Input: RAX = system physical address (1GB aligned) +* RCX = operation type +* Output: CF set if the range was optimized +*/
[ ... ]
Quoted 5 lines
arch/x86/virt/svm/sev.c +5
-0+/* +* RMPOPT optimizations skip RMP checks at 1GB granularity if this +* range of memory does not contain any SNP guest memory. +*/ +static void rmpopt_work_handler (struct work_struct *work)
arch/x86/virt/svm/sev.c void snp_clear_rmpopt_capable(void) · line 699
Quoted 10 lines
arch/x86/virt/svm/sev.c +10
-0+{ +cpumask_var_t follower_mask; +phys_addr_t pa; +int this_cpu; + +pr_info ("Attempt RMP optimizations on physical address range @1GB alignment [0x%016llx - 0x%016llx]\n" , + rmpopt_pa_start, rmpopt_pa_end); + +if (!alloc_cpumask_var (&follower_mask,GFP_KERNEL )) +return ;
[Severity: Low]
Does this code silently drop the RMP optimization pass if the cpumask allocation fails?
If alloc_cpumask_var() returns false due to memory pressure, the work handler returns immediately without rescheduling or logging a warning, which permanently abandons the performance optimization for these ranges.
Could this be updated to either log a warning or reschedule the work to be tried again later?
Quoted 4 lines
arch/x86/virt/svm/sev.c +4
-0+ +/* +* RMPOPT scans the RMP table, stores the result of the scan in the +* reserved processor memory. The RMP scan is the most expensive
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Ashish Kalra
maintainerPATCH v9 5/6 x86/sev: Add interface to re-enable RMP optimizations.
In reply to a message not in the archiveFrom: Ashish Kalra <[email protected]>
RMPOPT table is a per-CPU table which indicates if 1GB regions of physical memory are entirely hypervisor-owned or not.
When performing host memory accesses in hypervisor mode as well as non-SNP guest mode, the processor may consult the RMPOPT table to potentially skip an RMP access and improve performance.
Normal guest events clear RMP optimizations: pages are converted from shared to private as SNP guests are launched, and large pages are split and collapsed during guest operation -- both clear the RMPOPT optimizations for the affected 1GB regions. Conversely, guest pages are converted back to shared during SNP guest termination, so those regions may become eligible for RMPOPT optimization again.
Without some intervention, all RMP optimizations would eventually be lost. Add an interface to re-optimize all of physical memory.
The interface uses mod_delayed_work() instead of queue_delayed_work() so that the delay timer is reset on each call. This provides proper batching semantics: re-optimization runs 10 seconds after the *last* VM termination rather than after the first. mod_delayed_work() also re-queues work that is already in-flight, so a re-scan request during an active scan is not silently dropped.
--- arch/x86/include/asm/sev.h | 2 ++ arch/x86/virt/svm/sev.c | 15 +++++++++++++++ 2 files changed, 17 insertions(+)
arch/x86/include/asm/sev.h +2 -0
@@ -662,6 +662,7 @@ static inline void snp_leak_pages(u64 pfn, unsigned int pages)__snp_leak_pages (pfn, pages, true); }int snp_prepare (void ); +void snp_rmpopt_all_physmem (void );void snp_setup_rmpopt (void );void snp_clear_rmpopt_capable (void );void snp_disable_cpu_hotplug (void );
@@ -683,6 +684,7 @@ static inline void snp_leak_pages(u64 pfn, unsigned int npages) {}static inline void kdump_sev_callback (void ) { }static inline void snp_fixup_e820_tables (void ) {}static inline int snp_prepare (void ) {return -ENODEV ; } +static inline void snp_rmpopt_all_physmem (void ) {}static inline void snp_setup_rmpopt (void ) {}static inline void snp_clear_rmpopt_capable (void ) {}static inline void snp_disable_cpu_hotplug (void ) {}
arch/x86/virt/svm/sev.c +15 -0
@@ -743,6 +743,21 @@ static void rmpopt_work_handler(struct work_struct *work)free_cpumask_var (follower_mask); } +void snp_rmpopt_all_physmem (void ) +{ +if (!cpu_feature_enabled (X86_FEATURE_RMPOPT ) || !rmpopt_capable) +return ; + +guard (mutex)(&rmpopt_wq_mutex); + +if (!rmpopt_wq) +return ; + +mod_delayed_work (rmpopt_wq, &rmpopt_delayed_work, +msecs_to_jiffies (RMPOPT_WORK_TIMEOUT )); +} +EXPORT_SYMBOL_FOR_MODULES (snp_rmpopt_all_physmem,"kvm-amd" ); +void snp_setup_rmpopt (void ) {u64 rmpopt_base;
Signature · 1 line
2.43.0
Ashish Kalra
maintainerPATCH v9 6/6 KVM: SEV: Perform RMP optimizations on SNP guest shutdown
In reply to a message not in the archiveFrom: Ashish Kalra <[email protected]>
Pages are converted from shared to private as SNP guests are launched. This destroys exisiting RMPOPT optimizations in the regions where pages are converted.
Conversely, guest pages are converted back to shared during SNP guest termination and their region may become eligible for RMPOPT optimization.
To take advantage of this, perform RMPOPT after guest termination. Do it after a delay so that a single RMPOPT pass can be done if multiple guests terminate in a short period of time.
--- arch/x86/kvm/svm/sev.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
arch/x86/kvm/svm/sev.c +10 -0
@@ -3005,6 +3005,16 @@ void sev_vm_destroy(struct kvm *kvm)*/ if (snp_decommission_context (kvm))return ; + +/* +* Perform RMP optimizations on memory freed by terminating +* guests. The scan is deferred, so it normally runs after +* sev_gmem_invalidate() has converted this guest's pages back to +* shared, and picks them up then. A very large guest whose +* conversion has not finished by then is picked up by a later +* teardown's scan. +*/ +snp_rmpopt_all_physmem (); }else {sev_unbind_asid (kvm, sev->handle); }
Signature · 1 line
2.43.0